bgfx.cpp 153 KB

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