bgfx.cpp 148 KB

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