CImage.cpp 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301
  1. #include "CImage.h"
  2. #include "WallpaperEngine/Data/Model/Property.h"
  3. #include "WallpaperEngine/Data/Parsers/ObjectParser.h"
  4. #include "CRenderable.h"
  5. #include <algorithm>
  6. #include <array>
  7. #include <cstdio>
  8. #include <cstdlib>
  9. #include <cstring>
  10. #include <iterator>
  11. #include <limits>
  12. #include <optional>
  13. #include <sstream>
  14. #include <strings.h>
  15. #include <vector>
  16. #include <glm/glm.hpp>
  17. #include <glm/gtc/matrix_transform.hpp>
  18. #define GLM_ENABLE_EXPERIMENTAL
  19. #include <glm/gtx/rotate_vector.hpp>
  20. #undef GLM_ENABLE_EXPERIMENTAL
  21. #include "WallpaperEngine/Assets/AssetLoadException.h"
  22. #include "WallpaperEngine/Data/Model/DynamicValue.h"
  23. #include "WallpaperEngine/Data/Model/Material.h"
  24. #include "WallpaperEngine/Data/Model/Object.h"
  25. #include "WallpaperEngine/Data/Model/UserSetting.h"
  26. #include "WallpaperEngine/Data/Parsers/MaterialParser.h"
  27. #include "WallpaperEngine/Data/Utils/BinaryReader.h"
  28. #include "WallpaperEngine/Data/Utils/MemoryStream.h"
  29. #include "WallpaperEngine/Logging/Log.h"
  30. #include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
  31. #include "WallpaperEngine/Scripting/ScriptEngine.h"
  32. using namespace WallpaperEngine;
  33. using namespace WallpaperEngine::Render::Objects;
  34. using namespace WallpaperEngine::Render::Objects::Effects;
  35. using namespace WallpaperEngine::Data::Parsers;
  36. using namespace WallpaperEngine::Data::Builders;
  37. using namespace WallpaperEngine::Data::Utils;
  38. extern float g_Time;
  39. extern float g_TimeLast;
  40. namespace {
  41. glm::vec2 rotateVec2 (const glm::vec2& value, float angle) {
  42. const float cosAngle = std::cos (angle);
  43. const float sinAngle = std::sin (angle);
  44. return { value.x * cosAngle - value.y * sinAngle, value.x * sinAngle + value.y * cosAngle };
  45. }
  46. bool isMagentaNeonTint (const glm::vec3& color) { return color.r > 0.55f && color.g < 0.25f && color.b > 0.45f; }
  47. std::optional<glm::vec3> findMagentaCompositeTint (const Image& image, const std::vector<int>& skippedEffectIds) {
  48. for (const auto& effect : image.effects) {
  49. if (std::find (skippedEffectIds.begin (), skippedEffectIds.end (), static_cast<int> (effect->id))
  50. != skippedEffectIds.end ()) {
  51. continue;
  52. }
  53. if (!effect->visible->value->getBool ()) {
  54. continue;
  55. }
  56. for (const auto& passOverride : effect->passOverrides) {
  57. const auto compositeCombo = passOverride->combos.find ("COMPOSITE");
  58. if (compositeCombo == passOverride->combos.end () || compositeCombo->second != 2) {
  59. continue;
  60. }
  61. const auto compositeColor = passOverride->constants.find ("compositecolor");
  62. if (compositeColor == passOverride->constants.end () || compositeColor->second == nullptr
  63. || compositeColor->second->value == nullptr) {
  64. continue;
  65. }
  66. const auto tint = compositeColor->second->value->getVec3 ();
  67. if (isMagentaNeonTint (tint)) {
  68. return tint;
  69. }
  70. }
  71. }
  72. return std::nullopt;
  73. }
  74. struct PuppetMeshBlock {
  75. size_t headerOffset = 0;
  76. uint32_t vertexBytes = 0;
  77. uint32_t indexBytes = 0;
  78. };
  79. // Finds every byte offset that could plausibly be a MDLV mesh header (DWORD vertexByteLength
  80. // immediately followed by that many bytes of vertex data, then a DWORD indexByteLength followed by
  81. // that many bytes of indices, all landing before the MDLS block). This intentionally doesn't know or
  82. // care about the per-vertex stride - that's resolved afterwards against whatever candidates come back,
  83. // since the stride isn't reliably predictable from the MDLV header version alone (see
  84. // resolvePuppetVertexLayout).
  85. std::vector<PuppetMeshBlock> findPuppetMeshBlockCandidates (
  86. const BinaryReader& reader, size_t markerSize, size_t mdlsOffset, size_t meshHeaderSize
  87. ) {
  88. std::vector<PuppetMeshBlock> candidates;
  89. for (size_t offset = markerSize; offset + meshHeaderSize + sizeof (uint32_t) < mdlsOffset; offset++) {
  90. reader.base ().seekg (static_cast<std::streamoff> (offset + sizeof (uint32_t)), std::ios::beg);
  91. const uint32_t candidateVertexBytes = reader.nextUInt32 ();
  92. const size_t verticesOffset = offset + meshHeaderSize;
  93. const size_t indexLengthOffset = verticesOffset + candidateVertexBytes;
  94. if (candidateVertexBytes == 0 || indexLengthOffset + sizeof (uint32_t) > mdlsOffset) {
  95. continue;
  96. }
  97. reader.base ().seekg (static_cast<std::streamoff> (indexLengthOffset), std::ios::beg);
  98. const uint32_t candidateIndexBytes = reader.nextUInt32 ();
  99. const size_t indicesOffset = indexLengthOffset + sizeof (uint32_t);
  100. if (candidateIndexBytes == 0 || candidateIndexBytes % (sizeof (uint16_t) * 3) != 0
  101. || indicesOffset + candidateIndexBytes > mdlsOffset) {
  102. continue;
  103. }
  104. candidates.push_back (
  105. PuppetMeshBlock {
  106. .headerOffset = offset, .vertexBytes = candidateVertexBytes, .indexBytes = candidateIndexBytes }
  107. );
  108. }
  109. return candidates;
  110. }
  111. struct PuppetVertexLayout {
  112. PuppetMeshBlock block;
  113. size_t vertexStride = 0;
  114. size_t uvOffset = 0;
  115. };
  116. // Reads raw positions/UVs/indices for a candidate (block, stride) pair. The UV pair has only ever
  117. // been observed as the trailing 8 bytes of the vertex record, whatever bone/weight data precedes it
  118. // (position(12) + ... + uv(8)), so uvOffset = stride - 8 throughout.
  119. struct PuppetMeshData {
  120. std::vector<GLfloat> positions;
  121. std::vector<GLfloat> texcoords;
  122. std::vector<GLushort> indices;
  123. };
  124. std::optional<PuppetMeshData> readPuppetMeshData (
  125. const BinaryReader& reader, const PuppetMeshBlock& block, size_t meshHeaderSize, size_t vertexStride
  126. ) {
  127. if (block.vertexBytes % vertexStride != 0) {
  128. return std::nullopt;
  129. }
  130. const size_t uvOffset = vertexStride - sizeof (GLfloat) * 2;
  131. const size_t vertexCount = block.vertexBytes / vertexStride;
  132. const size_t verticesOffset = block.headerOffset + meshHeaderSize;
  133. const size_t indicesOffset = verticesOffset + block.vertexBytes + sizeof (uint32_t);
  134. const size_t indexCount = block.indexBytes / sizeof (uint16_t);
  135. PuppetMeshData data;
  136. data.positions.reserve (vertexCount * 3);
  137. data.texcoords.reserve (vertexCount * 2);
  138. data.indices.reserve (indexCount);
  139. for (size_t index = 0; index < vertexCount; index++) {
  140. const size_t vertexOffset = verticesOffset + index * vertexStride;
  141. reader.base ().seekg (static_cast<std::streamoff> (vertexOffset), std::ios::beg);
  142. const float x = reader.nextFloat ();
  143. const float y = reader.nextFloat ();
  144. const float z = reader.nextFloat ();
  145. reader.base ().seekg (static_cast<std::streamoff> (vertexOffset + uvOffset), std::ios::beg);
  146. const float u = reader.nextFloat ();
  147. const float v = reader.nextFloat ();
  148. data.positions.push_back (x);
  149. data.positions.push_back (y);
  150. data.positions.push_back (z);
  151. data.texcoords.push_back (u);
  152. data.texcoords.push_back (v);
  153. }
  154. reader.base ().seekg (static_cast<std::streamoff> (indicesOffset), std::ios::beg);
  155. for (size_t index = 0; index < indexCount; index++) {
  156. uint16_t value = 0;
  157. reader.next (reinterpret_cast<char*> (&value), sizeof (value));
  158. if (value >= vertexCount) {
  159. return std::nullopt;
  160. }
  161. data.indices.push_back (value);
  162. }
  163. return data;
  164. }
  165. // Blend indices/weights are always the 32 bytes immediately before the UV pair, regardless of stride
  166. // (see docs/rendering/MDL_FILES.md) - position(12) + [normal(12) + tangent4(16), wide format only] +
  167. // blendindices(16) + blendweight(16) + uv(8).
  168. struct PuppetBlendData {
  169. std::vector<glm::uvec4> indices;
  170. std::vector<glm::vec4> weights;
  171. };
  172. std::optional<PuppetBlendData> readPuppetBlendData (
  173. const BinaryReader& reader, const PuppetMeshBlock& block, size_t meshHeaderSize, size_t vertexStride
  174. ) {
  175. if (vertexStride < 40 || block.vertexBytes % vertexStride != 0) {
  176. return std::nullopt;
  177. }
  178. const size_t blendIndicesOffset = vertexStride - 40;
  179. const size_t blendWeightsOffset = vertexStride - 24;
  180. const size_t vertexCount = block.vertexBytes / vertexStride;
  181. const size_t verticesOffset = block.headerOffset + meshHeaderSize;
  182. PuppetBlendData data;
  183. data.indices.reserve (vertexCount);
  184. data.weights.reserve (vertexCount);
  185. for (size_t index = 0; index < vertexCount; index++) {
  186. const size_t vertexOffset = verticesOffset + index * vertexStride;
  187. reader.base ().seekg (static_cast<std::streamoff> (vertexOffset + blendIndicesOffset), std::ios::beg);
  188. glm::uvec4 boneIndices;
  189. boneIndices.x = reader.nextUInt32 ();
  190. boneIndices.y = reader.nextUInt32 ();
  191. boneIndices.z = reader.nextUInt32 ();
  192. boneIndices.w = reader.nextUInt32 ();
  193. reader.base ().seekg (static_cast<std::streamoff> (vertexOffset + blendWeightsOffset), std::ios::beg);
  194. glm::vec4 boneWeights;
  195. boneWeights.x = reader.nextFloat ();
  196. boneWeights.y = reader.nextFloat ();
  197. boneWeights.z = reader.nextFloat ();
  198. boneWeights.w = reader.nextFloat ();
  199. data.indices.push_back (boneIndices);
  200. data.weights.push_back (boneWeights);
  201. }
  202. return data;
  203. }
  204. // Scores how plausible a candidate vertex layout is: real puppet meshes are triangulated warp grids,
  205. // so triangles formed by adjacent indices should be small relative to the mesh's overall size. A wrong
  206. // stride reinterprets bone/weight bytes as positions, which decorrelates neighbouring vertices and
  207. // produces comparatively huge, inconsistent triangles. Lower is better; nullopt if unscorable (e.g. a
  208. // degenerate single-point mesh).
  209. std::optional<double> scorePuppetMeshCoherence (const PuppetMeshData& data) {
  210. if (data.indices.size () < 3) {
  211. return std::nullopt;
  212. }
  213. glm::vec3 min (std::numeric_limits<float>::max ());
  214. glm::vec3 max (std::numeric_limits<float>::lowest ());
  215. const size_t vertexCount = data.positions.size () / 3;
  216. for (size_t i = 0; i < vertexCount; i++) {
  217. const glm::vec3 p (data.positions[i * 3], data.positions[i * 3 + 1], data.positions[i * 3 + 2]);
  218. min = glm::min (min, p);
  219. max = glm::max (max, p);
  220. }
  221. const double diagonal = glm::length (max - min);
  222. if (diagonal <= 0.0) {
  223. return std::nullopt;
  224. }
  225. double totalEdgeLength = 0.0;
  226. size_t edgeCount = 0;
  227. for (size_t triangle = 0; triangle + 2 < data.indices.size (); triangle += 3) {
  228. const auto vertexPosition = [&data] (size_t index) {
  229. return glm::vec3 (data.positions[index * 3], data.positions[index * 3 + 1], data.positions[index * 3 + 2]);
  230. };
  231. const glm::vec3 a = vertexPosition (data.indices[triangle]);
  232. const glm::vec3 b = vertexPosition (data.indices[triangle + 1]);
  233. const glm::vec3 c = vertexPosition (data.indices[triangle + 2]);
  234. totalEdgeLength += glm::length (a - b) + glm::length (b - c) + glm::length (c - a);
  235. edgeCount += 3;
  236. }
  237. if (edgeCount == 0) {
  238. return std::nullopt;
  239. }
  240. return (totalEdgeLength / static_cast<double> (edgeCount)) / diagonal;
  241. }
  242. // The MDLV vertex layout isn't reliably predictable from the header version number alone - the same
  243. // version (e.g. MDLV0023) has been observed with different per-vertex strides depending on how many
  244. // bone influences a given puppet part carries. So instead of a fixed version->stride table, every
  245. // plausible stride is tried against every candidate mesh header found in the file, and whichever
  246. // combination produces the most coherent triangulated mesh wins.
  247. std::optional<PuppetVertexLayout>
  248. resolvePuppetVertexLayout (const BinaryReader& reader, size_t markerSize, size_t mdlsOffset, size_t meshHeaderSize) {
  249. constexpr size_t minVertexStride = 20; // position (12 bytes) + uv (8 bytes), no bone data at all
  250. constexpr size_t maxVertexStride = 256; // generous upper bound, comfortably covers multi-bone rigs
  251. constexpr size_t strideStep = 4; // every field observed so far is a 4-byte float/uint
  252. const auto candidates = findPuppetMeshBlockCandidates (reader, markerSize, mdlsOffset, meshHeaderSize);
  253. std::optional<PuppetVertexLayout> best;
  254. double bestScore = std::numeric_limits<double>::max ();
  255. for (const auto& block : candidates) {
  256. for (size_t stride = minVertexStride; stride <= maxVertexStride; stride += strideStep) {
  257. const auto data = readPuppetMeshData (reader, block, meshHeaderSize, stride);
  258. if (!data.has_value ()) {
  259. continue;
  260. }
  261. const auto score = scorePuppetMeshCoherence (*data);
  262. if (!score.has_value ()) {
  263. continue;
  264. }
  265. if (*score >= bestScore) {
  266. continue;
  267. }
  268. bestScore = *score;
  269. best = PuppetVertexLayout { .block = block,
  270. .vertexStride = stride,
  271. .uvOffset = stride - sizeof (GLfloat) * 2 };
  272. }
  273. }
  274. return best;
  275. }
  276. }
  277. CImage::ResolvedTransform CImage::localTransform (const Object& object) {
  278. glm::vec3 origin = object.origin->value->getVec3 ();
  279. glm::vec3 scale = glm::vec3 (1.0f);
  280. float angle = 0.0f;
  281. if (object.is<Image> ()) {
  282. const auto* image = object.as<Image> ();
  283. scale = image->scale->value->getVec3 ();
  284. angle = image->angles->value->getVec3 ().z;
  285. // cropoffset is already baked into the object's origin, adding it again shifts the layer
  286. } else if (object.is<Text> ()) {
  287. const auto* text = object.as<Text> ();
  288. scale = text->scale->value->getVec3 ();
  289. } else {
  290. scale = object.groupScale->value->getVec3 ();
  291. angle = object.groupAngles->value->getVec3 ().z;
  292. }
  293. return { origin, scale, angle };
  294. }
  295. CImage::ResolvedTransform CImage::resolveTransform (const Object& object) const {
  296. constexpr int kMaxParentDepth = 32;
  297. // Walk up the parent chain leaf-first, bounded by kMaxParentDepth to guard
  298. // against cycles. chain[0] is the requested object; the last entry is the root.
  299. const Object* chain[kMaxParentDepth + 1];
  300. int count = 0;
  301. const Object* current = &object;
  302. chain[count++] = current;
  303. while (current->parent.has_value ()) {
  304. if (count > kMaxParentDepth) {
  305. sLog.error ("Parent transform chain is too deep; possible cycle at object id=", current->id);
  306. break;
  307. }
  308. const auto* parentObject = this->getScene ().getObject (current->parent.value ());
  309. if (parentObject == nullptr) {
  310. break;
  311. }
  312. current = &parentObject->getObject ();
  313. chain[count++] = current;
  314. }
  315. // Accumulate top-down: the root's local transform is already its resolved
  316. // transform, then fold each child onto its already-resolved parent.
  317. ResolvedTransform resolved = localTransform (*chain[count - 1]);
  318. for (int i = count - 2; i >= 0; --i) {
  319. ResolvedTransform local = localTransform (*chain[i]);
  320. // scene.json's "attachment" follows a named point on the direct parent's puppet rig (see
  321. // PuppetAttachmentPoint): WE's world matrix is parentWorld * (animated bone world * point local) * childLocal
  322. // (sub_140148A20), so the point's animated angle rotates the child's offset and adds to its own angle, and the
  323. // mesh turns around the object origin
  324. glm::vec3 anchorOrigin = resolved.origin;
  325. float anchorAngle = resolved.angle;
  326. glm::vec2 anchorScale = { 1.0f, 1.0f };
  327. if (chain[i]->attachment.has_value () && chain[i]->parent.has_value ()) {
  328. const auto* parentCObject = this->getScene ().getObject (chain[i]->parent.value ());
  329. if (const auto* parentImage = dynamic_cast<const CImage*> (parentCObject); parentImage != nullptr) {
  330. if (const auto meshTransform = parentImage->getAttachmentPointMeshTransform (*chain[i]->attachment);
  331. meshTransform.has_value ()) {
  332. const glm::vec2 meshOffset = rotateVec2 (
  333. { meshTransform->position.x * resolved.scale.x, meshTransform->position.y * resolved.scale.y },
  334. resolved.angle
  335. );
  336. anchorOrigin.x = resolved.origin.x + meshOffset.x;
  337. anchorOrigin.y = resolved.origin.y + meshOffset.y;
  338. anchorAngle = resolved.angle + meshTransform->angle;
  339. // the bone's own scale (possibly negative, i.e. a mirrored bone) carries into whatever
  340. // rides it, same as position/rotation
  341. anchorScale = meshTransform->scale;
  342. if (!this->m_attachmentDiagnosticLogged.contains (chain[i]->id)) {
  343. this->m_attachmentDiagnosticLogged.insert (chain[i]->id);
  344. sLog.out (
  345. "Attachment resolve for ", chain[i]->name, " (", chain[i]->id,
  346. "): point=", *chain[i]->attachment, " meshPosition=(", meshTransform->position.x, ",",
  347. meshTransform->position.y, ") boneAngleDeg=", glm::degrees (meshTransform->angle),
  348. " boneScale=(", meshTransform->scale.x, ",", meshTransform->scale.y, ") parentOrigin=(",
  349. resolved.origin.x, ",", resolved.origin.y, ") parentScale=", resolved.scale.x,
  350. " anchorOrigin=(", anchorOrigin.x, ",", anchorOrigin.y,
  351. ") anchorAngleDeg=", glm::degrees (anchorAngle)
  352. );
  353. }
  354. }
  355. }
  356. }
  357. const glm::vec2 offset
  358. = rotateVec2 ({ local.origin.x * resolved.scale.x, local.origin.y * resolved.scale.y }, anchorAngle);
  359. local.origin.x = anchorOrigin.x + offset.x;
  360. local.origin.y = anchorOrigin.y + offset.y;
  361. local.origin.z = resolved.origin.z + local.origin.z * resolved.scale.z;
  362. local.scale.x *= anchorScale.x;
  363. local.scale.y *= anchorScale.y;
  364. resolved = { local.origin, local.scale * resolved.scale, local.angle + anchorAngle };
  365. }
  366. return resolved;
  367. }
  368. CImage::CImage (Wallpapers::CScene& scene, const Image& image) :
  369. CObject (scene, image), CRenderable (scene, image, *image.model->material), ScriptableObject (scene, image),
  370. m_sceneSpacePosition (GL_NONE), m_copySpacePosition (GL_NONE), m_passSpacePosition (GL_NONE),
  371. m_texcoordCopy (GL_NONE), m_texcoordPass (GL_NONE), m_modelViewProjectionScreen (),
  372. m_modelViewProjectionPass (glm::mat4 (1.0)), m_modelViewProjectionCopy (), m_modelViewProjectionScreenInverse (),
  373. m_modelViewProjectionPassInverse (glm::inverse (m_modelViewProjectionPass)), m_modelViewProjectionCopyInverse (),
  374. m_modelMatrix (), m_viewProjectionMatrix (), m_image (image), m_pos (), m_initialized (false) {
  375. this->registerProperty ("origin", *image.origin->value);
  376. this->registerProperty ("scale", *image.scale->value);
  377. this->registerProperty ("angles", *image.angles->value);
  378. this->registerProperty ("visible", *image.visible->value);
  379. this->registerProperty ("copybackground", *image.copyBackground->value);
  380. this->registerProperty ("alpha", *image.alpha->value);
  381. this->registerProperty ("color", *image.color->value);
  382. this->registerProperty ("parallaxDepth", *image.parallaxDepth->value);
  383. this->registerProperty ("alignment", *image.alignmentName->value);
  384. this->registerEffectConstants (image.effects);
  385. // animation layers carry their own property scripts, WE runs them with the layer as thisObject (the JSON loader
  386. // sub_1401730D0 binds them to the IAnimationLayer object, sub_14026C980 lists its properties and methods)
  387. for (size_t layerIndex = 0; layerIndex < image.animationLayers.size (); layerIndex++) {
  388. const auto& layer = image.animationLayers[layerIndex];
  389. const std::string prefix = "animationlayers[" + std::to_string (layerIndex) + "].";
  390. for (const auto& [name, setting] :
  391. { std::pair { "visible", &layer->visible }, std::pair { "rate", &layer->rate },
  392. std::pair { "blend", &layer->blend } }) {
  393. if (*setting == nullptr) {
  394. continue;
  395. }
  396. this->registerProperty (prefix + name, *(*setting)->value);
  397. scene.getScriptEngine ().setThisObjectFactory (
  398. this->getProperties ().at (prefix + name).key, [this, layerIndex] (Scripting::ScriptEngine& engine) {
  399. return Scripting::Adapters::makeAnimationLayerHandle (engine, *this, layerIndex);
  400. }
  401. );
  402. }
  403. }
  404. auto scene_width = static_cast<float> (scene.getWidth ());
  405. auto scene_height = static_cast<float> (scene.getHeight ());
  406. const auto transform = this->resolveTransform (this->getImage ());
  407. glm::vec3 origin = transform.origin;
  408. glm::vec2 size = this->getSize ();
  409. glm::vec3 scale = transform.scale;
  410. try {
  411. this->detectTexture ();
  412. } catch (const Assets::AssetLoadException& e) {
  413. // live WE loads the scene anyway and draws the layer empty
  414. sLog.error ("Image ", image.id, " has no texture, drawing it empty: ", e.what ());
  415. }
  416. const bool placeholderTexture = this->m_texture == nullptr;
  417. if (this->m_texture == nullptr) {
  418. if (this->m_image.model->solidlayer && size.x == 0.0f && size.y == 0.0f) {
  419. size.x = static_cast<float> (scene.getCanvasWidth ());
  420. size.y = static_cast<float> (scene.getCanvasHeight ());
  421. }
  422. // TODO: create a dummy texture of correct size, fbo constructors should be enough, but this should be
  423. // properly handled
  424. // solid layers are often declared far larger than the scene, nothing samples
  425. // these buffers past the canvas so only the layout size has to stay as declared
  426. const glm::vec2 placeholderSize = { std::min (size.x, static_cast<float> (scene.getCanvasWidth ())),
  427. std::min (size.y, static_cast<float> (scene.getCanvasHeight ())) };
  428. this->m_texture = std::make_shared<CFBO> (
  429. "", TextureFormat_ARGB8888, TextureFlags_NoFlags, 1, size.x, size.y, placeholderSize.x, placeholderSize.y
  430. );
  431. }
  432. // If the wallpaper doesn't specify a size, fall back to the texture or model dimensions
  433. if ((size.x == 0.0f || size.y == 0.0f) && this->m_texture != nullptr) {
  434. size.x = static_cast<float> (this->m_texture->getRealWidth ());
  435. size.y = static_cast<float> (this->m_texture->getRealHeight ());
  436. } else if (
  437. (size.x == 0.0f || size.y == 0.0f) && this->getImage ().model->width.has_value ()
  438. && this->getImage ().model->height.has_value ()
  439. ) {
  440. size.x = static_cast<float> (this->getImage ().model->width.value ());
  441. size.y = static_cast<float> (this->getImage ().model->height.value ());
  442. }
  443. // autosize takes the size of the loaded texture (a single frame for sprite sheets) over the
  444. // declared one, or the scene's for project layers. fullscreen still wins over it
  445. if (this->getImage ().model->autosize && this->getImage ().model->projectlayer) {
  446. size = { scene_width, scene_height };
  447. } else if (
  448. this->getImage ().model->autosize && !placeholderTexture
  449. && std::dynamic_pointer_cast<const CFBO> (this->m_texture) == nullptr
  450. ) {
  451. size.x = static_cast<float> (this->m_texture->getRealWidth ());
  452. size.y = static_cast<float> (this->m_texture->getRealHeight ());
  453. }
  454. // fullscreen layers should use the whole projection's size
  455. if (this->getImage ().model->fullscreen) {
  456. size = { static_cast<float> (scene.getCanvasWidth ()), static_cast<float> (scene.getCanvasHeight ()) };
  457. origin = { scene_width / 2, scene_height / 2, 0 };
  458. }
  459. this->m_size = size;
  460. // taken after the texture/model/fullscreen fallbacks above, unsized layers would otherwise get 0x0 buffers
  461. glm::vec2 bufferSize = size;
  462. if (placeholderTexture) {
  463. bufferSize = glm::min (bufferSize, glm::vec2 (scene.getCanvasWidth (), scene.getCanvasHeight ()));
  464. }
  465. this->updateScenePosition (origin, size, scale, scene_width, scene_height);
  466. // register both FBOs into the scene
  467. std::ostringstream nameA, nameB;
  468. // WE renders layers with LIGHTING or REFLECTION unlit into _rt_imageLayerAlbedo_<id> when they have offscreen
  469. // passes and lights them last (sub_1401914B0); here the first pass is lit instead, through PRELIGHTING
  470. nameA << "_rt_imageLayerComposite_" << this->getImage ().id << "_a";
  471. nameB << "_rt_imageLayerComposite_" << this->getImage ().id << "_b";
  472. // scene.json's own "clampuvs" is a per-object override on top of whatever the base texture
  473. // asset defaults to - without it, effects that distort UVs near the edges (refraction, ripples)
  474. // can wrap around and sample the opposite edge of the buffer instead of clamping.
  475. // compose layers always clamp, their effects would otherwise wrap samples from the opposite edge
  476. const uint32_t compositeFlags = (this->getImage ().clampUVs || this->getImage ().model->passthrough)
  477. ? (this->m_texture->getFlags () | TextureFlags_ClampUVs)
  478. : this->m_texture->getFlags ();
  479. // layer buffers are 16 bit float in HDR scene rendering (sub_1401E7170)
  480. const TextureFormat layerFormat = this->getScene ().isHDR () ? TextureFormat_RGBA16161616f : TextureFormat_ARGB8888;
  481. const auto mainFBO = scene.create (
  482. nameA.str (), layerFormat, compositeFlags, 1, { bufferSize.x, bufferSize.y }, { bufferSize.x, bufferSize.y }
  483. );
  484. const auto subFBO = scene.create (
  485. nameB.str (), layerFormat, compositeFlags, 1, { bufferSize.x, bufferSize.y }, { bufferSize.x, bufferSize.y }
  486. );
  487. if (this->followsOutputSize ()) {
  488. scene.followOutputSize (mainFBO, 1);
  489. scene.followOutputSize (subFBO, 1);
  490. }
  491. this->m_currentMainFBO = this->m_mainFBO = mainFBO;
  492. this->m_currentSubFBO = this->m_subFBO = subFBO;
  493. GLfloat sceneSpacePosition[] = { this->m_pos.x, this->m_pos.y, 0.0f, this->m_pos.x, this->m_pos.w, 0.0f,
  494. this->m_pos.z, this->m_pos.y, 0.0f, this->m_pos.z, this->m_pos.y, 0.0f,
  495. this->m_pos.x, this->m_pos.w, 0.0f, this->m_pos.z, this->m_pos.w, 0.0f };
  496. float width = 1.0f;
  497. float height = 1.0f;
  498. if (this->getTexture ()->isAnimated ()) {
  499. // animated images use different coordinates as they're essentially a texture atlas
  500. width = static_cast<float> (this->getTexture ()->getRealWidth ())
  501. / static_cast<float> (this->getTexture ()->getTextureWidth (0));
  502. height = static_cast<float> (this->getTexture ()->getRealHeight ())
  503. / static_cast<float> (this->getTexture ()->getTextureHeight (0));
  504. } else if (
  505. this->getTexture () != nullptr
  506. && (this->getTexture ()->getTextureWidth (0) != this->getTexture ()->getRealWidth ()
  507. || this->getTexture ()->getTextureHeight (0) != this->getTexture ()->getRealHeight ())
  508. ) {
  509. // Account for padding in non-power-of-two textures: clamp UVs to the real content
  510. width = static_cast<float> (this->getTexture ()->getRealWidth ())
  511. / static_cast<float> (this->getTexture ()->getTextureWidth (0));
  512. height = static_cast<float> (this->getTexture ()->getRealHeight ())
  513. / static_cast<float> (this->getTexture ()->getTextureHeight (0));
  514. }
  515. float x = 0.0f;
  516. float y = 0.0f;
  517. if (this->getTexture ()->isAnimated ()) {
  518. // animations should be copied completely
  519. x = 0.0f;
  520. y = 0.0f;
  521. width = 1.0f;
  522. height = 1.0f;
  523. }
  524. GLfloat realWidth = size.x;
  525. GLfloat realHeight = size.y;
  526. GLfloat realX = 0.0;
  527. GLfloat realY = 0.0;
  528. if (this->getImage ().model->passthrough) {
  529. // Passthrough shaders fill the destination FBO from texcoords and sample the scene using positions.
  530. // Keep the destination quad full-screen in local FBO space, but pass scene-space positions through.
  531. x = 0.0f;
  532. y = 0.0f;
  533. width = 1.0f;
  534. height = 1.0f;
  535. realX = this->m_pos.x;
  536. realY = this->m_pos.w;
  537. realWidth = this->m_pos.z;
  538. realHeight = this->m_pos.y;
  539. if (this->getImage ().model->fullscreen) {
  540. realX = -1.0;
  541. realY = -1.0;
  542. realWidth = 1.0;
  543. realHeight = 1.0;
  544. }
  545. }
  546. GLfloat texcoordCopy[] = { x, height, x, y, width, height, width, height, x, y, width, y };
  547. GLfloat copySpacePosition[] = { realX, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realHeight, 0.0f,
  548. realWidth, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realY, 0.0f };
  549. GLfloat texcoordPass[] = { 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f };
  550. GLfloat passSpacePosition[]
  551. = { -1.0, 1.0, 0.0f, -1.0, -1.0, 0.0f, 1.0, 1.0, 0.0f, 1.0, 1.0, 0.0f, -1.0, -1.0, 0.0f, 1.0, -1.0, 0.0f };
  552. glGenBuffers (1, &this->m_sceneSpacePosition);
  553. glBindBuffer (GL_ARRAY_BUFFER, this->m_sceneSpacePosition);
  554. glBufferData (GL_ARRAY_BUFFER, sizeof (sceneSpacePosition), sceneSpacePosition, GL_STATIC_DRAW);
  555. glGenBuffers (1, &this->m_copySpacePosition);
  556. glBindBuffer (GL_ARRAY_BUFFER, this->m_copySpacePosition);
  557. glBufferData (GL_ARRAY_BUFFER, sizeof (copySpacePosition), copySpacePosition, GL_STATIC_DRAW);
  558. glGenBuffers (1, &this->m_passSpacePosition);
  559. glBindBuffer (GL_ARRAY_BUFFER, this->m_passSpacePosition);
  560. glBufferData (GL_ARRAY_BUFFER, sizeof (passSpacePosition), passSpacePosition, GL_STATIC_DRAW);
  561. glGenBuffers (1, &this->m_texcoordCopy);
  562. glBindBuffer (GL_ARRAY_BUFFER, this->m_texcoordCopy);
  563. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoordCopy), texcoordCopy, GL_STATIC_DRAW);
  564. glGenBuffers (1, &this->m_texcoordPass);
  565. glBindBuffer (GL_ARRAY_BUFFER, this->m_texcoordPass);
  566. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoordPass), texcoordPass, GL_STATIC_DRAW);
  567. this->m_hasPuppetMesh = this->loadPuppetMesh (size);
  568. this->m_sceneCenter
  569. = glm::vec3 ((this->m_pos.x + this->m_pos.z) / 2.0f, (this->m_pos.y + this->m_pos.w) / 2.0f, 0.0f);
  570. this->m_modelViewProjectionScreen = this->getViewProjection ();
  571. // must match m_modelViewProjectionScreen - updateScreenSpacePosition() may skip recomputing it
  572. this->m_modelViewProjectionScreenInverse = glm::inverse (this->m_modelViewProjectionScreen);
  573. this->updateEffectTextureProjection ();
  574. if (this->getImage ().model->passthrough) {
  575. this->m_modelViewProjectionCopy = this->m_modelViewProjectionScreen;
  576. } else {
  577. this->m_modelViewProjectionCopy = glm::ortho<float> (0.0, size.x, 0.0, size.y);
  578. }
  579. this->m_modelViewProjectionCopyInverse = glm::inverse (this->m_modelViewProjectionCopy);
  580. this->m_modelMatrix = glm::ortho<float> (0.0, size.x, 0.0, size.y);
  581. this->m_viewProjectionMatrix = glm::mat4 (1.0);
  582. // marks the texture as used, which starts video playback if it isn't already
  583. this->m_texture->incrementUsageCount ();
  584. }
  585. void CImage::updateTextures () const {
  586. this->getTexture ()->update ();
  587. for (const auto* pass : this->m_passes) {
  588. pass->updatePlaybackTextures ();
  589. }
  590. }
  591. void CImage::renderPassthroughChildren (const std::shared_ptr<const CFBO>& buffer) {
  592. // the buffer holds the layer's quad (m_pos, copy pass texcoords: v = 1 at m_pos.y), children land in it through
  593. // model = inverse (layer world), view = identity, ortho (-w/2, w/2, -h/2, h/2, -1000, 1000) (sub_1401ECB20).
  594. // Fullscreen layers keep the scene's camera
  595. glm::mat4 transform (1.0f);
  596. glm::mat4 viewProjection = this->getScene ().getWorldViewProjection ();
  597. if (!this->getImage ().model->fullscreen) {
  598. const glm::vec3 center ((this->m_pos.x + this->m_pos.z) / 2.0f, (this->m_pos.y + this->m_pos.w) / 2.0f, 0.0f);
  599. const glm::vec3 halfExtent (
  600. (this->m_pos.z - this->m_pos.x) / 2.0f, (this->m_pos.y - this->m_pos.w) / 2.0f, 1000.0f
  601. );
  602. transform = glm::inverse (glm::scale (glm::translate (this->m_modelViewProjectionScreen, center), halfExtent));
  603. // lights skip the model stack (volumetricsfront.vert only has g_ViewProjectionMatrix), so they see the bare
  604. // ortho with the scene's y flip: their world position lands in the layer as if the layer sat at the origin
  605. const glm::vec2 size = this->getSize ();
  606. viewProjection = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
  607. * glm::ortho (-size.x / 2.0f, size.x / 2.0f, -size.y / 2.0f, size.y / 2.0f, -1000.0f, 1000.0f);
  608. }
  609. this->getScene ().renderPassthroughChildren (
  610. this->getId (),
  611. {
  612. .fbo = buffer,
  613. .transform = transform,
  614. .alphaMax = !this->m_image.copyBackground->value->getBool (),
  615. .viewProjection = viewProjection,
  616. }
  617. );
  618. }
  619. bool CImage::hitTest (const glm::vec2& ndc) {
  620. if (this->getImage ().model->fullscreen) {
  621. return true;
  622. }
  623. this->updateScreenSpacePosition ();
  624. const glm::vec3 center ((this->m_pos.x + this->m_pos.z) / 2.0f, (this->m_pos.y + this->m_pos.w) / 2.0f, 0.0f);
  625. const glm::vec2 half (
  626. std::abs (this->m_pos.z - this->m_pos.x) / 2.0f, std::abs (this->m_pos.w - this->m_pos.y) / 2.0f
  627. );
  628. return Wallpapers::CScene::quadContainsPoint (
  629. glm::translate (this->m_modelViewProjectionScreen, center), half, ndc
  630. );
  631. }
  632. glm::vec2 CImage::cursorLocalPosition (const glm::vec2& ndc) {
  633. this->updateScreenSpacePosition ();
  634. const glm::vec3 center ((this->m_pos.x + this->m_pos.z) / 2.0f, (this->m_pos.y + this->m_pos.w) / 2.0f, 0.0f);
  635. const auto point
  636. = Wallpapers::CScene::quadPlanePoint (glm::translate (this->m_modelViewProjectionScreen, center), ndc);
  637. const glm::vec2 extent (this->m_pos.z - this->m_pos.x, this->m_pos.y - this->m_pos.w);
  638. if (!point.has_value () || extent.x == 0.0f || extent.y == 0.0f) {
  639. return glm::vec2 (0.0f);
  640. }
  641. // m_pos runs y down from the top edge (.w), x from the texture's left edge (.x)
  642. const glm::vec2 u (
  643. (point->x + center.x - this->m_pos.x) / extent.x, (point->y + center.y - this->m_pos.w) / extent.y
  644. );
  645. return u * this->m_displaySize;
  646. }
  647. CImage::~CImage () {
  648. this->m_texture->decrementUsageCount ();
  649. // delete passes first as they depend on the image's data
  650. for (auto* pass : this->m_allPasses.empty () ? this->m_passes : this->m_allPasses) {
  651. delete pass;
  652. }
  653. this->m_passes.clear ();
  654. this->m_allPasses.clear ();
  655. glDeleteBuffers (1, &this->m_sceneSpacePosition);
  656. glDeleteBuffers (1, &this->m_copySpacePosition);
  657. glDeleteBuffers (1, &this->m_passSpacePosition);
  658. glDeleteBuffers (1, &this->m_texcoordCopy);
  659. glDeleteBuffers (1, &this->m_texcoordPass);
  660. if (this->m_puppetSpacePosition != GL_NONE) {
  661. glDeleteBuffers (1, &this->m_puppetSpacePosition);
  662. }
  663. if (this->m_puppetTexCoord != GL_NONE) {
  664. glDeleteBuffers (1, &this->m_puppetTexCoord);
  665. }
  666. if (this->m_puppetIndices != GL_NONE) {
  667. glDeleteBuffers (1, &this->m_puppetIndices);
  668. }
  669. }
  670. bool CImage::loadPuppetMesh (const glm::vec2& size) {
  671. if (!this->getImage ().model->puppet.has_value ()) {
  672. return false;
  673. }
  674. try {
  675. const auto stream = this->getScene ().getScene ().project.assetLocator->read (*this->getImage ().model->puppet);
  676. std::vector<char> data { std::istreambuf_iterator<char> (*stream), std::istreambuf_iterator<char> () };
  677. constexpr size_t markerSize = 9;
  678. constexpr size_t meshHeaderSize = sizeof (uint32_t) * 2;
  679. const std::string puppetVersion
  680. = data.size () >= markerSize ? std::string (data.data (), strlen ("MDLV0021")) : "";
  681. const size_t mdlsOffset = [&data] () -> size_t {
  682. for (size_t offset = markerSize; offset + strlen ("MDLS") < data.size (); offset++) {
  683. if (std::memcmp (data.data () + offset, "MDLS", strlen ("MDLS")) == 0) {
  684. return offset;
  685. }
  686. }
  687. return data.size ();
  688. }();
  689. auto meshBuffer = std::make_unique<char[]> (data.size ());
  690. std::copy (data.begin (), data.end (), meshBuffer.get ());
  691. const BinaryReader reader (std::make_shared<MemoryStream> (std::move (meshBuffer), data.size ()));
  692. const auto layout = resolvePuppetVertexLayout (reader, markerSize, mdlsOffset, meshHeaderSize);
  693. if (!layout.has_value ()) {
  694. sLog.error ("Could not find a usable MDLV mesh block in ", *this->getImage ().model->puppet);
  695. return false;
  696. }
  697. const auto mesh = readPuppetMeshData (reader, layout->block, meshHeaderSize, layout->vertexStride);
  698. if (!mesh.has_value ()) {
  699. sLog.error ("Could not find a usable MDLV mesh block in ", *this->getImage ().model->puppet);
  700. return false;
  701. }
  702. this->m_puppetRawPositions = mesh->positions;
  703. this->updatePuppetPositionBuffer (size);
  704. glGenBuffers (1, &this->m_puppetTexCoord);
  705. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetTexCoord);
  706. glBufferData (
  707. GL_ARRAY_BUFFER, mesh->texcoords.size () * sizeof (GLfloat), mesh->texcoords.data (), GL_STATIC_DRAW
  708. );
  709. glGenBuffers (1, &this->m_puppetIndices);
  710. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetIndices);
  711. glBufferData (
  712. GL_ELEMENT_ARRAY_BUFFER, mesh->indices.size () * sizeof (GLushort), mesh->indices.data (), GL_STATIC_DRAW
  713. );
  714. this->m_puppetIndexCount = static_cast<GLsizei> (mesh->indices.size ());
  715. sLog.out (
  716. "Loaded puppet mesh ", *this->getImage ().model->puppet, " version=", puppetVersion,
  717. " stride=", layout->vertexStride, " vertices=", this->m_puppetRawPositions.size () / 3,
  718. " indices=", this->m_puppetIndexCount
  719. );
  720. this->m_rig.clear ();
  721. this->m_puppetBlendIndices.clear ();
  722. this->m_puppetBlendWeights.clear ();
  723. this->m_puppetSkinnedPositions.clear ();
  724. const auto blend = readPuppetBlendData (reader, layout->block, meshHeaderSize, layout->vertexStride);
  725. if (blend.has_value ()) {
  726. this->m_puppetBlendIndices = blend->indices;
  727. this->m_puppetBlendWeights = blend->weights;
  728. }
  729. if (mdlsOffset < data.size () && blend.has_value ()) {
  730. try {
  731. // MDLV header: tag, flags, a second field and the mesh count (2.8.42 sub_140261880)
  732. uint32_t meshCount = 0;
  733. if (data.size () >= 21) {
  734. std::memcpy (&meshCount, data.data () + 17, sizeof (meshCount));
  735. }
  736. this->m_rig.load (data, mdlsOffset, meshCount, *this->getImage ().model->puppet);
  737. this->m_rig.addSceneLayers (this->getImage ().animationLayers);
  738. } catch (const std::exception& ex) {
  739. sLog.error (
  740. "Could not load puppet skeleton/animation from ", *this->getImage ().model->puppet, ": ",
  741. ex.what (), " (falling back to the static bind pose)"
  742. );
  743. this->m_rig.clear ();
  744. }
  745. }
  746. return true;
  747. } catch (const std::exception& ex) {
  748. sLog.error ("Could not load puppet mesh ", *this->getImage ().model->puppet, ": ", ex.what ());
  749. return false;
  750. }
  751. }
  752. void CImage::updatePuppetPositionBuffer (const glm::vec2& size) {
  753. // once an animation clip is driving the mesh, its skinned output replaces the static bind pose
  754. // as the source of truth - the bind pose (m_puppetRawPositions) is kept around unchanged, since
  755. // skinning is recomputed from it fresh every frame, not accumulated from the previous frame
  756. const auto& source
  757. = !this->m_puppetSkinnedPositions.empty () ? this->m_puppetSkinnedPositions : this->m_puppetRawPositions;
  758. if (source.empty ()) {
  759. return;
  760. }
  761. // A puppet with effects is multi-pass: its geometry pass renders into its own object-sized
  762. // intermediate FBO (see setupPasses(), the "writesToTarget" branch) using the local-canvas
  763. // m_modelViewProjectionCopy projection, and later passes composite that FBO's texture onto the
  764. // scene the normal (non-puppet) way - that first pass still needs plain local canvas coordinates
  765. // (0..size, matching its texcoords) to line up with that projection. Only a puppet with no
  766. // effects skips straight from its one and only pass to the shared scene FBO, using
  767. // m_modelViewProjectionScreen (see setupPasses()) - that path needs vertices already in the same
  768. // absolute scene-space coordinates uploadGeometryBuffers() bakes into sceneSpacePosition for a
  769. // normal quad, or every vertex renders shifted by a constant offset equal to wherever this object
  770. // should have been, reading as the whole mesh floating somewhere else on screen entirely.
  771. const bool bakeScenePosition = this->m_passes.size () <= 1 || this->m_puppetMeshLast;
  772. std::vector<GLfloat> positions;
  773. positions.reserve (source.size ());
  774. for (size_t index = 0; index + 2 < source.size (); index += 3) {
  775. const float localX = size.x / 2.0f + source[index];
  776. const float localY = size.y / 2.0f - source[index + 1];
  777. if (bakeScenePosition) {
  778. // maps the local-canvas coordinate onto this object's scene-space bounding box; m_pos.w is
  779. // its bottom edge (m_pos.y is the top, see updateScenePosition()) so localY==0 has to land
  780. // there, not on m_pos.y, or the puppet renders vertically flipped
  781. positions.push_back (this->m_pos.x + localX * this->m_puppetScale.x);
  782. positions.push_back (this->m_pos.w + localY * this->m_puppetScale.y);
  783. } else {
  784. positions.push_back (localX);
  785. positions.push_back (localY);
  786. }
  787. // raw .mdl Z values aren't used by this engine's orthographic puppet compositing (depth test
  788. // is disabled for puppets; layering comes from draw order + alpha blending) - and glm::ortho's
  789. // clip.z = -localZ has no near/far normalization, so a puppet's real mesh depth (tens of units)
  790. // would get clipped outside [-1,1] and lose most of the mesh. Zero it instead.
  791. positions.push_back (0.0f);
  792. }
  793. // skip the constructor's pre-setup() call, where m_passes/m_pos/m_puppetScale aren't resolved yet
  794. if (!this->m_puppetPositionDiagnosticLogged && !this->m_passes.empty ()) {
  795. this->m_puppetPositionDiagnosticLogged = true;
  796. glm::vec3 boundsMin (std::numeric_limits<float>::max ());
  797. glm::vec3 boundsMax (std::numeric_limits<float>::lowest ());
  798. for (size_t i = 0; i + 2 < positions.size (); i += 3) {
  799. const glm::vec3 p (positions[i], positions[i + 1], positions[i + 2]);
  800. boundsMin = glm::min (boundsMin, p);
  801. boundsMax = glm::max (boundsMax, p);
  802. }
  803. sLog.out (
  804. "Puppet position bake for ", this->getImage ().name, " (", this->getId (),
  805. "): bakeScenePosition=", bakeScenePosition, " passes=", this->m_passes.size (),
  806. " vertexCount=", positions.size () / 3, " boundsMin=(", boundsMin.x, ",", boundsMin.y, ",", boundsMin.z,
  807. ") boundsMax=(", boundsMax.x, ",", boundsMax.y, ",", boundsMax.z, ")"
  808. );
  809. }
  810. if (this->m_puppetSpacePosition == GL_NONE) {
  811. glGenBuffers (1, &this->m_puppetSpacePosition);
  812. }
  813. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetSpacePosition);
  814. glBufferData (GL_ARRAY_BUFFER, positions.size () * sizeof (GLfloat), positions.data (), GL_DYNAMIC_DRAW);
  815. }
  816. PuppetActiveAnimation* CImage::findPuppetAnimationLayer (size_t serial) { return this->m_rig.findLayer (serial); }
  817. size_t CImage::getPuppetAnimationLayerCount () const { return this->m_rig.getLayerCount (); }
  818. std::optional<size_t> CImage::getPuppetAnimationLayerAt (int64_t index) const { return this->m_rig.getLayerAt (index); }
  819. std::optional<size_t> CImage::findPuppetAnimationLayerByName (const std::string& name) const {
  820. return this->m_rig.findLayerByName (name);
  821. }
  822. std::optional<size_t> CImage::createPuppetAnimationLayer (
  823. const Data::JSON::JSON& animation, const Data::JSON::JSON& config, bool autoRemove
  824. ) {
  825. return this->m_rig.createLayer (animation, config, autoRemove, this->getScene ().getScene ().project);
  826. }
  827. bool CImage::destroyPuppetAnimationLayersByName (const std::string& name) {
  828. return this->m_rig.destroyLayersByName (name);
  829. }
  830. bool CImage::destroyPuppetAnimationLayer (size_t serial) { return this->m_rig.destroyLayer (serial); }
  831. void CImage::updatePuppetPose () {
  832. if (!this->m_hasPuppetMesh || this->m_rig.bones.empty ()) {
  833. return;
  834. }
  835. if (this->getScene ().getContext ().getApp ().getContext ().settings.render.debug.noPuppetAnimation) {
  836. return;
  837. }
  838. this->m_rig.updatePose (this->puppetObjectWorld ());
  839. this->m_rig.finishEndedLayers ([this] (size_t serial) {
  840. this->getScene ().getScriptEngine ().dispatchAnimationLayerEnded (*this, serial);
  841. });
  842. }
  843. void CImage::updatePuppetSkinning () {
  844. if (!this->m_rig.poseAnimated || this->m_rig.boneModel.size () != this->m_rig.bones.size ()) {
  845. return;
  846. }
  847. const auto& worldAnimated = this->m_rig.boneModel;
  848. std::vector<glm::mat4> skinMatrices (this->m_rig.bones.size ());
  849. for (size_t i = 0; i < this->m_rig.bones.size (); i++) {
  850. skinMatrices[i] = worldAnimated[i] * this->m_rig.bones[i].inverseBindWorld;
  851. }
  852. const size_t vertexCount = this->m_puppetRawPositions.size () / 3;
  853. this->m_puppetSkinnedPositions.assign (this->m_puppetRawPositions.size (), 0.0f);
  854. for (size_t v = 0; v < vertexCount; v++) {
  855. const glm::vec4 bindPos (
  856. this->m_puppetRawPositions[v * 3], this->m_puppetRawPositions[v * 3 + 1],
  857. this->m_puppetRawPositions[v * 3 + 2], 1.0f
  858. );
  859. glm::vec3 skinned (0.0f);
  860. const glm::uvec4& indices
  861. = v < this->m_puppetBlendIndices.size () ? this->m_puppetBlendIndices[v] : glm::uvec4 (0);
  862. const glm::vec4& weights
  863. = v < this->m_puppetBlendWeights.size () ? this->m_puppetBlendWeights[v] : glm::vec4 (0.0f);
  864. for (int influence = 0; influence < 4; influence++) {
  865. const float weight = weights[influence];
  866. if (weight == 0.0f) {
  867. continue;
  868. }
  869. const uint32_t boneIndex = indices[influence];
  870. if (boneIndex >= skinMatrices.size ()) {
  871. continue;
  872. }
  873. skinned += weight * glm::vec3 (skinMatrices[boneIndex] * bindPos);
  874. }
  875. this->m_puppetSkinnedPositions[v * 3] = skinned.x;
  876. this->m_puppetSkinnedPositions[v * 3 + 1] = skinned.y;
  877. this->m_puppetSkinnedPositions[v * 3 + 2] = skinned.z;
  878. }
  879. this->updatePuppetPositionBuffer (this->m_size);
  880. }
  881. glm::mat4 CImage::puppetObjectWorld () const {
  882. // WE's bone world (image vtable slot 16, sub_1401FD3F0) also moves by the alignment offset (sub_1402066A0),
  883. // left out: the size it uses for puppets isn't traced yet
  884. return this->getScene ().objectWorldMatrix (this->getObject ());
  885. }
  886. bool CImage::hasPuppetPose () const { return this->m_rig.hasPose (); }
  887. int CImage::findPuppetBone (const std::string& name) const { return this->m_rig.findBone (name); }
  888. const glm::mat4& CImage::getPuppetBoneTransform (int bone) const { return this->m_rig.getBoneTransform (bone); }
  889. void CImage::setPuppetBoneTransform (int bone, const glm::mat4& transform) {
  890. this->m_rig.setBoneTransform (bone, transform, this->puppetObjectWorld ());
  891. }
  892. const glm::mat4& CImage::getPuppetLocalBoneTransform (int bone) const {
  893. return this->m_rig.getLocalBoneTransform (bone);
  894. }
  895. void CImage::setPuppetLocalBoneTransform (int bone, const glm::mat4& transform) {
  896. this->m_rig.setLocalBoneTransform (bone, transform, this->puppetObjectWorld ());
  897. }
  898. void CImage::applyPuppetBonePhysicsImpulse (int bone, const glm::vec3& directional, const glm::vec3& angularDegrees) {
  899. this->m_rig.applyBonePhysicsImpulse (bone, directional, angularDegrees);
  900. }
  901. void CImage::resetPuppetBonePhysics (int bone) { this->m_rig.resetBonePhysics (bone); }
  902. std::optional<CImage::AttachmentPointTransform>
  903. CImage::getAttachmentPointMeshTransform (const std::string& name) const {
  904. if (this->m_rig.boneModel.empty ()) {
  905. return std::nullopt;
  906. }
  907. const auto it = std::find_if (
  908. this->m_rig.attachmentPoints.begin (), this->m_rig.attachmentPoints.end (),
  909. [&name] (const PuppetAttachmentPoint& point) { return point.name == name; }
  910. );
  911. if (it == this->m_rig.attachmentPoints.end ()
  912. || static_cast<size_t> (it->boneIndex) >= this->m_rig.boneModel.size ()) {
  913. return std::nullopt;
  914. }
  915. const glm::mat4 animatedWorld = this->m_rig.boneModel[it->boneIndex] * it->localTransform;
  916. const float angle = std::atan2 (animatedWorld[0][1], animatedWorld[0][0]);
  917. // scale.y = det(X,Y)/scale.x, projecting the transformed Y-basis onto what an unreflected
  918. // rotation by `angle` would have produced - comes out negative if the bone's matrix includes a
  919. // reflection (mirrored bone), instead of folding that into a bogus rotation angle
  920. const float scaleX = glm::length (glm::vec2 (animatedWorld[0]));
  921. const glm::vec2 scale = scaleX > 1e-6f
  922. ? glm::vec2 (
  923. scaleX, (animatedWorld[0][0] * animatedWorld[1][1] - animatedWorld[0][1] * animatedWorld[1][0]) / scaleX
  924. )
  925. : glm::vec2 (scaleX, glm::length (glm::vec2 (animatedWorld[1])));
  926. return AttachmentPointTransform { .position = glm::vec3 (animatedWorld[3]), .angle = angle, .scale = scale };
  927. }
  928. void CImage::setupPuppetGeometryCallback (Effects::CPass* pass) const {
  929. pass->setGeometryCallback (
  930. [this, pass] () {
  931. const GLint position = glGetAttribLocation (pass->getProgramID (), "a_Position");
  932. const GLint texCoord = glGetAttribLocation (pass->getProgramID (), "a_TexCoord");
  933. if (!this->m_puppetDrawDiagnosticLogged) {
  934. this->m_puppetDrawDiagnosticLogged = true;
  935. sLog.out (
  936. "Puppet draw setup for ", this->getImage ().name, " (", this->getId (),
  937. "): programID=", pass->getProgramID (), " a_Position=", position, " a_TexCoord=", texCoord,
  938. " indexCount=", this->m_puppetIndexCount, " size=", this->m_size.x, "x", this->m_size.y
  939. );
  940. }
  941. if (position >= 0) {
  942. glEnableVertexAttribArray (position);
  943. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetSpacePosition);
  944. glVertexAttribPointer (position, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  945. }
  946. if (texCoord >= 0) {
  947. glEnableVertexAttribArray (texCoord);
  948. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetTexCoord);
  949. glVertexAttribPointer (texCoord, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
  950. }
  951. // updatePuppetPositionBuffer flips Y when converting mesh-space positions to screen space,
  952. // which mirrors the mesh and reverses triangle winding relative to what the MDL file's index
  953. // buffer encodes - but not necessarily uniformly across the whole mesh, since real puppet
  954. // meshes aren't guaranteed to be consistently wound to begin with. Puppet content is flat 2D
  955. // art with no real backface concept, so rather than chase the "correct" winding, just never
  956. // cull it - a material requesting cullmode "normal" would otherwise silently drop whichever
  957. // subset of triangles ends up on the wrong side, which looks like patchy missing geometry.
  958. glDisable (GL_CULL_FACE);
  959. },
  960. [this, pass] () {
  961. // a mesh pass into the layer's own buffer starts it fresh, one meant for the scene may be going into a
  962. // passthrough layer's buffer right now, which holds its other children
  963. if (pass->getDestination () != this->getScene ().getFBO ()) {
  964. GLfloat previousClearColor[4] = {};
  965. glGetFloatv (GL_COLOR_CLEAR_VALUE, previousClearColor);
  966. glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
  967. glClear (GL_COLOR_BUFFER_BIT);
  968. glClearColor (
  969. previousClearColor[0], previousClearColor[1], previousClearColor[2], previousClearColor[3]
  970. );
  971. }
  972. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetIndices);
  973. glDrawElements (GL_TRIANGLES, this->m_puppetIndexCount, GL_UNSIGNED_SHORT, nullptr);
  974. if (!this->m_puppetDrawErrorChecked) {
  975. this->m_puppetDrawErrorChecked = true;
  976. GLint boundFBO = 0;
  977. GLint viewport[4] = {};
  978. GLint boundTexture = 0;
  979. glGetIntegerv (GL_DRAW_FRAMEBUFFER_BINDING, &boundFBO);
  980. glGetIntegerv (GL_VIEWPORT, viewport);
  981. glActiveTexture (GL_TEXTURE0);
  982. glGetIntegerv (GL_TEXTURE_BINDING_2D, &boundTexture);
  983. const GLenum err = glGetError ();
  984. const GLboolean cullEnabled = glIsEnabled (GL_CULL_FACE);
  985. const GLboolean depthEnabled = glIsEnabled (GL_DEPTH_TEST);
  986. const GLboolean scissorEnabled = glIsEnabled (GL_SCISSOR_TEST);
  987. const GLboolean blendEnabled = glIsEnabled (GL_BLEND);
  988. GLint cullFaceMode = 0, frontFace = 0;
  989. glGetIntegerv (GL_CULL_FACE_MODE, &cullFaceMode);
  990. glGetIntegerv (GL_FRONT_FACE, &frontFace);
  991. GLboolean colorMask[4] = {};
  992. glGetBooleanv (GL_COLOR_WRITEMASK, colorMask);
  993. sLog.out (
  994. "Puppet draw result for ", this->getImage ().name, " (", this->getId (), "): glError=", err,
  995. " boundFBO=", boundFBO, " sceneFBO=", this->getScene ().getFBO ()->getFramebuffer (), " viewport=(",
  996. viewport[0], ",", viewport[1], ",", viewport[2], ",", viewport[3], ") boundTexture=", boundTexture,
  997. " ownTextureReady=", (this->getTexture () != nullptr && this->getTexture ()->isReady ()),
  998. " ownTextureID=", (this->getTexture () != nullptr ? this->getTexture ()->getTextureID (0) : 0),
  999. " color4=(", this->getColor4 ().r, ",", this->getColor4 ().g, ",", this->getColor4 ().b, ",",
  1000. this->getColor4 ().a, ") alpha=", this->getUserAlpha (), " brightness=", this->getBrightness (),
  1001. " cullEnabled=", (int)cullEnabled, " cullFaceMode=", cullFaceMode, " frontFace=", frontFace,
  1002. " depthEnabled=", (int)depthEnabled, " scissorEnabled=", (int)scissorEnabled,
  1003. " blendEnabled=", (int)blendEnabled, " colorMask=(", (int)colorMask[0], ",", (int)colorMask[1], ",",
  1004. (int)colorMask[2], ",", (int)colorMask[3], ")"
  1005. );
  1006. }
  1007. },
  1008. [pass] () {
  1009. const GLint position = glGetAttribLocation (pass->getProgramID (), "a_Position");
  1010. const GLint texCoord = glGetAttribLocation (pass->getProgramID (), "a_TexCoord");
  1011. if (position >= 0) {
  1012. glDisableVertexAttribArray (position);
  1013. }
  1014. if (texCoord >= 0) {
  1015. glDisableVertexAttribArray (texCoord);
  1016. }
  1017. }
  1018. );
  1019. }
  1020. bool CImage::followsOutputSize () const {
  1021. // a fullscreen layer takes its texture's size (sub_1401912C0), which for the usual one is _rt_FullFrameBuffer
  1022. return this->getImage ().model->fullscreen && this->m_texture == this->getScene ().getFBO ();
  1023. }
  1024. void CImage::addEffectPasses (const ImageEffect& effect) {
  1025. const auto fboProvider = std::make_shared<FBOProvider> (this);
  1026. for (const auto& fbo : effect.effect->fbos) {
  1027. const auto created = fboProvider->create (
  1028. *fbo,
  1029. this->m_image.model->passthrough ? (this->m_texture->getFlags () | TextureFlags_ClampUVs)
  1030. : this->m_texture->getFlags (),
  1031. this->getSize ()
  1032. );
  1033. if (this->followsOutputSize ()) {
  1034. this->getScene ().followOutputSize (created, fbo->scale);
  1035. }
  1036. }
  1037. auto curEffect = effect.effect->passes.begin ();
  1038. auto endEffect = effect.effect->passes.end ();
  1039. auto curOverride = effect.passOverrides.begin ();
  1040. auto endOverride = effect.passOverrides.end ();
  1041. for (; curEffect != endEffect; ++curEffect) {
  1042. if (!(*curEffect)->material.has_value ()) {
  1043. if (!(*curEffect)->command.has_value ()) {
  1044. sLog.error ("Pass without material and command not supported");
  1045. continue;
  1046. }
  1047. if (!(*curEffect)->source.has_value ()) {
  1048. sLog.error ("Pass without material and source not supported");
  1049. continue;
  1050. }
  1051. if (!(*curEffect)->target.has_value ()) {
  1052. sLog.error ("Pass without material and target not supported");
  1053. continue;
  1054. }
  1055. if ((*curEffect)->command != Command_Copy) {
  1056. sLog.error ("Only copy command is supported for pass without material");
  1057. continue;
  1058. }
  1059. auto virtualPass
  1060. = std::make_unique<MaterialPass> (MaterialPass { .blending = BlendingMode_Normal,
  1061. .cullmode = CullingMode_Disable,
  1062. .depthtest = DepthtestMode_Disabled,
  1063. .depthwrite = DepthwriteMode_Disabled,
  1064. .shader = "commands/copy",
  1065. .textures = { { 0, *(*curEffect)->source } },
  1066. .combos = {},
  1067. .constants = {} });
  1068. const auto& config = *this->m_virtualPassess.emplace_back (std::move (virtualPass));
  1069. this->m_passes.push_back (
  1070. new CPass (*this, fboProvider, config, std::nullopt, std::nullopt, (*curEffect)->target.value ())
  1071. );
  1072. } else {
  1073. for (auto& pass : (*curEffect)->material.value ()->passes) {
  1074. const auto override = curOverride != endOverride
  1075. ? **curOverride
  1076. : std::optional<std::reference_wrapper<const ImageEffectPassOverride>> (std::nullopt);
  1077. const auto target = (*curEffect)->target.has_value ()
  1078. ? *(*curEffect)->target
  1079. : std::optional<std::reference_wrapper<std::string>> (std::nullopt);
  1080. this->m_passes.push_back (new CPass (*this, fboProvider, *pass, override, (*curEffect)->binds, target));
  1081. }
  1082. if (curOverride != endOverride) {
  1083. ++curOverride;
  1084. }
  1085. }
  1086. }
  1087. }
  1088. void CImage::setup () {
  1089. if (this->m_initialized) {
  1090. return;
  1091. }
  1092. this->m_readByOtherLayer = std::ranges::any_of (this->getScene ().getScene ().objects, [this] (const auto& object) {
  1093. return object->id != this->getImage ().id
  1094. && std::ranges::find (object->dependencies, this->getImage ().id) != object->dependencies.end ();
  1095. });
  1096. this->m_hasPassthroughChildren = this->m_image.model->passthrough
  1097. && std::ranges::any_of (this->getScene ().getScene ().objects,
  1098. [this] (const auto& object) { return object->parent == this->getImage ().id; });
  1099. // passthrough without effects has nothing to draw unless another layer reads its _rt_imageLayerComposite or it
  1100. // has children to draw into its buffer
  1101. if (this->m_image.model->passthrough && this->m_image.effects.empty () && !this->m_readByOtherLayer
  1102. && !this->m_hasPassthroughChildren) {
  1103. return;
  1104. }
  1105. const auto& debug = this->getScene ().getContext ().getApp ().getContext ().settings.render.debug;
  1106. for (const auto& cur : this->getImage ().model->material->passes) {
  1107. this->m_passes.push_back (
  1108. new CPass (*this, std::make_shared<FBOProvider> (this), *cur, std::nullopt, std::nullopt, std::nullopt)
  1109. );
  1110. }
  1111. std::vector<const DynamicValue*> passVisibility (this->m_passes.size (), nullptr);
  1112. std::vector<bool> passFromEffect (this->m_passes.size (), false);
  1113. if (!debug.baseOnly && !this->getImage ().effects.empty ()) {
  1114. for (const auto& cur : this->m_image.effects) {
  1115. if (std::find (debug.skipEffects.begin (), debug.skipEffects.end (), static_cast<int> (cur->id))
  1116. != debug.skipEffects.end ()) {
  1117. continue;
  1118. }
  1119. const auto effectVisibility
  1120. = this->getScene ().getContext ().getApp ().getContext ().resolveEffectVisibility (
  1121. static_cast<int> (cur->id), cur->name
  1122. );
  1123. // an explicit --disable-effect/--enable-effect override wins over the scene's own visibility
  1124. if (effectVisibility.has_value () && !*effectVisibility) {
  1125. continue;
  1126. }
  1127. // scripts can toggle hidden effects at runtime; puppets can't, their mesh pass layout
  1128. // depends on the pass count
  1129. const bool followsVisibility = !effectVisibility.has_value () && !this->m_hasPuppetMesh;
  1130. if (!followsVisibility && !effectVisibility.has_value () && !cur->visible->value->getBool ()) {
  1131. continue;
  1132. }
  1133. const DynamicValue* visibleValue = followsVisibility ? cur->visible->value.get () : nullptr;
  1134. const size_t firstEffectPass = this->m_passes.size ();
  1135. try {
  1136. this->addEffectPasses (*cur);
  1137. } catch (const std::exception& e) {
  1138. if (visibleValue == nullptr || visibleValue->getBool ()) {
  1139. throw;
  1140. }
  1141. for (size_t i = firstEffectPass; i < this->m_passes.size (); i++) {
  1142. delete this->m_passes[i];
  1143. }
  1144. this->m_passes.resize (firstEffectPass);
  1145. sLog.error (
  1146. "Dropping hidden effect ", cur->id, " (", cur->name, ") on ", this->getImage ().name, ": ",
  1147. e.what ()
  1148. );
  1149. continue;
  1150. }
  1151. passVisibility.resize (this->m_passes.size (), visibleValue);
  1152. passFromEffect.resize (this->m_passes.size (), true);
  1153. }
  1154. }
  1155. const size_t passCountBeforeTrailingPasses = this->m_passes.size ();
  1156. if (!debug.baseOnly) {
  1157. const auto magentaCompositeTint = findMagentaCompositeTint (this->m_image, debug.skipEffects);
  1158. if (magentaCompositeTint.has_value ()) {
  1159. auto tintOverride = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  1160. .id = -1,
  1161. .combos = {
  1162. { "BLENDMODE", 30 },
  1163. },
  1164. .constants = {},
  1165. .textures = {},
  1166. });
  1167. tintOverride->constants.emplace ("color", UserSettingBuilder::fromValue (magentaCompositeTint.value ()));
  1168. tintOverride->constants.emplace ("alpha", UserSettingBuilder::fromValue (1.0f));
  1169. this->m_materials.compatibilityMaterials.emplace_back (
  1170. MaterialParser::load (this->getScene ().getScene ().project, "materials/effects/tint.json")
  1171. );
  1172. this->m_materials.compatibilityOverrides.emplace_back (std::move (tintOverride));
  1173. this->m_passes.push_back (new CPass (
  1174. *this, std::make_shared<FBOProvider> (this),
  1175. **this->m_materials.compatibilityMaterials.back ()->passes.begin (),
  1176. *this->m_materials.compatibilityOverrides.back (), std::nullopt, std::nullopt
  1177. ));
  1178. }
  1179. }
  1180. const int colorBlendMode = this->m_image.colorBlendMode->value->getInt ();
  1181. // WE keeps the result of a layer another one reads in _a and only copies it to the screen from there,
  1182. // drawing the last effect pass straight to the screen would leave _a one pass behind (or empty)
  1183. const bool copyForReaders = this->m_readByOtherLayer && this->getImage ().visible->value->getBool ();
  1184. // fog sends every layer through its buffer and a FOG_COMPUTED composite (sub_1401E6F50, sub_1401EBBC0)
  1185. const bool fog = this->getScene ().hasDistanceFog () || this->getScene ().hasHeightFog ();
  1186. this->m_fogPass = nullptr;
  1187. // children go into the layer's buffer, which then needs a composite onto the scene even without effects
  1188. // (sub_1401E8AA0 with children, sub_140208670)
  1189. if (!debug.baseOnly && (colorBlendMode > 0 || copyForReaders || fog || this->m_hasPassthroughChildren)) {
  1190. // scenes from version 3 on composite with genericimage4, the one with fog (sub_1401EBBC0)
  1191. const auto& project = this->getScene ().getScene ().project;
  1192. this->m_materials.colorBlending.material = MaterialParser::load (
  1193. project,
  1194. project.sceneVersion >= 3 ? "materials/util/effectpassthrough_4.json"
  1195. : "materials/util/effectpassthrough.json"
  1196. );
  1197. ComboMap combos;
  1198. if (colorBlendMode > 0) {
  1199. combos.emplace ("BLENDMODE", colorBlendMode);
  1200. }
  1201. if (fog) {
  1202. combos.emplace ("FOG_COMPUTED", 1);
  1203. }
  1204. this->m_materials.colorBlending.override = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  1205. .id = -1,
  1206. .combos = combos,
  1207. .constants = {},
  1208. .textures = {},
  1209. });
  1210. this->m_passes.push_back (new CPass (
  1211. *this, std::make_shared<FBOProvider> (this), **this->m_materials.colorBlending.material->passes.begin (),
  1212. *this->m_materials.colorBlending.override, std::nullopt, std::nullopt
  1213. ));
  1214. // the layer buffer already holds color and alpha, WE draws this composite with a white renderer color
  1215. // (sub_1401E8AA0 sets renderer +288..+300 to 1 before it)
  1216. this->m_passes.back ()->setNeutralColor (true);
  1217. if (fog) {
  1218. this->m_fogPass = this->m_passes.back ();
  1219. }
  1220. }
  1221. if (this->m_hasPuppetMesh && !this->m_passes.empty ()) {
  1222. this->m_puppetMeshPass = this->m_passes.front ();
  1223. this->m_puppetMeshLast = this->m_passes.size () == 1;
  1224. // effect masks are laid out over the source texture, so effects run on the flat texture first
  1225. // and the warped mesh is drawn last, sampling their output
  1226. const auto& materialPasses = this->getImage ().model->material->passes;
  1227. const bool hasTrailingPasses = this->m_passes.size () != passCountBeforeTrailingPasses;
  1228. if (this->m_passes.size () > 1 && !hasTrailingPasses && materialPasses.size () == 1
  1229. && materialPasses.front ()->constants.empty ()) {
  1230. const auto& base = *materialPasses.front ();
  1231. const auto& config = *this->m_virtualPassess.emplace_back (
  1232. std::make_unique<MaterialPass> (MaterialPass {
  1233. .blending = base.blending,
  1234. .cullmode = base.cullmode,
  1235. .depthtest = base.depthtest,
  1236. .depthwrite = base.depthwrite,
  1237. .shader = base.shader,
  1238. .textures = {},
  1239. .usertextures = {},
  1240. .combos = base.combos,
  1241. .constants = {},
  1242. })
  1243. );
  1244. this->m_puppetMeshPass = new CPass (
  1245. *this, std::make_shared<FBOProvider> (this), config, std::nullopt, std::nullopt, std::nullopt
  1246. );
  1247. this->m_passes.push_back (this->m_puppetMeshPass);
  1248. this->m_puppetMeshLast = true;
  1249. }
  1250. }
  1251. passVisibility.resize (this->m_passes.size (), nullptr);
  1252. passFromEffect.resize (this->m_passes.size (), false);
  1253. for (size_t i = 0; i < this->m_passes.size (); i++) {
  1254. this->m_allPassStates.push_back (
  1255. { passVisibility[i], this->m_passes[i]->getBlendingMode (), passFromEffect[i] }
  1256. );
  1257. }
  1258. this->m_allPasses = this->m_passes;
  1259. CRenderable::setup ();
  1260. this->rebuildActivePasses ();
  1261. this->m_initialized = true;
  1262. }
  1263. bool CImage::effectVisibilityChanged () const {
  1264. for (size_t i = 0; i < this->m_allPassStates.size (); i++) {
  1265. const auto* visible = this->m_allPassStates[i].visible;
  1266. if (visible != nullptr && visible->getBool () != this->m_activePassMask[i]) {
  1267. return true;
  1268. }
  1269. }
  1270. return false;
  1271. }
  1272. void CImage::rebuildActivePasses () {
  1273. this->m_passes.clear ();
  1274. this->m_activePassMask.assign (this->m_allPasses.size (), false);
  1275. this->m_hasActiveEffectPass = false;
  1276. for (size_t i = 0; i < this->m_allPasses.size (); i++) {
  1277. const auto& state = this->m_allPassStates[i];
  1278. this->m_allPasses[i]->setBlendingMode (state.blending);
  1279. if (state.visible == nullptr || state.visible->getBool ()) {
  1280. this->m_activePassMask[i] = true;
  1281. this->m_hasActiveEffectPass |= state.fromEffect;
  1282. this->m_passes.push_back (this->m_allPasses[i]);
  1283. }
  1284. }
  1285. // if there's more than one pass the blendmode has to be moved from the beginning to the end
  1286. if (this->m_passes.size () > 1) {
  1287. const auto first = this->m_passes.begin ();
  1288. const auto last = this->m_passes.rbegin ();
  1289. (*last)->setBlendingMode ((*first)->getBlendingMode ());
  1290. (*first)->setBlendingMode (BlendingMode_Normal);
  1291. }
  1292. // setupPasses() ping-pongs these, every rebuild has to start from the same pair
  1293. this->m_currentMainFBO = this->m_mainFBO;
  1294. this->m_currentSubFBO = this->m_subFBO;
  1295. this->setupPasses ();
  1296. }
  1297. void CImage::setupPasses () {
  1298. // like WE, start on whichever buffer makes the last offscreen pass land in _a, which is what other layers read
  1299. auto offscreenPasses = std::ranges::count_if (this->m_passes, [] (const Effects::CPass* pass) {
  1300. return !pass->getTarget ().has_value ();
  1301. });
  1302. this->m_passesDrawToScreen = this->shouldRenderFinalPass (true);
  1303. if (!this->m_passes.empty () && !this->m_passes.back ()->getTarget ().has_value () && this->m_passesDrawToScreen) {
  1304. offscreenPasses--;
  1305. }
  1306. if (offscreenPasses % 2 == 0) {
  1307. std::swap (this->m_currentMainFBO, this->m_currentSubFBO);
  1308. }
  1309. std::shared_ptr<const CFBO> drawTo = this->m_currentMainFBO;
  1310. std::shared_ptr<const TextureProvider> asInput = this->getTexture ();
  1311. GLuint texcoord = this->getTexCoordCopy ();
  1312. auto cur = this->m_passes.begin ();
  1313. auto end = this->m_passes.end ();
  1314. bool first = true;
  1315. bool inTargetEffectSequence = false;
  1316. std::shared_ptr<const TextureProvider> effectInput = nullptr;
  1317. for (; cur != end; ++cur) {
  1318. Effects::CPass* pass = *cur;
  1319. std::shared_ptr<const CFBO> prevDrawTo = drawTo;
  1320. bool writesToTarget = false;
  1321. const bool isFirstPass = first;
  1322. const bool isMeshPass = this->m_hasPuppetMesh && pass == this->m_puppetMeshPass;
  1323. GLuint spacePosition = isMeshPass ? this->m_puppetSpacePosition
  1324. : isFirstPass ? this->getCopySpacePosition ()
  1325. : this->getPassSpacePosition ();
  1326. const glm::mat4* projection
  1327. = (isFirstPass) ? &this->m_modelViewProjectionCopy : &this->m_modelViewProjectionPass;
  1328. const glm::mat4* inverseProjection
  1329. = (isFirstPass) ? &this->m_modelViewProjectionCopyInverse : &this->m_modelViewProjectionPassInverse;
  1330. first = false;
  1331. if (isMeshPass) {
  1332. pass->setBlendingMode (BlendingMode_Translucent);
  1333. this->setupPuppetGeometryCallback (pass);
  1334. }
  1335. pass->setModelMatrix (&this->m_modelMatrix);
  1336. pass->setViewProjectionMatrix (&this->m_viewProjectionMatrix);
  1337. pass->setLayerModelMatrix (&this->m_layerModelMatrix);
  1338. pass->setEffectTextureProjectionMatrix (
  1339. &this->m_effectTextureProjection, &this->m_effectTextureProjectionInverse
  1340. );
  1341. writesToTarget = this->configurePassTarget (pass, drawTo, asInput, effectInput, inTargetEffectSequence);
  1342. // TODO: PROPERLY CHECK IF THIS IS ALL THAT'S NEEDED
  1343. if (!writesToTarget && this->shouldRenderFinalPass (std::next (cur) == end)) {
  1344. drawTo = this->getScene ().getFBO ();
  1345. // A puppet with no effects has its geometry pass be both the first AND the last pass, drawn
  1346. // straight into the shared scene FBO below - same as any other object's final pass, so it
  1347. // needs the same screen-space projection. updatePuppetPositionBuffer() bakes this object's
  1348. // resolved scene position/scale directly into m_puppetSpacePosition (mirroring what
  1349. // uploadGeometryBuffers does for a normal quad's sceneSpacePosition), so m_modelViewProjectionScreen
  1350. // is the correct projection for those vertices now, not the local-canvas m_modelViewProjectionCopy
  1351. // this pass otherwise uses when rendering to an intermediate, object-sized target. The
  1352. // spacePosition reassignment below is a no-op for puppets either way - the puppet geometry
  1353. // callback always binds m_puppetSpacePosition itself, ignoring whatever spacePosition holds.
  1354. spacePosition = this->getSceneSpacePosition ();
  1355. projection = &this->m_modelViewProjectionScreen;
  1356. // WE's final pass inverse lands in the layer's local space (origin at its center, unscaled
  1357. // pixels); older shaders like the bundled xray.vert unproject the pointer through it
  1358. inverseProjection = &this->m_objectSpaceProjectionInverse;
  1359. }
  1360. pass->setLightingTransform (
  1361. projection == &this->m_modelViewProjectionCopy ? &this->m_lightingCopyModel : &this->m_lightingSceneModel,
  1362. &this->m_lightingNormal, &this->m_lightingViewProjection
  1363. );
  1364. // the fog composite measures in WE's world, the lighting model already maps the layer there
  1365. if (pass == this->m_fogPass && projection == &this->m_modelViewProjectionScreen) {
  1366. pass->setModelMatrix (&this->m_lightingSceneModel);
  1367. pass->setFogWorld (true);
  1368. }
  1369. pass->setDestination (drawTo);
  1370. pass->setInput (asInput);
  1371. pass->setPreviousInput (inTargetEffectSequence ? effectInput : nullptr);
  1372. pass->setPosition (spacePosition);
  1373. pass->setTexCoord (texcoord);
  1374. pass->setModelViewProjectionMatrix (projection);
  1375. pass->setModelViewProjectionMatrixInverse (inverseProjection);
  1376. // what WE's intermediate passes see as g_EffectModelViewProjectionMatrix: their geometry where the layer
  1377. // is on screen (sub_1401EBF60), the final pass keeps its own MVP
  1378. pass->setEffectModelViewProjectionMatrix (
  1379. projection == &this->m_modelViewProjectionCopy ? &this->m_effectModelViewProjectionCopy
  1380. : projection == &this->m_modelViewProjectionPass ? &this->m_effectModelViewProjectionPass
  1381. : nullptr
  1382. );
  1383. texcoord = this->getTexCoordPass ();
  1384. if (writesToTarget) {
  1385. asInput = drawTo;
  1386. drawTo = prevDrawTo;
  1387. } else {
  1388. drawTo = prevDrawTo;
  1389. this->pinpongFramebuffer (&drawTo, &asInput);
  1390. inTargetEffectSequence = false;
  1391. effectInput = nullptr;
  1392. }
  1393. }
  1394. }
  1395. bool CImage::shouldRenderFinalPass (bool isLastPass) const {
  1396. const auto& appContext = this->getScene ().getContext ().getApp ().getContext ();
  1397. const auto visibility = appContext.resolveObjectVisibility (this->getId (), this->getObject ().name);
  1398. const bool visible = visibility.value_or (this->getImage ().visible->value->getBool ());
  1399. if (!isLastPass || !visible) {
  1400. return false;
  1401. }
  1402. const auto& debug = this->getScene ().getContext ().getApp ().getContext ().settings.render.debug;
  1403. return !(debug.noSolidFinal && this->getImage ().model->solidlayer);
  1404. }
  1405. bool CImage::configurePassTarget (
  1406. Effects::CPass* pass, std::shared_ptr<const CFBO>& drawTo, const std::shared_ptr<const TextureProvider>& asInput,
  1407. std::shared_ptr<const TextureProvider>& effectInput, bool& inTargetEffectSequence
  1408. ) {
  1409. if (!pass->getTarget ().has_value ()) {
  1410. return false;
  1411. }
  1412. const std::string target = pass->getTarget ().value ();
  1413. std::shared_ptr<const CFBO> resolved = pass->getFBOProvider ()->find (target);
  1414. if (resolved == nullptr) {
  1415. resolved = this->getScene ().findFBO (target);
  1416. }
  1417. if (resolved == nullptr) {
  1418. sLog.error (
  1419. "Pass target FBO '", target, "' could not be resolved for object ", pass->getRenderable ().getId (),
  1420. " shader=", pass->getPass ().shader
  1421. );
  1422. return false;
  1423. }
  1424. if (!inTargetEffectSequence) {
  1425. effectInput = asInput;
  1426. inTargetEffectSequence = true;
  1427. }
  1428. drawTo = resolved;
  1429. return true;
  1430. }
  1431. void CImage::pinpongFramebuffer (std::shared_ptr<const CFBO>* drawTo, std::shared_ptr<const TextureProvider>* asInput) {
  1432. std::shared_ptr<const CFBO> currentMainFBO = this->m_currentMainFBO;
  1433. std::shared_ptr<const CFBO> currentSubFBO = this->m_currentSubFBO;
  1434. if (drawTo != nullptr) {
  1435. *drawTo = currentSubFBO;
  1436. }
  1437. if (asInput != nullptr) {
  1438. *asInput = currentMainFBO;
  1439. }
  1440. this->m_currentMainFBO = currentSubFBO;
  1441. this->m_currentSubFBO = currentMainFBO;
  1442. }
  1443. void CImage::render () {
  1444. if (!this->m_initialized) {
  1445. return;
  1446. }
  1447. const auto& appContext = this->getScene ().getContext ().getApp ().getContext ();
  1448. const auto visibility = appContext.resolveObjectVisibility (this->getId (), this->getObject ().name);
  1449. // a hidden layer another object reads through _rt_imageLayerComposite_<id> (xray's "bloody" twins) still
  1450. // has to fill that FBO every frame, shouldRenderFinalPass() keeps it off the screen
  1451. if (!visibility.value_or (this->getImage ().visible->value->getBool ())
  1452. && (visibility.has_value () || !this->m_isDependency)) {
  1453. return;
  1454. }
  1455. // the last pass only goes to the screen if the layer was visible when the passes were set up,
  1456. // layers a script shows later (hidden in scene.json) need that redone
  1457. if (this->effectVisibilityChanged () || this->shouldRenderFinalPass (true) != this->m_passesDrawToScreen) {
  1458. this->rebuildActivePasses ();
  1459. }
  1460. if (this->m_image.model->passthrough && !this->m_hasActiveEffectPass && !this->m_readByOtherLayer
  1461. && !this->m_hasPassthroughChildren) {
  1462. return;
  1463. }
  1464. glColorMask (true, true, true, true);
  1465. this->updateScreenSpacePosition ();
  1466. if (this->m_hasPuppetMesh) {
  1467. this->updatePuppetSkinning ();
  1468. }
  1469. #if !NDEBUG
  1470. std::string str = "Image ";
  1471. if (this->getScene ().getScene ().camera.bloom.enabled->value->getBool () && this->getId () == -1) {
  1472. str += "bloom";
  1473. } else {
  1474. str += this->getImage ().name + " (" + std::to_string (this->getId ()) + ", "
  1475. + this->getImage ().model->material->filename + ")";
  1476. }
  1477. glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, str.c_str ());
  1478. #endif /* DEBUG */
  1479. // WE (sub_140207B50): a passthrough layer without copybackground clears its buffer to 0,0,0,0 instead of
  1480. // drawing the scene behind it, so its effects start from a transparent image
  1481. const Effects::CPass* skippedBasePass = this->m_image.model->passthrough
  1482. && !this->m_image.copyBackground->value->getBool () && !this->m_allPasses.empty ()
  1483. ? this->m_allPasses.front ()
  1484. : nullptr;
  1485. auto cur = this->m_passes.begin ();
  1486. const auto end = this->m_passes.end ();
  1487. for (; cur != end; ++cur) {
  1488. // the scene keeps its own alpha, but a hidden dependency's last pass fills the _a buffer other layers
  1489. // read and needs its alpha (2938612768's audio cover drawn through the background's blend effects)
  1490. if (std::next (cur) == end && this->m_passesDrawToScreen) {
  1491. glColorMask (true, true, true, false);
  1492. }
  1493. if (*cur == skippedBasePass && std::next (cur) != end) {
  1494. (*cur)->clearDestination ();
  1495. } else {
  1496. (*cur)->render ();
  1497. }
  1498. if (this->m_hasPassthroughChildren && *cur == this->m_allPasses.front () && std::next (cur) != end) {
  1499. this->renderPassthroughChildren ((*cur)->getDestination ());
  1500. // the children's final passes leave the scene's rgb only mask behind
  1501. glColorMask (true, true, true, true);
  1502. }
  1503. }
  1504. // restore alpha writes - CParticle::render() never resets glColorMask, so leaving this
  1505. // disabled here leaks into the next frame's clear if bloom renders last
  1506. glColorMask (true, true, true, true);
  1507. #if !NDEBUG
  1508. glPopDebugGroup ();
  1509. #endif /* DEBUG */
  1510. }
  1511. const float& CImage::getBrightness () const { return this->m_image.brightness->value->getFloat (); }
  1512. const float& CImage::getUserAlpha () const { return this->getAlpha (); }
  1513. const float& CImage::getAlpha () const {
  1514. // some scenes store out-of-range alpha (e.g. 222) - it feeds mix() in blend modes, so it must stay in 0..1
  1515. m_alphaCache = glm::clamp (this->m_image.alpha->value->getFloat (), 0.0f, 1.0f);
  1516. return m_alphaCache;
  1517. }
  1518. const glm::vec3& CImage::getColor () const {
  1519. // a solid layer showing an image the user picked draws it untinted, its color only tints the plain
  1520. // white fill (checked against WE with 3765586324's local file background, black and white color alike)
  1521. const glm::vec3 color
  1522. = this->showsUserTextureOnSolidLayer () ? glm::vec3 (1.0f) : this->m_image.color->value->getVec3 ();
  1523. // the object's brightness only scales its color in HDR scene rendering (sub_140207740)
  1524. m_colorCache = color * (this->getScene ().isHDR () ? this->m_image.brightness->value->getFloat () : 1.0f);
  1525. return m_colorCache;
  1526. }
  1527. bool CImage::showsUserTextureOnSolidLayer () const {
  1528. if (!this->m_image.model->solidlayer || this->m_image.model->material->passes.empty ()) {
  1529. return false;
  1530. }
  1531. const auto& properties = this->getScene ().getScene ().project.properties;
  1532. for (const auto& [index, propertyName] : (*this->m_image.model->material->passes.begin ())->usertextures) {
  1533. const auto it = properties.find (propertyName);
  1534. if (it != properties.end () && !it->second->is<Data::Model::PropertyUserShortcut> ()
  1535. && !it->second->getString ().empty ()) {
  1536. return true;
  1537. }
  1538. }
  1539. return false;
  1540. }
  1541. const glm::vec4& CImage::getColor4 () const {
  1542. // "version" 2 materials take color and alpha together through g_Color4
  1543. m_color4Cache = glm::vec4 (this->getColor (), this->getAlpha ());
  1544. return m_color4Cache;
  1545. }
  1546. const glm::vec3& CImage::getCompositeColor () const { return this->m_image.color->value->getVec3 (); }
  1547. glm::vec2 CImage::resolveGeometrySize (float sceneWidth, float sceneHeight, glm::vec3& origin) const {
  1548. glm::vec2 size = this->getSize ();
  1549. if ((size.x == 0.0f || size.y == 0.0f) && this->m_texture != nullptr) {
  1550. size.x = static_cast<float> (this->m_texture->getRealWidth ());
  1551. size.y = static_cast<float> (this->m_texture->getRealHeight ());
  1552. } else if (
  1553. (size.x == 0.0f || size.y == 0.0f) && this->getImage ().model->width.has_value ()
  1554. && this->getImage ().model->height.has_value ()
  1555. ) {
  1556. size.x = static_cast<float> (this->getImage ().model->width.value ());
  1557. size.y = static_cast<float> (this->getImage ().model->height.value ());
  1558. }
  1559. if (this->getImage ().model->fullscreen) {
  1560. size = { static_cast<float> (this->getScene ().getCanvasWidth ()),
  1561. static_cast<float> (this->getScene ().getCanvasHeight ()) };
  1562. origin = { sceneWidth / 2.0f, sceneHeight / 2.0f, 0.0f };
  1563. }
  1564. return size;
  1565. }
  1566. void CImage::updateScenePosition (
  1567. const glm::vec3& origin, const glm::vec2& size, const glm::vec3& scale, float sceneWidth, float sceneHeight
  1568. ) {
  1569. glm::vec2 displaySize = size;
  1570. const glm::vec2 declared = this->getImage ().size;
  1571. const auto& model = *this->getImage ().model;
  1572. if (!model.fullscreen && !model.autosize && !model.puppet.has_value () && declared.x > 0.0f && declared.y > 0.0f) {
  1573. displaySize = declared;
  1574. }
  1575. const glm::vec2 scaledSize = displaySize * glm::vec2 (scale);
  1576. this->m_displaySize = displaySize;
  1577. this->m_pos.x = origin.x - (scaledSize.x / 2.0f);
  1578. this->m_pos.w = origin.y + (scaledSize.y / 2.0f);
  1579. this->m_pos.z = origin.x + (scaledSize.x / 2.0f);
  1580. this->m_pos.y = origin.y - (scaledSize.y / 2.0f);
  1581. const uint32_t alignment
  1582. = Data::Parsers::ObjectParser::parseAlignment (this->getImage ().alignmentName->value->getString ());
  1583. if (alignment & ImageAlignment_Top) {
  1584. this->m_pos.y -= scaledSize.y / 2.0f;
  1585. this->m_pos.w -= scaledSize.y / 2.0f;
  1586. } else if (alignment & ImageAlignment_Bottom) {
  1587. this->m_pos.y += scaledSize.y / 2.0f;
  1588. this->m_pos.w += scaledSize.y / 2.0f;
  1589. }
  1590. if (alignment & ImageAlignment_Left) {
  1591. this->m_pos.x += scaledSize.x / 2.0f;
  1592. this->m_pos.z += scaledSize.x / 2.0f;
  1593. } else if (alignment & ImageAlignment_Right) {
  1594. this->m_pos.x -= scaledSize.x / 2.0f;
  1595. this->m_pos.z -= scaledSize.x / 2.0f;
  1596. }
  1597. this->m_pos.x -= sceneWidth / 2.0f;
  1598. this->m_pos.y = sceneHeight / 2.0f - this->m_pos.y;
  1599. this->m_pos.z -= sceneWidth / 2.0f;
  1600. this->m_pos.w = sceneHeight / 2.0f - this->m_pos.w;
  1601. }
  1602. void CImage::uploadGeometryBuffers (const glm::vec2& size) {
  1603. GLfloat sceneSpacePosition[] = { this->m_pos.x, this->m_pos.y, 0.0f, this->m_pos.x, this->m_pos.w, 0.0f,
  1604. this->m_pos.z, this->m_pos.y, 0.0f, this->m_pos.z, this->m_pos.y, 0.0f,
  1605. this->m_pos.x, this->m_pos.w, 0.0f, this->m_pos.z, this->m_pos.w, 0.0f };
  1606. float width = 1.0f;
  1607. float height = 1.0f;
  1608. if (this->getTexture () != nullptr && !this->getTexture ()->isAnimated ()
  1609. && (this->getTexture ()->getTextureWidth (0) != this->getTexture ()->getRealWidth ()
  1610. || this->getTexture ()->getTextureHeight (0) != this->getTexture ()->getRealHeight ())) {
  1611. width = static_cast<float> (this->getTexture ()->getRealWidth ())
  1612. / static_cast<float> (this->getTexture ()->getTextureWidth (0));
  1613. height = static_cast<float> (this->getTexture ()->getRealHeight ())
  1614. / static_cast<float> (this->getTexture ()->getTextureHeight (0));
  1615. }
  1616. float x = 0.0f;
  1617. float y = 0.0f;
  1618. GLfloat realWidth = size.x;
  1619. GLfloat realHeight = size.y;
  1620. GLfloat realX = 0.0f;
  1621. GLfloat realY = 0.0f;
  1622. if (this->getImage ().model->passthrough) {
  1623. width = 1.0f;
  1624. height = 1.0f;
  1625. realX = this->m_pos.x;
  1626. realY = this->m_pos.w;
  1627. realWidth = this->m_pos.z;
  1628. realHeight = this->m_pos.y;
  1629. if (this->getImage ().model->fullscreen) {
  1630. realX = -1.0f;
  1631. realY = -1.0f;
  1632. realWidth = 1.0f;
  1633. realHeight = 1.0f;
  1634. }
  1635. }
  1636. GLfloat texcoordCopy[] = { x, height, x, y, width, height, width, height, x, y, width, y };
  1637. GLfloat copySpacePosition[] = { realX, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realHeight, 0.0f,
  1638. realWidth, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realY, 0.0f };
  1639. glBindBuffer (GL_ARRAY_BUFFER, this->m_sceneSpacePosition);
  1640. glBufferData (GL_ARRAY_BUFFER, sizeof (sceneSpacePosition), sceneSpacePosition, GL_DYNAMIC_DRAW);
  1641. glBindBuffer (GL_ARRAY_BUFFER, this->m_copySpacePosition);
  1642. glBufferData (GL_ARRAY_BUFFER, sizeof (copySpacePosition), copySpacePosition, GL_DYNAMIC_DRAW);
  1643. glBindBuffer (GL_ARRAY_BUFFER, this->m_texcoordCopy);
  1644. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoordCopy), texcoordCopy, GL_DYNAMIC_DRAW);
  1645. this->m_sceneCenter
  1646. = glm::vec3 ((this->m_pos.x + this->m_pos.z) / 2.0f, (this->m_pos.y + this->m_pos.w) / 2.0f, 0.0f);
  1647. this->m_modelViewProjectionCopy = this->getImage ().model->passthrough
  1648. ? this->m_modelViewProjectionScreen
  1649. : glm::ortho<float> (0.0, size.x, 0.0, size.y);
  1650. this->m_modelViewProjectionCopyInverse = glm::inverse (this->m_modelViewProjectionCopy);
  1651. this->m_modelMatrix = glm::ortho<float> (0.0, size.x, 0.0, size.y);
  1652. }
  1653. CImage::ResolvedTransform CImage::updateGeometryBuffers () {
  1654. auto sceneWidth = static_cast<float> (this->getScene ().getWidth ());
  1655. auto sceneHeight = static_cast<float> (this->getScene ().getHeight ());
  1656. const auto transform = this->resolveTransform (this->getImage ());
  1657. glm::vec3 origin = transform.origin;
  1658. const glm::vec3 scale = transform.scale;
  1659. const glm::vec2 size = this->resolveGeometrySize (sceneWidth, sceneHeight, origin);
  1660. this->m_size = size;
  1661. this->m_puppetScale = scale;
  1662. // must run before the puppet position buffer rebake below - it needs this frame's m_pos, not the
  1663. // previous one, to place puppet vertices at this object's actual scene position instead of its
  1664. // position from before whatever moved it (parallax, a script, an attachment point it follows, ...)
  1665. this->updateScenePosition (origin, size, scale, sceneWidth, sceneHeight);
  1666. if (this->m_pos != this->m_lastUploadedPos || size != this->m_lastUploadedGeometrySize) {
  1667. this->uploadGeometryBuffers (size);
  1668. // puppet vertices bake m_pos/scale in directly (see updatePuppetPositionBuffer), so they need
  1669. // the same "position or size changed" rebake trigger as the quad buffers above - a puppet whose
  1670. // animation is disabled (or one with no MDLA data at all, i.e. always static) would otherwise
  1671. // never get repositioned after its very first, load-time bake
  1672. if (this->m_hasPuppetMesh) {
  1673. this->updatePuppetPositionBuffer (size);
  1674. }
  1675. this->m_lastUploadedPos = this->m_pos;
  1676. this->m_lastUploadedGeometrySize = size;
  1677. }
  1678. return transform;
  1679. }
  1680. namespace {
  1681. // keeps an edge pair (e.g. m_pos.x/.z) from sliding into the on-screen part of the canvas once `offset` is added
  1682. // to both, so the image never uncovers ground it doesn't have pixels for; an image too small to cover it on this
  1683. // axis has no ground to uncover, it is an object sitting on the scene and moves freely. Canvas cropped away by the
  1684. // cover scaling is free to scroll in, WE has no clamp at all (sub_14018AAC0 adds the raw offset to the view)
  1685. float clampParallaxAxis (float offset, float edgeA, float edgeB, float visibleLow, float visibleHigh) {
  1686. const float low = std::min (edgeA, edgeB);
  1687. const float high = std::max (edgeA, edgeB);
  1688. const float maxOffset = visibleLow - low;
  1689. const float minOffset = visibleHigh - high;
  1690. if (minOffset > maxOffset) {
  1691. return offset;
  1692. }
  1693. return std::clamp (offset, minOffset, maxOffset);
  1694. }
  1695. } // namespace
  1696. glm::mat4 CImage::ancestorTiltCorrection () const {
  1697. // the quad above is placed with the parent chain folded in 2D (origin, scale, z angle). WE multiplies the full
  1698. // world matrix into the model stack instead (sub_1401E8AA0), so parents' x/y angles tilt their children too:
  1699. // map from the chain without those angles to the full one, in this centered y down space
  1700. const auto& scene = this->getScene ();
  1701. const auto localMatrix = [] (const Object& object, bool tilt) {
  1702. glm::vec3 scale = object.groupScale->value->getVec3 ();
  1703. glm::vec3 angles = object.groupAngles->value->getVec3 ();
  1704. if (object.is<Image> ()) {
  1705. scale = object.as<Image> ()->scale->value->getVec3 ();
  1706. angles = object.as<Image> ()->angles->value->getVec3 ();
  1707. } else if (object.is<Particle> ()) {
  1708. scale = object.as<Particle> ()->scale->value->getVec3 ();
  1709. angles = object.as<Particle> ()->angles->value->getVec3 ();
  1710. } else if (object.is<Text> ()) {
  1711. scale = object.as<Text> ()->scale->value->getVec3 ();
  1712. }
  1713. glm::mat4 local = glm::translate (glm::mat4 (1.0f), object.origin->value->getVec3 ());
  1714. local = glm::rotate (local, angles.z, glm::vec3 (0.0f, 0.0f, 1.0f));
  1715. if (tilt) {
  1716. local = glm::rotate (local, angles.y, glm::vec3 (0.0f, 1.0f, 0.0f));
  1717. local = glm::rotate (local, angles.x, glm::vec3 (1.0f, 0.0f, 0.0f));
  1718. }
  1719. return std::pair { glm::scale (local, scale), angles.x != 0.0f || angles.y != 0.0f };
  1720. };
  1721. glm::mat4 full (1.0f);
  1722. glm::mat4 flat (1.0f);
  1723. bool tilted = false;
  1724. const Object* current = &this->getImage ();
  1725. for (int depth = 0; current->parent.has_value () && depth < 64; depth++) {
  1726. // attachments follow a puppet bone, which the folded chain resolves on its own
  1727. if (current->attachment.has_value ()) {
  1728. return glm::mat4 (1.0f);
  1729. }
  1730. const CObject* parent = scene.getObject (current->parent.value ());
  1731. if (parent == nullptr) {
  1732. break;
  1733. }
  1734. current = &parent->getObject ();
  1735. const auto [withTilt, hasTilt] = localMatrix (*current, true);
  1736. full = withTilt * full;
  1737. flat = localMatrix (*current, false).first * flat;
  1738. tilted |= hasTilt;
  1739. }
  1740. if (!tilted) {
  1741. return glm::mat4 (1.0f);
  1742. }
  1743. const glm::mat4 toScreen = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
  1744. * glm::translate (glm::mat4 (1.0f), glm::vec3 (-scene.getWidth () / 2.0f, -scene.getHeight () / 2.0f, 0.0f));
  1745. return toScreen * full * glm::inverse (flat) * glm::inverse (toScreen);
  1746. }
  1747. void CImage::updateScreenSpacePosition () {
  1748. const ResolvedTransform transform = this->updateGeometryBuffers ();
  1749. // angles are already in radians from scene.json. WE's Rz * Ry * Rx seen through the y flip of this space is
  1750. // Rz (-z) * Ry (y) * Rx (-x) (see CParticle.cpp). Only the object's own x/y angles, the parent chain folds z only
  1751. const float angle = transform.angle;
  1752. const glm::vec3 ownAngles = this->getImage ().angles->value->getVec3 ();
  1753. // origin z only shows through a perspective camera, the ortho one keeps -2000..2000 like WE
  1754. glm::mat4 rotModel = glm::translate (glm::mat4 (1.0f), glm::vec3 (0.0f, 0.0f, transform.origin.z));
  1755. if (angle != 0.0f || ownAngles.x != 0.0f || ownAngles.y != 0.0f) {
  1756. rotModel = glm::translate (rotModel, this->m_sceneCenter);
  1757. rotModel = glm::rotate (rotModel, -angle, glm::vec3 (0.0f, 0.0f, 1.0f));
  1758. rotModel = glm::rotate (rotModel, ownAngles.y, glm::vec3 (0.0f, 1.0f, 0.0f));
  1759. rotModel = glm::rotate (rotModel, -ownAngles.x, glm::vec3 (1.0f, 0.0f, 0.0f));
  1760. rotModel = glm::translate (rotModel, -this->m_sceneCenter);
  1761. }
  1762. rotModel = this->ancestorTiltCorrection () * rotModel;
  1763. glm::mat4 mvp = this->getViewProjection () * rotModel;
  1764. const bool fullscreen = this->getImage ().model->fullscreen;
  1765. const auto& camera = this->getScene ().getCamera ();
  1766. // WE draws fullscreen layers with an identity transform, camera movement and parallax don't reach them
  1767. if (fullscreen) {
  1768. mvp = camera.getFullscreenProjection ();
  1769. } else if (camera.isPerspective () && !this->m_hasPuppetMesh) {
  1770. // 3D scenes: the quad (size in world units) goes through the scene camera with the image's world matrix like
  1771. // any other object (sub_1401E8AA0), "perspective" layers through their own camera. The vertices here are laid
  1772. // out in the 2D scene space, this takes them back to the object's own space first. WE's quad is the declared
  1773. // size (+752, sub_1402066A0) whatever the texture size, like the 2D layout
  1774. const glm::vec2 size = this->m_displaySize;
  1775. const glm::vec2 extent (this->m_pos.z - this->m_pos.x, this->m_pos.w - this->m_pos.y);
  1776. if (extent.x != 0.0f && extent.y != 0.0f) {
  1777. const glm::vec3 center (
  1778. (this->m_pos.x + this->m_pos.z) / 2.0f, (this->m_pos.y + this->m_pos.w) / 2.0f, 0.0f
  1779. );
  1780. const glm::mat4 toLocal
  1781. = glm::translate (glm::scale (glm::mat4 (1.0f), glm::vec3 (size / extent, 0.0f)), -center);
  1782. const glm::mat4 viewProjection = this->getImage ().perspective->value->getBool ()
  1783. ? camera.getPerspectiveLayerViewProjection ()
  1784. : this->getScene ().getWorldViewProjection ();
  1785. mvp = viewProjection * this->getScene ().objectWorldMatrix (this->getImage ()) * toLocal;
  1786. }
  1787. }
  1788. // CScene::renderFrame() already folds disableparallax into getParallaxDisplacement(). WE's camera parallax only
  1789. // exists in orthographic scenes (scene flags & 0x108, sub_14018AAC0)
  1790. if (this->getScene ().getScene ().camera.parallax.enabled->value->getBool () && !fullscreen
  1791. && !camera.isPerspective ()) {
  1792. const glm::vec2 offset = this->getScene ().getParallaxOffset (this->getImage ());
  1793. float x = offset.x;
  1794. float y = offset.y;
  1795. // a texture that isn't UV-clamped tiles/repeats instead of showing black past its edges (GL_REPEAT,
  1796. // see CTexture.cpp), so sliding it further is harmless and exempt from the clamp; scene.json's own
  1797. // "clampuvs" overrides the base texture's flag the same way it does for the composite FBOs above
  1798. const bool textureTiles = !this->getImage ().clampUVs && this->getTexture () != nullptr
  1799. && (this->getTexture ()->getFlags () & TextureFlags_ClampUVs) == 0;
  1800. if (this->getScene ().getContext ().getApp ().getContext ().settings.mouse.clampParallaxToImageSize
  1801. && !textureTiles) {
  1802. const glm::vec4 visible = this->getScene ().getVisibleCanvasRegion ();
  1803. x = clampParallaxAxis (x, this->m_pos.x, this->m_pos.z, visible.x, visible.y);
  1804. y = clampParallaxAxis (y, this->m_pos.y, this->m_pos.w, visible.z, visible.w);
  1805. }
  1806. // WE translates the view (sub_14018AAC0), so its offset isn't turned by the layer's own rotation. The clamp's
  1807. // correction is measured on the unrotated quad and stays inside the rotation
  1808. rotModel = glm::translate (glm::mat4 (1.0f), { offset.x, offset.y, 0.0f }) * rotModel
  1809. * glm::translate (glm::mat4 (1.0f), { x - offset.x, y - offset.y, 0.0f });
  1810. mvp = this->getViewProjection () * rotModel;
  1811. }
  1812. this->updateLightingTransform (rotModel);
  1813. // only the inverse is expensive; skip it when mvp didn't actually change
  1814. if (mvp != this->m_modelViewProjectionScreen) {
  1815. this->m_modelViewProjectionScreenInverse = glm::inverse (mvp);
  1816. }
  1817. this->m_modelViewProjectionScreen = mvp;
  1818. this->m_layerModelMatrix = this->getScene ().objectWorldMatrix (this->getImage ());
  1819. // buffer space (0..size, y = size at m_pos.y like the copy quad) onto the layer's scene quad, then the screen
  1820. const glm::vec2 bufferSize = this->m_size;
  1821. if (bufferSize.x > 0.0f && bufferSize.y > 0.0f) {
  1822. glm::mat4 bufferToScene (1.0f);
  1823. bufferToScene[0][0] = (this->m_pos.z - this->m_pos.x) / bufferSize.x;
  1824. bufferToScene[1][1] = (this->m_pos.y - this->m_pos.w) / bufferSize.y;
  1825. bufferToScene[3][0] = this->m_pos.x;
  1826. bufferToScene[3][1] = this->m_pos.w;
  1827. this->m_effectModelViewProjectionCopy = mvp * bufferToScene;
  1828. // later passes draw WE's unit quad (-1..1), sub_1401EBF60 scales it by half the layer size first
  1829. glm::mat4 unitToBuffer (1.0f);
  1830. unitToBuffer[0][0] = bufferSize.x * 0.5f;
  1831. unitToBuffer[1][1] = bufferSize.y * 0.5f;
  1832. unitToBuffer[3][0] = bufferSize.x * 0.5f;
  1833. unitToBuffer[3][1] = bufferSize.y * 0.5f;
  1834. this->m_effectModelViewProjectionPass = this->m_effectModelViewProjectionCopy * unitToBuffer;
  1835. }
  1836. this->updateEffectTextureProjection ();
  1837. if (this->getImage ().model->passthrough) {
  1838. this->m_modelViewProjectionCopy = this->m_modelViewProjectionScreen;
  1839. this->m_modelViewProjectionCopyInverse = this->m_modelViewProjectionScreenInverse;
  1840. }
  1841. }
  1842. glm::mat4 CImage::getViewProjection () const {
  1843. const auto& camera = this->getScene ().getCamera ();
  1844. // "perspective" layers get their own camera in 2D scenes (sub_1401E8AA0 -> sub_1401E5B60)
  1845. if (camera.isOrthogonal () && this->getImage ().perspective->value->getBool ()) {
  1846. return camera.getPerspectiveLayerViewProjection ();
  1847. }
  1848. return camera.getProjection () * camera.getLookAt ();
  1849. }
  1850. void CImage::updateLightingTransform (const glm::mat4& sceneTransform) {
  1851. const auto width = static_cast<float> (this->getScene ().getWidth ());
  1852. const auto height = static_cast<float> (this->getScene ().getHeight ());
  1853. const glm::mat4 toWorld = glm::scale (
  1854. glm::translate (glm::mat4 (1.0f), glm::vec3 (width / 2.0f, height / 2.0f, 0.0f)), glm::vec3 (1.0f, -1.0f, 1.0f)
  1855. );
  1856. const glm::mat3 flip = glm::mat3 (glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f)));
  1857. this->m_lightingSceneModel = toWorld * sceneTransform;
  1858. this->m_lightingNormal = flip * glm::mat3 (sceneTransform) * flip;
  1859. this->m_lightingViewProjection = this->getViewProjection () * glm::inverse (toWorld);
  1860. // the first pass draws into the layer's own buffer, (0, 0) there is the image's top left corner in the scene
  1861. if (this->getImage ().model->passthrough) {
  1862. this->m_lightingCopyModel = this->m_lightingSceneModel;
  1863. return;
  1864. }
  1865. const glm::vec2 size = glm::max (this->getSize (), glm::vec2 (1.0f));
  1866. const glm::mat4 copyToScene = glm::scale (
  1867. glm::translate (glm::mat4 (1.0f), glm::vec3 (this->m_pos.x, this->m_pos.w, 0.0f)),
  1868. glm::vec3 ((this->m_pos.z - this->m_pos.x) / size.x, (this->m_pos.y - this->m_pos.w) / size.y, 1.0f)
  1869. );
  1870. this->m_lightingCopyModel = this->m_lightingSceneModel * copyToScene;
  1871. }
  1872. void CImage::updateEffectTextureProjection () {
  1873. // the final quad puts texcoord (0, 0) at (m_pos.x, m_pos.w), which is the layer's local (-1, +1) corner;
  1874. // the scene FBO is y-flipped against the screen the pointer position is measured on, hence the flip
  1875. const glm::vec3 center ((this->m_pos.x + this->m_pos.z) / 2.0f, (this->m_pos.y + this->m_pos.w) / 2.0f, 0.0f);
  1876. const glm::vec3 halfSize ((this->m_pos.z - this->m_pos.x) / 2.0f, (this->m_pos.w - this->m_pos.y) / 2.0f, 1.0f);
  1877. const glm::mat4 projection = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
  1878. * this->m_modelViewProjectionScreen * glm::scale (glm::translate (glm::mat4 (1.0f), center), halfSize);
  1879. if (projection == this->m_effectTextureProjection) {
  1880. return;
  1881. }
  1882. this->m_effectTextureProjection = projection;
  1883. // a zero-sized layer has no inverse, keep the last usable one instead of feeding NaNs to the shader
  1884. if (halfSize.x != 0.0f && halfSize.y != 0.0f) {
  1885. this->m_effectTextureProjectionInverse = glm::inverse (projection);
  1886. }
  1887. const glm::vec2 size = this->getSize ();
  1888. this->m_objectSpaceProjectionInverse = glm::scale (glm::mat4 (1.0f), glm::vec3 (size.x / 2.0f, size.y / 2.0f, 1.0f))
  1889. * this->m_effectTextureProjectionInverse;
  1890. }
  1891. const Image& CImage::getImage () const { return this->m_image; }
  1892. void CImage::markAsDependency () { this->m_isDependency = true; }
  1893. glm::vec2 CImage::getSize () const {
  1894. if (this->m_texture == nullptr) {
  1895. return this->getImage ().size;
  1896. }
  1897. // compose layers sample the whole scene, but effect masks map over the layer's own size
  1898. if (this->getImage ().model->passthrough && this->getImage ().size.x > 0.0f && this->getImage ().size.y > 0.0f) {
  1899. return this->getImage ().size;
  1900. }
  1901. // solid layers use a stock white texture, the real footprint is declared by the scene
  1902. if (this->getImage ().model->solidlayer && this->getImage ().size.x > 0.0f && this->getImage ().size.y > 0.0f) {
  1903. return this->getImage ().size;
  1904. }
  1905. return { this->m_texture->getRealWidth (), this->m_texture->getRealHeight () };
  1906. }
  1907. GLuint CImage::getSceneSpacePosition () const { return this->m_sceneSpacePosition; }
  1908. GLuint CImage::getCopySpacePosition () const { return this->m_copySpacePosition; }
  1909. GLuint CImage::getPassSpacePosition () const { return this->m_passSpacePosition; }
  1910. GLuint CImage::getTexCoordCopy () const { return this->m_texcoordCopy; }
  1911. GLuint CImage::getTexCoordPass () const { return this->m_texcoordPass; }