bgfx.cpp 169 KB

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