bgfx.cpp 176 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129
  1. /*
  2. * Copyright 2011-2026 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. #include <bx/platform.h>
  6. #include "bgfx_p.h"
  7. #include <bgfx/embedded_shader.h>
  8. #include <bx/file.h>
  9. #include <bx/mutex.h>
  10. #include "topology.h"
  11. #if BX_PLATFORM_OSX || BX_PLATFORM_IOS || BX_PLATFORM_VISIONOS
  12. # include <objc/message.h>
  13. #elif BX_PLATFORM_WINDOWS
  14. # ifndef WIN32_LEAN_AND_MEAN
  15. # define WIN32_LEAN_AND_MEAN
  16. # endif // WIN32_LEAN_AND_MEAN
  17. # include <windows.h>
  18. # include <psapi.h>
  19. #elif BX_PLATFORM_LINUX
  20. # include <link.h> // dl_iterate_phdr
  21. #endif // BX_PLATFORM_*
  22. BX_ERROR_RESULT(BGFX_ERROR_TEXTURE_VALIDATION, BX_MAKEFOURCC('b', 'g', 0, 1) );
  23. BX_ERROR_RESULT(BGFX_ERROR_FRAME_BUFFER_VALIDATION, BX_MAKEFOURCC('b', 'g', 0, 2) );
  24. BX_ERROR_RESULT(BGFX_ERROR_IDENTIFIER_VALIDATION, BX_MAKEFOURCC('b', 'g', 0, 3) );
  25. namespace bgfx
  26. {
  27. #define BGFX_API_THREAD_MAGIC UINT32_C(0x78666762)
  28. #if BGFX_CONFIG_MULTITHREADED
  29. # define BGFX_CHECK_API_THREAD() \
  30. BX_ASSERT(NULL != s_ctx, "Library is not initialized yet."); \
  31. BX_ASSERT(BGFX_API_THREAD_MAGIC == s_threadIndex, "Must be called from main thread.")
  32. # define BGFX_CHECK_RENDER_THREAD() \
  33. BX_ASSERT( (NULL != s_ctx && s_ctx->m_singleThreaded) \
  34. || ~BGFX_API_THREAD_MAGIC == s_threadIndex \
  35. , "Must be called from render thread." \
  36. )
  37. #else
  38. # define BGFX_CHECK_API_THREAD()
  39. # define BGFX_CHECK_RENDER_THREAD()
  40. #endif // BGFX_CONFIG_MULTITHREADED
  41. #define BGFX_CHECK_CAPS(_caps, _msg) \
  42. BX_ASSERT(0 != (g_caps.supported & (_caps) ) \
  43. , _msg " Use bgfx::getCaps to check " #_caps " backend renderer capabilities." \
  44. );
  45. #if BGFX_CONFIG_USE_TINYSTL
  46. void* TinyStlAllocator::static_allocate(size_t _bytes)
  47. {
  48. return bx::alloc(g_allocator, _bytes);
  49. }
  50. void TinyStlAllocator::static_deallocate(void* _ptr, size_t /*_bytes*/)
  51. {
  52. if (NULL != _ptr)
  53. {
  54. bx::free(g_allocator, _ptr);
  55. }
  56. }
  57. #endif // BGFX_CONFIG_USE_TINYSTL
  58. struct Superluminal
  59. {
  60. struct SuppressTailCallOptimization
  61. {
  62. int64_t SuppressTailCall[3];
  63. };
  64. typedef void (*SuperluminalBeginEventtFn)(const char* _inID, const char* _inData, uint32_t _inColor);
  65. typedef SuppressTailCallOptimization(*SuperluminalEndEventFn)();
  66. static void stubSuperluminalBeginEvent(const char* _inID, const char* _inData, uint32_t _inColor)
  67. {
  68. BX_UNUSED(_inID, _inData, _inColor);
  69. }
  70. static SuppressTailCallOptimization stubSuperluminalEndEvent()
  71. {
  72. return {};
  73. }
  74. bool init()
  75. {
  76. if (!BX_ENABLED(BGFX_CONFIG_PROFILER) )
  77. {
  78. return false;
  79. }
  80. const char* superluminalDllName = "PerformanceAPI.dll";
  81. superluminalDll = bx::dlopen(superluminalDllName);
  82. if (NULL != superluminalDll)
  83. {
  84. void* funcPtrs[11];
  85. typedef int (*PerformanceAPI_GetAPI)(int32_t _version, void** _funcPtrs);
  86. constexpr int32_t version = 0x30000;
  87. PerformanceAPI_GetAPI getApi = bx::dlsym<PerformanceAPI_GetAPI>(superluminalDll, "PerformanceAPI_GetAPI");
  88. if (NULL == getApi)
  89. {
  90. BX_TRACE("Failed to obtain Superluminal's %s GetAPI function!", superluminalDllName);
  91. bx::dlclose(superluminalDll);
  92. return false;
  93. }
  94. if (getApi(version, funcPtrs) )
  95. {
  96. BX_TRACE("Superluminal's PerformanceAPI.dll is loaded!");
  97. beginEvent = (SuperluminalBeginEventtFn)funcPtrs[2];
  98. endEvent = (SuperluminalEndEventFn )funcPtrs[6];
  99. return true;
  100. }
  101. BX_TRACE("Failed to obtain Superluminal's %s GetAPI function!", superluminalDllName);
  102. bx::dlclose(superluminalDll);
  103. }
  104. else
  105. {
  106. BX_TRACE("Failed to load Superluminal's %s!", superluminalDllName);
  107. }
  108. return false;
  109. }
  110. void shutdown()
  111. {
  112. if (NULL != superluminalDll)
  113. {
  114. bx::dlclose(superluminalDll);
  115. superluminalDll = NULL;
  116. beginEvent = stubSuperluminalBeginEvent;
  117. endEvent = stubSuperluminalEndEvent;
  118. }
  119. }
  120. void* superluminalDll = NULL;
  121. SuperluminalBeginEventtFn beginEvent = stubSuperluminalBeginEvent;
  122. SuperluminalEndEventFn endEvent = stubSuperluminalEndEvent;
  123. };
  124. struct CallbackStub : public CallbackI
  125. {
  126. Superluminal m_superluminal;
  127. CallbackStub()
  128. {
  129. m_superluminal.init();
  130. }
  131. virtual ~CallbackStub()
  132. {
  133. m_superluminal.shutdown();
  134. }
  135. virtual void fatal(const char* _filePath, uint16_t _line, Fatal::Enum _code, const char* _str) override
  136. {
  137. bgfx::trace(_filePath, _line, "BGFX FATAL 0x%08x: %s\n", _code, _str);
  138. if (Fatal::DebugCheck == _code)
  139. {
  140. bx::debugBreak();
  141. }
  142. else
  143. {
  144. abort();
  145. }
  146. }
  147. virtual void traceVargs(const char* _filePath, uint16_t _line, const char* _format, va_list _argList) override
  148. {
  149. char temp[2048];
  150. char* out = temp;
  151. va_list argListCopy;
  152. va_copy(argListCopy, _argList);
  153. int32_t len = bx::snprintf(out, sizeof(temp), "%s (%d): ", _filePath, _line);
  154. int32_t total = len + bx::vsnprintf(out + len, sizeof(temp)-len, _format, argListCopy);
  155. va_end(argListCopy);
  156. if ( (int32_t)sizeof(temp) < total)
  157. {
  158. out = (char*)BX_STACK_ALLOC(total+1);
  159. bx::memCopy(out, temp, len);
  160. bx::vsnprintf(out + len, total-len, _format, _argList);
  161. }
  162. out[total] = '\0';
  163. bx::debugOutput(out);
  164. }
  165. virtual void profilerBegin(const char* _name, uint32_t _abgr, const char* /*_filePath*/, uint16_t /*_line*/) override
  166. {
  167. m_superluminal.beginEvent(" ", _name, _abgr);
  168. }
  169. virtual void profilerBeginLiteral(const char* _name, uint32_t _abgr, const char* /*_filePath*/, uint16_t /*_line*/) override
  170. {
  171. m_superluminal.beginEvent(_name, NULL, _abgr);
  172. }
  173. virtual void profilerEnd() override
  174. {
  175. m_superluminal.endEvent();
  176. }
  177. virtual uint32_t cacheReadSize(uint64_t /*_id*/) override
  178. {
  179. return 0;
  180. }
  181. virtual bool cacheRead(uint64_t /*_id*/, void* /*_data*/, uint32_t /*_size*/) override
  182. {
  183. return false;
  184. }
  185. virtual void cacheWrite(uint64_t /*_id*/, const void* /*_data*/, uint32_t /*_size*/) override
  186. {
  187. }
  188. virtual void screenShot(const char* _filePath, uint32_t _width, uint32_t _height, uint32_t _pitch, const void* _data, uint32_t _size, bool _yflip) override
  189. {
  190. BX_UNUSED(_filePath, _width, _height, _pitch, _data, _size, _yflip);
  191. const int32_t len = bx::strLen(_filePath)+5;
  192. char* filePath = (char*)BX_STACK_ALLOC(len);
  193. bx::strCopy(filePath, len, _filePath);
  194. bx::strCat(filePath, len, ".tga");
  195. bx::FileWriter writer;
  196. if (bx::open(&writer, filePath) )
  197. {
  198. bimg::imageWriteTga(&writer, _width, _height, _pitch, _data, false, _yflip);
  199. bx::close(&writer);
  200. }
  201. }
  202. virtual void captureBegin(uint32_t /*_width*/, uint32_t /*_height*/, uint32_t /*_pitch*/, TextureFormat::Enum /*_format*/, bool /*_yflip*/) override
  203. {
  204. BX_TRACE("Warning: using capture without callback (a.k.a. pointless).");
  205. }
  206. virtual void captureEnd() override
  207. {
  208. }
  209. virtual void captureFrame(const void* /*_data*/, uint32_t /*_size*/) override
  210. {
  211. }
  212. };
  213. #ifndef BGFX_CONFIG_MEMORY_TRACKING
  214. # define BGFX_CONFIG_MEMORY_TRACKING (BGFX_CONFIG_DEBUG && BX_CONFIG_SUPPORTS_THREADING)
  215. #endif // BGFX_CONFIG_MEMORY_TRACKING
  216. const size_t kNaturalAlignment = 8;
  217. class AllocatorStub : public bx::AllocatorI
  218. {
  219. public:
  220. AllocatorStub()
  221. #if BGFX_CONFIG_MEMORY_TRACKING
  222. : m_numBlocks(0)
  223. , m_maxBlocks(0)
  224. #endif // BGFX_CONFIG_MEMORY_TRACKING
  225. {
  226. }
  227. virtual void* realloc(void* _ptr, size_t _size, size_t _align, const char* _file, uint32_t _line) override
  228. {
  229. if (0 == _size)
  230. {
  231. if (NULL != _ptr)
  232. {
  233. if (kNaturalAlignment >= _align)
  234. {
  235. #if BGFX_CONFIG_MEMORY_TRACKING
  236. {
  237. bx::MutexScope scope(m_mutex);
  238. BX_ASSERT(m_numBlocks > 0, "Number of blocks is 0. Possible alloc/free mismatch?");
  239. --m_numBlocks;
  240. }
  241. #endif // BGFX_CONFIG_MEMORY_TRACKING
  242. ::free(_ptr);
  243. }
  244. else
  245. {
  246. bx::alignedFree(this, _ptr, _align, bx::Location(_file, _line) );
  247. }
  248. }
  249. return NULL;
  250. }
  251. else if (NULL == _ptr)
  252. {
  253. if (kNaturalAlignment >= _align)
  254. {
  255. #if BGFX_CONFIG_MEMORY_TRACKING
  256. {
  257. bx::MutexScope scope(m_mutex);
  258. ++m_numBlocks;
  259. m_maxBlocks = bx::max(m_maxBlocks, m_numBlocks);
  260. }
  261. #endif // BGFX_CONFIG_MEMORY_TRACKING
  262. void* ptr = ::malloc(_size);
  263. BX_ASSERT(NULL != ptr, "Out of memory!");
  264. return ptr;
  265. }
  266. void* ptr = bx::alignedAlloc(this, _size, _align, bx::Location(_file, _line) );
  267. BX_ASSERT(NULL != ptr, "Out of memory!");
  268. return ptr;
  269. }
  270. if (kNaturalAlignment >= _align)
  271. {
  272. void* ptr = ::realloc(_ptr, _size);
  273. BX_ASSERT(NULL != ptr, "Out of memory!");
  274. return ptr;
  275. }
  276. void* ptr = bx::alignedRealloc(this, _ptr, _size, _align, bx::Location(_file, _line) );
  277. BX_ASSERT(NULL != ptr, "Out of memory!");
  278. return ptr;
  279. }
  280. void checkLeaks();
  281. protected:
  282. #if BGFX_CONFIG_MEMORY_TRACKING
  283. bx::Mutex m_mutex;
  284. uint32_t m_numBlocks;
  285. uint32_t m_maxBlocks;
  286. #endif // BGFX_CONFIG_MEMORY_TRACKING
  287. };
  288. static CallbackStub* s_callbackStub = NULL;
  289. static AllocatorStub* s_allocatorStub = NULL;
  290. static bool s_graphicsDebuggerPresent = false;
  291. CallbackI* g_callback = NULL;
  292. bx::AllocatorI* g_allocator = NULL;
  293. Caps g_caps;
  294. #if BGFX_CONFIG_MULTITHREADED
  295. static BX_THREAD_LOCAL uint32_t s_threadIndex(0);
  296. #else
  297. static uint32_t s_threadIndex(0);
  298. #endif // BGFX_CONFIG_MULTITHREADED
  299. static Context* s_ctx = NULL;
  300. static bool s_renderFrameCalled = false;
  301. InternalData g_internalData;
  302. PlatformData g_platformData;
  303. bool g_platformDataChangedSinceReset = false;
  304. static Handle::TypeName s_typeName[] =
  305. {
  306. { "DIB", "DynamicIndexBuffer" },
  307. { "DVB", "DynamicVertexBuffer" },
  308. { "FB", "FrameBuffer" },
  309. { "IB", "IndexBuffer" },
  310. { "IndB", "IndirectBuffer" },
  311. { "OQ", "OcclusionQuery" },
  312. { "P", "Program" },
  313. { "S", "Shader" },
  314. { "T", "Texture" },
  315. { "U", "Uniform" },
  316. { "VB", "VertexBuffer" },
  317. { "VL", "VertexLayout" },
  318. { "?", "?" },
  319. };
  320. static_assert(BX_COUNTOF(s_typeName) == Handle::Count+1, "");
  321. const Handle::TypeName& Handle::getTypeName(Handle::Enum _enum)
  322. {
  323. BX_ASSERT(_enum < Handle::Count, "Invalid Handle::Enum %d!", _enum);
  324. return s_typeName[bx::min(_enum, Handle::Count)];
  325. }
  326. void AllocatorStub::checkLeaks()
  327. {
  328. #if BGFX_CONFIG_MEMORY_TRACKING
  329. // BK - CallbackStub will be deleted after printing this info, so there is always one
  330. // leak if CallbackStub is used.
  331. BX_WARN(uint32_t(NULL != s_callbackStub ? 1 : 0) == m_numBlocks
  332. , "\n\n"
  333. "\n########################################################"
  334. "\n"
  335. "\nMEMORY LEAK: Number of leaked blocks %d (Max blocks: %d)"
  336. "\n"
  337. "\n########################################################"
  338. "\n\n"
  339. , m_numBlocks
  340. , m_maxBlocks
  341. );
  342. #endif // BGFX_CONFIG_MEMORY_TRACKING
  343. }
  344. void setPlatformData(const PlatformData& _data)
  345. {
  346. if (NULL != s_ctx)
  347. {
  348. BGFX_FATAL(true
  349. && g_platformData.ndt == _data.ndt
  350. && g_platformData.context == _data.context
  351. , Fatal::UnableToInitialize
  352. , "Only backbuffer pointer and native window handle can be changed after initialization!"
  353. );
  354. }
  355. bx::memCopy(&g_platformData, &_data, sizeof(PlatformData) );
  356. g_platformDataChangedSinceReset = true;
  357. }
  358. const InternalData* getInternalData()
  359. {
  360. return &g_internalData;
  361. }
  362. uintptr_t overrideInternal(TextureHandle _handle, uintptr_t _ptr, uint16_t _layerIndex)
  363. {
  364. BGFX_CHECK_RENDER_THREAD();
  365. RendererContextI* rci = s_ctx->m_renderCtx;
  366. if (0 == rci->getInternal(_handle) )
  367. {
  368. return 0;
  369. }
  370. rci->overrideInternal(_handle, _ptr, _layerIndex);
  371. return rci->getInternal(_handle);
  372. }
  373. uintptr_t overrideInternal(TextureHandle _handle, uint16_t _width, uint16_t _height, uint8_t _numMips, TextureFormat::Enum _format, uint64_t _flags)
  374. {
  375. BGFX_CHECK_RENDER_THREAD();
  376. RendererContextI* rci = s_ctx->m_renderCtx;
  377. if (0 == rci->getInternal(_handle) )
  378. {
  379. return 0;
  380. }
  381. uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate);
  382. Memory* mem = const_cast<Memory*>(alloc(size) );
  383. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  384. bx::write(&writer, kChunkMagicTex, bx::ErrorAssert{});
  385. TextureCreate tc;
  386. tc.m_width = _width;
  387. tc.m_height = _height;
  388. tc.m_depth = 0;
  389. tc.m_numLayers = 1;
  390. tc.m_numMips = bx::max<uint8_t>(1, _numMips);
  391. tc.m_format = _format;
  392. tc.m_cubeMap = false;
  393. tc.m_mem = NULL;
  394. bx::write(&writer, tc, bx::ErrorAssert{});
  395. rci->destroyTexture(_handle);
  396. rci->createTexture(_handle, mem, _flags, 0);
  397. release(mem);
  398. return rci->getInternal(_handle);
  399. }
  400. void setGraphicsDebuggerPresent(bool _present)
  401. {
  402. BX_TRACE("Graphics debugger is %spresent.", _present ? "" : "not ");
  403. s_graphicsDebuggerPresent = _present;
  404. }
  405. bool isGraphicsDebuggerPresent()
  406. {
  407. return s_graphicsDebuggerPresent;
  408. }
  409. void fatal(const char* _filePath, uint16_t _line, Fatal::Enum _code, const char* _format, ...)
  410. {
  411. va_list argList;
  412. va_start(argList, _format);
  413. char temp[8192];
  414. char* out = temp;
  415. int32_t len = bx::vsnprintf(out, sizeof(temp), _format, argList);
  416. if ( (int32_t)sizeof(temp) < len)
  417. {
  418. out = (char*)BX_STACK_ALLOC(len+1);
  419. len = bx::vsnprintf(out, len, _format, argList);
  420. }
  421. out[len] = '\0';
  422. if (BX_UNLIKELY(NULL == g_callback) )
  423. {
  424. bx::debugPrintf("%s(%d): BGFX FATAL 0x%08x: %s", _filePath, _line, _code, out);
  425. abort();
  426. }
  427. else
  428. {
  429. g_callback->fatal(_filePath, _line, _code, out);
  430. }
  431. va_end(argList);
  432. }
  433. void trace(const char* _filePath, uint16_t _line, const char* _format, ...)
  434. {
  435. va_list argList;
  436. va_start(argList, _format);
  437. if (BX_UNLIKELY(NULL == g_callback) )
  438. {
  439. bx::debugPrintfVargs(_format, argList);
  440. }
  441. else
  442. {
  443. g_callback->traceVargs(_filePath, _line, _format, argList);
  444. }
  445. va_end(argList);
  446. }
  447. #include "vs_debugfont.bin.h"
  448. #include "fs_debugfont.bin.h"
  449. #include "vs_clear.bin.h"
  450. #include "fs_clear0.bin.h"
  451. #include "fs_clear1.bin.h"
  452. #include "fs_clear2.bin.h"
  453. #include "fs_clear3.bin.h"
  454. #include "fs_clear4.bin.h"
  455. #include "fs_clear5.bin.h"
  456. #include "fs_clear6.bin.h"
  457. #include "fs_clear7.bin.h"
  458. static const EmbeddedShader s_embeddedShaders[] =
  459. {
  460. BGFX_EMBEDDED_SHADER(vs_debugfont),
  461. BGFX_EMBEDDED_SHADER(fs_debugfont),
  462. BGFX_EMBEDDED_SHADER(vs_clear),
  463. BGFX_EMBEDDED_SHADER(fs_clear0),
  464. BGFX_EMBEDDED_SHADER(fs_clear1),
  465. BGFX_EMBEDDED_SHADER(fs_clear2),
  466. BGFX_EMBEDDED_SHADER(fs_clear3),
  467. BGFX_EMBEDDED_SHADER(fs_clear4),
  468. BGFX_EMBEDDED_SHADER(fs_clear5),
  469. BGFX_EMBEDDED_SHADER(fs_clear6),
  470. BGFX_EMBEDDED_SHADER(fs_clear7),
  471. BGFX_EMBEDDED_SHADER_END()
  472. };
  473. ShaderHandle createEmbeddedShader(const EmbeddedShader* _es, RendererType::Enum _type, const char* _name)
  474. {
  475. for (const EmbeddedShader* es = _es; NULL != es->name; ++es)
  476. {
  477. if (0 == bx::strCmp(_name, es->name) )
  478. {
  479. for (const EmbeddedShader::Data* esd = es->data; RendererType::Count != esd->type; ++esd)
  480. {
  481. if (_type == esd->type
  482. && 1 < esd->size)
  483. {
  484. ShaderHandle handle = createShader(makeRef(esd->data, esd->size) );
  485. if (isValid(handle) )
  486. {
  487. setName(handle, _name);
  488. }
  489. return handle;
  490. }
  491. }
  492. }
  493. }
  494. ShaderHandle handle = BGFX_INVALID_HANDLE;
  495. return handle;
  496. }
  497. void dump(const VertexLayout& _layout)
  498. {
  499. if (BX_ENABLED(BGFX_CONFIG_DEBUG) )
  500. {
  501. BX_TRACE("VertexLayout %08x (%08x), stride %d"
  502. , _layout.m_hash
  503. , bx::hash<bx::HashMurmur2A>(_layout.m_attributes)
  504. , _layout.m_stride
  505. );
  506. for (uint32_t attr = 0; attr < Attrib::Count; ++attr)
  507. {
  508. if (UINT16_MAX != _layout.m_attributes[attr])
  509. {
  510. uint8_t num;
  511. AttribType::Enum type;
  512. bool normalized;
  513. bool asInt;
  514. _layout.decode(Attrib::Enum(attr), num, type, normalized, asInt);
  515. BX_TRACE("\tattr %2d: %-20s num %d, type %d, norm [%c], asint [%c], offset %2d"
  516. , attr
  517. , getAttribName(Attrib::Enum(attr) )
  518. , num
  519. , type
  520. , normalized ? 'x' : ' '
  521. , asInt ? 'x' : ' '
  522. , _layout.m_offset[attr]
  523. );
  524. }
  525. }
  526. }
  527. }
  528. #include "charset.h"
  529. void charsetFillTexture(const uint8_t* _charset, uint8_t* _rgba, uint32_t _height, uint32_t _pitch, uint32_t _bpp)
  530. {
  531. for (uint32_t ii = 0; ii < 256; ++ii)
  532. {
  533. uint8_t* pix = &_rgba[ii*8*_bpp];
  534. for (uint32_t yy = 0; yy < _height; ++yy)
  535. {
  536. for (uint32_t xx = 0; xx < 8; ++xx)
  537. {
  538. uint8_t bit = 1<<(7-xx);
  539. bx::memSet(&pix[xx*_bpp], _charset[ii*_height+yy]&bit ? 255 : 0, _bpp);
  540. }
  541. pix += _pitch;
  542. }
  543. }
  544. }
  545. static uint8_t parseAttrTo(char*& _ptr, char _to, uint8_t _default)
  546. {
  547. const bx::StringView str = bx::strFind(_ptr, _to);
  548. if (!str.isEmpty()
  549. && 3 > str.getPtr()-_ptr)
  550. {
  551. char tmp[4];
  552. int32_t len = int32_t(str.getPtr()-_ptr);
  553. bx::strCopy(tmp, sizeof(tmp), _ptr, len);
  554. uint32_t attr;
  555. bx::fromString(&attr, tmp);
  556. _ptr += len+1;
  557. return uint8_t(attr);
  558. }
  559. return _default;
  560. }
  561. static uint8_t parseAttr(char*& _ptr, uint8_t _default)
  562. {
  563. char* ptr = _ptr;
  564. if (*ptr++ != '[')
  565. {
  566. return _default;
  567. }
  568. if (0 == bx::strCmp(ptr, "0m", 2) )
  569. {
  570. _ptr = ptr + 2;
  571. return _default;
  572. }
  573. uint8_t fg = parseAttrTo(ptr, ';', _default & 0xf);
  574. uint8_t bg = parseAttrTo(ptr, 'm', _default >> 4);
  575. uint8_t attr = (bg<<4) | fg;
  576. _ptr = ptr;
  577. return attr;
  578. }
  579. void TextVideoMem::printfVargs(uint16_t _x, uint16_t _y, uint8_t _attr, const char* _format, va_list _argList)
  580. {
  581. if (_x < m_width && _y < m_height)
  582. {
  583. va_list argListCopy;
  584. va_copy(argListCopy, _argList);
  585. uint32_t num = bx::vsnprintf(NULL, 0, _format, argListCopy) + 1;
  586. char* temp = (char*)BX_STACK_ALLOC(num);
  587. va_copy(argListCopy, _argList);
  588. num = bx::vsnprintf(temp, num, _format, argListCopy);
  589. uint8_t attr = _attr;
  590. MemSlot* mem = &m_mem[_y*m_width+_x];
  591. for (uint32_t ii = 0, xx = _x; ii < num && xx < m_width; ++ii)
  592. {
  593. char ch = temp[ii];
  594. if (BX_UNLIKELY(ch == '\x1b') )
  595. {
  596. char* ptr = &temp[ii+1];
  597. attr = parseAttr(ptr, _attr);
  598. ii += uint32_t(ptr - &temp[ii+1]);
  599. }
  600. else
  601. {
  602. mem->character = ch;
  603. mem->attribute = attr;
  604. ++mem;
  605. ++xx;
  606. }
  607. }
  608. }
  609. }
  610. static constexpr uint32_t kNumCharsPerBatch = 1024;
  611. static constexpr uint32_t kNumBatchVertices = kNumCharsPerBatch*4;
  612. static constexpr uint32_t kNumBatchIndices = kNumCharsPerBatch*6;
  613. void TextVideoMemBlitter::init(uint8_t scale)
  614. {
  615. BGFX_CHECK_API_THREAD();
  616. m_layout
  617. .begin()
  618. .add(Attrib::Position, 3, AttribType::Float)
  619. .add(Attrib::Color0, 4, AttribType::Uint8, true)
  620. .add(Attrib::Color1, 4, AttribType::Uint8, true)
  621. .add(Attrib::TexCoord0, 2, AttribType::Float)
  622. .end();
  623. const uint16_t width = 2048;
  624. const uint16_t height = 24;
  625. const uint8_t bpp = 1;
  626. const uint32_t pitch = width*bpp;
  627. const Memory* mem;
  628. mem = alloc(pitch*height);
  629. uint8_t* rgba = mem->data;
  630. charsetFillTexture(vga8x8, rgba, 8, pitch, bpp);
  631. charsetFillTexture(vga8x16, &rgba[8*pitch], 16, pitch, bpp);
  632. m_texture = createTexture2D(width, height, false, 1, TextureFormat::R8
  633. , BGFX_SAMPLER_MIN_POINT
  634. | BGFX_SAMPLER_MAG_POINT
  635. | BGFX_SAMPLER_MIP_POINT
  636. | BGFX_SAMPLER_U_CLAMP
  637. | BGFX_SAMPLER_V_CLAMP
  638. , mem
  639. );
  640. ShaderHandle vsh = createEmbeddedShader(s_embeddedShaders, g_caps.rendererType, "vs_debugfont");
  641. ShaderHandle fsh = createEmbeddedShader(s_embeddedShaders, g_caps.rendererType, "fs_debugfont");
  642. BX_ASSERT(isValid(vsh) && isValid(fsh), "Failed to create embedded blit shaders");
  643. m_program = createProgram(vsh, fsh, true);
  644. m_vb = s_ctx->createTransientVertexBuffer(kNumBatchVertices*m_layout.m_stride, &m_layout);
  645. m_ib = s_ctx->createTransientIndexBuffer(kNumBatchIndices*2);
  646. m_scale = bx::max<uint8_t>(scale, 1);
  647. m_usedData = 0;
  648. }
  649. void TextVideoMemBlitter::shutdown()
  650. {
  651. BGFX_CHECK_API_THREAD();
  652. if (isValid(m_program) )
  653. {
  654. destroy(m_program);
  655. }
  656. destroy(m_texture);
  657. s_ctx->destroyTransientVertexBuffer(m_vb);
  658. s_ctx->destroyTransientIndexBuffer(m_ib);
  659. }
  660. static const uint32_t s_paletteSrgb[] =
  661. {
  662. 0x0, // Black
  663. 0xffa46534, // Blue
  664. 0xff069a4e, // Green
  665. 0xff9a9806, // Cyan
  666. 0xff0000cc, // Red
  667. 0xff7b5075, // Magenta
  668. 0xff00a0c4, // Brown
  669. 0xffcfd7d3, // Light Gray
  670. 0xff535755, // Dark Gray
  671. 0xffcf9f72, // Light Blue
  672. 0xff34e28a, // Light Green
  673. 0xffe2e234, // Light Cyan
  674. 0xff2929ef, // Light Red
  675. 0xffa87fad, // Light Magenta
  676. 0xff4fe9fc, // Yellow
  677. 0xffeceeee, // White
  678. };
  679. static_assert(BX_COUNTOF(s_paletteSrgb) == 16);
  680. static const uint32_t s_paletteLinear[] =
  681. {
  682. 0x0, // Black
  683. 0xff5e2108, // Blue
  684. 0xff005213, // Green
  685. 0xff525000, // Cyan
  686. 0xff000099, // Red
  687. 0xff32142d, // Magenta
  688. 0xff00598c, // Brown
  689. 0xff9fada6, // Light Gray
  690. 0xff161817, // Dark Gray
  691. 0xff9f582a, // Light Blue
  692. 0xff08c140, // Light Green
  693. 0xffc1c108, // Light Cyan
  694. 0xff0505dc, // Light Red
  695. 0xff63366a, // Light Magenta
  696. 0xff13cff8, // Yellow
  697. 0xffd5dada // White
  698. };
  699. static_assert(BX_COUNTOF(s_paletteLinear) == 16);
  700. void dbgTextSubmit(RendererContextI* _renderCtx, TextVideoMemBlitter& _blitter, const TextVideoMem& _mem)
  701. {
  702. struct Vertex
  703. {
  704. float m_x;
  705. float m_y;
  706. float m_z;
  707. uint32_t m_fg;
  708. uint32_t m_bg;
  709. float m_u;
  710. float m_v;
  711. };
  712. uint32_t yy = 0;
  713. uint32_t xx = 0;
  714. const float texelWidth = 1.0f/2048.0f;
  715. const float texelHeight = 1.0f/24.0f;
  716. const float utop = (_mem.m_small ? 0.0f : 8.0f)*texelHeight;
  717. const float ubottom = (_mem.m_small ? 8.0f : 24.0f)*texelHeight;
  718. const float fontHeight = (_mem.m_small ? 8.0f : 16.0f)*_blitter.m_scale;
  719. const float fontWidth = 8.0f * _blitter.m_scale;
  720. _renderCtx->dbgTextRenderBegin(_blitter);
  721. const uint32_t* palette = 0 != (s_ctx->m_init.resolution.reset & BGFX_RESET_SRGB_BACKBUFFER)
  722. ? s_paletteLinear
  723. : s_paletteSrgb
  724. ;
  725. for (;yy < _mem.m_height;)
  726. {
  727. Vertex* vertex = (Vertex *)_blitter.m_vb->data;
  728. uint16_t* indices = (uint16_t*)_blitter.m_ib->data;
  729. uint32_t startVertex = 0;
  730. uint32_t numIndices = 0;
  731. for (; yy < _mem.m_height && numIndices < kNumBatchIndices; ++yy)
  732. {
  733. xx = xx < _mem.m_width ? xx : 0;
  734. const TextVideoMem::MemSlot* line = &_mem.m_mem[yy*_mem.m_width+xx];
  735. for (; xx < _mem.m_width && numIndices < kNumBatchIndices; ++xx)
  736. {
  737. uint32_t ch = line->character;
  738. const uint8_t attr = line->attribute;
  739. if (ch > 0xff)
  740. {
  741. ch = 0;
  742. }
  743. if (0 != (ch|attr)
  744. && (' ' != ch || 0 != (attr&0xf0) ) )
  745. {
  746. const uint32_t fg = palette[attr&0xf];
  747. const uint32_t bg = palette[(attr>>4)&0xf];
  748. const Vertex vert[4] =
  749. {
  750. { (xx )*fontWidth, (yy )*fontHeight, 0.0f, fg, bg, (ch )*8.0f*texelWidth, utop },
  751. { (xx+1)*fontWidth, (yy )*fontHeight, 0.0f, fg, bg, (ch+1)*8.0f*texelWidth, utop },
  752. { (xx+1)*fontWidth, (yy+1)*fontHeight, 0.0f, fg, bg, (ch+1)*8.0f*texelWidth, ubottom },
  753. { (xx )*fontWidth, (yy+1)*fontHeight, 0.0f, fg, bg, (ch )*8.0f*texelWidth, ubottom },
  754. };
  755. bx::memCopy(vertex, vert, sizeof(vert) );
  756. vertex += 4;
  757. indices[0] = uint16_t(startVertex+0);
  758. indices[1] = uint16_t(startVertex+1);
  759. indices[2] = uint16_t(startVertex+2);
  760. indices[3] = uint16_t(startVertex+2);
  761. indices[4] = uint16_t(startVertex+3);
  762. indices[5] = uint16_t(startVertex+0);
  763. startVertex += 4;
  764. indices += 6;
  765. numIndices += 6;
  766. }
  767. line++;
  768. }
  769. if (numIndices >= kNumBatchIndices)
  770. {
  771. break;
  772. }
  773. }
  774. _renderCtx->dbgTextRender(_blitter, numIndices);
  775. }
  776. _renderCtx->dbgTextRenderEnd(_blitter);
  777. }
  778. void ClearQuad::init()
  779. {
  780. BGFX_CHECK_API_THREAD();
  781. if (RendererType::Noop != g_caps.rendererType)
  782. {
  783. VertexLayout layout;
  784. layout
  785. .begin()
  786. .add(Attrib::Position, 2, AttribType::Float)
  787. .end();
  788. ShaderHandle vsh = createEmbeddedShader(s_embeddedShaders, g_caps.rendererType, "vs_clear");
  789. BX_ASSERT(isValid(vsh), "Failed to create clear quad embedded vertex shader \"vs_clear\"");
  790. for (uint32_t ii = 0, num = g_caps.limits.maxFBAttachments; ii < num; ++ii)
  791. {
  792. char name[32];
  793. bx::snprintf(name, BX_COUNTOF(name), "fs_clear%d", ii);
  794. ShaderHandle fsh = createEmbeddedShader(s_embeddedShaders, g_caps.rendererType, name);
  795. BX_ASSERT(isValid(fsh), "Failed to create clear quad embedded fragment shader \"%s\"", name);
  796. m_program[ii] = createProgram(vsh, fsh);
  797. BX_ASSERT(isValid(m_program[ii]), "Failed to create clear quad program.");
  798. destroy(fsh);
  799. }
  800. destroy(vsh);
  801. struct Vertex
  802. {
  803. float m_x;
  804. float m_y;
  805. };
  806. const uint16_t stride = layout.m_stride;
  807. const bgfx::Memory* mem = bgfx::alloc(4 * stride);
  808. Vertex* vertex = (Vertex*)mem->data;
  809. BX_ASSERT(stride == sizeof(Vertex), "Stride/Vertex mismatch (stride %d, sizeof(Vertex) %d)", stride, sizeof(Vertex));
  810. vertex->m_x = -1.0f;
  811. vertex->m_y = -1.0f;
  812. vertex++;
  813. vertex->m_x = 1.0f;
  814. vertex->m_y = -1.0f;
  815. vertex++;
  816. vertex->m_x = -1.0f;
  817. vertex->m_y = 1.0f;
  818. vertex++;
  819. vertex->m_x = 1.0f;
  820. vertex->m_y = 1.0f;
  821. m_layout = s_ctx->createVertexLayout(layout);
  822. m_vb = s_ctx->createVertexBuffer(mem, layout, 0);
  823. }
  824. }
  825. void ClearQuad::shutdown()
  826. {
  827. BGFX_CHECK_API_THREAD();
  828. if (RendererType::Noop != g_caps.rendererType)
  829. {
  830. for (uint32_t ii = 0, num = g_caps.limits.maxFBAttachments; ii < num; ++ii)
  831. {
  832. if (isValid(m_program[ii]) )
  833. {
  834. destroy(m_program[ii]);
  835. m_program[ii] = BGFX_INVALID_HANDLE;
  836. }
  837. }
  838. s_ctx->destroyVertexBuffer(m_vb);
  839. s_ctx->destroyVertexLayout(m_layout);
  840. }
  841. }
  842. const char* s_uniformTypeName[] =
  843. {
  844. "sampler1",
  845. NULL,
  846. "vec4",
  847. "mat3",
  848. "mat4",
  849. };
  850. static_assert(UniformType::Count == BX_COUNTOF(s_uniformTypeName) );
  851. const char* getUniformTypeName(UniformType::Enum _enum)
  852. {
  853. BX_ASSERT(_enum < UniformType::Count, "%d < UniformType::Count %d", _enum, UniformType::Count);
  854. return s_uniformTypeName[_enum];
  855. }
  856. UniformType::Enum nameToUniformTypeEnum(const char* _name)
  857. {
  858. for (uint32_t ii = 0; ii < UniformType::Count; ++ii)
  859. {
  860. if (NULL != s_uniformTypeName[ii]
  861. && 0 == bx::strCmp(_name, s_uniformTypeName[ii]) )
  862. {
  863. return UniformType::Enum(ii);
  864. }
  865. }
  866. return UniformType::Count;
  867. }
  868. static const char* s_predefinedName[PredefinedUniform::Count] =
  869. {
  870. "u_viewRect",
  871. "u_viewTexel",
  872. "u_view",
  873. "u_invView",
  874. "u_proj",
  875. "u_invProj",
  876. "u_viewProj",
  877. "u_invViewProj",
  878. "u_model",
  879. "u_modelView",
  880. "u_invModelView",
  881. "u_modelViewProj",
  882. "u_alphaRef4",
  883. };
  884. const char* getPredefinedUniformName(PredefinedUniform::Enum _enum)
  885. {
  886. return s_predefinedName[_enum];
  887. }
  888. PredefinedUniform::Enum nameToPredefinedUniformEnum(const bx::StringView& _name)
  889. {
  890. for (uint32_t ii = 0; ii < PredefinedUniform::Count; ++ii)
  891. {
  892. if (0 == bx::strCmp(_name, s_predefinedName[ii]) )
  893. {
  894. return PredefinedUniform::Enum(ii);
  895. }
  896. }
  897. return PredefinedUniform::Count;
  898. }
  899. void srtToMatrix4_x1(void* _dst, const void* _src)
  900. {
  901. Matrix4* mtx = reinterpret_cast< Matrix4*>(_dst);
  902. const Srt* srt = reinterpret_cast<const Srt*>(_src);
  903. const float rx = srt->rotate[0];
  904. const float ry = srt->rotate[1];
  905. const float rz = srt->rotate[2];
  906. const float rw = srt->rotate[3];
  907. const float xx2 = 2.0f * rx * rx;
  908. const float yy2 = 2.0f * ry * ry;
  909. const float zz2 = 2.0f * rz * rz;
  910. const float yx2 = 2.0f * ry * rx;
  911. const float yz2 = 2.0f * ry * rz;
  912. const float yw2 = 2.0f * ry * rw;
  913. const float wz2 = 2.0f * rw * rz;
  914. const float wx2 = 2.0f * rw * rx;
  915. const float xz2 = 2.0f * rx * rz;
  916. const float sx = srt->scale[0];
  917. const float sy = srt->scale[1];
  918. const float sz = srt->scale[2];
  919. mtx->un.val[ 0] = (1.0f - yy2 - zz2)*sx;
  920. mtx->un.val[ 1] = ( yx2 + wz2)*sx;
  921. mtx->un.val[ 2] = ( xz2 - yw2)*sx;
  922. mtx->un.val[ 3] = 0.0f;
  923. mtx->un.val[ 4] = ( yx2 - wz2)*sy;
  924. mtx->un.val[ 5] = (1.0f - xx2 - zz2)*sy;
  925. mtx->un.val[ 6] = ( yz2 + wx2)*sy;
  926. mtx->un.val[ 7] = 0.0f;
  927. mtx->un.val[ 8] = ( xz2 + yw2)*sz;
  928. mtx->un.val[ 9] = ( yz2 - wx2)*sz;
  929. mtx->un.val[10] = (1.0f - xx2 - yy2)*sz;
  930. mtx->un.val[11] = 0.0f;
  931. const float tx = srt->translate[0];
  932. const float ty = srt->translate[1];
  933. const float tz = srt->translate[2];
  934. mtx->un.val[12] = tx;
  935. mtx->un.val[13] = ty;
  936. mtx->un.val[14] = tz;
  937. mtx->un.val[15] = 1.0f;
  938. }
  939. void transpose(void* _dst, uint32_t _dstStride, const void* _src, uint32_t _srcStride = sizeof(bx::simd128_t) )
  940. {
  941. uint8_t* dst = reinterpret_cast< uint8_t *>(_dst);
  942. const uint8_t* src = reinterpret_cast<const uint8_t *>(_src);
  943. using namespace bx;
  944. const simd128_t r0 = simd_ld<simd128_t>(src);
  945. src += _srcStride;
  946. const simd128_t r1 = simd_ld<simd128_t>(src);
  947. src += _srcStride;
  948. const simd128_t r2 = simd_ld<simd128_t>(src);
  949. src += _srcStride;
  950. const simd128_t r3 = simd_ld<simd128_t>(src);
  951. const simd128_t aibj = simd_shuf_xAyB(r0, r2); // aibj
  952. const simd128_t emfn = simd_shuf_xAyB(r1, r3); // emfn
  953. const simd128_t ckdl = simd_shuf_zCwD(r0, r2); // ckdl
  954. const simd128_t gohp = simd_shuf_zCwD(r1, r3); // gohp
  955. const simd128_t aeim = simd_shuf_xAyB(aibj, emfn); // aeim
  956. const simd128_t bfjn = simd_shuf_zCwD(aibj, emfn); // bfjn
  957. const simd128_t cgko = simd_shuf_xAyB(ckdl, gohp); // cgko
  958. const simd128_t dhlp = simd_shuf_zCwD(ckdl, gohp); // dhlp
  959. simd_st(dst, aeim);
  960. dst += _dstStride;
  961. simd_st(dst, bfjn);
  962. dst += _dstStride;
  963. simd_st(dst, cgko);
  964. dst += _dstStride;
  965. simd_st(dst, dhlp);
  966. }
  967. void srtToMatrix4_x4_Ref(void* _dst, const void* _src)
  968. {
  969. uint8_t* dst = reinterpret_cast< uint8_t*>(_dst);
  970. const uint8_t* src = reinterpret_cast<const uint8_t*>(_src);
  971. srtToMatrix4_x1(dst + 0*sizeof(Matrix4), src + 0*sizeof(Srt) );
  972. srtToMatrix4_x1(dst + 1*sizeof(Matrix4), src + 1*sizeof(Srt) );
  973. srtToMatrix4_x1(dst + 2*sizeof(Matrix4), src + 2*sizeof(Srt) );
  974. srtToMatrix4_x1(dst + 3*sizeof(Matrix4), src + 3*sizeof(Srt) );
  975. }
  976. void srtToMatrix4_x4_Simd(void* _dst, const void* _src)
  977. {
  978. using namespace bx;
  979. simd128_t* dst = reinterpret_cast< simd128_t*>(_dst);
  980. const simd128_t* src = reinterpret_cast<const simd128_t*>(_src);
  981. simd128_t rotate[4];
  982. simd128_t translate[4];
  983. simd128_t scale[4];
  984. transpose(rotate, sizeof(simd128_t), src + 0, sizeof(Srt) );
  985. transpose(translate, sizeof(simd128_t), src + 1, sizeof(Srt) );
  986. transpose(scale, sizeof(simd128_t), src + 2, sizeof(Srt) );
  987. const simd128_t rx = simd_ld<simd128_t>(rotate + 0);
  988. const simd128_t ry = simd_ld<simd128_t>(rotate + 1);
  989. const simd128_t rz = simd_ld<simd128_t>(rotate + 2);
  990. const simd128_t rw = simd_ld<simd128_t>(rotate + 3);
  991. const simd128_t tx = simd_ld<simd128_t>(translate + 0);
  992. const simd128_t ty = simd_ld<simd128_t>(translate + 1);
  993. const simd128_t tz = simd_ld<simd128_t>(translate + 2);
  994. const simd128_t sx = simd_ld<simd128_t>(scale + 0);
  995. const simd128_t sy = simd_ld<simd128_t>(scale + 1);
  996. const simd128_t sz = simd_ld<simd128_t>(scale + 2);
  997. const simd128_t zero = simd_splat(0.0f);
  998. const simd128_t one = simd_splat(1.0f);
  999. const simd128_t two = simd_splat(2.0f);
  1000. const simd128_t xx = simd_mul(rx, rx);
  1001. const simd128_t xx2 = simd_mul(two, xx);
  1002. const simd128_t yy = simd_mul(ry, ry);
  1003. const simd128_t yy2 = simd_mul(two, yy);
  1004. const simd128_t zz = simd_mul(rz, rz);
  1005. const simd128_t zz2 = simd_mul(two, zz);
  1006. const simd128_t yx = simd_mul(ry, rx);
  1007. const simd128_t yx2 = simd_mul(two, yx);
  1008. const simd128_t yz = simd_mul(ry, rz);
  1009. const simd128_t yz2 = simd_mul(two, yz);
  1010. const simd128_t yw = simd_mul(ry, rw);
  1011. const simd128_t yw2 = simd_mul(two, yw);
  1012. const simd128_t wz = simd_mul(rw, rz);
  1013. const simd128_t wz2 = simd_mul(two, wz);
  1014. const simd128_t wx = simd_mul(rw, rx);
  1015. const simd128_t wx2 = simd_mul(two, wx);
  1016. const simd128_t xz = simd_mul(rx, rz);
  1017. const simd128_t xz2 = simd_mul(two, xz);
  1018. const simd128_t t0x = simd_sub(one, yy2);
  1019. const simd128_t r0x = simd_sub(t0x, zz2);
  1020. const simd128_t r0y = simd_add(yx2, wz2);
  1021. const simd128_t r0z = simd_sub(xz2, yw2);
  1022. const simd128_t r1x = simd_sub(yx2, wz2);
  1023. const simd128_t omxx2 = simd_sub(one, xx2);
  1024. const simd128_t r1y = simd_sub(omxx2, zz2);
  1025. const simd128_t r1z = simd_add(yz2, wx2);
  1026. const simd128_t r2x = simd_add(xz2, yw2);
  1027. const simd128_t r2y = simd_sub(yz2, wx2);
  1028. const simd128_t r2z = simd_sub(omxx2, yy2);
  1029. simd128_t tmp[4];
  1030. tmp[0] = simd_mul(r0x, sx);
  1031. tmp[1] = simd_mul(r0y, sx);
  1032. tmp[2] = simd_mul(r0z, sx);
  1033. tmp[3] = zero;
  1034. transpose(dst + 0, sizeof(Matrix4), tmp);
  1035. tmp[0] = simd_mul(r1x, sy);
  1036. tmp[1] = simd_mul(r1y, sy);
  1037. tmp[2] = simd_mul(r1z, sy);
  1038. tmp[3] = zero;
  1039. transpose(dst + 1, sizeof(Matrix4), tmp);
  1040. tmp[0] = simd_mul(r2x, sz);
  1041. tmp[1] = simd_mul(r2y, sz);
  1042. tmp[2] = simd_mul(r2z, sz);
  1043. tmp[3] = zero;
  1044. transpose(dst + 2, sizeof(Matrix4), tmp);
  1045. tmp[0] = tx;
  1046. tmp[1] = ty;
  1047. tmp[2] = tz;
  1048. tmp[3] = one;
  1049. transpose(dst + 3, sizeof(Matrix4), tmp);
  1050. }
  1051. void srtToMatrix4(void* _dst, const void* _src, uint32_t _num)
  1052. {
  1053. uint8_t* dst = reinterpret_cast< uint8_t*>(_dst);
  1054. const uint8_t* src = reinterpret_cast<const uint8_t*>(_src);
  1055. if (!bx::isAligned(src, 16) )
  1056. {
  1057. for (uint32_t ii = 0, num = _num / 4; ii < num; ++ii)
  1058. {
  1059. srtToMatrix4_x4_Ref(dst, src);
  1060. src += 4*sizeof(Srt);
  1061. dst += 4*sizeof(Matrix4);
  1062. }
  1063. }
  1064. else
  1065. {
  1066. for (uint32_t ii = 0, num = _num / 4; ii < num; ++ii)
  1067. {
  1068. srtToMatrix4_x4_Simd(dst, src);
  1069. src += 4*sizeof(Srt);
  1070. dst += 4*sizeof(Matrix4);
  1071. }
  1072. }
  1073. for (uint32_t ii = 0, num = _num & 3; ii < num; ++ii)
  1074. {
  1075. srtToMatrix4_x1(dst, src);
  1076. src += sizeof(Srt);
  1077. dst += sizeof(Matrix4);
  1078. }
  1079. }
  1080. void EncoderImpl::submit(ViewId _id, ProgramHandle _program, OcclusionQueryHandle _occlusionQuery, uint32_t _depth, uint8_t _flags)
  1081. {
  1082. if (BX_ENABLED(BGFX_CONFIG_DEBUG_UNIFORM)
  1083. && (_flags & BGFX_DISCARD_STATE))
  1084. {
  1085. m_uniformSet.clear();
  1086. }
  1087. if (BX_ENABLED(BGFX_CONFIG_DEBUG_OCCLUSION)
  1088. && isValid(_occlusionQuery) )
  1089. {
  1090. BX_ASSERT(m_occlusionQuerySet.end() == m_occlusionQuerySet.find(_occlusionQuery.idx)
  1091. , "OcclusionQuery %d was already used for this frame."
  1092. , _occlusionQuery.idx
  1093. );
  1094. m_occlusionQuerySet.insert(_occlusionQuery.idx);
  1095. }
  1096. if (m_discard)
  1097. {
  1098. discard(_flags);
  1099. return;
  1100. }
  1101. if (0 == m_draw.m_numVertices
  1102. && 0 == m_draw.m_numIndices)
  1103. {
  1104. discard(_flags);
  1105. ++m_numDropped;
  1106. return;
  1107. }
  1108. const uint32_t renderItemIdx = bx::atomicFetchAndAddsat<uint32_t>(&m_frame->m_numRenderItems, 1, BGFX_CONFIG_MAX_DRAW_CALLS);
  1109. if (BGFX_CONFIG_MAX_DRAW_CALLS <= renderItemIdx)
  1110. {
  1111. discard(_flags);
  1112. ++m_numDropped;
  1113. return;
  1114. }
  1115. ++m_numSubmitted;
  1116. UniformBuffer* uniformBuffer = m_frame->m_uniformBuffer[m_uniformIdx];
  1117. m_uniformEnd = uniformBuffer->getPos();
  1118. m_key.m_program = isValid(_program)
  1119. ? _program
  1120. : ProgramHandle{0}
  1121. ;
  1122. m_key.m_view = _id;
  1123. SortKey::Enum type;
  1124. switch (s_ctx->m_view[_id].m_mode)
  1125. {
  1126. case ViewMode::Sequential: m_key.m_seq = s_ctx->getSeqIncr(_id); type = SortKey::SortSequence; break;
  1127. case ViewMode::DepthAscending: m_key.m_depth = _depth; type = SortKey::SortDepth; break;
  1128. case ViewMode::DepthDescending: m_key.m_depth = UINT32_MAX-_depth; type = SortKey::SortDepth; break;
  1129. default: m_key.m_depth = _depth; type = SortKey::SortProgram; break;
  1130. }
  1131. uint64_t key = m_key.encodeDraw(type);
  1132. m_frame->m_sortKeys[renderItemIdx] = key;
  1133. m_frame->m_sortValues[renderItemIdx] = RenderItemCount(renderItemIdx);
  1134. m_draw.m_uniformIdx = m_uniformIdx;
  1135. m_draw.m_uniformBegin = m_uniformBegin;
  1136. m_draw.m_uniformEnd = m_uniformEnd;
  1137. if (UINT8_MAX != m_draw.m_streamMask)
  1138. {
  1139. uint32_t numVertices = UINT32_MAX;
  1140. for (BitMaskToIndexIteratorT it(m_draw.m_streamMask); !it.isDone(); it.next() )
  1141. {
  1142. numVertices = bx::min(numVertices, m_numVertices[it.idx]);
  1143. }
  1144. m_draw.m_numVertices = numVertices;
  1145. }
  1146. else
  1147. {
  1148. m_draw.m_numVertices = m_numVertices[0];
  1149. }
  1150. if (isValid(_occlusionQuery) )
  1151. {
  1152. m_draw.m_stateFlags |= BGFX_STATE_INTERNAL_OCCLUSION_QUERY;
  1153. m_draw.m_occlusionQuery = _occlusionQuery;
  1154. }
  1155. m_frame->m_renderItem[renderItemIdx].draw = m_draw;
  1156. m_frame->m_renderItemBind[renderItemIdx] = m_bind;
  1157. m_draw.clear(_flags);
  1158. m_bind.clear(_flags);
  1159. if (_flags & BGFX_DISCARD_STATE)
  1160. {
  1161. m_uniformBegin = m_uniformEnd;
  1162. }
  1163. }
  1164. void EncoderImpl::dispatch(ViewId _id, ProgramHandle _handle, uint32_t _numX, uint32_t _numY, uint32_t _numZ, uint8_t _flags)
  1165. {
  1166. if (BX_ENABLED(BGFX_CONFIG_DEBUG_UNIFORM) )
  1167. {
  1168. m_uniformSet.clear();
  1169. }
  1170. if (m_discard)
  1171. {
  1172. discard(_flags);
  1173. return;
  1174. }
  1175. const uint32_t renderItemIdx = bx::atomicFetchAndAddsat<uint32_t>(&m_frame->m_numRenderItems, 1, BGFX_CONFIG_MAX_DRAW_CALLS);
  1176. if (BGFX_CONFIG_MAX_DRAW_CALLS-1 <= renderItemIdx)
  1177. {
  1178. discard(_flags);
  1179. ++m_numDropped;
  1180. return;
  1181. }
  1182. ++m_numSubmitted;
  1183. UniformBuffer* uniformBuffer = m_frame->m_uniformBuffer[m_uniformIdx];
  1184. m_uniformEnd = uniformBuffer->getPos();
  1185. m_compute.m_startMatrix = m_draw.m_startMatrix;
  1186. m_compute.m_numMatrices = m_draw.m_numMatrices;
  1187. m_compute.m_numX = bx::max(_numX, 1u);
  1188. m_compute.m_numY = bx::max(_numY, 1u);
  1189. m_compute.m_numZ = bx::max(_numZ, 1u);
  1190. m_key.m_program = _handle;
  1191. m_key.m_depth = 0;
  1192. m_key.m_view = _id;
  1193. m_key.m_seq = s_ctx->getSeqIncr(_id);
  1194. uint64_t key = m_key.encodeCompute();
  1195. m_frame->m_sortKeys[renderItemIdx] = key;
  1196. m_frame->m_sortValues[renderItemIdx] = RenderItemCount(renderItemIdx);
  1197. m_compute.m_uniformIdx = m_uniformIdx;
  1198. m_compute.m_uniformBegin = m_uniformBegin;
  1199. m_compute.m_uniformEnd = m_uniformEnd;
  1200. m_frame->m_renderItem[renderItemIdx].compute = m_compute;
  1201. m_frame->m_renderItemBind[renderItemIdx] = m_bind;
  1202. m_compute.clear(_flags);
  1203. m_bind.clear(_flags);
  1204. m_uniformBegin = m_uniformEnd;
  1205. }
  1206. void EncoderImpl::blit(ViewId _id, TextureHandle _dst, uint8_t _dstMip, uint16_t _dstX, uint16_t _dstY, uint16_t _dstZ, TextureHandle _src, uint8_t _srcMip, uint16_t _srcX, uint16_t _srcY, uint16_t _srcZ, uint16_t _width, uint16_t _height, uint16_t _depth)
  1207. {
  1208. BX_WARN(m_frame->m_numBlitItems < BGFX_CONFIG_MAX_BLIT_ITEMS
  1209. , "Exceed number of available blit items per frame. BGFX_CONFIG_MAX_BLIT_ITEMS is %d. Skipping blit."
  1210. , BGFX_CONFIG_MAX_BLIT_ITEMS
  1211. );
  1212. const uint32_t blitItemIdx = bx::atomicFetchAndAddsat<uint32_t>(&m_frame->m_numBlitItems, 1, BGFX_CONFIG_MAX_BLIT_ITEMS);
  1213. if (BGFX_CONFIG_MAX_BLIT_ITEMS-1 <= blitItemIdx)
  1214. {
  1215. return;
  1216. }
  1217. BlitItem& bi = m_frame->m_blitItem[blitItemIdx];
  1218. bi.m_srcX = _srcX;
  1219. bi.m_srcY = _srcY;
  1220. bi.m_srcZ = _srcZ;
  1221. bi.m_dstX = _dstX;
  1222. bi.m_dstY = _dstY;
  1223. bi.m_dstZ = _dstZ;
  1224. bi.m_width = _width;
  1225. bi.m_height = _height;
  1226. bi.m_depth = _depth;
  1227. bi.m_srcMip = _srcMip;
  1228. bi.m_dstMip = _dstMip;
  1229. bi.m_src = _src;
  1230. bi.m_dst = _dst;
  1231. BlitKey key;
  1232. key.m_view = _id;
  1233. key.m_item = bx::narrowCast<uint16_t>(blitItemIdx);
  1234. m_frame->m_blitKeys[blitItemIdx] = key.encode();
  1235. }
  1236. void Frame::sort()
  1237. {
  1238. BGFX_PROFILER_SCOPE("bgfx/Sort", kColorSubmit);
  1239. ViewId viewRemap[BGFX_CONFIG_MAX_VIEWS];
  1240. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  1241. {
  1242. viewRemap[m_viewRemap[ii] ] = ViewId(ii);
  1243. View& view = m_view[ii];
  1244. Rect rect(0, 0, uint16_t(m_resolution.width), uint16_t(m_resolution.height) );
  1245. if (isValid(view.m_fbh) )
  1246. {
  1247. const FrameBufferRef& fbr = s_ctx->m_frameBufferRef[view.m_fbh.idx];
  1248. const BackbufferRatio::Enum bbRatio = fbr.m_window
  1249. ? BackbufferRatio::Count
  1250. : BackbufferRatio::Enum(s_ctx->m_textureRef[fbr.un.m_th[0].idx].m_bbRatio)
  1251. ;
  1252. if (BackbufferRatio::Count != bbRatio)
  1253. {
  1254. getTextureSizeFromRatio(bbRatio, rect.m_width, rect.m_height);
  1255. }
  1256. else
  1257. {
  1258. rect.m_width = fbr.m_width;
  1259. rect.m_height = fbr.m_height;
  1260. }
  1261. }
  1262. view.m_rect.intersect(rect);
  1263. if (!view.m_scissor.isZero() )
  1264. {
  1265. view.m_scissor.intersect(rect);
  1266. }
  1267. }
  1268. for (uint32_t ii = 0, num = m_numRenderItems; ii < num; ++ii)
  1269. {
  1270. m_sortKeys[ii] = SortKey::remapView(m_sortKeys[ii], viewRemap);
  1271. }
  1272. bx::radixSort(m_sortKeys, s_ctx->m_tempKeys, m_sortValues, s_ctx->m_tempValues, m_numRenderItems);
  1273. for (uint32_t ii = 0, num = m_numBlitItems; ii < num; ++ii)
  1274. {
  1275. m_blitKeys[ii] = BlitKey::remapView(m_blitKeys[ii], viewRemap);
  1276. }
  1277. bx::radixSort(m_blitKeys, (uint32_t*)&s_ctx->m_tempKeys, m_numBlitItems);
  1278. m_uniformCacheFrame.sort(viewRemap, s_ctx->m_tempKeys);
  1279. }
  1280. RenderFrame::Enum renderFrame(int32_t _msecs)
  1281. {
  1282. if (BX_ENABLED(BGFX_CONFIG_MULTITHREADED) )
  1283. {
  1284. if (s_renderFrameCalled)
  1285. {
  1286. BGFX_CHECK_RENDER_THREAD();
  1287. }
  1288. if (NULL == s_ctx)
  1289. {
  1290. s_renderFrameCalled = true;
  1291. s_threadIndex = ~BGFX_API_THREAD_MAGIC;
  1292. return RenderFrame::NoContext;
  1293. }
  1294. int32_t msecs = -1 == _msecs
  1295. ? BGFX_CONFIG_API_SEMAPHORE_TIMEOUT
  1296. : _msecs
  1297. ;
  1298. RenderFrame::Enum result = s_ctx->renderFrame(msecs);
  1299. if (RenderFrame::Exiting == result)
  1300. {
  1301. Context* ctx = s_ctx;
  1302. ctx->apiSemWait();
  1303. s_ctx = NULL;
  1304. ctx->renderSemPost();
  1305. }
  1306. return result;
  1307. }
  1308. BX_ASSERT(false, "This call only makes sense if used with multi-threaded renderer.");
  1309. return RenderFrame::NoContext;
  1310. }
  1311. const uint32_t g_uniformTypeSize[] =
  1312. {
  1313. sizeof(int32_t),
  1314. 0,
  1315. 4*sizeof(float),
  1316. 3*3*sizeof(float),
  1317. 4*4*sizeof(float),
  1318. 1,
  1319. };
  1320. static_assert(UniformType::Count+1 == BX_COUNTOF(g_uniformTypeSize), "Must match UniformType::Enum!");
  1321. void UniformBuffer::writeUniform(UniformType::Enum _type, uint16_t _loc, const void* _value, uint16_t _num)
  1322. {
  1323. const uint32_t opcode = encodeOpcode(uint8_t(_type), _loc, _num, true);
  1324. write(opcode);
  1325. write(_value, g_uniformTypeSize[_type]*_num);
  1326. }
  1327. void UniformBuffer::writeUniformHandle(uint8_t _type, uint16_t _loc, UniformHandle _handle, uint16_t _num)
  1328. {
  1329. const uint32_t opcode = encodeOpcode(_type, _loc, _num, false);
  1330. write(opcode);
  1331. write(&_handle, sizeof(UniformHandle) );
  1332. }
  1333. void UniformBuffer::writeMarker(const bx::StringView& _name)
  1334. {
  1335. const uint16_t num = bx::narrowCast<uint16_t>(_name.getLength()+1);
  1336. const uint32_t opcode = encodeOpcode(bgfx::UniformType::Count, 0, num, true);
  1337. write(opcode);
  1338. write(_name.getPtr(), num-1);
  1339. const char zero = '\0';
  1340. write(&zero, 1);
  1341. }
  1342. struct CapsFlags
  1343. {
  1344. uint64_t m_flag;
  1345. const char* m_str;
  1346. };
  1347. static const CapsFlags s_capsFlags[] =
  1348. {
  1349. #define CAPS_FLAGS(_x) { _x, #_x }
  1350. CAPS_FLAGS(BGFX_CAPS_ALPHA_TO_COVERAGE),
  1351. CAPS_FLAGS(BGFX_CAPS_BLEND_INDEPENDENT),
  1352. CAPS_FLAGS(BGFX_CAPS_COMPUTE),
  1353. CAPS_FLAGS(BGFX_CAPS_CONSERVATIVE_RASTER),
  1354. CAPS_FLAGS(BGFX_CAPS_DRAW_INDIRECT),
  1355. CAPS_FLAGS(BGFX_CAPS_FRAGMENT_DEPTH),
  1356. CAPS_FLAGS(BGFX_CAPS_FRAGMENT_ORDERING),
  1357. CAPS_FLAGS(BGFX_CAPS_GRAPHICS_DEBUGGER),
  1358. CAPS_FLAGS(BGFX_CAPS_HDR10),
  1359. CAPS_FLAGS(BGFX_CAPS_HIDPI),
  1360. CAPS_FLAGS(BGFX_CAPS_IMAGE_RW),
  1361. CAPS_FLAGS(BGFX_CAPS_INDEX32),
  1362. CAPS_FLAGS(BGFX_CAPS_INSTANCING),
  1363. CAPS_FLAGS(BGFX_CAPS_OCCLUSION_QUERY),
  1364. CAPS_FLAGS(BGFX_CAPS_PRIMITIVE_ID),
  1365. CAPS_FLAGS(BGFX_CAPS_RENDERER_MULTITHREADED),
  1366. CAPS_FLAGS(BGFX_CAPS_SWAP_CHAIN),
  1367. CAPS_FLAGS(BGFX_CAPS_TEXTURE_2D_ARRAY),
  1368. CAPS_FLAGS(BGFX_CAPS_TEXTURE_3D),
  1369. CAPS_FLAGS(BGFX_CAPS_TEXTURE_BLIT),
  1370. CAPS_FLAGS(BGFX_CAPS_TEXTURE_COMPARE_ALL),
  1371. CAPS_FLAGS(BGFX_CAPS_TEXTURE_COMPARE_LEQUAL),
  1372. CAPS_FLAGS(BGFX_CAPS_TEXTURE_CUBE_ARRAY),
  1373. CAPS_FLAGS(BGFX_CAPS_TEXTURE_DIRECT_ACCESS),
  1374. CAPS_FLAGS(BGFX_CAPS_TEXTURE_READ_BACK),
  1375. CAPS_FLAGS(BGFX_CAPS_TRANSPARENT_BACKBUFFER),
  1376. CAPS_FLAGS(BGFX_CAPS_VARIABLE_RATE_SHADING),
  1377. CAPS_FLAGS(BGFX_CAPS_VERTEX_ATTRIB_HALF),
  1378. CAPS_FLAGS(BGFX_CAPS_VERTEX_ATTRIB_UINT10),
  1379. CAPS_FLAGS(BGFX_CAPS_VERTEX_ID),
  1380. CAPS_FLAGS(BGFX_CAPS_VIEWPORT_LAYER_ARRAY),
  1381. #undef CAPS_FLAGS
  1382. };
  1383. static void dumpCaps()
  1384. {
  1385. BX_TRACE("");
  1386. if (0 < g_caps.numGPUs)
  1387. {
  1388. BX_TRACE("Detected GPUs (%d):", g_caps.numGPUs);
  1389. BX_TRACE("\t +---------------- Index");
  1390. BX_TRACE("\t | +------------- Device ID");
  1391. BX_TRACE("\t | | +-------- Vendor ID");
  1392. for (uint32_t ii = 0; ii < g_caps.numGPUs; ++ii)
  1393. {
  1394. const Caps::GPU& gpu = g_caps.gpu[ii];
  1395. BX_UNUSED(gpu);
  1396. BX_TRACE("\t %d: %04x %04x"
  1397. , ii
  1398. , gpu.deviceId
  1399. , gpu.vendorId
  1400. );
  1401. }
  1402. BX_TRACE("");
  1403. }
  1404. BX_TRACE("GPU device, Device ID: %04x, Vendor ID: %04x", g_caps.deviceId, g_caps.vendorId);
  1405. BX_TRACE("");
  1406. RendererType::Enum renderers[RendererType::Count];
  1407. uint8_t num = getSupportedRenderers(BX_COUNTOF(renderers), renderers);
  1408. BX_TRACE("Supported renderer backends (%d):", num);
  1409. for (uint32_t ii = 0; ii < num; ++ii)
  1410. {
  1411. BX_TRACE("\t - %s", getRendererName(renderers[ii]) );
  1412. }
  1413. BX_TRACE("");
  1414. BX_TRACE("Sort key masks:");
  1415. BX_TRACE("\t View %016" PRIx64, kSortKeyViewMask);
  1416. BX_TRACE("\t Draw bit %016" PRIx64, kSortKeyDrawBit);
  1417. BX_TRACE("");
  1418. BX_TRACE("\tD Type %016" PRIx64, kSortKeyDrawTypeMask);
  1419. BX_TRACE("");
  1420. BX_TRACE("\tD0 Blend %016" PRIx64, kSortKeyDraw0BlendMask);
  1421. BX_TRACE("\tD0 Program %016" PRIx64, kSortKeyDraw0ProgramMask);
  1422. BX_TRACE("\tD0 Depth %016" PRIx64, kSortKeyDraw0DepthMask);
  1423. BX_TRACE("");
  1424. BX_TRACE("\tD1 Depth %016" PRIx64, kSortKeyDraw1DepthMask);
  1425. BX_TRACE("\tD1 Blend %016" PRIx64, kSortKeyDraw1BlendMask);
  1426. BX_TRACE("\tD1 Program %016" PRIx64, kSortKeyDraw1ProgramMask);
  1427. BX_TRACE("");
  1428. BX_TRACE("\tD2 Seq %016" PRIx64, kSortKeyDraw2SeqMask);
  1429. BX_TRACE("\tD2 Blend %016" PRIx64, kSortKeyDraw2BlendMask);
  1430. BX_TRACE("\tD2 Program %016" PRIx64, kSortKeyDraw2ProgramMask);
  1431. BX_TRACE("");
  1432. BX_TRACE("\t C Seq %016" PRIx64, kSortKeyComputeSeqMask);
  1433. BX_TRACE("\t C Program %016" PRIx64, kSortKeyComputeProgramMask);
  1434. BX_TRACE("");
  1435. BX_TRACE("Blit key masks:");
  1436. BX_TRACE("\tView %08" PRIx32, BlitKey::kViewMask);
  1437. BX_TRACE("\tItem %08" PRIx32, BlitKey::kItemMask);
  1438. BX_TRACE("");
  1439. BX_TRACE("Uniform cache key masks:");
  1440. BX_TRACE("\tView %016" PRIx64, UniformCacheKey::kViewMask);
  1441. BX_TRACE("\tHandle %016" PRIx64, UniformCacheKey::kHandleMask);
  1442. BX_TRACE("\tOffset %016" PRIx64, UniformCacheKey::kOffsetMask);
  1443. BX_TRACE("\tSize %016" PRIx64, UniformCacheKey::kSizeMask);
  1444. BX_TRACE("");
  1445. BX_TRACE("Capabilities (renderer %s, vendor 0x%04x, device 0x%04x):"
  1446. , s_ctx->m_renderCtx->getRendererName()
  1447. , g_caps.vendorId
  1448. , g_caps.deviceId
  1449. );
  1450. for (uint32_t ii = 0; ii < BX_COUNTOF(s_capsFlags); ++ii)
  1451. {
  1452. BX_TRACE("\t[%c] %s"
  1453. , 0 != (g_caps.supported & s_capsFlags[ii].m_flag) ? 'x' : ' '
  1454. , s_capsFlags[ii].m_str
  1455. );
  1456. }
  1457. BX_UNUSED(s_capsFlags);
  1458. BX_TRACE("");
  1459. BX_TRACE("Limits:");
  1460. #define LIMITS(_x) BX_TRACE("\t%-24s%10d", #_x, g_caps.limits._x)
  1461. LIMITS(maxDrawCalls);
  1462. LIMITS(maxBlits);
  1463. LIMITS(maxTextureSize);
  1464. LIMITS(maxTextureLayers);
  1465. LIMITS(maxViews);
  1466. LIMITS(maxFrameBuffers);
  1467. LIMITS(maxFBAttachments);
  1468. LIMITS(maxPrograms);
  1469. LIMITS(maxShaders);
  1470. LIMITS(maxTextures);
  1471. LIMITS(maxTextureSamplers);
  1472. LIMITS(maxComputeBindings);
  1473. LIMITS(maxVertexLayouts);
  1474. LIMITS(maxVertexStreams);
  1475. LIMITS(maxIndexBuffers);
  1476. LIMITS(maxVertexBuffers);
  1477. LIMITS(maxDynamicIndexBuffers);
  1478. LIMITS(maxDynamicVertexBuffers);
  1479. LIMITS(maxUniforms);
  1480. LIMITS(maxOcclusionQueries);
  1481. LIMITS(maxEncoders);
  1482. LIMITS(minResourceCbSize);
  1483. LIMITS(maxTransientVbSize);
  1484. LIMITS(maxTransientIbSize);
  1485. LIMITS(minUniformBufferSize);
  1486. #undef LIMITS
  1487. BX_TRACE("");
  1488. BX_TRACE("Supported texture formats:");
  1489. BX_TRACE("\t +---------------- 2D: x = supported / * = emulated");
  1490. BX_TRACE("\t |+--------------- 2D: sRGB format");
  1491. BX_TRACE("\t ||+-------------- 3D: x = supported / * = emulated");
  1492. BX_TRACE("\t |||+------------- 3D: sRGB format");
  1493. BX_TRACE("\t ||||+------------ Cube: x = supported / * = emulated");
  1494. BX_TRACE("\t |||||+----------- Cube: sRGB format");
  1495. BX_TRACE("\t ||||||+---------- vertex format");
  1496. BX_TRACE("\t |||||||+--------- image: i = read-write / r = read / w = write");
  1497. BX_TRACE("\t ||||||||+-------- framebuffer");
  1498. BX_TRACE("\t |||||||||+------- MSAA framebuffer");
  1499. BX_TRACE("\t ||||||||||+------ MSAA texture");
  1500. BX_TRACE("\t |||||||||||+----- Auto-generated mips");
  1501. BX_TRACE("\t |||||||||||| +-- name");
  1502. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  1503. {
  1504. if (TextureFormat::Unknown != ii
  1505. && TextureFormat::UnknownDepth != ii)
  1506. {
  1507. uint32_t flags = g_caps.formats[ii];
  1508. BX_TRACE("\t[%c%c%c%c%c%c%c%c%c%c%c%c] %s"
  1509. , flags&BGFX_CAPS_FORMAT_TEXTURE_2D ? 'x' : flags&BGFX_CAPS_FORMAT_TEXTURE_2D_EMULATED ? '*' : ' '
  1510. , flags&BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB ? 'l' : ' '
  1511. , flags&BGFX_CAPS_FORMAT_TEXTURE_3D ? 'x' : flags&BGFX_CAPS_FORMAT_TEXTURE_3D_EMULATED ? '*' : ' '
  1512. , flags&BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB ? 'l' : ' '
  1513. , flags&BGFX_CAPS_FORMAT_TEXTURE_CUBE ? 'x' : flags&BGFX_CAPS_FORMAT_TEXTURE_CUBE_EMULATED ? '*' : ' '
  1514. , flags&BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB ? 'l' : ' '
  1515. , flags&BGFX_CAPS_FORMAT_TEXTURE_VERTEX ? 'v' : ' '
  1516. , (flags&BGFX_CAPS_FORMAT_TEXTURE_IMAGE_READ) &&
  1517. (flags&BGFX_CAPS_FORMAT_TEXTURE_IMAGE_WRITE) ? 'i' : flags&BGFX_CAPS_FORMAT_TEXTURE_IMAGE_READ ? 'r' : flags&BGFX_CAPS_FORMAT_TEXTURE_IMAGE_WRITE ? 'w' : ' '
  1518. , flags&BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER ? 'f' : ' '
  1519. , flags&BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA ? '+' : ' '
  1520. , flags&BGFX_CAPS_FORMAT_TEXTURE_MSAA ? 'm' : ' '
  1521. , flags&BGFX_CAPS_FORMAT_TEXTURE_MIP_AUTOGEN ? 'M' : ' '
  1522. , getName(TextureFormat::Enum(ii) )
  1523. );
  1524. BX_UNUSED(flags);
  1525. }
  1526. }
  1527. BX_TRACE("");
  1528. BX_TRACE("NDC depth [%d, 1], origin %s left."
  1529. , g_caps.homogeneousDepth ? -1 : 0
  1530. , g_caps.originBottomLeft ? "bottom" : "top"
  1531. );
  1532. BX_TRACE("");
  1533. }
  1534. void dump(const Resolution& _resolution)
  1535. {
  1536. const uint32_t reset = _resolution.reset;
  1537. const uint32_t msaa = (reset&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  1538. BX_UNUSED(reset, msaa);
  1539. BX_TRACE("Reset back-buffer swap chain:");
  1540. BX_TRACE("\t%dx%d, formatColor: %s, formatDepthStencil: %s, numBackBuffers: %d, maxFrameLatency: %d"
  1541. , _resolution.width
  1542. , _resolution.height
  1543. , TextureFormat::Count == _resolution.formatColor
  1544. ? "*default*"
  1545. : bimg::getName(bimg::TextureFormat::Enum(_resolution.formatColor) )
  1546. , TextureFormat::Count == _resolution.formatDepthStencil
  1547. ? "*default*"
  1548. : bimg::getName(bimg::TextureFormat::Enum(_resolution.formatDepthStencil) )
  1549. , _resolution.numBackBuffers
  1550. , _resolution.maxFrameLatency
  1551. );
  1552. BX_TRACE("\t[%c] MSAAx%d", 0 != msaa ? 'x' : ' ', 1<<msaa);
  1553. BX_TRACE("\t[%c] Fullscreen", 0 != (reset & BGFX_RESET_FULLSCREEN) ? 'x' : ' ');
  1554. BX_TRACE("\t[%c] V-sync", 0 != (reset & BGFX_RESET_VSYNC) ? 'x' : ' ');
  1555. BX_TRACE("\t[%c] Max Anisotropy", 0 != (reset & BGFX_RESET_MAXANISOTROPY) ? 'x' : ' ');
  1556. BX_TRACE("\t[%c] Capture", 0 != (reset & BGFX_RESET_CAPTURE) ? 'x' : ' ');
  1557. BX_TRACE("\t[%c] Flush After Render", 0 != (reset & BGFX_RESET_FLUSH_AFTER_RENDER) ? 'x' : ' ');
  1558. BX_TRACE("\t[%c] Flip After Render", 0 != (reset & BGFX_RESET_FLIP_AFTER_RENDER) ? 'x' : ' ');
  1559. BX_TRACE("\t[%c] sRGB Back Buffer", 0 != (reset & BGFX_RESET_SRGB_BACKBUFFER) ? 'x' : ' ');
  1560. BX_TRACE("\t[%c] Transparent Back Buffer", 0 != (reset & BGFX_RESET_TRANSPARENT_BACKBUFFER) ? 'x' : ' ');
  1561. BX_TRACE("\t[%c] HDR10", 0 != (reset & BGFX_RESET_HDR10) ? 'x' : ' ');
  1562. BX_TRACE("\t[%c] Hi-DPI", 0 != (reset & BGFX_RESET_HIDPI) ? 'x' : ' ');
  1563. BX_TRACE("\t[%c] Depth Clamp", 0 != (reset & BGFX_RESET_DEPTH_CLAMP) ? 'x' : ' ');
  1564. BX_TRACE("\t[%c] Suspend", 0 != (reset & BGFX_RESET_SUSPEND) ? 'x' : ' ');
  1565. }
  1566. TextureFormat::Enum getViableTextureFormat(const bimg::ImageContainer& _imageContainer)
  1567. {
  1568. const uint32_t formatCaps = g_caps.formats[_imageContainer.m_format];
  1569. bool convert = 0 == formatCaps;
  1570. if (_imageContainer.m_cubeMap)
  1571. {
  1572. convert |= 0 == (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_CUBE)
  1573. && 0 != (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_CUBE_EMULATED)
  1574. ;
  1575. }
  1576. else if (_imageContainer.m_depth > 1)
  1577. {
  1578. convert |= 0 == (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_3D)
  1579. && 0 != (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_3D_EMULATED)
  1580. ;
  1581. }
  1582. else
  1583. {
  1584. convert |= 0 == (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_2D)
  1585. && 0 != (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_2D_EMULATED)
  1586. ;
  1587. }
  1588. if (convert)
  1589. {
  1590. return TextureFormat::BGRA8;
  1591. }
  1592. return TextureFormat::Enum(_imageContainer.m_format);
  1593. }
  1594. const char* getName(TextureFormat::Enum _fmt)
  1595. {
  1596. return bimg::getName(bimg::TextureFormat::Enum(_fmt));
  1597. }
  1598. const char* getName(UniformHandle _handle)
  1599. {
  1600. return getUniformRef(_handle).m_name.getCPtr();
  1601. }
  1602. const UniformRef& getUniformRef(UniformHandle _handle)
  1603. {
  1604. return s_ctx->m_uniformRef[_handle.idx];
  1605. }
  1606. const char* getName(ShaderHandle _handle)
  1607. {
  1608. return s_ctx->m_shaderRef[_handle.idx].m_name.getCPtr();
  1609. }
  1610. static const char* s_topologyName[] =
  1611. {
  1612. "Triangles",
  1613. "TriStrip",
  1614. "Lines",
  1615. "LineStrip",
  1616. "Points",
  1617. };
  1618. static_assert(Topology::Count == BX_COUNTOF(s_topologyName) );
  1619. const char* getName(Topology::Enum _topology)
  1620. {
  1621. return s_topologyName[bx::min(_topology, Topology::PointList)];
  1622. }
  1623. const char* getShaderTypeName(uint32_t _magic)
  1624. {
  1625. if (isShaderType(_magic, 'C') )
  1626. {
  1627. return "Compute";
  1628. }
  1629. else if (isShaderType(_magic, 'F') )
  1630. {
  1631. return "Fragment";
  1632. }
  1633. else if (isShaderType(_magic, 'V') )
  1634. {
  1635. return "Vertex";
  1636. }
  1637. BX_ASSERT(false, "Invalid shader type!");
  1638. return NULL;
  1639. }
  1640. static TextureFormat::Enum s_emulatedFormats[] =
  1641. {
  1642. TextureFormat::BC1,
  1643. TextureFormat::BC2,
  1644. TextureFormat::BC3,
  1645. TextureFormat::BC4,
  1646. TextureFormat::BC5,
  1647. TextureFormat::ETC1,
  1648. TextureFormat::ETC2,
  1649. TextureFormat::ETC2A,
  1650. TextureFormat::ETC2A1,
  1651. TextureFormat::PTC12,
  1652. TextureFormat::PTC14,
  1653. TextureFormat::PTC12A,
  1654. TextureFormat::PTC14A,
  1655. TextureFormat::PTC22,
  1656. TextureFormat::PTC24,
  1657. TextureFormat::ATC,
  1658. TextureFormat::ATCE,
  1659. TextureFormat::ATCI,
  1660. TextureFormat::ASTC4x4,
  1661. TextureFormat::ASTC5x4,
  1662. TextureFormat::ASTC5x5,
  1663. TextureFormat::ASTC6x5,
  1664. TextureFormat::ASTC6x6,
  1665. TextureFormat::ASTC8x5,
  1666. TextureFormat::ASTC8x6,
  1667. TextureFormat::ASTC8x8,
  1668. TextureFormat::ASTC10x5,
  1669. TextureFormat::ASTC10x6,
  1670. TextureFormat::ASTC10x8,
  1671. TextureFormat::ASTC10x10,
  1672. TextureFormat::ASTC12x10,
  1673. TextureFormat::ASTC12x12,
  1674. TextureFormat::BGRA8, // GL doesn't support BGRA8 without extensions.
  1675. TextureFormat::RGBA8, // D3D9 doesn't support RGBA8
  1676. };
  1677. bool Context::init(const Init& _init)
  1678. {
  1679. if (m_rendererInitialized)
  1680. {
  1681. BX_TRACE("Already initialized!");
  1682. return false;
  1683. }
  1684. m_headless = true
  1685. && RendererType::Noop != _init.type
  1686. && NULL == _init.platformData.ndt
  1687. && NULL == _init.platformData.nwh
  1688. && NULL == _init.platformData.context
  1689. && NULL == _init.platformData.backBuffer
  1690. && NULL == _init.platformData.backBufferDS
  1691. ;
  1692. BX_WARN(!m_headless, "bgfx platform data like window handle or backbuffer is not set, creating headless device.");
  1693. if (m_headless
  1694. && 0 != _init.resolution.width
  1695. && 0 != _init.resolution.height)
  1696. {
  1697. BX_TRACE("Initializing headless mode, resolution of non-existing backbuffer can't be larger than 0x0!");
  1698. return false;
  1699. }
  1700. m_init = _init;
  1701. m_init.resolution.reset &= ~BGFX_RESET_INTERNAL_FORCE;
  1702. m_init.resolution.numBackBuffers = bx::clamp<uint8_t>(_init.resolution.numBackBuffers, 2, BGFX_CONFIG_MAX_BACK_BUFFERS);
  1703. m_init.resolution.maxFrameLatency = bx::min<uint8_t>(_init.resolution.maxFrameLatency, BGFX_CONFIG_MAX_FRAME_LATENCY);
  1704. m_init.resolution.debugTextScale = bx::clamp<uint8_t>(_init.resolution.debugTextScale, 1, BGFX_CONFIG_DEBUG_TEXT_MAX_SCALE);
  1705. dump(m_init.resolution);
  1706. bx::memCopy(&g_platformData, &m_init.platformData, sizeof(PlatformData) );
  1707. m_exit = false;
  1708. m_flipped = true;
  1709. m_debug = BGFX_DEBUG_NONE;
  1710. m_frameTimeLast = bx::getHPCounter();
  1711. m_flipAfterRender = !!(m_init.resolution.reset & BGFX_RESET_FLIP_AFTER_RENDER);
  1712. m_submit->create(_init.limits.minResourceCbSize);
  1713. #if BGFX_CONFIG_MULTITHREADED
  1714. m_render->create(_init.limits.minResourceCbSize);
  1715. if (s_renderFrameCalled)
  1716. {
  1717. // When bgfx::renderFrame is called before init render thread
  1718. // should not be created.
  1719. BX_TRACE("Application called bgfx::renderFrame directly, not creating render thread.");
  1720. m_singleThreaded = true
  1721. && ~BGFX_API_THREAD_MAGIC == s_threadIndex
  1722. ;
  1723. }
  1724. else
  1725. {
  1726. BX_TRACE("Creating rendering thread.");
  1727. m_thread.init(renderThread, this, 0, "bgfx - renderer backend thread");
  1728. m_singleThreaded = false;
  1729. }
  1730. #else
  1731. BX_TRACE("Multithreaded renderer is disabled.");
  1732. m_singleThreaded = true;
  1733. #endif // BGFX_CONFIG_MULTITHREADED
  1734. BX_TRACE("Running in %s-threaded mode", m_singleThreaded ? "single" : "multi");
  1735. s_threadIndex = BGFX_API_THREAD_MAGIC;
  1736. for (uint32_t ii = 0; ii < BX_COUNTOF(m_viewRemap); ++ii)
  1737. {
  1738. m_viewRemap[ii] = ViewId(ii);
  1739. }
  1740. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  1741. {
  1742. resetView(ViewId(ii) );
  1743. }
  1744. for (uint32_t ii = 0; ii < BX_COUNTOF(m_clearColor); ++ii)
  1745. {
  1746. m_clearColor[ii][0] = 0.0f;
  1747. m_clearColor[ii][1] = 0.0f;
  1748. m_clearColor[ii][2] = 0.0f;
  1749. m_clearColor[ii][3] = 1.0f;
  1750. }
  1751. m_vertexLayoutRef.init();
  1752. CommandBuffer& cmdbuf = getCommandBuffer(CommandBuffer::RendererInit);
  1753. cmdbuf.write(_init);
  1754. frameNoRenderWait();
  1755. m_encoderHandle = bx::createHandleAlloc(g_allocator, _init.limits.maxEncoders);
  1756. m_encoder = (EncoderImpl*)bx::alignedAlloc(g_allocator, sizeof(EncoderImpl)*_init.limits.maxEncoders, BX_ALIGNOF(EncoderImpl) );
  1757. m_encoderStats = (EncoderStats*)bx::alloc(g_allocator, sizeof(EncoderStats)*_init.limits.maxEncoders);
  1758. for (uint32_t ii = 0, num = _init.limits.maxEncoders; ii < num; ++ii)
  1759. {
  1760. BX_PLACEMENT_NEW(&m_encoder[ii], EncoderImpl);
  1761. }
  1762. uint16_t idx = m_encoderHandle->alloc();
  1763. BX_ASSERT(0 == idx, "Internal encoder handle is not 0 (idx %d).", idx); BX_UNUSED(idx);
  1764. m_encoder[0].begin(m_submit, 0);
  1765. m_encoder0 = BX_ENABLED(BGFX_CONFIG_ENCODER_API_ONLY)
  1766. ? NULL
  1767. : reinterpret_cast<Encoder*>(&m_encoder[0])
  1768. ;
  1769. // Make sure renderer init is called from render thread.
  1770. // g_caps is initialized and available after this point.
  1771. frame();
  1772. if (!m_rendererInitialized)
  1773. {
  1774. getCommandBuffer(CommandBuffer::RendererShutdownEnd);
  1775. frame();
  1776. frame();
  1777. m_vertexLayoutRef.shutdown(m_layoutHandle);
  1778. m_submit->destroy();
  1779. #if BGFX_CONFIG_MULTITHREADED
  1780. m_render->destroy();
  1781. #endif // BGFX_CONFIG_MULTITHREADED
  1782. return false;
  1783. }
  1784. for (uint32_t ii = 0; ii < BX_COUNTOF(s_emulatedFormats); ++ii)
  1785. {
  1786. const uint32_t fmt = s_emulatedFormats[ii];
  1787. g_caps.formats[fmt] |= 0 == (g_caps.formats[fmt] & BGFX_CAPS_FORMAT_TEXTURE_2D ) ? BGFX_CAPS_FORMAT_TEXTURE_2D_EMULATED : 0;
  1788. g_caps.formats[fmt] |= 0 == (g_caps.formats[fmt] & BGFX_CAPS_FORMAT_TEXTURE_3D ) ? BGFX_CAPS_FORMAT_TEXTURE_3D_EMULATED : 0;
  1789. g_caps.formats[fmt] |= 0 == (g_caps.formats[fmt] & BGFX_CAPS_FORMAT_TEXTURE_CUBE) ? BGFX_CAPS_FORMAT_TEXTURE_CUBE_EMULATED : 0;
  1790. }
  1791. for (uint32_t ii = 0; ii < TextureFormat::UnknownDepth; ++ii)
  1792. {
  1793. bool convertable = bimg::imageConvert(bimg::TextureFormat::BGRA8, bimg::TextureFormat::Enum(ii) );
  1794. g_caps.formats[ii] |= 0 == (g_caps.formats[ii] & BGFX_CAPS_FORMAT_TEXTURE_2D ) && convertable ? BGFX_CAPS_FORMAT_TEXTURE_2D_EMULATED : 0;
  1795. g_caps.formats[ii] |= 0 == (g_caps.formats[ii] & BGFX_CAPS_FORMAT_TEXTURE_3D ) && convertable ? BGFX_CAPS_FORMAT_TEXTURE_3D_EMULATED : 0;
  1796. g_caps.formats[ii] |= 0 == (g_caps.formats[ii] & BGFX_CAPS_FORMAT_TEXTURE_CUBE) && convertable ? BGFX_CAPS_FORMAT_TEXTURE_CUBE_EMULATED : 0;
  1797. }
  1798. g_caps.rendererType = m_renderCtx->getRendererType();
  1799. initAttribTypeSizeTable(g_caps.rendererType);
  1800. g_caps.supported &= _init.capabilities;
  1801. g_caps.supported |= 0
  1802. | (BX_ENABLED(BGFX_CONFIG_MULTITHREADED) && !m_singleThreaded ? BGFX_CAPS_RENDERER_MULTITHREADED : 0)
  1803. | (isGraphicsDebuggerPresent() ? BGFX_CAPS_GRAPHICS_DEBUGGER : 0)
  1804. ;
  1805. dumpCaps();
  1806. m_textVideoMemBlitter.init(m_init.resolution.debugTextScale);
  1807. m_clearQuad.init();
  1808. m_submit->m_transientVb = createTransientVertexBuffer(_init.limits.maxTransientVbSize);
  1809. m_submit->m_transientIb = createTransientIndexBuffer(_init.limits.maxTransientIbSize);
  1810. frame();
  1811. if (BX_ENABLED(BGFX_CONFIG_MULTITHREADED) )
  1812. {
  1813. m_submit->m_transientVb = createTransientVertexBuffer(_init.limits.maxTransientVbSize);
  1814. m_submit->m_transientIb = createTransientIndexBuffer(_init.limits.maxTransientIbSize);
  1815. frame();
  1816. }
  1817. g_internalData.caps = getCaps();
  1818. return true;
  1819. }
  1820. void Context::shutdown()
  1821. {
  1822. getCommandBuffer(CommandBuffer::RendererShutdownBegin);
  1823. frame();
  1824. destroyTransientVertexBuffer(m_submit->m_transientVb);
  1825. destroyTransientIndexBuffer(m_submit->m_transientIb);
  1826. m_textVideoMemBlitter.shutdown();
  1827. m_clearQuad.shutdown();
  1828. frame();
  1829. if (BX_ENABLED(BGFX_CONFIG_MULTITHREADED) )
  1830. {
  1831. destroyTransientVertexBuffer(m_submit->m_transientVb);
  1832. destroyTransientIndexBuffer(m_submit->m_transientIb);
  1833. frame();
  1834. }
  1835. frame(); // If any VertexLayouts needs to be destroyed.
  1836. getCommandBuffer(CommandBuffer::RendererShutdownEnd);
  1837. frame();
  1838. m_encoder[0].end(true);
  1839. m_encoderHandle->free(0);
  1840. bx::destroyHandleAlloc(g_allocator, m_encoderHandle);
  1841. m_encoderHandle = NULL;
  1842. for (uint32_t ii = 0, num = g_caps.limits.maxEncoders; ii < num; ++ii)
  1843. {
  1844. m_encoder[ii].~EncoderImpl();
  1845. }
  1846. bx::alignedFree(g_allocator, m_encoder, BX_ALIGNOF(EncoderImpl) );
  1847. bx::free(g_allocator, m_encoderStats);
  1848. m_dynVertexBufferAllocator.compact();
  1849. m_dynIndexBufferAllocator.compact();
  1850. BX_ASSERT(
  1851. m_layoutHandle.getNumHandles() == m_vertexLayoutRef.m_vertexLayoutMap.getNumElements()
  1852. , "VertexLayoutRef mismatch, num handles %d, handles in hash map %d."
  1853. , m_layoutHandle.getNumHandles()
  1854. , m_vertexLayoutRef.m_vertexLayoutMap.getNumElements()
  1855. );
  1856. m_vertexLayoutRef.shutdown(m_layoutHandle);
  1857. #if BGFX_CONFIG_MULTITHREADED
  1858. // Render thread shutdown sequence.
  1859. renderSemWait(); // Wait for previous frame.
  1860. apiSemPost(); // OK to set context to NULL.
  1861. // s_ctx is NULL here.
  1862. renderSemWait(); // In RenderFrame::Exiting state.
  1863. if (m_thread.isRunning() )
  1864. {
  1865. m_thread.shutdown();
  1866. }
  1867. m_render->destroy();
  1868. #endif // BGFX_CONFIG_MULTITHREADED
  1869. bx::memSet(&g_internalData, 0, sizeof(InternalData) );
  1870. s_ctx = NULL;
  1871. m_submit->destroy();
  1872. if (BX_ENABLED(BGFX_CONFIG_DEBUG) )
  1873. {
  1874. #define CHECK_HANDLE_LEAK(_name, _handleAlloc) \
  1875. BX_MACRO_BLOCK_BEGIN \
  1876. if (0 != _handleAlloc.getNumHandles() ) \
  1877. { \
  1878. BX_TRACE("LEAK: %s %d (max: %d)" \
  1879. , _name \
  1880. , _handleAlloc.getNumHandles() \
  1881. , _handleAlloc.getMaxHandles() \
  1882. ); \
  1883. for (uint16_t ii = 0, num = _handleAlloc.getNumHandles(); ii < num; ++ii) \
  1884. { \
  1885. BX_TRACE("\t%3d: %4d", ii, _handleAlloc.getHandleAt(ii) ); \
  1886. } \
  1887. } \
  1888. BX_MACRO_BLOCK_END
  1889. #define CHECK_HANDLE_LEAK_NAME(_name, _handleAlloc, _type, _ref) \
  1890. BX_MACRO_BLOCK_BEGIN \
  1891. if (0 != _handleAlloc.getNumHandles() ) \
  1892. { \
  1893. BX_TRACE("LEAK: %s %d (max: %d)" \
  1894. , _name \
  1895. , _handleAlloc.getNumHandles() \
  1896. , _handleAlloc.getMaxHandles() \
  1897. ); \
  1898. for (uint16_t ii = 0, num = _handleAlloc.getNumHandles(); ii < num; ++ii) \
  1899. { \
  1900. uint16_t idx = _handleAlloc.getHandleAt(ii); \
  1901. const _type& ref = _ref[idx]; BX_UNUSED(ref); \
  1902. BX_TRACE("\t%3d: %4d %s" \
  1903. , ii \
  1904. , idx \
  1905. , ref.m_name.getCPtr() \
  1906. ); \
  1907. } \
  1908. } \
  1909. BX_MACRO_BLOCK_END
  1910. #define CHECK_HANDLE_LEAK_RC_NAME(_name, _handleAlloc, _type, _ref) \
  1911. BX_MACRO_BLOCK_BEGIN \
  1912. if (0 != _handleAlloc.getNumHandles() ) \
  1913. { \
  1914. BX_TRACE("LEAK: %s %d (max: %d)" \
  1915. , _name \
  1916. , _handleAlloc.getNumHandles() \
  1917. , _handleAlloc.getMaxHandles() \
  1918. ); \
  1919. for (uint16_t ii = 0, num = _handleAlloc.getNumHandles(); ii < num; ++ii) \
  1920. { \
  1921. uint16_t idx = _handleAlloc.getHandleAt(ii); \
  1922. const _type& ref = _ref[idx]; BX_UNUSED(ref); \
  1923. BX_TRACE("\t%3d: %4d %s (count %d)" \
  1924. , ii \
  1925. , idx \
  1926. , ref.m_name.getCPtr() \
  1927. , ref.m_refCount \
  1928. ); \
  1929. } \
  1930. } \
  1931. BX_MACRO_BLOCK_END
  1932. CHECK_HANDLE_LEAK ("DynamicIndexBufferHandle", m_dynamicIndexBufferHandle );
  1933. CHECK_HANDLE_LEAK ("DynamicVertexBufferHandle", m_dynamicVertexBufferHandle );
  1934. CHECK_HANDLE_LEAK_NAME ("IndexBufferHandle", m_indexBufferHandle, IndexBuffer, m_indexBuffers );
  1935. CHECK_HANDLE_LEAK ("VertexLayoutHandle", m_layoutHandle );
  1936. CHECK_HANDLE_LEAK_NAME ("VertexBufferHandle", m_vertexBufferHandle, VertexBuffer, m_vertexBuffers );
  1937. CHECK_HANDLE_LEAK_RC_NAME("ShaderHandle", m_shaderHandle, ShaderRef, m_shaderRef );
  1938. CHECK_HANDLE_LEAK ("ProgramHandle", m_programHandle );
  1939. CHECK_HANDLE_LEAK_RC_NAME("TextureHandle", m_textureHandle, TextureRef, m_textureRef );
  1940. CHECK_HANDLE_LEAK_NAME ("FrameBufferHandle", m_frameBufferHandle, FrameBufferRef, m_frameBufferRef);
  1941. CHECK_HANDLE_LEAK_RC_NAME("UniformHandle", m_uniformHandle, UniformRef, m_uniformRef );
  1942. CHECK_HANDLE_LEAK ("OcclusionQueryHandle", m_occlusionQueryHandle );
  1943. #undef CHECK_HANDLE_LEAK
  1944. #undef CHECK_HANDLE_LEAK_NAME
  1945. }
  1946. }
  1947. void Context::freeDynamicBuffers()
  1948. {
  1949. for (uint16_t ii = 0, num = m_numFreeDynamicIndexBufferHandles; ii < num; ++ii)
  1950. {
  1951. destroyDynamicIndexBufferInternal(m_freeDynamicIndexBufferHandle[ii]);
  1952. }
  1953. m_numFreeDynamicIndexBufferHandles = 0;
  1954. for (uint16_t ii = 0, num = m_numFreeDynamicVertexBufferHandles; ii < num; ++ii)
  1955. {
  1956. destroyDynamicVertexBufferInternal(m_freeDynamicVertexBufferHandle[ii]);
  1957. }
  1958. m_numFreeDynamicVertexBufferHandles = 0;
  1959. for (uint16_t ii = 0, num = m_numFreeOcclusionQueryHandles; ii < num; ++ii)
  1960. {
  1961. m_occlusionQueryHandle.free(m_freeOcclusionQueryHandle[ii].idx);
  1962. }
  1963. m_numFreeOcclusionQueryHandles = 0;
  1964. }
  1965. void Context::freeAllHandles(Frame* _frame)
  1966. {
  1967. for (uint16_t ii = 0, num = _frame->m_freeIndexBuffer.getNumQueued(); ii < num; ++ii)
  1968. {
  1969. m_indexBufferHandle.free(_frame->m_freeIndexBuffer.get(ii).idx);
  1970. }
  1971. for (uint16_t ii = 0, num = _frame->m_freeVertexBuffer.getNumQueued(); ii < num; ++ii)
  1972. {
  1973. destroyVertexBufferInternal(_frame->m_freeVertexBuffer.get(ii));
  1974. }
  1975. for (uint16_t ii = 0, num = _frame->m_freeVertexLayout.getNumQueued(); ii < num; ++ii)
  1976. {
  1977. m_layoutHandle.free(_frame->m_freeVertexLayout.get(ii).idx);
  1978. }
  1979. for (uint16_t ii = 0, num = _frame->m_freeShader.getNumQueued(); ii < num; ++ii)
  1980. {
  1981. m_shaderHandle.free(_frame->m_freeShader.get(ii).idx);
  1982. }
  1983. for (uint16_t ii = 0, num = _frame->m_freeProgram.getNumQueued(); ii < num; ++ii)
  1984. {
  1985. m_programHandle.free(_frame->m_freeProgram.get(ii).idx);
  1986. }
  1987. for (uint16_t ii = 0, num = _frame->m_freeTexture.getNumQueued(); ii < num; ++ii)
  1988. {
  1989. m_textureHandle.free(_frame->m_freeTexture.get(ii).idx);
  1990. }
  1991. for (uint16_t ii = 0, num = _frame->m_freeFrameBuffer.getNumQueued(); ii < num; ++ii)
  1992. {
  1993. m_frameBufferHandle.free(_frame->m_freeFrameBuffer.get(ii).idx);
  1994. }
  1995. for (uint16_t ii = 0, num = _frame->m_freeUniform.getNumQueued(); ii < num; ++ii)
  1996. {
  1997. UniformHandle handle = _frame->m_freeUniform.get(ii);
  1998. m_uniformCache.invalidate(handle);
  1999. m_uniformHandle.free(handle.idx);
  2000. }
  2001. }
  2002. Encoder* Context::begin(bool _forThread)
  2003. {
  2004. EncoderImpl* encoder = &m_encoder[0];
  2005. #if BGFX_CONFIG_MULTITHREADED
  2006. if (_forThread || BGFX_API_THREAD_MAGIC != s_threadIndex)
  2007. {
  2008. bx::MutexScope scopeLock(m_encoderApiLock);
  2009. uint16_t idx = m_encoderHandle->alloc();
  2010. if (kInvalidHandle == idx)
  2011. {
  2012. return NULL;
  2013. }
  2014. encoder = &m_encoder[idx];
  2015. encoder->begin(m_submit, uint8_t(idx) );
  2016. }
  2017. #else
  2018. BX_UNUSED(_forThread);
  2019. #endif // BGFX_CONFIG_MULTITHREADED
  2020. return reinterpret_cast<Encoder*>(encoder);
  2021. }
  2022. void Context::end(Encoder* _encoder)
  2023. {
  2024. #if BGFX_CONFIG_MULTITHREADED
  2025. EncoderImpl* encoder = reinterpret_cast<EncoderImpl*>(_encoder);
  2026. if (encoder != &m_encoder[0])
  2027. {
  2028. encoder->end(true);
  2029. m_encoderEndSem.post();
  2030. }
  2031. #else
  2032. BX_UNUSED(_encoder);
  2033. #endif // BGFX_CONFIG_MULTITHREADED
  2034. }
  2035. uint32_t Context::frame(bool _capture)
  2036. {
  2037. m_encoder[0].end(true);
  2038. #if BGFX_CONFIG_MULTITHREADED
  2039. bx::MutexScope resourceApiScope(m_resourceApiLock);
  2040. encoderApiWait();
  2041. bx::MutexScope encoderApiScope(m_encoderApiLock);
  2042. #else
  2043. encoderApiWait();
  2044. #endif // BGFX_CONFIG_MULTITHREADED
  2045. m_submit->m_capture = _capture;
  2046. uint32_t frameNum = m_submit->m_frameNum;
  2047. BGFX_PROFILER_SCOPE("bgfx/API thread frame", kColorSubmit);
  2048. // wait for render thread to finish
  2049. renderSemWait();
  2050. frameNoRenderWait();
  2051. m_encoder[0].begin(m_submit, 0);
  2052. return frameNum;
  2053. }
  2054. void Context::frameNoRenderWait()
  2055. {
  2056. swap();
  2057. // release render thread
  2058. apiSemPost();
  2059. }
  2060. void Context::swap()
  2061. {
  2062. freeDynamicBuffers();
  2063. m_submit->m_resolution = m_init.resolution;
  2064. m_init.resolution.reset &= ~BGFX_RESET_INTERNAL_FORCE;
  2065. m_submit->m_debug = m_debug;
  2066. m_submit->m_perfStats.numViews = 0;
  2067. bx::memCopy(m_submit->m_viewRemap, m_viewRemap, sizeof(m_viewRemap) );
  2068. m_uniformCache.frame(m_submit->m_uniformCacheFrame);
  2069. static_assert(bx::isTriviallyCopyable<View>(), "Must be memcopyiable...");
  2070. bx::memCopy(m_submit->m_view, m_view, sizeof(m_view) );
  2071. if (m_colorPaletteDirty > 0)
  2072. {
  2073. --m_colorPaletteDirty;
  2074. bx::memCopy(m_submit->m_colorPalette, m_clearColor, sizeof(m_clearColor) );
  2075. }
  2076. freeAllHandles(m_submit);
  2077. m_submit->resetFreeHandles();
  2078. m_submit->finish();
  2079. bx::swap(m_render, m_submit);
  2080. bx::memCopy(m_render->m_occlusion, m_submit->m_occlusion, sizeof(m_submit->m_occlusion) );
  2081. if (!BX_ENABLED(BGFX_CONFIG_MULTITHREADED)
  2082. || m_singleThreaded)
  2083. {
  2084. renderFrame();
  2085. }
  2086. uint32_t nextFrameNum = m_render->m_frameNum + 1;
  2087. m_submit->start(nextFrameNum);
  2088. bx::memSet(m_seq, 0, sizeof(m_seq) );
  2089. m_submit->m_textVideoMem->resize(
  2090. m_render->m_textVideoMem->m_small
  2091. , m_init.resolution.width
  2092. , m_init.resolution.height
  2093. );
  2094. const int64_t now = bx::getHPCounter();
  2095. m_submit->m_perfStats.cpuTimeFrame = now - m_frameTimeLast;
  2096. m_frameTimeLast = now;
  2097. }
  2098. ///
  2099. RendererContextI* rendererCreate(const Init& _init);
  2100. ///
  2101. void rendererDestroy(RendererContextI* _renderCtx);
  2102. void Context::flip()
  2103. {
  2104. if (m_rendererInitialized
  2105. && !m_flipped)
  2106. {
  2107. m_renderCtx->flip();
  2108. m_flipped = true;
  2109. if (m_renderCtx->isDeviceRemoved() )
  2110. {
  2111. // Something horribly went wrong, fallback to noop renderer.
  2112. rendererDestroy(m_renderCtx);
  2113. Init init;
  2114. init.type = RendererType::Noop;
  2115. m_renderCtx = rendererCreate(init);
  2116. g_caps.rendererType = RendererType::Noop;
  2117. }
  2118. }
  2119. }
  2120. #if BX_PLATFORM_OSX || BX_PLATFORM_IOS || BX_PLATFORM_VISIONOS
  2121. struct NSAutoreleasePoolScope
  2122. {
  2123. NSAutoreleasePoolScope()
  2124. {
  2125. id obj = class_createInstance(objc_getClass("NSAutoreleasePool"), 0);
  2126. typedef id(*objc_msgSend_init)(void*, SEL);
  2127. pool = ((objc_msgSend_init)objc_msgSend)(obj, sel_getUid("init") );
  2128. }
  2129. ~NSAutoreleasePoolScope()
  2130. {
  2131. typedef void(*objc_msgSend_release)(void*, SEL);
  2132. ((objc_msgSend_release)objc_msgSend)(pool, sel_getUid("release") );
  2133. }
  2134. id pool;
  2135. };
  2136. #endif // BX_PLATFORM_OSX || BX_PLATFORM_IOS || BX_PLATFORM_VISIONOS
  2137. RenderFrame::Enum Context::renderFrame(int32_t _msecs)
  2138. {
  2139. BGFX_PROFILER_SCOPE("bgfx::renderFrame", kColorSubmit);
  2140. #if BX_PLATFORM_OSX || BX_PLATFORM_IOS || BX_PLATFORM_VISIONOS
  2141. NSAutoreleasePoolScope pool;
  2142. #endif // BX_PLATFORM_OSX || BX_PLATFORM_IOS || BX_PLATFORM_VISIONOS
  2143. if (!m_flipAfterRender)
  2144. {
  2145. BGFX_PROFILER_SCOPE("bgfx/flip", kColorSubmit);
  2146. flip();
  2147. }
  2148. if (apiSemWait(_msecs) )
  2149. {
  2150. {
  2151. BGFX_PROFILER_SCOPE("bgfx/Exec commands pre", kColorResource);
  2152. rendererExecCommands(m_render->m_cmdPre);
  2153. }
  2154. if (m_rendererInitialized)
  2155. {
  2156. {
  2157. BGFX_PROFILER_SCOPE("bgfx/Render submit", kColorSubmit);
  2158. m_renderCtx->submit(m_render, m_clearQuad, m_textVideoMemBlitter);
  2159. m_flipped = false;
  2160. }
  2161. {
  2162. BGFX_PROFILER_SCOPE("bgfx/Screenshot", kColorResource);
  2163. for (uint8_t ii = 0, num = m_render->m_numScreenShots; ii < num; ++ii)
  2164. {
  2165. const ScreenShot& screenShot = m_render->m_screenShot[ii];
  2166. m_renderCtx->requestScreenShot(screenShot.handle, screenShot.filePath.getCPtr() );
  2167. }
  2168. }
  2169. }
  2170. {
  2171. BGFX_PROFILER_SCOPE("bgfx/Exec commands post", kColorResource);
  2172. rendererExecCommands(m_render->m_cmdPost);
  2173. }
  2174. renderSemPost();
  2175. if (m_flipAfterRender)
  2176. {
  2177. BGFX_PROFILER_SCOPE("bgfx/flip", kColorSubmit);
  2178. flip();
  2179. }
  2180. }
  2181. else
  2182. {
  2183. return RenderFrame::Timeout;
  2184. }
  2185. return m_exit
  2186. ? RenderFrame::Exiting
  2187. : RenderFrame::Render
  2188. ;
  2189. }
  2190. void rendererUpdateUniforms(RendererContextI* _renderCtx, UniformBuffer* _uniformBuffer, uint32_t _begin, uint32_t _end)
  2191. {
  2192. _uniformBuffer->reset(_begin);
  2193. while (_uniformBuffer->getPos() < _end)
  2194. {
  2195. uint32_t opcode = _uniformBuffer->read();
  2196. if (UniformType::End == opcode)
  2197. {
  2198. break;
  2199. }
  2200. uint8_t type;
  2201. uint16_t loc;
  2202. uint16_t num;
  2203. uint16_t copy;
  2204. UniformBuffer::decodeOpcode(opcode, type, loc, num, copy);
  2205. const uint32_t size = g_uniformTypeSize[type]*num;
  2206. const char* data = _uniformBuffer->read(size);
  2207. if (UniformType::Count > type)
  2208. {
  2209. if (copy)
  2210. {
  2211. _renderCtx->updateUniform(loc, data, size);
  2212. }
  2213. else
  2214. {
  2215. _renderCtx->updateUniform(loc, *(const char**)(data), size);
  2216. }
  2217. }
  2218. else
  2219. {
  2220. _renderCtx->setMarker(data, uint16_t(size)-1);
  2221. }
  2222. }
  2223. }
  2224. void Context::flushTextureUpdateBatch(CommandBuffer& _cmdbuf)
  2225. {
  2226. BGFX_PROFILER_SCOPE("flushTextureUpdateBatch", kColorResource);
  2227. if (m_textureUpdateBatch.sort() )
  2228. {
  2229. const uint32_t pos = _cmdbuf.m_pos;
  2230. for (uint32_t ii = 0, num = m_textureUpdateBatch.m_num; ii < num; ++ii)
  2231. {
  2232. _cmdbuf.m_pos = m_textureUpdateBatch.m_values[ii];
  2233. TextureHandle handle;
  2234. _cmdbuf.read(handle);
  2235. uint8_t side;
  2236. _cmdbuf.read(side);
  2237. uint8_t mip;
  2238. _cmdbuf.read(mip);
  2239. Rect rect;
  2240. _cmdbuf.read(rect);
  2241. uint16_t zz;
  2242. _cmdbuf.read(zz);
  2243. uint16_t depth;
  2244. _cmdbuf.read(depth);
  2245. uint16_t pitch;
  2246. _cmdbuf.read(pitch);
  2247. const Memory* mem;
  2248. _cmdbuf.read(mem);
  2249. m_renderCtx->updateTexture(handle, side, mip, rect, zz, depth, pitch, mem);
  2250. release(mem);
  2251. }
  2252. m_textureUpdateBatch.reset();
  2253. _cmdbuf.m_pos = pos;
  2254. }
  2255. }
  2256. typedef RendererContextI* (*RendererCreateFn)(const Init& _init);
  2257. typedef void (*RendererDestroyFn)();
  2258. #define BGFX_RENDERER_CONTEXT(_namespace) \
  2259. namespace _namespace \
  2260. { \
  2261. extern RendererContextI* rendererCreate(const Init& _init); \
  2262. extern void rendererDestroy(); \
  2263. }
  2264. BGFX_RENDERER_CONTEXT(noop);
  2265. BGFX_RENDERER_CONTEXT(agc);
  2266. BGFX_RENDERER_CONTEXT(d3d11);
  2267. BGFX_RENDERER_CONTEXT(d3d12);
  2268. BGFX_RENDERER_CONTEXT(gnm);
  2269. BGFX_RENDERER_CONTEXT(mtl);
  2270. BGFX_RENDERER_CONTEXT(nvn);
  2271. BGFX_RENDERER_CONTEXT(gl);
  2272. BGFX_RENDERER_CONTEXT(vk);
  2273. BGFX_RENDERER_CONTEXT(wgpu);
  2274. #undef BGFX_RENDERER_CONTEXT
  2275. struct RendererCreator
  2276. {
  2277. RendererCreateFn createFn;
  2278. RendererDestroyFn destroyFn;
  2279. const char* name;
  2280. bool supported;
  2281. };
  2282. static RendererCreator s_rendererCreator[] =
  2283. {
  2284. { noop::rendererCreate, noop::rendererDestroy, BGFX_RENDERER_NOOP_NAME, true }, // Noop
  2285. { agc::rendererCreate, agc::rendererDestroy, BGFX_RENDERER_AGC_NAME, !!BGFX_CONFIG_RENDERER_AGC }, // GNM
  2286. { d3d11::rendererCreate, d3d11::rendererDestroy, BGFX_RENDERER_DIRECT3D11_NAME, !!BGFX_CONFIG_RENDERER_DIRECT3D11 }, // Direct3D11
  2287. { d3d12::rendererCreate, d3d12::rendererDestroy, BGFX_RENDERER_DIRECT3D12_NAME, !!BGFX_CONFIG_RENDERER_DIRECT3D12 }, // Direct3D12
  2288. { gnm::rendererCreate, gnm::rendererDestroy, BGFX_RENDERER_GNM_NAME, !!BGFX_CONFIG_RENDERER_GNM }, // GNM
  2289. #if BX_PLATFORM_OSX || BX_PLATFORM_IOS || BX_PLATFORM_VISIONOS
  2290. { mtl::rendererCreate, mtl::rendererDestroy, BGFX_RENDERER_METAL_NAME, !!BGFX_CONFIG_RENDERER_METAL }, // Metal
  2291. #else
  2292. { noop::rendererCreate, noop::rendererDestroy, BGFX_RENDERER_NOOP_NAME, false }, // Noop
  2293. #endif // BX_PLATFORM_OSX || BX_PLATFORM_IOS || BX_PLATFORM_VISIONOS
  2294. { nvn::rendererCreate, nvn::rendererDestroy, BGFX_RENDERER_NVN_NAME, !!BGFX_CONFIG_RENDERER_NVN }, // NVN
  2295. { gl::rendererCreate, gl::rendererDestroy, BGFX_RENDERER_OPENGL_NAME, !!BGFX_CONFIG_RENDERER_OPENGLES }, // OpenGLES
  2296. { gl::rendererCreate, gl::rendererDestroy, BGFX_RENDERER_OPENGL_NAME, !!BGFX_CONFIG_RENDERER_OPENGL }, // OpenGL
  2297. { vk::rendererCreate, vk::rendererDestroy, BGFX_RENDERER_VULKAN_NAME, !!BGFX_CONFIG_RENDERER_VULKAN }, // Vulkan
  2298. { wgpu::rendererCreate, wgpu::rendererDestroy, BGFX_RENDERER_WEBGPU_NAME, !!BGFX_CONFIG_RENDERER_WEBGPU }, // WebGPU
  2299. };
  2300. static_assert(BX_COUNTOF(s_rendererCreator) == RendererType::Count);
  2301. void* findModule(const char* _name)
  2302. {
  2303. #if BX_PLATFORM_WINDOWS
  2304. if (NULL == _name
  2305. || '\0' == *_name)
  2306. {
  2307. return GetModuleHandleA(NULL);
  2308. }
  2309. HANDLE process = GetCurrentProcess();
  2310. DWORD size;
  2311. BOOL result = EnumProcessModules(process
  2312. , NULL
  2313. , 0
  2314. , &size
  2315. );
  2316. if (0 != result)
  2317. {
  2318. HMODULE* modules = (HMODULE*)BX_STACK_ALLOC(size);
  2319. result = EnumProcessModules(process
  2320. , modules
  2321. , size
  2322. , &size
  2323. );
  2324. if (0 != result)
  2325. {
  2326. char moduleName[MAX_PATH];
  2327. for (uint32_t ii = 0, num = uint32_t(size/sizeof(HMODULE) ); ii < num; ++ii)
  2328. {
  2329. result = GetModuleBaseNameA(process
  2330. , modules[ii]
  2331. , moduleName
  2332. , BX_COUNTOF(moduleName)
  2333. );
  2334. if (0 != result
  2335. && 0 == bx::strCmpI(_name, moduleName) )
  2336. {
  2337. return (void*)modules[ii];
  2338. }
  2339. }
  2340. }
  2341. }
  2342. return NULL;
  2343. #elif BX_PLATFORM_LINUX
  2344. struct DlIterateCallbackData
  2345. {
  2346. const char* name;
  2347. void* ptr;
  2348. } cbData =
  2349. {
  2350. .name = _name,
  2351. .ptr = NULL,
  2352. };
  2353. auto dlIterateCb = [](struct dl_phdr_info* _info, size_t /* _size */, void* _data) -> int
  2354. {
  2355. DlIterateCallbackData& data = *(DlIterateCallbackData*)_data;
  2356. if (bx::hasSuffix(_info->dlpi_name, data.name) )
  2357. {
  2358. data.ptr = dlopen(_info->dlpi_name, RTLD_NOW | RTLD_NOLOAD);
  2359. return 1;
  2360. }
  2361. return 0;
  2362. };
  2363. dl_iterate_phdr(dlIterateCb, &cbData);
  2364. return cbData.ptr;
  2365. #else
  2366. BX_UNUSED(_name);
  2367. return NULL;
  2368. #endif // BX_PLATFORM_WINDOWS
  2369. }
  2370. bool windowsVersionIs(Condition::Enum _op, uint32_t _version, uint32_t _build)
  2371. {
  2372. #if BX_PLATFORM_WINDOWS
  2373. RTL_OSVERSIONINFOW ovi;
  2374. bx::memSet(&ovi, 0 , sizeof(ovi));
  2375. ovi.dwOSVersionInfoSize = sizeof(ovi);
  2376. const HMODULE hMod = GetModuleHandleW(L"ntdll.dll");
  2377. if (NULL != hMod)
  2378. {
  2379. FARPROC (WINAPI* rtlGetVersionPtr) (PRTL_OSVERSIONINFOW) = reinterpret_cast<FARPROC (WINAPI*)(PRTL_OSVERSIONINFOW)>(bx::dlsym(hMod, "RtlGetVersion"));
  2380. if (NULL != rtlGetVersionPtr)
  2381. {
  2382. rtlGetVersionPtr(&ovi);
  2383. if (ovi.dwMajorVersion == 0)
  2384. {
  2385. return false;
  2386. }
  2387. ovi.dwBuildNumber = UINT32_MAX == _build ? UINT32_MAX : ovi.dwBuildNumber;
  2388. }
  2389. }
  2390. // _WIN32_WINNT_WIN10 0x0A00
  2391. // _WIN32_WINNT_WINBLUE 0x0603
  2392. // _WIN32_WINNT_WIN8 0x0602
  2393. // _WIN32_WINNT_WIN7 0x0601
  2394. // _WIN32_WINNT_VISTA 0x0600
  2395. const DWORD cMajorVersion = HIBYTE(_version);
  2396. const DWORD cMinorVersion = LOBYTE(_version);
  2397. switch (_op)
  2398. {
  2399. case Condition::LessEqual:
  2400. return (ovi.dwMajorVersion < cMajorVersion || (ovi.dwMajorVersion == cMajorVersion && ovi.dwMinorVersion <= cMinorVersion)) && ovi.dwBuildNumber <= _build;
  2401. case Condition::GreaterEqual:
  2402. return (ovi.dwMajorVersion > cMajorVersion || (ovi.dwMajorVersion == cMajorVersion && ovi.dwMinorVersion >= cMinorVersion)) && ovi.dwBuildNumber >= _build;
  2403. default:
  2404. return false;
  2405. }
  2406. #else
  2407. BX_UNUSED(_op, _version, _build);
  2408. return false;
  2409. #endif // BX_PLATFORM_WINDOWS
  2410. }
  2411. RendererContextI* rendererCreate(const Init& _init)
  2412. {
  2413. int32_t scores[RendererType::Count];
  2414. uint32_t numScores = 0;
  2415. for (uint32_t ii = 0; ii < RendererType::Count; ++ii)
  2416. {
  2417. RendererType::Enum renderer = RendererType::Enum(ii);
  2418. if (s_rendererCreator[ii].supported)
  2419. {
  2420. int32_t score = 0;
  2421. if (_init.type == renderer)
  2422. {
  2423. score += 1000;
  2424. }
  2425. score += RendererType::Noop != renderer ? 1 : 0;
  2426. if (BX_ENABLED(BX_PLATFORM_WINDOWS) )
  2427. {
  2428. if (windowsVersionIs(Condition::GreaterEqual, 0x0602) )
  2429. {
  2430. score += RendererType::Direct3D11 == renderer ? 20 : 0;
  2431. score += RendererType::Direct3D12 == renderer ? 10 : 0;
  2432. }
  2433. else if (windowsVersionIs(Condition::GreaterEqual, 0x0601) )
  2434. {
  2435. score += RendererType::Direct3D11 == renderer ? 20 : 0;
  2436. score += RendererType::Direct3D12 == renderer ? -100 : 0;
  2437. }
  2438. else
  2439. {
  2440. score += RendererType::Direct3D12 == renderer ? -100 : 0;
  2441. }
  2442. }
  2443. else if (BX_ENABLED(BX_PLATFORM_LINUX) )
  2444. {
  2445. score += RendererType::Vulkan == renderer ? 50 : 0;
  2446. score += RendererType::OpenGL == renderer ? 40 : 0;
  2447. score += RendererType::OpenGLES == renderer ? 30 : 0;
  2448. score += RendererType::Direct3D12 == renderer ? 20 : 0;
  2449. score += RendererType::Direct3D11 == renderer ? 10 : 0;
  2450. }
  2451. else if (BX_ENABLED(BX_PLATFORM_OSX) )
  2452. {
  2453. score += RendererType::Metal == renderer ? 20 : 0;
  2454. score += RendererType::Vulkan == renderer ? 10 : 0;
  2455. }
  2456. else if (BX_ENABLED(BX_PLATFORM_IOS) || BX_ENABLED(BX_PLATFORM_VISIONOS))
  2457. {
  2458. score += RendererType::Metal == renderer ? 20 : 0;
  2459. }
  2460. else if (BX_ENABLED(0
  2461. || BX_PLATFORM_ANDROID
  2462. || BX_PLATFORM_EMSCRIPTEN
  2463. || BX_PLATFORM_RPI
  2464. ) )
  2465. {
  2466. score += RendererType::OpenGLES == renderer ? 20 : 0;
  2467. }
  2468. else if (BX_ENABLED(BX_PLATFORM_PS4) )
  2469. {
  2470. score += RendererType::Gnm == renderer ? 20 : 0;
  2471. }
  2472. else if (BX_ENABLED(0
  2473. || BX_PLATFORM_XBOXONE
  2474. || BX_PLATFORM_WINRT
  2475. ) )
  2476. {
  2477. score += RendererType::Direct3D12 == renderer ? 20 : 0;
  2478. score += RendererType::Direct3D11 == renderer ? 10 : 0;
  2479. }
  2480. scores[numScores++] = (score<<8) | uint8_t(renderer);
  2481. }
  2482. }
  2483. bx::quickSort(scores, numScores, bx::compareDescending<int32_t>);
  2484. RendererContextI* renderCtx = NULL;
  2485. for (uint32_t ii = 0; ii < numScores; ++ii)
  2486. {
  2487. RendererType::Enum renderer = RendererType::Enum(scores[ii] & 0xff);
  2488. renderCtx = s_rendererCreator[renderer].createFn(_init);
  2489. if (NULL != renderCtx
  2490. || !_init.fallback)
  2491. {
  2492. break;
  2493. }
  2494. s_rendererCreator[renderer].supported = false;
  2495. }
  2496. return renderCtx;
  2497. }
  2498. void rendererDestroy(RendererContextI* _renderCtx)
  2499. {
  2500. if (NULL != _renderCtx)
  2501. {
  2502. s_rendererCreator[_renderCtx->getRendererType()].destroyFn();
  2503. }
  2504. }
  2505. void Context::rendererExecCommands(CommandBuffer& _cmdbuf)
  2506. {
  2507. _cmdbuf.reset();
  2508. bool end = false;
  2509. if (NULL == m_renderCtx)
  2510. {
  2511. uint8_t command;
  2512. _cmdbuf.read(command);
  2513. switch (command)
  2514. {
  2515. case CommandBuffer::RendererShutdownEnd:
  2516. m_exit = true;
  2517. return;
  2518. case CommandBuffer::End:
  2519. return;
  2520. default:
  2521. {
  2522. BX_ASSERT(CommandBuffer::RendererInit == command
  2523. , "RendererInit must be the first command in command buffer before initialization. Unexpected command %d?"
  2524. , command
  2525. );
  2526. BX_ASSERT(!m_rendererInitialized, "This shouldn't happen! Bad synchronization?");
  2527. Init init;
  2528. _cmdbuf.read(init);
  2529. m_renderCtx = rendererCreate(init);
  2530. m_rendererInitialized = NULL != m_renderCtx;
  2531. if (!m_rendererInitialized)
  2532. {
  2533. _cmdbuf.read(command);
  2534. BX_ASSERT(CommandBuffer::End == command, "Unexpected command %d?"
  2535. , command
  2536. );
  2537. return;
  2538. }
  2539. }
  2540. break;
  2541. }
  2542. }
  2543. do
  2544. {
  2545. uint8_t command;
  2546. _cmdbuf.read(command);
  2547. switch (command)
  2548. {
  2549. case CommandBuffer::RendererShutdownBegin:
  2550. {
  2551. BX_ASSERT(m_rendererInitialized, "This shouldn't happen! Bad synchronization?");
  2552. m_rendererInitialized = false;
  2553. }
  2554. break;
  2555. case CommandBuffer::RendererShutdownEnd:
  2556. {
  2557. BX_ASSERT(!m_rendererInitialized && !m_exit, "This shouldn't happen! Bad synchronization?");
  2558. rendererDestroy(m_renderCtx);
  2559. m_renderCtx = NULL;
  2560. m_exit = true;
  2561. }
  2562. [[fallthrough]];
  2563. case CommandBuffer::End:
  2564. end = true;
  2565. break;
  2566. case CommandBuffer::CreateIndexBuffer:
  2567. {
  2568. BGFX_PROFILER_SCOPE("CreateIndexBuffer", kColorResource);
  2569. IndexBufferHandle handle;
  2570. _cmdbuf.read(handle);
  2571. const Memory* mem;
  2572. _cmdbuf.read(mem);
  2573. uint16_t flags;
  2574. _cmdbuf.read(flags);
  2575. m_renderCtx->createIndexBuffer(handle, mem, flags);
  2576. release(mem);
  2577. }
  2578. break;
  2579. case CommandBuffer::DestroyIndexBuffer:
  2580. {
  2581. BGFX_PROFILER_SCOPE("DestroyIndexBuffer", kColorResource);
  2582. IndexBufferHandle handle;
  2583. _cmdbuf.read(handle);
  2584. m_renderCtx->destroyIndexBuffer(handle);
  2585. }
  2586. break;
  2587. case CommandBuffer::CreateVertexLayout:
  2588. {
  2589. BGFX_PROFILER_SCOPE("CreateVertexLayout", kColorResource);
  2590. VertexLayoutHandle handle;
  2591. _cmdbuf.read(handle);
  2592. VertexLayout layout;
  2593. _cmdbuf.read(layout);
  2594. m_renderCtx->createVertexLayout(handle, layout);
  2595. }
  2596. break;
  2597. case CommandBuffer::DestroyVertexLayout:
  2598. {
  2599. BGFX_PROFILER_SCOPE("DestroyVertexLayout", kColorResource);
  2600. VertexLayoutHandle handle;
  2601. _cmdbuf.read(handle);
  2602. m_renderCtx->destroyVertexLayout(handle);
  2603. }
  2604. break;
  2605. case CommandBuffer::CreateVertexBuffer:
  2606. {
  2607. BGFX_PROFILER_SCOPE("CreateVertexBuffer", kColorResource);
  2608. VertexBufferHandle handle;
  2609. _cmdbuf.read(handle);
  2610. const Memory* mem;
  2611. _cmdbuf.read(mem);
  2612. VertexLayoutHandle layoutHandle;
  2613. _cmdbuf.read(layoutHandle);
  2614. uint16_t flags;
  2615. _cmdbuf.read(flags);
  2616. m_renderCtx->createVertexBuffer(handle, mem, layoutHandle, flags);
  2617. release(mem);
  2618. }
  2619. break;
  2620. case CommandBuffer::DestroyVertexBuffer:
  2621. {
  2622. BGFX_PROFILER_SCOPE("DestroyVertexBuffer", kColorResource);
  2623. VertexBufferHandle handle;
  2624. _cmdbuf.read(handle);
  2625. m_renderCtx->destroyVertexBuffer(handle);
  2626. }
  2627. break;
  2628. case CommandBuffer::CreateDynamicIndexBuffer:
  2629. {
  2630. BGFX_PROFILER_SCOPE("CreateDynamicIndexBuffer", kColorResource);
  2631. IndexBufferHandle handle;
  2632. _cmdbuf.read(handle);
  2633. uint32_t size;
  2634. _cmdbuf.read(size);
  2635. uint16_t flags;
  2636. _cmdbuf.read(flags);
  2637. m_renderCtx->createDynamicIndexBuffer(handle, size, flags);
  2638. }
  2639. break;
  2640. case CommandBuffer::UpdateDynamicIndexBuffer:
  2641. {
  2642. BGFX_PROFILER_SCOPE("UpdateDynamicIndexBuffer", kColorResource);
  2643. IndexBufferHandle handle;
  2644. _cmdbuf.read(handle);
  2645. uint32_t offset;
  2646. _cmdbuf.read(offset);
  2647. uint32_t size;
  2648. _cmdbuf.read(size);
  2649. const Memory* mem;
  2650. _cmdbuf.read(mem);
  2651. m_renderCtx->updateDynamicIndexBuffer(handle, offset, size, mem);
  2652. release(mem);
  2653. }
  2654. break;
  2655. case CommandBuffer::DestroyDynamicIndexBuffer:
  2656. {
  2657. BGFX_PROFILER_SCOPE("DestroyDynamicIndexBuffer", kColorResource);
  2658. IndexBufferHandle handle;
  2659. _cmdbuf.read(handle);
  2660. m_renderCtx->destroyDynamicIndexBuffer(handle);
  2661. }
  2662. break;
  2663. case CommandBuffer::CreateDynamicVertexBuffer:
  2664. {
  2665. BGFX_PROFILER_SCOPE("CreateDynamicVertexBuffer", kColorResource);
  2666. VertexBufferHandle handle;
  2667. _cmdbuf.read(handle);
  2668. uint32_t size;
  2669. _cmdbuf.read(size);
  2670. uint16_t flags;
  2671. _cmdbuf.read(flags);
  2672. m_renderCtx->createDynamicVertexBuffer(handle, size, flags);
  2673. }
  2674. break;
  2675. case CommandBuffer::UpdateDynamicVertexBuffer:
  2676. {
  2677. BGFX_PROFILER_SCOPE("UpdateDynamicVertexBuffer", kColorResource);
  2678. VertexBufferHandle handle;
  2679. _cmdbuf.read(handle);
  2680. uint32_t offset;
  2681. _cmdbuf.read(offset);
  2682. uint32_t size;
  2683. _cmdbuf.read(size);
  2684. const Memory* mem;
  2685. _cmdbuf.read(mem);
  2686. m_renderCtx->updateDynamicVertexBuffer(handle, offset, size, mem);
  2687. release(mem);
  2688. }
  2689. break;
  2690. case CommandBuffer::DestroyDynamicVertexBuffer:
  2691. {
  2692. BGFX_PROFILER_SCOPE("DestroyDynamicVertexBuffer", kColorResource);
  2693. VertexBufferHandle handle;
  2694. _cmdbuf.read(handle);
  2695. m_renderCtx->destroyDynamicVertexBuffer(handle);
  2696. }
  2697. break;
  2698. case CommandBuffer::CreateShader:
  2699. {
  2700. BGFX_PROFILER_SCOPE("CreateShader", kColorResource);
  2701. ShaderHandle handle;
  2702. _cmdbuf.read(handle);
  2703. const Memory* mem;
  2704. _cmdbuf.read(mem);
  2705. m_renderCtx->createShader(handle, mem);
  2706. release(mem);
  2707. }
  2708. break;
  2709. case CommandBuffer::DestroyShader:
  2710. {
  2711. BGFX_PROFILER_SCOPE("DestroyShader", kColorResource);
  2712. ShaderHandle handle;
  2713. _cmdbuf.read(handle);
  2714. m_renderCtx->destroyShader(handle);
  2715. }
  2716. break;
  2717. case CommandBuffer::CreateProgram:
  2718. {
  2719. BGFX_PROFILER_SCOPE("CreateProgram", kColorResource);
  2720. ProgramHandle handle;
  2721. _cmdbuf.read(handle);
  2722. ShaderHandle vsh;
  2723. _cmdbuf.read(vsh);
  2724. ShaderHandle fsh;
  2725. _cmdbuf.read(fsh);
  2726. m_renderCtx->createProgram(handle, vsh, fsh);
  2727. }
  2728. break;
  2729. case CommandBuffer::DestroyProgram:
  2730. {
  2731. BGFX_PROFILER_SCOPE("DestroyProgram", kColorResource);
  2732. ProgramHandle handle;
  2733. _cmdbuf.read(handle);
  2734. m_renderCtx->destroyProgram(handle);
  2735. }
  2736. break;
  2737. case CommandBuffer::CreateTexture:
  2738. {
  2739. BGFX_PROFILER_SCOPE("CreateTexture", kColorResource);
  2740. TextureHandle handle;
  2741. _cmdbuf.read(handle);
  2742. const Memory* mem;
  2743. _cmdbuf.read(mem);
  2744. uint64_t flags;
  2745. _cmdbuf.read(flags);
  2746. uint8_t skip;
  2747. _cmdbuf.read(skip);
  2748. void* ptr = m_renderCtx->createTexture(handle, mem, flags, skip);
  2749. if (NULL != ptr)
  2750. {
  2751. setDirectAccessPtr(handle, ptr);
  2752. }
  2753. bx::MemoryReader reader(mem->data, mem->size);
  2754. bx::Error err;
  2755. uint32_t magic;
  2756. bx::read(&reader, magic, &err);
  2757. if (kChunkMagicTex == magic)
  2758. {
  2759. TextureCreate tc;
  2760. bx::read(&reader, tc, &err);
  2761. if (NULL != tc.m_mem)
  2762. {
  2763. release(tc.m_mem);
  2764. }
  2765. }
  2766. release(mem);
  2767. }
  2768. break;
  2769. case CommandBuffer::UpdateTexture:
  2770. {
  2771. BGFX_PROFILER_SCOPE("UpdateTexture", kColorResource);
  2772. if (m_textureUpdateBatch.isFull() )
  2773. {
  2774. flushTextureUpdateBatch(_cmdbuf);
  2775. }
  2776. uint32_t value = _cmdbuf.m_pos;
  2777. TextureHandle handle;
  2778. _cmdbuf.read(handle);
  2779. uint8_t side;
  2780. _cmdbuf.read(side);
  2781. uint8_t mip;
  2782. _cmdbuf.read(mip);
  2783. _cmdbuf.skip<Rect>();
  2784. _cmdbuf.skip<uint16_t>();
  2785. _cmdbuf.skip<uint16_t>();
  2786. _cmdbuf.skip<uint16_t>();
  2787. _cmdbuf.skip<Memory*>();
  2788. uint32_t key = (handle.idx<<16)
  2789. | (side<<8)
  2790. | mip
  2791. ;
  2792. m_textureUpdateBatch.add(key, value);
  2793. }
  2794. break;
  2795. case CommandBuffer::ReadTexture:
  2796. {
  2797. BGFX_PROFILER_SCOPE("ReadTexture", kColorResource);
  2798. TextureHandle handle;
  2799. _cmdbuf.read(handle);
  2800. void* data;
  2801. _cmdbuf.read(data);
  2802. uint8_t mip;
  2803. _cmdbuf.read(mip);
  2804. m_renderCtx->readTexture(handle, data, mip);
  2805. }
  2806. break;
  2807. case CommandBuffer::ResizeTexture:
  2808. {
  2809. BGFX_PROFILER_SCOPE("ResizeTexture", kColorResource);
  2810. TextureHandle handle;
  2811. _cmdbuf.read(handle);
  2812. uint16_t width;
  2813. _cmdbuf.read(width);
  2814. uint16_t height;
  2815. _cmdbuf.read(height);
  2816. uint8_t numMips;
  2817. _cmdbuf.read(numMips);
  2818. uint16_t numLayers;
  2819. _cmdbuf.read(numLayers);
  2820. m_renderCtx->resizeTexture(handle, width, height, numMips, numLayers);
  2821. }
  2822. break;
  2823. case CommandBuffer::DestroyTexture:
  2824. {
  2825. BGFX_PROFILER_SCOPE("DestroyTexture", kColorResource);
  2826. TextureHandle handle;
  2827. _cmdbuf.read(handle);
  2828. m_renderCtx->destroyTexture(handle);
  2829. }
  2830. break;
  2831. case CommandBuffer::CreateFrameBuffer:
  2832. {
  2833. BGFX_PROFILER_SCOPE("CreateFrameBuffer", kColorResource);
  2834. FrameBufferHandle handle;
  2835. _cmdbuf.read(handle);
  2836. bool window;
  2837. _cmdbuf.read(window);
  2838. if (window)
  2839. {
  2840. void* nwh;
  2841. _cmdbuf.read(nwh);
  2842. uint16_t width;
  2843. _cmdbuf.read(width);
  2844. uint16_t height;
  2845. _cmdbuf.read(height);
  2846. TextureFormat::Enum format;
  2847. _cmdbuf.read(format);
  2848. TextureFormat::Enum depthFormat;
  2849. _cmdbuf.read(depthFormat);
  2850. m_renderCtx->createFrameBuffer(handle, nwh, width, height, format, depthFormat);
  2851. }
  2852. else
  2853. {
  2854. uint8_t num;
  2855. _cmdbuf.read(num);
  2856. Attachment attachment[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS];
  2857. _cmdbuf.read(attachment, sizeof(Attachment) * num);
  2858. m_renderCtx->createFrameBuffer(handle, num, attachment);
  2859. }
  2860. }
  2861. break;
  2862. case CommandBuffer::DestroyFrameBuffer:
  2863. {
  2864. BGFX_PROFILER_SCOPE("DestroyFrameBuffer", kColorResource);
  2865. FrameBufferHandle handle;
  2866. _cmdbuf.read(handle);
  2867. m_renderCtx->destroyFrameBuffer(handle);
  2868. }
  2869. break;
  2870. case CommandBuffer::CreateUniform:
  2871. {
  2872. BGFX_PROFILER_SCOPE("CreateUniform", kColorResource);
  2873. UniformHandle handle;
  2874. _cmdbuf.read(handle);
  2875. UniformType::Enum type;
  2876. _cmdbuf.read(type);
  2877. uint16_t num;
  2878. _cmdbuf.read(num);
  2879. uint8_t len;
  2880. _cmdbuf.read(len);
  2881. const char* name = (const char*)_cmdbuf.skip(len);
  2882. m_renderCtx->createUniform(handle, type, num, name);
  2883. }
  2884. break;
  2885. case CommandBuffer::DestroyUniform:
  2886. {
  2887. BGFX_PROFILER_SCOPE("DestroyUniform", kColorResource);
  2888. UniformHandle handle;
  2889. _cmdbuf.read(handle);
  2890. m_renderCtx->destroyUniform(handle);
  2891. }
  2892. break;
  2893. case CommandBuffer::UpdateViewName:
  2894. {
  2895. BGFX_PROFILER_SCOPE("UpdateViewName", kColorResource);
  2896. ViewId id;
  2897. _cmdbuf.read(id);
  2898. uint16_t len;
  2899. _cmdbuf.read(len);
  2900. const char* name = (const char*)_cmdbuf.skip(len);
  2901. m_renderCtx->updateViewName(id, name);
  2902. }
  2903. break;
  2904. case CommandBuffer::InvalidateOcclusionQuery:
  2905. {
  2906. BGFX_PROFILER_SCOPE("InvalidateOcclusionQuery", kColorResource);
  2907. OcclusionQueryHandle handle;
  2908. _cmdbuf.read(handle);
  2909. m_renderCtx->invalidateOcclusionQuery(handle);
  2910. }
  2911. break;
  2912. case CommandBuffer::SetName:
  2913. {
  2914. BGFX_PROFILER_SCOPE("SetName", kColorResource);
  2915. Handle handle;
  2916. _cmdbuf.read(handle);
  2917. uint16_t len;
  2918. _cmdbuf.read(len);
  2919. const char* name = (const char*)_cmdbuf.skip(len);
  2920. m_renderCtx->setName(handle, name, len-1);
  2921. }
  2922. break;
  2923. default:
  2924. BX_ASSERT(false, "Invalid command: %d", command);
  2925. break;
  2926. }
  2927. } while (!end);
  2928. flushTextureUpdateBatch(_cmdbuf);
  2929. }
  2930. uint32_t weldVertices(void* _output, const VertexLayout& _layout, const void* _data, uint32_t _num, bool _index32, float _epsilon)
  2931. {
  2932. return weldVertices(_output, _layout, _data, _num, _index32, _epsilon, g_allocator);
  2933. }
  2934. uint32_t topologyConvert(TopologyConvert::Enum _conversion, void* _dst, uint32_t _dstSize, const void* _indices, uint32_t _numIndices, bool _index32)
  2935. {
  2936. return topologyConvert(_conversion, _dst, _dstSize, _indices, _numIndices, _index32, g_allocator);
  2937. }
  2938. void topologySortTriList(TopologySort::Enum _sort, void* _dst, uint32_t _dstSize, const float _dir[3], const float _pos[3], const void* _vertices, uint32_t _stride, const void* _indices, uint32_t _numIndices, bool _index32)
  2939. {
  2940. topologySortTriList(_sort, _dst, _dstSize, _dir, _pos, _vertices, _stride, _indices, _numIndices, _index32, g_allocator);
  2941. }
  2942. uint8_t getSupportedRenderers(uint8_t _max, RendererType::Enum* _enum)
  2943. {
  2944. _enum = _max == 0 ? NULL : _enum;
  2945. uint8_t num = 0;
  2946. for (uint8_t ii = 0; ii < RendererType::Count; ++ii)
  2947. {
  2948. if ( (RendererType::Direct3D11 == ii || RendererType::Direct3D12 == ii)
  2949. && windowsVersionIs(Condition::LessEqual, 0x0502) )
  2950. {
  2951. continue;
  2952. }
  2953. if (NULL == _enum)
  2954. {
  2955. num++;
  2956. }
  2957. else
  2958. {
  2959. if (num < _max
  2960. && s_rendererCreator[ii].supported)
  2961. {
  2962. _enum[num++] = RendererType::Enum(ii);
  2963. }
  2964. }
  2965. }
  2966. return num;
  2967. }
  2968. const char* getRendererName(RendererType::Enum _type)
  2969. {
  2970. BX_ASSERT(_type < RendererType::Count, "Invalid renderer type %d.", _type);
  2971. return s_rendererCreator[_type].name;
  2972. }
  2973. PlatformData::PlatformData()
  2974. : ndt(NULL)
  2975. , nwh(NULL)
  2976. , context(NULL)
  2977. , backBuffer(NULL)
  2978. , backBufferDS(NULL)
  2979. , type(NativeWindowHandleType::Default)
  2980. {
  2981. }
  2982. Resolution::Resolution()
  2983. : formatColor(TextureFormat::BGRA8)
  2984. , formatDepthStencil(TextureFormat::D24S8)
  2985. , width(1280)
  2986. , height(720)
  2987. , reset(BGFX_RESET_NONE)
  2988. , numBackBuffers(2)
  2989. , maxFrameLatency(0)
  2990. , debugTextScale(0)
  2991. {
  2992. }
  2993. Init::Limits::Limits()
  2994. : maxEncoders(BGFX_CONFIG_DEFAULT_MAX_ENCODERS)
  2995. , minResourceCbSize(BGFX_CONFIG_MIN_RESOURCE_COMMAND_BUFFER_SIZE)
  2996. , maxTransientVbSize(BGFX_CONFIG_MAX_TRANSIENT_VERTEX_BUFFER_SIZE)
  2997. , maxTransientIbSize(BGFX_CONFIG_MAX_TRANSIENT_INDEX_BUFFER_SIZE)
  2998. , minUniformBufferSize(BGFX_CONFIG_MIN_UNIFORM_BUFFER_SIZE)
  2999. {
  3000. }
  3001. Init::Init()
  3002. : type(RendererType::Count)
  3003. , vendorId(BGFX_PCI_ID_NONE)
  3004. , deviceId(0)
  3005. , capabilities(UINT64_MAX)
  3006. , debug(BX_ENABLED(BGFX_CONFIG_DEBUG) )
  3007. , profile(BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION) )
  3008. , fallback(true)
  3009. , callback(NULL)
  3010. , allocator(NULL)
  3011. {
  3012. }
  3013. void Attachment::init(TextureHandle _handle, Access::Enum _access, uint16_t _layer, uint16_t _numLayers, uint16_t _mip, uint8_t _resolve)
  3014. {
  3015. access = _access;
  3016. handle = _handle;
  3017. mip = _mip;
  3018. layer = _layer;
  3019. numLayers = _numLayers;
  3020. resolve = _resolve;
  3021. }
  3022. bool init(const Init& _userInit)
  3023. {
  3024. if (NULL != s_ctx)
  3025. {
  3026. BX_TRACE("bgfx is already initialized.");
  3027. return false;
  3028. }
  3029. Init init = _userInit;
  3030. init.limits.maxEncoders = bx::clamp<uint16_t>(init.limits.maxEncoders, 1, (0 != BGFX_CONFIG_MULTITHREADED) ? 128 : 1);
  3031. init.limits.minResourceCbSize = bx::min<uint32_t>(init.limits.minResourceCbSize, BGFX_CONFIG_MIN_RESOURCE_COMMAND_BUFFER_SIZE);
  3032. struct ErrorState
  3033. {
  3034. enum Enum
  3035. {
  3036. Default,
  3037. ContextAllocated,
  3038. };
  3039. };
  3040. ErrorState::Enum errorState = ErrorState::Default;
  3041. if (NULL != init.allocator)
  3042. {
  3043. g_allocator = init.allocator;
  3044. }
  3045. else
  3046. {
  3047. bx::DefaultAllocator allocator;
  3048. g_allocator =
  3049. s_allocatorStub = BX_NEW(&allocator, AllocatorStub);
  3050. }
  3051. if (NULL != init.callback)
  3052. {
  3053. g_callback = init.callback;
  3054. }
  3055. else
  3056. {
  3057. g_callback =
  3058. s_callbackStub = BX_NEW(g_allocator, CallbackStub);
  3059. }
  3060. bx::memSet(&g_caps, 0, sizeof(g_caps) );
  3061. g_caps.limits.maxDrawCalls = BGFX_CONFIG_MAX_DRAW_CALLS;
  3062. g_caps.limits.maxBlits = BGFX_CONFIG_MAX_BLIT_ITEMS;
  3063. g_caps.limits.maxTextureSize = 0;
  3064. g_caps.limits.maxTextureLayers = 1;
  3065. g_caps.limits.maxViews = BGFX_CONFIG_MAX_VIEWS;
  3066. g_caps.limits.maxFrameBuffers = BGFX_CONFIG_MAX_FRAME_BUFFERS;
  3067. g_caps.limits.maxPrograms = BGFX_CONFIG_MAX_PROGRAMS;
  3068. g_caps.limits.maxShaders = BGFX_CONFIG_MAX_SHADERS;
  3069. g_caps.limits.maxTextures = BGFX_CONFIG_MAX_TEXTURES;
  3070. g_caps.limits.maxTextureSamplers = BGFX_CONFIG_MAX_TEXTURE_SAMPLERS;
  3071. g_caps.limits.maxComputeBindings = 0;
  3072. g_caps.limits.maxVertexLayouts = BGFX_CONFIG_MAX_VERTEX_LAYOUTS;
  3073. g_caps.limits.maxVertexStreams = 1;
  3074. g_caps.limits.maxIndexBuffers = BGFX_CONFIG_MAX_INDEX_BUFFERS;
  3075. g_caps.limits.maxVertexBuffers = BGFX_CONFIG_MAX_VERTEX_BUFFERS;
  3076. g_caps.limits.maxDynamicIndexBuffers = BGFX_CONFIG_MAX_DYNAMIC_INDEX_BUFFERS;
  3077. g_caps.limits.maxDynamicVertexBuffers = BGFX_CONFIG_MAX_DYNAMIC_VERTEX_BUFFERS;
  3078. g_caps.limits.maxUniforms = BGFX_CONFIG_MAX_UNIFORMS;
  3079. g_caps.limits.maxOcclusionQueries = BGFX_CONFIG_MAX_OCCLUSION_QUERIES;
  3080. g_caps.limits.maxFBAttachments = 1;
  3081. g_caps.limits.maxEncoders = init.limits.maxEncoders;
  3082. g_caps.limits.minResourceCbSize = init.limits.minResourceCbSize;
  3083. g_caps.limits.maxTransientVbSize = init.limits.maxTransientVbSize;
  3084. g_caps.limits.maxTransientIbSize = init.limits.maxTransientIbSize;
  3085. g_caps.limits.minUniformBufferSize = init.limits.minUniformBufferSize;
  3086. g_caps.vendorId = init.vendorId;
  3087. g_caps.deviceId = init.deviceId;
  3088. BX_TRACE("Init...");
  3089. // bgfx 1.104.7082
  3090. // ^ ^^^ ^^^^
  3091. // | | +--- Commit number (https://github.com/bkaradzic/bgfx / git rev-list --count HEAD)
  3092. // | +------- API version (from https://github.com/bkaradzic/bgfx/blob/master/scripts/bgfx.idl#L4)
  3093. // +--------- Major revision (always 1)
  3094. BX_TRACE("Version 1.%d.%d (commit: " BGFX_REV_SHA1 ")", BGFX_API_VERSION, BGFX_REV_NUMBER);
  3095. errorState = ErrorState::ContextAllocated;
  3096. s_ctx = BX_ALIGNED_NEW(g_allocator, Context, Context::kAlignment);
  3097. if (s_ctx->init(init) )
  3098. {
  3099. BX_TRACE("Init complete.");
  3100. return true;
  3101. }
  3102. BX_TRACE("Init failed.");
  3103. switch (errorState)
  3104. {
  3105. case ErrorState::ContextAllocated:
  3106. bx::deleteObject(g_allocator, s_ctx, Context::kAlignment);
  3107. s_ctx = NULL;
  3108. [[fallthrough]];
  3109. case ErrorState::Default:
  3110. if (NULL != s_callbackStub)
  3111. {
  3112. bx::deleteObject(g_allocator, s_callbackStub);
  3113. s_callbackStub = NULL;
  3114. }
  3115. if (NULL != s_allocatorStub)
  3116. {
  3117. bx::DefaultAllocator allocator;
  3118. bx::deleteObject(&allocator, s_allocatorStub);
  3119. s_allocatorStub = NULL;
  3120. }
  3121. s_threadIndex = 0;
  3122. g_callback = NULL;
  3123. g_allocator = NULL;
  3124. break;
  3125. }
  3126. return false;
  3127. }
  3128. void shutdown()
  3129. {
  3130. BX_TRACE("Shutdown...");
  3131. BGFX_CHECK_API_THREAD();
  3132. Context* ctx = s_ctx; // it's going to be NULLd inside shutdown.
  3133. ctx->shutdown();
  3134. BX_ASSERT(NULL == s_ctx, "bgfx is should be uninitialized here.");
  3135. bx::deleteObject(g_allocator, ctx, Context::kAlignment);
  3136. BX_TRACE("Shutdown complete.");
  3137. if (NULL != s_allocatorStub)
  3138. {
  3139. s_allocatorStub->checkLeaks();
  3140. }
  3141. if (NULL != s_callbackStub)
  3142. {
  3143. bx::deleteObject(g_allocator, s_callbackStub);
  3144. s_callbackStub = NULL;
  3145. }
  3146. if (NULL != s_allocatorStub)
  3147. {
  3148. bx::DefaultAllocator allocator;
  3149. bx::deleteObject(&allocator, s_allocatorStub);
  3150. s_allocatorStub = NULL;
  3151. }
  3152. s_threadIndex = 0;
  3153. g_callback = NULL;
  3154. g_allocator = NULL;
  3155. }
  3156. void reset(uint32_t _width, uint32_t _height, uint32_t _flags, TextureFormat::Enum _format)
  3157. {
  3158. BGFX_CHECK_API_THREAD();
  3159. BX_ASSERT(0 == (_flags&BGFX_RESET_RESERVED_MASK), "Do not set reset reserved flags!");
  3160. s_ctx->reset(_width, _height, _flags, _format);
  3161. }
  3162. Encoder* begin(bool _forThread)
  3163. {
  3164. return s_ctx->begin(_forThread);
  3165. }
  3166. #define BGFX_ENCODER(_func) reinterpret_cast<EncoderImpl*>(this)->_func
  3167. void Encoder::setMarker(const char* _name, int32_t _len)
  3168. {
  3169. BGFX_ENCODER(setMarker(bx::StringView(_name, _len) ) );
  3170. }
  3171. void Encoder::setState(uint64_t _state, uint32_t _rgba)
  3172. {
  3173. BX_ASSERT(0 == (_state&BGFX_STATE_RESERVED_MASK), "Do not set state reserved flags!");
  3174. BGFX_ENCODER(setState(_state, _rgba) );
  3175. }
  3176. void Encoder::setCondition(OcclusionQueryHandle _handle, bool _visible)
  3177. {
  3178. BGFX_CHECK_CAPS(BGFX_CAPS_OCCLUSION_QUERY, "Occlusion query is not supported!");
  3179. BGFX_ENCODER(setCondition(_handle, _visible) );
  3180. }
  3181. void Encoder::setStencil(uint32_t _fstencil, uint32_t _bstencil)
  3182. {
  3183. BGFX_ENCODER(setStencil(_fstencil, _bstencil) );
  3184. }
  3185. uint16_t Encoder::setScissor(uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height)
  3186. {
  3187. return BGFX_ENCODER(setScissor(_x, _y, _width, _height) );
  3188. }
  3189. void Encoder::setScissor(uint16_t _cache)
  3190. {
  3191. BGFX_ENCODER(setScissor(_cache) );
  3192. }
  3193. uint32_t Encoder::setTransform(const void* _mtx, uint16_t _num)
  3194. {
  3195. return BGFX_ENCODER(setTransform(_mtx, _num) );
  3196. }
  3197. uint32_t Encoder::allocTransform(Transform* _transform, uint16_t _num)
  3198. {
  3199. return BGFX_ENCODER(allocTransform(_transform, _num) );
  3200. }
  3201. void Encoder::setTransform(uint32_t _cache, uint16_t _num)
  3202. {
  3203. BGFX_ENCODER(setTransform(_cache, _num) );
  3204. }
  3205. void Encoder::setUniform(UniformHandle _handle, const void* _value, uint16_t _num)
  3206. {
  3207. BGFX_CHECK_HANDLE("setUniform", s_ctx->m_uniformHandle, _handle);
  3208. const UniformRef& uniform = s_ctx->m_uniformRef[_handle.idx];
  3209. BX_ASSERT(uniform.m_freq == UniformFreq::Draw, "Setting uniform per draw call, but uniform is created with different bgfx::UniformFreq::Enum!");
  3210. BX_ASSERT(isValid(_handle) && 0 < uniform.m_refCount, "Setting invalid uniform (handle %3d)!", _handle.idx);
  3211. BX_ASSERT(_num == UINT16_MAX || uniform.m_num >= _num, "Truncated uniform update. %d (max: %d)", _num, uniform.m_num);
  3212. BGFX_ENCODER(setUniform(uniform.m_type, _handle, _value, UINT16_MAX != _num ? _num : uniform.m_num) );
  3213. }
  3214. void Encoder::setIndexBuffer(IndexBufferHandle _handle)
  3215. {
  3216. setIndexBuffer(_handle, 0, UINT32_MAX);
  3217. }
  3218. void Encoder::setIndexBuffer(IndexBufferHandle _handle, uint32_t _firstIndex, uint32_t _numIndices)
  3219. {
  3220. BGFX_CHECK_HANDLE("setIndexBuffer", s_ctx->m_indexBufferHandle, _handle);
  3221. const IndexBuffer& ib = s_ctx->m_indexBuffers[_handle.idx];
  3222. BGFX_ENCODER(setIndexBuffer(_handle, ib, _firstIndex, _numIndices) );
  3223. }
  3224. void Encoder::setIndexBuffer(DynamicIndexBufferHandle _handle)
  3225. {
  3226. setIndexBuffer(_handle, 0, UINT32_MAX);
  3227. }
  3228. void Encoder::setIndexBuffer(DynamicIndexBufferHandle _handle, uint32_t _firstIndex, uint32_t _numIndices)
  3229. {
  3230. BGFX_CHECK_HANDLE("setIndexBuffer", s_ctx->m_dynamicIndexBufferHandle, _handle);
  3231. const DynamicIndexBuffer& dib = s_ctx->m_dynamicIndexBuffers[_handle.idx];
  3232. BGFX_ENCODER(setIndexBuffer(dib, _firstIndex, _numIndices) );
  3233. }
  3234. void Encoder::setIndexBuffer(const TransientIndexBuffer* _tib)
  3235. {
  3236. setIndexBuffer(_tib, 0, UINT32_MAX);
  3237. }
  3238. void Encoder::setIndexBuffer(const TransientIndexBuffer* _tib, uint32_t _firstIndex, uint32_t _numIndices)
  3239. {
  3240. BX_ASSERT(NULL != _tib, "_tib can't be NULL");
  3241. BGFX_CHECK_HANDLE("setIndexBuffer", s_ctx->m_indexBufferHandle, _tib->handle);
  3242. BGFX_ENCODER(setIndexBuffer(_tib, _firstIndex, _numIndices) );
  3243. }
  3244. void Encoder::setVertexBuffer(
  3245. uint8_t _stream
  3246. , VertexBufferHandle _handle
  3247. , uint32_t _startVertex
  3248. , uint32_t _numVertices
  3249. , VertexLayoutHandle _layoutHandle
  3250. )
  3251. {
  3252. BGFX_CHECK_HANDLE("setVertexBuffer", s_ctx->m_vertexBufferHandle, _handle);
  3253. BGFX_CHECK_HANDLE_INVALID_OK("setVertexBuffer", s_ctx->m_layoutHandle, _layoutHandle);
  3254. BGFX_ENCODER(setVertexBuffer(_stream, _handle, _startVertex, _numVertices, _layoutHandle) );
  3255. }
  3256. void Encoder::setVertexBuffer(uint8_t _stream, VertexBufferHandle _handle)
  3257. {
  3258. setVertexBuffer(_stream, _handle, 0, UINT32_MAX);
  3259. }
  3260. void Encoder::setVertexBuffer(
  3261. uint8_t _stream
  3262. , DynamicVertexBufferHandle _handle
  3263. , uint32_t _startVertex
  3264. , uint32_t _numVertices
  3265. , VertexLayoutHandle _layoutHandle
  3266. )
  3267. {
  3268. BGFX_CHECK_HANDLE("setVertexBuffer", s_ctx->m_dynamicVertexBufferHandle, _handle);
  3269. BGFX_CHECK_HANDLE_INVALID_OK("setVertexBuffer", s_ctx->m_layoutHandle, _layoutHandle);
  3270. const DynamicVertexBuffer& dvb = s_ctx->m_dynamicVertexBuffers[_handle.idx];
  3271. BGFX_ENCODER(setVertexBuffer(_stream, dvb, _startVertex, _numVertices, _layoutHandle) );
  3272. }
  3273. void Encoder::setVertexBuffer(uint8_t _stream, DynamicVertexBufferHandle _handle)
  3274. {
  3275. setVertexBuffer(_stream, _handle, 0, UINT32_MAX);
  3276. }
  3277. void Encoder::setVertexBuffer(
  3278. uint8_t _stream
  3279. , const TransientVertexBuffer* _tvb
  3280. , uint32_t _startVertex
  3281. , uint32_t _numVertices
  3282. , VertexLayoutHandle _layoutHandle
  3283. )
  3284. {
  3285. BX_ASSERT(NULL != _tvb, "_tvb can't be NULL");
  3286. BGFX_CHECK_HANDLE("setVertexBuffer", s_ctx->m_vertexBufferHandle, _tvb->handle);
  3287. BGFX_CHECK_HANDLE_INVALID_OK("setVertexBuffer", s_ctx->m_layoutHandle, _layoutHandle);
  3288. BGFX_ENCODER(setVertexBuffer(_stream, _tvb, _startVertex, _numVertices, _layoutHandle) );
  3289. }
  3290. void Encoder::setVertexBuffer(uint8_t _stream, const TransientVertexBuffer* _tvb)
  3291. {
  3292. setVertexBuffer(_stream, _tvb, 0, UINT32_MAX);
  3293. }
  3294. void Encoder::setVertexCount(uint32_t _numVertices)
  3295. {
  3296. BGFX_CHECK_CAPS(BGFX_CAPS_VERTEX_ID, "Auto generated vertices are not supported!");
  3297. BGFX_ENCODER(setVertexCount(_numVertices) );
  3298. }
  3299. void Encoder::setInstanceDataBuffer(const InstanceDataBuffer* _idb)
  3300. {
  3301. setInstanceDataBuffer(_idb, 0, UINT32_MAX);
  3302. }
  3303. void Encoder::setInstanceDataBuffer(const InstanceDataBuffer* _idb, uint32_t _start, uint32_t _num)
  3304. {
  3305. BX_ASSERT(NULL != _idb, "_idb can't be NULL");
  3306. BGFX_ENCODER(setInstanceDataBuffer(_idb, _start, _num) );
  3307. }
  3308. void Encoder::setInstanceDataBuffer(VertexBufferHandle _handle, uint32_t _startVertex, uint32_t _num)
  3309. {
  3310. BGFX_CHECK_HANDLE("setInstanceDataBuffer", s_ctx->m_vertexBufferHandle, _handle);
  3311. const VertexBuffer& vb = s_ctx->m_vertexBuffers[_handle.idx];
  3312. BGFX_ENCODER(setInstanceDataBuffer(_handle, _startVertex, _num, vb.m_stride) );
  3313. }
  3314. void Encoder::setInstanceDataBuffer(DynamicVertexBufferHandle _handle, uint32_t _startVertex, uint32_t _num)
  3315. {
  3316. BGFX_CHECK_HANDLE("setInstanceDataBuffer", s_ctx->m_dynamicVertexBufferHandle, _handle);
  3317. const DynamicVertexBuffer& dvb = s_ctx->m_dynamicVertexBuffers[_handle.idx];
  3318. BGFX_ENCODER(setInstanceDataBuffer(dvb.m_handle
  3319. , dvb.m_startVertex + _startVertex
  3320. , _num
  3321. , dvb.m_stride
  3322. ) );
  3323. }
  3324. void Encoder::setInstanceCount(uint32_t _numInstances)
  3325. {
  3326. BGFX_CHECK_CAPS(BGFX_CAPS_VERTEX_ID, "Auto generated instances are not supported!");
  3327. BGFX_ENCODER(setInstanceCount(_numInstances) );
  3328. }
  3329. void Encoder::setTexture(uint8_t _stage, UniformHandle _sampler, TextureHandle _handle, uint32_t _flags)
  3330. {
  3331. BGFX_CHECK_HANDLE("setTexture/UniformHandle", s_ctx->m_uniformHandle, _sampler);
  3332. BGFX_CHECK_HANDLE_INVALID_OK("setTexture/TextureHandle", s_ctx->m_textureHandle, _handle);
  3333. BX_ASSERT(_stage < g_caps.limits.maxTextureSamplers, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxTextureSamplers);
  3334. if (isValid(_handle) )
  3335. {
  3336. const TextureRef& ref = s_ctx->m_textureRef[_handle.idx];
  3337. BX_ASSERT(!ref.isReadBack()
  3338. , "Can't sample from texture which was created with BGFX_TEXTURE_READ_BACK. This is CPU only texture."
  3339. );
  3340. BX_UNUSED(ref);
  3341. }
  3342. BGFX_ENCODER(setTexture(_stage, _sampler, _handle, _flags) );
  3343. }
  3344. void Encoder::touch(ViewId _id)
  3345. {
  3346. discard();
  3347. submit(_id, BGFX_INVALID_HANDLE);
  3348. }
  3349. void Encoder::submit(ViewId _id, ProgramHandle _program, uint32_t _depth, uint8_t _flags)
  3350. {
  3351. OcclusionQueryHandle handle = BGFX_INVALID_HANDLE;
  3352. submit(_id, _program, handle, _depth, _flags);
  3353. }
  3354. void Encoder::submit(ViewId _id, ProgramHandle _program, OcclusionQueryHandle _occlusionQuery, uint32_t _depth, uint8_t _flags)
  3355. {
  3356. BX_ASSERT(false
  3357. || !isValid(_occlusionQuery)
  3358. || 0 != (g_caps.supported & BGFX_CAPS_OCCLUSION_QUERY)
  3359. , "Occlusion query is not supported! Use bgfx::getCaps to check BGFX_CAPS_OCCLUSION_QUERY backend renderer capabilities."
  3360. );
  3361. BGFX_CHECK_HANDLE_INVALID_OK("submit", s_ctx->m_programHandle, _program);
  3362. BGFX_CHECK_HANDLE_INVALID_OK("submit", s_ctx->m_occlusionQueryHandle, _occlusionQuery);
  3363. BGFX_ENCODER(submit(_id, _program, _occlusionQuery, _depth, _flags) );
  3364. }
  3365. void Encoder::submit(ViewId _id, ProgramHandle _program, IndirectBufferHandle _indirectHandle, uint32_t _start, uint32_t _num, uint32_t _depth, uint8_t _flags)
  3366. {
  3367. BGFX_CHECK_HANDLE_INVALID_OK("submit", s_ctx->m_programHandle, _program);
  3368. BGFX_CHECK_HANDLE("submit", s_ctx->m_vertexBufferHandle, _indirectHandle);
  3369. BGFX_CHECK_CAPS(BGFX_CAPS_DRAW_INDIRECT, "Draw indirect is not supported!");
  3370. BGFX_ENCODER(submit(_id, _program, _indirectHandle, _start, _num, _depth, _flags) );
  3371. }
  3372. void Encoder::submit(ViewId _id, ProgramHandle _program, IndirectBufferHandle _indirectHandle, uint32_t _start, IndexBufferHandle _numHandle, uint32_t _numIndex, uint32_t _numMax, uint32_t _depth, uint8_t _flags)
  3373. {
  3374. BGFX_CHECK_HANDLE_INVALID_OK("submit", s_ctx->m_programHandle, _program);
  3375. BGFX_CHECK_HANDLE("submit", s_ctx->m_vertexBufferHandle, _indirectHandle);
  3376. BGFX_CHECK_HANDLE("submit", s_ctx->m_indexBufferHandle, _numHandle);
  3377. BGFX_CHECK_CAPS(BGFX_CAPS_DRAW_INDIRECT, "Draw indirect is not supported!");
  3378. BGFX_CHECK_CAPS(BGFX_CAPS_DRAW_INDIRECT_COUNT, "Draw indirect count is not supported!");
  3379. BGFX_ENCODER(submit(_id, _program, _indirectHandle, _start, _numHandle, _numIndex, _numMax, _depth, _flags) );
  3380. }
  3381. void Encoder::setBuffer(uint8_t _stage, IndexBufferHandle _handle, Access::Enum _access)
  3382. {
  3383. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3384. BGFX_CHECK_HANDLE("setBuffer", s_ctx->m_indexBufferHandle, _handle);
  3385. BGFX_ENCODER(setBuffer(_stage, _handle, _access) );
  3386. }
  3387. void Encoder::setBuffer(uint8_t _stage, VertexBufferHandle _handle, Access::Enum _access)
  3388. {
  3389. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3390. BGFX_CHECK_HANDLE("setBuffer", s_ctx->m_vertexBufferHandle, _handle);
  3391. BGFX_ENCODER(setBuffer(_stage, _handle, _access) );
  3392. }
  3393. void Encoder::setBuffer(uint8_t _stage, DynamicIndexBufferHandle _handle, Access::Enum _access)
  3394. {
  3395. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3396. BGFX_CHECK_HANDLE("setBuffer", s_ctx->m_dynamicIndexBufferHandle, _handle);
  3397. const DynamicIndexBuffer& dib = s_ctx->m_dynamicIndexBuffers[_handle.idx];
  3398. BGFX_ENCODER(setBuffer(_stage, dib.m_handle, _access) );
  3399. }
  3400. void Encoder::setBuffer(uint8_t _stage, DynamicVertexBufferHandle _handle, Access::Enum _access)
  3401. {
  3402. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3403. BGFX_CHECK_HANDLE("setBuffer", s_ctx->m_dynamicVertexBufferHandle, _handle);
  3404. const DynamicVertexBuffer& dvb = s_ctx->m_dynamicVertexBuffers[_handle.idx];
  3405. BGFX_ENCODER(setBuffer(_stage, dvb.m_handle, _access) );
  3406. }
  3407. void Encoder::setBuffer(uint8_t _stage, IndirectBufferHandle _handle, Access::Enum _access)
  3408. {
  3409. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3410. BGFX_CHECK_HANDLE("setBuffer", s_ctx->m_vertexBufferHandle, _handle);
  3411. VertexBufferHandle handle = { _handle.idx };
  3412. BGFX_ENCODER(setBuffer(_stage, handle, _access) );
  3413. }
  3414. void Encoder::setImage(uint8_t _stage, TextureHandle _handle, uint8_t _mip, Access::Enum _access, TextureFormat::Enum _format)
  3415. {
  3416. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3417. BGFX_CHECK_HANDLE_INVALID_OK("setImage/TextureHandle", s_ctx->m_textureHandle, _handle);
  3418. _format = TextureFormat::Count == _format
  3419. ? TextureFormat::Enum(s_ctx->m_textureRef[_handle.idx].m_format)
  3420. : _format
  3421. ;
  3422. BX_ASSERT(_format != TextureFormat::BGRA8
  3423. , "Can't use TextureFormat::BGRA8 with compute, use TextureFormat::RGBA8 instead."
  3424. );
  3425. if (isValid(_handle) )
  3426. {
  3427. const TextureRef& ref = s_ctx->m_textureRef[_handle.idx];
  3428. BX_ASSERT(!ref.isReadBack()
  3429. , "Can't texture (handle %d, '%S') which was created with BGFX_TEXTURE_READ_BACK with compute. This is CPU only texture."
  3430. , _handle.idx
  3431. , &ref.m_name
  3432. );
  3433. BX_UNUSED(ref);
  3434. }
  3435. BGFX_ENCODER(setImage(_stage, _handle, _mip, _access, _format) );
  3436. }
  3437. void Encoder::dispatch(ViewId _id, ProgramHandle _program, uint32_t _numX, uint32_t _numY, uint32_t _numZ, uint8_t _flags)
  3438. {
  3439. BGFX_CHECK_CAPS(BGFX_CAPS_COMPUTE, "Compute is not supported!");
  3440. BGFX_CHECK_HANDLE_INVALID_OK("dispatch", s_ctx->m_programHandle, _program);
  3441. BGFX_ENCODER(dispatch(_id, _program, _numX, _numY, _numZ, _flags) );
  3442. }
  3443. void Encoder::dispatch(ViewId _id, ProgramHandle _program, IndirectBufferHandle _indirectHandle, uint32_t _start, uint32_t _num, uint8_t _flags)
  3444. {
  3445. BGFX_CHECK_CAPS(BGFX_CAPS_DRAW_INDIRECT, "Dispatch indirect is not supported!");
  3446. BGFX_CHECK_CAPS(BGFX_CAPS_COMPUTE, "Compute is not supported!");
  3447. BGFX_CHECK_HANDLE_INVALID_OK("dispatch", s_ctx->m_programHandle, _program);
  3448. BGFX_CHECK_HANDLE("dispatch", s_ctx->m_vertexBufferHandle, _indirectHandle);
  3449. BGFX_ENCODER(dispatch(_id, _program, _indirectHandle, _start, _num, _flags) );
  3450. }
  3451. void Encoder::discard(uint8_t _flags)
  3452. {
  3453. BGFX_ENCODER(discard(_flags) );
  3454. }
  3455. void Encoder::blit(ViewId _id, TextureHandle _dst, uint16_t _dstX, uint16_t _dstY, TextureHandle _src, uint16_t _srcX, uint16_t _srcY, uint16_t _width, uint16_t _height)
  3456. {
  3457. blit(_id, _dst, 0, _dstX, _dstY, 0, _src, 0, _srcX, _srcY, 0, _width, _height, 0);
  3458. }
  3459. void Encoder::blit(ViewId _id, TextureHandle _dst, uint8_t _dstMip, uint16_t _dstX, uint16_t _dstY, uint16_t _dstZ, TextureHandle _src, uint8_t _srcMip, uint16_t _srcX, uint16_t _srcY, uint16_t _srcZ, uint16_t _width, uint16_t _height, uint16_t _depth)
  3460. {
  3461. BGFX_CHECK_CAPS(BGFX_CAPS_TEXTURE_BLIT, "Texture blit is not supported!");
  3462. BGFX_CHECK_HANDLE("blit/src TextureHandle", s_ctx->m_textureHandle, _src);
  3463. BGFX_CHECK_HANDLE("blit/dst TextureHandle", s_ctx->m_textureHandle, _dst);
  3464. const TextureRef& src = s_ctx->m_textureRef[_src.idx];
  3465. const TextureRef& dst = s_ctx->m_textureRef[_dst.idx];
  3466. BX_ASSERT(dst.isBlitDst()
  3467. , "Blit destination texture (handle %d, '%S') is not created with `BGFX_TEXTURE_BLIT_DST` flag."
  3468. , _dst.idx
  3469. , &dst.m_name
  3470. );
  3471. BX_ASSERT(src.m_format == dst.m_format
  3472. , "Texture format must match (src %s, dst %s)."
  3473. , bimg::getName(bimg::TextureFormat::Enum(src.m_format) )
  3474. , bimg::getName(bimg::TextureFormat::Enum(dst.m_format) )
  3475. );
  3476. BX_ASSERT(_srcMip < src.m_numMips, "Invalid blit src mip (%d > %d)", _srcMip, src.m_numMips - 1);
  3477. BX_ASSERT(_dstMip < dst.m_numMips, "Invalid blit dst mip (%d > %d)", _dstMip, dst.m_numMips - 1);
  3478. uint32_t srcWidth = bx::max<uint32_t>(1, src.m_width >> _srcMip);
  3479. uint32_t srcHeight = bx::max<uint32_t>(1, src.m_height >> _srcMip);
  3480. uint32_t dstWidth = bx::max<uint32_t>(1, dst.m_width >> _dstMip);
  3481. uint32_t dstHeight = bx::max<uint32_t>(1, dst.m_height >> _dstMip);
  3482. uint32_t srcDepth = src.isCubeMap() ? 6 * src.m_numLayers : src.m_numLayers > 1 ? src.m_numLayers : bx::max<uint32_t>(1, src.m_depth >> _srcMip);
  3483. uint32_t dstDepth = dst.isCubeMap() ? 6 * dst.m_numLayers : dst.m_numLayers > 1 ? dst.m_numLayers : bx::max<uint32_t>(1, dst.m_depth >> _dstMip);
  3484. BX_ASSERT(_srcX < srcWidth && _srcY < srcHeight && _srcZ < srcDepth
  3485. , "Blit src coordinates out of range (%d, %d, %d) >= (%d, %d, %d)"
  3486. , _srcX, _srcY, _srcZ
  3487. , srcWidth, srcHeight, srcDepth
  3488. );
  3489. BX_ASSERT(_dstX < dstWidth && _dstY < dstHeight && _dstZ < dstDepth
  3490. , "Blit dst coordinates out of range (%d, %d, %d) >= (%d, %d, %d)"
  3491. , _dstX, _dstY, _dstZ
  3492. , dstWidth, dstHeight, dstDepth
  3493. );
  3494. srcWidth = bx::min<uint32_t>(srcWidth, _srcX + _width ) - _srcX;
  3495. srcHeight = bx::min<uint32_t>(srcHeight, _srcY + _height) - _srcY;
  3496. srcDepth = bx::min<uint32_t>(srcDepth, _srcZ + _depth ) - _srcZ;
  3497. dstWidth = bx::min<uint32_t>(dstWidth, _dstX + _width ) - _dstX;
  3498. dstHeight = bx::min<uint32_t>(dstHeight, _dstY + _height) - _dstY;
  3499. dstDepth = bx::min<uint32_t>(dstDepth, _dstZ + _depth ) - _dstZ;
  3500. const uint16_t width = uint16_t(bx::min(srcWidth, dstWidth ) );
  3501. const uint16_t height = uint16_t(bx::min(srcHeight, dstHeight) );
  3502. const uint16_t depth = uint16_t(bx::min(srcDepth, dstDepth ) );
  3503. BGFX_ENCODER(blit(_id, _dst, _dstMip, _dstX, _dstY, _dstZ, _src, _srcMip, _srcX, _srcY, _srcZ, width, height, depth) );
  3504. }
  3505. #undef BGFX_ENCODER
  3506. void end(Encoder* _encoder)
  3507. {
  3508. s_ctx->end(_encoder);
  3509. }
  3510. uint32_t frame(bool _capture)
  3511. {
  3512. BGFX_CHECK_API_THREAD();
  3513. return s_ctx->frame(_capture);
  3514. }
  3515. const Caps* getCaps()
  3516. {
  3517. return &g_caps;
  3518. }
  3519. const Stats* getStats()
  3520. {
  3521. return s_ctx->getPerfStats();
  3522. }
  3523. RendererType::Enum getRendererType()
  3524. {
  3525. return g_caps.rendererType;
  3526. }
  3527. const Memory* alloc(uint32_t _size)
  3528. {
  3529. BX_ASSERT(0 < _size, "Invalid memory operation. _size is 0.");
  3530. Memory* mem = (Memory*)bx::alloc(g_allocator, sizeof(Memory) + _size);
  3531. mem->size = _size;
  3532. mem->data = (uint8_t*)mem + sizeof(Memory);
  3533. return mem;
  3534. }
  3535. const Memory* copy(const void* _data, uint32_t _size)
  3536. {
  3537. BX_ASSERT(0 < _size, "Invalid memory operation. _size is 0.");
  3538. const Memory* mem = alloc(_size);
  3539. bx::memCopy(mem->data, _data, _size);
  3540. return mem;
  3541. }
  3542. struct MemoryRef
  3543. {
  3544. Memory mem;
  3545. ReleaseFn releaseFn;
  3546. void* userData;
  3547. };
  3548. const Memory* makeRef(const void* _data, uint32_t _size, ReleaseFn _releaseFn, void* _userData)
  3549. {
  3550. MemoryRef* memRef = (MemoryRef*)bx::alloc(g_allocator, sizeof(MemoryRef) );
  3551. memRef->mem.size = _size;
  3552. memRef->mem.data = (uint8_t*)_data;
  3553. memRef->releaseFn = _releaseFn;
  3554. memRef->userData = _userData;
  3555. return &memRef->mem;
  3556. }
  3557. bool isMemoryRef(const Memory* _mem)
  3558. {
  3559. return _mem->data != (uint8_t*)_mem + sizeof(Memory);
  3560. }
  3561. void release(const Memory* _mem)
  3562. {
  3563. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3564. Memory* mem = const_cast<Memory*>(_mem);
  3565. if (isMemoryRef(mem) )
  3566. {
  3567. MemoryRef* memRef = reinterpret_cast<MemoryRef*>(mem);
  3568. if (NULL != memRef->releaseFn)
  3569. {
  3570. memRef->releaseFn(mem->data, memRef->userData);
  3571. }
  3572. }
  3573. bx::free(g_allocator, mem);
  3574. }
  3575. void setDebug(uint32_t _debug)
  3576. {
  3577. BGFX_CHECK_API_THREAD();
  3578. s_ctx->setDebug(_debug);
  3579. }
  3580. void dbgTextClear(uint8_t _attr, bool _small)
  3581. {
  3582. BGFX_CHECK_API_THREAD();
  3583. s_ctx->dbgTextClear(_attr, _small);
  3584. }
  3585. void dbgTextPrintfVargs(uint16_t _x, uint16_t _y, uint8_t _attr, const char* _format, va_list _argList)
  3586. {
  3587. s_ctx->dbgTextPrintfVargs(_x, _y, _attr, _format, _argList);
  3588. }
  3589. void dbgTextPrintf(uint16_t _x, uint16_t _y, uint8_t _attr, const char* _format, ...)
  3590. {
  3591. BGFX_CHECK_API_THREAD();
  3592. va_list argList;
  3593. va_start(argList, _format);
  3594. s_ctx->dbgTextPrintfVargs(_x, _y, _attr, _format, argList);
  3595. va_end(argList);
  3596. }
  3597. void dbgTextImage(uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height, const void* _data, uint16_t _pitch)
  3598. {
  3599. BGFX_CHECK_API_THREAD();
  3600. s_ctx->dbgTextImage(_x, _y, _width, _height, _data, _pitch);
  3601. }
  3602. IndexBufferHandle createIndexBuffer(const Memory* _mem, uint16_t _flags)
  3603. {
  3604. BX_ASSERT(
  3605. 0 == (_flags & BGFX_BUFFER_INDEX32) || 0 != (g_caps.supported & BGFX_CAPS_INDEX32)
  3606. , "32-bit indices are not supported. Use bgfx::getCaps to check BGFX_CAPS_INDEX32 backend renderer capabilities."
  3607. );
  3608. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3609. return s_ctx->createIndexBuffer(_mem, _flags);
  3610. }
  3611. void setName(IndexBufferHandle _handle, const char* _name, int32_t _len)
  3612. {
  3613. s_ctx->setName(_handle, bx::StringView(_name, _len) );
  3614. }
  3615. void destroy(IndexBufferHandle _handle)
  3616. {
  3617. s_ctx->destroyIndexBuffer(_handle);
  3618. }
  3619. VertexLayoutHandle createVertexLayout(const VertexLayout& _layout)
  3620. {
  3621. return s_ctx->createVertexLayout(_layout);
  3622. }
  3623. void destroy(VertexLayoutHandle _handle)
  3624. {
  3625. s_ctx->destroyVertexLayout(_handle);
  3626. }
  3627. VertexBufferHandle createVertexBuffer(const Memory* _mem, const VertexLayout& _layout, uint16_t _flags)
  3628. {
  3629. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3630. BX_ASSERT(isValid(_layout), "Invalid VertexLayout.");
  3631. return s_ctx->createVertexBuffer(_mem, _layout, _flags);
  3632. }
  3633. void setName(VertexBufferHandle _handle, const char* _name, int32_t _len)
  3634. {
  3635. s_ctx->setName(_handle, bx::StringView(_name, _len) );
  3636. }
  3637. void destroy(VertexBufferHandle _handle)
  3638. {
  3639. s_ctx->destroyVertexBuffer(_handle);
  3640. }
  3641. DynamicIndexBufferHandle createDynamicIndexBuffer(uint32_t _num, uint16_t _flags)
  3642. {
  3643. return s_ctx->createDynamicIndexBuffer(_num, _flags);
  3644. }
  3645. DynamicIndexBufferHandle createDynamicIndexBuffer(const Memory* _mem, uint16_t _flags)
  3646. {
  3647. BX_ASSERT(
  3648. 0 == (_flags & BGFX_BUFFER_INDEX32) || 0 != (g_caps.supported & BGFX_CAPS_INDEX32)
  3649. , "32-bit indices are not supported. Use bgfx::getCaps to check BGFX_CAPS_INDEX32 backend renderer capabilities."
  3650. );
  3651. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3652. return s_ctx->createDynamicIndexBuffer(_mem, _flags);
  3653. }
  3654. void update(DynamicIndexBufferHandle _handle, uint32_t _startIndex, const Memory* _mem)
  3655. {
  3656. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3657. s_ctx->update(_handle, _startIndex, _mem);
  3658. }
  3659. void destroy(DynamicIndexBufferHandle _handle)
  3660. {
  3661. s_ctx->destroyDynamicIndexBuffer(_handle);
  3662. }
  3663. DynamicVertexBufferHandle createDynamicVertexBuffer(uint32_t _num, const VertexLayout& _layout, uint16_t _flags)
  3664. {
  3665. BX_ASSERT(isValid(_layout), "Invalid VertexLayout.");
  3666. return s_ctx->createDynamicVertexBuffer(_num, _layout, _flags);
  3667. }
  3668. DynamicVertexBufferHandle createDynamicVertexBuffer(const Memory* _mem, const VertexLayout& _layout, uint16_t _flags)
  3669. {
  3670. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3671. BX_ASSERT(isValid(_layout), "Invalid VertexLayout.");
  3672. return s_ctx->createDynamicVertexBuffer(_mem, _layout, _flags);
  3673. }
  3674. void update(DynamicVertexBufferHandle _handle, uint32_t _startVertex, const Memory* _mem)
  3675. {
  3676. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3677. s_ctx->update(_handle, _startVertex, _mem);
  3678. }
  3679. void destroy(DynamicVertexBufferHandle _handle)
  3680. {
  3681. s_ctx->destroyDynamicVertexBuffer(_handle);
  3682. }
  3683. uint32_t getAvailTransientIndexBuffer(uint32_t _num, bool _index32)
  3684. {
  3685. BX_ASSERT(0 < _num, "Requesting 0 indices.");
  3686. return s_ctx->getAvailTransientIndexBuffer(_num, _index32);
  3687. }
  3688. uint32_t getAvailTransientVertexBuffer(uint32_t _num, const VertexLayout& _layout)
  3689. {
  3690. BX_ASSERT(0 < _num, "Requesting 0 vertices.");
  3691. BX_ASSERT(isValid(_layout), "Invalid VertexLayout.");
  3692. return s_ctx->getAvailTransientVertexBuffer(_num, _layout.m_stride);
  3693. }
  3694. uint32_t getAvailInstanceDataBuffer(uint32_t _num, uint16_t _stride)
  3695. {
  3696. BX_ASSERT(0 < _num, "Requesting 0 instances.");
  3697. return s_ctx->getAvailTransientVertexBuffer(_num, _stride);
  3698. }
  3699. void allocTransientIndexBuffer(TransientIndexBuffer* _tib, uint32_t _num, bool _index32)
  3700. {
  3701. BX_ASSERT(NULL != _tib, "_tib can't be NULL");
  3702. BX_ASSERT(0 < _num, "Requesting 0 indices.");
  3703. BX_ASSERT(
  3704. !_index32 || 0 != (g_caps.supported & BGFX_CAPS_INDEX32)
  3705. , "32-bit indices are not supported. Use bgfx::getCaps to check BGFX_CAPS_INDEX32 backend renderer capabilities."
  3706. );
  3707. s_ctx->allocTransientIndexBuffer(_tib, _num, _index32);
  3708. const uint32_t indexSize = _tib->isIndex16 ? 2 : 4;
  3709. BX_ASSERT(_num == _tib->size/ indexSize
  3710. , "Failed to allocate transient index buffer (requested %d, available %d). "
  3711. "Use bgfx::getAvailTransient* functions to ensure availability."
  3712. , _num
  3713. , _tib->size/indexSize
  3714. );
  3715. BX_UNUSED(indexSize);
  3716. }
  3717. void allocTransientVertexBuffer(TransientVertexBuffer* _tvb, uint32_t _num, const VertexLayout& _layout)
  3718. {
  3719. BX_ASSERT(NULL != _tvb, "_tvb can't be NULL");
  3720. BX_ASSERT(0 < _num, "Requesting 0 vertices.");
  3721. BX_ASSERT(isValid(_layout), "Invalid VertexLayout.");
  3722. VertexLayoutHandle layoutHandle;
  3723. {
  3724. BGFX_MUTEX_SCOPE(s_ctx->m_resourceApiLock);
  3725. layoutHandle = s_ctx->findOrCreateVertexLayout(_layout, true);
  3726. }
  3727. BX_ASSERT(isValid(layoutHandle), "Failed to allocate vertex layout handle (BGFX_CONFIG_MAX_VERTEX_LAYOUTS, max: %d).", BGFX_CONFIG_MAX_VERTEX_LAYOUTS);
  3728. s_ctx->allocTransientVertexBuffer(_tvb, _num, layoutHandle, _layout.m_stride);
  3729. BX_ASSERT(_num == _tvb->size / _layout.m_stride
  3730. , "Failed to allocate transient vertex buffer (requested %d, available %d). "
  3731. "Use bgfx::getAvailTransient* functions to ensure availability."
  3732. , _num
  3733. , _tvb->size / _layout.m_stride
  3734. );
  3735. }
  3736. bool allocTransientBuffers(bgfx::TransientVertexBuffer* _tvb, const bgfx::VertexLayout& _layout, uint32_t _numVertices, bgfx::TransientIndexBuffer* _tib, uint32_t _numIndices, bool _index32)
  3737. {
  3738. BGFX_MUTEX_SCOPE(s_ctx->m_resourceApiLock);
  3739. if (_numVertices == getAvailTransientVertexBuffer(_numVertices, _layout)
  3740. && _numIndices == getAvailTransientIndexBuffer(_numIndices, _index32) )
  3741. {
  3742. allocTransientVertexBuffer(_tvb, _numVertices, _layout);
  3743. allocTransientIndexBuffer(_tib, _numIndices, _index32);
  3744. return true;
  3745. }
  3746. return false;
  3747. }
  3748. void allocInstanceDataBuffer(InstanceDataBuffer* _idb, uint32_t _num, uint16_t _stride)
  3749. {
  3750. BGFX_CHECK_CAPS(BGFX_CAPS_INSTANCING, "Instancing is not supported!");
  3751. BX_ASSERT(bx::isAligned(_stride, 16), "Stride must be multiple of 16.");
  3752. BX_ASSERT(0 < _num, "Requesting 0 instanced data vertices.");
  3753. s_ctx->allocInstanceDataBuffer(_idb, _num, _stride);
  3754. BX_ASSERT(_num == _idb->size / _stride
  3755. , "Failed to allocate instance data buffer (requested %d, available %d). "
  3756. "Use bgfx::getAvailTransient* functions to ensure availability."
  3757. , _num
  3758. , _idb->size / _stride
  3759. );
  3760. }
  3761. IndirectBufferHandle createIndirectBuffer(uint32_t _num)
  3762. {
  3763. return s_ctx->createIndirectBuffer(_num);
  3764. }
  3765. void destroy(IndirectBufferHandle _handle)
  3766. {
  3767. s_ctx->destroyIndirectBuffer(_handle);
  3768. }
  3769. ShaderHandle createShader(const Memory* _mem)
  3770. {
  3771. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3772. return s_ctx->createShader(_mem);
  3773. }
  3774. uint16_t getShaderUniforms(ShaderHandle _handle, UniformHandle* _uniforms, uint16_t _max)
  3775. {
  3776. BX_WARN(NULL == _uniforms || 0 != _max
  3777. , "Passing uniforms array pointer, but array maximum capacity is set to 0."
  3778. );
  3779. uint16_t num = s_ctx->getShaderUniforms(_handle, _uniforms, _max);
  3780. BX_WARN(0 == _max || num <= _max
  3781. , "Shader has more uniforms that capacity of output array. Output is truncated (num %d, max %d)."
  3782. , num
  3783. , _max
  3784. );
  3785. return num;
  3786. }
  3787. void setName(ShaderHandle _handle, const char* _name, int32_t _len)
  3788. {
  3789. s_ctx->setName(_handle, bx::StringView(_name, _len) );
  3790. }
  3791. void destroy(ShaderHandle _handle)
  3792. {
  3793. s_ctx->destroyShader(_handle);
  3794. }
  3795. ProgramHandle createProgram(ShaderHandle _vsh, ShaderHandle _fsh, bool _destroyShaders)
  3796. {
  3797. if (!isValid(_fsh) )
  3798. {
  3799. return createProgram(_vsh, _destroyShaders);
  3800. }
  3801. return s_ctx->createProgram(_vsh, _fsh, _destroyShaders);
  3802. }
  3803. ProgramHandle createProgram(ShaderHandle _csh, bool _destroyShader)
  3804. {
  3805. return s_ctx->createProgram(_csh, _destroyShader);
  3806. }
  3807. void destroy(ProgramHandle _handle)
  3808. {
  3809. s_ctx->destroyProgram(_handle);
  3810. }
  3811. void isFrameBufferValid(uint8_t _num, const Attachment* _attachment, bx::Error* _err)
  3812. {
  3813. BX_ERROR_SCOPE(_err, "Frame buffer validation");
  3814. uint8_t color = 0;
  3815. uint8_t depth = 0;
  3816. const TextureRef& firstTexture = s_ctx->m_textureRef[_attachment[0].handle.idx];
  3817. const uint16_t firstAttachmentWidth = bx::max<uint16_t>(firstTexture.m_width >> _attachment[0].mip, 1);
  3818. const uint16_t firstAttachmentHeight = bx::max<uint16_t>(firstTexture.m_height >> _attachment[0].mip, 1);
  3819. for (uint32_t ii = 0; ii < _num; ++ii)
  3820. {
  3821. const Attachment& at = _attachment[ii];
  3822. const TextureHandle texHandle = at.handle;
  3823. const TextureRef& tr = s_ctx->m_textureRef[texHandle.idx];
  3824. BGFX_ERROR_CHECK(true
  3825. && isValid(texHandle)
  3826. && s_ctx->m_textureHandle.isValid(texHandle.idx)
  3827. , _err
  3828. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3829. , "Invalid texture attachment."
  3830. , "Attachment %d, texture handle %d."
  3831. , ii
  3832. , texHandle.idx
  3833. );
  3834. BGFX_ERROR_CHECK(true
  3835. && at.mip < tr.m_numMips
  3836. , _err
  3837. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3838. , "Invalid texture mip level."
  3839. , "Attachment %d, Mip %d, texture (handle %d) number of mips %d."
  3840. , ii
  3841. , at.mip
  3842. , texHandle.idx
  3843. , tr.m_numMips
  3844. );
  3845. {
  3846. const uint16_t numLayers = tr.is3D()
  3847. ? bx::max<uint16_t>(tr.m_depth >> at.mip, 1)
  3848. : tr.m_numLayers * (tr.isCubeMap() ? 6 : 1)
  3849. ;
  3850. BGFX_ERROR_CHECK(true
  3851. && (at.layer + at.numLayers) <= numLayers
  3852. , _err
  3853. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3854. , "Invalid texture layer range."
  3855. , "Attachment %d, Layer: %d, Num: %d, Max number of layers: %d."
  3856. , ii
  3857. , at.layer
  3858. , at.numLayers
  3859. , numLayers
  3860. );
  3861. }
  3862. BGFX_ERROR_CHECK(true
  3863. && _attachment[0].numLayers == at.numLayers
  3864. , _err
  3865. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3866. , "Mismatch in attachment layer count."
  3867. , "Attachment %d, Given: %d, Expected: %d."
  3868. , ii
  3869. , at.numLayers
  3870. , _attachment[0].numLayers
  3871. );
  3872. BGFX_ERROR_CHECK(true
  3873. && firstTexture.m_bbRatio == tr.m_bbRatio
  3874. , _err
  3875. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3876. , "Mismatch in texture back-buffer ratio."
  3877. , "Attachment %d, Given: %d, Expected: %d."
  3878. , ii
  3879. , tr.m_bbRatio
  3880. , firstTexture.m_bbRatio
  3881. );
  3882. BGFX_ERROR_CHECK(true
  3883. && firstTexture.m_numSamples == tr.m_numSamples
  3884. , _err
  3885. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3886. , "Mismatch in texture sample count."
  3887. , "Attachment %d, Given: %d, Expected: %d."
  3888. , ii
  3889. , tr.m_numSamples
  3890. , firstTexture.m_numSamples
  3891. );
  3892. if (BackbufferRatio::Count == firstTexture.m_bbRatio)
  3893. {
  3894. const uint16_t width = bx::max<uint16_t>(tr.m_width >> at.mip, 1);
  3895. const uint16_t height = bx::max<uint16_t>(tr.m_height >> at.mip, 1);
  3896. BGFX_ERROR_CHECK(true
  3897. && width == firstAttachmentWidth
  3898. && height == firstAttachmentHeight
  3899. , _err
  3900. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3901. , "Mismatch in texture size."
  3902. , "Attachment %d, Given: %dx%d, Expected: %dx%d."
  3903. , ii
  3904. , width
  3905. , height
  3906. , firstAttachmentWidth
  3907. , firstAttachmentHeight
  3908. );
  3909. }
  3910. if (bimg::isDepth(bimg::TextureFormat::Enum(tr.m_format) ) )
  3911. {
  3912. ++depth;
  3913. BGFX_ERROR_CHECK(
  3914. // if BGFX_TEXTURE_RT_MSAA_X2 or greater than either BGFX_TEXTURE_RT_WRITE_ONLY or BGFX_TEXTURE_MSAA_SAMPLE is required
  3915. // if BGFX_TEXTURE_RT with no MSSA then this is not required.
  3916. (1 == ( (tr.m_flags & BGFX_TEXTURE_RT_MSAA_MASK) >> BGFX_TEXTURE_RT_MSAA_SHIFT) )
  3917. || (0 != (tr.m_flags & (BGFX_TEXTURE_RT_WRITE_ONLY | BGFX_TEXTURE_MSAA_SAMPLE) ) )
  3918. , _err
  3919. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3920. , "Frame buffer depth MSAA texture cannot be resolved. It must be created with either `BGFX_TEXTURE_RT_WRITE_ONLY` or `BGFX_TEXTURE_MSAA_SAMPLE` flag."
  3921. , "Attachment %d, texture flags 0x%016" PRIx64 "."
  3922. , ii
  3923. , tr.m_flags
  3924. );
  3925. }
  3926. else
  3927. {
  3928. ++color;
  3929. }
  3930. BGFX_ERROR_CHECK(true
  3931. && 0 == (tr.m_flags & BGFX_TEXTURE_READ_BACK)
  3932. , _err
  3933. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3934. , "Frame buffer texture cannot be created with `BGFX_TEXTURE_READ_BACK`."
  3935. , "Attachment %d, texture flags 0x%016" PRIx64 "."
  3936. , ii
  3937. , tr.m_flags
  3938. );
  3939. BGFX_ERROR_CHECK(true
  3940. && 0 != (tr.m_flags & BGFX_TEXTURE_RT_MASK)
  3941. , _err
  3942. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3943. , "Frame buffer texture is not created with one of `BGFX_TEXTURE_RT*` flags."
  3944. , "Attachment %d, texture flags 0x%016" PRIx64 "."
  3945. , ii
  3946. , tr.m_flags
  3947. );
  3948. }
  3949. BGFX_ERROR_CHECK(true
  3950. && color <= g_caps.limits.maxFBAttachments
  3951. , _err
  3952. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3953. , "Too many frame buffer color attachments."
  3954. , "Num: %d, Max: %d."
  3955. , _num
  3956. , g_caps.limits.maxFBAttachments
  3957. );
  3958. BGFX_ERROR_CHECK(true
  3959. && depth <= 1
  3960. , _err
  3961. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3962. , "There can be only one depth texture attachment."
  3963. , "Num depth attachments %d."
  3964. , depth
  3965. );
  3966. }
  3967. bool isFrameBufferValid(uint8_t _num, const Attachment* _attachment)
  3968. {
  3969. BGFX_MUTEX_SCOPE(s_ctx->m_resourceApiLock);
  3970. bx::Error err;
  3971. isFrameBufferValid(_num, _attachment, &err);
  3972. return err.isOk();
  3973. }
  3974. static void isTextureValid(uint16_t _width, uint16_t _height, uint16_t _depth, bool _cubeMap, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags, bx::Error* _err)
  3975. {
  3976. BX_ERROR_SCOPE(_err, "Texture validation");
  3977. const bool is3DTexture = 1 < _depth;
  3978. BGFX_ERROR_CHECK(false
  3979. || !_cubeMap
  3980. || !is3DTexture
  3981. , _err
  3982. , BGFX_ERROR_TEXTURE_VALIDATION
  3983. , "Texture can't be 3D and cube map at the same time."
  3984. , ""
  3985. );
  3986. BGFX_ERROR_CHECK(false
  3987. || !is3DTexture
  3988. || 0 != (g_caps.supported & BGFX_CAPS_TEXTURE_3D)
  3989. , _err
  3990. , BGFX_ERROR_TEXTURE_VALIDATION
  3991. , "Texture3D is not supported! "
  3992. "Use bgfx::getCaps to check `BGFX_CAPS_TEXTURE_3D` backend renderer capabilities."
  3993. , ""
  3994. );
  3995. BGFX_ERROR_CHECK(false
  3996. || _width <= g_caps.limits.maxTextureSize
  3997. || _height <= g_caps.limits.maxTextureSize
  3998. , _err
  3999. , BGFX_ERROR_TEXTURE_VALIDATION
  4000. , "Requested texture width/height is above the `maxTextureSize` limit."
  4001. , "Texture width x height requested %d x %d (Max: %d)."
  4002. , _width
  4003. , _height
  4004. , g_caps.limits.maxTextureSize
  4005. );
  4006. BGFX_ERROR_CHECK(false
  4007. || 0 == (_flags & BGFX_TEXTURE_RT_MASK)
  4008. || 0 == (_flags & BGFX_TEXTURE_READ_BACK)
  4009. , _err
  4010. , BGFX_ERROR_TEXTURE_VALIDATION
  4011. , "Can't create render target with `BGFX_TEXTURE_READ_BACK` flag."
  4012. , ""
  4013. );
  4014. BGFX_ERROR_CHECK(false
  4015. || 0 == (_flags & BGFX_TEXTURE_COMPUTE_WRITE)
  4016. || 0 == (_flags & BGFX_TEXTURE_READ_BACK)
  4017. , _err
  4018. , BGFX_ERROR_TEXTURE_VALIDATION
  4019. , "Can't create compute texture with `BGFX_TEXTURE_READ_BACK` flag."
  4020. , ""
  4021. );
  4022. BGFX_ERROR_CHECK(false
  4023. || 1 >= _numLayers
  4024. || 0 != (g_caps.supported & BGFX_CAPS_TEXTURE_2D_ARRAY)
  4025. , _err
  4026. , BGFX_ERROR_TEXTURE_VALIDATION
  4027. , "Texture array is not supported! "
  4028. "Use bgfx::getCaps to check `BGFX_CAPS_TEXTURE_2D_ARRAY` backend renderer capabilities."
  4029. , ""
  4030. );
  4031. BGFX_ERROR_CHECK(false
  4032. || _numLayers <= g_caps.limits.maxTextureLayers
  4033. , _err
  4034. , BGFX_ERROR_TEXTURE_VALIDATION
  4035. , "Requested number of texture array layers is above the `maxTextureLayers` limit."
  4036. , "Number of texture array layers requested %d (Max: %d)."
  4037. , _numLayers
  4038. , g_caps.limits.maxTextureLayers
  4039. );
  4040. bool formatSupported;
  4041. if (0 != (_flags & (BGFX_TEXTURE_RT | BGFX_TEXTURE_RT_WRITE_ONLY)) )
  4042. {
  4043. formatSupported = 0 != (g_caps.formats[_format] & BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER);
  4044. }
  4045. else
  4046. {
  4047. formatSupported = 0 != (g_caps.formats[_format] & (0
  4048. | BGFX_CAPS_FORMAT_TEXTURE_2D
  4049. | BGFX_CAPS_FORMAT_TEXTURE_2D_EMULATED
  4050. | BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB
  4051. ) );
  4052. }
  4053. uint16_t srgbCaps = BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB;
  4054. if (_cubeMap)
  4055. {
  4056. formatSupported = 0 != (g_caps.formats[_format] & (0
  4057. | BGFX_CAPS_FORMAT_TEXTURE_CUBE
  4058. | BGFX_CAPS_FORMAT_TEXTURE_CUBE_EMULATED
  4059. | BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB
  4060. ) );
  4061. srgbCaps = BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB;
  4062. }
  4063. else if (is3DTexture)
  4064. {
  4065. formatSupported = 0 != (g_caps.formats[_format] & (0
  4066. | BGFX_CAPS_FORMAT_TEXTURE_3D
  4067. | BGFX_CAPS_FORMAT_TEXTURE_3D_EMULATED
  4068. | BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB
  4069. ) );
  4070. srgbCaps = BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB;
  4071. }
  4072. if (formatSupported
  4073. && 0 != (_flags & BGFX_TEXTURE_RT_MASK) )
  4074. {
  4075. formatSupported = 0 != (g_caps.formats[_format] & (0
  4076. | BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER
  4077. ) );
  4078. }
  4079. BGFX_ERROR_CHECK(
  4080. formatSupported
  4081. , _err
  4082. , BGFX_ERROR_TEXTURE_VALIDATION
  4083. , "Texture format is not supported! "
  4084. "Use bgfx::isTextureValid to check support for texture format before creating it."
  4085. , "Texture format: %s."
  4086. , getName(_format)
  4087. );
  4088. BGFX_ERROR_CHECK(false
  4089. || 1 >= ( (_flags & BGFX_TEXTURE_RT_MSAA_MASK) >> BGFX_TEXTURE_RT_MSAA_SHIFT)
  4090. || 0 != (g_caps.formats[_format] & BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA)
  4091. , _err
  4092. , BGFX_ERROR_TEXTURE_VALIDATION
  4093. , "Creating MSAA render target for this texture format is not supported."
  4094. , "Texture format: %s."
  4095. , getName(_format)
  4096. );
  4097. BGFX_ERROR_CHECK(false
  4098. || 0 == (_flags & BGFX_TEXTURE_MSAA_SAMPLE)
  4099. || 0 != (g_caps.formats[_format] & BGFX_CAPS_FORMAT_TEXTURE_MSAA)
  4100. , _err
  4101. , BGFX_ERROR_TEXTURE_VALIDATION
  4102. , "MSAA sampling for this texture format is not supported."
  4103. , "Texture format: %s."
  4104. , getName(_format)
  4105. );
  4106. BGFX_ERROR_CHECK(false
  4107. || 0 == (_flags & BGFX_TEXTURE_SRGB)
  4108. || 0 != (g_caps.formats[_format] & srgbCaps & (0
  4109. | BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB
  4110. | BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB
  4111. | BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB
  4112. ) )
  4113. , _err
  4114. , BGFX_ERROR_TEXTURE_VALIDATION
  4115. , "sRGB sampling for this texture format is not supported."
  4116. , "Texture format: %s."
  4117. , getName(_format)
  4118. );
  4119. }
  4120. bool isTextureValid(uint16_t _depth, bool _cubeMap, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags)
  4121. {
  4122. bx::Error err;
  4123. isTextureValid(0, 0, _depth, _cubeMap, _numLayers, _format, _flags, &err);
  4124. return err.isOk();
  4125. }
  4126. void isIdentifierValid(const bx::StringView& _name, bx::Error* _err)
  4127. {
  4128. BX_ERROR_SCOPE(_err, "Uniform identifier validation");
  4129. BGFX_ERROR_CHECK(false
  4130. || !_name.isEmpty()
  4131. , _err
  4132. , BGFX_ERROR_IDENTIFIER_VALIDATION
  4133. , "Identifier can't be empty."
  4134. , ""
  4135. );
  4136. BGFX_ERROR_CHECK(false
  4137. || PredefinedUniform::Count == nameToPredefinedUniformEnum(_name)
  4138. , _err
  4139. , BGFX_ERROR_IDENTIFIER_VALIDATION
  4140. , "Identifier can't use predefined uniform name."
  4141. , ""
  4142. );
  4143. const char ch = *_name.getPtr();
  4144. BGFX_ERROR_CHECK(false
  4145. || bx::isAlpha(ch)
  4146. || '_' == ch
  4147. , _err
  4148. , BGFX_ERROR_IDENTIFIER_VALIDATION
  4149. , "The first character of an identifier should be either an alphabet character or an underscore."
  4150. , ""
  4151. );
  4152. bool result = true;
  4153. for (const char* ptr = _name.getPtr() + 1, *term = _name.getTerm()
  4154. ; ptr != term && result
  4155. ; ++ptr
  4156. )
  4157. {
  4158. result &= bx::isAlphaNum(*ptr) || '_' == *ptr;
  4159. }
  4160. BGFX_ERROR_CHECK(false
  4161. || result
  4162. , _err
  4163. , BGFX_ERROR_IDENTIFIER_VALIDATION
  4164. , "Identifier contains invalid characters. Identifier must be the alphabet character, number, or underscore."
  4165. , ""
  4166. );
  4167. }
  4168. void calcTextureSize(TextureInfo& _info, uint16_t _width, uint16_t _height, uint16_t _depth, bool _cubeMap, bool _hasMips, uint16_t _numLayers, TextureFormat::Enum _format)
  4169. {
  4170. bimg::imageGetSize( (bimg::TextureInfo*)&_info, _width, _height, _depth, _cubeMap, _hasMips, _numLayers, bimg::TextureFormat::Enum(_format) );
  4171. }
  4172. TextureHandle createTexture(const Memory* _mem, uint64_t _flags, uint8_t _skip, TextureInfo* _info)
  4173. {
  4174. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  4175. return s_ctx->createTexture(_mem, _flags, _skip, _info, BackbufferRatio::Count, false);
  4176. }
  4177. void getTextureSizeFromRatio(BackbufferRatio::Enum _ratio, uint16_t& _width, uint16_t& _height)
  4178. {
  4179. switch (_ratio)
  4180. {
  4181. case BackbufferRatio::Half: _width /= 2; _height /= 2; break;
  4182. case BackbufferRatio::Quarter: _width /= 4; _height /= 4; break;
  4183. case BackbufferRatio::Eighth: _width /= 8; _height /= 8; break;
  4184. case BackbufferRatio::Sixteenth: _width /= 16; _height /= 16; break;
  4185. case BackbufferRatio::Double: _width *= 2; _height *= 2; break;
  4186. default:
  4187. break;
  4188. }
  4189. _width = bx::max<uint16_t>(1, _width);
  4190. _height = bx::max<uint16_t>(1, _height);
  4191. }
  4192. static TextureHandle createTexture2D(BackbufferRatio::Enum _ratio, uint16_t _width, uint16_t _height, bool _hasMips, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags, const Memory* _mem)
  4193. {
  4194. if (BackbufferRatio::Count != _ratio)
  4195. {
  4196. _width = uint16_t(s_ctx->m_init.resolution.width);
  4197. _height = uint16_t(s_ctx->m_init.resolution.height);
  4198. getTextureSizeFromRatio(_ratio, _width, _height);
  4199. }
  4200. bx::ErrorAssert err;
  4201. isTextureValid(_width, _height, 0, false, _numLayers, _format, _flags, &err);
  4202. if (!err.isOk() )
  4203. {
  4204. return BGFX_INVALID_HANDLE;
  4205. }
  4206. const uint8_t numMips = calcNumMips(_hasMips, _width, _height);
  4207. _numLayers = bx::max<uint16_t>(_numLayers, 1);
  4208. if (BX_ENABLED(BGFX_CONFIG_DEBUG)
  4209. && NULL != _mem)
  4210. {
  4211. TextureInfo ti;
  4212. calcTextureSize(ti, _width, _height, 1, false, _hasMips, _numLayers, _format);
  4213. BX_ASSERT(ti.storageSize == _mem->size
  4214. , "createTexture2D: Texture storage size doesn't match passed memory size (storage size: %d, memory size: %d)"
  4215. , ti.storageSize
  4216. , _mem->size
  4217. );
  4218. }
  4219. uint32_t size = sizeof(uint32_t)+sizeof(TextureCreate);
  4220. const Memory* mem = alloc(size);
  4221. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  4222. bx::write(&writer, kChunkMagicTex, bx::ErrorAssert{});
  4223. TextureCreate tc;
  4224. tc.m_width = _width;
  4225. tc.m_height = _height;
  4226. tc.m_depth = 0;
  4227. tc.m_numLayers = _numLayers;
  4228. tc.m_numMips = numMips;
  4229. tc.m_format = _format;
  4230. tc.m_cubeMap = false;
  4231. tc.m_mem = _mem;
  4232. bx::write(&writer, tc, bx::ErrorAssert{});
  4233. return s_ctx->createTexture(mem, _flags, 0, NULL, _ratio, NULL != _mem);
  4234. }
  4235. TextureHandle createTexture2D(uint16_t _width, uint16_t _height, bool _hasMips, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags, const Memory* _mem)
  4236. {
  4237. BX_ASSERT(_width > 0 && _height > 0, "Invalid texture size (width %d, height %d).", _width, _height);
  4238. return createTexture2D(BackbufferRatio::Count, _width, _height, _hasMips, _numLayers, _format, _flags, _mem);
  4239. }
  4240. TextureHandle createTexture2D(BackbufferRatio::Enum _ratio, bool _hasMips, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags)
  4241. {
  4242. BX_ASSERT(_ratio < BackbufferRatio::Count, "Invalid back buffer ratio.");
  4243. return createTexture2D(_ratio, 0, 0, _hasMips, _numLayers, _format, _flags, NULL);
  4244. }
  4245. TextureHandle createTexture3D(uint16_t _width, uint16_t _height, uint16_t _depth, bool _hasMips, TextureFormat::Enum _format, uint64_t _flags, const Memory* _mem)
  4246. {
  4247. bx::ErrorAssert err;
  4248. isTextureValid(_width, _height, _depth, false, 1, _format, _flags, &err);
  4249. if (!err.isOk() )
  4250. {
  4251. return BGFX_INVALID_HANDLE;
  4252. }
  4253. const uint8_t numMips = calcNumMips(_hasMips, _width, _height, _depth);
  4254. if (BX_ENABLED(BGFX_CONFIG_DEBUG)
  4255. && NULL != _mem)
  4256. {
  4257. TextureInfo ti;
  4258. calcTextureSize(ti, _width, _height, _depth, false, _hasMips, 1, _format);
  4259. BX_ASSERT(ti.storageSize == _mem->size
  4260. , "createTexture3D: Texture storage size doesn't match passed memory size (storage size: %d, memory size: %d)"
  4261. , ti.storageSize
  4262. , _mem->size
  4263. );
  4264. }
  4265. uint32_t size = sizeof(uint32_t)+sizeof(TextureCreate);
  4266. const Memory* mem = alloc(size);
  4267. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  4268. bx::write(&writer, kChunkMagicTex, bx::ErrorAssert{});
  4269. TextureCreate tc;
  4270. tc.m_width = _width;
  4271. tc.m_height = _height;
  4272. tc.m_depth = _depth;
  4273. tc.m_numLayers = 1;
  4274. tc.m_numMips = numMips;
  4275. tc.m_format = _format;
  4276. tc.m_cubeMap = false;
  4277. tc.m_mem = _mem;
  4278. bx::write(&writer, tc, bx::ErrorAssert{});
  4279. return s_ctx->createTexture(mem, _flags, 0, NULL, BackbufferRatio::Count, NULL != _mem);
  4280. }
  4281. TextureHandle createTextureCube(uint16_t _size, bool _hasMips, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags, const Memory* _mem)
  4282. {
  4283. bx::ErrorAssert err;
  4284. isTextureValid(_size, _size, 0, true, _numLayers, _format, _flags, &err);
  4285. if (!err.isOk() )
  4286. {
  4287. return BGFX_INVALID_HANDLE;
  4288. }
  4289. const uint8_t numMips = calcNumMips(_hasMips, _size, _size);
  4290. _numLayers = bx::max<uint16_t>(_numLayers, 1);
  4291. if (BX_ENABLED(BGFX_CONFIG_DEBUG)
  4292. && NULL != _mem)
  4293. {
  4294. TextureInfo ti;
  4295. calcTextureSize(ti, _size, _size, 1, true, _hasMips, _numLayers, _format);
  4296. BX_ASSERT(ti.storageSize == _mem->size
  4297. , "createTextureCube: Texture storage size doesn't match passed memory size (storage size: %d, memory size: %d)"
  4298. , ti.storageSize
  4299. , _mem->size
  4300. );
  4301. }
  4302. uint32_t size = sizeof(uint32_t)+sizeof(TextureCreate);
  4303. const Memory* mem = alloc(size);
  4304. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  4305. bx::write(&writer, kChunkMagicTex, bx::ErrorAssert{});
  4306. TextureCreate tc;
  4307. tc.m_width = _size;
  4308. tc.m_height = _size;
  4309. tc.m_depth = 0;
  4310. tc.m_numLayers = _numLayers;
  4311. tc.m_numMips = numMips;
  4312. tc.m_format = _format;
  4313. tc.m_cubeMap = true;
  4314. tc.m_mem = _mem;
  4315. bx::write(&writer, tc, bx::ErrorAssert{});
  4316. return s_ctx->createTexture(mem, _flags, 0, NULL, BackbufferRatio::Count, NULL != _mem);
  4317. }
  4318. void setName(TextureHandle _handle, const char* _name, int32_t _len)
  4319. {
  4320. s_ctx->setName(_handle, bx::StringView(_name, _len) );
  4321. }
  4322. void* getDirectAccessPtr(TextureHandle _handle)
  4323. {
  4324. return s_ctx->getDirectAccessPtr(_handle);
  4325. }
  4326. void destroy(TextureHandle _handle)
  4327. {
  4328. s_ctx->destroyTexture(_handle);
  4329. }
  4330. void updateTexture2D(TextureHandle _handle, uint16_t _layer, uint8_t _mip, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height, const Memory* _mem, uint16_t _pitch)
  4331. {
  4332. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  4333. if (_width == 0
  4334. || _height == 0)
  4335. {
  4336. release(_mem);
  4337. }
  4338. else
  4339. {
  4340. s_ctx->updateTexture(_handle, 0, _mip, _x, _y, _layer, _width, _height, 1, _pitch, _mem);
  4341. }
  4342. }
  4343. void updateTexture3D(TextureHandle _handle, uint8_t _mip, uint16_t _x, uint16_t _y, uint16_t _z, uint16_t _width, uint16_t _height, uint16_t _depth, const Memory* _mem)
  4344. {
  4345. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  4346. BGFX_CHECK_CAPS(BGFX_CAPS_TEXTURE_3D, "Texture3D is not supported!");
  4347. if (0 == _width
  4348. || 0 == _height
  4349. || 0 == _depth)
  4350. {
  4351. release(_mem);
  4352. }
  4353. else
  4354. {
  4355. s_ctx->updateTexture(_handle, 0, _mip, _x, _y, _z, _width, _height, _depth, UINT16_MAX, _mem);
  4356. }
  4357. }
  4358. void updateTextureCube(TextureHandle _handle, uint16_t _layer, uint8_t _side, uint8_t _mip, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height, const Memory* _mem, uint16_t _pitch)
  4359. {
  4360. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  4361. BX_ASSERT(_side <= 5, "Invalid side %d.", _side);
  4362. if (0 == _width
  4363. || 0 == _height)
  4364. {
  4365. release(_mem);
  4366. }
  4367. else
  4368. {
  4369. s_ctx->updateTexture(_handle, _side, _mip, _x, _y, _layer, _width, _height, 1, _pitch, _mem);
  4370. }
  4371. }
  4372. uint32_t readTexture(TextureHandle _handle, void* _data, uint8_t _mip)
  4373. {
  4374. BX_ASSERT(NULL != _data, "_data can't be NULL");
  4375. BGFX_CHECK_CAPS(BGFX_CAPS_TEXTURE_READ_BACK, "Texture read-back is not supported!");
  4376. return s_ctx->readTexture(_handle, _data, _mip);
  4377. }
  4378. FrameBufferHandle createFrameBuffer(uint16_t _width, uint16_t _height, TextureFormat::Enum _format, uint64_t _textureFlags)
  4379. {
  4380. _textureFlags |= _textureFlags&BGFX_TEXTURE_RT_MSAA_MASK ? 0 : BGFX_TEXTURE_RT;
  4381. TextureHandle th = createTexture2D(_width, _height, false, 1, _format, _textureFlags);
  4382. return createFrameBuffer(1, &th, true);
  4383. }
  4384. FrameBufferHandle createFrameBuffer(BackbufferRatio::Enum _ratio, TextureFormat::Enum _format, uint64_t _textureFlags)
  4385. {
  4386. BX_ASSERT(_ratio < BackbufferRatio::Count, "Invalid back buffer ratio.");
  4387. _textureFlags |= _textureFlags&BGFX_TEXTURE_RT_MSAA_MASK ? 0 : BGFX_TEXTURE_RT;
  4388. TextureHandle th = createTexture2D(_ratio, false, 1, _format, _textureFlags);
  4389. return createFrameBuffer(1, &th, true);
  4390. }
  4391. FrameBufferHandle createFrameBuffer(uint8_t _num, const TextureHandle* _handles, bool _destroyTextures)
  4392. {
  4393. Attachment attachment[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS];
  4394. for (uint8_t ii = 0; ii < _num; ++ii)
  4395. {
  4396. Attachment& at = attachment[ii];
  4397. at.init(_handles[ii], Access::Write, 0, 1, 0, BGFX_RESOLVE_AUTO_GEN_MIPS);
  4398. }
  4399. return createFrameBuffer(_num, attachment, _destroyTextures);
  4400. }
  4401. FrameBufferHandle createFrameBuffer(uint8_t _num, const Attachment* _attachment, bool _destroyTextures)
  4402. {
  4403. BX_ASSERT(_num != 0, "Number of frame buffer attachments can't be 0.");
  4404. BX_ASSERT(_num <= BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS
  4405. , "Number of frame buffer attachments is larger than allowed %d (max: %d)."
  4406. , _num
  4407. , BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS
  4408. );
  4409. BX_ASSERT(NULL != _attachment, "_attachment can't be NULL");
  4410. return s_ctx->createFrameBuffer(_num, _attachment, _destroyTextures);
  4411. }
  4412. FrameBufferHandle createFrameBuffer(void* _nwh, uint16_t _width, uint16_t _height, TextureFormat::Enum _format, TextureFormat::Enum _depthFormat)
  4413. {
  4414. BGFX_CHECK_CAPS(BGFX_CAPS_SWAP_CHAIN, "Swap chain is not supported!");
  4415. BX_WARN(_width > 0 && _height > 0
  4416. , "Invalid frame buffer dimensions (width %d, height %d)."
  4417. , _width
  4418. , _height
  4419. );
  4420. BX_ASSERT(_format == TextureFormat::Count || bimg::isColor(bimg::TextureFormat::Enum(_format) )
  4421. , "Invalid texture format for color (%s)."
  4422. , bimg::getName(bimg::TextureFormat::Enum(_format) )
  4423. );
  4424. BX_ASSERT(_depthFormat == TextureFormat::Count || bimg::isDepth(bimg::TextureFormat::Enum(_depthFormat) )
  4425. , "Invalid texture format for depth (%s)."
  4426. , bimg::getName(bimg::TextureFormat::Enum(_depthFormat) )
  4427. );
  4428. return s_ctx->createFrameBuffer(
  4429. _nwh
  4430. , bx::max<uint16_t>(_width, 1)
  4431. , bx::max<uint16_t>(_height, 1)
  4432. , _format
  4433. , _depthFormat
  4434. );
  4435. }
  4436. void setName(FrameBufferHandle _handle, const char* _name, int32_t _len)
  4437. {
  4438. s_ctx->setName(_handle, bx::StringView(_name, _len) );
  4439. }
  4440. TextureHandle getTexture(FrameBufferHandle _handle, uint8_t _attachment)
  4441. {
  4442. return s_ctx->getTexture(_handle, _attachment);
  4443. }
  4444. void destroy(FrameBufferHandle _handle)
  4445. {
  4446. s_ctx->destroyFrameBuffer(_handle);
  4447. }
  4448. UniformHandle createUniform(const char* _name, UniformType::Enum _type, uint16_t _num)
  4449. {
  4450. BX_ASSERT(UniformType::End != _type && UniformType::Count > _type
  4451. , "UniformType argument is not valid (_type: %d)!"
  4452. , _type
  4453. );
  4454. return s_ctx->createUniform(_name, UniformFreq::Draw, _type, _num);
  4455. }
  4456. UniformHandle createUniform(const char* _name, UniformFreq::Enum _freq, UniformType::Enum _type, uint16_t _num)
  4457. {
  4458. BX_ASSERT(UniformType::End != _type && UniformType::Count > _type
  4459. , "UniformType argument is not valid (_type: %d)!"
  4460. , _type
  4461. );
  4462. BX_ASSERT(UniformFreq::Count > _freq
  4463. , "UniformFreq argument is not valid (_freq: %d)!"
  4464. , _freq
  4465. );
  4466. return s_ctx->createUniform(_name, _freq, _type, _num);
  4467. }
  4468. void getUniformInfo(UniformHandle _handle, UniformInfo& _info)
  4469. {
  4470. s_ctx->getUniformInfo(_handle, _info);
  4471. }
  4472. void destroy(UniformHandle _handle)
  4473. {
  4474. s_ctx->destroyUniform(_handle);
  4475. }
  4476. OcclusionQueryHandle createOcclusionQuery()
  4477. {
  4478. BGFX_CHECK_CAPS(BGFX_CAPS_OCCLUSION_QUERY, "Occlusion query is not supported!");
  4479. return s_ctx->createOcclusionQuery();
  4480. }
  4481. OcclusionQueryResult::Enum getResult(OcclusionQueryHandle _handle, int32_t* _result)
  4482. {
  4483. BGFX_CHECK_CAPS(BGFX_CAPS_OCCLUSION_QUERY, "Occlusion query is not supported!");
  4484. return s_ctx->getResult(_handle, _result);
  4485. }
  4486. void destroy(OcclusionQueryHandle _handle)
  4487. {
  4488. BGFX_CHECK_CAPS(BGFX_CAPS_OCCLUSION_QUERY, "Occlusion query is not supported!");
  4489. s_ctx->destroyOcclusionQuery(_handle);
  4490. }
  4491. void setPaletteColor(uint8_t _index, uint32_t _rgba)
  4492. {
  4493. const uint8_t rr = uint8_t(_rgba>>24);
  4494. const uint8_t gg = uint8_t(_rgba>>16);
  4495. const uint8_t bb = uint8_t(_rgba>> 8);
  4496. const uint8_t aa = uint8_t(_rgba>> 0);
  4497. const float rgba[4] =
  4498. {
  4499. rr * 1.0f/255.0f,
  4500. gg * 1.0f/255.0f,
  4501. bb * 1.0f/255.0f,
  4502. aa * 1.0f/255.0f,
  4503. };
  4504. s_ctx->setPaletteColor(_index, rgba);
  4505. }
  4506. void setPaletteColor(uint8_t _index, float _r, float _g, float _b, float _a)
  4507. {
  4508. float rgba[4] = { _r, _g, _b, _a };
  4509. s_ctx->setPaletteColor(_index, rgba);
  4510. }
  4511. void setPaletteColor(uint8_t _index, const float _rgba[4])
  4512. {
  4513. s_ctx->setPaletteColor(_index, _rgba);
  4514. }
  4515. bool checkView(ViewId _id)
  4516. {
  4517. // workaround GCC 4.9 type-limit check.
  4518. const uint32_t id = _id;
  4519. return id < BGFX_CONFIG_MAX_VIEWS;
  4520. }
  4521. void setViewName(ViewId _id, const char* _name, int32_t _len)
  4522. {
  4523. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4524. s_ctx->setViewName(_id, bx::StringView(_name, _len) );
  4525. }
  4526. void setViewRect(ViewId _id, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height)
  4527. {
  4528. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4529. s_ctx->setViewRect(_id, _x, _y, _width, _height);
  4530. }
  4531. void setViewRect(ViewId _id, uint16_t _x, uint16_t _y, BackbufferRatio::Enum _ratio)
  4532. {
  4533. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4534. uint16_t width = uint16_t(s_ctx->m_init.resolution.width);
  4535. uint16_t height = uint16_t(s_ctx->m_init.resolution.height);
  4536. getTextureSizeFromRatio(_ratio, width, height);
  4537. setViewRect(_id, _x, _y, width, height);
  4538. }
  4539. void setViewScissor(ViewId _id, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height)
  4540. {
  4541. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4542. s_ctx->setViewScissor(_id, _x, _y, _width, _height);
  4543. }
  4544. void setViewClear(ViewId _id, uint16_t _flags, uint32_t _rgba, float _depth, uint8_t _stencil)
  4545. {
  4546. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4547. s_ctx->setViewClear(_id, _flags, _rgba, _depth, _stencil);
  4548. }
  4549. void setViewClear(ViewId _id, uint16_t _flags, float _depth, uint8_t _stencil, uint8_t _0, uint8_t _1, uint8_t _2, uint8_t _3, uint8_t _4, uint8_t _5, uint8_t _6, uint8_t _7)
  4550. {
  4551. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4552. s_ctx->setViewClear(_id, _flags, _depth, _stencil, _0, _1, _2, _3, _4, _5, _6, _7);
  4553. }
  4554. void setViewMode(ViewId _id, ViewMode::Enum _mode)
  4555. {
  4556. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4557. s_ctx->setViewMode(_id, _mode);
  4558. }
  4559. void setViewFrameBuffer(ViewId _id, FrameBufferHandle _handle)
  4560. {
  4561. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4562. s_ctx->setViewFrameBuffer(_id, _handle);
  4563. }
  4564. void setViewTransform(ViewId _id, const void* _view, const void* _proj)
  4565. {
  4566. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4567. s_ctx->setViewTransform(_id, _view, _proj);
  4568. }
  4569. void setViewOrder(ViewId _id, uint16_t _num, const ViewId* _order)
  4570. {
  4571. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4572. s_ctx->setViewOrder(_id, _num, _order);
  4573. }
  4574. void setViewShadingRate(ViewId _id, ShadingRate::Enum _shadingRate)
  4575. {
  4576. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4577. s_ctx->setViewShadingRate(_id, _shadingRate);
  4578. }
  4579. void resetView(ViewId _id)
  4580. {
  4581. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4582. s_ctx->resetView(_id);
  4583. }
  4584. #define BGFX_CHECK_ENCODER0() \
  4585. BGFX_CHECK_API_THREAD(); \
  4586. BGFX_FATAL(NULL != s_ctx->m_encoder0, Fatal::DebugCheck \
  4587. , "bgfx is configured to allow only encoder API. See: `BGFX_CONFIG_ENCODER_API_ONLY`.")
  4588. void setMarker(const char* _name, int32_t _len)
  4589. {
  4590. BGFX_CHECK_ENCODER0();
  4591. s_ctx->m_encoder0->setMarker(_name, _len);
  4592. }
  4593. void setState(uint64_t _state, uint32_t _rgba)
  4594. {
  4595. BGFX_CHECK_ENCODER0();
  4596. s_ctx->m_encoder0->setState(_state, _rgba);
  4597. }
  4598. void setCondition(OcclusionQueryHandle _handle, bool _visible)
  4599. {
  4600. BGFX_CHECK_ENCODER0();
  4601. s_ctx->m_encoder0->setCondition(_handle, _visible);
  4602. }
  4603. void setStencil(uint32_t _fstencil, uint32_t _bstencil)
  4604. {
  4605. BGFX_CHECK_ENCODER0();
  4606. s_ctx->m_encoder0->setStencil(_fstencil, _bstencil);
  4607. }
  4608. uint16_t setScissor(uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height)
  4609. {
  4610. BGFX_CHECK_ENCODER0();
  4611. return s_ctx->m_encoder0->setScissor(_x, _y, _width, _height);
  4612. }
  4613. void setScissor(uint16_t _cache)
  4614. {
  4615. BGFX_CHECK_ENCODER0();
  4616. s_ctx->m_encoder0->setScissor(_cache);
  4617. }
  4618. uint32_t setTransform(const void* _mtx, uint16_t _num)
  4619. {
  4620. BGFX_CHECK_ENCODER0();
  4621. return s_ctx->m_encoder0->setTransform(_mtx, _num);
  4622. }
  4623. uint32_t allocTransform(Transform* _transform, uint16_t _num)
  4624. {
  4625. BGFX_CHECK_ENCODER0();
  4626. return s_ctx->m_encoder0->allocTransform(_transform, _num);
  4627. }
  4628. void setTransform(uint32_t _cache, uint16_t _num)
  4629. {
  4630. BGFX_CHECK_ENCODER0();
  4631. s_ctx->m_encoder0->setTransform(_cache, _num);
  4632. }
  4633. void setUniform(UniformHandle _handle, const void* _value, uint16_t _num)
  4634. {
  4635. BGFX_CHECK_ENCODER0();
  4636. s_ctx->m_encoder0->setUniform(_handle, _value, _num);
  4637. }
  4638. void setViewUniform(ViewId _id, UniformHandle _handle, const void* _value, uint16_t _num)
  4639. {
  4640. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4641. BGFX_CHECK_HANDLE("setUniform", s_ctx->m_uniformHandle, _handle);
  4642. s_ctx->setViewUniform(_id, _handle, _value, _num);
  4643. }
  4644. void setFrameUniform(UniformHandle _handle, const void* _value, uint16_t _num)
  4645. {
  4646. BGFX_CHECK_HANDLE("setUniform", s_ctx->m_uniformHandle, _handle);
  4647. s_ctx->setViewUniform(UINT16_MAX, _handle, _value, _num);
  4648. }
  4649. void setIndexBuffer(IndexBufferHandle _handle)
  4650. {
  4651. BGFX_CHECK_ENCODER0();
  4652. s_ctx->m_encoder0->setIndexBuffer(_handle);
  4653. }
  4654. void setIndexBuffer(IndexBufferHandle _handle, uint32_t _firstIndex, uint32_t _numIndices)
  4655. {
  4656. BGFX_CHECK_ENCODER0();
  4657. s_ctx->m_encoder0->setIndexBuffer(_handle, _firstIndex, _numIndices);
  4658. }
  4659. void setIndexBuffer(DynamicIndexBufferHandle _handle)
  4660. {
  4661. BGFX_CHECK_ENCODER0();
  4662. s_ctx->m_encoder0->setIndexBuffer(_handle);
  4663. }
  4664. void setIndexBuffer(DynamicIndexBufferHandle _handle, uint32_t _firstIndex, uint32_t _numIndices)
  4665. {
  4666. BGFX_CHECK_ENCODER0();
  4667. s_ctx->m_encoder0->setIndexBuffer(_handle, _firstIndex, _numIndices);
  4668. }
  4669. void setIndexBuffer(const TransientIndexBuffer* _tib)
  4670. {
  4671. BGFX_CHECK_ENCODER0();
  4672. s_ctx->m_encoder0->setIndexBuffer(_tib);
  4673. }
  4674. void setIndexBuffer(const TransientIndexBuffer* _tib, uint32_t _firstIndex, uint32_t _numIndices)
  4675. {
  4676. BGFX_CHECK_ENCODER0();
  4677. s_ctx->m_encoder0->setIndexBuffer(_tib, _firstIndex, _numIndices);
  4678. }
  4679. void setVertexBuffer(
  4680. uint8_t _stream
  4681. , VertexBufferHandle _handle
  4682. , uint32_t _startVertex
  4683. , uint32_t _numVertices
  4684. , VertexLayoutHandle _layoutHandle
  4685. )
  4686. {
  4687. BGFX_CHECK_ENCODER0();
  4688. s_ctx->m_encoder0->setVertexBuffer(_stream, _handle, _startVertex, _numVertices, _layoutHandle);
  4689. }
  4690. void setVertexBuffer(uint8_t _stream, VertexBufferHandle _handle)
  4691. {
  4692. BGFX_CHECK_ENCODER0();
  4693. s_ctx->m_encoder0->setVertexBuffer(_stream, _handle);
  4694. }
  4695. void setVertexBuffer(
  4696. uint8_t _stream
  4697. , DynamicVertexBufferHandle _handle
  4698. , uint32_t _startVertex
  4699. , uint32_t _numVertices
  4700. , VertexLayoutHandle _layoutHandle
  4701. )
  4702. {
  4703. BGFX_CHECK_ENCODER0();
  4704. s_ctx->m_encoder0->setVertexBuffer(_stream, _handle, _startVertex, _numVertices, _layoutHandle);
  4705. }
  4706. void setVertexBuffer(uint8_t _stream, DynamicVertexBufferHandle _handle)
  4707. {
  4708. BGFX_CHECK_ENCODER0();
  4709. s_ctx->m_encoder0->setVertexBuffer(_stream, _handle);
  4710. }
  4711. void setVertexBuffer(
  4712. uint8_t _stream
  4713. , const TransientVertexBuffer* _tvb
  4714. , uint32_t _startVertex
  4715. , uint32_t _numVertices
  4716. , VertexLayoutHandle _layoutHandle
  4717. )
  4718. {
  4719. BGFX_CHECK_ENCODER0();
  4720. s_ctx->m_encoder0->setVertexBuffer(_stream, _tvb, _startVertex, _numVertices, _layoutHandle);
  4721. }
  4722. void setVertexBuffer(uint8_t _stream, const TransientVertexBuffer* _tvb)
  4723. {
  4724. BGFX_CHECK_ENCODER0();
  4725. s_ctx->m_encoder0->setVertexBuffer(_stream, _tvb);
  4726. }
  4727. void setVertexCount(uint32_t _numVertices)
  4728. {
  4729. BGFX_CHECK_ENCODER0();
  4730. s_ctx->m_encoder0->setVertexCount(_numVertices);
  4731. }
  4732. void setInstanceDataBuffer(const InstanceDataBuffer* _idb)
  4733. {
  4734. BGFX_CHECK_ENCODER0();
  4735. s_ctx->m_encoder0->setInstanceDataBuffer(_idb);
  4736. }
  4737. void setInstanceDataBuffer(const InstanceDataBuffer* _idb, uint32_t _start, uint32_t _num)
  4738. {
  4739. BGFX_CHECK_ENCODER0();
  4740. s_ctx->m_encoder0->setInstanceDataBuffer(_idb, _start, _num);
  4741. }
  4742. void setInstanceDataBuffer(VertexBufferHandle _handle, uint32_t _startVertex, uint32_t _num)
  4743. {
  4744. BGFX_CHECK_ENCODER0();
  4745. s_ctx->m_encoder0->setInstanceDataBuffer(_handle, _startVertex, _num);
  4746. }
  4747. void setInstanceDataBuffer(DynamicVertexBufferHandle _handle, uint32_t _startVertex, uint32_t _num)
  4748. {
  4749. BGFX_CHECK_ENCODER0();
  4750. s_ctx->m_encoder0->setInstanceDataBuffer(_handle, _startVertex, _num);
  4751. }
  4752. void setInstanceCount(uint32_t _numInstances)
  4753. {
  4754. BGFX_CHECK_ENCODER0();
  4755. s_ctx->m_encoder0->setInstanceCount(_numInstances);
  4756. }
  4757. void setTexture(uint8_t _stage, UniformHandle _sampler, TextureHandle _handle, uint32_t _flags)
  4758. {
  4759. BGFX_CHECK_ENCODER0();
  4760. s_ctx->m_encoder0->setTexture(_stage, _sampler, _handle, _flags);
  4761. }
  4762. void touch(ViewId _id)
  4763. {
  4764. BGFX_CHECK_ENCODER0();
  4765. s_ctx->m_encoder0->touch(_id);
  4766. }
  4767. void submit(ViewId _id, ProgramHandle _program, uint32_t _depth, uint8_t _flags)
  4768. {
  4769. BGFX_CHECK_ENCODER0();
  4770. s_ctx->m_encoder0->submit(_id, _program, _depth, _flags);
  4771. }
  4772. void submit(ViewId _id, ProgramHandle _program, OcclusionQueryHandle _occlusionQuery, uint32_t _depth, uint8_t _flags)
  4773. {
  4774. BGFX_CHECK_ENCODER0();
  4775. s_ctx->m_encoder0->submit(_id, _program, _occlusionQuery, _depth, _flags);
  4776. }
  4777. void submit(ViewId _id, ProgramHandle _program, IndirectBufferHandle _indirectHandle, uint32_t _start, uint32_t _num, uint32_t _depth, uint8_t _flags)
  4778. {
  4779. BGFX_CHECK_ENCODER0();
  4780. s_ctx->m_encoder0->submit(_id, _program, _indirectHandle, _start, _num, _depth, _flags);
  4781. }
  4782. void submit(ViewId _id, ProgramHandle _program, IndirectBufferHandle _indirectHandle, uint32_t _start, IndexBufferHandle _numHandle, uint32_t _numIndex, uint32_t _numMax, uint32_t _depth, uint8_t _flags)
  4783. {
  4784. BGFX_CHECK_ENCODER0();
  4785. s_ctx->m_encoder0->submit(_id, _program, _indirectHandle, _start, _numHandle, _numIndex, _numMax, _depth, _flags);
  4786. }
  4787. void setBuffer(uint8_t _stage, IndexBufferHandle _handle, Access::Enum _access)
  4788. {
  4789. BGFX_CHECK_ENCODER0();
  4790. s_ctx->m_encoder0->setBuffer(_stage, _handle, _access);
  4791. }
  4792. void setBuffer(uint8_t _stage, VertexBufferHandle _handle, Access::Enum _access)
  4793. {
  4794. BGFX_CHECK_ENCODER0();
  4795. s_ctx->m_encoder0->setBuffer(_stage, _handle, _access);
  4796. }
  4797. void setBuffer(uint8_t _stage, DynamicIndexBufferHandle _handle, Access::Enum _access)
  4798. {
  4799. BGFX_CHECK_ENCODER0();
  4800. s_ctx->m_encoder0->setBuffer(_stage, _handle, _access);
  4801. }
  4802. void setBuffer(uint8_t _stage, DynamicVertexBufferHandle _handle, Access::Enum _access)
  4803. {
  4804. BGFX_CHECK_ENCODER0();
  4805. s_ctx->m_encoder0->setBuffer(_stage, _handle, _access);
  4806. }
  4807. void setBuffer(uint8_t _stage, IndirectBufferHandle _handle, Access::Enum _access)
  4808. {
  4809. BGFX_CHECK_ENCODER0();
  4810. s_ctx->m_encoder0->setBuffer(_stage, _handle, _access);
  4811. }
  4812. void setImage(uint8_t _stage, TextureHandle _handle, uint8_t _mip, Access::Enum _access, TextureFormat::Enum _format)
  4813. {
  4814. BGFX_CHECK_ENCODER0();
  4815. s_ctx->m_encoder0->setImage(_stage, _handle, _mip, _access, _format);
  4816. }
  4817. void dispatch(ViewId _id, ProgramHandle _handle, uint32_t _numX, uint32_t _numY, uint32_t _numZ, uint8_t _flags)
  4818. {
  4819. BGFX_CHECK_ENCODER0();
  4820. s_ctx->m_encoder0->dispatch(_id, _handle, _numX, _numY, _numZ, _flags);
  4821. }
  4822. void dispatch(ViewId _id, ProgramHandle _handle, IndirectBufferHandle _indirectHandle, uint32_t _start, uint32_t _num, uint8_t _flags)
  4823. {
  4824. BGFX_CHECK_ENCODER0();
  4825. s_ctx->m_encoder0->dispatch(_id, _handle, _indirectHandle, _start, _num, _flags);
  4826. }
  4827. void discard(uint8_t _flags)
  4828. {
  4829. BGFX_CHECK_ENCODER0();
  4830. s_ctx->m_encoder0->discard(_flags);
  4831. }
  4832. void blit(ViewId _id, TextureHandle _dst, uint16_t _dstX, uint16_t _dstY, TextureHandle _src, uint16_t _srcX, uint16_t _srcY, uint16_t _width, uint16_t _height)
  4833. {
  4834. BGFX_CHECK_ENCODER0();
  4835. s_ctx->m_encoder0->blit(_id, _dst, _dstX, _dstY, _src, _srcX, _srcY, _width, _height);
  4836. }
  4837. void blit(ViewId _id, TextureHandle _dst, uint8_t _dstMip, uint16_t _dstX, uint16_t _dstY, uint16_t _dstZ, TextureHandle _src, uint8_t _srcMip, uint16_t _srcX, uint16_t _srcY, uint16_t _srcZ, uint16_t _width, uint16_t _height, uint16_t _depth)
  4838. {
  4839. BGFX_CHECK_ENCODER0();
  4840. s_ctx->m_encoder0->blit(_id, _dst, _dstMip, _dstX, _dstY, _dstZ, _src, _srcMip, _srcX, _srcY, _srcZ, _width, _height, _depth);
  4841. }
  4842. void requestScreenShot(FrameBufferHandle _handle, const char* _filePath)
  4843. {
  4844. BGFX_CHECK_API_THREAD();
  4845. s_ctx->requestScreenShot(_handle, _filePath);
  4846. }
  4847. #undef BGFX_CHECK_ENCODER0
  4848. } // namespace bgfx
  4849. #if BGFX_CONFIG_PREFER_DISCRETE_GPU
  4850. extern "C"
  4851. {
  4852. // When laptop setup has integrated and discrete GPU, following driver workarounds will
  4853. // select discrete GPU:
  4854. // Reference(s):
  4855. // - https://web.archive.org/web/20180722051003/https://docs.nvidia.com/gameworks/content/technologies/desktop/optimus.htm
  4856. //
  4857. __declspec(dllexport) uint32_t NvOptimusEnablement = UINT32_C(1);
  4858. // Reference(s):
  4859. // - https://web.archive.org/web/20180722051032/https://gpuopen.com/amdpowerxpressrequesthighperformance/
  4860. //
  4861. __declspec(dllexport) uint32_t AmdPowerXpressRequestHighPerformance = UINT32_C(1);
  4862. }
  4863. #endif // BGFX_CONFIG_PREFER_DISCRETE_GPU
  4864. #define BGFX_TEXTURE_FORMAT_BIMG(_fmt) \
  4865. static_assert(uint32_t(bgfx::TextureFormat::_fmt) == uint32_t(bimg::TextureFormat::_fmt) )
  4866. BGFX_TEXTURE_FORMAT_BIMG(BC1);
  4867. BGFX_TEXTURE_FORMAT_BIMG(BC2);
  4868. BGFX_TEXTURE_FORMAT_BIMG(BC3);
  4869. BGFX_TEXTURE_FORMAT_BIMG(BC4);
  4870. BGFX_TEXTURE_FORMAT_BIMG(BC5);
  4871. BGFX_TEXTURE_FORMAT_BIMG(BC6H);
  4872. BGFX_TEXTURE_FORMAT_BIMG(BC7);
  4873. BGFX_TEXTURE_FORMAT_BIMG(ETC1);
  4874. BGFX_TEXTURE_FORMAT_BIMG(ETC2);
  4875. BGFX_TEXTURE_FORMAT_BIMG(ETC2A);
  4876. BGFX_TEXTURE_FORMAT_BIMG(ETC2A1);
  4877. BGFX_TEXTURE_FORMAT_BIMG(PTC12);
  4878. BGFX_TEXTURE_FORMAT_BIMG(PTC14);
  4879. BGFX_TEXTURE_FORMAT_BIMG(PTC12A);
  4880. BGFX_TEXTURE_FORMAT_BIMG(PTC14A);
  4881. BGFX_TEXTURE_FORMAT_BIMG(PTC22);
  4882. BGFX_TEXTURE_FORMAT_BIMG(PTC24);
  4883. BGFX_TEXTURE_FORMAT_BIMG(ATC);
  4884. BGFX_TEXTURE_FORMAT_BIMG(ATCE);
  4885. BGFX_TEXTURE_FORMAT_BIMG(ATCI);
  4886. BGFX_TEXTURE_FORMAT_BIMG(ASTC4x4);
  4887. BGFX_TEXTURE_FORMAT_BIMG(ASTC5x4);
  4888. BGFX_TEXTURE_FORMAT_BIMG(ASTC5x5);
  4889. BGFX_TEXTURE_FORMAT_BIMG(ASTC6x5);
  4890. BGFX_TEXTURE_FORMAT_BIMG(ASTC6x6);
  4891. BGFX_TEXTURE_FORMAT_BIMG(ASTC8x5);
  4892. BGFX_TEXTURE_FORMAT_BIMG(ASTC8x6);
  4893. BGFX_TEXTURE_FORMAT_BIMG(ASTC8x8);
  4894. BGFX_TEXTURE_FORMAT_BIMG(ASTC10x5);
  4895. BGFX_TEXTURE_FORMAT_BIMG(ASTC10x6);
  4896. BGFX_TEXTURE_FORMAT_BIMG(ASTC10x8);
  4897. BGFX_TEXTURE_FORMAT_BIMG(ASTC10x10);
  4898. BGFX_TEXTURE_FORMAT_BIMG(ASTC12x10);
  4899. BGFX_TEXTURE_FORMAT_BIMG(ASTC12x12);
  4900. BGFX_TEXTURE_FORMAT_BIMG(Unknown);
  4901. BGFX_TEXTURE_FORMAT_BIMG(R1);
  4902. BGFX_TEXTURE_FORMAT_BIMG(A8);
  4903. BGFX_TEXTURE_FORMAT_BIMG(R8);
  4904. BGFX_TEXTURE_FORMAT_BIMG(R8I);
  4905. BGFX_TEXTURE_FORMAT_BIMG(R8U);
  4906. BGFX_TEXTURE_FORMAT_BIMG(R8S);
  4907. BGFX_TEXTURE_FORMAT_BIMG(R16);
  4908. BGFX_TEXTURE_FORMAT_BIMG(R16I);
  4909. BGFX_TEXTURE_FORMAT_BIMG(R16U);
  4910. BGFX_TEXTURE_FORMAT_BIMG(R16F);
  4911. BGFX_TEXTURE_FORMAT_BIMG(R16S);
  4912. BGFX_TEXTURE_FORMAT_BIMG(R32I);
  4913. BGFX_TEXTURE_FORMAT_BIMG(R32U);
  4914. BGFX_TEXTURE_FORMAT_BIMG(R32F);
  4915. BGFX_TEXTURE_FORMAT_BIMG(RG8);
  4916. BGFX_TEXTURE_FORMAT_BIMG(RG8I);
  4917. BGFX_TEXTURE_FORMAT_BIMG(RG8U);
  4918. BGFX_TEXTURE_FORMAT_BIMG(RG8S);
  4919. BGFX_TEXTURE_FORMAT_BIMG(RG16);
  4920. BGFX_TEXTURE_FORMAT_BIMG(RG16I);
  4921. BGFX_TEXTURE_FORMAT_BIMG(RG16U);
  4922. BGFX_TEXTURE_FORMAT_BIMG(RG16F);
  4923. BGFX_TEXTURE_FORMAT_BIMG(RG16S);
  4924. BGFX_TEXTURE_FORMAT_BIMG(RG32I);
  4925. BGFX_TEXTURE_FORMAT_BIMG(RG32U);
  4926. BGFX_TEXTURE_FORMAT_BIMG(RG32F);
  4927. BGFX_TEXTURE_FORMAT_BIMG(RGB8);
  4928. BGFX_TEXTURE_FORMAT_BIMG(RGB8I);
  4929. BGFX_TEXTURE_FORMAT_BIMG(RGB8U);
  4930. BGFX_TEXTURE_FORMAT_BIMG(RGB8S);
  4931. BGFX_TEXTURE_FORMAT_BIMG(RGB9E5F);
  4932. BGFX_TEXTURE_FORMAT_BIMG(BGRA8);
  4933. BGFX_TEXTURE_FORMAT_BIMG(RGBA8);
  4934. BGFX_TEXTURE_FORMAT_BIMG(RGBA8I);
  4935. BGFX_TEXTURE_FORMAT_BIMG(RGBA8U);
  4936. BGFX_TEXTURE_FORMAT_BIMG(RGBA8S);
  4937. BGFX_TEXTURE_FORMAT_BIMG(RGBA16);
  4938. BGFX_TEXTURE_FORMAT_BIMG(RGBA16I);
  4939. BGFX_TEXTURE_FORMAT_BIMG(RGBA16U);
  4940. BGFX_TEXTURE_FORMAT_BIMG(RGBA16F);
  4941. BGFX_TEXTURE_FORMAT_BIMG(RGBA16S);
  4942. BGFX_TEXTURE_FORMAT_BIMG(RGBA32I);
  4943. BGFX_TEXTURE_FORMAT_BIMG(RGBA32U);
  4944. BGFX_TEXTURE_FORMAT_BIMG(RGBA32F);
  4945. BGFX_TEXTURE_FORMAT_BIMG(B5G6R5);
  4946. BGFX_TEXTURE_FORMAT_BIMG(R5G6B5);
  4947. BGFX_TEXTURE_FORMAT_BIMG(BGRA4);
  4948. BGFX_TEXTURE_FORMAT_BIMG(RGBA4);
  4949. BGFX_TEXTURE_FORMAT_BIMG(BGR5A1);
  4950. BGFX_TEXTURE_FORMAT_BIMG(RGB5A1);
  4951. BGFX_TEXTURE_FORMAT_BIMG(RGB10A2);
  4952. BGFX_TEXTURE_FORMAT_BIMG(RG11B10F);
  4953. BGFX_TEXTURE_FORMAT_BIMG(UnknownDepth);
  4954. BGFX_TEXTURE_FORMAT_BIMG(D16);
  4955. BGFX_TEXTURE_FORMAT_BIMG(D24);
  4956. BGFX_TEXTURE_FORMAT_BIMG(D24S8);
  4957. BGFX_TEXTURE_FORMAT_BIMG(D32);
  4958. BGFX_TEXTURE_FORMAT_BIMG(D16F);
  4959. BGFX_TEXTURE_FORMAT_BIMG(D24F);
  4960. BGFX_TEXTURE_FORMAT_BIMG(D32F);
  4961. BGFX_TEXTURE_FORMAT_BIMG(D0S8);
  4962. BGFX_TEXTURE_FORMAT_BIMG(Count);
  4963. #undef BGFX_TEXTURE_FORMAT_BIMG
  4964. #include <bgfx/c99/bgfx.h>
  4965. #define FLAGS_MASK_TEST(_flags, _mask) ( (_flags) == ( (_flags) & (_mask) ) )
  4966. static_assert(FLAGS_MASK_TEST(0
  4967. | BGFX_SAMPLER_INTERNAL_DEFAULT
  4968. | BGFX_SAMPLER_INTERNAL_SHARED
  4969. , BGFX_SAMPLER_RESERVED_MASK
  4970. ) );
  4971. static_assert(FLAGS_MASK_TEST(0
  4972. | BGFX_RESET_INTERNAL_FORCE
  4973. , BGFX_RESET_RESERVED_MASK
  4974. ) );
  4975. static_assert(FLAGS_MASK_TEST(0
  4976. | BGFX_STATE_INTERNAL_SCISSOR
  4977. | BGFX_STATE_INTERNAL_OCCLUSION_QUERY
  4978. , BGFX_STATE_RESERVED_MASK
  4979. ) );
  4980. static_assert(FLAGS_MASK_TEST(0
  4981. | BGFX_SUBMIT_INTERNAL_OCCLUSION_VISIBLE
  4982. , BGFX_SUBMIT_INTERNAL_RESERVED_MASK
  4983. ) );
  4984. static_assert( (0
  4985. | BGFX_STATE_ALPHA_REF_MASK
  4986. | BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  4987. | BGFX_STATE_BLEND_EQUATION_MASK
  4988. | BGFX_STATE_BLEND_INDEPENDENT
  4989. | BGFX_STATE_BLEND_MASK
  4990. | BGFX_STATE_CONSERVATIVE_RASTER
  4991. | BGFX_STATE_CULL_MASK
  4992. | BGFX_STATE_DEPTH_TEST_MASK
  4993. | BGFX_STATE_FRONT_CCW
  4994. | BGFX_STATE_LINEAA
  4995. | BGFX_STATE_MSAA
  4996. | BGFX_STATE_POINT_SIZE_MASK
  4997. | BGFX_STATE_PT_MASK
  4998. | BGFX_STATE_RESERVED_MASK
  4999. | BGFX_STATE_WRITE_MASK
  5000. ) == (0
  5001. ^ BGFX_STATE_ALPHA_REF_MASK
  5002. ^ BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  5003. ^ BGFX_STATE_BLEND_EQUATION_MASK
  5004. ^ BGFX_STATE_BLEND_INDEPENDENT
  5005. ^ BGFX_STATE_BLEND_MASK
  5006. ^ BGFX_STATE_CONSERVATIVE_RASTER
  5007. ^ BGFX_STATE_CULL_MASK
  5008. ^ BGFX_STATE_DEPTH_TEST_MASK
  5009. ^ BGFX_STATE_FRONT_CCW
  5010. ^ BGFX_STATE_LINEAA
  5011. ^ BGFX_STATE_MSAA
  5012. ^ BGFX_STATE_POINT_SIZE_MASK
  5013. ^ BGFX_STATE_PT_MASK
  5014. ^ BGFX_STATE_RESERVED_MASK
  5015. ^ BGFX_STATE_WRITE_MASK
  5016. ) );
  5017. static_assert(FLAGS_MASK_TEST(BGFX_CAPS_TEXTURE_COMPARE_LEQUAL, BGFX_CAPS_TEXTURE_COMPARE_ALL) );
  5018. static_assert( (0
  5019. | BGFX_CAPS_ALPHA_TO_COVERAGE
  5020. | BGFX_CAPS_BLEND_INDEPENDENT
  5021. | BGFX_CAPS_COMPUTE
  5022. | BGFX_CAPS_CONSERVATIVE_RASTER
  5023. | BGFX_CAPS_DRAW_INDIRECT
  5024. | BGFX_CAPS_FRAGMENT_DEPTH
  5025. | BGFX_CAPS_FRAGMENT_ORDERING
  5026. | BGFX_CAPS_GRAPHICS_DEBUGGER
  5027. | BGFX_CAPS_HDR10
  5028. | BGFX_CAPS_HIDPI
  5029. | BGFX_CAPS_INDEX32
  5030. | BGFX_CAPS_INSTANCING
  5031. | BGFX_CAPS_OCCLUSION_QUERY
  5032. | BGFX_CAPS_RENDERER_MULTITHREADED
  5033. | BGFX_CAPS_SWAP_CHAIN
  5034. | BGFX_CAPS_TEXTURE_2D_ARRAY
  5035. | BGFX_CAPS_TEXTURE_3D
  5036. | BGFX_CAPS_TEXTURE_BLIT
  5037. | BGFX_CAPS_TEXTURE_CUBE_ARRAY
  5038. | BGFX_CAPS_TEXTURE_DIRECT_ACCESS
  5039. | BGFX_CAPS_TEXTURE_READ_BACK
  5040. | BGFX_CAPS_VERTEX_ATTRIB_HALF
  5041. | BGFX_CAPS_VERTEX_ATTRIB_UINT10
  5042. | BGFX_CAPS_VERTEX_ID
  5043. | BGFX_CAPS_PRIMITIVE_ID
  5044. | BGFX_CAPS_VIEWPORT_LAYER_ARRAY
  5045. | BGFX_CAPS_DRAW_INDIRECT_COUNT
  5046. ) == (0
  5047. ^ BGFX_CAPS_ALPHA_TO_COVERAGE
  5048. ^ BGFX_CAPS_BLEND_INDEPENDENT
  5049. ^ BGFX_CAPS_COMPUTE
  5050. ^ BGFX_CAPS_CONSERVATIVE_RASTER
  5051. ^ BGFX_CAPS_DRAW_INDIRECT
  5052. ^ BGFX_CAPS_FRAGMENT_DEPTH
  5053. ^ BGFX_CAPS_FRAGMENT_ORDERING
  5054. ^ BGFX_CAPS_GRAPHICS_DEBUGGER
  5055. ^ BGFX_CAPS_HDR10
  5056. ^ BGFX_CAPS_HIDPI
  5057. ^ BGFX_CAPS_INDEX32
  5058. ^ BGFX_CAPS_INSTANCING
  5059. ^ BGFX_CAPS_OCCLUSION_QUERY
  5060. ^ BGFX_CAPS_RENDERER_MULTITHREADED
  5061. ^ BGFX_CAPS_SWAP_CHAIN
  5062. ^ BGFX_CAPS_TEXTURE_2D_ARRAY
  5063. ^ BGFX_CAPS_TEXTURE_3D
  5064. ^ BGFX_CAPS_TEXTURE_BLIT
  5065. ^ BGFX_CAPS_TEXTURE_CUBE_ARRAY
  5066. ^ BGFX_CAPS_TEXTURE_DIRECT_ACCESS
  5067. ^ BGFX_CAPS_TEXTURE_READ_BACK
  5068. ^ BGFX_CAPS_VERTEX_ATTRIB_HALF
  5069. ^ BGFX_CAPS_VERTEX_ATTRIB_UINT10
  5070. ^ BGFX_CAPS_VERTEX_ID
  5071. ^ BGFX_CAPS_PRIMITIVE_ID
  5072. ^ BGFX_CAPS_VIEWPORT_LAYER_ARRAY
  5073. ^ BGFX_CAPS_DRAW_INDIRECT_COUNT
  5074. ) );
  5075. #undef FLAGS_MASK_TEST
  5076. namespace bgfx
  5077. {
  5078. struct CallbackC99 : public CallbackI
  5079. {
  5080. virtual ~CallbackC99()
  5081. {
  5082. }
  5083. virtual void fatal(const char* _filePath, uint16_t _line, Fatal::Enum _code, const char* _str) override
  5084. {
  5085. m_interface->vtbl->fatal(m_interface, _filePath, _line, (bgfx_fatal_t)_code, _str);
  5086. }
  5087. virtual void traceVargs(const char* _filePath, uint16_t _line, const char* _format, va_list _argList) override
  5088. {
  5089. m_interface->vtbl->trace_vargs(m_interface, _filePath, _line, _format, _argList);
  5090. }
  5091. virtual void profilerBegin(const char* _name, uint32_t _abgr, const char* _filePath, uint16_t _line) override
  5092. {
  5093. m_interface->vtbl->profiler_begin(m_interface, _name, _abgr, _filePath, _line);
  5094. }
  5095. virtual void profilerBeginLiteral(const char* _name, uint32_t _abgr, const char* _filePath, uint16_t _line) override
  5096. {
  5097. m_interface->vtbl->profiler_begin_literal(m_interface, _name, _abgr, _filePath, _line);
  5098. }
  5099. virtual void profilerEnd() override
  5100. {
  5101. m_interface->vtbl->profiler_end(m_interface);
  5102. }
  5103. virtual uint32_t cacheReadSize(uint64_t _id) override
  5104. {
  5105. return m_interface->vtbl->cache_read_size(m_interface, _id);
  5106. }
  5107. virtual bool cacheRead(uint64_t _id, void* _data, uint32_t _size) override
  5108. {
  5109. return m_interface->vtbl->cache_read(m_interface, _id, _data, _size);
  5110. }
  5111. virtual void cacheWrite(uint64_t _id, const void* _data, uint32_t _size) override
  5112. {
  5113. m_interface->vtbl->cache_write(m_interface, _id, _data, _size);
  5114. }
  5115. virtual void screenShot(const char* _filePath, uint32_t _width, uint32_t _height, uint32_t _pitch, const void* _data, uint32_t _size, bool _yflip) override
  5116. {
  5117. m_interface->vtbl->screen_shot(m_interface, _filePath, _width, _height, _pitch, _data, _size, _yflip);
  5118. }
  5119. virtual void captureBegin(uint32_t _width, uint32_t _height, uint32_t _pitch, TextureFormat::Enum _format, bool _yflip) override
  5120. {
  5121. m_interface->vtbl->capture_begin(m_interface, _width, _height, _pitch, (bgfx_texture_format_t)_format, _yflip);
  5122. }
  5123. virtual void captureEnd() override
  5124. {
  5125. m_interface->vtbl->capture_end(m_interface);
  5126. }
  5127. virtual void captureFrame(const void* _data, uint32_t _size) override
  5128. {
  5129. m_interface->vtbl->capture_frame(m_interface, _data, _size);
  5130. }
  5131. bgfx_callback_interface_t* m_interface;
  5132. };
  5133. class AllocatorC99 : public bx::AllocatorI
  5134. {
  5135. public:
  5136. virtual ~AllocatorC99()
  5137. {
  5138. }
  5139. virtual void* realloc(void* _ptr, size_t _size, size_t _align, const char* _file, uint32_t _line) override
  5140. {
  5141. return m_interface->vtbl->realloc(m_interface, _ptr, _size, _align, _file, _line);
  5142. }
  5143. bgfx_allocator_interface_t* m_interface;
  5144. };
  5145. } // namespace bgfx
  5146. #include "bgfx.idl.inl"