bgfx.cpp 151 KB

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