bgfx.cpp 169 KB

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