CImage.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. #pragma once
  2. #include "CRenderable.h"
  3. #include "WallpaperEngine/Render/CObject.h"
  4. #include "WallpaperEngine/Render/Objects/Effects/CPass.h"
  5. #include "WallpaperEngine/Render/Wallpapers/CScene.h"
  6. #include "WallpaperEngine/Render/Shaders/Shader.h"
  7. #include "../TextureProvider.h"
  8. #include "PuppetPhysics.h"
  9. #include "WallpaperEngine/Scripting/ScriptableObject.h"
  10. #include <glm/gtc/quaternion.hpp>
  11. #include <glm/mat4x4.hpp>
  12. #include <glm/vec3.hpp>
  13. #include <glm/vec4.hpp>
  14. #include <limits>
  15. #include <optional>
  16. #include <set>
  17. #include <vector>
  18. using namespace WallpaperEngine;
  19. using namespace WallpaperEngine::Render;
  20. using namespace WallpaperEngine::Scripting;
  21. namespace WallpaperEngine::Render::Objects::Effects {
  22. class CMaterial;
  23. class CPass;
  24. } // namespace WallpaperEngine::Render::Objects::Effects
  25. namespace WallpaperEngine::Render::Objects {
  26. /** A puppet skeleton bone, parsed from the MDLS section of the puppet .mdl */
  27. struct PuppetBone {
  28. std::string name;
  29. int parent = -1;
  30. /** Local bind-pose transform, relative to the parent bone (identity for a root bone's "world" reference) */
  31. glm::mat4 bindLocal { 1.0f };
  32. /** Inverse of the bone's bind-pose world transform, derived by walking the parent chain */
  33. glm::mat4 inverseBindWorld { 1.0f };
  34. PuppetBonePhysics physics {};
  35. };
  36. /** A single sampled TRS pose for one bone at one point in time, from the MDLA section */
  37. struct PuppetKeyframe {
  38. glm::vec3 position {};
  39. glm::vec3 rotation {};
  40. glm::vec3 scale { 1.0f };
  41. /** rotation as WE blends it, Rz * Ry * Rx */
  42. glm::quat orientation { 1.0f, 0.0f, 0.0f, 0.0f };
  43. };
  44. /** A baked animation clip: one keyframe track per bone, sampled at a fixed rate */
  45. struct PuppetAnimationClip {
  46. /** what animationlayers[].animation refers to */
  47. uint64_t id = 0;
  48. std::string name;
  49. std::string mode;
  50. float fps = 30.0f;
  51. uint32_t frameCount = 0;
  52. /** [boneIndex][sampleIndex], each track has frameCount+1 samples */
  53. std::vector<std::vector<PuppetKeyframe>> boneTracks;
  54. /** per bone, false when its track flags have bit 0 set: the clip leaves that bone alone */
  55. std::vector<bool> boneAnimated;
  56. };
  57. /** A named point on a puppet's rig that other objects can follow via scene.json's "attachment" field */
  58. struct PuppetAttachmentPoint {
  59. std::string name;
  60. int boneIndex = -1;
  61. /** Transform of the point relative to its bone, in the same convention as PuppetBone::bindLocal */
  62. glm::mat4 localTransform { 1.0f };
  63. };
  64. /** One of a puppet's animationlayers[] entries, paired with the baked clip it plays */
  65. struct PuppetActiveAnimation {
  66. PuppetAnimationClip clip;
  67. const WallpaperEngine::Data::Model::ImageAnimationLayer* layer = nullptr;
  68. };
  69. class CImage final : public CRenderable, public ScriptableObject {
  70. friend CObject;
  71. public:
  72. CImage (Wallpapers::CScene& scene, const Image& image);
  73. ~CImage () override;
  74. void setup () override;
  75. void render () override;
  76. /** Refreshes the image's own texture plus any video a pass pulled in from a user texture slot */
  77. void updateTextures () const;
  78. /** Cursor hit test (sub_14019DBB0): the layer's quad as it is drawn, rotation and parallax included, ndc in the
  79. * scene buffer's clip space. Fullscreen layers are always hit */
  80. [[nodiscard]] bool hitTest (const glm::vec2& ndc);
  81. /** A cursor event's localPosition: (u * width, (1 - v) * height) of the unscaled layer, from its top left, where
  82. * the cursor meets the quad's plane (sub_14019DBB0), off the quad too. Zero when it doesn't meet the plane */
  83. [[nodiscard]] glm::vec2 cursorLocalPosition (const glm::vec2& ndc);
  84. void renderPassthroughChildren (const std::shared_ptr<const CFBO>& buffer);
  85. [[nodiscard]] const Image& getImage () const;
  86. [[nodiscard]] glm::vec2 getSize () const;
  87. /** Another object samples this layer's composite FBO, so its passes run even while it's hidden */
  88. void markAsDependency ();
  89. [[nodiscard]] GLuint getSceneSpacePosition () const;
  90. [[nodiscard]] GLuint getCopySpacePosition () const;
  91. [[nodiscard]] GLuint getPassSpacePosition () const;
  92. [[nodiscard]] GLuint getTexCoordCopy () const;
  93. [[nodiscard]] GLuint getTexCoordPass () const;
  94. [[nodiscard]] const float& getBrightness () const override;
  95. [[nodiscard]] const float& getUserAlpha () const override;
  96. [[nodiscard]] const float& getAlpha () const override;
  97. [[nodiscard]] const glm::vec3& getColor () const override;
  98. /** a solid layer instance whose user texture slot the user filled */
  99. [[nodiscard]] bool showsUserTextureOnSolidLayer () const;
  100. [[nodiscard]] const glm::vec4& getColor4 () const override;
  101. [[nodiscard]] const glm::vec3& getCompositeColor () const override;
  102. void pinpongFramebuffer (std::shared_ptr<const CFBO>* drawTo, std::shared_ptr<const TextureProvider>* asInput);
  103. /** A puppet attachment point's current animated position, rotation and scale, in this puppet's own
  104. * local mesh space (same space as PuppetAttachmentPoint's position/localTransform). A negative
  105. * scale component means the bone's transform includes a reflection (a mirrored bone). */
  106. struct AttachmentPointTransform {
  107. glm::vec3 position;
  108. float angle;
  109. glm::vec2 scale;
  110. /** the same attachment point's rotation in the rig's bind pose */
  111. float restAngle;
  112. };
  113. /**
  114. * @param name A named attachment point on this puppet's rig (see PuppetAttachmentPoint)
  115. * @return The point's current animated transform, or nullopt if there's no such point (or no puppet mesh)
  116. */
  117. [[nodiscard]] std::optional<AttachmentPointTransform>
  118. getAttachmentPointMeshTransform (const std::string& name) const;
  119. /** Per frame puppet update (WE's image update, sub_1401FDF90): animation, physics and the bone matrices, before
  120. * the scripts run so they read and change this frame's pose */
  121. void updatePuppetPose ();
  122. /**
  123. * Bone access for IImageLayer scripts (wallpaper64 2.8.42 sub_140211070). Matrices are column-vector glm, the
  124. * transpose of WE's row-vector ones with the same 16 floats in memory. Scene matrices are object world * bone,
  125. * local ones relative to the parent bone. Only valid while hasPuppetPose(), for bones below the bone count.
  126. */
  127. [[nodiscard]] bool hasPuppetPose () const;
  128. [[nodiscard]] const std::vector<PuppetBone>& getPuppetBones () const { return this->m_puppetBones; }
  129. [[nodiscard]] int findPuppetBone (const std::string& name) const;
  130. [[nodiscard]] const glm::mat4& getPuppetBoneTransform (int bone) const;
  131. void setPuppetBoneTransform (int bone, const glm::mat4& transform);
  132. [[nodiscard]] const glm::mat4& getPuppetLocalBoneTransform (int bone) const;
  133. void setPuppetLocalBoneTransform (int bone, const glm::mat4& transform);
  134. void applyPuppetBonePhysicsImpulse (int bone, const glm::vec3& directional, const glm::vec3& angularDegrees);
  135. void resetPuppetBonePhysics (int bone);
  136. protected:
  137. void setupPasses ();
  138. void rebuildActivePasses ();
  139. void addEffectPasses (const ImageEffect& effect);
  140. [[nodiscard]] bool effectVisibilityChanged () const;
  141. void updateScreenSpacePosition ();
  142. [[nodiscard]] glm::mat4 ancestorTiltCorrection () const;
  143. void updateEffectTextureProjection ();
  144. void updateLightingTransform (const glm::mat4& sceneTransform);
  145. struct ResolvedTransform {
  146. glm::vec3 origin;
  147. glm::vec3 scale;
  148. float angle;
  149. /** part of `angle` that should pivot around the puppet mesh's own center instead of the object origin */
  150. float meshPivotAngle = 0.0f;
  151. };
  152. [[nodiscard]] ResolvedTransform resolveTransform (const WallpaperEngine::Data::Model::Object& object) const;
  153. /** Scene camera of this layer, the perspective layer camera when "perspective" is set */
  154. [[nodiscard]] glm::mat4 getViewProjection () const;
  155. private:
  156. /** Composite pass that applies the scene's fog, when there is fog */
  157. Effects::CPass* m_fogPass = nullptr;
  158. public:
  159. /**
  160. * Computes the object's own transform (origin/scale/angle) without walking the
  161. * parent chain. Used as the per-node step of resolveTransform.
  162. */
  163. [[nodiscard]] static ResolvedTransform localTransform (const WallpaperEngine::Data::Model::Object& object);
  164. private:
  165. bool loadPuppetMesh (const glm::vec2& size);
  166. void updatePuppetPositionBuffer (const glm::vec2& size);
  167. void composePuppetPose (const std::vector<int>& parents, const std::vector<glm::mat4>& locals);
  168. [[nodiscard]] glm::mat4 puppetObjectWorld () const;
  169. /** Skins the puppet vertices with the current bone matrices and re-uploads them */
  170. void updatePuppetSkinning ();
  171. void setupPuppetGeometryCallback (Effects::CPass* pass) const;
  172. ResolvedTransform updateGeometryBuffers ();
  173. [[nodiscard]] glm::vec2 resolveGeometrySize (float sceneWidth, float sceneHeight, glm::vec3& origin) const;
  174. void updateScenePosition (
  175. const glm::vec3& origin, const glm::vec2& size, const glm::vec3& scale, float sceneWidth, float sceneHeight
  176. );
  177. void uploadGeometryBuffers (const glm::vec2& size);
  178. [[nodiscard]] bool shouldRenderFinalPass (bool isLastPass) const;
  179. bool configurePassTarget (
  180. Effects::CPass* pass, std::shared_ptr<const CFBO>& drawTo,
  181. const std::shared_ptr<const TextureProvider>& asInput, std::shared_ptr<const TextureProvider>& effectInput,
  182. bool& inTargetEffectSequence
  183. );
  184. GLuint m_sceneSpacePosition;
  185. GLuint m_copySpacePosition;
  186. GLuint m_passSpacePosition;
  187. GLuint m_texcoordCopy;
  188. GLuint m_texcoordPass;
  189. GLuint m_puppetSpacePosition = GL_NONE;
  190. GLuint m_puppetTexCoord = GL_NONE;
  191. GLuint m_puppetIndices = GL_NONE;
  192. GLsizei m_puppetIndexCount = 0;
  193. bool m_hasPuppetMesh = false;
  194. // the pass that draws the warped mesh, and whether it is the last one (straight into the scene FBO)
  195. Effects::CPass* m_puppetMeshPass = nullptr;
  196. bool m_puppetMeshLast = false;
  197. mutable bool m_puppetDrawDiagnosticLogged = false;
  198. mutable bool m_puppetDrawErrorChecked = false;
  199. bool m_puppetPositionDiagnosticLogged = false;
  200. mutable std::set<int> m_attachmentDiagnosticLogged = {};
  201. std::vector<GLfloat> m_puppetRawPositions = {};
  202. /** This object's current resolved scale, mirrored here so updatePuppetSkinning() (called after
  203. * updateGeometryBuffers() each frame, see render()) can fold it into puppet vertex positions
  204. * without needing resolveTransform() run twice */
  205. glm::vec3 m_puppetScale { 1.0f };
  206. std::vector<glm::uvec4> m_puppetBlendIndices = {};
  207. std::vector<glm::vec4> m_puppetBlendWeights = {};
  208. std::vector<PuppetBone> m_puppetBones = {};
  209. /**
  210. * Every animationlayers[] entry that matched a baked clip. Wallpaper Engine puppets almost always
  211. * declare several "additive" layers (idle sway, blinking, hand movement, ...) that all play at once
  212. * on top of each other rather than one layer replacing another - see updatePuppetSkinning for how
  213. * they're composed.
  214. */
  215. std::vector<PuppetActiveAnimation> m_puppetActiveAnimations = {};
  216. std::vector<GLfloat> m_puppetSkinnedPositions = {};
  217. std::vector<PuppetAttachmentPoint> m_puppetAttachmentPoints = {};
  218. /** Per-bone current animated world transform, in the puppet's own local mesh space; starts out equal
  219. * to the bind pose and is refreshed every frame by updatePuppetPose */
  220. std::vector<glm::mat4> m_puppetBoneWorldAnimated = {};
  221. /** the bones' local matrices this frame (WE P+784) and their scene matrices (P+832), empty until the first update */
  222. std::vector<glm::mat4> m_puppetBoneLocal = {};
  223. std::vector<glm::mat4> m_puppetBoneScene = {};
  224. /** Bone physics state and last frame's scene transforms, empty until the first frame */
  225. std::vector<PuppetBonePhysicsState> m_puppetPhysicsState = {};
  226. std::vector<glm::mat4> m_puppetPhysicsPreviousWorld = {};
  227. bool m_puppetHasPhysics = false;
  228. /** a script wrote bone matrices, the mesh has to be skinned from then on */
  229. bool m_puppetPoseScripted = false;
  230. /** the pose differs from the bind pose (animation, physics or scripts), so render skins the mesh */
  231. bool m_puppetPoseAnimated = false;
  232. glm::mat4 m_modelViewProjectionScreen = {};
  233. glm::mat4 m_modelViewProjectionPass = {};
  234. /** effect passes: their buffer's geometry mapped to where the layer is on screen */
  235. glm::mat4 m_effectModelViewProjectionCopy { 1.0f };
  236. /** WE's object world matrix (y up, scene pixels), shaders read g_LayerModelMatrix for the layer's scale */
  237. glm::mat4 m_layerModelMatrix { 1.0f };
  238. glm::mat4 m_effectModelViewProjectionPass { 1.0f };
  239. glm::mat4 m_modelViewProjectionCopy = {};
  240. glm::mat4 m_modelViewProjectionScreenInverse = {};
  241. glm::mat4 m_modelViewProjectionPassInverse = {};
  242. glm::mat4 m_modelViewProjectionCopyInverse = {};
  243. /** Maps the layer quad's own -1..1 space (+y = texture top) to screen clip space, effects like xray and
  244. * cursorripple use its inverse to bring g_PointerPosition into the layer's texture space */
  245. glm::mat4 m_effectTextureProjection = glm::mat4 (1.0);
  246. glm::mat4 m_effectTextureProjectionInverse = glm::mat4 (1.0);
  247. glm::mat4 m_objectSpaceProjectionInverse = glm::mat4 (1.0);
  248. glm::mat4 m_modelMatrix = {};
  249. glm::mat4 m_viewProjectionMatrix = {};
  250. std::shared_ptr<const CFBO> m_mainFBO = nullptr;
  251. std::shared_ptr<const CFBO> m_subFBO = nullptr;
  252. std::shared_ptr<const CFBO> m_currentMainFBO = nullptr;
  253. std::shared_ptr<const CFBO> m_currentSubFBO = nullptr;
  254. const Image& m_image;
  255. mutable glm::vec3 m_colorCache {};
  256. mutable glm::vec4 m_color4Cache {};
  257. mutable float m_alphaCache = 1.0f;
  258. std::vector<Effects::CPass*> m_passes = {};
  259. std::vector<Effects::CPass*> m_allPasses = {};
  260. struct PassState {
  261. /** nullptr for passes that always render */
  262. const DynamicValue* visible;
  263. BlendingMode blending;
  264. bool fromEffect;
  265. };
  266. std::vector<PassState> m_allPassStates = {};
  267. std::vector<bool> m_activePassMask = {};
  268. bool m_hasActiveEffectPass = false;
  269. bool m_passesDrawToScreen = false;
  270. std::vector<MaterialPassUniquePtr> m_virtualPassess = {};
  271. glm::vec4 m_pos = {};
  272. /** The quad's size before the layer's scale, what m_pos spans */
  273. glm::vec2 m_displaySize = {};
  274. glm::vec3 m_sceneCenter = {};
  275. /** Lit passes: scene/copy space vertices -> WE world (y up, bottom left origin), see CPass::setLightingTransform */
  276. glm::mat4 m_lightingSceneModel { 1.0f };
  277. glm::mat4 m_lightingCopyModel { 1.0f };
  278. glm::mat3 m_lightingNormal { 1.0f };
  279. glm::mat4 m_lightingViewProjection { 1.0f };
  280. glm::vec2 m_size = {};
  281. // last m_pos/size uploaded to the GL geometry buffers; NaN forces the first upload
  282. glm::vec4 m_lastUploadedPos = glm::vec4 (std::numeric_limits<float>::quiet_NaN ());
  283. glm::vec2 m_lastUploadedGeometrySize = glm::vec2 (std::numeric_limits<float>::quiet_NaN ());
  284. bool m_initialized = false;
  285. bool m_isDependency = false;
  286. bool m_readByOtherLayer = false;
  287. /** A passthrough layer with objects under it, it draws them into its buffer after the base pass */
  288. bool m_hasPassthroughChildren = false;
  289. struct {
  290. struct {
  291. MaterialUniquePtr material;
  292. ImageEffectPassOverrideUniquePtr override;
  293. } colorBlending;
  294. std::vector<MaterialUniquePtr> compatibilityMaterials = {};
  295. std::vector<ImageEffectPassOverrideUniquePtr> compatibilityOverrides = {};
  296. } m_materials;
  297. };
  298. } // namespace WallpaperEngine::Render::Objects