CImage.cpp 139 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586
  1. #include "CImage.h"
  2. #include "WallpaperEngine/Data/Model/Property.h"
  3. #include "WallpaperEngine/Data/Parsers/ObjectParser.h"
  4. #include "CMesh.h"
  5. #include "CRenderable.h"
  6. #include <algorithm>
  7. #include <array>
  8. #include <cmath>
  9. #include <cstdio>
  10. #include <cstdlib>
  11. #include <cstring>
  12. #include <iterator>
  13. #include <limits>
  14. #include <optional>
  15. #include <sstream>
  16. #include <strings.h>
  17. #include <tuple>
  18. #include <vector>
  19. #include <glm/glm.hpp>
  20. #include <glm/gtc/matrix_transform.hpp>
  21. #define GLM_ENABLE_EXPERIMENTAL
  22. #include <glm/gtx/rotate_vector.hpp>
  23. #undef GLM_ENABLE_EXPERIMENTAL
  24. #include "WallpaperEngine/Assets/AssetLoadException.h"
  25. #include "WallpaperEngine/Data/Model/DynamicValue.h"
  26. #include "WallpaperEngine/Data/Model/Material.h"
  27. #include "WallpaperEngine/Data/Model/Object.h"
  28. #include "WallpaperEngine/Data/Model/UserSetting.h"
  29. #include "WallpaperEngine/Data/Parsers/MaterialParser.h"
  30. #include "WallpaperEngine/Data/Utils/BinaryReader.h"
  31. #include "WallpaperEngine/Data/Utils/MemoryStream.h"
  32. #include "WallpaperEngine/Logging/Log.h"
  33. #include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
  34. #include "WallpaperEngine/Scripting/ScriptEngine.h"
  35. using namespace WallpaperEngine;
  36. using namespace WallpaperEngine::Render::Objects;
  37. using namespace WallpaperEngine::Render::Objects::Effects;
  38. using namespace WallpaperEngine::Data::Parsers;
  39. using namespace WallpaperEngine::Data::Builders;
  40. using namespace WallpaperEngine::Data::Utils;
  41. extern float g_Time;
  42. extern float g_TimeLast;
  43. namespace {
  44. glm::vec2 rotateVec2 (const glm::vec2& value, float angle) {
  45. const float cosAngle = std::cos (angle);
  46. const float sinAngle = std::sin (angle);
  47. return { value.x * cosAngle - value.y * sinAngle, value.x * sinAngle + value.y * cosAngle };
  48. }
  49. bool isMagentaNeonTint (const glm::vec3& color) { return color.r > 0.55f && color.g < 0.25f && color.b > 0.45f; }
  50. std::optional<glm::vec3> findMagentaCompositeTint (const Image& image, const std::vector<int>& skippedEffectIds) {
  51. for (const auto& effect : image.effects) {
  52. if (std::find (skippedEffectIds.begin (), skippedEffectIds.end (), static_cast<int> (effect->id))
  53. != skippedEffectIds.end ()) {
  54. continue;
  55. }
  56. if (!effect->visible->value->getBool ()) {
  57. continue;
  58. }
  59. for (const auto& passOverride : effect->passOverrides) {
  60. const auto compositeCombo = passOverride->combos.find ("COMPOSITE");
  61. if (compositeCombo == passOverride->combos.end () || compositeCombo->second != 2) {
  62. continue;
  63. }
  64. const auto compositeColor = passOverride->constants.find ("compositecolor");
  65. if (compositeColor == passOverride->constants.end () || compositeColor->second == nullptr
  66. || compositeColor->second->value == nullptr) {
  67. continue;
  68. }
  69. const auto tint = compositeColor->second->value->getVec3 ();
  70. if (isMagentaNeonTint (tint)) {
  71. return tint;
  72. }
  73. }
  74. }
  75. return std::nullopt;
  76. }
  77. struct PuppetMeshBlock {
  78. size_t headerOffset = 0;
  79. uint32_t vertexBytes = 0;
  80. uint32_t indexBytes = 0;
  81. };
  82. // Finds every byte offset that could plausibly be a MDLV mesh header (DWORD vertexByteLength
  83. // immediately followed by that many bytes of vertex data, then a DWORD indexByteLength followed by
  84. // that many bytes of indices, all landing before the MDLS block). This intentionally doesn't know or
  85. // care about the per-vertex stride - that's resolved afterwards against whatever candidates come back,
  86. // since the stride isn't reliably predictable from the MDLV header version alone (see
  87. // resolvePuppetVertexLayout).
  88. std::vector<PuppetMeshBlock> findPuppetMeshBlockCandidates (
  89. const BinaryReader& reader, size_t markerSize, size_t mdlsOffset, size_t meshHeaderSize
  90. ) {
  91. std::vector<PuppetMeshBlock> candidates;
  92. for (size_t offset = markerSize; offset + meshHeaderSize + sizeof (uint32_t) < mdlsOffset; offset++) {
  93. reader.base ().seekg (static_cast<std::streamoff> (offset + sizeof (uint32_t)), std::ios::beg);
  94. const uint32_t candidateVertexBytes = reader.nextUInt32 ();
  95. const size_t verticesOffset = offset + meshHeaderSize;
  96. const size_t indexLengthOffset = verticesOffset + candidateVertexBytes;
  97. if (candidateVertexBytes == 0 || indexLengthOffset + sizeof (uint32_t) > mdlsOffset) {
  98. continue;
  99. }
  100. reader.base ().seekg (static_cast<std::streamoff> (indexLengthOffset), std::ios::beg);
  101. const uint32_t candidateIndexBytes = reader.nextUInt32 ();
  102. const size_t indicesOffset = indexLengthOffset + sizeof (uint32_t);
  103. if (candidateIndexBytes == 0 || candidateIndexBytes % (sizeof (uint16_t) * 3) != 0
  104. || indicesOffset + candidateIndexBytes > mdlsOffset) {
  105. continue;
  106. }
  107. candidates.push_back (
  108. PuppetMeshBlock {
  109. .headerOffset = offset, .vertexBytes = candidateVertexBytes, .indexBytes = candidateIndexBytes }
  110. );
  111. }
  112. return candidates;
  113. }
  114. struct PuppetVertexLayout {
  115. PuppetMeshBlock block;
  116. size_t vertexStride = 0;
  117. size_t uvOffset = 0;
  118. };
  119. // Reads raw positions/UVs/indices for a candidate (block, stride) pair. The UV pair has only ever
  120. // been observed as the trailing 8 bytes of the vertex record, whatever bone/weight data precedes it
  121. // (position(12) + ... + uv(8)), so uvOffset = stride - 8 throughout.
  122. struct PuppetMeshData {
  123. std::vector<GLfloat> positions;
  124. std::vector<GLfloat> texcoords;
  125. std::vector<GLushort> indices;
  126. };
  127. std::optional<PuppetMeshData> readPuppetMeshData (
  128. const BinaryReader& reader, const PuppetMeshBlock& block, size_t meshHeaderSize, size_t vertexStride
  129. ) {
  130. if (block.vertexBytes % vertexStride != 0) {
  131. return std::nullopt;
  132. }
  133. const size_t uvOffset = vertexStride - sizeof (GLfloat) * 2;
  134. const size_t vertexCount = block.vertexBytes / vertexStride;
  135. const size_t verticesOffset = block.headerOffset + meshHeaderSize;
  136. const size_t indicesOffset = verticesOffset + block.vertexBytes + sizeof (uint32_t);
  137. const size_t indexCount = block.indexBytes / sizeof (uint16_t);
  138. PuppetMeshData data;
  139. data.positions.reserve (vertexCount * 3);
  140. data.texcoords.reserve (vertexCount * 2);
  141. data.indices.reserve (indexCount);
  142. for (size_t index = 0; index < vertexCount; index++) {
  143. const size_t vertexOffset = verticesOffset + index * vertexStride;
  144. reader.base ().seekg (static_cast<std::streamoff> (vertexOffset), std::ios::beg);
  145. const float x = reader.nextFloat ();
  146. const float y = reader.nextFloat ();
  147. const float z = reader.nextFloat ();
  148. reader.base ().seekg (static_cast<std::streamoff> (vertexOffset + uvOffset), std::ios::beg);
  149. const float u = reader.nextFloat ();
  150. const float v = reader.nextFloat ();
  151. data.positions.push_back (x);
  152. data.positions.push_back (y);
  153. data.positions.push_back (z);
  154. data.texcoords.push_back (u);
  155. data.texcoords.push_back (v);
  156. }
  157. reader.base ().seekg (static_cast<std::streamoff> (indicesOffset), std::ios::beg);
  158. for (size_t index = 0; index < indexCount; index++) {
  159. uint16_t value = 0;
  160. reader.next (reinterpret_cast<char*> (&value), sizeof (value));
  161. if (value >= vertexCount) {
  162. return std::nullopt;
  163. }
  164. data.indices.push_back (value);
  165. }
  166. return data;
  167. }
  168. // Blend indices/weights are always the 32 bytes immediately before the UV pair, regardless of stride
  169. // (see docs/rendering/MDL_FILES.md) - position(12) + [normal(12) + tangent4(16), wide format only] +
  170. // blendindices(16) + blendweight(16) + uv(8).
  171. struct PuppetBlendData {
  172. std::vector<glm::uvec4> indices;
  173. std::vector<glm::vec4> weights;
  174. };
  175. std::optional<PuppetBlendData> readPuppetBlendData (
  176. const BinaryReader& reader, const PuppetMeshBlock& block, size_t meshHeaderSize, size_t vertexStride
  177. ) {
  178. if (vertexStride < 40 || block.vertexBytes % vertexStride != 0) {
  179. return std::nullopt;
  180. }
  181. const size_t blendIndicesOffset = vertexStride - 40;
  182. const size_t blendWeightsOffset = vertexStride - 24;
  183. const size_t vertexCount = block.vertexBytes / vertexStride;
  184. const size_t verticesOffset = block.headerOffset + meshHeaderSize;
  185. PuppetBlendData data;
  186. data.indices.reserve (vertexCount);
  187. data.weights.reserve (vertexCount);
  188. for (size_t index = 0; index < vertexCount; index++) {
  189. const size_t vertexOffset = verticesOffset + index * vertexStride;
  190. reader.base ().seekg (static_cast<std::streamoff> (vertexOffset + blendIndicesOffset), std::ios::beg);
  191. glm::uvec4 boneIndices;
  192. boneIndices.x = reader.nextUInt32 ();
  193. boneIndices.y = reader.nextUInt32 ();
  194. boneIndices.z = reader.nextUInt32 ();
  195. boneIndices.w = reader.nextUInt32 ();
  196. reader.base ().seekg (static_cast<std::streamoff> (vertexOffset + blendWeightsOffset), std::ios::beg);
  197. glm::vec4 boneWeights;
  198. boneWeights.x = reader.nextFloat ();
  199. boneWeights.y = reader.nextFloat ();
  200. boneWeights.z = reader.nextFloat ();
  201. boneWeights.w = reader.nextFloat ();
  202. data.indices.push_back (boneIndices);
  203. data.weights.push_back (boneWeights);
  204. }
  205. return data;
  206. }
  207. // Scores how plausible a candidate vertex layout is: real puppet meshes are triangulated warp grids,
  208. // so triangles formed by adjacent indices should be small relative to the mesh's overall size. A wrong
  209. // stride reinterprets bone/weight bytes as positions, which decorrelates neighbouring vertices and
  210. // produces comparatively huge, inconsistent triangles. Lower is better; nullopt if unscorable (e.g. a
  211. // degenerate single-point mesh).
  212. std::optional<double> scorePuppetMeshCoherence (const PuppetMeshData& data) {
  213. if (data.indices.size () < 3) {
  214. return std::nullopt;
  215. }
  216. glm::vec3 min (std::numeric_limits<float>::max ());
  217. glm::vec3 max (std::numeric_limits<float>::lowest ());
  218. const size_t vertexCount = data.positions.size () / 3;
  219. for (size_t i = 0; i < vertexCount; i++) {
  220. const glm::vec3 p (data.positions[i * 3], data.positions[i * 3 + 1], data.positions[i * 3 + 2]);
  221. min = glm::min (min, p);
  222. max = glm::max (max, p);
  223. }
  224. const double diagonal = glm::length (max - min);
  225. if (diagonal <= 0.0) {
  226. return std::nullopt;
  227. }
  228. double totalEdgeLength = 0.0;
  229. size_t edgeCount = 0;
  230. for (size_t triangle = 0; triangle + 2 < data.indices.size (); triangle += 3) {
  231. const auto vertexPosition = [&data] (size_t index) {
  232. return glm::vec3 (data.positions[index * 3], data.positions[index * 3 + 1], data.positions[index * 3 + 2]);
  233. };
  234. const glm::vec3 a = vertexPosition (data.indices[triangle]);
  235. const glm::vec3 b = vertexPosition (data.indices[triangle + 1]);
  236. const glm::vec3 c = vertexPosition (data.indices[triangle + 2]);
  237. totalEdgeLength += glm::length (a - b) + glm::length (b - c) + glm::length (c - a);
  238. edgeCount += 3;
  239. }
  240. if (edgeCount == 0) {
  241. return std::nullopt;
  242. }
  243. return (totalEdgeLength / static_cast<double> (edgeCount)) / diagonal;
  244. }
  245. // The MDLV vertex layout isn't reliably predictable from the header version number alone - the same
  246. // version (e.g. MDLV0023) has been observed with different per-vertex strides depending on how many
  247. // bone influences a given puppet part carries. So instead of a fixed version->stride table, every
  248. // plausible stride is tried against every candidate mesh header found in the file, and whichever
  249. // combination produces the most coherent triangulated mesh wins.
  250. std::optional<PuppetVertexLayout>
  251. resolvePuppetVertexLayout (const BinaryReader& reader, size_t markerSize, size_t mdlsOffset, size_t meshHeaderSize) {
  252. constexpr size_t minVertexStride = 20; // position (12 bytes) + uv (8 bytes), no bone data at all
  253. constexpr size_t maxVertexStride = 256; // generous upper bound, comfortably covers multi-bone rigs
  254. constexpr size_t strideStep = 4; // every field observed so far is a 4-byte float/uint
  255. const auto candidates = findPuppetMeshBlockCandidates (reader, markerSize, mdlsOffset, meshHeaderSize);
  256. std::optional<PuppetVertexLayout> best;
  257. double bestScore = std::numeric_limits<double>::max ();
  258. for (const auto& block : candidates) {
  259. for (size_t stride = minVertexStride; stride <= maxVertexStride; stride += strideStep) {
  260. const auto data = readPuppetMeshData (reader, block, meshHeaderSize, stride);
  261. if (!data.has_value ()) {
  262. continue;
  263. }
  264. const auto score = scorePuppetMeshCoherence (*data);
  265. if (!score.has_value ()) {
  266. continue;
  267. }
  268. if (*score >= bestScore) {
  269. continue;
  270. }
  271. bestScore = *score;
  272. best = PuppetVertexLayout { .block = block,
  273. .vertexStride = stride,
  274. .uvOffset = stride - sizeof (GLfloat) * 2 };
  275. }
  276. }
  277. return best;
  278. }
  279. // bounds-checked little endian reads for MDLV/MDMP (sub_140261880)
  280. class PuppetFileReader {
  281. public:
  282. PuppetFileReader (const std::vector<char>& data, size_t offset) : m_data (data), m_offset (offset) { }
  283. template <typename T> T next () {
  284. if (this->m_offset + sizeof (T) > this->m_data.size ()) {
  285. throw std::runtime_error ("truncated puppet file");
  286. }
  287. T value;
  288. std::memcpy (&value, this->m_data.data () + this->m_offset, sizeof (T));
  289. this->m_offset += sizeof (T);
  290. return value;
  291. }
  292. void string () {
  293. while (this->next<char> () != '\0') { }
  294. }
  295. std::string text () {
  296. std::string result;
  297. for (char c = this->next<char> (); c != '\0'; c = this->next<char> ()) {
  298. result.push_back (c);
  299. }
  300. return result;
  301. }
  302. /** u32 size + bytes */
  303. std::pair<size_t, uint32_t> blob () {
  304. const auto bytes = this->next<uint32_t> ();
  305. const size_t start = this->m_offset;
  306. if (start + bytes > this->m_data.size ()) {
  307. throw std::runtime_error ("truncated puppet file");
  308. }
  309. this->m_offset += bytes;
  310. return { start, bytes };
  311. }
  312. void skip (size_t bytes) { this->m_offset += bytes; }
  313. [[nodiscard]] size_t offset () const { return this->m_offset; }
  314. private:
  315. const std::vector<char>& m_data;
  316. size_t m_offset;
  317. };
  318. struct PuppetMeshHeader {
  319. uint32_t flags = 0;
  320. uint32_t format = 0;
  321. size_t vertices = 0;
  322. uint32_t vertexBytes = 0;
  323. uint32_t indexBytes = 0;
  324. };
  325. // first mesh header: tag, default format, materials per mesh, mesh count, then per mesh: material names, flags
  326. // (+u32 with flag 2), bounds (v17+), format (v15+)
  327. PuppetMeshHeader readPuppetMeshHeader (const std::vector<char>& data) {
  328. PuppetFileReader reader (data, 0);
  329. reader.string ();
  330. const int version = std::atoi (data.data () + strlen ("MDLV"));
  331. PuppetMeshHeader header;
  332. header.format = reader.next<uint32_t> ();
  333. const auto materials = reader.next<uint32_t> ();
  334. (void)reader.next<uint32_t> ();
  335. for (uint32_t material = 0; material < materials; material++) {
  336. reader.string ();
  337. }
  338. if (version >= 4) {
  339. header.flags = reader.next<uint32_t> ();
  340. if (header.flags & 2) {
  341. (void)reader.next<uint32_t> ();
  342. }
  343. if (version >= 17) {
  344. reader.skip (sizeof (float) * 6);
  345. }
  346. if (version >= 15) {
  347. header.format = reader.next<uint32_t> ();
  348. }
  349. }
  350. header.vertexBytes = reader.next<uint32_t> ();
  351. header.vertices = reader.offset ();
  352. reader.skip (header.vertexBytes);
  353. header.indexBytes = reader.next<uint32_t> ();
  354. return header;
  355. }
  356. // sub_140261880 layout of the first mesh; texcoords not last in the vertex fall back to the heuristic
  357. std::optional<PuppetVertexLayout> readPuppetVertexLayout (const std::vector<char>& data, size_t meshHeaderSize) {
  358. const auto header = readPuppetMeshHeader (data);
  359. const uint32_t stride = CMesh::vertexStride (header.format);
  360. const auto texcoord = CMesh::vertexComponentOffset (header.format, 0x8);
  361. if (stride == 0 || header.vertexBytes % stride != 0 || !texcoord.has_value ()
  362. || *texcoord != stride - sizeof (GLfloat) * 2 || header.vertices + header.vertexBytes > data.size ()) {
  363. return std::nullopt;
  364. }
  365. return PuppetVertexLayout {
  366. .block = PuppetMeshBlock { .headerOffset = header.vertices - meshHeaderSize,
  367. .vertexBytes = header.vertexBytes,
  368. .indexBytes = header.indexBytes },
  369. .vertexStride = stride,
  370. .uvOffset = *texcoord,
  371. };
  372. }
  373. // first mesh with flag 2 (sub_1401FBAE0, puppet +912), BLENDROWCOUNT = the u32 after its flags (sub_140209540)
  374. std::optional<PuppetBlendMesh> readPuppetBlendMesh (const std::vector<char>& data) {
  375. PuppetFileReader reader (data, 0);
  376. reader.string ();
  377. const int version = std::atoi (data.data () + strlen ("MDLV"));
  378. if (version < 4) {
  379. return std::nullopt;
  380. }
  381. const auto defaultFormat = reader.next<uint32_t> ();
  382. const auto materials = reader.next<uint32_t> ();
  383. const auto meshes = reader.next<uint32_t> ();
  384. for (uint32_t mesh = 0; mesh < meshes; mesh++) {
  385. PuppetBlendMesh result;
  386. for (uint32_t material = 0; material < materials; material++) {
  387. const std::string name = reader.text ();
  388. if (material == 0) {
  389. result.material = name;
  390. }
  391. }
  392. const auto flags = reader.next<uint32_t> ();
  393. if (flags & 2) {
  394. result.rows = reader.next<uint32_t> ();
  395. }
  396. if (version >= 17) {
  397. reader.skip (sizeof (float) * 6);
  398. }
  399. result.format = version >= 15 ? reader.next<uint32_t> () : defaultFormat;
  400. std::tie (result.vertices, result.vertexBytes) = reader.blob ();
  401. std::tie (result.indices, result.indexBytes) = reader.blob ();
  402. if (flags & 2) {
  403. return result;
  404. }
  405. if (version >= 21) {
  406. if (reader.next<uint8_t> () != 0) {
  407. (void)reader.next<uint32_t> ();
  408. (void)reader.blob ();
  409. }
  410. if (reader.next<uint8_t> () != 0) {
  411. (void)reader.blob ();
  412. }
  413. }
  414. if (version >= 23) {
  415. const auto records = reader.next<uint32_t> ();
  416. for (uint32_t record = 0; record < records; record++) {
  417. reader.skip (sizeof (uint64_t));
  418. reader.string ();
  419. (void)reader.next<uint32_t> ();
  420. reader.skip (sizeof (uint32_t) * reader.next<uint32_t> ());
  421. reader.skip (sizeof (uint32_t) * reader.next<uint32_t> ());
  422. }
  423. }
  424. }
  425. return std::nullopt;
  426. }
  427. // MDMP per mesh (sub_140261880): u16 targets, scale, vertex count, then per target u64, name and 16 bit blobs:
  428. // positions, normals (0x400), 3 more (0x800), alpha (0x1000), bone rule (0x2000, u32 u32 f32 f32)
  429. std::optional<PuppetMorphTargets>
  430. readPuppetMorphTargets (const std::vector<char>& data, size_t section, uint32_t flags) {
  431. PuppetFileReader reader (data, section);
  432. reader.string ();
  433. (void)reader.next<uint32_t> ();
  434. const auto targets = reader.next<uint16_t> ();
  435. if (targets == 0) {
  436. return std::nullopt;
  437. }
  438. PuppetMorphTargets morph;
  439. morph.scale = reader.next<float> ();
  440. morph.vertexCount = reader.next<uint32_t> ();
  441. std::vector<size_t> positions;
  442. std::vector<size_t> alphas;
  443. for (uint16_t target = 0; target < targets; target++) {
  444. (void)reader.next<uint64_t> ();
  445. reader.string ();
  446. const auto [position, positionBytes] = reader.blob ();
  447. morph.vertexCount = std::min (morph.vertexCount, positionBytes / 6);
  448. if (positionBytes != morph.vertexCount * 6) {
  449. throw std::runtime_error ("morph target positions don't match the vertex count");
  450. }
  451. positions.push_back (position);
  452. for (const uint32_t flag : { 0x400u, 0x800u }) {
  453. if ((flags & flag) && reader.blob ().second != positionBytes) {
  454. throw std::runtime_error ("morph target normals don't match the vertex count");
  455. }
  456. }
  457. if (flags & 0x1000) {
  458. const auto [alpha, alphaBytes] = reader.blob ();
  459. if (alphaBytes != morph.vertexCount * 2) {
  460. throw std::runtime_error ("morph target alphas don't match the vertex count");
  461. }
  462. alphas.push_back (alpha);
  463. }
  464. if (flags & 0x2000) {
  465. reader.skip (sizeof (uint32_t) * 4);
  466. }
  467. }
  468. // square of vertexCount * targets + 1 texels, texel 0 is (0, 0, 0, 1)
  469. const uint32_t texels = morph.vertexCount * targets + 1;
  470. auto side = static_cast<uint32_t> (std::sqrt (static_cast<float> (texels)));
  471. if (side * side < texels) {
  472. side++;
  473. }
  474. const auto snorm = [&data] (size_t offset) {
  475. int16_t value;
  476. std::memcpy (&value, data.data () + offset, sizeof (value));
  477. return std::max (static_cast<float> (value) / 32767.0f, -1.0f);
  478. };
  479. morph.texels.assign (static_cast<size_t> (side) * side, glm::vec4 (0.0f));
  480. morph.texels[0] = glm::vec4 (0.0f, 0.0f, 0.0f, 1.0f);
  481. // without 0x1000 morphed vertices read alpha 0
  482. morph.alpha = (flags & 0x1000) == 0;
  483. size_t out = 1;
  484. for (size_t target = 0; target < alphas.size (); target++) {
  485. for (uint32_t vertex = 0; vertex < morph.vertexCount; vertex++) {
  486. const size_t position = positions[target] + vertex * 6;
  487. morph.texels[out] = glm::vec4 (
  488. snorm (position), snorm (position + 2), snorm (position + 4), snorm (alphas[target] + vertex * 2)
  489. );
  490. morph.alpha = morph.alpha || morph.texels[out].w != 1.0f;
  491. out++;
  492. }
  493. }
  494. return morph;
  495. }
  496. }
  497. CImage::ResolvedTransform CImage::localTransform (const Object& object) {
  498. glm::vec3 origin = object.origin->value->getVec3 ();
  499. glm::vec3 scale = glm::vec3 (1.0f);
  500. float angle = 0.0f;
  501. if (object.is<Image> ()) {
  502. const auto* image = object.as<Image> ();
  503. scale = image->scale->value->getVec3 ();
  504. angle = image->angles->value->getVec3 ().z;
  505. // cropoffset is already baked into the object's origin, adding it again shifts the layer
  506. } else if (object.is<Text> ()) {
  507. const auto* text = object.as<Text> ();
  508. scale = text->scale->value->getVec3 ();
  509. } else {
  510. scale = object.groupScale->value->getVec3 ();
  511. angle = object.groupAngles->value->getVec3 ().z;
  512. }
  513. return { origin, scale, angle };
  514. }
  515. CImage::ResolvedTransform CImage::resolveTransform (const Object& object) const {
  516. constexpr int kMaxParentDepth = 32;
  517. // Walk up the parent chain leaf-first, bounded by kMaxParentDepth to guard
  518. // against cycles. chain[0] is the requested object; the last entry is the root.
  519. const Object* chain[kMaxParentDepth + 1];
  520. int count = 0;
  521. const Object* current = &object;
  522. chain[count++] = current;
  523. while (current->parent.has_value ()) {
  524. if (count > kMaxParentDepth) {
  525. sLog.error ("Parent transform chain is too deep; possible cycle at object id=", current->id);
  526. break;
  527. }
  528. const auto* parentObject = this->getScene ().getObject (current->parent.value ());
  529. if (parentObject == nullptr) {
  530. break;
  531. }
  532. current = &parentObject->getObject ();
  533. chain[count++] = current;
  534. }
  535. // Accumulate top-down: the root's local transform is already its resolved
  536. // transform, then fold each child onto its already-resolved parent.
  537. ResolvedTransform resolved = localTransform (*chain[count - 1]);
  538. for (int i = count - 2; i >= 0; --i) {
  539. ResolvedTransform local = localTransform (*chain[i]);
  540. // scene.json's "attachment" follows a named point on the direct parent's puppet rig (see
  541. // PuppetAttachmentPoint): WE's world matrix is parentWorld * (animated bone world * point local) * childLocal
  542. // (sub_140148A20), so the point's animated angle rotates the child's offset and adds to its own angle, and the
  543. // mesh turns around the object origin
  544. glm::vec3 anchorOrigin = resolved.origin;
  545. float anchorAngle = resolved.angle;
  546. glm::vec2 anchorScale = { 1.0f, 1.0f };
  547. if (chain[i]->attachment.has_value () && chain[i]->parent.has_value ()) {
  548. const auto* parentCObject = this->getScene ().getObject (chain[i]->parent.value ());
  549. if (const auto* parentImage = dynamic_cast<const CImage*> (parentCObject); parentImage != nullptr) {
  550. if (const auto meshTransform = parentImage->getAttachmentPointMeshTransform (*chain[i]->attachment);
  551. meshTransform.has_value ()) {
  552. const glm::vec2 meshOffset = rotateVec2 (
  553. { meshTransform->position.x * resolved.scale.x, meshTransform->position.y * resolved.scale.y },
  554. resolved.angle
  555. );
  556. anchorOrigin.x = resolved.origin.x + meshOffset.x;
  557. anchorOrigin.y = resolved.origin.y + meshOffset.y;
  558. anchorAngle = resolved.angle + meshTransform->angle;
  559. // the bone's own scale (possibly negative, i.e. a mirrored bone) carries into whatever
  560. // rides it, same as position/rotation
  561. anchorScale = meshTransform->scale;
  562. if (!this->m_attachmentDiagnosticLogged.contains (chain[i]->id)) {
  563. this->m_attachmentDiagnosticLogged.insert (chain[i]->id);
  564. sLog.out (
  565. "Attachment resolve for ", chain[i]->name, " (", chain[i]->id,
  566. "): point=", *chain[i]->attachment, " meshPosition=(", meshTransform->position.x, ",",
  567. meshTransform->position.y, ") boneAngleDeg=", glm::degrees (meshTransform->angle),
  568. " boneScale=(", meshTransform->scale.x, ",", meshTransform->scale.y, ") parentOrigin=(",
  569. resolved.origin.x, ",", resolved.origin.y, ") parentScale=", resolved.scale.x,
  570. " anchorOrigin=(", anchorOrigin.x, ",", anchorOrigin.y,
  571. ") anchorAngleDeg=", glm::degrees (anchorAngle)
  572. );
  573. }
  574. }
  575. }
  576. }
  577. const glm::vec2 offset
  578. = rotateVec2 ({ local.origin.x * resolved.scale.x, local.origin.y * resolved.scale.y }, anchorAngle);
  579. local.origin.x = anchorOrigin.x + offset.x;
  580. local.origin.y = anchorOrigin.y + offset.y;
  581. local.origin.z = resolved.origin.z + local.origin.z * resolved.scale.z;
  582. local.scale.x *= anchorScale.x;
  583. local.scale.y *= anchorScale.y;
  584. resolved = { local.origin, local.scale * resolved.scale, local.angle + anchorAngle };
  585. }
  586. return resolved;
  587. }
  588. CImage::CImage (Wallpapers::CScene& scene, const Image& image) :
  589. CObject (scene, image), CRenderable (scene, image, *image.model->material), ScriptableObject (scene, image),
  590. m_sceneSpacePosition (GL_NONE), m_copySpacePosition (GL_NONE), m_passSpacePosition (GL_NONE),
  591. m_texcoordCopy (GL_NONE), m_texcoordPass (GL_NONE), m_modelViewProjectionScreen (),
  592. m_modelViewProjectionPass (glm::mat4 (1.0)), m_modelViewProjectionCopy (), m_modelViewProjectionScreenInverse (),
  593. m_modelViewProjectionPassInverse (glm::inverse (m_modelViewProjectionPass)), m_modelViewProjectionCopyInverse (),
  594. m_modelMatrix (), m_viewProjectionMatrix (), m_image (image), m_pos (), m_initialized (false) {
  595. this->registerProperty ("origin", *image.origin->value);
  596. this->registerProperty ("scale", *image.scale->value);
  597. this->registerProperty ("angles", *image.angles->value);
  598. this->registerProperty ("visible", *image.visible->value);
  599. this->registerProperty ("copybackground", *image.copyBackground->value);
  600. this->registerProperty ("alpha", *image.alpha->value);
  601. this->registerProperty ("color", *image.color->value);
  602. this->registerProperty ("parallaxDepth", *image.parallaxDepth->value);
  603. this->registerProperty ("alignment", *image.alignmentName->value);
  604. this->registerEffectConstants (image.effects);
  605. // animation layers carry their own property scripts, WE runs them with the layer as thisObject (the JSON loader
  606. // sub_1401730D0 binds them to the IAnimationLayer object, sub_14026C980 lists its properties and methods)
  607. for (size_t layerIndex = 0; layerIndex < image.animationLayers.size (); layerIndex++) {
  608. const auto& layer = image.animationLayers[layerIndex];
  609. const std::string prefix = "animationlayers[" + std::to_string (layerIndex) + "].";
  610. for (const auto& [name, setting] :
  611. { std::pair { "visible", &layer->visible }, std::pair { "rate", &layer->rate },
  612. std::pair { "blend", &layer->blend } }) {
  613. if (*setting == nullptr) {
  614. continue;
  615. }
  616. this->registerProperty (
  617. prefix + name, *(*setting)->value,
  618. Scripting::Adapters::animationLayerGroup (this->getId (), layerIndex), name
  619. );
  620. scene.getScriptEngine ().setThisObjectFactory (
  621. this->getProperties ().at (prefix + name).key, [this, layerIndex] (Scripting::ScriptEngine& engine) {
  622. return Scripting::Adapters::makeAnimationLayerHandle (engine, *this, layerIndex);
  623. }
  624. );
  625. }
  626. }
  627. auto scene_width = static_cast<float> (scene.getWidth ());
  628. auto scene_height = static_cast<float> (scene.getHeight ());
  629. const auto transform = this->resolveTransform (this->getImage ());
  630. glm::vec3 origin = transform.origin;
  631. glm::vec2 size = this->getSize ();
  632. glm::vec3 scale = transform.scale;
  633. // a shape's quad is a square of the scene height (shape load sub_14025FAC0, renderer +136)
  634. if (this->getImage ().shape) {
  635. size = { scene_height, scene_height };
  636. }
  637. try {
  638. this->detectTexture ();
  639. } catch (const Assets::AssetLoadException& e) {
  640. // live WE loads the scene anyway and draws the layer empty
  641. sLog.error ("Image ", image.id, " has no texture, drawing it empty: ", e.what ());
  642. }
  643. const bool placeholderTexture = this->m_texture == nullptr;
  644. if (this->m_texture == nullptr) {
  645. if (this->m_image.model->solidlayer && size.x == 0.0f && size.y == 0.0f) {
  646. size.x = static_cast<float> (scene.getCanvasWidth ());
  647. size.y = static_cast<float> (scene.getCanvasHeight ());
  648. }
  649. // TODO: create a dummy texture of correct size, fbo constructors should be enough, but this should be
  650. // properly handled
  651. // solid layers are often declared far larger than the scene, nothing samples
  652. // these buffers past the canvas so only the layout size has to stay as declared
  653. const glm::vec2 placeholderSize = { std::min (size.x, static_cast<float> (scene.getCanvasWidth ())),
  654. std::min (size.y, static_cast<float> (scene.getCanvasHeight ())) };
  655. this->m_texture = std::make_shared<CFBO> (
  656. "", TextureFormat_ARGB8888, TextureFlags_NoFlags, 1, size.x, size.y, placeholderSize.x, placeholderSize.y
  657. );
  658. }
  659. // If the wallpaper doesn't specify a size, fall back to the texture or model dimensions
  660. if ((size.x == 0.0f || size.y == 0.0f) && this->m_texture != nullptr) {
  661. size.x = static_cast<float> (this->m_texture->getRealWidth ());
  662. size.y = static_cast<float> (this->m_texture->getRealHeight ());
  663. } else if (
  664. (size.x == 0.0f || size.y == 0.0f) && this->getImage ().model->width.has_value ()
  665. && this->getImage ().model->height.has_value ()
  666. ) {
  667. size.x = static_cast<float> (this->getImage ().model->width.value ());
  668. size.y = static_cast<float> (this->getImage ().model->height.value ());
  669. }
  670. // autosize takes the size of the loaded texture (a single frame for sprite sheets) over the
  671. // declared one, or the scene's for project layers. fullscreen still wins over it
  672. if (this->getImage ().model->autosize && this->getImage ().model->projectlayer) {
  673. size = { scene_width, scene_height };
  674. } else if (
  675. this->getImage ().model->autosize && !placeholderTexture
  676. && std::dynamic_pointer_cast<const CFBO> (this->m_texture) == nullptr
  677. ) {
  678. size.x = static_cast<float> (this->m_texture->getRealWidth ());
  679. size.y = static_cast<float> (this->m_texture->getRealHeight ());
  680. }
  681. // fullscreen layers should use the whole projection's size
  682. if (this->getImage ().model->fullscreen) {
  683. size = { static_cast<float> (scene.getCanvasWidth ()), static_cast<float> (scene.getCanvasHeight ()) };
  684. origin = { scene_width / 2, scene_height / 2, 0 };
  685. }
  686. this->m_size = size;
  687. // taken after the texture/model/fullscreen fallbacks above, unsized layers would otherwise get 0x0 buffers
  688. glm::vec2 bufferSize = size;
  689. if (placeholderTexture) {
  690. bufferSize = glm::min (bufferSize, glm::vec2 (scene.getCanvasWidth (), scene.getCanvasHeight ()));
  691. }
  692. this->updateScenePosition (origin, size, scale, scene_width, scene_height);
  693. // register both FBOs into the scene
  694. std::ostringstream nameA, nameB;
  695. // WE renders layers with LIGHTING or REFLECTION unlit into _rt_imageLayerAlbedo_<id> when they have offscreen
  696. // passes and lights them last (sub_1401914B0); here the first pass is lit instead, through PRELIGHTING
  697. nameA << "_rt_imageLayerComposite_" << this->getImage ().id << "_a";
  698. nameB << "_rt_imageLayerComposite_" << this->getImage ().id << "_b";
  699. // scene.json's own "clampuvs" is a per-object override on top of whatever the base texture
  700. // asset defaults to - without it, effects that distort UVs near the edges (refraction, ripples)
  701. // can wrap around and sample the opposite edge of the buffer instead of clamping.
  702. // compose layers always clamp, their effects would otherwise wrap samples from the opposite edge
  703. const uint32_t compositeFlags = (this->getImage ().clampUVs || this->getImage ().model->passthrough)
  704. ? (this->m_texture->getFlags () | TextureFlags_ClampUVs)
  705. : this->m_texture->getFlags ();
  706. // layer buffers are 16 bit float in HDR scene rendering (sub_1401E7170)
  707. const TextureFormat layerFormat = this->getScene ().isHDR () ? TextureFormat_RGBA16161616f : TextureFormat_ARGB8888;
  708. const auto mainFBO = scene.create (
  709. nameA.str (), layerFormat, compositeFlags, 1, { bufferSize.x, bufferSize.y }, { bufferSize.x, bufferSize.y }
  710. );
  711. const auto subFBO = scene.create (
  712. nameB.str (), layerFormat, compositeFlags, 1, { bufferSize.x, bufferSize.y }, { bufferSize.x, bufferSize.y }
  713. );
  714. if (this->followsOutputSize ()) {
  715. scene.followOutputSize (mainFBO, 1);
  716. scene.followOutputSize (subFBO, 1);
  717. }
  718. this->m_currentMainFBO = this->m_mainFBO = mainFBO;
  719. this->m_currentSubFBO = this->m_subFBO = subFBO;
  720. GLfloat sceneSpacePosition[] = { this->m_pos.x, this->m_pos.y, 0.0f, this->m_pos.x, this->m_pos.w, 0.0f,
  721. this->m_pos.z, this->m_pos.y, 0.0f, this->m_pos.z, this->m_pos.y, 0.0f,
  722. this->m_pos.x, this->m_pos.w, 0.0f, this->m_pos.z, this->m_pos.w, 0.0f };
  723. float width = 1.0f;
  724. float height = 1.0f;
  725. if (this->getTexture ()->isAnimated ()) {
  726. // animated images use different coordinates as they're essentially a texture atlas
  727. width = static_cast<float> (this->getTexture ()->getRealWidth ())
  728. / static_cast<float> (this->getTexture ()->getTextureWidth (0));
  729. height = static_cast<float> (this->getTexture ()->getRealHeight ())
  730. / static_cast<float> (this->getTexture ()->getTextureHeight (0));
  731. } else if (
  732. this->getTexture () != nullptr
  733. && (this->getTexture ()->getTextureWidth (0) != this->getTexture ()->getRealWidth ()
  734. || this->getTexture ()->getTextureHeight (0) != this->getTexture ()->getRealHeight ())
  735. ) {
  736. // Account for padding in non-power-of-two textures: clamp UVs to the real content
  737. width = static_cast<float> (this->getTexture ()->getRealWidth ())
  738. / static_cast<float> (this->getTexture ()->getTextureWidth (0));
  739. height = static_cast<float> (this->getTexture ()->getRealHeight ())
  740. / static_cast<float> (this->getTexture ()->getTextureHeight (0));
  741. }
  742. float x = 0.0f;
  743. float y = 0.0f;
  744. if (this->getTexture ()->isAnimated ()) {
  745. // animations should be copied completely
  746. x = 0.0f;
  747. y = 0.0f;
  748. width = 1.0f;
  749. height = 1.0f;
  750. }
  751. GLfloat realWidth = size.x;
  752. GLfloat realHeight = size.y;
  753. GLfloat realX = 0.0;
  754. GLfloat realY = 0.0;
  755. if (this->getImage ().model->passthrough) {
  756. // Passthrough shaders fill the destination FBO from texcoords and sample the scene using positions.
  757. // Keep the destination quad full-screen in local FBO space, but pass scene-space positions through.
  758. x = 0.0f;
  759. y = 0.0f;
  760. width = 1.0f;
  761. height = 1.0f;
  762. realX = this->m_pos.x;
  763. realY = this->m_pos.w;
  764. realWidth = this->m_pos.z;
  765. realHeight = this->m_pos.y;
  766. if (this->getImage ().model->fullscreen) {
  767. realX = -1.0;
  768. realY = -1.0;
  769. realWidth = 1.0;
  770. realHeight = 1.0;
  771. }
  772. }
  773. GLfloat texcoordCopy[] = { x, height, x, y, width, height, width, height, x, y, width, y };
  774. GLfloat copySpacePosition[] = { realX, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realHeight, 0.0f,
  775. realWidth, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realY, 0.0f };
  776. 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 };
  777. GLfloat passSpacePosition[]
  778. = { -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 };
  779. glGenBuffers (1, &this->m_sceneSpacePosition);
  780. glBindBuffer (GL_ARRAY_BUFFER, this->m_sceneSpacePosition);
  781. glBufferData (GL_ARRAY_BUFFER, sizeof (sceneSpacePosition), sceneSpacePosition, GL_STATIC_DRAW);
  782. glGenBuffers (1, &this->m_copySpacePosition);
  783. glBindBuffer (GL_ARRAY_BUFFER, this->m_copySpacePosition);
  784. glBufferData (GL_ARRAY_BUFFER, sizeof (copySpacePosition), copySpacePosition, GL_STATIC_DRAW);
  785. glGenBuffers (1, &this->m_passSpacePosition);
  786. glBindBuffer (GL_ARRAY_BUFFER, this->m_passSpacePosition);
  787. glBufferData (GL_ARRAY_BUFFER, sizeof (passSpacePosition), passSpacePosition, GL_STATIC_DRAW);
  788. glGenBuffers (1, &this->m_texcoordCopy);
  789. glBindBuffer (GL_ARRAY_BUFFER, this->m_texcoordCopy);
  790. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoordCopy), texcoordCopy, GL_STATIC_DRAW);
  791. glGenBuffers (1, &this->m_texcoordPass);
  792. glBindBuffer (GL_ARRAY_BUFFER, this->m_texcoordPass);
  793. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoordPass), texcoordPass, GL_STATIC_DRAW);
  794. this->m_hasPuppetMesh = this->loadPuppetMesh (size);
  795. this->m_modelViewProjectionScreen = this->getViewProjection ();
  796. // must match m_modelViewProjectionScreen - updateScreenSpacePosition() may skip recomputing it
  797. this->m_modelViewProjectionScreenInverse = glm::inverse (this->m_modelViewProjectionScreen);
  798. this->updateEffectTextureProjection ();
  799. if (this->getImage ().model->passthrough) {
  800. this->m_modelViewProjectionCopy = this->m_modelViewProjectionScreen;
  801. } else {
  802. this->m_modelViewProjectionCopy = glm::ortho<float> (0.0, size.x, 0.0, size.y);
  803. }
  804. this->m_modelViewProjectionCopyInverse = glm::inverse (this->m_modelViewProjectionCopy);
  805. this->m_modelMatrix = glm::ortho<float> (0.0, size.x, 0.0, size.y);
  806. this->m_viewProjectionMatrix = glm::mat4 (1.0);
  807. // marks the texture as used, which starts video playback if it isn't already
  808. this->m_texture->incrementUsageCount ();
  809. }
  810. void CImage::updateTextures () const {
  811. this->getTexture ()->update ();
  812. for (const auto* pass : this->m_passes) {
  813. pass->updatePlaybackTextures ();
  814. }
  815. }
  816. void CImage::renderPassthroughChildren (const std::shared_ptr<const CFBO>& buffer) {
  817. // the buffer holds the layer's quad (m_pos, copy pass texcoords: v = 1 at m_pos.y), children land in it through
  818. // model = inverse (layer world), view = identity, ortho (-w/2, w/2, -h/2, h/2, -1000, 1000) (sub_1401ECB20).
  819. // Fullscreen layers keep the scene's camera
  820. glm::mat4 transform (1.0f);
  821. glm::mat4 viewProjection = this->getScene ().getWorldViewProjection ();
  822. if (!this->getImage ().model->fullscreen) {
  823. 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);
  824. const glm::vec3 halfExtent (
  825. (this->m_pos.z - this->m_pos.x) / 2.0f, (this->m_pos.y - this->m_pos.w) / 2.0f, 1000.0f
  826. );
  827. transform = glm::inverse (glm::scale (glm::translate (this->m_modelViewProjectionScreen, center), halfExtent));
  828. // lights skip the model stack (volumetricsfront.vert only has g_ViewProjectionMatrix), so they see the bare
  829. // ortho with the scene's y flip: their world position lands in the layer as if the layer sat at the origin
  830. const glm::vec2 size = this->getSize ();
  831. viewProjection = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
  832. * glm::ortho (-size.x / 2.0f, size.x / 2.0f, -size.y / 2.0f, size.y / 2.0f, -1000.0f, 1000.0f);
  833. }
  834. this->getScene ().renderPassthroughChildren (
  835. this->getId (),
  836. {
  837. .fbo = buffer,
  838. .transform = transform,
  839. .alphaMax = !this->m_image.copyBackground->value->getBool (),
  840. .viewProjection = viewProjection,
  841. }
  842. );
  843. }
  844. bool CImage::hitTest (const glm::vec2& ndc) {
  845. if (this->getImage ().model->fullscreen) {
  846. return true;
  847. }
  848. this->updateScreenSpacePosition ();
  849. 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);
  850. const glm::vec2 half (
  851. std::abs (this->m_pos.z - this->m_pos.x) / 2.0f, std::abs (this->m_pos.w - this->m_pos.y) / 2.0f
  852. );
  853. return Wallpapers::CScene::quadContainsPoint (
  854. glm::translate (this->m_modelViewProjectionScreen, center), half, ndc
  855. );
  856. }
  857. glm::vec2 CImage::cursorLocalPosition (const glm::vec2& ndc) {
  858. this->updateScreenSpacePosition ();
  859. 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);
  860. const auto point
  861. = Wallpapers::CScene::quadPlanePoint (glm::translate (this->m_modelViewProjectionScreen, center), ndc);
  862. const glm::vec2 extent (this->m_pos.z - this->m_pos.x, this->m_pos.y - this->m_pos.w);
  863. if (!point.has_value () || extent.x == 0.0f || extent.y == 0.0f) {
  864. return glm::vec2 (0.0f);
  865. }
  866. // m_pos runs y down from the top edge (.w), x from the texture's left edge (.x)
  867. const glm::vec2 u (
  868. (point->x + center.x - this->m_pos.x) / extent.x, (point->y + center.y - this->m_pos.w) / extent.y
  869. );
  870. return u * this->m_displaySize;
  871. }
  872. CImage::~CImage () {
  873. this->m_texture->decrementUsageCount ();
  874. // delete passes first as they depend on the image's data
  875. for (auto* pass : this->m_allPasses.empty () ? this->m_passes : this->m_allPasses) {
  876. delete pass;
  877. }
  878. this->m_passes.clear ();
  879. this->m_allPasses.clear ();
  880. for (auto* pass : this->m_puppetClipMaskPasses) {
  881. delete pass;
  882. }
  883. delete this->m_puppetClipTargetPass;
  884. delete this->m_puppetClipComposePass;
  885. glDeleteBuffers (1, &this->m_sceneSpacePosition);
  886. glDeleteBuffers (1, &this->m_copySpacePosition);
  887. glDeleteBuffers (1, &this->m_passSpacePosition);
  888. glDeleteBuffers (1, &this->m_texcoordCopy);
  889. glDeleteBuffers (1, &this->m_texcoordPass);
  890. if (this->m_puppetSpacePosition != GL_NONE) {
  891. glDeleteBuffers (1, &this->m_puppetSpacePosition);
  892. }
  893. if (this->m_puppetTexCoord != GL_NONE) {
  894. glDeleteBuffers (1, &this->m_puppetTexCoord);
  895. }
  896. if (this->m_puppetVertexAlphaWeights != GL_NONE) {
  897. glDeleteBuffers (1, &this->m_puppetVertexAlphaWeights);
  898. }
  899. if (this->m_puppetIndices != GL_NONE) {
  900. glDeleteBuffers (1, &this->m_puppetIndices);
  901. }
  902. delete this->m_blendMap.copyPass;
  903. delete this->m_blendMap.pass;
  904. for (const GLuint buffer :
  905. { this->m_puppetClipIndices, this->m_puppetClipComposePosition, this->m_puppetClipComposeTexCoord,
  906. this->m_blendMap.vertices, this->m_blendMap.indices, this->m_blendMap.quad }) {
  907. if (buffer != GL_NONE) {
  908. glDeleteBuffers (1, &buffer);
  909. }
  910. }
  911. }
  912. bool CImage::loadPuppetMesh (const glm::vec2& size) {
  913. if (!this->getImage ().model->puppet.has_value ()) {
  914. return false;
  915. }
  916. try {
  917. const auto stream = this->getScene ().getScene ().project.assetLocator->read (*this->getImage ().model->puppet);
  918. std::vector<char> data { std::istreambuf_iterator<char> (*stream), std::istreambuf_iterator<char> () };
  919. constexpr size_t markerSize = 9;
  920. constexpr size_t meshHeaderSize = sizeof (uint32_t) * 2;
  921. const std::string puppetVersion
  922. = data.size () >= markerSize ? std::string (data.data (), strlen ("MDLV0021")) : "";
  923. const size_t mdlsOffset = [&data] () -> size_t {
  924. for (size_t offset = markerSize; offset + strlen ("MDLS") < data.size (); offset++) {
  925. if (std::memcmp (data.data () + offset, "MDLS", strlen ("MDLS")) == 0) {
  926. return offset;
  927. }
  928. }
  929. return data.size ();
  930. }();
  931. auto meshBuffer = std::make_unique<char[]> (data.size ());
  932. std::copy (data.begin (), data.end (), meshBuffer.get ());
  933. const BinaryReader reader (std::make_shared<MemoryStream> (std::move (meshBuffer), data.size ()));
  934. std::optional<PuppetVertexLayout> layout;
  935. try {
  936. layout = readPuppetVertexLayout (data, meshHeaderSize);
  937. } catch (const std::exception& ex) {
  938. sLog.error ("Could not read the first mesh of ", *this->getImage ().model->puppet, ": ", ex.what ());
  939. }
  940. if (!layout.has_value ()) {
  941. layout = resolvePuppetVertexLayout (reader, markerSize, mdlsOffset, meshHeaderSize);
  942. }
  943. if (!layout.has_value ()) {
  944. sLog.error ("Could not find a usable MDLV mesh block in ", *this->getImage ().model->puppet);
  945. return false;
  946. }
  947. const auto mesh = readPuppetMeshData (reader, layout->block, meshHeaderSize, layout->vertexStride);
  948. if (!mesh.has_value ()) {
  949. sLog.error ("Could not find a usable MDLV mesh block in ", *this->getImage ().model->puppet);
  950. return false;
  951. }
  952. this->m_puppetRawPositions = mesh->positions;
  953. this->updatePuppetPositionBuffer (size);
  954. glGenBuffers (1, &this->m_puppetTexCoord);
  955. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetTexCoord);
  956. glBufferData (
  957. GL_ARRAY_BUFFER, mesh->texcoords.size () * sizeof (GLfloat), mesh->texcoords.data (), GL_STATIC_DRAW
  958. );
  959. glGenBuffers (1, &this->m_puppetIndices);
  960. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetIndices);
  961. glBufferData (
  962. GL_ELEMENT_ARRAY_BUFFER, mesh->indices.size () * sizeof (GLushort), mesh->indices.data (), GL_STATIC_DRAW
  963. );
  964. this->m_puppetIndexCount = static_cast<GLsizei> (mesh->indices.size ());
  965. this->m_puppetDrawBuffer = this->m_puppetIndices;
  966. this->m_puppetDrawCount = this->m_puppetIndexCount;
  967. this->loadPuppetBlendMesh (data);
  968. // the part ranges and clipping records follow the index buffer (sub_140261880)
  969. const int version
  970. = puppetVersion.size () > strlen ("MDLV") ? std::atoi (puppetVersion.c_str () + strlen ("MDLV")) : 0;
  971. const size_t indexEnd = layout->block.headerOffset + meshHeaderSize + layout->block.vertexBytes
  972. + sizeof (uint32_t) + layout->block.indexBytes;
  973. this->m_puppetClipping.reset ();
  974. this->m_puppetParts.clear ();
  975. this->m_puppetPartOrder.clear ();
  976. this->m_puppetMeshIndices.clear ();
  977. // 4 bone alpha, 8 draw order, 0x1000 morph alpha
  978. this->m_puppetMeshFlags = 0;
  979. this->m_puppetMeshFormat = 0;
  980. try {
  981. const auto header = readPuppetMeshHeader (data);
  982. if (header.vertices == layout->block.headerOffset + meshHeaderSize) {
  983. this->m_puppetMeshFlags = header.flags;
  984. this->m_puppetMeshFormat = header.format;
  985. } else {
  986. sLog.error (
  987. "The first mesh header of ", *this->getImage ().model->puppet, " isn't where its vertices are"
  988. );
  989. }
  990. } catch (const std::exception& ex) {
  991. sLog.error ("Could not read the mesh header of ", *this->getImage ().model->puppet, ": ", ex.what ());
  992. }
  993. const uint32_t meshFlags = this->m_puppetMeshFlags;
  994. // position.w is the morph texel, <= 0 means not morphed
  995. this->m_puppetMorph.reset ();
  996. this->m_puppetMorphIndices.clear ();
  997. if (this->m_puppetMeshFormat & 0x10000) {
  998. const size_t vertexCount = layout->block.vertexBytes / layout->vertexStride;
  999. const size_t vertices = layout->block.headerOffset + meshHeaderSize;
  1000. this->m_puppetMorphIndices.resize (vertexCount);
  1001. for (size_t vertex = 0; vertex < vertexCount; vertex++) {
  1002. float w;
  1003. std::memcpy (
  1004. &w, data.data () + vertices + vertex * layout->vertexStride + sizeof (float) * 3, sizeof (w)
  1005. );
  1006. if (w > 0.0f) {
  1007. this->m_puppetMorphIndices[vertex] = static_cast<uint32_t> (w);
  1008. }
  1009. }
  1010. }
  1011. if (meshFlags & 8) {
  1012. try {
  1013. this->m_puppetParts = PuppetClipping::readParts (data, indexEnd, version, mesh->indices.size ());
  1014. } catch (const std::exception& ex) {
  1015. sLog.error ("Ignoring the part ranges of ", *this->getImage ().model->puppet, ": ", ex.what ());
  1016. }
  1017. if (!this->m_puppetParts.empty ()) {
  1018. this->m_puppetMeshIndices = mesh->indices;
  1019. this->m_puppetPartOrder.resize (this->m_puppetParts.size ());
  1020. for (uint32_t index = 0; index < this->m_puppetPartOrder.size (); index++) {
  1021. this->m_puppetPartOrder[index] = index;
  1022. }
  1023. }
  1024. }
  1025. try {
  1026. auto clipping = PuppetClipping::read (data, indexEnd, version, mesh->indices.size ());
  1027. if (clipping.has_value () && clipping->build (mesh->indices)) {
  1028. glGenBuffers (1, &this->m_puppetClipIndices);
  1029. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetClipIndices);
  1030. glBufferData (
  1031. GL_ELEMENT_ARRAY_BUFFER, clipping->indices.size () * sizeof (GLushort), clipping->indices.data (),
  1032. GL_STATIC_DRAW
  1033. );
  1034. sLog.out (
  1035. "Puppet ", *this->getImage ().model->puppet, " clipping: ", clipping->records.size (), " masks, ",
  1036. clipping->parts.size (), " parts, ", clipping->draws.size (), " draws"
  1037. );
  1038. this->m_puppetClipping = std::move (clipping);
  1039. } else if (clipping.has_value ()) {
  1040. sLog.error (
  1041. "Puppet ", *this->getImage ().model->puppet, " has clipping masks drawn where their targets are, ",
  1042. "which aren't supported, drawing it without them"
  1043. );
  1044. }
  1045. } catch (const std::exception& ex) {
  1046. sLog.error ("Ignoring the clipping masks of ", *this->getImage ().model->puppet, ": ", ex.what ());
  1047. }
  1048. sLog.out (
  1049. "Loaded puppet mesh ", *this->getImage ().model->puppet, " version=", puppetVersion,
  1050. " stride=", layout->vertexStride, " vertices=", this->m_puppetRawPositions.size () / 3,
  1051. " indices=", this->m_puppetIndexCount
  1052. );
  1053. this->m_rig.clear ();
  1054. this->m_puppetBlendIndices.clear ();
  1055. this->m_puppetBlendWeights.clear ();
  1056. this->m_puppetSkinnedPositions.clear ();
  1057. const auto blend = readPuppetBlendData (reader, layout->block, meshHeaderSize, layout->vertexStride);
  1058. if (blend.has_value ()) {
  1059. this->m_puppetBlendIndices = blend->indices;
  1060. this->m_puppetBlendWeights = blend->weights;
  1061. }
  1062. if (mdlsOffset < data.size () && blend.has_value ()) {
  1063. try {
  1064. // MDLV header: tag, flags, a second field and the mesh count (2.8.42 sub_140261880)
  1065. uint32_t meshCount = 0;
  1066. if (data.size () >= 21) {
  1067. std::memcpy (&meshCount, data.data () + 17, sizeof (meshCount));
  1068. }
  1069. this->m_rig.load (data, mdlsOffset, meshCount, *this->getImage ().model->puppet);
  1070. this->m_rig.drawOrderEnabled = !this->m_puppetParts.empty ();
  1071. this->m_rig.boneAlphaEnabled = (meshFlags & 4) != 0;
  1072. this->m_rig.morphBlendClamped = false;
  1073. this->m_rig.addSceneLayers (this->getImage ().animationLayers);
  1074. if ((this->m_puppetMeshFormat & 0x10000) && this->m_rig.getMorphSection () != 0) {
  1075. try {
  1076. this->m_puppetMorph = readPuppetMorphTargets (data, this->m_rig.getMorphSection (), meshFlags);
  1077. } catch (const std::exception& ex) {
  1078. sLog.error (
  1079. "Ignoring the morph targets of ", *this->getImage ().model->puppet, ": ", ex.what ()
  1080. );
  1081. }
  1082. // MORPHING_MODIFIERS (0x2000) not ported
  1083. if (this->m_puppetMorph.has_value () && (meshFlags & 0x2000)) {
  1084. sLog.error (
  1085. "Puppet ", *this->getImage ().model->puppet,
  1086. " has morph targets with bone rules, which aren't supported, drawing it without them"
  1087. );
  1088. this->m_puppetMorph.reset ();
  1089. }
  1090. }
  1091. } catch (const std::exception& ex) {
  1092. sLog.error (
  1093. "Could not load puppet skeleton/animation from ", *this->getImage ().model->puppet, ": ",
  1094. ex.what (), " (falling back to the static bind pose)"
  1095. );
  1096. this->m_rig.clear ();
  1097. }
  1098. }
  1099. // vertex alpha via SKINNING_ALPHA (flag 4) or morph alpha < 1, both need the skinned material
  1100. this->m_puppetVertexAlpha = !this->m_rig.bones.empty ()
  1101. && ((meshFlags & 4) != 0 || (this->m_puppetMorph.has_value () && this->m_puppetMorph->alpha));
  1102. if (this->m_puppetVertexAlpha) {
  1103. this->updatePuppetVertexAlpha ({});
  1104. }
  1105. return true;
  1106. } catch (const std::exception& ex) {
  1107. sLog.error ("Could not load puppet mesh ", *this->getImage ().model->puppet, ": ", ex.what ());
  1108. return false;
  1109. }
  1110. }
  1111. void CImage::updatePuppetPositionBuffer (const glm::vec2& size) {
  1112. // once an animation clip is driving the mesh, its skinned output replaces the static bind pose
  1113. // as the source of truth - the bind pose (m_puppetRawPositions) is kept around unchanged, since
  1114. // skinning is recomputed from it fresh every frame, not accumulated from the previous frame
  1115. const auto& source
  1116. = !this->m_puppetSkinnedPositions.empty () ? this->m_puppetSkinnedPositions : this->m_puppetRawPositions;
  1117. if (source.empty ()) {
  1118. return;
  1119. }
  1120. // A puppet with effects is multi-pass: its geometry pass renders into its own object-sized
  1121. // intermediate FBO (see setupPasses(), the "writesToTarget" branch) using the local-canvas
  1122. // m_modelViewProjectionCopy projection, and later passes composite that FBO's texture onto the
  1123. // scene the normal (non-puppet) way - that first pass still needs plain local canvas coordinates
  1124. // (0..size, matching its texcoords) to line up with that projection. Only a puppet with no
  1125. // effects skips straight from its one and only pass to the shared scene FBO, using
  1126. // m_modelViewProjectionScreen (see setupPasses()) - that path needs vertices already in the same
  1127. // absolute scene-space coordinates uploadGeometryBuffers() bakes into sceneSpacePosition for a
  1128. // normal quad, or every vertex renders shifted by a constant offset equal to wherever this object
  1129. // should have been, reading as the whole mesh floating somewhere else on screen entirely.
  1130. const bool bakeScenePosition = this->m_passes.size () <= 1 || this->m_puppetMeshLast;
  1131. std::vector<GLfloat> positions;
  1132. positions.reserve (source.size ());
  1133. for (size_t index = 0; index + 2 < source.size (); index += 3) {
  1134. const float localX = size.x / 2.0f + source[index];
  1135. const float localY = size.y / 2.0f - source[index + 1];
  1136. if (bakeScenePosition) {
  1137. // maps the local-canvas coordinate onto this object's scene-space bounding box; m_pos.w is
  1138. // its bottom edge (m_pos.y is the top, see updateScenePosition()) so localY==0 has to land
  1139. // there, not on m_pos.y, or the puppet renders vertically flipped
  1140. positions.push_back (this->m_pos.x + localX * this->m_puppetScale.x);
  1141. positions.push_back (this->m_pos.w + localY * this->m_puppetScale.y);
  1142. } else {
  1143. positions.push_back (localX);
  1144. positions.push_back (localY);
  1145. }
  1146. // raw .mdl Z values aren't used by this engine's orthographic puppet compositing (depth test
  1147. // is disabled for puppets; layering comes from draw order + alpha blending) - and glm::ortho's
  1148. // clip.z = -localZ has no near/far normalization, so a puppet's real mesh depth (tens of units)
  1149. // would get clipped outside [-1,1] and lose most of the mesh. Zero it instead.
  1150. positions.push_back (0.0f);
  1151. }
  1152. // skip the constructor's pre-setup() call, where m_passes/m_pos/m_puppetScale aren't resolved yet
  1153. if (!this->m_puppetPositionDiagnosticLogged && !this->m_passes.empty ()) {
  1154. this->m_puppetPositionDiagnosticLogged = true;
  1155. glm::vec3 boundsMin (std::numeric_limits<float>::max ());
  1156. glm::vec3 boundsMax (std::numeric_limits<float>::lowest ());
  1157. for (size_t i = 0; i + 2 < positions.size (); i += 3) {
  1158. const glm::vec3 p (positions[i], positions[i + 1], positions[i + 2]);
  1159. boundsMin = glm::min (boundsMin, p);
  1160. boundsMax = glm::max (boundsMax, p);
  1161. }
  1162. sLog.out (
  1163. "Puppet position bake for ", this->getImage ().name, " (", this->getId (),
  1164. "): bakeScenePosition=", bakeScenePosition, " passes=", this->m_passes.size (),
  1165. " vertexCount=", positions.size () / 3, " boundsMin=(", boundsMin.x, ",", boundsMin.y, ",", boundsMin.z,
  1166. ") boundsMax=(", boundsMax.x, ",", boundsMax.y, ",", boundsMax.z, ")"
  1167. );
  1168. }
  1169. if (this->m_puppetSpacePosition == GL_NONE) {
  1170. glGenBuffers (1, &this->m_puppetSpacePosition);
  1171. }
  1172. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetSpacePosition);
  1173. glBufferData (GL_ARRAY_BUFFER, positions.size () * sizeof (GLfloat), positions.data (), GL_DYNAMIC_DRAW);
  1174. }
  1175. PuppetActiveAnimation* CImage::findPuppetAnimationLayer (size_t serial) { return this->m_rig.findLayer (serial); }
  1176. size_t CImage::getPuppetAnimationLayerCount () const { return this->m_rig.getLayerCount (); }
  1177. std::optional<size_t> CImage::getPuppetAnimationLayerAt (int64_t index) const { return this->m_rig.getLayerAt (index); }
  1178. std::optional<size_t> CImage::findPuppetAnimationLayerByName (const std::string& name) const {
  1179. return this->m_rig.findLayerByName (name);
  1180. }
  1181. std::optional<size_t> CImage::createPuppetAnimationLayer (
  1182. const Data::JSON::JSON& animation, const Data::JSON::JSON& config, bool autoRemove
  1183. ) {
  1184. return this->m_rig.createLayer (animation, config, autoRemove, this->getScene ().getScene ().project);
  1185. }
  1186. bool CImage::destroyPuppetAnimationLayersByName (const std::string& name) {
  1187. return this->m_rig.destroyLayersByName (name);
  1188. }
  1189. bool CImage::destroyPuppetAnimationLayer (size_t serial) { return this->m_rig.destroyLayer (serial); }
  1190. void CImage::updatePuppetPose () {
  1191. if (!this->m_hasPuppetMesh || this->m_rig.bones.empty ()) {
  1192. return;
  1193. }
  1194. if (this->getScene ().getContext ().getApp ().getContext ().settings.render.debug.noPuppetAnimation) {
  1195. return;
  1196. }
  1197. this->m_rig.ropeEnvironment = this->getScene ().getRopeEnvironment ();
  1198. this->m_rig.updatePose (this->puppetObjectWorld ());
  1199. this->updatePuppetDrawOrder ();
  1200. for (const auto& payload : this->m_rig.takeFiredEvents ()) {
  1201. this->getScene ().getScriptEngine ().dispatchClipEvent (*this, payload);
  1202. }
  1203. this->m_rig.finishEndedLayers ([this] (size_t serial) {
  1204. this->getScene ().getScriptEngine ().dispatchAnimationLayerEnded (*this, serial);
  1205. });
  1206. }
  1207. void CImage::updatePuppetDrawOrder () {
  1208. if (!this->m_rig.drawOrderTouched || this->m_puppetParts.empty ()) {
  1209. return;
  1210. }
  1211. // a part's key is (int) (its order + its bone's MDLS order, made when the parts are, + the bone's animated value)
  1212. const auto& boneOrder = this->m_rig.boneDrawOrder;
  1213. const auto& animated = this->m_rig.drawOrder;
  1214. std::vector<int> keys (this->m_puppetParts.size (), 0);
  1215. for (size_t index = 0; index < this->m_puppetParts.size (); index++) {
  1216. const auto& part = this->m_puppetParts[index];
  1217. const int base = static_cast<int> (part.order) + (part.bone < boneOrder.size () ? boneOrder[part.bone] : 0);
  1218. keys[index] = static_cast<int> (
  1219. static_cast<float> (base) + (part.bone < animated.size () ? animated[part.bone] : 0.0f)
  1220. );
  1221. }
  1222. const auto byKey = [&keys] (uint32_t a, uint32_t b) { return keys[a] < keys[b]; };
  1223. if (std::ranges::is_sorted (this->m_puppetPartOrder, byKey)) {
  1224. return;
  1225. }
  1226. // MSVC's std::sort (sub_1402154D0) is an insertion sort up to 32 elements, which keeps equal keys in order
  1227. std::ranges::stable_sort (this->m_puppetPartOrder, byKey);
  1228. if (this->m_puppetClipping.has_value ()) {
  1229. this->m_puppetClipping->order = this->m_puppetPartOrder;
  1230. if (this->m_puppetClipping->build (this->m_puppetMeshIndices)) {
  1231. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetClipIndices);
  1232. glBufferData (
  1233. GL_ELEMENT_ARRAY_BUFFER, this->m_puppetClipping->indices.size () * sizeof (GLushort),
  1234. this->m_puppetClipping->indices.data (), GL_DYNAMIC_DRAW
  1235. );
  1236. }
  1237. return;
  1238. }
  1239. std::vector<uint16_t> indices;
  1240. indices.reserve (this->m_puppetMeshIndices.size ());
  1241. for (const uint32_t index : this->m_puppetPartOrder) {
  1242. const auto& part = this->m_puppetParts[index];
  1243. indices.insert (
  1244. indices.end (), this->m_puppetMeshIndices.begin () + part.firstIndex,
  1245. this->m_puppetMeshIndices.begin () + part.firstIndex + part.indexCount
  1246. );
  1247. }
  1248. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetIndices);
  1249. glBufferData (GL_ELEMENT_ARRAY_BUFFER, indices.size () * sizeof (GLushort), indices.data (), GL_DYNAMIC_DRAW);
  1250. this->m_puppetIndexCount = static_cast<GLsizei> (indices.size ());
  1251. this->m_puppetDrawCount = this->m_puppetIndexCount;
  1252. }
  1253. void CImage::updatePuppetSkinning () {
  1254. if (!this->m_rig.poseAnimated || this->m_rig.boneModel.size () != this->m_rig.bones.size ()) {
  1255. return;
  1256. }
  1257. const auto& worldAnimated = this->m_rig.boneModel;
  1258. std::vector<glm::mat4> skinMatrices (this->m_rig.bones.size ());
  1259. for (size_t i = 0; i < this->m_rig.bones.size (); i++) {
  1260. skinMatrices[i] = worldAnimated[i] * this->m_rig.bones[i].inverseBindWorld;
  1261. }
  1262. // sub_14020CFF0: up to 11 active targets, stable sorted by weight descending
  1263. std::vector<std::pair<uint32_t, float>> targets;
  1264. if (this->m_puppetMorph.has_value () && !this->m_rig.morphWeights.empty ()) {
  1265. const auto& state = this->m_rig.morphWeights.front ();
  1266. for (uint32_t target = 0; target < state.weights.size () && target < 64 && targets.size () < 11; target++) {
  1267. if (state.active & (uint64_t (1) << target)) {
  1268. targets.emplace_back (target, state.weights[target]);
  1269. }
  1270. }
  1271. std::ranges::stable_sort (targets, std::ranges::greater {}, &std::pair<uint32_t, float>::second);
  1272. }
  1273. const size_t vertexCount = this->m_puppetRawPositions.size () / 3;
  1274. std::vector<float> morphAlpha;
  1275. if (this->m_puppetVertexAlpha && !targets.empty ()) {
  1276. morphAlpha.assign (vertexCount, 1.0f);
  1277. }
  1278. this->m_puppetSkinnedPositions.assign (this->m_puppetRawPositions.size (), 0.0f);
  1279. for (size_t v = 0; v < vertexCount; v++) {
  1280. glm::vec4 bindPos (
  1281. this->m_puppetRawPositions[v * 3], this->m_puppetRawPositions[v * 3 + 1],
  1282. this->m_puppetRawPositions[v * 3 + 2], 1.0f
  1283. );
  1284. if (!targets.empty () && v < this->m_puppetMorphIndices.size () && this->m_puppetMorphIndices[v].has_value ()) {
  1285. const auto& morph = *this->m_puppetMorph;
  1286. glm::vec3 delta (0.0f);
  1287. float alpha = 1.0f;
  1288. for (const auto& [target, weight] : targets) {
  1289. const size_t texel = *this->m_puppetMorphIndices[v] + static_cast<size_t> (morph.vertexCount) * target;
  1290. const glm::vec4 value = texel < morph.texels.size () ? morph.texels[texel] : glm::vec4 (0.0f);
  1291. delta += glm::vec3 (value) * weight;
  1292. alpha *= value.w * weight + (1.0f - weight);
  1293. }
  1294. bindPos += glm::vec4 (delta * morph.scale, 0.0f);
  1295. if (!morphAlpha.empty ()) {
  1296. morphAlpha[v] = alpha;
  1297. }
  1298. }
  1299. glm::vec3 skinned (0.0f);
  1300. const glm::uvec4& indices
  1301. = v < this->m_puppetBlendIndices.size () ? this->m_puppetBlendIndices[v] : glm::uvec4 (0);
  1302. const glm::vec4& weights
  1303. = v < this->m_puppetBlendWeights.size () ? this->m_puppetBlendWeights[v] : glm::vec4 (0.0f);
  1304. for (int influence = 0; influence < 4; influence++) {
  1305. const float weight = weights[influence];
  1306. if (weight == 0.0f) {
  1307. continue;
  1308. }
  1309. const uint32_t boneIndex = indices[influence];
  1310. if (boneIndex >= skinMatrices.size ()) {
  1311. continue;
  1312. }
  1313. skinned += weight * glm::vec3 (skinMatrices[boneIndex] * bindPos);
  1314. }
  1315. this->m_puppetSkinnedPositions[v * 3] = skinned.x;
  1316. this->m_puppetSkinnedPositions[v * 3 + 1] = skinned.y;
  1317. this->m_puppetSkinnedPositions[v * 3 + 2] = skinned.z;
  1318. }
  1319. this->updatePuppetPositionBuffer (this->m_size);
  1320. if (this->m_puppetVertexAlpha) {
  1321. this->updatePuppetVertexAlpha (morphAlpha);
  1322. }
  1323. }
  1324. void CImage::updatePuppetVertexAlpha (const std::vector<float>& morphAlpha) {
  1325. // morph alpha * saturate (sum of bone alpha * weight), sub_140206430
  1326. const size_t vertexCount = this->m_puppetRawPositions.size () / 3;
  1327. const auto& boneAlpha = this->m_rig.boneAlpha;
  1328. this->m_puppetVertexAlphaData.assign (vertexCount * 4, 0.0f);
  1329. for (size_t v = 0; v < vertexCount; v++) {
  1330. float alpha = v < morphAlpha.size () ? morphAlpha[v] : 1.0f;
  1331. if (this->m_puppetMeshFlags & 4) {
  1332. const glm::uvec4& indices
  1333. = v < this->m_puppetBlendIndices.size () ? this->m_puppetBlendIndices[v] : glm::uvec4 (0);
  1334. const glm::vec4& weights
  1335. = v < this->m_puppetBlendWeights.size () ? this->m_puppetBlendWeights[v] : glm::vec4 (0.0f);
  1336. float bones = 0.0f;
  1337. for (int influence = 0; influence < 4; influence++) {
  1338. if (indices[influence] < this->m_rig.bones.size ()) {
  1339. bones += (indices[influence] < boneAlpha.size () ? boneAlpha[indices[influence]] : 1.0f)
  1340. * weights[influence];
  1341. }
  1342. }
  1343. alpha *= std::clamp (bones, 0.0f, 1.0f);
  1344. }
  1345. this->m_puppetVertexAlphaData[v * 4] = alpha;
  1346. this->m_puppetVertexAlphaData[v * 4 + 1] = 1.0f - alpha;
  1347. }
  1348. if (this->m_puppetVertexAlphaWeights == GL_NONE) {
  1349. glGenBuffers (1, &this->m_puppetVertexAlphaWeights);
  1350. }
  1351. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetVertexAlphaWeights);
  1352. glBufferData (
  1353. GL_ARRAY_BUFFER, this->m_puppetVertexAlphaData.size () * sizeof (GLfloat),
  1354. this->m_puppetVertexAlphaData.data (), GL_DYNAMIC_DRAW
  1355. );
  1356. }
  1357. ComboMap CImage::puppetVertexAlphaCombos () const {
  1358. if (!this->m_puppetVertexAlpha) {
  1359. return {};
  1360. }
  1361. // sub_140209540; BONECOUNT at least 2 for the alpha trick below
  1362. return {
  1363. { "SKINNING", 1 },
  1364. { "BONECOUNT", std::max<int> (2, static_cast<int> (this->m_rig.bones.size ())) },
  1365. { "SKINNING_ALPHA", 1 },
  1366. };
  1367. }
  1368. glm::mat4 CImage::worldMatrix () const {
  1369. const glm::mat4 world = this->getScene ().objectWorldMatrix (this->getObject ());
  1370. const uint32_t alignment
  1371. = Data::Parsers::ObjectParser::parseAlignment (this->getImage ().alignmentName->value->getString ());
  1372. if (alignment == ImageAlignment_Center) {
  1373. return world;
  1374. }
  1375. // sub_1402066A0 takes half the object size (+752, truncated to int, 2x2 for fullscreen layers via
  1376. // sub_140209360), puppets included, in the layer's own scaled and rotated space
  1377. const glm::vec2 size = this->getImage ().model->fullscreen ? glm::vec2 (2.0f) : glm::trunc (this->m_displaySize);
  1378. glm::vec3 offset (0.0f);
  1379. if (alignment & ImageAlignment_Left) {
  1380. offset.x = size.x * 0.5f;
  1381. } else if (alignment & ImageAlignment_Right) {
  1382. offset.x = -size.x * 0.5f;
  1383. }
  1384. if (alignment & ImageAlignment_Top) {
  1385. offset.y = -size.y * 0.5f;
  1386. } else if (alignment & ImageAlignment_Bottom) {
  1387. offset.y = size.y * 0.5f;
  1388. }
  1389. return glm::translate (world, offset);
  1390. }
  1391. glm::mat4 CImage::puppetObjectWorld () const { return this->worldMatrix (); }
  1392. CImage::TextureAnimation* CImage::getTextureAnimation () {
  1393. if (!this->m_textureAnimation.has_value ()) {
  1394. if (this->m_texture == nullptr || !this->m_texture->isAnimated () || this->m_texture->getFrames ().empty ()) {
  1395. return nullptr;
  1396. }
  1397. this->m_textureAnimation = TextureAnimation {};
  1398. }
  1399. return &*this->m_textureAnimation;
  1400. }
  1401. std::pair<int, float> CImage::sharedTextureFrame () const {
  1402. if (this->m_texture == nullptr || !this->m_texture->isAnimated ()) {
  1403. return { 0, 0.0f };
  1404. }
  1405. // the same walk CPass::resolveTextureAnimationState does on the scene clock
  1406. const auto& frames = this->m_texture->getFrames ();
  1407. double time = fmod (static_cast<double> (g_Time), this->getAnimationTime ());
  1408. for (size_t i = 0; i < frames.size (); i++) {
  1409. if (time - frames[i]->frametime <= 0.0) {
  1410. return { static_cast<int> (i), static_cast<float> (time) };
  1411. }
  1412. time -= frames[i]->frametime;
  1413. }
  1414. return { 0, 0.0f };
  1415. }
  1416. int CImage::getTextureFrameCount () const {
  1417. return this->m_texture != nullptr && this->m_texture->isAnimated ()
  1418. ? static_cast<int> (this->m_texture->getFrames ().size ())
  1419. : 0;
  1420. }
  1421. float CImage::getTextureDuration () const {
  1422. return this->m_texture != nullptr && this->m_texture->isAnimated () ? static_cast<float> (this->getAnimationTime ())
  1423. : 0.0f;
  1424. }
  1425. void CImage::updateTextureAnimation (float frametime) {
  1426. // a scene drawn on several outputs updates its objects once per output
  1427. if (this->m_textureAnimationClock == g_Time) {
  1428. return;
  1429. }
  1430. this->m_textureAnimationClock = g_Time;
  1431. if (!this->m_textureAnimation.has_value () || !this->m_textureAnimation->detached
  1432. || !this->m_textureAnimation->playing || this->m_texture == nullptr || !this->m_texture->isAnimated ()) {
  1433. return;
  1434. }
  1435. // sub_14015FDD0: forwards wraps to the first frame, backwards to the last, the time stays inside the frame
  1436. auto& animation = *this->m_textureAnimation;
  1437. const auto& frames = this->m_texture->getFrames ();
  1438. const int count = static_cast<int> (frames.size ());
  1439. const float step = frametime * animation.rate;
  1440. const auto frameTime = [&frames, count] (int index) {
  1441. return static_cast<float> (frames[index >= 0 && index < count ? index : 0]->frametime);
  1442. };
  1443. if (count == 0 || step == 0.0f) {
  1444. return;
  1445. }
  1446. animation.time += step;
  1447. if (step > 0.0f) {
  1448. const float current = frameTime (animation.frame);
  1449. if (animation.time >= current) {
  1450. const float rest = animation.time - current;
  1451. // compared unsigned, a negative frame wraps to the first one too
  1452. animation.frame = animation.frame + 1 < 0 || animation.frame + 1 >= count ? 0 : animation.frame + 1;
  1453. animation.time = std::min (rest, frameTime (animation.frame));
  1454. }
  1455. } else if (animation.time <= 0.0f) {
  1456. animation.frame = animation.frame - 1 >= 0 ? animation.frame - 1 : count - 1;
  1457. animation.time = std::max (animation.time + frameTime (animation.frame), 0.0f);
  1458. }
  1459. }
  1460. std::optional<int> CImage::getTextureFrameOverride () const {
  1461. // a negative frame leaves the texture on its shared clock
  1462. if (!this->m_textureAnimation.has_value () || !this->m_textureAnimation->detached
  1463. || this->m_textureAnimation->frame < 0) {
  1464. return std::nullopt;
  1465. }
  1466. return this->m_textureAnimation->frame;
  1467. }
  1468. bool CImage::hasPuppetPose () const { return this->m_rig.hasPose (); }
  1469. int CImage::findPuppetBone (const std::string& name) const { return this->m_rig.findBone (name); }
  1470. const glm::mat4& CImage::getPuppetBoneTransform (int bone) const { return this->m_rig.getBoneTransform (bone); }
  1471. void CImage::setPuppetBoneTransform (int bone, const glm::mat4& transform) {
  1472. this->m_rig.setBoneTransform (bone, transform, this->puppetObjectWorld ());
  1473. }
  1474. const glm::mat4& CImage::getPuppetLocalBoneTransform (int bone) const {
  1475. return this->m_rig.getLocalBoneTransform (bone);
  1476. }
  1477. void CImage::setPuppetLocalBoneTransform (int bone, const glm::mat4& transform) {
  1478. this->m_rig.setLocalBoneTransform (bone, transform, this->puppetObjectWorld ());
  1479. }
  1480. void CImage::applyPuppetBonePhysicsImpulse (int bone, const glm::vec3& directional, const glm::vec3& angularDegrees) {
  1481. this->m_rig.applyBonePhysicsImpulse (bone, directional, angularDegrees);
  1482. }
  1483. void CImage::resetPuppetBonePhysics (int bone) { this->m_rig.resetBonePhysics (bone); }
  1484. std::optional<CImage::AttachmentPointTransform>
  1485. CImage::getAttachmentPointMeshTransform (const std::string& name) const {
  1486. if (this->m_rig.boneModel.empty ()) {
  1487. return std::nullopt;
  1488. }
  1489. const auto it = std::find_if (
  1490. this->m_rig.attachmentPoints.begin (), this->m_rig.attachmentPoints.end (),
  1491. [&name] (const PuppetAttachmentPoint& point) { return point.name == name; }
  1492. );
  1493. if (it == this->m_rig.attachmentPoints.end ()
  1494. || static_cast<size_t> (it->boneIndex) >= this->m_rig.boneModel.size ()) {
  1495. return std::nullopt;
  1496. }
  1497. const glm::mat4 animatedWorld = this->m_rig.boneModel[it->boneIndex] * it->localTransform;
  1498. const float angle = std::atan2 (animatedWorld[0][1], animatedWorld[0][0]);
  1499. // scale.y = det(X,Y)/scale.x, projecting the transformed Y-basis onto what an unreflected
  1500. // rotation by `angle` would have produced - comes out negative if the bone's matrix includes a
  1501. // reflection (mirrored bone), instead of folding that into a bogus rotation angle
  1502. const float scaleX = glm::length (glm::vec2 (animatedWorld[0]));
  1503. const glm::vec2 scale = scaleX > 1e-6f
  1504. ? glm::vec2 (
  1505. scaleX, (animatedWorld[0][0] * animatedWorld[1][1] - animatedWorld[0][1] * animatedWorld[1][0]) / scaleX
  1506. )
  1507. : glm::vec2 (scaleX, glm::length (glm::vec2 (animatedWorld[1])));
  1508. return AttachmentPointTransform { .position = glm::vec3 (animatedWorld[3]), .angle = angle, .scale = scale };
  1509. }
  1510. void CImage::setupPuppetGeometryCallback (Effects::CPass* pass) const {
  1511. pass->setGeometryCallback (
  1512. [this, pass] () {
  1513. const GLint position = glGetAttribLocation (pass->getProgramID (), "a_Position");
  1514. const GLint texCoord = glGetAttribLocation (pass->getProgramID (), "a_TexCoord");
  1515. if (!this->m_puppetDrawDiagnosticLogged) {
  1516. this->m_puppetDrawDiagnosticLogged = true;
  1517. sLog.out (
  1518. "Puppet draw setup for ", this->getImage ().name, " (", this->getId (),
  1519. "): programID=", pass->getProgramID (), " a_Position=", position, " a_TexCoord=", texCoord,
  1520. " indexCount=", this->m_puppetIndexCount, " size=", this->m_size.x, "x", this->m_size.y
  1521. );
  1522. }
  1523. if (position >= 0) {
  1524. glEnableVertexAttribArray (position);
  1525. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetSpacePosition);
  1526. glVertexAttribPointer (position, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  1527. }
  1528. if (texCoord >= 0) {
  1529. glEnableVertexAttribArray (texCoord);
  1530. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetTexCoord);
  1531. glVertexAttribPointer (texCoord, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
  1532. }
  1533. // skinning is on the CPU; two identity bones with alpha 1 and 0, weighted (alpha, 1 - alpha), carry the
  1534. // vertex alpha through SKINNING_ALPHA
  1535. if (this->m_puppetVertexAlpha && this->m_puppetVertexAlphaWeights != GL_NONE) {
  1536. const GLuint program = pass->getProgramID ();
  1537. const GLint blendWeights = glGetAttribLocation (program, "a_BlendWeights");
  1538. const GLint blendIndices = glGetAttribLocation (program, "a_BlendIndices");
  1539. const GLint normal = glGetAttribLocation (program, "a_Normal");
  1540. const GLint tangent = glGetAttribLocation (program, "a_Tangent4");
  1541. if (blendWeights >= 0) {
  1542. glEnableVertexAttribArray (blendWeights);
  1543. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetVertexAlphaWeights);
  1544. glVertexAttribPointer (blendWeights, 4, GL_FLOAT, GL_FALSE, 0, nullptr);
  1545. }
  1546. if (blendIndices >= 0) {
  1547. glDisableVertexAttribArray (blendIndices);
  1548. glVertexAttribI4ui (blendIndices, 0, 1, 0, 0);
  1549. }
  1550. if (normal >= 0) {
  1551. glDisableVertexAttribArray (normal);
  1552. glVertexAttrib3f (normal, 0.0f, 0.0f, 1.0f);
  1553. }
  1554. if (tangent >= 0) {
  1555. glDisableVertexAttribArray (tangent);
  1556. glVertexAttrib4f (tangent, 1.0f, 0.0f, 0.0f, 1.0f);
  1557. }
  1558. constexpr GLfloat bones[24]
  1559. = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
  1560. 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f };
  1561. constexpr GLfloat bonesAlpha[2] = { 1.0f, 0.0f };
  1562. if (const GLint location = glGetUniformLocation (program, "g_Bones"); location >= 0) {
  1563. glUniformMatrix4x3fv (location, 2, GL_FALSE, bones);
  1564. }
  1565. if (const GLint location = glGetUniformLocation (program, "g_BonesAlpha"); location >= 0) {
  1566. glUniform1fv (location, 2, bonesAlpha);
  1567. }
  1568. }
  1569. // updatePuppetPositionBuffer flips Y when converting mesh-space positions to screen space,
  1570. // which mirrors the mesh and reverses triangle winding relative to what the MDL file's index
  1571. // buffer encodes - but not necessarily uniformly across the whole mesh, since real puppet
  1572. // meshes aren't guaranteed to be consistently wound to begin with. Puppet content is flat 2D
  1573. // art with no real backface concept, so rather than chase the "correct" winding, just never
  1574. // cull it - a material requesting cullmode "normal" would otherwise silently drop whichever
  1575. // subset of triangles ends up on the wrong side, which looks like patchy missing geometry.
  1576. glDisable (GL_CULL_FACE);
  1577. },
  1578. [this, pass] () {
  1579. // a mesh pass into the layer's own buffer starts it fresh, one meant for the scene may be going into a
  1580. // passthrough layer's buffer right now, which holds its other children
  1581. if (pass == this->m_puppetMeshPass && !this->m_puppetDrawKeep
  1582. && pass->getDestination () != this->getScene ().getFBO ()) {
  1583. GLfloat previousClearColor[4] = {};
  1584. glGetFloatv (GL_COLOR_CLEAR_VALUE, previousClearColor);
  1585. glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
  1586. glClear (GL_COLOR_BUFFER_BIT);
  1587. glClearColor (
  1588. previousClearColor[0], previousClearColor[1], previousClearColor[2], previousClearColor[3]
  1589. );
  1590. }
  1591. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetDrawBuffer);
  1592. glDrawElements (
  1593. GL_TRIANGLES, this->m_puppetDrawCount, GL_UNSIGNED_SHORT,
  1594. reinterpret_cast<const void*> (static_cast<uintptr_t> (this->m_puppetDrawOffset) * sizeof (GLushort))
  1595. );
  1596. if (!this->m_puppetDrawErrorChecked) {
  1597. this->m_puppetDrawErrorChecked = true;
  1598. GLint boundFBO = 0;
  1599. GLint viewport[4] = {};
  1600. GLint boundTexture = 0;
  1601. glGetIntegerv (GL_DRAW_FRAMEBUFFER_BINDING, &boundFBO);
  1602. glGetIntegerv (GL_VIEWPORT, viewport);
  1603. glActiveTexture (GL_TEXTURE0);
  1604. glGetIntegerv (GL_TEXTURE_BINDING_2D, &boundTexture);
  1605. const GLenum err = glGetError ();
  1606. const GLboolean cullEnabled = glIsEnabled (GL_CULL_FACE);
  1607. const GLboolean depthEnabled = glIsEnabled (GL_DEPTH_TEST);
  1608. const GLboolean scissorEnabled = glIsEnabled (GL_SCISSOR_TEST);
  1609. const GLboolean blendEnabled = glIsEnabled (GL_BLEND);
  1610. GLint cullFaceMode = 0, frontFace = 0;
  1611. glGetIntegerv (GL_CULL_FACE_MODE, &cullFaceMode);
  1612. glGetIntegerv (GL_FRONT_FACE, &frontFace);
  1613. GLboolean colorMask[4] = {};
  1614. glGetBooleanv (GL_COLOR_WRITEMASK, colorMask);
  1615. sLog.out (
  1616. "Puppet draw result for ", this->getImage ().name, " (", this->getId (), "): glError=", err,
  1617. " boundFBO=", boundFBO, " sceneFBO=", this->getScene ().getFBO ()->getFramebuffer (), " viewport=(",
  1618. viewport[0], ",", viewport[1], ",", viewport[2], ",", viewport[3], ") boundTexture=", boundTexture,
  1619. " ownTextureReady=", (this->getTexture () != nullptr && this->getTexture ()->isReady ()),
  1620. " ownTextureID=", (this->getTexture () != nullptr ? this->getTexture ()->getTextureID (0) : 0),
  1621. " color4=(", this->getColor4 ().r, ",", this->getColor4 ().g, ",", this->getColor4 ().b, ",",
  1622. this->getColor4 ().a, ") alpha=", this->getUserAlpha (), " brightness=", this->getBrightness (),
  1623. " cullEnabled=", (int)cullEnabled, " cullFaceMode=", cullFaceMode, " frontFace=", frontFace,
  1624. " depthEnabled=", (int)depthEnabled, " scissorEnabled=", (int)scissorEnabled,
  1625. " blendEnabled=", (int)blendEnabled, " colorMask=(", (int)colorMask[0], ",", (int)colorMask[1], ",",
  1626. (int)colorMask[2], ",", (int)colorMask[3], ")"
  1627. );
  1628. }
  1629. },
  1630. [pass] () {
  1631. for (const char* name : { "a_Position", "a_TexCoord", "a_BlendWeights" }) {
  1632. if (const GLint location = glGetAttribLocation (pass->getProgramID (), name); location >= 0) {
  1633. glDisableVertexAttribArray (location);
  1634. }
  1635. }
  1636. }
  1637. );
  1638. }
  1639. // sub_140209540 / sub_140206AE0: a puppet with clipping records gets clippingmaskimage4 for its masks and its own
  1640. // material again with CLIPPINGUVS and CLIPPINGTARGET for what they clip
  1641. void CImage::setupPuppetClipping () {
  1642. if (!this->m_puppetClipping.has_value () || this->m_puppetMeshPass == nullptr) {
  1643. return;
  1644. }
  1645. const auto& project = this->getScene ().getScene ().project;
  1646. const auto& records = this->m_puppetClipping->records;
  1647. auto& overrides = this->m_materials.clippingOverrides;
  1648. const auto fboProvider = std::make_shared<FBOProvider> (this);
  1649. overrides.push_back (
  1650. std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  1651. .id = -1,
  1652. .combos = this->puppetVertexAlphaCombos (),
  1653. .constants = {},
  1654. .textures = {},
  1655. })
  1656. );
  1657. overrides.back ()->combos.insert_or_assign ("CLIPPINGUVS", 1);
  1658. overrides.back ()->combos.insert_or_assign ("CLIPPINGTARGET", 1);
  1659. this->m_puppetClipTargetPass = new CPass (
  1660. *this, fboProvider, this->m_puppetMeshPass->getPass (), *overrides.back (), std::nullopt, std::nullopt
  1661. );
  1662. this->m_puppetClipTargetPass->setTexture (8, this->getScene ().requireAlphaMaskFrameBuffer (false));
  1663. this->setupPuppetGeometryCallback (this->m_puppetClipTargetPass);
  1664. ComboMap maskCombos = this->puppetVertexAlphaCombos ();
  1665. const auto& imagePasses = this->getImage ().model->material->passes;
  1666. if (!imagePasses.empty () && imagePasses.front ()->blending == BlendingMode_AlphaToCoverage) {
  1667. maskCombos.emplace ("ALPHATOCOVERAGE", 1);
  1668. }
  1669. this->m_materials.clippingMask = MaterialParser::load (project, "materials/util/clippingmaskimage4.json");
  1670. for (const auto& record : records) {
  1671. overrides.push_back (
  1672. std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  1673. .id = -1,
  1674. .combos = maskCombos,
  1675. .constants = {},
  1676. .textures = { { 1, record.mask } },
  1677. })
  1678. );
  1679. auto* pass = new CPass (
  1680. *this, fboProvider, **this->m_materials.clippingMask->passes.begin (), *overrides.back (), std::nullopt,
  1681. std::nullopt
  1682. );
  1683. pass->addUniform ("g_RenderVar0", &this->m_puppetClipRenderVar0);
  1684. pass->setClearColor (&this->m_puppetClipClearColor);
  1685. this->setupPuppetGeometryCallback (pass);
  1686. this->m_puppetClipMaskPasses.push_back (pass);
  1687. }
  1688. if (std::ranges::none_of (records, [] (const PuppetClipping::Record& record) { return record.parent != -1; })) {
  1689. return;
  1690. }
  1691. // nested masks: the intermediate goes through flattexture onto _rt_FullAlphaMask with identity matrices
  1692. 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 };
  1693. constexpr GLfloat texcoords[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f };
  1694. glGenBuffers (1, &this->m_puppetClipComposePosition);
  1695. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetClipComposePosition);
  1696. glBufferData (GL_ARRAY_BUFFER, sizeof (positions), positions, GL_STATIC_DRAW);
  1697. glGenBuffers (1, &this->m_puppetClipComposeTexCoord);
  1698. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetClipComposeTexCoord);
  1699. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoords), texcoords, GL_STATIC_DRAW);
  1700. this->m_materials.clippingCompose = MaterialParser::load (project, "materials/util/flattexture.json");
  1701. auto* compose = new CPass (
  1702. *this, fboProvider, **this->m_materials.clippingCompose->passes.begin (), std::nullopt, std::nullopt,
  1703. std::nullopt
  1704. );
  1705. compose->setDestination (this->getScene ().requireAlphaMaskFrameBuffer (false));
  1706. compose->setInput (this->getScene ().requireAlphaMaskFrameBuffer (true));
  1707. compose->setKeepDestination (true);
  1708. compose->setModelViewProjectionMatrix (&this->m_puppetClipIdentity);
  1709. compose->setModelViewProjectionMatrixInverse (&this->m_puppetClipIdentity);
  1710. compose->setModelMatrix (&this->m_puppetClipIdentity);
  1711. compose->setViewProjectionMatrix (&this->m_puppetClipIdentity);
  1712. static const glm::mat3 identityNormal (1.0f);
  1713. compose->setLightingTransform (&this->m_puppetClipIdentity, &identityNormal, &this->m_puppetClipIdentity);
  1714. compose->setEffectTextureProjectionMatrix (&this->m_puppetClipIdentity, &this->m_puppetClipIdentity);
  1715. // sub_14020D6A0 sets the renderer alpha to 1 for it
  1716. compose->addUniform ("g_Alpha", &this->m_puppetClipComposeAlpha);
  1717. compose->setGeometryCallback (
  1718. [this, compose] () {
  1719. const GLint position = glGetAttribLocation (compose->getProgramID (), "a_Position");
  1720. const GLint texCoord = glGetAttribLocation (compose->getProgramID (), "a_TexCoord");
  1721. if (position >= 0) {
  1722. glEnableVertexAttribArray (position);
  1723. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetClipComposePosition);
  1724. glVertexAttribPointer (position, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  1725. }
  1726. if (texCoord >= 0) {
  1727. glEnableVertexAttribArray (texCoord);
  1728. glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetClipComposeTexCoord);
  1729. glVertexAttribPointer (texCoord, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
  1730. }
  1731. },
  1732. [] () {
  1733. // translucent with renderer flag 0x100 (sub_140099F60): the source color becomes DEST_COLOR, alpha ONE/ONE,
  1734. // rgb written only, so the intermediate multiplies into the mask
  1735. GLboolean colorMask[4] = {};
  1736. glGetBooleanv (GL_COLOR_WRITEMASK, colorMask);
  1737. glEnable (GL_BLEND);
  1738. glBlendFuncSeparate (GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE);
  1739. glColorMask (true, true, true, false);
  1740. glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
  1741. glColorMask (colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
  1742. },
  1743. [compose] () {
  1744. for (const char* name : { "a_Position", "a_TexCoord" }) {
  1745. const GLint location = glGetAttribLocation (compose->getProgramID (), name);
  1746. if (location >= 0) {
  1747. glDisableVertexAttribArray (location);
  1748. }
  1749. }
  1750. }
  1751. );
  1752. this->m_puppetClipComposePass = compose;
  1753. }
  1754. void CImage::loadPuppetBlendMesh (const std::vector<char>& data) {
  1755. std::optional<PuppetBlendMesh> mesh;
  1756. try {
  1757. mesh = readPuppetBlendMesh (data);
  1758. } catch (const std::exception& ex) {
  1759. sLog.error ("Could not read the blend map mesh of ", *this->getImage ().model->puppet, ": ", ex.what ());
  1760. return;
  1761. }
  1762. if (!mesh.has_value ()) {
  1763. return;
  1764. }
  1765. const uint32_t stride = CMesh::vertexStride (mesh->format);
  1766. if (stride == 0 || mesh->vertexBytes % stride != 0 || mesh->material.empty ()
  1767. || !CMesh::vertexComponentOffset (mesh->format, 0x1).has_value ()) {
  1768. sLog.error (
  1769. "Ignoring the blend map mesh of ", *this->getImage ().model->puppet, ": vertex format ", mesh->format,
  1770. " doesn't match its data"
  1771. );
  1772. return;
  1773. }
  1774. glGenBuffers (1, &this->m_blendMap.vertices);
  1775. glBindBuffer (GL_ARRAY_BUFFER, this->m_blendMap.vertices);
  1776. glBufferData (GL_ARRAY_BUFFER, mesh->vertexBytes, data.data () + mesh->vertices, GL_STATIC_DRAW);
  1777. glGenBuffers (1, &this->m_blendMap.indices);
  1778. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_blendMap.indices);
  1779. glBufferData (GL_ELEMENT_ARRAY_BUFFER, mesh->indexBytes, data.data () + mesh->indices, GL_STATIC_DRAW);
  1780. this->m_blendMap.indexCount = static_cast<GLsizei> (mesh->indexBytes / sizeof (GLushort));
  1781. this->m_blendMap.format = mesh->format;
  1782. this->m_blendMap.stride = stride;
  1783. // g_BlendMap rows from puppet +848
  1784. this->m_blendMap.rows = std::min<uint32_t> (mesh->rows, this->m_rig.blendMap.size () / 4);
  1785. this->m_blendMap.material = mesh->material;
  1786. }
  1787. // sub_140209540: texture + flag 2 mesh into _rt_imageLayerAlbedo_<id>, which the layer samples instead of its
  1788. // texture. Only the pass flags 0x8/0x10 path is ported
  1789. void CImage::setupPuppetBlendMap () {
  1790. if (this->m_blendMap.indexCount == 0 || this->m_passes.empty () || this->m_texture == nullptr) {
  1791. return;
  1792. }
  1793. const auto& project = this->getScene ().getScene ().project;
  1794. const auto fboProvider = std::make_shared<FBOProvider> (this);
  1795. const auto& texture = this->m_texture;
  1796. try {
  1797. this->m_materials.blendMap = MaterialParser::load (project, this->m_blendMap.material);
  1798. } catch (const std::exception& ex) {
  1799. sLog.error ("Cannot load the blend map material ", this->m_blendMap.material, ": ", ex.what ());
  1800. return;
  1801. }
  1802. if (this->m_materials.blendMap->passes.empty ()) {
  1803. return;
  1804. }
  1805. this->m_blendMap.albedo = std::make_shared<CFBO> (
  1806. "_rt_imageLayerAlbedo_" + std::to_string (this->getId ()), TextureFormat_ARGB8888, texture->getFlags (), 1.0f,
  1807. texture->getRealWidth (), texture->getRealHeight (), texture->getTextureWidth (0), texture->getTextureHeight (0)
  1808. );
  1809. const glm::vec2 albedoSize (texture->getTextureWidth (0), texture->getTextureHeight (0));
  1810. // mesh is in texture pixels, y up
  1811. this->m_blendMap.projection = glm::ortho (0.0f, albedoSize.x, albedoSize.y, 0.0f, -1.0f, 1.0f);
  1812. constexpr GLfloat quad[] = { -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
  1813. -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f };
  1814. glGenBuffers (1, &this->m_blendMap.quad);
  1815. glBindBuffer (GL_ARRAY_BUFFER, this->m_blendMap.quad);
  1816. glBufferData (GL_ARRAY_BUFFER, sizeof (quad), quad, GL_STATIC_DRAW);
  1817. const auto setMatrices = [this] (Effects::CPass* pass, const glm::mat4* projection) {
  1818. static const glm::mat3 identityNormal (1.0f);
  1819. pass->setModelViewProjectionMatrix (projection);
  1820. pass->setModelViewProjectionMatrixInverse (&this->m_puppetClipIdentity);
  1821. pass->setModelMatrix (&this->m_puppetClipIdentity);
  1822. pass->setViewProjectionMatrix (&this->m_puppetClipIdentity);
  1823. pass->setLightingTransform (&this->m_puppetClipIdentity, &identityNormal, &this->m_puppetClipIdentity);
  1824. pass->setEffectTextureProjectionMatrix (&this->m_puppetClipIdentity, &this->m_puppetClipIdentity);
  1825. };
  1826. // fullscreenlayer.json copy, normal blending
  1827. ComboMap copyCombos;
  1828. if (texture->isAnimated ()) {
  1829. copyCombos.emplace ("SPRITESHEET", 1);
  1830. }
  1831. const auto& copyConfig = *this->m_virtualPassess.emplace_back (
  1832. std::make_unique<MaterialPass> (MaterialPass {
  1833. .blending = BlendingMode_Normal,
  1834. .cullmode = CullingMode_Disable,
  1835. .depthtest = DepthtestMode_Disabled,
  1836. .depthwrite = DepthwriteMode_Disabled,
  1837. .shader = "passthrough",
  1838. .textures = {},
  1839. .usertextures = {},
  1840. .combos = copyCombos,
  1841. .constants = {},
  1842. })
  1843. );
  1844. auto* copy = new CPass (*this, fboProvider, copyConfig, std::nullopt, std::nullopt, std::nullopt);
  1845. copy->setInput (texture);
  1846. copy->setDestination (this->m_blendMap.albedo);
  1847. setMatrices (copy, &this->m_puppetClipIdentity);
  1848. copy->setGeometryCallback (
  1849. [this, copy] () {
  1850. const GLint position = glGetAttribLocation (copy->getProgramID (), "a_Position");
  1851. const GLint texCoord = glGetAttribLocation (copy->getProgramID (), "a_TexCoord");
  1852. glBindBuffer (GL_ARRAY_BUFFER, this->m_blendMap.quad);
  1853. if (position >= 0) {
  1854. glEnableVertexAttribArray (position);
  1855. glVertexAttribPointer (position, 3, GL_FLOAT, GL_FALSE, sizeof (GLfloat) * 5, nullptr);
  1856. }
  1857. if (texCoord >= 0) {
  1858. glEnableVertexAttribArray (texCoord);
  1859. glVertexAttribPointer (
  1860. texCoord, 2, GL_FLOAT, GL_FALSE, sizeof (GLfloat) * 5,
  1861. reinterpret_cast<const void*> (sizeof (GLfloat) * 3)
  1862. );
  1863. }
  1864. },
  1865. [] () { glDrawArrays (GL_TRIANGLE_STRIP, 0, 4); },
  1866. [copy] () {
  1867. for (const char* name : { "a_Position", "a_TexCoord" }) {
  1868. if (const GLint location = glGetAttribLocation (copy->getProgramID (), name); location >= 0) {
  1869. glDisableVertexAttribArray (location);
  1870. }
  1871. }
  1872. }
  1873. );
  1874. this->m_blendMap.copyPass = copy;
  1875. this->m_materials.blendMapOverride = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  1876. .id = -1,
  1877. .combos = { { "BLENDROWCOUNT", static_cast<int> (this->m_blendMap.rows) } },
  1878. .constants = {},
  1879. .textures = {},
  1880. });
  1881. auto* pass = new CPass (
  1882. *this, fboProvider, **this->m_materials.blendMap->passes.begin (), *this->m_materials.blendMapOverride,
  1883. std::nullopt, std::nullopt
  1884. );
  1885. pass->setInput (texture);
  1886. pass->setDestination (this->m_blendMap.albedo);
  1887. pass->setKeepDestination (true);
  1888. setMatrices (pass, &this->m_blendMap.projection);
  1889. pass->setGeometryCallback (
  1890. [this, pass] () {
  1891. const GLuint program = pass->getProgramID ();
  1892. const auto stride = static_cast<GLsizei> (this->m_blendMap.stride);
  1893. const auto attribute = [&] (const char* name, uint32_t bit, GLint size, bool integer) {
  1894. const GLint location = glGetAttribLocation (program, name);
  1895. const auto offset = CMesh::vertexComponentOffset (this->m_blendMap.format, bit);
  1896. if (location < 0) {
  1897. return;
  1898. }
  1899. if (!offset.has_value ()) {
  1900. glDisableVertexAttribArray (location);
  1901. return;
  1902. }
  1903. const auto* pointer = reinterpret_cast<const void*> (static_cast<uintptr_t> (*offset));
  1904. glEnableVertexAttribArray (location);
  1905. if (integer) {
  1906. glVertexAttribIPointer (location, size, GL_UNSIGNED_INT, stride, pointer);
  1907. } else {
  1908. glVertexAttribPointer (location, size, GL_FLOAT, GL_FALSE, stride, pointer);
  1909. }
  1910. };
  1911. glBindBuffer (GL_ARRAY_BUFFER, this->m_blendMap.vertices);
  1912. attribute ("a_Position", 0x1, 3, false);
  1913. attribute ("a_BlendIndices", 0x800000, 4, true);
  1914. attribute ("a_TexCoordVec4", 0x20, 4, false);
  1915. if (const GLint location = glGetUniformLocation (program, "g_BlendMap");
  1916. location >= 0 && this->m_blendMap.rows > 0) {
  1917. glUniform4fv (location, static_cast<GLsizei> (this->m_blendMap.rows), this->m_rig.blendMap.data ());
  1918. }
  1919. },
  1920. [this] () {
  1921. glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_blendMap.indices);
  1922. glDrawElements (GL_TRIANGLES, this->m_blendMap.indexCount, GL_UNSIGNED_SHORT, nullptr);
  1923. },
  1924. [pass] () {
  1925. for (const char* name : { "a_Position", "a_BlendIndices", "a_TexCoordVec4" }) {
  1926. if (const GLint location = glGetAttribLocation (pass->getProgramID (), name); location >= 0) {
  1927. glDisableVertexAttribArray (location);
  1928. }
  1929. }
  1930. }
  1931. );
  1932. this->m_blendMap.pass = pass;
  1933. this->m_passes.front ()->setTexture (0, this->m_blendMap.albedo);
  1934. if (this->m_puppetClipTargetPass != nullptr && this->m_puppetMeshPass == this->m_passes.front ()) {
  1935. this->m_puppetClipTargetPass->setTexture (0, this->m_blendMap.albedo);
  1936. }
  1937. }
  1938. void CImage::selectPuppetDraw (const int draw) {
  1939. if (draw < 0 || !this->m_puppetClipping.has_value ()
  1940. || static_cast<size_t> (draw) >= this->m_puppetClipping->draws.size ()) {
  1941. this->m_puppetDrawBuffer = this->m_puppetIndices;
  1942. this->m_puppetDrawOffset = 0;
  1943. this->m_puppetDrawCount = draw < 0 ? this->m_puppetIndexCount : 0;
  1944. return;
  1945. }
  1946. const auto& range = this->m_puppetClipping->draws[draw];
  1947. this->m_puppetDrawBuffer = this->m_puppetClipIndices;
  1948. this->m_puppetDrawOffset = static_cast<GLsizei> (range.offset);
  1949. this->m_puppetDrawCount = static_cast<GLsizei> (range.count);
  1950. }
  1951. void CImage::renderPuppetClipMask (
  1952. const Effects::CPass& meshPass, const int record, const int draw, const bool clear, const bool intermediate
  1953. ) {
  1954. auto& scene = this->getScene ();
  1955. auto* pass = this->m_puppetClipMaskPasses[record];
  1956. const bool inverted = this->m_puppetClipping->records[record].flags & PuppetClipping::Inverted;
  1957. pass->copyBindings (meshPass);
  1958. pass->setDestination (scene.requireAlphaMaskFrameBuffer (intermediate));
  1959. // a mesh going onto the scene may be drawn into a passthrough layer, the mask has to be laid out the same way
  1960. pass->setFollowLayerTarget (meshPass.getDestination () == scene.getFBO ());
  1961. pass->setKeepDestination (!clear && !intermediate);
  1962. this->m_puppetClipClearColor = glm::vec4 (inverted ? 1.0f : 0.0f);
  1963. this->m_puppetClipRenderVar0.x = inverted ? 1.0f : 0.0f;
  1964. this->selectPuppetDraw (draw);
  1965. pass->render ();
  1966. if (intermediate && this->m_puppetClipComposePass != nullptr) {
  1967. this->m_puppetClipComposePass->render ();
  1968. }
  1969. }
  1970. void CImage::renderPuppetClipped (Effects::CPass* meshPass) {
  1971. const auto& commands = this->m_puppetClipping->commands;
  1972. const auto& records = this->m_puppetClipping->records;
  1973. auto* target = this->m_puppetClipTargetPass;
  1974. int draw = 0;
  1975. bool drawn = false;
  1976. target->copyBindings (*meshPass);
  1977. const auto drawMesh = [&] (Effects::CPass* pass, const int index) {
  1978. this->selectPuppetDraw (index);
  1979. this->m_puppetDrawKeep = drawn;
  1980. pass->setKeepDestination (drawn);
  1981. pass->render ();
  1982. drawn = true;
  1983. };
  1984. const auto drawTargets = [&] (const int record, const int index) {
  1985. target->setBlendingMode (
  1986. records[record].flags & PuppetClipping::Additive ? BlendingMode_Additive : BlendingMode_Translucent
  1987. );
  1988. drawMesh (target, index);
  1989. };
  1990. for (size_t i = 0; i < commands.size (); i++) {
  1991. switch (commands[i]) {
  1992. case PuppetClipping::PlainDraw:
  1993. drawMesh (meshPass, draw++);
  1994. break;
  1995. case PuppetClipping::Mask:
  1996. {
  1997. const int record = commands[++i];
  1998. if (static_cast<size_t> (record) < records.size ()) {
  1999. this->renderPuppetClipMask (*meshPass, record, draw, true, false);
  2000. drawTargets (record, draw + 1);
  2001. }
  2002. draw += 2;
  2003. break;
  2004. }
  2005. case PuppetClipping::NestedMask:
  2006. {
  2007. const int chain = commands[++i];
  2008. for (int link = 0; link < chain; link++) {
  2009. const int parent = commands[++i];
  2010. const int parentDraw = commands[++i];
  2011. this->renderPuppetClipMask (*meshPass, parent, parentDraw, link == 0, link != 0);
  2012. }
  2013. const int record = commands[++i];
  2014. this->renderPuppetClipMask (*meshPass, record, draw, false, true);
  2015. drawTargets (record, draw + 1);
  2016. draw += 2;
  2017. break;
  2018. }
  2019. default:
  2020. break;
  2021. }
  2022. }
  2023. meshPass->setKeepDestination (false);
  2024. this->m_puppetDrawKeep = false;
  2025. this->selectPuppetDraw (-1);
  2026. }
  2027. bool CImage::followsOutputSize () const {
  2028. // a fullscreen layer takes its texture's size (sub_1401912C0), which for the usual one is _rt_FullFrameBuffer
  2029. return this->getImage ().model->fullscreen && this->m_texture == this->getScene ().getFBO ();
  2030. }
  2031. void CImage::addEffectPasses (const ImageEffect& effect) {
  2032. const auto fboProvider = std::make_shared<FBOProvider> (this);
  2033. std::vector<std::shared_ptr<CFBO>> buffers;
  2034. for (const auto& fbo : effect.effect->fbos) {
  2035. const auto created = fboProvider->create (
  2036. *fbo,
  2037. this->m_image.model->passthrough ? (this->m_texture->getFlags () | TextureFlags_ClampUVs)
  2038. : this->m_texture->getFlags (),
  2039. this->getSize ()
  2040. );
  2041. if (this->followsOutputSize ()) {
  2042. this->getScene ().followOutputSize (created, fbo->scale);
  2043. }
  2044. buffers.push_back (created);
  2045. }
  2046. this->registerEffectBuffers (effect, std::move (buffers));
  2047. auto curEffect = effect.effect->passes.begin ();
  2048. auto endEffect = effect.effect->passes.end ();
  2049. auto curOverride = effect.passOverrides.begin ();
  2050. auto endOverride = effect.passOverrides.end ();
  2051. for (; curEffect != endEffect; ++curEffect) {
  2052. if (!(*curEffect)->material.has_value ()) {
  2053. if (!(*curEffect)->command.has_value ()) {
  2054. sLog.error ("Pass without material and command not supported");
  2055. continue;
  2056. }
  2057. if (!(*curEffect)->source.has_value ()) {
  2058. sLog.error ("Pass without material and source not supported");
  2059. continue;
  2060. }
  2061. if (!(*curEffect)->target.has_value ()) {
  2062. sLog.error ("Pass without material and target not supported");
  2063. continue;
  2064. }
  2065. if ((*curEffect)->command != Command_Copy) {
  2066. sLog.error ("Only copy command is supported for pass without material");
  2067. continue;
  2068. }
  2069. auto virtualPass
  2070. = std::make_unique<MaterialPass> (MaterialPass { .blending = BlendingMode_Normal,
  2071. .cullmode = CullingMode_Disable,
  2072. .depthtest = DepthtestMode_Disabled,
  2073. .depthwrite = DepthwriteMode_Disabled,
  2074. .shader = "commands/copy",
  2075. .textures = { { 0, *(*curEffect)->source } },
  2076. .combos = {},
  2077. .constants = {} });
  2078. const auto& config = *this->m_virtualPassess.emplace_back (std::move (virtualPass));
  2079. this->m_passes.push_back (
  2080. new CPass (*this, fboProvider, config, std::nullopt, std::nullopt, (*curEffect)->target.value ())
  2081. );
  2082. } else {
  2083. for (auto& pass : (*curEffect)->material.value ()->passes) {
  2084. const auto override = curOverride != endOverride
  2085. ? **curOverride
  2086. : std::optional<std::reference_wrapper<const ImageEffectPassOverride>> (std::nullopt);
  2087. const auto target = (*curEffect)->target.has_value ()
  2088. ? *(*curEffect)->target
  2089. : std::optional<std::reference_wrapper<std::string>> (std::nullopt);
  2090. this->m_passes.push_back (new CPass (*this, fboProvider, *pass, override, (*curEffect)->binds, target));
  2091. }
  2092. if (curOverride != endOverride) {
  2093. ++curOverride;
  2094. }
  2095. }
  2096. }
  2097. }
  2098. void CImage::setup () {
  2099. if (this->m_initialized) {
  2100. return;
  2101. }
  2102. this->m_readByOtherLayer = std::ranges::any_of (this->getScene ().getScene ().objects, [this] (const auto& object) {
  2103. return object->id != this->getImage ().id
  2104. && std::ranges::find (object->dependencies, this->getImage ().id) != object->dependencies.end ();
  2105. });
  2106. this->m_hasPassthroughChildren = this->m_image.model->passthrough
  2107. && std::ranges::any_of (this->getScene ().getScene ().objects,
  2108. [this] (const auto& object) { return object->parent == this->getImage ().id; });
  2109. // passthrough without effects has nothing to draw unless another layer reads its _rt_imageLayerComposite or it
  2110. // has children to draw into its buffer
  2111. if (this->m_image.model->passthrough && this->m_image.effects.empty () && !this->m_readByOtherLayer
  2112. && !this->m_hasPassthroughChildren) {
  2113. return;
  2114. }
  2115. const auto& debug = this->getScene ().getContext ().getApp ().getContext ().settings.render.debug;
  2116. // a shape has no image of its own, only its effect is drawn (sub_14025FAF0)
  2117. if (!this->getImage ().shape) {
  2118. for (const auto& cur : this->getImage ().model->material->passes) {
  2119. this->m_passes.push_back (
  2120. new CPass (*this, std::make_shared<FBOProvider> (this), *cur, std::nullopt, std::nullopt, std::nullopt)
  2121. );
  2122. }
  2123. }
  2124. std::vector<const DynamicValue*> passVisibility (this->m_passes.size (), nullptr);
  2125. std::vector<bool> passFromEffect (this->m_passes.size (), false);
  2126. if (!debug.baseOnly && !this->getImage ().effects.empty ()) {
  2127. for (const auto& cur : this->m_image.effects) {
  2128. if (std::find (debug.skipEffects.begin (), debug.skipEffects.end (), static_cast<int> (cur->id))
  2129. != debug.skipEffects.end ()) {
  2130. continue;
  2131. }
  2132. const auto effectVisibility
  2133. = this->getScene ().getContext ().getApp ().getContext ().resolveEffectVisibility (
  2134. static_cast<int> (cur->id), cur->name
  2135. );
  2136. // an explicit --disable-effect/--enable-effect override wins over the scene's own visibility
  2137. if (effectVisibility.has_value () && !*effectVisibility) {
  2138. continue;
  2139. }
  2140. // scripts can toggle hidden effects at runtime; puppets can't, their mesh pass layout
  2141. // depends on the pass count
  2142. const bool followsVisibility = !effectVisibility.has_value () && !this->m_hasPuppetMesh;
  2143. if (!followsVisibility && !effectVisibility.has_value () && !cur->visible->value->getBool ()) {
  2144. continue;
  2145. }
  2146. const DynamicValue* visibleValue = followsVisibility ? cur->visible->value.get () : nullptr;
  2147. const size_t firstEffectPass = this->m_passes.size ();
  2148. try {
  2149. this->addEffectPasses (*cur);
  2150. } catch (const std::exception& e) {
  2151. if (visibleValue == nullptr || visibleValue->getBool ()) {
  2152. throw;
  2153. }
  2154. for (size_t i = firstEffectPass; i < this->m_passes.size (); i++) {
  2155. delete this->m_passes[i];
  2156. }
  2157. this->m_passes.resize (firstEffectPass);
  2158. sLog.error (
  2159. "Dropping hidden effect ", cur->id, " (", cur->name, ") on ", this->getImage ().name, ": ",
  2160. e.what ()
  2161. );
  2162. continue;
  2163. }
  2164. passVisibility.resize (this->m_passes.size (), visibleValue);
  2165. passFromEffect.resize (this->m_passes.size (), true);
  2166. }
  2167. }
  2168. const size_t passCountBeforeTrailingPasses = this->m_passes.size ();
  2169. if (!debug.baseOnly && !this->getImage ().shape) {
  2170. const auto magentaCompositeTint = findMagentaCompositeTint (this->m_image, debug.skipEffects);
  2171. if (magentaCompositeTint.has_value ()) {
  2172. auto tintOverride = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  2173. .id = -1,
  2174. .combos = {
  2175. { "BLENDMODE", 30 },
  2176. },
  2177. .constants = {},
  2178. .textures = {},
  2179. });
  2180. tintOverride->constants.emplace ("color", UserSettingBuilder::fromValue (magentaCompositeTint.value ()));
  2181. tintOverride->constants.emplace ("alpha", UserSettingBuilder::fromValue (1.0f));
  2182. this->m_materials.compatibilityMaterials.emplace_back (
  2183. MaterialParser::load (this->getScene ().getScene ().project, "materials/effects/tint.json")
  2184. );
  2185. this->m_materials.compatibilityOverrides.emplace_back (std::move (tintOverride));
  2186. this->m_passes.push_back (new CPass (
  2187. *this, std::make_shared<FBOProvider> (this),
  2188. **this->m_materials.compatibilityMaterials.back ()->passes.begin (),
  2189. *this->m_materials.compatibilityOverrides.back (), std::nullopt, std::nullopt
  2190. ));
  2191. }
  2192. }
  2193. const int colorBlendMode = this->m_image.colorBlendMode->value->getInt ();
  2194. // WE keeps the result of a layer another one reads in _a and only copies it to the screen from there,
  2195. // drawing the last effect pass straight to the screen would leave _a one pass behind (or empty)
  2196. const bool copyForReaders = this->m_readByOtherLayer && this->getImage ().visible->value->getBool ();
  2197. // fog sends every layer through its buffer and a FOG_COMPUTED composite (sub_1401E6F50, sub_1401EBBC0)
  2198. const bool fog = this->getScene ().hasDistanceFog () || this->getScene ().hasHeightFog ();
  2199. this->m_fogPass = nullptr;
  2200. // children go into the layer's buffer, which then needs a composite onto the scene even without effects
  2201. // (sub_1401E8AA0 with children, sub_140208670)
  2202. if (!debug.baseOnly && !this->getImage ().shape
  2203. && (colorBlendMode > 0 || copyForReaders || fog || this->m_hasPassthroughChildren)) {
  2204. // scenes from version 3 on composite with genericimage4, the one with fog (sub_1401EBBC0)
  2205. const auto& project = this->getScene ().getScene ().project;
  2206. this->m_materials.colorBlending.material = MaterialParser::load (
  2207. project,
  2208. project.sceneVersion >= 3 ? "materials/util/effectpassthrough_4.json"
  2209. : "materials/util/effectpassthrough.json"
  2210. );
  2211. ComboMap combos;
  2212. if (colorBlendMode > 0) {
  2213. combos.emplace ("BLENDMODE", colorBlendMode);
  2214. }
  2215. if (fog) {
  2216. combos.emplace ("FOG_COMPUTED", 1);
  2217. }
  2218. this->m_materials.colorBlending.override = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  2219. .id = -1,
  2220. .combos = combos,
  2221. .constants = {},
  2222. .textures = {},
  2223. });
  2224. this->m_passes.push_back (new CPass (
  2225. *this, std::make_shared<FBOProvider> (this), **this->m_materials.colorBlending.material->passes.begin (),
  2226. *this->m_materials.colorBlending.override, std::nullopt, std::nullopt
  2227. ));
  2228. // the layer buffer already holds color and alpha, WE draws this composite with a white renderer color
  2229. // (sub_1401E8AA0 sets renderer +288..+300 to 1 before it)
  2230. this->m_passes.back ()->setNeutralColor (true);
  2231. if (fog) {
  2232. this->m_fogPass = this->m_passes.back ();
  2233. }
  2234. }
  2235. if (this->m_hasPuppetMesh && !this->m_passes.empty ()) {
  2236. this->m_puppetMeshPass = this->m_passes.front ();
  2237. this->m_puppetMeshLast = this->m_passes.size () == 1;
  2238. this->m_materials.puppetVertexAlpha = nullptr;
  2239. if (this->m_puppetVertexAlpha) {
  2240. this->m_materials.puppetVertexAlpha = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  2241. .id = -1,
  2242. .combos = this->puppetVertexAlphaCombos (),
  2243. .constants = {},
  2244. .textures = {},
  2245. });
  2246. }
  2247. // effect masks are laid out over the source texture, so effects run on the flat texture first
  2248. // and the warped mesh is drawn last, sampling their output
  2249. const auto& materialPasses = this->getImage ().model->material->passes;
  2250. const bool hasTrailingPasses = this->m_passes.size () != passCountBeforeTrailingPasses;
  2251. if (this->m_passes.size () > 1 && !hasTrailingPasses && materialPasses.size () == 1
  2252. && materialPasses.front ()->constants.empty ()) {
  2253. const auto& base = *materialPasses.front ();
  2254. const auto& config = *this->m_virtualPassess.emplace_back (
  2255. std::make_unique<MaterialPass> (MaterialPass {
  2256. .blending = base.blending,
  2257. .cullmode = base.cullmode,
  2258. .depthtest = base.depthtest,
  2259. .depthwrite = base.depthwrite,
  2260. .shader = base.shader,
  2261. .textures = {},
  2262. .usertextures = {},
  2263. .combos = base.combos,
  2264. .constants = {},
  2265. })
  2266. );
  2267. this->m_puppetMeshPass = this->m_materials.puppetVertexAlpha != nullptr
  2268. ? new CPass (
  2269. *this, std::make_shared<FBOProvider> (this), config, *this->m_materials.puppetVertexAlpha,
  2270. std::nullopt, std::nullopt
  2271. )
  2272. : new CPass (
  2273. *this, std::make_shared<FBOProvider> (this), config, std::nullopt, std::nullopt, std::nullopt
  2274. );
  2275. this->m_passes.push_back (this->m_puppetMeshPass);
  2276. this->m_puppetMeshLast = true;
  2277. } else if (this->m_materials.puppetVertexAlpha != nullptr) {
  2278. // first pass draws the mesh, rebuilt with the combos
  2279. auto* pass = new CPass (
  2280. *this, std::make_shared<FBOProvider> (this), this->m_passes.front ()->getPass (),
  2281. *this->m_materials.puppetVertexAlpha, std::nullopt, std::nullopt
  2282. );
  2283. delete this->m_passes.front ();
  2284. this->m_passes.front () = pass;
  2285. this->m_puppetMeshPass = pass;
  2286. }
  2287. }
  2288. this->setupPuppetClipping ();
  2289. this->setupPuppetBlendMap ();
  2290. passVisibility.resize (this->m_passes.size (), nullptr);
  2291. passFromEffect.resize (this->m_passes.size (), false);
  2292. for (size_t i = 0; i < this->m_passes.size (); i++) {
  2293. this->m_allPassStates.push_back (
  2294. { passVisibility[i], this->m_passes[i]->getBlendingMode (), passFromEffect[i] }
  2295. );
  2296. }
  2297. this->m_allPasses = this->m_passes;
  2298. CRenderable::setup ();
  2299. this->rebuildActivePasses ();
  2300. this->m_initialized = true;
  2301. }
  2302. bool CImage::effectVisibilityChanged () const {
  2303. for (size_t i = 0; i < this->m_allPassStates.size (); i++) {
  2304. const auto* visible = this->m_allPassStates[i].visible;
  2305. if (visible != nullptr && visible->getBool () != this->m_activePassMask[i]) {
  2306. return true;
  2307. }
  2308. }
  2309. return false;
  2310. }
  2311. void CImage::rebuildActivePasses () {
  2312. this->m_passes.clear ();
  2313. this->m_activePassMask.assign (this->m_allPasses.size (), false);
  2314. this->m_hasActiveEffectPass = false;
  2315. for (size_t i = 0; i < this->m_allPasses.size (); i++) {
  2316. const auto& state = this->m_allPassStates[i];
  2317. this->m_allPasses[i]->setBlendingMode (state.blending);
  2318. this->m_allPasses[i]->setDepthState (std::nullopt);
  2319. if (state.visible == nullptr || state.visible->getBool ()) {
  2320. this->m_activePassMask[i] = true;
  2321. this->m_hasActiveEffectPass |= state.fromEffect;
  2322. this->m_passes.push_back (this->m_allPasses[i]);
  2323. }
  2324. }
  2325. // if there's more than one pass the blendmode has to be moved from the beginning to the end
  2326. if (this->m_passes.size () > 1) {
  2327. const auto first = this->m_passes.begin ();
  2328. const auto last = this->m_passes.rbegin ();
  2329. (*last)->setBlendingMode ((*first)->getBlendingMode ());
  2330. (*first)->setBlendingMode (BlendingMode_Normal);
  2331. // the pass that draws an image's effects onto the scene also takes the image material's depth test and write
  2332. // (sub_1401EBF60 through image slot 33 sub_140209160, material bytes +498/+499): a 3D layer behind a model
  2333. // stays behind it (3453730450's moon_BBB)
  2334. const auto& materialPasses = this->getImage ().model->material->passes;
  2335. const auto lastState = std::ranges::find (this->m_allPasses, *last) - this->m_allPasses.begin ();
  2336. if (!this->getImage ().shape && !materialPasses.empty () && this->m_allPassStates[lastState].fromEffect) {
  2337. const auto& base = *materialPasses.front ();
  2338. (*last)->setDepthState (std::make_pair (base.depthtest, base.depthwrite));
  2339. }
  2340. }
  2341. // a shape's last pass goes onto the scene additively (its blend override sub_140260790 writes 2)
  2342. if (this->getImage ().shape && !this->m_passes.empty ()) {
  2343. this->m_passes.back ()->setBlendingMode (BlendingMode_Additive);
  2344. }
  2345. // setupPasses() ping-pongs these, every rebuild has to start from the same pair
  2346. this->m_currentMainFBO = this->m_mainFBO;
  2347. this->m_currentSubFBO = this->m_subFBO;
  2348. this->setupPasses ();
  2349. }
  2350. void CImage::setupPasses () {
  2351. // like WE, start on whichever buffer makes the last offscreen pass land in _a, which is what other layers read
  2352. auto offscreenPasses = std::ranges::count_if (this->m_passes, [] (const Effects::CPass* pass) {
  2353. return !pass->getTarget ().has_value ();
  2354. });
  2355. this->m_passesDrawToScreen = this->shouldRenderFinalPass (true);
  2356. if (!this->m_passes.empty () && !this->m_passes.back ()->getTarget ().has_value () && this->m_passesDrawToScreen) {
  2357. offscreenPasses--;
  2358. }
  2359. if (offscreenPasses % 2 == 0) {
  2360. std::swap (this->m_currentMainFBO, this->m_currentSubFBO);
  2361. }
  2362. std::shared_ptr<const CFBO> drawTo = this->m_currentMainFBO;
  2363. std::shared_ptr<const TextureProvider> asInput = this->getTexture ();
  2364. GLuint texcoord = this->getTexCoordCopy ();
  2365. auto cur = this->m_passes.begin ();
  2366. auto end = this->m_passes.end ();
  2367. bool first = true;
  2368. bool inTargetEffectSequence = false;
  2369. std::shared_ptr<const TextureProvider> effectInput = nullptr;
  2370. for (; cur != end; ++cur) {
  2371. Effects::CPass* pass = *cur;
  2372. std::shared_ptr<const CFBO> prevDrawTo = drawTo;
  2373. bool writesToTarget = false;
  2374. const bool isFirstPass = first;
  2375. const bool isMeshPass = this->m_hasPuppetMesh && pass == this->m_puppetMeshPass;
  2376. GLuint spacePosition = isMeshPass ? this->m_puppetSpacePosition
  2377. : isFirstPass ? this->getCopySpacePosition ()
  2378. : this->getPassSpacePosition ();
  2379. const glm::mat4* projection
  2380. = (isFirstPass) ? &this->m_modelViewProjectionCopy : &this->m_modelViewProjectionPass;
  2381. const glm::mat4* inverseProjection
  2382. = (isFirstPass) ? &this->m_modelViewProjectionCopyInverse : &this->m_modelViewProjectionPassInverse;
  2383. first = false;
  2384. if (isMeshPass) {
  2385. pass->setBlendingMode (BlendingMode_Translucent);
  2386. this->setupPuppetGeometryCallback (pass);
  2387. }
  2388. pass->setModelMatrix (&this->m_modelMatrix);
  2389. pass->setViewProjectionMatrix (&this->m_viewProjectionMatrix);
  2390. pass->setLayerModelMatrix (&this->m_layerModelMatrix);
  2391. pass->setEffectTextureProjectionMatrix (
  2392. &this->m_effectTextureProjection, &this->m_effectTextureProjectionInverse
  2393. );
  2394. writesToTarget = this->configurePassTarget (pass, drawTo, asInput, effectInput, inTargetEffectSequence);
  2395. // TODO: PROPERLY CHECK IF THIS IS ALL THAT'S NEEDED
  2396. if (!writesToTarget && this->shouldRenderFinalPass (std::next (cur) == end)) {
  2397. drawTo = this->getScene ().getFBO ();
  2398. // A puppet with no effects has its geometry pass be both the first AND the last pass, drawn
  2399. // straight into the shared scene FBO below - same as any other object's final pass, so it
  2400. // needs the same screen-space projection. updatePuppetPositionBuffer() bakes this object's
  2401. // resolved scene position/scale directly into m_puppetSpacePosition (mirroring what
  2402. // uploadGeometryBuffers does for a normal quad's sceneSpacePosition), so m_modelViewProjectionScreen
  2403. // is the correct projection for those vertices now, not the local-canvas m_modelViewProjectionCopy
  2404. // this pass otherwise uses when rendering to an intermediate, object-sized target. The
  2405. // spacePosition reassignment below is a no-op for puppets either way - the puppet geometry
  2406. // callback always binds m_puppetSpacePosition itself, ignoring whatever spacePosition holds.
  2407. spacePosition = this->getSceneSpacePosition ();
  2408. projection = &this->m_modelViewProjectionScreen;
  2409. // WE's final pass inverse lands in the layer's local space (origin at its center, unscaled
  2410. // pixels); older shaders like the bundled xray.vert unproject the pointer through it
  2411. inverseProjection = &this->m_objectSpaceProjectionInverse;
  2412. }
  2413. pass->setLightingTransform (
  2414. projection == &this->m_modelViewProjectionCopy ? &this->m_lightingCopyModel : &this->m_lightingSceneModel,
  2415. &this->m_lightingNormal, &this->m_lightingViewProjection
  2416. );
  2417. // the fog composite measures in WE's world, the lighting model already maps the layer there
  2418. if (pass == this->m_fogPass && projection == &this->m_modelViewProjectionScreen) {
  2419. pass->setModelMatrix (&this->m_lightingSceneModel);
  2420. pass->setFogWorld (true);
  2421. }
  2422. pass->setDestination (drawTo);
  2423. pass->setInput (asInput);
  2424. pass->setPreviousInput (inTargetEffectSequence ? effectInput : nullptr);
  2425. pass->setPosition (spacePosition);
  2426. pass->setTexCoord (texcoord);
  2427. pass->setModelViewProjectionMatrix (projection);
  2428. pass->setModelViewProjectionMatrixInverse (inverseProjection);
  2429. // what WE's intermediate passes see as g_EffectModelViewProjectionMatrix: their geometry where the layer
  2430. // is on screen (sub_1401EBF60), the final pass keeps its own MVP
  2431. pass->setEffectModelViewProjectionMatrix (
  2432. projection == &this->m_modelViewProjectionCopy ? &this->m_effectModelViewProjectionCopy
  2433. : projection == &this->m_modelViewProjectionPass ? &this->m_effectModelViewProjectionPass
  2434. : nullptr
  2435. );
  2436. texcoord = this->getTexCoordPass ();
  2437. if (writesToTarget) {
  2438. asInput = drawTo;
  2439. drawTo = prevDrawTo;
  2440. } else {
  2441. drawTo = prevDrawTo;
  2442. this->pinpongFramebuffer (&drawTo, &asInput);
  2443. inTargetEffectSequence = false;
  2444. effectInput = nullptr;
  2445. }
  2446. }
  2447. }
  2448. bool CImage::shouldRenderFinalPass (bool isLastPass) const {
  2449. const auto& appContext = this->getScene ().getContext ().getApp ().getContext ();
  2450. const auto visibility = appContext.resolveObjectVisibility (this->getId (), this->getObject ().name);
  2451. const bool visible = visibility.value_or (this->getImage ().visible->value->getBool ());
  2452. if (!isLastPass || !visible) {
  2453. return false;
  2454. }
  2455. const auto& debug = this->getScene ().getContext ().getApp ().getContext ().settings.render.debug;
  2456. return !(debug.noSolidFinal && this->getImage ().model->solidlayer);
  2457. }
  2458. bool CImage::configurePassTarget (
  2459. Effects::CPass* pass, std::shared_ptr<const CFBO>& drawTo, const std::shared_ptr<const TextureProvider>& asInput,
  2460. std::shared_ptr<const TextureProvider>& effectInput, bool& inTargetEffectSequence
  2461. ) {
  2462. if (!pass->getTarget ().has_value ()) {
  2463. return false;
  2464. }
  2465. const std::string target = pass->getTarget ().value ();
  2466. std::shared_ptr<const CFBO> resolved = pass->getFBOProvider ()->find (target);
  2467. if (resolved == nullptr) {
  2468. resolved = this->getScene ().findFBO (target);
  2469. }
  2470. if (resolved == nullptr) {
  2471. sLog.error (
  2472. "Pass target FBO '", target, "' could not be resolved for object ", pass->getRenderable ().getId (),
  2473. " shader=", pass->getPass ().shader
  2474. );
  2475. return false;
  2476. }
  2477. if (!inTargetEffectSequence) {
  2478. effectInput = asInput;
  2479. inTargetEffectSequence = true;
  2480. }
  2481. drawTo = resolved;
  2482. return true;
  2483. }
  2484. void CImage::pinpongFramebuffer (std::shared_ptr<const CFBO>* drawTo, std::shared_ptr<const TextureProvider>* asInput) {
  2485. std::shared_ptr<const CFBO> currentMainFBO = this->m_currentMainFBO;
  2486. std::shared_ptr<const CFBO> currentSubFBO = this->m_currentSubFBO;
  2487. if (drawTo != nullptr) {
  2488. *drawTo = currentSubFBO;
  2489. }
  2490. if (asInput != nullptr) {
  2491. *asInput = currentMainFBO;
  2492. }
  2493. this->m_currentMainFBO = currentSubFBO;
  2494. this->m_currentSubFBO = currentMainFBO;
  2495. }
  2496. void CImage::render () {
  2497. if (!this->m_initialized) {
  2498. return;
  2499. }
  2500. const auto& appContext = this->getScene ().getContext ().getApp ().getContext ();
  2501. const auto visibility = appContext.resolveObjectVisibility (this->getId (), this->getObject ().name);
  2502. // a hidden layer another object reads through _rt_imageLayerComposite_<id> (xray's "bloody" twins) still
  2503. // has to fill that FBO every frame, shouldRenderFinalPass() keeps it off the screen
  2504. if (!visibility.value_or (this->getImage ().visible->value->getBool ())
  2505. && (visibility.has_value () || !this->m_isDependency)) {
  2506. return;
  2507. }
  2508. // the last pass only goes to the screen if the layer was visible when the passes were set up,
  2509. // layers a script shows later (hidden in scene.json) need that redone
  2510. if (this->effectVisibilityChanged () || this->shouldRenderFinalPass (true) != this->m_passesDrawToScreen) {
  2511. this->rebuildActivePasses ();
  2512. }
  2513. if (this->m_image.model->passthrough && !this->m_hasActiveEffectPass && !this->m_readByOtherLayer
  2514. && !this->m_hasPassthroughChildren) {
  2515. return;
  2516. }
  2517. glColorMask (true, true, true, true);
  2518. this->updateScreenSpacePosition ();
  2519. if (this->m_hasPuppetMesh) {
  2520. this->updatePuppetSkinning ();
  2521. }
  2522. if (this->m_blendMap.pass != nullptr) {
  2523. this->m_blendMap.copyPass->render ();
  2524. this->m_blendMap.pass->render ();
  2525. }
  2526. #if !NDEBUG
  2527. std::string str = "Image ";
  2528. if (this->getScene ().getScene ().camera.bloom.enabled->value->getBool () && this->getId () == -1) {
  2529. str += "bloom";
  2530. } else {
  2531. str += this->getImage ().name + " (" + std::to_string (this->getId ()) + ", "
  2532. + this->getImage ().model->material->filename + ")";
  2533. }
  2534. glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, str.c_str ());
  2535. #endif /* DEBUG */
  2536. // WE (sub_140207B50): a passthrough layer without copybackground clears its buffer to 0,0,0,0 instead of
  2537. // drawing the scene behind it, so its effects start from a transparent image
  2538. const Effects::CPass* skippedBasePass = this->m_image.model->passthrough
  2539. && !this->m_image.copyBackground->value->getBool () && !this->m_allPasses.empty ()
  2540. ? this->m_allPasses.front ()
  2541. : nullptr;
  2542. auto cur = this->m_passes.begin ();
  2543. const auto end = this->m_passes.end ();
  2544. for (; cur != end; ++cur) {
  2545. // the scene keeps its own alpha, but a hidden dependency's last pass fills the _a buffer other layers
  2546. // read and needs its alpha (2938612768's audio cover drawn through the background's blend effects)
  2547. if (std::next (cur) == end && this->m_passesDrawToScreen) {
  2548. glColorMask (true, true, true, false);
  2549. }
  2550. if (*cur == skippedBasePass && std::next (cur) != end) {
  2551. (*cur)->clearDestination ();
  2552. } else if (*cur == this->m_puppetMeshPass && this->m_puppetClipTargetPass != nullptr) {
  2553. this->renderPuppetClipped (*cur);
  2554. } else {
  2555. (*cur)->render ();
  2556. }
  2557. if (this->m_hasPassthroughChildren && *cur == this->m_allPasses.front () && std::next (cur) != end) {
  2558. this->renderPassthroughChildren ((*cur)->getDestination ());
  2559. // the children's final passes leave the scene's rgb only mask behind
  2560. glColorMask (true, true, true, true);
  2561. }
  2562. }
  2563. // restore alpha writes - CParticle::render() never resets glColorMask, so leaving this
  2564. // disabled here leaks into the next frame's clear if bloom renders last
  2565. glColorMask (true, true, true, true);
  2566. #if !NDEBUG
  2567. glPopDebugGroup ();
  2568. #endif /* DEBUG */
  2569. }
  2570. const float& CImage::getBrightness () const { return this->m_image.brightness->value->getFloat (); }
  2571. const float& CImage::getUserAlpha () const { return this->getAlpha (); }
  2572. const float& CImage::getAlpha () const {
  2573. // some scenes store out-of-range alpha (e.g. 222) - it feeds mix() in blend modes, so it must stay in 0..1
  2574. m_alphaCache = glm::clamp (this->m_image.alpha->value->getFloat (), 0.0f, 1.0f);
  2575. return m_alphaCache;
  2576. }
  2577. const glm::vec3& CImage::getColor () const {
  2578. // a solid layer showing an image the user picked draws it untinted, its color only tints the plain
  2579. // white fill (checked against WE with 3765586324's local file background, black and white color alike)
  2580. const glm::vec3 color
  2581. = this->showsUserTextureOnSolidLayer () ? glm::vec3 (1.0f) : this->m_image.color->value->getVec3 ();
  2582. // the object's brightness only scales its color in HDR scene rendering (sub_140207740)
  2583. m_colorCache = color * (this->getScene ().isHDR () ? this->m_image.brightness->value->getFloat () : 1.0f);
  2584. return m_colorCache;
  2585. }
  2586. bool CImage::showsUserTextureOnSolidLayer () const {
  2587. if (!this->m_image.model->solidlayer || this->m_image.model->material->passes.empty ()) {
  2588. return false;
  2589. }
  2590. const auto& properties = this->getScene ().getScene ().project.properties;
  2591. for (const auto& [index, propertyName] : (*this->m_image.model->material->passes.begin ())->usertextures) {
  2592. const auto it = properties.find (propertyName);
  2593. if (it != properties.end () && !it->second->is<Data::Model::PropertyUserShortcut> ()
  2594. && !it->second->getString ().empty ()) {
  2595. return true;
  2596. }
  2597. }
  2598. return false;
  2599. }
  2600. const glm::vec4& CImage::getColor4 () const {
  2601. // "version" 2 materials take color and alpha together through g_Color4
  2602. m_color4Cache = glm::vec4 (this->getColor (), this->getAlpha ());
  2603. return m_color4Cache;
  2604. }
  2605. const glm::vec3& CImage::getCompositeColor () const { return this->m_image.color->value->getVec3 (); }
  2606. glm::vec2 CImage::resolveGeometrySize (float sceneWidth, float sceneHeight, glm::vec3& origin) const {
  2607. glm::vec2 size = this->getSize ();
  2608. if ((size.x == 0.0f || size.y == 0.0f) && this->m_texture != nullptr) {
  2609. size.x = static_cast<float> (this->m_texture->getRealWidth ());
  2610. size.y = static_cast<float> (this->m_texture->getRealHeight ());
  2611. } else if (
  2612. (size.x == 0.0f || size.y == 0.0f) && this->getImage ().model->width.has_value ()
  2613. && this->getImage ().model->height.has_value ()
  2614. ) {
  2615. size.x = static_cast<float> (this->getImage ().model->width.value ());
  2616. size.y = static_cast<float> (this->getImage ().model->height.value ());
  2617. }
  2618. if (this->getImage ().model->fullscreen) {
  2619. size = { static_cast<float> (this->getScene ().getCanvasWidth ()),
  2620. static_cast<float> (this->getScene ().getCanvasHeight ()) };
  2621. origin = { sceneWidth / 2.0f, sceneHeight / 2.0f, 0.0f };
  2622. }
  2623. return size;
  2624. }
  2625. void CImage::updateScenePosition (
  2626. const glm::vec3& origin, const glm::vec2& size, const glm::vec3& scale, float sceneWidth, float sceneHeight
  2627. ) {
  2628. glm::vec2 displaySize = size;
  2629. const glm::vec2 declared = this->getImage ().size;
  2630. const auto& model = *this->getImage ().model;
  2631. if (!model.fullscreen && !model.autosize && !model.puppet.has_value () && declared.x > 0.0f && declared.y > 0.0f) {
  2632. displaySize = declared;
  2633. }
  2634. const glm::vec2 scaledSize = displaySize * glm::vec2 (scale);
  2635. this->m_displaySize = displaySize;
  2636. this->m_pos.x = origin.x - (scaledSize.x / 2.0f);
  2637. this->m_pos.w = origin.y + (scaledSize.y / 2.0f);
  2638. this->m_pos.z = origin.x + (scaledSize.x / 2.0f);
  2639. this->m_pos.y = origin.y - (scaledSize.y / 2.0f);
  2640. const uint32_t alignment
  2641. = Data::Parsers::ObjectParser::parseAlignment (this->getImage ().alignmentName->value->getString ());
  2642. if (alignment & ImageAlignment_Top) {
  2643. this->m_pos.y -= scaledSize.y / 2.0f;
  2644. this->m_pos.w -= scaledSize.y / 2.0f;
  2645. } else if (alignment & ImageAlignment_Bottom) {
  2646. this->m_pos.y += scaledSize.y / 2.0f;
  2647. this->m_pos.w += scaledSize.y / 2.0f;
  2648. }
  2649. if (alignment & ImageAlignment_Left) {
  2650. this->m_pos.x += scaledSize.x / 2.0f;
  2651. this->m_pos.z += scaledSize.x / 2.0f;
  2652. } else if (alignment & ImageAlignment_Right) {
  2653. this->m_pos.x -= scaledSize.x / 2.0f;
  2654. this->m_pos.z -= scaledSize.x / 2.0f;
  2655. }
  2656. this->m_scenePivot = { origin.x - sceneWidth / 2.0f, sceneHeight / 2.0f - origin.y, 0.0f };
  2657. this->m_pos.x -= sceneWidth / 2.0f;
  2658. this->m_pos.y = sceneHeight / 2.0f - this->m_pos.y;
  2659. this->m_pos.z -= sceneWidth / 2.0f;
  2660. this->m_pos.w = sceneHeight / 2.0f - this->m_pos.w;
  2661. }
  2662. void CImage::uploadGeometryBuffers (const glm::vec2& size) {
  2663. GLfloat sceneSpacePosition[] = { this->m_pos.x, this->m_pos.y, 0.0f, this->m_pos.x, this->m_pos.w, 0.0f,
  2664. this->m_pos.z, this->m_pos.y, 0.0f, this->m_pos.z, this->m_pos.y, 0.0f,
  2665. this->m_pos.x, this->m_pos.w, 0.0f, this->m_pos.z, this->m_pos.w, 0.0f };
  2666. float width = 1.0f;
  2667. float height = 1.0f;
  2668. if (this->getTexture () != nullptr && !this->getTexture ()->isAnimated ()
  2669. && (this->getTexture ()->getTextureWidth (0) != this->getTexture ()->getRealWidth ()
  2670. || this->getTexture ()->getTextureHeight (0) != this->getTexture ()->getRealHeight ())) {
  2671. width = static_cast<float> (this->getTexture ()->getRealWidth ())
  2672. / static_cast<float> (this->getTexture ()->getTextureWidth (0));
  2673. height = static_cast<float> (this->getTexture ()->getRealHeight ())
  2674. / static_cast<float> (this->getTexture ()->getTextureHeight (0));
  2675. }
  2676. float x = 0.0f;
  2677. float y = 0.0f;
  2678. GLfloat realWidth = size.x;
  2679. GLfloat realHeight = size.y;
  2680. GLfloat realX = 0.0f;
  2681. GLfloat realY = 0.0f;
  2682. if (this->getImage ().model->passthrough) {
  2683. width = 1.0f;
  2684. height = 1.0f;
  2685. realX = this->m_pos.x;
  2686. realY = this->m_pos.w;
  2687. realWidth = this->m_pos.z;
  2688. realHeight = this->m_pos.y;
  2689. if (this->getImage ().model->fullscreen) {
  2690. realX = -1.0f;
  2691. realY = -1.0f;
  2692. realWidth = 1.0f;
  2693. realHeight = 1.0f;
  2694. }
  2695. }
  2696. GLfloat texcoordCopy[] = { x, height, x, y, width, height, width, height, x, y, width, y };
  2697. GLfloat copySpacePosition[] = { realX, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realHeight, 0.0f,
  2698. realWidth, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realY, 0.0f };
  2699. glBindBuffer (GL_ARRAY_BUFFER, this->m_sceneSpacePosition);
  2700. glBufferData (GL_ARRAY_BUFFER, sizeof (sceneSpacePosition), sceneSpacePosition, GL_DYNAMIC_DRAW);
  2701. glBindBuffer (GL_ARRAY_BUFFER, this->m_copySpacePosition);
  2702. glBufferData (GL_ARRAY_BUFFER, sizeof (copySpacePosition), copySpacePosition, GL_DYNAMIC_DRAW);
  2703. glBindBuffer (GL_ARRAY_BUFFER, this->m_texcoordCopy);
  2704. glBufferData (GL_ARRAY_BUFFER, sizeof (texcoordCopy), texcoordCopy, GL_DYNAMIC_DRAW);
  2705. this->m_modelViewProjectionCopy = this->getImage ().model->passthrough
  2706. ? this->m_modelViewProjectionScreen
  2707. : glm::ortho<float> (0.0, size.x, 0.0, size.y);
  2708. this->m_modelViewProjectionCopyInverse = glm::inverse (this->m_modelViewProjectionCopy);
  2709. this->m_modelMatrix = glm::ortho<float> (0.0, size.x, 0.0, size.y);
  2710. }
  2711. CImage::ResolvedTransform CImage::updateGeometryBuffers () {
  2712. auto sceneWidth = static_cast<float> (this->getScene ().getWidth ());
  2713. auto sceneHeight = static_cast<float> (this->getScene ().getHeight ());
  2714. const auto transform = this->resolveTransform (this->getImage ());
  2715. glm::vec3 origin = transform.origin;
  2716. const glm::vec3 scale = transform.scale;
  2717. const glm::vec2 size = this->resolveGeometrySize (sceneWidth, sceneHeight, origin);
  2718. this->m_size = size;
  2719. this->m_puppetScale = scale;
  2720. // must run before the puppet position buffer rebake below - it needs this frame's m_pos, not the
  2721. // previous one, to place puppet vertices at this object's actual scene position instead of its
  2722. // position from before whatever moved it (parallax, a script, an attachment point it follows, ...)
  2723. this->updateScenePosition (origin, size, scale, sceneWidth, sceneHeight);
  2724. if (this->m_pos != this->m_lastUploadedPos || size != this->m_lastUploadedGeometrySize) {
  2725. this->uploadGeometryBuffers (size);
  2726. // puppet vertices bake m_pos/scale in directly (see updatePuppetPositionBuffer), so they need
  2727. // the same "position or size changed" rebake trigger as the quad buffers above - a puppet whose
  2728. // animation is disabled (or one with no MDLA data at all, i.e. always static) would otherwise
  2729. // never get repositioned after its very first, load-time bake
  2730. if (this->m_hasPuppetMesh) {
  2731. this->updatePuppetPositionBuffer (size);
  2732. }
  2733. this->m_lastUploadedPos = this->m_pos;
  2734. this->m_lastUploadedGeometrySize = size;
  2735. }
  2736. return transform;
  2737. }
  2738. namespace {
  2739. // keeps an edge pair (e.g. m_pos.x/.z) from sliding into the on-screen part of the canvas once `offset` is added
  2740. // to both, so the image never uncovers ground it doesn't have pixels for; an image too small to cover it on this
  2741. // axis has no ground to uncover, it is an object sitting on the scene and moves freely. Canvas cropped away by the
  2742. // cover scaling is free to scroll in, WE has no clamp at all (sub_14018AAC0 adds the raw offset to the view)
  2743. float clampParallaxAxis (float offset, float edgeA, float edgeB, float visibleLow, float visibleHigh) {
  2744. const float low = std::min (edgeA, edgeB);
  2745. const float high = std::max (edgeA, edgeB);
  2746. const float maxOffset = visibleLow - low;
  2747. const float minOffset = visibleHigh - high;
  2748. if (minOffset > maxOffset) {
  2749. return offset;
  2750. }
  2751. // a layer that doesn't cover the screen at rest stays where the scene puts it (3621923790's hair), the clamp
  2752. // only keeps the parallax from uncovering more
  2753. return std::clamp (offset, std::min (minOffset, 0.0f), std::max (maxOffset, 0.0f));
  2754. }
  2755. } // namespace
  2756. glm::mat4 CImage::ancestorTiltCorrection () const {
  2757. // the quad above is placed with the parent chain folded in 2D (origin, scale, z angle). WE multiplies the full
  2758. // world matrix into the model stack instead (sub_1401E8AA0), so parents' x/y angles tilt their children too:
  2759. // map from the chain without those angles to the full one, in this centered y down space
  2760. const auto& scene = this->getScene ();
  2761. const auto localMatrix = [] (const Object& object, bool tilt) {
  2762. glm::vec3 scale = object.groupScale->value->getVec3 ();
  2763. glm::vec3 angles = object.groupAngles->value->getVec3 ();
  2764. if (object.is<Image> ()) {
  2765. scale = object.as<Image> ()->scale->value->getVec3 ();
  2766. angles = object.as<Image> ()->angles->value->getVec3 ();
  2767. } else if (object.is<Particle> ()) {
  2768. scale = object.as<Particle> ()->scale->value->getVec3 ();
  2769. angles = object.as<Particle> ()->angles->value->getVec3 ();
  2770. } else if (object.is<Text> ()) {
  2771. scale = object.as<Text> ()->scale->value->getVec3 ();
  2772. }
  2773. glm::mat4 local = glm::translate (glm::mat4 (1.0f), object.origin->value->getVec3 ());
  2774. local = glm::rotate (local, angles.z, glm::vec3 (0.0f, 0.0f, 1.0f));
  2775. if (tilt) {
  2776. local = glm::rotate (local, angles.y, glm::vec3 (0.0f, 1.0f, 0.0f));
  2777. local = glm::rotate (local, angles.x, glm::vec3 (1.0f, 0.0f, 0.0f));
  2778. }
  2779. return std::pair { glm::scale (local, scale), angles.x != 0.0f || angles.y != 0.0f };
  2780. };
  2781. glm::mat4 full (1.0f);
  2782. glm::mat4 flat (1.0f);
  2783. bool tilted = false;
  2784. const Object* current = &this->getImage ();
  2785. for (int depth = 0; current->parent.has_value () && depth < 64; depth++) {
  2786. // attachments follow a puppet bone, which the folded chain resolves on its own
  2787. if (current->attachment.has_value ()) {
  2788. return glm::mat4 (1.0f);
  2789. }
  2790. const CObject* parent = scene.getObject (current->parent.value ());
  2791. if (parent == nullptr) {
  2792. break;
  2793. }
  2794. current = &parent->getObject ();
  2795. const auto [withTilt, hasTilt] = localMatrix (*current, true);
  2796. full = withTilt * full;
  2797. flat = localMatrix (*current, false).first * flat;
  2798. tilted |= hasTilt;
  2799. }
  2800. if (!tilted) {
  2801. return glm::mat4 (1.0f);
  2802. }
  2803. const glm::mat4 toScreen = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
  2804. * glm::translate (glm::mat4 (1.0f), glm::vec3 (-scene.getWidth () / 2.0f, -scene.getHeight () / 2.0f, 0.0f));
  2805. return toScreen * full * glm::inverse (flat) * glm::inverse (toScreen);
  2806. }
  2807. void CImage::updateScreenSpacePosition () {
  2808. const ResolvedTransform transform = this->updateGeometryBuffers ();
  2809. // angles are already in radians from scene.json. WE's Rz * Ry * Rx seen through the y flip of this space is
  2810. // Rz (-z) * Ry (y) * Rx (-x) (see CParticle.cpp). Only the object's own x/y angles, the parent chain folds z only
  2811. const float angle = transform.angle;
  2812. const glm::vec3 ownAngles = this->getImage ().angles->value->getVec3 ();
  2813. // origin z only shows through a perspective camera, the ortho one keeps -2000..2000 like WE
  2814. glm::mat4 rotModel = glm::translate (glm::mat4 (1.0f), glm::vec3 (0.0f, 0.0f, transform.origin.z));
  2815. if (angle != 0.0f || ownAngles.x != 0.0f || ownAngles.y != 0.0f) {
  2816. rotModel = glm::translate (rotModel, this->m_scenePivot);
  2817. rotModel = glm::rotate (rotModel, -angle, glm::vec3 (0.0f, 0.0f, 1.0f));
  2818. rotModel = glm::rotate (rotModel, ownAngles.y, glm::vec3 (0.0f, 1.0f, 0.0f));
  2819. rotModel = glm::rotate (rotModel, -ownAngles.x, glm::vec3 (1.0f, 0.0f, 0.0f));
  2820. rotModel = glm::translate (rotModel, -this->m_scenePivot);
  2821. }
  2822. rotModel = this->ancestorTiltCorrection () * rotModel;
  2823. glm::mat4 mvp = this->getViewProjection () * rotModel;
  2824. const bool fullscreen = this->getImage ().model->fullscreen;
  2825. const auto& camera = this->getScene ().getCamera ();
  2826. // WE draws fullscreen layers with an identity transform, camera movement and parallax don't reach them
  2827. if (fullscreen) {
  2828. mvp = camera.getFullscreenProjection ();
  2829. } else if (camera.isPerspective () && !this->m_hasPuppetMesh) {
  2830. // 3D scenes: the quad (size in world units) goes through the scene camera with the image's world matrix like
  2831. // any other object (sub_1401E8AA0), "perspective" layers through their own camera. The vertices here are laid
  2832. // out in the 2D scene space, this takes them back to the object's own space first. WE's quad is the declared
  2833. // size (+752, sub_1402066A0) whatever the texture size, like the 2D layout
  2834. const glm::vec2 size = this->m_displaySize;
  2835. const glm::vec2 extent (this->m_pos.z - this->m_pos.x, this->m_pos.w - this->m_pos.y);
  2836. if (extent.x != 0.0f && extent.y != 0.0f) {
  2837. const glm::vec3 center (
  2838. (this->m_pos.x + this->m_pos.z) / 2.0f, (this->m_pos.y + this->m_pos.w) / 2.0f, 0.0f
  2839. );
  2840. // z keeps scale 1 (the quad is flat anyway), a passthrough layer inverts this matrix to draw its children
  2841. const glm::mat4 toLocal
  2842. = glm::translate (glm::scale (glm::mat4 (1.0f), glm::vec3 (size / extent, 1.0f)), -center);
  2843. const glm::mat4 viewProjection = this->getImage ().perspective->value->getBool ()
  2844. ? camera.getPerspectiveLayerViewProjection ()
  2845. : this->getScene ().getWorldViewProjection ();
  2846. mvp = viewProjection * this->worldMatrix () * toLocal;
  2847. }
  2848. }
  2849. // CScene::renderFrame() already folds disableparallax into getParallaxDisplacement(). WE's camera parallax only
  2850. // exists in orthographic scenes (scene flags & 0x108, sub_14018AAC0)
  2851. if (this->getScene ().getScene ().camera.parallax.enabled->value->getBool () && !fullscreen
  2852. && !camera.isPerspective ()) {
  2853. const glm::vec2 offset = this->getScene ().getParallaxOffset (this->getImage ());
  2854. float x = offset.x;
  2855. float y = offset.y;
  2856. // a texture that isn't UV-clamped tiles/repeats instead of showing black past its edges (GL_REPEAT,
  2857. // see CTexture.cpp), so sliding it further is harmless and exempt from the clamp; scene.json's own
  2858. // "clampuvs" overrides the base texture's flag the same way it does for the composite FBOs above
  2859. const bool textureTiles = !this->getImage ().clampUVs && this->getTexture () != nullptr
  2860. && (this->getTexture ()->getFlags () & TextureFlags_ClampUVs) == 0;
  2861. if (this->getScene ().getContext ().getApp ().getContext ().settings.mouse.clampParallaxToImageSize
  2862. && !textureTiles) {
  2863. const glm::vec4 visible = this->getScene ().getVisibleCanvasRegion ();
  2864. x = clampParallaxAxis (x, this->m_pos.x, this->m_pos.z, visible.x, visible.y);
  2865. y = clampParallaxAxis (y, this->m_pos.y, this->m_pos.w, visible.z, visible.w);
  2866. }
  2867. // WE translates the view (sub_14018AAC0), so its offset isn't turned by the layer's own rotation. The clamp's
  2868. // correction is measured on the unrotated quad and stays inside the rotation
  2869. rotModel = glm::translate (glm::mat4 (1.0f), { offset.x, offset.y, 0.0f }) * rotModel
  2870. * glm::translate (glm::mat4 (1.0f), { x - offset.x, y - offset.y, 0.0f });
  2871. mvp = this->getViewProjection () * rotModel;
  2872. }
  2873. this->updateLightingTransform (rotModel);
  2874. // only the inverse is expensive; skip it when mvp didn't actually change
  2875. if (mvp != this->m_modelViewProjectionScreen) {
  2876. this->m_modelViewProjectionScreenInverse = glm::inverse (mvp);
  2877. }
  2878. this->m_modelViewProjectionScreen = mvp;
  2879. this->m_layerModelMatrix = this->getScene ().objectWorldMatrix (this->getImage ());
  2880. // buffer space (0..size, y = size at m_pos.y like the copy quad) onto the layer's scene quad, then the screen
  2881. const glm::vec2 bufferSize = this->m_size;
  2882. if (bufferSize.x > 0.0f && bufferSize.y > 0.0f) {
  2883. glm::mat4 bufferToScene (1.0f);
  2884. bufferToScene[0][0] = (this->m_pos.z - this->m_pos.x) / bufferSize.x;
  2885. bufferToScene[1][1] = (this->m_pos.y - this->m_pos.w) / bufferSize.y;
  2886. bufferToScene[3][0] = this->m_pos.x;
  2887. bufferToScene[3][1] = this->m_pos.w;
  2888. this->m_effectModelViewProjectionCopy = mvp * bufferToScene;
  2889. // later passes draw WE's unit quad (-1..1), sub_1401EBF60 scales it by half the layer size first
  2890. glm::mat4 unitToBuffer (1.0f);
  2891. unitToBuffer[0][0] = bufferSize.x * 0.5f;
  2892. unitToBuffer[1][1] = bufferSize.y * 0.5f;
  2893. unitToBuffer[3][0] = bufferSize.x * 0.5f;
  2894. unitToBuffer[3][1] = bufferSize.y * 0.5f;
  2895. this->m_effectModelViewProjectionPass = this->m_effectModelViewProjectionCopy * unitToBuffer;
  2896. }
  2897. this->updateEffectTextureProjection ();
  2898. if (this->getImage ().model->passthrough) {
  2899. this->m_modelViewProjectionCopy = this->m_modelViewProjectionScreen;
  2900. this->m_modelViewProjectionCopyInverse = this->m_modelViewProjectionScreenInverse;
  2901. }
  2902. }
  2903. glm::mat4 CImage::getViewProjection () const {
  2904. const auto& camera = this->getScene ().getCamera ();
  2905. // "perspective" layers get their own camera in 2D scenes (sub_1401E8AA0 -> sub_1401E5B60)
  2906. if (camera.isOrthogonal () && this->getImage ().perspective->value->getBool ()) {
  2907. return camera.getPerspectiveLayerViewProjection ();
  2908. }
  2909. return camera.getProjection () * camera.getLookAt ();
  2910. }
  2911. void CImage::updateLightingTransform (const glm::mat4& sceneTransform) {
  2912. const auto width = static_cast<float> (this->getScene ().getWidth ());
  2913. const auto height = static_cast<float> (this->getScene ().getHeight ());
  2914. const glm::mat4 toWorld = glm::scale (
  2915. glm::translate (glm::mat4 (1.0f), glm::vec3 (width / 2.0f, height / 2.0f, 0.0f)), glm::vec3 (1.0f, -1.0f, 1.0f)
  2916. );
  2917. const glm::mat3 flip = glm::mat3 (glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f)));
  2918. this->m_lightingSceneModel = toWorld * sceneTransform;
  2919. this->m_lightingNormal = flip * glm::mat3 (sceneTransform) * flip;
  2920. this->m_lightingViewProjection = this->getViewProjection () * glm::inverse (toWorld);
  2921. // the first pass draws into the layer's own buffer, (0, 0) there is the image's top left corner in the scene
  2922. if (this->getImage ().model->passthrough) {
  2923. this->m_lightingCopyModel = this->m_lightingSceneModel;
  2924. return;
  2925. }
  2926. const glm::vec2 size = glm::max (this->getSize (), glm::vec2 (1.0f));
  2927. const glm::mat4 copyToScene = glm::scale (
  2928. glm::translate (glm::mat4 (1.0f), glm::vec3 (this->m_pos.x, this->m_pos.w, 0.0f)),
  2929. glm::vec3 ((this->m_pos.z - this->m_pos.x) / size.x, (this->m_pos.y - this->m_pos.w) / size.y, 1.0f)
  2930. );
  2931. this->m_lightingCopyModel = this->m_lightingSceneModel * copyToScene;
  2932. }
  2933. void CImage::updateEffectTextureProjection () {
  2934. // the final quad puts texcoord (0, 0) at (m_pos.x, m_pos.w), which is the layer's local (-1, +1) corner;
  2935. // the scene FBO is y-flipped against the screen the pointer position is measured on, hence the flip
  2936. 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);
  2937. 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);
  2938. const glm::mat4 projection = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
  2939. * this->m_modelViewProjectionScreen * glm::scale (glm::translate (glm::mat4 (1.0f), center), halfSize);
  2940. if (projection == this->m_effectTextureProjection) {
  2941. return;
  2942. }
  2943. this->m_effectTextureProjection = projection;
  2944. // a zero-sized layer has no inverse, keep the last usable one instead of feeding NaNs to the shader
  2945. if (halfSize.x != 0.0f && halfSize.y != 0.0f) {
  2946. this->m_effectTextureProjectionInverse = glm::inverse (projection);
  2947. }
  2948. const glm::vec2 size = this->getSize ();
  2949. this->m_objectSpaceProjectionInverse = glm::scale (glm::mat4 (1.0f), glm::vec3 (size.x / 2.0f, size.y / 2.0f, 1.0f))
  2950. * this->m_effectTextureProjectionInverse;
  2951. }
  2952. const Image& CImage::getImage () const { return this->m_image; }
  2953. void CImage::markAsDependency () { this->m_isDependency = true; }
  2954. glm::vec2 CImage::getSize () const {
  2955. if (this->m_texture == nullptr) {
  2956. return this->getImage ().size;
  2957. }
  2958. // compose layers sample the whole scene, but effect masks map over the layer's own size
  2959. if (this->getImage ().model->passthrough && this->getImage ().size.x > 0.0f && this->getImage ().size.y > 0.0f) {
  2960. return this->getImage ().size;
  2961. }
  2962. // solid layers use a stock white texture, the real footprint is declared by the scene
  2963. if (this->getImage ().model->solidlayer && this->getImage ().size.x > 0.0f && this->getImage ().size.y > 0.0f) {
  2964. return this->getImage ().size;
  2965. }
  2966. return { this->m_texture->getRealWidth (), this->m_texture->getRealHeight () };
  2967. }
  2968. GLuint CImage::getSceneSpacePosition () const { return this->m_sceneSpacePosition; }
  2969. GLuint CImage::getCopySpacePosition () const { return this->m_copySpacePosition; }
  2970. GLuint CImage::getPassSpacePosition () const { return this->m_passSpacePosition; }
  2971. GLuint CImage::getTexCoordCopy () const { return this->m_texcoordCopy; }
  2972. GLuint CImage::getTexCoordPass () const { return this->m_texcoordPass; }