bgfx.cpp 169 KB

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