| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683 |
- #include "WallpaperEngine/Data/Model/Property.h"
- #include "WallpaperEngine/Debugging/Profiling.h"
- #include "WallpaperEngine/Render/DepthRange.h"
- #include "WallpaperEngine/Render/MissingTexture.h"
- #include "WallpaperEngine/Render/Objects/CCamera.h"
- #include "WallpaperEngine/Render/Objects/CImage.h"
- #include "WallpaperEngine/Render/Objects/CLight.h"
- #include "WallpaperEngine/Render/Objects/CMesh.h"
- #include "WallpaperEngine/Render/Objects/CParticle.h"
- #include "WallpaperEngine/Render/Objects/CSound.h"
- #include "WallpaperEngine/Render/Objects/CText.h"
- #include "WallpaperEngine/Render/Objects/PuppetIK.h"
- #include "WallpaperEngine/Render/WallpaperState.h"
- #include "CScene.h"
- #include "MouseMapping.h"
- #include "WallpaperEngine/Led/LedHub.h"
- #include "WallpaperEngine/Logging/Log.h"
- #include "WallpaperEngine/Render/LedFrameGrabber.h"
- #include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
- #include "WallpaperEngine/Scripting/ScriptableObject.h"
- #include "WallpaperEngine/VideoPlayback/MPV/GLPlayer.h"
- #include "WallpaperEngine/Data/Model/Wallpaper.h"
- #include "WallpaperEngine/Data/Parsers/MaterialParser.h"
- #include "WallpaperEngine/Data/Parsers/ObjectParser.h"
- #include "WallpaperEngine/Render/Shaders/GLSLContext.h"
- #include "WallpaperEngine/Render/Shaders/Shader.h"
- #include "WallpaperEngine/Data/Utils/FloatCompare.h"
- #include <algorithm>
- #include <bit>
- #include <chrono>
- #include <cmath>
- #include <cstdlib>
- #include <glm/gtc/type_ptr.hpp>
- #include <limits>
- #include <ranges>
- #include <regex>
- #include <unordered_map>
- extern float g_Time;
- extern float g_TimeLast;
- using namespace WallpaperEngine;
- using namespace WallpaperEngine::Render;
- using namespace WallpaperEngine::Data::Model;
- using namespace WallpaperEngine::Data::Parsers;
- using namespace WallpaperEngine::Render::Wallpapers;
- namespace {
- // general properties go through sub_1401A4DB0 like object ones with the scene as owner, so they run scripts too
- class SceneSettingsScripts final : public Scripting::ScriptableObject {
- public:
- SceneSettingsScripts (CScene& owner, const Object& object, const Scene& scene) :
- CObject (owner, object), ScriptableObject (owner, object) {
- const std::pair<const char*, const UserSettingUniquePtr&> settings[] = {
- { "ambientcolor", scene.colors.ambient },
- { "skylightcolor", scene.colors.skylight },
- { "clearcolor", scene.colors.clear },
- { "fogdistance", scene.fog.distanceEnabled },
- { "fogdistancecolor", scene.fog.distanceColor },
- { "fogdistancestart", scene.fog.distanceStart },
- { "fogdistanceend", scene.fog.distanceEnd },
- { "fogdistancestartdensity", scene.fog.distanceStartDensity },
- { "fogdistanceenddensity", scene.fog.distanceEndDensity },
- { "fogheight", scene.fog.heightEnabled },
- { "fogheightcolor", scene.fog.heightColor },
- { "fogheightstart", scene.fog.heightStart },
- { "fogheightend", scene.fog.heightEnd },
- { "fogheightstartdensity", scene.fog.heightStartDensity },
- { "fogheightenddensity", scene.fog.heightEndDensity },
- { "camerafade", scene.camera.fade },
- { "bloom", scene.camera.bloom.enabled },
- { "bloomstrength", scene.camera.bloom.strength },
- { "bloomthreshold", scene.camera.bloom.threshold },
- { "hdr", scene.camera.bloom.hdr },
- { "bloomhdrstrength", scene.camera.bloom.hdrStrength },
- { "bloomhdrthreshold", scene.camera.bloom.hdrThreshold },
- { "bloomhdrfeather", scene.camera.bloom.hdrFeather },
- { "bloomhdrscatter", scene.camera.bloom.hdrScatter },
- { "bloomhdriterations", scene.camera.bloom.hdrIterations },
- { "bloomtint", scene.camera.bloom.tint },
- { "cameraparallax", scene.camera.parallax.enabled },
- { "cameraparallaxamount", scene.camera.parallax.amount },
- { "cameraparallaxdelay", scene.camera.parallax.delay },
- { "cameraparallaxmouseinfluence", scene.camera.parallax.mouseInfluence },
- { "camerashake", scene.camera.shake.enabled },
- { "camerashakeamplitude", scene.camera.shake.amplitude },
- { "camerashakeroughness", scene.camera.shake.roughness },
- { "camerashakespeed", scene.camera.shake.speed },
- { "nearz", scene.camera.projection.nearz },
- { "farz", scene.camera.projection.farz },
- { "fov", scene.camera.projection.fov },
- { "perspectiveoverridefov", scene.camera.projection.perspectiveOverrideFov },
- { "zoom", scene.camera.projection.zoom },
- { "transparentsorting", scene.transparentSorting },
- { "gravitydirection", scene.physics.gravityDirection },
- { "gravitystrength", scene.physics.gravityStrength },
- { "windenabled", scene.physics.windEnabled },
- { "winddirection", scene.physics.windDirection },
- { "windstrength", scene.physics.windStrength },
- };
- for (const auto& [name, setting] : settings) {
- this->registerProperty (name, *setting->value);
- }
- }
- };
- }
- CScene::CScene (
- const Wallpaper& wallpaper, RenderContext& context, AudioContext& audioContext,
- const WallpaperState::TextureUVsScaling& scalingMode, const uint32_t& clampMode
- ) : CWallpaper (wallpaper, context, audioContext, scalingMode, clampMode) {
- LWE_ZONE ("scene construct");
- // the caller checks this, std::bad_cast otherwise
- auto scene = wallpaper.as<Scene> ();
- this->m_startTime = g_Time;
- this->m_scriptEngine = std::make_unique<Scripting::ScriptEngine> (*this, context.getMediaSource ());
- this->m_camera = std::make_unique<Camera> (*this, scene->camera);
- // shaders get FOG_DIST/FOG_HEIGHT from the renderer flags set when the scene loads (sub_140186440, sub_1401A5C40)
- this->m_fogDistance = scene->fog.distanceEnabled->value->getBool ();
- this->m_fogHeight = scene->fog.heightEnabled->value->getBool ();
- float width = scene->camera.projection.width;
- float height = scene->camera.projection.height;
- // "auto" always matches the output resolution, same as real Wallpaper Engine
- if (scene->camera.projection.isAuto) {
- width = this->getContext ().getOutput ().getFullWidth ();
- height = this->getContext ().getOutput ().getFullHeight ();
- }
- this->m_cameraParallax = { 0, 0 };
- this->m_parallaxBias = { 0, 0 };
- this->m_parallaxPosition = { 0.5f, 0.5f };
- const bool perspective = scene->camera.projection.isPerspective;
- if (perspective) {
- // 3D scenes render at the output's size, the perspective camera stretches to whatever aspect that has
- this->m_camera->setPerspectiveProjection (width, height);
- } else {
- float canvasWidth = width;
- float canvasHeight = height;
- if (this->getContext ().getApp ().getContext ().settings.general.expandCanvas) {
- this->expandCanvasToContent (*scene, width, height, canvasWidth, canvasHeight);
- }
- this->m_camera->setOrthogonalProjection (width, height, canvasWidth, canvasHeight);
- }
- // HDR rendering needs WE's "ultra" post processing plus bloom and hdr in the scene (sub_14010DF40), then the
- // scene and layer buffers are 16 bit float and bloom is the HDR mip chain (sub_140183610)
- this->m_hdr = this->getContext ().getApp ().getContext ().settings.general.ultraPostProcessing
- && scene->camera.bloom.enabled->value->getBool () && scene->camera.bloom.hdr->value->getBool ();
- // postprocessing "displayhdr" sets 0x6000 instead of 0x2000 (sub_14010DF40): the same HDR scene with the
- // combine_dhdr_upsample combine
- this->m_displayHDR = this->m_hdr && this->getContext ().getApp ().getContext ().settings.general.displayHDR;
- // HDR combine writes WE's FP16 swapchain format (sub_14012AC60)
- this->setScRGBInput (this->m_hdr);
- this->m_volumetrics = std::make_unique<Volumetrics> (*this);
- // lightconfig as the scene constructor packs it (sub_140186C90): with WE's shadow setting off spotshadowcookie
- // folds into spotcookie and the other shadow counts are dropped. Passes read these when they're built
- const auto& lightConfig = this->getScene ().lightConfig;
- this->m_shadowQuality = this->getContext ().getApp ().getContext ().settings.general.shadowQuality;
- this->m_lightingV1.points = lightConfig.point;
- this->m_lightingV1.spots = lightConfig.spot;
- this->m_lightingV1.tubes = lightConfig.tube;
- this->m_lightingV1.directionals = lightConfig.directional;
- if (this->m_shadowQuality > 0) {
- this->m_lightingV1.spotCookies = lightConfig.spotCookie;
- this->m_lightingV1.spotShadowCookies = lightConfig.spotShadowCookie;
- this->m_lightingV1.spotShadows = lightConfig.spotShadow;
- this->m_lightingV1.directionalShadows = lightConfig.directionalShadow;
- this->m_lightingV1.pointShadows = lightConfig.pointShadow;
- } else {
- this->m_lightingV1.spotCookies = lightConfig.spotCookie | lightConfig.spotShadowCookie;
- }
- const bool hasModels
- = std::ranges::any_of (scene->objects, [] (const auto& object) { return object->template is<Mesh> (); });
- this->setupFramebuffers (
- perspective || hasModels, this->m_hdr ? TextureFormat_RGBA16161616f : TextureFormat_ARGB8888
- );
- this->followOutputSize (this->find ("_rt_FullFrameBuffer"), 1);
- // wallpaper64.exe 2.8.42 sub_14010DF40 flags a scene when an object has a "model", only then the device gets the
- // msaa setting's sample count (sub_140110630, sub_14012AC60) and sub_140181AF0 makes the multisampled target
- if (hasModels) {
- this->m_msaaSamples = this->getContext ().getApp ().getContext ().settings.general.msaaSamples;
- }
- const uint32_t sceneWidth = this->m_camera->getCanvasWidth ();
- const uint32_t sceneHeight = this->m_camera->getCanvasHeight ();
- // WE creates it on the first frame with shadows at the size the tiles need (sub_140190C80), it only grows
- this->_rt_shadowAtlas
- = this->create ("_rt_shadowAtlas", TextureFormat_D32f, TextureFlags_ClampUVsBorder, 1.0, { 2, 2 }, { 2, 2 });
- this->alias ("_alias_lightCookie", "_rt_shadowAtlas");
- this->m_shadowMapping = std::make_unique<ShadowMapping> (*this, this->_rt_shadowAtlas);
- const glm::vec3 clearColor = scene->colors.clear->value->getVec3 ();
- glClearColor (clearColor.r, clearColor.g, clearColor.b, 1.0f);
- // general section loads before the objects, its scripts update first
- this->m_settingsScriptsData = ObjectParser::parse ({ { "id", -1 }, { "name", "" } }, scene->project);
- this->m_settingsScripts = std::make_unique<SceneSettingsScripts> (*this, *this->m_settingsScriptsData, *scene);
- // a constructor that throws never runs the destructor: the objects made so far (a sound's reader thread among
- // them) would leak and keep running
- struct ObjectsGuard {
- CScene& scene;
- bool armed = true;
- ~ObjectsGuard () {
- if (armed) {
- scene.destroyObjects ();
- }
- }
- } objectsGuard { *this };
- // a chain of parents that comes back to its start never reaches a root, and every walk along it (a layer's buffer
- // name, its world matrix) would go on forever: break it before any object is made
- std::unordered_map<int, const Object*> objectsById;
- for (const auto& object : scene->objects) {
- objectsById.emplace (object->id, object.get ());
- }
- for (const auto& object : scene->objects) {
- int steps = 0;
- for (auto current = object->parent; current.has_value () && steps < 4096; steps++) {
- if (*current == object->id) {
- sLog.error ("Parent loop through object ", object->id, " (", object->name, "), dropping its parent");
- object->parent.reset ();
- object->attachment.reset ();
- break;
- }
- const auto next = objectsById.find (*current);
- if (next == objectsById.end ()) {
- break;
- }
- current = next->second->parent;
- }
- }
- {
- LWE_ZONE ("create objects");
- for (const auto& object : scene->objects) {
- this->createObject (*object);
- }
- }
- for (const auto& object : scene->objects) {
- if (object->parent.has_value ()) {
- this->m_children[*object->parent].push_back (object->id);
- }
- }
- // real Wallpaper Engine draws its object list in scene.json array order unless the scene sets
- // customsortorder (then by each object's sortorder); parent/attachment links don't reorder anything
- std::vector<std::pair<const Object*, int>> objectsByPaintOrder;
- objectsByPaintOrder.reserve (scene->objects.size ());
- for (int index = 0; index < static_cast<int> (scene->objects.size ()); index++) {
- const Object* object = scene->objects[index].get ();
- objectsByPaintOrder.emplace_back (object, object->sortOrder.value_or (index));
- }
- std::ranges::stable_sort (objectsByPaintOrder, [] (const auto& a, const auto& b) { return a.second < b.second; });
- for (const auto& [object, sortKey] : objectsByPaintOrder) {
- this->addObjectToRenderOrder (*object);
- }
- // LDR bloom buffers, output sized (sub_14017F1B0); HDR scenes use the mip chain instead
- if (!this->m_hdr) {
- for (const auto& [name, divisor] : { std::pair<const char*, uint32_t> { "_rt_4FrameBuffer", 4 },
- { "_rt_8FrameBuffer", 8 },
- { "_rt_Bloom", 8 } }) {
- const glm::vec2 size (sceneWidth / divisor, sceneHeight / divisor);
- this->followOutputSize (
- this->create (name, TextureFormat_ARGB8888, TextureFlags_ClampUVs, 1.0, size, size),
- static_cast<float> (divisor)
- );
- }
- }
- this->m_loading = false;
- this->m_modelFiles.clear ();
- objectsGuard.armed = false;
- }
- CScene::~CScene () {
- Led::releaseFeed (this);
- Objects::Effects::CPass::dropRecentShaders ();
- if (this->m_nullTexture != GL_NONE) {
- glDeleteTextures (1, &this->m_nullTexture);
- }
- this->destroyObjects ();
- this->releaseMultisample ();
- }
- void CScene::destroyObjects () {
- for (const auto& val : this->m_objects | std::views::values) {
- delete val;
- }
- for (const auto* object : this->m_destroyedObjects) {
- delete object;
- }
- this->m_destroyedObjects.clear ();
- for (const auto& layer : this->m_releasableLayers) {
- delete layer.object;
- }
- this->m_releasableLayers.clear ();
- this->m_objectsByRenderOrder.clear ();
- this->m_objects.clear ();
- }
- Render::CObject* CScene::createObject (const Object& object) {
- Render::CObject* renderObject = nullptr;
- if (const auto current = this->m_objects.find (object.id); current != this->m_objects.end ()) {
- return current->second;
- }
- // dependency/parent loops spanning several objects exist in the wild, the object further
- // up the stack finishes creating itself once this call unwinds
- if (!this->m_objectsInCreation.insert (object.id).second) {
- sLog.error ("Dependency or parent cycle through object ", object.id, ", ignoring the back reference");
- return nullptr;
- }
- bool dependenciesReady = false;
- try {
- dependenciesReady = this->createObjectDependencies (object);
- } catch (...) {
- this->m_objectsInCreation.erase (object.id);
- throw;
- }
- this->m_objectsInCreation.erase (object.id);
- if (!dependenciesReady) {
- return nullptr;
- }
- {
- LWE_ZONE_TEXT ("create object", object.name);
- renderObject = this->dispatchObjectType (object);
- }
- if (renderObject != nullptr) {
- this->m_objects.emplace (renderObject->getId (), renderObject);
- }
- return renderObject;
- }
- bool CScene::createObjectDependencies (const Object& object) {
- for (const auto& cur : object.dependencies) {
- if (cur == object.id) {
- continue;
- }
- const auto dep
- = std::ranges::find_if (this->getScene ().objects, [&cur] (const auto& o) { return o->id == cur; });
- if (dep != this->getScene ().objects.end ()) {
- this->createObject (**dep);
- }
- }
- if (object.parent.has_value ()) {
- int parentId = object.parent.value ();
- const auto dep = std::ranges::find_if (this->getScene ().objects, [&parentId] (const auto& o) {
- return o->id == parentId;
- });
- if (dep == this->getScene ().objects.end ()) {
- // one object without its parent has nowhere to go, the rest of the scene still loads
- sLog.error (
- "Cannot find parent ", parentId, " for object ", object.id, " (", object.name, "), skipping it"
- );
- return false;
- }
- this->createObject (**dep);
- }
- return true;
- }
- Render::CObject* CScene::dispatchObjectType (const Object& object) {
- Render::CObject* renderObject = nullptr;
- const auto scriptMark = this->getScriptEngine ().moduleMark ();
- try {
- LWE_ZONE ("construct");
- renderObject = this->constructObject (object);
- } catch (const std::exception& e) {
- // the half built object is gone, the scripts its constructor queued still point at it
- sLog.error ("Failed to create object ", object.id, " (", object.name, "): ", e.what ());
- this->getScriptEngine ().dropModulesSince (scriptMark);
- return nullptr;
- }
- if (renderObject == nullptr) {
- return nullptr;
- }
- try {
- LWE_ZONE ("setup");
- renderObject->setup ();
- } catch (const std::exception& e) {
- sLog.error ("Failed to setup object ", object.id, ": ", e.what ());
- if (auto* scriptable = dynamic_cast<Scripting::ScriptableObject*> (renderObject); scriptable != nullptr) {
- this->getScriptEngine ().dropObjectScripts (*scriptable);
- }
- std::erase (this->m_sceneCameras, renderObject);
- delete renderObject;
- renderObject = nullptr;
- }
- return renderObject;
- }
- Render::CObject* CScene::constructObject (const Object& object) {
- Render::CObject* renderObject = nullptr;
- if (object.is<Image> ()) {
- renderObject = new Objects::CImage (*this, *object.as<Image> ());
- } else if (object.is<Sound> ()) {
- renderObject = new Objects::CSound (*this, *object.as<Sound> ());
- } else if (object.is<Text> ()) {
- renderObject = new Objects::CText (*this, *object.as<Text> ());
- } else if (object.is<Light> ()) {
- renderObject = new Objects::CLight (*this, *object.as<Light> (), this->nextFreeLightSlot ());
- } else if (object.is<SceneCamera> ()) {
- auto* camera = new Objects::CCamera (*this, *object.as<SceneCamera> ());
- this->m_sceneCameras.push_back (camera);
- renderObject = camera;
- } else if (object.is<Mesh> ()) {
- renderObject = new Objects::CMesh (*this, *object.as<Mesh> ());
- } else if (object.is<Particle> ()) {
- const auto& particleData = *object.as<Particle> ();
- if (this->getContext ().getApp ().getContext ().settings.general.disableParticles == true) {
- sLog.debug ("Ignoring particle system (disabled in settings): ", particleData.name);
- return nullptr;
- }
- if (!particleData.material || !particleData.material->material) {
- sLog.error ("Ignoring particle system with no usable material: ", particleData.name);
- return nullptr;
- }
- renderObject = new Objects::CParticle (*this, particleData);
- } else {
- // group/locator nodes can still carry scripts, and the shared-state bootstrap script often lives on one
- sLog.debug ("Creating group object without renderable: ", object.id);
- renderObject = new Scripting::ScriptableObject (*this, object);
- }
- return renderObject;
- }
- void CScene::addObjectToRenderOrder (const Object& object) {
- const auto obj = this->m_objects.find (object.id);
- if (obj == this->m_objects.end ()) {
- return;
- }
- if (!this->m_objectsInRenderOrderWalk.insert (object.id).second) {
- return;
- }
- for (const auto& dep : object.dependencies) {
- if (dep == object.id) {
- continue;
- }
- auto depIt = std::ranges::find_if (this->getScene ().objects, [&dep] (const auto& o) { return o->id == dep; });
- if (depIt != this->getScene ().objects.end ()) {
- this->addObjectToRenderOrder (**depIt);
- if (const auto created = this->m_objects.find (dep);
- created != this->m_objects.end () && created->second->is<Objects::CImage> ()) {
- created->second->as<Objects::CImage> ()->markAsDependency ();
- }
- } else {
- sLog.error ("Cannot find dependency ", dep, " for object ", object.id);
- }
- }
- const auto renderIt = std::ranges::find_if (this->m_objectsByRenderOrder, [&object] (const auto& o) {
- return o->getId () == object.id;
- });
- if (renderIt == this->m_objectsByRenderOrder.end ()) {
- this->m_objectsByRenderOrder.emplace_back (obj->second);
- }
- this->m_objectsInRenderOrderWalk.erase (object.id);
- }
- ScriptEngine& CScene::getScriptEngine () const { return *this->m_scriptEngine; }
- Camera& CScene::getCamera () const { return *this->m_camera; }
- namespace {
- // with LWE_FRAME_STATS set, any single step of a scene frame slower than this is logged by name, LWE_FRAME_STALL_MS
- // changes it (0 logs every step)
- double stallThresholdMs () {
- const char* value = std::getenv ("LWE_FRAME_STALL_MS");
- char* end = nullptr;
- const double ms = value ? std::strtod (value, &end) : 0.0;
- return end != value && ms >= 0.0 ? ms : 15.0;
- }
- template <typename Step> void timeStep (const std::string& label, Step&& step) {
- LWE_ZONE_NAMED (label);
- static const bool enabled = std::getenv ("LWE_FRAME_STATS") != nullptr;
- static const double threshold = stallThresholdMs ();
- if (!enabled) {
- step ();
- return;
- }
- GLuint queries[2];
- glGenQueries (2, queries);
- glFinish ();
- const auto start = std::chrono::steady_clock::now ();
- glQueryCounter (queries[0], GL_TIMESTAMP);
- step ();
- glQueryCounter (queries[1], GL_TIMESTAMP);
- glFinish ();
- const double ms = std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now () - start).count ();
- GLuint64 gpuStart = 0, gpuEnd = 0;
- glGetQueryObjectui64v (queries[0], GL_QUERY_RESULT, &gpuStart);
- glGetQueryObjectui64v (queries[1], GL_QUERY_RESULT, &gpuEnd);
- glDeleteQueries (2, queries);
- if (ms >= threshold) {
- sLog.out ("FRAME-STALL ", label, ": ", ms, "ms (gpu ", (gpuEnd - gpuStart) / 1e6, "ms)");
- }
- }
- }
- void CScene::renderFrame (const glm::ivec4& viewport) {
- // WE draws its scenes with a reversed float depth buffer, so does this where the driver can map clip z to 0..1
- const DepthRange::Scope depthRange;
- timeStep ("renderFrame total", [&] { this->renderFrameSteps (viewport); });
- }
- void CScene::renderFrameSteps (const glm::ivec4& viewport) {
- // --ssaa only scales the buffers, cursor/visible region/scripts stay in output pixels
- this->m_outputSize = glm::ivec2 (viewport.z, viewport.w) * this->getSupersampling ();
- this->m_texelSize = 1.0f / glm::max (glm::vec2 (this->m_outputSize), glm::vec2 (2.0f));
- this->m_texelSizeHalf = 0.5f * this->m_texelSize;
- this->resizeOutputBuffers (this->m_outputSize);
- // wallpaper64.exe sub_14017FA70 counts every frame (scene render object +340, zeroed by sub_14017C6D0) before
- // anything is simulated, boids pick their sample block with it
- this->m_frameCounter++;
- VideoPlayback::MPV::GLPlayer::advanceFrame ();
- timeStep ("updateMouse", [&] { this->updateMouse (this->cursorViewport ()); });
- // WE: init () while loading, then the static camera (sub_140186C90), then the first update
- this->getScriptEngine ().initializePending ();
- this->loadStaticCamera ();
- // WE updates every object before cursor events and scripts (sub_1401891A0 from sub_14017FA70), so scripts read
- // and change this frame's puppet bones and the render draws what they left
- for (const auto& cur : this->m_objectsByRenderOrder) {
- if (cur->is<Objects::CImage> ()) {
- cur->as<Objects::CImage> ()->updatePuppetPose ();
- cur->as<Objects::CImage> ()->updateTextureAnimation (this->getDeltaTime ());
- } else if (cur->is<Objects::CMesh> ()) {
- cur->as<Objects::CMesh> ()->updateAnimation ();
- } else if (cur->is<Objects::CParticle> ()) {
- cur->as<Objects::CParticle> ()->simulate ();
- } else if (cur->is<Objects::CSound> ()) {
- cur->as<Objects::CSound> ()->update (this->getDeltaTime ());
- }
- }
- // after the tick, so a layer a script moves this frame (e.g. onto input.cursorWorldPosition) is hit tested where it
- // is now
- timeStep ("script tick", [&] { this->getScriptEngine ().tick (); });
- // WE runs the object updates first, then the camera, then the parallax camera
- this->updateCamera ();
- this->updateParallax ();
- timeStep ("cursor events", [&] { this->dispatchCursorEvents (); });
- // sub_14018B390: layers the scripts destroyed go before drawing
- this->destroyPendingLayers ();
- this->updateLights ();
- this->updateLightingV1 ();
- timeStep ("shadows", [&] { this->m_shadowMapping->render (this->m_shadowEntries); });
- for (const auto& cur : this->m_objectsByRenderOrder) {
- if (!cur->is<Objects::CImage> ()) {
- continue;
- }
- const Objects::CImage* image = cur->as<Objects::CImage> ();
- #if !NDEBUG
- const std::string message = "Updating texture " + image->getImage ().model->filename;
- glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, message.c_str ());
- #endif
- timeStep ("updateTextures " + image->getObject ().name, [&] { image->updateTextures (); });
- #if !NDEBUG
- glPopDebugGroup ();
- #endif
- }
- glBindVertexArray (this->m_vaoBuffer);
- this->renderReflection ();
- glBindFramebuffer (GL_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
- glViewport (0, 0, this->m_sceneFBO->getRealWidth (), this->m_sceneFBO->getRealHeight ());
- // sub_140183550: the objects draw into _rt_FullFrameBufferMultiSampled, which resolves into the scene buffer
- // once they are done
- this->m_msaaActive = this->m_msaaSamples > 1 && this->prepareMultisample ();
- if (this->m_msaaActive) {
- glBindFramebuffer (GL_FRAMEBUFFER, this->m_msaaFramebuffer);
- }
- // passes leave their depthwrite and color mask behind and glClear skips masked channels; composites write rgb only,
- // so alpha would never reset and fullscreen layers would vanish
- glDepthMask (GL_TRUE);
- glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
- const glm::vec3 clearColor = this->getScene ().colors.clear->value->getVec3 ();
- glClearColor (clearColor.r, clearColor.g, clearColor.b, 1.0f);
- glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
- this->paintLetterbox ();
- // transparentsorting only does something in 3D scenes (render flags & 0x1008 == 0x1000, sub_14018AAC0): the rest
- // goes first in list order, then the transparent objects back to front
- if (this->getCamera ().isPerspective () && this->getScene ().transparentSorting->value->getBool ()) {
- std::vector<CObject*> transparent;
- for (auto* cur : std::vector (this->m_objectsByRenderOrder)) {
- if (this->isTransparentSorted (*cur)) {
- transparent.push_back (cur);
- } else {
- this->renderSceneObject (cur);
- }
- }
- for (auto* cur : this->sortedByDepth (std::move (transparent))) {
- this->renderSceneObject (cur);
- }
- } else {
- for (const auto& cur : this->m_objectsByRenderOrder) {
- this->renderSceneObject (cur);
- }
- }
- this->m_volumetrics->composite ();
- if (this->m_msaaActive) {
- this->resolveMultisample ();
- this->m_msaaActive = false;
- glBindFramebuffer (GL_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
- }
- this->updateMipMappedFrameBuffer ();
- // after every object (sub_14017FA70)
- timeStep ("post processing", [&] { this->renderPostProcessing (); });
- this->feedLeds ();
- }
- void CScene::feedLeds () {
- auto& output = Led::sharedOutput ();
- if (!output.running () || !Led::claimFeed (this)) {
- return;
- }
- using namespace std::chrono_literals;
- const auto now = std::chrono::steady_clock::now ();
- // wallpaper64.exe asks for a frame every 1/30 s
- if (now < this->m_ledNext) {
- return;
- }
- this->m_ledNext = now + 33ms;
- std::shared_ptr<const CFBO> source = this->m_sceneFBO;
- for (const auto& object : this->getScene ().objects) {
- const bool led = object->is<Image> ()
- ? object->as<Image> ()->renderable.ledSource->value->getBool ()
- : object->is<Text> () && object->as<Text> ()->renderable.ledSource->value->getBool ();
- if (!led) {
- continue;
- }
- if (auto layer = this->find ("_rt_imageLayerComposite_" + std::to_string (object->id) + "_a");
- layer != nullptr) {
- source = std::move (layer);
- break;
- }
- }
- if (this->m_ledGrabber == nullptr) {
- this->m_ledGrabber = std::make_unique<LedFrameGrabber> ();
- }
- if (this->m_ledGrabber->grab (
- source->getTextureID (0), static_cast<int> (source->getRealWidth ()),
- static_cast<int> (source->getRealHeight ()), this->m_ledFrame
- )) {
- output.submit (this->m_ledFrame);
- }
- }
- void CScene::paintLetterbox () const {
- // the bars a fit/center/free alignment leaves are part of WE's scene buffer (sub_140183A70 widens the projection
- // over them) and only get the clear color, whatever is drawn there shows (text screen anchors move into them).
- // --corner-color (with the border clamp) takes the clear color's place there, right after the clear
- if (this->getState ().getClampingMode () != TextureFlags_ClampUVsBorder || this->m_camera->isPerspective ()) {
- return;
- }
- glm::vec4 margins = this->getVisibleMargins ();
- if (margins.x >= 0.0f && margins.y >= 0.0f && margins.z >= 0.0f && margins.w >= 0.0f) {
- return;
- }
- // alignmentfliph mirrors the projection, the left bar ends up on the right
- if (this->isFlippedHorizontally ()) {
- std::swap (margins.x, margins.y);
- }
- const float width = static_cast<float> (this->getCanvasWidth ());
- const float height = static_cast<float> (this->getCanvasHeight ());
- const float visibleWidth = width - margins.x - margins.y;
- const float visibleHeight = height - margins.z - margins.w;
- const auto bufferWidth = static_cast<float> (this->m_sceneFBO->getRealWidth ());
- const auto bufferHeight = static_cast<float> (this->m_sceneFBO->getRealHeight ());
- // scene units to buffer pixels, the buffer's rows run from the bottom of the scene up
- const auto columnOf = [&] (const float x) {
- return static_cast<GLint> (std::lround ((x - margins.x) / visibleWidth * bufferWidth));
- };
- const auto rowOf = [&] (const float y) {
- return static_cast<GLint> (std::lround ((y - margins.z) / visibleHeight * bufferHeight));
- };
- const GLint left = std::clamp (columnOf (0.0f), 0, static_cast<GLint> (bufferWidth));
- const GLint right = std::clamp (columnOf (width), 0, static_cast<GLint> (bufferWidth));
- const GLint bottom = std::clamp (rowOf (0.0f), 0, static_cast<GLint> (bufferHeight));
- const GLint top = std::clamp (rowOf (height), 0, static_cast<GLint> (bufferHeight));
- const glm::vec4& color = this->getCornerColor ();
- glBindFramebuffer (GL_FRAMEBUFFER, this->getSceneDrawFramebuffer ());
- glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
- glClearColor (color.r, color.g, color.b, color.a);
- glEnable (GL_SCISSOR_TEST);
- const auto fill = [] (const GLint x, const GLint y, const GLint w, const GLint h) {
- if (w > 0 && h > 0) {
- glScissor (x, y, w, h);
- glClear (GL_COLOR_BUFFER_BIT);
- }
- };
- fill (0, 0, left, static_cast<GLint> (bufferHeight));
- fill (right, 0, static_cast<GLint> (bufferWidth) - right, static_cast<GLint> (bufferHeight));
- fill (left, 0, right - left, bottom);
- fill (left, top, right - left, static_cast<GLint> (bufferHeight) - top);
- glDisable (GL_SCISSOR_TEST);
- }
- bool CScene::isShadowCasterVisible (const CObject& object) const {
- // the object's visible check (vtable +104) and flag 2 (under a passthrough layer), like renderSceneObject
- const auto visibility = this->getContext ().getApp ().getContext ().resolveObjectVisibility (
- object.getId (), object.getObject ().name
- );
- if (visibility.has_value () && !visibility.value ()) {
- return false;
- }
- if (this->isHiddenByAncestor (object) || this->isDrawnByPassthroughLayer (object)) {
- return false;
- }
- if (!object.is<Objects::CMesh> ()) {
- return true;
- }
- // casters have object flags 0xC00: "castshadow" (0x800) and a normal or alphatocoverage material (0x400)
- const auto& mesh = object.as<Objects::CMesh> ()->getMesh ();
- return mesh.groupVisible->value->getBool () && mesh.castShadow->value->getBool ();
- }
- void CScene::renderSceneObject (CObject* cur) {
- const auto& debug = this->getContext ().getApp ().getContext ().settings.render.debug;
- if (debug.objectFilter.has_value () && cur->getId () != debug.objectFilter.value ()) {
- return;
- }
- if (std::ranges::find (debug.skipObjects, cur->getId ()) != debug.skipObjects.end ()) {
- return;
- }
- const auto visibility
- = this->getContext ().getApp ().getContext ().resolveObjectVisibility (cur->getId (), cur->getObject ().name);
- if (visibility.has_value () && !visibility.value ()) {
- return;
- }
- if (this->isHiddenByAncestor (*cur)) {
- return;
- }
- // a passthrough layer above it draws it into its own buffer (object flag 2, skipped by sub_14018AAC0)
- if (this->isDrawnByPassthroughLayer (*cur)) {
- return;
- }
- // lights draw their volumes into the light buffer, which goes onto the scene before the next other object
- if (cur->is<Objects::CLight> ()) {
- this->renderLightVolume (*cur->as<Objects::CLight> (), this->getWorldViewProjection ());
- return;
- }
- this->m_volumetrics->composite ();
- timeStep ("render " + cur->getObject ().name, [&] { cur->render (); });
- }
- namespace {
- // sub_1400D2C60 with flag 0x10: max (1, min (log2 (np2 (w) / 2), log2 (np2 (h) / 2)) - 2) levels, np2 = the next power
- // of two, 8 for a 1920x1058 buffer
- uint32_t mipMappedLevels (const uint32_t width, const uint32_t height) {
- const auto halfPowerOfTwo
- = [] (const uint32_t value) { return std::bit_width (std::bit_ceil (std::max (value, 2u)) >> 1) - 1; };
- return static_cast<uint32_t> (
- std::max (1, static_cast<int> (std::min (halfPowerOfTwo (width), halfPowerOfTwo (height))) - 2)
- );
- }
- }
- void CScene::followOutputSize (const std::shared_ptr<CFBO>& fbo, const float divisor) {
- if (fbo == nullptr) {
- return;
- }
- const auto& buffer = this->m_outputSizedBuffers.emplace_back (OutputSizedBuffer { .fbo = fbo, .divisor = divisor });
- if (this->m_outputBufferSize.x > 0) {
- const auto size = buffer.sizeFor (this->m_outputBufferSize);
- fbo->resize (size.x, size.y);
- }
- }
- void CScene::followOutputSize (const std::shared_ptr<CFBO>& fbo, const FBO& base) {
- if (fbo == nullptr) {
- return;
- }
- const auto& buffer
- = this->m_outputSizedBuffers.emplace_back (OutputSizedBuffer { .fbo = fbo, .divisor = 1.0f, .base = &base });
- if (this->m_outputBufferSize.x > 0) {
- const auto size = buffer.sizeFor (this->m_outputBufferSize);
- fbo->resize (size.x, size.y);
- }
- }
- glm::uvec2 CScene::OutputSizedBuffer::sizeFor (const glm::ivec2 output) const {
- if (this->base != nullptr) {
- return this->base->bufferSize (output);
- }
- return { std::max (static_cast<uint32_t> (output.x / this->divisor), 1u),
- std::max (static_cast<uint32_t> (output.y / this->divisor), 1u) };
- }
- void CScene::resizeOutputBuffers (const glm::ivec2 size) {
- if (size == this->m_outputBufferSize || size.x <= 0 || size.y <= 0) {
- return;
- }
- const bool resized = this->m_outputBufferSize != glm::ivec2 (0);
- this->m_outputBufferSize = size;
- std::erase_if (this->m_outputSizedBuffers, [] (const auto& buffer) { return buffer.fbo.expired (); });
- for (const auto& buffer : this->m_outputSizedBuffers) {
- const auto bufferSize = buffer.sizeFor (size);
- buffer.fbo.lock ()->resize (bufferSize.x, bufferSize.y);
- }
- if (this->_rt_MipMappedFrameBuffer != nullptr) {
- const auto width = static_cast<uint32_t> (size.x);
- const auto height = static_cast<uint32_t> (size.y);
- this->find ("_rt_MipMappedFrameBuffer")->resize (width, height, mipMappedLevels (width, height));
- }
- if (resized) {
- this->getScriptEngine ().notifyResizeScreen (glm::vec2 (size / this->getSupersampling ()));
- }
- }
- std::shared_ptr<const CFBO> CScene::requireMipMappedFrameBuffer () {
- if (this->_rt_MipMappedFrameBuffer != nullptr) {
- return this->_rt_MipMappedFrameBuffer;
- }
- const uint32_t width = this->m_sceneFBO->getRealWidth ();
- const uint32_t height = this->m_sceneFBO->getRealHeight ();
- this->_rt_MipMappedFrameBuffer = this->create (
- "_rt_MipMappedFrameBuffer", this->m_sceneFBO->getFormat (), TextureFlags_ClampUVs, 1.0, { width, height },
- { width, height }, { 0.0f, 0.0f, 0.0f, 1.0f }, mipMappedLevels (width, height)
- );
- return this->_rt_MipMappedFrameBuffer;
- }
- std::shared_ptr<const CFBO> CScene::requireReflectionFrameBuffer () {
- if (this->_rt_Reflection != nullptr) {
- return this->_rt_Reflection;
- }
- // output size, format 1 (8 bit even in HDR scenes), a depth buffer, no mips (sub_140181AF0)
- const uint32_t width = this->m_sceneFBO->getRealWidth ();
- const uint32_t height = this->m_sceneFBO->getRealHeight ();
- this->_rt_Reflection = this->create (
- "_rt_Reflection", TextureFormat_ARGB8888, TextureFlags_ClampUVs, 1.0, { width, height }, { width, height }
- );
- this->_rt_Reflection->attachDepthBuffer ();
- this->followOutputSize (this->_rt_Reflection, 1);
- return this->_rt_Reflection;
- }
- std::shared_ptr<const CFBO> CScene::requireAlphaMaskFrameBuffer (const bool intermediate) {
- auto& buffer = intermediate ? this->_rt_FullAlphaMaskIntermediate : this->_rt_FullAlphaMask;
- if (buffer != nullptr) {
- return buffer;
- }
- // sub_1401AADB0 with divisor 2, no depth
- const uint32_t width = std::max (this->m_sceneFBO->getRealWidth () / 2, 2u);
- const uint32_t height = std::max (this->m_sceneFBO->getRealHeight () / 2, 2u);
- buffer = this->create (
- intermediate ? "_rt_FullAlphaMaskIntermediate" : "_rt_FullAlphaMask", TextureFormat_R8, TextureFlags_ClampUVs,
- 1.0, { width, height }, { width, height }
- );
- this->followOutputSize (buffer, 2);
- return buffer;
- }
- void CScene::addReflectionReceiver (const int id) { this->m_reflectionReceivers.insert (id); }
- void CScene::renderReflection () {
- // sub_14017FA70: with _rt_Reflection sampled and the reflection setting on, the scene is drawn again first,
- // mirrored on world y = 0 (view * diag (1, -1, 1, 1)); WE's extra projection y flip only offsets Direct3D's row
- // order, here the mirror alone flips the winding, so culling is inverted
- if (this->m_reflectionReceivers.empty () || this->_rt_Reflection == nullptr) {
- return;
- }
- auto& camera = this->getCamera ();
- const glm::mat4 view = camera.getWorldView ();
- const glm::mat4 mirrored = view * glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f));
- if (camera.isPerspective ()) {
- camera.setPerspectiveView (mirrored, camera.getViewFov ());
- } else {
- camera.setWorldView (mirrored);
- camera.updatePerspectiveLayers ();
- }
- glBindFramebuffer (GL_FRAMEBUFFER, this->_rt_Reflection->getFramebuffer ());
- glViewport (0, 0, this->_rt_Reflection->getRealWidth (), this->_rt_Reflection->getRealHeight ());
- glDepthMask (GL_TRUE);
- glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
- const glm::vec3 clearColor = this->getScene ().colors.clear->value->getVec3 ();
- glClearColor (clearColor.r, clearColor.g, clearColor.b, 1.0f);
- glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
- // everything the scene draws goes into the reflection target, like a passthrough layer's buffer
- this->m_layerTargets.push_back (
- {
- .fbo = this->_rt_Reflection,
- .transform = glm::mat4 (1.0f),
- .alphaMax = false,
- .viewProjection = this->getWorldViewProjection (),
- .viewProjectionApplied = true,
- }
- );
- this->m_renderingReflection = true;
- // scene +456 (sub_14018FF60): images, models, text and particles in creation order, minus the ones that sample the
- // reflection themselves and the ones with "reflected" false; no lights, sounds, cameras or groups
- for (auto* cur : this->m_objectsByRenderOrder) {
- if (cur->is<Objects::CLight> () || cur->is<Objects::CSound> () || cur->is<Objects::CCamera> ()) {
- continue;
- }
- if (!cur->getObject ().reflected || this->m_reflectionReceivers.contains (cur->getId ())) {
- continue;
- }
- this->renderSceneObject (cur);
- }
- this->m_renderingReflection = false;
- this->m_layerTargets.pop_back ();
- if (camera.isPerspective ()) {
- camera.setPerspectiveView (view, camera.getViewFov ());
- } else {
- camera.setWorldView (view);
- camera.updatePerspectiveLayers ();
- }
- }
- void CScene::executeEffectFunction (const ImageEffect& effect, const std::string& name) const {
- for (const auto* object : this->m_objects | std::views::values) {
- if (object->is<Objects::CRenderable> ()
- && object->as<Objects::CRenderable> ()->executeEffectFunction (effect, name)) {
- return;
- }
- }
- }
- Objects::Effects::CPass* CScene::findEffectMaterial (const ImageEffect& effect, size_t passIndex) const {
- for (const auto* object : this->m_objects | std::views::values) {
- if (object->is<Objects::CRenderable> ()) {
- if (auto* pass = object->as<Objects::CRenderable> ()->getEffectMaterial (effect, passIndex)) {
- return pass;
- }
- }
- }
- return nullptr;
- }
- GLuint CScene::getSceneDrawFramebuffer () const {
- return this->m_msaaActive ? this->m_msaaFramebuffer : this->m_sceneFBO->getFramebuffer ();
- }
- bool CScene::prepareMultisample () {
- const glm::ivec2 size (this->m_sceneFBO->getRealWidth (), this->m_sceneFBO->getRealHeight ());
- if (this->m_msaaFramebuffer != GL_NONE && size == this->m_msaaSize) {
- return true;
- }
- this->releaseMultisample ();
- this->m_msaaSize = size;
- // same color format as the scene buffer (sub_140181AF0: RGBA8, RGBA16F in HDR), a resolve needs it
- GLint colorFormat = GL_RGBA8;
- GLint maxSamples = 0;
- glBindTexture (GL_TEXTURE_2D, this->m_sceneFBO->getTextureID (0));
- glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &colorFormat);
- glGetIntegerv (GL_MAX_SAMPLES, &maxSamples);
- // the device check (CheckMultisampleQualityLevels in sub_14012AC60) falls back to one sample, no MSAA
- if (this->m_msaaSamples > maxSamples) {
- sLog.error (
- "MSAA x", this->m_msaaSamples, " is not supported here (at most ", maxSamples, "), drawing without"
- );
- this->m_msaaSamples = 0;
- return false;
- }
- glGenRenderbuffers (1, &this->m_msaaColor);
- glBindRenderbuffer (GL_RENDERBUFFER, this->m_msaaColor);
- glRenderbufferStorageMultisample (GL_RENDERBUFFER, this->m_msaaSamples, colorFormat, size.x, size.y);
- if (this->m_sceneFBO->getDepthbuffer () != GL_NONE) {
- glGenRenderbuffers (1, &this->m_msaaDepth);
- glBindRenderbuffer (GL_RENDERBUFFER, this->m_msaaDepth);
- glRenderbufferStorageMultisample (GL_RENDERBUFFER, this->m_msaaSamples, GL_DEPTH_COMPONENT32F, size.x, size.y);
- }
- glBindRenderbuffer (GL_RENDERBUFFER, 0);
- glGenFramebuffers (1, &this->m_msaaFramebuffer);
- glBindFramebuffer (GL_FRAMEBUFFER, this->m_msaaFramebuffer);
- glFramebufferRenderbuffer (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, this->m_msaaColor);
- if (this->m_msaaDepth != GL_NONE) {
- glFramebufferRenderbuffer (GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, this->m_msaaDepth);
- }
- const bool complete = glCheckFramebufferStatus (GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
- glBindFramebuffer (GL_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
- if (!complete) {
- sLog.error ("Cannot create the MSAA x", this->m_msaaSamples, " scene buffer, drawing without");
- this->releaseMultisample ();
- this->m_msaaSamples = 0;
- return false;
- }
- #if !NDEBUG
- glObjectLabel (GL_FRAMEBUFFER, this->m_msaaFramebuffer, -1, "_rt_FullFrameBufferMultiSampled");
- #endif
- return true;
- }
- void CScene::releaseMultisample () {
- if (this->m_msaaFramebuffer != GL_NONE) {
- glDeleteFramebuffers (1, &this->m_msaaFramebuffer);
- }
- if (this->m_msaaColor != GL_NONE) {
- glDeleteRenderbuffers (1, &this->m_msaaColor);
- }
- if (this->m_msaaDepth != GL_NONE) {
- glDeleteRenderbuffers (1, &this->m_msaaDepth);
- }
- this->m_msaaFramebuffer = this->m_msaaColor = this->m_msaaDepth = GL_NONE;
- }
- void CScene::resolveMultisample () const {
- if (!this->m_msaaActive) {
- return;
- }
- GLint readFramebuffer = 0;
- GLint drawFramebuffer = 0;
- glGetIntegerv (GL_READ_FRAMEBUFFER_BINDING, &readFramebuffer);
- glGetIntegerv (GL_DRAW_FRAMEBUFFER_BINDING, &drawFramebuffer);
- const GLbitfield mask = GL_COLOR_BUFFER_BIT | (this->m_msaaDepth != GL_NONE ? GL_DEPTH_BUFFER_BIT : 0);
- glBindFramebuffer (GL_READ_FRAMEBUFFER, this->m_msaaFramebuffer);
- glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
- glBlitFramebuffer (
- 0, 0, this->m_msaaSize.x, this->m_msaaSize.y, 0, 0, this->m_msaaSize.x, this->m_msaaSize.y, mask, GL_NEAREST
- );
- glBindFramebuffer (GL_READ_FRAMEBUFFER, readFramebuffer);
- glBindFramebuffer (GL_DRAW_FRAMEBUFFER, drawFramebuffer);
- }
- void CScene::updateMipMappedFrameBuffer () const {
- if (this->_rt_MipMappedFrameBuffer == nullptr) {
- return;
- }
- const auto width = static_cast<GLint> (this->m_sceneFBO->getRealWidth ());
- const auto height = static_cast<GLint> (this->m_sceneFBO->getRealHeight ());
- this->resolveMultisample ();
- glBindFramebuffer (GL_READ_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
- glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->_rt_MipMappedFrameBuffer->getFramebuffer ());
- glBlitFramebuffer (0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
- this->_rt_MipMappedFrameBuffer->generateMipmaps ();
- glBindFramebuffer (GL_FRAMEBUFFER, this->getSceneDrawFramebuffer ());
- }
- glm::ivec2 CScene::getOutputResolution () const {
- return { std::max (this->getFramebufferWidth (), 1), std::max (this->getFramebufferHeight (), 1) };
- }
- glm::mat4 CScene::getWorldViewProjection (const bool perspectiveLayer) const {
- const auto& camera = this->getCamera ();
- if (!camera.isOrthogonal ()) {
- return camera.getPerspective () * camera.getView ();
- }
- const glm::vec3 center (this->getWidth () * 0.5f, this->getHeight () * 0.5f, 0.0f);
- // "perspective" objects get the perspective layer camera (sub_1401E5B60), models too (sub_1402222A0)
- const glm::mat4 viewProjection = perspectiveLayer ? camera.getPerspectiveLayerViewProjection ()
- : camera.getProjection () * camera.getLookAt ();
- return viewProjection * glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
- * glm::translate (glm::mat4 (1.0f), -center);
- }
- void CScene::cursorLine (
- const glm::vec2& ndc, const bool perspectiveLayer, glm::vec3& origin, glm::vec3& direction
- ) const {
- const glm::mat4 toWorld = glm::inverse (this->getWorldViewProjection (perspectiveLayer));
- const glm::vec4 nearPoint = toWorld * glm::vec4 (ndc, DepthRange::nearClip (), 1.0f);
- const glm::vec4 farPoint = toWorld * glm::vec4 (ndc, DepthRange::farClip (), 1.0f);
- origin = glm::vec3 (nearPoint) / nearPoint.w;
- direction = glm::vec3 (farPoint) / farPoint.w - origin;
- }
- glm::mat4 CScene::getCullViewProjection () const {
- // 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
- // of GL's. Both come out of the scene matrices from a depth remap, which reversed ones already have for 2D ortho
- const bool reversed = DepthRange::supported ();
- if (reversed && this->getCamera ().isOrthogonal ()) {
- return this->getWorldViewProjection ();
- }
- const float direction = reversed ? -1.0f : (this->getCamera ().isOrthogonal () ? -0.5f : 0.5f);
- glm::mat4 depth (1.0f);
- depth[2][2] = direction;
- depth[3][2] = reversed ? 1.0f : 0.5f;
- return depth * this->getWorldViewProjection ();
- }
- void CScene::renderPostProcessing () {
- this->m_presentBackBuffer = false;
- const bool postProcessing = !this->getContext ().getApp ().getContext ().settings.general.postProcessingDisabled;
- if (this->m_frameMaterials == nullptr) {
- auto materials = std::make_unique<FrameMaterials> ();
- const auto load = [this] (const char* file) {
- return std::make_unique<FrameMaterial> (*this, this->getScene ().project, file);
- };
- materials->combine = load (
- this->m_displayHDR ? "materials/util/combine_dhdr_upsample.json"
- : this->m_hdr ? "materials/util/combine_hdr_upsample.json"
- : "materials/util/combine_ldr.json"
- );
- if (this->m_hdr) {
- // combine_video_hdr.json needs renderer flag 0x10000, never set here
- materials->combineWithoutBloom = load ("materials/util/combine_srgb.json");
- materials->hdrDownsample = load ("materials/util/hdr_downsample.json");
- materials->hdrDownsampleBloom = load ("materials/util/hdr_downsample_bloom.json");
- materials->hdrUpsample = load ("materials/util/hdr_upsample.json");
- materials->hdrUpsampleCubic = load ("materials/util/hdr_upsample_cubic.json");
- } else if (postProcessing) {
- materials->downsampleQuarterBloom = load ("materials/util/downsample_quarter_bloom.json");
- materials->downsampleEighthBlurV = load ("materials/util/downsample_eighth_blur_v.json");
- materials->blurHBloom = load ("materials/util/blur_h_bloom.json");
- }
- this->m_frameMaterials = std::move (materials);
- }
- // post processing not disabled, scene bloom on, something in the scene; checked every frame
- const bool bloom = postProcessing && this->getScene ().camera.bloom.enabled->value->getBool ()
- && !this->m_objectsByRenderOrder.empty ();
- // HDR scenes go through combine_srgb even without bloom
- if (bloom || this->m_hdr) {
- if (bloom) {
- if (this->m_hdr) {
- this->renderHDRBloom ();
- } else {
- this->renderBloom ();
- }
- }
- // ours draw into _rt_FullFrameBuffer and combine into their own back buffer, WE copies its back buffer there
- // first
- this->prepareBackBuffer (this->backBufferSize (), this->m_hdr ? GL_RGBA16F : GL_RGBA8);
- FrameMaterial& combine
- = bloom || !this->m_hdr ? *this->m_frameMaterials->combine : *this->m_frameMaterials->combineWithoutBloom;
- combine.setUniform ("g_TexelSize", *this->getTexelSize ());
- // slot 1 is _rt_2FrameBuffer
- if (this->m_hdr && bloom && !this->m_hdrBloomLevels.empty ()) {
- combine.setTexture (1, this->m_hdrBloomLevels.front ()->getTextureID (0));
- }
- combine.setUniform ("g_RenderVar0", glm::vec4 (this->combineRenderVar (), 0.0f, 0.0f));
- combine.draw (this->m_backBuffer.framebuffer, this->m_backBuffer.size);
- this->m_presentBackBuffer = true;
- }
- this->renderImageAdjustments (this->backBufferSize (), this->m_hdr ? GL_RGBA16F : GL_RGBA8);
- this->renderCameraFade ();
- }
- glm::ivec2 CScene::backBufferSize () const {
- return { this->m_sceneFBO->getRealWidth (), this->m_sceneFBO->getRealHeight () };
- }
- void CScene::renderCameraFade () {
- // sub_14017FA70: fade alpha goes to g_Alpha, fade.json blends over the back buffer
- if (this->m_cameraFade <= 0.0f) {
- return;
- }
- auto& materials = *this->m_frameMaterials;
- if (materials.fade == nullptr) {
- materials.fade = std::make_unique<FrameMaterial> (*this, this->getScene ().project, "materials/util/fade.json");
- }
- // project schemecolor -> "tint" (sub_140154480)
- const auto& properties = this->getUserProperties ();
- if (const auto scheme = properties.find ("schemecolor"); scheme != properties.end () && scheme->second != nullptr) {
- materials.fade->setConstant ("tint", scheme->second->getVec3 ());
- }
- this->prepareBackBuffer (this->backBufferSize (), this->m_hdr ? GL_RGBA16F : GL_RGBA8);
- if (!this->m_presentBackBuffer) {
- glBindFramebuffer (GL_READ_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
- glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->m_backBuffer.framebuffer);
- glBlitFramebuffer (
- 0, 0, this->m_backBuffer.size.x, this->m_backBuffer.size.y, 0, 0, this->m_backBuffer.size.x,
- this->m_backBuffer.size.y, GL_COLOR_BUFFER_BIT, GL_NEAREST
- );
- this->m_presentBackBuffer = true;
- }
- materials.fade->setUniform ("g_Alpha", this->m_cameraFade);
- materials.fade->draw (this->m_backBuffer.framebuffer, this->m_backBuffer.size);
- }
- void CScene::renderBloom () {
- const auto& materials = *this->m_frameMaterials;
- const auto& settings = this->getScene ().camera.bloom;
- // sub_140184020 / sub_14017F1B0
- materials.downsampleQuarterBloom->setConstant ("bloomstrength", settings.strength->value->getFloat ());
- materials.downsampleQuarterBloom->setConstant ("bloomthreshold", settings.threshold->value->getFloat ());
- materials.downsampleQuarterBloom->setConstant ("bloomtint", settings.tint->value->getVec3 ());
- // sub_140183610: _rt_FullFrameBuffer -> _rt_4FrameBuffer -> _rt_8FrameBuffer -> _rt_Bloom
- for (const auto& [material, target] :
- { std::pair<FrameMaterial*, const char*> { materials.downsampleQuarterBloom.get (), "_rt_4FrameBuffer" },
- { materials.downsampleEighthBlurV.get (), "_rt_8FrameBuffer" },
- { materials.blurHBloom.get (), "_rt_Bloom" } }) {
- material->setUniform ("g_TexelSize", *this->getTexelSize ());
- material->draw (*this->find (target));
- }
- }
- void CScene::renderHDRBloom () {
- const auto& materials = *this->m_frameMaterials;
- const auto& settings = this->getScene ().camera.bloom;
- // sub_14017F1B0: a level per halving of the smaller side, 8 at most
- const glm::ivec2 client = glm::max (this->m_outputSize, glm::ivec2 (2));
- int available = 0;
- for (int side = std::min (client.x, client.y) / 2; side > 0 && available < 8; side /= 2) {
- available++;
- }
- while (static_cast<int> (this->m_hdrBloomLevels.size ()) < available) {
- const int divisor = 2 << this->m_hdrBloomLevels.size ();
- const glm::vec2 size = glm::max (glm::vec2 (client / divisor), glm::vec2 (1.0f));
- auto fbo = this->create (
- "_rt_" + std::to_string (divisor) + "FrameBuffer", TextureFormat_RGBA16161616f, TextureFlags_ClampUVs, 1.0,
- size, size
- );
- this->followOutputSize (fbo, static_cast<float> (divisor));
- this->m_hdrBloomLevels.push_back (std::move (fbo));
- }
- if (available == 0) {
- return;
- }
- // sub_140184020
- const int levels = std::max (std::min (available, settings.hdrIterations->value->getInt ()), 1);
- const float scatter = settings.hdrScatter->value->getFloat ();
- const float threshold = settings.hdrThreshold->value->getFloat ();
- const float knee = threshold * settings.hdrFeather->value->getFloat ();
- materials.hdrDownsampleBloom->setConstant (
- "bloomstrength",
- settings.hdrStrength->value->getFloat ()
- / (std::pow (scatter, static_cast<float> (std::max (levels, 2) - 2)) + 1.0f)
- );
- materials.hdrDownsampleBloom->setConstant (
- "blend", glm::vec4 (threshold, threshold - knee, knee + knee, 0.25f / (knee + 0.0000099999997f))
- );
- materials.hdrDownsampleBloom->setConstant ("bloomtint", settings.tint->value->getVec3 ());
- materials.hdrUpsample->setConstant ("scatter", scatter);
- materials.hdrUpsampleCubic->setConstant ("scatter", scatter);
- // sub_140183610: g_RenderVar0 = (1, 1, -1, -1) / client size * step
- const glm::vec2 texel = 1.0f / glm::vec2 (client);
- const auto draw = [&] (FrameMaterial& material, const GLuint source, const CFBO& target, const float step) {
- material.setTexture (0, source);
- material.setUniform ("g_RenderVar0", glm::vec4 (texel * step, -texel * step));
- material.setUniform ("g_TexelSize", *this->getTexelSize ());
- material.draw (target);
- };
- // threshold into level 0, halve down the chain, add back up (last two bicubic)
- draw (*materials.hdrDownsampleBloom, this->m_sceneFBO->getTextureID (0), *this->m_hdrBloomLevels[0], 1.0f);
- for (int level = 1; level < levels; level++) {
- draw (
- *materials.hdrDownsample, this->m_hdrBloomLevels[level - 1]->getTextureID (0),
- *this->m_hdrBloomLevels[level], static_cast<float> (1 << level)
- );
- }
- for (int level = levels - 1; level > 0; level--) {
- draw (
- level < levels - 2 ? *materials.hdrUpsample : *materials.hdrUpsampleCubic,
- this->m_hdrBloomLevels[level]->getTextureID (0), *this->m_hdrBloomLevels[level - 1],
- static_cast<float> (2 << (level - 1))
- );
- }
- }
- glm::vec2 CScene::combineRenderVar () const {
- // (white, peak - white) / 80 in WE's scRGB (sub_14012AC60), relative to the output's reference white here
- const glm::vec2& luminance = this->getOutputLuminance ();
- if (!this->isOutputHDR () || luminance.x <= 0.0f) {
- return glm::vec2 (1.0f);
- }
- const float peak = std::max (luminance.y, 80.0f);
- const float white = std::max (std::min (luminance.x, peak), 80.0f);
- return glm::vec2 (white, peak - white) / luminance.x;
- }
- void CScene::updateParallax () {
- if (this->getScene ().camera.parallax.enabled->value->getBool ()) {
- // the wallpaper's position goes through the mouse parallax depth/clamp, halved to match its range; only x keeps
- // WallpaperState's sign flip, y is applied after the y-up conversion
- const glm::vec2 positionBias
- = { -this->getState ().getOffsetX () * 0.5f, this->getState ().getOffsetY () * 0.5f };
- if (this->getContext ().getApp ().getContext ().settings.mouse.disableparallax) {
- this->m_parallaxBias = positionBias;
- this->m_cameraParallax = { 0.0f, 0.0f };
- } else {
- const float influence = this->getScene ().camera.parallax.mouseInfluence->value->getFloat ();
- const float amount = this->getScene ().camera.parallax.amount->value->getFloat ();
- const float delay = this->getScene ().camera.parallax.delay->value->getFloat ();
- this->m_parallaxBias = positionBias * amount * influence;
- // WE's easing: no delay snaps to the mouse, else a fast exponential follow. A camera object's eye moves it
- // too, before the smoothing (sub_1401891A0); y up, the cursor is flipped, the eye isn't
- const glm::vec2 eye = { this->m_cameraEye.x / static_cast<float> (this->getWidth ()),
- this->m_cameraEye.y / static_cast<float> (this->getHeight ()) };
- const glm::vec2 cursor
- = glm::clamp (glm::vec2 (this->m_mousePosition.x, 1.0f - this->m_mousePosition.y), 0.0f, 1.0f);
- const glm::vec2 target = (cursor - glm::vec2 (0.5f, 0.5f)) * influence + eye;
- if (delay <= 0.0f) {
- this->m_cameraParallax = target;
- } else {
- const float dt = std::max (g_Time - g_TimeLast, 0.0f);
- const float follow = std::min (1.0f, (1.0f - delay / 3.0f) * 10.0f * dt);
- this->m_cameraParallax += (target - this->m_cameraParallax) * follow;
- }
- }
- this->m_parallaxPosition = glm::clamp (glm::vec2 (0.5f) + this->m_cameraParallax, 0.0f, 1.0f);
- }
- }
- glm::mat4 CScene::objectLocalMatrix (const Object& object) {
- // images and particles keep their own (scriptable) scale and angles next to the base object's copy
- glm::vec3 scale = object.groupScale->value->getVec3 ();
- glm::vec3 angles = object.groupAngles->value->getVec3 ();
- if (object.is<Image> ()) {
- scale = object.as<Image> ()->scale->value->getVec3 ();
- angles = object.as<Image> ()->angles->value->getVec3 ();
- } else if (object.is<Particle> ()) {
- scale = object.as<Particle> ()->scale->value->getVec3 ();
- angles = object.as<Particle> ()->angles->value->getVec3 ();
- } else if (object.is<Text> ()) {
- scale = object.as<Text> ()->scale->value->getVec3 ();
- }
- glm::mat4 transform = glm::translate (glm::mat4 (1.0f), object.origin->value->getVec3 ());
- transform = glm::rotate (transform, angles.z, glm::vec3 (0.0f, 0.0f, 1.0f));
- transform = glm::rotate (transform, angles.y, glm::vec3 (0.0f, 1.0f, 0.0f));
- transform = glm::rotate (transform, angles.x, glm::vec3 (1.0f, 0.0f, 0.0f));
- return glm::scale (transform, scale);
- }
- namespace {
- // sub_1401DD630, without the scale
- glm::mat4 objectFrameLocal (const Object& object) {
- const glm::vec3 angles = object.is<Image> () ? object.as<Image> ()->angles->value->getVec3 ()
- : object.is<Particle> () ? object.as<Particle> ()->angles->value->getVec3 ()
- : object.groupAngles->value->getVec3 ();
- glm::mat4 transform = glm::translate (glm::mat4 (1.0f), object.origin->value->getVec3 ());
- transform = glm::rotate (transform, angles.z, glm::vec3 (0.0f, 0.0f, 1.0f));
- transform = glm::rotate (transform, angles.y, glm::vec3 (0.0f, 1.0f, 0.0f));
- return glm::rotate (transform, angles.x, glm::vec3 (1.0f, 0.0f, 0.0f));
- }
- bool isPassthroughImage (const CObject& object) {
- return object.is<Objects::CImage> () && object.as<Objects::CImage> ()->getImage ().model->passthrough;
- }
- }
- glm::mat4 CScene::parentChainMatrix (const Object& object, bool scaled) const {
- glm::mat4 chain (1.0f);
- const Object* current = &object;
- for (int depth = 0; current->parent.has_value () && depth < 64; depth++) {
- const CObject* parent = this->getObject (current->parent.value ());
- if (parent == nullptr) {
- break;
- }
- // sub_1401850A0: onto the parent's attachment point first
- if (current->attachment.has_value ()) {
- std::optional<glm::mat4> attachment;
- if (parent->is<Objects::CMesh> ()) {
- attachment = parent->as<Objects::CMesh> ()->getAttachmentMatrix (*current->attachment);
- } else if (parent->is<Objects::CImage> ()) {
- attachment = parent->as<Objects::CImage> ()->getAttachmentMatrix (*current->attachment);
- }
- if (attachment.has_value ()) {
- chain = *attachment * chain;
- }
- }
- current = &parent->getObject ();
- chain = (scaled ? objectLocalMatrix (*current) : objectFrameLocal (*current)) * chain;
- }
- return chain;
- }
- glm::mat4 CScene::objectWorldMatrix (const Object& object) const {
- return this->parentChainMatrix (object, true) * objectLocalMatrix (object);
- }
- glm::mat4 CScene::objectFrameMatrix (const Object& object) const {
- return this->parentChainMatrix (object, false) * objectFrameLocal (object);
- }
- bool CScene::queueDestroyLayer (CObject& object) {
- if (std::ranges::find (this->m_objectsByRenderOrder, &object) == this->m_objectsByRenderOrder.end ()) {
- return false;
- }
- this->m_pendingDestroy.insert (&object);
- return true;
- }
- bool CScene::isPendingDestroy (const CObject& object) const {
- return this->m_pendingDestroy.contains (const_cast<CObject*> (&object));
- }
- // a layer's own buffers and render object are what a script that keeps creating and destroying layers piles up (two
- // layer sized framebuffers each, which the scene's name map and the output follower list never let go)
- bool CScene::isReleasable (const CObject& object) const {
- // only what scripts made while running: nothing in the scene file can name them. Cameras, lights and models are
- // listed elsewhere too (m_sceneCameras, the light slots, the shadow casters)
- return object.getId () >= DYNAMIC_LAYER_ID_BASE && !object.is<Objects::CMesh> () && !object.is<Objects::CLight> ()
- && !object.is<Objects::CCamera> ();
- }
- void CScene::releaseDestroyedLayers () {
- // destroyed in an earlier frame: the lists, the script handles (forgotten) and the render order let go of it then
- constexpr uint32_t gracePeriod = 2;
- const auto due = std::ranges::stable_partition (this->m_releasableLayers, [this] (const DestroyedLayer& layer) {
- return this->m_frameCounter - layer.frame < gracePeriod;
- });
- for (const auto& layer : due) {
- const int id = layer.object->getId ();
- this->m_transparentSorted.erase (layer.object);
- // the text a layer was made from is most of what the model costs, and the model has to stay: animation clocks
- // and script handles may still point into it
- if (auto* scriptable = dynamic_cast<Scripting::ScriptableObject*> (layer.object); scriptable != nullptr) {
- scriptable->dropScriptSources ();
- }
- delete layer.object;
- this->remove ("_rt_imageLayerComposite_" + std::to_string (id) + "_a");
- this->remove ("_rt_imageLayerComposite_" + std::to_string (id) + "_b");
- this->releaseLayerModel (id);
- }
- if (due.empty ()) {
- return;
- }
- this->m_releasableLayers.erase (due.begin (), due.end ());
- std::erase_if (this->m_outputSizedBuffers, [] (const OutputSizedBuffer& buffer) { return buffer.fbo.expired (); });
- }
- void CScene::releaseLayerModel (int id) {
- const auto data = this->m_dynamicObjectData.find (id);
- if (data == this->m_dynamicObjectData.end ()) {
- return;
- }
- // the timelines of its values go first, they write into them every frame
- this->getScriptEngine ().getAnimations ().removeObject (id);
- // an IEffect or IMaterial a script holds points into the model for good, those layers keep it
- if (this->getScriptEngine ().getAdapters ().object->hasEffectHandles (*data->second)) {
- std::string ().swap (data->second->initialConfig);
- return;
- }
- this->m_dynamicObjectData.erase (data);
- }
- void CScene::destroyPendingLayers () {
- this->releaseDestroyedLayers ();
- // sub_1401909C0: children keep their transforms but lose the parent, scripts get destroy (). A scene's own layer
- // stays allocated until the scene goes, others may hold its buffers
- const auto pending = std::exchange (this->m_pendingDestroy, {});
- for (auto* object : pending) {
- for (auto* child : this->childrenOf (object->getId ())) {
- child->getObject ().parent.reset ();
- child->getObject ().attachment.reset ();
- }
- this->m_children.erase (object->getId ());
- this->detachChild (*object);
- object->getObject ().parent.reset ();
- if (auto* scriptable = dynamic_cast<Scripting::ScriptableObject*> (object)) {
- this->getScriptEngine ().destroyObjectScripts (*scriptable);
- }
- std::erase (this->m_objectsByRenderOrder, object);
- this->m_objects.erase (object->getId ());
- this->m_cursorInside.erase (object->getId ());
- this->m_cursorPressed.erase (object->getId ());
- if (this->isReleasable (*object)) {
- this->m_releasableLayers.push_back ({ object, this->m_frameCounter });
- } else {
- this->m_destroyedObjects.push_back (object);
- }
- }
- }
- bool CScene::scriptsMayReparent () const {
- if (!this->m_scriptsMayReparent.has_value ()) {
- this->m_scriptsMayReparent = std::ranges::any_of (this->getScene ().objects, [] (const auto& object) {
- return object->initialConfig.find ("setParent") != std::string::npos;
- });
- }
- return *this->m_scriptsMayReparent;
- }
- int CScene::passthroughDepth (const CObject& object, const int level) const {
- const int own = isPassthroughImage (object) ? 1 : 0;
- int depth = own;
- if (level >= 64) {
- return depth;
- }
- for (const auto* child : this->childrenOf (object.getId ())) {
- depth = std::max (depth, this->passthroughDepth (*child, level + 1) + own);
- }
- return depth;
- }
- bool CScene::setObjectParent (CObject& object, const CObject* parent, int attachment, bool adjustTransforms) {
- const Object& data = object.getObject ();
- const CObject* current = data.parent.has_value () ? this->getObject (*data.parent) : nullptr;
- // an index without a point keeps the identity like WE
- std::optional<std::string> attachmentName;
- if (parent != nullptr && attachment >= 0) {
- const Objects::PuppetRig* rig = parent->is<Objects::CImage> () ? &parent->as<Objects::CImage> ()->getRig ()
- : parent->is<Objects::CMesh> () ? &parent->as<Objects::CMesh> ()->getRig ()
- : nullptr;
- if (rig != nullptr && static_cast<size_t> (attachment) < rig->attachmentPoints.size ()) {
- attachmentName = rig->attachmentPoints[attachment].name;
- }
- }
- if (current == parent && (parent == nullptr || data.attachment == attachmentName)) {
- return true;
- }
- // itself, or more than 3 passthrough layers deep: WE drops the parent and reports the error
- int parentDepth = 0;
- int steps = 0;
- bool loops = false;
- // the chain of parents ends at a root, unless it comes back to the object (or loops among others, which only the
- // step count stops: a loop of plain groups never raises parentDepth)
- for (const CObject* ancestor = parent; ancestor != nullptr && parentDepth < 64 && steps < 1024; steps++) {
- loops = loops || ancestor == &object;
- parentDepth += isPassthroughImage (*ancestor) ? 1 : 0;
- const auto& next = ancestor->getObject ().parent;
- ancestor = next.has_value () ? this->getObject (*next) : nullptr;
- }
- this->detachChild (object);
- if (parent != nullptr && (loops || steps >= 1024)) {
- sLog.error (
- "Cannot make object ", object.getId (), " a child of ", parent->getId (), ", the parents would loop"
- );
- }
- if (parent == &object || loops || steps >= 1024 || parentDepth + this->passthroughDepth (object) > 3) {
- data.parent.reset ();
- data.attachment.reset ();
- return false;
- }
- auto* scriptable = dynamic_cast<Scripting::ScriptableObject*> (&object);
- DynamicValue* origin = scriptable != nullptr ? scriptable->tryGetProperty ("origin") : nullptr;
- DynamicValue* angles = scriptable != nullptr ? scriptable->tryGetProperty ("angles") : nullptr;
- DynamicValue* scale = scriptable != nullptr ? scriptable->tryGetProperty ("scale") : nullptr;
- if (!adjustTransforms || origin == nullptr || angles == nullptr || scale == nullptr) {
- data.parent = parent != nullptr ? std::optional (parent->getId ()) : std::nullopt;
- data.attachment = attachmentName;
- this->attachChild (object);
- return true;
- }
- const glm::mat4 world = this->objectWorldMatrix (data);
- const glm::mat4 frame = this->objectFrameMatrix (data);
- const glm::mat4 unscaledWorld = this->parentChainMatrix (data, true) * objectFrameLocal (data);
- const glm::vec3 savedScale = scale->getVec3 ();
- data.parent = parent != nullptr ? std::optional (parent->getId ()) : std::nullopt;
- data.attachment = attachmentName;
- this->attachChild (object);
- if (parent != nullptr && attachment >= 0) {
- origin->update (glm::vec3 (0.0f), DynamicValue::UpdateSource::Script);
- angles->update (glm::vec3 (0.0f), DynamicValue::UpdateSource::Script);
- return true;
- }
- const glm::mat4 parentWorld = parent != nullptr ? this->objectWorldMatrix (parent->getObject ()) : glm::mat4 (1.0f);
- const glm::mat4 parentFrame = parent != nullptr ? this->objectFrameMatrix (parent->getObject ()) : glm::mat4 (1.0f);
- const glm::mat4 local = glm::inverse (parentWorld) * world;
- const glm::mat4 rotation = glm::inverse (parentFrame) * frame;
- const float* m = glm::value_ptr (rotation);
- const float z = std::atan2 (m[1], m[0]);
- const float y = std::atan2 (-m[2], std::sqrt (m[6] * m[6] + m[10] * m[10]));
- 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]);
- origin->update (glm::vec3 (local[3]), DynamicValue::UpdateSource::Script);
- angles->update (glm::vec3 (x, y, z), DynamicValue::UpdateSource::Script);
- const glm::mat4 newUnscaledWorld = this->parentChainMatrix (data, true) * objectFrameLocal (data);
- glm::vec3 adjusted;
- for (int axis = 0; axis < 3; axis++) {
- const float length = glm::length (newUnscaledWorld[axis]);
- adjusted[axis]
- = savedScale[axis] * glm::length (unscaledWorld[axis]) * (length > 1.1920929e-7f ? 1.0f / length : 1.0f);
- }
- scale->update (adjusted, DynamicValue::UpdateSource::Script);
- return true;
- }
- void CScene::updateCameraPath (const float dt, glm::vec3& eye, glm::vec3& center, glm::vec3& up, float& zoom) {
- // sub_1401891A0: the keys of one path at a time, cubic Hermite between two keys with tangents of half their
- // difference, then the next path once the last key is done
- const auto& paths = this->getScene ().camera.paths;
- this->m_pathIndex %= static_cast<int> (paths.size ());
- const auto& path = paths[this->m_pathIndex];
- if (path.keys.empty ()) {
- this->m_pathIndex = (this->m_pathIndex + 1) % static_cast<int> (paths.size ());
- return;
- }
- const int count = static_cast<int> (path.keys.size ());
- this->m_pathKey = std::min (this->m_pathKey, count - 1);
- const auto& key = path.keys[this->m_pathKey];
- const float time = this->m_pathTime;
- float until;
- eye = key.eye;
- center = key.center;
- up = key.up;
- zoom = key.zoom;
- if (time < key.time) {
- until = (this->m_pathKey + 1 < count ? path.keys[this->m_pathKey + 1].time : 0.0f) + key.time;
- } else if (this->m_pathKey + 1 < count) {
- const auto& next = path.keys[this->m_pathKey + 1];
- // two keys at one time (an editor can write them) are a jump to the second, not a division by zero
- const float s = next.time > key.time ? (time - key.time) / (next.time - key.time) : 1.0f;
- const float s2 = s * s;
- const float s3 = s2 * s;
- const float h00 = 2.0f * s3 - 3.0f * s2 + 1.0f;
- const float h10 = s3 - 2.0f * s2 + s;
- const float h01 = 3.0f * s2 - 2.0f * s3;
- const float h11 = s3 - s2;
- const auto hermite = [&] (const auto& a, const auto& b) {
- const auto tangent = (b - a) * 0.5f;
- return a * h00 + tangent * h10 + b * h01 + tangent * h11;
- };
- eye = hermite (key.eye, next.eye);
- center = hermite (key.center, next.center);
- up = hermite (key.up, next.up);
- zoom = hermite (key.zoom, next.zoom);
- until = next.time;
- } else {
- until = path.duration - key.time;
- }
- this->m_pathTime = time + dt;
- if (this->m_pathTime > until) {
- if (this->m_pathKey + 1 >= count || path.duration <= path.keys[this->m_pathKey + 1].time) {
- this->m_pathIndex = (this->m_pathIndex + 1) % static_cast<int> (paths.size ());
- this->m_pathKey = 0;
- this->m_pathTime = 0.0f;
- } else {
- this->m_pathKey++;
- }
- }
- // camerafade darkens the first and last half second of every path (sub_14017FA70)
- if (this->getScene ().camera.fade->value->getBool ()) {
- const auto& current = paths[this->m_pathIndex];
- const float left = current.duration - this->m_pathTime;
- if (left < 0.5f) {
- this->m_cameraFade = 1.0f - 2.0f * left;
- } else if (left > current.duration - 0.5f) {
- this->m_cameraFade = 1.0f - 2.0f * (current.duration - left);
- }
- }
- }
- void CScene::updateFog (const glm::vec3& eye) {
- const auto& fog = this->getScene ().fog;
- const auto params = [] (const auto& start, const auto& end, const auto& startDensity, const auto& endDensity) {
- const float from = start->value->getFloat ();
- const float density = startDensity->value->getFloat ();
- return glm::vec4 (from, end->value->getFloat () - from, density, endDensity->value->getFloat () - density);
- };
- this->m_fog.distanceColor = fog.distanceColor->value->getVec3 ();
- this->m_fog.distanceParams
- = params (fog.distanceStart, fog.distanceEnd, fog.distanceStartDensity, fog.distanceEndDensity);
- this->m_fog.heightColor = fog.heightColor->value->getVec3 ();
- this->m_fog.heightParamsWorld
- = params (fog.heightStart, fog.heightEnd, fog.heightStartDensity, fog.heightEndDensity);
- this->m_fog.heightParamsLocal = this->m_fog.heightParamsWorld;
- this->m_fog.eyeWorld = eye;
- this->m_fog.eyeLocal = eye;
- if (!this->m_camera->isPerspective ()) {
- // 2D scenes: WE's eye sits 2000 units out over the scene center plus the camera (end of sub_1401891A0), and
- // a height of y here is H/2 - y there
- const float height = static_cast<float> (this->getHeight ());
- this->m_fog.eyeWorld
- = glm::vec3 (static_cast<float> (this->getWidth ()) * 0.5f + eye.x, height * 0.5f + eye.y, 2000.0f);
- this->m_fog.eyeLocal = glm::vec3 (eye.x, -eye.y, 2000.0f);
- this->m_fog.heightParamsLocal.x = height * 0.5f - this->m_fog.heightParamsWorld.x;
- this->m_fog.heightParamsLocal.y = -this->m_fog.heightParamsWorld.y;
- }
- }
- void CScene::updateCamera () {
- const auto& appContext = this->getContext ().getApp ().getContext ();
- Objects::CCamera* active = nullptr;
- for (CObject* object : this->m_sceneCameras) {
- const auto override = appContext.resolveObjectVisibility (object->getId (), object->getObject ().name);
- if (override.value_or (object->getObject ().groupVisible->value->getBool ())
- && !this->isHiddenByAncestor (*object)) {
- active = object->as<Objects::CCamera> ();
- }
- }
- const float dt = std::max (g_Time - g_TimeLast, 0.0f);
- // without a camera object or path the camera is the static one, which scripts can move
- const bool perspective = this->m_camera->isPerspective ();
- const StaticCamera& base = this->getStaticCamera ();
- glm::vec3 eye = base.eye;
- glm::vec3 center = base.center;
- glm::vec3 up = base.up;
- float fov = this->m_camera->getFov ();
- float zoom = base.zoom;
- this->m_cameraFade = 0.0f;
- if (active != nullptr) {
- glm::mat4 world = this->objectWorldMatrix (active->getObject ());
- zoom = active->getCamera ().zoom->value->getFloat ();
- fov = active->getCamera ().fov->value->getFloat ();
- // a camera path file drives the camera's transform, zoom and fov (sub_1401F2AD0)
- const auto& data = active->getObject ();
- const CObject* parent = data.parent.has_value () ? this->getObject (data.parent.value ()) : nullptr;
- const glm::mat4 parentWorld
- = parent != nullptr ? this->objectWorldMatrix (parent->getObject ()) : glm::mat4 (1.0f);
- if (const auto pose = active->updateTimeline (dt, world, parentWorld); pose.has_value ()) {
- world = pose->world;
- zoom = pose->zoom;
- fov = pose->fov;
- }
- // eye at the camera's position, looking down its -z axis, its y axis up
- eye = glm::vec3 (world[3]);
- center = eye - glm::vec3 (world[2]);
- up = glm::vec3 (world[1]);
- } else if (!this->getScene ().camera.paths.empty ()) {
- this->updateCameraPath (dt, eye, center, up, zoom);
- }
- if (this->getScene ().camera.shake.enabled->value->getBool ()) {
- // sub_140199580: speed and roughness shape a cos/sin wobble on the scene clock, it moves eye and center alike
- const auto& shake = this->getScene ().camera.shake;
- const float roughness = std::pow (shake.roughness->value->getFloat (), 3.0f);
- const float speed = shake.speed->value->getFloat ();
- const float time = speed * speed * this->getSceneClock ();
- glm::vec3 offset (std::cos (time), std::sin (time * 1.333f), perspective ? std::sin (time) : 0.0f);
- float amplitude = shake.amplitude->value->getFloat () * 0.1f;
- if (!perspective) {
- amplitude *= static_cast<float> (this->getHeight ()) * 0.1f;
- }
- if (roughness > 0.001f && !WallpaperEngine::Data::Utils::sameFloat (roughness, 1.0f)) {
- const float length = glm::length (offset);
- if (length > 0.0f) {
- offset *= std::pow (length, roughness) / length;
- }
- }
- eye += offset * amplitude;
- center += offset * amplitude;
- }
- const glm::mat4 view = glm::lookAt (eye, center, up);
- this->m_cameraEye = perspective ? glm::vec2 (0.0f) : glm::vec2 (eye);
- this->updateFog (eye);
- if (perspective) {
- this->m_camera->setVisibleRegion ({}, this->getOutputAspect ());
- this->m_camera->setPerspectiveView (view, fov);
- return;
- }
- this->m_camera->setWorldView (view);
- this->m_camera->setZoom (this->getScene ().camera.projection.zoom->value->getFloat () * zoom);
- this->m_camera->setVisibleRegion (this->getVisibleMargins (), this->getOutputAspect ());
- this->m_camera->updatePerspectiveLayers ();
- }
- void CScene::dispatchCursorEvents () {
- if (!this->getContext ().getApp ().getContext ().settings.mouse.enabled) {
- return;
- }
- const bool down = this->cursorLeftClick () == Input::MouseClickStatus::Clicked;
- const bool pressed = down && !this->m_cursorLeftDown;
- const bool released = !down && this->m_cursorLeftDown;
- this->m_cursorLeftDown = down;
- const glm::vec2 scenePosition = { this->m_mousePositionNormalized.x * static_cast<float> (this->getWidth ()),
- this->m_mousePositionNormalized.y * static_cast<float> (this->getHeight ()) };
- const bool moved = scenePosition != this->m_cursorLastScenePosition;
- this->m_cursorLastScenePosition = scenePosition;
- auto& engine = this->getScriptEngine ();
- // handlers are free to create layers, which would move things around under a live iteration. 3D scenes walk a
- // copy sorted by depth like the transparent pass (sub_1401865C0), 2D ones the creation order
- const auto objects = this->getCamera ().isPerspective () ? this->sortedByDepth (this->m_objectsByRenderOrder)
- : this->m_objectsByRenderOrder;
- // WE (sub_140189E10) checks for a drag before the pass: while the button is held on something pressed,
- // only the pressed objects hear about it, and only through cursorMove
- const bool dragging = down && !this->m_cursorPressed.empty ();
- // hitBox only while pressed or the button changed
- const bool wantsHitBox = !this->m_cursorPressed.empty () || pressed || released;
- // scene buffer clip space, what the objects' matrices project to (clip y grows towards the bottom of the screen);
- // m_cursorScreen.y is mirrored on flipped outputs, the hover zones of 3599498791 picked the opposite weekday on
- // Wayland
- const glm::vec2 ndc { this->m_cursorScreen.x * 2.0f - 1.0f,
- cursorClipY (this->m_cursorScreen.y, this->getState ().isVFlipped ()) };
- // topmost first, like WE. Hidden objects are hit tested and get events too, they just can't stop propagation.
- // Images and text (object types 1 and 4) test their quad, models (type 5) their bounds
- for (auto it = objects.rbegin (); it != objects.rend (); ++it) {
- auto* cur = *it;
- if (!cur->getObject ().solid->value->getBool ()) {
- continue;
- }
- Scripting::ScriptableObject* scriptable = nullptr;
- bool hit = false;
- bool visible = false;
- // the event's localPosition is whatever the object's hit test left behind (sub_14019DBB0 / sub_140185520),
- // quads fill it in off the quad too
- glm::vec3 local {};
- std::optional<std::string> hitBox;
- if (cur->is<Objects::CImage> ()) {
- auto* image = cur->as<Objects::CImage> ();
- scriptable = image;
- hit = image->hitTest (ndc);
- // fullscreen layers get the cursor in window pixels: WE stores ScreenToClient / client size and multiplies
- // it back by the client size (sub_140110630, sub_14017F1B0)
- local = image->getImage ().model->fullscreen ? glm::vec3 (this->m_mousePositionViewport, 0.0f)
- : glm::vec3 (image->cursorLocalPosition (ndc), 0.0f);
- visible = image->getImage ().visible->value->getBool ();
- if (wantsHitBox) {
- hitBox = image->cursorHitBox (ndc);
- }
- } else if (cur->is<Objects::CText> ()) {
- auto* text = cur->as<Objects::CText> ();
- scriptable = text;
- hit = text->hitTest (ndc);
- local = glm::vec3 (text->cursorLocalPosition (ndc), 0.0f);
- visible = text->getText ().visible->value->getBool ();
- } else if (cur->is<Objects::CMesh> ()) {
- auto* mesh = cur->as<Objects::CMesh> ();
- scriptable = mesh;
- hit = mesh->hitTest (ndc);
- local = mesh->cursorLocalPosition (ndc);
- visible = mesh->getMesh ().groupVisible->value->getBool ();
- if (wantsHitBox) {
- hitBox = mesh->cursorHitBox (ndc, local);
- }
- } else {
- continue;
- }
- const int id = cur->getId ();
- const bool handlers = engine.hasCursorHandlers (*scriptable);
- const auto dispatch = [&] (const char* event) {
- if (handlers) {
- engine.dispatchCursorEvent (event, *scriptable, scenePosition, local, hitBox);
- }
- };
- if (dragging) {
- if (moved && this->m_cursorPressed.contains (id)) {
- dispatch ("cursorMove");
- }
- continue;
- }
- if (!hit) {
- if (released && this->m_cursorPressed.contains (id)) {
- dispatch ("cursorUp");
- }
- if (this->m_cursorInside.erase (id) > 0) {
- dispatch ("cursorLeave");
- }
- continue;
- }
- if (this->m_cursorInside.insert (id).second) {
- dispatch ("cursorEnter");
- }
- if (moved) {
- dispatch ("cursorMove");
- }
- if (pressed) {
- dispatch ("cursorDown");
- this->m_cursorPressed.insert (id);
- } else if (released) {
- dispatch ("cursorUp");
- if (this->m_cursorPressed.contains (id)) {
- dispatch ("cursorClick");
- }
- }
- if (!cur->getObject ().disablePropagation->value->getBool ()) {
- continue;
- }
- const auto visibility
- = this->getContext ().getApp ().getContext ().resolveObjectVisibility (id, cur->getObject ().name);
- if (visibility.value_or (visible) && !this->isHiddenByAncestor (*cur)) {
- break;
- }
- }
- if (!down) {
- this->m_cursorPressed.clear ();
- }
- }
- void CScene::updateMouse (const glm::ivec4& viewport) {
- const glm::dvec2 position = this->cursorPosition ();
- this->m_pointerPositionLast = this->m_pointerPosition;
- this->m_mousePositionViewport = glm::vec2 (position.x - viewport.x, position.y - viewport.y);
- // not clamped: WE stores ScreenToClient over the client size as is (sub_140110630, renderer +140/+144), so a
- // pointer off the window or on another monitor reaches scripts, events and g_PointerPosition outside 0..1; only
- // the parallax clamps it (sub_1401891A0)
- double mouseX = (position.x - viewport.x) / viewport.z;
- // WE flips by mirroring its projection, so the cursor lands on what is shown under it
- if (this->isFlippedHorizontally ()) {
- mouseX = 1.0 - mouseX;
- }
- // GL convention, 0 bottom 1 top
- double normalizedMouseY = (position.y - viewport.y) / viewport.w;
- // the scene buffer holds what the output shows, the visible region maps the cursor onto the scene
- const glm::vec4 output = this->getOutputUVs ();
- const glm::vec4 visible = this->getVisibleUVs ();
- this->m_cursorScreen.x = output.x + mouseX * (output.y - output.x);
- this->m_cursorScreen.y = output.z + normalizedMouseY * (output.w - output.z);
- this->m_mousePositionNormalized.x = visible.x + mouseX * (visible.y - visible.x);
- this->m_mousePositionNormalized.y = visible.z + normalizedMouseY * (visible.w - visible.z);
- // WE's renderer +140/+144: client coords, y from the top
- this->m_mousePosition.x = this->m_cursorScreen.x;
- this->m_mousePosition.y = static_cast<float> (1.0 - normalizedMouseY);
- // g_PointerPosition is ScreenToClient over the client size, never mirrored by alignmentfliph (sub_140110630,
- // uniform 105 reads renderer +140 in sub_1400D8300)
- const float pointerX = this->isFlippedHorizontally () ? 1.0f - this->m_mousePosition.x : this->m_mousePosition.x;
- this->m_pointerPosition = { pointerX, this->m_mousePosition.y };
- }
- glm::vec4 CScene::getVisibleUVs () const {
- const auto& state = this->getState ();
- // 3D scenes keep the whole view, the perspective takes the output's aspect instead
- if (this->m_camera->isPerspective () || state.getViewportWidth () <= 0 || state.getViewportHeight () <= 0) {
- return this->getOutputUVs ();
- }
- const auto uvs = state.getTextureUVs ();
- return { uvs.ustart, uvs.uend, uvs.vstart, uvs.vend };
- }
- glm::vec4 CScene::getVisibleMargins () const {
- const glm::vec4 uvs = this->getVisibleUVs ();
- const float width = this->getCanvasWidth ();
- const float height = this->getCanvasHeight ();
- const bool vflip = this->getState ().isVFlipped ();
- // v runs top down in a flipped state, bottom up otherwise
- return { uvs.x * width, (1.0f - uvs.y) * width, (vflip ? 1.0f - uvs.w : uvs.w) * height,
- (vflip ? uvs.z : 1.0f - uvs.z) * height };
- }
- glm::vec4 CScene::getVisibleCanvasRegion () const {
- glm::vec4 margins = glm::max (this->getVisibleMargins (), glm::vec4 (0.0f));
- const float halfWidth = static_cast<float> (this->getCanvasWidth ()) / 2.0f;
- const float halfHeight = static_cast<float> (this->getCanvasHeight ()) / 2.0f;
- // the margins are on screen, a mirrored projection puts the left one on the canvas' right
- if (this->isFlippedHorizontally ()) {
- std::swap (margins.x, margins.y);
- }
- return { -halfWidth + margins.x, halfWidth - margins.y, -halfHeight + margins.w, halfHeight - margins.z };
- }
- const Data::Model::Properties& CScene::getUserProperties () const {
- return this->getWallpaperData ().project.properties;
- }
- const Scene& CScene::getScene () const { return *this->getWallpaperData ().as<Scene> (); }
- void CScene::expandCanvasToContent (
- const Scene& scene, const float width, const float height, float& canvasWidth, float& canvasHeight
- ) const {
- // keeps the expanded canvas within what the GPU is guaranteed to be able to allocate for a framebuffer
- constexpr float maxCanvasSize = 8192.0f;
- float extentX = width / 2.0f;
- float extentY = height / 2.0f;
- for (const auto& object : scene.objects) {
- if (!object->is<Image> ()) {
- continue;
- }
- const auto* image = object->as<Image> ();
- // children are positioned relative to their parent, and a layer with no declared size takes its
- // texture's, which isn't known this early
- if (image->parent.has_value () || image->size.x <= 0.0f || image->size.y <= 0.0f || image->origin == nullptr
- || image->scale == nullptr) {
- continue;
- }
- const auto visibility
- = this->getContext ().getApp ().getContext ().resolveObjectVisibility (image->id, image->name);
- if (visibility.has_value () && !visibility.value ()) {
- continue;
- }
- if (image->visible != nullptr && !image->visible->value->getBool ()) {
- continue;
- }
- const glm::vec3 origin = image->origin->value->getVec3 ();
- const glm::vec3 scale = image->scale->value->getVec3 ();
- // rotation is ignored on purpose, a rotated layer just keeps the extent its unrotated box has
- extentX = std::max (extentX, std::abs (origin.x - width / 2.0f) + std::abs (scale.x) * image->size.x / 2.0f);
- extentY = std::max (extentY, std::abs (origin.y - height / 2.0f) + std::abs (scale.y) * image->size.y / 2.0f);
- }
- canvasWidth = std::min (std::ceil (extentX * 2.0f), std::max (width, maxCanvasSize));
- canvasHeight = std::min (std::ceil (extentY * 2.0f), std::max (height, maxCanvasSize));
- if (!WallpaperEngine::Data::Utils::sameFloat (canvasWidth, width)
- || !WallpaperEngine::Data::Utils::sameFloat (canvasHeight, height)) {
- sLog.out ("Expanded scene canvas from ", width, "x", height, " to ", canvasWidth, "x", canvasHeight);
- }
- }
- int CScene::getWidth () const { return this->m_camera->getWidth (); }
- int CScene::getHeight () const { return this->m_camera->getHeight (); }
- int CScene::getCanvasWidth () const { return this->m_camera->getCanvasWidth (); }
- int CScene::getCanvasHeight () const { return this->m_camera->getCanvasHeight (); }
- float CScene::getTime () const { return g_Time; }
- float CScene::getDeltaTime () const { return g_Time - g_TimeLast; }
- Objects::PuppetRopeEnvironment CScene::getRopeEnvironment () const {
- const auto& physics = this->getScene ().physics;
- return {
- .gravity = physics.gravityDirection->value->getVec3 () * physics.gravityStrength->value->getFloat (),
- .wind = physics.windEnabled->value->getBool (),
- .windDirection = physics.windDirection->value->getVec3 (),
- .windStrength = physics.windStrength->value->getFloat (),
- .clock = this->getSceneClock (),
- // 0 for perspective scenes (sub_140186C90)
- .width = this->getScene ().camera.projection.isPerspective ? 0.0f : static_cast<float> (this->getWidth ()),
- };
- }
- float CScene::getSceneClock () const {
- // wallpaper64.exe sub_14017FA70 starts over at 0 once it passes 432000 (the frame crossing it is dropped there)
- return std::fmod (std::max (g_Time - this->m_startTime, 0.0f), 432000.0f);
- }
- uint32_t CScene::getFrameCounter () const { return this->m_frameCounter; }
- float CScene::getFps () const {
- const float dt = g_Time - g_TimeLast;
- if (dt <= 1e-6f) {
- return 60.0f;
- }
- return 1.0f / dt;
- }
- const glm::vec2* CScene::getPointerPosition () const { return &this->m_pointerPosition; }
- const glm::vec2* CScene::getPointerPositionLast () const { return &this->m_pointerPositionLast; }
- const glm::vec2* CScene::getMousePositionNormalized () const { return &this->m_mousePositionNormalized; }
- const glm::vec2* CScene::getCursorScreenPosition () const { return &this->m_cursorScreen; }
- glm::vec3 CScene::unprojectCursor () const {
- // WE unprojects the cursor (x, 1 - y) through the view and projection on top of the renderer's stacks, with glm's
- // unProject (depth 0.5 -> NDC 0) for scripts (sub_14018E070 -> sub_14019DF90) and NDC depth 0 for particle control
- // points (sub_14022E3E0). Its projections are Direct3D ones, so NDC depth 0 is the near plane
- const glm::vec2 ndc { this->m_cursorScreen.x * 2.0f - 1.0f,
- cursorClipY (this->m_cursorScreen.y, this->getState ().isVFlipped ()) };
- const auto& camera = this->getCamera ();
- if (camera.isPerspective ()) {
- const glm::vec4 world = glm::inverse (camera.getPerspective () * camera.getView ())
- * glm::vec4 (ndc, DepthRange::nearClip (), 1.0f);
- return glm::vec3 (world) / world.w;
- }
- return glm::vec3 (
- glm::inverse (camera.getProjection () * camera.getLookAt ()) * glm::vec4 (ndc, DepthRange::middleClip (), 1.0f)
- );
- }
- glm::vec3 CScene::getCursorWorldPosition () const {
- const glm::vec3 position = this->unprojectCursor ();
- if (this->getCamera ().isPerspective ()) {
- return position;
- }
- // the 2D layout is WE's world moved to the scene center and flipped vertically (Camera::setWorldView); WE zeroes z
- // in orthographic scenes (renderer flag 0x400)
- return { position.x + static_cast<float> (this->getWidth ()) / 2.0f,
- static_cast<float> (this->getHeight ()) / 2.0f - position.y, 0.0f };
- }
- glm::vec2 CScene::getCursorPixelPosition () const {
- // sub_14018E070 with its screen flag: g_PointerPosition times the window client size, x mirrored on renderer flag
- // 0x800 (horizontal flip). m_mousePosition is already mirrored
- const auto& state = this->getState ();
- return { this->m_mousePosition.x * static_cast<float> (state.getViewportWidth ()),
- this->m_mousePosition.y * static_cast<float> (state.getViewportHeight ()) };
- }
- float CScene::getOutputAspect () const {
- const auto& state = this->getState ();
- if (state.getViewportWidth () <= 0 || state.getViewportHeight () <= 0) {
- return static_cast<float> (this->getCanvasWidth ()) / static_cast<float> (this->getCanvasHeight ());
- }
- return static_cast<float> (state.getViewportWidth ()) / static_cast<float> (state.getViewportHeight ());
- }
- const glm::vec2* CScene::getParallaxPosition () const { return &this->m_parallaxPosition; }
- glm::vec2 CScene::getParallaxOffset (const Object& object) const {
- if (!this->getScene ().camera.parallax.enabled->value->getBool ()) {
- return { 0.0f, 0.0f };
- }
- // every object has a parallaxDepth, (1, 1) unless set (base object constructor sub_14016BE90)
- const auto depthOf = [] (const Object& candidate) -> glm::vec2 {
- if (candidate.is<Image> ()) {
- return candidate.as<Image> ()->parallaxDepth->value->getVec2 ();
- }
- if (candidate.is<Text> ()) {
- return candidate.as<Text> ()->parallaxDepth->value->getVec2 ();
- }
- if (candidate.is<Particle> ()) {
- return candidate.as<Particle> ()->parallaxDepth->value->getVec2 ();
- }
- return candidate.groupParallaxDepth->value->getVec2 ();
- };
- // the topmost ancestor moves its whole subtree, guarded against a malformed parent loop
- constexpr int maxParentDepth = 32;
- const Object* anchor = &object;
- for (int i = 0; i < maxParentDepth && anchor->parent.has_value (); ++i) {
- const CObject* parent = this->getObject (anchor->parent.value ());
- if (parent == nullptr) {
- break;
- }
- anchor = &parent->getObject ();
- }
- const std::optional<glm::vec2> depth = depthOf (*anchor);
- const float amount = this->getScene ().camera.parallax.amount->value->getFloat ();
- const float width = static_cast<float> (this->getWidth ());
- const float height = static_cast<float> (this->getHeight ());
- glm::vec2 shift = (*depth + amount) * this->m_parallaxBias * width;
- if (!this->getContext ().getApp ().getContext ().settings.mouse.disableparallax) {
- // real engine: (origin - cameraPosition) * amount * depth in its y up world (sub_14018AAC0), the camera
- // sitting at the mouse-driven point of the scene. This space is y down, hence the negated y
- const glm::vec3 origin = anchor->origin->value->getVec3 ();
- shift.x += (origin.x - width * 0.5f - this->m_cameraParallax.x * width) * amount * depth->x;
- shift.y -= (origin.y - height * 0.5f - this->m_cameraParallax.y * height) * amount * depth->y;
- }
- return shift;
- }
- const std::vector<CObject*>& CScene::getObjectsByRenderOrder () const { return this->m_objectsByRenderOrder; }
- int CScene::nextFreeLightSlot () const {
- int used = 0;
- for (const auto* object : this->m_objects | std::views::values) {
- if (object->is<Objects::CLight> ()) {
- used |= 1 << object->as<Objects::CLight> ()->getSlot ();
- }
- }
- for (int slot = 0; slot < 4; slot++) {
- if ((used & (1 << slot)) == 0) {
- return slot;
- }
- }
- return 0;
- }
- void CScene::updateLights () {
- // an empty slot is black with radius 1, WE parks it at (0, 100, 0)
- glm::vec4 colors[4];
- glm::vec3 positions[4];
- std::ranges::fill (colors, glm::vec4 (0.0f, 0.0f, 0.0f, 1.0f));
- std::ranges::fill (positions, glm::vec3 (0.0f, 100.0f, 0.0f));
- for (const auto* object : this->m_objects | std::views::values) {
- if (!object->is<Objects::CLight> ()) {
- continue;
- }
- const auto* light = object->as<Objects::CLight> ();
- const auto& data = light->getLight ();
- if (data.type != LightType::Legacy) {
- continue;
- }
- const auto override = this->getContext ().getApp ().getContext ().resolveObjectVisibility (data.id, data.name);
- const bool visible = override.has_value () ? override.value () : data.visible->value->getBool ();
- if (!visible || this->isHiddenByAncestor (*light)) {
- continue;
- }
- const int slot = light->getSlot ();
- const float intensity = data.intensity->value->getFloat ();
- colors[slot]
- = glm::vec4 (glm::vec3 (data.color->value->getVec3 ()) * intensity, data.radius->value->getFloat ());
- positions[slot] = data.origin->value->getVec3 ();
- }
- std::ranges::copy (colors, this->m_lightsColorRadius);
- // radiance is color / distance^2 in the shader, so the color is scaled by radius^2; the fourth light's
- // color rides in the .w of the other three
- for (int i = 0; i < 3; i++) {
- this->m_lightsColorPremultiplied[i] = glm::vec4 (glm::vec3 (colors[i]) * colors[i].w * colors[i].w, 0.0f);
- this->m_lightsColorPremultiplied[i].w = colors[3][i] * colors[3].w * colors[3].w;
- }
- std::ranges::copy (positions, this->m_lightsPosition);
- }
- std::vector<const Light*> CScene::sortedLightingV1Lights () const {
- // sub_140186990 orders the visible lights by type, then shadow/cookie flags (set ones first), then by their own
- // origin along the camera's forward axis
- const auto& camera = this->getCamera ();
- const glm::vec3 forward = camera.isOrthogonal ()
- ? glm::vec3 (0.0f, 0.0f, -1.0f)
- : -glm::vec3 (camera.getView ()[0][2], camera.getView ()[1][2], camera.getView ()[2][2]);
- struct Entry {
- int type;
- int flags;
- float depth;
- const Light* light;
- };
- std::vector<Entry> entries;
- for (const auto* object : this->m_objects | std::views::values) {
- if (!object->is<Objects::CLight> ()) {
- continue;
- }
- const auto& data = object->as<Objects::CLight> ()->getLight ();
- if (data.type == LightType::Legacy) {
- continue;
- }
- const auto override = this->getContext ().getApp ().getContext ().resolveObjectVisibility (data.id, data.name);
- const bool visible = override.has_value () ? override.value () : data.visible->value->getBool ();
- if (!visible || this->isHiddenByAncestor (*object)) {
- continue;
- }
- entries.push_back (
- { static_cast<int> (data.type),
- (data.castShadow->value->getBool () ? 1 : 0) | (data.useCookie->value->getBool () ? 2 : 0),
- glm::dot (data.origin->value->getVec3 (), forward), &data }
- );
- }
- std::ranges::stable_sort (entries, [] (const Entry& a, const Entry& b) {
- if (a.type != b.type) {
- return a.type < b.type;
- }
- if (a.flags != b.flags) {
- return a.flags > b.flags;
- }
- return a.depth < b.depth;
- });
- std::vector<const Light*> lights;
- lights.reserve (entries.size ());
- for (const auto& entry : entries) {
- lights.push_back (entry.light);
- }
- return lights;
- }
- std::shared_ptr<const TextureProvider> CScene::getMissingTexture () const {
- if (this->m_missingTexture == nullptr) {
- this->m_missingTexture = std::make_shared<MissingTexture> ();
- }
- return this->m_missingTexture;
- }
- GLuint CScene::getNullTexture () const {
- if (this->m_nullTexture == GL_NONE) {
- constexpr uint8_t transparent[4] = { 0, 0, 0, 0 };
- glGenTextures (1, &this->m_nullTexture);
- glBindTexture (GL_TEXTURE_2D, this->m_nullTexture);
- glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, transparent);
- glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- }
- return this->m_nullTexture;
- }
- bool CScene::hasNamedLayerBuffer (int id) const {
- if (const auto* created = this->getObject (id); created != nullptr && created->is<Objects::CImage> ()) {
- return !created->as<Objects::CImage> ()->usesPooledBuffer ();
- }
- const auto& objects = this->getScene ().objects;
- const auto model = std::ranges::find_if (objects, [id] (const auto& object) { return object->id == id; });
- if (model == objects.end ()) {
- return false;
- }
- const bool dependency = std::ranges::any_of (objects, [id] (const auto& object) {
- return std::ranges::find (object->dependencies, id) != object->dependencies.end ();
- });
- const auto blended = [] (const auto& colorBlendMode) {
- const int mode = colorBlendMode->value->getInt ();
- return mode != 0 && mode != 31;
- };
- if (dependency || this->hasDistanceFog () || this->hasHeightFog ()) {
- return (*model)->template is<Image> () || (*model)->template is<Text> ();
- }
- if ((*model)->template is<Image> ()) {
- const auto* image = (*model)->template as<Image> ();
- return blended (image->colorBlendMode) || image->renderable.ledSource->value->getBool ()
- || (image->model->puppet.has_value () && !image->effects.empty ());
- }
- if ((*model)->template is<Text> ()) {
- const auto* text = (*model)->template as<Text> ();
- return blended (text->colorBlendMode) || text->renderable.ledSource->value->getBool ();
- }
- return false;
- }
- std::shared_ptr<const TextureProvider> CScene::getLightCookie () const {
- // one cookie for every lit material: the last cookie spot the packing takes (sub_140190C80), its "cookie" or
- // cookie/flashlight1 (sub_14025D080); passes are built before the objects exist, so this goes by the scene data in
- // the packing's order
- const auto& camera = this->getCamera ();
- const glm::vec3 forward = camera.isOrthogonal ()
- ? glm::vec3 (0.0f, 0.0f, -1.0f)
- : -glm::vec3 (camera.getView ()[0][2], camera.getView ()[1][2], camera.getView ()[2][2]);
- std::vector<const Light*> spots;
- for (const auto& object : this->getScene ().objects) {
- if (!object->is<Light> ()) {
- continue;
- }
- const auto* light = object->as<Light> ();
- const auto override
- = this->getContext ().getApp ().getContext ().resolveObjectVisibility (light->id, light->name);
- if (light->type == LightType::Spot
- && (override.has_value () ? override.value () : light->visible->value->getBool ())) {
- spots.push_back (light);
- }
- }
- std::ranges::stable_sort (spots, [&forward] (const Light* a, const Light* b) {
- const int flagsA = (a->castShadow->value->getBool () ? 1 : 0) | (a->useCookie->value->getBool () ? 2 : 0);
- const int flagsB = (b->castShadow->value->getBool () ? 1 : 0) | (b->useCookie->value->getBool () ? 2 : 0);
- if (flagsA != flagsB) {
- return flagsA > flagsB;
- }
- return glm::dot (a->origin->value->getVec3 (), forward) < glm::dot (b->origin->value->getVec3 (), forward);
- });
- const Light* last = nullptr;
- for (int i = 0; i < static_cast<int> (spots.size ()) && i < this->m_lightingV1.spots; i++) {
- if (spots[i]->useCookie->value->getBool ()) {
- last = spots[i];
- }
- }
- // without a cookie spot nothing samples it
- return this->getContext ().resolveTexture (
- last == nullptr || last->cookie.empty () ? "cookie/flashlight1" : last->cookie, this->getScene ().project
- );
- }
- namespace {
- // point light cube faces as assets/shaders/common_pbr_2.h picks them (CalculateProjectedCoordsPoint), the same
- // matrices sub_140190C80 renders the six viewports with: +x, -x, +y, -y, +z, -z
- glm::mat4 pointFaceView (const int face, const glm::vec3& o) {
- switch (face) {
- case 0:
- return { { 0, 0, -1, 0 }, { 0, 1, 0, 0 }, { 1, 0, 0, 0 }, { -o.z, -o.y, o.x, 1 } };
- case 1:
- return { { 0, 0, 1, 0 }, { 0, 1, 0, 0 }, { -1, 0, 0, 0 }, { o.z, -o.y, -o.x, 1 } };
- case 2:
- return { { 1, 0, 0, 0 }, { 0, 0, -1, 0 }, { 0, 1, 0, 0 }, { -o.x, -o.z, o.y, 1 } };
- case 3:
- return { { 1, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, -1, 0, 0 }, { -o.x, o.z, -o.y, 1 } };
- case 4:
- return { { -1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, -1, 0 }, { o.x, -o.y, o.z, 1 } };
- default:
- return { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { -o.x, -o.y, -o.z, 1 } };
- }
- }
- // WE's device projections have 1 at the near plane (sub_14009A360); Volumetrics::spotViewProjection keeps the usual
- // 0 there, this turns one into the other (depth' = 1 - depth)
- glm::mat4 reverseDepth (const glm::mat4& projection) {
- glm::mat4 reverse (1.0f);
- reverse[2][2] = -1.0f;
- reverse[3][2] = 1.0f;
- return reverse * projection;
- }
- }
- void CScene::updateLightingV1 () {
- auto& lighting = this->m_lightingV1;
- const LightingV1 counts = lighting;
- lighting = LightingV1 {};
- lighting.points = counts.points;
- lighting.spots = counts.spots;
- lighting.tubes = counts.tubes;
- lighting.directionals = counts.directionals;
- lighting.spotCookies = counts.spotCookies;
- lighting.spotShadowCookies = counts.spotShadowCookies;
- lighting.spotShadows = counts.spotShadows;
- lighting.directionalShadows = counts.directionalShadows;
- lighting.pointShadows = counts.pointShadows;
- this->m_shadowEntries.clear ();
- this->m_volumeShadows.clear ();
- if (lighting.points + lighting.spots + lighting.tubes + lighting.directionals == 0) {
- return;
- }
- const auto& camera = this->getCamera ();
- const bool orthographic = camera.isOrthogonal ();
- const std::vector<const Light*> lights = this->sortedLightingV1Lights ();
- const bool shadows = this->m_shadowQuality > 0;
- const int tile = ShadowMapping::tileSize (this->m_shadowQuality);
- // renderer +104 (eye) and +352 (camera forward) as sub_14017FA70 leaves them
- const glm::vec3 eye = this->m_fog.eyeWorld;
- const glm::vec3 forward = orthographic
- ? glm::vec3 (0.0f, 0.0f, -1.0f)
- : -glm::vec3 (camera.getView ()[0][2], camera.getView ()[1][2], camera.getView ()[2][2]);
- const int ssc = lighting.spotShadowCookies;
- const int sc = lighting.spotCookies;
- const int ss = lighting.spotShadows;
- // next slot per light class (sub_140190C80): shadowed points first, spots shadow+cookie / cookie / shadow / plain
- // by castshadow | usecookie << 1, shadowed directionals first; ShadowProjection follows the spot classes, cascades
- // after them, a directional light takes one feature for its three cascades
- int pointsLeft = lighting.points;
- int pointSlot[2] = { lighting.pointShadows, 0 };
- int pointShadowsLeft = lighting.pointShadows;
- int pointShadow = 0;
- int spotsLeft = lighting.spots;
- int spotSlot[4] = { ssc + sc + ss, ssc + sc, ssc, 0 };
- int featureSlot[4] = { ssc + sc + ss, ssc + sc, ssc, 0 };
- int featuresLeft = lighting.features ();
- int tube = 0;
- int directionalsLeft = lighting.directionals;
- int directionalSlot[2] = { lighting.directionalShadows, 0 };
- const int featureCapacity = static_cast<int> (std::size (lighting.featureProjection));
- for (const Light* entry : lights) {
- const Light& light = *entry;
- const glm::mat4 world = this->objectWorldMatrix (light);
- const glm::vec3 color = light.color->value->getVec3 () * light.intensity->value->getFloat ();
- const float radius = light.radius->value->getFloat ();
- const float exponent = light.exponent->value->getFloat ();
- const glm::vec3 origin (world[3]);
- const bool shadowed = shadows && light.castShadow->value->getBool ();
- switch (light.type) {
- case LightType::Point:
- {
- if (pointsLeft == 0) {
- break;
- }
- pointsLeft--;
- if (const int slot = pointSlot[shadowed ? 1 : 0]++; slot < lighting.points) {
- lighting.pointColor[slot] = glm::vec4 (color, radius);
- lighting.pointOrigin[slot] = glm::vec4 (origin, exponent);
- }
- if (!shadowed || pointShadowsLeft == 0) {
- break;
- }
- // sub_14025D420: a fov a bit over 90 degrees per quality, aspect 1, near the light source size (1
- // in orthographic scenes), far the radius
- pointShadowsLeft--;
- const int quality = this->m_shadowQuality;
- const float fov = quality <= 2 ? 94.0f : quality == 3 ? 92.0f : 91.2f;
- const float near
- = orthographic ? 1.0f : std::max (0.05f, light.lightSourceSize->value->getFloat ());
- const float far = std::max (radius, near + 0.01f);
- const glm::mat4 projection = ShadowMapping::perspective (fov * 0.017453292f, 1.0f, near, far);
- ShadowMapping::Entry shadow { .point = true, .size = tile };
- lighting.pointShadowProjection[pointShadow]
- = glm::vec4 (projection[2][2], projection[3][2], projection[2][3], projection[3][3]);
- shadow.transform = &lighting.pointShadowProjectionTransform[pointShadow];
- pointShadow++;
- for (int face = 0; face < 6; face++) {
- shadow.viewProjection[face] = projection * pointFaceView (face, origin);
- }
- this->m_volumeShadows[&light]
- = { .atlasTransform = shadow.transform,
- .pointProjection = lighting.pointShadowProjection[pointShadow - 1] };
- this->m_shadowEntries.push_back (shadow);
- break;
- }
- case LightType::Spot:
- {
- if (spotsLeft == 0) {
- break;
- }
- spotsLeft--;
- const int type
- = (light.castShadow->value->getBool () ? 1 : 0) | (light.useCookie->value->getBool () ? 2 : 0);
- const int kind = type & (shadows ? 3 : 2);
- // cosines of the cone angles in the .w, the direction is the world matrix's x column as it is
- if (const int slot = spotSlot[kind]++; slot < lighting.spots) {
- lighting.spotColor[slot] = glm::vec4 (color, radius);
- lighting.spotOrigin[slot]
- = glm::vec4 (origin, std::cos (light.innerCone->value->getFloat () * 0.017453292f));
- lighting.spotDirection[slot] = glm::vec4 (
- glm::vec3 (world[0]), std::cos (light.outerCone->value->getFloat () * 0.017453292f)
- );
- lighting.spotExponent[slot] = glm::vec4 (exponent, 0.0f, 0.0f, 0.0f);
- }
- if ((!shadowed && !light.useCookie->value->getBool ()) || featuresLeft == 0) {
- break;
- }
- featuresLeft--;
- const int feature = featureSlot[kind]++;
- if (feature >= featureCapacity) {
- break;
- }
- lighting.featureProjection[feature]
- = reverseDepth (Volumetrics::spotViewProjection (light, world, orthographic));
- if (shadowed) {
- ShadowMapping::Entry shadow { .size = tile,
- .transform = &lighting.featureProjectionTransform[feature] };
- shadow.viewProjection[0] = lighting.featureProjection[feature];
- this->m_volumeShadows[&light]
- = { .matrix = lighting.featureProjection[feature], .atlasTransform = shadow.transform };
- this->m_shadowEntries.push_back (shadow);
- }
- break;
- }
- case LightType::Tube:
- if (tube < lighting.tubes) {
- lighting.tubeColor[tube] = glm::vec4 (color, radius);
- lighting.tubeOriginA[tube] = glm::vec4 (origin, exponent);
- lighting.tubeOriginB[tube]
- = glm::vec4 (glm::vec3 (world * glm::vec4 (light.controlPoint->value->getVec3 (), 1.0f)), 0.0f);
- tube++;
- }
- break;
- case LightType::Directional:
- {
- if (directionalsLeft == 0) {
- break;
- }
- directionalsLeft--;
- if (const int slot = directionalSlot[shadowed ? 1 : 0]++; slot < lighting.directionals) {
- lighting.directionalColor[slot] = glm::vec4 (color, 1.0f);
- lighting.directionalDirection[slot] = glm::vec4 (-glm::vec3 (world[0]), 0.0f);
- }
- if (!shadowed || featuresLeft == 0) {
- break;
- }
- featuresLeft--;
- // sub_14025D370 / sub_140190C80: each cascade is a square of its distance, centered half of it
- // ahead of the eye (forward along the light half counted, z 0 in 2D), snapped to texels on the
- // light's y/z; view down the light's x axis like a spot, ortho box (sub_14009A630) of +-distance/2
- // and depth +-range/2
- const float cascade0 = light.cascadeDistance[0]->value->getFloat ();
- const float cascade1 = light.cascadeDistance[1]->value->getFloat ();
- const float cascade2 = light.cascadeDistance[2]->value->getFloat ();
- const glm::vec2 ranges[3] = {
- { cascade0, cascade1 * 4.0f },
- { cascade1, cascade1 * 4.0f },
- { cascade2, std::max (cascade2 * 1.5f, cascade1 * 4.0f) },
- };
- const glm::vec3 direction = glm::normalize (glm::vec3 (world[0]));
- const glm::vec3 y (world[1]);
- const glm::vec3 z (world[2]);
- const glm::vec3 rows[3]
- = { Volumetrics::approximateNormalize (z), Volumetrics::approximateNormalize (y),
- Volumetrics::approximateNormalize (-glm::vec3 (world[0])) };
- const glm::vec3 ahead = forward - direction * (glm::dot (forward, direction) * 0.5f);
- for (const glm::vec2& range : ranges) {
- const float half = range.x * 0.5f;
- glm::vec3 center = eye + ahead * half;
- if (orthographic) {
- center.z = 0.0f;
- }
- const float texel = range.x / static_cast<float> (tile);
- const float alongZ = glm::dot (z, center);
- const float alongY = glm::dot (y, center);
- center -= y * std::fmod (alongY, texel);
- center -= z * std::fmod (alongZ, texel);
- glm::mat4 view (1.0f);
- for (int row = 0; row < 3; row++) {
- for (int column = 0; column < 3; column++) {
- view[column][row] = rows[row][column];
- }
- view[3][row] = -glm::dot (rows[row], center);
- }
- glm::mat4 projection (1.0f);
- projection[0][0] = 1.0f / half;
- projection[1][1] = 1.0f / half;
- projection[2][2] = 1.0f / range.y;
- projection[3][2] = 0.5f;
- const int feature = featureSlot[0]++;
- if (feature >= featureCapacity) {
- continue;
- }
- lighting.featureProjection[feature] = projection * view;
- ShadowMapping::Entry shadow { .size = tile,
- .transform = &lighting.featureProjectionTransform[feature] };
- shadow.viewProjection[0] = lighting.featureProjection[feature];
- this->m_shadowEntries.push_back (shadow);
- }
- break;
- }
- default:
- break;
- }
- }
- }
- const CScene::LayerTarget* CScene::getLayerTarget () const {
- return this->m_layerTargets.empty () ? nullptr : &this->m_layerTargets.back ();
- }
- bool CScene::isDrawnByPassthroughLayer (const CObject& object) const {
- const Object* current = &object.getObject ();
- // set when the parent has flag 2 or 4 (sub_1401DD9A0), so any passthrough ancestor
- for (int depth = 0; current->parent.has_value () && depth < 64; depth++) {
- const auto* parent = this->getObject (current->parent.value ());
- if (parent == nullptr) {
- return false;
- }
- // one set up without children leaves later ones to the scene
- if (isPassthroughImage (*parent)) {
- return parent->as<Objects::CImage> ()->drawsPassthroughChildren ();
- }
- current = &parent->getObject ();
- }
- return false;
- }
- std::vector<CObject*> CScene::childrenOf (int id) const {
- std::vector<CObject*> children;
- const auto list = this->m_children.find (id);
- if (list != this->m_children.end ()) {
- for (const int child : list->second) {
- if (const auto it = this->m_objects.find (child);
- it != this->m_objects.end () && it->second->getObject ().parent == id) {
- children.push_back (it->second);
- }
- }
- }
- // unlisted objects after the listed ones
- for (auto* object : this->m_objectsByRenderOrder) {
- if (object->getObject ().parent == id && std::ranges::find (children, object) == children.end ()) {
- children.push_back (object);
- }
- }
- return children;
- }
- void CScene::detachChild (const CObject& child) {
- if (const auto& parent = child.getObject ().parent; parent.has_value ()) {
- if (const auto list = this->m_children.find (*parent); list != this->m_children.end ()) {
- std::erase (list->second, child.getId ());
- }
- }
- }
- void CScene::attachChild (const CObject& child) {
- const auto& parent = child.getObject ().parent;
- if (!parent.has_value ()) {
- return;
- }
- // sub_1401DDA60 / sub_140196C40: after the parent's existing children in scene order, at the end when the child
- // comes first or a root object is met
- auto& list = this->m_children[*parent];
- std::erase (list, child.getId ());
- const auto layers = this->getLayers ();
- const auto from
- = std::ranges::find_if (layers, [&parent] (const CObject* cur) { return cur->getId () == *parent; });
- size_t position = list.size ();
- if (from != layers.end ()) {
- size_t count = 0;
- for (auto it = std::next (from); it != layers.end (); ++it) {
- if (*it == &child) {
- position = std::min (count, list.size ());
- break;
- }
- const auto& itsParent = (*it)->getObject ().parent;
- if (itsParent == parent) {
- count++;
- } else if (!itsParent.has_value ()) {
- break;
- }
- }
- }
- list.insert (list.begin () + static_cast<std::ptrdiff_t> (position), child.getId ());
- }
- void CScene::renderPassthroughChildren (int layerId, const LayerTarget& target) {
- this->m_layerTargets.push_back (target);
- // direct children only when visible (slot 13), their subtrees unless they are passthrough layers themselves,
- // which draw their own (sub_1401ECB20)
- for (auto* child : this->childrenOf (layerId)) {
- this->renderPassthroughChild (child);
- if (!isPassthroughImage (*child)) {
- this->renderPassthroughSubtree (child->getId (), 1);
- }
- }
- this->m_layerTargets.pop_back ();
- }
- void CScene::renderPassthroughSubtree (int parentId, int depth) {
- if (depth >= 64) {
- return;
- }
- for (auto* child : this->childrenOf (parentId)) {
- this->renderPassthroughChild (child);
- if (!isPassthroughImage (*child)) {
- this->renderPassthroughSubtree (child->getId (), depth + 1);
- }
- }
- }
- void CScene::renderPassthroughChild (CObject* object) {
- const auto& debug = this->getContext ().getApp ().getContext ().settings.render.debug;
- if (debug.objectFilter.has_value () && object->getId () != debug.objectFilter.value ()) {
- return;
- }
- if (std::ranges::find (debug.skipObjects, object->getId ()) != debug.skipObjects.end ()) {
- return;
- }
- const auto visibility = this->getContext ().getApp ().getContext ().resolveObjectVisibility (
- object->getId (), object->getObject ().name
- );
- if ((visibility.has_value () && !visibility.value ()) || this->isHiddenByAncestor (*object)) {
- return;
- }
- // lights go into the shared light buffer (sub_140196CE0 from sub_1401ECB20), added onto the scene before the next
- // non-light top level object; a light before any other child still sees the scene's view projection (live WE)
- if (object->is<Objects::CLight> ()) {
- const auto& target = this->m_layerTargets.back ();
- this->renderLightVolume (
- *object->as<Objects::CLight> (),
- target.viewProjectionApplied ? target.viewProjection : this->getWorldViewProjection ()
- );
- return;
- }
- timeStep ("render " + object->getObject ().name, [&] { object->render (); });
- // nested layers push and pop their own targets while rendering, look it up again
- this->m_layerTargets.back ().viewProjectionApplied = true;
- }
- void CScene::renderLightVolume (const Objects::CLight& object, const glm::mat4& viewProjection) {
- const auto& light = object.getLight ();
- // WE sends every light through the same code, but only point and spot lights get a volume matrix
- // (sub_14025D420). Tubes and directional lights would draw the cone through a matrix nothing sets, left out
- if ((light.type != LightType::Point && light.type != LightType::Spot) || !light.castVolumetrics->value->getBool ()
- || !light.visible->value->getBool ()) {
- return;
- }
- timeStep ("volumetrics " + light.name, [&] {
- const auto shadow = this->m_volumeShadows.find (&light);
- this->m_volumetrics->renderLight (
- light, this->objectWorldMatrix (light), viewProjection,
- shadow != this->m_volumeShadows.end () ? &shadow->second : nullptr
- );
- });
- }
- bool CScene::isTransparentSorted (const CObject& object) {
- const auto cached = this->m_transparentSorted.find (&object);
- if (cached != this->m_transparentSorted.end ()) {
- return cached->second;
- }
- bool sorted = false;
- // particles, lights and text always, images by their material's blending or as passthrough layers without
- if (object.is<Objects::CParticle> () || object.is<Objects::CLight> () || object.is<Objects::CText> ()) {
- sorted = true;
- } else if (object.is<Objects::CImage> ()) {
- const auto& image = object.as<Objects::CImage> ()->getImage ();
- const auto& passes = image.model->material->passes;
- const BlendingMode blending = passes.empty () ? BlendingMode_Normal : passes.front ()->blending;
- sorted = blending == BlendingMode_Translucent || blending == BlendingMode_Additive
- || (image.model->passthrough && !image.copyBackground->value->getBool ());
- }
- this->m_transparentSorted.emplace (&object, sorted);
- return sorted;
- }
- std::vector<CObject*> CScene::sortedByDepth (std::vector<CObject*> objects) const {
- // key = origin . view direction, the renderer keeps -row 2 of the view matrix for it (sub_14017FA70); fullscreen
- // and project layers (object flag 0x200) get -inf. Stable, largest key first
- const glm::mat4& view = this->getCamera ().getView ();
- const glm::vec3 forward = -glm::vec3 (view[0][2], view[1][2], view[2][2]);
- std::vector<std::pair<float, CObject*>> keyed;
- keyed.reserve (objects.size ());
- for (auto* object : objects) {
- float key = glm::dot (object->getObject ().origin->value->getVec3 (), forward);
- if (object->is<Objects::CImage> ()) {
- const auto& model = *object->as<Objects::CImage> ()->getImage ().model;
- if (model.fullscreen || model.projectlayer) {
- key = -std::numeric_limits<float>::infinity ();
- }
- }
- keyed.emplace_back (key, object);
- }
- std::ranges::stable_sort (keyed, [] (const auto& a, const auto& b) { return a.first > b.first; });
- for (size_t i = 0; i < keyed.size (); i++) {
- objects[i] = keyed[i].second;
- }
- return objects;
- }
- bool CScene::quadContainsPoint (const glm::mat4& mvp, const glm::vec2& half, const glm::vec2& ndc) {
- const glm::vec2 corners[] = { { -half.x, -half.y }, { half.x, -half.y }, { half.x, half.y }, { -half.x, half.y } };
- glm::vec2 projected[4];
- for (int i = 0; i < 4; i++) {
- const glm::vec4 clip = mvp * glm::vec4 (corners[i], 0.0f, 1.0f);
- if (clip.w <= 0.0f) {
- return false;
- }
- projected[i] = glm::vec2 (clip) / clip.w;
- }
- bool positive = false;
- bool negative = false;
- for (int i = 0; i < 4; i++) {
- const glm::vec2 edge = projected[(i + 1) % 4] - projected[i];
- const glm::vec2 toPoint = ndc - projected[i];
- const float cross = edge.x * toPoint.y - edge.y * toPoint.x;
- positive |= cross > 0.0f;
- negative |= cross < 0.0f;
- }
- // a quad seen edge on has no area and nothing to hit
- const glm::vec2 diagonalA = projected[2] - projected[0];
- const glm::vec2 diagonalB = projected[3] - projected[1];
- return !(positive && negative) && (diagonalA.x * diagonalB.y - diagonalA.y * diagonalB.x) != 0.0f;
- }
- std::optional<glm::vec2> CScene::quadPlanePoint (const glm::mat4& mvp, const glm::vec2& ndc) {
- // clip = x * col0 + y * col1 + col3, and the point lands on ndc when clip.xy = ndc * clip.w
- const glm::vec4& ax = mvp[0];
- const glm::vec4& ay = mvp[1];
- const glm::vec4& at = mvp[3];
- const float a = ax.x - ndc.x * ax.w;
- const float b = ay.x - ndc.x * ay.w;
- const float c = ax.y - ndc.y * ax.w;
- const float d = ay.y - ndc.y * ay.w;
- const float det = a * d - b * c;
- if (std::abs (det) <= 1.1920929e-7f) {
- return std::nullopt;
- }
- const float ex = ndc.x * at.w - at.x;
- const float ey = ndc.y * at.w - at.y;
- const glm::vec2 point = { (ex * d - b * ey) / det, (a * ey - ex * c) / det };
- if (point.x * ax.w + point.y * ay.w + at.w <= 0.0f) {
- return std::nullopt;
- }
- return point;
- }
- bool CScene::isHiddenByAncestor (const CObject& object) const {
- const auto& appContext = this->getContext ().getApp ().getContext ();
- const Object* current = &object.getObject ();
- // objects nest through "parent"; a child is only shown while every group above it is, whatever
- // its own visible property says (the guard keeps a malformed parent loop from spinning)
- for (int depth = 0; current->parent.has_value () && depth < 64; depth++) {
- const auto* parent = this->getObject (current->parent.value ());
- if (parent == nullptr) {
- return false;
- }
- const Object& data = parent->getObject ();
- const auto override = appContext.resolveObjectVisibility (parent->getId (), data.name);
- bool visible;
- if (override.has_value ()) {
- visible = override.value ();
- } else if (data.is<Image> ()) {
- visible = data.as<Image> ()->visible->value->getBool ();
- } else if (data.is<Text> ()) {
- visible = data.as<Text> ()->visible->value->getBool ();
- } else if (data.is<Particle> ()) {
- visible = data.as<Particle> ()->visible->value->getBool ();
- } else {
- visible = data.groupVisible->value->getBool ();
- }
- if (!visible) {
- return true;
- }
- current = &data;
- }
- return false;
- }
- const CObject* CScene::getObject (int id) const {
- const auto object = this->m_objects.find (id);
- return object == this->m_objects.end () ? nullptr : object->second;
- }
- CObject* CScene::getObject (int id) {
- const auto object = this->m_objects.find (id);
- return object == this->m_objects.end () ? nullptr : object->second;
- }
- void CScene::setSoundPlaying (int id, bool playing) {
- this->m_soundPlayRequests[id] = playing;
- const auto object = this->m_objects.find (id);
- if (object == this->m_objects.end () || !object->second->is<Objects::CSound> ()) {
- return;
- }
- auto* sound = object->second->as<Objects::CSound> ();
- if (playing) {
- sound->play ();
- } else {
- sound->stop ();
- }
- }
- void CScene::pauseSound (int id) {
- if (auto* sound = this->getObject (id); sound != nullptr && sound->is<Objects::CSound> ()) {
- sound->as<Objects::CSound> ()->pause ();
- }
- }
- bool CScene::isSoundPlaying (int id, bool startSilent) const {
- if (const auto* sound = this->getObject (id); sound != nullptr && sound->is<Objects::CSound> ()) {
- return sound->as<Objects::CSound> ()->isPlaying ();
- }
- return this->getSoundPlayRequest (id).value_or (!startSilent);
- }
- std::optional<bool> CScene::getSoundPlayRequest (int id) const {
- const auto request = this->m_soundPlayRequests.find (id);
- return request == this->m_soundPlayRequests.end () ? std::nullopt : std::optional<bool> (request->second);
- }
- std::optional<float> CScene::spriteSheetSyncDelay () const {
- if (!this->getScene ().spriteSheetRefreshSync) {
- return std::nullopt;
- }
- // only the first image object, animated or not
- for (const auto* object : this->getLayers ()) {
- if (!object->is<Objects::CImage> ()) {
- continue;
- }
- const auto* image = object->as<Objects::CImage> ();
- const auto texture = image->getTexture ();
- if (texture == nullptr || !texture->isAnimated () || texture->getFrames ().empty ()) {
- return 0.0f;
- }
- const auto [frame, elapsed] = image->sharedTextureFrame ();
- return std::max (static_cast<float> (texture->getFrames ()[frame]->frametime) - elapsed, 0.0f);
- }
- return 0.0f;
- }
- std::vector<CObject*> CScene::getLayers () const { return this->m_objectsByRenderOrder; }
- int CScene::getObjectIndex (const CObject* object) const {
- const auto layers = this->getLayers ();
- const auto it = std::ranges::find (layers, object);
- if (it == layers.end ()) {
- return -1;
- }
- return static_cast<int> (std::distance (layers.begin (), it));
- }
- void CScene::appendLayer (CObject* object) { this->m_objectsByRenderOrder.push_back (object); }
- Render::CObject* CScene::buildLayer (JSON layerJson) {
- const int id = this->m_nextDynamicLayerId++;
- layerJson["id"] = id;
- if (!layerJson.contains ("name") || !layerJson["name"].is_string ()) {
- layerJson["name"] = "scriptlayer_" + std::to_string (id);
- }
- if (!layerJson.contains ("visible")) {
- layerJson["visible"] = true;
- }
- auto objectData = ObjectParser::parse (layerJson, this->getScene ().project);
- Render::CObject* renderObject = this->createObject (*objectData);
- if (renderObject == nullptr) {
- return nullptr;
- }
- this->m_dynamicObjectData.emplace (id, std::move (objectData));
- this->appendLayer (renderObject);
- return renderObject;
- }
- // scripts write into createLayer()'s result without a null check, so failures get a scriptable, non-rendering
- // placeholder
- Render::CObject* CScene::createPlaceholderLayer () {
- try {
- const int id = this->m_nextDynamicLayerId++;
- const JSON placeholderJson
- = { { "id", id }, { "name", "scriptlayer_" + std::to_string (id) }, { "visible", true } };
- auto objectData = ObjectParser::parse (placeholderJson, this->getScene ().project);
- auto* renderObject = new Scripting::ScriptableObject (*this, *objectData);
- this->m_objects.emplace (renderObject->getId (), renderObject);
- this->m_dynamicObjectData.emplace (id, std::move (objectData));
- this->appendLayer (renderObject);
- return renderObject;
- } catch (const std::exception& placeholderError) {
- sLog.error ("createLayer placeholder fallback also failed: ", placeholderError.what ());
- return nullptr;
- }
- }
- Render::CObject* CScene::createLayer (const std::string& imagePath) {
- // createObject() throws on a missing asset, and unwinding a C++ exception through the V8 callback is undefined
- // behavior
- try {
- if (const auto cached = this->m_createLayerAliases.find (imagePath);
- cached != this->m_createLayerAliases.end ()) {
- return this->buildLayer ({ { "image", cached->second } });
- }
- return this->buildLayer ({ { "image", imagePath } });
- } catch (const std::exception& e) {
- // scripts written against a workshop dependency's original layout use the un-prefixed name, try the prefixed
- // copy first
- if (const auto alias = this->getScene ().project.assetLocator->resolveWorkshopDependencyAlias (imagePath);
- alias.has_value () && !this->m_createLayerAliases.contains (imagePath)) {
- try {
- sLog.out (
- "createLayer: '", imagePath, "' not found, found and using workshop-dependency copy '",
- alias->string (), "' instead"
- );
- auto* layer = this->buildLayer ({ { "image", alias->string () } });
- this->m_createLayerAliases.emplace (imagePath, alias->string ());
- return layer;
- } catch (const std::exception& aliasError) {
- sLog.error (
- "createLayer: workshop-dependency copy '", alias->string (), "' also failed: ", aliasError.what ()
- );
- }
- } else {
- sLog.error (
- "createLayer failed for '", imagePath, "', falling back to an invisible placeholder: ", e.what ()
- );
- }
- return this->createPlaceholderLayer ();
- }
- }
- Render::CObject* CScene::createLayerFromConfig (JSON config) {
- // WE (scenescript64 sub_180011340): a config with "color" and no layer type key becomes a solid layer
- static constexpr std::array layerTypes
- = { "model", "particle", "sprite", "image", "text", "light", "sound", "camera" };
- if (config.contains ("color")
- && std::ranges::none_of (layerTypes, [&config] (const char* key) { return config.contains (key); })) {
- // ortho scenes get the depth tested material (sub_181633290)
- config["image"] = this->getCamera ().isOrthogonal () ? "models/util/solidlayer_depthtest.json"
- : "models/util/solidlayer.json";
- }
- try {
- return this->buildLayer (config);
- } catch (const std::exception& e) {
- sLog.error (
- "createLayer failed for ", config.dump (), ", falling back to an invisible placeholder: ", e.what ()
- );
- return this->createPlaceholderLayer ();
- }
- }
- void CScene::sortLayer (CObject* object, int index) {
- const auto current = std::ranges::find (this->m_objectsByRenderOrder, object);
- if (current == this->m_objectsByRenderOrder.end ()) {
- return;
- }
- this->m_objectsByRenderOrder.erase (current);
- // index counts script-visible layers, so place it before whichever layer currently holds that slot
- const auto layers = this->getLayers ();
- const int clampedIndex = std::clamp (index, 0, static_cast<int> (layers.size ()));
- const auto before = clampedIndex < static_cast<int> (layers.size ())
- ? std::ranges::find (this->m_objectsByRenderOrder, layers[clampedIndex])
- : this->m_objectsByRenderOrder.end ();
- this->m_objectsByRenderOrder.insert (before, object);
- }
- void CScene::loadStaticCamera () {
- if (this->m_staticCameraLoaded) {
- return;
- }
- this->m_staticCameraLoaded = true;
- // 2D scenes without camera paths get the reset camera, the others scene.json's (sub_140186C90); zoom stays
- if (!this->m_camera->isPerspective () && this->getScene ().camera.paths.empty ()) {
- this->m_staticCamera.eye = glm::vec3 (0.0f);
- this->m_staticCamera.center = glm::vec3 (0.0f, 0.0f, -1.0f);
- this->m_staticCamera.up = glm::vec3 (0.0f, 1.0f, 0.0f);
- } else {
- this->m_staticCamera.eye = this->m_camera->getConfiguredEye ();
- this->m_staticCamera.center = this->m_camera->getCenter ();
- this->m_staticCamera.up = this->m_camera->getUp ();
- }
- }
- uint32_t CScene::createModelData (const ModelData::Config& config, ModelData::Error& error) {
- return this->m_modelData.create (
- config,
- [this] (const std::string& material, uint32_t format) {
- return this->checkModelDataMaterial (material, format);
- },
- error
- );
- }
- void CScene::applyModelData (uint32_t token, const ModelData::Config& config, bool replace, ModelData::Error& error) {
- this->m_modelData.apply (
- token, config, replace,
- [this] (const std::string& material, uint32_t format) {
- return this->checkModelDataMaterial (material, format);
- },
- error
- );
- }
- void CScene::destroyModelData (uint32_t token) { this->m_modelData.release (token); }
- std::shared_ptr<ModelData::Model> CScene::acquireModelData (int token) { return this->m_modelData.acquire (token); }
- std::shared_ptr<const std::vector<char>> CScene::readModelFile (const std::string& filename) {
- if (const auto it = this->m_modelFiles.find (filename); it != this->m_modelFiles.end ()) {
- return it->second;
- }
- const auto stream = this->getScene ().project.assetLocator->read (filename);
- auto data = std::make_shared<std::vector<char>> ();
- char buffer[65536];
- while (stream->read (buffer, sizeof (buffer)) || stream->gcount () > 0) {
- data->insert (data->end (), buffer, buffer + stream->gcount ());
- }
- if (this->m_loading) {
- this->m_modelFiles.emplace (filename, data);
- }
- return data;
- }
- void CScene::releaseModelData (uint32_t token) { this->m_modelData.release (token); }
- ModelData::Error CScene::checkModelDataMaterial (const std::string& material, uint32_t format) {
- const auto key = std::make_pair (material, format);
- if (const auto cached = this->m_modelDataMaterialChecks.find (key);
- cached != this->m_modelDataMaterialChecks.end ()) {
- return cached->second;
- }
- // semantic of every vertex format bit and of every attribute name WE's shader translation knows (0x140482AF0,
- // 0x140484A90), sub_1400D7B60 only compares semantic names
- static const std::pair<uint32_t, const char*> formatSemantics[] = {
- { 0x1, "POSITION" }, { 0x10000, "POSITION" }, { 0x2000000, "POSITION" }, { 0x2, "NORMAL" },
- { 0x4, "TANGENT" }, { 0x800000, "BLENDINDICES" }, { 0x1000000, "BLENDWEIGHT" }, { 0x8, "TEXCOORD" },
- { 0x10, "TEXCOORD" }, { 0x20, "TEXCOORD" }, { 0x40, "TEXCOORD" }, { 0x80, "TEXCOORD" },
- { 0x100, "TEXCOORD" }, { 0x200, "TEXCOORD" }, { 0x400, "TEXCOORD" }, { 0x800, "TEXCOORD" },
- { 0x1000, "TEXCOORD" }, { 0x2000, "TEXCOORD" }, { 0x4000, "TEXCOORD" }, { 0x20000, "TEXCOORD" },
- { 0x40000, "TEXCOORD" }, { 0x80000, "TEXCOORD" }, { 0x100000, "TEXCOORD" }, { 0x200000, "TEXCOORD" },
- { 0x400000, "TEXCOORD" }, { 0x8000, "COLOR" },
- };
- static const std::map<std::string, std::string> attributeSemantics = {
- { "a_Position", "POSITION" }, { "a_PositionVec4", "POSITION" },
- { "a_PositionC1", "POSITION" }, { "a_Normal", "NORMAL" },
- { "a_Tangent4", "TANGENT" }, { "a_BlendIndices", "BLENDINDICES" },
- { "a_BlendWeights", "BLENDWEIGHT" }, { "a_TexCoord", "TEXCOORD" },
- { "a_TexCoordVec3", "TEXCOORD" }, { "a_TexCoordVec4", "TEXCOORD" },
- { "a_TexCoordC1", "TEXCOORD" }, { "a_TexCoordVec3C1", "TEXCOORD" },
- { "a_TexCoordVec4C1", "TEXCOORD" }, { "a_TexCoordC2", "TEXCOORD" },
- { "a_TexCoordVec3C2", "TEXCOORD" }, { "a_TexCoordVec4C2", "TEXCOORD" },
- { "a_TexCoordC3", "TEXCOORD" }, { "a_TexCoordVec3C3", "TEXCOORD" },
- { "a_TexCoordVec4C3", "TEXCOORD" }, { "a_TexCoordC4", "TEXCOORD" },
- { "a_TexCoordVec3C4", "TEXCOORD" }, { "a_TexCoordVec4C4", "TEXCOORD" },
- { "a_TexCoordC5", "TEXCOORD" }, { "a_TexCoordVec3C5", "TEXCOORD" },
- { "a_TexCoordVec4C5", "TEXCOORD" }, { "a_Color", "COLOR" },
- };
- static const std::regex input (R"(\bin\s+\w+\s+(a_\w+)\s*;)");
- ModelData::Error result = ModelData::Error::None;
- const auto& project = this->getScene ().project;
- const auto loaded = Data::Parsers::MaterialParser::load (project, material);
- if (loaded == nullptr || loaded->passes.empty ()) {
- result = ModelData::Error::InvalidMaterial;
- } else {
- // the program WE compiles for the material by itself (sub_1401A5C40): the pass's combos plus the scene wide
- // defines every pass gets
- const auto& pass = *loaded->passes.front ();
- ComboMap combos = pass.combos;
- const ComboMap overrideCombos;
- const TextureMap overrideTextures;
- static const ShaderConstantMap noConstants;
- if (this->getCamera ().isOrthogonal ()) {
- combos.insert_or_assign ("SCENE_ORTHO", 1);
- }
- if (this->isHDR ()) {
- combos.insert_or_assign ("HDR", 1);
- }
- try {
- Shaders::Shader shader (
- *project.assetLocator, pass.shader, combos, overrideCombos, pass.textures, overrideTextures, noConstants
- );
- const auto sources
- = Shaders::GLSLContext::get ().toGlsl (shader.vertex (), shader.fragment (), pass.shader);
- std::set<std::string> provided;
- for (const auto& [bit, semantic] : formatSemantics) {
- if (format & bit) {
- provided.insert (semantic);
- }
- }
- // the translation keeps the original source in an "#if 0" block at the end, that doesn't count
- const std::string code = sources.vertex.substr (0, sources.vertex.rfind ("\n#if 0"));
- for (std::sregex_iterator it (code.begin (), code.end (), input), end; it != end; ++it) {
- const std::string name = (*it)[1].str ();
- const auto semantic = attributeSemantics.find (name);
- const std::regex use ("\\b" + name + "\\b");
- const auto uses
- = std::distance (std::sregex_iterator (code.begin (), code.end (), use), std::sregex_iterator ());
- // the D3D input signature only has the inputs the shader reads: live WE takes a position-only shape
- // with util/flat.json, whose flat.vert declares a_Color but only reads it with VERTEXCOLOR
- if (uses < 2) {
- continue;
- }
- if (semantic != attributeSemantics.end () && !provided.contains (semantic->second)) {
- result = ModelData::Error::ShaderExpectingMoreVertexData;
- break;
- }
- }
- } catch (const std::exception& e) {
- sLog.error ("Model data material ", material, " has no usable shader: ", e.what ());
- result = ModelData::Error::InvalidMaterial;
- }
- }
- this->m_modelDataMaterialChecks.emplace (key, result);
- return result;
- }
- bool CScene::wantsPointerButtons () const {
- return this->m_scriptEngine != nullptr && this->m_scriptEngine->wantsPointerButtons ();
- }
- void CScene::setAudioPolicy (bool muted, std::optional<int> ambientVolume) {
- const std::optional<int> volume = muted ? std::optional<int> (0) : ambientVolume;
- for (const auto& entry : this->m_objects) {
- if (entry.second->is<Objects::CSound> ()) {
- entry.second->as<Objects::CSound> ()->setVolumeOverride (volume);
- }
- }
- }
|