CScene.cpp 137 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683
  1. #include "WallpaperEngine/Data/Model/Property.h"
  2. #include "WallpaperEngine/Debugging/Profiling.h"
  3. #include "WallpaperEngine/Render/DepthRange.h"
  4. #include "WallpaperEngine/Render/MissingTexture.h"
  5. #include "WallpaperEngine/Render/Objects/CCamera.h"
  6. #include "WallpaperEngine/Render/Objects/CImage.h"
  7. #include "WallpaperEngine/Render/Objects/CLight.h"
  8. #include "WallpaperEngine/Render/Objects/CMesh.h"
  9. #include "WallpaperEngine/Render/Objects/CParticle.h"
  10. #include "WallpaperEngine/Render/Objects/CSound.h"
  11. #include "WallpaperEngine/Render/Objects/CText.h"
  12. #include "WallpaperEngine/Render/Objects/PuppetIK.h"
  13. #include "WallpaperEngine/Render/WallpaperState.h"
  14. #include "CScene.h"
  15. #include "MouseMapping.h"
  16. #include "WallpaperEngine/Led/LedHub.h"
  17. #include "WallpaperEngine/Logging/Log.h"
  18. #include "WallpaperEngine/Render/LedFrameGrabber.h"
  19. #include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
  20. #include "WallpaperEngine/Scripting/ScriptableObject.h"
  21. #include "WallpaperEngine/VideoPlayback/MPV/GLPlayer.h"
  22. #include "WallpaperEngine/Data/Model/Wallpaper.h"
  23. #include "WallpaperEngine/Data/Parsers/MaterialParser.h"
  24. #include "WallpaperEngine/Data/Parsers/ObjectParser.h"
  25. #include "WallpaperEngine/Render/Shaders/GLSLContext.h"
  26. #include "WallpaperEngine/Render/Shaders/Shader.h"
  27. #include "WallpaperEngine/Data/Utils/FloatCompare.h"
  28. #include <algorithm>
  29. #include <bit>
  30. #include <chrono>
  31. #include <cmath>
  32. #include <cstdlib>
  33. #include <glm/gtc/type_ptr.hpp>
  34. #include <limits>
  35. #include <ranges>
  36. #include <regex>
  37. #include <unordered_map>
  38. extern float g_Time;
  39. extern float g_TimeLast;
  40. using namespace WallpaperEngine;
  41. using namespace WallpaperEngine::Render;
  42. using namespace WallpaperEngine::Data::Model;
  43. using namespace WallpaperEngine::Data::Parsers;
  44. using namespace WallpaperEngine::Render::Wallpapers;
  45. namespace {
  46. // general properties go through sub_1401A4DB0 like object ones with the scene as owner, so they run scripts too
  47. class SceneSettingsScripts final : public Scripting::ScriptableObject {
  48. public:
  49. SceneSettingsScripts (CScene& owner, const Object& object, const Scene& scene) :
  50. CObject (owner, object), ScriptableObject (owner, object) {
  51. const std::pair<const char*, const UserSettingUniquePtr&> settings[] = {
  52. { "ambientcolor", scene.colors.ambient },
  53. { "skylightcolor", scene.colors.skylight },
  54. { "clearcolor", scene.colors.clear },
  55. { "fogdistance", scene.fog.distanceEnabled },
  56. { "fogdistancecolor", scene.fog.distanceColor },
  57. { "fogdistancestart", scene.fog.distanceStart },
  58. { "fogdistanceend", scene.fog.distanceEnd },
  59. { "fogdistancestartdensity", scene.fog.distanceStartDensity },
  60. { "fogdistanceenddensity", scene.fog.distanceEndDensity },
  61. { "fogheight", scene.fog.heightEnabled },
  62. { "fogheightcolor", scene.fog.heightColor },
  63. { "fogheightstart", scene.fog.heightStart },
  64. { "fogheightend", scene.fog.heightEnd },
  65. { "fogheightstartdensity", scene.fog.heightStartDensity },
  66. { "fogheightenddensity", scene.fog.heightEndDensity },
  67. { "camerafade", scene.camera.fade },
  68. { "bloom", scene.camera.bloom.enabled },
  69. { "bloomstrength", scene.camera.bloom.strength },
  70. { "bloomthreshold", scene.camera.bloom.threshold },
  71. { "hdr", scene.camera.bloom.hdr },
  72. { "bloomhdrstrength", scene.camera.bloom.hdrStrength },
  73. { "bloomhdrthreshold", scene.camera.bloom.hdrThreshold },
  74. { "bloomhdrfeather", scene.camera.bloom.hdrFeather },
  75. { "bloomhdrscatter", scene.camera.bloom.hdrScatter },
  76. { "bloomhdriterations", scene.camera.bloom.hdrIterations },
  77. { "bloomtint", scene.camera.bloom.tint },
  78. { "cameraparallax", scene.camera.parallax.enabled },
  79. { "cameraparallaxamount", scene.camera.parallax.amount },
  80. { "cameraparallaxdelay", scene.camera.parallax.delay },
  81. { "cameraparallaxmouseinfluence", scene.camera.parallax.mouseInfluence },
  82. { "camerashake", scene.camera.shake.enabled },
  83. { "camerashakeamplitude", scene.camera.shake.amplitude },
  84. { "camerashakeroughness", scene.camera.shake.roughness },
  85. { "camerashakespeed", scene.camera.shake.speed },
  86. { "nearz", scene.camera.projection.nearz },
  87. { "farz", scene.camera.projection.farz },
  88. { "fov", scene.camera.projection.fov },
  89. { "perspectiveoverridefov", scene.camera.projection.perspectiveOverrideFov },
  90. { "zoom", scene.camera.projection.zoom },
  91. { "transparentsorting", scene.transparentSorting },
  92. { "gravitydirection", scene.physics.gravityDirection },
  93. { "gravitystrength", scene.physics.gravityStrength },
  94. { "windenabled", scene.physics.windEnabled },
  95. { "winddirection", scene.physics.windDirection },
  96. { "windstrength", scene.physics.windStrength },
  97. };
  98. for (const auto& [name, setting] : settings) {
  99. this->registerProperty (name, *setting->value);
  100. }
  101. }
  102. };
  103. }
  104. CScene::CScene (
  105. const Wallpaper& wallpaper, RenderContext& context, AudioContext& audioContext,
  106. const WallpaperState::TextureUVsScaling& scalingMode, const uint32_t& clampMode
  107. ) : CWallpaper (wallpaper, context, audioContext, scalingMode, clampMode) {
  108. LWE_ZONE ("scene construct");
  109. // the caller checks this, std::bad_cast otherwise
  110. auto scene = wallpaper.as<Scene> ();
  111. this->m_startTime = g_Time;
  112. this->m_scriptEngine = std::make_unique<Scripting::ScriptEngine> (*this, context.getMediaSource ());
  113. this->m_camera = std::make_unique<Camera> (*this, scene->camera);
  114. // shaders get FOG_DIST/FOG_HEIGHT from the renderer flags set when the scene loads (sub_140186440, sub_1401A5C40)
  115. this->m_fogDistance = scene->fog.distanceEnabled->value->getBool ();
  116. this->m_fogHeight = scene->fog.heightEnabled->value->getBool ();
  117. float width = scene->camera.projection.width;
  118. float height = scene->camera.projection.height;
  119. // "auto" always matches the output resolution, same as real Wallpaper Engine
  120. if (scene->camera.projection.isAuto) {
  121. width = this->getContext ().getOutput ().getFullWidth ();
  122. height = this->getContext ().getOutput ().getFullHeight ();
  123. }
  124. this->m_cameraParallax = { 0, 0 };
  125. this->m_parallaxBias = { 0, 0 };
  126. this->m_parallaxPosition = { 0.5f, 0.5f };
  127. const bool perspective = scene->camera.projection.isPerspective;
  128. if (perspective) {
  129. // 3D scenes render at the output's size, the perspective camera stretches to whatever aspect that has
  130. this->m_camera->setPerspectiveProjection (width, height);
  131. } else {
  132. float canvasWidth = width;
  133. float canvasHeight = height;
  134. if (this->getContext ().getApp ().getContext ().settings.general.expandCanvas) {
  135. this->expandCanvasToContent (*scene, width, height, canvasWidth, canvasHeight);
  136. }
  137. this->m_camera->setOrthogonalProjection (width, height, canvasWidth, canvasHeight);
  138. }
  139. // HDR rendering needs WE's "ultra" post processing plus bloom and hdr in the scene (sub_14010DF40), then the
  140. // scene and layer buffers are 16 bit float and bloom is the HDR mip chain (sub_140183610)
  141. this->m_hdr = this->getContext ().getApp ().getContext ().settings.general.ultraPostProcessing
  142. && scene->camera.bloom.enabled->value->getBool () && scene->camera.bloom.hdr->value->getBool ();
  143. // postprocessing "displayhdr" sets 0x6000 instead of 0x2000 (sub_14010DF40): the same HDR scene with the
  144. // combine_dhdr_upsample combine
  145. this->m_displayHDR = this->m_hdr && this->getContext ().getApp ().getContext ().settings.general.displayHDR;
  146. // HDR combine writes WE's FP16 swapchain format (sub_14012AC60)
  147. this->setScRGBInput (this->m_hdr);
  148. this->m_volumetrics = std::make_unique<Volumetrics> (*this);
  149. // lightconfig as the scene constructor packs it (sub_140186C90): with WE's shadow setting off spotshadowcookie
  150. // folds into spotcookie and the other shadow counts are dropped. Passes read these when they're built
  151. const auto& lightConfig = this->getScene ().lightConfig;
  152. this->m_shadowQuality = this->getContext ().getApp ().getContext ().settings.general.shadowQuality;
  153. this->m_lightingV1.points = lightConfig.point;
  154. this->m_lightingV1.spots = lightConfig.spot;
  155. this->m_lightingV1.tubes = lightConfig.tube;
  156. this->m_lightingV1.directionals = lightConfig.directional;
  157. if (this->m_shadowQuality > 0) {
  158. this->m_lightingV1.spotCookies = lightConfig.spotCookie;
  159. this->m_lightingV1.spotShadowCookies = lightConfig.spotShadowCookie;
  160. this->m_lightingV1.spotShadows = lightConfig.spotShadow;
  161. this->m_lightingV1.directionalShadows = lightConfig.directionalShadow;
  162. this->m_lightingV1.pointShadows = lightConfig.pointShadow;
  163. } else {
  164. this->m_lightingV1.spotCookies = lightConfig.spotCookie | lightConfig.spotShadowCookie;
  165. }
  166. const bool hasModels
  167. = std::ranges::any_of (scene->objects, [] (const auto& object) { return object->template is<Mesh> (); });
  168. this->setupFramebuffers (
  169. perspective || hasModels, this->m_hdr ? TextureFormat_RGBA16161616f : TextureFormat_ARGB8888
  170. );
  171. this->followOutputSize (this->find ("_rt_FullFrameBuffer"), 1);
  172. // wallpaper64.exe 2.8.42 sub_14010DF40 flags a scene when an object has a "model", only then the device gets the
  173. // msaa setting's sample count (sub_140110630, sub_14012AC60) and sub_140181AF0 makes the multisampled target
  174. if (hasModels) {
  175. this->m_msaaSamples = this->getContext ().getApp ().getContext ().settings.general.msaaSamples;
  176. }
  177. const uint32_t sceneWidth = this->m_camera->getCanvasWidth ();
  178. const uint32_t sceneHeight = this->m_camera->getCanvasHeight ();
  179. // WE creates it on the first frame with shadows at the size the tiles need (sub_140190C80), it only grows
  180. this->_rt_shadowAtlas
  181. = this->create ("_rt_shadowAtlas", TextureFormat_D32f, TextureFlags_ClampUVsBorder, 1.0, { 2, 2 }, { 2, 2 });
  182. this->alias ("_alias_lightCookie", "_rt_shadowAtlas");
  183. this->m_shadowMapping = std::make_unique<ShadowMapping> (*this, this->_rt_shadowAtlas);
  184. const glm::vec3 clearColor = scene->colors.clear->value->getVec3 ();
  185. glClearColor (clearColor.r, clearColor.g, clearColor.b, 1.0f);
  186. // general section loads before the objects, its scripts update first
  187. this->m_settingsScriptsData = ObjectParser::parse ({ { "id", -1 }, { "name", "" } }, scene->project);
  188. this->m_settingsScripts = std::make_unique<SceneSettingsScripts> (*this, *this->m_settingsScriptsData, *scene);
  189. // a constructor that throws never runs the destructor: the objects made so far (a sound's reader thread among
  190. // them) would leak and keep running
  191. struct ObjectsGuard {
  192. CScene& scene;
  193. bool armed = true;
  194. ~ObjectsGuard () {
  195. if (armed) {
  196. scene.destroyObjects ();
  197. }
  198. }
  199. } objectsGuard { *this };
  200. // a chain of parents that comes back to its start never reaches a root, and every walk along it (a layer's buffer
  201. // name, its world matrix) would go on forever: break it before any object is made
  202. std::unordered_map<int, const Object*> objectsById;
  203. for (const auto& object : scene->objects) {
  204. objectsById.emplace (object->id, object.get ());
  205. }
  206. for (const auto& object : scene->objects) {
  207. int steps = 0;
  208. for (auto current = object->parent; current.has_value () && steps < 4096; steps++) {
  209. if (*current == object->id) {
  210. sLog.error ("Parent loop through object ", object->id, " (", object->name, "), dropping its parent");
  211. object->parent.reset ();
  212. object->attachment.reset ();
  213. break;
  214. }
  215. const auto next = objectsById.find (*current);
  216. if (next == objectsById.end ()) {
  217. break;
  218. }
  219. current = next->second->parent;
  220. }
  221. }
  222. {
  223. LWE_ZONE ("create objects");
  224. for (const auto& object : scene->objects) {
  225. this->createObject (*object);
  226. }
  227. }
  228. for (const auto& object : scene->objects) {
  229. if (object->parent.has_value ()) {
  230. this->m_children[*object->parent].push_back (object->id);
  231. }
  232. }
  233. // real Wallpaper Engine draws its object list in scene.json array order unless the scene sets
  234. // customsortorder (then by each object's sortorder); parent/attachment links don't reorder anything
  235. std::vector<std::pair<const Object*, int>> objectsByPaintOrder;
  236. objectsByPaintOrder.reserve (scene->objects.size ());
  237. for (int index = 0; index < static_cast<int> (scene->objects.size ()); index++) {
  238. const Object* object = scene->objects[index].get ();
  239. objectsByPaintOrder.emplace_back (object, object->sortOrder.value_or (index));
  240. }
  241. std::ranges::stable_sort (objectsByPaintOrder, [] (const auto& a, const auto& b) { return a.second < b.second; });
  242. for (const auto& [object, sortKey] : objectsByPaintOrder) {
  243. this->addObjectToRenderOrder (*object);
  244. }
  245. // LDR bloom buffers, output sized (sub_14017F1B0); HDR scenes use the mip chain instead
  246. if (!this->m_hdr) {
  247. for (const auto& [name, divisor] : { std::pair<const char*, uint32_t> { "_rt_4FrameBuffer", 4 },
  248. { "_rt_8FrameBuffer", 8 },
  249. { "_rt_Bloom", 8 } }) {
  250. const glm::vec2 size (sceneWidth / divisor, sceneHeight / divisor);
  251. this->followOutputSize (
  252. this->create (name, TextureFormat_ARGB8888, TextureFlags_ClampUVs, 1.0, size, size),
  253. static_cast<float> (divisor)
  254. );
  255. }
  256. }
  257. this->m_loading = false;
  258. this->m_modelFiles.clear ();
  259. objectsGuard.armed = false;
  260. }
  261. CScene::~CScene () {
  262. Led::releaseFeed (this);
  263. Objects::Effects::CPass::dropRecentShaders ();
  264. if (this->m_nullTexture != GL_NONE) {
  265. glDeleteTextures (1, &this->m_nullTexture);
  266. }
  267. this->destroyObjects ();
  268. this->releaseMultisample ();
  269. }
  270. void CScene::destroyObjects () {
  271. for (const auto& val : this->m_objects | std::views::values) {
  272. delete val;
  273. }
  274. for (const auto* object : this->m_destroyedObjects) {
  275. delete object;
  276. }
  277. this->m_destroyedObjects.clear ();
  278. for (const auto& layer : this->m_releasableLayers) {
  279. delete layer.object;
  280. }
  281. this->m_releasableLayers.clear ();
  282. this->m_objectsByRenderOrder.clear ();
  283. this->m_objects.clear ();
  284. }
  285. Render::CObject* CScene::createObject (const Object& object) {
  286. Render::CObject* renderObject = nullptr;
  287. if (const auto current = this->m_objects.find (object.id); current != this->m_objects.end ()) {
  288. return current->second;
  289. }
  290. // dependency/parent loops spanning several objects exist in the wild, the object further
  291. // up the stack finishes creating itself once this call unwinds
  292. if (!this->m_objectsInCreation.insert (object.id).second) {
  293. sLog.error ("Dependency or parent cycle through object ", object.id, ", ignoring the back reference");
  294. return nullptr;
  295. }
  296. bool dependenciesReady = false;
  297. try {
  298. dependenciesReady = this->createObjectDependencies (object);
  299. } catch (...) {
  300. this->m_objectsInCreation.erase (object.id);
  301. throw;
  302. }
  303. this->m_objectsInCreation.erase (object.id);
  304. if (!dependenciesReady) {
  305. return nullptr;
  306. }
  307. {
  308. LWE_ZONE_TEXT ("create object", object.name);
  309. renderObject = this->dispatchObjectType (object);
  310. }
  311. if (renderObject != nullptr) {
  312. this->m_objects.emplace (renderObject->getId (), renderObject);
  313. }
  314. return renderObject;
  315. }
  316. bool CScene::createObjectDependencies (const Object& object) {
  317. for (const auto& cur : object.dependencies) {
  318. if (cur == object.id) {
  319. continue;
  320. }
  321. const auto dep
  322. = std::ranges::find_if (this->getScene ().objects, [&cur] (const auto& o) { return o->id == cur; });
  323. if (dep != this->getScene ().objects.end ()) {
  324. this->createObject (**dep);
  325. }
  326. }
  327. if (object.parent.has_value ()) {
  328. int parentId = object.parent.value ();
  329. const auto dep = std::ranges::find_if (this->getScene ().objects, [&parentId] (const auto& o) {
  330. return o->id == parentId;
  331. });
  332. if (dep == this->getScene ().objects.end ()) {
  333. // one object without its parent has nowhere to go, the rest of the scene still loads
  334. sLog.error (
  335. "Cannot find parent ", parentId, " for object ", object.id, " (", object.name, "), skipping it"
  336. );
  337. return false;
  338. }
  339. this->createObject (**dep);
  340. }
  341. return true;
  342. }
  343. Render::CObject* CScene::dispatchObjectType (const Object& object) {
  344. Render::CObject* renderObject = nullptr;
  345. const auto scriptMark = this->getScriptEngine ().moduleMark ();
  346. try {
  347. LWE_ZONE ("construct");
  348. renderObject = this->constructObject (object);
  349. } catch (const std::exception& e) {
  350. // the half built object is gone, the scripts its constructor queued still point at it
  351. sLog.error ("Failed to create object ", object.id, " (", object.name, "): ", e.what ());
  352. this->getScriptEngine ().dropModulesSince (scriptMark);
  353. return nullptr;
  354. }
  355. if (renderObject == nullptr) {
  356. return nullptr;
  357. }
  358. try {
  359. LWE_ZONE ("setup");
  360. renderObject->setup ();
  361. } catch (const std::exception& e) {
  362. sLog.error ("Failed to setup object ", object.id, ": ", e.what ());
  363. if (auto* scriptable = dynamic_cast<Scripting::ScriptableObject*> (renderObject); scriptable != nullptr) {
  364. this->getScriptEngine ().dropObjectScripts (*scriptable);
  365. }
  366. std::erase (this->m_sceneCameras, renderObject);
  367. delete renderObject;
  368. renderObject = nullptr;
  369. }
  370. return renderObject;
  371. }
  372. Render::CObject* CScene::constructObject (const Object& object) {
  373. Render::CObject* renderObject = nullptr;
  374. if (object.is<Image> ()) {
  375. renderObject = new Objects::CImage (*this, *object.as<Image> ());
  376. } else if (object.is<Sound> ()) {
  377. renderObject = new Objects::CSound (*this, *object.as<Sound> ());
  378. } else if (object.is<Text> ()) {
  379. renderObject = new Objects::CText (*this, *object.as<Text> ());
  380. } else if (object.is<Light> ()) {
  381. renderObject = new Objects::CLight (*this, *object.as<Light> (), this->nextFreeLightSlot ());
  382. } else if (object.is<SceneCamera> ()) {
  383. auto* camera = new Objects::CCamera (*this, *object.as<SceneCamera> ());
  384. this->m_sceneCameras.push_back (camera);
  385. renderObject = camera;
  386. } else if (object.is<Mesh> ()) {
  387. renderObject = new Objects::CMesh (*this, *object.as<Mesh> ());
  388. } else if (object.is<Particle> ()) {
  389. const auto& particleData = *object.as<Particle> ();
  390. if (this->getContext ().getApp ().getContext ().settings.general.disableParticles == true) {
  391. sLog.debug ("Ignoring particle system (disabled in settings): ", particleData.name);
  392. return nullptr;
  393. }
  394. if (!particleData.material || !particleData.material->material) {
  395. sLog.error ("Ignoring particle system with no usable material: ", particleData.name);
  396. return nullptr;
  397. }
  398. renderObject = new Objects::CParticle (*this, particleData);
  399. } else {
  400. // group/locator nodes can still carry scripts, and the shared-state bootstrap script often lives on one
  401. sLog.debug ("Creating group object without renderable: ", object.id);
  402. renderObject = new Scripting::ScriptableObject (*this, object);
  403. }
  404. return renderObject;
  405. }
  406. void CScene::addObjectToRenderOrder (const Object& object) {
  407. const auto obj = this->m_objects.find (object.id);
  408. if (obj == this->m_objects.end ()) {
  409. return;
  410. }
  411. if (!this->m_objectsInRenderOrderWalk.insert (object.id).second) {
  412. return;
  413. }
  414. for (const auto& dep : object.dependencies) {
  415. if (dep == object.id) {
  416. continue;
  417. }
  418. auto depIt = std::ranges::find_if (this->getScene ().objects, [&dep] (const auto& o) { return o->id == dep; });
  419. if (depIt != this->getScene ().objects.end ()) {
  420. this->addObjectToRenderOrder (**depIt);
  421. if (const auto created = this->m_objects.find (dep);
  422. created != this->m_objects.end () && created->second->is<Objects::CImage> ()) {
  423. created->second->as<Objects::CImage> ()->markAsDependency ();
  424. }
  425. } else {
  426. sLog.error ("Cannot find dependency ", dep, " for object ", object.id);
  427. }
  428. }
  429. const auto renderIt = std::ranges::find_if (this->m_objectsByRenderOrder, [&object] (const auto& o) {
  430. return o->getId () == object.id;
  431. });
  432. if (renderIt == this->m_objectsByRenderOrder.end ()) {
  433. this->m_objectsByRenderOrder.emplace_back (obj->second);
  434. }
  435. this->m_objectsInRenderOrderWalk.erase (object.id);
  436. }
  437. ScriptEngine& CScene::getScriptEngine () const { return *this->m_scriptEngine; }
  438. Camera& CScene::getCamera () const { return *this->m_camera; }
  439. namespace {
  440. // with LWE_FRAME_STATS set, any single step of a scene frame slower than this is logged by name, LWE_FRAME_STALL_MS
  441. // changes it (0 logs every step)
  442. double stallThresholdMs () {
  443. const char* value = std::getenv ("LWE_FRAME_STALL_MS");
  444. char* end = nullptr;
  445. const double ms = value ? std::strtod (value, &end) : 0.0;
  446. return end != value && ms >= 0.0 ? ms : 15.0;
  447. }
  448. template <typename Step> void timeStep (const std::string& label, Step&& step) {
  449. LWE_ZONE_NAMED (label);
  450. static const bool enabled = std::getenv ("LWE_FRAME_STATS") != nullptr;
  451. static const double threshold = stallThresholdMs ();
  452. if (!enabled) {
  453. step ();
  454. return;
  455. }
  456. GLuint queries[2];
  457. glGenQueries (2, queries);
  458. glFinish ();
  459. const auto start = std::chrono::steady_clock::now ();
  460. glQueryCounter (queries[0], GL_TIMESTAMP);
  461. step ();
  462. glQueryCounter (queries[1], GL_TIMESTAMP);
  463. glFinish ();
  464. const double ms = std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now () - start).count ();
  465. GLuint64 gpuStart = 0, gpuEnd = 0;
  466. glGetQueryObjectui64v (queries[0], GL_QUERY_RESULT, &gpuStart);
  467. glGetQueryObjectui64v (queries[1], GL_QUERY_RESULT, &gpuEnd);
  468. glDeleteQueries (2, queries);
  469. if (ms >= threshold) {
  470. sLog.out ("FRAME-STALL ", label, ": ", ms, "ms (gpu ", (gpuEnd - gpuStart) / 1e6, "ms)");
  471. }
  472. }
  473. }
  474. void CScene::renderFrame (const glm::ivec4& viewport) {
  475. // WE draws its scenes with a reversed float depth buffer, so does this where the driver can map clip z to 0..1
  476. const DepthRange::Scope depthRange;
  477. timeStep ("renderFrame total", [&] { this->renderFrameSteps (viewport); });
  478. }
  479. void CScene::renderFrameSteps (const glm::ivec4& viewport) {
  480. // --ssaa only scales the buffers, cursor/visible region/scripts stay in output pixels
  481. this->m_outputSize = glm::ivec2 (viewport.z, viewport.w) * this->getSupersampling ();
  482. this->m_texelSize = 1.0f / glm::max (glm::vec2 (this->m_outputSize), glm::vec2 (2.0f));
  483. this->m_texelSizeHalf = 0.5f * this->m_texelSize;
  484. this->resizeOutputBuffers (this->m_outputSize);
  485. // wallpaper64.exe sub_14017FA70 counts every frame (scene render object +340, zeroed by sub_14017C6D0) before
  486. // anything is simulated, boids pick their sample block with it
  487. this->m_frameCounter++;
  488. VideoPlayback::MPV::GLPlayer::advanceFrame ();
  489. timeStep ("updateMouse", [&] { this->updateMouse (this->cursorViewport ()); });
  490. // WE: init () while loading, then the static camera (sub_140186C90), then the first update
  491. this->getScriptEngine ().initializePending ();
  492. this->loadStaticCamera ();
  493. // WE updates every object before cursor events and scripts (sub_1401891A0 from sub_14017FA70), so scripts read
  494. // and change this frame's puppet bones and the render draws what they left
  495. for (const auto& cur : this->m_objectsByRenderOrder) {
  496. if (cur->is<Objects::CImage> ()) {
  497. cur->as<Objects::CImage> ()->updatePuppetPose ();
  498. cur->as<Objects::CImage> ()->updateTextureAnimation (this->getDeltaTime ());
  499. } else if (cur->is<Objects::CMesh> ()) {
  500. cur->as<Objects::CMesh> ()->updateAnimation ();
  501. } else if (cur->is<Objects::CParticle> ()) {
  502. cur->as<Objects::CParticle> ()->simulate ();
  503. } else if (cur->is<Objects::CSound> ()) {
  504. cur->as<Objects::CSound> ()->update (this->getDeltaTime ());
  505. }
  506. }
  507. // after the tick, so a layer a script moves this frame (e.g. onto input.cursorWorldPosition) is hit tested where it
  508. // is now
  509. timeStep ("script tick", [&] { this->getScriptEngine ().tick (); });
  510. // WE runs the object updates first, then the camera, then the parallax camera
  511. this->updateCamera ();
  512. this->updateParallax ();
  513. timeStep ("cursor events", [&] { this->dispatchCursorEvents (); });
  514. // sub_14018B390: layers the scripts destroyed go before drawing
  515. this->destroyPendingLayers ();
  516. this->updateLights ();
  517. this->updateLightingV1 ();
  518. timeStep ("shadows", [&] { this->m_shadowMapping->render (this->m_shadowEntries); });
  519. for (const auto& cur : this->m_objectsByRenderOrder) {
  520. if (!cur->is<Objects::CImage> ()) {
  521. continue;
  522. }
  523. const Objects::CImage* image = cur->as<Objects::CImage> ();
  524. #if !NDEBUG
  525. const std::string message = "Updating texture " + image->getImage ().model->filename;
  526. glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, message.c_str ());
  527. #endif
  528. timeStep ("updateTextures " + image->getObject ().name, [&] { image->updateTextures (); });
  529. #if !NDEBUG
  530. glPopDebugGroup ();
  531. #endif
  532. }
  533. glBindVertexArray (this->m_vaoBuffer);
  534. this->renderReflection ();
  535. glBindFramebuffer (GL_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
  536. glViewport (0, 0, this->m_sceneFBO->getRealWidth (), this->m_sceneFBO->getRealHeight ());
  537. // sub_140183550: the objects draw into _rt_FullFrameBufferMultiSampled, which resolves into the scene buffer
  538. // once they are done
  539. this->m_msaaActive = this->m_msaaSamples > 1 && this->prepareMultisample ();
  540. if (this->m_msaaActive) {
  541. glBindFramebuffer (GL_FRAMEBUFFER, this->m_msaaFramebuffer);
  542. }
  543. // passes leave their depthwrite and color mask behind and glClear skips masked channels; composites write rgb only,
  544. // so alpha would never reset and fullscreen layers would vanish
  545. glDepthMask (GL_TRUE);
  546. glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  547. const glm::vec3 clearColor = this->getScene ().colors.clear->value->getVec3 ();
  548. glClearColor (clearColor.r, clearColor.g, clearColor.b, 1.0f);
  549. glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  550. this->paintLetterbox ();
  551. // transparentsorting only does something in 3D scenes (render flags & 0x1008 == 0x1000, sub_14018AAC0): the rest
  552. // goes first in list order, then the transparent objects back to front
  553. if (this->getCamera ().isPerspective () && this->getScene ().transparentSorting->value->getBool ()) {
  554. std::vector<CObject*> transparent;
  555. for (auto* cur : std::vector (this->m_objectsByRenderOrder)) {
  556. if (this->isTransparentSorted (*cur)) {
  557. transparent.push_back (cur);
  558. } else {
  559. this->renderSceneObject (cur);
  560. }
  561. }
  562. for (auto* cur : this->sortedByDepth (std::move (transparent))) {
  563. this->renderSceneObject (cur);
  564. }
  565. } else {
  566. for (const auto& cur : this->m_objectsByRenderOrder) {
  567. this->renderSceneObject (cur);
  568. }
  569. }
  570. this->m_volumetrics->composite ();
  571. if (this->m_msaaActive) {
  572. this->resolveMultisample ();
  573. this->m_msaaActive = false;
  574. glBindFramebuffer (GL_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
  575. }
  576. this->updateMipMappedFrameBuffer ();
  577. // after every object (sub_14017FA70)
  578. timeStep ("post processing", [&] { this->renderPostProcessing (); });
  579. this->feedLeds ();
  580. }
  581. void CScene::feedLeds () {
  582. auto& output = Led::sharedOutput ();
  583. if (!output.running () || !Led::claimFeed (this)) {
  584. return;
  585. }
  586. using namespace std::chrono_literals;
  587. const auto now = std::chrono::steady_clock::now ();
  588. // wallpaper64.exe asks for a frame every 1/30 s
  589. if (now < this->m_ledNext) {
  590. return;
  591. }
  592. this->m_ledNext = now + 33ms;
  593. std::shared_ptr<const CFBO> source = this->m_sceneFBO;
  594. for (const auto& object : this->getScene ().objects) {
  595. const bool led = object->is<Image> ()
  596. ? object->as<Image> ()->renderable.ledSource->value->getBool ()
  597. : object->is<Text> () && object->as<Text> ()->renderable.ledSource->value->getBool ();
  598. if (!led) {
  599. continue;
  600. }
  601. if (auto layer = this->find ("_rt_imageLayerComposite_" + std::to_string (object->id) + "_a");
  602. layer != nullptr) {
  603. source = std::move (layer);
  604. break;
  605. }
  606. }
  607. if (this->m_ledGrabber == nullptr) {
  608. this->m_ledGrabber = std::make_unique<LedFrameGrabber> ();
  609. }
  610. if (this->m_ledGrabber->grab (
  611. source->getTextureID (0), static_cast<int> (source->getRealWidth ()),
  612. static_cast<int> (source->getRealHeight ()), this->m_ledFrame
  613. )) {
  614. output.submit (this->m_ledFrame);
  615. }
  616. }
  617. void CScene::paintLetterbox () const {
  618. // the bars a fit/center/free alignment leaves are part of WE's scene buffer (sub_140183A70 widens the projection
  619. // over them) and only get the clear color, whatever is drawn there shows (text screen anchors move into them).
  620. // --corner-color (with the border clamp) takes the clear color's place there, right after the clear
  621. if (this->getState ().getClampingMode () != TextureFlags_ClampUVsBorder || this->m_camera->isPerspective ()) {
  622. return;
  623. }
  624. glm::vec4 margins = this->getVisibleMargins ();
  625. if (margins.x >= 0.0f && margins.y >= 0.0f && margins.z >= 0.0f && margins.w >= 0.0f) {
  626. return;
  627. }
  628. // alignmentfliph mirrors the projection, the left bar ends up on the right
  629. if (this->isFlippedHorizontally ()) {
  630. std::swap (margins.x, margins.y);
  631. }
  632. const float width = static_cast<float> (this->getCanvasWidth ());
  633. const float height = static_cast<float> (this->getCanvasHeight ());
  634. const float visibleWidth = width - margins.x - margins.y;
  635. const float visibleHeight = height - margins.z - margins.w;
  636. const auto bufferWidth = static_cast<float> (this->m_sceneFBO->getRealWidth ());
  637. const auto bufferHeight = static_cast<float> (this->m_sceneFBO->getRealHeight ());
  638. // scene units to buffer pixels, the buffer's rows run from the bottom of the scene up
  639. const auto columnOf = [&] (const float x) {
  640. return static_cast<GLint> (std::lround ((x - margins.x) / visibleWidth * bufferWidth));
  641. };
  642. const auto rowOf = [&] (const float y) {
  643. return static_cast<GLint> (std::lround ((y - margins.z) / visibleHeight * bufferHeight));
  644. };
  645. const GLint left = std::clamp (columnOf (0.0f), 0, static_cast<GLint> (bufferWidth));
  646. const GLint right = std::clamp (columnOf (width), 0, static_cast<GLint> (bufferWidth));
  647. const GLint bottom = std::clamp (rowOf (0.0f), 0, static_cast<GLint> (bufferHeight));
  648. const GLint top = std::clamp (rowOf (height), 0, static_cast<GLint> (bufferHeight));
  649. const glm::vec4& color = this->getCornerColor ();
  650. glBindFramebuffer (GL_FRAMEBUFFER, this->getSceneDrawFramebuffer ());
  651. glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  652. glClearColor (color.r, color.g, color.b, color.a);
  653. glEnable (GL_SCISSOR_TEST);
  654. const auto fill = [] (const GLint x, const GLint y, const GLint w, const GLint h) {
  655. if (w > 0 && h > 0) {
  656. glScissor (x, y, w, h);
  657. glClear (GL_COLOR_BUFFER_BIT);
  658. }
  659. };
  660. fill (0, 0, left, static_cast<GLint> (bufferHeight));
  661. fill (right, 0, static_cast<GLint> (bufferWidth) - right, static_cast<GLint> (bufferHeight));
  662. fill (left, 0, right - left, bottom);
  663. fill (left, top, right - left, static_cast<GLint> (bufferHeight) - top);
  664. glDisable (GL_SCISSOR_TEST);
  665. }
  666. bool CScene::isShadowCasterVisible (const CObject& object) const {
  667. // the object's visible check (vtable +104) and flag 2 (under a passthrough layer), like renderSceneObject
  668. const auto visibility = this->getContext ().getApp ().getContext ().resolveObjectVisibility (
  669. object.getId (), object.getObject ().name
  670. );
  671. if (visibility.has_value () && !visibility.value ()) {
  672. return false;
  673. }
  674. if (this->isHiddenByAncestor (object) || this->isDrawnByPassthroughLayer (object)) {
  675. return false;
  676. }
  677. if (!object.is<Objects::CMesh> ()) {
  678. return true;
  679. }
  680. // casters have object flags 0xC00: "castshadow" (0x800) and a normal or alphatocoverage material (0x400)
  681. const auto& mesh = object.as<Objects::CMesh> ()->getMesh ();
  682. return mesh.groupVisible->value->getBool () && mesh.castShadow->value->getBool ();
  683. }
  684. void CScene::renderSceneObject (CObject* cur) {
  685. const auto& debug = this->getContext ().getApp ().getContext ().settings.render.debug;
  686. if (debug.objectFilter.has_value () && cur->getId () != debug.objectFilter.value ()) {
  687. return;
  688. }
  689. if (std::ranges::find (debug.skipObjects, cur->getId ()) != debug.skipObjects.end ()) {
  690. return;
  691. }
  692. const auto visibility
  693. = this->getContext ().getApp ().getContext ().resolveObjectVisibility (cur->getId (), cur->getObject ().name);
  694. if (visibility.has_value () && !visibility.value ()) {
  695. return;
  696. }
  697. if (this->isHiddenByAncestor (*cur)) {
  698. return;
  699. }
  700. // a passthrough layer above it draws it into its own buffer (object flag 2, skipped by sub_14018AAC0)
  701. if (this->isDrawnByPassthroughLayer (*cur)) {
  702. return;
  703. }
  704. // lights draw their volumes into the light buffer, which goes onto the scene before the next other object
  705. if (cur->is<Objects::CLight> ()) {
  706. this->renderLightVolume (*cur->as<Objects::CLight> (), this->getWorldViewProjection ());
  707. return;
  708. }
  709. this->m_volumetrics->composite ();
  710. timeStep ("render " + cur->getObject ().name, [&] { cur->render (); });
  711. }
  712. namespace {
  713. // sub_1400D2C60 with flag 0x10: max (1, min (log2 (np2 (w) / 2), log2 (np2 (h) / 2)) - 2) levels, np2 = the next power
  714. // of two, 8 for a 1920x1058 buffer
  715. uint32_t mipMappedLevels (const uint32_t width, const uint32_t height) {
  716. const auto halfPowerOfTwo
  717. = [] (const uint32_t value) { return std::bit_width (std::bit_ceil (std::max (value, 2u)) >> 1) - 1; };
  718. return static_cast<uint32_t> (
  719. std::max (1, static_cast<int> (std::min (halfPowerOfTwo (width), halfPowerOfTwo (height))) - 2)
  720. );
  721. }
  722. }
  723. void CScene::followOutputSize (const std::shared_ptr<CFBO>& fbo, const float divisor) {
  724. if (fbo == nullptr) {
  725. return;
  726. }
  727. const auto& buffer = this->m_outputSizedBuffers.emplace_back (OutputSizedBuffer { .fbo = fbo, .divisor = divisor });
  728. if (this->m_outputBufferSize.x > 0) {
  729. const auto size = buffer.sizeFor (this->m_outputBufferSize);
  730. fbo->resize (size.x, size.y);
  731. }
  732. }
  733. void CScene::followOutputSize (const std::shared_ptr<CFBO>& fbo, const FBO& base) {
  734. if (fbo == nullptr) {
  735. return;
  736. }
  737. const auto& buffer
  738. = this->m_outputSizedBuffers.emplace_back (OutputSizedBuffer { .fbo = fbo, .divisor = 1.0f, .base = &base });
  739. if (this->m_outputBufferSize.x > 0) {
  740. const auto size = buffer.sizeFor (this->m_outputBufferSize);
  741. fbo->resize (size.x, size.y);
  742. }
  743. }
  744. glm::uvec2 CScene::OutputSizedBuffer::sizeFor (const glm::ivec2 output) const {
  745. if (this->base != nullptr) {
  746. return this->base->bufferSize (output);
  747. }
  748. return { std::max (static_cast<uint32_t> (output.x / this->divisor), 1u),
  749. std::max (static_cast<uint32_t> (output.y / this->divisor), 1u) };
  750. }
  751. void CScene::resizeOutputBuffers (const glm::ivec2 size) {
  752. if (size == this->m_outputBufferSize || size.x <= 0 || size.y <= 0) {
  753. return;
  754. }
  755. const bool resized = this->m_outputBufferSize != glm::ivec2 (0);
  756. this->m_outputBufferSize = size;
  757. std::erase_if (this->m_outputSizedBuffers, [] (const auto& buffer) { return buffer.fbo.expired (); });
  758. for (const auto& buffer : this->m_outputSizedBuffers) {
  759. const auto bufferSize = buffer.sizeFor (size);
  760. buffer.fbo.lock ()->resize (bufferSize.x, bufferSize.y);
  761. }
  762. if (this->_rt_MipMappedFrameBuffer != nullptr) {
  763. const auto width = static_cast<uint32_t> (size.x);
  764. const auto height = static_cast<uint32_t> (size.y);
  765. this->find ("_rt_MipMappedFrameBuffer")->resize (width, height, mipMappedLevels (width, height));
  766. }
  767. if (resized) {
  768. this->getScriptEngine ().notifyResizeScreen (glm::vec2 (size / this->getSupersampling ()));
  769. }
  770. }
  771. std::shared_ptr<const CFBO> CScene::requireMipMappedFrameBuffer () {
  772. if (this->_rt_MipMappedFrameBuffer != nullptr) {
  773. return this->_rt_MipMappedFrameBuffer;
  774. }
  775. const uint32_t width = this->m_sceneFBO->getRealWidth ();
  776. const uint32_t height = this->m_sceneFBO->getRealHeight ();
  777. this->_rt_MipMappedFrameBuffer = this->create (
  778. "_rt_MipMappedFrameBuffer", this->m_sceneFBO->getFormat (), TextureFlags_ClampUVs, 1.0, { width, height },
  779. { width, height }, { 0.0f, 0.0f, 0.0f, 1.0f }, mipMappedLevels (width, height)
  780. );
  781. return this->_rt_MipMappedFrameBuffer;
  782. }
  783. std::shared_ptr<const CFBO> CScene::requireReflectionFrameBuffer () {
  784. if (this->_rt_Reflection != nullptr) {
  785. return this->_rt_Reflection;
  786. }
  787. // output size, format 1 (8 bit even in HDR scenes), a depth buffer, no mips (sub_140181AF0)
  788. const uint32_t width = this->m_sceneFBO->getRealWidth ();
  789. const uint32_t height = this->m_sceneFBO->getRealHeight ();
  790. this->_rt_Reflection = this->create (
  791. "_rt_Reflection", TextureFormat_ARGB8888, TextureFlags_ClampUVs, 1.0, { width, height }, { width, height }
  792. );
  793. this->_rt_Reflection->attachDepthBuffer ();
  794. this->followOutputSize (this->_rt_Reflection, 1);
  795. return this->_rt_Reflection;
  796. }
  797. std::shared_ptr<const CFBO> CScene::requireAlphaMaskFrameBuffer (const bool intermediate) {
  798. auto& buffer = intermediate ? this->_rt_FullAlphaMaskIntermediate : this->_rt_FullAlphaMask;
  799. if (buffer != nullptr) {
  800. return buffer;
  801. }
  802. // sub_1401AADB0 with divisor 2, no depth
  803. const uint32_t width = std::max (this->m_sceneFBO->getRealWidth () / 2, 2u);
  804. const uint32_t height = std::max (this->m_sceneFBO->getRealHeight () / 2, 2u);
  805. buffer = this->create (
  806. intermediate ? "_rt_FullAlphaMaskIntermediate" : "_rt_FullAlphaMask", TextureFormat_R8, TextureFlags_ClampUVs,
  807. 1.0, { width, height }, { width, height }
  808. );
  809. this->followOutputSize (buffer, 2);
  810. return buffer;
  811. }
  812. void CScene::addReflectionReceiver (const int id) { this->m_reflectionReceivers.insert (id); }
  813. void CScene::renderReflection () {
  814. // sub_14017FA70: with _rt_Reflection sampled and the reflection setting on, the scene is drawn again first,
  815. // mirrored on world y = 0 (view * diag (1, -1, 1, 1)); WE's extra projection y flip only offsets Direct3D's row
  816. // order, here the mirror alone flips the winding, so culling is inverted
  817. if (this->m_reflectionReceivers.empty () || this->_rt_Reflection == nullptr) {
  818. return;
  819. }
  820. auto& camera = this->getCamera ();
  821. const glm::mat4 view = camera.getWorldView ();
  822. const glm::mat4 mirrored = view * glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f));
  823. if (camera.isPerspective ()) {
  824. camera.setPerspectiveView (mirrored, camera.getViewFov ());
  825. } else {
  826. camera.setWorldView (mirrored);
  827. camera.updatePerspectiveLayers ();
  828. }
  829. glBindFramebuffer (GL_FRAMEBUFFER, this->_rt_Reflection->getFramebuffer ());
  830. glViewport (0, 0, this->_rt_Reflection->getRealWidth (), this->_rt_Reflection->getRealHeight ());
  831. glDepthMask (GL_TRUE);
  832. glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  833. const glm::vec3 clearColor = this->getScene ().colors.clear->value->getVec3 ();
  834. glClearColor (clearColor.r, clearColor.g, clearColor.b, 1.0f);
  835. glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  836. // everything the scene draws goes into the reflection target, like a passthrough layer's buffer
  837. this->m_layerTargets.push_back (
  838. {
  839. .fbo = this->_rt_Reflection,
  840. .transform = glm::mat4 (1.0f),
  841. .alphaMax = false,
  842. .viewProjection = this->getWorldViewProjection (),
  843. .viewProjectionApplied = true,
  844. }
  845. );
  846. this->m_renderingReflection = true;
  847. // scene +456 (sub_14018FF60): images, models, text and particles in creation order, minus the ones that sample the
  848. // reflection themselves and the ones with "reflected" false; no lights, sounds, cameras or groups
  849. for (auto* cur : this->m_objectsByRenderOrder) {
  850. if (cur->is<Objects::CLight> () || cur->is<Objects::CSound> () || cur->is<Objects::CCamera> ()) {
  851. continue;
  852. }
  853. if (!cur->getObject ().reflected || this->m_reflectionReceivers.contains (cur->getId ())) {
  854. continue;
  855. }
  856. this->renderSceneObject (cur);
  857. }
  858. this->m_renderingReflection = false;
  859. this->m_layerTargets.pop_back ();
  860. if (camera.isPerspective ()) {
  861. camera.setPerspectiveView (view, camera.getViewFov ());
  862. } else {
  863. camera.setWorldView (view);
  864. camera.updatePerspectiveLayers ();
  865. }
  866. }
  867. void CScene::executeEffectFunction (const ImageEffect& effect, const std::string& name) const {
  868. for (const auto* object : this->m_objects | std::views::values) {
  869. if (object->is<Objects::CRenderable> ()
  870. && object->as<Objects::CRenderable> ()->executeEffectFunction (effect, name)) {
  871. return;
  872. }
  873. }
  874. }
  875. Objects::Effects::CPass* CScene::findEffectMaterial (const ImageEffect& effect, size_t passIndex) const {
  876. for (const auto* object : this->m_objects | std::views::values) {
  877. if (object->is<Objects::CRenderable> ()) {
  878. if (auto* pass = object->as<Objects::CRenderable> ()->getEffectMaterial (effect, passIndex)) {
  879. return pass;
  880. }
  881. }
  882. }
  883. return nullptr;
  884. }
  885. GLuint CScene::getSceneDrawFramebuffer () const {
  886. return this->m_msaaActive ? this->m_msaaFramebuffer : this->m_sceneFBO->getFramebuffer ();
  887. }
  888. bool CScene::prepareMultisample () {
  889. const glm::ivec2 size (this->m_sceneFBO->getRealWidth (), this->m_sceneFBO->getRealHeight ());
  890. if (this->m_msaaFramebuffer != GL_NONE && size == this->m_msaaSize) {
  891. return true;
  892. }
  893. this->releaseMultisample ();
  894. this->m_msaaSize = size;
  895. // same color format as the scene buffer (sub_140181AF0: RGBA8, RGBA16F in HDR), a resolve needs it
  896. GLint colorFormat = GL_RGBA8;
  897. GLint maxSamples = 0;
  898. glBindTexture (GL_TEXTURE_2D, this->m_sceneFBO->getTextureID (0));
  899. glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &colorFormat);
  900. glGetIntegerv (GL_MAX_SAMPLES, &maxSamples);
  901. // the device check (CheckMultisampleQualityLevels in sub_14012AC60) falls back to one sample, no MSAA
  902. if (this->m_msaaSamples > maxSamples) {
  903. sLog.error (
  904. "MSAA x", this->m_msaaSamples, " is not supported here (at most ", maxSamples, "), drawing without"
  905. );
  906. this->m_msaaSamples = 0;
  907. return false;
  908. }
  909. glGenRenderbuffers (1, &this->m_msaaColor);
  910. glBindRenderbuffer (GL_RENDERBUFFER, this->m_msaaColor);
  911. glRenderbufferStorageMultisample (GL_RENDERBUFFER, this->m_msaaSamples, colorFormat, size.x, size.y);
  912. if (this->m_sceneFBO->getDepthbuffer () != GL_NONE) {
  913. glGenRenderbuffers (1, &this->m_msaaDepth);
  914. glBindRenderbuffer (GL_RENDERBUFFER, this->m_msaaDepth);
  915. glRenderbufferStorageMultisample (GL_RENDERBUFFER, this->m_msaaSamples, GL_DEPTH_COMPONENT32F, size.x, size.y);
  916. }
  917. glBindRenderbuffer (GL_RENDERBUFFER, 0);
  918. glGenFramebuffers (1, &this->m_msaaFramebuffer);
  919. glBindFramebuffer (GL_FRAMEBUFFER, this->m_msaaFramebuffer);
  920. glFramebufferRenderbuffer (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, this->m_msaaColor);
  921. if (this->m_msaaDepth != GL_NONE) {
  922. glFramebufferRenderbuffer (GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, this->m_msaaDepth);
  923. }
  924. const bool complete = glCheckFramebufferStatus (GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
  925. glBindFramebuffer (GL_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
  926. if (!complete) {
  927. sLog.error ("Cannot create the MSAA x", this->m_msaaSamples, " scene buffer, drawing without");
  928. this->releaseMultisample ();
  929. this->m_msaaSamples = 0;
  930. return false;
  931. }
  932. #if !NDEBUG
  933. glObjectLabel (GL_FRAMEBUFFER, this->m_msaaFramebuffer, -1, "_rt_FullFrameBufferMultiSampled");
  934. #endif
  935. return true;
  936. }
  937. void CScene::releaseMultisample () {
  938. if (this->m_msaaFramebuffer != GL_NONE) {
  939. glDeleteFramebuffers (1, &this->m_msaaFramebuffer);
  940. }
  941. if (this->m_msaaColor != GL_NONE) {
  942. glDeleteRenderbuffers (1, &this->m_msaaColor);
  943. }
  944. if (this->m_msaaDepth != GL_NONE) {
  945. glDeleteRenderbuffers (1, &this->m_msaaDepth);
  946. }
  947. this->m_msaaFramebuffer = this->m_msaaColor = this->m_msaaDepth = GL_NONE;
  948. }
  949. void CScene::resolveMultisample () const {
  950. if (!this->m_msaaActive) {
  951. return;
  952. }
  953. GLint readFramebuffer = 0;
  954. GLint drawFramebuffer = 0;
  955. glGetIntegerv (GL_READ_FRAMEBUFFER_BINDING, &readFramebuffer);
  956. glGetIntegerv (GL_DRAW_FRAMEBUFFER_BINDING, &drawFramebuffer);
  957. const GLbitfield mask = GL_COLOR_BUFFER_BIT | (this->m_msaaDepth != GL_NONE ? GL_DEPTH_BUFFER_BIT : 0);
  958. glBindFramebuffer (GL_READ_FRAMEBUFFER, this->m_msaaFramebuffer);
  959. glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
  960. glBlitFramebuffer (
  961. 0, 0, this->m_msaaSize.x, this->m_msaaSize.y, 0, 0, this->m_msaaSize.x, this->m_msaaSize.y, mask, GL_NEAREST
  962. );
  963. glBindFramebuffer (GL_READ_FRAMEBUFFER, readFramebuffer);
  964. glBindFramebuffer (GL_DRAW_FRAMEBUFFER, drawFramebuffer);
  965. }
  966. void CScene::updateMipMappedFrameBuffer () const {
  967. if (this->_rt_MipMappedFrameBuffer == nullptr) {
  968. return;
  969. }
  970. const auto width = static_cast<GLint> (this->m_sceneFBO->getRealWidth ());
  971. const auto height = static_cast<GLint> (this->m_sceneFBO->getRealHeight ());
  972. this->resolveMultisample ();
  973. glBindFramebuffer (GL_READ_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
  974. glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->_rt_MipMappedFrameBuffer->getFramebuffer ());
  975. glBlitFramebuffer (0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  976. this->_rt_MipMappedFrameBuffer->generateMipmaps ();
  977. glBindFramebuffer (GL_FRAMEBUFFER, this->getSceneDrawFramebuffer ());
  978. }
  979. glm::ivec2 CScene::getOutputResolution () const {
  980. return { std::max (this->getFramebufferWidth (), 1), std::max (this->getFramebufferHeight (), 1) };
  981. }
  982. glm::mat4 CScene::getWorldViewProjection (const bool perspectiveLayer) const {
  983. const auto& camera = this->getCamera ();
  984. if (!camera.isOrthogonal ()) {
  985. return camera.getPerspective () * camera.getView ();
  986. }
  987. const glm::vec3 center (this->getWidth () * 0.5f, this->getHeight () * 0.5f, 0.0f);
  988. // "perspective" objects get the perspective layer camera (sub_1401E5B60), models too (sub_1402222A0)
  989. const glm::mat4 viewProjection = perspectiveLayer ? camera.getPerspectiveLayerViewProjection ()
  990. : camera.getProjection () * camera.getLookAt ();
  991. return viewProjection * glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
  992. * glm::translate (glm::mat4 (1.0f), -center);
  993. }
  994. void CScene::cursorLine (
  995. const glm::vec2& ndc, const bool perspectiveLayer, glm::vec3& origin, glm::vec3& direction
  996. ) const {
  997. const glm::mat4 toWorld = glm::inverse (this->getWorldViewProjection (perspectiveLayer));
  998. const glm::vec4 nearPoint = toWorld * glm::vec4 (ndc, DepthRange::nearClip (), 1.0f);
  999. const glm::vec4 farPoint = toWorld * glm::vec4 (ndc, DepthRange::farClip (), 1.0f);
  1000. origin = glm::vec3 (nearPoint) / nearPoint.w;
  1001. direction = glm::vec3 (farPoint) / farPoint.w - origin;
  1002. }
  1003. glm::mat4 CScene::getCullViewProjection () const {
  1004. // the culling test wants WE's clip z: perspective 0 at the near plane and 1 at the far one, 2D ortho (w - z) / 2
  1005. // of GL's. Both come out of the scene matrices from a depth remap, which reversed ones already have for 2D ortho
  1006. const bool reversed = DepthRange::supported ();
  1007. if (reversed && this->getCamera ().isOrthogonal ()) {
  1008. return this->getWorldViewProjection ();
  1009. }
  1010. const float direction = reversed ? -1.0f : (this->getCamera ().isOrthogonal () ? -0.5f : 0.5f);
  1011. glm::mat4 depth (1.0f);
  1012. depth[2][2] = direction;
  1013. depth[3][2] = reversed ? 1.0f : 0.5f;
  1014. return depth * this->getWorldViewProjection ();
  1015. }
  1016. void CScene::renderPostProcessing () {
  1017. this->m_presentBackBuffer = false;
  1018. const bool postProcessing = !this->getContext ().getApp ().getContext ().settings.general.postProcessingDisabled;
  1019. if (this->m_frameMaterials == nullptr) {
  1020. auto materials = std::make_unique<FrameMaterials> ();
  1021. const auto load = [this] (const char* file) {
  1022. return std::make_unique<FrameMaterial> (*this, this->getScene ().project, file);
  1023. };
  1024. materials->combine = load (
  1025. this->m_displayHDR ? "materials/util/combine_dhdr_upsample.json"
  1026. : this->m_hdr ? "materials/util/combine_hdr_upsample.json"
  1027. : "materials/util/combine_ldr.json"
  1028. );
  1029. if (this->m_hdr) {
  1030. // combine_video_hdr.json needs renderer flag 0x10000, never set here
  1031. materials->combineWithoutBloom = load ("materials/util/combine_srgb.json");
  1032. materials->hdrDownsample = load ("materials/util/hdr_downsample.json");
  1033. materials->hdrDownsampleBloom = load ("materials/util/hdr_downsample_bloom.json");
  1034. materials->hdrUpsample = load ("materials/util/hdr_upsample.json");
  1035. materials->hdrUpsampleCubic = load ("materials/util/hdr_upsample_cubic.json");
  1036. } else if (postProcessing) {
  1037. materials->downsampleQuarterBloom = load ("materials/util/downsample_quarter_bloom.json");
  1038. materials->downsampleEighthBlurV = load ("materials/util/downsample_eighth_blur_v.json");
  1039. materials->blurHBloom = load ("materials/util/blur_h_bloom.json");
  1040. }
  1041. this->m_frameMaterials = std::move (materials);
  1042. }
  1043. // post processing not disabled, scene bloom on, something in the scene; checked every frame
  1044. const bool bloom = postProcessing && this->getScene ().camera.bloom.enabled->value->getBool ()
  1045. && !this->m_objectsByRenderOrder.empty ();
  1046. // HDR scenes go through combine_srgb even without bloom
  1047. if (bloom || this->m_hdr) {
  1048. if (bloom) {
  1049. if (this->m_hdr) {
  1050. this->renderHDRBloom ();
  1051. } else {
  1052. this->renderBloom ();
  1053. }
  1054. }
  1055. // ours draw into _rt_FullFrameBuffer and combine into their own back buffer, WE copies its back buffer there
  1056. // first
  1057. this->prepareBackBuffer (this->backBufferSize (), this->m_hdr ? GL_RGBA16F : GL_RGBA8);
  1058. FrameMaterial& combine
  1059. = bloom || !this->m_hdr ? *this->m_frameMaterials->combine : *this->m_frameMaterials->combineWithoutBloom;
  1060. combine.setUniform ("g_TexelSize", *this->getTexelSize ());
  1061. // slot 1 is _rt_2FrameBuffer
  1062. if (this->m_hdr && bloom && !this->m_hdrBloomLevels.empty ()) {
  1063. combine.setTexture (1, this->m_hdrBloomLevels.front ()->getTextureID (0));
  1064. }
  1065. combine.setUniform ("g_RenderVar0", glm::vec4 (this->combineRenderVar (), 0.0f, 0.0f));
  1066. combine.draw (this->m_backBuffer.framebuffer, this->m_backBuffer.size);
  1067. this->m_presentBackBuffer = true;
  1068. }
  1069. this->renderImageAdjustments (this->backBufferSize (), this->m_hdr ? GL_RGBA16F : GL_RGBA8);
  1070. this->renderCameraFade ();
  1071. }
  1072. glm::ivec2 CScene::backBufferSize () const {
  1073. return { this->m_sceneFBO->getRealWidth (), this->m_sceneFBO->getRealHeight () };
  1074. }
  1075. void CScene::renderCameraFade () {
  1076. // sub_14017FA70: fade alpha goes to g_Alpha, fade.json blends over the back buffer
  1077. if (this->m_cameraFade <= 0.0f) {
  1078. return;
  1079. }
  1080. auto& materials = *this->m_frameMaterials;
  1081. if (materials.fade == nullptr) {
  1082. materials.fade = std::make_unique<FrameMaterial> (*this, this->getScene ().project, "materials/util/fade.json");
  1083. }
  1084. // project schemecolor -> "tint" (sub_140154480)
  1085. const auto& properties = this->getUserProperties ();
  1086. if (const auto scheme = properties.find ("schemecolor"); scheme != properties.end () && scheme->second != nullptr) {
  1087. materials.fade->setConstant ("tint", scheme->second->getVec3 ());
  1088. }
  1089. this->prepareBackBuffer (this->backBufferSize (), this->m_hdr ? GL_RGBA16F : GL_RGBA8);
  1090. if (!this->m_presentBackBuffer) {
  1091. glBindFramebuffer (GL_READ_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
  1092. glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->m_backBuffer.framebuffer);
  1093. glBlitFramebuffer (
  1094. 0, 0, this->m_backBuffer.size.x, this->m_backBuffer.size.y, 0, 0, this->m_backBuffer.size.x,
  1095. this->m_backBuffer.size.y, GL_COLOR_BUFFER_BIT, GL_NEAREST
  1096. );
  1097. this->m_presentBackBuffer = true;
  1098. }
  1099. materials.fade->setUniform ("g_Alpha", this->m_cameraFade);
  1100. materials.fade->draw (this->m_backBuffer.framebuffer, this->m_backBuffer.size);
  1101. }
  1102. void CScene::renderBloom () {
  1103. const auto& materials = *this->m_frameMaterials;
  1104. const auto& settings = this->getScene ().camera.bloom;
  1105. // sub_140184020 / sub_14017F1B0
  1106. materials.downsampleQuarterBloom->setConstant ("bloomstrength", settings.strength->value->getFloat ());
  1107. materials.downsampleQuarterBloom->setConstant ("bloomthreshold", settings.threshold->value->getFloat ());
  1108. materials.downsampleQuarterBloom->setConstant ("bloomtint", settings.tint->value->getVec3 ());
  1109. // sub_140183610: _rt_FullFrameBuffer -> _rt_4FrameBuffer -> _rt_8FrameBuffer -> _rt_Bloom
  1110. for (const auto& [material, target] :
  1111. { std::pair<FrameMaterial*, const char*> { materials.downsampleQuarterBloom.get (), "_rt_4FrameBuffer" },
  1112. { materials.downsampleEighthBlurV.get (), "_rt_8FrameBuffer" },
  1113. { materials.blurHBloom.get (), "_rt_Bloom" } }) {
  1114. material->setUniform ("g_TexelSize", *this->getTexelSize ());
  1115. material->draw (*this->find (target));
  1116. }
  1117. }
  1118. void CScene::renderHDRBloom () {
  1119. const auto& materials = *this->m_frameMaterials;
  1120. const auto& settings = this->getScene ().camera.bloom;
  1121. // sub_14017F1B0: a level per halving of the smaller side, 8 at most
  1122. const glm::ivec2 client = glm::max (this->m_outputSize, glm::ivec2 (2));
  1123. int available = 0;
  1124. for (int side = std::min (client.x, client.y) / 2; side > 0 && available < 8; side /= 2) {
  1125. available++;
  1126. }
  1127. while (static_cast<int> (this->m_hdrBloomLevels.size ()) < available) {
  1128. const int divisor = 2 << this->m_hdrBloomLevels.size ();
  1129. const glm::vec2 size = glm::max (glm::vec2 (client / divisor), glm::vec2 (1.0f));
  1130. auto fbo = this->create (
  1131. "_rt_" + std::to_string (divisor) + "FrameBuffer", TextureFormat_RGBA16161616f, TextureFlags_ClampUVs, 1.0,
  1132. size, size
  1133. );
  1134. this->followOutputSize (fbo, static_cast<float> (divisor));
  1135. this->m_hdrBloomLevels.push_back (std::move (fbo));
  1136. }
  1137. if (available == 0) {
  1138. return;
  1139. }
  1140. // sub_140184020
  1141. const int levels = std::max (std::min (available, settings.hdrIterations->value->getInt ()), 1);
  1142. const float scatter = settings.hdrScatter->value->getFloat ();
  1143. const float threshold = settings.hdrThreshold->value->getFloat ();
  1144. const float knee = threshold * settings.hdrFeather->value->getFloat ();
  1145. materials.hdrDownsampleBloom->setConstant (
  1146. "bloomstrength",
  1147. settings.hdrStrength->value->getFloat ()
  1148. / (std::pow (scatter, static_cast<float> (std::max (levels, 2) - 2)) + 1.0f)
  1149. );
  1150. materials.hdrDownsampleBloom->setConstant (
  1151. "blend", glm::vec4 (threshold, threshold - knee, knee + knee, 0.25f / (knee + 0.0000099999997f))
  1152. );
  1153. materials.hdrDownsampleBloom->setConstant ("bloomtint", settings.tint->value->getVec3 ());
  1154. materials.hdrUpsample->setConstant ("scatter", scatter);
  1155. materials.hdrUpsampleCubic->setConstant ("scatter", scatter);
  1156. // sub_140183610: g_RenderVar0 = (1, 1, -1, -1) / client size * step
  1157. const glm::vec2 texel = 1.0f / glm::vec2 (client);
  1158. const auto draw = [&] (FrameMaterial& material, const GLuint source, const CFBO& target, const float step) {
  1159. material.setTexture (0, source);
  1160. material.setUniform ("g_RenderVar0", glm::vec4 (texel * step, -texel * step));
  1161. material.setUniform ("g_TexelSize", *this->getTexelSize ());
  1162. material.draw (target);
  1163. };
  1164. // threshold into level 0, halve down the chain, add back up (last two bicubic)
  1165. draw (*materials.hdrDownsampleBloom, this->m_sceneFBO->getTextureID (0), *this->m_hdrBloomLevels[0], 1.0f);
  1166. for (int level = 1; level < levels; level++) {
  1167. draw (
  1168. *materials.hdrDownsample, this->m_hdrBloomLevels[level - 1]->getTextureID (0),
  1169. *this->m_hdrBloomLevels[level], static_cast<float> (1 << level)
  1170. );
  1171. }
  1172. for (int level = levels - 1; level > 0; level--) {
  1173. draw (
  1174. level < levels - 2 ? *materials.hdrUpsample : *materials.hdrUpsampleCubic,
  1175. this->m_hdrBloomLevels[level]->getTextureID (0), *this->m_hdrBloomLevels[level - 1],
  1176. static_cast<float> (2 << (level - 1))
  1177. );
  1178. }
  1179. }
  1180. glm::vec2 CScene::combineRenderVar () const {
  1181. // (white, peak - white) / 80 in WE's scRGB (sub_14012AC60), relative to the output's reference white here
  1182. const glm::vec2& luminance = this->getOutputLuminance ();
  1183. if (!this->isOutputHDR () || luminance.x <= 0.0f) {
  1184. return glm::vec2 (1.0f);
  1185. }
  1186. const float peak = std::max (luminance.y, 80.0f);
  1187. const float white = std::max (std::min (luminance.x, peak), 80.0f);
  1188. return glm::vec2 (white, peak - white) / luminance.x;
  1189. }
  1190. void CScene::updateParallax () {
  1191. if (this->getScene ().camera.parallax.enabled->value->getBool ()) {
  1192. // the wallpaper's position goes through the mouse parallax depth/clamp, halved to match its range; only x keeps
  1193. // WallpaperState's sign flip, y is applied after the y-up conversion
  1194. const glm::vec2 positionBias
  1195. = { -this->getState ().getOffsetX () * 0.5f, this->getState ().getOffsetY () * 0.5f };
  1196. if (this->getContext ().getApp ().getContext ().settings.mouse.disableparallax) {
  1197. this->m_parallaxBias = positionBias;
  1198. this->m_cameraParallax = { 0.0f, 0.0f };
  1199. } else {
  1200. const float influence = this->getScene ().camera.parallax.mouseInfluence->value->getFloat ();
  1201. const float amount = this->getScene ().camera.parallax.amount->value->getFloat ();
  1202. const float delay = this->getScene ().camera.parallax.delay->value->getFloat ();
  1203. this->m_parallaxBias = positionBias * amount * influence;
  1204. // WE's easing: no delay snaps to the mouse, else a fast exponential follow. A camera object's eye moves it
  1205. // too, before the smoothing (sub_1401891A0); y up, the cursor is flipped, the eye isn't
  1206. const glm::vec2 eye = { this->m_cameraEye.x / static_cast<float> (this->getWidth ()),
  1207. this->m_cameraEye.y / static_cast<float> (this->getHeight ()) };
  1208. const glm::vec2 cursor
  1209. = glm::clamp (glm::vec2 (this->m_mousePosition.x, 1.0f - this->m_mousePosition.y), 0.0f, 1.0f);
  1210. const glm::vec2 target = (cursor - glm::vec2 (0.5f, 0.5f)) * influence + eye;
  1211. if (delay <= 0.0f) {
  1212. this->m_cameraParallax = target;
  1213. } else {
  1214. const float dt = std::max (g_Time - g_TimeLast, 0.0f);
  1215. const float follow = std::min (1.0f, (1.0f - delay / 3.0f) * 10.0f * dt);
  1216. this->m_cameraParallax += (target - this->m_cameraParallax) * follow;
  1217. }
  1218. }
  1219. this->m_parallaxPosition = glm::clamp (glm::vec2 (0.5f) + this->m_cameraParallax, 0.0f, 1.0f);
  1220. }
  1221. }
  1222. glm::mat4 CScene::objectLocalMatrix (const Object& object) {
  1223. // images and particles keep their own (scriptable) scale and angles next to the base object's copy
  1224. glm::vec3 scale = object.groupScale->value->getVec3 ();
  1225. glm::vec3 angles = object.groupAngles->value->getVec3 ();
  1226. if (object.is<Image> ()) {
  1227. scale = object.as<Image> ()->scale->value->getVec3 ();
  1228. angles = object.as<Image> ()->angles->value->getVec3 ();
  1229. } else if (object.is<Particle> ()) {
  1230. scale = object.as<Particle> ()->scale->value->getVec3 ();
  1231. angles = object.as<Particle> ()->angles->value->getVec3 ();
  1232. } else if (object.is<Text> ()) {
  1233. scale = object.as<Text> ()->scale->value->getVec3 ();
  1234. }
  1235. glm::mat4 transform = glm::translate (glm::mat4 (1.0f), object.origin->value->getVec3 ());
  1236. transform = glm::rotate (transform, angles.z, glm::vec3 (0.0f, 0.0f, 1.0f));
  1237. transform = glm::rotate (transform, angles.y, glm::vec3 (0.0f, 1.0f, 0.0f));
  1238. transform = glm::rotate (transform, angles.x, glm::vec3 (1.0f, 0.0f, 0.0f));
  1239. return glm::scale (transform, scale);
  1240. }
  1241. namespace {
  1242. // sub_1401DD630, without the scale
  1243. glm::mat4 objectFrameLocal (const Object& object) {
  1244. const glm::vec3 angles = object.is<Image> () ? object.as<Image> ()->angles->value->getVec3 ()
  1245. : object.is<Particle> () ? object.as<Particle> ()->angles->value->getVec3 ()
  1246. : object.groupAngles->value->getVec3 ();
  1247. glm::mat4 transform = glm::translate (glm::mat4 (1.0f), object.origin->value->getVec3 ());
  1248. transform = glm::rotate (transform, angles.z, glm::vec3 (0.0f, 0.0f, 1.0f));
  1249. transform = glm::rotate (transform, angles.y, glm::vec3 (0.0f, 1.0f, 0.0f));
  1250. return glm::rotate (transform, angles.x, glm::vec3 (1.0f, 0.0f, 0.0f));
  1251. }
  1252. bool isPassthroughImage (const CObject& object) {
  1253. return object.is<Objects::CImage> () && object.as<Objects::CImage> ()->getImage ().model->passthrough;
  1254. }
  1255. }
  1256. glm::mat4 CScene::parentChainMatrix (const Object& object, bool scaled) const {
  1257. glm::mat4 chain (1.0f);
  1258. const Object* current = &object;
  1259. for (int depth = 0; current->parent.has_value () && depth < 64; depth++) {
  1260. const CObject* parent = this->getObject (current->parent.value ());
  1261. if (parent == nullptr) {
  1262. break;
  1263. }
  1264. // sub_1401850A0: onto the parent's attachment point first
  1265. if (current->attachment.has_value ()) {
  1266. std::optional<glm::mat4> attachment;
  1267. if (parent->is<Objects::CMesh> ()) {
  1268. attachment = parent->as<Objects::CMesh> ()->getAttachmentMatrix (*current->attachment);
  1269. } else if (parent->is<Objects::CImage> ()) {
  1270. attachment = parent->as<Objects::CImage> ()->getAttachmentMatrix (*current->attachment);
  1271. }
  1272. if (attachment.has_value ()) {
  1273. chain = *attachment * chain;
  1274. }
  1275. }
  1276. current = &parent->getObject ();
  1277. chain = (scaled ? objectLocalMatrix (*current) : objectFrameLocal (*current)) * chain;
  1278. }
  1279. return chain;
  1280. }
  1281. glm::mat4 CScene::objectWorldMatrix (const Object& object) const {
  1282. return this->parentChainMatrix (object, true) * objectLocalMatrix (object);
  1283. }
  1284. glm::mat4 CScene::objectFrameMatrix (const Object& object) const {
  1285. return this->parentChainMatrix (object, false) * objectFrameLocal (object);
  1286. }
  1287. bool CScene::queueDestroyLayer (CObject& object) {
  1288. if (std::ranges::find (this->m_objectsByRenderOrder, &object) == this->m_objectsByRenderOrder.end ()) {
  1289. return false;
  1290. }
  1291. this->m_pendingDestroy.insert (&object);
  1292. return true;
  1293. }
  1294. bool CScene::isPendingDestroy (const CObject& object) const {
  1295. return this->m_pendingDestroy.contains (const_cast<CObject*> (&object));
  1296. }
  1297. // a layer's own buffers and render object are what a script that keeps creating and destroying layers piles up (two
  1298. // layer sized framebuffers each, which the scene's name map and the output follower list never let go)
  1299. bool CScene::isReleasable (const CObject& object) const {
  1300. // only what scripts made while running: nothing in the scene file can name them. Cameras, lights and models are
  1301. // listed elsewhere too (m_sceneCameras, the light slots, the shadow casters)
  1302. return object.getId () >= DYNAMIC_LAYER_ID_BASE && !object.is<Objects::CMesh> () && !object.is<Objects::CLight> ()
  1303. && !object.is<Objects::CCamera> ();
  1304. }
  1305. void CScene::releaseDestroyedLayers () {
  1306. // destroyed in an earlier frame: the lists, the script handles (forgotten) and the render order let go of it then
  1307. constexpr uint32_t gracePeriod = 2;
  1308. const auto due = std::ranges::stable_partition (this->m_releasableLayers, [this] (const DestroyedLayer& layer) {
  1309. return this->m_frameCounter - layer.frame < gracePeriod;
  1310. });
  1311. for (const auto& layer : due) {
  1312. const int id = layer.object->getId ();
  1313. this->m_transparentSorted.erase (layer.object);
  1314. // the text a layer was made from is most of what the model costs, and the model has to stay: animation clocks
  1315. // and script handles may still point into it
  1316. if (auto* scriptable = dynamic_cast<Scripting::ScriptableObject*> (layer.object); scriptable != nullptr) {
  1317. scriptable->dropScriptSources ();
  1318. }
  1319. delete layer.object;
  1320. this->remove ("_rt_imageLayerComposite_" + std::to_string (id) + "_a");
  1321. this->remove ("_rt_imageLayerComposite_" + std::to_string (id) + "_b");
  1322. this->releaseLayerModel (id);
  1323. }
  1324. if (due.empty ()) {
  1325. return;
  1326. }
  1327. this->m_releasableLayers.erase (due.begin (), due.end ());
  1328. std::erase_if (this->m_outputSizedBuffers, [] (const OutputSizedBuffer& buffer) { return buffer.fbo.expired (); });
  1329. }
  1330. void CScene::releaseLayerModel (int id) {
  1331. const auto data = this->m_dynamicObjectData.find (id);
  1332. if (data == this->m_dynamicObjectData.end ()) {
  1333. return;
  1334. }
  1335. // the timelines of its values go first, they write into them every frame
  1336. this->getScriptEngine ().getAnimations ().removeObject (id);
  1337. // an IEffect or IMaterial a script holds points into the model for good, those layers keep it
  1338. if (this->getScriptEngine ().getAdapters ().object->hasEffectHandles (*data->second)) {
  1339. std::string ().swap (data->second->initialConfig);
  1340. return;
  1341. }
  1342. this->m_dynamicObjectData.erase (data);
  1343. }
  1344. void CScene::destroyPendingLayers () {
  1345. this->releaseDestroyedLayers ();
  1346. // sub_1401909C0: children keep their transforms but lose the parent, scripts get destroy (). A scene's own layer
  1347. // stays allocated until the scene goes, others may hold its buffers
  1348. const auto pending = std::exchange (this->m_pendingDestroy, {});
  1349. for (auto* object : pending) {
  1350. for (auto* child : this->childrenOf (object->getId ())) {
  1351. child->getObject ().parent.reset ();
  1352. child->getObject ().attachment.reset ();
  1353. }
  1354. this->m_children.erase (object->getId ());
  1355. this->detachChild (*object);
  1356. object->getObject ().parent.reset ();
  1357. if (auto* scriptable = dynamic_cast<Scripting::ScriptableObject*> (object)) {
  1358. this->getScriptEngine ().destroyObjectScripts (*scriptable);
  1359. }
  1360. std::erase (this->m_objectsByRenderOrder, object);
  1361. this->m_objects.erase (object->getId ());
  1362. this->m_cursorInside.erase (object->getId ());
  1363. this->m_cursorPressed.erase (object->getId ());
  1364. if (this->isReleasable (*object)) {
  1365. this->m_releasableLayers.push_back ({ object, this->m_frameCounter });
  1366. } else {
  1367. this->m_destroyedObjects.push_back (object);
  1368. }
  1369. }
  1370. }
  1371. bool CScene::scriptsMayReparent () const {
  1372. if (!this->m_scriptsMayReparent.has_value ()) {
  1373. this->m_scriptsMayReparent = std::ranges::any_of (this->getScene ().objects, [] (const auto& object) {
  1374. return object->initialConfig.find ("setParent") != std::string::npos;
  1375. });
  1376. }
  1377. return *this->m_scriptsMayReparent;
  1378. }
  1379. int CScene::passthroughDepth (const CObject& object, const int level) const {
  1380. const int own = isPassthroughImage (object) ? 1 : 0;
  1381. int depth = own;
  1382. if (level >= 64) {
  1383. return depth;
  1384. }
  1385. for (const auto* child : this->childrenOf (object.getId ())) {
  1386. depth = std::max (depth, this->passthroughDepth (*child, level + 1) + own);
  1387. }
  1388. return depth;
  1389. }
  1390. bool CScene::setObjectParent (CObject& object, const CObject* parent, int attachment, bool adjustTransforms) {
  1391. const Object& data = object.getObject ();
  1392. const CObject* current = data.parent.has_value () ? this->getObject (*data.parent) : nullptr;
  1393. // an index without a point keeps the identity like WE
  1394. std::optional<std::string> attachmentName;
  1395. if (parent != nullptr && attachment >= 0) {
  1396. const Objects::PuppetRig* rig = parent->is<Objects::CImage> () ? &parent->as<Objects::CImage> ()->getRig ()
  1397. : parent->is<Objects::CMesh> () ? &parent->as<Objects::CMesh> ()->getRig ()
  1398. : nullptr;
  1399. if (rig != nullptr && static_cast<size_t> (attachment) < rig->attachmentPoints.size ()) {
  1400. attachmentName = rig->attachmentPoints[attachment].name;
  1401. }
  1402. }
  1403. if (current == parent && (parent == nullptr || data.attachment == attachmentName)) {
  1404. return true;
  1405. }
  1406. // itself, or more than 3 passthrough layers deep: WE drops the parent and reports the error
  1407. int parentDepth = 0;
  1408. int steps = 0;
  1409. bool loops = false;
  1410. // the chain of parents ends at a root, unless it comes back to the object (or loops among others, which only the
  1411. // step count stops: a loop of plain groups never raises parentDepth)
  1412. for (const CObject* ancestor = parent; ancestor != nullptr && parentDepth < 64 && steps < 1024; steps++) {
  1413. loops = loops || ancestor == &object;
  1414. parentDepth += isPassthroughImage (*ancestor) ? 1 : 0;
  1415. const auto& next = ancestor->getObject ().parent;
  1416. ancestor = next.has_value () ? this->getObject (*next) : nullptr;
  1417. }
  1418. this->detachChild (object);
  1419. if (parent != nullptr && (loops || steps >= 1024)) {
  1420. sLog.error (
  1421. "Cannot make object ", object.getId (), " a child of ", parent->getId (), ", the parents would loop"
  1422. );
  1423. }
  1424. if (parent == &object || loops || steps >= 1024 || parentDepth + this->passthroughDepth (object) > 3) {
  1425. data.parent.reset ();
  1426. data.attachment.reset ();
  1427. return false;
  1428. }
  1429. auto* scriptable = dynamic_cast<Scripting::ScriptableObject*> (&object);
  1430. DynamicValue* origin = scriptable != nullptr ? scriptable->tryGetProperty ("origin") : nullptr;
  1431. DynamicValue* angles = scriptable != nullptr ? scriptable->tryGetProperty ("angles") : nullptr;
  1432. DynamicValue* scale = scriptable != nullptr ? scriptable->tryGetProperty ("scale") : nullptr;
  1433. if (!adjustTransforms || origin == nullptr || angles == nullptr || scale == nullptr) {
  1434. data.parent = parent != nullptr ? std::optional (parent->getId ()) : std::nullopt;
  1435. data.attachment = attachmentName;
  1436. this->attachChild (object);
  1437. return true;
  1438. }
  1439. const glm::mat4 world = this->objectWorldMatrix (data);
  1440. const glm::mat4 frame = this->objectFrameMatrix (data);
  1441. const glm::mat4 unscaledWorld = this->parentChainMatrix (data, true) * objectFrameLocal (data);
  1442. const glm::vec3 savedScale = scale->getVec3 ();
  1443. data.parent = parent != nullptr ? std::optional (parent->getId ()) : std::nullopt;
  1444. data.attachment = attachmentName;
  1445. this->attachChild (object);
  1446. if (parent != nullptr && attachment >= 0) {
  1447. origin->update (glm::vec3 (0.0f), DynamicValue::UpdateSource::Script);
  1448. angles->update (glm::vec3 (0.0f), DynamicValue::UpdateSource::Script);
  1449. return true;
  1450. }
  1451. const glm::mat4 parentWorld = parent != nullptr ? this->objectWorldMatrix (parent->getObject ()) : glm::mat4 (1.0f);
  1452. const glm::mat4 parentFrame = parent != nullptr ? this->objectFrameMatrix (parent->getObject ()) : glm::mat4 (1.0f);
  1453. const glm::mat4 local = glm::inverse (parentWorld) * world;
  1454. const glm::mat4 rotation = glm::inverse (parentFrame) * frame;
  1455. const float* m = glm::value_ptr (rotation);
  1456. const float z = std::atan2 (m[1], m[0]);
  1457. const float y = std::atan2 (-m[2], std::sqrt (m[6] * m[6] + m[10] * m[10]));
  1458. const float x = std::atan2 (std::sin (z) * m[8] - std::cos (z) * m[9], std::cos (z) * m[5] - std::sin (z) * m[4]);
  1459. origin->update (glm::vec3 (local[3]), DynamicValue::UpdateSource::Script);
  1460. angles->update (glm::vec3 (x, y, z), DynamicValue::UpdateSource::Script);
  1461. const glm::mat4 newUnscaledWorld = this->parentChainMatrix (data, true) * objectFrameLocal (data);
  1462. glm::vec3 adjusted;
  1463. for (int axis = 0; axis < 3; axis++) {
  1464. const float length = glm::length (newUnscaledWorld[axis]);
  1465. adjusted[axis]
  1466. = savedScale[axis] * glm::length (unscaledWorld[axis]) * (length > 1.1920929e-7f ? 1.0f / length : 1.0f);
  1467. }
  1468. scale->update (adjusted, DynamicValue::UpdateSource::Script);
  1469. return true;
  1470. }
  1471. void CScene::updateCameraPath (const float dt, glm::vec3& eye, glm::vec3& center, glm::vec3& up, float& zoom) {
  1472. // sub_1401891A0: the keys of one path at a time, cubic Hermite between two keys with tangents of half their
  1473. // difference, then the next path once the last key is done
  1474. const auto& paths = this->getScene ().camera.paths;
  1475. this->m_pathIndex %= static_cast<int> (paths.size ());
  1476. const auto& path = paths[this->m_pathIndex];
  1477. if (path.keys.empty ()) {
  1478. this->m_pathIndex = (this->m_pathIndex + 1) % static_cast<int> (paths.size ());
  1479. return;
  1480. }
  1481. const int count = static_cast<int> (path.keys.size ());
  1482. this->m_pathKey = std::min (this->m_pathKey, count - 1);
  1483. const auto& key = path.keys[this->m_pathKey];
  1484. const float time = this->m_pathTime;
  1485. float until;
  1486. eye = key.eye;
  1487. center = key.center;
  1488. up = key.up;
  1489. zoom = key.zoom;
  1490. if (time < key.time) {
  1491. until = (this->m_pathKey + 1 < count ? path.keys[this->m_pathKey + 1].time : 0.0f) + key.time;
  1492. } else if (this->m_pathKey + 1 < count) {
  1493. const auto& next = path.keys[this->m_pathKey + 1];
  1494. // two keys at one time (an editor can write them) are a jump to the second, not a division by zero
  1495. const float s = next.time > key.time ? (time - key.time) / (next.time - key.time) : 1.0f;
  1496. const float s2 = s * s;
  1497. const float s3 = s2 * s;
  1498. const float h00 = 2.0f * s3 - 3.0f * s2 + 1.0f;
  1499. const float h10 = s3 - 2.0f * s2 + s;
  1500. const float h01 = 3.0f * s2 - 2.0f * s3;
  1501. const float h11 = s3 - s2;
  1502. const auto hermite = [&] (const auto& a, const auto& b) {
  1503. const auto tangent = (b - a) * 0.5f;
  1504. return a * h00 + tangent * h10 + b * h01 + tangent * h11;
  1505. };
  1506. eye = hermite (key.eye, next.eye);
  1507. center = hermite (key.center, next.center);
  1508. up = hermite (key.up, next.up);
  1509. zoom = hermite (key.zoom, next.zoom);
  1510. until = next.time;
  1511. } else {
  1512. until = path.duration - key.time;
  1513. }
  1514. this->m_pathTime = time + dt;
  1515. if (this->m_pathTime > until) {
  1516. if (this->m_pathKey + 1 >= count || path.duration <= path.keys[this->m_pathKey + 1].time) {
  1517. this->m_pathIndex = (this->m_pathIndex + 1) % static_cast<int> (paths.size ());
  1518. this->m_pathKey = 0;
  1519. this->m_pathTime = 0.0f;
  1520. } else {
  1521. this->m_pathKey++;
  1522. }
  1523. }
  1524. // camerafade darkens the first and last half second of every path (sub_14017FA70)
  1525. if (this->getScene ().camera.fade->value->getBool ()) {
  1526. const auto& current = paths[this->m_pathIndex];
  1527. const float left = current.duration - this->m_pathTime;
  1528. if (left < 0.5f) {
  1529. this->m_cameraFade = 1.0f - 2.0f * left;
  1530. } else if (left > current.duration - 0.5f) {
  1531. this->m_cameraFade = 1.0f - 2.0f * (current.duration - left);
  1532. }
  1533. }
  1534. }
  1535. void CScene::updateFog (const glm::vec3& eye) {
  1536. const auto& fog = this->getScene ().fog;
  1537. const auto params = [] (const auto& start, const auto& end, const auto& startDensity, const auto& endDensity) {
  1538. const float from = start->value->getFloat ();
  1539. const float density = startDensity->value->getFloat ();
  1540. return glm::vec4 (from, end->value->getFloat () - from, density, endDensity->value->getFloat () - density);
  1541. };
  1542. this->m_fog.distanceColor = fog.distanceColor->value->getVec3 ();
  1543. this->m_fog.distanceParams
  1544. = params (fog.distanceStart, fog.distanceEnd, fog.distanceStartDensity, fog.distanceEndDensity);
  1545. this->m_fog.heightColor = fog.heightColor->value->getVec3 ();
  1546. this->m_fog.heightParamsWorld
  1547. = params (fog.heightStart, fog.heightEnd, fog.heightStartDensity, fog.heightEndDensity);
  1548. this->m_fog.heightParamsLocal = this->m_fog.heightParamsWorld;
  1549. this->m_fog.eyeWorld = eye;
  1550. this->m_fog.eyeLocal = eye;
  1551. if (!this->m_camera->isPerspective ()) {
  1552. // 2D scenes: WE's eye sits 2000 units out over the scene center plus the camera (end of sub_1401891A0), and
  1553. // a height of y here is H/2 - y there
  1554. const float height = static_cast<float> (this->getHeight ());
  1555. this->m_fog.eyeWorld
  1556. = glm::vec3 (static_cast<float> (this->getWidth ()) * 0.5f + eye.x, height * 0.5f + eye.y, 2000.0f);
  1557. this->m_fog.eyeLocal = glm::vec3 (eye.x, -eye.y, 2000.0f);
  1558. this->m_fog.heightParamsLocal.x = height * 0.5f - this->m_fog.heightParamsWorld.x;
  1559. this->m_fog.heightParamsLocal.y = -this->m_fog.heightParamsWorld.y;
  1560. }
  1561. }
  1562. void CScene::updateCamera () {
  1563. const auto& appContext = this->getContext ().getApp ().getContext ();
  1564. Objects::CCamera* active = nullptr;
  1565. for (CObject* object : this->m_sceneCameras) {
  1566. const auto override = appContext.resolveObjectVisibility (object->getId (), object->getObject ().name);
  1567. if (override.value_or (object->getObject ().groupVisible->value->getBool ())
  1568. && !this->isHiddenByAncestor (*object)) {
  1569. active = object->as<Objects::CCamera> ();
  1570. }
  1571. }
  1572. const float dt = std::max (g_Time - g_TimeLast, 0.0f);
  1573. // without a camera object or path the camera is the static one, which scripts can move
  1574. const bool perspective = this->m_camera->isPerspective ();
  1575. const StaticCamera& base = this->getStaticCamera ();
  1576. glm::vec3 eye = base.eye;
  1577. glm::vec3 center = base.center;
  1578. glm::vec3 up = base.up;
  1579. float fov = this->m_camera->getFov ();
  1580. float zoom = base.zoom;
  1581. this->m_cameraFade = 0.0f;
  1582. if (active != nullptr) {
  1583. glm::mat4 world = this->objectWorldMatrix (active->getObject ());
  1584. zoom = active->getCamera ().zoom->value->getFloat ();
  1585. fov = active->getCamera ().fov->value->getFloat ();
  1586. // a camera path file drives the camera's transform, zoom and fov (sub_1401F2AD0)
  1587. const auto& data = active->getObject ();
  1588. const CObject* parent = data.parent.has_value () ? this->getObject (data.parent.value ()) : nullptr;
  1589. const glm::mat4 parentWorld
  1590. = parent != nullptr ? this->objectWorldMatrix (parent->getObject ()) : glm::mat4 (1.0f);
  1591. if (const auto pose = active->updateTimeline (dt, world, parentWorld); pose.has_value ()) {
  1592. world = pose->world;
  1593. zoom = pose->zoom;
  1594. fov = pose->fov;
  1595. }
  1596. // eye at the camera's position, looking down its -z axis, its y axis up
  1597. eye = glm::vec3 (world[3]);
  1598. center = eye - glm::vec3 (world[2]);
  1599. up = glm::vec3 (world[1]);
  1600. } else if (!this->getScene ().camera.paths.empty ()) {
  1601. this->updateCameraPath (dt, eye, center, up, zoom);
  1602. }
  1603. if (this->getScene ().camera.shake.enabled->value->getBool ()) {
  1604. // sub_140199580: speed and roughness shape a cos/sin wobble on the scene clock, it moves eye and center alike
  1605. const auto& shake = this->getScene ().camera.shake;
  1606. const float roughness = std::pow (shake.roughness->value->getFloat (), 3.0f);
  1607. const float speed = shake.speed->value->getFloat ();
  1608. const float time = speed * speed * this->getSceneClock ();
  1609. glm::vec3 offset (std::cos (time), std::sin (time * 1.333f), perspective ? std::sin (time) : 0.0f);
  1610. float amplitude = shake.amplitude->value->getFloat () * 0.1f;
  1611. if (!perspective) {
  1612. amplitude *= static_cast<float> (this->getHeight ()) * 0.1f;
  1613. }
  1614. if (roughness > 0.001f && !WallpaperEngine::Data::Utils::sameFloat (roughness, 1.0f)) {
  1615. const float length = glm::length (offset);
  1616. if (length > 0.0f) {
  1617. offset *= std::pow (length, roughness) / length;
  1618. }
  1619. }
  1620. eye += offset * amplitude;
  1621. center += offset * amplitude;
  1622. }
  1623. const glm::mat4 view = glm::lookAt (eye, center, up);
  1624. this->m_cameraEye = perspective ? glm::vec2 (0.0f) : glm::vec2 (eye);
  1625. this->updateFog (eye);
  1626. if (perspective) {
  1627. this->m_camera->setVisibleRegion ({}, this->getOutputAspect ());
  1628. this->m_camera->setPerspectiveView (view, fov);
  1629. return;
  1630. }
  1631. this->m_camera->setWorldView (view);
  1632. this->m_camera->setZoom (this->getScene ().camera.projection.zoom->value->getFloat () * zoom);
  1633. this->m_camera->setVisibleRegion (this->getVisibleMargins (), this->getOutputAspect ());
  1634. this->m_camera->updatePerspectiveLayers ();
  1635. }
  1636. void CScene::dispatchCursorEvents () {
  1637. if (!this->getContext ().getApp ().getContext ().settings.mouse.enabled) {
  1638. return;
  1639. }
  1640. const bool down = this->cursorLeftClick () == Input::MouseClickStatus::Clicked;
  1641. const bool pressed = down && !this->m_cursorLeftDown;
  1642. const bool released = !down && this->m_cursorLeftDown;
  1643. this->m_cursorLeftDown = down;
  1644. const glm::vec2 scenePosition = { this->m_mousePositionNormalized.x * static_cast<float> (this->getWidth ()),
  1645. this->m_mousePositionNormalized.y * static_cast<float> (this->getHeight ()) };
  1646. const bool moved = scenePosition != this->m_cursorLastScenePosition;
  1647. this->m_cursorLastScenePosition = scenePosition;
  1648. auto& engine = this->getScriptEngine ();
  1649. // handlers are free to create layers, which would move things around under a live iteration. 3D scenes walk a
  1650. // copy sorted by depth like the transparent pass (sub_1401865C0), 2D ones the creation order
  1651. const auto objects = this->getCamera ().isPerspective () ? this->sortedByDepth (this->m_objectsByRenderOrder)
  1652. : this->m_objectsByRenderOrder;
  1653. // WE (sub_140189E10) checks for a drag before the pass: while the button is held on something pressed,
  1654. // only the pressed objects hear about it, and only through cursorMove
  1655. const bool dragging = down && !this->m_cursorPressed.empty ();
  1656. // hitBox only while pressed or the button changed
  1657. const bool wantsHitBox = !this->m_cursorPressed.empty () || pressed || released;
  1658. // scene buffer clip space, what the objects' matrices project to (clip y grows towards the bottom of the screen);
  1659. // m_cursorScreen.y is mirrored on flipped outputs, the hover zones of 3599498791 picked the opposite weekday on
  1660. // Wayland
  1661. const glm::vec2 ndc { this->m_cursorScreen.x * 2.0f - 1.0f,
  1662. cursorClipY (this->m_cursorScreen.y, this->getState ().isVFlipped ()) };
  1663. // topmost first, like WE. Hidden objects are hit tested and get events too, they just can't stop propagation.
  1664. // Images and text (object types 1 and 4) test their quad, models (type 5) their bounds
  1665. for (auto it = objects.rbegin (); it != objects.rend (); ++it) {
  1666. auto* cur = *it;
  1667. if (!cur->getObject ().solid->value->getBool ()) {
  1668. continue;
  1669. }
  1670. Scripting::ScriptableObject* scriptable = nullptr;
  1671. bool hit = false;
  1672. bool visible = false;
  1673. // the event's localPosition is whatever the object's hit test left behind (sub_14019DBB0 / sub_140185520),
  1674. // quads fill it in off the quad too
  1675. glm::vec3 local {};
  1676. std::optional<std::string> hitBox;
  1677. if (cur->is<Objects::CImage> ()) {
  1678. auto* image = cur->as<Objects::CImage> ();
  1679. scriptable = image;
  1680. hit = image->hitTest (ndc);
  1681. // fullscreen layers get the cursor in window pixels: WE stores ScreenToClient / client size and multiplies
  1682. // it back by the client size (sub_140110630, sub_14017F1B0)
  1683. local = image->getImage ().model->fullscreen ? glm::vec3 (this->m_mousePositionViewport, 0.0f)
  1684. : glm::vec3 (image->cursorLocalPosition (ndc), 0.0f);
  1685. visible = image->getImage ().visible->value->getBool ();
  1686. if (wantsHitBox) {
  1687. hitBox = image->cursorHitBox (ndc);
  1688. }
  1689. } else if (cur->is<Objects::CText> ()) {
  1690. auto* text = cur->as<Objects::CText> ();
  1691. scriptable = text;
  1692. hit = text->hitTest (ndc);
  1693. local = glm::vec3 (text->cursorLocalPosition (ndc), 0.0f);
  1694. visible = text->getText ().visible->value->getBool ();
  1695. } else if (cur->is<Objects::CMesh> ()) {
  1696. auto* mesh = cur->as<Objects::CMesh> ();
  1697. scriptable = mesh;
  1698. hit = mesh->hitTest (ndc);
  1699. local = mesh->cursorLocalPosition (ndc);
  1700. visible = mesh->getMesh ().groupVisible->value->getBool ();
  1701. if (wantsHitBox) {
  1702. hitBox = mesh->cursorHitBox (ndc, local);
  1703. }
  1704. } else {
  1705. continue;
  1706. }
  1707. const int id = cur->getId ();
  1708. const bool handlers = engine.hasCursorHandlers (*scriptable);
  1709. const auto dispatch = [&] (const char* event) {
  1710. if (handlers) {
  1711. engine.dispatchCursorEvent (event, *scriptable, scenePosition, local, hitBox);
  1712. }
  1713. };
  1714. if (dragging) {
  1715. if (moved && this->m_cursorPressed.contains (id)) {
  1716. dispatch ("cursorMove");
  1717. }
  1718. continue;
  1719. }
  1720. if (!hit) {
  1721. if (released && this->m_cursorPressed.contains (id)) {
  1722. dispatch ("cursorUp");
  1723. }
  1724. if (this->m_cursorInside.erase (id) > 0) {
  1725. dispatch ("cursorLeave");
  1726. }
  1727. continue;
  1728. }
  1729. if (this->m_cursorInside.insert (id).second) {
  1730. dispatch ("cursorEnter");
  1731. }
  1732. if (moved) {
  1733. dispatch ("cursorMove");
  1734. }
  1735. if (pressed) {
  1736. dispatch ("cursorDown");
  1737. this->m_cursorPressed.insert (id);
  1738. } else if (released) {
  1739. dispatch ("cursorUp");
  1740. if (this->m_cursorPressed.contains (id)) {
  1741. dispatch ("cursorClick");
  1742. }
  1743. }
  1744. if (!cur->getObject ().disablePropagation->value->getBool ()) {
  1745. continue;
  1746. }
  1747. const auto visibility
  1748. = this->getContext ().getApp ().getContext ().resolveObjectVisibility (id, cur->getObject ().name);
  1749. if (visibility.value_or (visible) && !this->isHiddenByAncestor (*cur)) {
  1750. break;
  1751. }
  1752. }
  1753. if (!down) {
  1754. this->m_cursorPressed.clear ();
  1755. }
  1756. }
  1757. void CScene::updateMouse (const glm::ivec4& viewport) {
  1758. const glm::dvec2 position = this->cursorPosition ();
  1759. this->m_pointerPositionLast = this->m_pointerPosition;
  1760. this->m_mousePositionViewport = glm::vec2 (position.x - viewport.x, position.y - viewport.y);
  1761. // not clamped: WE stores ScreenToClient over the client size as is (sub_140110630, renderer +140/+144), so a
  1762. // pointer off the window or on another monitor reaches scripts, events and g_PointerPosition outside 0..1; only
  1763. // the parallax clamps it (sub_1401891A0)
  1764. double mouseX = (position.x - viewport.x) / viewport.z;
  1765. // WE flips by mirroring its projection, so the cursor lands on what is shown under it
  1766. if (this->isFlippedHorizontally ()) {
  1767. mouseX = 1.0 - mouseX;
  1768. }
  1769. // GL convention, 0 bottom 1 top
  1770. double normalizedMouseY = (position.y - viewport.y) / viewport.w;
  1771. // the scene buffer holds what the output shows, the visible region maps the cursor onto the scene
  1772. const glm::vec4 output = this->getOutputUVs ();
  1773. const glm::vec4 visible = this->getVisibleUVs ();
  1774. this->m_cursorScreen.x = output.x + mouseX * (output.y - output.x);
  1775. this->m_cursorScreen.y = output.z + normalizedMouseY * (output.w - output.z);
  1776. this->m_mousePositionNormalized.x = visible.x + mouseX * (visible.y - visible.x);
  1777. this->m_mousePositionNormalized.y = visible.z + normalizedMouseY * (visible.w - visible.z);
  1778. // WE's renderer +140/+144: client coords, y from the top
  1779. this->m_mousePosition.x = this->m_cursorScreen.x;
  1780. this->m_mousePosition.y = static_cast<float> (1.0 - normalizedMouseY);
  1781. // g_PointerPosition is ScreenToClient over the client size, never mirrored by alignmentfliph (sub_140110630,
  1782. // uniform 105 reads renderer +140 in sub_1400D8300)
  1783. const float pointerX = this->isFlippedHorizontally () ? 1.0f - this->m_mousePosition.x : this->m_mousePosition.x;
  1784. this->m_pointerPosition = { pointerX, this->m_mousePosition.y };
  1785. }
  1786. glm::vec4 CScene::getVisibleUVs () const {
  1787. const auto& state = this->getState ();
  1788. // 3D scenes keep the whole view, the perspective takes the output's aspect instead
  1789. if (this->m_camera->isPerspective () || state.getViewportWidth () <= 0 || state.getViewportHeight () <= 0) {
  1790. return this->getOutputUVs ();
  1791. }
  1792. const auto uvs = state.getTextureUVs ();
  1793. return { uvs.ustart, uvs.uend, uvs.vstart, uvs.vend };
  1794. }
  1795. glm::vec4 CScene::getVisibleMargins () const {
  1796. const glm::vec4 uvs = this->getVisibleUVs ();
  1797. const float width = this->getCanvasWidth ();
  1798. const float height = this->getCanvasHeight ();
  1799. const bool vflip = this->getState ().isVFlipped ();
  1800. // v runs top down in a flipped state, bottom up otherwise
  1801. return { uvs.x * width, (1.0f - uvs.y) * width, (vflip ? 1.0f - uvs.w : uvs.w) * height,
  1802. (vflip ? uvs.z : 1.0f - uvs.z) * height };
  1803. }
  1804. glm::vec4 CScene::getVisibleCanvasRegion () const {
  1805. glm::vec4 margins = glm::max (this->getVisibleMargins (), glm::vec4 (0.0f));
  1806. const float halfWidth = static_cast<float> (this->getCanvasWidth ()) / 2.0f;
  1807. const float halfHeight = static_cast<float> (this->getCanvasHeight ()) / 2.0f;
  1808. // the margins are on screen, a mirrored projection puts the left one on the canvas' right
  1809. if (this->isFlippedHorizontally ()) {
  1810. std::swap (margins.x, margins.y);
  1811. }
  1812. return { -halfWidth + margins.x, halfWidth - margins.y, -halfHeight + margins.w, halfHeight - margins.z };
  1813. }
  1814. const Data::Model::Properties& CScene::getUserProperties () const {
  1815. return this->getWallpaperData ().project.properties;
  1816. }
  1817. const Scene& CScene::getScene () const { return *this->getWallpaperData ().as<Scene> (); }
  1818. void CScene::expandCanvasToContent (
  1819. const Scene& scene, const float width, const float height, float& canvasWidth, float& canvasHeight
  1820. ) const {
  1821. // keeps the expanded canvas within what the GPU is guaranteed to be able to allocate for a framebuffer
  1822. constexpr float maxCanvasSize = 8192.0f;
  1823. float extentX = width / 2.0f;
  1824. float extentY = height / 2.0f;
  1825. for (const auto& object : scene.objects) {
  1826. if (!object->is<Image> ()) {
  1827. continue;
  1828. }
  1829. const auto* image = object->as<Image> ();
  1830. // children are positioned relative to their parent, and a layer with no declared size takes its
  1831. // texture's, which isn't known this early
  1832. if (image->parent.has_value () || image->size.x <= 0.0f || image->size.y <= 0.0f || image->origin == nullptr
  1833. || image->scale == nullptr) {
  1834. continue;
  1835. }
  1836. const auto visibility
  1837. = this->getContext ().getApp ().getContext ().resolveObjectVisibility (image->id, image->name);
  1838. if (visibility.has_value () && !visibility.value ()) {
  1839. continue;
  1840. }
  1841. if (image->visible != nullptr && !image->visible->value->getBool ()) {
  1842. continue;
  1843. }
  1844. const glm::vec3 origin = image->origin->value->getVec3 ();
  1845. const glm::vec3 scale = image->scale->value->getVec3 ();
  1846. // rotation is ignored on purpose, a rotated layer just keeps the extent its unrotated box has
  1847. extentX = std::max (extentX, std::abs (origin.x - width / 2.0f) + std::abs (scale.x) * image->size.x / 2.0f);
  1848. extentY = std::max (extentY, std::abs (origin.y - height / 2.0f) + std::abs (scale.y) * image->size.y / 2.0f);
  1849. }
  1850. canvasWidth = std::min (std::ceil (extentX * 2.0f), std::max (width, maxCanvasSize));
  1851. canvasHeight = std::min (std::ceil (extentY * 2.0f), std::max (height, maxCanvasSize));
  1852. if (!WallpaperEngine::Data::Utils::sameFloat (canvasWidth, width)
  1853. || !WallpaperEngine::Data::Utils::sameFloat (canvasHeight, height)) {
  1854. sLog.out ("Expanded scene canvas from ", width, "x", height, " to ", canvasWidth, "x", canvasHeight);
  1855. }
  1856. }
  1857. int CScene::getWidth () const { return this->m_camera->getWidth (); }
  1858. int CScene::getHeight () const { return this->m_camera->getHeight (); }
  1859. int CScene::getCanvasWidth () const { return this->m_camera->getCanvasWidth (); }
  1860. int CScene::getCanvasHeight () const { return this->m_camera->getCanvasHeight (); }
  1861. float CScene::getTime () const { return g_Time; }
  1862. float CScene::getDeltaTime () const { return g_Time - g_TimeLast; }
  1863. Objects::PuppetRopeEnvironment CScene::getRopeEnvironment () const {
  1864. const auto& physics = this->getScene ().physics;
  1865. return {
  1866. .gravity = physics.gravityDirection->value->getVec3 () * physics.gravityStrength->value->getFloat (),
  1867. .wind = physics.windEnabled->value->getBool (),
  1868. .windDirection = physics.windDirection->value->getVec3 (),
  1869. .windStrength = physics.windStrength->value->getFloat (),
  1870. .clock = this->getSceneClock (),
  1871. // 0 for perspective scenes (sub_140186C90)
  1872. .width = this->getScene ().camera.projection.isPerspective ? 0.0f : static_cast<float> (this->getWidth ()),
  1873. };
  1874. }
  1875. float CScene::getSceneClock () const {
  1876. // wallpaper64.exe sub_14017FA70 starts over at 0 once it passes 432000 (the frame crossing it is dropped there)
  1877. return std::fmod (std::max (g_Time - this->m_startTime, 0.0f), 432000.0f);
  1878. }
  1879. uint32_t CScene::getFrameCounter () const { return this->m_frameCounter; }
  1880. float CScene::getFps () const {
  1881. const float dt = g_Time - g_TimeLast;
  1882. if (dt <= 1e-6f) {
  1883. return 60.0f;
  1884. }
  1885. return 1.0f / dt;
  1886. }
  1887. const glm::vec2* CScene::getPointerPosition () const { return &this->m_pointerPosition; }
  1888. const glm::vec2* CScene::getPointerPositionLast () const { return &this->m_pointerPositionLast; }
  1889. const glm::vec2* CScene::getMousePositionNormalized () const { return &this->m_mousePositionNormalized; }
  1890. const glm::vec2* CScene::getCursorScreenPosition () const { return &this->m_cursorScreen; }
  1891. glm::vec3 CScene::unprojectCursor () const {
  1892. // WE unprojects the cursor (x, 1 - y) through the view and projection on top of the renderer's stacks, with glm's
  1893. // unProject (depth 0.5 -> NDC 0) for scripts (sub_14018E070 -> sub_14019DF90) and NDC depth 0 for particle control
  1894. // points (sub_14022E3E0). Its projections are Direct3D ones, so NDC depth 0 is the near plane
  1895. const glm::vec2 ndc { this->m_cursorScreen.x * 2.0f - 1.0f,
  1896. cursorClipY (this->m_cursorScreen.y, this->getState ().isVFlipped ()) };
  1897. const auto& camera = this->getCamera ();
  1898. if (camera.isPerspective ()) {
  1899. const glm::vec4 world = glm::inverse (camera.getPerspective () * camera.getView ())
  1900. * glm::vec4 (ndc, DepthRange::nearClip (), 1.0f);
  1901. return glm::vec3 (world) / world.w;
  1902. }
  1903. return glm::vec3 (
  1904. glm::inverse (camera.getProjection () * camera.getLookAt ()) * glm::vec4 (ndc, DepthRange::middleClip (), 1.0f)
  1905. );
  1906. }
  1907. glm::vec3 CScene::getCursorWorldPosition () const {
  1908. const glm::vec3 position = this->unprojectCursor ();
  1909. if (this->getCamera ().isPerspective ()) {
  1910. return position;
  1911. }
  1912. // the 2D layout is WE's world moved to the scene center and flipped vertically (Camera::setWorldView); WE zeroes z
  1913. // in orthographic scenes (renderer flag 0x400)
  1914. return { position.x + static_cast<float> (this->getWidth ()) / 2.0f,
  1915. static_cast<float> (this->getHeight ()) / 2.0f - position.y, 0.0f };
  1916. }
  1917. glm::vec2 CScene::getCursorPixelPosition () const {
  1918. // sub_14018E070 with its screen flag: g_PointerPosition times the window client size, x mirrored on renderer flag
  1919. // 0x800 (horizontal flip). m_mousePosition is already mirrored
  1920. const auto& state = this->getState ();
  1921. return { this->m_mousePosition.x * static_cast<float> (state.getViewportWidth ()),
  1922. this->m_mousePosition.y * static_cast<float> (state.getViewportHeight ()) };
  1923. }
  1924. float CScene::getOutputAspect () const {
  1925. const auto& state = this->getState ();
  1926. if (state.getViewportWidth () <= 0 || state.getViewportHeight () <= 0) {
  1927. return static_cast<float> (this->getCanvasWidth ()) / static_cast<float> (this->getCanvasHeight ());
  1928. }
  1929. return static_cast<float> (state.getViewportWidth ()) / static_cast<float> (state.getViewportHeight ());
  1930. }
  1931. const glm::vec2* CScene::getParallaxPosition () const { return &this->m_parallaxPosition; }
  1932. glm::vec2 CScene::getParallaxOffset (const Object& object) const {
  1933. if (!this->getScene ().camera.parallax.enabled->value->getBool ()) {
  1934. return { 0.0f, 0.0f };
  1935. }
  1936. // every object has a parallaxDepth, (1, 1) unless set (base object constructor sub_14016BE90)
  1937. const auto depthOf = [] (const Object& candidate) -> glm::vec2 {
  1938. if (candidate.is<Image> ()) {
  1939. return candidate.as<Image> ()->parallaxDepth->value->getVec2 ();
  1940. }
  1941. if (candidate.is<Text> ()) {
  1942. return candidate.as<Text> ()->parallaxDepth->value->getVec2 ();
  1943. }
  1944. if (candidate.is<Particle> ()) {
  1945. return candidate.as<Particle> ()->parallaxDepth->value->getVec2 ();
  1946. }
  1947. return candidate.groupParallaxDepth->value->getVec2 ();
  1948. };
  1949. // the topmost ancestor moves its whole subtree, guarded against a malformed parent loop
  1950. constexpr int maxParentDepth = 32;
  1951. const Object* anchor = &object;
  1952. for (int i = 0; i < maxParentDepth && anchor->parent.has_value (); ++i) {
  1953. const CObject* parent = this->getObject (anchor->parent.value ());
  1954. if (parent == nullptr) {
  1955. break;
  1956. }
  1957. anchor = &parent->getObject ();
  1958. }
  1959. const std::optional<glm::vec2> depth = depthOf (*anchor);
  1960. const float amount = this->getScene ().camera.parallax.amount->value->getFloat ();
  1961. const float width = static_cast<float> (this->getWidth ());
  1962. const float height = static_cast<float> (this->getHeight ());
  1963. glm::vec2 shift = (*depth + amount) * this->m_parallaxBias * width;
  1964. if (!this->getContext ().getApp ().getContext ().settings.mouse.disableparallax) {
  1965. // real engine: (origin - cameraPosition) * amount * depth in its y up world (sub_14018AAC0), the camera
  1966. // sitting at the mouse-driven point of the scene. This space is y down, hence the negated y
  1967. const glm::vec3 origin = anchor->origin->value->getVec3 ();
  1968. shift.x += (origin.x - width * 0.5f - this->m_cameraParallax.x * width) * amount * depth->x;
  1969. shift.y -= (origin.y - height * 0.5f - this->m_cameraParallax.y * height) * amount * depth->y;
  1970. }
  1971. return shift;
  1972. }
  1973. const std::vector<CObject*>& CScene::getObjectsByRenderOrder () const { return this->m_objectsByRenderOrder; }
  1974. int CScene::nextFreeLightSlot () const {
  1975. int used = 0;
  1976. for (const auto* object : this->m_objects | std::views::values) {
  1977. if (object->is<Objects::CLight> ()) {
  1978. used |= 1 << object->as<Objects::CLight> ()->getSlot ();
  1979. }
  1980. }
  1981. for (int slot = 0; slot < 4; slot++) {
  1982. if ((used & (1 << slot)) == 0) {
  1983. return slot;
  1984. }
  1985. }
  1986. return 0;
  1987. }
  1988. void CScene::updateLights () {
  1989. // an empty slot is black with radius 1, WE parks it at (0, 100, 0)
  1990. glm::vec4 colors[4];
  1991. glm::vec3 positions[4];
  1992. std::ranges::fill (colors, glm::vec4 (0.0f, 0.0f, 0.0f, 1.0f));
  1993. std::ranges::fill (positions, glm::vec3 (0.0f, 100.0f, 0.0f));
  1994. for (const auto* object : this->m_objects | std::views::values) {
  1995. if (!object->is<Objects::CLight> ()) {
  1996. continue;
  1997. }
  1998. const auto* light = object->as<Objects::CLight> ();
  1999. const auto& data = light->getLight ();
  2000. if (data.type != LightType::Legacy) {
  2001. continue;
  2002. }
  2003. const auto override = this->getContext ().getApp ().getContext ().resolveObjectVisibility (data.id, data.name);
  2004. const bool visible = override.has_value () ? override.value () : data.visible->value->getBool ();
  2005. if (!visible || this->isHiddenByAncestor (*light)) {
  2006. continue;
  2007. }
  2008. const int slot = light->getSlot ();
  2009. const float intensity = data.intensity->value->getFloat ();
  2010. colors[slot]
  2011. = glm::vec4 (glm::vec3 (data.color->value->getVec3 ()) * intensity, data.radius->value->getFloat ());
  2012. positions[slot] = data.origin->value->getVec3 ();
  2013. }
  2014. std::ranges::copy (colors, this->m_lightsColorRadius);
  2015. // radiance is color / distance^2 in the shader, so the color is scaled by radius^2; the fourth light's
  2016. // color rides in the .w of the other three
  2017. for (int i = 0; i < 3; i++) {
  2018. this->m_lightsColorPremultiplied[i] = glm::vec4 (glm::vec3 (colors[i]) * colors[i].w * colors[i].w, 0.0f);
  2019. this->m_lightsColorPremultiplied[i].w = colors[3][i] * colors[3].w * colors[3].w;
  2020. }
  2021. std::ranges::copy (positions, this->m_lightsPosition);
  2022. }
  2023. std::vector<const Light*> CScene::sortedLightingV1Lights () const {
  2024. // sub_140186990 orders the visible lights by type, then shadow/cookie flags (set ones first), then by their own
  2025. // origin along the camera's forward axis
  2026. const auto& camera = this->getCamera ();
  2027. const glm::vec3 forward = camera.isOrthogonal ()
  2028. ? glm::vec3 (0.0f, 0.0f, -1.0f)
  2029. : -glm::vec3 (camera.getView ()[0][2], camera.getView ()[1][2], camera.getView ()[2][2]);
  2030. struct Entry {
  2031. int type;
  2032. int flags;
  2033. float depth;
  2034. const Light* light;
  2035. };
  2036. std::vector<Entry> entries;
  2037. for (const auto* object : this->m_objects | std::views::values) {
  2038. if (!object->is<Objects::CLight> ()) {
  2039. continue;
  2040. }
  2041. const auto& data = object->as<Objects::CLight> ()->getLight ();
  2042. if (data.type == LightType::Legacy) {
  2043. continue;
  2044. }
  2045. const auto override = this->getContext ().getApp ().getContext ().resolveObjectVisibility (data.id, data.name);
  2046. const bool visible = override.has_value () ? override.value () : data.visible->value->getBool ();
  2047. if (!visible || this->isHiddenByAncestor (*object)) {
  2048. continue;
  2049. }
  2050. entries.push_back (
  2051. { static_cast<int> (data.type),
  2052. (data.castShadow->value->getBool () ? 1 : 0) | (data.useCookie->value->getBool () ? 2 : 0),
  2053. glm::dot (data.origin->value->getVec3 (), forward), &data }
  2054. );
  2055. }
  2056. std::ranges::stable_sort (entries, [] (const Entry& a, const Entry& b) {
  2057. if (a.type != b.type) {
  2058. return a.type < b.type;
  2059. }
  2060. if (a.flags != b.flags) {
  2061. return a.flags > b.flags;
  2062. }
  2063. return a.depth < b.depth;
  2064. });
  2065. std::vector<const Light*> lights;
  2066. lights.reserve (entries.size ());
  2067. for (const auto& entry : entries) {
  2068. lights.push_back (entry.light);
  2069. }
  2070. return lights;
  2071. }
  2072. std::shared_ptr<const TextureProvider> CScene::getMissingTexture () const {
  2073. if (this->m_missingTexture == nullptr) {
  2074. this->m_missingTexture = std::make_shared<MissingTexture> ();
  2075. }
  2076. return this->m_missingTexture;
  2077. }
  2078. GLuint CScene::getNullTexture () const {
  2079. if (this->m_nullTexture == GL_NONE) {
  2080. constexpr uint8_t transparent[4] = { 0, 0, 0, 0 };
  2081. glGenTextures (1, &this->m_nullTexture);
  2082. glBindTexture (GL_TEXTURE_2D, this->m_nullTexture);
  2083. glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, transparent);
  2084. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  2085. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  2086. }
  2087. return this->m_nullTexture;
  2088. }
  2089. bool CScene::hasNamedLayerBuffer (int id) const {
  2090. if (const auto* created = this->getObject (id); created != nullptr && created->is<Objects::CImage> ()) {
  2091. return !created->as<Objects::CImage> ()->usesPooledBuffer ();
  2092. }
  2093. const auto& objects = this->getScene ().objects;
  2094. const auto model = std::ranges::find_if (objects, [id] (const auto& object) { return object->id == id; });
  2095. if (model == objects.end ()) {
  2096. return false;
  2097. }
  2098. const bool dependency = std::ranges::any_of (objects, [id] (const auto& object) {
  2099. return std::ranges::find (object->dependencies, id) != object->dependencies.end ();
  2100. });
  2101. const auto blended = [] (const auto& colorBlendMode) {
  2102. const int mode = colorBlendMode->value->getInt ();
  2103. return mode != 0 && mode != 31;
  2104. };
  2105. if (dependency || this->hasDistanceFog () || this->hasHeightFog ()) {
  2106. return (*model)->template is<Image> () || (*model)->template is<Text> ();
  2107. }
  2108. if ((*model)->template is<Image> ()) {
  2109. const auto* image = (*model)->template as<Image> ();
  2110. return blended (image->colorBlendMode) || image->renderable.ledSource->value->getBool ()
  2111. || (image->model->puppet.has_value () && !image->effects.empty ());
  2112. }
  2113. if ((*model)->template is<Text> ()) {
  2114. const auto* text = (*model)->template as<Text> ();
  2115. return blended (text->colorBlendMode) || text->renderable.ledSource->value->getBool ();
  2116. }
  2117. return false;
  2118. }
  2119. std::shared_ptr<const TextureProvider> CScene::getLightCookie () const {
  2120. // one cookie for every lit material: the last cookie spot the packing takes (sub_140190C80), its "cookie" or
  2121. // cookie/flashlight1 (sub_14025D080); passes are built before the objects exist, so this goes by the scene data in
  2122. // the packing's order
  2123. const auto& camera = this->getCamera ();
  2124. const glm::vec3 forward = camera.isOrthogonal ()
  2125. ? glm::vec3 (0.0f, 0.0f, -1.0f)
  2126. : -glm::vec3 (camera.getView ()[0][2], camera.getView ()[1][2], camera.getView ()[2][2]);
  2127. std::vector<const Light*> spots;
  2128. for (const auto& object : this->getScene ().objects) {
  2129. if (!object->is<Light> ()) {
  2130. continue;
  2131. }
  2132. const auto* light = object->as<Light> ();
  2133. const auto override
  2134. = this->getContext ().getApp ().getContext ().resolveObjectVisibility (light->id, light->name);
  2135. if (light->type == LightType::Spot
  2136. && (override.has_value () ? override.value () : light->visible->value->getBool ())) {
  2137. spots.push_back (light);
  2138. }
  2139. }
  2140. std::ranges::stable_sort (spots, [&forward] (const Light* a, const Light* b) {
  2141. const int flagsA = (a->castShadow->value->getBool () ? 1 : 0) | (a->useCookie->value->getBool () ? 2 : 0);
  2142. const int flagsB = (b->castShadow->value->getBool () ? 1 : 0) | (b->useCookie->value->getBool () ? 2 : 0);
  2143. if (flagsA != flagsB) {
  2144. return flagsA > flagsB;
  2145. }
  2146. return glm::dot (a->origin->value->getVec3 (), forward) < glm::dot (b->origin->value->getVec3 (), forward);
  2147. });
  2148. const Light* last = nullptr;
  2149. for (int i = 0; i < static_cast<int> (spots.size ()) && i < this->m_lightingV1.spots; i++) {
  2150. if (spots[i]->useCookie->value->getBool ()) {
  2151. last = spots[i];
  2152. }
  2153. }
  2154. // without a cookie spot nothing samples it
  2155. return this->getContext ().resolveTexture (
  2156. last == nullptr || last->cookie.empty () ? "cookie/flashlight1" : last->cookie, this->getScene ().project
  2157. );
  2158. }
  2159. namespace {
  2160. // point light cube faces as assets/shaders/common_pbr_2.h picks them (CalculateProjectedCoordsPoint), the same
  2161. // matrices sub_140190C80 renders the six viewports with: +x, -x, +y, -y, +z, -z
  2162. glm::mat4 pointFaceView (const int face, const glm::vec3& o) {
  2163. switch (face) {
  2164. case 0:
  2165. return { { 0, 0, -1, 0 }, { 0, 1, 0, 0 }, { 1, 0, 0, 0 }, { -o.z, -o.y, o.x, 1 } };
  2166. case 1:
  2167. return { { 0, 0, 1, 0 }, { 0, 1, 0, 0 }, { -1, 0, 0, 0 }, { o.z, -o.y, -o.x, 1 } };
  2168. case 2:
  2169. return { { 1, 0, 0, 0 }, { 0, 0, -1, 0 }, { 0, 1, 0, 0 }, { -o.x, -o.z, o.y, 1 } };
  2170. case 3:
  2171. return { { 1, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, -1, 0, 0 }, { -o.x, o.z, -o.y, 1 } };
  2172. case 4:
  2173. return { { -1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, -1, 0 }, { o.x, -o.y, o.z, 1 } };
  2174. default:
  2175. return { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { -o.x, -o.y, -o.z, 1 } };
  2176. }
  2177. }
  2178. // WE's device projections have 1 at the near plane (sub_14009A360); Volumetrics::spotViewProjection keeps the usual
  2179. // 0 there, this turns one into the other (depth' = 1 - depth)
  2180. glm::mat4 reverseDepth (const glm::mat4& projection) {
  2181. glm::mat4 reverse (1.0f);
  2182. reverse[2][2] = -1.0f;
  2183. reverse[3][2] = 1.0f;
  2184. return reverse * projection;
  2185. }
  2186. }
  2187. void CScene::updateLightingV1 () {
  2188. auto& lighting = this->m_lightingV1;
  2189. const LightingV1 counts = lighting;
  2190. lighting = LightingV1 {};
  2191. lighting.points = counts.points;
  2192. lighting.spots = counts.spots;
  2193. lighting.tubes = counts.tubes;
  2194. lighting.directionals = counts.directionals;
  2195. lighting.spotCookies = counts.spotCookies;
  2196. lighting.spotShadowCookies = counts.spotShadowCookies;
  2197. lighting.spotShadows = counts.spotShadows;
  2198. lighting.directionalShadows = counts.directionalShadows;
  2199. lighting.pointShadows = counts.pointShadows;
  2200. this->m_shadowEntries.clear ();
  2201. this->m_volumeShadows.clear ();
  2202. if (lighting.points + lighting.spots + lighting.tubes + lighting.directionals == 0) {
  2203. return;
  2204. }
  2205. const auto& camera = this->getCamera ();
  2206. const bool orthographic = camera.isOrthogonal ();
  2207. const std::vector<const Light*> lights = this->sortedLightingV1Lights ();
  2208. const bool shadows = this->m_shadowQuality > 0;
  2209. const int tile = ShadowMapping::tileSize (this->m_shadowQuality);
  2210. // renderer +104 (eye) and +352 (camera forward) as sub_14017FA70 leaves them
  2211. const glm::vec3 eye = this->m_fog.eyeWorld;
  2212. const glm::vec3 forward = orthographic
  2213. ? glm::vec3 (0.0f, 0.0f, -1.0f)
  2214. : -glm::vec3 (camera.getView ()[0][2], camera.getView ()[1][2], camera.getView ()[2][2]);
  2215. const int ssc = lighting.spotShadowCookies;
  2216. const int sc = lighting.spotCookies;
  2217. const int ss = lighting.spotShadows;
  2218. // next slot per light class (sub_140190C80): shadowed points first, spots shadow+cookie / cookie / shadow / plain
  2219. // by castshadow | usecookie << 1, shadowed directionals first; ShadowProjection follows the spot classes, cascades
  2220. // after them, a directional light takes one feature for its three cascades
  2221. int pointsLeft = lighting.points;
  2222. int pointSlot[2] = { lighting.pointShadows, 0 };
  2223. int pointShadowsLeft = lighting.pointShadows;
  2224. int pointShadow = 0;
  2225. int spotsLeft = lighting.spots;
  2226. int spotSlot[4] = { ssc + sc + ss, ssc + sc, ssc, 0 };
  2227. int featureSlot[4] = { ssc + sc + ss, ssc + sc, ssc, 0 };
  2228. int featuresLeft = lighting.features ();
  2229. int tube = 0;
  2230. int directionalsLeft = lighting.directionals;
  2231. int directionalSlot[2] = { lighting.directionalShadows, 0 };
  2232. const int featureCapacity = static_cast<int> (std::size (lighting.featureProjection));
  2233. for (const Light* entry : lights) {
  2234. const Light& light = *entry;
  2235. const glm::mat4 world = this->objectWorldMatrix (light);
  2236. const glm::vec3 color = light.color->value->getVec3 () * light.intensity->value->getFloat ();
  2237. const float radius = light.radius->value->getFloat ();
  2238. const float exponent = light.exponent->value->getFloat ();
  2239. const glm::vec3 origin (world[3]);
  2240. const bool shadowed = shadows && light.castShadow->value->getBool ();
  2241. switch (light.type) {
  2242. case LightType::Point:
  2243. {
  2244. if (pointsLeft == 0) {
  2245. break;
  2246. }
  2247. pointsLeft--;
  2248. if (const int slot = pointSlot[shadowed ? 1 : 0]++; slot < lighting.points) {
  2249. lighting.pointColor[slot] = glm::vec4 (color, radius);
  2250. lighting.pointOrigin[slot] = glm::vec4 (origin, exponent);
  2251. }
  2252. if (!shadowed || pointShadowsLeft == 0) {
  2253. break;
  2254. }
  2255. // sub_14025D420: a fov a bit over 90 degrees per quality, aspect 1, near the light source size (1
  2256. // in orthographic scenes), far the radius
  2257. pointShadowsLeft--;
  2258. const int quality = this->m_shadowQuality;
  2259. const float fov = quality <= 2 ? 94.0f : quality == 3 ? 92.0f : 91.2f;
  2260. const float near
  2261. = orthographic ? 1.0f : std::max (0.05f, light.lightSourceSize->value->getFloat ());
  2262. const float far = std::max (radius, near + 0.01f);
  2263. const glm::mat4 projection = ShadowMapping::perspective (fov * 0.017453292f, 1.0f, near, far);
  2264. ShadowMapping::Entry shadow { .point = true, .size = tile };
  2265. lighting.pointShadowProjection[pointShadow]
  2266. = glm::vec4 (projection[2][2], projection[3][2], projection[2][3], projection[3][3]);
  2267. shadow.transform = &lighting.pointShadowProjectionTransform[pointShadow];
  2268. pointShadow++;
  2269. for (int face = 0; face < 6; face++) {
  2270. shadow.viewProjection[face] = projection * pointFaceView (face, origin);
  2271. }
  2272. this->m_volumeShadows[&light]
  2273. = { .atlasTransform = shadow.transform,
  2274. .pointProjection = lighting.pointShadowProjection[pointShadow - 1] };
  2275. this->m_shadowEntries.push_back (shadow);
  2276. break;
  2277. }
  2278. case LightType::Spot:
  2279. {
  2280. if (spotsLeft == 0) {
  2281. break;
  2282. }
  2283. spotsLeft--;
  2284. const int type
  2285. = (light.castShadow->value->getBool () ? 1 : 0) | (light.useCookie->value->getBool () ? 2 : 0);
  2286. const int kind = type & (shadows ? 3 : 2);
  2287. // cosines of the cone angles in the .w, the direction is the world matrix's x column as it is
  2288. if (const int slot = spotSlot[kind]++; slot < lighting.spots) {
  2289. lighting.spotColor[slot] = glm::vec4 (color, radius);
  2290. lighting.spotOrigin[slot]
  2291. = glm::vec4 (origin, std::cos (light.innerCone->value->getFloat () * 0.017453292f));
  2292. lighting.spotDirection[slot] = glm::vec4 (
  2293. glm::vec3 (world[0]), std::cos (light.outerCone->value->getFloat () * 0.017453292f)
  2294. );
  2295. lighting.spotExponent[slot] = glm::vec4 (exponent, 0.0f, 0.0f, 0.0f);
  2296. }
  2297. if ((!shadowed && !light.useCookie->value->getBool ()) || featuresLeft == 0) {
  2298. break;
  2299. }
  2300. featuresLeft--;
  2301. const int feature = featureSlot[kind]++;
  2302. if (feature >= featureCapacity) {
  2303. break;
  2304. }
  2305. lighting.featureProjection[feature]
  2306. = reverseDepth (Volumetrics::spotViewProjection (light, world, orthographic));
  2307. if (shadowed) {
  2308. ShadowMapping::Entry shadow { .size = tile,
  2309. .transform = &lighting.featureProjectionTransform[feature] };
  2310. shadow.viewProjection[0] = lighting.featureProjection[feature];
  2311. this->m_volumeShadows[&light]
  2312. = { .matrix = lighting.featureProjection[feature], .atlasTransform = shadow.transform };
  2313. this->m_shadowEntries.push_back (shadow);
  2314. }
  2315. break;
  2316. }
  2317. case LightType::Tube:
  2318. if (tube < lighting.tubes) {
  2319. lighting.tubeColor[tube] = glm::vec4 (color, radius);
  2320. lighting.tubeOriginA[tube] = glm::vec4 (origin, exponent);
  2321. lighting.tubeOriginB[tube]
  2322. = glm::vec4 (glm::vec3 (world * glm::vec4 (light.controlPoint->value->getVec3 (), 1.0f)), 0.0f);
  2323. tube++;
  2324. }
  2325. break;
  2326. case LightType::Directional:
  2327. {
  2328. if (directionalsLeft == 0) {
  2329. break;
  2330. }
  2331. directionalsLeft--;
  2332. if (const int slot = directionalSlot[shadowed ? 1 : 0]++; slot < lighting.directionals) {
  2333. lighting.directionalColor[slot] = glm::vec4 (color, 1.0f);
  2334. lighting.directionalDirection[slot] = glm::vec4 (-glm::vec3 (world[0]), 0.0f);
  2335. }
  2336. if (!shadowed || featuresLeft == 0) {
  2337. break;
  2338. }
  2339. featuresLeft--;
  2340. // sub_14025D370 / sub_140190C80: each cascade is a square of its distance, centered half of it
  2341. // ahead of the eye (forward along the light half counted, z 0 in 2D), snapped to texels on the
  2342. // light's y/z; view down the light's x axis like a spot, ortho box (sub_14009A630) of +-distance/2
  2343. // and depth +-range/2
  2344. const float cascade0 = light.cascadeDistance[0]->value->getFloat ();
  2345. const float cascade1 = light.cascadeDistance[1]->value->getFloat ();
  2346. const float cascade2 = light.cascadeDistance[2]->value->getFloat ();
  2347. const glm::vec2 ranges[3] = {
  2348. { cascade0, cascade1 * 4.0f },
  2349. { cascade1, cascade1 * 4.0f },
  2350. { cascade2, std::max (cascade2 * 1.5f, cascade1 * 4.0f) },
  2351. };
  2352. const glm::vec3 direction = glm::normalize (glm::vec3 (world[0]));
  2353. const glm::vec3 y (world[1]);
  2354. const glm::vec3 z (world[2]);
  2355. const glm::vec3 rows[3]
  2356. = { Volumetrics::approximateNormalize (z), Volumetrics::approximateNormalize (y),
  2357. Volumetrics::approximateNormalize (-glm::vec3 (world[0])) };
  2358. const glm::vec3 ahead = forward - direction * (glm::dot (forward, direction) * 0.5f);
  2359. for (const glm::vec2& range : ranges) {
  2360. const float half = range.x * 0.5f;
  2361. glm::vec3 center = eye + ahead * half;
  2362. if (orthographic) {
  2363. center.z = 0.0f;
  2364. }
  2365. const float texel = range.x / static_cast<float> (tile);
  2366. const float alongZ = glm::dot (z, center);
  2367. const float alongY = glm::dot (y, center);
  2368. center -= y * std::fmod (alongY, texel);
  2369. center -= z * std::fmod (alongZ, texel);
  2370. glm::mat4 view (1.0f);
  2371. for (int row = 0; row < 3; row++) {
  2372. for (int column = 0; column < 3; column++) {
  2373. view[column][row] = rows[row][column];
  2374. }
  2375. view[3][row] = -glm::dot (rows[row], center);
  2376. }
  2377. glm::mat4 projection (1.0f);
  2378. projection[0][0] = 1.0f / half;
  2379. projection[1][1] = 1.0f / half;
  2380. projection[2][2] = 1.0f / range.y;
  2381. projection[3][2] = 0.5f;
  2382. const int feature = featureSlot[0]++;
  2383. if (feature >= featureCapacity) {
  2384. continue;
  2385. }
  2386. lighting.featureProjection[feature] = projection * view;
  2387. ShadowMapping::Entry shadow { .size = tile,
  2388. .transform = &lighting.featureProjectionTransform[feature] };
  2389. shadow.viewProjection[0] = lighting.featureProjection[feature];
  2390. this->m_shadowEntries.push_back (shadow);
  2391. }
  2392. break;
  2393. }
  2394. default:
  2395. break;
  2396. }
  2397. }
  2398. }
  2399. const CScene::LayerTarget* CScene::getLayerTarget () const {
  2400. return this->m_layerTargets.empty () ? nullptr : &this->m_layerTargets.back ();
  2401. }
  2402. bool CScene::isDrawnByPassthroughLayer (const CObject& object) const {
  2403. const Object* current = &object.getObject ();
  2404. // set when the parent has flag 2 or 4 (sub_1401DD9A0), so any passthrough ancestor
  2405. for (int depth = 0; current->parent.has_value () && depth < 64; depth++) {
  2406. const auto* parent = this->getObject (current->parent.value ());
  2407. if (parent == nullptr) {
  2408. return false;
  2409. }
  2410. // one set up without children leaves later ones to the scene
  2411. if (isPassthroughImage (*parent)) {
  2412. return parent->as<Objects::CImage> ()->drawsPassthroughChildren ();
  2413. }
  2414. current = &parent->getObject ();
  2415. }
  2416. return false;
  2417. }
  2418. std::vector<CObject*> CScene::childrenOf (int id) const {
  2419. std::vector<CObject*> children;
  2420. const auto list = this->m_children.find (id);
  2421. if (list != this->m_children.end ()) {
  2422. for (const int child : list->second) {
  2423. if (const auto it = this->m_objects.find (child);
  2424. it != this->m_objects.end () && it->second->getObject ().parent == id) {
  2425. children.push_back (it->second);
  2426. }
  2427. }
  2428. }
  2429. // unlisted objects after the listed ones
  2430. for (auto* object : this->m_objectsByRenderOrder) {
  2431. if (object->getObject ().parent == id && std::ranges::find (children, object) == children.end ()) {
  2432. children.push_back (object);
  2433. }
  2434. }
  2435. return children;
  2436. }
  2437. void CScene::detachChild (const CObject& child) {
  2438. if (const auto& parent = child.getObject ().parent; parent.has_value ()) {
  2439. if (const auto list = this->m_children.find (*parent); list != this->m_children.end ()) {
  2440. std::erase (list->second, child.getId ());
  2441. }
  2442. }
  2443. }
  2444. void CScene::attachChild (const CObject& child) {
  2445. const auto& parent = child.getObject ().parent;
  2446. if (!parent.has_value ()) {
  2447. return;
  2448. }
  2449. // sub_1401DDA60 / sub_140196C40: after the parent's existing children in scene order, at the end when the child
  2450. // comes first or a root object is met
  2451. auto& list = this->m_children[*parent];
  2452. std::erase (list, child.getId ());
  2453. const auto layers = this->getLayers ();
  2454. const auto from
  2455. = std::ranges::find_if (layers, [&parent] (const CObject* cur) { return cur->getId () == *parent; });
  2456. size_t position = list.size ();
  2457. if (from != layers.end ()) {
  2458. size_t count = 0;
  2459. for (auto it = std::next (from); it != layers.end (); ++it) {
  2460. if (*it == &child) {
  2461. position = std::min (count, list.size ());
  2462. break;
  2463. }
  2464. const auto& itsParent = (*it)->getObject ().parent;
  2465. if (itsParent == parent) {
  2466. count++;
  2467. } else if (!itsParent.has_value ()) {
  2468. break;
  2469. }
  2470. }
  2471. }
  2472. list.insert (list.begin () + static_cast<std::ptrdiff_t> (position), child.getId ());
  2473. }
  2474. void CScene::renderPassthroughChildren (int layerId, const LayerTarget& target) {
  2475. this->m_layerTargets.push_back (target);
  2476. // direct children only when visible (slot 13), their subtrees unless they are passthrough layers themselves,
  2477. // which draw their own (sub_1401ECB20)
  2478. for (auto* child : this->childrenOf (layerId)) {
  2479. this->renderPassthroughChild (child);
  2480. if (!isPassthroughImage (*child)) {
  2481. this->renderPassthroughSubtree (child->getId (), 1);
  2482. }
  2483. }
  2484. this->m_layerTargets.pop_back ();
  2485. }
  2486. void CScene::renderPassthroughSubtree (int parentId, int depth) {
  2487. if (depth >= 64) {
  2488. return;
  2489. }
  2490. for (auto* child : this->childrenOf (parentId)) {
  2491. this->renderPassthroughChild (child);
  2492. if (!isPassthroughImage (*child)) {
  2493. this->renderPassthroughSubtree (child->getId (), depth + 1);
  2494. }
  2495. }
  2496. }
  2497. void CScene::renderPassthroughChild (CObject* object) {
  2498. const auto& debug = this->getContext ().getApp ().getContext ().settings.render.debug;
  2499. if (debug.objectFilter.has_value () && object->getId () != debug.objectFilter.value ()) {
  2500. return;
  2501. }
  2502. if (std::ranges::find (debug.skipObjects, object->getId ()) != debug.skipObjects.end ()) {
  2503. return;
  2504. }
  2505. const auto visibility = this->getContext ().getApp ().getContext ().resolveObjectVisibility (
  2506. object->getId (), object->getObject ().name
  2507. );
  2508. if ((visibility.has_value () && !visibility.value ()) || this->isHiddenByAncestor (*object)) {
  2509. return;
  2510. }
  2511. // lights go into the shared light buffer (sub_140196CE0 from sub_1401ECB20), added onto the scene before the next
  2512. // non-light top level object; a light before any other child still sees the scene's view projection (live WE)
  2513. if (object->is<Objects::CLight> ()) {
  2514. const auto& target = this->m_layerTargets.back ();
  2515. this->renderLightVolume (
  2516. *object->as<Objects::CLight> (),
  2517. target.viewProjectionApplied ? target.viewProjection : this->getWorldViewProjection ()
  2518. );
  2519. return;
  2520. }
  2521. timeStep ("render " + object->getObject ().name, [&] { object->render (); });
  2522. // nested layers push and pop their own targets while rendering, look it up again
  2523. this->m_layerTargets.back ().viewProjectionApplied = true;
  2524. }
  2525. void CScene::renderLightVolume (const Objects::CLight& object, const glm::mat4& viewProjection) {
  2526. const auto& light = object.getLight ();
  2527. // WE sends every light through the same code, but only point and spot lights get a volume matrix
  2528. // (sub_14025D420). Tubes and directional lights would draw the cone through a matrix nothing sets, left out
  2529. if ((light.type != LightType::Point && light.type != LightType::Spot) || !light.castVolumetrics->value->getBool ()
  2530. || !light.visible->value->getBool ()) {
  2531. return;
  2532. }
  2533. timeStep ("volumetrics " + light.name, [&] {
  2534. const auto shadow = this->m_volumeShadows.find (&light);
  2535. this->m_volumetrics->renderLight (
  2536. light, this->objectWorldMatrix (light), viewProjection,
  2537. shadow != this->m_volumeShadows.end () ? &shadow->second : nullptr
  2538. );
  2539. });
  2540. }
  2541. bool CScene::isTransparentSorted (const CObject& object) {
  2542. const auto cached = this->m_transparentSorted.find (&object);
  2543. if (cached != this->m_transparentSorted.end ()) {
  2544. return cached->second;
  2545. }
  2546. bool sorted = false;
  2547. // particles, lights and text always, images by their material's blending or as passthrough layers without
  2548. if (object.is<Objects::CParticle> () || object.is<Objects::CLight> () || object.is<Objects::CText> ()) {
  2549. sorted = true;
  2550. } else if (object.is<Objects::CImage> ()) {
  2551. const auto& image = object.as<Objects::CImage> ()->getImage ();
  2552. const auto& passes = image.model->material->passes;
  2553. const BlendingMode blending = passes.empty () ? BlendingMode_Normal : passes.front ()->blending;
  2554. sorted = blending == BlendingMode_Translucent || blending == BlendingMode_Additive
  2555. || (image.model->passthrough && !image.copyBackground->value->getBool ());
  2556. }
  2557. this->m_transparentSorted.emplace (&object, sorted);
  2558. return sorted;
  2559. }
  2560. std::vector<CObject*> CScene::sortedByDepth (std::vector<CObject*> objects) const {
  2561. // key = origin . view direction, the renderer keeps -row 2 of the view matrix for it (sub_14017FA70); fullscreen
  2562. // and project layers (object flag 0x200) get -inf. Stable, largest key first
  2563. const glm::mat4& view = this->getCamera ().getView ();
  2564. const glm::vec3 forward = -glm::vec3 (view[0][2], view[1][2], view[2][2]);
  2565. std::vector<std::pair<float, CObject*>> keyed;
  2566. keyed.reserve (objects.size ());
  2567. for (auto* object : objects) {
  2568. float key = glm::dot (object->getObject ().origin->value->getVec3 (), forward);
  2569. if (object->is<Objects::CImage> ()) {
  2570. const auto& model = *object->as<Objects::CImage> ()->getImage ().model;
  2571. if (model.fullscreen || model.projectlayer) {
  2572. key = -std::numeric_limits<float>::infinity ();
  2573. }
  2574. }
  2575. keyed.emplace_back (key, object);
  2576. }
  2577. std::ranges::stable_sort (keyed, [] (const auto& a, const auto& b) { return a.first > b.first; });
  2578. for (size_t i = 0; i < keyed.size (); i++) {
  2579. objects[i] = keyed[i].second;
  2580. }
  2581. return objects;
  2582. }
  2583. bool CScene::quadContainsPoint (const glm::mat4& mvp, const glm::vec2& half, const glm::vec2& ndc) {
  2584. const glm::vec2 corners[] = { { -half.x, -half.y }, { half.x, -half.y }, { half.x, half.y }, { -half.x, half.y } };
  2585. glm::vec2 projected[4];
  2586. for (int i = 0; i < 4; i++) {
  2587. const glm::vec4 clip = mvp * glm::vec4 (corners[i], 0.0f, 1.0f);
  2588. if (clip.w <= 0.0f) {
  2589. return false;
  2590. }
  2591. projected[i] = glm::vec2 (clip) / clip.w;
  2592. }
  2593. bool positive = false;
  2594. bool negative = false;
  2595. for (int i = 0; i < 4; i++) {
  2596. const glm::vec2 edge = projected[(i + 1) % 4] - projected[i];
  2597. const glm::vec2 toPoint = ndc - projected[i];
  2598. const float cross = edge.x * toPoint.y - edge.y * toPoint.x;
  2599. positive |= cross > 0.0f;
  2600. negative |= cross < 0.0f;
  2601. }
  2602. // a quad seen edge on has no area and nothing to hit
  2603. const glm::vec2 diagonalA = projected[2] - projected[0];
  2604. const glm::vec2 diagonalB = projected[3] - projected[1];
  2605. return !(positive && negative) && (diagonalA.x * diagonalB.y - diagonalA.y * diagonalB.x) != 0.0f;
  2606. }
  2607. std::optional<glm::vec2> CScene::quadPlanePoint (const glm::mat4& mvp, const glm::vec2& ndc) {
  2608. // clip = x * col0 + y * col1 + col3, and the point lands on ndc when clip.xy = ndc * clip.w
  2609. const glm::vec4& ax = mvp[0];
  2610. const glm::vec4& ay = mvp[1];
  2611. const glm::vec4& at = mvp[3];
  2612. const float a = ax.x - ndc.x * ax.w;
  2613. const float b = ay.x - ndc.x * ay.w;
  2614. const float c = ax.y - ndc.y * ax.w;
  2615. const float d = ay.y - ndc.y * ay.w;
  2616. const float det = a * d - b * c;
  2617. if (std::abs (det) <= 1.1920929e-7f) {
  2618. return std::nullopt;
  2619. }
  2620. const float ex = ndc.x * at.w - at.x;
  2621. const float ey = ndc.y * at.w - at.y;
  2622. const glm::vec2 point = { (ex * d - b * ey) / det, (a * ey - ex * c) / det };
  2623. if (point.x * ax.w + point.y * ay.w + at.w <= 0.0f) {
  2624. return std::nullopt;
  2625. }
  2626. return point;
  2627. }
  2628. bool CScene::isHiddenByAncestor (const CObject& object) const {
  2629. const auto& appContext = this->getContext ().getApp ().getContext ();
  2630. const Object* current = &object.getObject ();
  2631. // objects nest through "parent"; a child is only shown while every group above it is, whatever
  2632. // its own visible property says (the guard keeps a malformed parent loop from spinning)
  2633. for (int depth = 0; current->parent.has_value () && depth < 64; depth++) {
  2634. const auto* parent = this->getObject (current->parent.value ());
  2635. if (parent == nullptr) {
  2636. return false;
  2637. }
  2638. const Object& data = parent->getObject ();
  2639. const auto override = appContext.resolveObjectVisibility (parent->getId (), data.name);
  2640. bool visible;
  2641. if (override.has_value ()) {
  2642. visible = override.value ();
  2643. } else if (data.is<Image> ()) {
  2644. visible = data.as<Image> ()->visible->value->getBool ();
  2645. } else if (data.is<Text> ()) {
  2646. visible = data.as<Text> ()->visible->value->getBool ();
  2647. } else if (data.is<Particle> ()) {
  2648. visible = data.as<Particle> ()->visible->value->getBool ();
  2649. } else {
  2650. visible = data.groupVisible->value->getBool ();
  2651. }
  2652. if (!visible) {
  2653. return true;
  2654. }
  2655. current = &data;
  2656. }
  2657. return false;
  2658. }
  2659. const CObject* CScene::getObject (int id) const {
  2660. const auto object = this->m_objects.find (id);
  2661. return object == this->m_objects.end () ? nullptr : object->second;
  2662. }
  2663. CObject* CScene::getObject (int id) {
  2664. const auto object = this->m_objects.find (id);
  2665. return object == this->m_objects.end () ? nullptr : object->second;
  2666. }
  2667. void CScene::setSoundPlaying (int id, bool playing) {
  2668. this->m_soundPlayRequests[id] = playing;
  2669. const auto object = this->m_objects.find (id);
  2670. if (object == this->m_objects.end () || !object->second->is<Objects::CSound> ()) {
  2671. return;
  2672. }
  2673. auto* sound = object->second->as<Objects::CSound> ();
  2674. if (playing) {
  2675. sound->play ();
  2676. } else {
  2677. sound->stop ();
  2678. }
  2679. }
  2680. void CScene::pauseSound (int id) {
  2681. if (auto* sound = this->getObject (id); sound != nullptr && sound->is<Objects::CSound> ()) {
  2682. sound->as<Objects::CSound> ()->pause ();
  2683. }
  2684. }
  2685. bool CScene::isSoundPlaying (int id, bool startSilent) const {
  2686. if (const auto* sound = this->getObject (id); sound != nullptr && sound->is<Objects::CSound> ()) {
  2687. return sound->as<Objects::CSound> ()->isPlaying ();
  2688. }
  2689. return this->getSoundPlayRequest (id).value_or (!startSilent);
  2690. }
  2691. std::optional<bool> CScene::getSoundPlayRequest (int id) const {
  2692. const auto request = this->m_soundPlayRequests.find (id);
  2693. return request == this->m_soundPlayRequests.end () ? std::nullopt : std::optional<bool> (request->second);
  2694. }
  2695. std::optional<float> CScene::spriteSheetSyncDelay () const {
  2696. if (!this->getScene ().spriteSheetRefreshSync) {
  2697. return std::nullopt;
  2698. }
  2699. // only the first image object, animated or not
  2700. for (const auto* object : this->getLayers ()) {
  2701. if (!object->is<Objects::CImage> ()) {
  2702. continue;
  2703. }
  2704. const auto* image = object->as<Objects::CImage> ();
  2705. const auto texture = image->getTexture ();
  2706. if (texture == nullptr || !texture->isAnimated () || texture->getFrames ().empty ()) {
  2707. return 0.0f;
  2708. }
  2709. const auto [frame, elapsed] = image->sharedTextureFrame ();
  2710. return std::max (static_cast<float> (texture->getFrames ()[frame]->frametime) - elapsed, 0.0f);
  2711. }
  2712. return 0.0f;
  2713. }
  2714. std::vector<CObject*> CScene::getLayers () const { return this->m_objectsByRenderOrder; }
  2715. int CScene::getObjectIndex (const CObject* object) const {
  2716. const auto layers = this->getLayers ();
  2717. const auto it = std::ranges::find (layers, object);
  2718. if (it == layers.end ()) {
  2719. return -1;
  2720. }
  2721. return static_cast<int> (std::distance (layers.begin (), it));
  2722. }
  2723. void CScene::appendLayer (CObject* object) { this->m_objectsByRenderOrder.push_back (object); }
  2724. Render::CObject* CScene::buildLayer (JSON layerJson) {
  2725. const int id = this->m_nextDynamicLayerId++;
  2726. layerJson["id"] = id;
  2727. if (!layerJson.contains ("name") || !layerJson["name"].is_string ()) {
  2728. layerJson["name"] = "scriptlayer_" + std::to_string (id);
  2729. }
  2730. if (!layerJson.contains ("visible")) {
  2731. layerJson["visible"] = true;
  2732. }
  2733. auto objectData = ObjectParser::parse (layerJson, this->getScene ().project);
  2734. Render::CObject* renderObject = this->createObject (*objectData);
  2735. if (renderObject == nullptr) {
  2736. return nullptr;
  2737. }
  2738. this->m_dynamicObjectData.emplace (id, std::move (objectData));
  2739. this->appendLayer (renderObject);
  2740. return renderObject;
  2741. }
  2742. // scripts write into createLayer()'s result without a null check, so failures get a scriptable, non-rendering
  2743. // placeholder
  2744. Render::CObject* CScene::createPlaceholderLayer () {
  2745. try {
  2746. const int id = this->m_nextDynamicLayerId++;
  2747. const JSON placeholderJson
  2748. = { { "id", id }, { "name", "scriptlayer_" + std::to_string (id) }, { "visible", true } };
  2749. auto objectData = ObjectParser::parse (placeholderJson, this->getScene ().project);
  2750. auto* renderObject = new Scripting::ScriptableObject (*this, *objectData);
  2751. this->m_objects.emplace (renderObject->getId (), renderObject);
  2752. this->m_dynamicObjectData.emplace (id, std::move (objectData));
  2753. this->appendLayer (renderObject);
  2754. return renderObject;
  2755. } catch (const std::exception& placeholderError) {
  2756. sLog.error ("createLayer placeholder fallback also failed: ", placeholderError.what ());
  2757. return nullptr;
  2758. }
  2759. }
  2760. Render::CObject* CScene::createLayer (const std::string& imagePath) {
  2761. // createObject() throws on a missing asset, and unwinding a C++ exception through the V8 callback is undefined
  2762. // behavior
  2763. try {
  2764. if (const auto cached = this->m_createLayerAliases.find (imagePath);
  2765. cached != this->m_createLayerAliases.end ()) {
  2766. return this->buildLayer ({ { "image", cached->second } });
  2767. }
  2768. return this->buildLayer ({ { "image", imagePath } });
  2769. } catch (const std::exception& e) {
  2770. // scripts written against a workshop dependency's original layout use the un-prefixed name, try the prefixed
  2771. // copy first
  2772. if (const auto alias = this->getScene ().project.assetLocator->resolveWorkshopDependencyAlias (imagePath);
  2773. alias.has_value () && !this->m_createLayerAliases.contains (imagePath)) {
  2774. try {
  2775. sLog.out (
  2776. "createLayer: '", imagePath, "' not found, found and using workshop-dependency copy '",
  2777. alias->string (), "' instead"
  2778. );
  2779. auto* layer = this->buildLayer ({ { "image", alias->string () } });
  2780. this->m_createLayerAliases.emplace (imagePath, alias->string ());
  2781. return layer;
  2782. } catch (const std::exception& aliasError) {
  2783. sLog.error (
  2784. "createLayer: workshop-dependency copy '", alias->string (), "' also failed: ", aliasError.what ()
  2785. );
  2786. }
  2787. } else {
  2788. sLog.error (
  2789. "createLayer failed for '", imagePath, "', falling back to an invisible placeholder: ", e.what ()
  2790. );
  2791. }
  2792. return this->createPlaceholderLayer ();
  2793. }
  2794. }
  2795. Render::CObject* CScene::createLayerFromConfig (JSON config) {
  2796. // WE (scenescript64 sub_180011340): a config with "color" and no layer type key becomes a solid layer
  2797. static constexpr std::array layerTypes
  2798. = { "model", "particle", "sprite", "image", "text", "light", "sound", "camera" };
  2799. if (config.contains ("color")
  2800. && std::ranges::none_of (layerTypes, [&config] (const char* key) { return config.contains (key); })) {
  2801. // ortho scenes get the depth tested material (sub_181633290)
  2802. config["image"] = this->getCamera ().isOrthogonal () ? "models/util/solidlayer_depthtest.json"
  2803. : "models/util/solidlayer.json";
  2804. }
  2805. try {
  2806. return this->buildLayer (config);
  2807. } catch (const std::exception& e) {
  2808. sLog.error (
  2809. "createLayer failed for ", config.dump (), ", falling back to an invisible placeholder: ", e.what ()
  2810. );
  2811. return this->createPlaceholderLayer ();
  2812. }
  2813. }
  2814. void CScene::sortLayer (CObject* object, int index) {
  2815. const auto current = std::ranges::find (this->m_objectsByRenderOrder, object);
  2816. if (current == this->m_objectsByRenderOrder.end ()) {
  2817. return;
  2818. }
  2819. this->m_objectsByRenderOrder.erase (current);
  2820. // index counts script-visible layers, so place it before whichever layer currently holds that slot
  2821. const auto layers = this->getLayers ();
  2822. const int clampedIndex = std::clamp (index, 0, static_cast<int> (layers.size ()));
  2823. const auto before = clampedIndex < static_cast<int> (layers.size ())
  2824. ? std::ranges::find (this->m_objectsByRenderOrder, layers[clampedIndex])
  2825. : this->m_objectsByRenderOrder.end ();
  2826. this->m_objectsByRenderOrder.insert (before, object);
  2827. }
  2828. void CScene::loadStaticCamera () {
  2829. if (this->m_staticCameraLoaded) {
  2830. return;
  2831. }
  2832. this->m_staticCameraLoaded = true;
  2833. // 2D scenes without camera paths get the reset camera, the others scene.json's (sub_140186C90); zoom stays
  2834. if (!this->m_camera->isPerspective () && this->getScene ().camera.paths.empty ()) {
  2835. this->m_staticCamera.eye = glm::vec3 (0.0f);
  2836. this->m_staticCamera.center = glm::vec3 (0.0f, 0.0f, -1.0f);
  2837. this->m_staticCamera.up = glm::vec3 (0.0f, 1.0f, 0.0f);
  2838. } else {
  2839. this->m_staticCamera.eye = this->m_camera->getConfiguredEye ();
  2840. this->m_staticCamera.center = this->m_camera->getCenter ();
  2841. this->m_staticCamera.up = this->m_camera->getUp ();
  2842. }
  2843. }
  2844. uint32_t CScene::createModelData (const ModelData::Config& config, ModelData::Error& error) {
  2845. return this->m_modelData.create (
  2846. config,
  2847. [this] (const std::string& material, uint32_t format) {
  2848. return this->checkModelDataMaterial (material, format);
  2849. },
  2850. error
  2851. );
  2852. }
  2853. void CScene::applyModelData (uint32_t token, const ModelData::Config& config, bool replace, ModelData::Error& error) {
  2854. this->m_modelData.apply (
  2855. token, config, replace,
  2856. [this] (const std::string& material, uint32_t format) {
  2857. return this->checkModelDataMaterial (material, format);
  2858. },
  2859. error
  2860. );
  2861. }
  2862. void CScene::destroyModelData (uint32_t token) { this->m_modelData.release (token); }
  2863. std::shared_ptr<ModelData::Model> CScene::acquireModelData (int token) { return this->m_modelData.acquire (token); }
  2864. std::shared_ptr<const std::vector<char>> CScene::readModelFile (const std::string& filename) {
  2865. if (const auto it = this->m_modelFiles.find (filename); it != this->m_modelFiles.end ()) {
  2866. return it->second;
  2867. }
  2868. const auto stream = this->getScene ().project.assetLocator->read (filename);
  2869. auto data = std::make_shared<std::vector<char>> ();
  2870. char buffer[65536];
  2871. while (stream->read (buffer, sizeof (buffer)) || stream->gcount () > 0) {
  2872. data->insert (data->end (), buffer, buffer + stream->gcount ());
  2873. }
  2874. if (this->m_loading) {
  2875. this->m_modelFiles.emplace (filename, data);
  2876. }
  2877. return data;
  2878. }
  2879. void CScene::releaseModelData (uint32_t token) { this->m_modelData.release (token); }
  2880. ModelData::Error CScene::checkModelDataMaterial (const std::string& material, uint32_t format) {
  2881. const auto key = std::make_pair (material, format);
  2882. if (const auto cached = this->m_modelDataMaterialChecks.find (key);
  2883. cached != this->m_modelDataMaterialChecks.end ()) {
  2884. return cached->second;
  2885. }
  2886. // semantic of every vertex format bit and of every attribute name WE's shader translation knows (0x140482AF0,
  2887. // 0x140484A90), sub_1400D7B60 only compares semantic names
  2888. static const std::pair<uint32_t, const char*> formatSemantics[] = {
  2889. { 0x1, "POSITION" }, { 0x10000, "POSITION" }, { 0x2000000, "POSITION" }, { 0x2, "NORMAL" },
  2890. { 0x4, "TANGENT" }, { 0x800000, "BLENDINDICES" }, { 0x1000000, "BLENDWEIGHT" }, { 0x8, "TEXCOORD" },
  2891. { 0x10, "TEXCOORD" }, { 0x20, "TEXCOORD" }, { 0x40, "TEXCOORD" }, { 0x80, "TEXCOORD" },
  2892. { 0x100, "TEXCOORD" }, { 0x200, "TEXCOORD" }, { 0x400, "TEXCOORD" }, { 0x800, "TEXCOORD" },
  2893. { 0x1000, "TEXCOORD" }, { 0x2000, "TEXCOORD" }, { 0x4000, "TEXCOORD" }, { 0x20000, "TEXCOORD" },
  2894. { 0x40000, "TEXCOORD" }, { 0x80000, "TEXCOORD" }, { 0x100000, "TEXCOORD" }, { 0x200000, "TEXCOORD" },
  2895. { 0x400000, "TEXCOORD" }, { 0x8000, "COLOR" },
  2896. };
  2897. static const std::map<std::string, std::string> attributeSemantics = {
  2898. { "a_Position", "POSITION" }, { "a_PositionVec4", "POSITION" },
  2899. { "a_PositionC1", "POSITION" }, { "a_Normal", "NORMAL" },
  2900. { "a_Tangent4", "TANGENT" }, { "a_BlendIndices", "BLENDINDICES" },
  2901. { "a_BlendWeights", "BLENDWEIGHT" }, { "a_TexCoord", "TEXCOORD" },
  2902. { "a_TexCoordVec3", "TEXCOORD" }, { "a_TexCoordVec4", "TEXCOORD" },
  2903. { "a_TexCoordC1", "TEXCOORD" }, { "a_TexCoordVec3C1", "TEXCOORD" },
  2904. { "a_TexCoordVec4C1", "TEXCOORD" }, { "a_TexCoordC2", "TEXCOORD" },
  2905. { "a_TexCoordVec3C2", "TEXCOORD" }, { "a_TexCoordVec4C2", "TEXCOORD" },
  2906. { "a_TexCoordC3", "TEXCOORD" }, { "a_TexCoordVec3C3", "TEXCOORD" },
  2907. { "a_TexCoordVec4C3", "TEXCOORD" }, { "a_TexCoordC4", "TEXCOORD" },
  2908. { "a_TexCoordVec3C4", "TEXCOORD" }, { "a_TexCoordVec4C4", "TEXCOORD" },
  2909. { "a_TexCoordC5", "TEXCOORD" }, { "a_TexCoordVec3C5", "TEXCOORD" },
  2910. { "a_TexCoordVec4C5", "TEXCOORD" }, { "a_Color", "COLOR" },
  2911. };
  2912. static const std::regex input (R"(\bin\s+\w+\s+(a_\w+)\s*;)");
  2913. ModelData::Error result = ModelData::Error::None;
  2914. const auto& project = this->getScene ().project;
  2915. const auto loaded = Data::Parsers::MaterialParser::load (project, material);
  2916. if (loaded == nullptr || loaded->passes.empty ()) {
  2917. result = ModelData::Error::InvalidMaterial;
  2918. } else {
  2919. // the program WE compiles for the material by itself (sub_1401A5C40): the pass's combos plus the scene wide
  2920. // defines every pass gets
  2921. const auto& pass = *loaded->passes.front ();
  2922. ComboMap combos = pass.combos;
  2923. const ComboMap overrideCombos;
  2924. const TextureMap overrideTextures;
  2925. static const ShaderConstantMap noConstants;
  2926. if (this->getCamera ().isOrthogonal ()) {
  2927. combos.insert_or_assign ("SCENE_ORTHO", 1);
  2928. }
  2929. if (this->isHDR ()) {
  2930. combos.insert_or_assign ("HDR", 1);
  2931. }
  2932. try {
  2933. Shaders::Shader shader (
  2934. *project.assetLocator, pass.shader, combos, overrideCombos, pass.textures, overrideTextures, noConstants
  2935. );
  2936. const auto sources
  2937. = Shaders::GLSLContext::get ().toGlsl (shader.vertex (), shader.fragment (), pass.shader);
  2938. std::set<std::string> provided;
  2939. for (const auto& [bit, semantic] : formatSemantics) {
  2940. if (format & bit) {
  2941. provided.insert (semantic);
  2942. }
  2943. }
  2944. // the translation keeps the original source in an "#if 0" block at the end, that doesn't count
  2945. const std::string code = sources.vertex.substr (0, sources.vertex.rfind ("\n#if 0"));
  2946. for (std::sregex_iterator it (code.begin (), code.end (), input), end; it != end; ++it) {
  2947. const std::string name = (*it)[1].str ();
  2948. const auto semantic = attributeSemantics.find (name);
  2949. const std::regex use ("\\b" + name + "\\b");
  2950. const auto uses
  2951. = std::distance (std::sregex_iterator (code.begin (), code.end (), use), std::sregex_iterator ());
  2952. // the D3D input signature only has the inputs the shader reads: live WE takes a position-only shape
  2953. // with util/flat.json, whose flat.vert declares a_Color but only reads it with VERTEXCOLOR
  2954. if (uses < 2) {
  2955. continue;
  2956. }
  2957. if (semantic != attributeSemantics.end () && !provided.contains (semantic->second)) {
  2958. result = ModelData::Error::ShaderExpectingMoreVertexData;
  2959. break;
  2960. }
  2961. }
  2962. } catch (const std::exception& e) {
  2963. sLog.error ("Model data material ", material, " has no usable shader: ", e.what ());
  2964. result = ModelData::Error::InvalidMaterial;
  2965. }
  2966. }
  2967. this->m_modelDataMaterialChecks.emplace (key, result);
  2968. return result;
  2969. }
  2970. bool CScene::wantsPointerButtons () const {
  2971. return this->m_scriptEngine != nullptr && this->m_scriptEngine->wantsPointerButtons ();
  2972. }
  2973. void CScene::setAudioPolicy (bool muted, std::optional<int> ambientVolume) {
  2974. const std::optional<int> volume = muted ? std::optional<int> (0) : ambientVolume;
  2975. for (const auto& entry : this->m_objects) {
  2976. if (entry.second->is<Objects::CSound> ()) {
  2977. entry.second->as<Objects::CSound> ()->setVolumeOverride (volume);
  2978. }
  2979. }
  2980. }