CImage.cpp 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739
  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. // a shape's quad is a square of the scene height (shape load sub_14025FAC0, renderer +136)
  411. if (this->getImage ().shape) {
  412. size = { scene_height, scene_height };
  413. }
  414. try {
  415. this->detectTexture ();
  416. } catch (const Assets::AssetLoadException& e) {
  417. // live WE loads the scene anyway and draws the layer empty
  418. sLog.error ("Image ", image.id, " has no texture, drawing it empty: ", e.what ());
  419. }
  420. const bool placeholderTexture = this->m_texture == nullptr;
  421. if (this->m_texture == nullptr) {
  422. if (this->m_image.model->solidlayer && size.x == 0.0f && size.y == 0.0f) {
  423. size.x = static_cast<float> (scene.getCanvasWidth ());
  424. size.y = static_cast<float> (scene.getCanvasHeight ());
  425. }
  426. // TODO: create a dummy texture of correct size, fbo constructors should be enough, but this should be
  427. // properly handled
  428. // solid layers are often declared far larger than the scene, nothing samples
  429. // these buffers past the canvas so only the layout size has to stay as declared
  430. const glm::vec2 placeholderSize = { std::min (size.x, static_cast<float> (scene.getCanvasWidth ())),
  431. std::min (size.y, static_cast<float> (scene.getCanvasHeight ())) };
  432. this->m_texture = std::make_shared<CFBO> (
  433. "", TextureFormat_ARGB8888, TextureFlags_NoFlags, 1, size.x, size.y, placeholderSize.x, placeholderSize.y
  434. );
  435. }
  436. // If the wallpaper doesn't specify a size, fall back to the texture or model dimensions
  437. if ((size.x == 0.0f || size.y == 0.0f) && this->m_texture != nullptr) {
  438. size.x = static_cast<float> (this->m_texture->getRealWidth ());
  439. size.y = static_cast<float> (this->m_texture->getRealHeight ());
  440. } else if (
  441. (size.x == 0.0f || size.y == 0.0f) && this->getImage ().model->width.has_value ()
  442. && this->getImage ().model->height.has_value ()
  443. ) {
  444. size.x = static_cast<float> (this->getImage ().model->width.value ());
  445. size.y = static_cast<float> (this->getImage ().model->height.value ());
  446. }
  447. // autosize takes the size of the loaded texture (a single frame for sprite sheets) over the
  448. // declared one, or the scene's for project layers. fullscreen still wins over it
  449. if (this->getImage ().model->autosize && this->getImage ().model->projectlayer) {
  450. size = { scene_width, scene_height };
  451. } else if (
  452. this->getImage ().model->autosize && !placeholderTexture
  453. && std::dynamic_pointer_cast<const CFBO> (this->m_texture) == nullptr
  454. ) {
  455. size.x = static_cast<float> (this->m_texture->getRealWidth ());
  456. size.y = static_cast<float> (this->m_texture->getRealHeight ());
  457. }
  458. // fullscreen layers should use the whole projection's size
  459. if (this->getImage ().model->fullscreen) {
  460. size = { static_cast<float> (scene.getCanvasWidth ()), static_cast<float> (scene.getCanvasHeight ()) };
  461. origin = { scene_width / 2, scene_height / 2, 0 };
  462. }
  463. this->m_size = size;
  464. // taken after the texture/model/fullscreen fallbacks above, unsized layers would otherwise get 0x0 buffers
  465. glm::vec2 bufferSize = size;
  466. if (placeholderTexture) {
  467. bufferSize = glm::min (bufferSize, glm::vec2 (scene.getCanvasWidth (), scene.getCanvasHeight ()));
  468. }
  469. this->updateScenePosition (origin, size, scale, scene_width, scene_height);
  470. // register both FBOs into the scene
  471. std::ostringstream nameA, nameB;
  472. // WE renders layers with LIGHTING or REFLECTION unlit into _rt_imageLayerAlbedo_<id> when they have offscreen
  473. // passes and lights them last (sub_1401914B0); here the first pass is lit instead, through PRELIGHTING
  474. nameA << "_rt_imageLayerComposite_" << this->getImage ().id << "_a";
  475. nameB << "_rt_imageLayerComposite_" << this->getImage ().id << "_b";
  476. // scene.json's own "clampuvs" is a per-object override on top of whatever the base texture
  477. // asset defaults to - without it, effects that distort UVs near the edges (refraction, ripples)
  478. // can wrap around and sample the opposite edge of the buffer instead of clamping.
  479. // compose layers always clamp, their effects would otherwise wrap samples from the opposite edge
  480. const uint32_t compositeFlags = (this->getImage ().clampUVs || this->getImage ().model->passthrough)
  481. ? (this->m_texture->getFlags () | TextureFlags_ClampUVs)
  482. : this->m_texture->getFlags ();
  483. // layer buffers are 16 bit float in HDR scene rendering (sub_1401E7170)
  484. const TextureFormat layerFormat = this->getScene ().isHDR () ? TextureFormat_RGBA16161616f : TextureFormat_ARGB8888;
  485. const auto mainFBO = scene.create (
  486. nameA.str (), layerFormat, compositeFlags, 1, { bufferSize.x, bufferSize.y }, { bufferSize.x, bufferSize.y }
  487. );
  488. const auto subFBO = scene.create (
  489. nameB.str (), layerFormat, compositeFlags, 1, { bufferSize.x, bufferSize.y }, { bufferSize.x, bufferSize.y }
  490. );
  491. if (this->followsOutputSize ()) {
  492. scene.followOutputSize (mainFBO, 1);
  493. scene.followOutputSize (subFBO, 1);
  494. }
  495. this->m_currentMainFBO = this->m_mainFBO = mainFBO;
  496. this->m_currentSubFBO = this->m_subFBO = subFBO;
  497. GLfloat sceneSpacePosition[] = { this->m_pos.x, this->m_pos.y, 0.0f, this->m_pos.x, this->m_pos.w, 0.0f,
  498. this->m_pos.z, this->m_pos.y, 0.0f, this->m_pos.z, this->m_pos.y, 0.0f,
  499. this->m_pos.x, this->m_pos.w, 0.0f, this->m_pos.z, this->m_pos.w, 0.0f };
  500. float width = 1.0f;
  501. float height = 1.0f;
  502. if (this->getTexture ()->isAnimated ()) {
  503. // animated images use different coordinates as they're essentially a texture atlas
  504. width = static_cast<float> (this->getTexture ()->getRealWidth ())
  505. / static_cast<float> (this->getTexture ()->getTextureWidth (0));
  506. height = static_cast<float> (this->getTexture ()->getRealHeight ())
  507. / static_cast<float> (this->getTexture ()->getTextureHeight (0));
  508. } else if (
  509. this->getTexture () != nullptr
  510. && (this->getTexture ()->getTextureWidth (0) != this->getTexture ()->getRealWidth ()
  511. || this->getTexture ()->getTextureHeight (0) != this->getTexture ()->getRealHeight ())
  512. ) {
  513. // Account for padding in non-power-of-two textures: clamp UVs to the real content
  514. width = static_cast<float> (this->getTexture ()->getRealWidth ())
  515. / static_cast<float> (this->getTexture ()->getTextureWidth (0));
  516. height = static_cast<float> (this->getTexture ()->getRealHeight ())
  517. / static_cast<float> (this->getTexture ()->getTextureHeight (0));
  518. }
  519. float x = 0.0f;
  520. float y = 0.0f;
  521. if (this->getTexture ()->isAnimated ()) {
  522. // animations should be copied completely
  523. x = 0.0f;
  524. y = 0.0f;
  525. width = 1.0f;
  526. height = 1.0f;
  527. }
  528. GLfloat realWidth = size.x;
  529. GLfloat realHeight = size.y;
  530. GLfloat realX = 0.0;
  531. GLfloat realY = 0.0;
  532. if (this->getImage ().model->passthrough) {
  533. // Passthrough shaders fill the destination FBO from texcoords and sample the scene using positions.
  534. // Keep the destination quad full-screen in local FBO space, but pass scene-space positions through.
  535. x = 0.0f;
  536. y = 0.0f;
  537. width = 1.0f;
  538. height = 1.0f;
  539. realX = this->m_pos.x;
  540. realY = this->m_pos.w;
  541. realWidth = this->m_pos.z;
  542. realHeight = this->m_pos.y;
  543. if (this->getImage ().model->fullscreen) {
  544. realX = -1.0;
  545. realY = -1.0;
  546. realWidth = 1.0;
  547. realHeight = 1.0;
  548. }
  549. }
  550. GLfloat texcoordCopy[] = { x, height, x, y, width, height, width, height, x, y, width, y };
  551. GLfloat copySpacePosition[] = { realX, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realHeight, 0.0f,
  552. realWidth, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realY, 0.0f };
  553. 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 };
  554. GLfloat passSpacePosition[]
  555. = { -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 };
  556. glGenBuffers (1, &this->m_sceneSpacePosition);
  557. glBindBuffer (GL_ARRAY_BUFFER, this->m_sceneSpacePosition);
  558. glBufferData (GL_ARRAY_BUFFER, sizeof (sceneSpacePosition), sceneSpacePosition, GL_STATIC_DRAW);
  559. glGenBuffers (1, &this->m_copySpacePosition);
  560. glBindBuffer (GL_ARRAY_BUFFER, this->m_copySpacePosition);
  561. glBufferData (GL_ARRAY_BUFFER, sizeof (copySpacePosition), copySpacePosition, GL_STATIC_DRAW);
  562. glGenBuffers (1, &this->m_passSpacePosition);
  563. glBindBuffer (GL_ARRAY_BUFFER, this->m_passSpacePosition);
  564. glBufferData (GL_ARRAY_BUFFER, sizeof (passSpacePosition), passSpacePosition, GL_STATIC_DRAW);
  565. glGenBuffers (1, &this->m_texcoordCopy);
  566. glBindBuffer (GL_ARRAY_BUFFER, this->m_texcoordCopy);
  567. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoordCopy), texcoordCopy, GL_STATIC_DRAW);
  568. glGenBuffers (1, &this->m_texcoordPass);
  569. glBindBuffer (GL_ARRAY_BUFFER, this->m_texcoordPass);
  570. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoordPass), texcoordPass, GL_STATIC_DRAW);
  571. this->m_hasPuppetMesh = this->loadPuppetMesh (size);
  572. this->m_modelViewProjectionScreen = this->getViewProjection ();
  573. // must match m_modelViewProjectionScreen - updateScreenSpacePosition() may skip recomputing it
  574. this->m_modelViewProjectionScreenInverse = glm::inverse (this->m_modelViewProjectionScreen);
  575. this->updateEffectTextureProjection ();
  576. if (this->getImage ().model->passthrough) {
  577. this->m_modelViewProjectionCopy = this->m_modelViewProjectionScreen;
  578. } else {
  579. this->m_modelViewProjectionCopy = glm::ortho<float> (0.0, size.x, 0.0, size.y);
  580. }
  581. this->m_modelViewProjectionCopyInverse = glm::inverse (this->m_modelViewProjectionCopy);
  582. this->m_modelMatrix = glm::ortho<float> (0.0, size.x, 0.0, size.y);
  583. this->m_viewProjectionMatrix = glm::mat4 (1.0);
  584. // marks the texture as used, which starts video playback if it isn't already
  585. this->m_texture->incrementUsageCount ();
  586. }
  587. void CImage::updateTextures () const {
  588. this->getTexture ()->update ();
  589. for (const auto* pass : this->m_passes) {
  590. pass->updatePlaybackTextures ();
  591. }
  592. }
  593. void CImage::renderPassthroughChildren (const std::shared_ptr<const CFBO>& buffer) {
  594. // the buffer holds the layer's quad (m_pos, copy pass texcoords: v = 1 at m_pos.y), children land in it through
  595. // model = inverse (layer world), view = identity, ortho (-w/2, w/2, -h/2, h/2, -1000, 1000) (sub_1401ECB20).
  596. // Fullscreen layers keep the scene's camera
  597. glm::mat4 transform (1.0f);
  598. glm::mat4 viewProjection = this->getScene ().getWorldViewProjection ();
  599. if (!this->getImage ().model->fullscreen) {
  600. 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);
  601. const glm::vec3 halfExtent (
  602. (this->m_pos.z - this->m_pos.x) / 2.0f, (this->m_pos.y - this->m_pos.w) / 2.0f, 1000.0f
  603. );
  604. transform = glm::inverse (glm::scale (glm::translate (this->m_modelViewProjectionScreen, center), halfExtent));
  605. // lights skip the model stack (volumetricsfront.vert only has g_ViewProjectionMatrix), so they see the bare
  606. // ortho with the scene's y flip: their world position lands in the layer as if the layer sat at the origin
  607. const glm::vec2 size = this->getSize ();
  608. viewProjection = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
  609. * glm::ortho (-size.x / 2.0f, size.x / 2.0f, -size.y / 2.0f, size.y / 2.0f, -1000.0f, 1000.0f);
  610. }
  611. this->getScene ().renderPassthroughChildren (
  612. this->getId (),
  613. {
  614. .fbo = buffer,
  615. .transform = transform,
  616. .alphaMax = !this->m_image.copyBackground->value->getBool (),
  617. .viewProjection = viewProjection,
  618. }
  619. );
  620. }
  621. bool CImage::hitTest (const glm::vec2& ndc) {
  622. if (this->getImage ().model->fullscreen) {
  623. return true;
  624. }
  625. this->updateScreenSpacePosition ();
  626. 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);
  627. const glm::vec2 half (
  628. std::abs (this->m_pos.z - this->m_pos.x) / 2.0f, std::abs (this->m_pos.w - this->m_pos.y) / 2.0f
  629. );
  630. return Wallpapers::CScene::quadContainsPoint (
  631. glm::translate (this->m_modelViewProjectionScreen, center), half, ndc
  632. );
  633. }
  634. glm::vec2 CImage::cursorLocalPosition (const glm::vec2& ndc) {
  635. this->updateScreenSpacePosition ();
  636. 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);
  637. const auto point
  638. = Wallpapers::CScene::quadPlanePoint (glm::translate (this->m_modelViewProjectionScreen, center), ndc);
  639. const glm::vec2 extent (this->m_pos.z - this->m_pos.x, this->m_pos.y - this->m_pos.w);
  640. if (!point.has_value () || extent.x == 0.0f || extent.y == 0.0f) {
  641. return glm::vec2 (0.0f);
  642. }
  643. // m_pos runs y down from the top edge (.w), x from the texture's left edge (.x)
  644. const glm::vec2 u (
  645. (point->x + center.x - this->m_pos.x) / extent.x, (point->y + center.y - this->m_pos.w) / extent.y
  646. );
  647. return u * this->m_displaySize;
  648. }
  649. CImage::~CImage () {
  650. this->m_texture->decrementUsageCount ();
  651. // delete passes first as they depend on the image's data
  652. for (auto* pass : this->m_allPasses.empty () ? this->m_passes : this->m_allPasses) {
  653. delete pass;
  654. }
  655. this->m_passes.clear ();
  656. this->m_allPasses.clear ();
  657. for (auto* pass : this->m_puppetClipMaskPasses) {
  658. delete pass;
  659. }
  660. delete this->m_puppetClipTargetPass;
  661. delete this->m_puppetClipComposePass;
  662. glDeleteBuffers (1, &this->m_sceneSpacePosition);
  663. glDeleteBuffers (1, &this->m_copySpacePosition);
  664. glDeleteBuffers (1, &this->m_passSpacePosition);
  665. glDeleteBuffers (1, &this->m_texcoordCopy);
  666. glDeleteBuffers (1, &this->m_texcoordPass);
  667. if (this->m_puppetSpacePosition != GL_NONE) {
  668. glDeleteBuffers (1, &this->m_puppetSpacePosition);
  669. }
  670. if (this->m_puppetTexCoord != GL_NONE) {
  671. glDeleteBuffers (1, &this->m_puppetTexCoord);
  672. }
  673. if (this->m_puppetIndices != GL_NONE) {
  674. glDeleteBuffers (1, &this->m_puppetIndices);
  675. }
  676. for (const GLuint buffer :
  677. { this->m_puppetClipIndices, this->m_puppetClipComposePosition, this->m_puppetClipComposeTexCoord }) {
  678. if (buffer != GL_NONE) {
  679. glDeleteBuffers (1, &buffer);
  680. }
  681. }
  682. }
  683. bool CImage::loadPuppetMesh (const glm::vec2& size) {
  684. if (!this->getImage ().model->puppet.has_value ()) {
  685. return false;
  686. }
  687. try {
  688. const auto stream = this->getScene ().getScene ().project.assetLocator->read (*this->getImage ().model->puppet);
  689. std::vector<char> data { std::istreambuf_iterator<char> (*stream), std::istreambuf_iterator<char> () };
  690. constexpr size_t markerSize = 9;
  691. constexpr size_t meshHeaderSize = sizeof (uint32_t) * 2;
  692. const std::string puppetVersion
  693. = data.size () >= markerSize ? std::string (data.data (), strlen ("MDLV0021")) : "";
  694. const size_t mdlsOffset = [&data] () -> size_t {
  695. for (size_t offset = markerSize; offset + strlen ("MDLS") < data.size (); offset++) {
  696. if (std::memcmp (data.data () + offset, "MDLS", strlen ("MDLS")) == 0) {
  697. return offset;
  698. }
  699. }
  700. return data.size ();
  701. }();
  702. auto meshBuffer = std::make_unique<char[]> (data.size ());
  703. std::copy (data.begin (), data.end (), meshBuffer.get ());
  704. const BinaryReader reader (std::make_shared<MemoryStream> (std::move (meshBuffer), data.size ()));
  705. const auto layout = resolvePuppetVertexLayout (reader, markerSize, mdlsOffset, meshHeaderSize);
  706. if (!layout.has_value ()) {
  707. sLog.error ("Could not find a usable MDLV mesh block in ", *this->getImage ().model->puppet);
  708. return false;
  709. }
  710. const auto mesh = readPuppetMeshData (reader, layout->block, meshHeaderSize, layout->vertexStride);
  711. if (!mesh.has_value ()) {
  712. sLog.error ("Could not find a usable MDLV mesh block in ", *this->getImage ().model->puppet);
  713. return false;
  714. }
  715. this->m_puppetRawPositions = mesh->positions;
  716. this->updatePuppetPositionBuffer (size);
  717. glGenBuffers (1, &this->m_puppetTexCoord);
  718. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetTexCoord);
  719. glBufferData (
  720. GL_ARRAY_BUFFER, mesh->texcoords.size () * sizeof (GLfloat), mesh->texcoords.data (), GL_STATIC_DRAW
  721. );
  722. glGenBuffers (1, &this->m_puppetIndices);
  723. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetIndices);
  724. glBufferData (
  725. GL_ELEMENT_ARRAY_BUFFER, mesh->indices.size () * sizeof (GLushort), mesh->indices.data (), GL_STATIC_DRAW
  726. );
  727. this->m_puppetIndexCount = static_cast<GLsizei> (mesh->indices.size ());
  728. this->m_puppetDrawBuffer = this->m_puppetIndices;
  729. this->m_puppetDrawCount = this->m_puppetIndexCount;
  730. // the part ranges and clipping records follow the index buffer (sub_140261880)
  731. const int version
  732. = puppetVersion.size () > strlen ("MDLV") ? std::atoi (puppetVersion.c_str () + strlen ("MDLV")) : 0;
  733. const size_t indexEnd = layout->block.headerOffset + meshHeaderSize + layout->block.vertexBytes
  734. + sizeof (uint32_t) + layout->block.indexBytes;
  735. this->m_puppetClipping.reset ();
  736. try {
  737. auto clipping = PuppetClipping::read (data, indexEnd, version, mesh->indices.size ());
  738. if (clipping.has_value () && clipping->build (mesh->indices)) {
  739. glGenBuffers (1, &this->m_puppetClipIndices);
  740. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetClipIndices);
  741. glBufferData (
  742. GL_ELEMENT_ARRAY_BUFFER, clipping->indices.size () * sizeof (GLushort), clipping->indices.data (),
  743. GL_STATIC_DRAW
  744. );
  745. sLog.out (
  746. "Puppet ", *this->getImage ().model->puppet, " clipping: ", clipping->records.size (), " masks, ",
  747. clipping->parts.size (), " parts, ", clipping->draws.size (), " draws"
  748. );
  749. this->m_puppetClipping = std::move (clipping);
  750. } else if (clipping.has_value ()) {
  751. sLog.error (
  752. "Puppet ", *this->getImage ().model->puppet, " has clipping masks drawn where their targets are, ",
  753. "which aren't supported, drawing it without them"
  754. );
  755. }
  756. } catch (const std::exception& ex) {
  757. sLog.error ("Ignoring the clipping masks of ", *this->getImage ().model->puppet, ": ", ex.what ());
  758. }
  759. sLog.out (
  760. "Loaded puppet mesh ", *this->getImage ().model->puppet, " version=", puppetVersion,
  761. " stride=", layout->vertexStride, " vertices=", this->m_puppetRawPositions.size () / 3,
  762. " indices=", this->m_puppetIndexCount
  763. );
  764. this->m_rig.clear ();
  765. this->m_puppetBlendIndices.clear ();
  766. this->m_puppetBlendWeights.clear ();
  767. this->m_puppetSkinnedPositions.clear ();
  768. const auto blend = readPuppetBlendData (reader, layout->block, meshHeaderSize, layout->vertexStride);
  769. if (blend.has_value ()) {
  770. this->m_puppetBlendIndices = blend->indices;
  771. this->m_puppetBlendWeights = blend->weights;
  772. }
  773. if (mdlsOffset < data.size () && blend.has_value ()) {
  774. try {
  775. // MDLV header: tag, flags, a second field and the mesh count (2.8.42 sub_140261880)
  776. uint32_t meshCount = 0;
  777. if (data.size () >= 21) {
  778. std::memcpy (&meshCount, data.data () + 17, sizeof (meshCount));
  779. }
  780. this->m_rig.load (data, mdlsOffset, meshCount, *this->getImage ().model->puppet);
  781. this->m_rig.addSceneLayers (this->getImage ().animationLayers);
  782. } catch (const std::exception& ex) {
  783. sLog.error (
  784. "Could not load puppet skeleton/animation from ", *this->getImage ().model->puppet, ": ",
  785. ex.what (), " (falling back to the static bind pose)"
  786. );
  787. this->m_rig.clear ();
  788. }
  789. }
  790. return true;
  791. } catch (const std::exception& ex) {
  792. sLog.error ("Could not load puppet mesh ", *this->getImage ().model->puppet, ": ", ex.what ());
  793. return false;
  794. }
  795. }
  796. void CImage::updatePuppetPositionBuffer (const glm::vec2& size) {
  797. // once an animation clip is driving the mesh, its skinned output replaces the static bind pose
  798. // as the source of truth - the bind pose (m_puppetRawPositions) is kept around unchanged, since
  799. // skinning is recomputed from it fresh every frame, not accumulated from the previous frame
  800. const auto& source
  801. = !this->m_puppetSkinnedPositions.empty () ? this->m_puppetSkinnedPositions : this->m_puppetRawPositions;
  802. if (source.empty ()) {
  803. return;
  804. }
  805. // A puppet with effects is multi-pass: its geometry pass renders into its own object-sized
  806. // intermediate FBO (see setupPasses(), the "writesToTarget" branch) using the local-canvas
  807. // m_modelViewProjectionCopy projection, and later passes composite that FBO's texture onto the
  808. // scene the normal (non-puppet) way - that first pass still needs plain local canvas coordinates
  809. // (0..size, matching its texcoords) to line up with that projection. Only a puppet with no
  810. // effects skips straight from its one and only pass to the shared scene FBO, using
  811. // m_modelViewProjectionScreen (see setupPasses()) - that path needs vertices already in the same
  812. // absolute scene-space coordinates uploadGeometryBuffers() bakes into sceneSpacePosition for a
  813. // normal quad, or every vertex renders shifted by a constant offset equal to wherever this object
  814. // should have been, reading as the whole mesh floating somewhere else on screen entirely.
  815. const bool bakeScenePosition = this->m_passes.size () <= 1 || this->m_puppetMeshLast;
  816. std::vector<GLfloat> positions;
  817. positions.reserve (source.size ());
  818. for (size_t index = 0; index + 2 < source.size (); index += 3) {
  819. const float localX = size.x / 2.0f + source[index];
  820. const float localY = size.y / 2.0f - source[index + 1];
  821. if (bakeScenePosition) {
  822. // maps the local-canvas coordinate onto this object's scene-space bounding box; m_pos.w is
  823. // its bottom edge (m_pos.y is the top, see updateScenePosition()) so localY==0 has to land
  824. // there, not on m_pos.y, or the puppet renders vertically flipped
  825. positions.push_back (this->m_pos.x + localX * this->m_puppetScale.x);
  826. positions.push_back (this->m_pos.w + localY * this->m_puppetScale.y);
  827. } else {
  828. positions.push_back (localX);
  829. positions.push_back (localY);
  830. }
  831. // raw .mdl Z values aren't used by this engine's orthographic puppet compositing (depth test
  832. // is disabled for puppets; layering comes from draw order + alpha blending) - and glm::ortho's
  833. // clip.z = -localZ has no near/far normalization, so a puppet's real mesh depth (tens of units)
  834. // would get clipped outside [-1,1] and lose most of the mesh. Zero it instead.
  835. positions.push_back (0.0f);
  836. }
  837. // skip the constructor's pre-setup() call, where m_passes/m_pos/m_puppetScale aren't resolved yet
  838. if (!this->m_puppetPositionDiagnosticLogged && !this->m_passes.empty ()) {
  839. this->m_puppetPositionDiagnosticLogged = true;
  840. glm::vec3 boundsMin (std::numeric_limits<float>::max ());
  841. glm::vec3 boundsMax (std::numeric_limits<float>::lowest ());
  842. for (size_t i = 0; i + 2 < positions.size (); i += 3) {
  843. const glm::vec3 p (positions[i], positions[i + 1], positions[i + 2]);
  844. boundsMin = glm::min (boundsMin, p);
  845. boundsMax = glm::max (boundsMax, p);
  846. }
  847. sLog.out (
  848. "Puppet position bake for ", this->getImage ().name, " (", this->getId (),
  849. "): bakeScenePosition=", bakeScenePosition, " passes=", this->m_passes.size (),
  850. " vertexCount=", positions.size () / 3, " boundsMin=(", boundsMin.x, ",", boundsMin.y, ",", boundsMin.z,
  851. ") boundsMax=(", boundsMax.x, ",", boundsMax.y, ",", boundsMax.z, ")"
  852. );
  853. }
  854. if (this->m_puppetSpacePosition == GL_NONE) {
  855. glGenBuffers (1, &this->m_puppetSpacePosition);
  856. }
  857. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetSpacePosition);
  858. glBufferData (GL_ARRAY_BUFFER, positions.size () * sizeof (GLfloat), positions.data (), GL_DYNAMIC_DRAW);
  859. }
  860. PuppetActiveAnimation* CImage::findPuppetAnimationLayer (size_t serial) { return this->m_rig.findLayer (serial); }
  861. size_t CImage::getPuppetAnimationLayerCount () const { return this->m_rig.getLayerCount (); }
  862. std::optional<size_t> CImage::getPuppetAnimationLayerAt (int64_t index) const { return this->m_rig.getLayerAt (index); }
  863. std::optional<size_t> CImage::findPuppetAnimationLayerByName (const std::string& name) const {
  864. return this->m_rig.findLayerByName (name);
  865. }
  866. std::optional<size_t> CImage::createPuppetAnimationLayer (
  867. const Data::JSON::JSON& animation, const Data::JSON::JSON& config, bool autoRemove
  868. ) {
  869. return this->m_rig.createLayer (animation, config, autoRemove, this->getScene ().getScene ().project);
  870. }
  871. bool CImage::destroyPuppetAnimationLayersByName (const std::string& name) {
  872. return this->m_rig.destroyLayersByName (name);
  873. }
  874. bool CImage::destroyPuppetAnimationLayer (size_t serial) { return this->m_rig.destroyLayer (serial); }
  875. void CImage::updatePuppetPose () {
  876. if (!this->m_hasPuppetMesh || this->m_rig.bones.empty ()) {
  877. return;
  878. }
  879. if (this->getScene ().getContext ().getApp ().getContext ().settings.render.debug.noPuppetAnimation) {
  880. return;
  881. }
  882. this->m_rig.updatePose (this->puppetObjectWorld ());
  883. this->m_rig.finishEndedLayers ([this] (size_t serial) {
  884. this->getScene ().getScriptEngine ().dispatchAnimationLayerEnded (*this, serial);
  885. });
  886. }
  887. void CImage::updatePuppetSkinning () {
  888. if (!this->m_rig.poseAnimated || this->m_rig.boneModel.size () != this->m_rig.bones.size ()) {
  889. return;
  890. }
  891. const auto& worldAnimated = this->m_rig.boneModel;
  892. std::vector<glm::mat4> skinMatrices (this->m_rig.bones.size ());
  893. for (size_t i = 0; i < this->m_rig.bones.size (); i++) {
  894. skinMatrices[i] = worldAnimated[i] * this->m_rig.bones[i].inverseBindWorld;
  895. }
  896. const size_t vertexCount = this->m_puppetRawPositions.size () / 3;
  897. this->m_puppetSkinnedPositions.assign (this->m_puppetRawPositions.size (), 0.0f);
  898. for (size_t v = 0; v < vertexCount; v++) {
  899. const glm::vec4 bindPos (
  900. this->m_puppetRawPositions[v * 3], this->m_puppetRawPositions[v * 3 + 1],
  901. this->m_puppetRawPositions[v * 3 + 2], 1.0f
  902. );
  903. glm::vec3 skinned (0.0f);
  904. const glm::uvec4& indices
  905. = v < this->m_puppetBlendIndices.size () ? this->m_puppetBlendIndices[v] : glm::uvec4 (0);
  906. const glm::vec4& weights
  907. = v < this->m_puppetBlendWeights.size () ? this->m_puppetBlendWeights[v] : glm::vec4 (0.0f);
  908. for (int influence = 0; influence < 4; influence++) {
  909. const float weight = weights[influence];
  910. if (weight == 0.0f) {
  911. continue;
  912. }
  913. const uint32_t boneIndex = indices[influence];
  914. if (boneIndex >= skinMatrices.size ()) {
  915. continue;
  916. }
  917. skinned += weight * glm::vec3 (skinMatrices[boneIndex] * bindPos);
  918. }
  919. this->m_puppetSkinnedPositions[v * 3] = skinned.x;
  920. this->m_puppetSkinnedPositions[v * 3 + 1] = skinned.y;
  921. this->m_puppetSkinnedPositions[v * 3 + 2] = skinned.z;
  922. }
  923. this->updatePuppetPositionBuffer (this->m_size);
  924. }
  925. glm::mat4 CImage::worldMatrix () const {
  926. const glm::mat4 world = this->getScene ().objectWorldMatrix (this->getObject ());
  927. const uint32_t alignment
  928. = Data::Parsers::ObjectParser::parseAlignment (this->getImage ().alignmentName->value->getString ());
  929. if (alignment == ImageAlignment_Center) {
  930. return world;
  931. }
  932. // sub_1402066A0 takes half the object size (+752, truncated to int, 2x2 for fullscreen layers via
  933. // sub_140209360), puppets included, in the layer's own scaled and rotated space
  934. const glm::vec2 size = this->getImage ().model->fullscreen ? glm::vec2 (2.0f) : glm::trunc (this->m_displaySize);
  935. glm::vec3 offset (0.0f);
  936. if (alignment & ImageAlignment_Left) {
  937. offset.x = size.x * 0.5f;
  938. } else if (alignment & ImageAlignment_Right) {
  939. offset.x = -size.x * 0.5f;
  940. }
  941. if (alignment & ImageAlignment_Top) {
  942. offset.y = -size.y * 0.5f;
  943. } else if (alignment & ImageAlignment_Bottom) {
  944. offset.y = size.y * 0.5f;
  945. }
  946. return glm::translate (world, offset);
  947. }
  948. glm::mat4 CImage::puppetObjectWorld () const { return this->worldMatrix (); }
  949. CImage::TextureAnimation* CImage::getTextureAnimation () {
  950. if (!this->m_textureAnimation.has_value ()) {
  951. if (this->m_texture == nullptr || !this->m_texture->isAnimated () || this->m_texture->getFrames ().empty ()) {
  952. return nullptr;
  953. }
  954. this->m_textureAnimation = TextureAnimation {};
  955. }
  956. return &*this->m_textureAnimation;
  957. }
  958. std::pair<int, float> CImage::sharedTextureFrame () const {
  959. if (this->m_texture == nullptr || !this->m_texture->isAnimated ()) {
  960. return { 0, 0.0f };
  961. }
  962. // the same walk CPass::resolveTextureAnimationState does on the scene clock
  963. const auto& frames = this->m_texture->getFrames ();
  964. double time = fmod (static_cast<double> (g_Time), this->getAnimationTime ());
  965. for (size_t i = 0; i < frames.size (); i++) {
  966. if (time - frames[i]->frametime <= 0.0) {
  967. return { static_cast<int> (i), static_cast<float> (time) };
  968. }
  969. time -= frames[i]->frametime;
  970. }
  971. return { 0, 0.0f };
  972. }
  973. int CImage::getTextureFrameCount () const {
  974. return this->m_texture != nullptr && this->m_texture->isAnimated ()
  975. ? static_cast<int> (this->m_texture->getFrames ().size ())
  976. : 0;
  977. }
  978. float CImage::getTextureDuration () const {
  979. return this->m_texture != nullptr && this->m_texture->isAnimated () ? static_cast<float> (this->getAnimationTime ())
  980. : 0.0f;
  981. }
  982. void CImage::updateTextureAnimation (float frametime) {
  983. // a scene drawn on several outputs updates its objects once per output
  984. if (this->m_textureAnimationClock == g_Time) {
  985. return;
  986. }
  987. this->m_textureAnimationClock = g_Time;
  988. if (!this->m_textureAnimation.has_value () || !this->m_textureAnimation->detached
  989. || !this->m_textureAnimation->playing || this->m_texture == nullptr || !this->m_texture->isAnimated ()) {
  990. return;
  991. }
  992. // sub_14015FDD0: forwards wraps to the first frame, backwards to the last, the time stays inside the frame
  993. auto& animation = *this->m_textureAnimation;
  994. const auto& frames = this->m_texture->getFrames ();
  995. const int count = static_cast<int> (frames.size ());
  996. const float step = frametime * animation.rate;
  997. const auto frameTime = [&frames, count] (int index) {
  998. return static_cast<float> (frames[index >= 0 && index < count ? index : 0]->frametime);
  999. };
  1000. if (count == 0 || step == 0.0f) {
  1001. return;
  1002. }
  1003. animation.time += step;
  1004. if (step > 0.0f) {
  1005. const float current = frameTime (animation.frame);
  1006. if (animation.time >= current) {
  1007. const float rest = animation.time - current;
  1008. // compared unsigned, a negative frame wraps to the first one too
  1009. animation.frame = animation.frame + 1 < 0 || animation.frame + 1 >= count ? 0 : animation.frame + 1;
  1010. animation.time = std::min (rest, frameTime (animation.frame));
  1011. }
  1012. } else if (animation.time <= 0.0f) {
  1013. animation.frame = animation.frame - 1 >= 0 ? animation.frame - 1 : count - 1;
  1014. animation.time = std::max (animation.time + frameTime (animation.frame), 0.0f);
  1015. }
  1016. }
  1017. std::optional<int> CImage::getTextureFrameOverride () const {
  1018. // a negative frame leaves the texture on its shared clock
  1019. if (!this->m_textureAnimation.has_value () || !this->m_textureAnimation->detached
  1020. || this->m_textureAnimation->frame < 0) {
  1021. return std::nullopt;
  1022. }
  1023. return this->m_textureAnimation->frame;
  1024. }
  1025. bool CImage::hasPuppetPose () const { return this->m_rig.hasPose (); }
  1026. int CImage::findPuppetBone (const std::string& name) const { return this->m_rig.findBone (name); }
  1027. const glm::mat4& CImage::getPuppetBoneTransform (int bone) const { return this->m_rig.getBoneTransform (bone); }
  1028. void CImage::setPuppetBoneTransform (int bone, const glm::mat4& transform) {
  1029. this->m_rig.setBoneTransform (bone, transform, this->puppetObjectWorld ());
  1030. }
  1031. const glm::mat4& CImage::getPuppetLocalBoneTransform (int bone) const {
  1032. return this->m_rig.getLocalBoneTransform (bone);
  1033. }
  1034. void CImage::setPuppetLocalBoneTransform (int bone, const glm::mat4& transform) {
  1035. this->m_rig.setLocalBoneTransform (bone, transform, this->puppetObjectWorld ());
  1036. }
  1037. void CImage::applyPuppetBonePhysicsImpulse (int bone, const glm::vec3& directional, const glm::vec3& angularDegrees) {
  1038. this->m_rig.applyBonePhysicsImpulse (bone, directional, angularDegrees);
  1039. }
  1040. void CImage::resetPuppetBonePhysics (int bone) { this->m_rig.resetBonePhysics (bone); }
  1041. std::optional<CImage::AttachmentPointTransform>
  1042. CImage::getAttachmentPointMeshTransform (const std::string& name) const {
  1043. if (this->m_rig.boneModel.empty ()) {
  1044. return std::nullopt;
  1045. }
  1046. const auto it = std::find_if (
  1047. this->m_rig.attachmentPoints.begin (), this->m_rig.attachmentPoints.end (),
  1048. [&name] (const PuppetAttachmentPoint& point) { return point.name == name; }
  1049. );
  1050. if (it == this->m_rig.attachmentPoints.end ()
  1051. || static_cast<size_t> (it->boneIndex) >= this->m_rig.boneModel.size ()) {
  1052. return std::nullopt;
  1053. }
  1054. const glm::mat4 animatedWorld = this->m_rig.boneModel[it->boneIndex] * it->localTransform;
  1055. const float angle = std::atan2 (animatedWorld[0][1], animatedWorld[0][0]);
  1056. // scale.y = det(X,Y)/scale.x, projecting the transformed Y-basis onto what an unreflected
  1057. // rotation by `angle` would have produced - comes out negative if the bone's matrix includes a
  1058. // reflection (mirrored bone), instead of folding that into a bogus rotation angle
  1059. const float scaleX = glm::length (glm::vec2 (animatedWorld[0]));
  1060. const glm::vec2 scale = scaleX > 1e-6f
  1061. ? glm::vec2 (
  1062. scaleX, (animatedWorld[0][0] * animatedWorld[1][1] - animatedWorld[0][1] * animatedWorld[1][0]) / scaleX
  1063. )
  1064. : glm::vec2 (scaleX, glm::length (glm::vec2 (animatedWorld[1])));
  1065. return AttachmentPointTransform { .position = glm::vec3 (animatedWorld[3]), .angle = angle, .scale = scale };
  1066. }
  1067. void CImage::setupPuppetGeometryCallback (Effects::CPass* pass) const {
  1068. pass->setGeometryCallback (
  1069. [this, pass] () {
  1070. const GLint position = glGetAttribLocation (pass->getProgramID (), "a_Position");
  1071. const GLint texCoord = glGetAttribLocation (pass->getProgramID (), "a_TexCoord");
  1072. if (!this->m_puppetDrawDiagnosticLogged) {
  1073. this->m_puppetDrawDiagnosticLogged = true;
  1074. sLog.out (
  1075. "Puppet draw setup for ", this->getImage ().name, " (", this->getId (),
  1076. "): programID=", pass->getProgramID (), " a_Position=", position, " a_TexCoord=", texCoord,
  1077. " indexCount=", this->m_puppetIndexCount, " size=", this->m_size.x, "x", this->m_size.y
  1078. );
  1079. }
  1080. if (position >= 0) {
  1081. glEnableVertexAttribArray (position);
  1082. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetSpacePosition);
  1083. glVertexAttribPointer (position, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  1084. }
  1085. if (texCoord >= 0) {
  1086. glEnableVertexAttribArray (texCoord);
  1087. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetTexCoord);
  1088. glVertexAttribPointer (texCoord, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
  1089. }
  1090. // updatePuppetPositionBuffer flips Y when converting mesh-space positions to screen space,
  1091. // which mirrors the mesh and reverses triangle winding relative to what the MDL file's index
  1092. // buffer encodes - but not necessarily uniformly across the whole mesh, since real puppet
  1093. // meshes aren't guaranteed to be consistently wound to begin with. Puppet content is flat 2D
  1094. // art with no real backface concept, so rather than chase the "correct" winding, just never
  1095. // cull it - a material requesting cullmode "normal" would otherwise silently drop whichever
  1096. // subset of triangles ends up on the wrong side, which looks like patchy missing geometry.
  1097. glDisable (GL_CULL_FACE);
  1098. },
  1099. [this, pass] () {
  1100. // a mesh pass into the layer's own buffer starts it fresh, one meant for the scene may be going into a
  1101. // passthrough layer's buffer right now, which holds its other children
  1102. if (pass == this->m_puppetMeshPass && !this->m_puppetDrawKeep
  1103. && pass->getDestination () != this->getScene ().getFBO ()) {
  1104. GLfloat previousClearColor[4] = {};
  1105. glGetFloatv (GL_COLOR_CLEAR_VALUE, previousClearColor);
  1106. glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
  1107. glClear (GL_COLOR_BUFFER_BIT);
  1108. glClearColor (
  1109. previousClearColor[0], previousClearColor[1], previousClearColor[2], previousClearColor[3]
  1110. );
  1111. }
  1112. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetDrawBuffer);
  1113. glDrawElements (
  1114. GL_TRIANGLES, this->m_puppetDrawCount, GL_UNSIGNED_SHORT,
  1115. reinterpret_cast<const void*> (static_cast<uintptr_t> (this->m_puppetDrawOffset) * sizeof (GLushort))
  1116. );
  1117. if (!this->m_puppetDrawErrorChecked) {
  1118. this->m_puppetDrawErrorChecked = true;
  1119. GLint boundFBO = 0;
  1120. GLint viewport[4] = {};
  1121. GLint boundTexture = 0;
  1122. glGetIntegerv (GL_DRAW_FRAMEBUFFER_BINDING, &boundFBO);
  1123. glGetIntegerv (GL_VIEWPORT, viewport);
  1124. glActiveTexture (GL_TEXTURE0);
  1125. glGetIntegerv (GL_TEXTURE_BINDING_2D, &boundTexture);
  1126. const GLenum err = glGetError ();
  1127. const GLboolean cullEnabled = glIsEnabled (GL_CULL_FACE);
  1128. const GLboolean depthEnabled = glIsEnabled (GL_DEPTH_TEST);
  1129. const GLboolean scissorEnabled = glIsEnabled (GL_SCISSOR_TEST);
  1130. const GLboolean blendEnabled = glIsEnabled (GL_BLEND);
  1131. GLint cullFaceMode = 0, frontFace = 0;
  1132. glGetIntegerv (GL_CULL_FACE_MODE, &cullFaceMode);
  1133. glGetIntegerv (GL_FRONT_FACE, &frontFace);
  1134. GLboolean colorMask[4] = {};
  1135. glGetBooleanv (GL_COLOR_WRITEMASK, colorMask);
  1136. sLog.out (
  1137. "Puppet draw result for ", this->getImage ().name, " (", this->getId (), "): glError=", err,
  1138. " boundFBO=", boundFBO, " sceneFBO=", this->getScene ().getFBO ()->getFramebuffer (), " viewport=(",
  1139. viewport[0], ",", viewport[1], ",", viewport[2], ",", viewport[3], ") boundTexture=", boundTexture,
  1140. " ownTextureReady=", (this->getTexture () != nullptr && this->getTexture ()->isReady ()),
  1141. " ownTextureID=", (this->getTexture () != nullptr ? this->getTexture ()->getTextureID (0) : 0),
  1142. " color4=(", this->getColor4 ().r, ",", this->getColor4 ().g, ",", this->getColor4 ().b, ",",
  1143. this->getColor4 ().a, ") alpha=", this->getUserAlpha (), " brightness=", this->getBrightness (),
  1144. " cullEnabled=", (int)cullEnabled, " cullFaceMode=", cullFaceMode, " frontFace=", frontFace,
  1145. " depthEnabled=", (int)depthEnabled, " scissorEnabled=", (int)scissorEnabled,
  1146. " blendEnabled=", (int)blendEnabled, " colorMask=(", (int)colorMask[0], ",", (int)colorMask[1], ",",
  1147. (int)colorMask[2], ",", (int)colorMask[3], ")"
  1148. );
  1149. }
  1150. },
  1151. [pass] () {
  1152. const GLint position = glGetAttribLocation (pass->getProgramID (), "a_Position");
  1153. const GLint texCoord = glGetAttribLocation (pass->getProgramID (), "a_TexCoord");
  1154. if (position >= 0) {
  1155. glDisableVertexAttribArray (position);
  1156. }
  1157. if (texCoord >= 0) {
  1158. glDisableVertexAttribArray (texCoord);
  1159. }
  1160. }
  1161. );
  1162. }
  1163. // sub_140209540 / sub_140206AE0: a puppet with clipping records gets clippingmaskimage4 for its masks and its own
  1164. // material again with CLIPPINGUVS and CLIPPINGTARGET for what they clip
  1165. void CImage::setupPuppetClipping () {
  1166. if (!this->m_puppetClipping.has_value () || this->m_puppetMeshPass == nullptr) {
  1167. return;
  1168. }
  1169. const auto& project = this->getScene ().getScene ().project;
  1170. const auto& records = this->m_puppetClipping->records;
  1171. auto& overrides = this->m_materials.clippingOverrides;
  1172. const auto fboProvider = std::make_shared<FBOProvider> (this);
  1173. overrides.push_back (
  1174. std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  1175. .id = -1,
  1176. .combos = { { "CLIPPINGUVS", 1 }, { "CLIPPINGTARGET", 1 } },
  1177. .constants = {},
  1178. .textures = {},
  1179. })
  1180. );
  1181. this->m_puppetClipTargetPass = new CPass (
  1182. *this, fboProvider, this->m_puppetMeshPass->getPass (), *overrides.back (), std::nullopt, std::nullopt
  1183. );
  1184. this->m_puppetClipTargetPass->setTexture (8, this->getScene ().requireAlphaMaskFrameBuffer (false));
  1185. this->setupPuppetGeometryCallback (this->m_puppetClipTargetPass);
  1186. ComboMap maskCombos;
  1187. const auto& imagePasses = this->getImage ().model->material->passes;
  1188. if (!imagePasses.empty () && imagePasses.front ()->blending == BlendingMode_AlphaToCoverage) {
  1189. maskCombos.emplace ("ALPHATOCOVERAGE", 1);
  1190. }
  1191. this->m_materials.clippingMask = MaterialParser::load (project, "materials/util/clippingmaskimage4.json");
  1192. for (const auto& record : records) {
  1193. overrides.push_back (
  1194. std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  1195. .id = -1,
  1196. .combos = maskCombos,
  1197. .constants = {},
  1198. .textures = { { 1, record.mask } },
  1199. })
  1200. );
  1201. auto* pass = new CPass (
  1202. *this, fboProvider, **this->m_materials.clippingMask->passes.begin (), *overrides.back (), std::nullopt,
  1203. std::nullopt
  1204. );
  1205. pass->addUniform ("g_RenderVar0", &this->m_puppetClipRenderVar0);
  1206. pass->setClearColor (&this->m_puppetClipClearColor);
  1207. this->setupPuppetGeometryCallback (pass);
  1208. this->m_puppetClipMaskPasses.push_back (pass);
  1209. }
  1210. if (std::ranges::none_of (records, [] (const PuppetClipping::Record& record) { return record.parent != -1; })) {
  1211. return;
  1212. }
  1213. // nested masks: the intermediate goes through flattexture onto _rt_FullAlphaMask with identity matrices
  1214. constexpr GLfloat positions[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f };
  1215. constexpr GLfloat texcoords[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f };
  1216. glGenBuffers (1, &this->m_puppetClipComposePosition);
  1217. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetClipComposePosition);
  1218. glBufferData (GL_ARRAY_BUFFER, sizeof (positions), positions, GL_STATIC_DRAW);
  1219. glGenBuffers (1, &this->m_puppetClipComposeTexCoord);
  1220. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetClipComposeTexCoord);
  1221. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoords), texcoords, GL_STATIC_DRAW);
  1222. this->m_materials.clippingCompose = MaterialParser::load (project, "materials/util/flattexture.json");
  1223. auto* compose = new CPass (
  1224. *this, fboProvider, **this->m_materials.clippingCompose->passes.begin (), std::nullopt, std::nullopt,
  1225. std::nullopt
  1226. );
  1227. compose->setDestination (this->getScene ().requireAlphaMaskFrameBuffer (false));
  1228. compose->setInput (this->getScene ().requireAlphaMaskFrameBuffer (true));
  1229. compose->setKeepDestination (true);
  1230. compose->setModelViewProjectionMatrix (&this->m_puppetClipIdentity);
  1231. compose->setModelViewProjectionMatrixInverse (&this->m_puppetClipIdentity);
  1232. compose->setModelMatrix (&this->m_puppetClipIdentity);
  1233. compose->setViewProjectionMatrix (&this->m_puppetClipIdentity);
  1234. static const glm::mat3 identityNormal (1.0f);
  1235. compose->setLightingTransform (&this->m_puppetClipIdentity, &identityNormal, &this->m_puppetClipIdentity);
  1236. compose->setEffectTextureProjectionMatrix (&this->m_puppetClipIdentity, &this->m_puppetClipIdentity);
  1237. // sub_14020D6A0 sets the renderer alpha to 1 for it
  1238. compose->addUniform ("g_Alpha", &this->m_puppetClipComposeAlpha);
  1239. compose->setGeometryCallback (
  1240. [this, compose] () {
  1241. const GLint position = glGetAttribLocation (compose->getProgramID (), "a_Position");
  1242. const GLint texCoord = glGetAttribLocation (compose->getProgramID (), "a_TexCoord");
  1243. if (position >= 0) {
  1244. glEnableVertexAttribArray (position);
  1245. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetClipComposePosition);
  1246. glVertexAttribPointer (position, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  1247. }
  1248. if (texCoord >= 0) {
  1249. glEnableVertexAttribArray (texCoord);
  1250. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetClipComposeTexCoord);
  1251. glVertexAttribPointer (texCoord, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
  1252. }
  1253. },
  1254. [] () {
  1255. // translucent with renderer flag 0x100 (sub_140099F60): the source color becomes DEST_COLOR, alpha ONE/ONE,
  1256. // rgb written only, so the intermediate multiplies into the mask
  1257. GLboolean colorMask[4] = {};
  1258. glGetBooleanv (GL_COLOR_WRITEMASK, colorMask);
  1259. glEnable (GL_BLEND);
  1260. glBlendFuncSeparate (GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE);
  1261. glColorMask (true, true, true, false);
  1262. glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
  1263. glColorMask (colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
  1264. },
  1265. [compose] () {
  1266. for (const char* name : { "a_Position", "a_TexCoord" }) {
  1267. const GLint location = glGetAttribLocation (compose->getProgramID (), name);
  1268. if (location >= 0) {
  1269. glDisableVertexAttribArray (location);
  1270. }
  1271. }
  1272. }
  1273. );
  1274. this->m_puppetClipComposePass = compose;
  1275. }
  1276. void CImage::selectPuppetDraw (const int draw) {
  1277. if (draw < 0 || !this->m_puppetClipping.has_value ()
  1278. || static_cast<size_t> (draw) >= this->m_puppetClipping->draws.size ()) {
  1279. this->m_puppetDrawBuffer = this->m_puppetIndices;
  1280. this->m_puppetDrawOffset = 0;
  1281. this->m_puppetDrawCount = draw < 0 ? this->m_puppetIndexCount : 0;
  1282. return;
  1283. }
  1284. const auto& range = this->m_puppetClipping->draws[draw];
  1285. this->m_puppetDrawBuffer = this->m_puppetClipIndices;
  1286. this->m_puppetDrawOffset = static_cast<GLsizei> (range.offset);
  1287. this->m_puppetDrawCount = static_cast<GLsizei> (range.count);
  1288. }
  1289. void CImage::renderPuppetClipMask (
  1290. const Effects::CPass& meshPass, const int record, const int draw, const bool clear, const bool intermediate
  1291. ) {
  1292. auto& scene = this->getScene ();
  1293. auto* pass = this->m_puppetClipMaskPasses[record];
  1294. const bool inverted = this->m_puppetClipping->records[record].flags & PuppetClipping::Inverted;
  1295. pass->copyBindings (meshPass);
  1296. pass->setDestination (scene.requireAlphaMaskFrameBuffer (intermediate));
  1297. // a mesh going onto the scene may be drawn into a passthrough layer, the mask has to be laid out the same way
  1298. pass->setFollowLayerTarget (meshPass.getDestination () == scene.getFBO ());
  1299. pass->setKeepDestination (!clear && !intermediate);
  1300. this->m_puppetClipClearColor = glm::vec4 (inverted ? 1.0f : 0.0f);
  1301. this->m_puppetClipRenderVar0.x = inverted ? 1.0f : 0.0f;
  1302. this->selectPuppetDraw (draw);
  1303. pass->render ();
  1304. if (intermediate && this->m_puppetClipComposePass != nullptr) {
  1305. this->m_puppetClipComposePass->render ();
  1306. }
  1307. }
  1308. void CImage::renderPuppetClipped (Effects::CPass* meshPass) {
  1309. const auto& commands = this->m_puppetClipping->commands;
  1310. const auto& records = this->m_puppetClipping->records;
  1311. auto* target = this->m_puppetClipTargetPass;
  1312. int draw = 0;
  1313. bool drawn = false;
  1314. target->copyBindings (*meshPass);
  1315. const auto drawMesh = [&] (Effects::CPass* pass, const int index) {
  1316. this->selectPuppetDraw (index);
  1317. this->m_puppetDrawKeep = drawn;
  1318. pass->setKeepDestination (drawn);
  1319. pass->render ();
  1320. drawn = true;
  1321. };
  1322. const auto drawTargets = [&] (const int record, const int index) {
  1323. target->setBlendingMode (
  1324. records[record].flags & PuppetClipping::Additive ? BlendingMode_Additive : BlendingMode_Translucent
  1325. );
  1326. drawMesh (target, index);
  1327. };
  1328. for (size_t i = 0; i < commands.size (); i++) {
  1329. switch (commands[i]) {
  1330. case PuppetClipping::PlainDraw:
  1331. drawMesh (meshPass, draw++);
  1332. break;
  1333. case PuppetClipping::Mask:
  1334. {
  1335. const int record = commands[++i];
  1336. if (static_cast<size_t> (record) < records.size ()) {
  1337. this->renderPuppetClipMask (*meshPass, record, draw, true, false);
  1338. drawTargets (record, draw + 1);
  1339. }
  1340. draw += 2;
  1341. break;
  1342. }
  1343. case PuppetClipping::NestedMask:
  1344. {
  1345. const int chain = commands[++i];
  1346. for (int link = 0; link < chain; link++) {
  1347. const int parent = commands[++i];
  1348. const int parentDraw = commands[++i];
  1349. this->renderPuppetClipMask (*meshPass, parent, parentDraw, link == 0, link != 0);
  1350. }
  1351. const int record = commands[++i];
  1352. this->renderPuppetClipMask (*meshPass, record, draw, false, true);
  1353. drawTargets (record, draw + 1);
  1354. draw += 2;
  1355. break;
  1356. }
  1357. default:
  1358. break;
  1359. }
  1360. }
  1361. meshPass->setKeepDestination (false);
  1362. this->m_puppetDrawKeep = false;
  1363. this->selectPuppetDraw (-1);
  1364. }
  1365. bool CImage::followsOutputSize () const {
  1366. // a fullscreen layer takes its texture's size (sub_1401912C0), which for the usual one is _rt_FullFrameBuffer
  1367. return this->getImage ().model->fullscreen && this->m_texture == this->getScene ().getFBO ();
  1368. }
  1369. void CImage::addEffectPasses (const ImageEffect& effect) {
  1370. const auto fboProvider = std::make_shared<FBOProvider> (this);
  1371. for (const auto& fbo : effect.effect->fbos) {
  1372. const auto created = fboProvider->create (
  1373. *fbo,
  1374. this->m_image.model->passthrough ? (this->m_texture->getFlags () | TextureFlags_ClampUVs)
  1375. : this->m_texture->getFlags (),
  1376. this->getSize ()
  1377. );
  1378. if (this->followsOutputSize ()) {
  1379. this->getScene ().followOutputSize (created, fbo->scale);
  1380. }
  1381. }
  1382. auto curEffect = effect.effect->passes.begin ();
  1383. auto endEffect = effect.effect->passes.end ();
  1384. auto curOverride = effect.passOverrides.begin ();
  1385. auto endOverride = effect.passOverrides.end ();
  1386. for (; curEffect != endEffect; ++curEffect) {
  1387. if (!(*curEffect)->material.has_value ()) {
  1388. if (!(*curEffect)->command.has_value ()) {
  1389. sLog.error ("Pass without material and command not supported");
  1390. continue;
  1391. }
  1392. if (!(*curEffect)->source.has_value ()) {
  1393. sLog.error ("Pass without material and source not supported");
  1394. continue;
  1395. }
  1396. if (!(*curEffect)->target.has_value ()) {
  1397. sLog.error ("Pass without material and target not supported");
  1398. continue;
  1399. }
  1400. if ((*curEffect)->command != Command_Copy) {
  1401. sLog.error ("Only copy command is supported for pass without material");
  1402. continue;
  1403. }
  1404. auto virtualPass
  1405. = std::make_unique<MaterialPass> (MaterialPass { .blending = BlendingMode_Normal,
  1406. .cullmode = CullingMode_Disable,
  1407. .depthtest = DepthtestMode_Disabled,
  1408. .depthwrite = DepthwriteMode_Disabled,
  1409. .shader = "commands/copy",
  1410. .textures = { { 0, *(*curEffect)->source } },
  1411. .combos = {},
  1412. .constants = {} });
  1413. const auto& config = *this->m_virtualPassess.emplace_back (std::move (virtualPass));
  1414. this->m_passes.push_back (
  1415. new CPass (*this, fboProvider, config, std::nullopt, std::nullopt, (*curEffect)->target.value ())
  1416. );
  1417. } else {
  1418. for (auto& pass : (*curEffect)->material.value ()->passes) {
  1419. const auto override = curOverride != endOverride
  1420. ? **curOverride
  1421. : std::optional<std::reference_wrapper<const ImageEffectPassOverride>> (std::nullopt);
  1422. const auto target = (*curEffect)->target.has_value ()
  1423. ? *(*curEffect)->target
  1424. : std::optional<std::reference_wrapper<std::string>> (std::nullopt);
  1425. this->m_passes.push_back (new CPass (*this, fboProvider, *pass, override, (*curEffect)->binds, target));
  1426. }
  1427. if (curOverride != endOverride) {
  1428. ++curOverride;
  1429. }
  1430. }
  1431. }
  1432. }
  1433. void CImage::setup () {
  1434. if (this->m_initialized) {
  1435. return;
  1436. }
  1437. this->m_readByOtherLayer = std::ranges::any_of (this->getScene ().getScene ().objects, [this] (const auto& object) {
  1438. return object->id != this->getImage ().id
  1439. && std::ranges::find (object->dependencies, this->getImage ().id) != object->dependencies.end ();
  1440. });
  1441. this->m_hasPassthroughChildren = this->m_image.model->passthrough
  1442. && std::ranges::any_of (this->getScene ().getScene ().objects,
  1443. [this] (const auto& object) { return object->parent == this->getImage ().id; });
  1444. // passthrough without effects has nothing to draw unless another layer reads its _rt_imageLayerComposite or it
  1445. // has children to draw into its buffer
  1446. if (this->m_image.model->passthrough && this->m_image.effects.empty () && !this->m_readByOtherLayer
  1447. && !this->m_hasPassthroughChildren) {
  1448. return;
  1449. }
  1450. const auto& debug = this->getScene ().getContext ().getApp ().getContext ().settings.render.debug;
  1451. // a shape has no image of its own, only its effect is drawn (sub_14025FAF0)
  1452. if (!this->getImage ().shape) {
  1453. for (const auto& cur : this->getImage ().model->material->passes) {
  1454. this->m_passes.push_back (
  1455. new CPass (*this, std::make_shared<FBOProvider> (this), *cur, std::nullopt, std::nullopt, std::nullopt)
  1456. );
  1457. }
  1458. }
  1459. std::vector<const DynamicValue*> passVisibility (this->m_passes.size (), nullptr);
  1460. std::vector<bool> passFromEffect (this->m_passes.size (), false);
  1461. if (!debug.baseOnly && !this->getImage ().effects.empty ()) {
  1462. for (const auto& cur : this->m_image.effects) {
  1463. if (std::find (debug.skipEffects.begin (), debug.skipEffects.end (), static_cast<int> (cur->id))
  1464. != debug.skipEffects.end ()) {
  1465. continue;
  1466. }
  1467. const auto effectVisibility
  1468. = this->getScene ().getContext ().getApp ().getContext ().resolveEffectVisibility (
  1469. static_cast<int> (cur->id), cur->name
  1470. );
  1471. // an explicit --disable-effect/--enable-effect override wins over the scene's own visibility
  1472. if (effectVisibility.has_value () && !*effectVisibility) {
  1473. continue;
  1474. }
  1475. // scripts can toggle hidden effects at runtime; puppets can't, their mesh pass layout
  1476. // depends on the pass count
  1477. const bool followsVisibility = !effectVisibility.has_value () && !this->m_hasPuppetMesh;
  1478. if (!followsVisibility && !effectVisibility.has_value () && !cur->visible->value->getBool ()) {
  1479. continue;
  1480. }
  1481. const DynamicValue* visibleValue = followsVisibility ? cur->visible->value.get () : nullptr;
  1482. const size_t firstEffectPass = this->m_passes.size ();
  1483. try {
  1484. this->addEffectPasses (*cur);
  1485. } catch (const std::exception& e) {
  1486. if (visibleValue == nullptr || visibleValue->getBool ()) {
  1487. throw;
  1488. }
  1489. for (size_t i = firstEffectPass; i < this->m_passes.size (); i++) {
  1490. delete this->m_passes[i];
  1491. }
  1492. this->m_passes.resize (firstEffectPass);
  1493. sLog.error (
  1494. "Dropping hidden effect ", cur->id, " (", cur->name, ") on ", this->getImage ().name, ": ",
  1495. e.what ()
  1496. );
  1497. continue;
  1498. }
  1499. passVisibility.resize (this->m_passes.size (), visibleValue);
  1500. passFromEffect.resize (this->m_passes.size (), true);
  1501. }
  1502. }
  1503. const size_t passCountBeforeTrailingPasses = this->m_passes.size ();
  1504. if (!debug.baseOnly && !this->getImage ().shape) {
  1505. const auto magentaCompositeTint = findMagentaCompositeTint (this->m_image, debug.skipEffects);
  1506. if (magentaCompositeTint.has_value ()) {
  1507. auto tintOverride = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  1508. .id = -1,
  1509. .combos = {
  1510. { "BLENDMODE", 30 },
  1511. },
  1512. .constants = {},
  1513. .textures = {},
  1514. });
  1515. tintOverride->constants.emplace ("color", UserSettingBuilder::fromValue (magentaCompositeTint.value ()));
  1516. tintOverride->constants.emplace ("alpha", UserSettingBuilder::fromValue (1.0f));
  1517. this->m_materials.compatibilityMaterials.emplace_back (
  1518. MaterialParser::load (this->getScene ().getScene ().project, "materials/effects/tint.json")
  1519. );
  1520. this->m_materials.compatibilityOverrides.emplace_back (std::move (tintOverride));
  1521. this->m_passes.push_back (new CPass (
  1522. *this, std::make_shared<FBOProvider> (this),
  1523. **this->m_materials.compatibilityMaterials.back ()->passes.begin (),
  1524. *this->m_materials.compatibilityOverrides.back (), std::nullopt, std::nullopt
  1525. ));
  1526. }
  1527. }
  1528. const int colorBlendMode = this->m_image.colorBlendMode->value->getInt ();
  1529. // WE keeps the result of a layer another one reads in _a and only copies it to the screen from there,
  1530. // drawing the last effect pass straight to the screen would leave _a one pass behind (or empty)
  1531. const bool copyForReaders = this->m_readByOtherLayer && this->getImage ().visible->value->getBool ();
  1532. // fog sends every layer through its buffer and a FOG_COMPUTED composite (sub_1401E6F50, sub_1401EBBC0)
  1533. const bool fog = this->getScene ().hasDistanceFog () || this->getScene ().hasHeightFog ();
  1534. this->m_fogPass = nullptr;
  1535. // children go into the layer's buffer, which then needs a composite onto the scene even without effects
  1536. // (sub_1401E8AA0 with children, sub_140208670)
  1537. if (!debug.baseOnly && !this->getImage ().shape
  1538. && (colorBlendMode > 0 || copyForReaders || fog || this->m_hasPassthroughChildren)) {
  1539. // scenes from version 3 on composite with genericimage4, the one with fog (sub_1401EBBC0)
  1540. const auto& project = this->getScene ().getScene ().project;
  1541. this->m_materials.colorBlending.material = MaterialParser::load (
  1542. project,
  1543. project.sceneVersion >= 3 ? "materials/util/effectpassthrough_4.json"
  1544. : "materials/util/effectpassthrough.json"
  1545. );
  1546. ComboMap combos;
  1547. if (colorBlendMode > 0) {
  1548. combos.emplace ("BLENDMODE", colorBlendMode);
  1549. }
  1550. if (fog) {
  1551. combos.emplace ("FOG_COMPUTED", 1);
  1552. }
  1553. this->m_materials.colorBlending.override = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  1554. .id = -1,
  1555. .combos = combos,
  1556. .constants = {},
  1557. .textures = {},
  1558. });
  1559. this->m_passes.push_back (new CPass (
  1560. *this, std::make_shared<FBOProvider> (this), **this->m_materials.colorBlending.material->passes.begin (),
  1561. *this->m_materials.colorBlending.override, std::nullopt, std::nullopt
  1562. ));
  1563. // the layer buffer already holds color and alpha, WE draws this composite with a white renderer color
  1564. // (sub_1401E8AA0 sets renderer +288..+300 to 1 before it)
  1565. this->m_passes.back ()->setNeutralColor (true);
  1566. if (fog) {
  1567. this->m_fogPass = this->m_passes.back ();
  1568. }
  1569. }
  1570. if (this->m_hasPuppetMesh && !this->m_passes.empty ()) {
  1571. this->m_puppetMeshPass = this->m_passes.front ();
  1572. this->m_puppetMeshLast = this->m_passes.size () == 1;
  1573. // effect masks are laid out over the source texture, so effects run on the flat texture first
  1574. // and the warped mesh is drawn last, sampling their output
  1575. const auto& materialPasses = this->getImage ().model->material->passes;
  1576. const bool hasTrailingPasses = this->m_passes.size () != passCountBeforeTrailingPasses;
  1577. if (this->m_passes.size () > 1 && !hasTrailingPasses && materialPasses.size () == 1
  1578. && materialPasses.front ()->constants.empty ()) {
  1579. const auto& base = *materialPasses.front ();
  1580. const auto& config = *this->m_virtualPassess.emplace_back (
  1581. std::make_unique<MaterialPass> (MaterialPass {
  1582. .blending = base.blending,
  1583. .cullmode = base.cullmode,
  1584. .depthtest = base.depthtest,
  1585. .depthwrite = base.depthwrite,
  1586. .shader = base.shader,
  1587. .textures = {},
  1588. .usertextures = {},
  1589. .combos = base.combos,
  1590. .constants = {},
  1591. })
  1592. );
  1593. this->m_puppetMeshPass = new CPass (
  1594. *this, std::make_shared<FBOProvider> (this), config, std::nullopt, std::nullopt, std::nullopt
  1595. );
  1596. this->m_passes.push_back (this->m_puppetMeshPass);
  1597. this->m_puppetMeshLast = true;
  1598. }
  1599. }
  1600. this->setupPuppetClipping ();
  1601. passVisibility.resize (this->m_passes.size (), nullptr);
  1602. passFromEffect.resize (this->m_passes.size (), false);
  1603. for (size_t i = 0; i < this->m_passes.size (); i++) {
  1604. this->m_allPassStates.push_back (
  1605. { passVisibility[i], this->m_passes[i]->getBlendingMode (), passFromEffect[i] }
  1606. );
  1607. }
  1608. this->m_allPasses = this->m_passes;
  1609. CRenderable::setup ();
  1610. this->rebuildActivePasses ();
  1611. this->m_initialized = true;
  1612. }
  1613. bool CImage::effectVisibilityChanged () const {
  1614. for (size_t i = 0; i < this->m_allPassStates.size (); i++) {
  1615. const auto* visible = this->m_allPassStates[i].visible;
  1616. if (visible != nullptr && visible->getBool () != this->m_activePassMask[i]) {
  1617. return true;
  1618. }
  1619. }
  1620. return false;
  1621. }
  1622. void CImage::rebuildActivePasses () {
  1623. this->m_passes.clear ();
  1624. this->m_activePassMask.assign (this->m_allPasses.size (), false);
  1625. this->m_hasActiveEffectPass = false;
  1626. for (size_t i = 0; i < this->m_allPasses.size (); i++) {
  1627. const auto& state = this->m_allPassStates[i];
  1628. this->m_allPasses[i]->setBlendingMode (state.blending);
  1629. this->m_allPasses[i]->setDepthState (std::nullopt);
  1630. if (state.visible == nullptr || state.visible->getBool ()) {
  1631. this->m_activePassMask[i] = true;
  1632. this->m_hasActiveEffectPass |= state.fromEffect;
  1633. this->m_passes.push_back (this->m_allPasses[i]);
  1634. }
  1635. }
  1636. // if there's more than one pass the blendmode has to be moved from the beginning to the end
  1637. if (this->m_passes.size () > 1) {
  1638. const auto first = this->m_passes.begin ();
  1639. const auto last = this->m_passes.rbegin ();
  1640. (*last)->setBlendingMode ((*first)->getBlendingMode ());
  1641. (*first)->setBlendingMode (BlendingMode_Normal);
  1642. // the pass that draws an image's effects onto the scene also takes the image material's depth test and write
  1643. // (sub_1401EBF60 through image slot 33 sub_140209160, material bytes +498/+499): a 3D layer behind a model
  1644. // stays behind it (3453730450's moon_BBB)
  1645. const auto& materialPasses = this->getImage ().model->material->passes;
  1646. const auto lastState = std::ranges::find (this->m_allPasses, *last) - this->m_allPasses.begin ();
  1647. if (!this->getImage ().shape && !materialPasses.empty () && this->m_allPassStates[lastState].fromEffect) {
  1648. const auto& base = *materialPasses.front ();
  1649. (*last)->setDepthState (std::make_pair (base.depthtest, base.depthwrite));
  1650. }
  1651. }
  1652. // a shape's last pass goes onto the scene additively (its blend override sub_140260790 writes 2)
  1653. if (this->getImage ().shape && !this->m_passes.empty ()) {
  1654. this->m_passes.back ()->setBlendingMode (BlendingMode_Additive);
  1655. }
  1656. // setupPasses() ping-pongs these, every rebuild has to start from the same pair
  1657. this->m_currentMainFBO = this->m_mainFBO;
  1658. this->m_currentSubFBO = this->m_subFBO;
  1659. this->setupPasses ();
  1660. }
  1661. void CImage::setupPasses () {
  1662. // like WE, start on whichever buffer makes the last offscreen pass land in _a, which is what other layers read
  1663. auto offscreenPasses = std::ranges::count_if (this->m_passes, [] (const Effects::CPass* pass) {
  1664. return !pass->getTarget ().has_value ();
  1665. });
  1666. this->m_passesDrawToScreen = this->shouldRenderFinalPass (true);
  1667. if (!this->m_passes.empty () && !this->m_passes.back ()->getTarget ().has_value () && this->m_passesDrawToScreen) {
  1668. offscreenPasses--;
  1669. }
  1670. if (offscreenPasses % 2 == 0) {
  1671. std::swap (this->m_currentMainFBO, this->m_currentSubFBO);
  1672. }
  1673. std::shared_ptr<const CFBO> drawTo = this->m_currentMainFBO;
  1674. std::shared_ptr<const TextureProvider> asInput = this->getTexture ();
  1675. GLuint texcoord = this->getTexCoordCopy ();
  1676. auto cur = this->m_passes.begin ();
  1677. auto end = this->m_passes.end ();
  1678. bool first = true;
  1679. bool inTargetEffectSequence = false;
  1680. std::shared_ptr<const TextureProvider> effectInput = nullptr;
  1681. for (; cur != end; ++cur) {
  1682. Effects::CPass* pass = *cur;
  1683. std::shared_ptr<const CFBO> prevDrawTo = drawTo;
  1684. bool writesToTarget = false;
  1685. const bool isFirstPass = first;
  1686. const bool isMeshPass = this->m_hasPuppetMesh && pass == this->m_puppetMeshPass;
  1687. GLuint spacePosition = isMeshPass ? this->m_puppetSpacePosition
  1688. : isFirstPass ? this->getCopySpacePosition ()
  1689. : this->getPassSpacePosition ();
  1690. const glm::mat4* projection
  1691. = (isFirstPass) ? &this->m_modelViewProjectionCopy : &this->m_modelViewProjectionPass;
  1692. const glm::mat4* inverseProjection
  1693. = (isFirstPass) ? &this->m_modelViewProjectionCopyInverse : &this->m_modelViewProjectionPassInverse;
  1694. first = false;
  1695. if (isMeshPass) {
  1696. pass->setBlendingMode (BlendingMode_Translucent);
  1697. this->setupPuppetGeometryCallback (pass);
  1698. }
  1699. pass->setModelMatrix (&this->m_modelMatrix);
  1700. pass->setViewProjectionMatrix (&this->m_viewProjectionMatrix);
  1701. pass->setLayerModelMatrix (&this->m_layerModelMatrix);
  1702. pass->setEffectTextureProjectionMatrix (
  1703. &this->m_effectTextureProjection, &this->m_effectTextureProjectionInverse
  1704. );
  1705. writesToTarget = this->configurePassTarget (pass, drawTo, asInput, effectInput, inTargetEffectSequence);
  1706. // TODO: PROPERLY CHECK IF THIS IS ALL THAT'S NEEDED
  1707. if (!writesToTarget && this->shouldRenderFinalPass (std::next (cur) == end)) {
  1708. drawTo = this->getScene ().getFBO ();
  1709. // A puppet with no effects has its geometry pass be both the first AND the last pass, drawn
  1710. // straight into the shared scene FBO below - same as any other object's final pass, so it
  1711. // needs the same screen-space projection. updatePuppetPositionBuffer() bakes this object's
  1712. // resolved scene position/scale directly into m_puppetSpacePosition (mirroring what
  1713. // uploadGeometryBuffers does for a normal quad's sceneSpacePosition), so m_modelViewProjectionScreen
  1714. // is the correct projection for those vertices now, not the local-canvas m_modelViewProjectionCopy
  1715. // this pass otherwise uses when rendering to an intermediate, object-sized target. The
  1716. // spacePosition reassignment below is a no-op for puppets either way - the puppet geometry
  1717. // callback always binds m_puppetSpacePosition itself, ignoring whatever spacePosition holds.
  1718. spacePosition = this->getSceneSpacePosition ();
  1719. projection = &this->m_modelViewProjectionScreen;
  1720. // WE's final pass inverse lands in the layer's local space (origin at its center, unscaled
  1721. // pixels); older shaders like the bundled xray.vert unproject the pointer through it
  1722. inverseProjection = &this->m_objectSpaceProjectionInverse;
  1723. }
  1724. pass->setLightingTransform (
  1725. projection == &this->m_modelViewProjectionCopy ? &this->m_lightingCopyModel : &this->m_lightingSceneModel,
  1726. &this->m_lightingNormal, &this->m_lightingViewProjection
  1727. );
  1728. // the fog composite measures in WE's world, the lighting model already maps the layer there
  1729. if (pass == this->m_fogPass && projection == &this->m_modelViewProjectionScreen) {
  1730. pass->setModelMatrix (&this->m_lightingSceneModel);
  1731. pass->setFogWorld (true);
  1732. }
  1733. pass->setDestination (drawTo);
  1734. pass->setInput (asInput);
  1735. pass->setPreviousInput (inTargetEffectSequence ? effectInput : nullptr);
  1736. pass->setPosition (spacePosition);
  1737. pass->setTexCoord (texcoord);
  1738. pass->setModelViewProjectionMatrix (projection);
  1739. pass->setModelViewProjectionMatrixInverse (inverseProjection);
  1740. // what WE's intermediate passes see as g_EffectModelViewProjectionMatrix: their geometry where the layer
  1741. // is on screen (sub_1401EBF60), the final pass keeps its own MVP
  1742. pass->setEffectModelViewProjectionMatrix (
  1743. projection == &this->m_modelViewProjectionCopy ? &this->m_effectModelViewProjectionCopy
  1744. : projection == &this->m_modelViewProjectionPass ? &this->m_effectModelViewProjectionPass
  1745. : nullptr
  1746. );
  1747. texcoord = this->getTexCoordPass ();
  1748. if (writesToTarget) {
  1749. asInput = drawTo;
  1750. drawTo = prevDrawTo;
  1751. } else {
  1752. drawTo = prevDrawTo;
  1753. this->pinpongFramebuffer (&drawTo, &asInput);
  1754. inTargetEffectSequence = false;
  1755. effectInput = nullptr;
  1756. }
  1757. }
  1758. }
  1759. bool CImage::shouldRenderFinalPass (bool isLastPass) const {
  1760. const auto& appContext = this->getScene ().getContext ().getApp ().getContext ();
  1761. const auto visibility = appContext.resolveObjectVisibility (this->getId (), this->getObject ().name);
  1762. const bool visible = visibility.value_or (this->getImage ().visible->value->getBool ());
  1763. if (!isLastPass || !visible) {
  1764. return false;
  1765. }
  1766. const auto& debug = this->getScene ().getContext ().getApp ().getContext ().settings.render.debug;
  1767. return !(debug.noSolidFinal && this->getImage ().model->solidlayer);
  1768. }
  1769. bool CImage::configurePassTarget (
  1770. Effects::CPass* pass, std::shared_ptr<const CFBO>& drawTo, const std::shared_ptr<const TextureProvider>& asInput,
  1771. std::shared_ptr<const TextureProvider>& effectInput, bool& inTargetEffectSequence
  1772. ) {
  1773. if (!pass->getTarget ().has_value ()) {
  1774. return false;
  1775. }
  1776. const std::string target = pass->getTarget ().value ();
  1777. std::shared_ptr<const CFBO> resolved = pass->getFBOProvider ()->find (target);
  1778. if (resolved == nullptr) {
  1779. resolved = this->getScene ().findFBO (target);
  1780. }
  1781. if (resolved == nullptr) {
  1782. sLog.error (
  1783. "Pass target FBO '", target, "' could not be resolved for object ", pass->getRenderable ().getId (),
  1784. " shader=", pass->getPass ().shader
  1785. );
  1786. return false;
  1787. }
  1788. if (!inTargetEffectSequence) {
  1789. effectInput = asInput;
  1790. inTargetEffectSequence = true;
  1791. }
  1792. drawTo = resolved;
  1793. return true;
  1794. }
  1795. void CImage::pinpongFramebuffer (std::shared_ptr<const CFBO>* drawTo, std::shared_ptr<const TextureProvider>* asInput) {
  1796. std::shared_ptr<const CFBO> currentMainFBO = this->m_currentMainFBO;
  1797. std::shared_ptr<const CFBO> currentSubFBO = this->m_currentSubFBO;
  1798. if (drawTo != nullptr) {
  1799. *drawTo = currentSubFBO;
  1800. }
  1801. if (asInput != nullptr) {
  1802. *asInput = currentMainFBO;
  1803. }
  1804. this->m_currentMainFBO = currentSubFBO;
  1805. this->m_currentSubFBO = currentMainFBO;
  1806. }
  1807. void CImage::render () {
  1808. if (!this->m_initialized) {
  1809. return;
  1810. }
  1811. const auto& appContext = this->getScene ().getContext ().getApp ().getContext ();
  1812. const auto visibility = appContext.resolveObjectVisibility (this->getId (), this->getObject ().name);
  1813. // a hidden layer another object reads through _rt_imageLayerComposite_<id> (xray's "bloody" twins) still
  1814. // has to fill that FBO every frame, shouldRenderFinalPass() keeps it off the screen
  1815. if (!visibility.value_or (this->getImage ().visible->value->getBool ())
  1816. && (visibility.has_value () || !this->m_isDependency)) {
  1817. return;
  1818. }
  1819. // the last pass only goes to the screen if the layer was visible when the passes were set up,
  1820. // layers a script shows later (hidden in scene.json) need that redone
  1821. if (this->effectVisibilityChanged () || this->shouldRenderFinalPass (true) != this->m_passesDrawToScreen) {
  1822. this->rebuildActivePasses ();
  1823. }
  1824. if (this->m_image.model->passthrough && !this->m_hasActiveEffectPass && !this->m_readByOtherLayer
  1825. && !this->m_hasPassthroughChildren) {
  1826. return;
  1827. }
  1828. glColorMask (true, true, true, true);
  1829. this->updateScreenSpacePosition ();
  1830. if (this->m_hasPuppetMesh) {
  1831. this->updatePuppetSkinning ();
  1832. }
  1833. #if !NDEBUG
  1834. std::string str = "Image ";
  1835. if (this->getScene ().getScene ().camera.bloom.enabled->value->getBool () && this->getId () == -1) {
  1836. str += "bloom";
  1837. } else {
  1838. str += this->getImage ().name + " (" + std::to_string (this->getId ()) + ", "
  1839. + this->getImage ().model->material->filename + ")";
  1840. }
  1841. glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, str.c_str ());
  1842. #endif /* DEBUG */
  1843. // WE (sub_140207B50): a passthrough layer without copybackground clears its buffer to 0,0,0,0 instead of
  1844. // drawing the scene behind it, so its effects start from a transparent image
  1845. const Effects::CPass* skippedBasePass = this->m_image.model->passthrough
  1846. && !this->m_image.copyBackground->value->getBool () && !this->m_allPasses.empty ()
  1847. ? this->m_allPasses.front ()
  1848. : nullptr;
  1849. auto cur = this->m_passes.begin ();
  1850. const auto end = this->m_passes.end ();
  1851. for (; cur != end; ++cur) {
  1852. // the scene keeps its own alpha, but a hidden dependency's last pass fills the _a buffer other layers
  1853. // read and needs its alpha (2938612768's audio cover drawn through the background's blend effects)
  1854. if (std::next (cur) == end && this->m_passesDrawToScreen) {
  1855. glColorMask (true, true, true, false);
  1856. }
  1857. if (*cur == skippedBasePass && std::next (cur) != end) {
  1858. (*cur)->clearDestination ();
  1859. } else if (*cur == this->m_puppetMeshPass && this->m_puppetClipTargetPass != nullptr) {
  1860. this->renderPuppetClipped (*cur);
  1861. } else {
  1862. (*cur)->render ();
  1863. }
  1864. if (this->m_hasPassthroughChildren && *cur == this->m_allPasses.front () && std::next (cur) != end) {
  1865. this->renderPassthroughChildren ((*cur)->getDestination ());
  1866. // the children's final passes leave the scene's rgb only mask behind
  1867. glColorMask (true, true, true, true);
  1868. }
  1869. }
  1870. // restore alpha writes - CParticle::render() never resets glColorMask, so leaving this
  1871. // disabled here leaks into the next frame's clear if bloom renders last
  1872. glColorMask (true, true, true, true);
  1873. #if !NDEBUG
  1874. glPopDebugGroup ();
  1875. #endif /* DEBUG */
  1876. }
  1877. const float& CImage::getBrightness () const { return this->m_image.brightness->value->getFloat (); }
  1878. const float& CImage::getUserAlpha () const { return this->getAlpha (); }
  1879. const float& CImage::getAlpha () const {
  1880. // some scenes store out-of-range alpha (e.g. 222) - it feeds mix() in blend modes, so it must stay in 0..1
  1881. m_alphaCache = glm::clamp (this->m_image.alpha->value->getFloat (), 0.0f, 1.0f);
  1882. return m_alphaCache;
  1883. }
  1884. const glm::vec3& CImage::getColor () const {
  1885. // a solid layer showing an image the user picked draws it untinted, its color only tints the plain
  1886. // white fill (checked against WE with 3765586324's local file background, black and white color alike)
  1887. const glm::vec3 color
  1888. = this->showsUserTextureOnSolidLayer () ? glm::vec3 (1.0f) : this->m_image.color->value->getVec3 ();
  1889. // the object's brightness only scales its color in HDR scene rendering (sub_140207740)
  1890. m_colorCache = color * (this->getScene ().isHDR () ? this->m_image.brightness->value->getFloat () : 1.0f);
  1891. return m_colorCache;
  1892. }
  1893. bool CImage::showsUserTextureOnSolidLayer () const {
  1894. if (!this->m_image.model->solidlayer || this->m_image.model->material->passes.empty ()) {
  1895. return false;
  1896. }
  1897. const auto& properties = this->getScene ().getScene ().project.properties;
  1898. for (const auto& [index, propertyName] : (*this->m_image.model->material->passes.begin ())->usertextures) {
  1899. const auto it = properties.find (propertyName);
  1900. if (it != properties.end () && !it->second->is<Data::Model::PropertyUserShortcut> ()
  1901. && !it->second->getString ().empty ()) {
  1902. return true;
  1903. }
  1904. }
  1905. return false;
  1906. }
  1907. const glm::vec4& CImage::getColor4 () const {
  1908. // "version" 2 materials take color and alpha together through g_Color4
  1909. m_color4Cache = glm::vec4 (this->getColor (), this->getAlpha ());
  1910. return m_color4Cache;
  1911. }
  1912. const glm::vec3& CImage::getCompositeColor () const { return this->m_image.color->value->getVec3 (); }
  1913. glm::vec2 CImage::resolveGeometrySize (float sceneWidth, float sceneHeight, glm::vec3& origin) const {
  1914. glm::vec2 size = this->getSize ();
  1915. if ((size.x == 0.0f || size.y == 0.0f) && this->m_texture != nullptr) {
  1916. size.x = static_cast<float> (this->m_texture->getRealWidth ());
  1917. size.y = static_cast<float> (this->m_texture->getRealHeight ());
  1918. } else if (
  1919. (size.x == 0.0f || size.y == 0.0f) && this->getImage ().model->width.has_value ()
  1920. && this->getImage ().model->height.has_value ()
  1921. ) {
  1922. size.x = static_cast<float> (this->getImage ().model->width.value ());
  1923. size.y = static_cast<float> (this->getImage ().model->height.value ());
  1924. }
  1925. if (this->getImage ().model->fullscreen) {
  1926. size = { static_cast<float> (this->getScene ().getCanvasWidth ()),
  1927. static_cast<float> (this->getScene ().getCanvasHeight ()) };
  1928. origin = { sceneWidth / 2.0f, sceneHeight / 2.0f, 0.0f };
  1929. }
  1930. return size;
  1931. }
  1932. void CImage::updateScenePosition (
  1933. const glm::vec3& origin, const glm::vec2& size, const glm::vec3& scale, float sceneWidth, float sceneHeight
  1934. ) {
  1935. glm::vec2 displaySize = size;
  1936. const glm::vec2 declared = this->getImage ().size;
  1937. const auto& model = *this->getImage ().model;
  1938. if (!model.fullscreen && !model.autosize && !model.puppet.has_value () && declared.x > 0.0f && declared.y > 0.0f) {
  1939. displaySize = declared;
  1940. }
  1941. const glm::vec2 scaledSize = displaySize * glm::vec2 (scale);
  1942. this->m_displaySize = displaySize;
  1943. this->m_pos.x = origin.x - (scaledSize.x / 2.0f);
  1944. this->m_pos.w = origin.y + (scaledSize.y / 2.0f);
  1945. this->m_pos.z = origin.x + (scaledSize.x / 2.0f);
  1946. this->m_pos.y = origin.y - (scaledSize.y / 2.0f);
  1947. const uint32_t alignment
  1948. = Data::Parsers::ObjectParser::parseAlignment (this->getImage ().alignmentName->value->getString ());
  1949. if (alignment & ImageAlignment_Top) {
  1950. this->m_pos.y -= scaledSize.y / 2.0f;
  1951. this->m_pos.w -= scaledSize.y / 2.0f;
  1952. } else if (alignment & ImageAlignment_Bottom) {
  1953. this->m_pos.y += scaledSize.y / 2.0f;
  1954. this->m_pos.w += scaledSize.y / 2.0f;
  1955. }
  1956. if (alignment & ImageAlignment_Left) {
  1957. this->m_pos.x += scaledSize.x / 2.0f;
  1958. this->m_pos.z += scaledSize.x / 2.0f;
  1959. } else if (alignment & ImageAlignment_Right) {
  1960. this->m_pos.x -= scaledSize.x / 2.0f;
  1961. this->m_pos.z -= scaledSize.x / 2.0f;
  1962. }
  1963. this->m_scenePivot = { origin.x - sceneWidth / 2.0f, sceneHeight / 2.0f - origin.y, 0.0f };
  1964. this->m_pos.x -= sceneWidth / 2.0f;
  1965. this->m_pos.y = sceneHeight / 2.0f - this->m_pos.y;
  1966. this->m_pos.z -= sceneWidth / 2.0f;
  1967. this->m_pos.w = sceneHeight / 2.0f - this->m_pos.w;
  1968. }
  1969. void CImage::uploadGeometryBuffers (const glm::vec2& size) {
  1970. GLfloat sceneSpacePosition[] = { this->m_pos.x, this->m_pos.y, 0.0f, this->m_pos.x, this->m_pos.w, 0.0f,
  1971. this->m_pos.z, this->m_pos.y, 0.0f, this->m_pos.z, this->m_pos.y, 0.0f,
  1972. this->m_pos.x, this->m_pos.w, 0.0f, this->m_pos.z, this->m_pos.w, 0.0f };
  1973. float width = 1.0f;
  1974. float height = 1.0f;
  1975. if (this->getTexture () != nullptr && !this->getTexture ()->isAnimated ()
  1976. && (this->getTexture ()->getTextureWidth (0) != this->getTexture ()->getRealWidth ()
  1977. || this->getTexture ()->getTextureHeight (0) != this->getTexture ()->getRealHeight ())) {
  1978. width = static_cast<float> (this->getTexture ()->getRealWidth ())
  1979. / static_cast<float> (this->getTexture ()->getTextureWidth (0));
  1980. height = static_cast<float> (this->getTexture ()->getRealHeight ())
  1981. / static_cast<float> (this->getTexture ()->getTextureHeight (0));
  1982. }
  1983. float x = 0.0f;
  1984. float y = 0.0f;
  1985. GLfloat realWidth = size.x;
  1986. GLfloat realHeight = size.y;
  1987. GLfloat realX = 0.0f;
  1988. GLfloat realY = 0.0f;
  1989. if (this->getImage ().model->passthrough) {
  1990. width = 1.0f;
  1991. height = 1.0f;
  1992. realX = this->m_pos.x;
  1993. realY = this->m_pos.w;
  1994. realWidth = this->m_pos.z;
  1995. realHeight = this->m_pos.y;
  1996. if (this->getImage ().model->fullscreen) {
  1997. realX = -1.0f;
  1998. realY = -1.0f;
  1999. realWidth = 1.0f;
  2000. realHeight = 1.0f;
  2001. }
  2002. }
  2003. GLfloat texcoordCopy[] = { x, height, x, y, width, height, width, height, x, y, width, y };
  2004. GLfloat copySpacePosition[] = { realX, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realHeight, 0.0f,
  2005. realWidth, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realY, 0.0f };
  2006. glBindBuffer (GL_ARRAY_BUFFER, this->m_sceneSpacePosition);
  2007. glBufferData (GL_ARRAY_BUFFER, sizeof (sceneSpacePosition), sceneSpacePosition, GL_DYNAMIC_DRAW);
  2008. glBindBuffer (GL_ARRAY_BUFFER, this->m_copySpacePosition);
  2009. glBufferData (GL_ARRAY_BUFFER, sizeof (copySpacePosition), copySpacePosition, GL_DYNAMIC_DRAW);
  2010. glBindBuffer (GL_ARRAY_BUFFER, this->m_texcoordCopy);
  2011. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoordCopy), texcoordCopy, GL_DYNAMIC_DRAW);
  2012. this->m_modelViewProjectionCopy = this->getImage ().model->passthrough
  2013. ? this->m_modelViewProjectionScreen
  2014. : glm::ortho<float> (0.0, size.x, 0.0, size.y);
  2015. this->m_modelViewProjectionCopyInverse = glm::inverse (this->m_modelViewProjectionCopy);
  2016. this->m_modelMatrix = glm::ortho<float> (0.0, size.x, 0.0, size.y);
  2017. }
  2018. CImage::ResolvedTransform CImage::updateGeometryBuffers () {
  2019. auto sceneWidth = static_cast<float> (this->getScene ().getWidth ());
  2020. auto sceneHeight = static_cast<float> (this->getScene ().getHeight ());
  2021. const auto transform = this->resolveTransform (this->getImage ());
  2022. glm::vec3 origin = transform.origin;
  2023. const glm::vec3 scale = transform.scale;
  2024. const glm::vec2 size = this->resolveGeometrySize (sceneWidth, sceneHeight, origin);
  2025. this->m_size = size;
  2026. this->m_puppetScale = scale;
  2027. // must run before the puppet position buffer rebake below - it needs this frame's m_pos, not the
  2028. // previous one, to place puppet vertices at this object's actual scene position instead of its
  2029. // position from before whatever moved it (parallax, a script, an attachment point it follows, ...)
  2030. this->updateScenePosition (origin, size, scale, sceneWidth, sceneHeight);
  2031. if (this->m_pos != this->m_lastUploadedPos || size != this->m_lastUploadedGeometrySize) {
  2032. this->uploadGeometryBuffers (size);
  2033. // puppet vertices bake m_pos/scale in directly (see updatePuppetPositionBuffer), so they need
  2034. // the same "position or size changed" rebake trigger as the quad buffers above - a puppet whose
  2035. // animation is disabled (or one with no MDLA data at all, i.e. always static) would otherwise
  2036. // never get repositioned after its very first, load-time bake
  2037. if (this->m_hasPuppetMesh) {
  2038. this->updatePuppetPositionBuffer (size);
  2039. }
  2040. this->m_lastUploadedPos = this->m_pos;
  2041. this->m_lastUploadedGeometrySize = size;
  2042. }
  2043. return transform;
  2044. }
  2045. namespace {
  2046. // keeps an edge pair (e.g. m_pos.x/.z) from sliding into the on-screen part of the canvas once `offset` is added
  2047. // to both, so the image never uncovers ground it doesn't have pixels for; an image too small to cover it on this
  2048. // axis has no ground to uncover, it is an object sitting on the scene and moves freely. Canvas cropped away by the
  2049. // cover scaling is free to scroll in, WE has no clamp at all (sub_14018AAC0 adds the raw offset to the view)
  2050. float clampParallaxAxis (float offset, float edgeA, float edgeB, float visibleLow, float visibleHigh) {
  2051. const float low = std::min (edgeA, edgeB);
  2052. const float high = std::max (edgeA, edgeB);
  2053. const float maxOffset = visibleLow - low;
  2054. const float minOffset = visibleHigh - high;
  2055. if (minOffset > maxOffset) {
  2056. return offset;
  2057. }
  2058. // a layer that doesn't cover the screen at rest stays where the scene puts it (3621923790's hair), the clamp
  2059. // only keeps the parallax from uncovering more
  2060. return std::clamp (offset, std::min (minOffset, 0.0f), std::max (maxOffset, 0.0f));
  2061. }
  2062. } // namespace
  2063. glm::mat4 CImage::ancestorTiltCorrection () const {
  2064. // the quad above is placed with the parent chain folded in 2D (origin, scale, z angle). WE multiplies the full
  2065. // world matrix into the model stack instead (sub_1401E8AA0), so parents' x/y angles tilt their children too:
  2066. // map from the chain without those angles to the full one, in this centered y down space
  2067. const auto& scene = this->getScene ();
  2068. const auto localMatrix = [] (const Object& object, bool tilt) {
  2069. glm::vec3 scale = object.groupScale->value->getVec3 ();
  2070. glm::vec3 angles = object.groupAngles->value->getVec3 ();
  2071. if (object.is<Image> ()) {
  2072. scale = object.as<Image> ()->scale->value->getVec3 ();
  2073. angles = object.as<Image> ()->angles->value->getVec3 ();
  2074. } else if (object.is<Particle> ()) {
  2075. scale = object.as<Particle> ()->scale->value->getVec3 ();
  2076. angles = object.as<Particle> ()->angles->value->getVec3 ();
  2077. } else if (object.is<Text> ()) {
  2078. scale = object.as<Text> ()->scale->value->getVec3 ();
  2079. }
  2080. glm::mat4 local = glm::translate (glm::mat4 (1.0f), object.origin->value->getVec3 ());
  2081. local = glm::rotate (local, angles.z, glm::vec3 (0.0f, 0.0f, 1.0f));
  2082. if (tilt) {
  2083. local = glm::rotate (local, angles.y, glm::vec3 (0.0f, 1.0f, 0.0f));
  2084. local = glm::rotate (local, angles.x, glm::vec3 (1.0f, 0.0f, 0.0f));
  2085. }
  2086. return std::pair { glm::scale (local, scale), angles.x != 0.0f || angles.y != 0.0f };
  2087. };
  2088. glm::mat4 full (1.0f);
  2089. glm::mat4 flat (1.0f);
  2090. bool tilted = false;
  2091. const Object* current = &this->getImage ();
  2092. for (int depth = 0; current->parent.has_value () && depth < 64; depth++) {
  2093. // attachments follow a puppet bone, which the folded chain resolves on its own
  2094. if (current->attachment.has_value ()) {
  2095. return glm::mat4 (1.0f);
  2096. }
  2097. const CObject* parent = scene.getObject (current->parent.value ());
  2098. if (parent == nullptr) {
  2099. break;
  2100. }
  2101. current = &parent->getObject ();
  2102. const auto [withTilt, hasTilt] = localMatrix (*current, true);
  2103. full = withTilt * full;
  2104. flat = localMatrix (*current, false).first * flat;
  2105. tilted |= hasTilt;
  2106. }
  2107. if (!tilted) {
  2108. return glm::mat4 (1.0f);
  2109. }
  2110. const glm::mat4 toScreen = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
  2111. * glm::translate (glm::mat4 (1.0f), glm::vec3 (-scene.getWidth () / 2.0f, -scene.getHeight () / 2.0f, 0.0f));
  2112. return toScreen * full * glm::inverse (flat) * glm::inverse (toScreen);
  2113. }
  2114. void CImage::updateScreenSpacePosition () {
  2115. const ResolvedTransform transform = this->updateGeometryBuffers ();
  2116. // angles are already in radians from scene.json. WE's Rz * Ry * Rx seen through the y flip of this space is
  2117. // Rz (-z) * Ry (y) * Rx (-x) (see CParticle.cpp). Only the object's own x/y angles, the parent chain folds z only
  2118. const float angle = transform.angle;
  2119. const glm::vec3 ownAngles = this->getImage ().angles->value->getVec3 ();
  2120. // origin z only shows through a perspective camera, the ortho one keeps -2000..2000 like WE
  2121. glm::mat4 rotModel = glm::translate (glm::mat4 (1.0f), glm::vec3 (0.0f, 0.0f, transform.origin.z));
  2122. if (angle != 0.0f || ownAngles.x != 0.0f || ownAngles.y != 0.0f) {
  2123. rotModel = glm::translate (rotModel, this->m_scenePivot);
  2124. rotModel = glm::rotate (rotModel, -angle, glm::vec3 (0.0f, 0.0f, 1.0f));
  2125. rotModel = glm::rotate (rotModel, ownAngles.y, glm::vec3 (0.0f, 1.0f, 0.0f));
  2126. rotModel = glm::rotate (rotModel, -ownAngles.x, glm::vec3 (1.0f, 0.0f, 0.0f));
  2127. rotModel = glm::translate (rotModel, -this->m_scenePivot);
  2128. }
  2129. rotModel = this->ancestorTiltCorrection () * rotModel;
  2130. glm::mat4 mvp = this->getViewProjection () * rotModel;
  2131. const bool fullscreen = this->getImage ().model->fullscreen;
  2132. const auto& camera = this->getScene ().getCamera ();
  2133. // WE draws fullscreen layers with an identity transform, camera movement and parallax don't reach them
  2134. if (fullscreen) {
  2135. mvp = camera.getFullscreenProjection ();
  2136. } else if (camera.isPerspective () && !this->m_hasPuppetMesh) {
  2137. // 3D scenes: the quad (size in world units) goes through the scene camera with the image's world matrix like
  2138. // any other object (sub_1401E8AA0), "perspective" layers through their own camera. The vertices here are laid
  2139. // out in the 2D scene space, this takes them back to the object's own space first. WE's quad is the declared
  2140. // size (+752, sub_1402066A0) whatever the texture size, like the 2D layout
  2141. const glm::vec2 size = this->m_displaySize;
  2142. const glm::vec2 extent (this->m_pos.z - this->m_pos.x, this->m_pos.w - this->m_pos.y);
  2143. if (extent.x != 0.0f && extent.y != 0.0f) {
  2144. const glm::vec3 center (
  2145. (this->m_pos.x + this->m_pos.z) / 2.0f, (this->m_pos.y + this->m_pos.w) / 2.0f, 0.0f
  2146. );
  2147. // z keeps scale 1 (the quad is flat anyway), a passthrough layer inverts this matrix to draw its children
  2148. const glm::mat4 toLocal
  2149. = glm::translate (glm::scale (glm::mat4 (1.0f), glm::vec3 (size / extent, 1.0f)), -center);
  2150. const glm::mat4 viewProjection = this->getImage ().perspective->value->getBool ()
  2151. ? camera.getPerspectiveLayerViewProjection ()
  2152. : this->getScene ().getWorldViewProjection ();
  2153. mvp = viewProjection * this->worldMatrix () * toLocal;
  2154. }
  2155. }
  2156. // CScene::renderFrame() already folds disableparallax into getParallaxDisplacement(). WE's camera parallax only
  2157. // exists in orthographic scenes (scene flags & 0x108, sub_14018AAC0)
  2158. if (this->getScene ().getScene ().camera.parallax.enabled->value->getBool () && !fullscreen
  2159. && !camera.isPerspective ()) {
  2160. const glm::vec2 offset = this->getScene ().getParallaxOffset (this->getImage ());
  2161. float x = offset.x;
  2162. float y = offset.y;
  2163. // a texture that isn't UV-clamped tiles/repeats instead of showing black past its edges (GL_REPEAT,
  2164. // see CTexture.cpp), so sliding it further is harmless and exempt from the clamp; scene.json's own
  2165. // "clampuvs" overrides the base texture's flag the same way it does for the composite FBOs above
  2166. const bool textureTiles = !this->getImage ().clampUVs && this->getTexture () != nullptr
  2167. && (this->getTexture ()->getFlags () & TextureFlags_ClampUVs) == 0;
  2168. if (this->getScene ().getContext ().getApp ().getContext ().settings.mouse.clampParallaxToImageSize
  2169. && !textureTiles) {
  2170. const glm::vec4 visible = this->getScene ().getVisibleCanvasRegion ();
  2171. x = clampParallaxAxis (x, this->m_pos.x, this->m_pos.z, visible.x, visible.y);
  2172. y = clampParallaxAxis (y, this->m_pos.y, this->m_pos.w, visible.z, visible.w);
  2173. }
  2174. // WE translates the view (sub_14018AAC0), so its offset isn't turned by the layer's own rotation. The clamp's
  2175. // correction is measured on the unrotated quad and stays inside the rotation
  2176. rotModel = glm::translate (glm::mat4 (1.0f), { offset.x, offset.y, 0.0f }) * rotModel
  2177. * glm::translate (glm::mat4 (1.0f), { x - offset.x, y - offset.y, 0.0f });
  2178. mvp = this->getViewProjection () * rotModel;
  2179. }
  2180. this->updateLightingTransform (rotModel);
  2181. // only the inverse is expensive; skip it when mvp didn't actually change
  2182. if (mvp != this->m_modelViewProjectionScreen) {
  2183. this->m_modelViewProjectionScreenInverse = glm::inverse (mvp);
  2184. }
  2185. this->m_modelViewProjectionScreen = mvp;
  2186. this->m_layerModelMatrix = this->getScene ().objectWorldMatrix (this->getImage ());
  2187. // buffer space (0..size, y = size at m_pos.y like the copy quad) onto the layer's scene quad, then the screen
  2188. const glm::vec2 bufferSize = this->m_size;
  2189. if (bufferSize.x > 0.0f && bufferSize.y > 0.0f) {
  2190. glm::mat4 bufferToScene (1.0f);
  2191. bufferToScene[0][0] = (this->m_pos.z - this->m_pos.x) / bufferSize.x;
  2192. bufferToScene[1][1] = (this->m_pos.y - this->m_pos.w) / bufferSize.y;
  2193. bufferToScene[3][0] = this->m_pos.x;
  2194. bufferToScene[3][1] = this->m_pos.w;
  2195. this->m_effectModelViewProjectionCopy = mvp * bufferToScene;
  2196. // later passes draw WE's unit quad (-1..1), sub_1401EBF60 scales it by half the layer size first
  2197. glm::mat4 unitToBuffer (1.0f);
  2198. unitToBuffer[0][0] = bufferSize.x * 0.5f;
  2199. unitToBuffer[1][1] = bufferSize.y * 0.5f;
  2200. unitToBuffer[3][0] = bufferSize.x * 0.5f;
  2201. unitToBuffer[3][1] = bufferSize.y * 0.5f;
  2202. this->m_effectModelViewProjectionPass = this->m_effectModelViewProjectionCopy * unitToBuffer;
  2203. }
  2204. this->updateEffectTextureProjection ();
  2205. if (this->getImage ().model->passthrough) {
  2206. this->m_modelViewProjectionCopy = this->m_modelViewProjectionScreen;
  2207. this->m_modelViewProjectionCopyInverse = this->m_modelViewProjectionScreenInverse;
  2208. }
  2209. }
  2210. glm::mat4 CImage::getViewProjection () const {
  2211. const auto& camera = this->getScene ().getCamera ();
  2212. // "perspective" layers get their own camera in 2D scenes (sub_1401E8AA0 -> sub_1401E5B60)
  2213. if (camera.isOrthogonal () && this->getImage ().perspective->value->getBool ()) {
  2214. return camera.getPerspectiveLayerViewProjection ();
  2215. }
  2216. return camera.getProjection () * camera.getLookAt ();
  2217. }
  2218. void CImage::updateLightingTransform (const glm::mat4& sceneTransform) {
  2219. const auto width = static_cast<float> (this->getScene ().getWidth ());
  2220. const auto height = static_cast<float> (this->getScene ().getHeight ());
  2221. const glm::mat4 toWorld = glm::scale (
  2222. glm::translate (glm::mat4 (1.0f), glm::vec3 (width / 2.0f, height / 2.0f, 0.0f)), glm::vec3 (1.0f, -1.0f, 1.0f)
  2223. );
  2224. const glm::mat3 flip = glm::mat3 (glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f)));
  2225. this->m_lightingSceneModel = toWorld * sceneTransform;
  2226. this->m_lightingNormal = flip * glm::mat3 (sceneTransform) * flip;
  2227. this->m_lightingViewProjection = this->getViewProjection () * glm::inverse (toWorld);
  2228. // the first pass draws into the layer's own buffer, (0, 0) there is the image's top left corner in the scene
  2229. if (this->getImage ().model->passthrough) {
  2230. this->m_lightingCopyModel = this->m_lightingSceneModel;
  2231. return;
  2232. }
  2233. const glm::vec2 size = glm::max (this->getSize (), glm::vec2 (1.0f));
  2234. const glm::mat4 copyToScene = glm::scale (
  2235. glm::translate (glm::mat4 (1.0f), glm::vec3 (this->m_pos.x, this->m_pos.w, 0.0f)),
  2236. glm::vec3 ((this->m_pos.z - this->m_pos.x) / size.x, (this->m_pos.y - this->m_pos.w) / size.y, 1.0f)
  2237. );
  2238. this->m_lightingCopyModel = this->m_lightingSceneModel * copyToScene;
  2239. }
  2240. void CImage::updateEffectTextureProjection () {
  2241. // the final quad puts texcoord (0, 0) at (m_pos.x, m_pos.w), which is the layer's local (-1, +1) corner;
  2242. // the scene FBO is y-flipped against the screen the pointer position is measured on, hence the flip
  2243. 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);
  2244. 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);
  2245. const glm::mat4 projection = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
  2246. * this->m_modelViewProjectionScreen * glm::scale (glm::translate (glm::mat4 (1.0f), center), halfSize);
  2247. if (projection == this->m_effectTextureProjection) {
  2248. return;
  2249. }
  2250. this->m_effectTextureProjection = projection;
  2251. // a zero-sized layer has no inverse, keep the last usable one instead of feeding NaNs to the shader
  2252. if (halfSize.x != 0.0f && halfSize.y != 0.0f) {
  2253. this->m_effectTextureProjectionInverse = glm::inverse (projection);
  2254. }
  2255. const glm::vec2 size = this->getSize ();
  2256. this->m_objectSpaceProjectionInverse = glm::scale (glm::mat4 (1.0f), glm::vec3 (size.x / 2.0f, size.y / 2.0f, 1.0f))
  2257. * this->m_effectTextureProjectionInverse;
  2258. }
  2259. const Image& CImage::getImage () const { return this->m_image; }
  2260. void CImage::markAsDependency () { this->m_isDependency = true; }
  2261. glm::vec2 CImage::getSize () const {
  2262. if (this->m_texture == nullptr) {
  2263. return this->getImage ().size;
  2264. }
  2265. // compose layers sample the whole scene, but effect masks map over the layer's own size
  2266. if (this->getImage ().model->passthrough && this->getImage ().size.x > 0.0f && this->getImage ().size.y > 0.0f) {
  2267. return this->getImage ().size;
  2268. }
  2269. // solid layers use a stock white texture, the real footprint is declared by the scene
  2270. if (this->getImage ().model->solidlayer && this->getImage ().size.x > 0.0f && this->getImage ().size.y > 0.0f) {
  2271. return this->getImage ().size;
  2272. }
  2273. return { this->m_texture->getRealWidth (), this->m_texture->getRealHeight () };
  2274. }
  2275. GLuint CImage::getSceneSpacePosition () const { return this->m_sceneSpacePosition; }
  2276. GLuint CImage::getCopySpacePosition () const { return this->m_copySpacePosition; }
  2277. GLuint CImage::getPassSpacePosition () const { return this->m_passSpacePosition; }
  2278. GLuint CImage::getTexCoordCopy () const { return this->m_texcoordCopy; }
  2279. GLuint CImage::getTexCoordPass () const { return this->m_texcoordPass; }