bgfx.cpp 165 KB

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