sokol_gfx.h 990 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325
  1. #if defined(SOKOL_IMPL) && !defined(SOKOL_GFX_IMPL)
  2. #define SOKOL_GFX_IMPL
  3. #endif
  4. #ifndef SOKOL_GFX_INCLUDED
  5. /*
  6. sokol_gfx.h -- simple 3D API wrapper
  7. Project URL: https://github.com/floooh/sokol
  8. Example code: https://github.com/floooh/sokol-samples
  9. Do this:
  10. #define SOKOL_IMPL or
  11. #define SOKOL_GFX_IMPL
  12. before you include this file in *one* C or C++ file to create the
  13. implementation.
  14. In the same place define one of the following to select the rendering
  15. backend:
  16. #define SOKOL_GLCORE
  17. #define SOKOL_GLES3
  18. #define SOKOL_D3D11
  19. #define SOKOL_METAL
  20. #define SOKOL_WGPU
  21. #define SOKOL_DUMMY_BACKEND
  22. I.e. for the desktop GL it should look like this:
  23. #include ...
  24. #include ...
  25. #define SOKOL_IMPL
  26. #define SOKOL_GLCORE
  27. #include "sokol_gfx.h"
  28. The dummy backend replaces the platform-specific backend code with empty
  29. stub functions. This is useful for writing tests that need to run on the
  30. command line.
  31. Optionally provide the following defines with your own implementations:
  32. SOKOL_ASSERT(c) - your own assert macro (default: assert(c))
  33. SOKOL_UNREACHABLE() - a guard macro for unreachable code (default: assert(false))
  34. SOKOL_GFX_API_DECL - public function declaration prefix (default: extern)
  35. SOKOL_API_DECL - same as SOKOL_GFX_API_DECL
  36. SOKOL_API_IMPL - public function implementation prefix (default: -)
  37. SOKOL_TRACE_HOOKS - enable trace hook callbacks (search below for TRACE HOOKS)
  38. SOKOL_EXTERNAL_GL_LOADER - indicates that you're using your own GL loader, in this case
  39. sokol_gfx.h will not include any platform GL headers and disable
  40. the integrated Win32 GL loader
  41. If sokol_gfx.h is compiled as a DLL, define the following before
  42. including the declaration or implementation:
  43. SOKOL_DLL
  44. On Windows, SOKOL_DLL will define SOKOL_GFX_API_DECL as __declspec(dllexport)
  45. or __declspec(dllimport) as needed.
  46. If you want to compile without deprecated structs and functions,
  47. define:
  48. SOKOL_NO_DEPRECATED
  49. Optionally define the following to force debug checks and validations
  50. even in release mode:
  51. SOKOL_DEBUG - by default this is defined if _DEBUG is defined
  52. sokol_gfx DOES NOT:
  53. ===================
  54. - create a window, swapchain or the 3D-API context/device, you must do this
  55. before sokol_gfx is initialized, and pass any required information
  56. (like 3D device pointers) to the sokol_gfx initialization call
  57. - present the rendered frame, how this is done exactly usually depends
  58. on how the window and 3D-API context/device was created
  59. - provide a unified shader language, instead 3D-API-specific shader
  60. source-code or shader-bytecode must be provided (for the "official"
  61. offline shader cross-compiler / code-generator, see here:
  62. https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md)
  63. STEP BY STEP
  64. ============
  65. --- to initialize sokol_gfx, after creating a window and a 3D-API
  66. context/device, call:
  67. sg_setup(const sg_desc*)
  68. Depending on the selected 3D backend, sokol-gfx requires some
  69. information about its runtime environment, like a GPU device pointer,
  70. default swapchain pixel formats and so on. If you are using sokol_app.h
  71. for the window system glue, you can use a helper function provided in
  72. the sokol_glue.h header:
  73. #include "sokol_gfx.h"
  74. #include "sokol_app.h"
  75. #include "sokol_glue.h"
  76. //...
  77. sg_setup(&(sg_desc){
  78. .environment = sglue_environment(),
  79. });
  80. To get any logging output for errors and from the validation layer, you
  81. need to provide a logging callback. Easiest way is through sokol_log.h:
  82. #include "sokol_log.h"
  83. //...
  84. sg_setup(&(sg_desc){
  85. //...
  86. .logger.func = slog_func,
  87. });
  88. --- create resource objects (at least buffers, shaders and pipelines,
  89. and optionally images, samplers and render/compute-pass-attachments):
  90. sg_buffer sg_make_buffer(const sg_buffer_desc*)
  91. sg_image sg_make_image(const sg_image_desc*)
  92. sg_sampler sg_make_sampler(const sg_sampler_desc*)
  93. sg_shader sg_make_shader(const sg_shader_desc*)
  94. sg_pipeline sg_make_pipeline(const sg_pipeline_desc*)
  95. sg_attachments sg_make_attachments(const sg_attachments_desc*)
  96. --- start a render- or compute-pass:
  97. sg_begin_pass(const sg_pass* pass);
  98. Typically, render passes render into an externally provided swapchain which
  99. presents the rendering result on the display. Such a 'swapchain pass'
  100. is started like this:
  101. sg_begin_pass(&(sg_pass){ .action = { ... }, .swapchain = sglue_swapchain() })
  102. ...where .action is an sg_pass_action struct containing actions to be performed
  103. at the start and end of a render pass (such as clearing the render surfaces to
  104. a specific color), and .swapchain is an sg_swapchain struct with all the required
  105. information to render into the swapchain's surfaces.
  106. To start an 'offscreen render pass' into sokol-gfx image objects, an sg_attachment
  107. object handle is required instead of an sg_swapchain struct. An offscreen
  108. pass is started like this (assuming attachments is an sg_attachments handle):
  109. sg_begin_pass(&(sg_pass){ .action = { ... }, .attachments = attachments });
  110. To start a compute-pass, just set the .compute item to true:
  111. sg_begin_pass(&(sg_pass){ .compute = true });
  112. If the compute pass writes into storage images, provide those as
  113. 'storage attachments' via an sg_attachments object:
  114. sg_begin_pass(&(sg_pass){ .compute = true, .attachments = attattachments });
  115. --- set the pipeline state for the next draw call with:
  116. sg_apply_pipeline(sg_pipeline pip)
  117. --- fill an sg_bindings struct with the resource bindings for the next
  118. draw- or dispatch-call (0..N vertex buffers, 0 or 1 index buffer, 0..N images,
  119. samplers and storage-buffers), and call
  120. sg_apply_bindings(const sg_bindings* bindings)
  121. ...to update the resource bindings. Note that in a compute pass, no vertex-
  122. or index-buffer bindings are allowed and will be rejected by the validation
  123. layer.
  124. --- optionally update shader uniform data with:
  125. sg_apply_uniforms(int ub_slot, const sg_range* data)
  126. Read the section 'UNIFORM DATA LAYOUT' to learn about the expected memory layout
  127. of the uniform data passed into sg_apply_uniforms().
  128. --- kick off a draw call with:
  129. sg_draw(int base_element, int num_elements, int num_instances)
  130. The sg_draw() function unifies all the different ways to render primitives
  131. in a single call (indexed vs non-indexed rendering, and instanced vs non-instanced
  132. rendering). In case of indexed rendering, base_element and num_element specify
  133. indices in the currently bound index buffer. In case of non-indexed rendering
  134. base_element and num_elements specify vertices in the currently bound
  135. vertex-buffer(s). To perform instanced rendering, the rendering pipeline
  136. must be setup for instancing (see sg_pipeline_desc below), a separate vertex buffer
  137. containing per-instance data must be bound, and the num_instances parameter
  138. must be > 1.
  139. --- ...or kick of a dispatch call to invoke a compute shader workload:
  140. sg_dispatch(int num_groups_x, int num_groups_y, int num_groups_z)
  141. The dispatch args define the number of 'compute workgroups' processed
  142. by the currently applied compute shader.
  143. --- finish the current pass with:
  144. sg_end_pass()
  145. --- when done with the current frame, call
  146. sg_commit()
  147. --- at the end of your program, shutdown sokol_gfx with:
  148. sg_shutdown()
  149. --- if you need to destroy resources before sg_shutdown(), call:
  150. sg_destroy_buffer(sg_buffer buf)
  151. sg_destroy_image(sg_image img)
  152. sg_destroy_sampler(sg_sampler smp)
  153. sg_destroy_shader(sg_shader shd)
  154. sg_destroy_pipeline(sg_pipeline pip)
  155. sg_destroy_attachments(sg_attachments atts)
  156. --- to set a new viewport rectangle, call:
  157. sg_apply_viewport(int x, int y, int width, int height, bool origin_top_left)
  158. ...or if you want to specify the viewport rectangle with float values:
  159. sg_apply_viewportf(float x, float y, float width, float height, bool origin_top_left)
  160. --- to set a new scissor rect, call:
  161. sg_apply_scissor_rect(int x, int y, int width, int height, bool origin_top_left)
  162. ...or with float values:
  163. sg_apply_scissor_rectf(float x, float y, float width, float height, bool origin_top_left)
  164. Both sg_apply_viewport() and sg_apply_scissor_rect() must be called
  165. inside a rendering pass (e.g. not in a compute pass, or outside a pass)
  166. Note that sg_begin_default_pass() and sg_begin_pass() will reset both the
  167. viewport and scissor rectangles to cover the entire framebuffer.
  168. --- to update (overwrite) the content of buffer and image resources, call:
  169. sg_update_buffer(sg_buffer buf, const sg_range* data)
  170. sg_update_image(sg_image img, const sg_image_data* data)
  171. Buffers and images to be updated must have been created with
  172. sg_buffer_desc.usage.dynamic_update or .stream_update.
  173. Only one update per frame is allowed for buffer and image resources when
  174. using the sg_update_*() functions. The rationale is to have a simple
  175. protection from the CPU scribbling over data the GPU is currently
  176. using, or the CPU having to wait for the GPU
  177. Buffer and image updates can be partial, as long as a rendering
  178. operation only references the valid (updated) data in the
  179. buffer or image.
  180. --- to append a chunk of data to a buffer resource, call:
  181. int sg_append_buffer(sg_buffer buf, const sg_range* data)
  182. The difference to sg_update_buffer() is that sg_append_buffer()
  183. can be called multiple times per frame to append new data to the
  184. buffer piece by piece, optionally interleaved with draw calls referencing
  185. the previously written data.
  186. sg_append_buffer() returns a byte offset to the start of the
  187. written data, this offset can be assigned to
  188. sg_bindings.vertex_buffer_offsets[n] or
  189. sg_bindings.index_buffer_offset
  190. Code example:
  191. for (...) {
  192. const void* data = ...;
  193. const int num_bytes = ...;
  194. int offset = sg_append_buffer(buf, &(sg_range) { .ptr=data, .size=num_bytes });
  195. bindings.vertex_buffer_offsets[0] = offset;
  196. sg_apply_pipeline(pip);
  197. sg_apply_bindings(&bindings);
  198. sg_apply_uniforms(...);
  199. sg_draw(...);
  200. }
  201. A buffer to be used with sg_append_buffer() must have been created
  202. with sg_buffer_desc.usage.dynamic_update or .stream_update.
  203. If the application appends more data to the buffer then fits into
  204. the buffer, the buffer will go into the "overflow" state for the
  205. rest of the frame.
  206. Any draw calls attempting to render an overflown buffer will be
  207. silently dropped (in debug mode this will also result in a
  208. validation error).
  209. You can also check manually if a buffer is in overflow-state by calling
  210. bool sg_query_buffer_overflow(sg_buffer buf)
  211. You can manually check to see if an overflow would occur before adding
  212. any data to a buffer by calling
  213. bool sg_query_buffer_will_overflow(sg_buffer buf, size_t size)
  214. NOTE: Due to restrictions in underlying 3D-APIs, appended chunks of
  215. data will be 4-byte aligned in the destination buffer. This means
  216. that there will be gaps in index buffers containing 16-bit indices
  217. when the number of indices in a call to sg_append_buffer() is
  218. odd. This isn't a problem when each call to sg_append_buffer()
  219. is associated with one draw call, but will be problematic when
  220. a single indexed draw call spans several appended chunks of indices.
  221. --- to check at runtime for optional features, limits and pixelformat support,
  222. call:
  223. sg_features sg_query_features()
  224. sg_limits sg_query_limits()
  225. sg_pixelformat_info sg_query_pixelformat(sg_pixel_format fmt)
  226. --- if you need to call into the underlying 3D-API directly, you must call:
  227. sg_reset_state_cache()
  228. ...before calling sokol_gfx functions again
  229. --- you can inspect the original sg_desc structure handed to sg_setup()
  230. by calling sg_query_desc(). This will return an sg_desc struct with
  231. the default values patched in instead of any zero-initialized values
  232. --- you can get a desc struct matching the creation attributes of a
  233. specific resource object via:
  234. sg_buffer_desc sg_query_buffer_desc(sg_buffer buf)
  235. sg_image_desc sg_query_image_desc(sg_image img)
  236. sg_sampler_desc sg_query_sampler_desc(sg_sampler smp)
  237. sg_shader_desc sq_query_shader_desc(sg_shader shd)
  238. sg_pipeline_desc sg_query_pipeline_desc(sg_pipeline pip)
  239. sg_attachments_desc sg_query_attachments_desc(sg_attachments atts)
  240. ...but NOTE that the returned desc structs may be incomplete, only
  241. creation attributes that are kept around internally after resource
  242. creation will be filled in, and in some cases (like shaders) that's
  243. very little. Any missing attributes will be set to zero. The returned
  244. desc structs might still be useful as partial blueprint for creating
  245. similar resources if filled up with the missing attributes.
  246. Calling the query-desc functions on an invalid resource will return
  247. completely zeroed structs (it makes sense to check the resource state
  248. with sg_query_*_state() first)
  249. --- you can query the default resource creation parameters through the functions
  250. sg_buffer_desc sg_query_buffer_defaults(const sg_buffer_desc* desc)
  251. sg_image_desc sg_query_image_defaults(const sg_image_desc* desc)
  252. sg_sampler_desc sg_query_sampler_defaults(const sg_sampler_desc* desc)
  253. sg_shader_desc sg_query_shader_defaults(const sg_shader_desc* desc)
  254. sg_pipeline_desc sg_query_pipeline_defaults(const sg_pipeline_desc* desc)
  255. sg_attachments_desc sg_query_attachments_defaults(const sg_attachments_desc* desc)
  256. These functions take a pointer to a desc structure which may contain
  257. zero-initialized items for default values. These zero-init values
  258. will be replaced with their concrete values in the returned desc
  259. struct.
  260. --- you can inspect various internal resource runtime values via:
  261. sg_buffer_info sg_query_buffer_info(sg_buffer buf)
  262. sg_image_info sg_query_image_info(sg_image img)
  263. sg_sampler_info sg_query_sampler_info(sg_sampler smp)
  264. sg_shader_info sg_query_shader_info(sg_shader shd)
  265. sg_pipeline_info sg_query_pipeline_info(sg_pipeline pip)
  266. sg_attachments_info sg_query_attachments_info(sg_attachments atts)
  267. ...please note that the returned info-structs are tied quite closely
  268. to sokol_gfx.h internals, and may change more often than other
  269. public API functions and structs.
  270. --- you can query frame stats and control stats collection via:
  271. sg_query_frame_stats()
  272. sg_enable_frame_stats()
  273. sg_disable_frame_stats()
  274. sg_frame_stats_enabled()
  275. --- you can ask at runtime what backend sokol_gfx.h has been compiled for:
  276. sg_backend sg_query_backend(void)
  277. --- call the following helper functions to compute the number of
  278. bytes in a texture row or surface for a specific pixel format.
  279. These functions might be helpful when preparing image data for consumption
  280. by sg_make_image() or sg_update_image():
  281. int sg_query_row_pitch(sg_pixel_format fmt, int width, int int row_align_bytes);
  282. int sg_query_surface_pitch(sg_pixel_format fmt, int width, int height, int row_align_bytes);
  283. Width and height are generally in number pixels, but note that 'row' has different meaning
  284. for uncompressed vs compressed pixel formats: for uncompressed formats, a row is identical
  285. with a single line if pixels, while in compressed formats, one row is a line of *compression blocks*.
  286. This is why calling sg_query_surface_pitch() for a compressed pixel format and height
  287. N, N+1, N+2, ... may return the same result.
  288. The row_align_bytes parameter is for added flexibility. For image data that goes into
  289. the sg_make_image() or sg_update_image() this should generally be 1, because these
  290. functions take tightly packed image data as input no matter what alignment restrictions
  291. exist in the backend 3D APIs.
  292. ON INITIALIZATION:
  293. ==================
  294. When calling sg_setup(), a pointer to an sg_desc struct must be provided
  295. which contains initialization options. These options provide two types
  296. of information to sokol-gfx:
  297. (1) upper bounds and limits needed to allocate various internal
  298. data structures:
  299. - the max number of resources of each type that can
  300. be alive at the same time, this is used for allocating
  301. internal pools
  302. - the max overall size of uniform data that can be
  303. updated per frame, including a worst-case alignment
  304. per uniform update (this worst-case alignment is 256 bytes)
  305. - the max size of all dynamic resource updates (sg_update_buffer,
  306. sg_append_buffer and sg_update_image) per frame
  307. - the max number of compute-dispatch calls in a compute pass
  308. Not all of those limit values are used by all backends, but it is
  309. good practice to provide them none-the-less.
  310. (2) 3D backend "environment information" in a nested sg_environment struct:
  311. - pointers to backend-specific context- or device-objects (for instance
  312. the D3D11, WebGPU or Metal device objects)
  313. - defaults for external swapchain pixel formats and sample counts,
  314. these will be used as default values in image and pipeline objects,
  315. and the sg_swapchain struct passed into sg_begin_pass()
  316. Usually you provide a complete sg_environment struct through
  317. a helper function, as an example look at the sglue_environment()
  318. function in the sokol_glue.h header.
  319. See the documentation block of the sg_desc struct below for more information.
  320. ON RENDER PASSES
  321. ================
  322. Relevant samples:
  323. - https://floooh.github.io/sokol-html5/offscreen-sapp.html
  324. - https://floooh.github.io/sokol-html5/offscreen-msaa-sapp.html
  325. - https://floooh.github.io/sokol-html5/mrt-sapp.html
  326. - https://floooh.github.io/sokol-html5/mrt-pixelformats-sapp.html
  327. A render pass groups rendering commands into a set of render target images
  328. (called 'pass attachments'). Render target images can be used in subsequent
  329. passes as textures (it is invalid to use the same image both as render target
  330. and as texture in the same pass).
  331. The following sokol-gfx functions must only be called inside a render-pass:
  332. sg_apply_viewport[f]
  333. sg_apply_scissor_rect[f]
  334. sg_draw
  335. The following function may be called inside a render- or compute-pass, but
  336. not outside a pass:
  337. sg_apply_pipeline
  338. sg_apply_bindings
  339. sg_apply_uniforms
  340. A frame must have at least one 'swapchain render pass' which renders into an
  341. externally provided swapchain provided as an sg_swapchain struct to the
  342. sg_begin_pass() function. If you use sokol_gfx.h together with sokol_app.h,
  343. just call the sglue_swapchain() helper function in sokol_glue.h to
  344. provide the swapchain information. Otherwise the following information
  345. must be provided:
  346. - the color pixel-format of the swapchain's render surface
  347. - an optional depth/stencil pixel format if the swapchain
  348. has a depth/stencil buffer
  349. - an optional sample-count for MSAA rendering
  350. - NOTE: the above three values can be zero-initialized, in that
  351. case the defaults from the sg_environment struct will be used that
  352. had been passed to the sg_setup() function.
  353. - a number of backend specific objects:
  354. - GL/GLES3: just a GL framebuffer handle
  355. - D3D11:
  356. - an ID3D11RenderTargetView for the rendering surface
  357. - if MSAA is used, an ID3D11RenderTargetView as
  358. MSAA resolve-target
  359. - an optional ID3D11DepthStencilView for the
  360. depth/stencil buffer
  361. - WebGPU
  362. - a WGPUTextureView object for the rendering surface
  363. - if MSAA is used, a WGPUTextureView object as MSAA resolve target
  364. - an optional WGPUTextureView for the
  365. - Metal (NOTE that the roles of provided surfaces is slightly
  366. different in Metal than in D3D11 or WebGPU, notably, the
  367. CAMetalDrawable is either rendered to directly, or serves
  368. as MSAA resolve target):
  369. - a CAMetalDrawable object which is either rendered
  370. into directly, or in case of MSAA rendering, serves
  371. as MSAA-resolve-target
  372. - if MSAA is used, an multisampled MTLTexture where
  373. rendering goes into
  374. - an optional MTLTexture for the depth/stencil buffer
  375. It's recommended that you create a helper function which returns an
  376. initialized sg_swapchain struct by value. This can then be directly plugged
  377. into the sg_begin_pass function like this:
  378. sg_begin_pass(&(sg_pass){ .swapchain = sglue_swapchain() });
  379. As an example for such a helper function check out the function sglue_swapchain()
  380. in the sokol_glue.h header.
  381. For offscreen render passes, the render target images used in a render pass
  382. are baked into an immutable sg_attachments object.
  383. For a simple offscreen scenario with one color-, one depth-stencil-render
  384. target and without multisampling, creating an attachment object looks like this:
  385. First create two render target images, one with a color pixel format,
  386. and one with the depth- or depth-stencil pixel format. Both images
  387. must have the same dimensions:
  388. const sg_image color_img = sg_make_image(&(sg_image_desc){
  389. .render_target = true,
  390. .width = 256,
  391. .height = 256,
  392. .pixel_format = SG_PIXELFORMAT_RGBA8,
  393. .sample_count = 1,
  394. });
  395. const sg_image depth_img = sg_make_image(&(sg_image_desc){
  396. .render_target = true,
  397. .width = 256,
  398. .height = 256,
  399. .pixel_format = SG_PIXELFORMAT_DEPTH,
  400. .sample_count = 1,
  401. });
  402. NOTE: when creating render target images, have in mind that some default values
  403. are aligned with the default environment attributes in the sg_environment struct
  404. that was passed into the sg_setup() call:
  405. - the default value for sg_image_desc.pixel_format is taken from
  406. sg_environment.defaults.color_format
  407. - the default value for sg_image_desc.sample_count is taken from
  408. sg_environment.defaults.sample_count
  409. - the default value for sg_image_desc.num_mipmaps is always 1
  410. Next create an attachments object:
  411. const sg_attachments atts = sg_make_attachments(&(sg_attachments_desc){
  412. .colors[0].image = color_img,
  413. .depth_stencil.image = depth_img,
  414. });
  415. This attachments object is then passed into the sg_begin_pass() function
  416. in place of the swapchain struct:
  417. sg_begin_pass(&(sg_pass){ .attachments = atts });
  418. Swapchain and offscreen passes form dependency trees each with a swapchain
  419. pass at the root, offscreen passes as nodes, and render target images as
  420. dependencies between passes.
  421. sg_pass_action structs are used to define actions that should happen at the
  422. start and end of rendering passes (such as clearing pass attachments to a
  423. specific color or depth-value, or performing an MSAA resolve operation at
  424. the end of a pass).
  425. A typical sg_pass_action object which clears the color attachment to black
  426. might look like this:
  427. const sg_pass_action = {
  428. .colors[0] = {
  429. .load_action = SG_LOADACTION_CLEAR,
  430. .clear_value = { 0.0f, 0.0f, 0.0f, 1.0f }
  431. }
  432. };
  433. This omits the defaults for the color attachment store action, and
  434. the depth-stencil-attachments actions. The same pass action with the
  435. defaults explicitly filled in would look like this:
  436. const sg_pass_action pass_action = {
  437. .colors[0] = {
  438. .load_action = SG_LOADACTION_CLEAR,
  439. .store_action = SG_STOREACTION_STORE,
  440. .clear_value = { 0.0f, 0.0f, 0.0f, 1.0f }
  441. },
  442. .depth = = {
  443. .load_action = SG_LOADACTION_CLEAR,
  444. .store_action = SG_STOREACTION_DONTCARE,
  445. .clear_value = 1.0f,
  446. },
  447. .stencil = {
  448. .load_action = SG_LOADACTION_CLEAR,
  449. .store_action = SG_STOREACTION_DONTCARE,
  450. .clear_value = 0
  451. }
  452. };
  453. With the sg_pass object and sg_pass_action struct in place everything
  454. is ready now for the actual render pass:
  455. Using such this prepared sg_pass_action in a swapchain pass looks like
  456. this:
  457. sg_begin_pass(&(sg_pass){
  458. .action = pass_action,
  459. .swapchain = sglue_swapchain()
  460. });
  461. ...
  462. sg_end_pass();
  463. ...of alternatively in one offscreen pass:
  464. sg_begin_pass(&(sg_pass){
  465. .action = pass_action,
  466. .attachments = attachments,
  467. });
  468. ...
  469. sg_end_pass();
  470. Offscreen rendering can also go into a mipmap, or a slice/face of
  471. a cube-, array- or 3d-image (which some restrictions, for instance
  472. it's not possible to create a 3D image with a depth/stencil pixel format,
  473. these exceptions are generally caught by the sokol-gfx validation layer).
  474. The mipmap/slice selection happens at attachments creation time, for instance
  475. to render into mipmap 2 of slice 3 of an array texture:
  476. const sg_attachments atts = sg_make_attachments(&(sg_attachments_desc){
  477. .colors[0] = {
  478. .image = color_img,
  479. .mip_level = 2,
  480. .slice = 3,
  481. },
  482. .depth_stencil.image = depth_img,
  483. });
  484. If MSAA offscreen rendering is desired, the multi-sample rendering result
  485. must be 'resolved' into a separate 'resolve image', before that image can
  486. be used as texture.
  487. Creating a simple attachments object for multisampled rendering requires
  488. 3 attachment images: the color attachment image which has a sample
  489. count > 1, a resolve attachment image of the same size and pixel format
  490. but a sample count == 1, and a depth/stencil attachment image with
  491. the same size and sample count as the color attachment image:
  492. const sg_image color_img = sg_make_image(&(sg_image_desc){
  493. .render_target = true,
  494. .width = 256,
  495. .height = 256,
  496. .pixel_format = SG_PIXELFORMAT_RGBA8,
  497. .sample_count = 4,
  498. });
  499. const sg_image resolve_img = sg_make_image(&(sg_image_desc){
  500. .render_target = true,
  501. .width = 256,
  502. .height = 256,
  503. .pixel_format = SG_PIXELFORMAT_RGBA8,
  504. .sample_count = 1,
  505. });
  506. const sg_image depth_img = sg_make_image(&(sg_image_desc){
  507. .render_target = true,
  508. .width = 256,
  509. .height = 256,
  510. .pixel_format = SG_PIXELFORMAT_DEPTH,
  511. .sample_count = 4,
  512. });
  513. ...create the attachments object:
  514. const sg_attachments atts = sg_make_attachments(&(sg_attachments_desc){
  515. .colors[0].image = color_img,
  516. .resolves[0].image = resolve_img,
  517. .depth_stencil.image = depth_img,
  518. });
  519. If an attachments object defines a resolve image in a specific resolve attachment slot,
  520. an 'msaa resolve operation' will happen in sg_end_pass().
  521. In this scenario, the content of the MSAA color attachment doesn't need to be
  522. preserved (since it's only needed inside sg_end_pass for the msaa-resolve), so
  523. the .store_action should be set to "don't care":
  524. const sg_pass_action = {
  525. .colors[0] = {
  526. .load_action = SG_LOADACTION_CLEAR,
  527. .store_action = SG_STOREACTION_DONTCARE,
  528. .clear_value = { 0.0f, 0.0f, 0.0f, 1.0f }
  529. }
  530. };
  531. The actual render pass looks as usual:
  532. sg_begin_pass(&(sg_pass){ .action = pass_action, .attachments = atts });
  533. ...
  534. sg_end_pass();
  535. ...after sg_end_pass() the only difference to the non-msaa scenario is that the
  536. rendering result which is going to be used as texture in a followup pass is
  537. in 'resolve_img', not in 'color_img' (in fact, trying to bind color_img as a
  538. texture would result in a validation error).
  539. ON COMPUTE PASSES
  540. =================
  541. Compute passes are used to update the content of storage buffers and
  542. storage images by running compute shader code on
  543. the GPU. Updating storage resources with a compute shader will almost always
  544. be more efficient than computing the same data on the CPU and then uploading
  545. it via `sg_update_buffer()` or `sg_update_image()`.
  546. NOTE: compute passes are only supported on the following platforms and
  547. backends:
  548. - macOS and iOS with Metal
  549. - Windows with D3D11 and OpenGL
  550. - Linux with OpenGL or GLES3.1+
  551. - Web with WebGPU
  552. - Android with GLES3.1+
  553. ...this means compute shaders can't be used on the following platform/backend
  554. combos (the same restrictions apply to using storage buffers without compute
  555. shaders):
  556. - macOS with GL
  557. - iOS with GLES3
  558. - Web with WebGL2
  559. A compute pass which only updates storage buffers is started with:
  560. sg_begin_pass(&(sg_pass){ .compute = true });
  561. ...if the compute pass updates storage images, the images must be 'bound'
  562. via an sg_attachments object:
  563. sg_begin_pass(&(sg_pass){ .compute = true, .attachments = attachments });
  564. Image objects in such a compute pass attachments object must be created with
  565. `storage_attachment` usage:
  566. sg_image storage_image = sg_make_image(&(sg_image_desc){
  567. .usage = {
  568. .storage_attachment = true,
  569. },
  570. // ...
  571. });
  572. ...a compute pass is finished with a regular:
  573. sg_end_pass();
  574. Typically the following functions will be called inside a compute pass:
  575. sg_apply_pipeline()
  576. sg_apply_bindings()
  577. sg_apply_uniforms()
  578. sg_dispatch()
  579. The following functions are disallowed inside a compute pass
  580. and will cause validation layer errors:
  581. sg_apply_viewport[f]()
  582. sg_apply_scissor_rect[f]()
  583. sg_draw()
  584. Only special 'compute shaders' and 'compute pipelines' can be used in
  585. compute passes. A compute shader only has a compute-function instead
  586. of a vertex- and fragment-function pair, and it doesn't accept vertex-
  587. and index-buffers as input, only storage-buffers, textures, non-filtering
  588. samplers and images via storage attachments (more details on compute shaders in
  589. the following section).
  590. A compute pipeline is created by providing a compute shader object,
  591. setting the .compute creation parameter to true and not defining any
  592. 'render state':
  593. sg_pipeline pip = sg_make_pipeline(&(sg_pipeline_desc){
  594. .compute = true,
  595. .shader = compute_shader,
  596. });
  597. The sg_apply_bindings and sg_apply_uniforms calls are the same as in
  598. render passes, with the exception that no vertex- and index-buffers
  599. can be bound in the sg_apply_bindings call.
  600. Finally to kick off a compute workload, call sg_dispatch with the
  601. number of workgroups in the x, y and z-dimension:
  602. sg_dispatch(int num_groups_x, int num_groups_y, int num_groups_z)
  603. Also see the following compute-shader samples:
  604. - https://floooh.github.io/sokol-webgpu/instancing-compute-sapp.html
  605. - https://floooh.github.io/sokol-webgpu/computeboids-sapp.html
  606. - https://floooh.github.io/sokol-webgpu/imageblur-sapp.html
  607. ON SHADER CREATION
  608. ==================
  609. sokol-gfx doesn't come with an integrated shader cross-compiler, instead
  610. backend-specific shader sources or binary blobs need to be provided when
  611. creating a shader object, along with reflection information about the
  612. shader resource binding interface needed to bind sokol-gfx resources to the
  613. proper shader inputs.
  614. The easiest way to provide all this shader creation data is to use the
  615. sokol-shdc shader compiler tool to compile shaders from a common
  616. GLSL syntax into backend-specific sources or binary blobs, along with
  617. shader interface information and uniform blocks and storage buffer array items
  618. mapped to C structs.
  619. To create a shader using a C header which has been code-generated by sokol-shdc:
  620. // include the C header code-generated by sokol-shdc:
  621. #include "myshader.glsl.h"
  622. ...
  623. // create shader using a code-generated helper function from the C header:
  624. sg_shader shd = sg_make_shader(myshader_shader_desc(sg_query_backend()));
  625. The samples in the 'sapp' subdirectory of the sokol-samples project
  626. also use the sokol-shdc approach:
  627. https://github.com/floooh/sokol-samples/tree/master/sapp
  628. If you're planning to use sokol-shdc, you can stop reading here, instead
  629. continue with the sokol-shdc documentation:
  630. https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md
  631. To create shaders with backend-specific shader code or binary blobs,
  632. the sg_make_shader() function requires the following information:
  633. - Shader code or shader binary blobs for the vertex- and fragment-, or the
  634. compute-shader-stage:
  635. - for the desktop GL backend, source code can be provided in '#version 410' or
  636. '#version 430', version 430 is required when using storage buffers and
  637. compute shaders support, but note that this is not available on macOS
  638. - for the GLES3 backend, source code must be provided in '#version 300 es' or
  639. '#version 310 es' syntax (version 310 is required for storage buffer and
  640. compute shader support, but note that this is not supported on WebGL2)
  641. - for the D3D11 backend, shaders can be provided as source or binary
  642. blobs, the source code should be in HLSL4.0 (for compatibility with old
  643. low-end GPUs) or preferably in HLSL5.0 syntax, note that when
  644. shader source code is provided for the D3D11 backend, sokol-gfx will
  645. dynamically load 'd3dcompiler_47.dll'
  646. - for the Metal backends, shaders can be provided as source or binary blobs, the
  647. MSL version should be in 'metal-1.1' (other versions may work but are not tested)
  648. - for the WebGPU backend, shaders must be provided as WGSL source code
  649. - optionally the following shader-code related attributes can be provided:
  650. - an entry function name (only on D3D11 or Metal, but not OpenGL)
  651. - on D3D11 only, a compilation target (default is "vs_4_0" and "ps_4_0")
  652. - Information about the input vertex attributes used by the vertex shader,
  653. most of that backend-specific:
  654. - An optional 'base type' (float, signed-/unsigned-int) for each vertex
  655. attribute. When provided, this used by the validation layer to check
  656. that the CPU-side input vertex format is compatible with the input
  657. vertex declaration of the vertex shader.
  658. - Metal: no location information needed since vertex attributes are always bound
  659. by their attribute location defined in the shader via '[[attribute(N)]]'
  660. - WebGPU: no location information needed since vertex attributes are always
  661. bound by their attribute location defined in the shader via `@location(N)`
  662. - GLSL: vertex attribute names can be optionally provided, in that case their
  663. location will be looked up by name, otherwise, the vertex attribute location
  664. can be defined with 'layout(location = N)'
  665. - D3D11: a 'semantic name' and 'semantic index' must be provided for each vertex
  666. attribute, e.g. if the vertex attribute is defined as 'TEXCOORD1' in the shader,
  667. the semantic name would be 'TEXCOORD', and the semantic index would be '1'
  668. NOTE that vertex attributes currently must not have gaps. This requirement
  669. may be relaxed in the future.
  670. - Specifically for Metal compute shaders, the 'number of threads per threadgroup'
  671. must be provided. Normally this is extracted by sokol-shdc from the GLSL
  672. shader source code. For instance the following statement in the input
  673. GLSL:
  674. layout(local_size_x=64, local_size_y=1, local_size_z=1) in;
  675. ...will be communicated to the sokol-gfx Metal backend in the
  676. code-generated sg_shader_desc struct:
  677. (sg_shader_desc){
  678. .mtl_threads_per_threadgroup = { .x = 64, .y = 1, .z = 1 },
  679. }
  680. - Information about each uniform block binding used in the shader:
  681. - the shader stage of the uniform block (vertex, fragment or compute)
  682. - the size of the uniform block in number of bytes
  683. - a memory layout hint (currently 'native' or 'std140') where 'native' defines a
  684. backend-specific memory layout which shouldn't be used for cross-platform code.
  685. Only std140 guarantees a backend-agnostic memory layout.
  686. - a backend-specific bind slot:
  687. - D3D11/HLSL: the buffer register N (`register(bN)`) where N is 0..7
  688. - Metal/MSL: the buffer bind slot N (`[[buffer(N)]]`) where N is 0..7
  689. - WebGPU: the binding N in `@group(0) @binding(N)` where N is 0..15
  690. - For GLSL only: a description of the internal uniform block layout, which maps
  691. member types and their offsets on the CPU side to uniform variable names
  692. in the GLSL shader
  693. - please also NOTE the documentation sections about UNIFORM DATA LAYOUT
  694. and CROSS-BACKEND COMMON UNIFORM DATA LAYOUT below!
  695. - A description of each storage buffer binding used in the shader:
  696. - the shader stage of the storage buffer
  697. - a boolean 'readonly' flag, this is used for validation and hazard
  698. tracking in some 3D backends. Note that in render passes, only
  699. readonly storage buffer bindings are allowed. In compute passes, any
  700. read/write storage buffer binding is assumed to be written to by the
  701. compute shader.
  702. - a backend-specific bind slot:
  703. - D3D11/HLSL:
  704. - for readonly storage buffer bindings: the texture register N
  705. (`register(tN)`) where N is 0..23 (in HLSL, readonly storage
  706. buffers and textures share the same bind space for
  707. 'shader resource views')
  708. - for read/write storage buffer buffer bindings: the UAV register N
  709. (`register(uN)`) where N is 0..11 (in HLSL, readwrite storage
  710. buffers use their own bind space for 'unordered access views')
  711. - Metal/MSL: the buffer bind slot N (`[[buffer(N)]]`) where N is 8..15
  712. - WebGPU/WGSL: the binding N in `@group(0) @binding(N)` where N is 0..127
  713. - GL/GLSL: the buffer binding N in `layout(binding=N)` where N is 0..7
  714. - note that storage buffer bindings are not supported on all backends
  715. and platforms
  716. - A description of each storage image binding used in the shader (only supported
  717. in compute shaders):
  718. - the shader stage (*must* be compute)
  719. - the expected image type:
  720. - SG_IMAGETYPE_2D
  721. - SG_IMAGETYPE_CUBE
  722. - SG_IMAGETYPE_3D
  723. - SG_IMAGETYPE_ARRAY
  724. - the 'access pixel format', this is currently limited to:
  725. - SG_PIXELFORMAT_RGBA8
  726. - SG_PIXELFORMAT_RGBA8SN/UI/SI
  727. - SG_PIXELFORMAT_RGBA16UI/SI/F
  728. - SG_PIXELFORMAT_R32UIUI/SI/F
  729. - SG_PIXELFORMAT_RG32UI/SI/F
  730. - SG_PIXELFORMAT_RGBA32UI/SI/F
  731. - the access type (readwrite or writeonly)
  732. - a backend-specific bind slot:
  733. - D3D11/HLSL: the UAV register N (`register(uN)` where N is 0..11, the
  734. bind slot must not collide with UAV storage buffer bindings
  735. - Metal/MSL: the texture bind slot N (`[[texture(N)]])` where N is 0..19,
  736. the bind slot must not collide with other texture bindings on the same
  737. stage
  738. - WebGPU/WGSL: the binding N in `@group(2) @binding(N)` where N is 0..3
  739. - GL/GLSL: the buffer binding N in `layout(binding=N)` where N is 0..3
  740. - note that storage image bindings are not supported on all backends and platforms
  741. - A description of each texture binding used in the shader:
  742. - the shader stage of the texture (vertex, fragment or compute)
  743. - the expected image type:
  744. - SG_IMAGETYPE_2D
  745. - SG_IMAGETYPE_CUBE
  746. - SG_IMAGETYPE_3D
  747. - SG_IMAGETYPE_ARRAY
  748. - the expected 'image sample type':
  749. - SG_IMAGESAMPLETYPE_FLOAT
  750. - SG_IMAGESAMPLETYPE_DEPTH
  751. - SG_IMAGESAMPLETYPE_SINT
  752. - SG_IMAGESAMPLETYPE_UINT
  753. - SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT
  754. - a flag whether the texture is expected to be multisampled
  755. - a backend-specific bind slot:
  756. - D3D11/HLSL: the texture register N (`register(tN)`) where N is 0..23
  757. (in HLSL, readonly storage buffers and texture share the same bind space)
  758. - Metal/MSL: the texture bind slot N (`[[texture(N)]]`) where N is 0..19
  759. (the bind slot must not collide with storage image bindings on the same stage)
  760. - WebGPU/WGSL: the binding N in `@group(0) @binding(N)` where N is 0..127
  761. - A description of each sampler used in the shader:
  762. - the shader stage of the sampler (vertex, fragment or compute)
  763. - the expected sampler type:
  764. - SG_SAMPLERTYPE_FILTERING,
  765. - SG_SAMPLERTYPE_NONFILTERING,
  766. - SG_SAMPLERTYPE_COMPARISON,
  767. - a backend-specific bind slot:
  768. - D3D11/HLSL: the sampler register N (`register(sN)`) where N is 0..15
  769. - Metal/MSL: the sampler bind slot N (`[[sampler(N)]]`) where N is 0..15
  770. - WebGPU/WGSL: the binding N in `@group(0) @binding(N)` where N is 0..127
  771. - An array of 'image-sampler-pairs' used by the shader to sample textures,
  772. for D3D11, Metal and WebGPU this is used for validation purposes to check
  773. whether the texture and sampler are compatible with each other (especially
  774. WebGPU is very picky about combining the correct
  775. texture-sample-type with the correct sampler-type). For GLSL an
  776. additional 'combined-image-sampler name' must be provided because 'OpenGL
  777. style GLSL' cannot handle separate texture and sampler objects, but still
  778. groups them into a traditional GLSL 'sampler object'.
  779. Compatibility rules for image-sample-type vs sampler-type are as follows:
  780. - SG_IMAGESAMPLETYPE_FLOAT => (SG_SAMPLERTYPE_FILTERING or SG_SAMPLERTYPE_NONFILTERING)
  781. - SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT => SG_SAMPLERTYPE_NONFILTERING
  782. - SG_IMAGESAMPLETYPE_SINT => SG_SAMPLERTYPE_NONFILTERING
  783. - SG_IMAGESAMPLETYPE_UINT => SG_SAMPLERTYPE_NONFILTERING
  784. - SG_IMAGESAMPLETYPE_DEPTH => SG_SAMPLERTYPE_COMPARISON
  785. Backend-specific bindslot ranges (not relevant when using sokol-shdc):
  786. - D3D11/HLSL:
  787. - separate bindslot space per shader stage
  788. - uniform block bindings (as cbuffer): `register(b0..b7)`
  789. - texture- and readonly storage buffer bindings: `register(t0..t23)`
  790. - read/write storage buffer and storage image bindings: `register(u0..u11)`
  791. - samplers: `register(s0..s15)`
  792. - Metal/MSL:
  793. - separate bindslot space per shader stage
  794. - uniform blocks: `[[buffer(0..7)]]`
  795. - storage buffers: `[[buffer(8..15)]]`
  796. - textures and storage image bindings: `[[texture(0..19)]]`
  797. - samplers: `[[sampler(0..15)]]`
  798. - WebGPU/WGSL:
  799. - common bindslot space across shader stages
  800. - uniform blocks: `@group(0) @binding(0..15)`
  801. - textures, samplers and storage buffers: `@group(1) @binding(0..127)`
  802. - storage image bindings: `@group(2) @binding(0..3)`
  803. - GL/GLSL:
  804. - uniforms and image-samplers are bound by name
  805. - storage buffer bindings: `layout(std430, binding=0..7)` (common
  806. bindslot space across shader stages)
  807. - storage image bindings: `layout(binding=0..3, [access_format])`
  808. For example code of how to create backend-specific shader objects,
  809. please refer to the following samples:
  810. - for D3D11: https://github.com/floooh/sokol-samples/tree/master/d3d11
  811. - for Metal: https://github.com/floooh/sokol-samples/tree/master/metal
  812. - for OpenGL: https://github.com/floooh/sokol-samples/tree/master/glfw
  813. - for GLES3: https://github.com/floooh/sokol-samples/tree/master/html5
  814. - for WebGPU: https://github.com/floooh/sokol-samples/tree/master/wgpu
  815. ON SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT AND SG_SAMPLERTYPE_NONFILTERING
  816. ========================================================================
  817. The WebGPU backend introduces the concept of 'unfilterable-float' textures,
  818. which can only be combined with 'nonfiltering' samplers (this is a restriction
  819. specific to WebGPU, but since the same sokol-gfx code should work across
  820. all backend, the sokol-gfx validation layer also enforces this restriction
  821. - the alternative would be undefined behaviour in some backend APIs on
  822. some devices).
  823. The background is that some mobile devices (most notably iOS devices) can
  824. not perform linear filtering when sampling textures with certain pixel
  825. formats, most notable the 32F formats:
  826. - SG_PIXELFORMAT_R32F
  827. - SG_PIXELFORMAT_RG32F
  828. - SG_PIXELFORMAT_RGBA32F
  829. The information of whether a shader is going to be used with such an
  830. unfilterable-float texture must already be provided in the sg_shader_desc
  831. struct when creating the shader (see the above section "ON SHADER CREATION").
  832. If you are using the sokol-shdc shader compiler, the information whether a
  833. texture/sampler binding expects an 'unfilterable-float/nonfiltering'
  834. texture/sampler combination cannot be inferred from the shader source
  835. alone, you'll need to provide this hint via annotation-tags. For instance
  836. here is an example from the ozz-skin-sapp.c sample shader which samples an
  837. RGBA32F texture with skinning matrices in the vertex shader:
  838. ```glsl
  839. @image_sample_type joint_tex unfilterable_float
  840. uniform texture2D joint_tex;
  841. @sampler_type smp nonfiltering
  842. uniform sampler smp;
  843. ```
  844. This will result in SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT and
  845. SG_SAMPLERTYPE_NONFILTERING being written to the code-generated
  846. sg_shader_desc struct.
  847. ON VERTEX FORMATS
  848. =================
  849. Sokol-gfx implements the same strict mapping rules from CPU-side
  850. vertex component formats to GPU-side vertex input data types:
  851. - float and packed normalized CPU-side formats must be used as
  852. floating point base type in the vertex shader
  853. - packed signed-integer CPU-side formats must be used as signed
  854. integer base type in the vertex shader
  855. - packed unsigned-integer CPU-side formats must be used as unsigned
  856. integer base type in the vertex shader
  857. These mapping rules are enforced by the sokol-gfx validation layer,
  858. but only when sufficient reflection information is provided in
  859. `sg_shader_desc.attrs[].base_type`. This is the case when sokol-shdc
  860. is used, otherwise the default base_type will be SG_SHADERATTRBASETYPE_UNDEFINED
  861. which causes the sokol-gfx validation check to be skipped (of course you
  862. can also provide the per-attribute base type information manually when
  863. not using sokol-shdc).
  864. The detailed mapping rules from SG_VERTEXFORMAT_* to GLSL data types
  865. are as follows:
  866. - FLOAT[*] => float, vec*
  867. - BYTE4N => vec* (scaled to -1.0 .. +1.0)
  868. - UBYTE4N => vec* (scaled to 0.0 .. +1.0)
  869. - SHORT[*]N => vec* (scaled to -1.0 .. +1.0)
  870. - USHORT[*]N => vec* (scaled to 0.0 .. +1.0)
  871. - INT[*] => int, ivec*
  872. - UINT[*] => uint, uvec*
  873. - BYTE4 => int*
  874. - UBYTE4 => uint*
  875. - SHORT[*] => int*
  876. - USHORT[*] => uint*
  877. NOTE that sokol-gfx only provides vertex formats with sizes of a multiple
  878. of 4 (e.g. BYTE4N but not BYTE2N). This is because vertex components must
  879. be 4-byte aligned anyway.
  880. UNIFORM DATA LAYOUT:
  881. ====================
  882. NOTE: if you use the sokol-shdc shader compiler tool, you don't need to worry
  883. about the following details.
  884. The data that's passed into the sg_apply_uniforms() function must adhere to
  885. specific layout rules so that the GPU shader finds the uniform block
  886. items at the right offset.
  887. For the D3D11 and Metal backends, sokol-gfx only cares about the size of uniform
  888. blocks, but not about the internal layout. The data will just be copied into
  889. a uniform/constant buffer in a single operation and it's up you to arrange the
  890. CPU-side layout so that it matches the GPU side layout. This also means that with
  891. the D3D11 and Metal backends you are not limited to a 'cross-platform' subset
  892. of uniform variable types.
  893. If you ever only use one of the D3D11, Metal *or* WebGPU backend, you can stop reading here.
  894. For the GL backends, the internal layout of uniform blocks matters though,
  895. and you are limited to a small number of uniform variable types. This is
  896. because sokol-gfx must be able to locate the uniform block members in order
  897. to upload them to the GPU with glUniformXXX() calls.
  898. To describe the uniform block layout to sokol-gfx, the following information
  899. must be passed to the sg_make_shader() call in the sg_shader_desc struct:
  900. - a hint about the used packing rule (either SG_UNIFORMLAYOUT_NATIVE or
  901. SG_UNIFORMLAYOUT_STD140)
  902. - a list of the uniform block members types in the correct order they
  903. appear on the CPU side
  904. For example if the GLSL shader has the following uniform declarations:
  905. uniform mat4 mvp;
  906. uniform vec2 offset0;
  907. uniform vec2 offset1;
  908. uniform vec2 offset2;
  909. ...and on the CPU side, there's a similar C struct:
  910. typedef struct {
  911. float mvp[16];
  912. float offset0[2];
  913. float offset1[2];
  914. float offset2[2];
  915. } params_t;
  916. ...the uniform block description in the sg_shader_desc must look like this:
  917. sg_shader_desc desc = {
  918. .vs.uniform_blocks[0] = {
  919. .size = sizeof(params_t),
  920. .layout = SG_UNIFORMLAYOUT_NATIVE, // this is the default and can be omitted
  921. .uniforms = {
  922. // order must be the same as in 'params_t':
  923. [0] = { .name = "mvp", .type = SG_UNIFORMTYPE_MAT4 },
  924. [1] = { .name = "offset0", .type = SG_UNIFORMTYPE_VEC2 },
  925. [2] = { .name = "offset1", .type = SG_UNIFORMTYPE_VEC2 },
  926. [3] = { .name = "offset2", .type = SG_UNIFORMTYPE_VEC2 },
  927. }
  928. }
  929. };
  930. With this information sokol-gfx can now compute the correct offsets of the data items
  931. within the uniform block struct.
  932. The SG_UNIFORMLAYOUT_NATIVE packing rule works fine if only the GL backends are used,
  933. but for proper D3D11/Metal/GL a subset of the std140 layout must be used which is
  934. described in the next section:
  935. CROSS-BACKEND COMMON UNIFORM DATA LAYOUT
  936. ========================================
  937. For cross-platform / cross-3D-backend code it is important that the same uniform block
  938. layout on the CPU side can be used for all sokol-gfx backends. To achieve this,
  939. a common subset of the std140 layout must be used:
  940. - The uniform block layout hint in sg_shader_desc must be explicitly set to
  941. SG_UNIFORMLAYOUT_STD140.
  942. - Only the following GLSL uniform types can be used (with their associated sokol-gfx enums):
  943. - float => SG_UNIFORMTYPE_FLOAT
  944. - vec2 => SG_UNIFORMTYPE_FLOAT2
  945. - vec3 => SG_UNIFORMTYPE_FLOAT3
  946. - vec4 => SG_UNIFORMTYPE_FLOAT4
  947. - int => SG_UNIFORMTYPE_INT
  948. - ivec2 => SG_UNIFORMTYPE_INT2
  949. - ivec3 => SG_UNIFORMTYPE_INT3
  950. - ivec4 => SG_UNIFORMTYPE_INT4
  951. - mat4 => SG_UNIFORMTYPE_MAT4
  952. - Alignment for those types must be as follows (in bytes):
  953. - float => 4
  954. - vec2 => 8
  955. - vec3 => 16
  956. - vec4 => 16
  957. - int => 4
  958. - ivec2 => 8
  959. - ivec3 => 16
  960. - ivec4 => 16
  961. - mat4 => 16
  962. - Arrays are only allowed for the following types: vec4, int4, mat4.
  963. Note that the HLSL cbuffer layout rules are slightly different from the
  964. std140 layout rules, this means that the cbuffer declarations in HLSL code
  965. must be tweaked so that the layout is compatible with std140.
  966. The by far easiest way to tackle the common uniform block layout problem is
  967. to use the sokol-shdc shader cross-compiler tool!
  968. ON STORAGE BUFFERS
  969. ==================
  970. The two main purpose of storage buffers are:
  971. - to be populated by compute shaders with dynamically generated data
  972. - for providing random-access data to all shader stages
  973. Storage buffers can be used to pass large amounts of random access structured
  974. data from the CPU side to the shaders. They are similar to data textures, but are
  975. more convenient to use both on the CPU and shader side since they can be accessed
  976. in shaders as as a 1-dimensional array of struct items.
  977. Storage buffers are *NOT* supported on the following platform/backend combos:
  978. - macOS+GL (because storage buffers require GL 4.3, while macOS only goes up to GL 4.1)
  979. - platforms which only support a GLES3.0 context (WebGL2 and iOS)
  980. To use storage buffers, the following steps are required:
  981. - write a shader which uses storage buffers (vertex- and fragment-shaders
  982. can only read from storage buffers, while compute-shaders can both read
  983. and write storage buffers)
  984. - create one or more storage buffers via sg_make_buffer() with the
  985. `.usage.storage_buffer = true`
  986. - when creating a shader via sg_make_shader(), populate the sg_shader_desc
  987. struct with binding info (when using sokol-shdc, this step will be taken care
  988. of automatically)
  989. - which storage buffer bind slots on the vertex-, fragment- or compute-stage
  990. are occupied
  991. - whether the storage buffer on that bind slot is readonly (readonly
  992. bindings are required for vertex- and fragment-shaders, and in compute
  993. shaders the readonly flag is used to control hazard tracking in some
  994. 3D backends)
  995. - when calling sg_apply_bindings(), apply the matching bind slots with the previously
  996. created storage buffers
  997. - ...and that's it.
  998. For more details, see the following backend-agnostic sokol samples:
  999. - simple vertex pulling from a storage buffer:
  1000. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/vertexpull-sapp.c
  1001. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/vertexpull-sapp.glsl
  1002. - instanced rendering via storage buffers (vertex- and instance-pulling):
  1003. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/instancing-pull-sapp.c
  1004. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/instancing-pull-sapp.glsl
  1005. - storage buffers both on the vertex- and fragment-stage:
  1006. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/sbuftex-sapp.c
  1007. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/sbuftex-sapp.glsl
  1008. - the Ozz animation sample rewritten to pull all rendering data from storage buffers:
  1009. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/ozz-storagebuffer-sapp.cc
  1010. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/ozz-storagebuffer-sapp.glsl
  1011. - the instancing sample modified to use compute shaders:
  1012. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/instancing-compute-sapp.c
  1013. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/instancing-compute-sapp.glsl
  1014. - the Compute Boids sample ported to sokol-gfx:
  1015. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/computeboids-sapp.c
  1016. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/computeboids-sapp.glsl
  1017. ...also see the following backend-specific vertex pulling samples (those also don't use sokol-shdc):
  1018. - D3D11: https://github.com/floooh/sokol-samples/blob/master/d3d11/vertexpulling-d3d11.c
  1019. - desktop GL: https://github.com/floooh/sokol-samples/blob/master/glfw/vertexpulling-glfw.c
  1020. - Metal: https://github.com/floooh/sokol-samples/blob/master/metal/vertexpulling-metal.c
  1021. - WebGPU: https://github.com/floooh/sokol-samples/blob/master/wgpu/vertexpulling-wgpu.c
  1022. ...and the backend specific compute shader samples:
  1023. - D3D11: https://github.com/floooh/sokol-samples/blob/master/d3d11/instancing-compute-d3d11.c
  1024. - desktop GL: https://github.com/floooh/sokol-samples/blob/master/glfw/instancing-compute-glfw.c
  1025. - Metal: https://github.com/floooh/sokol-samples/blob/master/metal/instancing-compute-metal.c
  1026. - WebGPU: https://github.com/floooh/sokol-samples/blob/master/wgpu/instancing-compute-wgpu.c
  1027. Storage buffer shader authoring caveats when using sokol-shdc:
  1028. - declare a read-only storage buffer interface block with `layout(binding=N) readonly buffer [name] { ... }`
  1029. (where 'N' is the index in `sg_bindings.storage_buffers[N]`)
  1030. - ...or a read/write storage buffer interface block with `layout(binding=N) buffer [name] { ... }`
  1031. - declare a struct which describes a single array item in the storage buffer interface block
  1032. - only put a single flexible array member into the storage buffer interface block
  1033. E.g. a complete example in 'sokol-shdc GLSL':
  1034. ```glsl
  1035. @vs
  1036. // declare a struct:
  1037. struct sb_vertex {
  1038. vec3 pos;
  1039. vec4 color;
  1040. }
  1041. // declare a buffer interface block with a single flexible struct array:
  1042. layout(binding=0) readonly buffer vertices {
  1043. sb_vertex vtx[];
  1044. }
  1045. // in the shader function, access the storage buffer like this:
  1046. void main() {
  1047. vec3 pos = vtx[gl_VertexIndex].pos;
  1048. ...
  1049. }
  1050. @end
  1051. ```
  1052. In a compute shader you can read and write the same item in the same
  1053. storage buffer (but you'll have to be careful for random access since
  1054. many threads of the same compute function run in parallel):
  1055. @cs
  1056. struct sb_item {
  1057. vec3 pos;
  1058. vec3 vel;
  1059. }
  1060. layout(binding=0) buffer items_ssbo {
  1061. sb_item items[];
  1062. }
  1063. layout(local_size_x=64, local_size_y=1, local_size_z=1) in;
  1064. void main() {
  1065. uint idx = gl_GlobalInvocationID.x;
  1066. vec3 pos = items[idx].pos;
  1067. ...
  1068. items[idx].pos = pos;
  1069. }
  1070. @end
  1071. Backend-specific storage-buffer caveats (not relevant when using sokol-shdc):
  1072. D3D11:
  1073. - storage buffers are created as 'raw' Byte Address Buffers
  1074. (https://learn.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-resources-intro#raw-views-of-buffers)
  1075. - in HLSL, use a ByteAddressBuffer for readonly access of the buffer content:
  1076. (https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-byteaddressbuffer)
  1077. - ...or RWByteAddressBuffer for read/write access:
  1078. (https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-rwbyteaddressbuffer)
  1079. - readonly-storage buffers and textures are both bound as 'shader-resource-view' and
  1080. share the same bind slots (declared as `register(tN)` in HLSL), where N must be in the range 0..23)
  1081. - read/write storage buffers and storage images are bound as 'unordered-access-view'
  1082. (declared as `register(uN)` in HLSL where N is in the range 0..11)
  1083. Metal:
  1084. - in Metal there is no internal difference between vertex-, uniform- and
  1085. storage-buffers, all are bound to the same 'buffer bind slots' with the
  1086. following reserved ranges:
  1087. - vertex shader stage:
  1088. - uniform buffers: slots 0..7
  1089. - storage buffers: slots 8..15
  1090. - vertex buffers: slots 15..23
  1091. - fragment shader stage:
  1092. - uniform buffers: slots 0..7
  1093. - storage buffers: slots 8..15
  1094. - this means in MSL, storage buffer bindings start at [[buffer(8)]] both in
  1095. the vertex and fragment stage
  1096. GL:
  1097. - the GL backend doesn't use name-lookup to find storage buffer bindings, this
  1098. means you must annotate buffers with `layout(std430, binding=N)` in GLSL
  1099. - ...where N is 0..7 in the vertex shader, and 8..15 in the fragment shader
  1100. WebGPU:
  1101. - in WGSL, textures, samplers and storage buffers all use a shared
  1102. bindspace across all shader stages on bindgroup 1:
  1103. `@group(1) @binding(0..127)
  1104. ON STORAGE IMAGES:
  1105. ==================
  1106. To write pixel data to texture objects in compute shaders, first an image
  1107. object must be created with `storage_attachment usage`:
  1108. sg_image storage_image = sg_make_image(&(sg_image_desc){
  1109. .usage = {
  1110. .storage_attachment = true,
  1111. },
  1112. .width = ...,
  1113. .height = ...,
  1114. .pixel_format = ...,
  1115. });
  1116. ...next the image object must be wrapped in an attachment object, this allows
  1117. to pick a specific mipmap level or slice to be accessed by the compute shader:
  1118. sg_attachments storage_attachment = sg_make_attachment(&(sg_attachments_desc){
  1119. .storages[0] = {
  1120. .image = storage_image,
  1121. .mip_level = ...,
  1122. .slice = ...,
  1123. },
  1124. });
  1125. Finally 'bind' the storage image as pass attachment in the `sg_begin_pass`
  1126. call of a compute pass:
  1127. sg_begin_pass(&(sg_pass){ .compute = true, .attachments = storage_attachments });
  1128. ...
  1129. sg_end_pass();
  1130. Storage attachments should only be accessed as `readwrite` or `writeonly` mode
  1131. in compute shaders because if the limited bind space of up to 4 slots. For
  1132. readonly access, just bind the storage image as regular texture via
  1133. `sg_apply_bindings()`.
  1134. For an example of using storage images in compute shaders see imageblur-sapp:
  1135. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/imageblur-sapp.c
  1136. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/imageblur-sapp.glsl
  1137. NOTE: in the (hopefully not-too-distant) future, working with storage
  1138. images will change by moving the resource binding from pass attachments to
  1139. regular bindings via `sg_apply_bindings()`, but this requires the
  1140. introduction of resource view objects into sokol-gfx (see planning
  1141. ticket: https://github.com/floooh/sokol/issues/1252)
  1142. TRACE HOOKS:
  1143. ============
  1144. sokol_gfx.h optionally allows to install "trace hook" callbacks for
  1145. each public API functions. When a public API function is called, and
  1146. a trace hook callback has been installed for this function, the
  1147. callback will be invoked with the parameters and result of the function.
  1148. This is useful for things like debugging- and profiling-tools, or
  1149. keeping track of resource creation and destruction.
  1150. To use the trace hook feature:
  1151. --- Define SOKOL_TRACE_HOOKS before including the implementation.
  1152. --- Setup an sg_trace_hooks structure with your callback function
  1153. pointers (keep all function pointers you're not interested
  1154. in zero-initialized), optionally set the user_data member
  1155. in the sg_trace_hooks struct.
  1156. --- Install the trace hooks by calling sg_install_trace_hooks(),
  1157. the return value of this function is another sg_trace_hooks
  1158. struct which contains the previously set of trace hooks.
  1159. You should keep this struct around, and call those previous
  1160. functions pointers from your own trace callbacks for proper
  1161. chaining.
  1162. As an example of how trace hooks are used, have a look at the
  1163. imgui/sokol_gfx_imgui.h header which implements a realtime
  1164. debugging UI for sokol_gfx.h on top of Dear ImGui.
  1165. MEMORY ALLOCATION OVERRIDE
  1166. ==========================
  1167. You can override the memory allocation functions at initialization time
  1168. like this:
  1169. void* my_alloc(size_t size, void* user_data) {
  1170. return malloc(size);
  1171. }
  1172. void my_free(void* ptr, void* user_data) {
  1173. free(ptr);
  1174. }
  1175. ...
  1176. sg_setup(&(sg_desc){
  1177. // ...
  1178. .allocator = {
  1179. .alloc_fn = my_alloc,
  1180. .free_fn = my_free,
  1181. .user_data = ...,
  1182. }
  1183. });
  1184. ...
  1185. If no overrides are provided, malloc and free will be used.
  1186. This only affects memory allocation calls done by sokol_gfx.h
  1187. itself though, not any allocations in OS libraries.
  1188. ERROR REPORTING AND LOGGING
  1189. ===========================
  1190. To get any logging information at all you need to provide a logging callback in the setup call
  1191. the easiest way is to use sokol_log.h:
  1192. #include "sokol_log.h"
  1193. sg_setup(&(sg_desc){ .logger.func = slog_func });
  1194. To override logging with your own callback, first write a logging function like this:
  1195. void my_log(const char* tag, // e.g. 'sg'
  1196. uint32_t log_level, // 0=panic, 1=error, 2=warn, 3=info
  1197. uint32_t log_item_id, // SG_LOGITEM_*
  1198. const char* message_or_null, // a message string, may be nullptr in release mode
  1199. uint32_t line_nr, // line number in sokol_gfx.h
  1200. const char* filename_or_null, // source filename, may be nullptr in release mode
  1201. void* user_data)
  1202. {
  1203. ...
  1204. }
  1205. ...and then setup sokol-gfx like this:
  1206. sg_setup(&(sg_desc){
  1207. .logger = {
  1208. .func = my_log,
  1209. .user_data = my_user_data,
  1210. }
  1211. });
  1212. The provided logging function must be reentrant (e.g. be callable from
  1213. different threads).
  1214. If you don't want to provide your own custom logger it is highly recommended to use
  1215. the standard logger in sokol_log.h instead, otherwise you won't see any warnings or
  1216. errors.
  1217. COMMIT LISTENERS
  1218. ================
  1219. It's possible to hook callback functions into sokol-gfx which are called from
  1220. inside sg_commit() in unspecified order. This is mainly useful for libraries
  1221. that build on top of sokol_gfx.h to be notified about the end/start of a frame.
  1222. To add a commit listener, call:
  1223. static void my_commit_listener(void* user_data) {
  1224. ...
  1225. }
  1226. bool success = sg_add_commit_listener((sg_commit_listener){
  1227. .func = my_commit_listener,
  1228. .user_data = ...,
  1229. });
  1230. The function returns false if the internal array of commit listeners is full,
  1231. or the same commit listener had already been added.
  1232. If the function returns true, my_commit_listener() will be called each frame
  1233. from inside sg_commit().
  1234. By default, 1024 distinct commit listeners can be added, but this number
  1235. can be tweaked in the sg_setup() call:
  1236. sg_setup(&(sg_desc){
  1237. .max_commit_listeners = 2048,
  1238. });
  1239. An sg_commit_listener item is equal to another if both the function
  1240. pointer and user_data field are equal.
  1241. To remove a commit listener:
  1242. bool success = sg_remove_commit_listener((sg_commit_listener){
  1243. .func = my_commit_listener,
  1244. .user_data = ...,
  1245. });
  1246. ...where the .func and .user_data field are equal to a previous
  1247. sg_add_commit_listener() call. The function returns true if the commit
  1248. listener item was found and removed, and false otherwise.
  1249. RESOURCE CREATION AND DESTRUCTION IN DETAIL
  1250. ===========================================
  1251. The 'vanilla' way to create resource objects is with the 'make functions':
  1252. sg_buffer sg_make_buffer(const sg_buffer_desc* desc)
  1253. sg_image sg_make_image(const sg_image_desc* desc)
  1254. sg_sampler sg_make_sampler(const sg_sampler_desc* desc)
  1255. sg_shader sg_make_shader(const sg_shader_desc* desc)
  1256. sg_pipeline sg_make_pipeline(const sg_pipeline_desc* desc)
  1257. sg_attachments sg_make_attachments(const sg_attachments_desc* desc)
  1258. This will result in one of three cases:
  1259. 1. The returned handle is invalid. This happens when there are no more
  1260. free slots in the resource pool for this resource type. An invalid
  1261. handle is associated with the INVALID resource state, for instance:
  1262. sg_buffer buf = sg_make_buffer(...)
  1263. if (sg_query_buffer_state(buf) == SG_RESOURCESTATE_INVALID) {
  1264. // buffer pool is exhausted
  1265. }
  1266. 2. The returned handle is valid, but creating the underlying resource
  1267. has failed for some reason. This results in a resource object in the
  1268. FAILED state. The reason *why* resource creation has failed differ
  1269. by resource type. Look for log messages with more details. A failed
  1270. resource state can be checked with:
  1271. sg_buffer buf = sg_make_buffer(...)
  1272. if (sg_query_buffer_state(buf) == SG_RESOURCESTATE_FAILED) {
  1273. // creating the resource has failed
  1274. }
  1275. 3. And finally, if everything goes right, the returned resource is
  1276. in resource state VALID and ready to use. This can be checked
  1277. with:
  1278. sg_buffer buf = sg_make_buffer(...)
  1279. if (sg_query_buffer_state(buf) == SG_RESOURCESTATE_VALID) {
  1280. // creating the resource has failed
  1281. }
  1282. When calling the 'make functions', the created resource goes through a number
  1283. of states:
  1284. - INITIAL: the resource slot associated with the new resource is currently
  1285. free (technically, there is no resource yet, just an empty pool slot)
  1286. - ALLOC: a handle for the new resource has been allocated, this just means
  1287. a pool slot has been reserved.
  1288. - VALID or FAILED: in VALID state any 3D API backend resource objects have
  1289. been successfully created, otherwise if anything went wrong, the resource
  1290. will be in FAILED state.
  1291. Sometimes it makes sense to first grab a handle, but initialize the
  1292. underlying resource at a later time. For instance when loading data
  1293. asynchronously from a slow data source, you may know what buffers and
  1294. textures are needed at an early stage of the loading process, but actually
  1295. loading the buffer or texture content can only be completed at a later time.
  1296. For such situations, sokol-gfx resource objects can be created in two steps.
  1297. You can allocate a handle upfront with one of the 'alloc functions':
  1298. sg_buffer sg_alloc_buffer(void)
  1299. sg_image sg_alloc_image(void)
  1300. sg_sampler sg_alloc_sampler(void)
  1301. sg_shader sg_alloc_shader(void)
  1302. sg_pipeline sg_alloc_pipeline(void)
  1303. sg_attachments sg_alloc_attachments(void)
  1304. This will return a handle with the underlying resource object in the
  1305. ALLOC state:
  1306. sg_image img = sg_alloc_image();
  1307. if (sg_query_image_state(img) == SG_RESOURCESTATE_ALLOC) {
  1308. // allocating an image handle has succeeded, otherwise
  1309. // the image pool is full
  1310. }
  1311. Such an 'incomplete' handle can be used in most sokol-gfx rendering functions
  1312. without doing any harm, sokol-gfx will simply skip any rendering operation
  1313. that involve resources which are not in VALID state.
  1314. At a later time (for instance once the texture has completed loading
  1315. asynchronously), the resource creation can be completed by calling one of
  1316. the 'init functions', those functions take an existing resource handle and
  1317. 'desc struct':
  1318. void sg_init_buffer(sg_buffer buf, const sg_buffer_desc* desc)
  1319. void sg_init_image(sg_image img, const sg_image_desc* desc)
  1320. void sg_init_sampler(sg_sampler smp, const sg_sampler_desc* desc)
  1321. void sg_init_shader(sg_shader shd, const sg_shader_desc* desc)
  1322. void sg_init_pipeline(sg_pipeline pip, const sg_pipeline_desc* desc)
  1323. void sg_init_attachments(sg_attachments atts, const sg_attachments_desc* desc)
  1324. The init functions expect a resource in ALLOC state, and after the function
  1325. returns, the resource will be either in VALID or FAILED state. Calling
  1326. an 'alloc function' followed by the matching 'init function' is fully
  1327. equivalent with calling the 'make function' alone.
  1328. Destruction can also happen as a two-step process. The 'uninit functions'
  1329. will put a resource object from the VALID or FAILED state back into the
  1330. ALLOC state:
  1331. void sg_uninit_buffer(sg_buffer buf)
  1332. void sg_uninit_image(sg_image img)
  1333. void sg_uninit_sampler(sg_sampler smp)
  1334. void sg_uninit_shader(sg_shader shd)
  1335. void sg_uninit_pipeline(sg_pipeline pip)
  1336. void sg_uninit_attachments(sg_attachments pass)
  1337. Calling the 'uninit functions' with a resource that is not in the VALID or
  1338. FAILED state is a no-op.
  1339. To finally free the pool slot for recycling call the 'dealloc functions':
  1340. void sg_dealloc_buffer(sg_buffer buf)
  1341. void sg_dealloc_image(sg_image img)
  1342. void sg_dealloc_sampler(sg_sampler smp)
  1343. void sg_dealloc_shader(sg_shader shd)
  1344. void sg_dealloc_pipeline(sg_pipeline pip)
  1345. void sg_dealloc_attachments(sg_attachments atts)
  1346. Calling the 'dealloc functions' on a resource that's not in ALLOC state is
  1347. a no-op, but will generate a warning log message.
  1348. Calling an 'uninit function' and 'dealloc function' in sequence is equivalent
  1349. with calling the associated 'destroy function':
  1350. void sg_destroy_buffer(sg_buffer buf)
  1351. void sg_destroy_image(sg_image img)
  1352. void sg_destroy_sampler(sg_sampler smp)
  1353. void sg_destroy_shader(sg_shader shd)
  1354. void sg_destroy_pipeline(sg_pipeline pip)
  1355. void sg_destroy_attachments(sg_attachments atts)
  1356. The 'destroy functions' can be called on resources in any state and generally
  1357. do the right thing (for instance if the resource is in ALLOC state, the destroy
  1358. function will be equivalent to the 'dealloc function' and skip the 'uninit part').
  1359. And finally to close the circle, the 'fail functions' can be called to manually
  1360. put a resource in ALLOC state into the FAILED state:
  1361. sg_fail_buffer(sg_buffer buf)
  1362. sg_fail_image(sg_image img)
  1363. sg_fail_sampler(sg_sampler smp)
  1364. sg_fail_shader(sg_shader shd)
  1365. sg_fail_pipeline(sg_pipeline pip)
  1366. sg_fail_attachments(sg_attachments atts)
  1367. This is recommended if anything went wrong outside of sokol-gfx during asynchronous
  1368. resource setup (for instance a file loading operation failed). In this case,
  1369. the 'fail function' should be called instead of the 'init function'.
  1370. Calling a 'fail function' on a resource that's not in ALLOC state is a no-op,
  1371. but will generate a warning log message.
  1372. NOTE: that two-step resource creation usually only makes sense for buffers
  1373. and images, but not for samplers, shaders, pipelines or attachments. Most notably, trying
  1374. to create a pipeline object with a shader that's not in VALID state will
  1375. trigger a validation layer error, or if the validation layer is disabled,
  1376. result in a pipeline object in FAILED state. Same when trying to create
  1377. an attachments object with invalid image objects.
  1378. WEBGPU CAVEATS
  1379. ==============
  1380. For a general overview and design notes of the WebGPU backend see:
  1381. https://floooh.github.io/2023/10/16/sokol-webgpu.html
  1382. In general, don't expect an automatic speedup when switching from the WebGL2
  1383. backend to the WebGPU backend. Some WebGPU functions currently actually
  1384. have a higher CPU overhead than similar WebGL2 functions, leading to the
  1385. paradoxical situation that some WebGPU code may be slower than similar WebGL2
  1386. code.
  1387. - when writing WGSL shader code by hand, a specific bind-slot convention
  1388. must be used:
  1389. All uniform block structs must use `@group(0)` and bindings in the
  1390. range 0..15
  1391. @group(0) @binding(0..15)
  1392. All textures, samplers and storage buffers must use `@group(1)` and
  1393. bindings must be in the range 0..127:
  1394. @group(1) @binding(0..127)
  1395. All storage image attachments must use `@group(2)` and bindings
  1396. must be in the range 0..3:
  1397. @group(2) @binding(0..3)
  1398. Note that the number of texture, sampler and storage buffer bindings
  1399. is still limited despite the large bind range:
  1400. - up to 16 textures and sampler across all shader stages
  1401. - up to 8 storage buffers across all shader stages
  1402. If you use sokol-shdc to generate WGSL shader code, you don't need to worry
  1403. about the above binding conventions since sokol-shdc.
  1404. - The sokol-gfx WebGPU backend uses the sg_desc.uniform_buffer_size item
  1405. to allocate a single per-frame uniform buffer which must be big enough
  1406. to hold all data written by sg_apply_uniforms() during a single frame,
  1407. including a worst-case 256-byte alignment (e.g. each sg_apply_uniform
  1408. call will cost at least 256 bytes of uniform buffer size). The default size
  1409. is 4 MB, which is enough for 16384 sg_apply_uniform() calls per
  1410. frame (assuming the uniform data 'payload' is less than 256 bytes
  1411. per call). These rules are the same as for the Metal backend, so if
  1412. you are already using the Metal backend you'll be fine.
  1413. - sg_apply_bindings(): the sokol-gfx WebGPU backend implements a bindgroup
  1414. cache to prevent excessive creation and destruction of BindGroup objects
  1415. when calling sg_apply_bindings(). The number of slots in the bindgroups
  1416. cache is defined in sg_desc.wgpu_bindgroups_cache_size when calling
  1417. sg_setup. The cache size must be a power-of-2 number, with the default being
  1418. 1024. The bindgroups cache behaviour can be observed by calling the new
  1419. function sg_query_frame_stats(), where the following struct items are
  1420. of interest:
  1421. .wgpu.num_bindgroup_cache_hits
  1422. .wgpu.num_bindgroup_cache_misses
  1423. .wgpu.num_bindgroup_cache_collisions
  1424. .wgpu_num_bindgroup_cache_invalidates
  1425. .wgpu.num_bindgroup_cache_vs_hash_key_mismatch
  1426. The value to pay attention to is `.wgpu.num_bindgroup_cache_collisions`,
  1427. if this number is consistently higher than a few percent of the
  1428. .wgpu.num_set_bindgroup value, it might be a good idea to bump the
  1429. bindgroups cache size to the next power-of-2.
  1430. - sg_apply_viewport(): WebGPU currently has a unique restriction that viewport
  1431. rectangles must be contained entirely within the framebuffer. As a shitty
  1432. workaround sokol_gfx.h will clip incoming viewport rectangles against
  1433. the framebuffer, but this will distort the clipspace-to-screenspace mapping.
  1434. There's no proper way to handle this inside sokol_gfx.h, this must be fixed
  1435. in a future WebGPU update (see: https://github.com/gpuweb/gpuweb/issues/373
  1436. and https://github.com/gpuweb/gpuweb/pull/5025)
  1437. - The sokol shader compiler generally adds `diagnostic(off, derivative_uniformity);`
  1438. into the WGSL output. Currently only the Chrome WebGPU implementation seems
  1439. to recognize this.
  1440. - Likewise, the following sokol-gfx pixel formats are not supported in WebGPU:
  1441. R16, R16SN, RG16, RG16SN, RGBA16, RGBA16SN.
  1442. Unlike unsupported vertex formats, unsupported pixel formats can be queried
  1443. in cross-backend code via sg_query_pixelformat() though.
  1444. - The Emscripten WebGPU shim currently doesn't support the Closure minification
  1445. post-link-step (e.g. currently the emcc argument '--closure 1' or '--closure 2'
  1446. will generate broken Javascript code.
  1447. - sokol-gfx requires the WebGPU device feature `depth32float-stencil8` to be enabled
  1448. (this should be widely supported)
  1449. - sokol-gfx expects that the WebGPU device feature `float32-filterable` to *not* be
  1450. enabled (since this would exclude all iOS devices)
  1451. LICENSE
  1452. =======
  1453. zlib/libpng license
  1454. Copyright (c) 2018 Andre Weissflog
  1455. This software is provided 'as-is', without any express or implied warranty.
  1456. In no event will the authors be held liable for any damages arising from the
  1457. use of this software.
  1458. Permission is granted to anyone to use this software for any purpose,
  1459. including commercial applications, and to alter it and redistribute it
  1460. freely, subject to the following restrictions:
  1461. 1. The origin of this software must not be misrepresented; you must not
  1462. claim that you wrote the original software. If you use this software in a
  1463. product, an acknowledgment in the product documentation would be
  1464. appreciated but is not required.
  1465. 2. Altered source versions must be plainly marked as such, and must not
  1466. be misrepresented as being the original software.
  1467. 3. This notice may not be removed or altered from any source
  1468. distribution.
  1469. */
  1470. #define SOKOL_GFX_INCLUDED (1)
  1471. #include <stddef.h> // size_t
  1472. #include <stdint.h>
  1473. #include <stdbool.h>
  1474. #if defined(SOKOL_API_DECL) && !defined(SOKOL_GFX_API_DECL)
  1475. #define SOKOL_GFX_API_DECL SOKOL_API_DECL
  1476. #endif
  1477. #ifndef SOKOL_GFX_API_DECL
  1478. #if defined(_WIN32) && defined(SOKOL_DLL) && defined(SOKOL_GFX_IMPL)
  1479. #define SOKOL_GFX_API_DECL __declspec(dllexport)
  1480. #elif defined(_WIN32) && defined(SOKOL_DLL)
  1481. #define SOKOL_GFX_API_DECL __declspec(dllimport)
  1482. #else
  1483. #define SOKOL_GFX_API_DECL extern
  1484. #endif
  1485. #endif
  1486. #ifdef __cplusplus
  1487. extern "C" {
  1488. #endif
  1489. /*
  1490. Resource id typedefs:
  1491. sg_buffer: vertex- and index-buffers
  1492. sg_image: images used as textures and render-pass attachments
  1493. sg_sampler sampler objects describing how a texture is sampled in a shader
  1494. sg_shader: vertex- and fragment-shaders and shader interface information
  1495. sg_pipeline: associated shader and vertex-layouts, and render states
  1496. sg_attachments: a baked collection of render pass attachment images
  1497. Instead of pointers, resource creation functions return a 32-bit
  1498. handle which uniquely identifies the resource object.
  1499. The 32-bit resource id is split into a 16-bit pool index in the lower bits,
  1500. and a 16-bit 'generation counter' in the upper bits. The index allows fast
  1501. pool lookups, and combined with the generation-counter it allows to detect
  1502. 'dangling accesses' (trying to use an object which no longer exists, and
  1503. its pool slot has been reused for a new object)
  1504. The resource ids are wrapped into a strongly-typed struct so that
  1505. trying to pass an incompatible resource id is a compile error.
  1506. */
  1507. typedef struct sg_buffer { uint32_t id; } sg_buffer;
  1508. typedef struct sg_image { uint32_t id; } sg_image;
  1509. typedef struct sg_sampler { uint32_t id; } sg_sampler;
  1510. typedef struct sg_shader { uint32_t id; } sg_shader;
  1511. typedef struct sg_pipeline { uint32_t id; } sg_pipeline;
  1512. typedef struct sg_attachments { uint32_t id; } sg_attachments;
  1513. /*
  1514. sg_range is a pointer-size-pair struct used to pass memory blobs into
  1515. sokol-gfx. When initialized from a value type (array or struct), you can
  1516. use the SG_RANGE() macro to build an sg_range struct. For functions which
  1517. take either a sg_range pointer, or a (C++) sg_range reference, use the
  1518. SG_RANGE_REF macro as a solution which compiles both in C and C++.
  1519. */
  1520. typedef struct sg_range {
  1521. const void* ptr;
  1522. size_t size;
  1523. } sg_range;
  1524. // disabling this for every includer isn't great, but the warnings are also quite pointless
  1525. #if defined(_MSC_VER)
  1526. #pragma warning(disable:4221) // /W4 only: nonstandard extension used: 'x': cannot be initialized using address of automatic variable 'y'
  1527. #pragma warning(disable:4204) // VS2015: nonstandard extension used: non-constant aggregate initializer
  1528. #endif
  1529. #if defined(__cplusplus)
  1530. #define SG_RANGE(x) sg_range{ &x, sizeof(x) }
  1531. #define SG_RANGE_REF(x) sg_range{ &x, sizeof(x) }
  1532. #else
  1533. #define SG_RANGE(x) (sg_range){ &x, sizeof(x) }
  1534. #define SG_RANGE_REF(x) &(sg_range){ &x, sizeof(x) }
  1535. #endif
  1536. // various compile-time constants in the public API
  1537. enum {
  1538. SG_INVALID_ID = 0,
  1539. SG_NUM_INFLIGHT_FRAMES = 2,
  1540. SG_MAX_COLOR_ATTACHMENTS = 4,
  1541. SG_MAX_STORAGE_ATTACHMENTS = 4,
  1542. SG_MAX_UNIFORMBLOCK_MEMBERS = 16,
  1543. SG_MAX_VERTEX_ATTRIBUTES = 16,
  1544. SG_MAX_MIPMAPS = 16,
  1545. SG_MAX_TEXTUREARRAY_LAYERS = 128,
  1546. SG_MAX_UNIFORMBLOCK_BINDSLOTS = 8,
  1547. SG_MAX_VERTEXBUFFER_BINDSLOTS = 8,
  1548. SG_MAX_IMAGE_BINDSLOTS = 16,
  1549. SG_MAX_SAMPLER_BINDSLOTS = 16,
  1550. SG_MAX_STORAGEBUFFER_BINDSLOTS = 8,
  1551. SG_MAX_IMAGE_SAMPLER_PAIRS = 16,
  1552. };
  1553. /*
  1554. sg_color
  1555. An RGBA color value.
  1556. */
  1557. typedef struct sg_color { float r, g, b, a; } sg_color;
  1558. /*
  1559. sg_backend
  1560. The active 3D-API backend, use the function sg_query_backend()
  1561. to get the currently active backend.
  1562. */
  1563. typedef enum sg_backend {
  1564. SG_BACKEND_GLCORE,
  1565. SG_BACKEND_GLES3,
  1566. SG_BACKEND_D3D11,
  1567. SG_BACKEND_METAL_IOS,
  1568. SG_BACKEND_METAL_MACOS,
  1569. SG_BACKEND_METAL_SIMULATOR,
  1570. SG_BACKEND_WGPU,
  1571. SG_BACKEND_DUMMY,
  1572. } sg_backend;
  1573. /*
  1574. sg_pixel_format
  1575. sokol_gfx.h basically uses the same pixel formats as WebGPU, since these
  1576. are supported on most newer GPUs.
  1577. A pixelformat name consist of three parts:
  1578. - components (R, RG, RGB or RGBA)
  1579. - bit width per component (8, 16 or 32)
  1580. - component data type:
  1581. - unsigned normalized (no postfix)
  1582. - signed normalized (SN postfix)
  1583. - unsigned integer (UI postfix)
  1584. - signed integer (SI postfix)
  1585. - float (F postfix)
  1586. Not all pixel formats can be used for everything, call sg_query_pixelformat()
  1587. to inspect the capabilities of a given pixelformat. The function returns
  1588. an sg_pixelformat_info struct with the following members:
  1589. - sample: the pixelformat can be sampled as texture at least with
  1590. nearest filtering
  1591. - filter: the pixelformat can be sampled as texture with linear
  1592. filtering
  1593. - render: the pixelformat can be used as render-pass attachment
  1594. - blend: blending is supported when used as render-pass attachment
  1595. - msaa: multisample-antialiasing is supported when used
  1596. as render-pass attachment
  1597. - depth: the pixelformat can be used for depth-stencil attachments
  1598. - compressed: this is a block-compressed format
  1599. - bytes_per_pixel: the numbers of bytes in a pixel (0 for compressed formats)
  1600. The default pixel format for texture images is SG_PIXELFORMAT_RGBA8.
  1601. The default pixel format for render target images is platform-dependent
  1602. and taken from the sg_environment struct passed into sg_setup(). Typically
  1603. the default formats are:
  1604. - for the Metal, D3D11 and WebGPU backends: SG_PIXELFORMAT_BGRA8
  1605. - for GL backends: SG_PIXELFORMAT_RGBA8
  1606. */
  1607. typedef enum sg_pixel_format {
  1608. _SG_PIXELFORMAT_DEFAULT, // value 0 reserved for default-init
  1609. SG_PIXELFORMAT_NONE,
  1610. SG_PIXELFORMAT_R8,
  1611. SG_PIXELFORMAT_R8SN,
  1612. SG_PIXELFORMAT_R8UI,
  1613. SG_PIXELFORMAT_R8SI,
  1614. SG_PIXELFORMAT_R16,
  1615. SG_PIXELFORMAT_R16SN,
  1616. SG_PIXELFORMAT_R16UI,
  1617. SG_PIXELFORMAT_R16SI,
  1618. SG_PIXELFORMAT_R16F,
  1619. SG_PIXELFORMAT_RG8,
  1620. SG_PIXELFORMAT_RG8SN,
  1621. SG_PIXELFORMAT_RG8UI,
  1622. SG_PIXELFORMAT_RG8SI,
  1623. SG_PIXELFORMAT_R32UI,
  1624. SG_PIXELFORMAT_R32SI,
  1625. SG_PIXELFORMAT_R32F,
  1626. SG_PIXELFORMAT_RG16,
  1627. SG_PIXELFORMAT_RG16SN,
  1628. SG_PIXELFORMAT_RG16UI,
  1629. SG_PIXELFORMAT_RG16SI,
  1630. SG_PIXELFORMAT_RG16F,
  1631. SG_PIXELFORMAT_RGBA8,
  1632. SG_PIXELFORMAT_SRGB8A8,
  1633. SG_PIXELFORMAT_RGBA8SN,
  1634. SG_PIXELFORMAT_RGBA8UI,
  1635. SG_PIXELFORMAT_RGBA8SI,
  1636. SG_PIXELFORMAT_BGRA8,
  1637. SG_PIXELFORMAT_RGB10A2,
  1638. SG_PIXELFORMAT_RG11B10F,
  1639. SG_PIXELFORMAT_RGB9E5,
  1640. SG_PIXELFORMAT_RG32UI,
  1641. SG_PIXELFORMAT_RG32SI,
  1642. SG_PIXELFORMAT_RG32F,
  1643. SG_PIXELFORMAT_RGBA16,
  1644. SG_PIXELFORMAT_RGBA16SN,
  1645. SG_PIXELFORMAT_RGBA16UI,
  1646. SG_PIXELFORMAT_RGBA16SI,
  1647. SG_PIXELFORMAT_RGBA16F,
  1648. SG_PIXELFORMAT_RGBA32UI,
  1649. SG_PIXELFORMAT_RGBA32SI,
  1650. SG_PIXELFORMAT_RGBA32F,
  1651. // NOTE: when adding/removing pixel formats before DEPTH, also update sokol_app.h/_SAPP_PIXELFORMAT_*
  1652. SG_PIXELFORMAT_DEPTH,
  1653. SG_PIXELFORMAT_DEPTH_STENCIL,
  1654. // NOTE: don't put any new compressed format in front of here
  1655. SG_PIXELFORMAT_BC1_RGBA,
  1656. SG_PIXELFORMAT_BC2_RGBA,
  1657. SG_PIXELFORMAT_BC3_RGBA,
  1658. SG_PIXELFORMAT_BC3_SRGBA,
  1659. SG_PIXELFORMAT_BC4_R,
  1660. SG_PIXELFORMAT_BC4_RSN,
  1661. SG_PIXELFORMAT_BC5_RG,
  1662. SG_PIXELFORMAT_BC5_RGSN,
  1663. SG_PIXELFORMAT_BC6H_RGBF,
  1664. SG_PIXELFORMAT_BC6H_RGBUF,
  1665. SG_PIXELFORMAT_BC7_RGBA,
  1666. SG_PIXELFORMAT_BC7_SRGBA,
  1667. SG_PIXELFORMAT_ETC2_RGB8,
  1668. SG_PIXELFORMAT_ETC2_SRGB8,
  1669. SG_PIXELFORMAT_ETC2_RGB8A1,
  1670. SG_PIXELFORMAT_ETC2_RGBA8,
  1671. SG_PIXELFORMAT_ETC2_SRGB8A8,
  1672. SG_PIXELFORMAT_EAC_R11,
  1673. SG_PIXELFORMAT_EAC_R11SN,
  1674. SG_PIXELFORMAT_EAC_RG11,
  1675. SG_PIXELFORMAT_EAC_RG11SN,
  1676. SG_PIXELFORMAT_ASTC_4x4_RGBA,
  1677. SG_PIXELFORMAT_ASTC_4x4_SRGBA,
  1678. _SG_PIXELFORMAT_NUM,
  1679. _SG_PIXELFORMAT_FORCE_U32 = 0x7FFFFFFF
  1680. } sg_pixel_format;
  1681. /*
  1682. Runtime information about a pixel format, returned by sg_query_pixelformat().
  1683. */
  1684. typedef struct sg_pixelformat_info {
  1685. bool sample; // pixel format can be sampled in shaders at least with nearest filtering
  1686. bool filter; // pixel format can be sampled with linear filtering
  1687. bool render; // pixel format can be used as render-pass attachment
  1688. bool blend; // pixel format supports alpha-blending when used as render-pass attachment
  1689. bool msaa; // pixel format supports MSAA when used as render-pass attachment
  1690. bool depth; // pixel format is a depth format
  1691. bool compressed; // true if this is a hardware-compressed format
  1692. bool read; // true if format supports compute shader read access
  1693. bool write; // true if format supports compute shader write access
  1694. int bytes_per_pixel; // NOTE: this is 0 for compressed formats, use sg_query_row_pitch() / sg_query_surface_pitch() as alternative
  1695. } sg_pixelformat_info;
  1696. /*
  1697. Runtime information about available optional features, returned by sg_query_features()
  1698. */
  1699. typedef struct sg_features {
  1700. bool origin_top_left; // framebuffer- and texture-origin is in top left corner
  1701. bool image_clamp_to_border; // border color and clamp-to-border uv-wrap mode is supported
  1702. bool mrt_independent_blend_state; // multiple-render-target rendering can use per-render-target blend state
  1703. bool mrt_independent_write_mask; // multiple-render-target rendering can use per-render-target color write masks
  1704. bool compute; // storage buffers and compute shaders are supported
  1705. bool msaa_image_bindings; // if true, multisampled images can be bound as texture resources
  1706. bool separate_buffer_types; // cannot use the same buffer for vertex and indices (onlu WebGL2)
  1707. } sg_features;
  1708. /*
  1709. Runtime information about resource limits, returned by sg_query_limit()
  1710. */
  1711. typedef struct sg_limits {
  1712. int max_image_size_2d; // max width/height of SG_IMAGETYPE_2D images
  1713. int max_image_size_cube; // max width/height of SG_IMAGETYPE_CUBE images
  1714. int max_image_size_3d; // max width/height/depth of SG_IMAGETYPE_3D images
  1715. int max_image_size_array; // max width/height of SG_IMAGETYPE_ARRAY images
  1716. int max_image_array_layers; // max number of layers in SG_IMAGETYPE_ARRAY images
  1717. int max_vertex_attrs; // max number of vertex attributes, clamped to SG_MAX_VERTEX_ATTRIBUTES
  1718. int gl_max_vertex_uniform_components; // <= GL_MAX_VERTEX_UNIFORM_COMPONENTS (only on GL backends)
  1719. int gl_max_combined_texture_image_units; // <= GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS (only on GL backends)
  1720. } sg_limits;
  1721. /*
  1722. sg_resource_state
  1723. The current state of a resource in its resource pool.
  1724. Resources start in the INITIAL state, which means the
  1725. pool slot is unoccupied and can be allocated. When a resource is
  1726. created, first an id is allocated, and the resource pool slot
  1727. is set to state ALLOC. After allocation, the resource is
  1728. initialized, which may result in the VALID or FAILED state. The
  1729. reason why allocation and initialization are separate is because
  1730. some resource types (e.g. buffers and images) might be asynchronously
  1731. initialized by the user application. If a resource which is not
  1732. in the VALID state is attempted to be used for rendering, rendering
  1733. operations will silently be dropped.
  1734. The special INVALID state is returned in sg_query_xxx_state() if no
  1735. resource object exists for the provided resource id.
  1736. */
  1737. typedef enum sg_resource_state {
  1738. SG_RESOURCESTATE_INITIAL,
  1739. SG_RESOURCESTATE_ALLOC,
  1740. SG_RESOURCESTATE_VALID,
  1741. SG_RESOURCESTATE_FAILED,
  1742. SG_RESOURCESTATE_INVALID,
  1743. _SG_RESOURCESTATE_FORCE_U32 = 0x7FFFFFFF
  1744. } sg_resource_state;
  1745. /*
  1746. sg_index_type
  1747. Indicates whether indexed rendering (fetching vertex-indices from an
  1748. index buffer) is used, and if yes, the index data type (16- or 32-bits).
  1749. This is used in the sg_pipeline_desc.index_type member when creating a
  1750. pipeline object.
  1751. The default index type is SG_INDEXTYPE_NONE.
  1752. */
  1753. typedef enum sg_index_type {
  1754. _SG_INDEXTYPE_DEFAULT, // value 0 reserved for default-init
  1755. SG_INDEXTYPE_NONE,
  1756. SG_INDEXTYPE_UINT16,
  1757. SG_INDEXTYPE_UINT32,
  1758. _SG_INDEXTYPE_NUM,
  1759. _SG_INDEXTYPE_FORCE_U32 = 0x7FFFFFFF
  1760. } sg_index_type;
  1761. /*
  1762. sg_image_type
  1763. Indicates the basic type of an image object (2D-texture, cubemap,
  1764. 3D-texture or 2D-array-texture). Used in the sg_image_desc.type member when
  1765. creating an image, and in sg_shader_image_desc to describe a sampled texture
  1766. in the shader (both must match and will be checked in the validation layer
  1767. when calling sg_apply_bindings).
  1768. The default image type when creating an image is SG_IMAGETYPE_2D.
  1769. */
  1770. typedef enum sg_image_type {
  1771. _SG_IMAGETYPE_DEFAULT, // value 0 reserved for default-init
  1772. SG_IMAGETYPE_2D,
  1773. SG_IMAGETYPE_CUBE,
  1774. SG_IMAGETYPE_3D,
  1775. SG_IMAGETYPE_ARRAY,
  1776. _SG_IMAGETYPE_NUM,
  1777. _SG_IMAGETYPE_FORCE_U32 = 0x7FFFFFFF
  1778. } sg_image_type;
  1779. /*
  1780. sg_image_sample_type
  1781. The basic data type of a texture sample as expected by a shader.
  1782. Must be provided in sg_shader_image and used by the validation
  1783. layer in sg_apply_bindings() to check if the provided image object
  1784. is compatible with what the shader expects. Apart from the sokol-gfx
  1785. validation layer, WebGPU is the only backend API which actually requires
  1786. matching texture and sampler type to be provided upfront for validation
  1787. (other 3D APIs treat texture/sampler type mismatches as undefined behaviour).
  1788. NOTE that the following texture pixel formats require the use
  1789. of SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT, combined with a sampler
  1790. of type SG_SAMPLERTYPE_NONFILTERING:
  1791. - SG_PIXELFORMAT_R32F
  1792. - SG_PIXELFORMAT_RG32F
  1793. - SG_PIXELFORMAT_RGBA32F
  1794. (when using sokol-shdc, also check out the meta tags `@image_sample_type`
  1795. and `@sampler_type`)
  1796. */
  1797. typedef enum sg_image_sample_type {
  1798. _SG_IMAGESAMPLETYPE_DEFAULT, // value 0 reserved for default-init
  1799. SG_IMAGESAMPLETYPE_FLOAT,
  1800. SG_IMAGESAMPLETYPE_DEPTH,
  1801. SG_IMAGESAMPLETYPE_SINT,
  1802. SG_IMAGESAMPLETYPE_UINT,
  1803. SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT,
  1804. _SG_IMAGESAMPLETYPE_NUM,
  1805. _SG_IMAGESAMPLETYPE_FORCE_U32 = 0x7FFFFFFF
  1806. } sg_image_sample_type;
  1807. /*
  1808. sg_sampler_type
  1809. The basic type of a texture sampler (sampling vs comparison) as
  1810. defined in a shader. Must be provided in sg_shader_sampler_desc.
  1811. sg_image_sample_type and sg_sampler_type for a texture/sampler
  1812. pair must be compatible with each other, specifically only
  1813. the following pairs are allowed:
  1814. - SG_IMAGESAMPLETYPE_FLOAT => (SG_SAMPLERTYPE_FILTERING or SG_SAMPLERTYPE_NONFILTERING)
  1815. - SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT => SG_SAMPLERTYPE_NONFILTERING
  1816. - SG_IMAGESAMPLETYPE_SINT => SG_SAMPLERTYPE_NONFILTERING
  1817. - SG_IMAGESAMPLETYPE_UINT => SG_SAMPLERTYPE_NONFILTERING
  1818. - SG_IMAGESAMPLETYPE_DEPTH => SG_SAMPLERTYPE_COMPARISON
  1819. */
  1820. typedef enum sg_sampler_type {
  1821. _SG_SAMPLERTYPE_DEFAULT,
  1822. SG_SAMPLERTYPE_FILTERING,
  1823. SG_SAMPLERTYPE_NONFILTERING,
  1824. SG_SAMPLERTYPE_COMPARISON,
  1825. _SG_SAMPLERTYPE_NUM,
  1826. _SG_SAMPLERTYPE_FORCE_U32,
  1827. } sg_sampler_type;
  1828. /*
  1829. sg_cube_face
  1830. The cubemap faces. Use these as indices in the sg_image_desc.content
  1831. array.
  1832. */
  1833. typedef enum sg_cube_face {
  1834. SG_CUBEFACE_POS_X,
  1835. SG_CUBEFACE_NEG_X,
  1836. SG_CUBEFACE_POS_Y,
  1837. SG_CUBEFACE_NEG_Y,
  1838. SG_CUBEFACE_POS_Z,
  1839. SG_CUBEFACE_NEG_Z,
  1840. SG_CUBEFACE_NUM,
  1841. _SG_CUBEFACE_FORCE_U32 = 0x7FFFFFFF
  1842. } sg_cube_face;
  1843. /*
  1844. sg_primitive_type
  1845. This is the common subset of 3D primitive types supported across all 3D
  1846. APIs. This is used in the sg_pipeline_desc.primitive_type member when
  1847. creating a pipeline object.
  1848. The default primitive type is SG_PRIMITIVETYPE_TRIANGLES.
  1849. */
  1850. typedef enum sg_primitive_type {
  1851. _SG_PRIMITIVETYPE_DEFAULT, // value 0 reserved for default-init
  1852. SG_PRIMITIVETYPE_POINTS,
  1853. SG_PRIMITIVETYPE_LINES,
  1854. SG_PRIMITIVETYPE_LINE_STRIP,
  1855. SG_PRIMITIVETYPE_TRIANGLES,
  1856. SG_PRIMITIVETYPE_TRIANGLE_STRIP,
  1857. _SG_PRIMITIVETYPE_NUM,
  1858. _SG_PRIMITIVETYPE_FORCE_U32 = 0x7FFFFFFF
  1859. } sg_primitive_type;
  1860. /*
  1861. sg_filter
  1862. The filtering mode when sampling a texture image. This is
  1863. used in the sg_sampler_desc.min_filter, sg_sampler_desc.mag_filter
  1864. and sg_sampler_desc.mipmap_filter members when creating a sampler object.
  1865. For the default is SG_FILTER_NEAREST.
  1866. */
  1867. typedef enum sg_filter {
  1868. _SG_FILTER_DEFAULT, // value 0 reserved for default-init
  1869. SG_FILTER_NEAREST,
  1870. SG_FILTER_LINEAR,
  1871. _SG_FILTER_NUM,
  1872. _SG_FILTER_FORCE_U32 = 0x7FFFFFFF
  1873. } sg_filter;
  1874. /*
  1875. sg_wrap
  1876. The texture coordinates wrapping mode when sampling a texture
  1877. image. This is used in the sg_image_desc.wrap_u, .wrap_v
  1878. and .wrap_w members when creating an image.
  1879. The default wrap mode is SG_WRAP_REPEAT.
  1880. NOTE: SG_WRAP_CLAMP_TO_BORDER is not supported on all backends
  1881. and platforms. To check for support, call sg_query_features()
  1882. and check the "clamp_to_border" boolean in the returned
  1883. sg_features struct.
  1884. Platforms which don't support SG_WRAP_CLAMP_TO_BORDER will silently fall back
  1885. to SG_WRAP_CLAMP_TO_EDGE without a validation error.
  1886. */
  1887. typedef enum sg_wrap {
  1888. _SG_WRAP_DEFAULT, // value 0 reserved for default-init
  1889. SG_WRAP_REPEAT,
  1890. SG_WRAP_CLAMP_TO_EDGE,
  1891. SG_WRAP_CLAMP_TO_BORDER,
  1892. SG_WRAP_MIRRORED_REPEAT,
  1893. _SG_WRAP_NUM,
  1894. _SG_WRAP_FORCE_U32 = 0x7FFFFFFF
  1895. } sg_wrap;
  1896. /*
  1897. sg_border_color
  1898. The border color to use when sampling a texture, and the UV wrap
  1899. mode is SG_WRAP_CLAMP_TO_BORDER.
  1900. The default border color is SG_BORDERCOLOR_OPAQUE_BLACK
  1901. */
  1902. typedef enum sg_border_color {
  1903. _SG_BORDERCOLOR_DEFAULT, // value 0 reserved for default-init
  1904. SG_BORDERCOLOR_TRANSPARENT_BLACK,
  1905. SG_BORDERCOLOR_OPAQUE_BLACK,
  1906. SG_BORDERCOLOR_OPAQUE_WHITE,
  1907. _SG_BORDERCOLOR_NUM,
  1908. _SG_BORDERCOLOR_FORCE_U32 = 0x7FFFFFFF
  1909. } sg_border_color;
  1910. /*
  1911. sg_vertex_format
  1912. The data type of a vertex component. This is used to describe
  1913. the layout of input vertex data when creating a pipeline object.
  1914. NOTE that specific mapping rules exist from the CPU-side vertex
  1915. formats to the vertex attribute base type in the vertex shader code
  1916. (see doc header section 'ON VERTEX FORMATS').
  1917. */
  1918. typedef enum sg_vertex_format {
  1919. SG_VERTEXFORMAT_INVALID,
  1920. SG_VERTEXFORMAT_FLOAT,
  1921. SG_VERTEXFORMAT_FLOAT2,
  1922. SG_VERTEXFORMAT_FLOAT3,
  1923. SG_VERTEXFORMAT_FLOAT4,
  1924. SG_VERTEXFORMAT_INT,
  1925. SG_VERTEXFORMAT_INT2,
  1926. SG_VERTEXFORMAT_INT3,
  1927. SG_VERTEXFORMAT_INT4,
  1928. SG_VERTEXFORMAT_UINT,
  1929. SG_VERTEXFORMAT_UINT2,
  1930. SG_VERTEXFORMAT_UINT3,
  1931. SG_VERTEXFORMAT_UINT4,
  1932. SG_VERTEXFORMAT_BYTE4,
  1933. SG_VERTEXFORMAT_BYTE4N,
  1934. SG_VERTEXFORMAT_UBYTE4,
  1935. SG_VERTEXFORMAT_UBYTE4N,
  1936. SG_VERTEXFORMAT_SHORT2,
  1937. SG_VERTEXFORMAT_SHORT2N,
  1938. SG_VERTEXFORMAT_USHORT2,
  1939. SG_VERTEXFORMAT_USHORT2N,
  1940. SG_VERTEXFORMAT_SHORT4,
  1941. SG_VERTEXFORMAT_SHORT4N,
  1942. SG_VERTEXFORMAT_USHORT4,
  1943. SG_VERTEXFORMAT_USHORT4N,
  1944. SG_VERTEXFORMAT_UINT10_N2,
  1945. SG_VERTEXFORMAT_HALF2,
  1946. SG_VERTEXFORMAT_HALF4,
  1947. _SG_VERTEXFORMAT_NUM,
  1948. _SG_VERTEXFORMAT_FORCE_U32 = 0x7FFFFFFF
  1949. } sg_vertex_format;
  1950. /*
  1951. sg_vertex_step
  1952. Defines whether the input pointer of a vertex input stream is advanced
  1953. 'per vertex' or 'per instance'. The default step-func is
  1954. SG_VERTEXSTEP_PER_VERTEX. SG_VERTEXSTEP_PER_INSTANCE is used with
  1955. instanced-rendering.
  1956. The vertex-step is part of the vertex-layout definition
  1957. when creating pipeline objects.
  1958. */
  1959. typedef enum sg_vertex_step {
  1960. _SG_VERTEXSTEP_DEFAULT, // value 0 reserved for default-init
  1961. SG_VERTEXSTEP_PER_VERTEX,
  1962. SG_VERTEXSTEP_PER_INSTANCE,
  1963. _SG_VERTEXSTEP_NUM,
  1964. _SG_VERTEXSTEP_FORCE_U32 = 0x7FFFFFFF
  1965. } sg_vertex_step;
  1966. /*
  1967. sg_uniform_type
  1968. The data type of a uniform block member. This is used to
  1969. describe the internal layout of uniform blocks when creating
  1970. a shader object. This is only required for the GL backend, all
  1971. other backends will ignore the interior layout of uniform blocks.
  1972. */
  1973. typedef enum sg_uniform_type {
  1974. SG_UNIFORMTYPE_INVALID,
  1975. SG_UNIFORMTYPE_FLOAT,
  1976. SG_UNIFORMTYPE_FLOAT2,
  1977. SG_UNIFORMTYPE_FLOAT3,
  1978. SG_UNIFORMTYPE_FLOAT4,
  1979. SG_UNIFORMTYPE_INT,
  1980. SG_UNIFORMTYPE_INT2,
  1981. SG_UNIFORMTYPE_INT3,
  1982. SG_UNIFORMTYPE_INT4,
  1983. SG_UNIFORMTYPE_MAT4,
  1984. _SG_UNIFORMTYPE_NUM,
  1985. _SG_UNIFORMTYPE_FORCE_U32 = 0x7FFFFFFF
  1986. } sg_uniform_type;
  1987. /*
  1988. sg_uniform_layout
  1989. A hint for the interior memory layout of uniform blocks. This is
  1990. only relevant for the GL backend where the internal layout
  1991. of uniform blocks must be known to sokol-gfx. For all other backends the
  1992. internal memory layout of uniform blocks doesn't matter, sokol-gfx
  1993. will just pass uniform data as an opaque memory blob to the
  1994. 3D backend.
  1995. SG_UNIFORMLAYOUT_NATIVE (default)
  1996. Native layout means that a 'backend-native' memory layout
  1997. is used. For the GL backend this means that uniforms
  1998. are packed tightly in memory (e.g. there are no padding
  1999. bytes).
  2000. SG_UNIFORMLAYOUT_STD140
  2001. The memory layout is a subset of std140. Arrays are only
  2002. allowed for the FLOAT4, INT4 and MAT4. Alignment is as
  2003. is as follows:
  2004. FLOAT, INT: 4 byte alignment
  2005. FLOAT2, INT2: 8 byte alignment
  2006. FLOAT3, INT3: 16 byte alignment(!)
  2007. FLOAT4, INT4: 16 byte alignment
  2008. MAT4: 16 byte alignment
  2009. FLOAT4[], INT4[]: 16 byte alignment
  2010. The overall size of the uniform block must be a multiple
  2011. of 16.
  2012. For more information search for 'UNIFORM DATA LAYOUT' in the documentation block
  2013. at the start of the header.
  2014. */
  2015. typedef enum sg_uniform_layout {
  2016. _SG_UNIFORMLAYOUT_DEFAULT, // value 0 reserved for default-init
  2017. SG_UNIFORMLAYOUT_NATIVE, // default: layout depends on currently active backend
  2018. SG_UNIFORMLAYOUT_STD140, // std140: memory layout according to std140
  2019. _SG_UNIFORMLAYOUT_NUM,
  2020. _SG_UNIFORMLAYOUT_FORCE_U32 = 0x7FFFFFFF
  2021. } sg_uniform_layout;
  2022. /*
  2023. sg_cull_mode
  2024. The face-culling mode, this is used in the
  2025. sg_pipeline_desc.cull_mode member when creating a
  2026. pipeline object.
  2027. The default cull mode is SG_CULLMODE_NONE
  2028. */
  2029. typedef enum sg_cull_mode {
  2030. _SG_CULLMODE_DEFAULT, // value 0 reserved for default-init
  2031. SG_CULLMODE_NONE,
  2032. SG_CULLMODE_FRONT,
  2033. SG_CULLMODE_BACK,
  2034. _SG_CULLMODE_NUM,
  2035. _SG_CULLMODE_FORCE_U32 = 0x7FFFFFFF
  2036. } sg_cull_mode;
  2037. /*
  2038. sg_face_winding
  2039. The vertex-winding rule that determines a front-facing primitive. This
  2040. is used in the member sg_pipeline_desc.face_winding
  2041. when creating a pipeline object.
  2042. The default winding is SG_FACEWINDING_CW (clockwise)
  2043. */
  2044. typedef enum sg_face_winding {
  2045. _SG_FACEWINDING_DEFAULT, // value 0 reserved for default-init
  2046. SG_FACEWINDING_CCW,
  2047. SG_FACEWINDING_CW,
  2048. _SG_FACEWINDING_NUM,
  2049. _SG_FACEWINDING_FORCE_U32 = 0x7FFFFFFF
  2050. } sg_face_winding;
  2051. /*
  2052. sg_compare_func
  2053. The compare-function for configuring depth- and stencil-ref tests
  2054. in pipeline objects, and for texture samplers which perform a comparison
  2055. instead of regular sampling operation.
  2056. Used in the following structs:
  2057. sg_pipeline_desc
  2058. .depth
  2059. .compare
  2060. .stencil
  2061. .front.compare
  2062. .back.compare
  2063. sg_sampler_desc
  2064. .compare
  2065. The default compare func for depth- and stencil-tests is
  2066. SG_COMPAREFUNC_ALWAYS.
  2067. The default compare func for samplers is SG_COMPAREFUNC_NEVER.
  2068. */
  2069. typedef enum sg_compare_func {
  2070. _SG_COMPAREFUNC_DEFAULT, // value 0 reserved for default-init
  2071. SG_COMPAREFUNC_NEVER,
  2072. SG_COMPAREFUNC_LESS,
  2073. SG_COMPAREFUNC_EQUAL,
  2074. SG_COMPAREFUNC_LESS_EQUAL,
  2075. SG_COMPAREFUNC_GREATER,
  2076. SG_COMPAREFUNC_NOT_EQUAL,
  2077. SG_COMPAREFUNC_GREATER_EQUAL,
  2078. SG_COMPAREFUNC_ALWAYS,
  2079. _SG_COMPAREFUNC_NUM,
  2080. _SG_COMPAREFUNC_FORCE_U32 = 0x7FFFFFFF
  2081. } sg_compare_func;
  2082. /*
  2083. sg_stencil_op
  2084. The operation performed on a currently stored stencil-value when a
  2085. comparison test passes or fails. This is used when creating a pipeline
  2086. object in the following sg_pipeline_desc struct items:
  2087. sg_pipeline_desc
  2088. .stencil
  2089. .front
  2090. .fail_op
  2091. .depth_fail_op
  2092. .pass_op
  2093. .back
  2094. .fail_op
  2095. .depth_fail_op
  2096. .pass_op
  2097. The default value is SG_STENCILOP_KEEP.
  2098. */
  2099. typedef enum sg_stencil_op {
  2100. _SG_STENCILOP_DEFAULT, // value 0 reserved for default-init
  2101. SG_STENCILOP_KEEP,
  2102. SG_STENCILOP_ZERO,
  2103. SG_STENCILOP_REPLACE,
  2104. SG_STENCILOP_INCR_CLAMP,
  2105. SG_STENCILOP_DECR_CLAMP,
  2106. SG_STENCILOP_INVERT,
  2107. SG_STENCILOP_INCR_WRAP,
  2108. SG_STENCILOP_DECR_WRAP,
  2109. _SG_STENCILOP_NUM,
  2110. _SG_STENCILOP_FORCE_U32 = 0x7FFFFFFF
  2111. } sg_stencil_op;
  2112. /*
  2113. sg_blend_factor
  2114. The source and destination factors in blending operations.
  2115. This is used in the following members when creating a pipeline object:
  2116. sg_pipeline_desc
  2117. .colors[i]
  2118. .blend
  2119. .src_factor_rgb
  2120. .dst_factor_rgb
  2121. .src_factor_alpha
  2122. .dst_factor_alpha
  2123. The default value is SG_BLENDFACTOR_ONE for source
  2124. factors, and for the destination SG_BLENDFACTOR_ZERO if the associated
  2125. blend-op is ADD, SUBTRACT or REVERSE_SUBTRACT or SG_BLENDFACTOR_ONE
  2126. if the associated blend-op is MIN or MAX.
  2127. */
  2128. typedef enum sg_blend_factor {
  2129. _SG_BLENDFACTOR_DEFAULT, // value 0 reserved for default-init
  2130. SG_BLENDFACTOR_ZERO,
  2131. SG_BLENDFACTOR_ONE,
  2132. SG_BLENDFACTOR_SRC_COLOR,
  2133. SG_BLENDFACTOR_ONE_MINUS_SRC_COLOR,
  2134. SG_BLENDFACTOR_SRC_ALPHA,
  2135. SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA,
  2136. SG_BLENDFACTOR_DST_COLOR,
  2137. SG_BLENDFACTOR_ONE_MINUS_DST_COLOR,
  2138. SG_BLENDFACTOR_DST_ALPHA,
  2139. SG_BLENDFACTOR_ONE_MINUS_DST_ALPHA,
  2140. SG_BLENDFACTOR_SRC_ALPHA_SATURATED,
  2141. SG_BLENDFACTOR_BLEND_COLOR,
  2142. SG_BLENDFACTOR_ONE_MINUS_BLEND_COLOR,
  2143. SG_BLENDFACTOR_BLEND_ALPHA,
  2144. SG_BLENDFACTOR_ONE_MINUS_BLEND_ALPHA,
  2145. _SG_BLENDFACTOR_NUM,
  2146. _SG_BLENDFACTOR_FORCE_U32 = 0x7FFFFFFF
  2147. } sg_blend_factor;
  2148. /*
  2149. sg_blend_op
  2150. Describes how the source and destination values are combined in the
  2151. fragment blending operation. It is used in the following struct items
  2152. when creating a pipeline object:
  2153. sg_pipeline_desc
  2154. .colors[i]
  2155. .blend
  2156. .op_rgb
  2157. .op_alpha
  2158. The default value is SG_BLENDOP_ADD.
  2159. */
  2160. typedef enum sg_blend_op {
  2161. _SG_BLENDOP_DEFAULT, // value 0 reserved for default-init
  2162. SG_BLENDOP_ADD,
  2163. SG_BLENDOP_SUBTRACT,
  2164. SG_BLENDOP_REVERSE_SUBTRACT,
  2165. SG_BLENDOP_MIN,
  2166. SG_BLENDOP_MAX,
  2167. _SG_BLENDOP_NUM,
  2168. _SG_BLENDOP_FORCE_U32 = 0x7FFFFFFF
  2169. } sg_blend_op;
  2170. /*
  2171. sg_color_mask
  2172. Selects the active color channels when writing a fragment color to the
  2173. framebuffer. This is used in the members
  2174. sg_pipeline_desc.colors[i].write_mask when creating a pipeline object.
  2175. The default colormask is SG_COLORMASK_RGBA (write all colors channels)
  2176. NOTE: since the color mask value 0 is reserved for the default value
  2177. (SG_COLORMASK_RGBA), use SG_COLORMASK_NONE if all color channels
  2178. should be disabled.
  2179. */
  2180. typedef enum sg_color_mask {
  2181. _SG_COLORMASK_DEFAULT = 0, // value 0 reserved for default-init
  2182. SG_COLORMASK_NONE = 0x10, // special value for 'all channels disabled
  2183. SG_COLORMASK_R = 0x1,
  2184. SG_COLORMASK_G = 0x2,
  2185. SG_COLORMASK_RG = 0x3,
  2186. SG_COLORMASK_B = 0x4,
  2187. SG_COLORMASK_RB = 0x5,
  2188. SG_COLORMASK_GB = 0x6,
  2189. SG_COLORMASK_RGB = 0x7,
  2190. SG_COLORMASK_A = 0x8,
  2191. SG_COLORMASK_RA = 0x9,
  2192. SG_COLORMASK_GA = 0xA,
  2193. SG_COLORMASK_RGA = 0xB,
  2194. SG_COLORMASK_BA = 0xC,
  2195. SG_COLORMASK_RBA = 0xD,
  2196. SG_COLORMASK_GBA = 0xE,
  2197. SG_COLORMASK_RGBA = 0xF,
  2198. _SG_COLORMASK_FORCE_U32 = 0x7FFFFFFF
  2199. } sg_color_mask;
  2200. /*
  2201. sg_load_action
  2202. Defines the load action that should be performed at the start of a render pass:
  2203. SG_LOADACTION_CLEAR: clear the render target
  2204. SG_LOADACTION_LOAD: load the previous content of the render target
  2205. SG_LOADACTION_DONTCARE: leave the render target in an undefined state
  2206. This is used in the sg_pass_action structure.
  2207. The default load action for all pass attachments is SG_LOADACTION_CLEAR,
  2208. with the values rgba = { 0.5f, 0.5f, 0.5f, 1.0f }, depth=1.0f and stencil=0.
  2209. If you want to override the default behaviour, it is important to not
  2210. only set the clear color, but the 'action' field as well (as long as this
  2211. is _SG_LOADACTION_DEFAULT, the value fields will be ignored).
  2212. */
  2213. typedef enum sg_load_action {
  2214. _SG_LOADACTION_DEFAULT,
  2215. SG_LOADACTION_CLEAR,
  2216. SG_LOADACTION_LOAD,
  2217. SG_LOADACTION_DONTCARE,
  2218. _SG_LOADACTION_FORCE_U32 = 0x7FFFFFFF
  2219. } sg_load_action;
  2220. /*
  2221. sg_store_action
  2222. Defines the store action that should be performed at the end of a render pass:
  2223. SG_STOREACTION_STORE: store the rendered content to the color attachment image
  2224. SG_STOREACTION_DONTCARE: allows the GPU to discard the rendered content
  2225. */
  2226. typedef enum sg_store_action {
  2227. _SG_STOREACTION_DEFAULT,
  2228. SG_STOREACTION_STORE,
  2229. SG_STOREACTION_DONTCARE,
  2230. _SG_STOREACTION_FORCE_U32 = 0x7FFFFFFF
  2231. } sg_store_action;
  2232. /*
  2233. sg_pass_action
  2234. The sg_pass_action struct defines the actions to be performed
  2235. at the start and end of a render pass.
  2236. - at the start of the pass: whether the render attachments should be cleared,
  2237. loaded with their previous content, or start in an undefined state
  2238. - for clear operations: the clear value (color, depth, or stencil values)
  2239. - at the end of the pass: whether the rendering result should be
  2240. stored back into the render attachment or discarded
  2241. */
  2242. typedef struct sg_color_attachment_action {
  2243. sg_load_action load_action; // default: SG_LOADACTION_CLEAR
  2244. sg_store_action store_action; // default: SG_STOREACTION_STORE
  2245. sg_color clear_value; // default: { 0.5f, 0.5f, 0.5f, 1.0f }
  2246. } sg_color_attachment_action;
  2247. typedef struct sg_depth_attachment_action {
  2248. sg_load_action load_action; // default: SG_LOADACTION_CLEAR
  2249. sg_store_action store_action; // default: SG_STOREACTION_DONTCARE
  2250. float clear_value; // default: 1.0
  2251. } sg_depth_attachment_action;
  2252. typedef struct sg_stencil_attachment_action {
  2253. sg_load_action load_action; // default: SG_LOADACTION_CLEAR
  2254. sg_store_action store_action; // default: SG_STOREACTION_DONTCARE
  2255. uint8_t clear_value; // default: 0
  2256. } sg_stencil_attachment_action;
  2257. typedef struct sg_pass_action {
  2258. sg_color_attachment_action colors[SG_MAX_COLOR_ATTACHMENTS];
  2259. sg_depth_attachment_action depth;
  2260. sg_stencil_attachment_action stencil;
  2261. } sg_pass_action;
  2262. /*
  2263. sg_swapchain
  2264. Used in sg_begin_pass() to provide details about an external swapchain
  2265. (pixel formats, sample count and backend-API specific render surface objects).
  2266. The following information must be provided:
  2267. - the width and height of the swapchain surfaces in number of pixels,
  2268. - the pixel format of the render- and optional msaa-resolve-surface
  2269. - the pixel format of the optional depth- or depth-stencil-surface
  2270. - the MSAA sample count for the render and depth-stencil surface
  2271. If the pixel formats and MSAA sample counts are left zero-initialized,
  2272. their defaults are taken from the sg_environment struct provided in the
  2273. sg_setup() call.
  2274. The width and height *must* be > 0.
  2275. Additionally the following backend API specific objects must be passed in
  2276. as 'type erased' void pointers:
  2277. GL:
  2278. - on all GL backends, a GL framebuffer object must be provided. This
  2279. can be zero for the default framebuffer.
  2280. D3D11:
  2281. - an ID3D11RenderTargetView for the rendering surface, without
  2282. MSAA rendering this surface will also be displayed
  2283. - an optional ID3D11DepthStencilView for the depth- or depth/stencil
  2284. buffer surface
  2285. - when MSAA rendering is used, another ID3D11RenderTargetView
  2286. which serves as MSAA resolve target and will be displayed
  2287. WebGPU (same as D3D11, except different types)
  2288. - a WGPUTextureView for the rendering surface, without
  2289. MSAA rendering this surface will also be displayed
  2290. - an optional WGPUTextureView for the depth- or depth/stencil
  2291. buffer surface
  2292. - when MSAA rendering is used, another WGPUTextureView
  2293. which serves as MSAA resolve target and will be displayed
  2294. Metal (NOTE that the roles of provided surfaces is slightly different
  2295. than on D3D11 or WebGPU in case of MSAA vs non-MSAA rendering):
  2296. - A current CAMetalDrawable (NOT an MTLDrawable!) which will be presented.
  2297. This will either be rendered to directly (if no MSAA is used), or serve
  2298. as MSAA-resolve target.
  2299. - an optional MTLTexture for the depth- or depth-stencil buffer
  2300. - an optional multisampled MTLTexture which serves as intermediate
  2301. rendering surface which will then be resolved into the
  2302. CAMetalDrawable.
  2303. NOTE that for Metal you must use an ObjC __bridge cast to
  2304. properly tunnel the ObjC object id through a C void*, e.g.:
  2305. swapchain.metal.current_drawable = (__bridge const void*) [mtkView currentDrawable];
  2306. On all other backends you shouldn't need to mess with the reference count.
  2307. It's a good practice to write a helper function which returns an initialized
  2308. sg_swapchain structs, which can then be plugged directly into
  2309. sg_pass.swapchain. Look at the function sglue_swapchain() in the sokol_glue.h
  2310. as an example.
  2311. */
  2312. typedef struct sg_metal_swapchain {
  2313. const void* current_drawable; // CAMetalDrawable (NOT MTLDrawable!!!)
  2314. const void* depth_stencil_texture; // MTLTexture
  2315. const void* msaa_color_texture; // MTLTexture
  2316. } sg_metal_swapchain;
  2317. typedef struct sg_d3d11_swapchain {
  2318. const void* render_view; // ID3D11RenderTargetView
  2319. const void* resolve_view; // ID3D11RenderTargetView
  2320. const void* depth_stencil_view; // ID3D11DepthStencilView
  2321. } sg_d3d11_swapchain;
  2322. typedef struct sg_wgpu_swapchain {
  2323. const void* render_view; // WGPUTextureView
  2324. const void* resolve_view; // WGPUTextureView
  2325. const void* depth_stencil_view; // WGPUTextureView
  2326. } sg_wgpu_swapchain;
  2327. typedef struct sg_gl_swapchain {
  2328. uint32_t framebuffer; // GL framebuffer object
  2329. } sg_gl_swapchain;
  2330. typedef struct sg_swapchain {
  2331. int width;
  2332. int height;
  2333. int sample_count;
  2334. sg_pixel_format color_format;
  2335. sg_pixel_format depth_format;
  2336. sg_metal_swapchain metal;
  2337. sg_d3d11_swapchain d3d11;
  2338. sg_wgpu_swapchain wgpu;
  2339. sg_gl_swapchain gl;
  2340. } sg_swapchain;
  2341. /*
  2342. sg_pass
  2343. The sg_pass structure is passed as argument into the sg_begin_pass()
  2344. function.
  2345. For a swapchain render pass, provide an sg_pass_action and sg_swapchain
  2346. struct (for instance via the sglue_swapchain() helper function from
  2347. sokol_glue.h):
  2348. sg_begin_pass(&(sg_pass){
  2349. .action = { ... },
  2350. .swapchain = sglue_swapchain(),
  2351. });
  2352. For an offscreen render pass, provide an sg_pass_action struct and
  2353. an sg_attachments handle:
  2354. sg_begin_pass(&(sg_pass){
  2355. .action = { ... },
  2356. .attachments = attachments,
  2357. });
  2358. You can also omit the .action object to get default pass action behaviour
  2359. (clear to color=grey, depth=1 and stencil=0).
  2360. For a compute pass, just set the sg_pass.compute boolean to true:
  2361. sg_begin_pass(&(sg_pass){ .compute = true });
  2362. */
  2363. typedef struct sg_pass {
  2364. uint32_t _start_canary;
  2365. bool compute;
  2366. sg_pass_action action;
  2367. sg_attachments attachments;
  2368. sg_swapchain swapchain;
  2369. const char* label;
  2370. uint32_t _end_canary;
  2371. } sg_pass;
  2372. /*
  2373. sg_bindings
  2374. The sg_bindings structure defines the buffers, images and
  2375. samplers resource bindings for the next draw call.
  2376. To update the resource bindings, call sg_apply_bindings() with
  2377. a pointer to a populated sg_bindings struct. Note that
  2378. sg_apply_bindings() must be called after sg_apply_pipeline()
  2379. and that bindings are not preserved across sg_apply_pipeline()
  2380. calls, even when the new pipeline uses the same 'bindings layout'.
  2381. A resource binding struct contains:
  2382. - 1..N vertex buffers
  2383. - 0..N vertex buffer offsets
  2384. - 0..1 index buffers
  2385. - 0..1 index buffer offsets
  2386. - 0..N images
  2387. - 0..N samplers
  2388. - 0..N storage buffers
  2389. Where 'N' is defined in the following constants:
  2390. - SG_MAX_VERTEXBUFFER_BINDSLOTS
  2391. - SG_MAX_IMAGE_BINDLOTS
  2392. - SG_MAX_SAMPLER_BINDSLOTS
  2393. - SG_MAX_STORAGEBUFFER_BINDGLOTS
  2394. Note that inside compute passes vertex- and index-buffer-bindings are
  2395. disallowed.
  2396. When using sokol-shdc for shader authoring, the `layout(binding=N)`
  2397. annotation in the shader code directly maps to the slot index for that
  2398. resource type in the bindings struct, for instance the following vertex-
  2399. and fragment-shader interface for sokol-shdc:
  2400. @vs vs
  2401. layout(binding=0) uniform vs_params { ... };
  2402. layout(binding=0) readonly buffer ssbo { ... };
  2403. layout(binding=0) uniform texture2D vs_tex;
  2404. layout(binding=0) uniform sampler vs_smp;
  2405. ...
  2406. @end
  2407. @fs fs
  2408. layout(binding=1) uniform fs_params { ... };
  2409. layout(binding=1) uniform texture2D fs_tex;
  2410. layout(binding=1) uniform sampler fs_smp;
  2411. ...
  2412. @end
  2413. ...would map to the following sg_bindings struct:
  2414. const sg_bindings bnd = {
  2415. .vertex_buffers[0] = ...,
  2416. .images[0] = vs_tex,
  2417. .images[1] = fs_tex,
  2418. .samplers[0] = vs_smp,
  2419. .samplers[1] = fs_smp,
  2420. .storage_buffers[0] = ssbo,
  2421. };
  2422. ...alternatively you can use code-generated slot indices:
  2423. const sg_bindings bnd = {
  2424. .vertex_buffers[0] = ...,
  2425. .images[IMG_vs_tex] = vs_tex,
  2426. .images[IMG_fs_tex] = fs_tex,
  2427. .samplers[SMP_vs_smp] = vs_smp,
  2428. .samplers[SMP_fs_smp] = fs_smp,
  2429. .storage_buffers[SBUF_ssbo] = ssbo,
  2430. };
  2431. Resource bindslots for a specific shader/pipeline may have gaps, and an
  2432. sg_bindings struct may have populated bind slots which are not used by a
  2433. specific shader. This allows to use the same sg_bindings struct across
  2434. different shader variants.
  2435. When not using sokol-shdc, the bindslot indices in the sg_bindings
  2436. struct need to match the per-resource reflection info slot indices
  2437. in the sg_shader_desc struct (for details about that see the
  2438. sg_shader_desc struct documentation).
  2439. The optional buffer offsets can be used to put different unrelated
  2440. chunks of vertex- and/or index-data into the same buffer objects.
  2441. */
  2442. typedef struct sg_bindings {
  2443. uint32_t _start_canary;
  2444. sg_buffer vertex_buffers[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  2445. int vertex_buffer_offsets[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  2446. sg_buffer index_buffer;
  2447. int index_buffer_offset;
  2448. sg_image images[SG_MAX_IMAGE_BINDSLOTS];
  2449. sg_sampler samplers[SG_MAX_SAMPLER_BINDSLOTS];
  2450. sg_buffer storage_buffers[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  2451. uint32_t _end_canary;
  2452. } sg_bindings;
  2453. /*
  2454. sg_buffer_usage
  2455. Describes how a buffer object is going to be used:
  2456. .vertex_buffer (default: true)
  2457. the buffer will bound as vertex buffer via sg_bindings.vertex_buffers[]
  2458. .index_buffer (default: false)
  2459. the buffer will bound as index buffer via sg_bindings.index_buffer
  2460. .storage_buffer (default: false)
  2461. the buffer will bound as storage buffer via sg_bindings.storage_buffers[]
  2462. .immutable (default: true)
  2463. the buffer content will never be updated from the CPU side (but
  2464. may be written to by a compute shader)
  2465. .dynamic_update (default: false)
  2466. the buffer content will be infrequently updated from the CPU side
  2467. .stream_upate (default: false)
  2468. the buffer content will be updated each frame from the CPU side
  2469. */
  2470. typedef struct sg_buffer_usage {
  2471. bool vertex_buffer;
  2472. bool index_buffer;
  2473. bool storage_buffer;
  2474. bool immutable;
  2475. bool dynamic_update;
  2476. bool stream_update;
  2477. } sg_buffer_usage;
  2478. /*
  2479. sg_buffer_desc
  2480. Creation parameters for sg_buffer objects, used in the sg_make_buffer() call.
  2481. The default configuration is:
  2482. .size: 0 (*must* be >0 for buffers without data)
  2483. .usage .vertex_buffer = true, .immutable = true
  2484. .data.ptr 0 (*must* be valid for immutable buffers without storage buffer usage)
  2485. .data.size 0 (*must* be > 0 for immutable buffers without storage buffer usage)
  2486. .label 0 (optional string label)
  2487. For immutable buffers which are initialized with initial data,
  2488. keep the .size item zero-initialized, and set the size together with the
  2489. pointer to the initial data in the .data item.
  2490. For immutable or mutable buffers without initial data, keep the .data item
  2491. zero-initialized, and set the buffer size in the .size item instead.
  2492. You can also set both size values, but currently both size values must
  2493. be identical (this may change in the future when the dynamic resource
  2494. management may become more flexible).
  2495. NOTE: Immutable buffers without storage-buffer-usage *must* be created
  2496. with initial content, this restriction doesn't apply to storage buffer usage,
  2497. because storage buffers may also get their initial content by running
  2498. a compute shader on them.
  2499. NOTE: Buffers without initial data will have undefined content, e.g.
  2500. do *not* expect the buffer to be zero-initialized!
  2501. ADVANCED TOPIC: Injecting native 3D-API buffers:
  2502. The following struct members allow to inject your own GL, Metal
  2503. or D3D11 buffers into sokol_gfx:
  2504. .gl_buffers[SG_NUM_INFLIGHT_FRAMES]
  2505. .mtl_buffers[SG_NUM_INFLIGHT_FRAMES]
  2506. .d3d11_buffer
  2507. You must still provide all other struct items except the .data item, and
  2508. these must match the creation parameters of the native buffers you provide.
  2509. For sg_buffer_desc.usage.immutable buffers, only provide a single native
  2510. 3D-API buffer, otherwise you need to provide SG_NUM_INFLIGHT_FRAMES buffers
  2511. (only for GL and Metal, not D3D11). Providing multiple buffers for GL and
  2512. Metal is necessary because sokol_gfx will rotate through them when calling
  2513. sg_update_buffer() to prevent lock-stalls.
  2514. Note that it is expected that immutable injected buffer have already been
  2515. initialized with content, and the .content member must be 0!
  2516. Also you need to call sg_reset_state_cache() after calling native 3D-API
  2517. functions, and before calling any sokol_gfx function.
  2518. */
  2519. typedef struct sg_buffer_desc {
  2520. uint32_t _start_canary;
  2521. size_t size;
  2522. sg_buffer_usage usage;
  2523. sg_range data;
  2524. const char* label;
  2525. // optionally inject backend-specific resources
  2526. uint32_t gl_buffers[SG_NUM_INFLIGHT_FRAMES];
  2527. const void* mtl_buffers[SG_NUM_INFLIGHT_FRAMES];
  2528. const void* d3d11_buffer;
  2529. const void* wgpu_buffer;
  2530. uint32_t _end_canary;
  2531. } sg_buffer_desc;
  2532. /*
  2533. sg_image_usage
  2534. Describes how the image object is going to be used:
  2535. .render_attachment (default: false)
  2536. the image object is used as color-, resolve- or depth-stencil-
  2537. attachment in a render pass
  2538. .storage_attachment (default: false)
  2539. the image object is used as storage-attachment in a
  2540. compute pass (to be written to by compute shaders)
  2541. .immutable (default: true)
  2542. the image content cannot be updated from the CPU side
  2543. (but may be updated by the GPU in a render- or compute-pass)
  2544. .dynamic_update (default: false)
  2545. the image content is updated infrequently by the CPU
  2546. .stream_update (default: false)
  2547. the image content is updated each frame by the CPU via
  2548. Note that the usage as texture binding is implicit and always allowed.
  2549. */
  2550. typedef struct sg_image_usage {
  2551. bool render_attachment;
  2552. bool storage_attachment;
  2553. bool immutable;
  2554. bool dynamic_update;
  2555. bool stream_update;
  2556. } sg_image_usage;
  2557. /*
  2558. sg_image_data
  2559. Defines the content of an image through a 2D array of sg_range structs.
  2560. The first array dimension is the cubemap face, and the second array
  2561. dimension the mipmap level.
  2562. */
  2563. typedef struct sg_image_data {
  2564. sg_range subimage[SG_CUBEFACE_NUM][SG_MAX_MIPMAPS];
  2565. } sg_image_data;
  2566. /*
  2567. sg_image_desc
  2568. Creation parameters for sg_image objects, used in the sg_make_image() call.
  2569. The default configuration is:
  2570. .type SG_IMAGETYPE_2D
  2571. .usage .immutable = true
  2572. .width 0 (must be set to >0)
  2573. .height 0 (must be set to >0)
  2574. .num_slices 1 (3D textures: depth; array textures: number of layers)
  2575. .num_mipmaps 1
  2576. .pixel_format SG_PIXELFORMAT_RGBA8 for textures, or sg_desc.environment.defaults.color_format for render targets
  2577. .sample_count 1 for textures, or sg_desc.environment.defaults.sample_count for render targets
  2578. .data an sg_image_data struct to define the initial content
  2579. .label 0 (optional string label for trace hooks)
  2580. Q: Why is the default sample_count for render targets identical with the
  2581. "default sample count" from sg_desc.environment.defaults.sample_count?
  2582. A: So that it matches the default sample count in pipeline objects. Even
  2583. though it is a bit strange/confusing that offscreen render targets by default
  2584. get the same sample count as 'default swapchains', but it's better that
  2585. an offscreen render target created with default parameters matches
  2586. a pipeline object created with default parameters.
  2587. NOTE:
  2588. Regular (non-attachment) images with usage.immutable must be fully initialized by
  2589. providing a valid .data member which points to initialization data.
  2590. Images with usage.render_attachment or usage.storage_attachment must
  2591. *not* be created with initial content. Be aware that the initial
  2592. content of render- and storage-attachment images is undefined.
  2593. ADVANCED TOPIC: Injecting native 3D-API textures:
  2594. The following struct members allow to inject your own GL, Metal or D3D11
  2595. textures into sokol_gfx:
  2596. .gl_textures[SG_NUM_INFLIGHT_FRAMES]
  2597. .mtl_textures[SG_NUM_INFLIGHT_FRAMES]
  2598. .d3d11_texture
  2599. .d3d11_shader_resource_view
  2600. .wgpu_texture
  2601. .wgpu_texture_view
  2602. For GL, you can also specify the texture target or leave it empty to use
  2603. the default texture target for the image type (GL_TEXTURE_2D for
  2604. SG_IMAGETYPE_2D etc)
  2605. For D3D11 and WebGPU, either only provide a texture, or both a texture and
  2606. shader-resource-view / texture-view object. If you want to use access the
  2607. injected texture in a shader you *must* provide a shader-resource-view.
  2608. The same rules apply as for injecting native buffers (see sg_buffer_desc
  2609. documentation for more details).
  2610. */
  2611. typedef struct sg_image_desc {
  2612. uint32_t _start_canary;
  2613. sg_image_type type;
  2614. sg_image_usage usage;
  2615. int width;
  2616. int height;
  2617. int num_slices;
  2618. int num_mipmaps;
  2619. sg_pixel_format pixel_format;
  2620. int sample_count;
  2621. sg_image_data data;
  2622. const char* label;
  2623. // optionally inject backend-specific resources
  2624. uint32_t gl_textures[SG_NUM_INFLIGHT_FRAMES];
  2625. uint32_t gl_texture_target;
  2626. const void* mtl_textures[SG_NUM_INFLIGHT_FRAMES];
  2627. const void* d3d11_texture;
  2628. const void* d3d11_shader_resource_view;
  2629. const void* wgpu_texture;
  2630. const void* wgpu_texture_view;
  2631. uint32_t _end_canary;
  2632. } sg_image_desc;
  2633. /*
  2634. sg_sampler_desc
  2635. Creation parameters for sg_sampler objects, used in the sg_make_sampler() call
  2636. .min_filter: SG_FILTER_NEAREST
  2637. .mag_filter: SG_FILTER_NEAREST
  2638. .mipmap_filter SG_FILTER_NEAREST
  2639. .wrap_u: SG_WRAP_REPEAT
  2640. .wrap_v: SG_WRAP_REPEAT
  2641. .wrap_w: SG_WRAP_REPEAT (only SG_IMAGETYPE_3D)
  2642. .min_lod 0.0f
  2643. .max_lod FLT_MAX
  2644. .border_color SG_BORDERCOLOR_OPAQUE_BLACK
  2645. .compare SG_COMPAREFUNC_NEVER
  2646. .max_anisotropy 1 (must be 1..16)
  2647. */
  2648. typedef struct sg_sampler_desc {
  2649. uint32_t _start_canary;
  2650. sg_filter min_filter;
  2651. sg_filter mag_filter;
  2652. sg_filter mipmap_filter;
  2653. sg_wrap wrap_u;
  2654. sg_wrap wrap_v;
  2655. sg_wrap wrap_w;
  2656. float min_lod;
  2657. float max_lod;
  2658. sg_border_color border_color;
  2659. sg_compare_func compare;
  2660. uint32_t max_anisotropy;
  2661. const char* label;
  2662. // optionally inject backend-specific resources
  2663. uint32_t gl_sampler;
  2664. const void* mtl_sampler;
  2665. const void* d3d11_sampler;
  2666. const void* wgpu_sampler;
  2667. uint32_t _end_canary;
  2668. } sg_sampler_desc;
  2669. /*
  2670. sg_shader_desc
  2671. Used as parameter of sg_make_shader() to create a shader object which
  2672. communicates shader source or bytecode and shader interface
  2673. reflection information to sokol-gfx.
  2674. If you use sokol-shdc you can ignore the following information since
  2675. the sg_shader_desc struct will be code-generated.
  2676. Otherwise you need to provide the following information to the
  2677. sg_make_shader() call:
  2678. - a vertex- and fragment-shader function:
  2679. - the shader source or bytecode
  2680. - an optional entry point name
  2681. - for D3D11: an optional compile target when source code is provided
  2682. (the defaults are "vs_4_0" and "ps_4_0")
  2683. - ...or alternatively, a compute function:
  2684. - the shader source or bytecode
  2685. - an optional entry point name
  2686. - for D3D11: an optional compile target when source code is provided
  2687. (the default is "cs_5_0")
  2688. - vertex attributes required by some backends (not for compute shaders):
  2689. - the vertex attribute base type (undefined, float, signed int, unsigned int),
  2690. this information is only used in the validation layer to check that the
  2691. pipeline object vertex formats are compatible with the input vertex attribute
  2692. type used in the vertex shader. NOTE that the default base type
  2693. 'undefined' skips the validation layer check.
  2694. - for the GL backend: optional vertex attribute names used for name lookup
  2695. - for the D3D11 backend: semantic names and indices
  2696. - only for compute shaders on the Metal backend:
  2697. - the workgroup size aka 'threads per thread-group'
  2698. In other 3D APIs this is declared in the shader code:
  2699. - GLSL: `layout(local_size_x=x, local_size_y=y, local_size_y=z) in;`
  2700. - HLSL: `[numthreads(x, y, z)]`
  2701. - WGSL: `@workgroup_size(x, y, z)`
  2702. ...but in Metal the workgroup size is declared on the CPU side
  2703. - reflection information for each uniform block binding used by the shader:
  2704. - the shader stage the uniform block appears in (SG_SHADERSTAGE_*)
  2705. - the size in bytes of the uniform block
  2706. - backend-specific bindslots:
  2707. - HLSL: the constant buffer register `register(b0..7)`
  2708. - MSL: the buffer attribute `[[buffer(0..7)]]`
  2709. - WGSL: the binding in `@group(0) @binding(0..15)`
  2710. - GLSL only: a description of the uniform block interior
  2711. - the memory layout standard (SG_UNIFORMLAYOUT_*)
  2712. - for each member in the uniform block:
  2713. - the member type (SG_UNIFORM_*)
  2714. - if the member is an array, the array count
  2715. - the member name
  2716. - reflection information for each texture binding used by the shader:
  2717. - the shader stage the texture appears in (SG_SHADERSTAGE_*)
  2718. - the image type (SG_IMAGETYPE_*)
  2719. - the image-sample type (SG_IMAGESAMPLETYPE_*)
  2720. - whether the texture is multisampled
  2721. - backend specific bindslots:
  2722. - HLSL: the texture register `register(t0..23)`
  2723. - MSL: the texture attribute `[[texture(0..19)]]`
  2724. - WGSL: the binding in `@group(1) @binding(0..127)`
  2725. - reflection information for each sampler used by the shader:
  2726. - the shader stage the sampler appears in (SG_SHADERSTAGE_*)
  2727. - the sampler type (SG_SAMPLERTYPE_*)
  2728. - backend specific bindslots:
  2729. - HLSL: the sampler register `register(s0..15)`
  2730. - MSL: the sampler attribute `[[sampler(0..15)]]`
  2731. - WGSL: the binding in `@group(0) @binding(0..127)`
  2732. - reflection information for each storage buffer binding used by the shader:
  2733. - the shader stage the storage buffer appears in (SG_SHADERSTAGE_*)
  2734. - whether the storage buffer is readonly
  2735. - backend specific bindslots:
  2736. - HLSL:
  2737. - for readonly storage buffer bindings: `register(t0..23)`
  2738. - for read/write storage buffer bindings: `register(u0..11)`
  2739. - MSL: the buffer attribute `[[buffer(8..15)]]`
  2740. - WGSL: the binding in `@group(1) @binding(0..127)`
  2741. - GL: the binding in `layout(binding=0..7)`
  2742. - reflection information for each storage image binding used by the shader:
  2743. - the shader stage (*must* be SG_SHADERSTAGE_COMPUTE)
  2744. - whether the storage image is writeonly or readwrite (for readonly
  2745. access use a regular texture binding instead)
  2746. - the image type expected by the shader (SG_IMAGETYPE_*)
  2747. - the access pixel format expected by the shader (SG_PIXELFORMAT_*),
  2748. note that only a subset of pixel formats is allowed for storage image
  2749. bindings
  2750. - backend specific bindslots:
  2751. - HLSL: the UAV register `register(u0..u11)`
  2752. - MSL: the texture attribute `[[texture(0..19)]]`
  2753. - WGSL: the binding in `@group(2) @binding(0..3)`
  2754. - GLSL: the binding in `layout(binding=0..3, [access_format])`
  2755. - reflection information for each combined image-sampler object
  2756. used by the shader:
  2757. - the shader stage (SG_SHADERSTAGE_*)
  2758. - the texture's array index in the sg_shader_desc.images[] array
  2759. - the sampler's array index in the sg_shader_desc.samplers[] array
  2760. - GLSL only: the name of the combined image-sampler object
  2761. The number and order of items in the sg_shader_desc.attrs[]
  2762. array corresponds to the items in sg_pipeline_desc.layout.attrs.
  2763. - sg_shader_desc.attrs[N] => sg_pipeline_desc.layout.attrs[N]
  2764. NOTE that vertex attribute indices currently cannot have gaps.
  2765. The items index in the sg_shader_desc.uniform_blocks[] array corresponds
  2766. to the ub_slot arg in sg_apply_uniforms():
  2767. - sg_shader_desc.uniform_blocks[N] => sg_apply_uniforms(N, ...)
  2768. The items in the shader_desc images, samplers and storage_buffers
  2769. arrays correspond to the same array items in the sg_bindings struct:
  2770. - sg_shader_desc.images[N] => sg_bindings.images[N]
  2771. - sg_shader_desc.samplers[N] => sg_bindings.samplers[N]
  2772. - sg_shader_desc.storage_buffers[N] => sg_bindings.storage_buffers[N]
  2773. For all GL backends, shader source-code must be provided. For D3D11 and Metal,
  2774. either shader source-code or byte-code can be provided.
  2775. NOTE that the uniform block, image, sampler, storage_buffer and
  2776. storage_image arrays may have gaps. This allows to use the same sg_bindings
  2777. struct for different related shader variants.
  2778. For D3D11, if source code is provided, the d3dcompiler_47.dll will be loaded
  2779. on demand. If this fails, shader creation will fail. When compiling HLSL
  2780. source code, you can provide an optional target string via
  2781. sg_shader_stage_desc.d3d11_target, the default target is "vs_4_0" for the
  2782. vertex shader stage and "ps_4_0" for the pixel shader stage.
  2783. */
  2784. typedef enum sg_shader_stage {
  2785. SG_SHADERSTAGE_NONE,
  2786. SG_SHADERSTAGE_VERTEX,
  2787. SG_SHADERSTAGE_FRAGMENT,
  2788. SG_SHADERSTAGE_COMPUTE,
  2789. _SG_SHADERSTAGE_FORCE_U32 = 0x7FFFFFFF,
  2790. } sg_shader_stage;
  2791. typedef struct sg_shader_function {
  2792. const char* source;
  2793. sg_range bytecode;
  2794. const char* entry;
  2795. const char* d3d11_target; // default: "vs_4_0" or "ps_4_0"
  2796. } sg_shader_function;
  2797. typedef enum sg_shader_attr_base_type {
  2798. SG_SHADERATTRBASETYPE_UNDEFINED,
  2799. SG_SHADERATTRBASETYPE_FLOAT,
  2800. SG_SHADERATTRBASETYPE_SINT,
  2801. SG_SHADERATTRBASETYPE_UINT,
  2802. _SG_SHADERATTRBASETYPE_FORCE_U32 = 0x7FFFFFFF,
  2803. } sg_shader_attr_base_type;
  2804. typedef struct sg_shader_vertex_attr {
  2805. sg_shader_attr_base_type base_type; // default: UNDEFINED (disables validation)
  2806. const char* glsl_name; // [optional] GLSL attribute name
  2807. const char* hlsl_sem_name; // HLSL semantic name
  2808. uint8_t hlsl_sem_index; // HLSL semantic index
  2809. } sg_shader_vertex_attr;
  2810. typedef struct sg_glsl_shader_uniform {
  2811. sg_uniform_type type;
  2812. uint16_t array_count; // 0 or 1 for scalars, >1 for arrays
  2813. const char* glsl_name; // glsl name binding is required on GL 4.1 and WebGL2
  2814. } sg_glsl_shader_uniform;
  2815. typedef struct sg_shader_uniform_block {
  2816. sg_shader_stage stage;
  2817. uint32_t size;
  2818. uint8_t hlsl_register_b_n; // HLSL register(bn)
  2819. uint8_t msl_buffer_n; // MSL [[buffer(n)]]
  2820. uint8_t wgsl_group0_binding_n; // WGSL @group(0) @binding(n)
  2821. sg_uniform_layout layout;
  2822. sg_glsl_shader_uniform glsl_uniforms[SG_MAX_UNIFORMBLOCK_MEMBERS];
  2823. } sg_shader_uniform_block;
  2824. typedef struct sg_shader_image {
  2825. sg_shader_stage stage;
  2826. sg_image_type image_type;
  2827. sg_image_sample_type sample_type;
  2828. bool multisampled;
  2829. uint8_t hlsl_register_t_n; // HLSL register(tn) bind slot
  2830. uint8_t msl_texture_n; // MSL [[texture(n)]] bind slot
  2831. uint8_t wgsl_group1_binding_n; // WGSL @group(1) @binding(n) bind slot
  2832. } sg_shader_image;
  2833. typedef struct sg_shader_sampler {
  2834. sg_shader_stage stage;
  2835. sg_sampler_type sampler_type;
  2836. uint8_t hlsl_register_s_n; // HLSL register(sn) bind slot
  2837. uint8_t msl_sampler_n; // MSL [[sampler(n)]] bind slot
  2838. uint8_t wgsl_group1_binding_n; // WGSL @group(1) @binding(n) bind slot
  2839. } sg_shader_sampler;
  2840. typedef struct sg_shader_storage_buffer {
  2841. sg_shader_stage stage;
  2842. bool readonly;
  2843. uint8_t hlsl_register_t_n; // HLSL register(tn) bind slot (for readonly access)
  2844. uint8_t hlsl_register_u_n; // HLSL register(un) bind slot (for read/write access)
  2845. uint8_t msl_buffer_n; // MSL [[buffer(n)]] bind slot
  2846. uint8_t wgsl_group1_binding_n; // WGSL @group(1) @binding(n) bind slot
  2847. uint8_t glsl_binding_n; // GLSL layout(binding=n)
  2848. } sg_shader_storage_buffer;
  2849. typedef struct sg_shader_storage_image {
  2850. sg_shader_stage stage; // must be NONE or COMPUTE
  2851. sg_image_type image_type;
  2852. sg_pixel_format access_format; // shader-access pixel format
  2853. bool writeonly; // false means read/write access
  2854. uint8_t hlsl_register_u_n; // HLSL register(un) bind slot
  2855. uint8_t msl_texture_n; // MSL [[texture(n)]] bind slot
  2856. uint8_t wgsl_group2_binding_n; // WGSL @group(2) @binding(n) bind slot
  2857. uint8_t glsl_binding_n; // GLSL layout(binding=n)
  2858. } sg_shader_storage_image;
  2859. typedef struct sg_shader_image_sampler_pair {
  2860. sg_shader_stage stage;
  2861. uint8_t image_slot;
  2862. uint8_t sampler_slot;
  2863. const char* glsl_name; // glsl name binding required because of GL 4.1 and WebGL2
  2864. } sg_shader_image_sampler_pair;
  2865. typedef struct sg_mtl_shader_threads_per_threadgroup {
  2866. int x, y, z;
  2867. } sg_mtl_shader_threads_per_threadgroup;
  2868. typedef struct sg_shader_desc {
  2869. uint32_t _start_canary;
  2870. sg_shader_function vertex_func;
  2871. sg_shader_function fragment_func;
  2872. sg_shader_function compute_func;
  2873. sg_shader_vertex_attr attrs[SG_MAX_VERTEX_ATTRIBUTES];
  2874. sg_shader_uniform_block uniform_blocks[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  2875. sg_shader_storage_buffer storage_buffers[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  2876. sg_shader_image images[SG_MAX_IMAGE_BINDSLOTS];
  2877. sg_shader_sampler samplers[SG_MAX_SAMPLER_BINDSLOTS];
  2878. sg_shader_image_sampler_pair image_sampler_pairs[SG_MAX_IMAGE_SAMPLER_PAIRS];
  2879. sg_shader_storage_image storage_images[SG_MAX_STORAGE_ATTACHMENTS];
  2880. sg_mtl_shader_threads_per_threadgroup mtl_threads_per_threadgroup;
  2881. const char* label;
  2882. uint32_t _end_canary;
  2883. } sg_shader_desc;
  2884. /*
  2885. sg_pipeline_desc
  2886. The sg_pipeline_desc struct defines all creation parameters for an
  2887. sg_pipeline object, used as argument to the sg_make_pipeline() function:
  2888. Pipeline objects come in two flavours:
  2889. - render pipelines for use in render passes
  2890. - compute pipelines for use in compute passes
  2891. A compute pipeline only requires a compute shader object but no
  2892. 'render state', while a render pipeline requires a vertex/fragment shader
  2893. object and additional render state declarations:
  2894. - the vertex layout for all input vertex buffers
  2895. - a shader object
  2896. - the 3D primitive type (points, lines, triangles, ...)
  2897. - the index type (none, 16- or 32-bit)
  2898. - all the fixed-function-pipeline state (depth-, stencil-, blend-state, etc...)
  2899. If the vertex data has no gaps between vertex components, you can omit
  2900. the .layout.buffers[].stride and layout.attrs[].offset items (leave them
  2901. default-initialized to 0), sokol-gfx will then compute the offsets and
  2902. strides from the vertex component formats (.layout.attrs[].format).
  2903. Please note that ALL vertex attribute offsets must be 0 in order for the
  2904. automatic offset computation to kick in.
  2905. Note that if you use vertex-pulling from storage buffers instead of
  2906. fixed-function vertex input you can simply omit the entire nested .layout
  2907. struct.
  2908. The default configuration is as follows:
  2909. .compute: false (must be set to true for a compute pipeline)
  2910. .shader: 0 (must be initialized with a valid sg_shader id!)
  2911. .layout:
  2912. .buffers[]: vertex buffer layouts
  2913. .stride: 0 (if no stride is given it will be computed)
  2914. .step_func SG_VERTEXSTEP_PER_VERTEX
  2915. .step_rate 1
  2916. .attrs[]: vertex attribute declarations
  2917. .buffer_index 0 the vertex buffer bind slot
  2918. .offset 0 (offsets can be omitted if the vertex layout has no gaps)
  2919. .format SG_VERTEXFORMAT_INVALID (must be initialized!)
  2920. .depth:
  2921. .pixel_format: sg_desc.context.depth_format
  2922. .compare: SG_COMPAREFUNC_ALWAYS
  2923. .write_enabled: false
  2924. .bias: 0.0f
  2925. .bias_slope_scale: 0.0f
  2926. .bias_clamp: 0.0f
  2927. .stencil:
  2928. .enabled: false
  2929. .front/back:
  2930. .compare: SG_COMPAREFUNC_ALWAYS
  2931. .fail_op: SG_STENCILOP_KEEP
  2932. .depth_fail_op: SG_STENCILOP_KEEP
  2933. .pass_op: SG_STENCILOP_KEEP
  2934. .read_mask: 0
  2935. .write_mask: 0
  2936. .ref: 0
  2937. .color_count 1
  2938. .colors[0..color_count]
  2939. .pixel_format sg_desc.context.color_format
  2940. .write_mask: SG_COLORMASK_RGBA
  2941. .blend:
  2942. .enabled: false
  2943. .src_factor_rgb: SG_BLENDFACTOR_ONE
  2944. .dst_factor_rgb: SG_BLENDFACTOR_ZERO
  2945. .op_rgb: SG_BLENDOP_ADD
  2946. .src_factor_alpha: SG_BLENDFACTOR_ONE
  2947. .dst_factor_alpha: SG_BLENDFACTOR_ZERO
  2948. .op_alpha: SG_BLENDOP_ADD
  2949. .primitive_type: SG_PRIMITIVETYPE_TRIANGLES
  2950. .index_type: SG_INDEXTYPE_NONE
  2951. .cull_mode: SG_CULLMODE_NONE
  2952. .face_winding: SG_FACEWINDING_CW
  2953. .sample_count: sg_desc.context.sample_count
  2954. .blend_color: (sg_color) { 0.0f, 0.0f, 0.0f, 0.0f }
  2955. .alpha_to_coverage_enabled: false
  2956. .label 0 (optional string label for trace hooks)
  2957. */
  2958. typedef struct sg_vertex_buffer_layout_state {
  2959. int stride;
  2960. sg_vertex_step step_func;
  2961. int step_rate;
  2962. } sg_vertex_buffer_layout_state;
  2963. typedef struct sg_vertex_attr_state {
  2964. int buffer_index;
  2965. int offset;
  2966. sg_vertex_format format;
  2967. } sg_vertex_attr_state;
  2968. typedef struct sg_vertex_layout_state {
  2969. sg_vertex_buffer_layout_state buffers[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  2970. sg_vertex_attr_state attrs[SG_MAX_VERTEX_ATTRIBUTES];
  2971. } sg_vertex_layout_state;
  2972. typedef struct sg_stencil_face_state {
  2973. sg_compare_func compare;
  2974. sg_stencil_op fail_op;
  2975. sg_stencil_op depth_fail_op;
  2976. sg_stencil_op pass_op;
  2977. } sg_stencil_face_state;
  2978. typedef struct sg_stencil_state {
  2979. bool enabled;
  2980. sg_stencil_face_state front;
  2981. sg_stencil_face_state back;
  2982. uint8_t read_mask;
  2983. uint8_t write_mask;
  2984. uint8_t ref;
  2985. } sg_stencil_state;
  2986. typedef struct sg_depth_state {
  2987. sg_pixel_format pixel_format;
  2988. sg_compare_func compare;
  2989. bool write_enabled;
  2990. float bias;
  2991. float bias_slope_scale;
  2992. float bias_clamp;
  2993. } sg_depth_state;
  2994. typedef struct sg_blend_state {
  2995. bool enabled;
  2996. sg_blend_factor src_factor_rgb;
  2997. sg_blend_factor dst_factor_rgb;
  2998. sg_blend_op op_rgb;
  2999. sg_blend_factor src_factor_alpha;
  3000. sg_blend_factor dst_factor_alpha;
  3001. sg_blend_op op_alpha;
  3002. } sg_blend_state;
  3003. typedef struct sg_color_target_state {
  3004. sg_pixel_format pixel_format;
  3005. sg_color_mask write_mask;
  3006. sg_blend_state blend;
  3007. } sg_color_target_state;
  3008. typedef struct sg_pipeline_desc {
  3009. uint32_t _start_canary;
  3010. bool compute;
  3011. sg_shader shader;
  3012. sg_vertex_layout_state layout;
  3013. sg_depth_state depth;
  3014. sg_stencil_state stencil;
  3015. int color_count;
  3016. sg_color_target_state colors[SG_MAX_COLOR_ATTACHMENTS];
  3017. sg_primitive_type primitive_type;
  3018. sg_index_type index_type;
  3019. sg_cull_mode cull_mode;
  3020. sg_face_winding face_winding;
  3021. int sample_count;
  3022. sg_color blend_color;
  3023. bool alpha_to_coverage_enabled;
  3024. const char* label;
  3025. uint32_t _end_canary;
  3026. } sg_pipeline_desc;
  3027. /*
  3028. sg_attachments_desc
  3029. Creation parameters for an sg_attachments object, used as argument to the
  3030. sg_make_attachments() function.
  3031. An attachments object bundles either bundles 'render attachments' for
  3032. a render pass, or 'storage attachments' for a compute pass which writes
  3033. to storage images.
  3034. Render attachments are:
  3035. - 0..4 color attachment images
  3036. - 0..4 msaa-resolve attachment images
  3037. - 0 or one depth-stencil attachment image
  3038. Note that all types of render attachment images must be created with
  3039. `sg_image_desc.usage.render_attachment = true`. At least one color-attachment
  3040. or depth-stencil-attachment image must be provided in a render pass
  3041. (only providing a depth-stencil-attachment is useful for depth-only passes).
  3042. Alternatively provide 1..4 storage attachment images which must be created
  3043. with `sg_image_desc.usage.storage_attachment = true`.
  3044. An sg_attachments object cannot have both render- and storage-attachments.
  3045. Each attachment definition consists of an image object, and two additional indices
  3046. describing which subimage the pass will render into: one mipmap index, and if the image
  3047. is a cubemap, array-texture or 3D-texture, the face-index, array-layer or
  3048. depth-slice.
  3049. All attachments must have the same width and height.
  3050. All color attachments and the depth-stencil attachment must have the
  3051. same sample count.
  3052. If a resolve attachment is set, an MSAA-resolve operation from the
  3053. associated color attachment image into the resolve attachment image will take
  3054. place in the sg_end_pass() function. In this case, the color attachment
  3055. must have a (sample_count>1), and the resolve attachment a
  3056. (sample_count==1). The resolve attachment also must have the same pixel
  3057. format as the color attachment.
  3058. NOTE that MSAA depth-stencil attachments cannot be msaa-resolved!
  3059. */
  3060. typedef struct sg_attachment_desc {
  3061. sg_image image;
  3062. int mip_level;
  3063. int slice; // cube texture: face; array texture: layer; 3D texture: slice
  3064. } sg_attachment_desc;
  3065. typedef struct sg_attachments_desc {
  3066. uint32_t _start_canary;
  3067. sg_attachment_desc colors[SG_MAX_COLOR_ATTACHMENTS];
  3068. sg_attachment_desc resolves[SG_MAX_COLOR_ATTACHMENTS];
  3069. sg_attachment_desc depth_stencil;
  3070. sg_attachment_desc storages[SG_MAX_STORAGE_ATTACHMENTS];
  3071. const char* label;
  3072. uint32_t _end_canary;
  3073. } sg_attachments_desc;
  3074. /*
  3075. sg_trace_hooks
  3076. Installable callback functions to keep track of the sokol-gfx calls,
  3077. this is useful for debugging, or keeping track of resource creation
  3078. and destruction.
  3079. Trace hooks are installed with sg_install_trace_hooks(), this returns
  3080. another sg_trace_hooks struct with the previous set of
  3081. trace hook function pointers. These should be invoked by the
  3082. new trace hooks to form a proper call chain.
  3083. */
  3084. typedef struct sg_trace_hooks {
  3085. void* user_data;
  3086. void (*reset_state_cache)(void* user_data);
  3087. void (*make_buffer)(const sg_buffer_desc* desc, sg_buffer result, void* user_data);
  3088. void (*make_image)(const sg_image_desc* desc, sg_image result, void* user_data);
  3089. void (*make_sampler)(const sg_sampler_desc* desc, sg_sampler result, void* user_data);
  3090. void (*make_shader)(const sg_shader_desc* desc, sg_shader result, void* user_data);
  3091. void (*make_pipeline)(const sg_pipeline_desc* desc, sg_pipeline result, void* user_data);
  3092. void (*make_attachments)(const sg_attachments_desc* desc, sg_attachments result, void* user_data);
  3093. void (*destroy_buffer)(sg_buffer buf, void* user_data);
  3094. void (*destroy_image)(sg_image img, void* user_data);
  3095. void (*destroy_sampler)(sg_sampler smp, void* user_data);
  3096. void (*destroy_shader)(sg_shader shd, void* user_data);
  3097. void (*destroy_pipeline)(sg_pipeline pip, void* user_data);
  3098. void (*destroy_attachments)(sg_attachments atts, void* user_data);
  3099. void (*update_buffer)(sg_buffer buf, const sg_range* data, void* user_data);
  3100. void (*update_image)(sg_image img, const sg_image_data* data, void* user_data);
  3101. void (*append_buffer)(sg_buffer buf, const sg_range* data, int result, void* user_data);
  3102. void (*begin_pass)(const sg_pass* pass, void* user_data);
  3103. void (*apply_viewport)(int x, int y, int width, int height, bool origin_top_left, void* user_data);
  3104. void (*apply_scissor_rect)(int x, int y, int width, int height, bool origin_top_left, void* user_data);
  3105. void (*apply_pipeline)(sg_pipeline pip, void* user_data);
  3106. void (*apply_bindings)(const sg_bindings* bindings, void* user_data);
  3107. void (*apply_uniforms)(int ub_index, const sg_range* data, void* user_data);
  3108. void (*draw)(int base_element, int num_elements, int num_instances, void* user_data);
  3109. void (*dispatch)(int num_groups_x, int num_groups_y, int num_groups_z, void* user_data);
  3110. void (*end_pass)(void* user_data);
  3111. void (*commit)(void* user_data);
  3112. void (*alloc_buffer)(sg_buffer result, void* user_data);
  3113. void (*alloc_image)(sg_image result, void* user_data);
  3114. void (*alloc_sampler)(sg_sampler result, void* user_data);
  3115. void (*alloc_shader)(sg_shader result, void* user_data);
  3116. void (*alloc_pipeline)(sg_pipeline result, void* user_data);
  3117. void (*alloc_attachments)(sg_attachments result, void* user_data);
  3118. void (*dealloc_buffer)(sg_buffer buf_id, void* user_data);
  3119. void (*dealloc_image)(sg_image img_id, void* user_data);
  3120. void (*dealloc_sampler)(sg_sampler smp_id, void* user_data);
  3121. void (*dealloc_shader)(sg_shader shd_id, void* user_data);
  3122. void (*dealloc_pipeline)(sg_pipeline pip_id, void* user_data);
  3123. void (*dealloc_attachments)(sg_attachments atts_id, void* user_data);
  3124. void (*init_buffer)(sg_buffer buf_id, const sg_buffer_desc* desc, void* user_data);
  3125. void (*init_image)(sg_image img_id, const sg_image_desc* desc, void* user_data);
  3126. void (*init_sampler)(sg_sampler smp_id, const sg_sampler_desc* desc, void* user_data);
  3127. void (*init_shader)(sg_shader shd_id, const sg_shader_desc* desc, void* user_data);
  3128. void (*init_pipeline)(sg_pipeline pip_id, const sg_pipeline_desc* desc, void* user_data);
  3129. void (*init_attachments)(sg_attachments atts_id, const sg_attachments_desc* desc, void* user_data);
  3130. void (*uninit_buffer)(sg_buffer buf_id, void* user_data);
  3131. void (*uninit_image)(sg_image img_id, void* user_data);
  3132. void (*uninit_sampler)(sg_sampler smp_id, void* user_data);
  3133. void (*uninit_shader)(sg_shader shd_id, void* user_data);
  3134. void (*uninit_pipeline)(sg_pipeline pip_id, void* user_data);
  3135. void (*uninit_attachments)(sg_attachments atts_id, void* user_data);
  3136. void (*fail_buffer)(sg_buffer buf_id, void* user_data);
  3137. void (*fail_image)(sg_image img_id, void* user_data);
  3138. void (*fail_sampler)(sg_sampler smp_id, void* user_data);
  3139. void (*fail_shader)(sg_shader shd_id, void* user_data);
  3140. void (*fail_pipeline)(sg_pipeline pip_id, void* user_data);
  3141. void (*fail_attachments)(sg_attachments atts_id, void* user_data);
  3142. void (*push_debug_group)(const char* name, void* user_data);
  3143. void (*pop_debug_group)(void* user_data);
  3144. } sg_trace_hooks;
  3145. /*
  3146. sg_buffer_info
  3147. sg_image_info
  3148. sg_sampler_info
  3149. sg_shader_info
  3150. sg_pipeline_info
  3151. sg_attachments_info
  3152. These structs contain various internal resource attributes which
  3153. might be useful for debug-inspection. Please don't rely on the
  3154. actual content of those structs too much, as they are quite closely
  3155. tied to sokol_gfx.h internals and may change more frequently than
  3156. the other public API elements.
  3157. The *_info structs are used as the return values of the following functions:
  3158. sg_query_buffer_info()
  3159. sg_query_image_info()
  3160. sg_query_sampler_info()
  3161. sg_query_shader_info()
  3162. sg_query_pipeline_info()
  3163. sg_query_attachments_info()
  3164. */
  3165. typedef struct sg_slot_info {
  3166. sg_resource_state state; // the current state of this resource slot
  3167. uint32_t res_id; // type-neutral resource if (e.g. sg_buffer.id)
  3168. uint32_t uninit_count;
  3169. } sg_slot_info;
  3170. typedef struct sg_buffer_info {
  3171. sg_slot_info slot; // resource pool slot info
  3172. uint32_t update_frame_index; // frame index of last sg_update_buffer()
  3173. uint32_t append_frame_index; // frame index of last sg_append_buffer()
  3174. int append_pos; // current position in buffer for sg_append_buffer()
  3175. bool append_overflow; // is buffer in overflow state (due to sg_append_buffer)
  3176. int num_slots; // number of renaming-slots for dynamically updated buffers
  3177. int active_slot; // currently active write-slot for dynamically updated buffers
  3178. } sg_buffer_info;
  3179. typedef struct sg_image_info {
  3180. sg_slot_info slot; // resource pool slot info
  3181. uint32_t upd_frame_index; // frame index of last sg_update_image()
  3182. int num_slots; // number of renaming-slots for dynamically updated images
  3183. int active_slot; // currently active write-slot for dynamically updated images
  3184. } sg_image_info;
  3185. typedef struct sg_sampler_info {
  3186. sg_slot_info slot; // resource pool slot info
  3187. } sg_sampler_info;
  3188. typedef struct sg_shader_info {
  3189. sg_slot_info slot; // resource pool slot info
  3190. } sg_shader_info;
  3191. typedef struct sg_pipeline_info {
  3192. sg_slot_info slot; // resource pool slot info
  3193. } sg_pipeline_info;
  3194. typedef struct sg_attachments_info {
  3195. sg_slot_info slot; // resource pool slot info
  3196. } sg_attachments_info;
  3197. /*
  3198. sg_frame_stats
  3199. Allows to track generic and backend-specific stats about a
  3200. render frame. Obtained by calling sg_query_frame_stats(). The returned
  3201. struct contains information about the *previous* frame.
  3202. */
  3203. typedef struct sg_frame_stats_gl {
  3204. uint32_t num_bind_buffer;
  3205. uint32_t num_active_texture;
  3206. uint32_t num_bind_texture;
  3207. uint32_t num_bind_sampler;
  3208. uint32_t num_use_program;
  3209. uint32_t num_render_state;
  3210. uint32_t num_vertex_attrib_pointer;
  3211. uint32_t num_vertex_attrib_divisor;
  3212. uint32_t num_enable_vertex_attrib_array;
  3213. uint32_t num_disable_vertex_attrib_array;
  3214. uint32_t num_uniform;
  3215. uint32_t num_memory_barriers;
  3216. } sg_frame_stats_gl;
  3217. typedef struct sg_frame_stats_d3d11_pass {
  3218. uint32_t num_om_set_render_targets;
  3219. uint32_t num_clear_render_target_view;
  3220. uint32_t num_clear_depth_stencil_view;
  3221. uint32_t num_resolve_subresource;
  3222. } sg_frame_stats_d3d11_pass;
  3223. typedef struct sg_frame_stats_d3d11_pipeline {
  3224. uint32_t num_rs_set_state;
  3225. uint32_t num_om_set_depth_stencil_state;
  3226. uint32_t num_om_set_blend_state;
  3227. uint32_t num_ia_set_primitive_topology;
  3228. uint32_t num_ia_set_input_layout;
  3229. uint32_t num_vs_set_shader;
  3230. uint32_t num_vs_set_constant_buffers;
  3231. uint32_t num_ps_set_shader;
  3232. uint32_t num_ps_set_constant_buffers;
  3233. uint32_t num_cs_set_shader;
  3234. uint32_t num_cs_set_constant_buffers;
  3235. } sg_frame_stats_d3d11_pipeline;
  3236. typedef struct sg_frame_stats_d3d11_bindings {
  3237. uint32_t num_ia_set_vertex_buffers;
  3238. uint32_t num_ia_set_index_buffer;
  3239. uint32_t num_vs_set_shader_resources;
  3240. uint32_t num_vs_set_samplers;
  3241. uint32_t num_ps_set_shader_resources;
  3242. uint32_t num_ps_set_samplers;
  3243. uint32_t num_cs_set_shader_resources;
  3244. uint32_t num_cs_set_samplers;
  3245. uint32_t num_cs_set_unordered_access_views;
  3246. } sg_frame_stats_d3d11_bindings;
  3247. typedef struct sg_frame_stats_d3d11_uniforms {
  3248. uint32_t num_update_subresource;
  3249. } sg_frame_stats_d3d11_uniforms;
  3250. typedef struct sg_frame_stats_d3d11_draw {
  3251. uint32_t num_draw_indexed_instanced;
  3252. uint32_t num_draw_indexed;
  3253. uint32_t num_draw_instanced;
  3254. uint32_t num_draw;
  3255. } sg_frame_stats_d3d11_draw;
  3256. typedef struct sg_frame_stats_d3d11 {
  3257. sg_frame_stats_d3d11_pass pass;
  3258. sg_frame_stats_d3d11_pipeline pipeline;
  3259. sg_frame_stats_d3d11_bindings bindings;
  3260. sg_frame_stats_d3d11_uniforms uniforms;
  3261. sg_frame_stats_d3d11_draw draw;
  3262. uint32_t num_map;
  3263. uint32_t num_unmap;
  3264. } sg_frame_stats_d3d11;
  3265. typedef struct sg_frame_stats_metal_idpool {
  3266. uint32_t num_added;
  3267. uint32_t num_released;
  3268. uint32_t num_garbage_collected;
  3269. } sg_frame_stats_metal_idpool;
  3270. typedef struct sg_frame_stats_metal_pipeline {
  3271. uint32_t num_set_blend_color;
  3272. uint32_t num_set_cull_mode;
  3273. uint32_t num_set_front_facing_winding;
  3274. uint32_t num_set_stencil_reference_value;
  3275. uint32_t num_set_depth_bias;
  3276. uint32_t num_set_render_pipeline_state;
  3277. uint32_t num_set_depth_stencil_state;
  3278. } sg_frame_stats_metal_pipeline;
  3279. typedef struct sg_frame_stats_metal_bindings {
  3280. uint32_t num_set_vertex_buffer;
  3281. uint32_t num_set_vertex_texture;
  3282. uint32_t num_set_vertex_sampler_state;
  3283. uint32_t num_set_fragment_buffer;
  3284. uint32_t num_set_fragment_texture;
  3285. uint32_t num_set_fragment_sampler_state;
  3286. uint32_t num_set_compute_buffer;
  3287. uint32_t num_set_compute_texture;
  3288. uint32_t num_set_compute_sampler_state;
  3289. } sg_frame_stats_metal_bindings;
  3290. typedef struct sg_frame_stats_metal_uniforms {
  3291. uint32_t num_set_vertex_buffer_offset;
  3292. uint32_t num_set_fragment_buffer_offset;
  3293. uint32_t num_set_compute_buffer_offset;
  3294. } sg_frame_stats_metal_uniforms;
  3295. typedef struct sg_frame_stats_metal {
  3296. sg_frame_stats_metal_idpool idpool;
  3297. sg_frame_stats_metal_pipeline pipeline;
  3298. sg_frame_stats_metal_bindings bindings;
  3299. sg_frame_stats_metal_uniforms uniforms;
  3300. } sg_frame_stats_metal;
  3301. typedef struct sg_frame_stats_wgpu_uniforms {
  3302. uint32_t num_set_bindgroup;
  3303. uint32_t size_write_buffer;
  3304. } sg_frame_stats_wgpu_uniforms;
  3305. typedef struct sg_frame_stats_wgpu_bindings {
  3306. uint32_t num_set_vertex_buffer;
  3307. uint32_t num_skip_redundant_vertex_buffer;
  3308. uint32_t num_set_index_buffer;
  3309. uint32_t num_skip_redundant_index_buffer;
  3310. uint32_t num_create_bindgroup;
  3311. uint32_t num_discard_bindgroup;
  3312. uint32_t num_set_bindgroup;
  3313. uint32_t num_skip_redundant_bindgroup;
  3314. uint32_t num_bindgroup_cache_hits;
  3315. uint32_t num_bindgroup_cache_misses;
  3316. uint32_t num_bindgroup_cache_collisions;
  3317. uint32_t num_bindgroup_cache_invalidates;
  3318. uint32_t num_bindgroup_cache_hash_vs_key_mismatch;
  3319. } sg_frame_stats_wgpu_bindings;
  3320. typedef struct sg_frame_stats_wgpu {
  3321. sg_frame_stats_wgpu_uniforms uniforms;
  3322. sg_frame_stats_wgpu_bindings bindings;
  3323. } sg_frame_stats_wgpu;
  3324. typedef struct sg_frame_stats {
  3325. uint32_t frame_index; // current frame counter, starts at 0
  3326. uint32_t num_passes;
  3327. uint32_t num_apply_viewport;
  3328. uint32_t num_apply_scissor_rect;
  3329. uint32_t num_apply_pipeline;
  3330. uint32_t num_apply_bindings;
  3331. uint32_t num_apply_uniforms;
  3332. uint32_t num_draw;
  3333. uint32_t num_dispatch;
  3334. uint32_t num_update_buffer;
  3335. uint32_t num_append_buffer;
  3336. uint32_t num_update_image;
  3337. uint32_t size_apply_uniforms;
  3338. uint32_t size_update_buffer;
  3339. uint32_t size_append_buffer;
  3340. uint32_t size_update_image;
  3341. sg_frame_stats_gl gl;
  3342. sg_frame_stats_d3d11 d3d11;
  3343. sg_frame_stats_metal metal;
  3344. sg_frame_stats_wgpu wgpu;
  3345. } sg_frame_stats;
  3346. /*
  3347. sg_log_item
  3348. An enum with a unique item for each log message, warning, error
  3349. and validation layer message. Note that these messages are only
  3350. visible when a logger function is installed in the sg_setup() call.
  3351. */
  3352. #define _SG_LOG_ITEMS \
  3353. _SG_LOGITEM_XMACRO(OK, "Ok") \
  3354. _SG_LOGITEM_XMACRO(MALLOC_FAILED, "memory allocation failed") \
  3355. _SG_LOGITEM_XMACRO(GL_TEXTURE_FORMAT_NOT_SUPPORTED, "pixel format not supported for texture (gl)") \
  3356. _SG_LOGITEM_XMACRO(GL_3D_TEXTURES_NOT_SUPPORTED, "3d textures not supported (gl)") \
  3357. _SG_LOGITEM_XMACRO(GL_ARRAY_TEXTURES_NOT_SUPPORTED, "array textures not supported (gl)") \
  3358. _SG_LOGITEM_XMACRO(GL_STORAGEBUFFER_GLSL_BINDING_OUT_OF_RANGE, "GLSL storage buffer bindslot is out of range (must be 0..7) (gl)") \
  3359. _SG_LOGITEM_XMACRO(GL_STORAGEIMAGE_GLSL_BINDING_OUT_OF_RANGE, "GLSL storage image bindslot is out of range (must be 0..3) (gl)") \
  3360. _SG_LOGITEM_XMACRO(GL_SHADER_COMPILATION_FAILED, "shader compilation failed (gl)") \
  3361. _SG_LOGITEM_XMACRO(GL_SHADER_LINKING_FAILED, "shader linking failed (gl)") \
  3362. _SG_LOGITEM_XMACRO(GL_VERTEX_ATTRIBUTE_NOT_FOUND_IN_SHADER, "vertex attribute not found in shader; NOTE: may be caused by GL driver's GLSL compiler removing unused globals") \
  3363. _SG_LOGITEM_XMACRO(GL_UNIFORMBLOCK_NAME_NOT_FOUND_IN_SHADER, "uniform block name not found in shader; NOTE: may be caused by GL driver's GLSL compiler removing unused globals") \
  3364. _SG_LOGITEM_XMACRO(GL_IMAGE_SAMPLER_NAME_NOT_FOUND_IN_SHADER, "image-sampler name not found in shader; NOTE: may be caused by GL driver's GLSL compiler removing unused globals") \
  3365. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_UNDEFINED, "framebuffer completeness check failed with GL_FRAMEBUFFER_UNDEFINED (gl)") \
  3366. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_INCOMPLETE_ATTACHMENT, "framebuffer completeness check failed with GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT (gl)") \
  3367. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MISSING_ATTACHMENT, "framebuffer completeness check failed with GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT (gl)") \
  3368. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_UNSUPPORTED, "framebuffer completeness check failed with GL_FRAMEBUFFER_UNSUPPORTED (gl)") \
  3369. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MULTISAMPLE, "framebuffer completeness check failed with GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE (gl)") \
  3370. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_UNKNOWN, "framebuffer completeness check failed (unknown reason) (gl)") \
  3371. _SG_LOGITEM_XMACRO(D3D11_CREATE_BUFFER_FAILED, "CreateBuffer() failed (d3d11)") \
  3372. _SG_LOGITEM_XMACRO(D3D11_CREATE_BUFFER_SRV_FAILED, "CreateShaderResourceView() failed for storage buffer (d3d11)") \
  3373. _SG_LOGITEM_XMACRO(D3D11_CREATE_BUFFER_UAV_FAILED, "CreateUnorderedAccessView() failed for storage buffer (d3d11)") \
  3374. _SG_LOGITEM_XMACRO(D3D11_CREATE_DEPTH_TEXTURE_UNSUPPORTED_PIXEL_FORMAT, "pixel format not supported for depth-stencil texture (d3d11)") \
  3375. _SG_LOGITEM_XMACRO(D3D11_CREATE_DEPTH_TEXTURE_FAILED, "CreateTexture2D() failed for depth-stencil texture (d3d11)") \
  3376. _SG_LOGITEM_XMACRO(D3D11_CREATE_2D_TEXTURE_UNSUPPORTED_PIXEL_FORMAT, "pixel format not supported for 2d-, cube- or array-texture (d3d11)") \
  3377. _SG_LOGITEM_XMACRO(D3D11_CREATE_2D_TEXTURE_FAILED, "CreateTexture2D() failed for 2d-, cube- or array-texture (d3d11)") \
  3378. _SG_LOGITEM_XMACRO(D3D11_CREATE_2D_SRV_FAILED, "CreateShaderResourceView() failed for 2d-, cube- or array-texture (d3d11)") \
  3379. _SG_LOGITEM_XMACRO(D3D11_CREATE_3D_TEXTURE_UNSUPPORTED_PIXEL_FORMAT, "pixel format not supported for 3D texture (d3d11)") \
  3380. _SG_LOGITEM_XMACRO(D3D11_CREATE_3D_TEXTURE_FAILED, "CreateTexture3D() failed (d3d11)") \
  3381. _SG_LOGITEM_XMACRO(D3D11_CREATE_3D_SRV_FAILED, "CreateShaderResourceView() failed for 3d texture (d3d11)") \
  3382. _SG_LOGITEM_XMACRO(D3D11_CREATE_MSAA_TEXTURE_FAILED, "CreateTexture2D() failed for MSAA render target texture (d3d11)") \
  3383. _SG_LOGITEM_XMACRO(D3D11_CREATE_SAMPLER_STATE_FAILED, "CreateSamplerState() failed (d3d11)") \
  3384. _SG_LOGITEM_XMACRO(D3D11_UNIFORMBLOCK_HLSL_REGISTER_B_OUT_OF_RANGE, "uniform block 'hlsl_register_b_n' is out of range (must be 0..7)") \
  3385. _SG_LOGITEM_XMACRO(D3D11_STORAGEBUFFER_HLSL_REGISTER_T_OUT_OF_RANGE, "storage buffer 'hlsl_register_t_n' is out of range (must be 0..23)") \
  3386. _SG_LOGITEM_XMACRO(D3D11_STORAGEBUFFER_HLSL_REGISTER_U_OUT_OF_RANGE, "storage buffer 'hlsl_register_u_n' is out of range (must be 0..11)") \
  3387. _SG_LOGITEM_XMACRO(D3D11_IMAGE_HLSL_REGISTER_T_OUT_OF_RANGE, "image 'hlsl_register_t_n' is out of range (must be 0..23)") \
  3388. _SG_LOGITEM_XMACRO(D3D11_SAMPLER_HLSL_REGISTER_S_OUT_OF_RANGE, "sampler 'hlsl_register_s_n' is out of rang (must be 0..15)") \
  3389. _SG_LOGITEM_XMACRO(D3D11_STORAGEIMAGE_HLSL_REGISTER_U_OUT_OF_RANGE, "storage image 'hlsl_register_u_n' is out of range (must be 0..11)") \
  3390. _SG_LOGITEM_XMACRO(D3D11_LOAD_D3DCOMPILER_47_DLL_FAILED, "loading d3dcompiler_47.dll failed (d3d11)") \
  3391. _SG_LOGITEM_XMACRO(D3D11_SHADER_COMPILATION_FAILED, "shader compilation failed (d3d11)") \
  3392. _SG_LOGITEM_XMACRO(D3D11_SHADER_COMPILATION_OUTPUT, "") \
  3393. _SG_LOGITEM_XMACRO(D3D11_CREATE_CONSTANT_BUFFER_FAILED, "CreateBuffer() failed for uniform constant buffer (d3d11)") \
  3394. _SG_LOGITEM_XMACRO(D3D11_CREATE_INPUT_LAYOUT_FAILED, "CreateInputLayout() failed (d3d11)") \
  3395. _SG_LOGITEM_XMACRO(D3D11_CREATE_RASTERIZER_STATE_FAILED, "CreateRasterizerState() failed (d3d11)") \
  3396. _SG_LOGITEM_XMACRO(D3D11_CREATE_DEPTH_STENCIL_STATE_FAILED, "CreateDepthStencilState() failed (d3d11)") \
  3397. _SG_LOGITEM_XMACRO(D3D11_CREATE_BLEND_STATE_FAILED, "CreateBlendState() failed (d3d11)") \
  3398. _SG_LOGITEM_XMACRO(D3D11_CREATE_RTV_FAILED, "CreateRenderTargetView() failed (d3d11)") \
  3399. _SG_LOGITEM_XMACRO(D3D11_CREATE_DSV_FAILED, "CreateDepthStencilView() failed (d3d11)") \
  3400. _SG_LOGITEM_XMACRO(D3D11_CREATE_UAV_FAILED, "CreateUnorderedAccessView() failed (d3d11)") \
  3401. _SG_LOGITEM_XMACRO(D3D11_MAP_FOR_UPDATE_BUFFER_FAILED, "Map() failed when updating buffer (d3d11)") \
  3402. _SG_LOGITEM_XMACRO(D3D11_MAP_FOR_APPEND_BUFFER_FAILED, "Map() failed when appending to buffer (d3d11)") \
  3403. _SG_LOGITEM_XMACRO(D3D11_MAP_FOR_UPDATE_IMAGE_FAILED, "Map() failed when updating image (d3d11)") \
  3404. _SG_LOGITEM_XMACRO(METAL_CREATE_BUFFER_FAILED, "failed to create buffer object (metal)") \
  3405. _SG_LOGITEM_XMACRO(METAL_TEXTURE_FORMAT_NOT_SUPPORTED, "pixel format not supported for texture (metal)") \
  3406. _SG_LOGITEM_XMACRO(METAL_CREATE_TEXTURE_FAILED, "failed to create texture object (metal)") \
  3407. _SG_LOGITEM_XMACRO(METAL_CREATE_SAMPLER_FAILED, "failed to create sampler object (metal)") \
  3408. _SG_LOGITEM_XMACRO(METAL_SHADER_COMPILATION_FAILED, "shader compilation failed (metal)") \
  3409. _SG_LOGITEM_XMACRO(METAL_SHADER_CREATION_FAILED, "shader creation failed (metal)") \
  3410. _SG_LOGITEM_XMACRO(METAL_SHADER_COMPILATION_OUTPUT, "") \
  3411. _SG_LOGITEM_XMACRO(METAL_SHADER_ENTRY_NOT_FOUND, "shader entry function not found (metal)") \
  3412. _SG_LOGITEM_XMACRO(METAL_UNIFORMBLOCK_MSL_BUFFER_SLOT_OUT_OF_RANGE, "uniform block 'msl_buffer_n' is out of range (must be 0..7)") \
  3413. _SG_LOGITEM_XMACRO(METAL_STORAGEBUFFER_MSL_BUFFER_SLOT_OUT_OF_RANGE, "storage buffer 'msl_buffer_n' is out of range (must be 8..15)") \
  3414. _SG_LOGITEM_XMACRO(METAL_STORAGEIMAGE_MSL_TEXTURE_SLOT_OUT_OF_RANGE, "storage image 'msl_texture_n' is out of range (must be 0..19)") \
  3415. _SG_LOGITEM_XMACRO(METAL_IMAGE_MSL_TEXTURE_SLOT_OUT_OF_RANGE, "image 'msl_texture_n' is out of range (must be 0..19)") \
  3416. _SG_LOGITEM_XMACRO(METAL_SAMPLER_MSL_SAMPLER_SLOT_OUT_OF_RANGE, "sampler 'msl_sampler_n' is out of range (must be 0..15)") \
  3417. _SG_LOGITEM_XMACRO(METAL_CREATE_CPS_FAILED, "failed to create compute pipeline state (metal)") \
  3418. _SG_LOGITEM_XMACRO(METAL_CREATE_CPS_OUTPUT, "") \
  3419. _SG_LOGITEM_XMACRO(METAL_CREATE_RPS_FAILED, "failed to create render pipeline state (metal)") \
  3420. _SG_LOGITEM_XMACRO(METAL_CREATE_RPS_OUTPUT, "") \
  3421. _SG_LOGITEM_XMACRO(METAL_CREATE_DSS_FAILED, "failed to create depth stencil state (metal)") \
  3422. _SG_LOGITEM_XMACRO(WGPU_BINDGROUPS_POOL_EXHAUSTED, "bindgroups pool exhausted (increase sg_desc.bindgroups_cache_size) (wgpu)") \
  3423. _SG_LOGITEM_XMACRO(WGPU_BINDGROUPSCACHE_SIZE_GREATER_ONE, "sg_desc.wgpu_bindgroups_cache_size must be > 1 (wgpu)") \
  3424. _SG_LOGITEM_XMACRO(WGPU_BINDGROUPSCACHE_SIZE_POW2, "sg_desc.wgpu_bindgroups_cache_size must be a power of 2 (wgpu)") \
  3425. _SG_LOGITEM_XMACRO(WGPU_CREATEBINDGROUP_FAILED, "wgpuDeviceCreateBindGroup failed") \
  3426. _SG_LOGITEM_XMACRO(WGPU_CREATE_BUFFER_FAILED, "wgpuDeviceCreateBuffer() failed") \
  3427. _SG_LOGITEM_XMACRO(WGPU_CREATE_TEXTURE_FAILED, "wgpuDeviceCreateTexture() failed") \
  3428. _SG_LOGITEM_XMACRO(WGPU_CREATE_TEXTURE_VIEW_FAILED, "wgpuTextureCreateView() failed") \
  3429. _SG_LOGITEM_XMACRO(WGPU_CREATE_SAMPLER_FAILED, "wgpuDeviceCreateSampler() failed") \
  3430. _SG_LOGITEM_XMACRO(WGPU_CREATE_SHADER_MODULE_FAILED, "wgpuDeviceCreateShaderModule() failed") \
  3431. _SG_LOGITEM_XMACRO(WGPU_SHADER_CREATE_BINDGROUP_LAYOUT_FAILED, "wgpuDeviceCreateBindGroupLayout() for shader stage failed") \
  3432. _SG_LOGITEM_XMACRO(WGPU_UNIFORMBLOCK_WGSL_GROUP0_BINDING_OUT_OF_RANGE, "uniform block 'wgsl_group0_binding_n' is out of range (must be 0..15)") \
  3433. _SG_LOGITEM_XMACRO(WGPU_STORAGEBUFFER_WGSL_GROUP1_BINDING_OUT_OF_RANGE, "storage buffer 'wgsl_group1_binding_n' is out of range (must be 0..127)") \
  3434. _SG_LOGITEM_XMACRO(WGPU_IMAGE_WGSL_GROUP1_BINDING_OUT_OF_RANGE, "image 'wgsl_group1_binding_n' is out of range (must be 0..127)") \
  3435. _SG_LOGITEM_XMACRO(WGPU_SAMPLER_WGSL_GROUP1_BINDING_OUT_OF_RANGE, "sampler 'wgsl_group1_binding_n' is out of range (must be 0..127)") \
  3436. _SG_LOGITEM_XMACRO(WGPU_STORAGEIMAGE_WGSL_GROUP2_BINDING_OUT_OF_RANGE, "storage image 'wgsl_group2_binding_n' is out of range (must be 0..3)") \
  3437. _SG_LOGITEM_XMACRO(WGPU_CREATE_PIPELINE_LAYOUT_FAILED, "wgpuDeviceCreatePipelineLayout() failed") \
  3438. _SG_LOGITEM_XMACRO(WGPU_CREATE_RENDER_PIPELINE_FAILED, "wgpuDeviceCreateRenderPipeline() failed") \
  3439. _SG_LOGITEM_XMACRO(WGPU_CREATE_COMPUTE_PIPELINE_FAILED, "wgpuDeviceCreateComputePipeline() failed") \
  3440. _SG_LOGITEM_XMACRO(WGPU_ATTACHMENTS_CREATE_TEXTURE_VIEW_FAILED, "wgpuTextureCreateView() failed in create attachments") \
  3441. _SG_LOGITEM_XMACRO(IDENTICAL_COMMIT_LISTENER, "attempting to add identical commit listener") \
  3442. _SG_LOGITEM_XMACRO(COMMIT_LISTENER_ARRAY_FULL, "commit listener array full") \
  3443. _SG_LOGITEM_XMACRO(TRACE_HOOKS_NOT_ENABLED, "sg_install_trace_hooks() called, but SOKOL_TRACE_HOOKS is not defined") \
  3444. _SG_LOGITEM_XMACRO(DEALLOC_BUFFER_INVALID_STATE, "sg_dealloc_buffer(): buffer must be in ALLOC state") \
  3445. _SG_LOGITEM_XMACRO(DEALLOC_IMAGE_INVALID_STATE, "sg_dealloc_image(): image must be in alloc state") \
  3446. _SG_LOGITEM_XMACRO(DEALLOC_SAMPLER_INVALID_STATE, "sg_dealloc_sampler(): sampler must be in alloc state") \
  3447. _SG_LOGITEM_XMACRO(DEALLOC_SHADER_INVALID_STATE, "sg_dealloc_shader(): shader must be in ALLOC state") \
  3448. _SG_LOGITEM_XMACRO(DEALLOC_PIPELINE_INVALID_STATE, "sg_dealloc_pipeline(): pipeline must be in ALLOC state") \
  3449. _SG_LOGITEM_XMACRO(DEALLOC_ATTACHMENTS_INVALID_STATE, "sg_dealloc_attachments(): attachments must be in ALLOC state") \
  3450. _SG_LOGITEM_XMACRO(INIT_BUFFER_INVALID_STATE, "sg_init_buffer(): buffer must be in ALLOC state") \
  3451. _SG_LOGITEM_XMACRO(INIT_IMAGE_INVALID_STATE, "sg_init_image(): image must be in ALLOC state") \
  3452. _SG_LOGITEM_XMACRO(INIT_SAMPLER_INVALID_STATE, "sg_init_sampler(): sampler must be in ALLOC state") \
  3453. _SG_LOGITEM_XMACRO(INIT_SHADER_INVALID_STATE, "sg_init_shader(): shader must be in ALLOC state") \
  3454. _SG_LOGITEM_XMACRO(INIT_PIPELINE_INVALID_STATE, "sg_init_pipeline(): pipeline must be in ALLOC state") \
  3455. _SG_LOGITEM_XMACRO(INIT_ATTACHMENTS_INVALID_STATE, "sg_init_attachments(): pass must be in ALLOC state") \
  3456. _SG_LOGITEM_XMACRO(UNINIT_BUFFER_INVALID_STATE, "sg_uninit_buffer(): buffer must be in VALID or FAILED state") \
  3457. _SG_LOGITEM_XMACRO(UNINIT_IMAGE_INVALID_STATE, "sg_uninit_image(): image must be in VALID or FAILED state") \
  3458. _SG_LOGITEM_XMACRO(UNINIT_SAMPLER_INVALID_STATE, "sg_uninit_sampler(): sampler must be in VALID or FAILED state") \
  3459. _SG_LOGITEM_XMACRO(UNINIT_SHADER_INVALID_STATE, "sg_uninit_shader(): shader must be in VALID or FAILED state") \
  3460. _SG_LOGITEM_XMACRO(UNINIT_PIPELINE_INVALID_STATE, "sg_uninit_pipeline(): pipeline must be in VALID or FAILED state") \
  3461. _SG_LOGITEM_XMACRO(UNINIT_ATTACHMENTS_INVALID_STATE, "sg_uninit_attachments(): attachments must be in VALID or FAILED state") \
  3462. _SG_LOGITEM_XMACRO(FAIL_BUFFER_INVALID_STATE, "sg_fail_buffer(): buffer must be in ALLOC state") \
  3463. _SG_LOGITEM_XMACRO(FAIL_IMAGE_INVALID_STATE, "sg_fail_image(): image must be in ALLOC state") \
  3464. _SG_LOGITEM_XMACRO(FAIL_SAMPLER_INVALID_STATE, "sg_fail_sampler(): sampler must be in ALLOC state") \
  3465. _SG_LOGITEM_XMACRO(FAIL_SHADER_INVALID_STATE, "sg_fail_shader(): shader must be in ALLOC state") \
  3466. _SG_LOGITEM_XMACRO(FAIL_PIPELINE_INVALID_STATE, "sg_fail_pipeline(): pipeline must be in ALLOC state") \
  3467. _SG_LOGITEM_XMACRO(FAIL_ATTACHMENTS_INVALID_STATE, "sg_fail_attachments(): attachments must be in ALLOC state") \
  3468. _SG_LOGITEM_XMACRO(BUFFER_POOL_EXHAUSTED, "buffer pool exhausted") \
  3469. _SG_LOGITEM_XMACRO(IMAGE_POOL_EXHAUSTED, "image pool exhausted") \
  3470. _SG_LOGITEM_XMACRO(SAMPLER_POOL_EXHAUSTED, "sampler pool exhausted") \
  3471. _SG_LOGITEM_XMACRO(SHADER_POOL_EXHAUSTED, "shader pool exhausted") \
  3472. _SG_LOGITEM_XMACRO(PIPELINE_POOL_EXHAUSTED, "pipeline pool exhausted") \
  3473. _SG_LOGITEM_XMACRO(PASS_POOL_EXHAUSTED, "pass pool exhausted") \
  3474. _SG_LOGITEM_XMACRO(BEGINPASS_ATTACHMENT_INVALID, "sg_begin_pass: an attachment was provided that no longer exists") \
  3475. _SG_LOGITEM_XMACRO(APPLY_BINDINGS_STORAGE_BUFFER_TRACKER_EXHAUSTED, "sg_apply_bindings: too many read/write storage buffers in pass (bump sg_desc.max_dispatch_calls_per_pass") \
  3476. _SG_LOGITEM_XMACRO(DRAW_WITHOUT_BINDINGS, "attempting to draw without resource bindings") \
  3477. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_CANARY, "sg_buffer_desc not initialized") \
  3478. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_IMMUTABLE_DYNAMIC_STREAM, "sg_buffer_desc.usage: only one of .immutable, .dynamic_update, .stream_update can be true") \
  3479. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_SEPARATE_BUFFER_TYPES, "sg_buffer_desc.usage: on WebGL2, only one of .vertex_buffer or .index_buffer can be true (check sg_features.separate_buffer_types)") \
  3480. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_EXPECT_NONZERO_SIZE, "sg_buffer_desc.size must be greater zero") \
  3481. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_EXPECT_MATCHING_DATA_SIZE, "sg_buffer_desc.size and .data.size must be equal") \
  3482. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_EXPECT_ZERO_DATA_SIZE, "sg_buffer_desc.data.size expected to be zero") \
  3483. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_EXPECT_NO_DATA, "sg_buffer_desc.data.ptr must be null for dynamic/stream buffers") \
  3484. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_EXPECT_DATA, "sg_buffer_desc: initial content data must be provided for immutable buffers without storage buffer usage") \
  3485. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_STORAGEBUFFER_SUPPORTED, "storage buffers not supported by the backend 3D API (requires OpenGL >= 4.3)") \
  3486. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_STORAGEBUFFER_SIZE_MULTIPLE_4, "size of storage buffers must be a multiple of 4") \
  3487. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDATA_NODATA, "sg_image_data: no data (.ptr and/or .size is zero)") \
  3488. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDATA_DATA_SIZE, "sg_image_data: data size doesn't match expected surface size") \
  3489. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_CANARY, "sg_image_desc not initialized") \
  3490. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_IMMUTABLE_DYNAMIC_STREAM, "sg_image_desc.usage: only one of .immutable, .dynamic_update, .stream_update can be true") \
  3491. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RENDER_VS_STORAGE_ATTACHMENT, "sg_image_desc.usage: only one of .render_attachment or .storage_attachment can be true") \
  3492. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_WIDTH, "sg_image_desc.width must be > 0") \
  3493. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_HEIGHT, "sg_image_desc.height must be > 0") \
  3494. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_NONRT_PIXELFORMAT, "invalid pixel format for non-render-target image") \
  3495. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_MSAA_BUT_NO_ATTACHMENT, "non-attachment images cannot be multisampled") \
  3496. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_DEPTH_3D_IMAGE, "3D images cannot have a depth/stencil image format") \
  3497. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_ATTACHMENT_EXPECT_IMMUTABLE, "render/storage attachment images must be sg_image_usage.immutable") \
  3498. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_ATTACHMENT_EXPECT_NO_DATA, "render/storage attachment images cannot be initialized with data") \
  3499. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RENDERATTACHMENT_NO_MSAA_SUPPORT, "multisampling not supported for this pixel format") \
  3500. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RENDERATTACHMENT_MSAA_NUM_MIPMAPS, "multisample images must have num_mipmaps == 1") \
  3501. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RENDERATTACHMENT_MSAA_3D_IMAGE, "3D images cannot have a sample_count > 1") \
  3502. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RENDERATTACHMENT_MSAA_CUBE_IMAGE, "cube images cannot have sample_count > 1") \
  3503. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RENDERATTACHMENT_MSAA_ARRAY_IMAGE, "array images cannot have sample_count > 1") \
  3504. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RENDERATTACHMENT_PIXELFORMAT, "invalid pixel format for render attachment image") \
  3505. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_STORAGEATTACHMENT_PIXELFORMAT, "invalid pixel format for storage attachment image") \
  3506. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_STORAGEATTACHMENT_EXPECT_NO_MSAA, "storage attachment images cannot be multisampled") \
  3507. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_INJECTED_NO_DATA, "images with injected textures cannot be initialized with data") \
  3508. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_DYNAMIC_NO_DATA, "dynamic/stream-update images cannot be initialized with data") \
  3509. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_COMPRESSED_IMMUTABLE, "compressed images must be immutable") \
  3510. _SG_LOGITEM_XMACRO(VALIDATE_SAMPLERDESC_CANARY, "sg_sampler_desc not initialized") \
  3511. _SG_LOGITEM_XMACRO(VALIDATE_SAMPLERDESC_ANISTROPIC_REQUIRES_LINEAR_FILTERING, "sg_sampler_desc.max_anisotropy > 1 requires min/mag/mipmap_filter to be SG_FILTER_LINEAR") \
  3512. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_CANARY, "sg_shader_desc not initialized") \
  3513. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_VERTEX_SOURCE, "vertex shader source code expected") \
  3514. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_FRAGMENT_SOURCE, "fragment shader source code expected") \
  3515. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_COMPUTE_SOURCE, "compute shader source code expected") \
  3516. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_VERTEX_SOURCE_OR_BYTECODE, "vertex shader source or byte code expected") \
  3517. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_FRAGMENT_SOURCE_OR_BYTECODE, "fragment shader source or byte code expected") \
  3518. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_COMPUTE_SOURCE_OR_BYTECODE, "compute shader source or byte code expected") \
  3519. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_INVALID_SHADER_COMBO, "cannot combine compute shaders with vertex or fragment shaders") \
  3520. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_NO_BYTECODE_SIZE, "shader byte code length (in bytes) required") \
  3521. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_METAL_THREADS_PER_THREADGROUP, "sg_shader_desc.mtl_threads_per_threadgroup must be initialized for compute shaders (metal)") \
  3522. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_NO_CONT_MEMBERS, "uniform block members must occupy continuous slots") \
  3523. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_SIZE_IS_ZERO, "bound uniform block size cannot be zero") \
  3524. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_METAL_BUFFER_SLOT_OUT_OF_RANGE, "uniform block 'msl_buffer_n' is out of range (must be 0..7)") \
  3525. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_METAL_BUFFER_SLOT_COLLISION, "uniform block 'msl_buffer_n' must be unique across uniform blocks and storage buffers in same shader stage") \
  3526. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_HLSL_REGISTER_B_OUT_OF_RANGE, "uniform block 'hlsl_register_b_n' is out of range (must be 0..7)") \
  3527. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_HLSL_REGISTER_B_COLLISION, "uniform block 'hlsl_register_b_n' must be unique across uniform blocks in same shader stage") \
  3528. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_WGSL_GROUP0_BINDING_OUT_OF_RANGE, "uniform block 'wgsl_group0_binding_n' is out of range (must be 0..15)") \
  3529. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_WGSL_GROUP0_BINDING_COLLISION, "uniform block 'wgsl_group0_binding_n' must be unique across all uniform blocks") \
  3530. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_NO_MEMBERS, "GL backend requires uniform block member declarations") \
  3531. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_UNIFORM_GLSL_NAME, "uniform block member 'glsl_name' missing") \
  3532. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_SIZE_MISMATCH, "size of uniform block members doesn't match uniform block size") \
  3533. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_ARRAY_COUNT, "uniform array count must be >= 1") \
  3534. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_STD140_ARRAY_TYPE, "uniform arrays only allowed for FLOAT4, INT4, MAT4 in std140 layout") \
  3535. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_METAL_BUFFER_SLOT_OUT_OF_RANGE, "storage buffer 'msl_buffer_n' is out of range (must be 8..15)") \
  3536. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_METAL_BUFFER_SLOT_COLLISION, "storage buffer 'msl_buffer_n' must be unique across uniform blocks and storage buffer in same shader stage") \
  3537. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_HLSL_REGISTER_T_OUT_OF_RANGE, "storage buffer 'hlsl_register_t_n' is out of range (must be 0..23)") \
  3538. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_HLSL_REGISTER_T_COLLISION, "storage_buffer 'hlsl_register_t_n' must be unique across read-only storage buffers and images in same shader stage") \
  3539. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_HLSL_REGISTER_U_OUT_OF_RANGE, "storage buffer 'hlsl_register_u_n' is out of range (must be 0..11)") \
  3540. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_HLSL_REGISTER_U_COLLISION, "storage_buffer 'hlsl_register_u_n' must be unique across read/write storage buffers and storage images in same shader stage") \
  3541. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_GLSL_BINDING_OUT_OF_RANGE, "storage buffer 'glsl_binding_n' is out of range (must be 0..7)") \
  3542. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_GLSL_BINDING_COLLISION, "storage buffer 'glsl_binding_n' must be unique across shader stages") \
  3543. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_WGSL_GROUP1_BINDING_OUT_OF_RANGE, "storage buffer 'wgsl_group1_binding_n' is out of range (must be 0..127)") \
  3544. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_WGSL_GROUP1_BINDING_COLLISION, "storage buffer 'wgsl_group1_binding_n' must be unique across all images, samplers and storage buffers") \
  3545. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEIMAGE_EXPECT_COMPUTE_STAGE, "storage images are only allowed on the compute stage") \
  3546. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEIMAGE_METAL_TEXTURE_SLOT_OUT_OF_RANGE, "storage image 'msl_texture_n' is out of range (must be 0..19") \
  3547. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEIMAGE_METAL_TEXTURE_SLOT_COLLISION, "storage image 'msl_texture_n' must be unique across images and storage images in same shader stage") \
  3548. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEIMAGE_HLSL_REGISTER_U_OUT_OF_RANGE, "storage image 'hlsl_register_u_n' is out of range (must be 0..11)") \
  3549. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEIMAGE_HLSL_REGISTER_U_COLLISION, "storage image 'hlsl_register_u_n' must be unique across storage images and read/write storage buffers in same shader stage") \
  3550. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEIMAGE_GLSL_BINDING_OUT_OF_RANGE, "storage image 'glsl_binding_n' is out of range (must be 0..4)") \
  3551. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEIMAGE_GLSL_BINDING_COLLISION, "storage image 'glsl_binding_n' must be unique across shader stages") \
  3552. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEIMAGE_WGSL_GROUP2_BINDING_OUT_OF_RANGE, "storage image 'wgsl_group2_binding_n' is out of range (must be 0..7)") \
  3553. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEIMAGE_WGSL_GROUP2_BINDING_COLLISION, "storage image 'wgsl_group2_binding_n' must be unique in same shader stage") \
  3554. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_METAL_TEXTURE_SLOT_OUT_OF_RANGE, "image 'msl_texture_n' is out of range (must be 0..19)") \
  3555. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_METAL_TEXTURE_SLOT_COLLISION, "image 'msl_texture_n' must be unique across images and storage images in same shader stage") \
  3556. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_HLSL_REGISTER_T_OUT_OF_RANGE, "image 'hlsl_register_t_n' is out of range (must be 0..23)") \
  3557. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_HLSL_REGISTER_T_COLLISION, "image 'hlsl_register_t_n' must be unique across images and storage buffers in same shader stage") \
  3558. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_WGSL_GROUP1_BINDING_OUT_OF_RANGE, "image 'wgsl_group1_binding_n' is out of range (must be 0..127)") \
  3559. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_WGSL_GROUP1_BINDING_COLLISION, "image 'wgsl_group1_binding_n' must be unique across all images, samplers and storage buffers") \
  3560. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_METAL_SAMPLER_SLOT_OUT_OF_RANGE, "sampler 'msl_sampler_n' is out of range (must be 0..15)") \
  3561. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_METAL_SAMPLER_SLOT_COLLISION, "sampler 'msl_sampler_n' must be unique in same shader stage") \
  3562. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_HLSL_REGISTER_S_OUT_OF_RANGE, "sampler 'hlsl_register_s_n' is out of rang (must be 0..15)") \
  3563. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_HLSL_REGISTER_S_COLLISION, "sampler 'hlsl_register_s_n' must be unique in same shader stage") \
  3564. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_WGSL_GROUP1_BINDING_OUT_OF_RANGE, "sampler 'wgsl_group1_binding_n' is out of range (must be 0..127)") \
  3565. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_WGSL_GROUP1_BINDING_COLLISION, "sampler 'wgsl_group1_binding_n' must be unique across all images, samplers and storage buffers") \
  3566. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_IMAGE_SLOT_OUT_OF_RANGE, "image-sampler-pair image slot index is out of range (sg_shader_desc.image_sampler_pairs[].image_slot)") \
  3567. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_SAMPLER_SLOT_OUT_OF_RANGE, "image-sampler-pair sampler slot index is out of range (sg_shader_desc.image_sampler_pairs[].sampler_slot)") \
  3568. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_IMAGE_STAGE_MISMATCH, "image-sampler-pair stage doesn't match referenced image stage") \
  3569. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_SAMPLER_STAGE_MISMATCH, "image-sampler-pair stage doesn't match referenced sampler stage") \
  3570. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_GLSL_NAME, "image-sampler-pair 'glsl_name' missing") \
  3571. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_NONFILTERING_SAMPLER_REQUIRED, "image sample type UNFILTERABLE_FLOAT, UINT, SINT can only be used with NONFILTERING sampler") \
  3572. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_COMPARISON_SAMPLER_REQUIRED, "image sample type DEPTH can only be used with COMPARISON sampler") \
  3573. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_NOT_REFERENCED_BY_IMAGE_SAMPLER_PAIRS, "one or more images are not referenced by by image-sampler-pairs (sg_shader_desc.image_sampler_pairs[].image_slot)") \
  3574. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_NOT_REFERENCED_BY_IMAGE_SAMPLER_PAIRS, "one or more samplers are not referenced by image-sampler-pairs (sg_shader_desc.image_sampler_pairs[].sampler_slot)") \
  3575. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_ATTR_STRING_TOO_LONG, "vertex attribute name/semantic string too long (max len 16)") \
  3576. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_CANARY, "sg_pipeline_desc not initialized") \
  3577. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_SHADER, "sg_pipeline_desc.shader missing or invalid") \
  3578. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_COMPUTE_SHADER_EXPECTED, "sg_pipeline_desc.shader must be a compute shader") \
  3579. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_NO_COMPUTE_SHADER_EXPECTED, "sg_pipeline_desc.compute is false, but shader is a compute shader") \
  3580. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_NO_CONT_ATTRS, "sg_pipeline_desc.layout.attrs is not continuous") \
  3581. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_ATTR_BASETYPE_MISMATCH, "sg_pipeline_desc.layout.attrs[].format is incompatible with sg_shader_desc.attrs[].base_type") \
  3582. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_LAYOUT_STRIDE4, "sg_pipeline_desc.layout.buffers[].stride must be multiple of 4") \
  3583. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_ATTR_SEMANTICS, "D3D11 missing vertex attribute semantics in shader") \
  3584. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_SHADER_READONLY_STORAGEBUFFERS, "sg_pipeline_desc.shader: only readonly storage buffer bindings allowed in render pipelines") \
  3585. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_BLENDOP_MINMAX_REQUIRES_BLENDFACTOR_ONE, "SG_BLENDOP_MIN/MAX requires all blend factors to be SG_BLENDFACTOR_ONE") \
  3586. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_CANARY, "sg_attachments_desc not initialized") \
  3587. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_NO_ATTACHMENTS, "sg_attachments_desc no color, depth-stencil or storage attachments") \
  3588. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_NO_CONT_COLOR_ATTS, "color attachments must occupy continuous slots") \
  3589. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_COLOR_IMAGE, "color attachment image is not valid") \
  3590. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_COLOR_MIPLEVEL, "color attachment mip level is higher than number of mipmaps in image") \
  3591. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_COLOR_FACE, "color attachment image is cubemap, but face index is too big") \
  3592. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_COLOR_LAYER, "color attachment image is array texture, but layer index is too big") \
  3593. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_COLOR_SLICE, "color attachment image is 3d texture, but slice value is too big") \
  3594. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_COLOR_IMAGE_NO_RENDERATTACHMENT, "color attachment images must be sg_image_desc.usage.render_attachment=true") \
  3595. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_COLOR_INV_PIXELFORMAT, "color attachment images must be renderable color pixel format") \
  3596. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_IMAGE_SIZES, "all color and depth attachment images must have the same size") \
  3597. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_IMAGE_SAMPLE_COUNTS, "all color and depth attachment images must have the same sample count") \
  3598. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_COLOR_IMAGE_MSAA, "resolve attachments must have a color attachment image with sample count > 1") \
  3599. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE, "resolve attachment image not valid") \
  3600. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_SAMPLE_COUNT, "pass resolve attachment image sample count must be 1") \
  3601. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_MIPLEVEL, "resolve attachment mip level is higher than number of mipmaps in image") \
  3602. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_FACE, "resolve attachment is cubemap, but face index is too big") \
  3603. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_LAYER, "resolve attachment is array texture, but layer index is too big") \
  3604. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_SLICE, "resolve attachment is 3d texture, but slice value is too big") \
  3605. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_NO_RT, "resolve attachment image must have render_target=true") \
  3606. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_SIZES, "resolve attachment size must match color attachment image size") \
  3607. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_FORMAT, "resolve attachment pixel format must match color attachment pixel format") \
  3608. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_INV_PIXELFORMAT, "depth attachment image must be depth or depth-stencil pixel format") \
  3609. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE, "depth attachment image is not valid") \
  3610. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_MIPLEVEL, "depth attachment mip level is higher than number of mipmaps in image") \
  3611. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_FACE, "depth attachment image is cubemap, but face index is too big") \
  3612. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_LAYER, "depth attachment image is array texture, but layer index is too big") \
  3613. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_SLICE, "depth attachment image is 3d texture, but slice value is too big") \
  3614. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_NO_RENDERATTACHMENT, "depth attachment image must be sg_image_desc.usage.render_attachment=true") \
  3615. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_SIZES, "depth attachment image size must match color attachment image size") \
  3616. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_SAMPLE_COUNT, "depth attachment sample count must match color attachment sample count") \
  3617. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_STORAGE_IMAGE, "storage attachment image is not valid") \
  3618. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_STORAGE_MIPLEVEL, "storage attachment mip level is higher than number of mipmaps in image") \
  3619. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_STORAGE_FACE, "storage attachment image is cubemap, but face index is too big") \
  3620. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_STORAGE_LAYER, "storage attachment image is array texture, but layer index is too big") \
  3621. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_STORAGE_SLICE, "storage attachment image is 3d texture, but slice value is too big") \
  3622. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_STORAGE_IMAGE_NO_STORAGEATTACHMENT, "storage attachment images must be sg_image_desc.usage.storage_attachment=true") \
  3623. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_STORAGE_INV_PIXELFORMAT, "storage attachment pixel format must have .compute_readwrite or .compute_writeonly capabilities") \
  3624. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RENDER_VS_STORAGE_ATTACHMENTS, "cannot use color/depth and storage attachment images on the same sg_attachments object") \
  3625. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_CANARY, "sg_begin_pass: pass struct not initialized") \
  3626. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_ATTACHMENTS_EXISTS, "sg_begin_pass: attachments object no longer alive") \
  3627. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_ATTACHMENTS_VALID, "sg_begin_pass: attachments object not in resource state VALID") \
  3628. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_COMPUTEPASS_STORAGE_ATTACHMENTS_ONLY, "sg_begin_pass: only storage attachments allowed on compute pass") \
  3629. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_RENDERPASS_RENDER_ATTACHMENTS_ONLY, "sg_begin_pass: a render pass cannot have storage attachments") \
  3630. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_COLOR_ATTACHMENT_IMAGE, "sg_begin_pass: one or more color attachment images are not valid") \
  3631. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_RESOLVE_ATTACHMENT_IMAGE, "sg_begin_pass: one or more resolve attachment images are not valid") \
  3632. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_DEPTHSTENCIL_ATTACHMENT_IMAGE, "sg_begin_pass: one or more depth-stencil attachment images are not valid") \
  3633. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_STORAGE_ATTACHMENT_IMAGE, "sg_begin_pass: one or more storage attachment images are not valid") \
  3634. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_WIDTH, "sg_begin_pass: expected pass.swapchain.width > 0") \
  3635. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_WIDTH_NOTSET, "sg_begin_pass: expected pass.swapchain.width == 0") \
  3636. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_HEIGHT, "sg_begin_pass: expected pass.swapchain.height > 0") \
  3637. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_HEIGHT_NOTSET, "sg_begin_pass: expected pass.swapchain.height == 0") \
  3638. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_SAMPLECOUNT, "sg_begin_pass: expected pass.swapchain.sample_count > 0") \
  3639. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_SAMPLECOUNT_NOTSET, "sg_begin_pass: expected pass.swapchain.sample_count == 0") \
  3640. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_COLORFORMAT, "sg_begin_pass: expected pass.swapchain.color_format to be valid") \
  3641. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_COLORFORMAT_NOTSET, "sg_begin_pass: expected pass.swapchain.color_format to be unset") \
  3642. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_DEPTHFORMAT_NOTSET, "sg_begin_pass: expected pass.swapchain.depth_format to be unset") \
  3643. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_CURRENTDRAWABLE, "sg_begin_pass: expected pass.swapchain.metal.current_drawable != 0") \
  3644. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_CURRENTDRAWABLE_NOTSET, "sg_begin_pass: expected pass.swapchain.metal.current_drawable == 0") \
  3645. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_DEPTHSTENCILTEXTURE, "sg_begin_pass: expected pass.swapchain.metal.depth_stencil_texture != 0") \
  3646. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_DEPTHSTENCILTEXTURE_NOTSET, "sg_begin_pass: expected pass.swapchain.metal.depth_stencil_texture == 0") \
  3647. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_MSAACOLORTEXTURE, "sg_begin_pass: expected pass.swapchain.metal.msaa_color_texture != 0") \
  3648. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_MSAACOLORTEXTURE_NOTSET, "sg_begin_pass: expected pass.swapchain.metal.msaa_color_texture == 0") \
  3649. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RENDERVIEW, "sg_begin_pass: expected pass.swapchain.d3d11.render_view != 0") \
  3650. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RENDERVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.d3d11.render_view == 0") \
  3651. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RESOLVEVIEW, "sg_begin_pass: expected pass.swapchain.d3d11.resolve_view != 0") \
  3652. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RESOLVEVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.d3d11.resolve_view == 0") \
  3653. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_DEPTHSTENCILVIEW, "sg_begin_pass: expected pass.swapchain.d3d11.depth_stencil_view != 0") \
  3654. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_DEPTHSTENCILVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.d3d11.depth_stencil_view == 0") \
  3655. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RENDERVIEW, "sg_begin_pass: expected pass.swapchain.wgpu.render_view != 0") \
  3656. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RENDERVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.wgpu.render_view == 0") \
  3657. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RESOLVEVIEW, "sg_begin_pass: expected pass.swapchain.wgpu.resolve_view != 0") \
  3658. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RESOLVEVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.wgpu.resolve_view == 0") \
  3659. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_DEPTHSTENCILVIEW, "sg_begin_pass: expected pass.swapchain.wgpu.depth_stencil_view != 0") \
  3660. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_DEPTHSTENCILVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.wgpu.depth_stencil_view == 0") \
  3661. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_GL_EXPECT_FRAMEBUFFER_NOTSET, "sg_begin_pass: expected pass.swapchain.gl.framebuffer == 0") \
  3662. _SG_LOGITEM_XMACRO(VALIDATE_AVP_RENDERPASS_EXPECTED, "sg_apply_viewport: must be called in a render pass") \
  3663. _SG_LOGITEM_XMACRO(VALIDATE_ASR_RENDERPASS_EXPECTED, "sg_apply_scissor_rect: must be called in a render pass") \
  3664. _SG_LOGITEM_XMACRO(VALIDATE_APIP_PIPELINE_VALID_ID, "sg_apply_pipeline: invalid pipeline id provided") \
  3665. _SG_LOGITEM_XMACRO(VALIDATE_APIP_PIPELINE_EXISTS, "sg_apply_pipeline: pipeline object no longer alive") \
  3666. _SG_LOGITEM_XMACRO(VALIDATE_APIP_PIPELINE_VALID, "sg_apply_pipeline: pipeline object not in valid state") \
  3667. _SG_LOGITEM_XMACRO(VALIDATE_APIP_PASS_EXPECTED, "sg_apply_pipeline: must be called in a pass") \
  3668. _SG_LOGITEM_XMACRO(VALIDATE_APIP_PIPELINE_SHADER_ALIVE, "sg_apply_pipeline: shader object associated with pipeline no longer alive") \
  3669. _SG_LOGITEM_XMACRO(VALIDATE_APIP_PIPELINE_SHADER_VALID, "sg_apply_pipeline: shader object associated with pipeline not in valid state") \
  3670. _SG_LOGITEM_XMACRO(VALIDATE_APIP_COMPUTEPASS_EXPECTED, "sg_apply_pipeline: trying to apply compute pipeline in render pass") \
  3671. _SG_LOGITEM_XMACRO(VALIDATE_APIP_RENDERPASS_EXPECTED, "sg_apply_pipeline: trying to apply render pipeline in compute pass") \
  3672. _SG_LOGITEM_XMACRO(VALIDATE_APIP_CURPASS_ATTACHMENTS_ALIVE, "sg_apply_pipeline: current pass attachments no longer alive") \
  3673. _SG_LOGITEM_XMACRO(VALIDATE_APIP_CURPASS_ATTACHMENTS_VALID, "sg_apply_pipeline: current pass attachments not in valid state") \
  3674. _SG_LOGITEM_XMACRO(VALIDATE_APIP_ATT_COUNT, "sg_apply_pipeline: number of pipeline color attachments doesn't match number of pass color attachments") \
  3675. _SG_LOGITEM_XMACRO(VALIDATE_APIP_COLOR_FORMAT, "sg_apply_pipeline: pipeline color attachment pixel format doesn't match pass color attachment pixel format") \
  3676. _SG_LOGITEM_XMACRO(VALIDATE_APIP_DEPTH_FORMAT, "sg_apply_pipeline: pipeline depth pixel_format doesn't match pass depth attachment pixel format") \
  3677. _SG_LOGITEM_XMACRO(VALIDATE_APIP_SAMPLE_COUNT, "sg_apply_pipeline: pipeline MSAA sample count doesn't match render pass attachment sample count") \
  3678. _SG_LOGITEM_XMACRO(VALIDATE_APIP_EXPECTED_STORAGE_ATTACHMENT_IMAGE, "sg_apply_pipeline: shader expects storage image binding but compute pass doesn't have storage attachment image at expected bind slot") \
  3679. _SG_LOGITEM_XMACRO(VALIDATE_APIP_STORAGE_ATTACHMENT_IMAGE_ALIVE, "sg_apply_pipeline: compute pass storage image attachment no longer exists") \
  3680. _SG_LOGITEM_XMACRO(VALIDATE_APIP_STORAGE_ATTACHMENT_IMAGE_VALID, "sg_apply_pipeline: compute pass storage image attachment is not in valid state") \
  3681. _SG_LOGITEM_XMACRO(VALIDATE_APIP_STORAGE_ATTACHMENT_PIXELFORMAT, "sg_apply_pipeline: compute pass storage image attachment pixel format doesn't match sg_shader_desc.storage_images[].access_format") \
  3682. _SG_LOGITEM_XMACRO(VALIDATE_APIP_STORAGE_ATTACHMENT_IMAGE_TYPE, "sg_apply_pipeline: compute pass storage image attachment image type doesn't match sg_shader_desc.storage_images[].image_type") \
  3683. _SG_LOGITEM_XMACRO(VALIDATE_ABND_PASS_EXPECTED, "sg_apply_bindings: must be called in a pass") \
  3684. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EMPTY_BINDINGS, "sg_apply_bindings: the provided sg_bindings struct is empty") \
  3685. _SG_LOGITEM_XMACRO(VALIDATE_ABND_NO_PIPELINE, "sg_apply_bindings: must be called after sg_apply_pipeline") \
  3686. _SG_LOGITEM_XMACRO(VALIDATE_ABND_PIPELINE_ALIVE, "sg_apply_bindings: currently applied pipeline object no longer alive") \
  3687. _SG_LOGITEM_XMACRO(VALIDATE_ABND_PIPELINE_VALID, "sg_apply_bindings: currently applied pipeline object not in valid state") \
  3688. _SG_LOGITEM_XMACRO(VALIDATE_ABND_PIPELINE_SHADER_ALIVE, "sg_apply_bindings: shader associated with currently applied pipeline is no longer alive") \
  3689. _SG_LOGITEM_XMACRO(VALIDATE_ABND_PIPELINE_SHADER_VALID, "sg_apply_bindings: shader associated with currently applied pipeline is not in valid state") \
  3690. _SG_LOGITEM_XMACRO(VALIDATE_ABND_COMPUTE_EXPECTED_NO_VBS, "sg_apply_bindings: vertex buffer bindings not allowed in a compute pass") \
  3691. _SG_LOGITEM_XMACRO(VALIDATE_ABND_COMPUTE_EXPECTED_NO_IB, "sg_apply_bindings: index buffer binding not allowed in compute pass") \
  3692. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_VB, "sg_apply_bindings: vertex buffer binding is missing or buffer handle is invalid") \
  3693. _SG_LOGITEM_XMACRO(VALIDATE_ABND_VB_ALIVE, "sg_apply_bindings: vertex buffer no longer alive") \
  3694. _SG_LOGITEM_XMACRO(VALIDATE_ABND_VB_TYPE, "sg_apply_bindings: buffer in vertex buffer slot doesn't have vertex buffer usage (sg_buffer_desc.usage.storage_buffer)") \
  3695. _SG_LOGITEM_XMACRO(VALIDATE_ABND_VB_OVERFLOW, "sg_apply_bindings: buffer in vertex buffer slot is overflown") \
  3696. _SG_LOGITEM_XMACRO(VALIDATE_ABND_NO_IB, "sg_apply_bindings: pipeline object defines indexed rendering, but no index buffer provided") \
  3697. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IB, "sg_apply_bindings: pipeline object defines non-indexed rendering, but index buffer provided") \
  3698. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IB_ALIVE, "sg_apply_bindings: index buffer no longer alive") \
  3699. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IB_TYPE, "sg_apply_bindings: buffer in index buffer slot doesn't have index buffer usage (sg_buffer_desc.usage.index_buffer)") \
  3700. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IB_OVERFLOW, "sg_apply_bindings: buffer in index buffer slot is overflown") \
  3701. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_IMAGE_BINDING, "sg_apply_bindings: image binding is missing or the image handle is invalid") \
  3702. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IMG_ALIVE, "sg_apply_bindings: bound image no longer alive") \
  3703. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IMAGE_TYPE_MISMATCH, "sg_apply_bindings: type of bound image doesn't match shader desc") \
  3704. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_MULTISAMPLED_IMAGE, "sg_apply_bindings: expected image with sample_count > 1") \
  3705. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IMAGE_MSAA, "sg_apply_bindings: cannot bind image with sample_count>1") \
  3706. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_FILTERABLE_IMAGE, "sg_apply_bindings: filterable image expected") \
  3707. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_DEPTH_IMAGE, "sg_apply_bindings: depth image expected") \
  3708. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_SAMPLER_BINDING, "sg_apply_bindings: sampler binding is missing or the sampler handle is invalid") \
  3709. _SG_LOGITEM_XMACRO(VALIDATE_ABND_UNEXPECTED_SAMPLER_COMPARE_NEVER, "sg_apply_bindings: shader expects SG_SAMPLERTYPE_COMPARISON but sampler has SG_COMPAREFUNC_NEVER") \
  3710. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_SAMPLER_COMPARE_NEVER, "sg_apply_bindings: shader expects SG_SAMPLERTYPE_FILTERING or SG_SAMPLERTYPE_NONFILTERING but sampler doesn't have SG_COMPAREFUNC_NEVER") \
  3711. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_NONFILTERING_SAMPLER, "sg_apply_bindings: shader expected SG_SAMPLERTYPE_NONFILTERING, but sampler has SG_FILTER_LINEAR filters") \
  3712. _SG_LOGITEM_XMACRO(VALIDATE_ABND_SMP_ALIVE, "sg_apply_bindings: bound sampler no longer alive") \
  3713. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_STORAGEBUFFER_BINDING, "sg_apply_bindings: storage buffer binding is missing or the buffer handle is invalid") \
  3714. _SG_LOGITEM_XMACRO(VALIDATE_ABND_STORAGEBUFFER_ALIVE, "sg_apply_bindings: bound storage buffer no longer alive") \
  3715. _SG_LOGITEM_XMACRO(VALIDATE_ABND_STORAGEBUFFER_BINDING_BUFFERTYPE, "sg_apply_bindings: buffer bound to storage buffer slot doesn't have storage buffer usage (sg_buffer_desc.usage.storage_buffer)") \
  3716. _SG_LOGITEM_XMACRO(VALIDATE_ABND_STORAGEBUFFER_READWRITE_IMMUTABLE, "sg_apply_bindings: storage buffers bound as read/write must have usage immutable") \
  3717. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IMAGE_BINDING_VS_DEPTHSTENCIL_ATTACHMENT, "sg_apply_bindings: cannot bind image in the same pass it is used as depth-stencil attachment") \
  3718. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IMAGE_BINDING_VS_COLOR_ATTACHMENT, "sg_apply_bindings: cannot bind image in the same pass it is used as color attachment") \
  3719. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IMAGE_BINDING_VS_RESOLVE_ATTACHMENT, "sg_apply_bindings: cannot bind image in the same pass it is used as resolve attachment") \
  3720. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IMAGE_BINDING_VS_STORAGE_ATTACHMENT, "sg_apply_bindings: cannot bind image in the same pass it is used as storage attachment") \
  3721. _SG_LOGITEM_XMACRO(VALIDATE_AU_PASS_EXPECTED, "sg_apply_uniforms: must be called in a pass") \
  3722. _SG_LOGITEM_XMACRO(VALIDATE_AU_NO_PIPELINE, "sg_apply_uniforms: must be called after sg_apply_pipeline()") \
  3723. _SG_LOGITEM_XMACRO(VALIDATE_AU_PIPELINE_ALIVE, "sg_apply_uniforms: currently applied pipeline object no longer alive") \
  3724. _SG_LOGITEM_XMACRO(VALIDATE_AU_PIPELINE_VALID, "sg_apply_uniforms: currently applied pipeline object not in valid state") \
  3725. _SG_LOGITEM_XMACRO(VALIDATE_AU_PIPELINE_SHADER_ALIVE, "sg_apply_uniforms: shader associated with currently applied pipeline is no longer alive") \
  3726. _SG_LOGITEM_XMACRO(VALIDATE_AU_PIPELINE_SHADER_VALID, "sg_apply_uniforms: shader associated with currently applied pipeline is not in valid state") \
  3727. _SG_LOGITEM_XMACRO(VALIDATE_AU_NO_UNIFORMBLOCK_AT_SLOT, "sg_apply_uniforms: no uniform block declaration at this shader stage UB slot") \
  3728. _SG_LOGITEM_XMACRO(VALIDATE_AU_SIZE, "sg_apply_uniforms: data size doesn't match declared uniform block size") \
  3729. _SG_LOGITEM_XMACRO(VALIDATE_DRAW_RENDERPASS_EXPECTED, "sg_draw: must be called in a render pass") \
  3730. _SG_LOGITEM_XMACRO(VALIDATE_DRAW_BASEELEMENT, "sg_draw: base_element cannot be < 0") \
  3731. _SG_LOGITEM_XMACRO(VALIDATE_DRAW_NUMELEMENTS, "sg_draw: num_elements cannot be < 0") \
  3732. _SG_LOGITEM_XMACRO(VALIDATE_DRAW_NUMINSTANCES, "sg_draw: num_instances cannot be < 0") \
  3733. _SG_LOGITEM_XMACRO(VALIDATE_DRAW_REQUIRED_BINDINGS_OR_UNIFORMS_MISSING, "sg_draw: call to sg_apply_bindings() and/or sg_apply_uniforms() missing after sg_apply_pipeline()") \
  3734. _SG_LOGITEM_XMACRO(VALIDATE_DISPATCH_COMPUTEPASS_EXPECTED, "sg_dispatch: must be called in a compute pass") \
  3735. _SG_LOGITEM_XMACRO(VALIDATE_DISPATCH_NUMGROUPSX, "sg_dispatch: num_groups_x must be >=0 and <65536") \
  3736. _SG_LOGITEM_XMACRO(VALIDATE_DISPATCH_NUMGROUPSY, "sg_dispatch: num_groups_y must be >=0 and <65536") \
  3737. _SG_LOGITEM_XMACRO(VALIDATE_DISPATCH_NUMGROUPSZ, "sg_dispatch: num_groups_z must be >=0 and <65536") \
  3738. _SG_LOGITEM_XMACRO(VALIDATE_DISPATCH_REQUIRED_BINDINGS_OR_UNIFORMS_MISSING, "sg_dispatch: call to sg_apply_bindings() and/or sg_apply_uniforms() missing after sg_apply_pipeline()") \
  3739. _SG_LOGITEM_XMACRO(VALIDATE_UPDATEBUF_USAGE, "sg_update_buffer: cannot update immutable buffer") \
  3740. _SG_LOGITEM_XMACRO(VALIDATE_UPDATEBUF_SIZE, "sg_update_buffer: update size is bigger than buffer size") \
  3741. _SG_LOGITEM_XMACRO(VALIDATE_UPDATEBUF_ONCE, "sg_update_buffer: only one update allowed per buffer and frame") \
  3742. _SG_LOGITEM_XMACRO(VALIDATE_UPDATEBUF_APPEND, "sg_update_buffer: cannot call sg_update_buffer and sg_append_buffer in same frame") \
  3743. _SG_LOGITEM_XMACRO(VALIDATE_APPENDBUF_USAGE, "sg_append_buffer: cannot append to immutable buffer") \
  3744. _SG_LOGITEM_XMACRO(VALIDATE_APPENDBUF_SIZE, "sg_append_buffer: overall appended size is bigger than buffer size") \
  3745. _SG_LOGITEM_XMACRO(VALIDATE_APPENDBUF_UPDATE, "sg_append_buffer: cannot call sg_append_buffer and sg_update_buffer in same frame") \
  3746. _SG_LOGITEM_XMACRO(VALIDATE_UPDIMG_USAGE, "sg_update_image: cannot update immutable image") \
  3747. _SG_LOGITEM_XMACRO(VALIDATE_UPDIMG_ONCE, "sg_update_image: only one update allowed per image and frame") \
  3748. _SG_LOGITEM_XMACRO(VALIDATION_FAILED, "validation layer checks failed") \
  3749. #define _SG_LOGITEM_XMACRO(item,msg) SG_LOGITEM_##item,
  3750. typedef enum sg_log_item {
  3751. _SG_LOG_ITEMS
  3752. } sg_log_item;
  3753. #undef _SG_LOGITEM_XMACRO
  3754. /*
  3755. sg_desc
  3756. The sg_desc struct contains configuration values for sokol_gfx,
  3757. it is used as parameter to the sg_setup() call.
  3758. The default configuration is:
  3759. .buffer_pool_size 128
  3760. .image_pool_size 128
  3761. .sampler_pool_size 64
  3762. .shader_pool_size 32
  3763. .pipeline_pool_size 64
  3764. .attachments_pool_size 16
  3765. .uniform_buffer_size 4 MB (4*1024*1024)
  3766. .max_dispatch_calls_per_pass 1024
  3767. .max_commit_listeners 1024
  3768. .disable_validation false
  3769. .mtl_force_managed_storage_mode false
  3770. .wgpu_disable_bindgroups_cache false
  3771. .wgpu_bindgroups_cache_size 1024
  3772. .allocator.alloc_fn 0 (in this case, malloc() will be called)
  3773. .allocator.free_fn 0 (in this case, free() will be called)
  3774. .allocator.user_data 0
  3775. .environment.defaults.color_format: default value depends on selected backend:
  3776. all GL backends: SG_PIXELFORMAT_RGBA8
  3777. Metal and D3D11: SG_PIXELFORMAT_BGRA8
  3778. WebGPU: *no default* (must be queried from WebGPU swapchain object)
  3779. .environment.defaults.depth_format: SG_PIXELFORMAT_DEPTH_STENCIL
  3780. .environment.defaults.sample_count: 1
  3781. Metal specific:
  3782. (NOTE: All Objective-C object references are transferred through
  3783. a bridged cast (__bridge const void*) to sokol_gfx, which will use an
  3784. unretained bridged cast (__bridge id<xxx>) to retrieve the Objective-C
  3785. references back. Since the bridge cast is unretained, the caller
  3786. must hold a strong reference to the Objective-C object until sg_setup()
  3787. returns.
  3788. .mtl_force_managed_storage_mode
  3789. when enabled, Metal buffers and texture resources are created in managed storage
  3790. mode, otherwise sokol-gfx will decide whether to create buffers and
  3791. textures in managed or shared storage mode (this is mainly a debugging option)
  3792. .mtl_use_command_buffer_with_retained_references
  3793. when true, the sokol-gfx Metal backend will use Metal command buffers which
  3794. bump the reference count of resource objects as long as they are inflight,
  3795. this is slower than the default command-buffer-with-unretained-references
  3796. method, this may be a workaround when confronted with lifetime validation
  3797. errors from the Metal validation layer until a proper fix has been implemented
  3798. .environment.metal.device
  3799. a pointer to the MTLDevice object
  3800. D3D11 specific:
  3801. .environment.d3d11.device
  3802. a pointer to the ID3D11Device object, this must have been created
  3803. before sg_setup() is called
  3804. .environment.d3d11.device_context
  3805. a pointer to the ID3D11DeviceContext object
  3806. .d3d11_shader_debugging
  3807. set this to true to compile shaders which are provided as HLSL source
  3808. code with debug information and without optimization, this allows
  3809. shader debugging in tools like RenderDoc, to output source code
  3810. instead of byte code from sokol-shdc, omit the `--binary` cmdline
  3811. option
  3812. WebGPU specific:
  3813. .wgpu_disable_bindgroups_cache
  3814. When this is true, the WebGPU backend will create and immediately
  3815. release a BindGroup object in the sg_apply_bindings() call, only
  3816. use this for debugging purposes.
  3817. .wgpu_bindgroups_cache_size
  3818. The size of the bindgroups cache for re-using BindGroup objects
  3819. between sg_apply_bindings() calls. The smaller the cache size,
  3820. the more likely are cache slot collisions which will cause
  3821. a BindGroups object to be destroyed and a new one created.
  3822. Use the information returned by sg_query_stats() to check
  3823. if this is a frequent occurrence, and increase the cache size as
  3824. needed (the default is 1024).
  3825. NOTE: wgpu_bindgroups_cache_size must be a power-of-2 number!
  3826. .environment.wgpu.device
  3827. a WGPUDevice handle
  3828. When using sokol_gfx.h and sokol_app.h together, consider using the
  3829. helper function sglue_environment() in the sokol_glue.h header to
  3830. initialize the sg_desc.environment nested struct. sglue_environment() returns
  3831. a completely initialized sg_environment struct with information
  3832. provided by sokol_app.h.
  3833. */
  3834. typedef struct sg_environment_defaults {
  3835. sg_pixel_format color_format;
  3836. sg_pixel_format depth_format;
  3837. int sample_count;
  3838. } sg_environment_defaults;
  3839. typedef struct sg_metal_environment {
  3840. const void* device;
  3841. } sg_metal_environment;
  3842. typedef struct sg_d3d11_environment {
  3843. const void* device;
  3844. const void* device_context;
  3845. } sg_d3d11_environment;
  3846. typedef struct sg_wgpu_environment {
  3847. const void* device;
  3848. } sg_wgpu_environment;
  3849. typedef struct sg_environment {
  3850. sg_environment_defaults defaults;
  3851. sg_metal_environment metal;
  3852. sg_d3d11_environment d3d11;
  3853. sg_wgpu_environment wgpu;
  3854. } sg_environment;
  3855. /*
  3856. sg_commit_listener
  3857. Used with function sg_add_commit_listener() to add a callback
  3858. which will be called in sg_commit(). This is useful for libraries
  3859. building on top of sokol-gfx to be notified about when a frame
  3860. ends (instead of having to guess, or add a manual 'new-frame'
  3861. function.
  3862. */
  3863. typedef struct sg_commit_listener {
  3864. void (*func)(void* user_data);
  3865. void* user_data;
  3866. } sg_commit_listener;
  3867. /*
  3868. sg_allocator
  3869. Used in sg_desc to provide custom memory-alloc and -free functions
  3870. to sokol_gfx.h. If memory management should be overridden, both the
  3871. alloc_fn and free_fn function must be provided (e.g. it's not valid to
  3872. override one function but not the other).
  3873. */
  3874. typedef struct sg_allocator {
  3875. void* (*alloc_fn)(size_t size, void* user_data);
  3876. void (*free_fn)(void* ptr, void* user_data);
  3877. void* user_data;
  3878. } sg_allocator;
  3879. /*
  3880. sg_logger
  3881. Used in sg_desc to provide a logging function. Please be aware
  3882. that without logging function, sokol-gfx will be completely
  3883. silent, e.g. it will not report errors, warnings and
  3884. validation layer messages. For maximum error verbosity,
  3885. compile in debug mode (e.g. NDEBUG *not* defined) and provide a
  3886. compatible logger function in the sg_setup() call
  3887. (for instance the standard logging function from sokol_log.h).
  3888. */
  3889. typedef struct sg_logger {
  3890. void (*func)(
  3891. const char* tag, // always "sg"
  3892. uint32_t log_level, // 0=panic, 1=error, 2=warning, 3=info
  3893. uint32_t log_item_id, // SG_LOGITEM_*
  3894. const char* message_or_null, // a message string, may be nullptr in release mode
  3895. uint32_t line_nr, // line number in sokol_gfx.h
  3896. const char* filename_or_null, // source filename, may be nullptr in release mode
  3897. void* user_data);
  3898. void* user_data;
  3899. } sg_logger;
  3900. typedef struct sg_desc {
  3901. uint32_t _start_canary;
  3902. int buffer_pool_size;
  3903. int image_pool_size;
  3904. int sampler_pool_size;
  3905. int shader_pool_size;
  3906. int pipeline_pool_size;
  3907. int attachments_pool_size;
  3908. int uniform_buffer_size;
  3909. int max_dispatch_calls_per_pass; // max expected number of dispatch calls per pass (default: 1024)
  3910. int max_commit_listeners;
  3911. bool disable_validation; // disable validation layer even in debug mode, useful for tests
  3912. bool d3d11_shader_debugging; // if true, HLSL shaders are compiled with D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION
  3913. bool mtl_force_managed_storage_mode; // for debugging: use Metal managed storage mode for resources even with UMA
  3914. bool mtl_use_command_buffer_with_retained_references; // Metal: use a managed MTLCommandBuffer which ref-counts used resources
  3915. bool wgpu_disable_bindgroups_cache; // set to true to disable the WebGPU backend BindGroup cache
  3916. int wgpu_bindgroups_cache_size; // number of slots in the WebGPU bindgroup cache (must be 2^N)
  3917. sg_allocator allocator;
  3918. sg_logger logger; // optional log function override
  3919. sg_environment environment;
  3920. uint32_t _end_canary;
  3921. } sg_desc;
  3922. // setup and misc functions
  3923. SOKOL_GFX_API_DECL void sg_setup(const sg_desc* desc);
  3924. SOKOL_GFX_API_DECL void sg_shutdown(void);
  3925. SOKOL_GFX_API_DECL bool sg_isvalid(void);
  3926. SOKOL_GFX_API_DECL void sg_reset_state_cache(void);
  3927. SOKOL_GFX_API_DECL sg_trace_hooks sg_install_trace_hooks(const sg_trace_hooks* trace_hooks);
  3928. SOKOL_GFX_API_DECL void sg_push_debug_group(const char* name);
  3929. SOKOL_GFX_API_DECL void sg_pop_debug_group(void);
  3930. SOKOL_GFX_API_DECL bool sg_add_commit_listener(sg_commit_listener listener);
  3931. SOKOL_GFX_API_DECL bool sg_remove_commit_listener(sg_commit_listener listener);
  3932. // resource creation, destruction and updating
  3933. SOKOL_GFX_API_DECL sg_buffer sg_make_buffer(const sg_buffer_desc* desc);
  3934. SOKOL_GFX_API_DECL sg_image sg_make_image(const sg_image_desc* desc);
  3935. SOKOL_GFX_API_DECL sg_sampler sg_make_sampler(const sg_sampler_desc* desc);
  3936. SOKOL_GFX_API_DECL sg_shader sg_make_shader(const sg_shader_desc* desc);
  3937. SOKOL_GFX_API_DECL sg_pipeline sg_make_pipeline(const sg_pipeline_desc* desc);
  3938. SOKOL_GFX_API_DECL sg_attachments sg_make_attachments(const sg_attachments_desc* desc);
  3939. SOKOL_GFX_API_DECL void sg_destroy_buffer(sg_buffer buf);
  3940. SOKOL_GFX_API_DECL void sg_destroy_image(sg_image img);
  3941. SOKOL_GFX_API_DECL void sg_destroy_sampler(sg_sampler smp);
  3942. SOKOL_GFX_API_DECL void sg_destroy_shader(sg_shader shd);
  3943. SOKOL_GFX_API_DECL void sg_destroy_pipeline(sg_pipeline pip);
  3944. SOKOL_GFX_API_DECL void sg_destroy_attachments(sg_attachments atts);
  3945. SOKOL_GFX_API_DECL void sg_update_buffer(sg_buffer buf, const sg_range* data);
  3946. SOKOL_GFX_API_DECL void sg_update_image(sg_image img, const sg_image_data* data);
  3947. SOKOL_GFX_API_DECL int sg_append_buffer(sg_buffer buf, const sg_range* data);
  3948. SOKOL_GFX_API_DECL bool sg_query_buffer_overflow(sg_buffer buf);
  3949. SOKOL_GFX_API_DECL bool sg_query_buffer_will_overflow(sg_buffer buf, size_t size);
  3950. // render and compute functions
  3951. SOKOL_GFX_API_DECL void sg_begin_pass(const sg_pass* pass);
  3952. SOKOL_GFX_API_DECL void sg_apply_viewport(int x, int y, int width, int height, bool origin_top_left);
  3953. SOKOL_GFX_API_DECL void sg_apply_viewportf(float x, float y, float width, float height, bool origin_top_left);
  3954. SOKOL_GFX_API_DECL void sg_apply_scissor_rect(int x, int y, int width, int height, bool origin_top_left);
  3955. SOKOL_GFX_API_DECL void sg_apply_scissor_rectf(float x, float y, float width, float height, bool origin_top_left);
  3956. SOKOL_GFX_API_DECL void sg_apply_pipeline(sg_pipeline pip);
  3957. SOKOL_GFX_API_DECL void sg_apply_bindings(const sg_bindings* bindings);
  3958. SOKOL_GFX_API_DECL void sg_apply_uniforms(int ub_slot, const sg_range* data);
  3959. SOKOL_GFX_API_DECL void sg_draw(int base_element, int num_elements, int num_instances);
  3960. SOKOL_GFX_API_DECL void sg_dispatch(int num_groups_x, int num_groups_y, int num_groups_z);
  3961. SOKOL_GFX_API_DECL void sg_end_pass(void);
  3962. SOKOL_GFX_API_DECL void sg_commit(void);
  3963. // getting information
  3964. SOKOL_GFX_API_DECL sg_desc sg_query_desc(void);
  3965. SOKOL_GFX_API_DECL sg_backend sg_query_backend(void);
  3966. SOKOL_GFX_API_DECL sg_features sg_query_features(void);
  3967. SOKOL_GFX_API_DECL sg_limits sg_query_limits(void);
  3968. SOKOL_GFX_API_DECL sg_pixelformat_info sg_query_pixelformat(sg_pixel_format fmt);
  3969. SOKOL_GFX_API_DECL int sg_query_row_pitch(sg_pixel_format fmt, int width, int row_align_bytes);
  3970. SOKOL_GFX_API_DECL int sg_query_surface_pitch(sg_pixel_format fmt, int width, int height, int row_align_bytes);
  3971. // get current state of a resource (INITIAL, ALLOC, VALID, FAILED, INVALID)
  3972. SOKOL_GFX_API_DECL sg_resource_state sg_query_buffer_state(sg_buffer buf);
  3973. SOKOL_GFX_API_DECL sg_resource_state sg_query_image_state(sg_image img);
  3974. SOKOL_GFX_API_DECL sg_resource_state sg_query_sampler_state(sg_sampler smp);
  3975. SOKOL_GFX_API_DECL sg_resource_state sg_query_shader_state(sg_shader shd);
  3976. SOKOL_GFX_API_DECL sg_resource_state sg_query_pipeline_state(sg_pipeline pip);
  3977. SOKOL_GFX_API_DECL sg_resource_state sg_query_attachments_state(sg_attachments atts);
  3978. // get runtime information about a resource
  3979. SOKOL_GFX_API_DECL sg_buffer_info sg_query_buffer_info(sg_buffer buf);
  3980. SOKOL_GFX_API_DECL sg_image_info sg_query_image_info(sg_image img);
  3981. SOKOL_GFX_API_DECL sg_sampler_info sg_query_sampler_info(sg_sampler smp);
  3982. SOKOL_GFX_API_DECL sg_shader_info sg_query_shader_info(sg_shader shd);
  3983. SOKOL_GFX_API_DECL sg_pipeline_info sg_query_pipeline_info(sg_pipeline pip);
  3984. SOKOL_GFX_API_DECL sg_attachments_info sg_query_attachments_info(sg_attachments atts);
  3985. // get desc structs matching a specific resource (NOTE that not all creation attributes may be provided)
  3986. SOKOL_GFX_API_DECL sg_buffer_desc sg_query_buffer_desc(sg_buffer buf);
  3987. SOKOL_GFX_API_DECL sg_image_desc sg_query_image_desc(sg_image img);
  3988. SOKOL_GFX_API_DECL sg_sampler_desc sg_query_sampler_desc(sg_sampler smp);
  3989. SOKOL_GFX_API_DECL sg_shader_desc sg_query_shader_desc(sg_shader shd);
  3990. SOKOL_GFX_API_DECL sg_pipeline_desc sg_query_pipeline_desc(sg_pipeline pip);
  3991. SOKOL_GFX_API_DECL sg_attachments_desc sg_query_attachments_desc(sg_attachments atts);
  3992. // get resource creation desc struct with their default values replaced
  3993. SOKOL_GFX_API_DECL sg_buffer_desc sg_query_buffer_defaults(const sg_buffer_desc* desc);
  3994. SOKOL_GFX_API_DECL sg_image_desc sg_query_image_defaults(const sg_image_desc* desc);
  3995. SOKOL_GFX_API_DECL sg_sampler_desc sg_query_sampler_defaults(const sg_sampler_desc* desc);
  3996. SOKOL_GFX_API_DECL sg_shader_desc sg_query_shader_defaults(const sg_shader_desc* desc);
  3997. SOKOL_GFX_API_DECL sg_pipeline_desc sg_query_pipeline_defaults(const sg_pipeline_desc* desc);
  3998. SOKOL_GFX_API_DECL sg_attachments_desc sg_query_attachments_defaults(const sg_attachments_desc* desc);
  3999. // assorted query functions
  4000. SOKOL_GFX_API_DECL size_t sg_query_buffer_size(sg_buffer buf);
  4001. SOKOL_GFX_API_DECL sg_buffer_usage sg_query_buffer_usage(sg_buffer buf);
  4002. SOKOL_GFX_API_DECL sg_image_type sg_query_image_type(sg_image img);
  4003. SOKOL_GFX_API_DECL int sg_query_image_width(sg_image img);
  4004. SOKOL_GFX_API_DECL int sg_query_image_height(sg_image img);
  4005. SOKOL_GFX_API_DECL int sg_query_image_num_slices(sg_image img);
  4006. SOKOL_GFX_API_DECL int sg_query_image_num_mipmaps(sg_image img);
  4007. SOKOL_GFX_API_DECL sg_pixel_format sg_query_image_pixelformat(sg_image img);
  4008. SOKOL_GFX_API_DECL sg_image_usage sg_query_image_usage(sg_image img);
  4009. SOKOL_GFX_API_DECL int sg_query_image_sample_count(sg_image img);
  4010. // separate resource allocation and initialization (for async setup)
  4011. SOKOL_GFX_API_DECL sg_buffer sg_alloc_buffer(void);
  4012. SOKOL_GFX_API_DECL sg_image sg_alloc_image(void);
  4013. SOKOL_GFX_API_DECL sg_sampler sg_alloc_sampler(void);
  4014. SOKOL_GFX_API_DECL sg_shader sg_alloc_shader(void);
  4015. SOKOL_GFX_API_DECL sg_pipeline sg_alloc_pipeline(void);
  4016. SOKOL_GFX_API_DECL sg_attachments sg_alloc_attachments(void);
  4017. SOKOL_GFX_API_DECL void sg_dealloc_buffer(sg_buffer buf);
  4018. SOKOL_GFX_API_DECL void sg_dealloc_image(sg_image img);
  4019. SOKOL_GFX_API_DECL void sg_dealloc_sampler(sg_sampler smp);
  4020. SOKOL_GFX_API_DECL void sg_dealloc_shader(sg_shader shd);
  4021. SOKOL_GFX_API_DECL void sg_dealloc_pipeline(sg_pipeline pip);
  4022. SOKOL_GFX_API_DECL void sg_dealloc_attachments(sg_attachments attachments);
  4023. SOKOL_GFX_API_DECL void sg_init_buffer(sg_buffer buf, const sg_buffer_desc* desc);
  4024. SOKOL_GFX_API_DECL void sg_init_image(sg_image img, const sg_image_desc* desc);
  4025. SOKOL_GFX_API_DECL void sg_init_sampler(sg_sampler smg, const sg_sampler_desc* desc);
  4026. SOKOL_GFX_API_DECL void sg_init_shader(sg_shader shd, const sg_shader_desc* desc);
  4027. SOKOL_GFX_API_DECL void sg_init_pipeline(sg_pipeline pip, const sg_pipeline_desc* desc);
  4028. SOKOL_GFX_API_DECL void sg_init_attachments(sg_attachments attachments, const sg_attachments_desc* desc);
  4029. SOKOL_GFX_API_DECL void sg_uninit_buffer(sg_buffer buf);
  4030. SOKOL_GFX_API_DECL void sg_uninit_image(sg_image img);
  4031. SOKOL_GFX_API_DECL void sg_uninit_sampler(sg_sampler smp);
  4032. SOKOL_GFX_API_DECL void sg_uninit_shader(sg_shader shd);
  4033. SOKOL_GFX_API_DECL void sg_uninit_pipeline(sg_pipeline pip);
  4034. SOKOL_GFX_API_DECL void sg_uninit_attachments(sg_attachments atts);
  4035. SOKOL_GFX_API_DECL void sg_fail_buffer(sg_buffer buf);
  4036. SOKOL_GFX_API_DECL void sg_fail_image(sg_image img);
  4037. SOKOL_GFX_API_DECL void sg_fail_sampler(sg_sampler smp);
  4038. SOKOL_GFX_API_DECL void sg_fail_shader(sg_shader shd);
  4039. SOKOL_GFX_API_DECL void sg_fail_pipeline(sg_pipeline pip);
  4040. SOKOL_GFX_API_DECL void sg_fail_attachments(sg_attachments atts);
  4041. // frame stats
  4042. SOKOL_GFX_API_DECL void sg_enable_frame_stats(void);
  4043. SOKOL_GFX_API_DECL void sg_disable_frame_stats(void);
  4044. SOKOL_GFX_API_DECL bool sg_frame_stats_enabled(void);
  4045. SOKOL_GFX_API_DECL sg_frame_stats sg_query_frame_stats(void);
  4046. /* Backend-specific structs and functions, these may come in handy for mixing
  4047. sokol-gfx rendering with 'native backend' rendering functions.
  4048. This group of functions will be expanded as needed.
  4049. */
  4050. typedef struct sg_d3d11_buffer_info {
  4051. const void* buf; // ID3D11Buffer*
  4052. } sg_d3d11_buffer_info;
  4053. typedef struct sg_d3d11_image_info {
  4054. const void* tex2d; // ID3D11Texture2D*
  4055. const void* tex3d; // ID3D11Texture3D*
  4056. const void* res; // ID3D11Resource* (either tex2d or tex3d)
  4057. const void* srv; // ID3D11ShaderResourceView*
  4058. } sg_d3d11_image_info;
  4059. typedef struct sg_d3d11_sampler_info {
  4060. const void* smp; // ID3D11SamplerState*
  4061. } sg_d3d11_sampler_info;
  4062. typedef struct sg_d3d11_shader_info {
  4063. const void* cbufs[SG_MAX_UNIFORMBLOCK_BINDSLOTS]; // ID3D11Buffer* (constant buffers by bind slot)
  4064. const void* vs; // ID3D11VertexShader*
  4065. const void* fs; // ID3D11PixelShader*
  4066. } sg_d3d11_shader_info;
  4067. typedef struct sg_d3d11_pipeline_info {
  4068. const void* il; // ID3D11InputLayout*
  4069. const void* rs; // ID3D11RasterizerState*
  4070. const void* dss; // ID3D11DepthStencilState*
  4071. const void* bs; // ID3D11BlendState*
  4072. } sg_d3d11_pipeline_info;
  4073. typedef struct sg_d3d11_attachments_info {
  4074. const void* color_rtv[SG_MAX_COLOR_ATTACHMENTS]; // ID3D11RenderTargetView
  4075. const void* resolve_rtv[SG_MAX_COLOR_ATTACHMENTS]; // ID3D11RenderTargetView
  4076. const void* dsv; // ID3D11DepthStencilView
  4077. } sg_d3d11_attachments_info;
  4078. typedef struct sg_mtl_buffer_info {
  4079. const void* buf[SG_NUM_INFLIGHT_FRAMES]; // id<MTLBuffer>
  4080. int active_slot;
  4081. } sg_mtl_buffer_info;
  4082. typedef struct sg_mtl_image_info {
  4083. const void* tex[SG_NUM_INFLIGHT_FRAMES]; // id<MTLTexture>
  4084. int active_slot;
  4085. } sg_mtl_image_info;
  4086. typedef struct sg_mtl_sampler_info {
  4087. const void* smp; // id<MTLSamplerState>
  4088. } sg_mtl_sampler_info;
  4089. typedef struct sg_mtl_shader_info {
  4090. const void* vertex_lib; // id<MTLLibrary>
  4091. const void* fragment_lib; // id<MTLLibrary>
  4092. const void* vertex_func; // id<MTLFunction>
  4093. const void* fragment_func; // id<MTLFunction>
  4094. } sg_mtl_shader_info;
  4095. typedef struct sg_mtl_pipeline_info {
  4096. const void* rps; // id<MTLRenderPipelineState>
  4097. const void* dss; // id<MTLDepthStencilState>
  4098. } sg_mtl_pipeline_info;
  4099. typedef struct sg_wgpu_buffer_info {
  4100. const void* buf; // WGPUBuffer
  4101. } sg_wgpu_buffer_info;
  4102. typedef struct sg_wgpu_image_info {
  4103. const void* tex; // WGPUTexture
  4104. const void* view; // WGPUTextureView
  4105. } sg_wgpu_image_info;
  4106. typedef struct sg_wgpu_sampler_info {
  4107. const void* smp; // WGPUSampler
  4108. } sg_wgpu_sampler_info;
  4109. typedef struct sg_wgpu_shader_info {
  4110. const void* vs_mod; // WGPUShaderModule
  4111. const void* fs_mod; // WGPUShaderModule
  4112. const void* bgl; // WGPUBindGroupLayout;
  4113. } sg_wgpu_shader_info;
  4114. typedef struct sg_wgpu_pipeline_info {
  4115. const void* render_pipeline; // WGPURenderPipeline
  4116. const void* compute_pipeline; // WGPUComputePipeline
  4117. } sg_wgpu_pipeline_info;
  4118. typedef struct sg_wgpu_attachments_info {
  4119. const void* color_view[SG_MAX_COLOR_ATTACHMENTS]; // WGPUTextureView
  4120. const void* resolve_view[SG_MAX_COLOR_ATTACHMENTS]; // WGPUTextureView
  4121. const void* ds_view; // WGPUTextureView
  4122. } sg_wgpu_attachments_info;
  4123. typedef struct sg_gl_buffer_info {
  4124. uint32_t buf[SG_NUM_INFLIGHT_FRAMES];
  4125. int active_slot;
  4126. } sg_gl_buffer_info;
  4127. typedef struct sg_gl_image_info {
  4128. uint32_t tex[SG_NUM_INFLIGHT_FRAMES];
  4129. uint32_t tex_target;
  4130. uint32_t msaa_render_buffer;
  4131. int active_slot;
  4132. } sg_gl_image_info;
  4133. typedef struct sg_gl_sampler_info {
  4134. uint32_t smp;
  4135. } sg_gl_sampler_info;
  4136. typedef struct sg_gl_shader_info {
  4137. uint32_t prog;
  4138. } sg_gl_shader_info;
  4139. typedef struct sg_gl_attachments_info {
  4140. uint32_t framebuffer;
  4141. uint32_t msaa_resolve_framebuffer[SG_MAX_COLOR_ATTACHMENTS];
  4142. } sg_gl_attachments_info;
  4143. // D3D11: return ID3D11Device
  4144. SOKOL_GFX_API_DECL const void* sg_d3d11_device(void);
  4145. // D3D11: return ID3D11DeviceContext
  4146. SOKOL_GFX_API_DECL const void* sg_d3d11_device_context(void);
  4147. // D3D11: get internal buffer resource objects
  4148. SOKOL_GFX_API_DECL sg_d3d11_buffer_info sg_d3d11_query_buffer_info(sg_buffer buf);
  4149. // D3D11: get internal image resource objects
  4150. SOKOL_GFX_API_DECL sg_d3d11_image_info sg_d3d11_query_image_info(sg_image img);
  4151. // D3D11: get internal sampler resource objects
  4152. SOKOL_GFX_API_DECL sg_d3d11_sampler_info sg_d3d11_query_sampler_info(sg_sampler smp);
  4153. // D3D11: get internal shader resource objects
  4154. SOKOL_GFX_API_DECL sg_d3d11_shader_info sg_d3d11_query_shader_info(sg_shader shd);
  4155. // D3D11: get internal pipeline resource objects
  4156. SOKOL_GFX_API_DECL sg_d3d11_pipeline_info sg_d3d11_query_pipeline_info(sg_pipeline pip);
  4157. // D3D11: get internal pass resource objects
  4158. SOKOL_GFX_API_DECL sg_d3d11_attachments_info sg_d3d11_query_attachments_info(sg_attachments atts);
  4159. // Metal: return __bridge-casted MTLDevice
  4160. SOKOL_GFX_API_DECL const void* sg_mtl_device(void);
  4161. // Metal: return __bridge-casted MTLRenderCommandEncoder when inside render pass (otherwise zero)
  4162. SOKOL_GFX_API_DECL const void* sg_mtl_render_command_encoder(void);
  4163. // Metal: return __bridge-casted MTLComputeCommandEncoder when inside compute pass (otherwise zero)
  4164. SOKOL_GFX_API_DECL const void* sg_mtl_compute_command_encoder(void);
  4165. // Metal: get internal __bridge-casted buffer resource objects
  4166. SOKOL_GFX_API_DECL sg_mtl_buffer_info sg_mtl_query_buffer_info(sg_buffer buf);
  4167. // Metal: get internal __bridge-casted image resource objects
  4168. SOKOL_GFX_API_DECL sg_mtl_image_info sg_mtl_query_image_info(sg_image img);
  4169. // Metal: get internal __bridge-casted sampler resource objects
  4170. SOKOL_GFX_API_DECL sg_mtl_sampler_info sg_mtl_query_sampler_info(sg_sampler smp);
  4171. // Metal: get internal __bridge-casted shader resource objects
  4172. SOKOL_GFX_API_DECL sg_mtl_shader_info sg_mtl_query_shader_info(sg_shader shd);
  4173. // Metal: get internal __bridge-casted pipeline resource objects
  4174. SOKOL_GFX_API_DECL sg_mtl_pipeline_info sg_mtl_query_pipeline_info(sg_pipeline pip);
  4175. // WebGPU: return WGPUDevice object
  4176. SOKOL_GFX_API_DECL const void* sg_wgpu_device(void);
  4177. // WebGPU: return WGPUQueue object
  4178. SOKOL_GFX_API_DECL const void* sg_wgpu_queue(void);
  4179. // WebGPU: return this frame's WGPUCommandEncoder
  4180. SOKOL_GFX_API_DECL const void* sg_wgpu_command_encoder(void);
  4181. // WebGPU: return WGPURenderPassEncoder of current pass (returns 0 when outside pass or in a compute pass)
  4182. SOKOL_GFX_API_DECL const void* sg_wgpu_render_pass_encoder(void);
  4183. // WebGPU: return WGPUComputePassEncoder of current pass (returns 0 when outside pass or in a render pass)
  4184. SOKOL_GFX_API_DECL const void* sg_wgpu_compute_pass_encoder(void);
  4185. // WebGPU: get internal buffer resource objects
  4186. SOKOL_GFX_API_DECL sg_wgpu_buffer_info sg_wgpu_query_buffer_info(sg_buffer buf);
  4187. // WebGPU: get internal image resource objects
  4188. SOKOL_GFX_API_DECL sg_wgpu_image_info sg_wgpu_query_image_info(sg_image img);
  4189. // WebGPU: get internal sampler resource objects
  4190. SOKOL_GFX_API_DECL sg_wgpu_sampler_info sg_wgpu_query_sampler_info(sg_sampler smp);
  4191. // WebGPU: get internal shader resource objects
  4192. SOKOL_GFX_API_DECL sg_wgpu_shader_info sg_wgpu_query_shader_info(sg_shader shd);
  4193. // WebGPU: get internal pipeline resource objects
  4194. SOKOL_GFX_API_DECL sg_wgpu_pipeline_info sg_wgpu_query_pipeline_info(sg_pipeline pip);
  4195. // WebGPU: get internal pass resource objects
  4196. SOKOL_GFX_API_DECL sg_wgpu_attachments_info sg_wgpu_query_attachments_info(sg_attachments atts);
  4197. // GL: get internal buffer resource objects
  4198. SOKOL_GFX_API_DECL sg_gl_buffer_info sg_gl_query_buffer_info(sg_buffer buf);
  4199. // GL: get internal image resource objects
  4200. SOKOL_GFX_API_DECL sg_gl_image_info sg_gl_query_image_info(sg_image img);
  4201. // GL: get internal sampler resource objects
  4202. SOKOL_GFX_API_DECL sg_gl_sampler_info sg_gl_query_sampler_info(sg_sampler smp);
  4203. // GL: get internal shader resource objects
  4204. SOKOL_GFX_API_DECL sg_gl_shader_info sg_gl_query_shader_info(sg_shader shd);
  4205. // GL: get internal pass resource objects
  4206. SOKOL_GFX_API_DECL sg_gl_attachments_info sg_gl_query_attachments_info(sg_attachments atts);
  4207. #ifdef __cplusplus
  4208. } // extern "C"
  4209. // reference-based equivalents for c++
  4210. inline void sg_setup(const sg_desc& desc) { return sg_setup(&desc); }
  4211. inline sg_buffer sg_make_buffer(const sg_buffer_desc& desc) { return sg_make_buffer(&desc); }
  4212. inline sg_image sg_make_image(const sg_image_desc& desc) { return sg_make_image(&desc); }
  4213. inline sg_sampler sg_make_sampler(const sg_sampler_desc& desc) { return sg_make_sampler(&desc); }
  4214. inline sg_shader sg_make_shader(const sg_shader_desc& desc) { return sg_make_shader(&desc); }
  4215. inline sg_pipeline sg_make_pipeline(const sg_pipeline_desc& desc) { return sg_make_pipeline(&desc); }
  4216. inline sg_attachments sg_make_attachments(const sg_attachments_desc& desc) { return sg_make_attachments(&desc); }
  4217. inline void sg_update_image(sg_image img, const sg_image_data& data) { return sg_update_image(img, &data); }
  4218. inline void sg_begin_pass(const sg_pass& pass) { return sg_begin_pass(&pass); }
  4219. inline void sg_apply_bindings(const sg_bindings& bindings) { return sg_apply_bindings(&bindings); }
  4220. inline void sg_apply_uniforms(int ub_slot, const sg_range& data) { return sg_apply_uniforms(ub_slot, &data); }
  4221. inline sg_buffer_desc sg_query_buffer_defaults(const sg_buffer_desc& desc) { return sg_query_buffer_defaults(&desc); }
  4222. inline sg_image_desc sg_query_image_defaults(const sg_image_desc& desc) { return sg_query_image_defaults(&desc); }
  4223. inline sg_sampler_desc sg_query_sampler_defaults(const sg_sampler_desc& desc) { return sg_query_sampler_defaults(&desc); }
  4224. inline sg_shader_desc sg_query_shader_defaults(const sg_shader_desc& desc) { return sg_query_shader_defaults(&desc); }
  4225. inline sg_pipeline_desc sg_query_pipeline_defaults(const sg_pipeline_desc& desc) { return sg_query_pipeline_defaults(&desc); }
  4226. inline sg_attachments_desc sg_query_attachments_defaults(const sg_attachments_desc& desc) { return sg_query_attachments_defaults(&desc); }
  4227. inline void sg_init_buffer(sg_buffer buf, const sg_buffer_desc& desc) { return sg_init_buffer(buf, &desc); }
  4228. inline void sg_init_image(sg_image img, const sg_image_desc& desc) { return sg_init_image(img, &desc); }
  4229. inline void sg_init_sampler(sg_sampler smp, const sg_sampler_desc& desc) { return sg_init_sampler(smp, &desc); }
  4230. inline void sg_init_shader(sg_shader shd, const sg_shader_desc& desc) { return sg_init_shader(shd, &desc); }
  4231. inline void sg_init_pipeline(sg_pipeline pip, const sg_pipeline_desc& desc) { return sg_init_pipeline(pip, &desc); }
  4232. inline void sg_init_attachments(sg_attachments atts, const sg_attachments_desc& desc) { return sg_init_attachments(atts, &desc); }
  4233. inline void sg_update_buffer(sg_buffer buf_id, const sg_range& data) { return sg_update_buffer(buf_id, &data); }
  4234. inline int sg_append_buffer(sg_buffer buf_id, const sg_range& data) { return sg_append_buffer(buf_id, &data); }
  4235. #endif
  4236. #endif // SOKOL_GFX_INCLUDED
  4237. // ██ ███ ███ ██████ ██ ███████ ███ ███ ███████ ███ ██ ████████ █████ ████████ ██ ██████ ███ ██
  4238. // ██ ████ ████ ██ ██ ██ ██ ████ ████ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
  4239. // ██ ██ ████ ██ ██████ ██ █████ ██ ████ ██ █████ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██
  4240. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  4241. // ██ ██ ██ ██ ███████ ███████ ██ ██ ███████ ██ ████ ██ ██ ██ ██ ██ ██████ ██ ████
  4242. //
  4243. // >>implementation
  4244. #ifdef SOKOL_GFX_IMPL
  4245. #define SOKOL_GFX_IMPL_INCLUDED (1)
  4246. #if !(defined(SOKOL_GLCORE)||defined(SOKOL_GLES3)||defined(SOKOL_D3D11)||defined(SOKOL_METAL)||defined(SOKOL_WGPU)||defined(SOKOL_DUMMY_BACKEND))
  4247. #error "Please select a backend with SOKOL_GLCORE, SOKOL_GLES3, SOKOL_D3D11, SOKOL_METAL, SOKOL_WGPU or SOKOL_DUMMY_BACKEND"
  4248. #endif
  4249. #if defined(SOKOL_MALLOC) || defined(SOKOL_CALLOC) || defined(SOKOL_FREE)
  4250. #error "SOKOL_MALLOC/CALLOC/FREE macros are no longer supported, please use sg_desc.allocator to override memory allocation functions"
  4251. #endif
  4252. #include <stdlib.h> // malloc, free, qsort
  4253. #include <string.h> // memset
  4254. #include <float.h> // FLT_MAX
  4255. #ifndef SOKOL_API_IMPL
  4256. #define SOKOL_API_IMPL
  4257. #endif
  4258. #ifndef SOKOL_DEBUG
  4259. #ifndef NDEBUG
  4260. #define SOKOL_DEBUG
  4261. #endif
  4262. #endif
  4263. #ifndef SOKOL_ASSERT
  4264. #include <assert.h>
  4265. #define SOKOL_ASSERT(c) assert(c)
  4266. #endif
  4267. #ifndef SOKOL_UNREACHABLE
  4268. #define SOKOL_UNREACHABLE SOKOL_ASSERT(false)
  4269. #endif
  4270. #ifndef _SOKOL_PRIVATE
  4271. #if defined(__GNUC__) || defined(__clang__)
  4272. #define _SOKOL_PRIVATE __attribute__((unused)) static
  4273. #else
  4274. #define _SOKOL_PRIVATE static
  4275. #endif
  4276. #endif
  4277. #ifndef _SOKOL_UNUSED
  4278. #define _SOKOL_UNUSED(x) (void)(x)
  4279. #endif
  4280. #if defined(SOKOL_TRACE_HOOKS)
  4281. #define _SG_TRACE_ARGS(fn, ...) if (_sg.hooks.fn) { _sg.hooks.fn(__VA_ARGS__, _sg.hooks.user_data); }
  4282. #define _SG_TRACE_NOARGS(fn) if (_sg.hooks.fn) { _sg.hooks.fn(_sg.hooks.user_data); }
  4283. #else
  4284. #define _SG_TRACE_ARGS(fn, ...)
  4285. #define _SG_TRACE_NOARGS(fn)
  4286. #endif
  4287. // default clear values
  4288. #ifndef SG_DEFAULT_CLEAR_RED
  4289. #define SG_DEFAULT_CLEAR_RED (0.5f)
  4290. #endif
  4291. #ifndef SG_DEFAULT_CLEAR_GREEN
  4292. #define SG_DEFAULT_CLEAR_GREEN (0.5f)
  4293. #endif
  4294. #ifndef SG_DEFAULT_CLEAR_BLUE
  4295. #define SG_DEFAULT_CLEAR_BLUE (0.5f)
  4296. #endif
  4297. #ifndef SG_DEFAULT_CLEAR_ALPHA
  4298. #define SG_DEFAULT_CLEAR_ALPHA (1.0f)
  4299. #endif
  4300. #ifndef SG_DEFAULT_CLEAR_DEPTH
  4301. #define SG_DEFAULT_CLEAR_DEPTH (1.0f)
  4302. #endif
  4303. #ifndef SG_DEFAULT_CLEAR_STENCIL
  4304. #define SG_DEFAULT_CLEAR_STENCIL (0)
  4305. #endif
  4306. #ifdef _MSC_VER
  4307. #pragma warning(push)
  4308. #pragma warning(disable:4115) // named type definition in parentheses
  4309. #pragma warning(disable:4505) // unreferenced local function has been removed
  4310. #pragma warning(disable:4201) // nonstandard extension used: nameless struct/union (needed by d3d11.h)
  4311. #pragma warning(disable:4054) // 'type cast': from function pointer
  4312. #pragma warning(disable:4055) // 'type cast': from data pointer
  4313. #endif
  4314. #if defined(SOKOL_D3D11)
  4315. #ifndef D3D11_NO_HELPERS
  4316. #define D3D11_NO_HELPERS
  4317. #endif
  4318. #ifndef WIN32_LEAN_AND_MEAN
  4319. #define WIN32_LEAN_AND_MEAN
  4320. #endif
  4321. #ifndef NOMINMAX
  4322. #define NOMINMAX
  4323. #endif
  4324. #include <d3d11.h>
  4325. #include <d3dcompiler.h>
  4326. #ifdef _MSC_VER
  4327. #pragma comment (lib, "kernel32")
  4328. #pragma comment (lib, "user32")
  4329. #pragma comment (lib, "dxgi")
  4330. #pragma comment (lib, "d3d11")
  4331. #endif
  4332. #elif defined(SOKOL_METAL)
  4333. // see https://clang.llvm.org/docs/LanguageExtensions.html#automatic-reference-counting
  4334. #if !defined(__cplusplus)
  4335. #if __has_feature(objc_arc) && !__has_feature(objc_arc_fields)
  4336. #error "sokol_gfx.h requires __has_feature(objc_arc_field) if ARC is enabled (use a more recent compiler version)"
  4337. #endif
  4338. #endif
  4339. #include <TargetConditionals.h>
  4340. #include <AvailabilityMacros.h>
  4341. #if defined(TARGET_OS_IPHONE) && !TARGET_OS_IPHONE
  4342. #define _SG_TARGET_MACOS (1)
  4343. #else
  4344. #define _SG_TARGET_IOS (1)
  4345. #if defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR
  4346. #define _SG_TARGET_IOS_SIMULATOR (1)
  4347. #endif
  4348. #endif
  4349. #import <Metal/Metal.h>
  4350. #import <QuartzCore/CoreAnimation.h> // needed for CAMetalDrawable
  4351. #elif defined(SOKOL_WGPU)
  4352. #include <webgpu/webgpu.h>
  4353. #if defined(__EMSCRIPTEN__)
  4354. #include <emscripten/emscripten.h>
  4355. #endif
  4356. #elif defined(SOKOL_GLCORE) || defined(SOKOL_GLES3)
  4357. #define _SOKOL_ANY_GL (1)
  4358. // include platform specific GL headers (or on Win32: use an embedded GL loader)
  4359. #if !defined(SOKOL_EXTERNAL_GL_LOADER)
  4360. #if defined(_WIN32)
  4361. #if defined(SOKOL_GLCORE)
  4362. #define _SOKOL_USE_WIN32_GL_LOADER (1)
  4363. #ifndef WIN32_LEAN_AND_MEAN
  4364. #define WIN32_LEAN_AND_MEAN
  4365. #endif
  4366. #ifndef NOMINMAX
  4367. #define NOMINMAX
  4368. #endif
  4369. #include <windows.h>
  4370. #pragma comment (lib, "kernel32") // GetProcAddress()
  4371. #define _SOKOL_GL_HAS_COMPUTE (1)
  4372. #define _SOKOL_GL_HAS_TEXSTORAGE (1)
  4373. #endif
  4374. #elif defined(__APPLE__)
  4375. #include <TargetConditionals.h>
  4376. #ifndef GL_SILENCE_DEPRECATION
  4377. #define GL_SILENCE_DEPRECATION
  4378. #endif
  4379. #if defined(TARGET_OS_IPHONE) && !TARGET_OS_IPHONE
  4380. #include <OpenGL/gl3.h>
  4381. #else
  4382. #include <OpenGLES/ES3/gl.h>
  4383. #include <OpenGLES/ES3/glext.h>
  4384. #define _SOKOL_GL_HAS_TEXSTORAGE (1)
  4385. #endif
  4386. #elif defined(__EMSCRIPTEN__)
  4387. #if defined(SOKOL_GLES3)
  4388. #include <GLES3/gl3.h>
  4389. #define _SOKOL_GL_HAS_TEXSTORAGE (1)
  4390. #endif
  4391. #elif defined(__ANDROID__)
  4392. #include <GLES3/gl31.h>
  4393. #define _SOKOL_GL_HAS_COMPUTE (1)
  4394. #define _SOKOL_GL_HAS_TEXSTORAGE (1)
  4395. #elif defined(__linux__) || defined(__unix__)
  4396. #if defined(SOKOL_GLCORE)
  4397. #define GL_GLEXT_PROTOTYPES
  4398. #include <GL/gl.h>
  4399. #else
  4400. #include <GLES3/gl31.h>
  4401. #include <GLES3/gl3ext.h>
  4402. #endif
  4403. #define _SOKOL_GL_HAS_COMPUTE (1)
  4404. #define _SOKOL_GL_HAS_TEXSTORAGE (1)
  4405. #endif
  4406. #endif
  4407. // optional GL loader definitions (only on Win32)
  4408. #if defined(_SOKOL_USE_WIN32_GL_LOADER)
  4409. #define __gl_h_ 1
  4410. #define __gl32_h_ 1
  4411. #define __gl31_h_ 1
  4412. #define __GL_H__ 1
  4413. #define __glext_h_ 1
  4414. #define __GLEXT_H_ 1
  4415. #define __gltypes_h_ 1
  4416. #define __glcorearb_h_ 1
  4417. #define __gl_glcorearb_h_ 1
  4418. #define GL_APIENTRY APIENTRY
  4419. typedef unsigned int GLenum;
  4420. typedef unsigned int GLuint;
  4421. typedef int GLsizei;
  4422. typedef char GLchar;
  4423. typedef ptrdiff_t GLintptr;
  4424. typedef ptrdiff_t GLsizeiptr;
  4425. typedef double GLclampd;
  4426. typedef unsigned short GLushort;
  4427. typedef unsigned char GLubyte;
  4428. typedef unsigned char GLboolean;
  4429. typedef uint64_t GLuint64;
  4430. typedef double GLdouble;
  4431. typedef unsigned short GLhalf;
  4432. typedef float GLclampf;
  4433. typedef unsigned int GLbitfield;
  4434. typedef signed char GLbyte;
  4435. typedef short GLshort;
  4436. typedef void GLvoid;
  4437. typedef int64_t GLint64;
  4438. typedef float GLfloat;
  4439. typedef int GLint;
  4440. #define GL_INT_2_10_10_10_REV 0x8D9F
  4441. #define GL_R32F 0x822E
  4442. #define GL_PROGRAM_POINT_SIZE 0x8642
  4443. #define GL_DEPTH_ATTACHMENT 0x8D00
  4444. #define GL_DEPTH_STENCIL_ATTACHMENT 0x821A
  4445. #define GL_COLOR_ATTACHMENT2 0x8CE2
  4446. #define GL_COLOR_ATTACHMENT0 0x8CE0
  4447. #define GL_R16F 0x822D
  4448. #define GL_COLOR_ATTACHMENT22 0x8CF6
  4449. #define GL_DRAW_FRAMEBUFFER 0x8CA9
  4450. #define GL_FRAMEBUFFER_COMPLETE 0x8CD5
  4451. #define GL_NUM_EXTENSIONS 0x821D
  4452. #define GL_INFO_LOG_LENGTH 0x8B84
  4453. #define GL_VERTEX_SHADER 0x8B31
  4454. #define GL_INCR 0x1E02
  4455. #define GL_DYNAMIC_DRAW 0x88E8
  4456. #define GL_STATIC_DRAW 0x88E4
  4457. #define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519
  4458. #define GL_TEXTURE_CUBE_MAP 0x8513
  4459. #define GL_FUNC_SUBTRACT 0x800A
  4460. #define GL_FUNC_REVERSE_SUBTRACT 0x800B
  4461. #define GL_CONSTANT_COLOR 0x8001
  4462. #define GL_DECR_WRAP 0x8508
  4463. #define GL_R8 0x8229
  4464. #define GL_LINEAR_MIPMAP_LINEAR 0x2703
  4465. #define GL_ELEMENT_ARRAY_BUFFER 0x8893
  4466. #define GL_SHORT 0x1402
  4467. #define GL_DEPTH_TEST 0x0B71
  4468. #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518
  4469. #define GL_LINK_STATUS 0x8B82
  4470. #define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517
  4471. #define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E
  4472. #define GL_RGBA16F 0x881A
  4473. #define GL_CONSTANT_ALPHA 0x8003
  4474. #define GL_READ_FRAMEBUFFER 0x8CA8
  4475. #define GL_TEXTURE0 0x84C0
  4476. #define GL_TEXTURE_MIN_LOD 0x813A
  4477. #define GL_CLAMP_TO_EDGE 0x812F
  4478. #define GL_UNSIGNED_SHORT_5_6_5 0x8363
  4479. #define GL_TEXTURE_WRAP_R 0x8072
  4480. #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034
  4481. #define GL_NEAREST_MIPMAP_NEAREST 0x2700
  4482. #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033
  4483. #define GL_SRC_ALPHA_SATURATE 0x0308
  4484. #define GL_STREAM_DRAW 0x88E0
  4485. #define GL_ONE 1
  4486. #define GL_NEAREST_MIPMAP_LINEAR 0x2702
  4487. #define GL_RGB10_A2 0x8059
  4488. #define GL_RGBA8 0x8058
  4489. #define GL_SRGB8_ALPHA8 0x8C43
  4490. #define GL_COLOR_ATTACHMENT1 0x8CE1
  4491. #define GL_RGBA4 0x8056
  4492. #define GL_RGB8 0x8051
  4493. #define GL_ARRAY_BUFFER 0x8892
  4494. #define GL_STENCIL 0x1802
  4495. #define GL_TEXTURE_2D 0x0DE1
  4496. #define GL_DEPTH 0x1801
  4497. #define GL_FRONT 0x0404
  4498. #define GL_STENCIL_BUFFER_BIT 0x00000400
  4499. #define GL_REPEAT 0x2901
  4500. #define GL_RGBA 0x1908
  4501. #define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515
  4502. #define GL_DECR 0x1E03
  4503. #define GL_FRAGMENT_SHADER 0x8B30
  4504. #define GL_COMPUTE_SHADER 0x91B9
  4505. #define GL_FLOAT 0x1406
  4506. #define GL_TEXTURE_MAX_LOD 0x813B
  4507. #define GL_DEPTH_COMPONENT 0x1902
  4508. #define GL_ONE_MINUS_DST_ALPHA 0x0305
  4509. #define GL_COLOR 0x1800
  4510. #define GL_TEXTURE_2D_ARRAY 0x8C1A
  4511. #define GL_TRIANGLES 0x0004
  4512. #define GL_UNSIGNED_BYTE 0x1401
  4513. #define GL_TEXTURE_MAG_FILTER 0x2800
  4514. #define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004
  4515. #define GL_NONE 0
  4516. #define GL_SRC_COLOR 0x0300
  4517. #define GL_BYTE 0x1400
  4518. #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A
  4519. #define GL_LINE_STRIP 0x0003
  4520. #define GL_TEXTURE_3D 0x806F
  4521. #define GL_CW 0x0900
  4522. #define GL_LINEAR 0x2601
  4523. #define GL_RENDERBUFFER 0x8D41
  4524. #define GL_GEQUAL 0x0206
  4525. #define GL_COLOR_BUFFER_BIT 0x00004000
  4526. #define GL_RGBA32F 0x8814
  4527. #define GL_BLEND 0x0BE2
  4528. #define GL_ONE_MINUS_SRC_ALPHA 0x0303
  4529. #define GL_ONE_MINUS_CONSTANT_COLOR 0x8002
  4530. #define GL_TEXTURE_WRAP_T 0x2803
  4531. #define GL_TEXTURE_WRAP_S 0x2802
  4532. #define GL_TEXTURE_MIN_FILTER 0x2801
  4533. #define GL_LINEAR_MIPMAP_NEAREST 0x2701
  4534. #define GL_EXTENSIONS 0x1F03
  4535. #define GL_NO_ERROR 0
  4536. #define GL_REPLACE 0x1E01
  4537. #define GL_KEEP 0x1E00
  4538. #define GL_CCW 0x0901
  4539. #define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516
  4540. #define GL_RGB 0x1907
  4541. #define GL_TRIANGLE_STRIP 0x0005
  4542. #define GL_FALSE 0
  4543. #define GL_ZERO 0
  4544. #define GL_CULL_FACE 0x0B44
  4545. #define GL_INVERT 0x150A
  4546. #define GL_INT 0x1404
  4547. #define GL_UNSIGNED_INT 0x1405
  4548. #define GL_UNSIGNED_SHORT 0x1403
  4549. #define GL_NEAREST 0x2600
  4550. #define GL_SCISSOR_TEST 0x0C11
  4551. #define GL_LEQUAL 0x0203
  4552. #define GL_STENCIL_TEST 0x0B90
  4553. #define GL_DITHER 0x0BD0
  4554. #define GL_DEPTH_COMPONENT32F 0x8CAC
  4555. #define GL_EQUAL 0x0202
  4556. #define GL_FRAMEBUFFER 0x8D40
  4557. #define GL_RGB5 0x8050
  4558. #define GL_LINES 0x0001
  4559. #define GL_DEPTH_BUFFER_BIT 0x00000100
  4560. #define GL_SRC_ALPHA 0x0302
  4561. #define GL_INCR_WRAP 0x8507
  4562. #define GL_LESS 0x0201
  4563. #define GL_MULTISAMPLE 0x809D
  4564. #define GL_FRAMEBUFFER_BINDING 0x8CA6
  4565. #define GL_BACK 0x0405
  4566. #define GL_ALWAYS 0x0207
  4567. #define GL_FUNC_ADD 0x8006
  4568. #define GL_ONE_MINUS_DST_COLOR 0x0307
  4569. #define GL_NOTEQUAL 0x0205
  4570. #define GL_DST_COLOR 0x0306
  4571. #define GL_COMPILE_STATUS 0x8B81
  4572. #define GL_RED 0x1903
  4573. #define GL_COLOR_ATTACHMENT3 0x8CE3
  4574. #define GL_DST_ALPHA 0x0304
  4575. #define GL_RGB5_A1 0x8057
  4576. #define GL_GREATER 0x0204
  4577. #define GL_POLYGON_OFFSET_FILL 0x8037
  4578. #define GL_TRUE 1
  4579. #define GL_NEVER 0x0200
  4580. #define GL_POINTS 0x0000
  4581. #define GL_ONE_MINUS_SRC_COLOR 0x0301
  4582. #define GL_MIRRORED_REPEAT 0x8370
  4583. #define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D
  4584. #define GL_R11F_G11F_B10F 0x8C3A
  4585. #define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B
  4586. #define GL_RGB9_E5 0x8C3D
  4587. #define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E
  4588. #define GL_RGBA32UI 0x8D70
  4589. #define GL_RGB32UI 0x8D71
  4590. #define GL_RGBA16UI 0x8D76
  4591. #define GL_RGB16UI 0x8D77
  4592. #define GL_RGBA8UI 0x8D7C
  4593. #define GL_RGB8UI 0x8D7D
  4594. #define GL_RGBA32I 0x8D82
  4595. #define GL_RGB32I 0x8D83
  4596. #define GL_RGBA16I 0x8D88
  4597. #define GL_RGB16I 0x8D89
  4598. #define GL_RGBA8I 0x8D8E
  4599. #define GL_RGB8I 0x8D8F
  4600. #define GL_RED_INTEGER 0x8D94
  4601. #define GL_RG 0x8227
  4602. #define GL_RG_INTEGER 0x8228
  4603. #define GL_R8 0x8229
  4604. #define GL_R16 0x822A
  4605. #define GL_RG8 0x822B
  4606. #define GL_RG16 0x822C
  4607. #define GL_R16F 0x822D
  4608. #define GL_R32F 0x822E
  4609. #define GL_RG16F 0x822F
  4610. #define GL_RG32F 0x8230
  4611. #define GL_R8I 0x8231
  4612. #define GL_R8UI 0x8232
  4613. #define GL_R16I 0x8233
  4614. #define GL_R16UI 0x8234
  4615. #define GL_R32I 0x8235
  4616. #define GL_R32UI 0x8236
  4617. #define GL_RG8I 0x8237
  4618. #define GL_RG8UI 0x8238
  4619. #define GL_RG16I 0x8239
  4620. #define GL_RG16UI 0x823A
  4621. #define GL_RG32I 0x823B
  4622. #define GL_RG32UI 0x823C
  4623. #define GL_RGBA_INTEGER 0x8D99
  4624. #define GL_R8_SNORM 0x8F94
  4625. #define GL_RG8_SNORM 0x8F95
  4626. #define GL_RGB8_SNORM 0x8F96
  4627. #define GL_RGBA8_SNORM 0x8F97
  4628. #define GL_R16_SNORM 0x8F98
  4629. #define GL_RG16_SNORM 0x8F99
  4630. #define GL_RGB16_SNORM 0x8F9A
  4631. #define GL_RGBA16_SNORM 0x8F9B
  4632. #define GL_RGBA16 0x805B
  4633. #define GL_MAX_TEXTURE_SIZE 0x0D33
  4634. #define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C
  4635. #define GL_MAX_3D_TEXTURE_SIZE 0x8073
  4636. #define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF
  4637. #define GL_MAX_VERTEX_ATTRIBS 0x8869
  4638. #define GL_CLAMP_TO_BORDER 0x812D
  4639. #define GL_TEXTURE_BORDER_COLOR 0x1004
  4640. #define GL_CURRENT_PROGRAM 0x8B8D
  4641. #define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A
  4642. #define GL_UNPACK_ALIGNMENT 0x0CF5
  4643. #define GL_FRAMEBUFFER_SRGB 0x8DB9
  4644. #define GL_TEXTURE_COMPARE_MODE 0x884C
  4645. #define GL_TEXTURE_COMPARE_FUNC 0x884D
  4646. #define GL_COMPARE_REF_TO_TEXTURE 0x884E
  4647. #define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F
  4648. #define GL_TEXTURE_MAX_LEVEL 0x813D
  4649. #define GL_FRAMEBUFFER_UNDEFINED 0x8219
  4650. #define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6
  4651. #define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7
  4652. #define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD
  4653. #define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56
  4654. #define GL_MAJOR_VERSION 0x821B
  4655. #define GL_MINOR_VERSION 0x821C
  4656. #define GL_TEXTURE_2D_MULTISAMPLE 0x9100
  4657. #define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102
  4658. #define GL_SHADER_STORAGE_BARRIER_BIT 0x2000
  4659. #define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001
  4660. #define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002
  4661. #define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008
  4662. #define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020
  4663. #define GL_MIN 0x8007
  4664. #define GL_MAX 0x8008
  4665. #define GL_WRITE_ONLY 0x88B9
  4666. #define GL_READ_WRITE 0x88BA
  4667. #endif
  4668. #ifndef GL_UNSIGNED_INT_2_10_10_10_REV
  4669. #define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368
  4670. #endif
  4671. #ifndef GL_UNSIGNED_INT_24_8
  4672. #define GL_UNSIGNED_INT_24_8 0x84FA
  4673. #endif
  4674. #ifndef GL_TEXTURE_MAX_ANISOTROPY_EXT
  4675. #define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
  4676. #endif
  4677. #ifndef GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT
  4678. #define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
  4679. #endif
  4680. #ifndef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
  4681. #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
  4682. #endif
  4683. #ifndef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
  4684. #define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
  4685. #endif
  4686. #ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
  4687. #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
  4688. #endif
  4689. #ifndef GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT
  4690. #define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT 0x8C4F
  4691. #endif
  4692. #ifndef GL_COMPRESSED_RED_RGTC1
  4693. #define GL_COMPRESSED_RED_RGTC1 0x8DBB
  4694. #endif
  4695. #ifndef GL_COMPRESSED_SIGNED_RED_RGTC1
  4696. #define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC
  4697. #endif
  4698. #ifndef GL_COMPRESSED_RED_GREEN_RGTC2
  4699. #define GL_COMPRESSED_RED_GREEN_RGTC2 0x8DBD
  4700. #endif
  4701. #ifndef GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2
  4702. #define GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2 0x8DBE
  4703. #endif
  4704. #ifndef GL_COMPRESSED_RGBA_BPTC_UNORM_ARB
  4705. #define GL_COMPRESSED_RGBA_BPTC_UNORM_ARB 0x8E8C
  4706. #endif
  4707. #ifndef GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB
  4708. #define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB 0x8E8D
  4709. #endif
  4710. #ifndef GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB
  4711. #define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB 0x8E8E
  4712. #endif
  4713. #ifndef GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB
  4714. #define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB 0x8E8F
  4715. #endif
  4716. #ifndef GL_COMPRESSED_RGB8_ETC2
  4717. #define GL_COMPRESSED_RGB8_ETC2 0x9274
  4718. #endif
  4719. #ifndef GL_COMPRESSED_SRGB8_ETC2
  4720. #define GL_COMPRESSED_SRGB8_ETC2 0x9275
  4721. #endif
  4722. #ifndef GL_COMPRESSED_RGBA8_ETC2_EAC
  4723. #define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278
  4724. #endif
  4725. #ifndef GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC
  4726. #define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279
  4727. #endif
  4728. #ifndef GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2
  4729. #define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276
  4730. #endif
  4731. #ifndef GL_COMPRESSED_R11_EAC
  4732. #define GL_COMPRESSED_R11_EAC 0x9270
  4733. #endif
  4734. #ifndef GL_COMPRESSED_SIGNED_R11_EAC
  4735. #define GL_COMPRESSED_SIGNED_R11_EAC 0x9271
  4736. #endif
  4737. #ifndef GL_COMPRESSED_RG11_EAC
  4738. #define GL_COMPRESSED_RG11_EAC 0x9272
  4739. #endif
  4740. #ifndef GL_COMPRESSED_SIGNED_RG11_EAC
  4741. #define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273
  4742. #endif
  4743. #ifndef GL_COMPRESSED_RGBA_ASTC_4x4_KHR
  4744. #define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93B0
  4745. #endif
  4746. #ifndef GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR
  4747. #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 0x93D0
  4748. #endif
  4749. #ifndef GL_DEPTH24_STENCIL8
  4750. #define GL_DEPTH24_STENCIL8 0x88F0
  4751. #endif
  4752. #ifndef GL_HALF_FLOAT
  4753. #define GL_HALF_FLOAT 0x140B
  4754. #endif
  4755. #ifndef GL_DEPTH_STENCIL
  4756. #define GL_DEPTH_STENCIL 0x84F9
  4757. #endif
  4758. #ifndef GL_LUMINANCE
  4759. #define GL_LUMINANCE 0x1909
  4760. #endif
  4761. #ifndef GL_COMPUTE_SHADER
  4762. #define GL_COMPUTE_SHADER 0x91B9
  4763. #endif
  4764. #ifndef _SG_GL_CHECK_ERROR
  4765. #define _SG_GL_CHECK_ERROR() { SOKOL_ASSERT(glGetError() == GL_NO_ERROR); }
  4766. #endif
  4767. // make some GL constants generally available to simplify compilation,
  4768. // use of those constants will be filtered by runtime flags
  4769. #ifndef GL_SHADER_STORAGE_BUFFER
  4770. #define GL_SHADER_STORAGE_BUFFER 0x90D2
  4771. #endif
  4772. #endif
  4773. #if defined(SOKOL_GLES3)
  4774. // on WebGL2, GL_FRAMEBUFFER_UNDEFINED technically doesn't exist (it is defined
  4775. // in the Emscripten headers, but may not exist in other WebGL2 shims)
  4776. // see: https://github.com/floooh/sokol/pull/933
  4777. #ifndef GL_FRAMEBUFFER_UNDEFINED
  4778. #define GL_FRAMEBUFFER_UNDEFINED 0x8219
  4779. #endif
  4780. #endif
  4781. // ███████ ████████ ██████ ██ ██ ██████ ████████ ███████
  4782. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  4783. // ███████ ██ ██████ ██ ██ ██ ██ ███████
  4784. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  4785. // ███████ ██ ██ ██ ██████ ██████ ██ ███████
  4786. //
  4787. // >>structs
  4788. // resource pool slots
  4789. typedef struct {
  4790. uint32_t id;
  4791. uint32_t uninit_count;
  4792. sg_resource_state state;
  4793. } _sg_slot_t;
  4794. // resource pool housekeeping struct
  4795. typedef struct {
  4796. int size;
  4797. int queue_top;
  4798. uint32_t* gen_ctrs;
  4799. int* free_queue;
  4800. } _sg_pool_t;
  4801. // resource func forward decls
  4802. struct _sg_buffer_s;
  4803. struct _sg_image_s;
  4804. struct _sg_sampler_s;
  4805. struct _sg_shader_s;
  4806. struct _sg_pipeline_s;
  4807. struct _sg_attachments_s;
  4808. // a general resource slot reference useful for caches
  4809. typedef struct _sg_sref_s {
  4810. uint32_t id;
  4811. uint32_t uninit_count;
  4812. } _sg_sref_t;
  4813. // safe (in debug mode) internal resource references
  4814. typedef struct _sg_buffer_ref_s {
  4815. struct _sg_buffer_s* ptr;
  4816. _sg_sref_t sref;
  4817. } _sg_buffer_ref_t;
  4818. typedef struct _sg_image_ref_s {
  4819. struct _sg_image_s* ptr;
  4820. _sg_sref_t sref;
  4821. } _sg_image_ref_t;
  4822. typedef struct _sg_sampler_ref_t {
  4823. struct _sg_sampler_s* ptr;
  4824. _sg_sref_t sref;
  4825. } _sg_sampler_ref_t;
  4826. typedef struct _sg_shader_ref_s {
  4827. struct _sg_shader_s* ptr;
  4828. _sg_sref_t sref;
  4829. } _sg_shader_ref_t;
  4830. typedef struct _sg_pipeline_ref_s {
  4831. struct _sg_pipeline_s* ptr;
  4832. _sg_sref_t sref;
  4833. } _sg_pipeline_ref_t;
  4834. typedef struct _sg_attachments_ref_s {
  4835. struct _sg_attachments_s* ptr;
  4836. _sg_sref_t sref;
  4837. } _sg_attachments_ref_t;
  4838. // resource tracking (for keeping track of gpu-written storage resources
  4839. typedef struct {
  4840. uint32_t size;
  4841. uint32_t cur;
  4842. uint32_t* items;
  4843. } _sg_tracker_t;
  4844. // constants
  4845. enum {
  4846. _SG_STRING_SIZE = 32,
  4847. _SG_SLOT_SHIFT = 16,
  4848. _SG_SLOT_MASK = (1<<_SG_SLOT_SHIFT)-1,
  4849. _SG_MAX_POOL_SIZE = (1<<_SG_SLOT_SHIFT),
  4850. _SG_DEFAULT_BUFFER_POOL_SIZE = 128,
  4851. _SG_DEFAULT_IMAGE_POOL_SIZE = 128,
  4852. _SG_DEFAULT_SAMPLER_POOL_SIZE = 64,
  4853. _SG_DEFAULT_SHADER_POOL_SIZE = 32,
  4854. _SG_DEFAULT_PIPELINE_POOL_SIZE = 64,
  4855. _SG_DEFAULT_ATTACHMENTS_POOL_SIZE = 16,
  4856. _SG_DEFAULT_UB_SIZE = 4 * 1024 * 1024,
  4857. _SG_DEFAULT_MAX_DISPATCH_CALLS_PER_PASS = 1024,
  4858. _SG_DEFAULT_MAX_COMMIT_LISTENERS = 1024,
  4859. _SG_DEFAULT_WGPU_BINDGROUP_CACHE_SIZE = 1024,
  4860. };
  4861. // fixed-size string
  4862. typedef struct {
  4863. char buf[_SG_STRING_SIZE];
  4864. } _sg_str_t;
  4865. typedef struct {
  4866. int size;
  4867. int append_pos;
  4868. bool append_overflow;
  4869. uint32_t update_frame_index;
  4870. uint32_t append_frame_index;
  4871. int num_slots;
  4872. int active_slot;
  4873. sg_buffer_usage usage;
  4874. } _sg_buffer_common_t;
  4875. typedef struct {
  4876. uint32_t upd_frame_index;
  4877. int num_slots;
  4878. int active_slot;
  4879. sg_image_type type;
  4880. int width;
  4881. int height;
  4882. int num_slices;
  4883. int num_mipmaps;
  4884. sg_image_usage usage;
  4885. sg_pixel_format pixel_format;
  4886. int sample_count;
  4887. } _sg_image_common_t;
  4888. typedef struct {
  4889. sg_filter min_filter;
  4890. sg_filter mag_filter;
  4891. sg_filter mipmap_filter;
  4892. sg_wrap wrap_u;
  4893. sg_wrap wrap_v;
  4894. sg_wrap wrap_w;
  4895. float min_lod;
  4896. float max_lod;
  4897. sg_border_color border_color;
  4898. sg_compare_func compare;
  4899. uint32_t max_anisotropy;
  4900. } _sg_sampler_common_t;
  4901. typedef struct {
  4902. sg_shader_attr_base_type base_type;
  4903. } _sg_shader_attr_t;
  4904. typedef struct {
  4905. sg_shader_stage stage;
  4906. uint32_t size;
  4907. } _sg_shader_uniform_block_t;
  4908. typedef struct {
  4909. sg_shader_stage stage;
  4910. bool readonly;
  4911. } _sg_shader_storage_buffer_t;
  4912. typedef struct {
  4913. sg_shader_stage stage;
  4914. sg_image_type image_type;
  4915. sg_pixel_format access_format;
  4916. bool writeonly;
  4917. } _sg_shader_storage_image_t;
  4918. typedef struct {
  4919. sg_shader_stage stage;
  4920. sg_image_type image_type;
  4921. sg_image_sample_type sample_type;
  4922. bool multisampled;
  4923. } _sg_shader_image_t;
  4924. typedef struct {
  4925. sg_shader_stage stage;
  4926. sg_sampler_type sampler_type;
  4927. } _sg_shader_sampler_t;
  4928. typedef struct {
  4929. sg_shader_stage stage;
  4930. uint8_t image_slot;
  4931. uint8_t sampler_slot;
  4932. } _sg_shader_image_sampler_t;
  4933. typedef struct {
  4934. uint32_t required_bindings_and_uniforms;
  4935. bool is_compute;
  4936. _sg_shader_attr_t attrs[SG_MAX_VERTEX_ATTRIBUTES];
  4937. _sg_shader_uniform_block_t uniform_blocks[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  4938. _sg_shader_storage_buffer_t storage_buffers[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  4939. _sg_shader_image_t images[SG_MAX_IMAGE_BINDSLOTS];
  4940. _sg_shader_sampler_t samplers[SG_MAX_SAMPLER_BINDSLOTS];
  4941. _sg_shader_image_sampler_t image_samplers[SG_MAX_IMAGE_SAMPLER_PAIRS];
  4942. _sg_shader_storage_image_t storage_images[SG_MAX_STORAGE_ATTACHMENTS];
  4943. } _sg_shader_common_t;
  4944. typedef struct {
  4945. bool vertex_buffer_layout_active[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  4946. bool use_instanced_draw;
  4947. bool is_compute;
  4948. uint32_t required_bindings_and_uniforms;
  4949. _sg_shader_ref_t shader;
  4950. sg_vertex_layout_state layout;
  4951. sg_depth_state depth;
  4952. sg_stencil_state stencil;
  4953. int color_count;
  4954. sg_color_target_state colors[SG_MAX_COLOR_ATTACHMENTS];
  4955. sg_primitive_type primitive_type;
  4956. sg_index_type index_type;
  4957. sg_cull_mode cull_mode;
  4958. sg_face_winding face_winding;
  4959. int sample_count;
  4960. sg_color blend_color;
  4961. bool alpha_to_coverage_enabled;
  4962. } _sg_pipeline_common_t;
  4963. typedef struct {
  4964. _sg_image_ref_t image;
  4965. int mip_level;
  4966. int slice;
  4967. } _sg_attachment_common_t;
  4968. typedef struct {
  4969. int width;
  4970. int height;
  4971. int num_colors;
  4972. bool has_render_attachments;
  4973. bool has_storage_attachments;
  4974. _sg_attachment_common_t colors[SG_MAX_COLOR_ATTACHMENTS];
  4975. _sg_attachment_common_t resolves[SG_MAX_COLOR_ATTACHMENTS];
  4976. _sg_attachment_common_t depth_stencil;
  4977. _sg_attachment_common_t storages[SG_MAX_STORAGE_ATTACHMENTS];
  4978. } _sg_attachments_common_t;
  4979. #if defined(SOKOL_DUMMY_BACKEND)
  4980. typedef struct _sg_buffer_s {
  4981. _sg_slot_t slot;
  4982. _sg_buffer_common_t cmn;
  4983. } _sg_dummy_buffer_t;
  4984. typedef _sg_dummy_buffer_t _sg_buffer_t;
  4985. typedef struct _sg_image_s {
  4986. _sg_slot_t slot;
  4987. _sg_image_common_t cmn;
  4988. } _sg_dummy_image_t;
  4989. typedef _sg_dummy_image_t _sg_image_t;
  4990. typedef struct _sg_sampler_s {
  4991. _sg_slot_t slot;
  4992. _sg_sampler_common_t cmn;
  4993. } _sg_dummy_sampler_t;
  4994. typedef _sg_dummy_sampler_t _sg_sampler_t;
  4995. typedef struct _sg_shader_s {
  4996. _sg_slot_t slot;
  4997. _sg_shader_common_t cmn;
  4998. } _sg_dummy_shader_t;
  4999. typedef _sg_dummy_shader_t _sg_shader_t;
  5000. typedef struct _sg_pipeline_s {
  5001. _sg_slot_t slot;
  5002. _sg_pipeline_common_t cmn;
  5003. } _sg_dummy_pipeline_t;
  5004. typedef _sg_dummy_pipeline_t _sg_pipeline_t;
  5005. typedef struct _sg_attachments_s {
  5006. _sg_slot_t slot;
  5007. _sg_attachments_common_t cmn;
  5008. } _sg_dummy_attachments_t;
  5009. typedef _sg_dummy_attachments_t _sg_attachments_t;
  5010. #elif defined(_SOKOL_ANY_GL)
  5011. typedef enum {
  5012. _SG_GL_GPUDIRTY_VERTEXBUFFER = (1<<0),
  5013. _SG_GL_GPUDIRTY_INDEXBUFFER = (1<<1),
  5014. _SG_GL_GPUDIRTY_STORAGEBUFFER = (1<<2),
  5015. _SG_GL_GPUDIRTY_BUFFER_ALL = _SG_GL_GPUDIRTY_VERTEXBUFFER | _SG_GL_GPUDIRTY_INDEXBUFFER | _SG_GL_GPUDIRTY_STORAGEBUFFER,
  5016. } _sg_gl_gpudirty_t;
  5017. typedef struct _sg_buffer_s {
  5018. _sg_slot_t slot;
  5019. _sg_buffer_common_t cmn;
  5020. struct {
  5021. GLuint buf[SG_NUM_INFLIGHT_FRAMES];
  5022. bool injected; // if true, external buffers were injected with sg_buffer_desc.gl_buffers
  5023. uint8_t gpu_dirty_flags; // combination of _sg_gl_gpudirty_t flags
  5024. } gl;
  5025. } _sg_gl_buffer_t;
  5026. typedef _sg_gl_buffer_t _sg_buffer_t;
  5027. typedef struct _sg_image_s {
  5028. _sg_slot_t slot;
  5029. _sg_image_common_t cmn;
  5030. struct {
  5031. GLenum target;
  5032. GLuint msaa_render_buffer;
  5033. GLuint tex[SG_NUM_INFLIGHT_FRAMES];
  5034. bool injected; // if true, external textures were injected with sg_image_desc.gl_textures
  5035. } gl;
  5036. } _sg_gl_image_t;
  5037. typedef _sg_gl_image_t _sg_image_t;
  5038. typedef struct _sg_sampler_s {
  5039. _sg_slot_t slot;
  5040. _sg_sampler_common_t cmn;
  5041. struct {
  5042. GLuint smp;
  5043. bool injected; // true if external sampler was injects in sg_sampler_desc.gl_sampler
  5044. } gl;
  5045. } _sg_gl_sampler_t;
  5046. typedef _sg_gl_sampler_t _sg_sampler_t;
  5047. typedef struct {
  5048. GLint gl_loc;
  5049. sg_uniform_type type;
  5050. uint16_t count;
  5051. uint16_t offset;
  5052. } _sg_gl_uniform_t;
  5053. typedef struct {
  5054. int num_uniforms;
  5055. _sg_gl_uniform_t uniforms[SG_MAX_UNIFORMBLOCK_MEMBERS];
  5056. } _sg_gl_uniform_block_t;
  5057. typedef struct {
  5058. _sg_str_t name;
  5059. } _sg_gl_shader_attr_t;
  5060. typedef struct _sg_shader_s {
  5061. _sg_slot_t slot;
  5062. _sg_shader_common_t cmn;
  5063. struct {
  5064. GLuint prog;
  5065. _sg_gl_shader_attr_t attrs[SG_MAX_VERTEX_ATTRIBUTES];
  5066. _sg_gl_uniform_block_t uniform_blocks[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  5067. uint8_t sbuf_binding[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  5068. uint8_t simg_binding[SG_MAX_STORAGE_ATTACHMENTS];
  5069. int8_t tex_slot[SG_MAX_IMAGE_SAMPLER_PAIRS]; // GL texture unit index
  5070. } gl;
  5071. } _sg_gl_shader_t;
  5072. typedef _sg_gl_shader_t _sg_shader_t;
  5073. typedef struct {
  5074. int8_t vb_index; // -1 if attr is not enabled
  5075. int8_t divisor; // -1 if not initialized
  5076. uint8_t stride;
  5077. uint8_t size;
  5078. uint8_t normalized;
  5079. int offset;
  5080. GLenum type;
  5081. sg_shader_attr_base_type base_type;
  5082. } _sg_gl_attr_t;
  5083. typedef struct _sg_pipeline_s {
  5084. _sg_slot_t slot;
  5085. _sg_pipeline_common_t cmn;
  5086. struct {
  5087. _sg_gl_attr_t attrs[SG_MAX_VERTEX_ATTRIBUTES];
  5088. sg_depth_state depth;
  5089. sg_stencil_state stencil;
  5090. sg_primitive_type primitive_type;
  5091. sg_blend_state blend;
  5092. sg_color_mask color_write_mask[SG_MAX_COLOR_ATTACHMENTS];
  5093. sg_cull_mode cull_mode;
  5094. sg_face_winding face_winding;
  5095. int sample_count;
  5096. bool alpha_to_coverage_enabled;
  5097. } gl;
  5098. } _sg_gl_pipeline_t;
  5099. typedef _sg_gl_pipeline_t _sg_pipeline_t;
  5100. typedef struct _sg_attachments_s {
  5101. _sg_slot_t slot;
  5102. _sg_attachments_common_t cmn;
  5103. struct {
  5104. GLuint fb;
  5105. GLuint msaa_resolve_framebuffer[SG_MAX_COLOR_ATTACHMENTS];
  5106. } gl;
  5107. } _sg_gl_attachments_t;
  5108. typedef _sg_gl_attachments_t _sg_attachments_t;
  5109. typedef struct {
  5110. _sg_gl_attr_t gl_attr;
  5111. GLuint gl_vbuf;
  5112. } _sg_gl_cache_attr_t;
  5113. typedef struct {
  5114. GLenum target;
  5115. GLuint texture;
  5116. GLuint sampler;
  5117. } _sg_gl_cache_texture_sampler_bind_slot;
  5118. #define _SG_GL_MAX_SBUF_BINDINGS (SG_MAX_STORAGEBUFFER_BINDSLOTS)
  5119. #define _SG_GL_MAX_SIMG_BINDINGS (SG_MAX_STORAGE_ATTACHMENTS)
  5120. #define _SG_GL_MAX_IMG_SMP_BINDINGS (SG_MAX_IMAGE_SAMPLER_PAIRS)
  5121. typedef struct {
  5122. sg_depth_state depth;
  5123. sg_stencil_state stencil;
  5124. sg_blend_state blend;
  5125. sg_color_mask color_write_mask[SG_MAX_COLOR_ATTACHMENTS];
  5126. sg_cull_mode cull_mode;
  5127. sg_face_winding face_winding;
  5128. bool polygon_offset_enabled;
  5129. int sample_count;
  5130. sg_color blend_color;
  5131. bool alpha_to_coverage_enabled;
  5132. _sg_gl_cache_attr_t attrs[SG_MAX_VERTEX_ATTRIBUTES];
  5133. GLuint vertex_buffer;
  5134. GLuint index_buffer;
  5135. GLuint storage_buffer; // general bind point
  5136. GLuint storage_buffers[_SG_GL_MAX_SBUF_BINDINGS];
  5137. GLuint stored_vertex_buffer;
  5138. GLuint stored_index_buffer;
  5139. GLuint stored_storage_buffer;
  5140. GLuint prog;
  5141. _sg_gl_cache_texture_sampler_bind_slot texture_samplers[_SG_GL_MAX_IMG_SMP_BINDINGS];
  5142. _sg_gl_cache_texture_sampler_bind_slot stored_texture_sampler;
  5143. int cur_ib_offset;
  5144. GLenum cur_primitive_type;
  5145. GLenum cur_index_type;
  5146. GLenum cur_active_texture;
  5147. _sg_sref_t cur_pip;
  5148. } _sg_gl_state_cache_t;
  5149. typedef struct {
  5150. bool valid;
  5151. GLuint vao;
  5152. _sg_gl_state_cache_t cache;
  5153. bool ext_anisotropic;
  5154. GLint max_anisotropy;
  5155. sg_store_action color_store_actions[SG_MAX_COLOR_ATTACHMENTS];
  5156. sg_store_action depth_store_action;
  5157. sg_store_action stencil_store_action;
  5158. #if _SOKOL_USE_WIN32_GL_LOADER
  5159. HINSTANCE opengl32_dll;
  5160. #endif
  5161. } _sg_gl_backend_t;
  5162. #elif defined(SOKOL_D3D11)
  5163. typedef struct _sg_buffer_s {
  5164. _sg_slot_t slot;
  5165. _sg_buffer_common_t cmn;
  5166. struct {
  5167. ID3D11Buffer* buf;
  5168. ID3D11ShaderResourceView* srv;
  5169. ID3D11UnorderedAccessView* uav;
  5170. } d3d11;
  5171. } _sg_d3d11_buffer_t;
  5172. typedef _sg_d3d11_buffer_t _sg_buffer_t;
  5173. typedef struct _sg_image_s {
  5174. _sg_slot_t slot;
  5175. _sg_image_common_t cmn;
  5176. struct {
  5177. DXGI_FORMAT format;
  5178. ID3D11Texture2D* tex2d;
  5179. ID3D11Texture3D* tex3d;
  5180. ID3D11Resource* res; // either tex2d or tex3d
  5181. ID3D11ShaderResourceView* srv;
  5182. } d3d11;
  5183. } _sg_d3d11_image_t;
  5184. typedef _sg_d3d11_image_t _sg_image_t;
  5185. typedef struct _sg_sampler_s {
  5186. _sg_slot_t slot;
  5187. _sg_sampler_common_t cmn;
  5188. struct {
  5189. ID3D11SamplerState* smp;
  5190. } d3d11;
  5191. } _sg_d3d11_sampler_t;
  5192. typedef _sg_d3d11_sampler_t _sg_sampler_t;
  5193. typedef struct {
  5194. _sg_str_t sem_name;
  5195. int sem_index;
  5196. } _sg_d3d11_shader_attr_t;
  5197. #define _SG_D3D11_MAX_STAGE_UB_BINDINGS (SG_MAX_UNIFORMBLOCK_BINDSLOTS)
  5198. #define _SG_D3D11_MAX_STAGE_SRV_BINDINGS (SG_MAX_IMAGE_BINDSLOTS + SG_MAX_STORAGEBUFFER_BINDSLOTS)
  5199. #define _SG_D3D11_MAX_STAGE_UAV_BINDINGS (SG_MAX_STORAGEBUFFER_BINDSLOTS + SG_MAX_STORAGE_ATTACHMENTS)
  5200. #define _SG_D3D11_MAX_STAGE_SMP_BINDINGS (SG_MAX_SAMPLER_BINDSLOTS)
  5201. typedef struct _sg_shader_s {
  5202. _sg_slot_t slot;
  5203. _sg_shader_common_t cmn;
  5204. struct {
  5205. _sg_d3d11_shader_attr_t attrs[SG_MAX_VERTEX_ATTRIBUTES];
  5206. ID3D11VertexShader* vs;
  5207. ID3D11PixelShader* fs;
  5208. ID3D11ComputeShader* cs;
  5209. void* vs_blob;
  5210. size_t vs_blob_length;
  5211. uint8_t ub_register_b_n[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  5212. uint8_t img_register_t_n[SG_MAX_IMAGE_BINDSLOTS];
  5213. uint8_t smp_register_s_n[SG_MAX_SAMPLER_BINDSLOTS];
  5214. uint8_t sbuf_register_t_n[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  5215. uint8_t sbuf_register_u_n[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  5216. uint8_t simg_register_u_n[SG_MAX_STORAGE_ATTACHMENTS];
  5217. ID3D11Buffer* all_cbufs[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  5218. ID3D11Buffer* vs_cbufs[_SG_D3D11_MAX_STAGE_UB_BINDINGS];
  5219. ID3D11Buffer* fs_cbufs[_SG_D3D11_MAX_STAGE_UB_BINDINGS];
  5220. ID3D11Buffer* cs_cbufs[_SG_D3D11_MAX_STAGE_UB_BINDINGS];
  5221. } d3d11;
  5222. } _sg_d3d11_shader_t;
  5223. typedef _sg_d3d11_shader_t _sg_shader_t;
  5224. typedef struct _sg_pipeline_s {
  5225. _sg_slot_t slot;
  5226. _sg_pipeline_common_t cmn;
  5227. struct {
  5228. UINT stencil_ref;
  5229. UINT vb_strides[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  5230. D3D_PRIMITIVE_TOPOLOGY topology;
  5231. DXGI_FORMAT index_format;
  5232. ID3D11InputLayout* il;
  5233. ID3D11RasterizerState* rs;
  5234. ID3D11DepthStencilState* dss;
  5235. ID3D11BlendState* bs;
  5236. } d3d11;
  5237. } _sg_d3d11_pipeline_t;
  5238. typedef _sg_d3d11_pipeline_t _sg_pipeline_t;
  5239. typedef struct {
  5240. union {
  5241. ID3D11RenderTargetView* rtv;
  5242. ID3D11DepthStencilView* dsv;
  5243. ID3D11UnorderedAccessView* uav;
  5244. } view;
  5245. } _sg_d3d11_attachment_t;
  5246. typedef struct _sg_attachments_s {
  5247. _sg_slot_t slot;
  5248. _sg_attachments_common_t cmn;
  5249. struct {
  5250. _sg_d3d11_attachment_t colors[SG_MAX_COLOR_ATTACHMENTS];
  5251. _sg_d3d11_attachment_t resolves[SG_MAX_COLOR_ATTACHMENTS];
  5252. _sg_d3d11_attachment_t depth_stencil;
  5253. _sg_d3d11_attachment_t storages[SG_MAX_STORAGE_ATTACHMENTS];
  5254. } d3d11;
  5255. } _sg_d3d11_attachments_t;
  5256. typedef _sg_d3d11_attachments_t _sg_attachments_t;
  5257. typedef struct {
  5258. bool valid;
  5259. ID3D11Device* dev;
  5260. ID3D11DeviceContext* ctx;
  5261. bool use_indexed_draw;
  5262. bool use_instanced_draw;
  5263. _sg_pipeline_t* cur_pipeline;
  5264. sg_pipeline cur_pipeline_id;
  5265. struct {
  5266. ID3D11RenderTargetView* render_view;
  5267. ID3D11RenderTargetView* resolve_view;
  5268. } cur_pass;
  5269. // on-demand loaded d3dcompiler_47.dll handles
  5270. HINSTANCE d3dcompiler_dll;
  5271. bool d3dcompiler_dll_load_failed;
  5272. pD3DCompile D3DCompile_func;
  5273. // global subresourcedata array for texture updates
  5274. D3D11_SUBRESOURCE_DATA subres_data[SG_MAX_MIPMAPS * SG_MAX_TEXTUREARRAY_LAYERS];
  5275. } _sg_d3d11_backend_t;
  5276. #elif defined(SOKOL_METAL)
  5277. #if defined(_SG_TARGET_MACOS) || defined(_SG_TARGET_IOS_SIMULATOR)
  5278. #define _SG_MTL_UB_ALIGN (256)
  5279. #else
  5280. #define _SG_MTL_UB_ALIGN (16)
  5281. #endif
  5282. #define _SG_MTL_INVALID_SLOT_INDEX (0)
  5283. typedef struct {
  5284. uint32_t frame_index; // frame index at which it is safe to release this resource
  5285. int slot_index;
  5286. } _sg_mtl_release_item_t;
  5287. typedef struct {
  5288. NSMutableArray* pool;
  5289. int num_slots;
  5290. int free_queue_top;
  5291. int* free_queue;
  5292. int release_queue_front;
  5293. int release_queue_back;
  5294. _sg_mtl_release_item_t* release_queue;
  5295. } _sg_mtl_idpool_t;
  5296. typedef struct _sg_buffer_s {
  5297. _sg_slot_t slot;
  5298. _sg_buffer_common_t cmn;
  5299. struct {
  5300. int buf[SG_NUM_INFLIGHT_FRAMES]; // index into _sg_mtl_pool
  5301. } mtl;
  5302. } _sg_mtl_buffer_t;
  5303. typedef _sg_mtl_buffer_t _sg_buffer_t;
  5304. typedef struct _sg_image_s {
  5305. _sg_slot_t slot;
  5306. _sg_image_common_t cmn;
  5307. struct {
  5308. int tex[SG_NUM_INFLIGHT_FRAMES];
  5309. } mtl;
  5310. } _sg_mtl_image_t;
  5311. typedef _sg_mtl_image_t _sg_image_t;
  5312. typedef struct _sg_sampler_s {
  5313. _sg_slot_t slot;
  5314. _sg_sampler_common_t cmn;
  5315. struct {
  5316. int sampler_state;
  5317. } mtl;
  5318. } _sg_mtl_sampler_t;
  5319. typedef _sg_mtl_sampler_t _sg_sampler_t;
  5320. typedef struct {
  5321. int mtl_lib;
  5322. int mtl_func;
  5323. } _sg_mtl_shader_func_t;
  5324. typedef struct _sg_shader_s {
  5325. _sg_slot_t slot;
  5326. _sg_shader_common_t cmn;
  5327. struct {
  5328. _sg_mtl_shader_func_t vertex_func;
  5329. _sg_mtl_shader_func_t fragment_func;
  5330. _sg_mtl_shader_func_t compute_func;
  5331. MTLSize threads_per_threadgroup;
  5332. uint8_t ub_buffer_n[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  5333. uint8_t img_texture_n[SG_MAX_IMAGE_BINDSLOTS];
  5334. uint8_t smp_sampler_n[SG_MAX_SAMPLER_BINDSLOTS];
  5335. uint8_t sbuf_buffer_n[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  5336. uint8_t simg_texture_n[SG_MAX_STORAGE_ATTACHMENTS];
  5337. } mtl;
  5338. } _sg_mtl_shader_t;
  5339. typedef _sg_mtl_shader_t _sg_shader_t;
  5340. typedef struct _sg_pipeline_s {
  5341. _sg_slot_t slot;
  5342. _sg_pipeline_common_t cmn;
  5343. struct {
  5344. MTLPrimitiveType prim_type;
  5345. int index_size;
  5346. MTLIndexType index_type;
  5347. MTLCullMode cull_mode;
  5348. MTLWinding winding;
  5349. uint32_t stencil_ref;
  5350. MTLSize threads_per_threadgroup;
  5351. int cps; // MTLComputePipelineState
  5352. int rps; // MTLRenderPipelineState
  5353. int dss; // MTLDepthStencilState
  5354. } mtl;
  5355. } _sg_mtl_pipeline_t;
  5356. typedef _sg_mtl_pipeline_t _sg_pipeline_t;
  5357. typedef struct _sg_attachments_s {
  5358. _sg_slot_t slot;
  5359. _sg_attachments_common_t cmn;
  5360. struct {
  5361. int storage_views[SG_MAX_STORAGE_ATTACHMENTS];
  5362. } mtl;
  5363. } _sg_mtl_attachments_t;
  5364. typedef _sg_mtl_attachments_t _sg_attachments_t;
  5365. // resource binding state cache
  5366. #define _SG_MTL_MAX_STAGE_UB_BINDINGS (SG_MAX_UNIFORMBLOCK_BINDSLOTS)
  5367. #define _SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS (_SG_MTL_MAX_STAGE_UB_BINDINGS + SG_MAX_STORAGEBUFFER_BINDSLOTS)
  5368. #define _SG_MTL_MAX_STAGE_BUFFER_BINDINGS (_SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS + SG_MAX_VERTEXBUFFER_BINDSLOTS)
  5369. #define _SG_MTL_MAX_STAGE_TEXTURE_BINDINGS (SG_MAX_IMAGE_BINDSLOTS + SG_MAX_STORAGE_ATTACHMENTS)
  5370. #define _SG_MTL_MAX_STAGE_SAMPLER_BINDINGS (SG_MAX_SAMPLER_BINDSLOTS)
  5371. typedef struct {
  5372. _sg_sref_t cur_pip;
  5373. _sg_buffer_ref_t cur_ibuf;
  5374. int cur_ibuf_offset;
  5375. int cur_vs_buffer_offsets[_SG_MTL_MAX_STAGE_BUFFER_BINDINGS];
  5376. _sg_sref_t cur_vsbufs[_SG_MTL_MAX_STAGE_BUFFER_BINDINGS];
  5377. _sg_sref_t cur_fsbufs[_SG_MTL_MAX_STAGE_BUFFER_BINDINGS];
  5378. _sg_sref_t cur_csbufs[_SG_MTL_MAX_STAGE_BUFFER_BINDINGS];
  5379. _sg_sref_t cur_vsimgs[_SG_MTL_MAX_STAGE_TEXTURE_BINDINGS];
  5380. _sg_sref_t cur_fsimgs[_SG_MTL_MAX_STAGE_TEXTURE_BINDINGS];
  5381. _sg_sref_t cur_vssmps[_SG_MTL_MAX_STAGE_SAMPLER_BINDINGS];
  5382. _sg_sref_t cur_fssmps[_SG_MTL_MAX_STAGE_SAMPLER_BINDINGS];
  5383. _sg_sref_t cur_cssmps[_SG_MTL_MAX_STAGE_SAMPLER_BINDINGS];
  5384. // NOTE: special case: uint64_t for storage images, because we need
  5385. // to differentiate between storage pass attachments and regular
  5386. // textures bound to compute stages (but both binding types live
  5387. // in the texture bind space in Metal)
  5388. // This special case will be removed in the view update!
  5389. uint64_t cur_cs_image_ids[_SG_MTL_MAX_STAGE_TEXTURE_BINDINGS];
  5390. } _sg_mtl_state_cache_t;
  5391. typedef struct {
  5392. bool valid;
  5393. bool use_shared_storage_mode;
  5394. uint32_t cur_frame_rotate_index;
  5395. int ub_size;
  5396. int cur_ub_offset;
  5397. uint8_t* cur_ub_base_ptr;
  5398. _sg_mtl_state_cache_t state_cache;
  5399. _sg_mtl_idpool_t idpool;
  5400. dispatch_semaphore_t sem;
  5401. id<MTLDevice> device;
  5402. id<MTLCommandQueue> cmd_queue;
  5403. id<MTLCommandBuffer> cmd_buffer;
  5404. id<MTLRenderCommandEncoder> render_cmd_encoder;
  5405. id<MTLComputeCommandEncoder> compute_cmd_encoder;
  5406. id<CAMetalDrawable> cur_drawable;
  5407. id<MTLBuffer> uniform_buffers[SG_NUM_INFLIGHT_FRAMES];
  5408. } _sg_mtl_backend_t;
  5409. #elif defined(SOKOL_WGPU)
  5410. #define _SG_WGPU_ROWPITCH_ALIGN (256)
  5411. #define _SG_WGPU_MAX_UNIFORM_UPDATE_SIZE (1<<16) // also see WGPULimits.maxUniformBufferBindingSize
  5412. #define _SG_WGPU_MAX_BINDGROUPS (3) // 0: uniforms, 1: images, samplers, storage buffers, 2: storage images (only in compute passes)
  5413. #define _SG_WGPU_UB_BINDGROUP_INDEX (0)
  5414. #define _SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX (1)
  5415. #define _SG_WGPU_SIMG_BINDGROUP_INDEX (2)
  5416. #define _SG_WGPU_MAX_UB_BINDGROUP_ENTRIES (SG_MAX_UNIFORMBLOCK_BINDSLOTS)
  5417. #define _SG_WGPU_MAX_UB_BINDGROUP_BIND_SLOTS (2 * SG_MAX_UNIFORMBLOCK_BINDSLOTS)
  5418. #define _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES (SG_MAX_IMAGE_BINDSLOTS + SG_MAX_SAMPLER_BINDSLOTS + SG_MAX_STORAGEBUFFER_BINDSLOTS)
  5419. #define _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS (128)
  5420. #define _SG_WGPU_MAX_SIMG_BIND_SLOTS (SG_MAX_STORAGE_ATTACHMENTS)
  5421. #define _SG_WGPU_MAX_SIMG_BINDGROUP_ENTRIES (SG_MAX_STORAGE_ATTACHMENTS)
  5422. typedef struct _sg_buffer_s {
  5423. _sg_slot_t slot;
  5424. _sg_buffer_common_t cmn;
  5425. struct {
  5426. WGPUBuffer buf;
  5427. } wgpu;
  5428. } _sg_wgpu_buffer_t;
  5429. typedef _sg_wgpu_buffer_t _sg_buffer_t;
  5430. typedef struct _sg_image_s {
  5431. _sg_slot_t slot;
  5432. _sg_image_common_t cmn;
  5433. struct {
  5434. WGPUTexture tex;
  5435. WGPUTextureView view;
  5436. } wgpu;
  5437. } _sg_wgpu_image_t;
  5438. typedef _sg_wgpu_image_t _sg_image_t;
  5439. typedef struct _sg_sampler_s {
  5440. _sg_slot_t slot;
  5441. _sg_sampler_common_t cmn;
  5442. struct {
  5443. WGPUSampler smp;
  5444. } wgpu;
  5445. } _sg_wgpu_sampler_t;
  5446. typedef _sg_wgpu_sampler_t _sg_sampler_t;
  5447. typedef struct {
  5448. WGPUShaderModule module;
  5449. _sg_str_t entry;
  5450. } _sg_wgpu_shader_func_t;
  5451. typedef struct _sg_shader_s {
  5452. _sg_slot_t slot;
  5453. _sg_shader_common_t cmn;
  5454. struct {
  5455. _sg_wgpu_shader_func_t vertex_func;
  5456. _sg_wgpu_shader_func_t fragment_func;
  5457. _sg_wgpu_shader_func_t compute_func;
  5458. WGPUBindGroupLayout bgl_ub;
  5459. WGPUBindGroup bg_ub;
  5460. WGPUBindGroupLayout bgl_img_smp_sbuf;
  5461. WGPUBindGroupLayout bgl_simg;
  5462. // a mapping of sokol-gfx bind slots to setBindGroup dynamic-offset-array indices
  5463. uint8_t ub_num_dynoffsets;
  5464. uint8_t ub_dynoffsets[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  5465. // indexed by sokol-gfx bind slot:
  5466. uint8_t ub_grp0_bnd_n[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  5467. uint8_t img_grp1_bnd_n[SG_MAX_IMAGE_BINDSLOTS];
  5468. uint8_t smp_grp1_bnd_n[SG_MAX_SAMPLER_BINDSLOTS];
  5469. uint8_t sbuf_grp1_bnd_n[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  5470. uint8_t simg_grp2_bnd_n[SG_MAX_STORAGE_ATTACHMENTS];
  5471. } wgpu;
  5472. } _sg_wgpu_shader_t;
  5473. typedef _sg_wgpu_shader_t _sg_shader_t;
  5474. typedef struct _sg_pipeline_s {
  5475. _sg_slot_t slot;
  5476. _sg_pipeline_common_t cmn;
  5477. struct {
  5478. WGPURenderPipeline rpip;
  5479. WGPUComputePipeline cpip;
  5480. WGPUColor blend_color;
  5481. } wgpu;
  5482. } _sg_wgpu_pipeline_t;
  5483. typedef _sg_wgpu_pipeline_t _sg_pipeline_t;
  5484. typedef struct {
  5485. WGPUTextureView view;
  5486. } _sg_wgpu_attachment_t;
  5487. typedef struct _sg_attachments_s {
  5488. _sg_slot_t slot;
  5489. _sg_attachments_common_t cmn;
  5490. struct {
  5491. _sg_wgpu_attachment_t colors[SG_MAX_COLOR_ATTACHMENTS];
  5492. _sg_wgpu_attachment_t resolves[SG_MAX_COLOR_ATTACHMENTS];
  5493. _sg_wgpu_attachment_t depth_stencil;
  5494. _sg_wgpu_attachment_t storages[SG_MAX_STORAGE_ATTACHMENTS];
  5495. } wgpu;
  5496. } _sg_wgpu_attachments_t;
  5497. typedef _sg_wgpu_attachments_t _sg_attachments_t;
  5498. // a pool of per-frame uniform buffers
  5499. typedef struct {
  5500. uint32_t num_bytes;
  5501. uint32_t offset; // current offset into buf
  5502. uint8_t* staging; // intermediate buffer for uniform data updates
  5503. WGPUBuffer buf; // the GPU-side uniform buffer
  5504. uint32_t bind_offsets[SG_MAX_UNIFORMBLOCK_BINDSLOTS]; // NOTE: index is sokol-gfx ub slot index!
  5505. } _sg_wgpu_uniform_buffer_t;
  5506. typedef struct {
  5507. uint32_t id;
  5508. } _sg_wgpu_bindgroup_handle_t;
  5509. typedef enum {
  5510. _SG_WGPU_BINDGROUPSCACHEITEMTYPE_NONE = 0,
  5511. _SG_WGPU_BINDGROUPSCACHEITEMTYPE_IMAGE = 0x00001111,
  5512. _SG_WGPU_BINDGROUPSCACHEITEMTYPE_SAMPLER = 0x00002222,
  5513. _SG_WGPU_BINDGROUPSCACHEITEMTYPE_STORAGEBUFFER = 0x00003333,
  5514. _SG_WGPU_BINDGROUPSCACHEITEMTYPE_PIPELINE = 0x00004444,
  5515. } _sg_wgpu_bindgroups_cache_item_type_t;
  5516. #define _SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS (1 + _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES)
  5517. typedef struct {
  5518. uint64_t hash;
  5519. // the format of cache key items is BBBBTTTTIIIIIIII
  5520. // where
  5521. // - BBBB is 2x the WGPU binding
  5522. // - TTTT is the _sg_wgpu_bindgroups_cache_item_type_t
  5523. // - IIIIIIII is the resource id
  5524. //
  5525. // where the item type is a per-resource-type bit pattern
  5526. uint64_t items[_SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS];
  5527. } _sg_wgpu_bindgroups_cache_key_t;
  5528. typedef struct {
  5529. uint32_t num; // must be 2^n
  5530. uint32_t index_mask; // mask to turn hash into valid index
  5531. _sg_wgpu_bindgroup_handle_t* items;
  5532. } _sg_wgpu_bindgroups_cache_t;
  5533. typedef struct {
  5534. _sg_slot_t slot;
  5535. WGPUBindGroup bindgroup;
  5536. _sg_wgpu_bindgroups_cache_key_t key;
  5537. } _sg_wgpu_bindgroup_t;
  5538. typedef struct {
  5539. _sg_pool_t pool;
  5540. _sg_wgpu_bindgroup_t* bindgroups;
  5541. } _sg_wgpu_bindgroups_pool_t;
  5542. typedef struct {
  5543. struct {
  5544. sg_buffer buffer;
  5545. uint64_t offset;
  5546. } vbs[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  5547. struct {
  5548. sg_buffer buffer;
  5549. uint64_t offset;
  5550. } ib;
  5551. _sg_wgpu_bindgroup_handle_t bg;
  5552. } _sg_wgpu_bindings_cache_t;
  5553. // the WGPU backend state
  5554. typedef struct {
  5555. bool valid;
  5556. bool use_indexed_draw;
  5557. WGPUDevice dev;
  5558. WGPUSupportedLimits limits;
  5559. WGPUQueue queue;
  5560. WGPUCommandEncoder cmd_enc;
  5561. WGPURenderPassEncoder rpass_enc;
  5562. WGPUComputePassEncoder cpass_enc;
  5563. WGPUBindGroup empty_bind_group;
  5564. const _sg_pipeline_t* cur_pipeline;
  5565. sg_pipeline cur_pipeline_id;
  5566. _sg_wgpu_uniform_buffer_t uniform;
  5567. _sg_wgpu_bindings_cache_t bindings_cache;
  5568. _sg_wgpu_bindgroups_cache_t bindgroups_cache;
  5569. _sg_wgpu_bindgroups_pool_t bindgroups_pool;
  5570. } _sg_wgpu_backend_t;
  5571. #endif
  5572. // this *MUST* remain 0
  5573. #define _SG_INVALID_SLOT_INDEX (0)
  5574. typedef struct _sg_pools_s {
  5575. _sg_pool_t buffer_pool;
  5576. _sg_pool_t image_pool;
  5577. _sg_pool_t sampler_pool;
  5578. _sg_pool_t shader_pool;
  5579. _sg_pool_t pipeline_pool;
  5580. _sg_pool_t attachments_pool;
  5581. _sg_buffer_t* buffers;
  5582. _sg_image_t* images;
  5583. _sg_sampler_t* samplers;
  5584. _sg_shader_t* shaders;
  5585. _sg_pipeline_t* pipelines;
  5586. _sg_attachments_t* attachments;
  5587. } _sg_pools_t;
  5588. typedef struct {
  5589. int num; // number of allocated commit listener items
  5590. int upper; // the current upper index (no valid items past this point)
  5591. sg_commit_listener* items;
  5592. } _sg_commit_listeners_t;
  5593. // resolved pass attachments struct
  5594. typedef struct {
  5595. _sg_image_t* color_images[SG_MAX_COLOR_ATTACHMENTS];
  5596. _sg_image_t* resolve_images[SG_MAX_COLOR_ATTACHMENTS];
  5597. _sg_image_t* ds_image;
  5598. _sg_image_t* storage_images[SG_MAX_STORAGE_ATTACHMENTS];
  5599. } _sg_attachments_ptrs_t;
  5600. // resolved resource bindings struct
  5601. typedef struct {
  5602. _sg_pipeline_t* pip;
  5603. int vb_offsets[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  5604. int ib_offset;
  5605. _sg_buffer_t* vbs[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  5606. _sg_buffer_t* ib;
  5607. _sg_image_t* imgs[SG_MAX_IMAGE_BINDSLOTS];
  5608. _sg_sampler_t* smps[SG_MAX_SAMPLER_BINDSLOTS];
  5609. _sg_buffer_t* sbufs[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  5610. _sg_image_t* simgs[SG_MAX_STORAGE_ATTACHMENTS];
  5611. } _sg_bindings_ptrs_t;
  5612. typedef struct {
  5613. bool sample;
  5614. bool filter;
  5615. bool render;
  5616. bool blend;
  5617. bool msaa;
  5618. bool depth;
  5619. bool read;
  5620. bool write;
  5621. } _sg_pixelformat_info_t;
  5622. typedef struct {
  5623. bool valid;
  5624. sg_desc desc; // original desc with default values patched in
  5625. uint32_t frame_index;
  5626. struct {
  5627. bool valid;
  5628. bool in_pass;
  5629. bool is_compute;
  5630. _sg_attachments_ref_t atts; // null in a swapchain pass
  5631. int width;
  5632. int height;
  5633. struct {
  5634. sg_pixel_format color_fmt;
  5635. sg_pixel_format depth_fmt;
  5636. int sample_count;
  5637. } swapchain;
  5638. } cur_pass;
  5639. _sg_pipeline_ref_t cur_pip;
  5640. bool next_draw_valid;
  5641. uint32_t required_bindings_and_uniforms; // used to check that bindings and uniforms are applied after applying pipeline
  5642. uint32_t applied_bindings_and_uniforms; // bits 0..7: uniform blocks, bit 8: bindings
  5643. #if defined(SOKOL_DEBUG)
  5644. sg_log_item validate_error;
  5645. #endif
  5646. struct {
  5647. _sg_tracker_t readwrite_sbufs; // tracks read/write storage buffers used in compute pass
  5648. } compute;
  5649. _sg_pools_t pools;
  5650. sg_backend backend;
  5651. sg_features features;
  5652. sg_limits limits;
  5653. _sg_pixelformat_info_t formats[_SG_PIXELFORMAT_NUM];
  5654. bool stats_enabled;
  5655. sg_frame_stats stats;
  5656. sg_frame_stats prev_stats;
  5657. #if defined(_SOKOL_ANY_GL)
  5658. _sg_gl_backend_t gl;
  5659. #elif defined(SOKOL_METAL)
  5660. _sg_mtl_backend_t mtl;
  5661. #elif defined(SOKOL_D3D11)
  5662. _sg_d3d11_backend_t d3d11;
  5663. #elif defined(SOKOL_WGPU)
  5664. _sg_wgpu_backend_t wgpu;
  5665. #endif
  5666. #if defined(SOKOL_TRACE_HOOKS)
  5667. sg_trace_hooks hooks;
  5668. #endif
  5669. _sg_commit_listeners_t commit_listeners;
  5670. } _sg_state_t;
  5671. static _sg_state_t _sg;
  5672. // ██ ██████ ██████ ██████ ██ ███ ██ ██████
  5673. // ██ ██ ██ ██ ██ ██ ████ ██ ██
  5674. // ██ ██ ██ ██ ███ ██ ███ ██ ██ ██ ██ ██ ███
  5675. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  5676. // ███████ ██████ ██████ ██████ ██ ██ ████ ██████
  5677. //
  5678. // >>logging
  5679. #if defined(SOKOL_DEBUG)
  5680. #define _SG_LOGITEM_XMACRO(item,msg) #item ": " msg,
  5681. static const char* _sg_log_messages[] = {
  5682. _SG_LOG_ITEMS
  5683. };
  5684. #undef _SG_LOGITEM_XMACRO
  5685. #endif // SOKOL_DEBUG
  5686. #define _SG_PANIC(code) _sg_log(SG_LOGITEM_ ##code, 0, 0, __LINE__)
  5687. #define _SG_ERROR(code) _sg_log(SG_LOGITEM_ ##code, 1, 0, __LINE__)
  5688. #define _SG_WARN(code) _sg_log(SG_LOGITEM_ ##code, 2, 0, __LINE__)
  5689. #define _SG_INFO(code) _sg_log(SG_LOGITEM_ ##code, 3, 0, __LINE__)
  5690. #define _SG_LOGMSG(code,msg) _sg_log(SG_LOGITEM_ ##code, 3, msg, __LINE__)
  5691. #define _SG_VALIDATE(cond,code) if (!(cond)){ _sg.validate_error = SG_LOGITEM_ ##code; _sg_log(SG_LOGITEM_ ##code, 1, 0, __LINE__); }
  5692. static void _sg_log(sg_log_item log_item, uint32_t log_level, const char* msg, uint32_t line_nr) {
  5693. if (_sg.desc.logger.func) {
  5694. const char* filename = 0;
  5695. #if defined(SOKOL_DEBUG)
  5696. filename = __FILE__;
  5697. if (0 == msg) {
  5698. msg = _sg_log_messages[log_item];
  5699. }
  5700. #endif
  5701. _sg.desc.logger.func("sg", log_level, (uint32_t)log_item, msg, line_nr, filename, _sg.desc.logger.user_data);
  5702. } else {
  5703. // for log level PANIC it would be 'undefined behaviour' to continue
  5704. if (log_level == 0) {
  5705. abort();
  5706. }
  5707. }
  5708. }
  5709. // ███ ███ ███████ ███ ███ ██████ ██████ ██ ██
  5710. // ████ ████ ██ ████ ████ ██ ██ ██ ██ ██ ██
  5711. // ██ ████ ██ █████ ██ ████ ██ ██ ██ ██████ ████
  5712. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  5713. // ██ ██ ███████ ██ ██ ██████ ██ ██ ██
  5714. //
  5715. // >>memory
  5716. // a helper macro to clear a struct with potentially ARC'ed ObjC references
  5717. #if defined(SOKOL_METAL)
  5718. #if defined(__cplusplus)
  5719. #define _SG_CLEAR_ARC_STRUCT(type, item) { item = type(); }
  5720. #else
  5721. #define _SG_CLEAR_ARC_STRUCT(type, item) { item = (type) { 0 }; }
  5722. #endif
  5723. #else
  5724. #define _SG_CLEAR_ARC_STRUCT(type, item) { _sg_clear(&item, sizeof(item)); }
  5725. #endif
  5726. _SOKOL_PRIVATE void _sg_clear(void* ptr, size_t size) {
  5727. SOKOL_ASSERT(ptr && (size > 0));
  5728. memset(ptr, 0, size);
  5729. }
  5730. _SOKOL_PRIVATE void* _sg_malloc(size_t size) {
  5731. SOKOL_ASSERT(size > 0);
  5732. void* ptr;
  5733. if (_sg.desc.allocator.alloc_fn) {
  5734. ptr = _sg.desc.allocator.alloc_fn(size, _sg.desc.allocator.user_data);
  5735. } else {
  5736. ptr = malloc(size);
  5737. }
  5738. if (0 == ptr) {
  5739. _SG_PANIC(MALLOC_FAILED);
  5740. }
  5741. return ptr;
  5742. }
  5743. _SOKOL_PRIVATE void* _sg_malloc_clear(size_t size) {
  5744. void* ptr = _sg_malloc(size);
  5745. _sg_clear(ptr, size);
  5746. return ptr;
  5747. }
  5748. _SOKOL_PRIVATE void _sg_free(void* ptr) {
  5749. if (_sg.desc.allocator.free_fn) {
  5750. _sg.desc.allocator.free_fn(ptr, _sg.desc.allocator.user_data);
  5751. } else {
  5752. free(ptr);
  5753. }
  5754. }
  5755. _SOKOL_PRIVATE bool _sg_strempty(const _sg_str_t* str) {
  5756. return 0 == str->buf[0];
  5757. }
  5758. _SOKOL_PRIVATE const char* _sg_strptr(const _sg_str_t* str) {
  5759. return &str->buf[0];
  5760. }
  5761. _SOKOL_PRIVATE void _sg_strcpy(_sg_str_t* dst, const char* src) {
  5762. SOKOL_ASSERT(dst);
  5763. if (src) {
  5764. #if defined(_MSC_VER)
  5765. strncpy_s(dst->buf, _SG_STRING_SIZE, src, (_SG_STRING_SIZE-1));
  5766. #else
  5767. strncpy(dst->buf, src, _SG_STRING_SIZE);
  5768. #endif
  5769. dst->buf[_SG_STRING_SIZE-1] = 0;
  5770. } else {
  5771. _sg_clear(dst->buf, _SG_STRING_SIZE);
  5772. }
  5773. }
  5774. // ██████ ██████ ██████ ██
  5775. // ██ ██ ██ ██ ██ ██ ██
  5776. // ██████ ██ ██ ██ ██ ██
  5777. // ██ ██ ██ ██ ██ ██
  5778. // ██ ██████ ██████ ███████
  5779. //
  5780. // >>pool
  5781. _SOKOL_PRIVATE void _sg_pool_init(_sg_pool_t* pool, int num) {
  5782. SOKOL_ASSERT(pool && (num >= 1));
  5783. // slot 0 is reserved for the 'invalid id', so bump the pool size by 1
  5784. pool->size = num + 1;
  5785. pool->queue_top = 0;
  5786. // generation counters indexable by pool slot index, slot 0 is reserved
  5787. size_t gen_ctrs_size = sizeof(uint32_t) * (size_t)pool->size;
  5788. pool->gen_ctrs = (uint32_t*)_sg_malloc_clear(gen_ctrs_size);
  5789. // it's not a bug to only reserve 'num' here
  5790. pool->free_queue = (int*) _sg_malloc_clear(sizeof(int) * (size_t)num);
  5791. // never allocate the zero-th pool item since the invalid id is 0
  5792. for (int i = pool->size-1; i >= 1; i--) {
  5793. pool->free_queue[pool->queue_top++] = i;
  5794. }
  5795. }
  5796. _SOKOL_PRIVATE void _sg_pool_discard(_sg_pool_t* pool) {
  5797. SOKOL_ASSERT(pool);
  5798. SOKOL_ASSERT(pool->free_queue);
  5799. _sg_free(pool->free_queue);
  5800. pool->free_queue = 0;
  5801. SOKOL_ASSERT(pool->gen_ctrs);
  5802. _sg_free(pool->gen_ctrs);
  5803. pool->gen_ctrs = 0;
  5804. pool->size = 0;
  5805. pool->queue_top = 0;
  5806. }
  5807. _SOKOL_PRIVATE int _sg_pool_alloc_index(_sg_pool_t* pool) {
  5808. SOKOL_ASSERT(pool);
  5809. SOKOL_ASSERT(pool->free_queue);
  5810. if (pool->queue_top > 0) {
  5811. int slot_index = pool->free_queue[--pool->queue_top];
  5812. SOKOL_ASSERT((slot_index > 0) && (slot_index < pool->size));
  5813. return slot_index;
  5814. } else {
  5815. // pool exhausted
  5816. return _SG_INVALID_SLOT_INDEX;
  5817. }
  5818. }
  5819. _SOKOL_PRIVATE void _sg_pool_free_index(_sg_pool_t* pool, int slot_index) {
  5820. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < pool->size));
  5821. SOKOL_ASSERT(pool);
  5822. SOKOL_ASSERT(pool->free_queue);
  5823. SOKOL_ASSERT(pool->queue_top < pool->size);
  5824. #ifdef SOKOL_DEBUG
  5825. // debug check against double-free
  5826. for (int i = 0; i < pool->queue_top; i++) {
  5827. SOKOL_ASSERT(pool->free_queue[i] != slot_index);
  5828. }
  5829. #endif
  5830. pool->free_queue[pool->queue_top++] = slot_index;
  5831. SOKOL_ASSERT(pool->queue_top <= (pool->size-1));
  5832. }
  5833. _SOKOL_PRIVATE void _sg_slot_reset(_sg_slot_t* slot) {
  5834. SOKOL_ASSERT(slot);
  5835. _sg_clear(slot, sizeof(_sg_slot_t));
  5836. }
  5837. _SOKOL_PRIVATE void _sg_reset_buffer_to_alloc_state(_sg_buffer_t* buf) {
  5838. SOKOL_ASSERT(buf);
  5839. _sg_slot_t slot = buf->slot;
  5840. _sg_clear(buf, sizeof(*buf));
  5841. buf->slot = slot;
  5842. buf->slot.uninit_count += 1;
  5843. buf->slot.state = SG_RESOURCESTATE_ALLOC;
  5844. }
  5845. _SOKOL_PRIVATE void _sg_reset_image_to_alloc_state(_sg_image_t* img) {
  5846. SOKOL_ASSERT(img);
  5847. _sg_slot_t slot = img->slot;
  5848. _sg_clear(img, sizeof(*img));
  5849. img->slot = slot;
  5850. img->slot.uninit_count += 1;
  5851. img->slot.state = SG_RESOURCESTATE_ALLOC;
  5852. }
  5853. _SOKOL_PRIVATE void _sg_reset_sampler_to_alloc_state(_sg_sampler_t* smp) {
  5854. SOKOL_ASSERT(smp);
  5855. _sg_slot_t slot = smp->slot;
  5856. _sg_clear(smp, sizeof(*smp));
  5857. smp->slot = slot;
  5858. smp->slot.uninit_count += 1;
  5859. smp->slot.state = SG_RESOURCESTATE_ALLOC;
  5860. }
  5861. _SOKOL_PRIVATE void _sg_reset_shader_to_alloc_state(_sg_shader_t* shd) {
  5862. SOKOL_ASSERT(shd);
  5863. _sg_slot_t slot = shd->slot;
  5864. _sg_clear(shd, sizeof(*shd));
  5865. shd->slot = slot;
  5866. shd->slot.uninit_count += 1;
  5867. shd->slot.state = SG_RESOURCESTATE_ALLOC;
  5868. }
  5869. _SOKOL_PRIVATE void _sg_reset_pipeline_to_alloc_state(_sg_pipeline_t* pip) {
  5870. SOKOL_ASSERT(pip);
  5871. _sg_slot_t slot = pip->slot;
  5872. _sg_clear(pip, sizeof(*pip));
  5873. pip->slot = slot;
  5874. pip->slot.uninit_count += 1;
  5875. pip->slot.state = SG_RESOURCESTATE_ALLOC;
  5876. }
  5877. _SOKOL_PRIVATE void _sg_reset_attachments_to_alloc_state(_sg_attachments_t* atts) {
  5878. SOKOL_ASSERT(atts);
  5879. _sg_slot_t slot = atts->slot;
  5880. _sg_clear(atts, sizeof(*atts));
  5881. atts->slot = slot;
  5882. atts->slot.uninit_count += 1;
  5883. atts->slot.state = SG_RESOURCESTATE_ALLOC;
  5884. }
  5885. _SOKOL_PRIVATE void _sg_setup_pools(_sg_pools_t* p, const sg_desc* desc) {
  5886. SOKOL_ASSERT(p);
  5887. SOKOL_ASSERT(desc);
  5888. // note: the pools here will have an additional item, since slot 0 is reserved
  5889. SOKOL_ASSERT((desc->buffer_pool_size > 0) && (desc->buffer_pool_size < _SG_MAX_POOL_SIZE));
  5890. _sg_pool_init(&p->buffer_pool, desc->buffer_pool_size);
  5891. size_t buffer_pool_byte_size = sizeof(_sg_buffer_t) * (size_t)p->buffer_pool.size;
  5892. p->buffers = (_sg_buffer_t*) _sg_malloc_clear(buffer_pool_byte_size);
  5893. SOKOL_ASSERT((desc->image_pool_size > 0) && (desc->image_pool_size < _SG_MAX_POOL_SIZE));
  5894. _sg_pool_init(&p->image_pool, desc->image_pool_size);
  5895. size_t image_pool_byte_size = sizeof(_sg_image_t) * (size_t)p->image_pool.size;
  5896. p->images = (_sg_image_t*) _sg_malloc_clear(image_pool_byte_size);
  5897. SOKOL_ASSERT((desc->sampler_pool_size > 0) && (desc->sampler_pool_size < _SG_MAX_POOL_SIZE));
  5898. _sg_pool_init(&p->sampler_pool, desc->sampler_pool_size);
  5899. size_t sampler_pool_byte_size = sizeof(_sg_sampler_t) * (size_t)p->sampler_pool.size;
  5900. p->samplers = (_sg_sampler_t*) _sg_malloc_clear(sampler_pool_byte_size);
  5901. SOKOL_ASSERT((desc->shader_pool_size > 0) && (desc->shader_pool_size < _SG_MAX_POOL_SIZE));
  5902. _sg_pool_init(&p->shader_pool, desc->shader_pool_size);
  5903. size_t shader_pool_byte_size = sizeof(_sg_shader_t) * (size_t)p->shader_pool.size;
  5904. p->shaders = (_sg_shader_t*) _sg_malloc_clear(shader_pool_byte_size);
  5905. SOKOL_ASSERT((desc->pipeline_pool_size > 0) && (desc->pipeline_pool_size < _SG_MAX_POOL_SIZE));
  5906. _sg_pool_init(&p->pipeline_pool, desc->pipeline_pool_size);
  5907. size_t pipeline_pool_byte_size = sizeof(_sg_pipeline_t) * (size_t)p->pipeline_pool.size;
  5908. p->pipelines = (_sg_pipeline_t*) _sg_malloc_clear(pipeline_pool_byte_size);
  5909. SOKOL_ASSERT((desc->attachments_pool_size > 0) && (desc->attachments_pool_size < _SG_MAX_POOL_SIZE));
  5910. _sg_pool_init(&p->attachments_pool, desc->attachments_pool_size);
  5911. size_t attachments_pool_byte_size = sizeof(_sg_attachments_t) * (size_t)p->attachments_pool.size;
  5912. p->attachments = (_sg_attachments_t*) _sg_malloc_clear(attachments_pool_byte_size);
  5913. }
  5914. _SOKOL_PRIVATE void _sg_discard_pools(_sg_pools_t* p) {
  5915. SOKOL_ASSERT(p);
  5916. _sg_free(p->attachments); p->attachments = 0;
  5917. _sg_free(p->pipelines); p->pipelines = 0;
  5918. _sg_free(p->shaders); p->shaders = 0;
  5919. _sg_free(p->samplers); p->samplers = 0;
  5920. _sg_free(p->images); p->images = 0;
  5921. _sg_free(p->buffers); p->buffers = 0;
  5922. _sg_pool_discard(&p->attachments_pool);
  5923. _sg_pool_discard(&p->pipeline_pool);
  5924. _sg_pool_discard(&p->shader_pool);
  5925. _sg_pool_discard(&p->sampler_pool);
  5926. _sg_pool_discard(&p->image_pool);
  5927. _sg_pool_discard(&p->buffer_pool);
  5928. }
  5929. /* allocate the slot at slot_index:
  5930. - bump the slot's generation counter
  5931. - create a resource id from the generation counter and slot index
  5932. - set the slot's id to this id
  5933. - set the slot's state to ALLOC
  5934. - return the resource id
  5935. */
  5936. _SOKOL_PRIVATE uint32_t _sg_slot_alloc(_sg_pool_t* pool, _sg_slot_t* slot, int slot_index) {
  5937. /* FIXME: add handling for an overflowing generation counter,
  5938. for now, just overflow (another option is to disable
  5939. the slot)
  5940. */
  5941. SOKOL_ASSERT(pool && pool->gen_ctrs);
  5942. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < pool->size));
  5943. SOKOL_ASSERT(slot->id == SG_INVALID_ID);
  5944. SOKOL_ASSERT(slot->state == SG_RESOURCESTATE_INITIAL);
  5945. uint32_t ctr = ++pool->gen_ctrs[slot_index];
  5946. slot->id = (ctr<<_SG_SLOT_SHIFT)|(slot_index & _SG_SLOT_MASK);
  5947. slot->state = SG_RESOURCESTATE_ALLOC;
  5948. return slot->id;
  5949. }
  5950. // extract slot index from id
  5951. _SOKOL_PRIVATE int _sg_slot_index(uint32_t id) {
  5952. int slot_index = (int) (id & _SG_SLOT_MASK);
  5953. SOKOL_ASSERT(_SG_INVALID_SLOT_INDEX != slot_index);
  5954. return slot_index;
  5955. }
  5956. // returns pointer to resource by id without matching id check
  5957. _SOKOL_PRIVATE _sg_buffer_t* _sg_buffer_at(uint32_t buf_id) {
  5958. SOKOL_ASSERT(SG_INVALID_ID != buf_id);
  5959. int slot_index = _sg_slot_index(buf_id);
  5960. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < _sg.pools.buffer_pool.size));
  5961. return &_sg.pools.buffers[slot_index];
  5962. }
  5963. _SOKOL_PRIVATE _sg_image_t* _sg_image_at(uint32_t img_id) {
  5964. SOKOL_ASSERT(SG_INVALID_ID != img_id);
  5965. int slot_index = _sg_slot_index(img_id);
  5966. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < _sg.pools.image_pool.size));
  5967. return &_sg.pools.images[slot_index];
  5968. }
  5969. _SOKOL_PRIVATE _sg_sampler_t* _sg_sampler_at(uint32_t smp_id) {
  5970. SOKOL_ASSERT(SG_INVALID_ID != smp_id);
  5971. int slot_index = _sg_slot_index(smp_id);
  5972. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < _sg.pools.sampler_pool.size));
  5973. return &_sg.pools.samplers[slot_index];
  5974. }
  5975. _SOKOL_PRIVATE _sg_shader_t* _sg_shader_at(uint32_t shd_id) {
  5976. SOKOL_ASSERT(SG_INVALID_ID != shd_id);
  5977. int slot_index = _sg_slot_index(shd_id);
  5978. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < _sg.pools.shader_pool.size));
  5979. return &_sg.pools.shaders[slot_index];
  5980. }
  5981. _SOKOL_PRIVATE _sg_pipeline_t* _sg_pipeline_at(uint32_t pip_id) {
  5982. SOKOL_ASSERT(SG_INVALID_ID != pip_id);
  5983. int slot_index = _sg_slot_index(pip_id);
  5984. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < _sg.pools.pipeline_pool.size));
  5985. return &_sg.pools.pipelines[slot_index];
  5986. }
  5987. _SOKOL_PRIVATE _sg_attachments_t* _sg_attachments_at(uint32_t atts_id) {
  5988. SOKOL_ASSERT(SG_INVALID_ID != atts_id);
  5989. int slot_index = _sg_slot_index(atts_id);
  5990. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < _sg.pools.attachments_pool.size));
  5991. return &_sg.pools.attachments[slot_index];
  5992. }
  5993. // returns pointer to resource with matching id check, may return 0
  5994. _SOKOL_PRIVATE _sg_buffer_t* _sg_lookup_buffer(uint32_t buf_id) {
  5995. if (SG_INVALID_ID != buf_id) {
  5996. _sg_buffer_t* buf = _sg_buffer_at(buf_id);
  5997. if (buf->slot.id == buf_id) {
  5998. return buf;
  5999. }
  6000. }
  6001. return 0;
  6002. }
  6003. _SOKOL_PRIVATE _sg_image_t* _sg_lookup_image(uint32_t img_id) {
  6004. if (SG_INVALID_ID != img_id) {
  6005. _sg_image_t* img = _sg_image_at(img_id);
  6006. if (img->slot.id == img_id) {
  6007. return img;
  6008. }
  6009. }
  6010. return 0;
  6011. }
  6012. _SOKOL_PRIVATE _sg_sampler_t* _sg_lookup_sampler(uint32_t smp_id) {
  6013. if (SG_INVALID_ID != smp_id) {
  6014. _sg_sampler_t* smp = _sg_sampler_at(smp_id);
  6015. if (smp->slot.id == smp_id) {
  6016. return smp;
  6017. }
  6018. }
  6019. return 0;
  6020. }
  6021. _SOKOL_PRIVATE _sg_shader_t* _sg_lookup_shader(uint32_t shd_id) {
  6022. if (SG_INVALID_ID != shd_id) {
  6023. _sg_shader_t* shd = _sg_shader_at(shd_id);
  6024. if (shd->slot.id == shd_id) {
  6025. return shd;
  6026. }
  6027. }
  6028. return 0;
  6029. }
  6030. _SOKOL_PRIVATE _sg_pipeline_t* _sg_lookup_pipeline(uint32_t pip_id) {
  6031. if (SG_INVALID_ID != pip_id) {
  6032. _sg_pipeline_t* pip = _sg_pipeline_at(pip_id);
  6033. if (pip->slot.id == pip_id) {
  6034. return pip;
  6035. }
  6036. }
  6037. return 0;
  6038. }
  6039. _SOKOL_PRIVATE _sg_attachments_t* _sg_lookup_attachments(uint32_t atts_id) {
  6040. if (SG_INVALID_ID != atts_id) {
  6041. _sg_attachments_t* atts = _sg_attachments_at(atts_id);
  6042. if (atts->slot.id == atts_id) {
  6043. return atts;
  6044. }
  6045. }
  6046. return 0;
  6047. }
  6048. // ██████ ███████ ███████ ███████
  6049. // ██ ██ ██ ██ ██
  6050. // ██████ █████ █████ ███████
  6051. // ██ ██ ██ ██ ██
  6052. // ██ ██ ███████ ██ ███████
  6053. //
  6054. // >>refs
  6055. _SOKOL_PRIVATE _sg_sref_t _sg_sref(const _sg_slot_t* slot) {
  6056. _sg_sref_t sref; _sg_clear(&sref, sizeof(sref));
  6057. if (slot) {
  6058. sref.id = slot->id;
  6059. sref.uninit_count = slot->uninit_count;
  6060. }
  6061. return sref;
  6062. }
  6063. _SOKOL_PRIVATE bool _sg_sref_eql(const _sg_sref_t* sref, const _sg_slot_t* slot) {
  6064. SOKOL_ASSERT(sref && slot);
  6065. return (sref->id == slot->id) && (sref->uninit_count == slot->uninit_count);
  6066. }
  6067. _SOKOL_PRIVATE _sg_buffer_ref_t _sg_buffer_ref(_sg_buffer_t* buf_or_null) {
  6068. _sg_buffer_ref_t ref; _sg_clear(&ref, sizeof(ref));
  6069. if (buf_or_null) {
  6070. _sg_buffer_t* buf = buf_or_null;
  6071. SOKOL_ASSERT(buf->slot.id != SG_INVALID_ID);
  6072. ref.ptr = buf;
  6073. ref.sref = _sg_sref(&buf->slot);
  6074. }
  6075. return ref;
  6076. }
  6077. _SOKOL_PRIVATE _sg_image_ref_t _sg_image_ref(_sg_image_t* img_or_null) {
  6078. _sg_image_ref_t ref; _sg_clear(&ref, sizeof(ref));
  6079. if (img_or_null) {
  6080. _sg_image_t* img = img_or_null;
  6081. SOKOL_ASSERT(img->slot.id != SG_INVALID_ID);
  6082. ref.ptr = img;
  6083. ref.sref = _sg_sref(&img->slot);
  6084. }
  6085. return ref;
  6086. }
  6087. _SOKOL_PRIVATE _sg_sampler_ref_t _sg_sampler_ref(_sg_sampler_t* smp_or_null) {
  6088. _sg_sampler_ref_t ref; _sg_clear(&ref, sizeof(ref));
  6089. if (smp_or_null) {
  6090. _sg_sampler_t* smp = smp_or_null;
  6091. SOKOL_ASSERT(smp->slot.id != SG_INVALID_ID);
  6092. ref.ptr = smp;
  6093. ref.sref = _sg_sref(&smp->slot);
  6094. }
  6095. return ref;
  6096. }
  6097. _SOKOL_PRIVATE _sg_shader_ref_t _sg_shader_ref(_sg_shader_t* shd_or_null) {
  6098. _sg_shader_ref_t ref; _sg_clear(&ref, sizeof(ref));
  6099. if (shd_or_null) {
  6100. _sg_shader_t* shd = shd_or_null;
  6101. SOKOL_ASSERT(shd->slot.id != SG_INVALID_ID);
  6102. ref.ptr = shd;
  6103. ref.sref = _sg_sref(&shd->slot);
  6104. }
  6105. return ref;
  6106. }
  6107. _SOKOL_PRIVATE _sg_pipeline_ref_t _sg_pipeline_ref(_sg_pipeline_t* pip_or_null) {
  6108. _sg_pipeline_ref_t ref; _sg_clear(&ref, sizeof(ref));
  6109. if (pip_or_null) {
  6110. _sg_pipeline_t* pip = pip_or_null;
  6111. SOKOL_ASSERT(pip->slot.id != SG_INVALID_ID);
  6112. ref.ptr = pip;
  6113. ref.sref = _sg_sref(&pip->slot);
  6114. }
  6115. return ref;
  6116. }
  6117. _SOKOL_PRIVATE _sg_attachments_ref_t _sg_attachments_ref(_sg_attachments_t* atts_or_null) {
  6118. _sg_attachments_ref_t ref; _sg_clear(&ref, sizeof(ref));
  6119. if (atts_or_null) {
  6120. _sg_attachments_t* atts = atts_or_null;
  6121. SOKOL_ASSERT(atts->slot.id != SG_INVALID_ID);
  6122. ref.ptr = atts;
  6123. ref.sref = _sg_sref(&atts->slot);
  6124. }
  6125. return ref;
  6126. }
  6127. #define _SG_IMPL_RES_EQL(NAME,REF,RES) _SOKOL_PRIVATE bool NAME(const REF* ref, const RES* res) { SOKOL_ASSERT(ref && res); return _sg_sref_eql(&ref->sref, &res->slot); }
  6128. _SG_IMPL_RES_EQL(_sg_buffer_ref_eql, _sg_buffer_ref_t, _sg_buffer_t)
  6129. _SG_IMPL_RES_EQL(_sg_image_ref_eql, _sg_image_ref_t, _sg_image_t)
  6130. _SG_IMPL_RES_EQL(_sg_sampler_ref_eql, _sg_sampler_ref_t, _sg_sampler_t)
  6131. _SG_IMPL_RES_EQL(_sg_shader_ref_eql, _sg_shader_ref_t, _sg_shader_t)
  6132. _SG_IMPL_RES_EQL(_sg_pipeline_ref_eql, _sg_pipeline_ref_t, _sg_pipeline_t)
  6133. _SG_IMPL_RES_EQL(_sg_attachments_ref_eql, _sg_attachments_ref_t, _sg_attachments_t)
  6134. #define _SG_IMPL_RES_NULL(NAME,REF) _SOKOL_PRIVATE bool NAME(const REF* ref) { SOKOL_ASSERT(ref); return SG_INVALID_ID == ref->sref.id; }
  6135. _SG_IMPL_RES_NULL(_sg_buffer_ref_null, _sg_buffer_ref_t)
  6136. _SG_IMPL_RES_NULL(_sg_image_ref_null, _sg_image_ref_t)
  6137. _SG_IMPL_RES_NULL(_sg_sampler_ref_null, _sg_sampler_ref_t)
  6138. _SG_IMPL_RES_NULL(_sg_shader_ref_null, _sg_shader_ref_t)
  6139. _SG_IMPL_RES_NULL(_sg_pipeline_ref_null, _sg_pipeline_ref_t)
  6140. _SG_IMPL_RES_NULL(_sg_attachments_ref_null, _sg_attachments_ref_t)
  6141. #define _SG_IMPL_RES_ALIVE(NAME,REF) _SOKOL_PRIVATE bool NAME(const REF* ref) { SOKOL_ASSERT(ref); return ref->ptr && _sg_sref_eql(&ref->sref, &ref->ptr->slot); }
  6142. _SG_IMPL_RES_ALIVE(_sg_buffer_ref_alive, _sg_buffer_ref_t)
  6143. _SG_IMPL_RES_ALIVE(_sg_image_ref_alive, _sg_image_ref_t)
  6144. _SG_IMPL_RES_ALIVE(_sg_sampler_ref_alive, _sg_sampler_ref_t)
  6145. _SG_IMPL_RES_ALIVE(_sg_shader_ref_alive, _sg_shader_ref_t)
  6146. _SG_IMPL_RES_ALIVE(_sg_pipeline_ref_alive, _sg_pipeline_ref_t)
  6147. _SG_IMPL_RES_ALIVE(_sg_attachments_ref_alive, _sg_attachments_ref_t)
  6148. #define _SG_IMPL_RES_PTR(NAME,REF,RES) _SOKOL_PRIVATE RES* NAME(const REF* ref) { SOKOL_ASSERT(ref && ref->ptr && _sg_sref_eql(&ref->sref, &ref->ptr->slot)); return ref->ptr; }
  6149. _SG_IMPL_RES_PTR(_sg_buffer_ref_ptr, _sg_buffer_ref_t, _sg_buffer_t)
  6150. _SG_IMPL_RES_PTR(_sg_image_ref_ptr, _sg_image_ref_t, _sg_image_t)
  6151. _SG_IMPL_RES_PTR(_sg_sampler_ref_ptr, _sg_sampler_ref_t, _sg_sampler_t)
  6152. _SG_IMPL_RES_PTR(_sg_shader_ref_ptr, _sg_shader_ref_t, _sg_shader_t)
  6153. _SG_IMPL_RES_PTR(_sg_pipeline_ref_ptr, _sg_pipeline_ref_t, _sg_pipeline_t)
  6154. _SG_IMPL_RES_PTR(_sg_attachments_ref_ptr, _sg_attachments_ref_t, _sg_attachments_t)
  6155. #define _SG_IMPL_RES_PTR_OR_NULL(NAME,REF,RES) _SOKOL_PRIVATE RES* NAME(const REF* ref) { SOKOL_ASSERT(ref); if (SG_INVALID_ID != ref->sref.id) { SOKOL_ASSERT(_sg_sref_eql(&ref->sref, &ref->ptr->slot)); return ref->ptr; } else { return 0; } }
  6156. _SG_IMPL_RES_PTR_OR_NULL(_sg_buffer_ref_ptr_or_null, _sg_buffer_ref_t, _sg_buffer_t)
  6157. _SG_IMPL_RES_PTR_OR_NULL(_sg_image_ref_ptr_or_null, _sg_image_ref_t, _sg_image_t)
  6158. _SG_IMPL_RES_PTR_OR_NULL(_sg_sampler_ref_ptr_or_null, _sg_sampler_ref_t, _sg_sampler_t)
  6159. _SG_IMPL_RES_PTR_OR_NULL(_sg_shader_ref_ptr_or_null, _sg_shader_ref_t, _sg_shader_t)
  6160. _SG_IMPL_RES_PTR_OR_NULL(_sg_pipeline_ref_ptr_or_null, _sg_pipeline_ref_t, _sg_pipeline_t)
  6161. _SG_IMPL_RES_PTR_OR_NULL(_sg_attachments_ref_ptr_or_null, _sg_attachments_ref_t, _sg_attachments_t)
  6162. // ████████ ██████ █████ ██████ ██ ██ ███████ ██████
  6163. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  6164. // ██ ██████ ███████ ██ █████ █████ ██████
  6165. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  6166. // ██ ██ ██ ██ ██ ██████ ██ ██ ███████ ██ ██
  6167. //
  6168. // >>tracker
  6169. _SOKOL_PRIVATE void _sg_tracker_init(_sg_tracker_t* tracker, uint32_t num) {
  6170. SOKOL_ASSERT(tracker);
  6171. SOKOL_ASSERT(num > 0);
  6172. SOKOL_ASSERT(0 == tracker->size);
  6173. SOKOL_ASSERT(0 == tracker->cur);
  6174. SOKOL_ASSERT(0 == tracker->items);
  6175. tracker->size = (uint32_t)num;
  6176. tracker->items = (uint32_t*)_sg_malloc_clear(num * sizeof(uint32_t));
  6177. }
  6178. _SOKOL_PRIVATE void _sg_tracker_discard(_sg_tracker_t* tracker) {
  6179. SOKOL_ASSERT(tracker);
  6180. if (tracker->items) {
  6181. _sg_free(tracker->items);
  6182. }
  6183. tracker->size = 0;
  6184. tracker->cur = 0;
  6185. tracker->items = 0;
  6186. }
  6187. _SOKOL_PRIVATE void _sg_tracker_reset(_sg_tracker_t* tracker) {
  6188. SOKOL_ASSERT(tracker && tracker->items);
  6189. tracker->cur = 0;
  6190. }
  6191. _SOKOL_PRIVATE bool _sg_tracker_add(_sg_tracker_t* tracker, uint32_t res_id) {
  6192. SOKOL_ASSERT(tracker && tracker->items);
  6193. if (tracker->cur < tracker->size) {
  6194. tracker->items[tracker->cur++] = res_id;
  6195. return true;
  6196. } else {
  6197. return false;
  6198. }
  6199. }
  6200. // ██ ██ ███████ ██ ██████ ███████ ██████ ███████
  6201. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  6202. // ███████ █████ ██ ██████ █████ ██████ ███████
  6203. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  6204. // ██ ██ ███████ ███████ ██ ███████ ██ ██ ███████
  6205. //
  6206. // >>helpers
  6207. // helper macros
  6208. #define _sg_def(val, def) (((val) == 0) ? (def) : (val))
  6209. #define _sg_def_flt(val, def) (((val) == 0.0f) ? (def) : (val))
  6210. #define _sg_min(a,b) (((a)<(b))?(a):(b))
  6211. #define _sg_max(a,b) (((a)>(b))?(a):(b))
  6212. #define _sg_clamp(v,v0,v1) (((v)<(v0))?(v0):(((v)>(v1))?(v1):(v)))
  6213. #define _sg_fequal(val,cmp,delta) ((((val)-(cmp))> -(delta))&&(((val)-(cmp))<(delta)))
  6214. #define _sg_ispow2(val) ((val&(val-1))==0)
  6215. #define _sg_stats_add(key,val) {if(_sg.stats_enabled){ _sg.stats.key+=val;}}
  6216. _SOKOL_PRIVATE uint32_t _sg_align_u32(uint32_t val, uint32_t align) {
  6217. SOKOL_ASSERT((align > 0) && ((align & (align - 1)) == 0));
  6218. return (val + (align - 1)) & ~(align - 1);
  6219. }
  6220. typedef struct { int x, y, w, h; } _sg_recti_t;
  6221. _SOKOL_PRIVATE _sg_recti_t _sg_clipi(int x, int y, int w, int h, int clip_width, int clip_height) {
  6222. x = _sg_min(_sg_max(0, x), clip_width-1);
  6223. y = _sg_min(_sg_max(0, y), clip_height-1);
  6224. if ((x + w) > clip_width) {
  6225. w = clip_width - x;
  6226. }
  6227. if ((y + h) > clip_height) {
  6228. h = clip_height - y;
  6229. }
  6230. w = _sg_max(w, 1);
  6231. h = _sg_max(h, 1);
  6232. const _sg_recti_t res = { x, y, w, h };
  6233. return res;
  6234. }
  6235. _SOKOL_PRIVATE void _sg_buffer_common_init(_sg_buffer_common_t* cmn, const sg_buffer_desc* desc) {
  6236. cmn->size = (int)desc->size;
  6237. cmn->append_pos = 0;
  6238. cmn->append_overflow = false;
  6239. cmn->update_frame_index = 0;
  6240. cmn->append_frame_index = 0;
  6241. cmn->num_slots = desc->usage.immutable ? 1 : SG_NUM_INFLIGHT_FRAMES;
  6242. cmn->active_slot = 0;
  6243. cmn->usage = desc->usage;
  6244. }
  6245. _SOKOL_PRIVATE void _sg_image_common_init(_sg_image_common_t* cmn, const sg_image_desc* desc) {
  6246. cmn->upd_frame_index = 0;
  6247. cmn->num_slots = desc->usage.immutable ? 1 : SG_NUM_INFLIGHT_FRAMES;
  6248. cmn->active_slot = 0;
  6249. cmn->type = desc->type;
  6250. cmn->width = desc->width;
  6251. cmn->height = desc->height;
  6252. cmn->num_slices = desc->num_slices;
  6253. cmn->num_mipmaps = desc->num_mipmaps;
  6254. cmn->usage = desc->usage;
  6255. cmn->pixel_format = desc->pixel_format;
  6256. cmn->sample_count = desc->sample_count;
  6257. }
  6258. _SOKOL_PRIVATE void _sg_sampler_common_init(_sg_sampler_common_t* cmn, const sg_sampler_desc* desc) {
  6259. cmn->min_filter = desc->min_filter;
  6260. cmn->mag_filter = desc->mag_filter;
  6261. cmn->mipmap_filter = desc->mipmap_filter;
  6262. cmn->wrap_u = desc->wrap_u;
  6263. cmn->wrap_v = desc->wrap_v;
  6264. cmn->wrap_w = desc->wrap_w;
  6265. cmn->min_lod = desc->min_lod;
  6266. cmn->max_lod = desc->max_lod;
  6267. cmn->border_color = desc->border_color;
  6268. cmn->compare = desc->compare;
  6269. cmn->max_anisotropy = desc->max_anisotropy;
  6270. }
  6271. _SOKOL_PRIVATE void _sg_shader_common_init(_sg_shader_common_t* cmn, const sg_shader_desc* desc) {
  6272. cmn->is_compute = desc->compute_func.source || desc->compute_func.bytecode.ptr;
  6273. for (size_t i = 0; i < SG_MAX_VERTEX_ATTRIBUTES; i++) {
  6274. cmn->attrs[i].base_type = desc->attrs[i].base_type;
  6275. }
  6276. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  6277. const sg_shader_uniform_block* src = &desc->uniform_blocks[i];
  6278. _sg_shader_uniform_block_t* dst = &cmn->uniform_blocks[i];
  6279. if (src->stage != SG_SHADERSTAGE_NONE) {
  6280. cmn->required_bindings_and_uniforms |= (1 << i);
  6281. dst->stage = src->stage;
  6282. dst->size = src->size;
  6283. }
  6284. }
  6285. const uint32_t required_bindings_flag = (1 << SG_MAX_UNIFORMBLOCK_BINDSLOTS);
  6286. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  6287. const sg_shader_storage_buffer* src = &desc->storage_buffers[i];
  6288. _sg_shader_storage_buffer_t* dst = &cmn->storage_buffers[i];
  6289. if (src->stage != SG_SHADERSTAGE_NONE) {
  6290. cmn->required_bindings_and_uniforms |= required_bindings_flag;
  6291. dst->stage = src->stage;
  6292. dst->readonly = src->readonly;
  6293. }
  6294. }
  6295. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  6296. const sg_shader_image* src = &desc->images[i];
  6297. _sg_shader_image_t* dst = &cmn->images[i];
  6298. if (src->stage != SG_SHADERSTAGE_NONE) {
  6299. cmn->required_bindings_and_uniforms |= required_bindings_flag;
  6300. dst->stage = src->stage;
  6301. dst->image_type = src->image_type;
  6302. dst->sample_type = src->sample_type;
  6303. dst->multisampled = src->multisampled;
  6304. }
  6305. }
  6306. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  6307. const sg_shader_sampler* src = &desc->samplers[i];
  6308. _sg_shader_sampler_t* dst = &cmn->samplers[i];
  6309. if (src->stage != SG_SHADERSTAGE_NONE) {
  6310. cmn->required_bindings_and_uniforms |= required_bindings_flag;
  6311. dst->stage = src->stage;
  6312. dst->sampler_type = src->sampler_type;
  6313. }
  6314. }
  6315. for (size_t i = 0; i < SG_MAX_IMAGE_SAMPLER_PAIRS; i++) {
  6316. const sg_shader_image_sampler_pair* src = &desc->image_sampler_pairs[i];
  6317. _sg_shader_image_sampler_t* dst = &cmn->image_samplers[i];
  6318. if (src->stage != SG_SHADERSTAGE_NONE) {
  6319. dst->stage = src->stage;
  6320. SOKOL_ASSERT((src->image_slot >= 0) && (src->image_slot < SG_MAX_IMAGE_BINDSLOTS));
  6321. SOKOL_ASSERT(desc->images[src->image_slot].stage == src->stage);
  6322. dst->image_slot = src->image_slot;
  6323. SOKOL_ASSERT((src->sampler_slot >= 0) && (src->sampler_slot < SG_MAX_SAMPLER_BINDSLOTS));
  6324. SOKOL_ASSERT(desc->samplers[src->sampler_slot].stage == src->stage);
  6325. dst->sampler_slot = src->sampler_slot;
  6326. }
  6327. }
  6328. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  6329. const sg_shader_storage_image* src = &desc->storage_images[i];
  6330. _sg_shader_storage_image_t* dst = &cmn->storage_images[i];
  6331. if (src->stage != SG_SHADERSTAGE_NONE) {
  6332. dst->stage = src->stage;
  6333. dst->image_type = src->image_type;
  6334. dst->access_format = src->access_format;
  6335. dst->writeonly = src->writeonly;
  6336. }
  6337. }
  6338. }
  6339. _SOKOL_PRIVATE void _sg_pipeline_common_init(_sg_pipeline_common_t* cmn, const sg_pipeline_desc* desc, _sg_shader_t* shd) {
  6340. SOKOL_ASSERT((desc->color_count >= 0) && (desc->color_count <= SG_MAX_COLOR_ATTACHMENTS));
  6341. // FIXME: most of this isn't needed for compute pipelines
  6342. const uint32_t required_bindings_flag = (1 << SG_MAX_UNIFORMBLOCK_BINDSLOTS);
  6343. for (int i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  6344. const sg_vertex_attr_state* a_state = &desc->layout.attrs[i];
  6345. if (a_state->format != SG_VERTEXFORMAT_INVALID) {
  6346. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  6347. cmn->vertex_buffer_layout_active[a_state->buffer_index] = true;
  6348. cmn->required_bindings_and_uniforms |= required_bindings_flag;
  6349. }
  6350. }
  6351. cmn->is_compute = desc->compute;
  6352. cmn->use_instanced_draw = false;
  6353. cmn->shader = _sg_shader_ref(shd);
  6354. cmn->layout = desc->layout;
  6355. cmn->depth = desc->depth;
  6356. cmn->stencil = desc->stencil;
  6357. cmn->color_count = desc->color_count;
  6358. for (int i = 0; i < desc->color_count; i++) {
  6359. cmn->colors[i] = desc->colors[i];
  6360. }
  6361. cmn->primitive_type = desc->primitive_type;
  6362. cmn->index_type = desc->index_type;
  6363. if (cmn->index_type != SG_INDEXTYPE_NONE) {
  6364. cmn->required_bindings_and_uniforms |= required_bindings_flag;
  6365. }
  6366. cmn->cull_mode = desc->cull_mode;
  6367. cmn->face_winding = desc->face_winding;
  6368. cmn->sample_count = desc->sample_count;
  6369. cmn->blend_color = desc->blend_color;
  6370. cmn->alpha_to_coverage_enabled = desc->alpha_to_coverage_enabled;
  6371. }
  6372. _SOKOL_PRIVATE void _sg_attachment_common_init(_sg_attachment_common_t* cmn, const sg_attachment_desc* desc, _sg_image_t* img) {
  6373. cmn->image = _sg_image_ref(img);
  6374. cmn->mip_level = desc->mip_level;
  6375. cmn->slice = desc->slice;
  6376. }
  6377. _SOKOL_PRIVATE void _sg_attachments_common_init(_sg_attachments_common_t* cmn, const sg_attachments_desc* desc, const _sg_attachments_ptrs_t* ptrs, int width, int height) {
  6378. // NOTE: width/height will be 0 for storage image attachments
  6379. cmn->width = width;
  6380. cmn->height = height;
  6381. for (size_t i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  6382. if (desc->colors[i].image.id != SG_INVALID_ID) {
  6383. cmn->num_colors++;
  6384. _sg_attachment_common_init(&cmn->colors[i], &desc->colors[i], ptrs->color_images[i]);
  6385. _sg_attachment_common_init(&cmn->resolves[i], &desc->resolves[i], ptrs->resolve_images[i]);
  6386. cmn->has_render_attachments = true;
  6387. }
  6388. }
  6389. if (desc->depth_stencil.image.id != SG_INVALID_ID) {
  6390. _sg_attachment_common_init(&cmn->depth_stencil, &desc->depth_stencil, ptrs->ds_image);
  6391. cmn->has_render_attachments = true;
  6392. }
  6393. // NOTE: storage attachment slots may be non-continuous,
  6394. // so a 'num_storages' doesn't make sense
  6395. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  6396. if (desc->storages[i].image.id != SG_INVALID_ID) {
  6397. cmn->has_storage_attachments = true;
  6398. _sg_attachment_common_init(&cmn->storages[i], &desc->storages[i], ptrs->storage_images[i]);
  6399. }
  6400. }
  6401. }
  6402. _SOKOL_PRIVATE int _sg_vertexformat_bytesize(sg_vertex_format fmt) {
  6403. switch (fmt) {
  6404. case SG_VERTEXFORMAT_FLOAT: return 4;
  6405. case SG_VERTEXFORMAT_FLOAT2: return 8;
  6406. case SG_VERTEXFORMAT_FLOAT3: return 12;
  6407. case SG_VERTEXFORMAT_FLOAT4: return 16;
  6408. case SG_VERTEXFORMAT_INT: return 4;
  6409. case SG_VERTEXFORMAT_INT2: return 8;
  6410. case SG_VERTEXFORMAT_INT3: return 12;
  6411. case SG_VERTEXFORMAT_INT4: return 16;
  6412. case SG_VERTEXFORMAT_UINT: return 4;
  6413. case SG_VERTEXFORMAT_UINT2: return 8;
  6414. case SG_VERTEXFORMAT_UINT3: return 12;
  6415. case SG_VERTEXFORMAT_UINT4: return 16;
  6416. case SG_VERTEXFORMAT_BYTE4: return 4;
  6417. case SG_VERTEXFORMAT_BYTE4N: return 4;
  6418. case SG_VERTEXFORMAT_UBYTE4: return 4;
  6419. case SG_VERTEXFORMAT_UBYTE4N: return 4;
  6420. case SG_VERTEXFORMAT_SHORT2: return 4;
  6421. case SG_VERTEXFORMAT_SHORT2N: return 4;
  6422. case SG_VERTEXFORMAT_USHORT2: return 4;
  6423. case SG_VERTEXFORMAT_USHORT2N: return 4;
  6424. case SG_VERTEXFORMAT_SHORT4: return 8;
  6425. case SG_VERTEXFORMAT_SHORT4N: return 8;
  6426. case SG_VERTEXFORMAT_USHORT4: return 8;
  6427. case SG_VERTEXFORMAT_USHORT4N: return 8;
  6428. case SG_VERTEXFORMAT_UINT10_N2: return 4;
  6429. case SG_VERTEXFORMAT_HALF2: return 4;
  6430. case SG_VERTEXFORMAT_HALF4: return 8;
  6431. case SG_VERTEXFORMAT_INVALID: return 0;
  6432. default:
  6433. SOKOL_UNREACHABLE;
  6434. return -1;
  6435. }
  6436. }
  6437. _SOKOL_PRIVATE const char* _sg_vertexformat_to_string(sg_vertex_format fmt) {
  6438. switch (fmt) {
  6439. case SG_VERTEXFORMAT_FLOAT: return "FLOAT";
  6440. case SG_VERTEXFORMAT_FLOAT2: return "FLOAT2";
  6441. case SG_VERTEXFORMAT_FLOAT3: return "FLOAT3";
  6442. case SG_VERTEXFORMAT_FLOAT4: return "FLOAT4";
  6443. case SG_VERTEXFORMAT_INT: return "INT";
  6444. case SG_VERTEXFORMAT_INT2: return "INT2";
  6445. case SG_VERTEXFORMAT_INT3: return "INT3";
  6446. case SG_VERTEXFORMAT_INT4: return "INT4";
  6447. case SG_VERTEXFORMAT_UINT: return "UINT";
  6448. case SG_VERTEXFORMAT_UINT2: return "UINT2";
  6449. case SG_VERTEXFORMAT_UINT3: return "UINT3";
  6450. case SG_VERTEXFORMAT_UINT4: return "UINT4";
  6451. case SG_VERTEXFORMAT_BYTE4: return "BYTE4";
  6452. case SG_VERTEXFORMAT_BYTE4N: return "BYTE4N";
  6453. case SG_VERTEXFORMAT_UBYTE4: return "UBYTE4";
  6454. case SG_VERTEXFORMAT_UBYTE4N: return "UBYTE4N";
  6455. case SG_VERTEXFORMAT_SHORT2: return "SHORT2";
  6456. case SG_VERTEXFORMAT_SHORT2N: return "SHORT2N";
  6457. case SG_VERTEXFORMAT_USHORT2: return "USHORT2";
  6458. case SG_VERTEXFORMAT_USHORT2N: return "USHORT2N";
  6459. case SG_VERTEXFORMAT_SHORT4: return "SHORT4";
  6460. case SG_VERTEXFORMAT_SHORT4N: return "SHORT4N";
  6461. case SG_VERTEXFORMAT_USHORT4: return "USHORT4";
  6462. case SG_VERTEXFORMAT_USHORT4N: return "USHORT4N";
  6463. case SG_VERTEXFORMAT_UINT10_N2: return "UINT10_N2";
  6464. case SG_VERTEXFORMAT_HALF2: return "HALF2";
  6465. case SG_VERTEXFORMAT_HALF4: return "HALF4";
  6466. default:
  6467. SOKOL_UNREACHABLE;
  6468. return "INVALID";
  6469. }
  6470. }
  6471. _SOKOL_PRIVATE const char* _sg_shaderattrbasetype_to_string(sg_shader_attr_base_type b) {
  6472. switch (b) {
  6473. case SG_SHADERATTRBASETYPE_UNDEFINED: return "UNDEFINED";
  6474. case SG_SHADERATTRBASETYPE_FLOAT: return "FLOAT";
  6475. case SG_SHADERATTRBASETYPE_SINT: return "SINT";
  6476. case SG_SHADERATTRBASETYPE_UINT: return "UINT";
  6477. default:
  6478. SOKOL_UNREACHABLE;
  6479. return "INVALID";
  6480. }
  6481. }
  6482. _SOKOL_PRIVATE sg_shader_attr_base_type _sg_vertexformat_basetype(sg_vertex_format fmt) {
  6483. switch (fmt) {
  6484. case SG_VERTEXFORMAT_FLOAT:
  6485. case SG_VERTEXFORMAT_FLOAT2:
  6486. case SG_VERTEXFORMAT_FLOAT3:
  6487. case SG_VERTEXFORMAT_FLOAT4:
  6488. case SG_VERTEXFORMAT_HALF2:
  6489. case SG_VERTEXFORMAT_HALF4:
  6490. case SG_VERTEXFORMAT_BYTE4N:
  6491. case SG_VERTEXFORMAT_UBYTE4N:
  6492. case SG_VERTEXFORMAT_SHORT2N:
  6493. case SG_VERTEXFORMAT_USHORT2N:
  6494. case SG_VERTEXFORMAT_SHORT4N:
  6495. case SG_VERTEXFORMAT_USHORT4N:
  6496. case SG_VERTEXFORMAT_UINT10_N2:
  6497. return SG_SHADERATTRBASETYPE_FLOAT;
  6498. case SG_VERTEXFORMAT_INT:
  6499. case SG_VERTEXFORMAT_INT2:
  6500. case SG_VERTEXFORMAT_INT3:
  6501. case SG_VERTEXFORMAT_INT4:
  6502. case SG_VERTEXFORMAT_BYTE4:
  6503. case SG_VERTEXFORMAT_SHORT2:
  6504. case SG_VERTEXFORMAT_SHORT4:
  6505. return SG_SHADERATTRBASETYPE_SINT;
  6506. case SG_VERTEXFORMAT_UINT:
  6507. case SG_VERTEXFORMAT_UINT2:
  6508. case SG_VERTEXFORMAT_UINT3:
  6509. case SG_VERTEXFORMAT_UINT4:
  6510. case SG_VERTEXFORMAT_UBYTE4:
  6511. case SG_VERTEXFORMAT_USHORT2:
  6512. case SG_VERTEXFORMAT_USHORT4:
  6513. return SG_SHADERATTRBASETYPE_UINT;
  6514. default:
  6515. SOKOL_UNREACHABLE;
  6516. return SG_SHADERATTRBASETYPE_UNDEFINED;
  6517. }
  6518. }
  6519. _SOKOL_PRIVATE uint32_t _sg_uniform_alignment(sg_uniform_type type, int array_count, sg_uniform_layout ub_layout) {
  6520. if (ub_layout == SG_UNIFORMLAYOUT_NATIVE) {
  6521. return 1;
  6522. } else {
  6523. SOKOL_ASSERT(array_count > 0);
  6524. if (array_count == 1) {
  6525. switch (type) {
  6526. case SG_UNIFORMTYPE_FLOAT:
  6527. case SG_UNIFORMTYPE_INT:
  6528. return 4;
  6529. case SG_UNIFORMTYPE_FLOAT2:
  6530. case SG_UNIFORMTYPE_INT2:
  6531. return 8;
  6532. case SG_UNIFORMTYPE_FLOAT3:
  6533. case SG_UNIFORMTYPE_FLOAT4:
  6534. case SG_UNIFORMTYPE_INT3:
  6535. case SG_UNIFORMTYPE_INT4:
  6536. return 16;
  6537. case SG_UNIFORMTYPE_MAT4:
  6538. return 16;
  6539. default:
  6540. SOKOL_UNREACHABLE;
  6541. return 1;
  6542. }
  6543. } else {
  6544. return 16;
  6545. }
  6546. }
  6547. }
  6548. _SOKOL_PRIVATE uint32_t _sg_uniform_size(sg_uniform_type type, int array_count, sg_uniform_layout ub_layout) {
  6549. SOKOL_ASSERT(array_count > 0);
  6550. if (array_count == 1) {
  6551. switch (type) {
  6552. case SG_UNIFORMTYPE_FLOAT:
  6553. case SG_UNIFORMTYPE_INT:
  6554. return 4;
  6555. case SG_UNIFORMTYPE_FLOAT2:
  6556. case SG_UNIFORMTYPE_INT2:
  6557. return 8;
  6558. case SG_UNIFORMTYPE_FLOAT3:
  6559. case SG_UNIFORMTYPE_INT3:
  6560. return 12;
  6561. case SG_UNIFORMTYPE_FLOAT4:
  6562. case SG_UNIFORMTYPE_INT4:
  6563. return 16;
  6564. case SG_UNIFORMTYPE_MAT4:
  6565. return 64;
  6566. default:
  6567. SOKOL_UNREACHABLE;
  6568. return 0;
  6569. }
  6570. } else {
  6571. if (ub_layout == SG_UNIFORMLAYOUT_NATIVE) {
  6572. switch (type) {
  6573. case SG_UNIFORMTYPE_FLOAT:
  6574. case SG_UNIFORMTYPE_INT:
  6575. return 4 * (uint32_t)array_count;
  6576. case SG_UNIFORMTYPE_FLOAT2:
  6577. case SG_UNIFORMTYPE_INT2:
  6578. return 8 * (uint32_t)array_count;
  6579. case SG_UNIFORMTYPE_FLOAT3:
  6580. case SG_UNIFORMTYPE_INT3:
  6581. return 12 * (uint32_t)array_count;
  6582. case SG_UNIFORMTYPE_FLOAT4:
  6583. case SG_UNIFORMTYPE_INT4:
  6584. return 16 * (uint32_t)array_count;
  6585. case SG_UNIFORMTYPE_MAT4:
  6586. return 64 * (uint32_t)array_count;
  6587. default:
  6588. SOKOL_UNREACHABLE;
  6589. return 0;
  6590. }
  6591. } else {
  6592. switch (type) {
  6593. case SG_UNIFORMTYPE_FLOAT:
  6594. case SG_UNIFORMTYPE_FLOAT2:
  6595. case SG_UNIFORMTYPE_FLOAT3:
  6596. case SG_UNIFORMTYPE_FLOAT4:
  6597. case SG_UNIFORMTYPE_INT:
  6598. case SG_UNIFORMTYPE_INT2:
  6599. case SG_UNIFORMTYPE_INT3:
  6600. case SG_UNIFORMTYPE_INT4:
  6601. return 16 * (uint32_t)array_count;
  6602. case SG_UNIFORMTYPE_MAT4:
  6603. return 64 * (uint32_t)array_count;
  6604. default:
  6605. SOKOL_UNREACHABLE;
  6606. return 0;
  6607. }
  6608. }
  6609. }
  6610. }
  6611. _SOKOL_PRIVATE bool _sg_is_compressed_pixel_format(sg_pixel_format fmt) {
  6612. switch (fmt) {
  6613. case SG_PIXELFORMAT_BC1_RGBA:
  6614. case SG_PIXELFORMAT_BC2_RGBA:
  6615. case SG_PIXELFORMAT_BC3_RGBA:
  6616. case SG_PIXELFORMAT_BC3_SRGBA:
  6617. case SG_PIXELFORMAT_BC4_R:
  6618. case SG_PIXELFORMAT_BC4_RSN:
  6619. case SG_PIXELFORMAT_BC5_RG:
  6620. case SG_PIXELFORMAT_BC5_RGSN:
  6621. case SG_PIXELFORMAT_BC6H_RGBF:
  6622. case SG_PIXELFORMAT_BC6H_RGBUF:
  6623. case SG_PIXELFORMAT_BC7_RGBA:
  6624. case SG_PIXELFORMAT_BC7_SRGBA:
  6625. case SG_PIXELFORMAT_ETC2_RGB8:
  6626. case SG_PIXELFORMAT_ETC2_SRGB8:
  6627. case SG_PIXELFORMAT_ETC2_RGB8A1:
  6628. case SG_PIXELFORMAT_ETC2_RGBA8:
  6629. case SG_PIXELFORMAT_ETC2_SRGB8A8:
  6630. case SG_PIXELFORMAT_EAC_R11:
  6631. case SG_PIXELFORMAT_EAC_R11SN:
  6632. case SG_PIXELFORMAT_EAC_RG11:
  6633. case SG_PIXELFORMAT_EAC_RG11SN:
  6634. case SG_PIXELFORMAT_ASTC_4x4_RGBA:
  6635. case SG_PIXELFORMAT_ASTC_4x4_SRGBA:
  6636. return true;
  6637. default:
  6638. return false;
  6639. }
  6640. }
  6641. _SOKOL_PRIVATE bool _sg_is_valid_attachment_color_format(sg_pixel_format fmt) {
  6642. const int fmt_index = (int) fmt;
  6643. SOKOL_ASSERT((fmt_index >= 0) && (fmt_index < _SG_PIXELFORMAT_NUM));
  6644. return _sg.formats[fmt_index].render && !_sg.formats[fmt_index].depth;
  6645. }
  6646. _SOKOL_PRIVATE bool _sg_is_valid_attachment_depth_format(sg_pixel_format fmt) {
  6647. const int fmt_index = (int) fmt;
  6648. SOKOL_ASSERT((fmt_index >= 0) && (fmt_index < _SG_PIXELFORMAT_NUM));
  6649. return _sg.formats[fmt_index].render && _sg.formats[fmt_index].depth;
  6650. }
  6651. _SOKOL_PRIVATE bool _sg_is_valid_attachment_storage_format(sg_pixel_format fmt) {
  6652. const int fmt_index = (int) fmt;
  6653. SOKOL_ASSERT((fmt_index >= 0) && (fmt_index < _SG_PIXELFORMAT_NUM));
  6654. return _sg.formats[fmt_index].read || _sg.formats[fmt_index].write;
  6655. }
  6656. _SOKOL_PRIVATE bool _sg_is_depth_or_depth_stencil_format(sg_pixel_format fmt) {
  6657. return (SG_PIXELFORMAT_DEPTH == fmt) || (SG_PIXELFORMAT_DEPTH_STENCIL == fmt);
  6658. }
  6659. _SOKOL_PRIVATE bool _sg_is_depth_stencil_format(sg_pixel_format fmt) {
  6660. return (SG_PIXELFORMAT_DEPTH_STENCIL == fmt);
  6661. }
  6662. _SOKOL_PRIVATE int _sg_pixelformat_bytesize(sg_pixel_format fmt) {
  6663. switch (fmt) {
  6664. case SG_PIXELFORMAT_R8:
  6665. case SG_PIXELFORMAT_R8SN:
  6666. case SG_PIXELFORMAT_R8UI:
  6667. case SG_PIXELFORMAT_R8SI:
  6668. return 1;
  6669. case SG_PIXELFORMAT_R16:
  6670. case SG_PIXELFORMAT_R16SN:
  6671. case SG_PIXELFORMAT_R16UI:
  6672. case SG_PIXELFORMAT_R16SI:
  6673. case SG_PIXELFORMAT_R16F:
  6674. case SG_PIXELFORMAT_RG8:
  6675. case SG_PIXELFORMAT_RG8SN:
  6676. case SG_PIXELFORMAT_RG8UI:
  6677. case SG_PIXELFORMAT_RG8SI:
  6678. return 2;
  6679. case SG_PIXELFORMAT_R32UI:
  6680. case SG_PIXELFORMAT_R32SI:
  6681. case SG_PIXELFORMAT_R32F:
  6682. case SG_PIXELFORMAT_RG16:
  6683. case SG_PIXELFORMAT_RG16SN:
  6684. case SG_PIXELFORMAT_RG16UI:
  6685. case SG_PIXELFORMAT_RG16SI:
  6686. case SG_PIXELFORMAT_RG16F:
  6687. case SG_PIXELFORMAT_RGBA8:
  6688. case SG_PIXELFORMAT_SRGB8A8:
  6689. case SG_PIXELFORMAT_RGBA8SN:
  6690. case SG_PIXELFORMAT_RGBA8UI:
  6691. case SG_PIXELFORMAT_RGBA8SI:
  6692. case SG_PIXELFORMAT_BGRA8:
  6693. case SG_PIXELFORMAT_RGB10A2:
  6694. case SG_PIXELFORMAT_RG11B10F:
  6695. case SG_PIXELFORMAT_RGB9E5:
  6696. return 4;
  6697. case SG_PIXELFORMAT_RG32UI:
  6698. case SG_PIXELFORMAT_RG32SI:
  6699. case SG_PIXELFORMAT_RG32F:
  6700. case SG_PIXELFORMAT_RGBA16:
  6701. case SG_PIXELFORMAT_RGBA16SN:
  6702. case SG_PIXELFORMAT_RGBA16UI:
  6703. case SG_PIXELFORMAT_RGBA16SI:
  6704. case SG_PIXELFORMAT_RGBA16F:
  6705. return 8;
  6706. case SG_PIXELFORMAT_RGBA32UI:
  6707. case SG_PIXELFORMAT_RGBA32SI:
  6708. case SG_PIXELFORMAT_RGBA32F:
  6709. return 16;
  6710. case SG_PIXELFORMAT_DEPTH:
  6711. case SG_PIXELFORMAT_DEPTH_STENCIL:
  6712. return 4;
  6713. default:
  6714. SOKOL_UNREACHABLE;
  6715. return 0;
  6716. }
  6717. }
  6718. _SOKOL_PRIVATE int _sg_roundup(int val, int round_to) {
  6719. return (val+(round_to-1)) & ~(round_to-1);
  6720. }
  6721. _SOKOL_PRIVATE uint32_t _sg_roundup_u32(uint32_t val, uint32_t round_to) {
  6722. return (val+(round_to-1)) & ~(round_to-1);
  6723. }
  6724. _SOKOL_PRIVATE uint64_t _sg_roundup_u64(uint64_t val, uint64_t round_to) {
  6725. return (val+(round_to-1)) & ~(round_to-1);
  6726. }
  6727. _SOKOL_PRIVATE bool _sg_multiple_u64(uint64_t val, uint64_t of) {
  6728. return (val & (of-1)) == 0;
  6729. }
  6730. /* return row pitch for an image
  6731. see ComputePitch in https://github.com/microsoft/DirectXTex/blob/master/DirectXTex/DirectXTexUtil.cpp
  6732. */
  6733. _SOKOL_PRIVATE int _sg_row_pitch(sg_pixel_format fmt, int width, int row_align) {
  6734. int pitch;
  6735. switch (fmt) {
  6736. case SG_PIXELFORMAT_BC1_RGBA:
  6737. case SG_PIXELFORMAT_BC4_R:
  6738. case SG_PIXELFORMAT_BC4_RSN:
  6739. case SG_PIXELFORMAT_ETC2_RGB8:
  6740. case SG_PIXELFORMAT_ETC2_SRGB8:
  6741. case SG_PIXELFORMAT_ETC2_RGB8A1:
  6742. case SG_PIXELFORMAT_EAC_R11:
  6743. case SG_PIXELFORMAT_EAC_R11SN:
  6744. pitch = ((width + 3) / 4) * 8;
  6745. pitch = pitch < 8 ? 8 : pitch;
  6746. break;
  6747. case SG_PIXELFORMAT_BC2_RGBA:
  6748. case SG_PIXELFORMAT_BC3_RGBA:
  6749. case SG_PIXELFORMAT_BC3_SRGBA:
  6750. case SG_PIXELFORMAT_BC5_RG:
  6751. case SG_PIXELFORMAT_BC5_RGSN:
  6752. case SG_PIXELFORMAT_BC6H_RGBF:
  6753. case SG_PIXELFORMAT_BC6H_RGBUF:
  6754. case SG_PIXELFORMAT_BC7_RGBA:
  6755. case SG_PIXELFORMAT_BC7_SRGBA:
  6756. case SG_PIXELFORMAT_ETC2_RGBA8:
  6757. case SG_PIXELFORMAT_ETC2_SRGB8A8:
  6758. case SG_PIXELFORMAT_EAC_RG11:
  6759. case SG_PIXELFORMAT_EAC_RG11SN:
  6760. case SG_PIXELFORMAT_ASTC_4x4_RGBA:
  6761. case SG_PIXELFORMAT_ASTC_4x4_SRGBA:
  6762. pitch = ((width + 3) / 4) * 16;
  6763. pitch = pitch < 16 ? 16 : pitch;
  6764. break;
  6765. default:
  6766. pitch = width * _sg_pixelformat_bytesize(fmt);
  6767. break;
  6768. }
  6769. pitch = _sg_roundup(pitch, row_align);
  6770. return pitch;
  6771. }
  6772. // compute the number of rows in a surface depending on pixel format
  6773. _SOKOL_PRIVATE int _sg_num_rows(sg_pixel_format fmt, int height) {
  6774. int num_rows;
  6775. switch (fmt) {
  6776. case SG_PIXELFORMAT_BC1_RGBA:
  6777. case SG_PIXELFORMAT_BC4_R:
  6778. case SG_PIXELFORMAT_BC4_RSN:
  6779. case SG_PIXELFORMAT_ETC2_RGB8:
  6780. case SG_PIXELFORMAT_ETC2_SRGB8:
  6781. case SG_PIXELFORMAT_ETC2_RGB8A1:
  6782. case SG_PIXELFORMAT_ETC2_RGBA8:
  6783. case SG_PIXELFORMAT_ETC2_SRGB8A8:
  6784. case SG_PIXELFORMAT_EAC_R11:
  6785. case SG_PIXELFORMAT_EAC_R11SN:
  6786. case SG_PIXELFORMAT_EAC_RG11:
  6787. case SG_PIXELFORMAT_EAC_RG11SN:
  6788. case SG_PIXELFORMAT_BC2_RGBA:
  6789. case SG_PIXELFORMAT_BC3_RGBA:
  6790. case SG_PIXELFORMAT_BC3_SRGBA:
  6791. case SG_PIXELFORMAT_BC5_RG:
  6792. case SG_PIXELFORMAT_BC5_RGSN:
  6793. case SG_PIXELFORMAT_BC6H_RGBF:
  6794. case SG_PIXELFORMAT_BC6H_RGBUF:
  6795. case SG_PIXELFORMAT_BC7_RGBA:
  6796. case SG_PIXELFORMAT_BC7_SRGBA:
  6797. case SG_PIXELFORMAT_ASTC_4x4_RGBA:
  6798. case SG_PIXELFORMAT_ASTC_4x4_SRGBA:
  6799. num_rows = ((height + 3) / 4);
  6800. break;
  6801. default:
  6802. num_rows = height;
  6803. break;
  6804. }
  6805. if (num_rows < 1) {
  6806. num_rows = 1;
  6807. }
  6808. return num_rows;
  6809. }
  6810. // return size of a mipmap level
  6811. _SOKOL_PRIVATE int _sg_miplevel_dim(int base_dim, int mip_level) {
  6812. return _sg_max(base_dim >> mip_level, 1);
  6813. }
  6814. /* return pitch of a 2D subimage / texture slice
  6815. see ComputePitch in https://github.com/microsoft/DirectXTex/blob/master/DirectXTex/DirectXTexUtil.cpp
  6816. */
  6817. _SOKOL_PRIVATE int _sg_surface_pitch(sg_pixel_format fmt, int width, int height, int row_align) {
  6818. int num_rows = _sg_num_rows(fmt, height);
  6819. return num_rows * _sg_row_pitch(fmt, width, row_align);
  6820. }
  6821. // capability table pixel format helper functions
  6822. _SOKOL_PRIVATE void _sg_pixelformat_all(_sg_pixelformat_info_t* pfi) {
  6823. pfi->sample = true;
  6824. pfi->filter = true;
  6825. pfi->blend = true;
  6826. pfi->render = true;
  6827. pfi->msaa = true;
  6828. }
  6829. _SOKOL_PRIVATE void _sg_pixelformat_s(_sg_pixelformat_info_t* pfi) {
  6830. pfi->sample = true;
  6831. }
  6832. _SOKOL_PRIVATE void _sg_pixelformat_sf(_sg_pixelformat_info_t* pfi) {
  6833. pfi->sample = true;
  6834. pfi->filter = true;
  6835. }
  6836. _SOKOL_PRIVATE void _sg_pixelformat_sr(_sg_pixelformat_info_t* pfi) {
  6837. pfi->sample = true;
  6838. pfi->render = true;
  6839. }
  6840. _SOKOL_PRIVATE void _sg_pixelformat_sfr(_sg_pixelformat_info_t* pfi) {
  6841. pfi->sample = true;
  6842. pfi->filter = true;
  6843. pfi->render = true;
  6844. }
  6845. _SOKOL_PRIVATE void _sg_pixelformat_srmd(_sg_pixelformat_info_t* pfi) {
  6846. pfi->sample = true;
  6847. pfi->render = true;
  6848. pfi->msaa = true;
  6849. pfi->depth = true;
  6850. }
  6851. _SOKOL_PRIVATE void _sg_pixelformat_srm(_sg_pixelformat_info_t* pfi) {
  6852. pfi->sample = true;
  6853. pfi->render = true;
  6854. pfi->msaa = true;
  6855. }
  6856. _SOKOL_PRIVATE void _sg_pixelformat_sfrm(_sg_pixelformat_info_t* pfi) {
  6857. pfi->sample = true;
  6858. pfi->filter = true;
  6859. pfi->render = true;
  6860. pfi->msaa = true;
  6861. }
  6862. _SOKOL_PRIVATE void _sg_pixelformat_sbrm(_sg_pixelformat_info_t* pfi) {
  6863. pfi->sample = true;
  6864. pfi->blend = true;
  6865. pfi->render = true;
  6866. pfi->msaa = true;
  6867. }
  6868. _SOKOL_PRIVATE void _sg_pixelformat_sbr(_sg_pixelformat_info_t* pfi) {
  6869. pfi->sample = true;
  6870. pfi->blend = true;
  6871. pfi->render = true;
  6872. }
  6873. _SOKOL_PRIVATE void _sg_pixelformat_sfbr(_sg_pixelformat_info_t* pfi) {
  6874. pfi->sample = true;
  6875. pfi->filter = true;
  6876. pfi->blend = true;
  6877. pfi->render = true;
  6878. }
  6879. _SOKOL_PRIVATE void _sg_pixelformat_compute_all(_sg_pixelformat_info_t* pfi) {
  6880. pfi->read = true;
  6881. pfi->write = true;
  6882. }
  6883. _SOKOL_PRIVATE void _sg_pixelformat_compute_writeonly(_sg_pixelformat_info_t* pfi) {
  6884. pfi->read = false;
  6885. pfi->write = true;
  6886. }
  6887. _SOKOL_PRIVATE sg_pass_action _sg_pass_action_defaults(const sg_pass_action* action) {
  6888. SOKOL_ASSERT(action);
  6889. sg_pass_action res = *action;
  6890. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  6891. if (res.colors[i].load_action == _SG_LOADACTION_DEFAULT) {
  6892. res.colors[i].load_action = SG_LOADACTION_CLEAR;
  6893. res.colors[i].clear_value.r = SG_DEFAULT_CLEAR_RED;
  6894. res.colors[i].clear_value.g = SG_DEFAULT_CLEAR_GREEN;
  6895. res.colors[i].clear_value.b = SG_DEFAULT_CLEAR_BLUE;
  6896. res.colors[i].clear_value.a = SG_DEFAULT_CLEAR_ALPHA;
  6897. }
  6898. if (res.colors[i].store_action == _SG_STOREACTION_DEFAULT) {
  6899. res.colors[i].store_action = SG_STOREACTION_STORE;
  6900. }
  6901. }
  6902. if (res.depth.load_action == _SG_LOADACTION_DEFAULT) {
  6903. res.depth.load_action = SG_LOADACTION_CLEAR;
  6904. res.depth.clear_value = SG_DEFAULT_CLEAR_DEPTH;
  6905. }
  6906. if (res.depth.store_action == _SG_STOREACTION_DEFAULT) {
  6907. res.depth.store_action = SG_STOREACTION_DONTCARE;
  6908. }
  6909. if (res.stencil.load_action == _SG_LOADACTION_DEFAULT) {
  6910. res.stencil.load_action = SG_LOADACTION_CLEAR;
  6911. res.stencil.clear_value = SG_DEFAULT_CLEAR_STENCIL;
  6912. }
  6913. if (res.stencil.store_action == _SG_STOREACTION_DEFAULT) {
  6914. res.stencil.store_action = SG_STOREACTION_DONTCARE;
  6915. }
  6916. return res;
  6917. }
  6918. // ██████ ██ ██ ███ ███ ███ ███ ██ ██ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  6919. // ██ ██ ██ ██ ████ ████ ████ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  6920. // ██ ██ ██ ██ ██ ████ ██ ██ ████ ██ ████ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  6921. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  6922. // ██████ ██████ ██ ██ ██ ██ ██ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  6923. //
  6924. // >>dummy backend
  6925. #if defined(SOKOL_DUMMY_BACKEND)
  6926. _SOKOL_PRIVATE void _sg_dummy_setup_backend(const sg_desc* desc) {
  6927. SOKOL_ASSERT(desc);
  6928. _SOKOL_UNUSED(desc);
  6929. _sg.backend = SG_BACKEND_DUMMY;
  6930. for (int i = SG_PIXELFORMAT_R8; i < SG_PIXELFORMAT_BC1_RGBA; i++) {
  6931. _sg.formats[i].sample = true;
  6932. _sg.formats[i].filter = true;
  6933. _sg.formats[i].render = true;
  6934. _sg.formats[i].blend = true;
  6935. _sg.formats[i].msaa = true;
  6936. }
  6937. _sg.formats[SG_PIXELFORMAT_DEPTH].depth = true;
  6938. _sg.formats[SG_PIXELFORMAT_DEPTH_STENCIL].depth = true;
  6939. }
  6940. _SOKOL_PRIVATE void _sg_dummy_discard_backend(void) {
  6941. // empty
  6942. }
  6943. _SOKOL_PRIVATE void _sg_dummy_reset_state_cache(void) {
  6944. // empty
  6945. }
  6946. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  6947. SOKOL_ASSERT(buf && desc);
  6948. _SOKOL_UNUSED(buf);
  6949. _SOKOL_UNUSED(desc);
  6950. return SG_RESOURCESTATE_VALID;
  6951. }
  6952. _SOKOL_PRIVATE void _sg_dummy_discard_buffer(_sg_buffer_t* buf) {
  6953. SOKOL_ASSERT(buf);
  6954. _SOKOL_UNUSED(buf);
  6955. }
  6956. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  6957. SOKOL_ASSERT(img && desc);
  6958. _SOKOL_UNUSED(img);
  6959. _SOKOL_UNUSED(desc);
  6960. return SG_RESOURCESTATE_VALID;
  6961. }
  6962. _SOKOL_PRIVATE void _sg_dummy_discard_image(_sg_image_t* img) {
  6963. SOKOL_ASSERT(img);
  6964. _SOKOL_UNUSED(img);
  6965. }
  6966. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  6967. SOKOL_ASSERT(smp && desc);
  6968. _SOKOL_UNUSED(smp);
  6969. _SOKOL_UNUSED(desc);
  6970. return SG_RESOURCESTATE_VALID;
  6971. }
  6972. _SOKOL_PRIVATE void _sg_dummy_discard_sampler(_sg_sampler_t* smp) {
  6973. SOKOL_ASSERT(smp);
  6974. _SOKOL_UNUSED(smp);
  6975. }
  6976. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  6977. SOKOL_ASSERT(shd && desc);
  6978. _SOKOL_UNUSED(shd);
  6979. _SOKOL_UNUSED(desc);
  6980. return SG_RESOURCESTATE_VALID;
  6981. }
  6982. _SOKOL_PRIVATE void _sg_dummy_discard_shader(_sg_shader_t* shd) {
  6983. SOKOL_ASSERT(shd);
  6984. _SOKOL_UNUSED(shd);
  6985. }
  6986. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_pipeline(_sg_pipeline_t* pip, const sg_pipeline_desc* desc) {
  6987. SOKOL_ASSERT(pip && desc);
  6988. _SOKOL_UNUSED(pip);
  6989. _SOKOL_UNUSED(desc);
  6990. return SG_RESOURCESTATE_VALID;
  6991. }
  6992. _SOKOL_PRIVATE void _sg_dummy_discard_pipeline(_sg_pipeline_t* pip) {
  6993. SOKOL_ASSERT(pip);
  6994. _SOKOL_UNUSED(pip);
  6995. }
  6996. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_attachments(_sg_attachments_t* atts, const sg_attachments_desc* desc) {
  6997. SOKOL_ASSERT(atts && desc);
  6998. _SOKOL_UNUSED(atts);
  6999. _SOKOL_UNUSED(desc);
  7000. return SG_RESOURCESTATE_VALID;
  7001. }
  7002. _SOKOL_PRIVATE void _sg_dummy_discard_attachments(_sg_attachments_t* atts) {
  7003. SOKOL_ASSERT(atts);
  7004. _SOKOL_UNUSED(atts);
  7005. }
  7006. _SOKOL_PRIVATE void _sg_dummy_begin_pass(const sg_pass* pass) {
  7007. SOKOL_ASSERT(pass);
  7008. _SOKOL_UNUSED(pass);
  7009. }
  7010. _SOKOL_PRIVATE void _sg_dummy_end_pass(void) {
  7011. // empty
  7012. }
  7013. _SOKOL_PRIVATE void _sg_dummy_commit(void) {
  7014. // empty
  7015. }
  7016. _SOKOL_PRIVATE void _sg_dummy_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  7017. _SOKOL_UNUSED(x);
  7018. _SOKOL_UNUSED(y);
  7019. _SOKOL_UNUSED(w);
  7020. _SOKOL_UNUSED(h);
  7021. _SOKOL_UNUSED(origin_top_left);
  7022. }
  7023. _SOKOL_PRIVATE void _sg_dummy_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  7024. _SOKOL_UNUSED(x);
  7025. _SOKOL_UNUSED(y);
  7026. _SOKOL_UNUSED(w);
  7027. _SOKOL_UNUSED(h);
  7028. _SOKOL_UNUSED(origin_top_left);
  7029. }
  7030. _SOKOL_PRIVATE void _sg_dummy_apply_pipeline(_sg_pipeline_t* pip) {
  7031. SOKOL_ASSERT(pip);
  7032. _SOKOL_UNUSED(pip);
  7033. }
  7034. _SOKOL_PRIVATE bool _sg_dummy_apply_bindings(_sg_bindings_ptrs_t* bnd) {
  7035. SOKOL_ASSERT(bnd);
  7036. SOKOL_ASSERT(bnd->pip);
  7037. _SOKOL_UNUSED(bnd);
  7038. return true;
  7039. }
  7040. _SOKOL_PRIVATE void _sg_dummy_apply_uniforms(int ub_slot, const sg_range* data) {
  7041. _SOKOL_UNUSED(ub_slot);
  7042. _SOKOL_UNUSED(data);
  7043. }
  7044. _SOKOL_PRIVATE void _sg_dummy_draw(int base_element, int num_elements, int num_instances) {
  7045. _SOKOL_UNUSED(base_element);
  7046. _SOKOL_UNUSED(num_elements);
  7047. _SOKOL_UNUSED(num_instances);
  7048. }
  7049. _SOKOL_PRIVATE void _sg_dummy_dispatch(int num_groups_x, int num_groups_y, int num_groups_z) {
  7050. _SOKOL_UNUSED(num_groups_x);
  7051. _SOKOL_UNUSED(num_groups_y);
  7052. _SOKOL_UNUSED(num_groups_z);
  7053. }
  7054. _SOKOL_PRIVATE void _sg_dummy_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  7055. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  7056. _SOKOL_UNUSED(data);
  7057. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  7058. buf->cmn.active_slot = 0;
  7059. }
  7060. }
  7061. _SOKOL_PRIVATE bool _sg_dummy_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  7062. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  7063. _SOKOL_UNUSED(data);
  7064. if (new_frame) {
  7065. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  7066. buf->cmn.active_slot = 0;
  7067. }
  7068. }
  7069. return true;
  7070. }
  7071. _SOKOL_PRIVATE void _sg_dummy_update_image(_sg_image_t* img, const sg_image_data* data) {
  7072. SOKOL_ASSERT(img && data);
  7073. _SOKOL_UNUSED(data);
  7074. if (++img->cmn.active_slot >= img->cmn.num_slots) {
  7075. img->cmn.active_slot = 0;
  7076. }
  7077. }
  7078. // ██████ ██████ ███████ ███ ██ ██████ ██ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  7079. // ██ ██ ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  7080. // ██ ██ ██████ █████ ██ ██ ██ ██ ███ ██ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  7081. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  7082. // ██████ ██ ███████ ██ ████ ██████ ███████ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  7083. //
  7084. // >>opengl backend
  7085. #elif defined(_SOKOL_ANY_GL)
  7086. // optional GL loader for win32
  7087. #if defined(_SOKOL_USE_WIN32_GL_LOADER)
  7088. #ifndef SG_GL_FUNCS_EXT
  7089. #define SG_GL_FUNCS_EXT
  7090. #endif
  7091. // X Macro list of GL function names and signatures
  7092. #define _SG_GL_FUNCS \
  7093. SG_GL_FUNCS_EXT \
  7094. _SG_XMACRO(glBindVertexArray, void, (GLuint array)) \
  7095. _SG_XMACRO(glFramebufferTextureLayer, void, (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer)) \
  7096. _SG_XMACRO(glGenFramebuffers, void, (GLsizei n, GLuint * framebuffers)) \
  7097. _SG_XMACRO(glBindFramebuffer, void, (GLenum target, GLuint framebuffer)) \
  7098. _SG_XMACRO(glBindRenderbuffer, void, (GLenum target, GLuint renderbuffer)) \
  7099. _SG_XMACRO(glGetStringi, const GLubyte *, (GLenum name, GLuint index)) \
  7100. _SG_XMACRO(glClearBufferfi, void, (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil)) \
  7101. _SG_XMACRO(glClearBufferfv, void, (GLenum buffer, GLint drawbuffer, const GLfloat * value)) \
  7102. _SG_XMACRO(glClearBufferuiv, void, (GLenum buffer, GLint drawbuffer, const GLuint * value)) \
  7103. _SG_XMACRO(glClearBufferiv, void, (GLenum buffer, GLint drawbuffer, const GLint * value)) \
  7104. _SG_XMACRO(glDeleteRenderbuffers, void, (GLsizei n, const GLuint * renderbuffers)) \
  7105. _SG_XMACRO(glUniform1fv, void, (GLint location, GLsizei count, const GLfloat * value)) \
  7106. _SG_XMACRO(glUniform2fv, void, (GLint location, GLsizei count, const GLfloat * value)) \
  7107. _SG_XMACRO(glUniform3fv, void, (GLint location, GLsizei count, const GLfloat * value)) \
  7108. _SG_XMACRO(glUniform4fv, void, (GLint location, GLsizei count, const GLfloat * value)) \
  7109. _SG_XMACRO(glUniform1iv, void, (GLint location, GLsizei count, const GLint * value)) \
  7110. _SG_XMACRO(glUniform2iv, void, (GLint location, GLsizei count, const GLint * value)) \
  7111. _SG_XMACRO(glUniform3iv, void, (GLint location, GLsizei count, const GLint * value)) \
  7112. _SG_XMACRO(glUniform4iv, void, (GLint location, GLsizei count, const GLint * value)) \
  7113. _SG_XMACRO(glUniformMatrix4fv, void, (GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)) \
  7114. _SG_XMACRO(glUseProgram, void, (GLuint program)) \
  7115. _SG_XMACRO(glShaderSource, void, (GLuint shader, GLsizei count, const GLchar *const* string, const GLint * length)) \
  7116. _SG_XMACRO(glLinkProgram, void, (GLuint program)) \
  7117. _SG_XMACRO(glGetUniformLocation, GLint, (GLuint program, const GLchar * name)) \
  7118. _SG_XMACRO(glGetShaderiv, void, (GLuint shader, GLenum pname, GLint * params)) \
  7119. _SG_XMACRO(glGetProgramInfoLog, void, (GLuint program, GLsizei bufSize, GLsizei * length, GLchar * infoLog)) \
  7120. _SG_XMACRO(glGetAttribLocation, GLint, (GLuint program, const GLchar * name)) \
  7121. _SG_XMACRO(glDisableVertexAttribArray, void, (GLuint index)) \
  7122. _SG_XMACRO(glDeleteShader, void, (GLuint shader)) \
  7123. _SG_XMACRO(glDeleteProgram, void, (GLuint program)) \
  7124. _SG_XMACRO(glCompileShader, void, (GLuint shader)) \
  7125. _SG_XMACRO(glStencilFuncSeparate, void, (GLenum face, GLenum func, GLint ref, GLuint mask)) \
  7126. _SG_XMACRO(glStencilOpSeparate, void, (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass)) \
  7127. _SG_XMACRO(glRenderbufferStorageMultisample, void, (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height)) \
  7128. _SG_XMACRO(glDrawBuffers, void, (GLsizei n, const GLenum * bufs)) \
  7129. _SG_XMACRO(glVertexAttribDivisor, void, (GLuint index, GLuint divisor)) \
  7130. _SG_XMACRO(glBufferSubData, void, (GLenum target, GLintptr offset, GLsizeiptr size, const void * data)) \
  7131. _SG_XMACRO(glGenBuffers, void, (GLsizei n, GLuint * buffers)) \
  7132. _SG_XMACRO(glCheckFramebufferStatus, GLenum, (GLenum target)) \
  7133. _SG_XMACRO(glFramebufferRenderbuffer, void, (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)) \
  7134. _SG_XMACRO(glCompressedTexImage2D, void, (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void * data)) \
  7135. _SG_XMACRO(glCompressedTexImage3D, void, (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void * data)) \
  7136. _SG_XMACRO(glActiveTexture, void, (GLenum texture)) \
  7137. _SG_XMACRO(glTexSubImage3D, void, (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void * pixels)) \
  7138. _SG_XMACRO(glRenderbufferStorage, void, (GLenum target, GLenum internalformat, GLsizei width, GLsizei height)) \
  7139. _SG_XMACRO(glGenTextures, void, (GLsizei n, GLuint * textures)) \
  7140. _SG_XMACRO(glPolygonOffset, void, (GLfloat factor, GLfloat units)) \
  7141. _SG_XMACRO(glDrawElements, void, (GLenum mode, GLsizei count, GLenum type, const void * indices)) \
  7142. _SG_XMACRO(glDeleteFramebuffers, void, (GLsizei n, const GLuint * framebuffers)) \
  7143. _SG_XMACRO(glBlendEquationSeparate, void, (GLenum modeRGB, GLenum modeAlpha)) \
  7144. _SG_XMACRO(glDeleteTextures, void, (GLsizei n, const GLuint * textures)) \
  7145. _SG_XMACRO(glGetProgramiv, void, (GLuint program, GLenum pname, GLint * params)) \
  7146. _SG_XMACRO(glBindTexture, void, (GLenum target, GLuint texture)) \
  7147. _SG_XMACRO(glTexImage3D, void, (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void * pixels)) \
  7148. _SG_XMACRO(glCreateShader, GLuint, (GLenum type)) \
  7149. _SG_XMACRO(glTexSubImage2D, void, (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void * pixels)) \
  7150. _SG_XMACRO(glFramebufferTexture2D, void, (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)) \
  7151. _SG_XMACRO(glCreateProgram, GLuint, (void)) \
  7152. _SG_XMACRO(glViewport, void, (GLint x, GLint y, GLsizei width, GLsizei height)) \
  7153. _SG_XMACRO(glDeleteBuffers, void, (GLsizei n, const GLuint * buffers)) \
  7154. _SG_XMACRO(glDrawArrays, void, (GLenum mode, GLint first, GLsizei count)) \
  7155. _SG_XMACRO(glDrawElementsInstanced, void, (GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount)) \
  7156. _SG_XMACRO(glVertexAttribPointer, void, (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void * pointer)) \
  7157. _SG_XMACRO(glVertexAttribIPointer, void, (GLuint index, GLint size, GLenum type, GLsizei stride, const void * pointer)) \
  7158. _SG_XMACRO(glUniform1i, void, (GLint location, GLint v0)) \
  7159. _SG_XMACRO(glDisable, void, (GLenum cap)) \
  7160. _SG_XMACRO(glColorMask, void, (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)) \
  7161. _SG_XMACRO(glColorMaski, void, (GLuint buf, GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)) \
  7162. _SG_XMACRO(glBindBuffer, void, (GLenum target, GLuint buffer)) \
  7163. _SG_XMACRO(glDeleteVertexArrays, void, (GLsizei n, const GLuint * arrays)) \
  7164. _SG_XMACRO(glDepthMask, void, (GLboolean flag)) \
  7165. _SG_XMACRO(glDrawArraysInstanced, void, (GLenum mode, GLint first, GLsizei count, GLsizei instancecount)) \
  7166. _SG_XMACRO(glScissor, void, (GLint x, GLint y, GLsizei width, GLsizei height)) \
  7167. _SG_XMACRO(glGenRenderbuffers, void, (GLsizei n, GLuint * renderbuffers)) \
  7168. _SG_XMACRO(glBufferData, void, (GLenum target, GLsizeiptr size, const void * data, GLenum usage)) \
  7169. _SG_XMACRO(glBlendFuncSeparate, void, (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha)) \
  7170. _SG_XMACRO(glTexParameteri, void, (GLenum target, GLenum pname, GLint param)) \
  7171. _SG_XMACRO(glGetIntegerv, void, (GLenum pname, GLint * data)) \
  7172. _SG_XMACRO(glEnable, void, (GLenum cap)) \
  7173. _SG_XMACRO(glBlitFramebuffer, void, (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter)) \
  7174. _SG_XMACRO(glStencilMask, void, (GLuint mask)) \
  7175. _SG_XMACRO(glAttachShader, void, (GLuint program, GLuint shader)) \
  7176. _SG_XMACRO(glGetError, GLenum, (void)) \
  7177. _SG_XMACRO(glBlendColor, void, (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)) \
  7178. _SG_XMACRO(glTexParameterf, void, (GLenum target, GLenum pname, GLfloat param)) \
  7179. _SG_XMACRO(glTexParameterfv, void, (GLenum target, GLenum pname, const GLfloat* params)) \
  7180. _SG_XMACRO(glGetShaderInfoLog, void, (GLuint shader, GLsizei bufSize, GLsizei * length, GLchar * infoLog)) \
  7181. _SG_XMACRO(glDepthFunc, void, (GLenum func)) \
  7182. _SG_XMACRO(glStencilOp , void, (GLenum fail, GLenum zfail, GLenum zpass)) \
  7183. _SG_XMACRO(glStencilFunc, void, (GLenum func, GLint ref, GLuint mask)) \
  7184. _SG_XMACRO(glEnableVertexAttribArray, void, (GLuint index)) \
  7185. _SG_XMACRO(glBlendFunc, void, (GLenum sfactor, GLenum dfactor)) \
  7186. _SG_XMACRO(glReadBuffer, void, (GLenum src)) \
  7187. _SG_XMACRO(glTexImage2D, void, (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void * pixels)) \
  7188. _SG_XMACRO(glGenVertexArrays, void, (GLsizei n, GLuint * arrays)) \
  7189. _SG_XMACRO(glFrontFace, void, (GLenum mode)) \
  7190. _SG_XMACRO(glCullFace, void, (GLenum mode)) \
  7191. _SG_XMACRO(glPixelStorei, void, (GLenum pname, GLint param)) \
  7192. _SG_XMACRO(glBindSampler, void, (GLuint unit, GLuint sampler)) \
  7193. _SG_XMACRO(glGenSamplers, void, (GLsizei n, GLuint* samplers)) \
  7194. _SG_XMACRO(glSamplerParameteri, void, (GLuint sampler, GLenum pname, GLint param)) \
  7195. _SG_XMACRO(glSamplerParameterf, void, (GLuint sampler, GLenum pname, GLfloat param)) \
  7196. _SG_XMACRO(glSamplerParameterfv, void, (GLuint sampler, GLenum pname, const GLfloat* params)) \
  7197. _SG_XMACRO(glDeleteSamplers, void, (GLsizei n, const GLuint* samplers)) \
  7198. _SG_XMACRO(glBindBufferBase, void, (GLenum target, GLuint index, GLuint buffer)) \
  7199. _SG_XMACRO(glTexImage2DMultisample, void, (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations)) \
  7200. _SG_XMACRO(glTexImage3DMultisample, void, (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations)) \
  7201. _SG_XMACRO(glDispatchCompute, void, (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z)) \
  7202. _SG_XMACRO(glMemoryBarrier, void, (GLbitfield barriers)) \
  7203. _SG_XMACRO(glBindImageTexture, void, (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format)) \
  7204. _SG_XMACRO(glTexStorage2DMultisample, void, (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations)) \
  7205. _SG_XMACRO(glTexStorage2D, void, (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height)) \
  7206. _SG_XMACRO(glTexStorage3DMultisample, void, (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations)) \
  7207. _SG_XMACRO(glTexStorage3D, void, (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth)) \
  7208. _SG_XMACRO(glCompressedTexSubImage2D, void, (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data)) \
  7209. _SG_XMACRO(glCompressedTexSubImage3D, void, (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data))
  7210. // generate GL function pointer typedefs
  7211. #define _SG_XMACRO(name, ret, args) typedef ret (GL_APIENTRY* PFN_ ## name) args;
  7212. _SG_GL_FUNCS
  7213. #undef _SG_XMACRO
  7214. // generate GL function pointers
  7215. #define _SG_XMACRO(name, ret, args) static PFN_ ## name name;
  7216. _SG_GL_FUNCS
  7217. #undef _SG_XMACRO
  7218. // helper function to lookup GL functions in GL DLL
  7219. typedef PROC (WINAPI * _sg_wglGetProcAddress)(LPCSTR);
  7220. _SOKOL_PRIVATE void* _sg_gl_getprocaddr(const char* name, _sg_wglGetProcAddress wgl_getprocaddress) {
  7221. void* proc_addr = (void*) wgl_getprocaddress(name);
  7222. if (0 == proc_addr) {
  7223. proc_addr = (void*) GetProcAddress(_sg.gl.opengl32_dll, name);
  7224. }
  7225. SOKOL_ASSERT(proc_addr);
  7226. return proc_addr;
  7227. }
  7228. // populate GL function pointers
  7229. _SOKOL_PRIVATE void _sg_gl_load_opengl(void) {
  7230. SOKOL_ASSERT(0 == _sg.gl.opengl32_dll);
  7231. _sg.gl.opengl32_dll = LoadLibraryA("opengl32.dll");
  7232. SOKOL_ASSERT(_sg.gl.opengl32_dll);
  7233. _sg_wglGetProcAddress wgl_getprocaddress = (_sg_wglGetProcAddress) GetProcAddress(_sg.gl.opengl32_dll, "wglGetProcAddress");
  7234. SOKOL_ASSERT(wgl_getprocaddress);
  7235. #define _SG_XMACRO(name, ret, args) name = (PFN_ ## name) _sg_gl_getprocaddr(#name, wgl_getprocaddress);
  7236. _SG_GL_FUNCS
  7237. #undef _SG_XMACRO
  7238. }
  7239. _SOKOL_PRIVATE void _sg_gl_unload_opengl(void) {
  7240. SOKOL_ASSERT(_sg.gl.opengl32_dll);
  7241. FreeLibrary(_sg.gl.opengl32_dll);
  7242. _sg.gl.opengl32_dll = 0;
  7243. }
  7244. #endif // _SOKOL_USE_WIN32_GL_LOADER
  7245. //-- type translation ----------------------------------------------------------
  7246. _SOKOL_PRIVATE GLenum _sg_gl_buffer_target(const sg_buffer_usage* usg) {
  7247. // NOTE: the buffer target returned here is only used for the bind point
  7248. // to copy data into the buffer, expect for WebGL2, the bind point doesn't
  7249. // need to match the later usage of the buffer (but because of the WebGL2
  7250. // restriction we cannot simply select a random bind point, because in WebGL2
  7251. // a buffer cannot 'switch' bind points later.
  7252. if (usg->vertex_buffer) {
  7253. return GL_ARRAY_BUFFER;
  7254. } else if (usg->index_buffer) {
  7255. return GL_ELEMENT_ARRAY_BUFFER;
  7256. } else if (usg->storage_buffer) {
  7257. return GL_SHADER_STORAGE_BUFFER;
  7258. } else {
  7259. SOKOL_UNREACHABLE; return 0;
  7260. }
  7261. }
  7262. _SOKOL_PRIVATE GLenum _sg_gl_texture_target(sg_image_type t, int sample_count) {
  7263. #if defined(SOKOL_GLCORE)
  7264. const bool msaa = sample_count > 1;
  7265. if (msaa) {
  7266. switch (t) {
  7267. case SG_IMAGETYPE_2D: return GL_TEXTURE_2D_MULTISAMPLE;
  7268. case SG_IMAGETYPE_ARRAY: return GL_TEXTURE_2D_MULTISAMPLE_ARRAY;
  7269. default: SOKOL_UNREACHABLE; return 0;
  7270. }
  7271. } else {
  7272. switch (t) {
  7273. case SG_IMAGETYPE_2D: return GL_TEXTURE_2D;
  7274. case SG_IMAGETYPE_CUBE: return GL_TEXTURE_CUBE_MAP;
  7275. case SG_IMAGETYPE_3D: return GL_TEXTURE_3D;
  7276. case SG_IMAGETYPE_ARRAY: return GL_TEXTURE_2D_ARRAY;
  7277. default: SOKOL_UNREACHABLE; return 0;
  7278. }
  7279. }
  7280. #else
  7281. SOKOL_ASSERT(sample_count == 1); _SOKOL_UNUSED(sample_count);
  7282. switch (t) {
  7283. case SG_IMAGETYPE_2D: return GL_TEXTURE_2D;
  7284. case SG_IMAGETYPE_CUBE: return GL_TEXTURE_CUBE_MAP;
  7285. case SG_IMAGETYPE_3D: return GL_TEXTURE_3D;
  7286. case SG_IMAGETYPE_ARRAY: return GL_TEXTURE_2D_ARRAY;
  7287. default: SOKOL_UNREACHABLE; return 0;
  7288. }
  7289. #endif
  7290. }
  7291. _SOKOL_PRIVATE GLenum _sg_gl_buffer_usage(const sg_buffer_usage* usg) {
  7292. if (usg->immutable) {
  7293. return GL_STATIC_DRAW;
  7294. } else if (usg->dynamic_update) {
  7295. return GL_DYNAMIC_DRAW;
  7296. } else if (usg->stream_update) {
  7297. return GL_STREAM_DRAW;
  7298. } else {
  7299. SOKOL_UNREACHABLE; return 0;
  7300. }
  7301. }
  7302. _SOKOL_PRIVATE GLenum _sg_gl_shader_stage(sg_shader_stage stage) {
  7303. switch (stage) {
  7304. case SG_SHADERSTAGE_VERTEX: return GL_VERTEX_SHADER;
  7305. case SG_SHADERSTAGE_FRAGMENT: return GL_FRAGMENT_SHADER;
  7306. case SG_SHADERSTAGE_COMPUTE: return GL_COMPUTE_SHADER;
  7307. default: SOKOL_UNREACHABLE; return 0;
  7308. }
  7309. }
  7310. _SOKOL_PRIVATE GLint _sg_gl_vertexformat_size(sg_vertex_format fmt) {
  7311. switch (fmt) {
  7312. case SG_VERTEXFORMAT_FLOAT: return 1;
  7313. case SG_VERTEXFORMAT_FLOAT2: return 2;
  7314. case SG_VERTEXFORMAT_FLOAT3: return 3;
  7315. case SG_VERTEXFORMAT_FLOAT4: return 4;
  7316. case SG_VERTEXFORMAT_INT: return 1;
  7317. case SG_VERTEXFORMAT_INT2: return 2;
  7318. case SG_VERTEXFORMAT_INT3: return 3;
  7319. case SG_VERTEXFORMAT_INT4: return 4;
  7320. case SG_VERTEXFORMAT_UINT: return 1;
  7321. case SG_VERTEXFORMAT_UINT2: return 2;
  7322. case SG_VERTEXFORMAT_UINT3: return 3;
  7323. case SG_VERTEXFORMAT_UINT4: return 4;
  7324. case SG_VERTEXFORMAT_BYTE4: return 4;
  7325. case SG_VERTEXFORMAT_BYTE4N: return 4;
  7326. case SG_VERTEXFORMAT_UBYTE4: return 4;
  7327. case SG_VERTEXFORMAT_UBYTE4N: return 4;
  7328. case SG_VERTEXFORMAT_SHORT2: return 2;
  7329. case SG_VERTEXFORMAT_SHORT2N: return 2;
  7330. case SG_VERTEXFORMAT_USHORT2: return 2;
  7331. case SG_VERTEXFORMAT_USHORT2N: return 2;
  7332. case SG_VERTEXFORMAT_SHORT4: return 4;
  7333. case SG_VERTEXFORMAT_SHORT4N: return 4;
  7334. case SG_VERTEXFORMAT_USHORT4: return 4;
  7335. case SG_VERTEXFORMAT_USHORT4N: return 4;
  7336. case SG_VERTEXFORMAT_UINT10_N2: return 4;
  7337. case SG_VERTEXFORMAT_HALF2: return 2;
  7338. case SG_VERTEXFORMAT_HALF4: return 4;
  7339. default: SOKOL_UNREACHABLE; return 0;
  7340. }
  7341. }
  7342. _SOKOL_PRIVATE GLenum _sg_gl_vertexformat_type(sg_vertex_format fmt) {
  7343. switch (fmt) {
  7344. case SG_VERTEXFORMAT_FLOAT:
  7345. case SG_VERTEXFORMAT_FLOAT2:
  7346. case SG_VERTEXFORMAT_FLOAT3:
  7347. case SG_VERTEXFORMAT_FLOAT4:
  7348. return GL_FLOAT;
  7349. case SG_VERTEXFORMAT_INT:
  7350. case SG_VERTEXFORMAT_INT2:
  7351. case SG_VERTEXFORMAT_INT3:
  7352. case SG_VERTEXFORMAT_INT4:
  7353. return GL_INT;
  7354. case SG_VERTEXFORMAT_UINT:
  7355. case SG_VERTEXFORMAT_UINT2:
  7356. case SG_VERTEXFORMAT_UINT3:
  7357. case SG_VERTEXFORMAT_UINT4:
  7358. return GL_UNSIGNED_INT;
  7359. case SG_VERTEXFORMAT_BYTE4:
  7360. case SG_VERTEXFORMAT_BYTE4N:
  7361. return GL_BYTE;
  7362. case SG_VERTEXFORMAT_UBYTE4:
  7363. case SG_VERTEXFORMAT_UBYTE4N:
  7364. return GL_UNSIGNED_BYTE;
  7365. case SG_VERTEXFORMAT_SHORT2:
  7366. case SG_VERTEXFORMAT_SHORT2N:
  7367. case SG_VERTEXFORMAT_SHORT4:
  7368. case SG_VERTEXFORMAT_SHORT4N:
  7369. return GL_SHORT;
  7370. case SG_VERTEXFORMAT_USHORT2:
  7371. case SG_VERTEXFORMAT_USHORT2N:
  7372. case SG_VERTEXFORMAT_USHORT4:
  7373. case SG_VERTEXFORMAT_USHORT4N:
  7374. return GL_UNSIGNED_SHORT;
  7375. case SG_VERTEXFORMAT_UINT10_N2:
  7376. return GL_UNSIGNED_INT_2_10_10_10_REV;
  7377. case SG_VERTEXFORMAT_HALF2:
  7378. case SG_VERTEXFORMAT_HALF4:
  7379. return GL_HALF_FLOAT;
  7380. default:
  7381. SOKOL_UNREACHABLE; return 0;
  7382. }
  7383. }
  7384. _SOKOL_PRIVATE GLboolean _sg_gl_vertexformat_normalized(sg_vertex_format fmt) {
  7385. switch (fmt) {
  7386. case SG_VERTEXFORMAT_BYTE4N:
  7387. case SG_VERTEXFORMAT_UBYTE4N:
  7388. case SG_VERTEXFORMAT_SHORT2N:
  7389. case SG_VERTEXFORMAT_USHORT2N:
  7390. case SG_VERTEXFORMAT_SHORT4N:
  7391. case SG_VERTEXFORMAT_USHORT4N:
  7392. case SG_VERTEXFORMAT_UINT10_N2:
  7393. return GL_TRUE;
  7394. default:
  7395. return GL_FALSE;
  7396. }
  7397. }
  7398. _SOKOL_PRIVATE GLenum _sg_gl_primitive_type(sg_primitive_type t) {
  7399. switch (t) {
  7400. case SG_PRIMITIVETYPE_POINTS: return GL_POINTS;
  7401. case SG_PRIMITIVETYPE_LINES: return GL_LINES;
  7402. case SG_PRIMITIVETYPE_LINE_STRIP: return GL_LINE_STRIP;
  7403. case SG_PRIMITIVETYPE_TRIANGLES: return GL_TRIANGLES;
  7404. case SG_PRIMITIVETYPE_TRIANGLE_STRIP: return GL_TRIANGLE_STRIP;
  7405. default: SOKOL_UNREACHABLE; return 0;
  7406. }
  7407. }
  7408. _SOKOL_PRIVATE GLenum _sg_gl_index_type(sg_index_type t) {
  7409. switch (t) {
  7410. case SG_INDEXTYPE_NONE: return 0;
  7411. case SG_INDEXTYPE_UINT16: return GL_UNSIGNED_SHORT;
  7412. case SG_INDEXTYPE_UINT32: return GL_UNSIGNED_INT;
  7413. default: SOKOL_UNREACHABLE; return 0;
  7414. }
  7415. }
  7416. _SOKOL_PRIVATE GLenum _sg_gl_compare_func(sg_compare_func cmp) {
  7417. switch (cmp) {
  7418. case SG_COMPAREFUNC_NEVER: return GL_NEVER;
  7419. case SG_COMPAREFUNC_LESS: return GL_LESS;
  7420. case SG_COMPAREFUNC_EQUAL: return GL_EQUAL;
  7421. case SG_COMPAREFUNC_LESS_EQUAL: return GL_LEQUAL;
  7422. case SG_COMPAREFUNC_GREATER: return GL_GREATER;
  7423. case SG_COMPAREFUNC_NOT_EQUAL: return GL_NOTEQUAL;
  7424. case SG_COMPAREFUNC_GREATER_EQUAL: return GL_GEQUAL;
  7425. case SG_COMPAREFUNC_ALWAYS: return GL_ALWAYS;
  7426. default: SOKOL_UNREACHABLE; return 0;
  7427. }
  7428. }
  7429. _SOKOL_PRIVATE GLenum _sg_gl_stencil_op(sg_stencil_op op) {
  7430. switch (op) {
  7431. case SG_STENCILOP_KEEP: return GL_KEEP;
  7432. case SG_STENCILOP_ZERO: return GL_ZERO;
  7433. case SG_STENCILOP_REPLACE: return GL_REPLACE;
  7434. case SG_STENCILOP_INCR_CLAMP: return GL_INCR;
  7435. case SG_STENCILOP_DECR_CLAMP: return GL_DECR;
  7436. case SG_STENCILOP_INVERT: return GL_INVERT;
  7437. case SG_STENCILOP_INCR_WRAP: return GL_INCR_WRAP;
  7438. case SG_STENCILOP_DECR_WRAP: return GL_DECR_WRAP;
  7439. default: SOKOL_UNREACHABLE; return 0;
  7440. }
  7441. }
  7442. _SOKOL_PRIVATE GLenum _sg_gl_blend_factor(sg_blend_factor f) {
  7443. switch (f) {
  7444. case SG_BLENDFACTOR_ZERO: return GL_ZERO;
  7445. case SG_BLENDFACTOR_ONE: return GL_ONE;
  7446. case SG_BLENDFACTOR_SRC_COLOR: return GL_SRC_COLOR;
  7447. case SG_BLENDFACTOR_ONE_MINUS_SRC_COLOR: return GL_ONE_MINUS_SRC_COLOR;
  7448. case SG_BLENDFACTOR_SRC_ALPHA: return GL_SRC_ALPHA;
  7449. case SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA: return GL_ONE_MINUS_SRC_ALPHA;
  7450. case SG_BLENDFACTOR_DST_COLOR: return GL_DST_COLOR;
  7451. case SG_BLENDFACTOR_ONE_MINUS_DST_COLOR: return GL_ONE_MINUS_DST_COLOR;
  7452. case SG_BLENDFACTOR_DST_ALPHA: return GL_DST_ALPHA;
  7453. case SG_BLENDFACTOR_ONE_MINUS_DST_ALPHA: return GL_ONE_MINUS_DST_ALPHA;
  7454. case SG_BLENDFACTOR_SRC_ALPHA_SATURATED: return GL_SRC_ALPHA_SATURATE;
  7455. case SG_BLENDFACTOR_BLEND_COLOR: return GL_CONSTANT_COLOR;
  7456. case SG_BLENDFACTOR_ONE_MINUS_BLEND_COLOR: return GL_ONE_MINUS_CONSTANT_COLOR;
  7457. case SG_BLENDFACTOR_BLEND_ALPHA: return GL_CONSTANT_ALPHA;
  7458. case SG_BLENDFACTOR_ONE_MINUS_BLEND_ALPHA: return GL_ONE_MINUS_CONSTANT_ALPHA;
  7459. default: SOKOL_UNREACHABLE; return 0;
  7460. }
  7461. }
  7462. _SOKOL_PRIVATE GLenum _sg_gl_blend_op(sg_blend_op op) {
  7463. switch (op) {
  7464. case SG_BLENDOP_ADD: return GL_FUNC_ADD;
  7465. case SG_BLENDOP_SUBTRACT: return GL_FUNC_SUBTRACT;
  7466. case SG_BLENDOP_REVERSE_SUBTRACT: return GL_FUNC_REVERSE_SUBTRACT;
  7467. case SG_BLENDOP_MIN: return GL_MIN;
  7468. case SG_BLENDOP_MAX: return GL_MAX;
  7469. default: SOKOL_UNREACHABLE; return 0;
  7470. }
  7471. }
  7472. _SOKOL_PRIVATE GLenum _sg_gl_min_filter(sg_filter min_f, sg_filter mipmap_f) {
  7473. if (min_f == SG_FILTER_NEAREST) {
  7474. switch (mipmap_f) {
  7475. case SG_FILTER_NEAREST: return GL_NEAREST_MIPMAP_NEAREST;
  7476. case SG_FILTER_LINEAR: return GL_NEAREST_MIPMAP_LINEAR;
  7477. default: SOKOL_UNREACHABLE; return (GLenum)0;
  7478. }
  7479. } else if (min_f == SG_FILTER_LINEAR) {
  7480. switch (mipmap_f) {
  7481. case SG_FILTER_NEAREST: return GL_LINEAR_MIPMAP_NEAREST;
  7482. case SG_FILTER_LINEAR: return GL_LINEAR_MIPMAP_LINEAR;
  7483. default: SOKOL_UNREACHABLE; return (GLenum)0;
  7484. }
  7485. } else {
  7486. SOKOL_UNREACHABLE; return (GLenum)0;
  7487. }
  7488. }
  7489. _SOKOL_PRIVATE GLenum _sg_gl_mag_filter(sg_filter mag_f) {
  7490. if (mag_f == SG_FILTER_NEAREST) {
  7491. return GL_NEAREST;
  7492. } else {
  7493. return GL_LINEAR;
  7494. }
  7495. }
  7496. _SOKOL_PRIVATE GLenum _sg_gl_wrap(sg_wrap w) {
  7497. switch (w) {
  7498. case SG_WRAP_CLAMP_TO_EDGE: return GL_CLAMP_TO_EDGE;
  7499. #if defined(SOKOL_GLCORE)
  7500. case SG_WRAP_CLAMP_TO_BORDER: return GL_CLAMP_TO_BORDER;
  7501. #else
  7502. case SG_WRAP_CLAMP_TO_BORDER: return GL_CLAMP_TO_EDGE;
  7503. #endif
  7504. case SG_WRAP_REPEAT: return GL_REPEAT;
  7505. case SG_WRAP_MIRRORED_REPEAT: return GL_MIRRORED_REPEAT;
  7506. default: SOKOL_UNREACHABLE; return 0;
  7507. }
  7508. }
  7509. _SOKOL_PRIVATE GLenum _sg_gl_teximage_type(sg_pixel_format fmt) {
  7510. switch (fmt) {
  7511. case SG_PIXELFORMAT_R8:
  7512. case SG_PIXELFORMAT_R8UI:
  7513. case SG_PIXELFORMAT_RG8:
  7514. case SG_PIXELFORMAT_RG8UI:
  7515. case SG_PIXELFORMAT_RGBA8:
  7516. case SG_PIXELFORMAT_SRGB8A8:
  7517. case SG_PIXELFORMAT_RGBA8UI:
  7518. case SG_PIXELFORMAT_BGRA8:
  7519. return GL_UNSIGNED_BYTE;
  7520. case SG_PIXELFORMAT_R8SN:
  7521. case SG_PIXELFORMAT_R8SI:
  7522. case SG_PIXELFORMAT_RG8SN:
  7523. case SG_PIXELFORMAT_RG8SI:
  7524. case SG_PIXELFORMAT_RGBA8SN:
  7525. case SG_PIXELFORMAT_RGBA8SI:
  7526. return GL_BYTE;
  7527. case SG_PIXELFORMAT_R16:
  7528. case SG_PIXELFORMAT_R16UI:
  7529. case SG_PIXELFORMAT_RG16:
  7530. case SG_PIXELFORMAT_RG16UI:
  7531. case SG_PIXELFORMAT_RGBA16:
  7532. case SG_PIXELFORMAT_RGBA16UI:
  7533. return GL_UNSIGNED_SHORT;
  7534. case SG_PIXELFORMAT_R16SN:
  7535. case SG_PIXELFORMAT_R16SI:
  7536. case SG_PIXELFORMAT_RG16SN:
  7537. case SG_PIXELFORMAT_RG16SI:
  7538. case SG_PIXELFORMAT_RGBA16SN:
  7539. case SG_PIXELFORMAT_RGBA16SI:
  7540. return GL_SHORT;
  7541. case SG_PIXELFORMAT_R16F:
  7542. case SG_PIXELFORMAT_RG16F:
  7543. case SG_PIXELFORMAT_RGBA16F:
  7544. return GL_HALF_FLOAT;
  7545. case SG_PIXELFORMAT_R32UI:
  7546. case SG_PIXELFORMAT_RG32UI:
  7547. case SG_PIXELFORMAT_RGBA32UI:
  7548. return GL_UNSIGNED_INT;
  7549. case SG_PIXELFORMAT_R32SI:
  7550. case SG_PIXELFORMAT_RG32SI:
  7551. case SG_PIXELFORMAT_RGBA32SI:
  7552. return GL_INT;
  7553. case SG_PIXELFORMAT_R32F:
  7554. case SG_PIXELFORMAT_RG32F:
  7555. case SG_PIXELFORMAT_RGBA32F:
  7556. return GL_FLOAT;
  7557. case SG_PIXELFORMAT_RGB10A2:
  7558. return GL_UNSIGNED_INT_2_10_10_10_REV;
  7559. case SG_PIXELFORMAT_RG11B10F:
  7560. return GL_UNSIGNED_INT_10F_11F_11F_REV;
  7561. case SG_PIXELFORMAT_RGB9E5:
  7562. return GL_UNSIGNED_INT_5_9_9_9_REV;
  7563. case SG_PIXELFORMAT_DEPTH:
  7564. return GL_FLOAT;
  7565. case SG_PIXELFORMAT_DEPTH_STENCIL:
  7566. return GL_UNSIGNED_INT_24_8;
  7567. default:
  7568. SOKOL_UNREACHABLE; return 0;
  7569. }
  7570. }
  7571. _SOKOL_PRIVATE GLenum _sg_gl_teximage_format(sg_pixel_format fmt) {
  7572. switch (fmt) {
  7573. case SG_PIXELFORMAT_R8:
  7574. case SG_PIXELFORMAT_R8SN:
  7575. case SG_PIXELFORMAT_R16:
  7576. case SG_PIXELFORMAT_R16SN:
  7577. case SG_PIXELFORMAT_R16F:
  7578. case SG_PIXELFORMAT_R32F:
  7579. return GL_RED;
  7580. case SG_PIXELFORMAT_R8UI:
  7581. case SG_PIXELFORMAT_R8SI:
  7582. case SG_PIXELFORMAT_R16UI:
  7583. case SG_PIXELFORMAT_R16SI:
  7584. case SG_PIXELFORMAT_R32UI:
  7585. case SG_PIXELFORMAT_R32SI:
  7586. return GL_RED_INTEGER;
  7587. case SG_PIXELFORMAT_RG8:
  7588. case SG_PIXELFORMAT_RG8SN:
  7589. case SG_PIXELFORMAT_RG16:
  7590. case SG_PIXELFORMAT_RG16SN:
  7591. case SG_PIXELFORMAT_RG16F:
  7592. case SG_PIXELFORMAT_RG32F:
  7593. return GL_RG;
  7594. case SG_PIXELFORMAT_RG8UI:
  7595. case SG_PIXELFORMAT_RG8SI:
  7596. case SG_PIXELFORMAT_RG16UI:
  7597. case SG_PIXELFORMAT_RG16SI:
  7598. case SG_PIXELFORMAT_RG32UI:
  7599. case SG_PIXELFORMAT_RG32SI:
  7600. return GL_RG_INTEGER;
  7601. case SG_PIXELFORMAT_RGBA8:
  7602. case SG_PIXELFORMAT_SRGB8A8:
  7603. case SG_PIXELFORMAT_RGBA8SN:
  7604. case SG_PIXELFORMAT_RGBA16:
  7605. case SG_PIXELFORMAT_RGBA16SN:
  7606. case SG_PIXELFORMAT_RGBA16F:
  7607. case SG_PIXELFORMAT_RGBA32F:
  7608. case SG_PIXELFORMAT_RGB10A2:
  7609. return GL_RGBA;
  7610. case SG_PIXELFORMAT_RGBA8UI:
  7611. case SG_PIXELFORMAT_RGBA8SI:
  7612. case SG_PIXELFORMAT_RGBA16UI:
  7613. case SG_PIXELFORMAT_RGBA16SI:
  7614. case SG_PIXELFORMAT_RGBA32UI:
  7615. case SG_PIXELFORMAT_RGBA32SI:
  7616. return GL_RGBA_INTEGER;
  7617. case SG_PIXELFORMAT_RG11B10F:
  7618. case SG_PIXELFORMAT_RGB9E5:
  7619. return GL_RGB;
  7620. case SG_PIXELFORMAT_DEPTH:
  7621. return GL_DEPTH_COMPONENT;
  7622. case SG_PIXELFORMAT_DEPTH_STENCIL:
  7623. return GL_DEPTH_STENCIL;
  7624. case SG_PIXELFORMAT_BC1_RGBA:
  7625. return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
  7626. case SG_PIXELFORMAT_BC2_RGBA:
  7627. return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
  7628. case SG_PIXELFORMAT_BC3_RGBA:
  7629. return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
  7630. case SG_PIXELFORMAT_BC3_SRGBA:
  7631. return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  7632. case SG_PIXELFORMAT_BC4_R:
  7633. return GL_COMPRESSED_RED_RGTC1;
  7634. case SG_PIXELFORMAT_BC4_RSN:
  7635. return GL_COMPRESSED_SIGNED_RED_RGTC1;
  7636. case SG_PIXELFORMAT_BC5_RG:
  7637. return GL_COMPRESSED_RED_GREEN_RGTC2;
  7638. case SG_PIXELFORMAT_BC5_RGSN:
  7639. return GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2;
  7640. case SG_PIXELFORMAT_BC6H_RGBF:
  7641. return GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB;
  7642. case SG_PIXELFORMAT_BC6H_RGBUF:
  7643. return GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB;
  7644. case SG_PIXELFORMAT_BC7_RGBA:
  7645. return GL_COMPRESSED_RGBA_BPTC_UNORM_ARB;
  7646. case SG_PIXELFORMAT_BC7_SRGBA:
  7647. return GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB;
  7648. case SG_PIXELFORMAT_ETC2_RGB8:
  7649. return GL_COMPRESSED_RGB8_ETC2;
  7650. case SG_PIXELFORMAT_ETC2_SRGB8:
  7651. return GL_COMPRESSED_SRGB8_ETC2;
  7652. case SG_PIXELFORMAT_ETC2_RGB8A1:
  7653. return GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
  7654. case SG_PIXELFORMAT_ETC2_RGBA8:
  7655. return GL_COMPRESSED_RGBA8_ETC2_EAC;
  7656. case SG_PIXELFORMAT_ETC2_SRGB8A8:
  7657. return GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
  7658. case SG_PIXELFORMAT_EAC_R11:
  7659. return GL_COMPRESSED_R11_EAC;
  7660. case SG_PIXELFORMAT_EAC_R11SN:
  7661. return GL_COMPRESSED_SIGNED_R11_EAC;
  7662. case SG_PIXELFORMAT_EAC_RG11:
  7663. return GL_COMPRESSED_RG11_EAC;
  7664. case SG_PIXELFORMAT_EAC_RG11SN:
  7665. return GL_COMPRESSED_SIGNED_RG11_EAC;
  7666. case SG_PIXELFORMAT_ASTC_4x4_RGBA:
  7667. return GL_COMPRESSED_RGBA_ASTC_4x4_KHR;
  7668. case SG_PIXELFORMAT_ASTC_4x4_SRGBA:
  7669. return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
  7670. default:
  7671. SOKOL_UNREACHABLE; return 0;
  7672. }
  7673. }
  7674. _SOKOL_PRIVATE GLenum _sg_gl_teximage_internal_format(sg_pixel_format fmt) {
  7675. switch (fmt) {
  7676. case SG_PIXELFORMAT_R8: return GL_R8;
  7677. case SG_PIXELFORMAT_R8SN: return GL_R8_SNORM;
  7678. case SG_PIXELFORMAT_R8UI: return GL_R8UI;
  7679. case SG_PIXELFORMAT_R8SI: return GL_R8I;
  7680. #if !defined(SOKOL_GLES3)
  7681. case SG_PIXELFORMAT_R16: return GL_R16;
  7682. case SG_PIXELFORMAT_R16SN: return GL_R16_SNORM;
  7683. #endif
  7684. case SG_PIXELFORMAT_R16UI: return GL_R16UI;
  7685. case SG_PIXELFORMAT_R16SI: return GL_R16I;
  7686. case SG_PIXELFORMAT_R16F: return GL_R16F;
  7687. case SG_PIXELFORMAT_RG8: return GL_RG8;
  7688. case SG_PIXELFORMAT_RG8SN: return GL_RG8_SNORM;
  7689. case SG_PIXELFORMAT_RG8UI: return GL_RG8UI;
  7690. case SG_PIXELFORMAT_RG8SI: return GL_RG8I;
  7691. case SG_PIXELFORMAT_R32UI: return GL_R32UI;
  7692. case SG_PIXELFORMAT_R32SI: return GL_R32I;
  7693. case SG_PIXELFORMAT_R32F: return GL_R32F;
  7694. #if !defined(SOKOL_GLES3)
  7695. case SG_PIXELFORMAT_RG16: return GL_RG16;
  7696. case SG_PIXELFORMAT_RG16SN: return GL_RG16_SNORM;
  7697. #endif
  7698. case SG_PIXELFORMAT_RG16UI: return GL_RG16UI;
  7699. case SG_PIXELFORMAT_RG16SI: return GL_RG16I;
  7700. case SG_PIXELFORMAT_RG16F: return GL_RG16F;
  7701. case SG_PIXELFORMAT_RGBA8: return GL_RGBA8;
  7702. case SG_PIXELFORMAT_SRGB8A8: return GL_SRGB8_ALPHA8;
  7703. case SG_PIXELFORMAT_RGBA8SN: return GL_RGBA8_SNORM;
  7704. case SG_PIXELFORMAT_RGBA8UI: return GL_RGBA8UI;
  7705. case SG_PIXELFORMAT_RGBA8SI: return GL_RGBA8I;
  7706. case SG_PIXELFORMAT_RGB10A2: return GL_RGB10_A2;
  7707. case SG_PIXELFORMAT_RG11B10F: return GL_R11F_G11F_B10F;
  7708. case SG_PIXELFORMAT_RGB9E5: return GL_RGB9_E5;
  7709. case SG_PIXELFORMAT_RG32UI: return GL_RG32UI;
  7710. case SG_PIXELFORMAT_RG32SI: return GL_RG32I;
  7711. case SG_PIXELFORMAT_RG32F: return GL_RG32F;
  7712. #if !defined(SOKOL_GLES3)
  7713. case SG_PIXELFORMAT_RGBA16: return GL_RGBA16;
  7714. case SG_PIXELFORMAT_RGBA16SN: return GL_RGBA16_SNORM;
  7715. #endif
  7716. case SG_PIXELFORMAT_RGBA16UI: return GL_RGBA16UI;
  7717. case SG_PIXELFORMAT_RGBA16SI: return GL_RGBA16I;
  7718. case SG_PIXELFORMAT_RGBA16F: return GL_RGBA16F;
  7719. case SG_PIXELFORMAT_RGBA32UI: return GL_RGBA32UI;
  7720. case SG_PIXELFORMAT_RGBA32SI: return GL_RGBA32I;
  7721. case SG_PIXELFORMAT_RGBA32F: return GL_RGBA32F;
  7722. case SG_PIXELFORMAT_DEPTH: return GL_DEPTH_COMPONENT32F;
  7723. case SG_PIXELFORMAT_DEPTH_STENCIL: return GL_DEPTH24_STENCIL8;
  7724. case SG_PIXELFORMAT_BC1_RGBA: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
  7725. case SG_PIXELFORMAT_BC2_RGBA: return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
  7726. case SG_PIXELFORMAT_BC3_RGBA: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
  7727. case SG_PIXELFORMAT_BC3_SRGBA: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  7728. case SG_PIXELFORMAT_BC4_R: return GL_COMPRESSED_RED_RGTC1;
  7729. case SG_PIXELFORMAT_BC4_RSN: return GL_COMPRESSED_SIGNED_RED_RGTC1;
  7730. case SG_PIXELFORMAT_BC5_RG: return GL_COMPRESSED_RED_GREEN_RGTC2;
  7731. case SG_PIXELFORMAT_BC5_RGSN: return GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2;
  7732. case SG_PIXELFORMAT_BC6H_RGBF: return GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB;
  7733. case SG_PIXELFORMAT_BC6H_RGBUF: return GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB;
  7734. case SG_PIXELFORMAT_BC7_RGBA: return GL_COMPRESSED_RGBA_BPTC_UNORM_ARB;
  7735. case SG_PIXELFORMAT_BC7_SRGBA: return GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB;
  7736. case SG_PIXELFORMAT_ETC2_RGB8: return GL_COMPRESSED_RGB8_ETC2;
  7737. case SG_PIXELFORMAT_ETC2_SRGB8: return GL_COMPRESSED_SRGB8_ETC2;
  7738. case SG_PIXELFORMAT_ETC2_RGB8A1: return GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
  7739. case SG_PIXELFORMAT_ETC2_RGBA8: return GL_COMPRESSED_RGBA8_ETC2_EAC;
  7740. case SG_PIXELFORMAT_ETC2_SRGB8A8: return GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
  7741. case SG_PIXELFORMAT_EAC_R11: return GL_COMPRESSED_R11_EAC;
  7742. case SG_PIXELFORMAT_EAC_R11SN: return GL_COMPRESSED_SIGNED_R11_EAC;
  7743. case SG_PIXELFORMAT_EAC_RG11: return GL_COMPRESSED_RG11_EAC;
  7744. case SG_PIXELFORMAT_EAC_RG11SN: return GL_COMPRESSED_SIGNED_RG11_EAC;
  7745. case SG_PIXELFORMAT_ASTC_4x4_RGBA: return GL_COMPRESSED_RGBA_ASTC_4x4_KHR;
  7746. case SG_PIXELFORMAT_ASTC_4x4_SRGBA: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
  7747. default: SOKOL_UNREACHABLE; return 0;
  7748. }
  7749. }
  7750. _SOKOL_PRIVATE GLenum _sg_gl_cubeface_target(int face_index) {
  7751. switch (face_index) {
  7752. case 0: return GL_TEXTURE_CUBE_MAP_POSITIVE_X;
  7753. case 1: return GL_TEXTURE_CUBE_MAP_NEGATIVE_X;
  7754. case 2: return GL_TEXTURE_CUBE_MAP_POSITIVE_Y;
  7755. case 3: return GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;
  7756. case 4: return GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
  7757. case 5: return GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
  7758. default: SOKOL_UNREACHABLE; return 0;
  7759. }
  7760. }
  7761. // see: https://www.khronos.org/registry/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  7762. _SOKOL_PRIVATE void _sg_gl_init_pixelformats(bool has_bgra) {
  7763. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R8]);
  7764. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_R8SN]);
  7765. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R8UI]);
  7766. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R8SI]);
  7767. #if !defined(SOKOL_GLES3)
  7768. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16]);
  7769. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16SN]);
  7770. #endif
  7771. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R16UI]);
  7772. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R16SI]);
  7773. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG8]);
  7774. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG8SN]);
  7775. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG8UI]);
  7776. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG8SI]);
  7777. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32UI]);
  7778. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32SI]);
  7779. #if !defined(SOKOL_GLES3)
  7780. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16]);
  7781. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16SN]);
  7782. #endif
  7783. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG16UI]);
  7784. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG16SI]);
  7785. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA8]);
  7786. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_SRGB8A8]);
  7787. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGBA8SN]);
  7788. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA8UI]);
  7789. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA8SI]);
  7790. if (has_bgra) {
  7791. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_BGRA8]);
  7792. }
  7793. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGB10A2]);
  7794. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGB9E5]);
  7795. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  7796. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  7797. #if !defined(SOKOL_GLES3)
  7798. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16]);
  7799. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16SN]);
  7800. #endif
  7801. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA16UI]);
  7802. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA16SI]);
  7803. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  7804. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  7805. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH]);
  7806. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH_STENCIL]);
  7807. }
  7808. // FIXME: OES_half_float_blend
  7809. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_half_float(bool has_colorbuffer_half_float) {
  7810. if (has_colorbuffer_half_float) {
  7811. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16F]);
  7812. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16F]);
  7813. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  7814. } else {
  7815. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_R16F]);
  7816. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG16F]);
  7817. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  7818. }
  7819. }
  7820. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_float(bool has_colorbuffer_float, bool has_texture_float_linear, bool has_float_blend) {
  7821. if (has_texture_float_linear) {
  7822. if (has_colorbuffer_float) {
  7823. if (has_float_blend) {
  7824. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R32F]);
  7825. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  7826. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  7827. } else {
  7828. _sg_pixelformat_sfrm(&_sg.formats[SG_PIXELFORMAT_R32F]);
  7829. _sg_pixelformat_sfrm(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  7830. _sg_pixelformat_sfrm(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  7831. }
  7832. _sg_pixelformat_sfrm(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  7833. } else {
  7834. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_R32F]);
  7835. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  7836. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  7837. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  7838. }
  7839. } else {
  7840. if (has_colorbuffer_float) {
  7841. _sg_pixelformat_sbrm(&_sg.formats[SG_PIXELFORMAT_R32F]);
  7842. _sg_pixelformat_sbrm(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  7843. _sg_pixelformat_sbrm(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  7844. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  7845. } else {
  7846. _sg_pixelformat_s(&_sg.formats[SG_PIXELFORMAT_R32F]);
  7847. _sg_pixelformat_s(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  7848. _sg_pixelformat_s(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  7849. _sg_pixelformat_s(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  7850. }
  7851. }
  7852. }
  7853. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_s3tc(void) {
  7854. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC1_RGBA]);
  7855. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC2_RGBA]);
  7856. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_RGBA]);
  7857. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_SRGBA]);
  7858. }
  7859. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_rgtc(void) {
  7860. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_R]);
  7861. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_RSN]);
  7862. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RG]);
  7863. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RGSN]);
  7864. }
  7865. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_bptc(void) {
  7866. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBF]);
  7867. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBUF]);
  7868. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_RGBA]);
  7869. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_SRGBA]);
  7870. }
  7871. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_etc2(void) {
  7872. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8]);
  7873. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8]);
  7874. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8A1]);
  7875. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGBA8]);
  7876. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8A8]);
  7877. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11]);
  7878. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11SN]);
  7879. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11]);
  7880. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11SN]);
  7881. }
  7882. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_astc(void) {
  7883. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_RGBA]);
  7884. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_SRGBA]);
  7885. }
  7886. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_compute(void) {
  7887. // using Vulkan's conservative default caps (see: https://github.com/gpuweb/gpuweb/issues/513)
  7888. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8]);
  7889. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8SN]);
  7890. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8UI]);
  7891. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8SI]);
  7892. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16UI]);
  7893. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16SI]);
  7894. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  7895. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32UI]);
  7896. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32SI]);
  7897. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32F]);
  7898. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  7899. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  7900. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  7901. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  7902. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  7903. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  7904. }
  7905. _SOKOL_PRIVATE void _sg_gl_init_limits(void) {
  7906. _SG_GL_CHECK_ERROR();
  7907. GLint gl_int;
  7908. glGetIntegerv(GL_MAX_TEXTURE_SIZE, &gl_int);
  7909. _SG_GL_CHECK_ERROR();
  7910. _sg.limits.max_image_size_2d = gl_int;
  7911. _sg.limits.max_image_size_array = gl_int;
  7912. glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &gl_int);
  7913. _SG_GL_CHECK_ERROR();
  7914. _sg.limits.max_image_size_cube = gl_int;
  7915. glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &gl_int);
  7916. _SG_GL_CHECK_ERROR();
  7917. if (gl_int > SG_MAX_VERTEX_ATTRIBUTES) {
  7918. gl_int = SG_MAX_VERTEX_ATTRIBUTES;
  7919. }
  7920. _sg.limits.max_vertex_attrs = gl_int;
  7921. glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, &gl_int);
  7922. _SG_GL_CHECK_ERROR();
  7923. _sg.limits.gl_max_vertex_uniform_components = gl_int;
  7924. glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE, &gl_int);
  7925. _SG_GL_CHECK_ERROR();
  7926. _sg.limits.max_image_size_3d = gl_int;
  7927. glGetIntegerv(GL_MAX_ARRAY_TEXTURE_LAYERS, &gl_int);
  7928. _SG_GL_CHECK_ERROR();
  7929. _sg.limits.max_image_array_layers = gl_int;
  7930. if (_sg.gl.ext_anisotropic) {
  7931. glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &gl_int);
  7932. _SG_GL_CHECK_ERROR();
  7933. _sg.gl.max_anisotropy = gl_int;
  7934. } else {
  7935. _sg.gl.max_anisotropy = 1;
  7936. }
  7937. glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &gl_int);
  7938. _SG_GL_CHECK_ERROR();
  7939. _sg.limits.gl_max_combined_texture_image_units = gl_int;
  7940. }
  7941. #if defined(SOKOL_GLCORE)
  7942. _SOKOL_PRIVATE void _sg_gl_init_caps_glcore(void) {
  7943. _sg.backend = SG_BACKEND_GLCORE;
  7944. GLint major_version = 0;
  7945. GLint minor_version = 0;
  7946. glGetIntegerv(GL_MAJOR_VERSION, &major_version);
  7947. glGetIntegerv(GL_MINOR_VERSION, &minor_version);
  7948. const int version = major_version * 100 + minor_version * 10;
  7949. _sg.features.origin_top_left = false;
  7950. _sg.features.image_clamp_to_border = true;
  7951. _sg.features.mrt_independent_blend_state = false;
  7952. _sg.features.mrt_independent_write_mask = true;
  7953. _sg.features.compute = version >= 430;
  7954. #if defined(__APPLE__)
  7955. _sg.features.msaa_image_bindings = false;
  7956. #else
  7957. _sg.features.msaa_image_bindings = true;
  7958. #endif
  7959. // scan extensions
  7960. bool has_s3tc = false; // BC1..BC3
  7961. bool has_rgtc = false; // BC4 and BC5
  7962. bool has_bptc = false; // BC6H and BC7
  7963. bool has_etc2 = false;
  7964. bool has_astc = false;
  7965. GLint num_ext = 0;
  7966. glGetIntegerv(GL_NUM_EXTENSIONS, &num_ext);
  7967. for (int i = 0; i < num_ext; i++) {
  7968. const char* ext = (const char*) glGetStringi(GL_EXTENSIONS, (GLuint)i);
  7969. if (ext) {
  7970. if (strstr(ext, "_texture_compression_s3tc")) {
  7971. has_s3tc = true;
  7972. } else if (strstr(ext, "_texture_compression_rgtc")) {
  7973. has_rgtc = true;
  7974. } else if (strstr(ext, "_texture_compression_bptc")) {
  7975. has_bptc = true;
  7976. } else if (strstr(ext, "_ES3_compatibility")) {
  7977. has_etc2 = true;
  7978. } else if (strstr(ext, "_texture_filter_anisotropic")) {
  7979. _sg.gl.ext_anisotropic = true;
  7980. } else if (strstr(ext, "_texture_compression_astc_ldr")) {
  7981. has_astc = true;
  7982. }
  7983. }
  7984. }
  7985. // limits
  7986. _sg_gl_init_limits();
  7987. // pixel formats
  7988. const bool has_bgra = false; // not a bug
  7989. const bool has_colorbuffer_float = true;
  7990. const bool has_colorbuffer_half_float = true;
  7991. const bool has_texture_float_linear = true; // FIXME???
  7992. const bool has_float_blend = true;
  7993. _sg_gl_init_pixelformats(has_bgra);
  7994. _sg_gl_init_pixelformats_float(has_colorbuffer_float, has_texture_float_linear, has_float_blend);
  7995. _sg_gl_init_pixelformats_half_float(has_colorbuffer_half_float);
  7996. if (has_s3tc) {
  7997. _sg_gl_init_pixelformats_s3tc();
  7998. }
  7999. if (has_rgtc) {
  8000. _sg_gl_init_pixelformats_rgtc();
  8001. }
  8002. if (has_bptc) {
  8003. _sg_gl_init_pixelformats_bptc();
  8004. }
  8005. if (has_etc2) {
  8006. _sg_gl_init_pixelformats_etc2();
  8007. }
  8008. if (has_astc) {
  8009. _sg_gl_init_pixelformats_astc();
  8010. }
  8011. if (_sg.features.compute) {
  8012. _sg_gl_init_pixelformats_compute();
  8013. }
  8014. }
  8015. #endif
  8016. #if defined(SOKOL_GLES3)
  8017. _SOKOL_PRIVATE void _sg_gl_init_caps_gles3(void) {
  8018. _sg.backend = SG_BACKEND_GLES3;
  8019. GLint major_version = 0;
  8020. GLint minor_version = 0;
  8021. glGetIntegerv(GL_MAJOR_VERSION, &major_version);
  8022. glGetIntegerv(GL_MINOR_VERSION, &minor_version);
  8023. const int version = major_version * 100 + minor_version * 10;
  8024. _sg.features.origin_top_left = false;
  8025. _sg.features.image_clamp_to_border = false;
  8026. _sg.features.mrt_independent_blend_state = false;
  8027. _sg.features.mrt_independent_write_mask = false;
  8028. _sg.features.compute = version >= 310;
  8029. _sg.features.msaa_image_bindings = false;
  8030. #if defined(__EMSCRIPTEN__)
  8031. _sg.features.separate_buffer_types = true;
  8032. #else
  8033. _sg.features.separate_buffer_types = false;
  8034. #endif
  8035. bool has_s3tc = false; // BC1..BC3
  8036. bool has_rgtc = false; // BC4 and BC5
  8037. bool has_bptc = false; // BC6H and BC7
  8038. #if defined(__EMSCRIPTEN__)
  8039. bool has_etc2 = false;
  8040. #else
  8041. bool has_etc2 = true;
  8042. #endif
  8043. bool has_astc = false;
  8044. bool has_colorbuffer_float = false;
  8045. bool has_colorbuffer_half_float = false;
  8046. bool has_texture_float_linear = false;
  8047. bool has_float_blend = false;
  8048. GLint num_ext = 0;
  8049. glGetIntegerv(GL_NUM_EXTENSIONS, &num_ext);
  8050. for (int i = 0; i < num_ext; i++) {
  8051. const char* ext = (const char*) glGetStringi(GL_EXTENSIONS, (GLuint)i);
  8052. if (ext) {
  8053. if (strstr(ext, "_texture_compression_s3tc")) {
  8054. has_s3tc = true;
  8055. } else if (strstr(ext, "_compressed_texture_s3tc")) {
  8056. has_s3tc = true;
  8057. } else if (strstr(ext, "_texture_compression_rgtc")) {
  8058. has_rgtc = true;
  8059. } else if (strstr(ext, "_texture_compression_bptc")) {
  8060. has_bptc = true;
  8061. } else if (strstr(ext, "_compressed_texture_etc")) {
  8062. has_etc2 = true;
  8063. } else if (strstr(ext, "_compressed_texture_astc")) {
  8064. has_astc = true;
  8065. } else if (strstr(ext, "_color_buffer_float")) {
  8066. has_colorbuffer_float = true;
  8067. } else if (strstr(ext, "_color_buffer_half_float")) {
  8068. has_colorbuffer_half_float = true;
  8069. } else if (strstr(ext, "_texture_float_linear")) {
  8070. has_texture_float_linear = true;
  8071. } else if (strstr(ext, "_float_blend")) {
  8072. has_float_blend = true;
  8073. } else if (strstr(ext, "_texture_filter_anisotropic")) {
  8074. _sg.gl.ext_anisotropic = true;
  8075. }
  8076. }
  8077. }
  8078. /* on WebGL2, color_buffer_float also includes 16-bit formats
  8079. see: https://developer.mozilla.org/en-US/docs/Web/API/EXT_color_buffer_float
  8080. */
  8081. #if defined(__EMSCRIPTEN__)
  8082. if (!has_colorbuffer_half_float && has_colorbuffer_float) {
  8083. has_colorbuffer_half_float = has_colorbuffer_float;
  8084. }
  8085. #endif
  8086. // limits
  8087. _sg_gl_init_limits();
  8088. // pixel formats
  8089. const bool has_bgra = false; // not a bug
  8090. _sg_gl_init_pixelformats(has_bgra);
  8091. _sg_gl_init_pixelformats_float(has_colorbuffer_float, has_texture_float_linear, has_float_blend);
  8092. _sg_gl_init_pixelformats_half_float(has_colorbuffer_half_float);
  8093. if (has_s3tc) {
  8094. _sg_gl_init_pixelformats_s3tc();
  8095. }
  8096. if (has_rgtc) {
  8097. _sg_gl_init_pixelformats_rgtc();
  8098. }
  8099. if (has_bptc) {
  8100. _sg_gl_init_pixelformats_bptc();
  8101. }
  8102. if (has_etc2) {
  8103. _sg_gl_init_pixelformats_etc2();
  8104. }
  8105. if (has_astc) {
  8106. _sg_gl_init_pixelformats_astc();
  8107. }
  8108. if (_sg.features.compute) {
  8109. _sg_gl_init_pixelformats_compute();
  8110. }
  8111. }
  8112. #endif
  8113. //-- state cache implementation ------------------------------------------------
  8114. _SOKOL_PRIVATE void _sg_gl_cache_clear_buffer_bindings(bool force) {
  8115. if (force || (_sg.gl.cache.vertex_buffer != 0)) {
  8116. glBindBuffer(GL_ARRAY_BUFFER, 0);
  8117. _sg.gl.cache.vertex_buffer = 0;
  8118. _sg_stats_add(gl.num_bind_buffer, 1);
  8119. }
  8120. if (force || (_sg.gl.cache.index_buffer != 0)) {
  8121. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  8122. _sg.gl.cache.index_buffer = 0;
  8123. _sg_stats_add(gl.num_bind_buffer, 1);
  8124. }
  8125. if (force || (_sg.gl.cache.storage_buffer != 0)) {
  8126. if (_sg.features.compute) {
  8127. glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
  8128. }
  8129. _sg.gl.cache.storage_buffer = 0;
  8130. _sg_stats_add(gl.num_bind_buffer, 1);
  8131. }
  8132. for (size_t i = 0; i < _SG_GL_MAX_SBUF_BINDINGS; i++) {
  8133. if (force || (_sg.gl.cache.storage_buffers[i] != 0)) {
  8134. if (_sg.features.compute) {
  8135. glBindBufferBase(GL_SHADER_STORAGE_BUFFER, (GLuint)i, 0);
  8136. }
  8137. _sg.gl.cache.storage_buffers[i] = 0;
  8138. _sg_stats_add(gl.num_bind_buffer, 1);
  8139. }
  8140. }
  8141. }
  8142. _SOKOL_PRIVATE void _sg_gl_cache_bind_buffer(GLenum target, GLuint buffer) {
  8143. SOKOL_ASSERT((GL_ARRAY_BUFFER == target) || (GL_ELEMENT_ARRAY_BUFFER == target) || (GL_SHADER_STORAGE_BUFFER == target));
  8144. if (target == GL_ARRAY_BUFFER) {
  8145. if (_sg.gl.cache.vertex_buffer != buffer) {
  8146. _sg.gl.cache.vertex_buffer = buffer;
  8147. glBindBuffer(target, buffer);
  8148. _sg_stats_add(gl.num_bind_buffer, 1);
  8149. }
  8150. } else if (target == GL_ELEMENT_ARRAY_BUFFER) {
  8151. if (_sg.gl.cache.index_buffer != buffer) {
  8152. _sg.gl.cache.index_buffer = buffer;
  8153. glBindBuffer(target, buffer);
  8154. _sg_stats_add(gl.num_bind_buffer, 1);
  8155. }
  8156. } else if (target == GL_SHADER_STORAGE_BUFFER) {
  8157. if (_sg.gl.cache.storage_buffer != buffer) {
  8158. _sg.gl.cache.storage_buffer = buffer;
  8159. if (_sg.features.compute) {
  8160. glBindBuffer(target, buffer);
  8161. }
  8162. _sg_stats_add(gl.num_bind_buffer, 1);
  8163. }
  8164. } else {
  8165. SOKOL_UNREACHABLE;
  8166. }
  8167. }
  8168. _SOKOL_PRIVATE void _sg_gl_cache_bind_storage_buffer(uint8_t glsl_binding_n, GLuint buffer) {
  8169. SOKOL_ASSERT(glsl_binding_n < _SG_GL_MAX_SBUF_BINDINGS);
  8170. if (_sg.gl.cache.storage_buffers[glsl_binding_n] != buffer) {
  8171. _sg.gl.cache.storage_buffers[glsl_binding_n] = buffer;
  8172. _sg.gl.cache.storage_buffer = buffer; // not a bug
  8173. if (_sg.features.compute) {
  8174. glBindBufferBase(GL_SHADER_STORAGE_BUFFER, glsl_binding_n, buffer);
  8175. }
  8176. _sg_stats_add(gl.num_bind_buffer, 1);
  8177. }
  8178. }
  8179. _SOKOL_PRIVATE void _sg_gl_cache_store_buffer_binding(GLenum target) {
  8180. if (target == GL_ARRAY_BUFFER) {
  8181. _sg.gl.cache.stored_vertex_buffer = _sg.gl.cache.vertex_buffer;
  8182. } else if (target == GL_ELEMENT_ARRAY_BUFFER) {
  8183. _sg.gl.cache.stored_index_buffer = _sg.gl.cache.index_buffer;
  8184. } else if (target == GL_SHADER_STORAGE_BUFFER) {
  8185. _sg.gl.cache.stored_storage_buffer = _sg.gl.cache.storage_buffer;
  8186. } else {
  8187. SOKOL_UNREACHABLE;
  8188. }
  8189. }
  8190. _SOKOL_PRIVATE void _sg_gl_cache_restore_buffer_binding(GLenum target) {
  8191. if (target == GL_ARRAY_BUFFER) {
  8192. if (_sg.gl.cache.stored_vertex_buffer != 0) {
  8193. // we only care about restoring valid ids
  8194. _sg_gl_cache_bind_buffer(target, _sg.gl.cache.stored_vertex_buffer);
  8195. _sg.gl.cache.stored_vertex_buffer = 0;
  8196. }
  8197. } else if (target == GL_ELEMENT_ARRAY_BUFFER) {
  8198. if (_sg.gl.cache.stored_index_buffer != 0) {
  8199. // we only care about restoring valid ids
  8200. _sg_gl_cache_bind_buffer(target, _sg.gl.cache.stored_index_buffer);
  8201. _sg.gl.cache.stored_index_buffer = 0;
  8202. }
  8203. } else if (target == GL_SHADER_STORAGE_BUFFER) {
  8204. if (_sg.gl.cache.stored_storage_buffer != 0) {
  8205. // we only care about restoring valid ids
  8206. _sg_gl_cache_bind_buffer(target, _sg.gl.cache.stored_storage_buffer);
  8207. _sg.gl.cache.stored_storage_buffer = 0;
  8208. }
  8209. } else {
  8210. SOKOL_UNREACHABLE;
  8211. }
  8212. }
  8213. // called from _sg_gl_discard_buffer()
  8214. _SOKOL_PRIVATE void _sg_gl_cache_invalidate_buffer(GLuint buf) {
  8215. if (buf == _sg.gl.cache.vertex_buffer) {
  8216. _sg.gl.cache.vertex_buffer = 0;
  8217. glBindBuffer(GL_ARRAY_BUFFER, 0);
  8218. _sg_stats_add(gl.num_bind_buffer, 1);
  8219. }
  8220. if (buf == _sg.gl.cache.index_buffer) {
  8221. _sg.gl.cache.index_buffer = 0;
  8222. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  8223. _sg_stats_add(gl.num_bind_buffer, 1);
  8224. }
  8225. if (buf == _sg.gl.cache.storage_buffer) {
  8226. _sg.gl.cache.storage_buffer = 0;
  8227. glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
  8228. _sg_stats_add(gl.num_bind_buffer, 1);
  8229. }
  8230. for (size_t i = 0; i < _SG_GL_MAX_SBUF_BINDINGS; i++) {
  8231. if (buf == _sg.gl.cache.storage_buffers[i]) {
  8232. _sg.gl.cache.storage_buffers[i] = 0;
  8233. _sg.gl.cache.storage_buffer = 0; // not a bug!
  8234. glBindBufferBase(GL_SHADER_STORAGE_BUFFER, (GLuint)i, 0);
  8235. _sg_stats_add(gl.num_bind_buffer, 1);
  8236. }
  8237. }
  8238. if (buf == _sg.gl.cache.stored_vertex_buffer) {
  8239. _sg.gl.cache.stored_vertex_buffer = 0;
  8240. }
  8241. if (buf == _sg.gl.cache.stored_index_buffer) {
  8242. _sg.gl.cache.stored_index_buffer = 0;
  8243. }
  8244. if (buf == _sg.gl.cache.stored_storage_buffer) {
  8245. _sg.gl.cache.stored_storage_buffer = 0;
  8246. }
  8247. for (int i = 0; i < SG_MAX_VERTEX_ATTRIBUTES; i++) {
  8248. if (buf == _sg.gl.cache.attrs[i].gl_vbuf) {
  8249. _sg.gl.cache.attrs[i].gl_vbuf = 0;
  8250. }
  8251. }
  8252. }
  8253. _SOKOL_PRIVATE void _sg_gl_cache_active_texture(GLenum texture) {
  8254. _SG_GL_CHECK_ERROR();
  8255. if (_sg.gl.cache.cur_active_texture != texture) {
  8256. _sg.gl.cache.cur_active_texture = texture;
  8257. glActiveTexture(texture);
  8258. _sg_stats_add(gl.num_active_texture, 1);
  8259. }
  8260. _SG_GL_CHECK_ERROR();
  8261. }
  8262. _SOKOL_PRIVATE void _sg_gl_cache_clear_texture_sampler_bindings(bool force) {
  8263. _SG_GL_CHECK_ERROR();
  8264. for (int i = 0; (i < _SG_GL_MAX_IMG_SMP_BINDINGS) && (i < _sg.limits.gl_max_combined_texture_image_units); i++) {
  8265. if (force || (_sg.gl.cache.texture_samplers[i].texture != 0)) {
  8266. GLenum gl_texture_unit = (GLenum) (GL_TEXTURE0 + i);
  8267. glActiveTexture(gl_texture_unit);
  8268. _sg_stats_add(gl.num_active_texture, 1);
  8269. glBindTexture(GL_TEXTURE_2D, 0);
  8270. glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
  8271. glBindTexture(GL_TEXTURE_3D, 0);
  8272. glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
  8273. _sg_stats_add(gl.num_bind_texture, 4);
  8274. glBindSampler((GLuint)i, 0);
  8275. _sg_stats_add(gl.num_bind_sampler, 1);
  8276. _sg.gl.cache.texture_samplers[i].target = 0;
  8277. _sg.gl.cache.texture_samplers[i].texture = 0;
  8278. _sg.gl.cache.texture_samplers[i].sampler = 0;
  8279. _sg.gl.cache.cur_active_texture = gl_texture_unit;
  8280. }
  8281. }
  8282. _SG_GL_CHECK_ERROR();
  8283. }
  8284. _SOKOL_PRIVATE void _sg_gl_cache_bind_texture_sampler(int8_t gl_tex_slot, GLenum target, GLuint texture, GLuint sampler) {
  8285. /* it's valid to call this function with target=0 and/or texture=0
  8286. target=0 will unbind the previous binding, texture=0 will clear
  8287. the new binding
  8288. */
  8289. SOKOL_ASSERT((gl_tex_slot >= 0) && (gl_tex_slot < _SG_GL_MAX_IMG_SMP_BINDINGS));
  8290. if (gl_tex_slot >= _sg.limits.gl_max_combined_texture_image_units) {
  8291. return;
  8292. }
  8293. _SG_GL_CHECK_ERROR();
  8294. _sg_gl_cache_texture_sampler_bind_slot* slot = &_sg.gl.cache.texture_samplers[gl_tex_slot];
  8295. if ((slot->target != target) || (slot->texture != texture) || (slot->sampler != sampler)) {
  8296. _sg_gl_cache_active_texture((GLenum)(GL_TEXTURE0 + gl_tex_slot));
  8297. // if the target has changed, clear the previous binding on that target
  8298. if ((target != slot->target) && (slot->target != 0)) {
  8299. glBindTexture(slot->target, 0);
  8300. _SG_GL_CHECK_ERROR();
  8301. _sg_stats_add(gl.num_bind_texture, 1);
  8302. }
  8303. // apply new binding (can be 0 to unbind)
  8304. if (target != 0) {
  8305. glBindTexture(target, texture);
  8306. _SG_GL_CHECK_ERROR();
  8307. _sg_stats_add(gl.num_bind_texture, 1);
  8308. }
  8309. // apply new sampler (can be 0 to unbind)
  8310. glBindSampler((GLuint)gl_tex_slot, sampler);
  8311. _SG_GL_CHECK_ERROR();
  8312. _sg_stats_add(gl.num_bind_sampler, 1);
  8313. slot->target = target;
  8314. slot->texture = texture;
  8315. slot->sampler = sampler;
  8316. }
  8317. }
  8318. _SOKOL_PRIVATE void _sg_gl_cache_store_texture_sampler_binding(int8_t gl_tex_slot) {
  8319. SOKOL_ASSERT((gl_tex_slot >= 0) && (gl_tex_slot < _SG_GL_MAX_IMG_SMP_BINDINGS));
  8320. _sg.gl.cache.stored_texture_sampler = _sg.gl.cache.texture_samplers[gl_tex_slot];
  8321. }
  8322. _SOKOL_PRIVATE void _sg_gl_cache_restore_texture_sampler_binding(int8_t gl_tex_slot) {
  8323. SOKOL_ASSERT((gl_tex_slot >= 0) && (gl_tex_slot < _SG_GL_MAX_IMG_SMP_BINDINGS));
  8324. _sg_gl_cache_texture_sampler_bind_slot* slot = &_sg.gl.cache.stored_texture_sampler;
  8325. if (slot->texture != 0) {
  8326. // we only care about restoring valid ids
  8327. SOKOL_ASSERT(slot->target != 0);
  8328. _sg_gl_cache_bind_texture_sampler(gl_tex_slot, slot->target, slot->texture, slot->sampler);
  8329. slot->target = 0;
  8330. slot->texture = 0;
  8331. slot->sampler = 0;
  8332. }
  8333. }
  8334. // called from _sg_gl_discard_texture() and _sg_gl_discard_sampler()
  8335. _SOKOL_PRIVATE void _sg_gl_cache_invalidate_texture_sampler(GLuint tex, GLuint smp) {
  8336. _SG_GL_CHECK_ERROR();
  8337. for (size_t i = 0; i < _SG_GL_MAX_IMG_SMP_BINDINGS; i++) {
  8338. _sg_gl_cache_texture_sampler_bind_slot* slot = &_sg.gl.cache.texture_samplers[i];
  8339. if ((0 != slot->target) && ((tex == slot->texture) || (smp == slot->sampler))) {
  8340. _sg_gl_cache_active_texture((GLenum)(GL_TEXTURE0 + i));
  8341. glBindTexture(slot->target, 0);
  8342. _SG_GL_CHECK_ERROR();
  8343. _sg_stats_add(gl.num_bind_texture, 1);
  8344. glBindSampler((GLuint)i, 0);
  8345. _SG_GL_CHECK_ERROR();
  8346. _sg_stats_add(gl.num_bind_sampler, 1);
  8347. slot->target = 0;
  8348. slot->texture = 0;
  8349. slot->sampler = 0;
  8350. }
  8351. }
  8352. if ((tex == _sg.gl.cache.stored_texture_sampler.texture) || (smp == _sg.gl.cache.stored_texture_sampler.sampler)) {
  8353. _sg.gl.cache.stored_texture_sampler.target = 0;
  8354. _sg.gl.cache.stored_texture_sampler.texture = 0;
  8355. _sg.gl.cache.stored_texture_sampler.sampler = 0;
  8356. }
  8357. }
  8358. // called from _sg_gl_discard_shader()
  8359. _SOKOL_PRIVATE void _sg_gl_cache_invalidate_program(GLuint prog) {
  8360. if (prog == _sg.gl.cache.prog) {
  8361. _sg.gl.cache.prog = 0;
  8362. glUseProgram(0);
  8363. _sg_stats_add(gl.num_use_program, 1);
  8364. }
  8365. }
  8366. // called from _sg_gl_discard_pipeline()
  8367. _SOKOL_PRIVATE void _sg_gl_cache_invalidate_pipeline(_sg_pipeline_t* pip) {
  8368. if (_sg_sref_eql(&_sg.gl.cache.cur_pip, &pip->slot)) {
  8369. _sg.gl.cache.cur_pip = _sg_sref(0);
  8370. }
  8371. }
  8372. _SOKOL_PRIVATE void _sg_gl_reset_state_cache(void) {
  8373. _SG_GL_CHECK_ERROR();
  8374. glBindVertexArray(_sg.gl.vao);
  8375. _SG_GL_CHECK_ERROR();
  8376. _sg_clear(&_sg.gl.cache, sizeof(_sg.gl.cache));
  8377. _sg_gl_cache_clear_buffer_bindings(true);
  8378. _SG_GL_CHECK_ERROR();
  8379. _sg_gl_cache_clear_texture_sampler_bindings(true);
  8380. _SG_GL_CHECK_ERROR();
  8381. for (int i = 0; i < _sg.limits.max_vertex_attrs; i++) {
  8382. _sg_gl_attr_t* attr = &_sg.gl.cache.attrs[i].gl_attr;
  8383. attr->vb_index = -1;
  8384. attr->divisor = -1;
  8385. glDisableVertexAttribArray((GLuint)i);
  8386. _SG_GL_CHECK_ERROR();
  8387. _sg_stats_add(gl.num_disable_vertex_attrib_array, 1);
  8388. }
  8389. _sg.gl.cache.cur_primitive_type = GL_TRIANGLES;
  8390. // shader program
  8391. glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&_sg.gl.cache.prog);
  8392. _SG_GL_CHECK_ERROR();
  8393. // depth and stencil state
  8394. _sg.gl.cache.depth.compare = SG_COMPAREFUNC_ALWAYS;
  8395. _sg.gl.cache.stencil.front.compare = SG_COMPAREFUNC_ALWAYS;
  8396. _sg.gl.cache.stencil.front.fail_op = SG_STENCILOP_KEEP;
  8397. _sg.gl.cache.stencil.front.depth_fail_op = SG_STENCILOP_KEEP;
  8398. _sg.gl.cache.stencil.front.pass_op = SG_STENCILOP_KEEP;
  8399. _sg.gl.cache.stencil.back.compare = SG_COMPAREFUNC_ALWAYS;
  8400. _sg.gl.cache.stencil.back.fail_op = SG_STENCILOP_KEEP;
  8401. _sg.gl.cache.stencil.back.depth_fail_op = SG_STENCILOP_KEEP;
  8402. _sg.gl.cache.stencil.back.pass_op = SG_STENCILOP_KEEP;
  8403. glEnable(GL_DEPTH_TEST);
  8404. glDepthFunc(GL_ALWAYS);
  8405. glDepthMask(GL_FALSE);
  8406. glDisable(GL_STENCIL_TEST);
  8407. glStencilFunc(GL_ALWAYS, 0, 0);
  8408. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  8409. glStencilMask(0);
  8410. _sg_stats_add(gl.num_render_state, 7);
  8411. // blend state
  8412. _sg.gl.cache.blend.src_factor_rgb = SG_BLENDFACTOR_ONE;
  8413. _sg.gl.cache.blend.dst_factor_rgb = SG_BLENDFACTOR_ZERO;
  8414. _sg.gl.cache.blend.op_rgb = SG_BLENDOP_ADD;
  8415. _sg.gl.cache.blend.src_factor_alpha = SG_BLENDFACTOR_ONE;
  8416. _sg.gl.cache.blend.dst_factor_alpha = SG_BLENDFACTOR_ZERO;
  8417. _sg.gl.cache.blend.op_alpha = SG_BLENDOP_ADD;
  8418. glDisable(GL_BLEND);
  8419. glBlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_ZERO);
  8420. glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
  8421. glBlendColor(0.0f, 0.0f, 0.0f, 0.0f);
  8422. _sg_stats_add(gl.num_render_state, 4);
  8423. // standalone state
  8424. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  8425. _sg.gl.cache.color_write_mask[i] = SG_COLORMASK_RGBA;
  8426. }
  8427. _sg.gl.cache.cull_mode = SG_CULLMODE_NONE;
  8428. _sg.gl.cache.face_winding = SG_FACEWINDING_CW;
  8429. _sg.gl.cache.sample_count = 1;
  8430. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  8431. glPolygonOffset(0.0f, 0.0f);
  8432. glDisable(GL_POLYGON_OFFSET_FILL);
  8433. glDisable(GL_CULL_FACE);
  8434. glFrontFace(GL_CW);
  8435. glCullFace(GL_BACK);
  8436. glEnable(GL_SCISSOR_TEST);
  8437. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  8438. glEnable(GL_DITHER);
  8439. glDisable(GL_POLYGON_OFFSET_FILL);
  8440. _sg_stats_add(gl.num_render_state, 10);
  8441. #if defined(SOKOL_GLCORE)
  8442. glEnable(GL_MULTISAMPLE);
  8443. glEnable(GL_PROGRAM_POINT_SIZE);
  8444. _sg_stats_add(gl.num_render_state, 2);
  8445. #endif
  8446. }
  8447. _SOKOL_PRIVATE void _sg_gl_setup_backend(const sg_desc* desc) {
  8448. _SOKOL_UNUSED(desc);
  8449. // assumes that _sg.gl is already zero-initialized
  8450. _sg.gl.valid = true;
  8451. #if defined(_SOKOL_USE_WIN32_GL_LOADER)
  8452. _sg_gl_load_opengl();
  8453. #endif
  8454. // clear initial GL error state
  8455. #if defined(SOKOL_DEBUG)
  8456. while (glGetError() != GL_NO_ERROR);
  8457. #endif
  8458. #if defined(SOKOL_GLCORE)
  8459. _sg_gl_init_caps_glcore();
  8460. #elif defined(SOKOL_GLES3)
  8461. _sg_gl_init_caps_gles3();
  8462. #endif
  8463. glGenVertexArrays(1, &_sg.gl.vao);
  8464. glBindVertexArray(_sg.gl.vao);
  8465. _SG_GL_CHECK_ERROR();
  8466. // incoming texture data is generally expected to be packed tightly
  8467. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  8468. #if defined(SOKOL_GLCORE)
  8469. // enable seamless cubemap sampling (only desktop GL)
  8470. glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
  8471. #endif
  8472. _sg_gl_reset_state_cache();
  8473. }
  8474. _SOKOL_PRIVATE void _sg_gl_discard_backend(void) {
  8475. SOKOL_ASSERT(_sg.gl.valid);
  8476. if (_sg.gl.vao) {
  8477. glDeleteVertexArrays(1, &_sg.gl.vao);
  8478. }
  8479. #if defined(_SOKOL_USE_WIN32_GL_LOADER)
  8480. _sg_gl_unload_opengl();
  8481. #endif
  8482. _sg.gl.valid = false;
  8483. }
  8484. //-- GL backend resource creation and destruction ------------------------------
  8485. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  8486. SOKOL_ASSERT(buf && desc);
  8487. _SG_GL_CHECK_ERROR();
  8488. buf->gl.injected = (0 != desc->gl_buffers[0]);
  8489. const GLenum gl_target = _sg_gl_buffer_target(&buf->cmn.usage);
  8490. const GLenum gl_usage = _sg_gl_buffer_usage(&buf->cmn.usage);
  8491. for (int slot = 0; slot < buf->cmn.num_slots; slot++) {
  8492. GLuint gl_buf = 0;
  8493. if (buf->gl.injected) {
  8494. SOKOL_ASSERT(desc->gl_buffers[slot]);
  8495. gl_buf = desc->gl_buffers[slot];
  8496. } else {
  8497. glGenBuffers(1, &gl_buf);
  8498. SOKOL_ASSERT(gl_buf);
  8499. _sg_gl_cache_store_buffer_binding(gl_target);
  8500. _sg_gl_cache_bind_buffer(gl_target, gl_buf);
  8501. glBufferData(gl_target, buf->cmn.size, 0, gl_usage);
  8502. if (desc->data.ptr) {
  8503. glBufferSubData(gl_target, 0, buf->cmn.size, desc->data.ptr);
  8504. }
  8505. _sg_gl_cache_restore_buffer_binding(gl_target);
  8506. }
  8507. buf->gl.buf[slot] = gl_buf;
  8508. }
  8509. _SG_GL_CHECK_ERROR();
  8510. return SG_RESOURCESTATE_VALID;
  8511. }
  8512. _SOKOL_PRIVATE void _sg_gl_discard_buffer(_sg_buffer_t* buf) {
  8513. SOKOL_ASSERT(buf);
  8514. _SG_GL_CHECK_ERROR();
  8515. for (int slot = 0; slot < buf->cmn.num_slots; slot++) {
  8516. if (buf->gl.buf[slot]) {
  8517. _sg_gl_cache_invalidate_buffer(buf->gl.buf[slot]);
  8518. if (!buf->gl.injected) {
  8519. glDeleteBuffers(1, &buf->gl.buf[slot]);
  8520. }
  8521. }
  8522. }
  8523. _SG_GL_CHECK_ERROR();
  8524. }
  8525. _SOKOL_PRIVATE bool _sg_gl_supported_texture_format(sg_pixel_format fmt) {
  8526. const int fmt_index = (int) fmt;
  8527. SOKOL_ASSERT((fmt_index > SG_PIXELFORMAT_NONE) && (fmt_index < _SG_PIXELFORMAT_NUM));
  8528. return _sg.formats[fmt_index].sample;
  8529. }
  8530. _SOKOL_PRIVATE void _sg_gl_texstorage(const _sg_image_t* img) {
  8531. const GLenum tgt = img->gl.target;
  8532. const int num_mips = img->cmn.num_mipmaps;
  8533. #if defined(_SOKOL_GL_HAS_TEXSTORAGE)
  8534. const GLenum ifmt = _sg_gl_teximage_internal_format(img->cmn.pixel_format);
  8535. const bool msaa = img->cmn.sample_count > 1;
  8536. const int w = img->cmn.width;
  8537. const int h = img->cmn.height;
  8538. if ((SG_IMAGETYPE_2D == img->cmn.type) || (SG_IMAGETYPE_CUBE == img->cmn.type)) {
  8539. #if defined(SOKOL_GLCORE)
  8540. if (msaa) {
  8541. glTexStorage2DMultisample(tgt, img->cmn.sample_count, ifmt, w, h, GL_TRUE);
  8542. } else {
  8543. glTexStorage2D(tgt, num_mips, ifmt, w, h);
  8544. }
  8545. #else
  8546. SOKOL_ASSERT(!msaa); _SOKOL_UNUSED(msaa);
  8547. glTexStorage2D(tgt, num_mips, ifmt, w, h);
  8548. #endif
  8549. } else if ((SG_IMAGETYPE_3D == img->cmn.type) || (SG_IMAGETYPE_ARRAY == img->cmn.type)) {
  8550. const int depth = img->cmn.num_slices;
  8551. #if defined(SOKOL_GLCORE)
  8552. if (msaa) {
  8553. // NOTE: MSAA works only for array textures, not 3D textures
  8554. glTexStorage3DMultisample(tgt, img->cmn.sample_count, ifmt, w, h, depth, GL_TRUE);
  8555. } else {
  8556. glTexStorage3D(tgt, num_mips, ifmt, w, h, depth);
  8557. }
  8558. #else
  8559. SOKOL_ASSERT(!msaa); _SOKOL_UNUSED(msaa);
  8560. glTexStorage3D(tgt, num_mips, ifmt, w, h, depth);
  8561. #endif
  8562. }
  8563. #else
  8564. glTexParameteri(tgt, GL_TEXTURE_MAX_LEVEL, num_mips - 1);
  8565. #endif
  8566. _SG_GL_CHECK_ERROR();
  8567. }
  8568. _SOKOL_PRIVATE void _sg_gl_teximage(const _sg_image_t* img, GLenum tgt, int mip_index, int w, int h, int depth, const GLvoid* data_ptr, GLsizei data_size) {
  8569. const bool compressed = _sg_is_compressed_pixel_format(img->cmn.pixel_format);
  8570. #if defined(_SOKOL_GL_HAS_TEXSTORAGE)
  8571. if (data_ptr == 0) {
  8572. return;
  8573. }
  8574. SOKOL_ASSERT(img->cmn.sample_count == 1);
  8575. if ((SG_IMAGETYPE_2D == img->cmn.type) || (SG_IMAGETYPE_CUBE == img->cmn.type)) {
  8576. if (compressed) {
  8577. const GLenum ifmt = _sg_gl_teximage_internal_format(img->cmn.pixel_format);
  8578. glCompressedTexSubImage2D(tgt, mip_index, 0, 0, w, h, ifmt, data_size, data_ptr);
  8579. } else {
  8580. const GLenum type = _sg_gl_teximage_type(img->cmn.pixel_format);
  8581. const GLenum fmt = _sg_gl_teximage_format(img->cmn.pixel_format);
  8582. glTexSubImage2D(tgt, mip_index, 0, 0, w, h, fmt, type, data_ptr);
  8583. }
  8584. } else if ((SG_IMAGETYPE_3D == img->cmn.type) || (SG_IMAGETYPE_ARRAY == img->cmn.type)) {
  8585. if (compressed) {
  8586. const GLenum ifmt = _sg_gl_teximage_internal_format(img->cmn.pixel_format);
  8587. glCompressedTexSubImage3D(tgt, mip_index, 0, 0, 0, w, h, depth, ifmt, data_size, data_ptr);
  8588. } else {
  8589. const GLenum type = _sg_gl_teximage_type(img->cmn.pixel_format);
  8590. const GLenum fmt = _sg_gl_teximage_format(img->cmn.pixel_format);
  8591. glTexSubImage3D(tgt, mip_index, 0, 0, 0, w, h, depth, fmt, type, data_ptr);
  8592. }
  8593. }
  8594. #else
  8595. const GLenum ifmt = _sg_gl_teximage_internal_format(img->cmn.pixel_format);
  8596. const bool msaa = img->cmn.sample_count > 1;
  8597. if ((SG_IMAGETYPE_2D == img->cmn.type) || (SG_IMAGETYPE_CUBE == img->cmn.type)) {
  8598. if (compressed) {
  8599. SOKOL_ASSERT(!msaa); _SOKOL_UNUSED(msaa);
  8600. glCompressedTexImage2D(tgt, mip_index, ifmt, w, h, 0, data_size, data_ptr);
  8601. } else {
  8602. const GLenum type = _sg_gl_teximage_type(img->cmn.pixel_format);
  8603. const GLenum fmt = _sg_gl_teximage_format(img->cmn.pixel_format);
  8604. #if defined(SOKOL_GLCORE)
  8605. if (msaa) {
  8606. glTexImage2DMultisample(tgt, img->cmn.sample_count, (GLint)ifmt, w, h, GL_TRUE);
  8607. } else {
  8608. glTexImage2D(tgt, mip_index, (GLint)ifmt, w, h, 0, fmt, type, data_ptr);
  8609. }
  8610. #else
  8611. SOKOL_ASSERT(!msaa); _SOKOL_UNUSED(msaa);
  8612. glTexImage2D(tgt, mip_index, (GLint)ifmt, w, h, 0, fmt, type, data_ptr);
  8613. #endif
  8614. }
  8615. } else if ((SG_IMAGETYPE_3D == img->cmn.type) || (SG_IMAGETYPE_ARRAY == img->cmn.type)) {
  8616. if (compressed) {
  8617. SOKOL_ASSERT(!msaa); _SOKOL_UNUSED(msaa);
  8618. glCompressedTexImage3D(tgt, mip_index, ifmt, w, h, depth, 0, data_size, data_ptr);
  8619. } else {
  8620. const GLenum type = _sg_gl_teximage_type(img->cmn.pixel_format);
  8621. const GLenum fmt = _sg_gl_teximage_format(img->cmn.pixel_format);
  8622. #if defined(SOKOL_GLCORE)
  8623. if (msaa) {
  8624. // NOTE: MSAA works only for array textures, not 3D textures
  8625. glTexImage3DMultisample(tgt, img->cmn.sample_count, (GLint)ifmt, w, h, depth, GL_TRUE);
  8626. } else {
  8627. glTexImage3D(tgt, mip_index, (GLint)ifmt, w, h, depth, 0, fmt, type, data_ptr);
  8628. }
  8629. #else
  8630. SOKOL_ASSERT(!msaa); _SOKOL_UNUSED(msaa);
  8631. glTexImage3D(tgt, mip_index, (GLint)ifmt, w, h, depth, 0, fmt, type, data_ptr);
  8632. #endif
  8633. }
  8634. }
  8635. #endif
  8636. _SG_GL_CHECK_ERROR();
  8637. }
  8638. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  8639. SOKOL_ASSERT(img && desc);
  8640. _SG_GL_CHECK_ERROR();
  8641. img->gl.injected = (0 != desc->gl_textures[0]);
  8642. // check if texture format is support
  8643. if (!_sg_gl_supported_texture_format(img->cmn.pixel_format)) {
  8644. _SG_ERROR(GL_TEXTURE_FORMAT_NOT_SUPPORTED);
  8645. return SG_RESOURCESTATE_FAILED;
  8646. }
  8647. // GLES3/WebGL2/macOS doesn't have support for multisampled textures, so create a render buffer object instead
  8648. const bool msaa = img->cmn.sample_count > 1;
  8649. if (!_sg.features.msaa_image_bindings && img->cmn.usage.render_attachment && msaa) {
  8650. const GLenum gl_internal_format = _sg_gl_teximage_internal_format(img->cmn.pixel_format);
  8651. glGenRenderbuffers(1, &img->gl.msaa_render_buffer);
  8652. glBindRenderbuffer(GL_RENDERBUFFER, img->gl.msaa_render_buffer);
  8653. glRenderbufferStorageMultisample(GL_RENDERBUFFER, img->cmn.sample_count, gl_internal_format, img->cmn.width, img->cmn.height);
  8654. } else if (img->gl.injected) {
  8655. img->gl.target = _sg_gl_texture_target(img->cmn.type, img->cmn.sample_count);
  8656. // inject externally GL textures
  8657. for (int slot = 0; slot < img->cmn.num_slots; slot++) {
  8658. SOKOL_ASSERT(desc->gl_textures[slot]);
  8659. img->gl.tex[slot] = desc->gl_textures[slot];
  8660. }
  8661. if (desc->gl_texture_target) {
  8662. img->gl.target = (GLenum)desc->gl_texture_target;
  8663. }
  8664. } else {
  8665. // create our own GL texture(s)
  8666. img->gl.target = _sg_gl_texture_target(img->cmn.type, img->cmn.sample_count);
  8667. for (int slot = 0; slot < img->cmn.num_slots; slot++) {
  8668. glGenTextures(1, &img->gl.tex[slot]);
  8669. SOKOL_ASSERT(img->gl.tex[slot]);
  8670. _sg_gl_cache_store_texture_sampler_binding(0);
  8671. _sg_gl_cache_bind_texture_sampler(0, img->gl.target, img->gl.tex[slot], 0);
  8672. _sg_gl_texstorage(img);
  8673. const int num_faces = img->cmn.type == SG_IMAGETYPE_CUBE ? 6 : 1;
  8674. for (int face_index = 0; face_index < num_faces; face_index++) {
  8675. for (int mip_index = 0; mip_index < img->cmn.num_mipmaps; mip_index++) {
  8676. GLenum gl_img_target = img->gl.target;
  8677. if (SG_IMAGETYPE_CUBE == img->cmn.type) {
  8678. gl_img_target = _sg_gl_cubeface_target(face_index);
  8679. }
  8680. const GLvoid* data_ptr = desc->data.subimage[face_index][mip_index].ptr;
  8681. const GLsizei data_size = (GLsizei)desc->data.subimage[face_index][mip_index].size;
  8682. const int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  8683. const int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  8684. const int mip_depth = (SG_IMAGETYPE_3D == img->cmn.type) ? _sg_miplevel_dim(img->cmn.num_slices, mip_index) : img->cmn.num_slices;
  8685. _sg_gl_teximage(img, gl_img_target, mip_index, mip_width, mip_height, mip_depth, data_ptr, data_size);
  8686. }
  8687. }
  8688. _sg_gl_cache_restore_texture_sampler_binding(0);
  8689. }
  8690. }
  8691. _SG_GL_CHECK_ERROR();
  8692. return SG_RESOURCESTATE_VALID;
  8693. }
  8694. _SOKOL_PRIVATE void _sg_gl_discard_image(_sg_image_t* img) {
  8695. SOKOL_ASSERT(img);
  8696. _SG_GL_CHECK_ERROR();
  8697. for (int slot = 0; slot < img->cmn.num_slots; slot++) {
  8698. if (img->gl.tex[slot]) {
  8699. _sg_gl_cache_invalidate_texture_sampler(img->gl.tex[slot], 0);
  8700. if (!img->gl.injected) {
  8701. glDeleteTextures(1, &img->gl.tex[slot]);
  8702. }
  8703. }
  8704. }
  8705. if (img->gl.msaa_render_buffer) {
  8706. glDeleteRenderbuffers(1, &img->gl.msaa_render_buffer);
  8707. }
  8708. _SG_GL_CHECK_ERROR();
  8709. }
  8710. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  8711. SOKOL_ASSERT(smp && desc);
  8712. _SG_GL_CHECK_ERROR();
  8713. smp->gl.injected = (0 != desc->gl_sampler);
  8714. if (smp->gl.injected) {
  8715. smp->gl.smp = (GLuint) desc->gl_sampler;
  8716. } else {
  8717. glGenSamplers(1, &smp->gl.smp);
  8718. SOKOL_ASSERT(smp->gl.smp);
  8719. const GLenum gl_min_filter = _sg_gl_min_filter(smp->cmn.min_filter, smp->cmn.mipmap_filter);
  8720. const GLenum gl_mag_filter = _sg_gl_mag_filter(smp->cmn.mag_filter);
  8721. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_MIN_FILTER, (GLint)gl_min_filter);
  8722. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_MAG_FILTER, (GLint)gl_mag_filter);
  8723. // GL spec has strange defaults for mipmap min/max lod: -1000 to +1000
  8724. const float min_lod = _sg_clamp(desc->min_lod, 0.0f, 1000.0f);
  8725. const float max_lod = _sg_clamp(desc->max_lod, 0.0f, 1000.0f);
  8726. glSamplerParameterf(smp->gl.smp, GL_TEXTURE_MIN_LOD, min_lod);
  8727. glSamplerParameterf(smp->gl.smp, GL_TEXTURE_MAX_LOD, max_lod);
  8728. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_WRAP_S, (GLint)_sg_gl_wrap(smp->cmn.wrap_u));
  8729. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_WRAP_T, (GLint)_sg_gl_wrap(smp->cmn.wrap_v));
  8730. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_WRAP_R, (GLint)_sg_gl_wrap(smp->cmn.wrap_w));
  8731. #if defined(SOKOL_GLCORE)
  8732. float border[4];
  8733. switch (smp->cmn.border_color) {
  8734. case SG_BORDERCOLOR_TRANSPARENT_BLACK:
  8735. border[0] = 0.0f; border[1] = 0.0f; border[2] = 0.0f; border[3] = 0.0f;
  8736. break;
  8737. case SG_BORDERCOLOR_OPAQUE_WHITE:
  8738. border[0] = 1.0f; border[1] = 1.0f; border[2] = 1.0f; border[3] = 1.0f;
  8739. break;
  8740. default:
  8741. border[0] = 0.0f; border[1] = 0.0f; border[2] = 0.0f; border[3] = 1.0f;
  8742. break;
  8743. }
  8744. glSamplerParameterfv(smp->gl.smp, GL_TEXTURE_BORDER_COLOR, border);
  8745. #endif
  8746. if (smp->cmn.compare != SG_COMPAREFUNC_NEVER) {
  8747. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  8748. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_COMPARE_FUNC, (GLint)_sg_gl_compare_func(smp->cmn.compare));
  8749. } else {
  8750. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  8751. }
  8752. if (_sg.gl.ext_anisotropic && (smp->cmn.max_anisotropy > 1)) {
  8753. GLint max_aniso = (GLint) smp->cmn.max_anisotropy;
  8754. if (max_aniso > _sg.gl.max_anisotropy) {
  8755. max_aniso = _sg.gl.max_anisotropy;
  8756. }
  8757. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_MAX_ANISOTROPY_EXT, max_aniso);
  8758. }
  8759. }
  8760. _SG_GL_CHECK_ERROR();
  8761. return SG_RESOURCESTATE_VALID;
  8762. }
  8763. _SOKOL_PRIVATE void _sg_gl_discard_sampler(_sg_sampler_t* smp) {
  8764. SOKOL_ASSERT(smp);
  8765. _SG_GL_CHECK_ERROR();
  8766. _sg_gl_cache_invalidate_texture_sampler(0, smp->gl.smp);
  8767. if (!smp->gl.injected) {
  8768. glDeleteSamplers(1, &smp->gl.smp);
  8769. }
  8770. _SG_GL_CHECK_ERROR();
  8771. }
  8772. _SOKOL_PRIVATE GLuint _sg_gl_compile_shader(sg_shader_stage stage, const char* src) {
  8773. SOKOL_ASSERT(src);
  8774. _SG_GL_CHECK_ERROR();
  8775. GLuint gl_shd = glCreateShader(_sg_gl_shader_stage(stage));
  8776. glShaderSource(gl_shd, 1, &src, 0);
  8777. glCompileShader(gl_shd);
  8778. GLint compile_status = 0;
  8779. glGetShaderiv(gl_shd, GL_COMPILE_STATUS, &compile_status);
  8780. if (!compile_status) {
  8781. // compilation failed, log error and delete shader
  8782. GLint log_len = 0;
  8783. glGetShaderiv(gl_shd, GL_INFO_LOG_LENGTH, &log_len);
  8784. if (log_len > 0) {
  8785. GLchar* log_buf = (GLchar*) _sg_malloc((size_t)log_len);
  8786. glGetShaderInfoLog(gl_shd, log_len, &log_len, log_buf);
  8787. _SG_ERROR(GL_SHADER_COMPILATION_FAILED);
  8788. _SG_LOGMSG(GL_SHADER_COMPILATION_FAILED, log_buf);
  8789. _sg_free(log_buf);
  8790. }
  8791. glDeleteShader(gl_shd);
  8792. gl_shd = 0;
  8793. }
  8794. _SG_GL_CHECK_ERROR();
  8795. return gl_shd;
  8796. }
  8797. // NOTE: this is an out-of-range check for GLSL bindslots that's also active in release mode
  8798. _SOKOL_PRIVATE bool _sg_gl_ensure_glsl_bindslot_ranges(const sg_shader_desc* desc) {
  8799. SOKOL_ASSERT(desc);
  8800. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  8801. if (desc->storage_buffers[i].glsl_binding_n >= _SG_GL_MAX_SBUF_BINDINGS) {
  8802. _SG_ERROR(GL_STORAGEBUFFER_GLSL_BINDING_OUT_OF_RANGE);
  8803. return false;
  8804. }
  8805. }
  8806. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  8807. if (desc->storage_images[i].glsl_binding_n >= _SG_GL_MAX_SIMG_BINDINGS) {
  8808. _SG_ERROR(GL_STORAGEIMAGE_GLSL_BINDING_OUT_OF_RANGE);
  8809. return false;
  8810. }
  8811. }
  8812. return true;
  8813. }
  8814. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  8815. SOKOL_ASSERT(shd && desc);
  8816. SOKOL_ASSERT(!shd->gl.prog);
  8817. _SG_GL_CHECK_ERROR();
  8818. // perform a fatal range-check on GLSL bindslots that's also active
  8819. // in release mode to avoid potential out-of-bounds array accesses
  8820. if (!_sg_gl_ensure_glsl_bindslot_ranges(desc)) {
  8821. return SG_RESOURCESTATE_FAILED;
  8822. }
  8823. // copy the optional vertex attribute names over
  8824. for (int i = 0; i < SG_MAX_VERTEX_ATTRIBUTES; i++) {
  8825. _sg_strcpy(&shd->gl.attrs[i].name, desc->attrs[i].glsl_name);
  8826. }
  8827. const bool has_vs = desc->vertex_func.source;
  8828. const bool has_fs = desc->fragment_func.source;
  8829. const bool has_cs = desc->compute_func.source;
  8830. SOKOL_ASSERT((has_vs && has_fs) || has_cs);
  8831. GLuint gl_prog = glCreateProgram();
  8832. if (has_vs && has_fs) {
  8833. GLuint gl_vs = _sg_gl_compile_shader(SG_SHADERSTAGE_VERTEX, desc->vertex_func.source);
  8834. GLuint gl_fs = _sg_gl_compile_shader(SG_SHADERSTAGE_FRAGMENT, desc->fragment_func.source);
  8835. if (!(gl_vs && gl_fs)) {
  8836. glDeleteProgram(gl_prog);
  8837. if (gl_vs) { glDeleteShader(gl_vs); }
  8838. if (gl_fs) { glDeleteShader(gl_fs); }
  8839. return SG_RESOURCESTATE_FAILED;
  8840. }
  8841. glAttachShader(gl_prog, gl_vs);
  8842. glAttachShader(gl_prog, gl_fs);
  8843. glLinkProgram(gl_prog);
  8844. glDeleteShader(gl_vs);
  8845. glDeleteShader(gl_fs);
  8846. _SG_GL_CHECK_ERROR();
  8847. } else if (has_cs) {
  8848. GLuint gl_cs = _sg_gl_compile_shader(SG_SHADERSTAGE_COMPUTE, desc->compute_func.source);
  8849. if (!gl_cs) {
  8850. glDeleteProgram(gl_prog);
  8851. return SG_RESOURCESTATE_FAILED;
  8852. }
  8853. glAttachShader(gl_prog, gl_cs);
  8854. glLinkProgram(gl_prog);
  8855. glDeleteShader(gl_cs);
  8856. _SG_GL_CHECK_ERROR();
  8857. } else {
  8858. SOKOL_UNREACHABLE;
  8859. }
  8860. GLint link_status;
  8861. glGetProgramiv(gl_prog, GL_LINK_STATUS, &link_status);
  8862. if (!link_status) {
  8863. GLint log_len = 0;
  8864. glGetProgramiv(gl_prog, GL_INFO_LOG_LENGTH, &log_len);
  8865. if (log_len > 0) {
  8866. GLchar* log_buf = (GLchar*) _sg_malloc((size_t)log_len);
  8867. glGetProgramInfoLog(gl_prog, log_len, &log_len, log_buf);
  8868. _SG_ERROR(GL_SHADER_LINKING_FAILED);
  8869. _SG_LOGMSG(GL_SHADER_LINKING_FAILED, log_buf);
  8870. _sg_free(log_buf);
  8871. }
  8872. glDeleteProgram(gl_prog);
  8873. return SG_RESOURCESTATE_FAILED;
  8874. }
  8875. shd->gl.prog = gl_prog;
  8876. // resolve uniforms
  8877. _SG_GL_CHECK_ERROR();
  8878. for (size_t ub_index = 0; ub_index < SG_MAX_UNIFORMBLOCK_BINDSLOTS; ub_index++) {
  8879. const sg_shader_uniform_block* ub_desc = &desc->uniform_blocks[ub_index];
  8880. if (ub_desc->stage == SG_SHADERSTAGE_NONE) {
  8881. continue;
  8882. }
  8883. SOKOL_ASSERT(ub_desc->size > 0);
  8884. _sg_gl_uniform_block_t* ub = &shd->gl.uniform_blocks[ub_index];
  8885. SOKOL_ASSERT(ub->num_uniforms == 0);
  8886. uint32_t cur_uniform_offset = 0;
  8887. for (int u_index = 0; u_index < SG_MAX_UNIFORMBLOCK_MEMBERS; u_index++) {
  8888. const sg_glsl_shader_uniform* u_desc = &ub_desc->glsl_uniforms[u_index];
  8889. if (u_desc->type == SG_UNIFORMTYPE_INVALID) {
  8890. break;
  8891. }
  8892. const uint32_t u_align = _sg_uniform_alignment(u_desc->type, u_desc->array_count, ub_desc->layout);
  8893. const uint32_t u_size = _sg_uniform_size(u_desc->type, u_desc->array_count, ub_desc->layout);
  8894. cur_uniform_offset = _sg_align_u32(cur_uniform_offset, u_align);
  8895. _sg_gl_uniform_t* u = &ub->uniforms[u_index];
  8896. u->type = u_desc->type;
  8897. u->count = (uint16_t) u_desc->array_count;
  8898. u->offset = (uint16_t) cur_uniform_offset;
  8899. SOKOL_ASSERT(u_desc->glsl_name);
  8900. u->gl_loc = glGetUniformLocation(gl_prog, u_desc->glsl_name);
  8901. if (u->gl_loc == -1) {
  8902. _SG_WARN(GL_UNIFORMBLOCK_NAME_NOT_FOUND_IN_SHADER);
  8903. _SG_LOGMSG(GL_UNIFORMBLOCK_NAME_NOT_FOUND_IN_SHADER, u_desc->glsl_name);
  8904. }
  8905. cur_uniform_offset += u_size;
  8906. ub->num_uniforms++;
  8907. }
  8908. if (ub_desc->layout == SG_UNIFORMLAYOUT_STD140) {
  8909. cur_uniform_offset = _sg_align_u32(cur_uniform_offset, 16);
  8910. }
  8911. SOKOL_ASSERT(ub_desc->size == (size_t)cur_uniform_offset);
  8912. _SOKOL_UNUSED(cur_uniform_offset);
  8913. }
  8914. // copy storage buffer bind slots
  8915. for (size_t sbuf_index = 0; sbuf_index < SG_MAX_STORAGEBUFFER_BINDSLOTS; sbuf_index++) {
  8916. const sg_shader_storage_buffer* sbuf_desc = &desc->storage_buffers[sbuf_index];
  8917. if (sbuf_desc->stage == SG_SHADERSTAGE_NONE) {
  8918. continue;
  8919. }
  8920. SOKOL_ASSERT(sbuf_desc->glsl_binding_n < _SG_GL_MAX_SBUF_BINDINGS);
  8921. shd->gl.sbuf_binding[sbuf_index] = sbuf_desc->glsl_binding_n;
  8922. }
  8923. // copy storage image bind slots
  8924. for (size_t simg_index = 0; simg_index < SG_MAX_STORAGE_ATTACHMENTS; simg_index++) {
  8925. const sg_shader_storage_image* simg_desc = &desc->storage_images[simg_index];
  8926. if (simg_desc->stage == SG_SHADERSTAGE_NONE) {
  8927. continue;
  8928. }
  8929. SOKOL_ASSERT(simg_desc->glsl_binding_n < _SG_GL_MAX_SIMG_BINDINGS);
  8930. shd->gl.simg_binding[simg_index] = simg_desc->glsl_binding_n;
  8931. }
  8932. // record image sampler location in shader program
  8933. _SG_GL_CHECK_ERROR();
  8934. GLuint cur_prog = 0;
  8935. glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&cur_prog);
  8936. glUseProgram(gl_prog);
  8937. GLint gl_tex_slot = 0;
  8938. for (size_t img_smp_index = 0; img_smp_index < SG_MAX_IMAGE_SAMPLER_PAIRS; img_smp_index++) {
  8939. const sg_shader_image_sampler_pair* img_smp_desc = &desc->image_sampler_pairs[img_smp_index];
  8940. if (img_smp_desc->stage == SG_SHADERSTAGE_NONE) {
  8941. continue;
  8942. }
  8943. SOKOL_ASSERT(img_smp_desc->glsl_name);
  8944. GLint gl_loc = glGetUniformLocation(gl_prog, img_smp_desc->glsl_name);
  8945. if (gl_loc != -1) {
  8946. glUniform1i(gl_loc, gl_tex_slot);
  8947. shd->gl.tex_slot[img_smp_index] = (int8_t)gl_tex_slot++;
  8948. } else {
  8949. shd->gl.tex_slot[img_smp_index] = -1;
  8950. _SG_WARN(GL_IMAGE_SAMPLER_NAME_NOT_FOUND_IN_SHADER);
  8951. _SG_LOGMSG(GL_IMAGE_SAMPLER_NAME_NOT_FOUND_IN_SHADER, img_smp_desc->glsl_name);
  8952. }
  8953. }
  8954. // it's legal to call glUseProgram with 0
  8955. glUseProgram(cur_prog);
  8956. _SG_GL_CHECK_ERROR();
  8957. return SG_RESOURCESTATE_VALID;
  8958. }
  8959. _SOKOL_PRIVATE void _sg_gl_discard_shader(_sg_shader_t* shd) {
  8960. SOKOL_ASSERT(shd);
  8961. _SG_GL_CHECK_ERROR();
  8962. if (shd->gl.prog) {
  8963. _sg_gl_cache_invalidate_program(shd->gl.prog);
  8964. glDeleteProgram(shd->gl.prog);
  8965. }
  8966. _SG_GL_CHECK_ERROR();
  8967. }
  8968. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_pipeline(_sg_pipeline_t* pip, const sg_pipeline_desc* desc) {
  8969. SOKOL_ASSERT(pip && desc);
  8970. SOKOL_ASSERT(_sg.limits.max_vertex_attrs <= SG_MAX_VERTEX_ATTRIBUTES);
  8971. if (pip->cmn.is_compute) {
  8972. // shortcut for compute pipelines
  8973. return SG_RESOURCESTATE_VALID;
  8974. }
  8975. pip->gl.primitive_type = desc->primitive_type;
  8976. pip->gl.depth = desc->depth;
  8977. pip->gl.stencil = desc->stencil;
  8978. // FIXME: blend color and write mask per draw-buffer-attachment (requires GL4)
  8979. pip->gl.blend = desc->colors[0].blend;
  8980. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  8981. pip->gl.color_write_mask[i] = desc->colors[i].write_mask;
  8982. }
  8983. pip->gl.cull_mode = desc->cull_mode;
  8984. pip->gl.face_winding = desc->face_winding;
  8985. pip->gl.sample_count = desc->sample_count;
  8986. pip->gl.alpha_to_coverage_enabled = desc->alpha_to_coverage_enabled;
  8987. // NOTE: GLSL compilers may remove unused vertex attributes so we can't rely
  8988. // on the 'prepopulated' vertex_buffer_layout_active[] state and need to
  8989. // fill this array from scratch with the actual info after GLSL compilation
  8990. for (int i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  8991. pip->cmn.vertex_buffer_layout_active[i] = false;
  8992. }
  8993. // resolve vertex attributes
  8994. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  8995. SOKOL_ASSERT(shd->gl.prog);
  8996. for (int attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  8997. pip->gl.attrs[attr_index].vb_index = -1;
  8998. }
  8999. for (int attr_index = 0; attr_index < _sg.limits.max_vertex_attrs; attr_index++) {
  9000. const sg_vertex_attr_state* a_state = &desc->layout.attrs[attr_index];
  9001. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  9002. break;
  9003. }
  9004. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  9005. const sg_vertex_buffer_layout_state* l_state = &desc->layout.buffers[a_state->buffer_index];
  9006. const sg_vertex_step step_func = l_state->step_func;
  9007. const int step_rate = l_state->step_rate;
  9008. GLint attr_loc = attr_index;
  9009. if (!_sg_strempty(&shd->gl.attrs[attr_index].name)) {
  9010. attr_loc = glGetAttribLocation(shd->gl.prog, _sg_strptr(&shd->gl.attrs[attr_index].name));
  9011. }
  9012. if (attr_loc != -1) {
  9013. SOKOL_ASSERT(attr_loc < (GLint)_sg.limits.max_vertex_attrs);
  9014. _sg_gl_attr_t* gl_attr = &pip->gl.attrs[attr_loc];
  9015. SOKOL_ASSERT(gl_attr->vb_index == -1);
  9016. gl_attr->vb_index = (int8_t) a_state->buffer_index;
  9017. if (step_func == SG_VERTEXSTEP_PER_VERTEX) {
  9018. gl_attr->divisor = 0;
  9019. } else {
  9020. gl_attr->divisor = (int8_t) step_rate;
  9021. pip->cmn.use_instanced_draw = true;
  9022. }
  9023. SOKOL_ASSERT(l_state->stride > 0);
  9024. gl_attr->stride = (uint8_t) l_state->stride;
  9025. gl_attr->offset = a_state->offset;
  9026. gl_attr->size = (uint8_t) _sg_gl_vertexformat_size(a_state->format);
  9027. gl_attr->type = _sg_gl_vertexformat_type(a_state->format);
  9028. gl_attr->normalized = _sg_gl_vertexformat_normalized(a_state->format);
  9029. gl_attr->base_type = _sg_vertexformat_basetype(a_state->format);
  9030. pip->cmn.vertex_buffer_layout_active[a_state->buffer_index] = true;
  9031. } else {
  9032. _SG_WARN(GL_VERTEX_ATTRIBUTE_NOT_FOUND_IN_SHADER);
  9033. _SG_LOGMSG(GL_VERTEX_ATTRIBUTE_NOT_FOUND_IN_SHADER, _sg_strptr(&shd->gl.attrs[attr_index].name));
  9034. }
  9035. }
  9036. return SG_RESOURCESTATE_VALID;
  9037. }
  9038. _SOKOL_PRIVATE void _sg_gl_discard_pipeline(_sg_pipeline_t* pip) {
  9039. SOKOL_ASSERT(pip);
  9040. _sg_gl_cache_invalidate_pipeline(pip);
  9041. }
  9042. _SOKOL_PRIVATE void _sg_gl_fb_attach_texture(const _sg_attachment_common_t* att, GLenum gl_att_type) {
  9043. const _sg_image_t* img = _sg_image_ref_ptr(&att->image);
  9044. const GLuint gl_tex = img->gl.tex[0];
  9045. SOKOL_ASSERT(gl_tex);
  9046. const GLuint gl_target = img->gl.target;
  9047. SOKOL_ASSERT(gl_target);
  9048. const int mip_level = att->mip_level;
  9049. const int slice = att->slice;
  9050. switch (img->cmn.type) {
  9051. case SG_IMAGETYPE_2D:
  9052. glFramebufferTexture2D(GL_FRAMEBUFFER, gl_att_type, gl_target, gl_tex, mip_level);
  9053. break;
  9054. case SG_IMAGETYPE_CUBE:
  9055. glFramebufferTexture2D(GL_FRAMEBUFFER, gl_att_type, _sg_gl_cubeface_target(slice), gl_tex, mip_level);
  9056. break;
  9057. default:
  9058. glFramebufferTextureLayer(GL_FRAMEBUFFER, gl_att_type, gl_tex, mip_level, slice);
  9059. break;
  9060. }
  9061. }
  9062. _SOKOL_PRIVATE GLenum _sg_gl_depth_stencil_attachment_type(const _sg_image_t* ds_img) {
  9063. if (_sg_is_depth_stencil_format(ds_img->cmn.pixel_format)) {
  9064. return GL_DEPTH_STENCIL_ATTACHMENT;
  9065. } else {
  9066. return GL_DEPTH_ATTACHMENT;
  9067. }
  9068. }
  9069. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_attachments(_sg_attachments_t* atts, const sg_attachments_desc* desc) {
  9070. SOKOL_ASSERT(atts && desc);
  9071. _SOKOL_UNUSED(desc);
  9072. _SG_GL_CHECK_ERROR();
  9073. // if this is a compute pass attachment we're done here
  9074. if (atts->cmn.has_storage_attachments) {
  9075. SOKOL_ASSERT(!atts->cmn.has_render_attachments);
  9076. return SG_RESOURCESTATE_VALID;
  9077. }
  9078. // store current framebuffer binding (restored at end of function)
  9079. GLuint gl_orig_fb;
  9080. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&gl_orig_fb);
  9081. // create a framebuffer object
  9082. glGenFramebuffers(1, &atts->gl.fb);
  9083. glBindFramebuffer(GL_FRAMEBUFFER, atts->gl.fb);
  9084. // attach color attachments to framebuffer
  9085. for (int i = 0; i < atts->cmn.num_colors; i++) {
  9086. const _sg_image_t* color_img = _sg_image_ref_ptr(&atts->cmn.colors[i].image);
  9087. const GLuint gl_msaa_render_buffer = color_img->gl.msaa_render_buffer;
  9088. if (gl_msaa_render_buffer) {
  9089. glFramebufferRenderbuffer(GL_FRAMEBUFFER, (GLenum)(GL_COLOR_ATTACHMENT0+i), GL_RENDERBUFFER, gl_msaa_render_buffer);
  9090. } else {
  9091. const GLenum gl_att_type = (GLenum)(GL_COLOR_ATTACHMENT0 + i);
  9092. _sg_gl_fb_attach_texture(&atts->cmn.colors[i], gl_att_type);
  9093. }
  9094. }
  9095. // attach depth-stencil attachment
  9096. if (!_sg_image_ref_null(&atts->cmn.depth_stencil.image)) {
  9097. const _sg_image_t* ds_img = _sg_image_ref_ptr(&atts->cmn.depth_stencil.image);
  9098. const GLenum gl_att_type = _sg_gl_depth_stencil_attachment_type(ds_img);
  9099. const GLuint gl_msaa_render_buffer = ds_img->gl.msaa_render_buffer;
  9100. if (gl_msaa_render_buffer) {
  9101. glFramebufferRenderbuffer(GL_FRAMEBUFFER, gl_att_type, GL_RENDERBUFFER, gl_msaa_render_buffer);
  9102. } else {
  9103. _sg_gl_fb_attach_texture(&atts->cmn.depth_stencil, gl_att_type);
  9104. }
  9105. }
  9106. // check if framebuffer is complete
  9107. {
  9108. const GLenum fb_status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  9109. if (fb_status != GL_FRAMEBUFFER_COMPLETE) {
  9110. switch (fb_status) {
  9111. case GL_FRAMEBUFFER_UNDEFINED:
  9112. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNDEFINED);
  9113. break;
  9114. case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  9115. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_ATTACHMENT);
  9116. break;
  9117. case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  9118. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MISSING_ATTACHMENT);
  9119. break;
  9120. case GL_FRAMEBUFFER_UNSUPPORTED:
  9121. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNSUPPORTED);
  9122. break;
  9123. case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
  9124. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MULTISAMPLE);
  9125. break;
  9126. default:
  9127. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNKNOWN);
  9128. break;
  9129. }
  9130. return SG_RESOURCESTATE_FAILED;
  9131. }
  9132. }
  9133. // setup color attachments for the framebuffer
  9134. static const GLenum gl_draw_bufs[SG_MAX_COLOR_ATTACHMENTS] = {
  9135. GL_COLOR_ATTACHMENT0,
  9136. GL_COLOR_ATTACHMENT1,
  9137. GL_COLOR_ATTACHMENT2,
  9138. GL_COLOR_ATTACHMENT3
  9139. };
  9140. glDrawBuffers(atts->cmn.num_colors, gl_draw_bufs);
  9141. // create MSAA resolve framebuffers if necessary
  9142. for (int i = 0; i < atts->cmn.num_colors; i++) {
  9143. _sg_attachment_common_t* cmn_resolve_att = &atts->cmn.resolves[i];
  9144. if (!_sg_image_ref_null(&cmn_resolve_att->image)) {
  9145. SOKOL_ASSERT(0 == atts->gl.msaa_resolve_framebuffer[i]);
  9146. glGenFramebuffers(1, &atts->gl.msaa_resolve_framebuffer[i]);
  9147. glBindFramebuffer(GL_FRAMEBUFFER, atts->gl.msaa_resolve_framebuffer[i]);
  9148. _sg_gl_fb_attach_texture(cmn_resolve_att, GL_COLOR_ATTACHMENT0);
  9149. // check if framebuffer is complete
  9150. const GLenum fb_status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  9151. if (fb_status != GL_FRAMEBUFFER_COMPLETE) {
  9152. switch (fb_status) {
  9153. case GL_FRAMEBUFFER_UNDEFINED:
  9154. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNDEFINED);
  9155. break;
  9156. case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  9157. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_ATTACHMENT);
  9158. break;
  9159. case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  9160. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MISSING_ATTACHMENT);
  9161. break;
  9162. case GL_FRAMEBUFFER_UNSUPPORTED:
  9163. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNSUPPORTED);
  9164. break;
  9165. case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
  9166. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MULTISAMPLE);
  9167. break;
  9168. default:
  9169. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNKNOWN);
  9170. break;
  9171. }
  9172. return SG_RESOURCESTATE_FAILED;
  9173. }
  9174. // setup color attachments for the framebuffer
  9175. glDrawBuffers(1, &gl_draw_bufs[0]);
  9176. }
  9177. }
  9178. // restore original framebuffer binding
  9179. glBindFramebuffer(GL_FRAMEBUFFER, gl_orig_fb);
  9180. _SG_GL_CHECK_ERROR();
  9181. return SG_RESOURCESTATE_VALID;
  9182. }
  9183. _SOKOL_PRIVATE void _sg_gl_discard_attachments(_sg_attachments_t* atts) {
  9184. SOKOL_ASSERT(atts);
  9185. _SG_GL_CHECK_ERROR();
  9186. if (0 != atts->gl.fb) {
  9187. glDeleteFramebuffers(1, &atts->gl.fb);
  9188. }
  9189. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  9190. if (atts->gl.msaa_resolve_framebuffer[i]) {
  9191. glDeleteFramebuffers(1, &atts->gl.msaa_resolve_framebuffer[i]);
  9192. }
  9193. }
  9194. _SG_GL_CHECK_ERROR();
  9195. }
  9196. _SOKOL_PRIVATE void _sg_gl_begin_pass(const sg_pass* pass) {
  9197. // FIXME: what if a texture used as render target is still bound, should we
  9198. // unbind all currently bound textures in begin pass?
  9199. SOKOL_ASSERT(pass);
  9200. _SG_GL_CHECK_ERROR();
  9201. const _sg_attachments_t* atts = _sg_attachments_ref_ptr_or_null(&_sg.cur_pass.atts);
  9202. // early out if this a compute pass
  9203. if (pass->compute) {
  9204. // first pipeline in pass needs to re-apply storage attachments
  9205. if (atts && atts->cmn.has_storage_attachments) {
  9206. _sg.gl.cache.cur_pip = _sg_sref(0);
  9207. }
  9208. return;
  9209. }
  9210. const sg_swapchain* swapchain = &pass->swapchain;
  9211. const sg_pass_action* action = &pass->action;
  9212. // bind the render pass framebuffer
  9213. //
  9214. // FIXME: Disabling SRGB conversion for the default framebuffer is
  9215. // a crude hack to make behaviour for sRGB render target textures
  9216. // identical with the Metal and D3D11 swapchains created by sokol-app.
  9217. //
  9218. // This will need a cleaner solution (e.g. allowing to configure
  9219. // sokol_app.h with an sRGB or RGB framebuffer.
  9220. if (atts) {
  9221. // offscreen pass
  9222. SOKOL_ASSERT(atts->gl.fb);
  9223. #if defined(SOKOL_GLCORE)
  9224. glEnable(GL_FRAMEBUFFER_SRGB);
  9225. #endif
  9226. glBindFramebuffer(GL_FRAMEBUFFER, atts->gl.fb);
  9227. } else {
  9228. // default pass
  9229. #if defined(SOKOL_GLCORE)
  9230. glDisable(GL_FRAMEBUFFER_SRGB);
  9231. #endif
  9232. // NOTE: on some platforms, the default framebuffer of a context
  9233. // is null, so we can't actually assert here that the
  9234. // framebuffer has been provided
  9235. glBindFramebuffer(GL_FRAMEBUFFER, swapchain->gl.framebuffer);
  9236. }
  9237. glViewport(0, 0, _sg.cur_pass.width, _sg.cur_pass.height);
  9238. glScissor(0, 0, _sg.cur_pass.width, _sg.cur_pass.height);
  9239. // number of color attachments
  9240. const int num_color_atts = atts ? atts->cmn.num_colors : 1;
  9241. // clear color and depth-stencil attachments if needed
  9242. bool clear_any_color = false;
  9243. for (int i = 0; i < num_color_atts; i++) {
  9244. if (SG_LOADACTION_CLEAR == action->colors[i].load_action) {
  9245. clear_any_color = true;
  9246. break;
  9247. }
  9248. }
  9249. const bool clear_depth = (action->depth.load_action == SG_LOADACTION_CLEAR);
  9250. const bool clear_stencil = (action->stencil.load_action == SG_LOADACTION_CLEAR);
  9251. bool need_pip_cache_flush = false;
  9252. if (clear_any_color) {
  9253. bool need_color_mask_flush = false;
  9254. // NOTE: not a bug to iterate over all possible color attachments
  9255. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  9256. if (SG_COLORMASK_RGBA != _sg.gl.cache.color_write_mask[i]) {
  9257. need_pip_cache_flush = true;
  9258. need_color_mask_flush = true;
  9259. _sg.gl.cache.color_write_mask[i] = SG_COLORMASK_RGBA;
  9260. }
  9261. }
  9262. if (need_color_mask_flush) {
  9263. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  9264. }
  9265. }
  9266. if (clear_depth) {
  9267. if (!_sg.gl.cache.depth.write_enabled) {
  9268. need_pip_cache_flush = true;
  9269. _sg.gl.cache.depth.write_enabled = true;
  9270. glDepthMask(GL_TRUE);
  9271. }
  9272. if (_sg.gl.cache.depth.compare != SG_COMPAREFUNC_ALWAYS) {
  9273. need_pip_cache_flush = true;
  9274. _sg.gl.cache.depth.compare = SG_COMPAREFUNC_ALWAYS;
  9275. glDepthFunc(GL_ALWAYS);
  9276. }
  9277. }
  9278. if (clear_stencil) {
  9279. if (_sg.gl.cache.stencil.write_mask != 0xFF) {
  9280. need_pip_cache_flush = true;
  9281. _sg.gl.cache.stencil.write_mask = 0xFF;
  9282. glStencilMask(0xFF);
  9283. }
  9284. }
  9285. if (need_pip_cache_flush) {
  9286. // we messed with the state cache directly, need to clear cached
  9287. // pipeline to force re-evaluation in next sg_apply_pipeline()
  9288. _sg.gl.cache.cur_pip = _sg_sref(0);
  9289. }
  9290. for (int i = 0; i < num_color_atts; i++) {
  9291. if (action->colors[i].load_action == SG_LOADACTION_CLEAR) {
  9292. glClearBufferfv(GL_COLOR, i, &action->colors[i].clear_value.r);
  9293. }
  9294. }
  9295. if ((atts == 0) || !_sg_image_ref_null(&atts->cmn.depth_stencil.image)) {
  9296. if (clear_depth && clear_stencil) {
  9297. glClearBufferfi(GL_DEPTH_STENCIL, 0, action->depth.clear_value, action->stencil.clear_value);
  9298. } else if (clear_depth) {
  9299. glClearBufferfv(GL_DEPTH, 0, &action->depth.clear_value);
  9300. } else if (clear_stencil) {
  9301. GLint val = (GLint) action->stencil.clear_value;
  9302. glClearBufferiv(GL_STENCIL, 0, &val);
  9303. }
  9304. }
  9305. // keep store actions for end-pass
  9306. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  9307. _sg.gl.color_store_actions[i] = action->colors[i].store_action;
  9308. }
  9309. _sg.gl.depth_store_action = action->depth.store_action;
  9310. _sg.gl.stencil_store_action = action->stencil.store_action;
  9311. _SG_GL_CHECK_ERROR();
  9312. }
  9313. _SOKOL_PRIVATE void _sg_gl_end_render_pass(void) {
  9314. const _sg_attachments_t* atts = _sg_attachments_ref_ptr_or_null(&_sg.cur_pass.atts);
  9315. if (atts) {
  9316. bool fb_read_bound = false;
  9317. bool fb_draw_bound = false;
  9318. const int num_color_atts = atts->cmn.num_colors;
  9319. for (int i = 0; i < num_color_atts; i++) {
  9320. // perform MSAA resolve if needed
  9321. if (atts->gl.msaa_resolve_framebuffer[i] != 0) {
  9322. if (!fb_read_bound) {
  9323. SOKOL_ASSERT(atts->gl.fb);
  9324. glBindFramebuffer(GL_READ_FRAMEBUFFER, atts->gl.fb);
  9325. fb_read_bound = true;
  9326. }
  9327. const _sg_image_t* img = _sg_image_ref_ptr(&atts->cmn.colors[i].image);
  9328. const int w = img->cmn.width;
  9329. const int h = img->cmn.height;
  9330. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, atts->gl.msaa_resolve_framebuffer[i]);
  9331. glReadBuffer((GLenum)(GL_COLOR_ATTACHMENT0 + i));
  9332. glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  9333. fb_draw_bound = true;
  9334. }
  9335. }
  9336. // invalidate framebuffers
  9337. _SOKOL_UNUSED(fb_draw_bound);
  9338. #if defined(SOKOL_GLES3)
  9339. // need to restore framebuffer binding before invalidate if the MSAA resolve had changed the binding
  9340. if (fb_draw_bound) {
  9341. glBindFramebuffer(GL_FRAMEBUFFER, atts->gl.fb);
  9342. }
  9343. GLenum invalidate_atts[SG_MAX_COLOR_ATTACHMENTS + 2] = { 0 };
  9344. int att_index = 0;
  9345. for (int i = 0; i < num_color_atts; i++) {
  9346. if (_sg.gl.color_store_actions[i] == SG_STOREACTION_DONTCARE) {
  9347. invalidate_atts[att_index++] = (GLenum)(GL_COLOR_ATTACHMENT0 + i);
  9348. }
  9349. }
  9350. if ((_sg.gl.depth_store_action == SG_STOREACTION_DONTCARE) && (_sg.cur_pass.atts->cmn.depth_stencil.image_id.id != SG_INVALID_ID)) {
  9351. invalidate_atts[att_index++] = GL_DEPTH_ATTACHMENT;
  9352. }
  9353. if ((_sg.gl.stencil_store_action == SG_STOREACTION_DONTCARE) && (_sg.cur_pass.atts->cmn.depth_stencil.image_id.id != SG_INVALID_ID)) {
  9354. invalidate_atts[att_index++] = GL_STENCIL_ATTACHMENT;
  9355. }
  9356. if (att_index > 0) {
  9357. glInvalidateFramebuffer(GL_DRAW_FRAMEBUFFER, att_index, invalidate_atts);
  9358. }
  9359. #endif
  9360. }
  9361. }
  9362. _SOKOL_PRIVATE void _sg_gl_end_compute_pass(void) {
  9363. #if defined(_SOKOL_GL_HAS_COMPUTE)
  9364. const _sg_attachments_t* atts = _sg_attachments_ref_ptr_or_null(&_sg.cur_pass.atts);
  9365. if (atts && atts->cmn.has_storage_attachments) {
  9366. glMemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT|GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
  9367. }
  9368. #endif
  9369. }
  9370. _SOKOL_PRIVATE void _sg_gl_end_pass(void) {
  9371. _SG_GL_CHECK_ERROR();
  9372. if (_sg.cur_pass.is_compute) {
  9373. _sg_gl_end_compute_pass();
  9374. } else {
  9375. _sg_gl_end_render_pass();
  9376. }
  9377. _SG_GL_CHECK_ERROR();
  9378. }
  9379. _SOKOL_PRIVATE void _sg_gl_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  9380. y = origin_top_left ? (_sg.cur_pass.height - (y+h)) : y;
  9381. glViewport(x, y, w, h);
  9382. }
  9383. _SOKOL_PRIVATE void _sg_gl_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  9384. y = origin_top_left ? (_sg.cur_pass.height - (y+h)) : y;
  9385. glScissor(x, y, w, h);
  9386. }
  9387. _SOKOL_PRIVATE void _sg_gl_apply_render_pipeline_state(_sg_pipeline_t* pip) {
  9388. // update render pipeline state
  9389. _sg.gl.cache.cur_primitive_type = _sg_gl_primitive_type(pip->gl.primitive_type);
  9390. _sg.gl.cache.cur_index_type = _sg_gl_index_type(pip->cmn.index_type);
  9391. // update depth state
  9392. {
  9393. const sg_depth_state* state_ds = &pip->gl.depth;
  9394. sg_depth_state* cache_ds = &_sg.gl.cache.depth;
  9395. if (state_ds->compare != cache_ds->compare) {
  9396. cache_ds->compare = state_ds->compare;
  9397. glDepthFunc(_sg_gl_compare_func(state_ds->compare));
  9398. _sg_stats_add(gl.num_render_state, 1);
  9399. }
  9400. if (state_ds->write_enabled != cache_ds->write_enabled) {
  9401. cache_ds->write_enabled = state_ds->write_enabled;
  9402. glDepthMask(state_ds->write_enabled);
  9403. _sg_stats_add(gl.num_render_state, 1);
  9404. }
  9405. if (!_sg_fequal(state_ds->bias, cache_ds->bias, 0.000001f) ||
  9406. !_sg_fequal(state_ds->bias_slope_scale, cache_ds->bias_slope_scale, 0.000001f))
  9407. {
  9408. /* according to ANGLE's D3D11 backend:
  9409. D3D11 SlopeScaledDepthBias ==> GL polygonOffsetFactor
  9410. D3D11 DepthBias ==> GL polygonOffsetUnits
  9411. DepthBiasClamp has no meaning on GL
  9412. */
  9413. cache_ds->bias = state_ds->bias;
  9414. cache_ds->bias_slope_scale = state_ds->bias_slope_scale;
  9415. glPolygonOffset(state_ds->bias_slope_scale, state_ds->bias);
  9416. _sg_stats_add(gl.num_render_state, 1);
  9417. bool po_enabled = true;
  9418. if (_sg_fequal(state_ds->bias, 0.0f, 0.000001f) &&
  9419. _sg_fequal(state_ds->bias_slope_scale, 0.0f, 0.000001f))
  9420. {
  9421. po_enabled = false;
  9422. }
  9423. if (po_enabled != _sg.gl.cache.polygon_offset_enabled) {
  9424. _sg.gl.cache.polygon_offset_enabled = po_enabled;
  9425. if (po_enabled) {
  9426. glEnable(GL_POLYGON_OFFSET_FILL);
  9427. } else {
  9428. glDisable(GL_POLYGON_OFFSET_FILL);
  9429. }
  9430. _sg_stats_add(gl.num_render_state, 1);
  9431. }
  9432. }
  9433. }
  9434. // update stencil state
  9435. {
  9436. const sg_stencil_state* state_ss = &pip->gl.stencil;
  9437. sg_stencil_state* cache_ss = &_sg.gl.cache.stencil;
  9438. if (state_ss->enabled != cache_ss->enabled) {
  9439. cache_ss->enabled = state_ss->enabled;
  9440. if (state_ss->enabled) {
  9441. glEnable(GL_STENCIL_TEST);
  9442. } else {
  9443. glDisable(GL_STENCIL_TEST);
  9444. }
  9445. _sg_stats_add(gl.num_render_state, 1);
  9446. }
  9447. if (state_ss->write_mask != cache_ss->write_mask) {
  9448. cache_ss->write_mask = state_ss->write_mask;
  9449. glStencilMask(state_ss->write_mask);
  9450. _sg_stats_add(gl.num_render_state, 1);
  9451. }
  9452. for (int i = 0; i < 2; i++) {
  9453. const sg_stencil_face_state* state_sfs = (i==0)? &state_ss->front : &state_ss->back;
  9454. sg_stencil_face_state* cache_sfs = (i==0)? &cache_ss->front : &cache_ss->back;
  9455. GLenum gl_face = (i==0)? GL_FRONT : GL_BACK;
  9456. if ((state_sfs->compare != cache_sfs->compare) ||
  9457. (state_ss->read_mask != cache_ss->read_mask) ||
  9458. (state_ss->ref != cache_ss->ref))
  9459. {
  9460. cache_sfs->compare = state_sfs->compare;
  9461. glStencilFuncSeparate(gl_face,
  9462. _sg_gl_compare_func(state_sfs->compare),
  9463. state_ss->ref,
  9464. state_ss->read_mask);
  9465. _sg_stats_add(gl.num_render_state, 1);
  9466. }
  9467. if ((state_sfs->fail_op != cache_sfs->fail_op) ||
  9468. (state_sfs->depth_fail_op != cache_sfs->depth_fail_op) ||
  9469. (state_sfs->pass_op != cache_sfs->pass_op))
  9470. {
  9471. cache_sfs->fail_op = state_sfs->fail_op;
  9472. cache_sfs->depth_fail_op = state_sfs->depth_fail_op;
  9473. cache_sfs->pass_op = state_sfs->pass_op;
  9474. glStencilOpSeparate(gl_face,
  9475. _sg_gl_stencil_op(state_sfs->fail_op),
  9476. _sg_gl_stencil_op(state_sfs->depth_fail_op),
  9477. _sg_gl_stencil_op(state_sfs->pass_op));
  9478. _sg_stats_add(gl.num_render_state, 1);
  9479. }
  9480. }
  9481. cache_ss->read_mask = state_ss->read_mask;
  9482. cache_ss->ref = state_ss->ref;
  9483. }
  9484. if (pip->cmn.color_count > 0) {
  9485. // update blend state
  9486. // FIXME: separate blend state per color attachment
  9487. const sg_blend_state* state_bs = &pip->gl.blend;
  9488. sg_blend_state* cache_bs = &_sg.gl.cache.blend;
  9489. if (state_bs->enabled != cache_bs->enabled) {
  9490. cache_bs->enabled = state_bs->enabled;
  9491. if (state_bs->enabled) {
  9492. glEnable(GL_BLEND);
  9493. } else {
  9494. glDisable(GL_BLEND);
  9495. }
  9496. _sg_stats_add(gl.num_render_state, 1);
  9497. }
  9498. if ((state_bs->src_factor_rgb != cache_bs->src_factor_rgb) ||
  9499. (state_bs->dst_factor_rgb != cache_bs->dst_factor_rgb) ||
  9500. (state_bs->src_factor_alpha != cache_bs->src_factor_alpha) ||
  9501. (state_bs->dst_factor_alpha != cache_bs->dst_factor_alpha))
  9502. {
  9503. cache_bs->src_factor_rgb = state_bs->src_factor_rgb;
  9504. cache_bs->dst_factor_rgb = state_bs->dst_factor_rgb;
  9505. cache_bs->src_factor_alpha = state_bs->src_factor_alpha;
  9506. cache_bs->dst_factor_alpha = state_bs->dst_factor_alpha;
  9507. glBlendFuncSeparate(_sg_gl_blend_factor(state_bs->src_factor_rgb),
  9508. _sg_gl_blend_factor(state_bs->dst_factor_rgb),
  9509. _sg_gl_blend_factor(state_bs->src_factor_alpha),
  9510. _sg_gl_blend_factor(state_bs->dst_factor_alpha));
  9511. _sg_stats_add(gl.num_render_state, 1);
  9512. }
  9513. if ((state_bs->op_rgb != cache_bs->op_rgb) || (state_bs->op_alpha != cache_bs->op_alpha)) {
  9514. cache_bs->op_rgb = state_bs->op_rgb;
  9515. cache_bs->op_alpha = state_bs->op_alpha;
  9516. glBlendEquationSeparate(_sg_gl_blend_op(state_bs->op_rgb), _sg_gl_blend_op(state_bs->op_alpha));
  9517. _sg_stats_add(gl.num_render_state, 1);
  9518. }
  9519. // standalone color target state
  9520. for (GLuint i = 0; i < (GLuint)pip->cmn.color_count; i++) {
  9521. if (pip->gl.color_write_mask[i] != _sg.gl.cache.color_write_mask[i]) {
  9522. const sg_color_mask cm = pip->gl.color_write_mask[i];
  9523. _sg.gl.cache.color_write_mask[i] = cm;
  9524. #ifdef SOKOL_GLCORE
  9525. glColorMaski(i,
  9526. (cm & SG_COLORMASK_R) != 0,
  9527. (cm & SG_COLORMASK_G) != 0,
  9528. (cm & SG_COLORMASK_B) != 0,
  9529. (cm & SG_COLORMASK_A) != 0);
  9530. #else
  9531. if (0 == i) {
  9532. glColorMask((cm & SG_COLORMASK_R) != 0,
  9533. (cm & SG_COLORMASK_G) != 0,
  9534. (cm & SG_COLORMASK_B) != 0,
  9535. (cm & SG_COLORMASK_A) != 0);
  9536. }
  9537. #endif
  9538. _sg_stats_add(gl.num_render_state, 1);
  9539. }
  9540. }
  9541. if (!_sg_fequal(pip->cmn.blend_color.r, _sg.gl.cache.blend_color.r, 0.0001f) ||
  9542. !_sg_fequal(pip->cmn.blend_color.g, _sg.gl.cache.blend_color.g, 0.0001f) ||
  9543. !_sg_fequal(pip->cmn.blend_color.b, _sg.gl.cache.blend_color.b, 0.0001f) ||
  9544. !_sg_fequal(pip->cmn.blend_color.a, _sg.gl.cache.blend_color.a, 0.0001f))
  9545. {
  9546. sg_color c = pip->cmn.blend_color;
  9547. _sg.gl.cache.blend_color = c;
  9548. glBlendColor(c.r, c.g, c.b, c.a);
  9549. _sg_stats_add(gl.num_render_state, 1);
  9550. }
  9551. } // pip->cmn.color_count > 0
  9552. if (pip->gl.cull_mode != _sg.gl.cache.cull_mode) {
  9553. _sg.gl.cache.cull_mode = pip->gl.cull_mode;
  9554. if (SG_CULLMODE_NONE == pip->gl.cull_mode) {
  9555. glDisable(GL_CULL_FACE);
  9556. _sg_stats_add(gl.num_render_state, 1);
  9557. } else {
  9558. glEnable(GL_CULL_FACE);
  9559. GLenum gl_mode = (SG_CULLMODE_FRONT == pip->gl.cull_mode) ? GL_FRONT : GL_BACK;
  9560. glCullFace(gl_mode);
  9561. _sg_stats_add(gl.num_render_state, 2);
  9562. }
  9563. }
  9564. if (pip->gl.face_winding != _sg.gl.cache.face_winding) {
  9565. _sg.gl.cache.face_winding = pip->gl.face_winding;
  9566. GLenum gl_winding = (SG_FACEWINDING_CW == pip->gl.face_winding) ? GL_CW : GL_CCW;
  9567. glFrontFace(gl_winding);
  9568. _sg_stats_add(gl.num_render_state, 1);
  9569. }
  9570. if (pip->gl.alpha_to_coverage_enabled != _sg.gl.cache.alpha_to_coverage_enabled) {
  9571. _sg.gl.cache.alpha_to_coverage_enabled = pip->gl.alpha_to_coverage_enabled;
  9572. if (pip->gl.alpha_to_coverage_enabled) {
  9573. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  9574. } else {
  9575. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  9576. }
  9577. _sg_stats_add(gl.num_render_state, 1);
  9578. }
  9579. #ifdef SOKOL_GLCORE
  9580. if (pip->gl.sample_count != _sg.gl.cache.sample_count) {
  9581. _sg.gl.cache.sample_count = pip->gl.sample_count;
  9582. if (pip->gl.sample_count > 1) {
  9583. glEnable(GL_MULTISAMPLE);
  9584. } else {
  9585. glDisable(GL_MULTISAMPLE);
  9586. }
  9587. _sg_stats_add(gl.num_render_state, 1);
  9588. }
  9589. #endif
  9590. }
  9591. _SOKOL_PRIVATE void _sg_gl_apply_compute_pipeline_state(_sg_pipeline_t* pip) {
  9592. #if defined(_SOKOL_GL_HAS_COMPUTE)
  9593. // apply storage attachment images (if any)
  9594. const _sg_attachments_t* atts = _sg_attachments_ref_ptr_or_null(&_sg.cur_pass.atts);
  9595. if (atts) {
  9596. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  9597. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  9598. if (shd->cmn.storage_images[i].stage == SG_SHADERSTAGE_NONE) {
  9599. continue;
  9600. }
  9601. SOKOL_ASSERT(shd->cmn.storage_images[i].stage == SG_SHADERSTAGE_COMPUTE);
  9602. SOKOL_ASSERT(shd->gl.simg_binding[i] < _SG_GL_MAX_SIMG_BINDINGS);
  9603. _sg_image_t* img = _sg_image_ref_ptr(&atts->cmn.storages[i].image);
  9604. GLuint gl_unit = shd->gl.simg_binding[i];
  9605. GLuint gl_tex = img->gl.tex[img->cmn.active_slot];
  9606. GLint level = atts->cmn.storages[i].mip_level;
  9607. GLint layer = atts->cmn.storages[i].slice;
  9608. GLboolean layered = shd->cmn.storage_images[i].image_type != SG_IMAGETYPE_2D;
  9609. GLenum access = shd->cmn.storage_images[i].writeonly ? GL_WRITE_ONLY : GL_READ_WRITE;
  9610. GLenum format = _sg_gl_teximage_internal_format(shd->cmn.storage_images[i].access_format);
  9611. // FIXME: go through state cache, use attachment id as key
  9612. glBindImageTexture(gl_unit, gl_tex, level, layered, layer, access, format);
  9613. _SG_GL_CHECK_ERROR();
  9614. }
  9615. }
  9616. #else
  9617. _SOKOL_UNUSED(pip);
  9618. #endif
  9619. }
  9620. _SOKOL_PRIVATE void _sg_gl_apply_pipeline(_sg_pipeline_t* pip) {
  9621. SOKOL_ASSERT(pip);
  9622. _SG_GL_CHECK_ERROR();
  9623. if (!_sg_sref_eql(&_sg.gl.cache.cur_pip, &pip->slot)) {
  9624. _sg.gl.cache.cur_pip = _sg_sref(&pip->slot);
  9625. // bind shader program
  9626. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  9627. if (shd->gl.prog != _sg.gl.cache.prog) {
  9628. _sg.gl.cache.prog = shd->gl.prog;
  9629. glUseProgram(shd->gl.prog);
  9630. _sg_stats_add(gl.num_use_program, 1);
  9631. }
  9632. if (pip->cmn.is_compute) {
  9633. _sg_gl_apply_compute_pipeline_state(pip);
  9634. } else {
  9635. _sg_gl_apply_render_pipeline_state(pip);
  9636. }
  9637. }
  9638. _SG_GL_CHECK_ERROR();
  9639. }
  9640. #if defined(_SOKOL_GL_HAS_COMPUTE)
  9641. _SOKOL_PRIVATE void _sg_gl_handle_memory_barriers(const _sg_shader_t* shd, const _sg_bindings_ptrs_t* bnd) {
  9642. if (!_sg.features.compute) {
  9643. return;
  9644. }
  9645. GLbitfield gl_barrier_bits = 0;
  9646. // if vertex-, index- or storage-buffer bindings have been written
  9647. // by a compute shader before, a barrier must be issued
  9648. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  9649. _sg_buffer_t* buf = bnd->vbs[i];
  9650. if (!buf) {
  9651. continue;
  9652. }
  9653. if (buf->gl.gpu_dirty_flags & _SG_GL_GPUDIRTY_VERTEXBUFFER) {
  9654. gl_barrier_bits |= GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT;
  9655. buf->gl.gpu_dirty_flags &= (uint8_t)~_SG_GL_GPUDIRTY_VERTEXBUFFER;
  9656. }
  9657. }
  9658. if (bnd->ib) {
  9659. _sg_buffer_t* buf = bnd->ib;
  9660. if (buf->gl.gpu_dirty_flags & _SG_GL_GPUDIRTY_INDEXBUFFER) {
  9661. gl_barrier_bits |= GL_ELEMENT_ARRAY_BARRIER_BIT;
  9662. buf->gl.gpu_dirty_flags &= (uint8_t)~_SG_GL_GPUDIRTY_INDEXBUFFER;
  9663. }
  9664. }
  9665. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  9666. _sg_buffer_t* buf = bnd->sbufs[i];
  9667. if (!buf) {
  9668. continue;
  9669. }
  9670. SOKOL_ASSERT(shd->cmn.storage_buffers[i].stage != SG_SHADERSTAGE_NONE);
  9671. if (buf->gl.gpu_dirty_flags & _SG_GL_GPUDIRTY_STORAGEBUFFER) {
  9672. gl_barrier_bits |= GL_SHADER_STORAGE_BARRIER_BIT;
  9673. buf->gl.gpu_dirty_flags &= (uint8_t)~_SG_GL_GPUDIRTY_STORAGEBUFFER;
  9674. }
  9675. }
  9676. // mark storage buffers as dirty which will be written by compute shaders
  9677. // (don't merge this into the above loop, this would mess up the dirty
  9678. // dirty flags if the same buffer is bound multiple times)
  9679. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  9680. _sg_buffer_t* buf = bnd->sbufs[i];
  9681. if (!buf) {
  9682. continue;
  9683. }
  9684. if (!shd->cmn.storage_buffers[i].readonly) {
  9685. buf->gl.gpu_dirty_flags = _SG_GL_GPUDIRTY_BUFFER_ALL;
  9686. }
  9687. }
  9688. if (0 != gl_barrier_bits) {
  9689. glMemoryBarrier(gl_barrier_bits);
  9690. _sg_stats_add(gl.num_memory_barriers, 1);
  9691. }
  9692. }
  9693. #endif
  9694. _SOKOL_PRIVATE bool _sg_gl_apply_bindings(_sg_bindings_ptrs_t* bnd) {
  9695. SOKOL_ASSERT(bnd);
  9696. SOKOL_ASSERT(bnd->pip);
  9697. _SG_GL_CHECK_ERROR();
  9698. const _sg_shader_t* shd = _sg_shader_ref_ptr(&bnd->pip->cmn.shader);
  9699. // bind combined image-samplers
  9700. _SG_GL_CHECK_ERROR();
  9701. for (size_t img_smp_index = 0; img_smp_index < SG_MAX_IMAGE_SAMPLER_PAIRS; img_smp_index++) {
  9702. const _sg_shader_image_sampler_t* img_smp = &shd->cmn.image_samplers[img_smp_index];
  9703. if (img_smp->stage == SG_SHADERSTAGE_NONE) {
  9704. continue;
  9705. }
  9706. const int8_t gl_tex_slot = (GLint)shd->gl.tex_slot[img_smp_index];
  9707. if (gl_tex_slot != -1) {
  9708. SOKOL_ASSERT(img_smp->image_slot < SG_MAX_IMAGE_BINDSLOTS);
  9709. SOKOL_ASSERT(img_smp->sampler_slot < SG_MAX_SAMPLER_BINDSLOTS);
  9710. const _sg_image_t* img = bnd->imgs[img_smp->image_slot];
  9711. const _sg_sampler_t* smp = bnd->smps[img_smp->sampler_slot];
  9712. SOKOL_ASSERT(img);
  9713. SOKOL_ASSERT(smp);
  9714. const GLenum gl_tgt = img->gl.target;
  9715. const GLuint gl_tex = img->gl.tex[img->cmn.active_slot];
  9716. const GLuint gl_smp = smp->gl.smp;
  9717. _sg_gl_cache_bind_texture_sampler(gl_tex_slot, gl_tgt, gl_tex, gl_smp);
  9718. }
  9719. }
  9720. _SG_GL_CHECK_ERROR();
  9721. // bind storage buffers
  9722. for (size_t sbuf_index = 0; sbuf_index < SG_MAX_STORAGEBUFFER_BINDSLOTS; sbuf_index++) {
  9723. if (shd->cmn.storage_buffers[sbuf_index].stage == SG_SHADERSTAGE_NONE) {
  9724. continue;
  9725. }
  9726. const _sg_buffer_t* sbuf = bnd->sbufs[sbuf_index];
  9727. const uint8_t binding = shd->gl.sbuf_binding[sbuf_index];
  9728. GLuint gl_sbuf = sbuf->gl.buf[sbuf->cmn.active_slot];
  9729. _sg_gl_cache_bind_storage_buffer(binding, gl_sbuf);
  9730. }
  9731. _SG_GL_CHECK_ERROR();
  9732. if (!bnd->pip->cmn.is_compute) {
  9733. // index buffer (can be 0)
  9734. const GLuint gl_ib = bnd->ib ? bnd->ib->gl.buf[bnd->ib->cmn.active_slot] : 0;
  9735. _sg_gl_cache_bind_buffer(GL_ELEMENT_ARRAY_BUFFER, gl_ib);
  9736. _sg.gl.cache.cur_ib_offset = bnd->ib_offset;
  9737. // vertex attributes
  9738. for (GLuint attr_index = 0; attr_index < (GLuint)_sg.limits.max_vertex_attrs; attr_index++) {
  9739. _sg_gl_attr_t* attr = &bnd->pip->gl.attrs[attr_index];
  9740. _sg_gl_cache_attr_t* cache_attr = &_sg.gl.cache.attrs[attr_index];
  9741. bool cache_attr_dirty = false;
  9742. int vb_offset = 0;
  9743. GLuint gl_vb = 0;
  9744. if (attr->vb_index >= 0) {
  9745. // attribute is enabled
  9746. SOKOL_ASSERT(attr->vb_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  9747. _sg_buffer_t* vb = bnd->vbs[attr->vb_index];
  9748. SOKOL_ASSERT(vb);
  9749. gl_vb = vb->gl.buf[vb->cmn.active_slot];
  9750. vb_offset = bnd->vb_offsets[attr->vb_index] + attr->offset;
  9751. if ((gl_vb != cache_attr->gl_vbuf) ||
  9752. (attr->size != cache_attr->gl_attr.size) ||
  9753. (attr->type != cache_attr->gl_attr.type) ||
  9754. (attr->normalized != cache_attr->gl_attr.normalized) ||
  9755. (attr->base_type != cache_attr->gl_attr.base_type) ||
  9756. (attr->stride != cache_attr->gl_attr.stride) ||
  9757. (vb_offset != cache_attr->gl_attr.offset) ||
  9758. (cache_attr->gl_attr.divisor != attr->divisor))
  9759. {
  9760. _sg_gl_cache_bind_buffer(GL_ARRAY_BUFFER, gl_vb);
  9761. if (attr->base_type == SG_SHADERATTRBASETYPE_FLOAT) {
  9762. glVertexAttribPointer(attr_index, attr->size, attr->type, attr->normalized, attr->stride, (const GLvoid*)(GLintptr)vb_offset);
  9763. } else {
  9764. glVertexAttribIPointer(attr_index, attr->size, attr->type, attr->stride, (const GLvoid*)(GLintptr)vb_offset);
  9765. }
  9766. _sg_stats_add(gl.num_vertex_attrib_pointer, 1);
  9767. glVertexAttribDivisor(attr_index, (GLuint)attr->divisor);
  9768. _sg_stats_add(gl.num_vertex_attrib_divisor, 1);
  9769. cache_attr_dirty = true;
  9770. }
  9771. if (cache_attr->gl_attr.vb_index == -1) {
  9772. glEnableVertexAttribArray(attr_index);
  9773. _sg_stats_add(gl.num_enable_vertex_attrib_array, 1);
  9774. cache_attr_dirty = true;
  9775. }
  9776. } else {
  9777. // attribute is disabled
  9778. if (cache_attr->gl_attr.vb_index != -1) {
  9779. glDisableVertexAttribArray(attr_index);
  9780. _sg_stats_add(gl.num_disable_vertex_attrib_array, 1);
  9781. cache_attr_dirty = true;
  9782. }
  9783. }
  9784. if (cache_attr_dirty) {
  9785. cache_attr->gl_attr = *attr;
  9786. cache_attr->gl_attr.offset = vb_offset;
  9787. cache_attr->gl_vbuf = gl_vb;
  9788. }
  9789. }
  9790. _SG_GL_CHECK_ERROR();
  9791. }
  9792. // take care of storage buffer memory barriers (this needs to happen after the bindings are set)
  9793. #if defined(_SOKOL_GL_HAS_COMPUTE)
  9794. _sg_gl_handle_memory_barriers(shd, bnd);
  9795. _SG_GL_CHECK_ERROR();
  9796. #endif
  9797. return true;
  9798. }
  9799. _SOKOL_PRIVATE void _sg_gl_apply_uniforms(int ub_slot, const sg_range* data) {
  9800. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  9801. const _sg_pipeline_t* pip = _sg_pipeline_ref_ptr(&_sg.cur_pip);
  9802. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  9803. SOKOL_ASSERT(SG_SHADERSTAGE_NONE != shd->cmn.uniform_blocks[ub_slot].stage);
  9804. SOKOL_ASSERT(data->size == shd->cmn.uniform_blocks[ub_slot].size);
  9805. const _sg_gl_uniform_block_t* gl_ub = &shd->gl.uniform_blocks[ub_slot];
  9806. for (int u_index = 0; u_index < gl_ub->num_uniforms; u_index++) {
  9807. const _sg_gl_uniform_t* u = &gl_ub->uniforms[u_index];
  9808. SOKOL_ASSERT(u->type != SG_UNIFORMTYPE_INVALID);
  9809. if (u->gl_loc == -1) {
  9810. continue;
  9811. }
  9812. _sg_stats_add(gl.num_uniform, 1);
  9813. GLfloat* fptr = (GLfloat*) (((uint8_t*)data->ptr) + u->offset);
  9814. GLint* iptr = (GLint*) (((uint8_t*)data->ptr) + u->offset);
  9815. switch (u->type) {
  9816. case SG_UNIFORMTYPE_INVALID:
  9817. break;
  9818. case SG_UNIFORMTYPE_FLOAT:
  9819. glUniform1fv(u->gl_loc, u->count, fptr);
  9820. break;
  9821. case SG_UNIFORMTYPE_FLOAT2:
  9822. glUniform2fv(u->gl_loc, u->count, fptr);
  9823. break;
  9824. case SG_UNIFORMTYPE_FLOAT3:
  9825. glUniform3fv(u->gl_loc, u->count, fptr);
  9826. break;
  9827. case SG_UNIFORMTYPE_FLOAT4:
  9828. glUniform4fv(u->gl_loc, u->count, fptr);
  9829. break;
  9830. case SG_UNIFORMTYPE_INT:
  9831. glUniform1iv(u->gl_loc, u->count, iptr);
  9832. break;
  9833. case SG_UNIFORMTYPE_INT2:
  9834. glUniform2iv(u->gl_loc, u->count, iptr);
  9835. break;
  9836. case SG_UNIFORMTYPE_INT3:
  9837. glUniform3iv(u->gl_loc, u->count, iptr);
  9838. break;
  9839. case SG_UNIFORMTYPE_INT4:
  9840. glUniform4iv(u->gl_loc, u->count, iptr);
  9841. break;
  9842. case SG_UNIFORMTYPE_MAT4:
  9843. glUniformMatrix4fv(u->gl_loc, u->count, GL_FALSE, fptr);
  9844. break;
  9845. default:
  9846. SOKOL_UNREACHABLE;
  9847. break;
  9848. }
  9849. }
  9850. }
  9851. _SOKOL_PRIVATE void _sg_gl_draw(int base_element, int num_elements, int num_instances) {
  9852. const GLenum i_type = _sg.gl.cache.cur_index_type;
  9853. const GLenum p_type = _sg.gl.cache.cur_primitive_type;
  9854. const bool use_instanced_draw = (num_instances > 1) || _sg_pipeline_ref_ptr(&_sg.cur_pip)->cmn.use_instanced_draw;
  9855. if (0 != i_type) {
  9856. // indexed rendering
  9857. const int i_size = (i_type == GL_UNSIGNED_SHORT) ? 2 : 4;
  9858. const int ib_offset = _sg.gl.cache.cur_ib_offset;
  9859. const GLvoid* indices = (const GLvoid*)(GLintptr)(base_element*i_size+ib_offset);
  9860. if (use_instanced_draw) {
  9861. glDrawElementsInstanced(p_type, num_elements, i_type, indices, num_instances);
  9862. } else {
  9863. glDrawElements(p_type, num_elements, i_type, indices);
  9864. }
  9865. } else {
  9866. // non-indexed rendering
  9867. if (use_instanced_draw) {
  9868. glDrawArraysInstanced(p_type, base_element, num_elements, num_instances);
  9869. } else {
  9870. glDrawArrays(p_type, base_element, num_elements);
  9871. }
  9872. }
  9873. }
  9874. _SOKOL_PRIVATE void _sg_gl_dispatch(int num_groups_x, int num_groups_y, int num_groups_z) {
  9875. #if defined(_SOKOL_GL_HAS_COMPUTE)
  9876. if (!_sg.features.compute) {
  9877. return;
  9878. }
  9879. glDispatchCompute((GLuint)num_groups_x, (GLuint)num_groups_y, (GLuint)num_groups_z);
  9880. #else
  9881. (void)num_groups_x; (void)num_groups_y; (void)num_groups_z;
  9882. #endif
  9883. }
  9884. _SOKOL_PRIVATE void _sg_gl_commit(void) {
  9885. // "soft" clear bindings (only those that are actually bound)
  9886. _sg_gl_cache_clear_buffer_bindings(false);
  9887. _sg_gl_cache_clear_texture_sampler_bindings(false);
  9888. }
  9889. _SOKOL_PRIVATE void _sg_gl_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  9890. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  9891. // only one update per buffer per frame allowed
  9892. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  9893. buf->cmn.active_slot = 0;
  9894. }
  9895. GLenum gl_tgt = _sg_gl_buffer_target(&buf->cmn.usage);
  9896. SOKOL_ASSERT(buf->cmn.active_slot < SG_NUM_INFLIGHT_FRAMES);
  9897. GLuint gl_buf = buf->gl.buf[buf->cmn.active_slot];
  9898. SOKOL_ASSERT(gl_buf);
  9899. _SG_GL_CHECK_ERROR();
  9900. _sg_gl_cache_store_buffer_binding(gl_tgt);
  9901. _sg_gl_cache_bind_buffer(gl_tgt, gl_buf);
  9902. glBufferSubData(gl_tgt, 0, (GLsizeiptr)data->size, data->ptr);
  9903. _sg_gl_cache_restore_buffer_binding(gl_tgt);
  9904. _SG_GL_CHECK_ERROR();
  9905. }
  9906. _SOKOL_PRIVATE void _sg_gl_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  9907. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  9908. if (new_frame) {
  9909. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  9910. buf->cmn.active_slot = 0;
  9911. }
  9912. }
  9913. GLenum gl_tgt = _sg_gl_buffer_target(&buf->cmn.usage);
  9914. SOKOL_ASSERT(buf->cmn.active_slot < SG_NUM_INFLIGHT_FRAMES);
  9915. GLuint gl_buf = buf->gl.buf[buf->cmn.active_slot];
  9916. SOKOL_ASSERT(gl_buf);
  9917. _SG_GL_CHECK_ERROR();
  9918. _sg_gl_cache_store_buffer_binding(gl_tgt);
  9919. _sg_gl_cache_bind_buffer(gl_tgt, gl_buf);
  9920. glBufferSubData(gl_tgt, buf->cmn.append_pos, (GLsizeiptr)data->size, data->ptr);
  9921. _sg_gl_cache_restore_buffer_binding(gl_tgt);
  9922. _SG_GL_CHECK_ERROR();
  9923. }
  9924. _SOKOL_PRIVATE void _sg_gl_update_image(_sg_image_t* img, const sg_image_data* data) {
  9925. SOKOL_ASSERT(img && data);
  9926. // only one update per image per frame allowed
  9927. if (++img->cmn.active_slot >= img->cmn.num_slots) {
  9928. img->cmn.active_slot = 0;
  9929. }
  9930. SOKOL_ASSERT(img->cmn.active_slot < SG_NUM_INFLIGHT_FRAMES);
  9931. SOKOL_ASSERT(0 != img->gl.tex[img->cmn.active_slot]);
  9932. _sg_gl_cache_store_texture_sampler_binding(0);
  9933. _sg_gl_cache_bind_texture_sampler(0, img->gl.target, img->gl.tex[img->cmn.active_slot], 0);
  9934. const GLenum gl_img_format = _sg_gl_teximage_format(img->cmn.pixel_format);
  9935. const GLenum gl_img_type = _sg_gl_teximage_type(img->cmn.pixel_format);
  9936. const int num_faces = img->cmn.type == SG_IMAGETYPE_CUBE ? 6 : 1;
  9937. const int num_mips = img->cmn.num_mipmaps;
  9938. for (int face_index = 0; face_index < num_faces; face_index++) {
  9939. for (int mip_index = 0; mip_index < num_mips; mip_index++) {
  9940. GLenum gl_img_target = img->gl.target;
  9941. if (SG_IMAGETYPE_CUBE == img->cmn.type) {
  9942. gl_img_target = _sg_gl_cubeface_target(face_index);
  9943. }
  9944. const GLvoid* data_ptr = data->subimage[face_index][mip_index].ptr;
  9945. int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  9946. int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  9947. if ((SG_IMAGETYPE_2D == img->cmn.type) || (SG_IMAGETYPE_CUBE == img->cmn.type)) {
  9948. glTexSubImage2D(gl_img_target, mip_index,
  9949. 0, 0,
  9950. mip_width, mip_height,
  9951. gl_img_format, gl_img_type,
  9952. data_ptr);
  9953. } else if ((SG_IMAGETYPE_3D == img->cmn.type) || (SG_IMAGETYPE_ARRAY == img->cmn.type)) {
  9954. int mip_depth = img->cmn.num_slices;
  9955. if (SG_IMAGETYPE_3D == img->cmn.type) {
  9956. mip_depth = _sg_miplevel_dim(img->cmn.num_slices, mip_index);
  9957. }
  9958. glTexSubImage3D(gl_img_target, mip_index,
  9959. 0, 0, 0,
  9960. mip_width, mip_height, mip_depth,
  9961. gl_img_format, gl_img_type,
  9962. data_ptr);
  9963. }
  9964. }
  9965. }
  9966. _sg_gl_cache_restore_texture_sampler_binding(0);
  9967. }
  9968. // ██████ ██████ ██████ ██ ██ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  9969. // ██ ██ ██ ██ ██ ███ ███ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  9970. // ██ ██ █████ ██ ██ ██ ██ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  9971. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  9972. // ██████ ██████ ██████ ██ ██ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  9973. //
  9974. // >>d3d11 backend
  9975. #elif defined(SOKOL_D3D11)
  9976. #if defined(__cplusplus)
  9977. #define _sg_d3d11_AddRef(self) (self)->AddRef()
  9978. #else
  9979. #define _sg_d3d11_AddRef(self) (self)->lpVtbl->AddRef(self)
  9980. #endif
  9981. #if defined(__cplusplus)
  9982. #define _sg_d3d11_Release(self) (self)->Release()
  9983. #else
  9984. #define _sg_d3d11_Release(self) (self)->lpVtbl->Release(self)
  9985. #endif
  9986. // NOTE: This needs to be a macro since we can't use the polymorphism in C. It's called on many kinds of resources.
  9987. // NOTE: Based on microsoft docs, it's fine to call this with pData=NULL if DataSize is also zero.
  9988. #if defined(__cplusplus)
  9989. #define _sg_d3d11_SetPrivateData(self, guid, DataSize, pData) (self)->SetPrivateData(guid, DataSize, pData)
  9990. #else
  9991. #define _sg_d3d11_SetPrivateData(self, guid, DataSize, pData) (self)->lpVtbl->SetPrivateData(self, guid, DataSize, pData)
  9992. #endif
  9993. #if defined(__cplusplus)
  9994. #define _sg_win32_refguid(guid) guid
  9995. #else
  9996. #define _sg_win32_refguid(guid) &guid
  9997. #endif
  9998. static const GUID _sg_d3d11_WKPDID_D3DDebugObjectName = { 0x429b8c22,0x9188,0x4b0c, {0x87,0x42,0xac,0xb0,0xbf,0x85,0xc2,0x00} };
  9999. #if defined(SOKOL_DEBUG)
  10000. #define _sg_d3d11_setlabel(self, label) _sg_d3d11_SetPrivateData(self, _sg_win32_refguid(_sg_d3d11_WKPDID_D3DDebugObjectName), label ? (UINT)strlen(label) : 0, label)
  10001. #else
  10002. #define _sg_d3d11_setlabel(self, label)
  10003. #endif
  10004. //-- D3D11 C/C++ wrappers ------------------------------------------------------
  10005. static inline HRESULT _sg_d3d11_CheckFormatSupport(ID3D11Device* self, DXGI_FORMAT Format, UINT* pFormatSupport) {
  10006. #if defined(__cplusplus)
  10007. return self->CheckFormatSupport(Format, pFormatSupport);
  10008. #else
  10009. return self->lpVtbl->CheckFormatSupport(self, Format, pFormatSupport);
  10010. #endif
  10011. }
  10012. static inline void _sg_d3d11_OMSetRenderTargets(ID3D11DeviceContext* self, UINT NumViews, ID3D11RenderTargetView* const* ppRenderTargetViews, ID3D11DepthStencilView *pDepthStencilView) {
  10013. #if defined(__cplusplus)
  10014. self->OMSetRenderTargets(NumViews, ppRenderTargetViews, pDepthStencilView);
  10015. #else
  10016. self->lpVtbl->OMSetRenderTargets(self, NumViews, ppRenderTargetViews, pDepthStencilView);
  10017. #endif
  10018. }
  10019. static inline void _sg_d3d11_RSSetState(ID3D11DeviceContext* self, ID3D11RasterizerState* pRasterizerState) {
  10020. #if defined(__cplusplus)
  10021. self->RSSetState(pRasterizerState);
  10022. #else
  10023. self->lpVtbl->RSSetState(self, pRasterizerState);
  10024. #endif
  10025. }
  10026. static inline void _sg_d3d11_OMSetDepthStencilState(ID3D11DeviceContext* self, ID3D11DepthStencilState* pDepthStencilState, UINT StencilRef) {
  10027. #if defined(__cplusplus)
  10028. self->OMSetDepthStencilState(pDepthStencilState, StencilRef);
  10029. #else
  10030. self->lpVtbl->OMSetDepthStencilState(self, pDepthStencilState, StencilRef);
  10031. #endif
  10032. }
  10033. static inline void _sg_d3d11_OMSetBlendState(ID3D11DeviceContext* self, ID3D11BlendState* pBlendState, const FLOAT BlendFactor[4], UINT SampleMask) {
  10034. #if defined(__cplusplus)
  10035. self->OMSetBlendState(pBlendState, BlendFactor, SampleMask);
  10036. #else
  10037. self->lpVtbl->OMSetBlendState(self, pBlendState, BlendFactor, SampleMask);
  10038. #endif
  10039. }
  10040. static inline void _sg_d3d11_IASetVertexBuffers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppVertexBuffers, const UINT* pStrides, const UINT* pOffsets) {
  10041. #if defined(__cplusplus)
  10042. self->IASetVertexBuffers(StartSlot, NumBuffers, ppVertexBuffers, pStrides, pOffsets);
  10043. #else
  10044. self->lpVtbl->IASetVertexBuffers(self, StartSlot, NumBuffers, ppVertexBuffers, pStrides, pOffsets);
  10045. #endif
  10046. }
  10047. static inline void _sg_d3d11_IASetIndexBuffer(ID3D11DeviceContext* self, ID3D11Buffer* pIndexBuffer, DXGI_FORMAT Format, UINT Offset) {
  10048. #if defined(__cplusplus)
  10049. self->IASetIndexBuffer(pIndexBuffer, Format, Offset);
  10050. #else
  10051. self->lpVtbl->IASetIndexBuffer(self, pIndexBuffer, Format, Offset);
  10052. #endif
  10053. }
  10054. static inline void _sg_d3d11_IASetInputLayout(ID3D11DeviceContext* self, ID3D11InputLayout* pInputLayout) {
  10055. #if defined(__cplusplus)
  10056. self->IASetInputLayout(pInputLayout);
  10057. #else
  10058. self->lpVtbl->IASetInputLayout(self, pInputLayout);
  10059. #endif
  10060. }
  10061. static inline void _sg_d3d11_VSSetShader(ID3D11DeviceContext* self, ID3D11VertexShader* pVertexShader, ID3D11ClassInstance* const* ppClassInstances, UINT NumClassInstances) {
  10062. #if defined(__cplusplus)
  10063. self->VSSetShader(pVertexShader, ppClassInstances, NumClassInstances);
  10064. #else
  10065. self->lpVtbl->VSSetShader(self, pVertexShader, ppClassInstances, NumClassInstances);
  10066. #endif
  10067. }
  10068. static inline void _sg_d3d11_PSSetShader(ID3D11DeviceContext* self, ID3D11PixelShader* pPixelShader, ID3D11ClassInstance* const* ppClassInstances, UINT NumClassInstances) {
  10069. #if defined(__cplusplus)
  10070. self->PSSetShader(pPixelShader, ppClassInstances, NumClassInstances);
  10071. #else
  10072. self->lpVtbl->PSSetShader(self, pPixelShader, ppClassInstances, NumClassInstances);
  10073. #endif
  10074. }
  10075. static inline void _sg_d3d11_CSSetShader(ID3D11DeviceContext* self, ID3D11ComputeShader* pComputeShader, ID3D11ClassInstance* const* ppClassInstances, UINT NumClassInstances) {
  10076. #if defined(__cplusplus)
  10077. self->CSSetShader(pComputeShader, ppClassInstances, NumClassInstances);
  10078. #else
  10079. self->lpVtbl->CSSetShader(self, pComputeShader, ppClassInstances, NumClassInstances);
  10080. #endif
  10081. }
  10082. static inline void _sg_d3d11_VSSetConstantBuffers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppConstantBuffers) {
  10083. #if defined(__cplusplus)
  10084. self->VSSetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers);
  10085. #else
  10086. self->lpVtbl->VSSetConstantBuffers(self, StartSlot, NumBuffers, ppConstantBuffers);
  10087. #endif
  10088. }
  10089. static inline void _sg_d3d11_PSSetConstantBuffers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppConstantBuffers) {
  10090. #if defined(__cplusplus)
  10091. self->PSSetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers);
  10092. #else
  10093. self->lpVtbl->PSSetConstantBuffers(self, StartSlot, NumBuffers, ppConstantBuffers);
  10094. #endif
  10095. }
  10096. static inline void _sg_d3d11_CSSetConstantBuffers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppConstantBuffers) {
  10097. #if defined(__cplusplus)
  10098. self->CSSetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers);
  10099. #else
  10100. self->lpVtbl->CSSetConstantBuffers(self, StartSlot, NumBuffers, ppConstantBuffers);
  10101. #endif
  10102. }
  10103. static inline void _sg_d3d11_VSSetShaderResources(ID3D11DeviceContext* self, UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView* const* ppShaderResourceViews) {
  10104. #if defined(__cplusplus)
  10105. self->VSSetShaderResources(StartSlot, NumViews, ppShaderResourceViews);
  10106. #else
  10107. self->lpVtbl->VSSetShaderResources(self, StartSlot, NumViews, ppShaderResourceViews);
  10108. #endif
  10109. }
  10110. static inline void _sg_d3d11_PSSetShaderResources(ID3D11DeviceContext* self, UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView* const* ppShaderResourceViews) {
  10111. #if defined(__cplusplus)
  10112. self->PSSetShaderResources(StartSlot, NumViews, ppShaderResourceViews);
  10113. #else
  10114. self->lpVtbl->PSSetShaderResources(self, StartSlot, NumViews, ppShaderResourceViews);
  10115. #endif
  10116. }
  10117. static inline void _sg_d3d11_CSSetShaderResources(ID3D11DeviceContext* self, UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView* const* ppShaderResourceViews) {
  10118. #if defined(__cplusplus)
  10119. self->CSSetShaderResources(StartSlot, NumViews, ppShaderResourceViews);
  10120. #else
  10121. self->lpVtbl->CSSetShaderResources(self, StartSlot, NumViews, ppShaderResourceViews);
  10122. #endif
  10123. }
  10124. static inline void _sg_d3d11_VSSetSamplers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumSamplers, ID3D11SamplerState* const* ppSamplers) {
  10125. #if defined(__cplusplus)
  10126. self->VSSetSamplers(StartSlot, NumSamplers, ppSamplers);
  10127. #else
  10128. self->lpVtbl->VSSetSamplers(self, StartSlot, NumSamplers, ppSamplers);
  10129. #endif
  10130. }
  10131. static inline void _sg_d3d11_PSSetSamplers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumSamplers, ID3D11SamplerState* const* ppSamplers) {
  10132. #if defined(__cplusplus)
  10133. self->PSSetSamplers(StartSlot, NumSamplers, ppSamplers);
  10134. #else
  10135. self->lpVtbl->PSSetSamplers(self, StartSlot, NumSamplers, ppSamplers);
  10136. #endif
  10137. }
  10138. static inline void _sg_d3d11_CSSetSamplers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumSamplers, ID3D11SamplerState* const* ppSamplers) {
  10139. #if defined(__cplusplus)
  10140. self->CSSetSamplers(StartSlot, NumSamplers, ppSamplers);
  10141. #else
  10142. self->lpVtbl->CSSetSamplers(self, StartSlot, NumSamplers, ppSamplers);
  10143. #endif
  10144. }
  10145. static inline void _sg_d3d11_CSSetUnorderedAccessViews(ID3D11DeviceContext* self, UINT StartSlot, UINT NumUAVs, ID3D11UnorderedAccessView* const* ppUnorderedAccessViews, const UINT* pUAVInitialCounts) {
  10146. #if defined(__cplusplus)
  10147. self->CSSetUnorderedAccessViews(StartSlot, NumUAVs, ppUnorderedAccessViews, pUAVInitialCounts);
  10148. #else
  10149. self->lpVtbl->CSSetUnorderedAccessViews(self, StartSlot, NumUAVs, ppUnorderedAccessViews, pUAVInitialCounts);
  10150. #endif
  10151. }
  10152. static inline HRESULT _sg_d3d11_CreateBuffer(ID3D11Device* self, const D3D11_BUFFER_DESC* pDesc, const D3D11_SUBRESOURCE_DATA* pInitialData, ID3D11Buffer** ppBuffer) {
  10153. #if defined(__cplusplus)
  10154. return self->CreateBuffer(pDesc, pInitialData, ppBuffer);
  10155. #else
  10156. return self->lpVtbl->CreateBuffer(self, pDesc, pInitialData, ppBuffer);
  10157. #endif
  10158. }
  10159. static inline HRESULT _sg_d3d11_CreateTexture2D(ID3D11Device* self, const D3D11_TEXTURE2D_DESC* pDesc, const D3D11_SUBRESOURCE_DATA* pInitialData, ID3D11Texture2D** ppTexture2D) {
  10160. #if defined(__cplusplus)
  10161. return self->CreateTexture2D(pDesc, pInitialData, ppTexture2D);
  10162. #else
  10163. return self->lpVtbl->CreateTexture2D(self, pDesc, pInitialData, ppTexture2D);
  10164. #endif
  10165. }
  10166. static inline HRESULT _sg_d3d11_CreateShaderResourceView(ID3D11Device* self, ID3D11Resource* pResource, const D3D11_SHADER_RESOURCE_VIEW_DESC* pDesc, ID3D11ShaderResourceView** ppSRView) {
  10167. #if defined(__cplusplus)
  10168. return self->CreateShaderResourceView(pResource, pDesc, ppSRView);
  10169. #else
  10170. return self->lpVtbl->CreateShaderResourceView(self, pResource, pDesc, ppSRView);
  10171. #endif
  10172. }
  10173. static inline HRESULT _sg_d3d11_CreateUnorderedAccessView(ID3D11Device* self, ID3D11Resource* pResource, const D3D11_UNORDERED_ACCESS_VIEW_DESC* pDesc, ID3D11UnorderedAccessView** ppUAVView) {
  10174. #if defined(__cplusplus)
  10175. return self->CreateUnorderedAccessView(pResource, pDesc, ppUAVView);
  10176. #else
  10177. return self->lpVtbl->CreateUnorderedAccessView(self, pResource, pDesc, ppUAVView);
  10178. #endif
  10179. }
  10180. static inline void _sg_d3d11_GetResource(ID3D11View* self, ID3D11Resource** ppResource) {
  10181. #if defined(__cplusplus)
  10182. self->GetResource(ppResource);
  10183. #else
  10184. self->lpVtbl->GetResource(self, ppResource);
  10185. #endif
  10186. }
  10187. static inline HRESULT _sg_d3d11_CreateTexture3D(ID3D11Device* self, const D3D11_TEXTURE3D_DESC* pDesc, const D3D11_SUBRESOURCE_DATA* pInitialData, ID3D11Texture3D** ppTexture3D) {
  10188. #if defined(__cplusplus)
  10189. return self->CreateTexture3D(pDesc, pInitialData, ppTexture3D);
  10190. #else
  10191. return self->lpVtbl->CreateTexture3D(self, pDesc, pInitialData, ppTexture3D);
  10192. #endif
  10193. }
  10194. static inline HRESULT _sg_d3d11_CreateSamplerState(ID3D11Device* self, const D3D11_SAMPLER_DESC* pSamplerDesc, ID3D11SamplerState** ppSamplerState) {
  10195. #if defined(__cplusplus)
  10196. return self->CreateSamplerState(pSamplerDesc, ppSamplerState);
  10197. #else
  10198. return self->lpVtbl->CreateSamplerState(self, pSamplerDesc, ppSamplerState);
  10199. #endif
  10200. }
  10201. static inline LPVOID _sg_d3d11_GetBufferPointer(ID3D10Blob* self) {
  10202. #if defined(__cplusplus)
  10203. return self->GetBufferPointer();
  10204. #else
  10205. return self->lpVtbl->GetBufferPointer(self);
  10206. #endif
  10207. }
  10208. static inline SIZE_T _sg_d3d11_GetBufferSize(ID3D10Blob* self) {
  10209. #if defined(__cplusplus)
  10210. return self->GetBufferSize();
  10211. #else
  10212. return self->lpVtbl->GetBufferSize(self);
  10213. #endif
  10214. }
  10215. static inline HRESULT _sg_d3d11_CreateVertexShader(ID3D11Device* self, const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage, ID3D11VertexShader** ppVertexShader) {
  10216. #if defined(__cplusplus)
  10217. return self->CreateVertexShader(pShaderBytecode, BytecodeLength, pClassLinkage, ppVertexShader);
  10218. #else
  10219. return self->lpVtbl->CreateVertexShader(self, pShaderBytecode, BytecodeLength, pClassLinkage, ppVertexShader);
  10220. #endif
  10221. }
  10222. static inline HRESULT _sg_d3d11_CreatePixelShader(ID3D11Device* self, const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage, ID3D11PixelShader** ppPixelShader) {
  10223. #if defined(__cplusplus)
  10224. return self->CreatePixelShader(pShaderBytecode, BytecodeLength, pClassLinkage, ppPixelShader);
  10225. #else
  10226. return self->lpVtbl->CreatePixelShader(self, pShaderBytecode, BytecodeLength, pClassLinkage, ppPixelShader);
  10227. #endif
  10228. }
  10229. static inline HRESULT _sg_d3d11_CreateComputeShader(ID3D11Device* self, const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage, ID3D11ComputeShader** ppComputeShader) {
  10230. #if defined(__cplusplus)
  10231. return self->CreateComputeShader(pShaderBytecode, BytecodeLength, pClassLinkage, ppComputeShader);
  10232. #else
  10233. return self->lpVtbl->CreateComputeShader(self, pShaderBytecode, BytecodeLength, pClassLinkage, ppComputeShader);
  10234. #endif
  10235. }
  10236. static inline HRESULT _sg_d3d11_CreateInputLayout(ID3D11Device* self, const D3D11_INPUT_ELEMENT_DESC* pInputElementDescs, UINT NumElements, const void* pShaderBytecodeWithInputSignature, SIZE_T BytecodeLength, ID3D11InputLayout **ppInputLayout) {
  10237. #if defined(__cplusplus)
  10238. return self->CreateInputLayout(pInputElementDescs, NumElements, pShaderBytecodeWithInputSignature, BytecodeLength, ppInputLayout);
  10239. #else
  10240. return self->lpVtbl->CreateInputLayout(self, pInputElementDescs, NumElements, pShaderBytecodeWithInputSignature, BytecodeLength, ppInputLayout);
  10241. #endif
  10242. }
  10243. static inline HRESULT _sg_d3d11_CreateRasterizerState(ID3D11Device* self, const D3D11_RASTERIZER_DESC* pRasterizerDesc, ID3D11RasterizerState** ppRasterizerState) {
  10244. #if defined(__cplusplus)
  10245. return self->CreateRasterizerState(pRasterizerDesc, ppRasterizerState);
  10246. #else
  10247. return self->lpVtbl->CreateRasterizerState(self, pRasterizerDesc, ppRasterizerState);
  10248. #endif
  10249. }
  10250. static inline HRESULT _sg_d3d11_CreateDepthStencilState(ID3D11Device* self, const D3D11_DEPTH_STENCIL_DESC* pDepthStencilDesc, ID3D11DepthStencilState** ppDepthStencilState) {
  10251. #if defined(__cplusplus)
  10252. return self->CreateDepthStencilState(pDepthStencilDesc, ppDepthStencilState);
  10253. #else
  10254. return self->lpVtbl->CreateDepthStencilState(self, pDepthStencilDesc, ppDepthStencilState);
  10255. #endif
  10256. }
  10257. static inline HRESULT _sg_d3d11_CreateBlendState(ID3D11Device* self, const D3D11_BLEND_DESC* pBlendStateDesc, ID3D11BlendState** ppBlendState) {
  10258. #if defined(__cplusplus)
  10259. return self->CreateBlendState(pBlendStateDesc, ppBlendState);
  10260. #else
  10261. return self->lpVtbl->CreateBlendState(self, pBlendStateDesc, ppBlendState);
  10262. #endif
  10263. }
  10264. static inline HRESULT _sg_d3d11_CreateRenderTargetView(ID3D11Device* self, ID3D11Resource *pResource, const D3D11_RENDER_TARGET_VIEW_DESC* pDesc, ID3D11RenderTargetView** ppRTView) {
  10265. #if defined(__cplusplus)
  10266. return self->CreateRenderTargetView(pResource, pDesc, ppRTView);
  10267. #else
  10268. return self->lpVtbl->CreateRenderTargetView(self, pResource, pDesc, ppRTView);
  10269. #endif
  10270. }
  10271. static inline HRESULT _sg_d3d11_CreateDepthStencilView(ID3D11Device* self, ID3D11Resource* pResource, const D3D11_DEPTH_STENCIL_VIEW_DESC* pDesc, ID3D11DepthStencilView** ppDepthStencilView) {
  10272. #if defined(__cplusplus)
  10273. return self->CreateDepthStencilView(pResource, pDesc, ppDepthStencilView);
  10274. #else
  10275. return self->lpVtbl->CreateDepthStencilView(self, pResource, pDesc, ppDepthStencilView);
  10276. #endif
  10277. }
  10278. static inline void _sg_d3d11_RSSetViewports(ID3D11DeviceContext* self, UINT NumViewports, const D3D11_VIEWPORT* pViewports) {
  10279. #if defined(__cplusplus)
  10280. self->RSSetViewports(NumViewports, pViewports);
  10281. #else
  10282. self->lpVtbl->RSSetViewports(self, NumViewports, pViewports);
  10283. #endif
  10284. }
  10285. static inline void _sg_d3d11_RSSetScissorRects(ID3D11DeviceContext* self, UINT NumRects, const D3D11_RECT* pRects) {
  10286. #if defined(__cplusplus)
  10287. self->RSSetScissorRects(NumRects, pRects);
  10288. #else
  10289. self->lpVtbl->RSSetScissorRects(self, NumRects, pRects);
  10290. #endif
  10291. }
  10292. static inline void _sg_d3d11_ClearRenderTargetView(ID3D11DeviceContext* self, ID3D11RenderTargetView* pRenderTargetView, const FLOAT ColorRGBA[4]) {
  10293. #if defined(__cplusplus)
  10294. self->ClearRenderTargetView(pRenderTargetView, ColorRGBA);
  10295. #else
  10296. self->lpVtbl->ClearRenderTargetView(self, pRenderTargetView, ColorRGBA);
  10297. #endif
  10298. }
  10299. static inline void _sg_d3d11_ClearDepthStencilView(ID3D11DeviceContext* self, ID3D11DepthStencilView* pDepthStencilView, UINT ClearFlags, FLOAT Depth, UINT8 Stencil) {
  10300. #if defined(__cplusplus)
  10301. self->ClearDepthStencilView(pDepthStencilView, ClearFlags, Depth, Stencil);
  10302. #else
  10303. self->lpVtbl->ClearDepthStencilView(self, pDepthStencilView, ClearFlags, Depth, Stencil);
  10304. #endif
  10305. }
  10306. static inline void _sg_d3d11_ResolveSubresource(ID3D11DeviceContext* self, ID3D11Resource* pDstResource, UINT DstSubresource, ID3D11Resource* pSrcResource, UINT SrcSubresource, DXGI_FORMAT Format) {
  10307. #if defined(__cplusplus)
  10308. self->ResolveSubresource(pDstResource, DstSubresource, pSrcResource, SrcSubresource, Format);
  10309. #else
  10310. self->lpVtbl->ResolveSubresource(self, pDstResource, DstSubresource, pSrcResource, SrcSubresource, Format);
  10311. #endif
  10312. }
  10313. static inline void _sg_d3d11_IASetPrimitiveTopology(ID3D11DeviceContext* self, D3D11_PRIMITIVE_TOPOLOGY Topology) {
  10314. #if defined(__cplusplus)
  10315. self->IASetPrimitiveTopology(Topology);
  10316. #else
  10317. self->lpVtbl->IASetPrimitiveTopology(self, Topology);
  10318. #endif
  10319. }
  10320. static inline void _sg_d3d11_UpdateSubresource(ID3D11DeviceContext* self, ID3D11Resource* pDstResource, UINT DstSubresource, const D3D11_BOX* pDstBox, const void* pSrcData, UINT SrcRowPitch, UINT SrcDepthPitch) {
  10321. #if defined(__cplusplus)
  10322. self->UpdateSubresource(pDstResource, DstSubresource, pDstBox, pSrcData, SrcRowPitch, SrcDepthPitch);
  10323. #else
  10324. self->lpVtbl->UpdateSubresource(self, pDstResource, DstSubresource, pDstBox, pSrcData, SrcRowPitch, SrcDepthPitch);
  10325. #endif
  10326. }
  10327. static inline void _sg_d3d11_DrawIndexed(ID3D11DeviceContext* self, UINT IndexCount, UINT StartIndexLocation, INT BaseVertexLocation) {
  10328. #if defined(__cplusplus)
  10329. self->DrawIndexed(IndexCount, StartIndexLocation, BaseVertexLocation);
  10330. #else
  10331. self->lpVtbl->DrawIndexed(self, IndexCount, StartIndexLocation, BaseVertexLocation);
  10332. #endif
  10333. }
  10334. static inline void _sg_d3d11_DrawIndexedInstanced(ID3D11DeviceContext* self, UINT IndexCountPerInstance, UINT InstanceCount, UINT StartIndexLocation, INT BaseVertexLocation, UINT StartInstanceLocation) {
  10335. #if defined(__cplusplus)
  10336. self->DrawIndexedInstanced(IndexCountPerInstance, InstanceCount, StartIndexLocation, BaseVertexLocation, StartInstanceLocation);
  10337. #else
  10338. self->lpVtbl->DrawIndexedInstanced(self, IndexCountPerInstance, InstanceCount, StartIndexLocation, BaseVertexLocation, StartInstanceLocation);
  10339. #endif
  10340. }
  10341. static inline void _sg_d3d11_Draw(ID3D11DeviceContext* self, UINT VertexCount, UINT StartVertexLocation) {
  10342. #if defined(__cplusplus)
  10343. self->Draw(VertexCount, StartVertexLocation);
  10344. #else
  10345. self->lpVtbl->Draw(self, VertexCount, StartVertexLocation);
  10346. #endif
  10347. }
  10348. static inline void _sg_d3d11_DrawInstanced(ID3D11DeviceContext* self, UINT VertexCountPerInstance, UINT InstanceCount, UINT StartVertexLocation, UINT StartInstanceLocation) {
  10349. #if defined(__cplusplus)
  10350. self->DrawInstanced(VertexCountPerInstance, InstanceCount, StartVertexLocation, StartInstanceLocation);
  10351. #else
  10352. self->lpVtbl->DrawInstanced(self, VertexCountPerInstance, InstanceCount, StartVertexLocation, StartInstanceLocation);
  10353. #endif
  10354. }
  10355. static inline void _sg_d3d11_Dispatch(ID3D11DeviceContext* self, UINT ThreadGroupCountX, UINT ThreadGroupCountY, UINT ThreadGroupCountZ) {
  10356. #if defined(__cplusplus)
  10357. self->Dispatch(ThreadGroupCountX, ThreadGroupCountY, ThreadGroupCountZ);
  10358. #else
  10359. self->lpVtbl->Dispatch(self, ThreadGroupCountX, ThreadGroupCountY, ThreadGroupCountZ);
  10360. #endif
  10361. }
  10362. static inline HRESULT _sg_d3d11_Map(ID3D11DeviceContext* self, ID3D11Resource* pResource, UINT Subresource, D3D11_MAP MapType, UINT MapFlags, D3D11_MAPPED_SUBRESOURCE* pMappedResource) {
  10363. #if defined(__cplusplus)
  10364. return self->Map(pResource, Subresource, MapType, MapFlags, pMappedResource);
  10365. #else
  10366. return self->lpVtbl->Map(self, pResource, Subresource, MapType, MapFlags, pMappedResource);
  10367. #endif
  10368. }
  10369. static inline void _sg_d3d11_Unmap(ID3D11DeviceContext* self, ID3D11Resource* pResource, UINT Subresource) {
  10370. #if defined(__cplusplus)
  10371. self->Unmap(pResource, Subresource);
  10372. #else
  10373. self->lpVtbl->Unmap(self, pResource, Subresource);
  10374. #endif
  10375. }
  10376. static inline void _sg_d3d11_ClearState(ID3D11DeviceContext* self) {
  10377. #if defined(__cplusplus)
  10378. self->ClearState();
  10379. #else
  10380. self->lpVtbl->ClearState(self);
  10381. #endif
  10382. }
  10383. //-- enum translation functions ------------------------------------------------
  10384. _SOKOL_PRIVATE D3D11_USAGE _sg_d3d11_image_usage(const sg_image_usage* usg) {
  10385. if (usg->immutable) {
  10386. if (usg->render_attachment || usg->storage_attachment) {
  10387. return D3D11_USAGE_DEFAULT;
  10388. } else {
  10389. return D3D11_USAGE_IMMUTABLE;
  10390. }
  10391. } else {
  10392. return D3D11_USAGE_DYNAMIC;
  10393. }
  10394. }
  10395. _SOKOL_PRIVATE UINT _sg_d3d11_image_bind_flags(const sg_image_usage* usg, sg_pixel_format fmt) {
  10396. UINT res = D3D11_BIND_SHADER_RESOURCE;
  10397. if (usg->render_attachment) {
  10398. if (_sg_is_depth_or_depth_stencil_format(fmt)) {
  10399. res |= D3D11_BIND_DEPTH_STENCIL;
  10400. } else {
  10401. res |= D3D11_BIND_RENDER_TARGET;
  10402. }
  10403. } else if (usg->storage_attachment) {
  10404. res |= D3D11_BIND_UNORDERED_ACCESS;
  10405. }
  10406. return res;
  10407. }
  10408. _SOKOL_PRIVATE UINT _sg_d3d11_image_cpu_access_flags(const sg_image_usage* usg) {
  10409. if (usg->render_attachment || usg->storage_attachment || usg->immutable) {
  10410. return 0;
  10411. } else {
  10412. return D3D11_CPU_ACCESS_WRITE;
  10413. }
  10414. }
  10415. _SOKOL_PRIVATE D3D11_USAGE _sg_d3d11_buffer_usage(const sg_buffer_usage* usg) {
  10416. if (usg->immutable) {
  10417. return usg->storage_buffer ? D3D11_USAGE_DEFAULT : D3D11_USAGE_IMMUTABLE;
  10418. } else {
  10419. return D3D11_USAGE_DYNAMIC;
  10420. }
  10421. }
  10422. _SOKOL_PRIVATE UINT _sg_d3d11_buffer_bind_flags(const sg_buffer_usage* usg) {
  10423. UINT res = 0;
  10424. if (usg->vertex_buffer) {
  10425. res |= D3D11_BIND_VERTEX_BUFFER;
  10426. }
  10427. if (usg->index_buffer) {
  10428. res |= D3D11_BIND_INDEX_BUFFER;
  10429. }
  10430. if (usg->storage_buffer) {
  10431. if (usg->immutable) {
  10432. res |= D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS;
  10433. } else {
  10434. res |= D3D11_BIND_SHADER_RESOURCE;
  10435. }
  10436. }
  10437. return res;
  10438. }
  10439. _SOKOL_PRIVATE UINT _sg_d3d11_buffer_misc_flags(const sg_buffer_usage* usg) {
  10440. return usg->storage_buffer ? D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS : 0;
  10441. }
  10442. _SOKOL_PRIVATE UINT _sg_d3d11_buffer_cpu_access_flags(const sg_buffer_usage* usg) {
  10443. return usg->immutable ? 0 : D3D11_CPU_ACCESS_WRITE;
  10444. }
  10445. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_texture_pixel_format(sg_pixel_format fmt) {
  10446. switch (fmt) {
  10447. case SG_PIXELFORMAT_R8: return DXGI_FORMAT_R8_UNORM;
  10448. case SG_PIXELFORMAT_R8SN: return DXGI_FORMAT_R8_SNORM;
  10449. case SG_PIXELFORMAT_R8UI: return DXGI_FORMAT_R8_UINT;
  10450. case SG_PIXELFORMAT_R8SI: return DXGI_FORMAT_R8_SINT;
  10451. case SG_PIXELFORMAT_R16: return DXGI_FORMAT_R16_UNORM;
  10452. case SG_PIXELFORMAT_R16SN: return DXGI_FORMAT_R16_SNORM;
  10453. case SG_PIXELFORMAT_R16UI: return DXGI_FORMAT_R16_UINT;
  10454. case SG_PIXELFORMAT_R16SI: return DXGI_FORMAT_R16_SINT;
  10455. case SG_PIXELFORMAT_R16F: return DXGI_FORMAT_R16_FLOAT;
  10456. case SG_PIXELFORMAT_RG8: return DXGI_FORMAT_R8G8_UNORM;
  10457. case SG_PIXELFORMAT_RG8SN: return DXGI_FORMAT_R8G8_SNORM;
  10458. case SG_PIXELFORMAT_RG8UI: return DXGI_FORMAT_R8G8_UINT;
  10459. case SG_PIXELFORMAT_RG8SI: return DXGI_FORMAT_R8G8_SINT;
  10460. case SG_PIXELFORMAT_R32UI: return DXGI_FORMAT_R32_UINT;
  10461. case SG_PIXELFORMAT_R32SI: return DXGI_FORMAT_R32_SINT;
  10462. case SG_PIXELFORMAT_R32F: return DXGI_FORMAT_R32_FLOAT;
  10463. case SG_PIXELFORMAT_RG16: return DXGI_FORMAT_R16G16_UNORM;
  10464. case SG_PIXELFORMAT_RG16SN: return DXGI_FORMAT_R16G16_SNORM;
  10465. case SG_PIXELFORMAT_RG16UI: return DXGI_FORMAT_R16G16_UINT;
  10466. case SG_PIXELFORMAT_RG16SI: return DXGI_FORMAT_R16G16_SINT;
  10467. case SG_PIXELFORMAT_RG16F: return DXGI_FORMAT_R16G16_FLOAT;
  10468. case SG_PIXELFORMAT_RGBA8: return DXGI_FORMAT_R8G8B8A8_UNORM;
  10469. case SG_PIXELFORMAT_SRGB8A8: return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
  10470. case SG_PIXELFORMAT_RGBA8SN: return DXGI_FORMAT_R8G8B8A8_SNORM;
  10471. case SG_PIXELFORMAT_RGBA8UI: return DXGI_FORMAT_R8G8B8A8_UINT;
  10472. case SG_PIXELFORMAT_RGBA8SI: return DXGI_FORMAT_R8G8B8A8_SINT;
  10473. case SG_PIXELFORMAT_BGRA8: return DXGI_FORMAT_B8G8R8A8_UNORM;
  10474. case SG_PIXELFORMAT_RGB10A2: return DXGI_FORMAT_R10G10B10A2_UNORM;
  10475. case SG_PIXELFORMAT_RG11B10F: return DXGI_FORMAT_R11G11B10_FLOAT;
  10476. case SG_PIXELFORMAT_RGB9E5: return DXGI_FORMAT_R9G9B9E5_SHAREDEXP;
  10477. case SG_PIXELFORMAT_RG32UI: return DXGI_FORMAT_R32G32_UINT;
  10478. case SG_PIXELFORMAT_RG32SI: return DXGI_FORMAT_R32G32_SINT;
  10479. case SG_PIXELFORMAT_RG32F: return DXGI_FORMAT_R32G32_FLOAT;
  10480. case SG_PIXELFORMAT_RGBA16: return DXGI_FORMAT_R16G16B16A16_UNORM;
  10481. case SG_PIXELFORMAT_RGBA16SN: return DXGI_FORMAT_R16G16B16A16_SNORM;
  10482. case SG_PIXELFORMAT_RGBA16UI: return DXGI_FORMAT_R16G16B16A16_UINT;
  10483. case SG_PIXELFORMAT_RGBA16SI: return DXGI_FORMAT_R16G16B16A16_SINT;
  10484. case SG_PIXELFORMAT_RGBA16F: return DXGI_FORMAT_R16G16B16A16_FLOAT;
  10485. case SG_PIXELFORMAT_RGBA32UI: return DXGI_FORMAT_R32G32B32A32_UINT;
  10486. case SG_PIXELFORMAT_RGBA32SI: return DXGI_FORMAT_R32G32B32A32_SINT;
  10487. case SG_PIXELFORMAT_RGBA32F: return DXGI_FORMAT_R32G32B32A32_FLOAT;
  10488. case SG_PIXELFORMAT_DEPTH: return DXGI_FORMAT_R32_TYPELESS;
  10489. case SG_PIXELFORMAT_DEPTH_STENCIL: return DXGI_FORMAT_R24G8_TYPELESS;
  10490. case SG_PIXELFORMAT_BC1_RGBA: return DXGI_FORMAT_BC1_UNORM;
  10491. case SG_PIXELFORMAT_BC2_RGBA: return DXGI_FORMAT_BC2_UNORM;
  10492. case SG_PIXELFORMAT_BC3_RGBA: return DXGI_FORMAT_BC3_UNORM;
  10493. case SG_PIXELFORMAT_BC3_SRGBA: return DXGI_FORMAT_BC3_UNORM_SRGB;
  10494. case SG_PIXELFORMAT_BC4_R: return DXGI_FORMAT_BC4_UNORM;
  10495. case SG_PIXELFORMAT_BC4_RSN: return DXGI_FORMAT_BC4_SNORM;
  10496. case SG_PIXELFORMAT_BC5_RG: return DXGI_FORMAT_BC5_UNORM;
  10497. case SG_PIXELFORMAT_BC5_RGSN: return DXGI_FORMAT_BC5_SNORM;
  10498. case SG_PIXELFORMAT_BC6H_RGBF: return DXGI_FORMAT_BC6H_SF16;
  10499. case SG_PIXELFORMAT_BC6H_RGBUF: return DXGI_FORMAT_BC6H_UF16;
  10500. case SG_PIXELFORMAT_BC7_RGBA: return DXGI_FORMAT_BC7_UNORM;
  10501. case SG_PIXELFORMAT_BC7_SRGBA: return DXGI_FORMAT_BC7_UNORM_SRGB;
  10502. default: return DXGI_FORMAT_UNKNOWN;
  10503. };
  10504. }
  10505. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_srv_pixel_format(sg_pixel_format fmt) {
  10506. if (fmt == SG_PIXELFORMAT_DEPTH) {
  10507. return DXGI_FORMAT_R32_FLOAT;
  10508. } else if (fmt == SG_PIXELFORMAT_DEPTH_STENCIL) {
  10509. return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
  10510. } else {
  10511. return _sg_d3d11_texture_pixel_format(fmt);
  10512. }
  10513. }
  10514. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_dsv_pixel_format(sg_pixel_format fmt) {
  10515. if (fmt == SG_PIXELFORMAT_DEPTH) {
  10516. return DXGI_FORMAT_D32_FLOAT;
  10517. } else if (fmt == SG_PIXELFORMAT_DEPTH_STENCIL) {
  10518. return DXGI_FORMAT_D24_UNORM_S8_UINT;
  10519. } else {
  10520. return _sg_d3d11_texture_pixel_format(fmt);
  10521. }
  10522. }
  10523. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_rtv_uav_pixel_format(sg_pixel_format fmt) {
  10524. if (fmt == SG_PIXELFORMAT_DEPTH) {
  10525. return DXGI_FORMAT_R32_FLOAT;
  10526. } else if (fmt == SG_PIXELFORMAT_DEPTH_STENCIL) {
  10527. return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
  10528. } else {
  10529. return _sg_d3d11_texture_pixel_format(fmt);
  10530. }
  10531. }
  10532. _SOKOL_PRIVATE D3D11_PRIMITIVE_TOPOLOGY _sg_d3d11_primitive_topology(sg_primitive_type prim_type) {
  10533. switch (prim_type) {
  10534. case SG_PRIMITIVETYPE_POINTS: return D3D11_PRIMITIVE_TOPOLOGY_POINTLIST;
  10535. case SG_PRIMITIVETYPE_LINES: return D3D11_PRIMITIVE_TOPOLOGY_LINELIST;
  10536. case SG_PRIMITIVETYPE_LINE_STRIP: return D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP;
  10537. case SG_PRIMITIVETYPE_TRIANGLES: return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  10538. case SG_PRIMITIVETYPE_TRIANGLE_STRIP: return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
  10539. default: SOKOL_UNREACHABLE; return (D3D11_PRIMITIVE_TOPOLOGY) 0;
  10540. }
  10541. }
  10542. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_index_format(sg_index_type index_type) {
  10543. switch (index_type) {
  10544. case SG_INDEXTYPE_NONE: return DXGI_FORMAT_UNKNOWN;
  10545. case SG_INDEXTYPE_UINT16: return DXGI_FORMAT_R16_UINT;
  10546. case SG_INDEXTYPE_UINT32: return DXGI_FORMAT_R32_UINT;
  10547. default: SOKOL_UNREACHABLE; return (DXGI_FORMAT) 0;
  10548. }
  10549. }
  10550. _SOKOL_PRIVATE D3D11_FILTER _sg_d3d11_filter(sg_filter min_f, sg_filter mag_f, sg_filter mipmap_f, bool comparison, uint32_t max_anisotropy) {
  10551. uint32_t d3d11_filter = 0;
  10552. if (max_anisotropy > 1) {
  10553. // D3D11_FILTER_ANISOTROPIC = 0x55,
  10554. d3d11_filter |= 0x55;
  10555. } else {
  10556. // D3D11_FILTER_MIN_MAG_MIP_POINT = 0,
  10557. // D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR = 0x1,
  10558. // D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x4,
  10559. // D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR = 0x5,
  10560. // D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT = 0x10,
  10561. // D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x11,
  10562. // D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT = 0x14,
  10563. // D3D11_FILTER_MIN_MAG_MIP_LINEAR = 0x15,
  10564. if (mipmap_f == SG_FILTER_LINEAR) {
  10565. d3d11_filter |= 0x01;
  10566. }
  10567. if (mag_f == SG_FILTER_LINEAR) {
  10568. d3d11_filter |= 0x04;
  10569. }
  10570. if (min_f == SG_FILTER_LINEAR) {
  10571. d3d11_filter |= 0x10;
  10572. }
  10573. }
  10574. // D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT = 0x80,
  10575. // D3D11_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR = 0x81,
  10576. // D3D11_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x84,
  10577. // D3D11_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR = 0x85,
  10578. // D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT = 0x90,
  10579. // D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x91,
  10580. // D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT = 0x94,
  10581. // D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR = 0x95,
  10582. // D3D11_FILTER_COMPARISON_ANISOTROPIC = 0xd5,
  10583. if (comparison) {
  10584. d3d11_filter |= 0x80;
  10585. }
  10586. return (D3D11_FILTER)d3d11_filter;
  10587. }
  10588. _SOKOL_PRIVATE D3D11_TEXTURE_ADDRESS_MODE _sg_d3d11_address_mode(sg_wrap m) {
  10589. switch (m) {
  10590. case SG_WRAP_REPEAT: return D3D11_TEXTURE_ADDRESS_WRAP;
  10591. case SG_WRAP_CLAMP_TO_EDGE: return D3D11_TEXTURE_ADDRESS_CLAMP;
  10592. case SG_WRAP_CLAMP_TO_BORDER: return D3D11_TEXTURE_ADDRESS_BORDER;
  10593. case SG_WRAP_MIRRORED_REPEAT: return D3D11_TEXTURE_ADDRESS_MIRROR;
  10594. default: SOKOL_UNREACHABLE; return (D3D11_TEXTURE_ADDRESS_MODE) 0;
  10595. }
  10596. }
  10597. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_vertex_format(sg_vertex_format fmt) {
  10598. switch (fmt) {
  10599. case SG_VERTEXFORMAT_FLOAT: return DXGI_FORMAT_R32_FLOAT;
  10600. case SG_VERTEXFORMAT_FLOAT2: return DXGI_FORMAT_R32G32_FLOAT;
  10601. case SG_VERTEXFORMAT_FLOAT3: return DXGI_FORMAT_R32G32B32_FLOAT;
  10602. case SG_VERTEXFORMAT_FLOAT4: return DXGI_FORMAT_R32G32B32A32_FLOAT;
  10603. case SG_VERTEXFORMAT_INT: return DXGI_FORMAT_R32_SINT;
  10604. case SG_VERTEXFORMAT_INT2: return DXGI_FORMAT_R32G32_SINT;
  10605. case SG_VERTEXFORMAT_INT3: return DXGI_FORMAT_R32G32B32_SINT;
  10606. case SG_VERTEXFORMAT_INT4: return DXGI_FORMAT_R32G32B32A32_SINT;
  10607. case SG_VERTEXFORMAT_UINT: return DXGI_FORMAT_R32_UINT;
  10608. case SG_VERTEXFORMAT_UINT2: return DXGI_FORMAT_R32G32_UINT;
  10609. case SG_VERTEXFORMAT_UINT3: return DXGI_FORMAT_R32G32B32_UINT;
  10610. case SG_VERTEXFORMAT_UINT4: return DXGI_FORMAT_R32G32B32A32_UINT;
  10611. case SG_VERTEXFORMAT_BYTE4: return DXGI_FORMAT_R8G8B8A8_SINT;
  10612. case SG_VERTEXFORMAT_BYTE4N: return DXGI_FORMAT_R8G8B8A8_SNORM;
  10613. case SG_VERTEXFORMAT_UBYTE4: return DXGI_FORMAT_R8G8B8A8_UINT;
  10614. case SG_VERTEXFORMAT_UBYTE4N: return DXGI_FORMAT_R8G8B8A8_UNORM;
  10615. case SG_VERTEXFORMAT_SHORT2: return DXGI_FORMAT_R16G16_SINT;
  10616. case SG_VERTEXFORMAT_SHORT2N: return DXGI_FORMAT_R16G16_SNORM;
  10617. case SG_VERTEXFORMAT_USHORT2: return DXGI_FORMAT_R16G16_UINT;
  10618. case SG_VERTEXFORMAT_USHORT2N: return DXGI_FORMAT_R16G16_UNORM;
  10619. case SG_VERTEXFORMAT_SHORT4: return DXGI_FORMAT_R16G16B16A16_SINT;
  10620. case SG_VERTEXFORMAT_SHORT4N: return DXGI_FORMAT_R16G16B16A16_SNORM;
  10621. case SG_VERTEXFORMAT_USHORT4: return DXGI_FORMAT_R16G16B16A16_UINT;
  10622. case SG_VERTEXFORMAT_USHORT4N: return DXGI_FORMAT_R16G16B16A16_UNORM;
  10623. case SG_VERTEXFORMAT_UINT10_N2: return DXGI_FORMAT_R10G10B10A2_UNORM;
  10624. case SG_VERTEXFORMAT_HALF2: return DXGI_FORMAT_R16G16_FLOAT;
  10625. case SG_VERTEXFORMAT_HALF4: return DXGI_FORMAT_R16G16B16A16_FLOAT;
  10626. default: SOKOL_UNREACHABLE; return (DXGI_FORMAT) 0;
  10627. }
  10628. }
  10629. _SOKOL_PRIVATE D3D11_INPUT_CLASSIFICATION _sg_d3d11_input_classification(sg_vertex_step step) {
  10630. switch (step) {
  10631. case SG_VERTEXSTEP_PER_VERTEX: return D3D11_INPUT_PER_VERTEX_DATA;
  10632. case SG_VERTEXSTEP_PER_INSTANCE: return D3D11_INPUT_PER_INSTANCE_DATA;
  10633. default: SOKOL_UNREACHABLE; return (D3D11_INPUT_CLASSIFICATION) 0;
  10634. }
  10635. }
  10636. _SOKOL_PRIVATE D3D11_CULL_MODE _sg_d3d11_cull_mode(sg_cull_mode m) {
  10637. switch (m) {
  10638. case SG_CULLMODE_NONE: return D3D11_CULL_NONE;
  10639. case SG_CULLMODE_FRONT: return D3D11_CULL_FRONT;
  10640. case SG_CULLMODE_BACK: return D3D11_CULL_BACK;
  10641. default: SOKOL_UNREACHABLE; return (D3D11_CULL_MODE) 0;
  10642. }
  10643. }
  10644. _SOKOL_PRIVATE D3D11_COMPARISON_FUNC _sg_d3d11_compare_func(sg_compare_func f) {
  10645. switch (f) {
  10646. case SG_COMPAREFUNC_NEVER: return D3D11_COMPARISON_NEVER;
  10647. case SG_COMPAREFUNC_LESS: return D3D11_COMPARISON_LESS;
  10648. case SG_COMPAREFUNC_EQUAL: return D3D11_COMPARISON_EQUAL;
  10649. case SG_COMPAREFUNC_LESS_EQUAL: return D3D11_COMPARISON_LESS_EQUAL;
  10650. case SG_COMPAREFUNC_GREATER: return D3D11_COMPARISON_GREATER;
  10651. case SG_COMPAREFUNC_NOT_EQUAL: return D3D11_COMPARISON_NOT_EQUAL;
  10652. case SG_COMPAREFUNC_GREATER_EQUAL: return D3D11_COMPARISON_GREATER_EQUAL;
  10653. case SG_COMPAREFUNC_ALWAYS: return D3D11_COMPARISON_ALWAYS;
  10654. default: SOKOL_UNREACHABLE; return (D3D11_COMPARISON_FUNC) 0;
  10655. }
  10656. }
  10657. _SOKOL_PRIVATE D3D11_STENCIL_OP _sg_d3d11_stencil_op(sg_stencil_op op) {
  10658. switch (op) {
  10659. case SG_STENCILOP_KEEP: return D3D11_STENCIL_OP_KEEP;
  10660. case SG_STENCILOP_ZERO: return D3D11_STENCIL_OP_ZERO;
  10661. case SG_STENCILOP_REPLACE: return D3D11_STENCIL_OP_REPLACE;
  10662. case SG_STENCILOP_INCR_CLAMP: return D3D11_STENCIL_OP_INCR_SAT;
  10663. case SG_STENCILOP_DECR_CLAMP: return D3D11_STENCIL_OP_DECR_SAT;
  10664. case SG_STENCILOP_INVERT: return D3D11_STENCIL_OP_INVERT;
  10665. case SG_STENCILOP_INCR_WRAP: return D3D11_STENCIL_OP_INCR;
  10666. case SG_STENCILOP_DECR_WRAP: return D3D11_STENCIL_OP_DECR;
  10667. default: SOKOL_UNREACHABLE; return (D3D11_STENCIL_OP) 0;
  10668. }
  10669. }
  10670. _SOKOL_PRIVATE D3D11_BLEND _sg_d3d11_blend_factor(sg_blend_factor f) {
  10671. switch (f) {
  10672. case SG_BLENDFACTOR_ZERO: return D3D11_BLEND_ZERO;
  10673. case SG_BLENDFACTOR_ONE: return D3D11_BLEND_ONE;
  10674. case SG_BLENDFACTOR_SRC_COLOR: return D3D11_BLEND_SRC_COLOR;
  10675. case SG_BLENDFACTOR_ONE_MINUS_SRC_COLOR: return D3D11_BLEND_INV_SRC_COLOR;
  10676. case SG_BLENDFACTOR_SRC_ALPHA: return D3D11_BLEND_SRC_ALPHA;
  10677. case SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA: return D3D11_BLEND_INV_SRC_ALPHA;
  10678. case SG_BLENDFACTOR_DST_COLOR: return D3D11_BLEND_DEST_COLOR;
  10679. case SG_BLENDFACTOR_ONE_MINUS_DST_COLOR: return D3D11_BLEND_INV_DEST_COLOR;
  10680. case SG_BLENDFACTOR_DST_ALPHA: return D3D11_BLEND_DEST_ALPHA;
  10681. case SG_BLENDFACTOR_ONE_MINUS_DST_ALPHA: return D3D11_BLEND_INV_DEST_ALPHA;
  10682. case SG_BLENDFACTOR_SRC_ALPHA_SATURATED: return D3D11_BLEND_SRC_ALPHA_SAT;
  10683. case SG_BLENDFACTOR_BLEND_COLOR: return D3D11_BLEND_BLEND_FACTOR;
  10684. case SG_BLENDFACTOR_ONE_MINUS_BLEND_COLOR: return D3D11_BLEND_INV_BLEND_FACTOR;
  10685. case SG_BLENDFACTOR_BLEND_ALPHA: return D3D11_BLEND_BLEND_FACTOR;
  10686. case SG_BLENDFACTOR_ONE_MINUS_BLEND_ALPHA: return D3D11_BLEND_INV_BLEND_FACTOR;
  10687. default: SOKOL_UNREACHABLE; return (D3D11_BLEND) 0;
  10688. }
  10689. }
  10690. _SOKOL_PRIVATE D3D11_BLEND_OP _sg_d3d11_blend_op(sg_blend_op op) {
  10691. switch (op) {
  10692. case SG_BLENDOP_ADD: return D3D11_BLEND_OP_ADD;
  10693. case SG_BLENDOP_SUBTRACT: return D3D11_BLEND_OP_SUBTRACT;
  10694. case SG_BLENDOP_REVERSE_SUBTRACT: return D3D11_BLEND_OP_REV_SUBTRACT;
  10695. case SG_BLENDOP_MIN: return D3D11_BLEND_OP_MIN;
  10696. case SG_BLENDOP_MAX: return D3D11_BLEND_OP_MAX;
  10697. default: SOKOL_UNREACHABLE; return (D3D11_BLEND_OP) 0;
  10698. }
  10699. }
  10700. _SOKOL_PRIVATE UINT8 _sg_d3d11_color_write_mask(sg_color_mask m) {
  10701. UINT8 res = 0;
  10702. if (m & SG_COLORMASK_R) {
  10703. res |= D3D11_COLOR_WRITE_ENABLE_RED;
  10704. }
  10705. if (m & SG_COLORMASK_G) {
  10706. res |= D3D11_COLOR_WRITE_ENABLE_GREEN;
  10707. }
  10708. if (m & SG_COLORMASK_B) {
  10709. res |= D3D11_COLOR_WRITE_ENABLE_BLUE;
  10710. }
  10711. if (m & SG_COLORMASK_A) {
  10712. res |= D3D11_COLOR_WRITE_ENABLE_ALPHA;
  10713. }
  10714. return res;
  10715. }
  10716. _SOKOL_PRIVATE UINT _sg_d3d11_dxgi_fmt_caps(DXGI_FORMAT dxgi_fmt) {
  10717. UINT dxgi_fmt_caps = 0;
  10718. if (dxgi_fmt != DXGI_FORMAT_UNKNOWN) {
  10719. HRESULT hr = _sg_d3d11_CheckFormatSupport(_sg.d3d11.dev, dxgi_fmt, &dxgi_fmt_caps);
  10720. SOKOL_ASSERT(SUCCEEDED(hr) || (E_FAIL == hr));
  10721. if (!SUCCEEDED(hr)) {
  10722. dxgi_fmt_caps = 0;
  10723. }
  10724. }
  10725. return dxgi_fmt_caps;
  10726. }
  10727. // see: https://docs.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-resources-limits#resource-limits-for-feature-level-11-hardware
  10728. _SOKOL_PRIVATE void _sg_d3d11_init_caps(void) {
  10729. _sg.backend = SG_BACKEND_D3D11;
  10730. _sg.features.origin_top_left = true;
  10731. _sg.features.image_clamp_to_border = true;
  10732. _sg.features.mrt_independent_blend_state = true;
  10733. _sg.features.mrt_independent_write_mask = true;
  10734. _sg.features.compute = true;
  10735. _sg.features.msaa_image_bindings = true;
  10736. _sg.limits.max_image_size_2d = 16 * 1024;
  10737. _sg.limits.max_image_size_cube = 16 * 1024;
  10738. _sg.limits.max_image_size_3d = 2 * 1024;
  10739. _sg.limits.max_image_size_array = 16 * 1024;
  10740. _sg.limits.max_image_array_layers = 2 * 1024;
  10741. _sg.limits.max_vertex_attrs = SG_MAX_VERTEX_ATTRIBUTES;
  10742. // see: https://docs.microsoft.com/en-us/windows/win32/api/d3d11/ne-d3d11-d3d11_format_support
  10743. for (int fmt = (SG_PIXELFORMAT_NONE+1); fmt < _SG_PIXELFORMAT_NUM; fmt++) {
  10744. const UINT srv_dxgi_fmt_caps = _sg_d3d11_dxgi_fmt_caps(_sg_d3d11_srv_pixel_format((sg_pixel_format)fmt));
  10745. const UINT rtv_uav_dxgi_fmt_caps = _sg_d3d11_dxgi_fmt_caps(_sg_d3d11_rtv_uav_pixel_format((sg_pixel_format)fmt));
  10746. const UINT dsv_dxgi_fmt_caps = _sg_d3d11_dxgi_fmt_caps(_sg_d3d11_dsv_pixel_format((sg_pixel_format)fmt));
  10747. _sg_pixelformat_info_t* info = &_sg.formats[fmt];
  10748. const bool render = 0 != (rtv_uav_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_RENDER_TARGET);
  10749. const bool depth = 0 != (dsv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_DEPTH_STENCIL);
  10750. info->sample = 0 != (srv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_TEXTURE2D);
  10751. info->filter = 0 != (srv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_SHADER_SAMPLE);
  10752. info->render = render || depth;
  10753. if (depth) {
  10754. info->blend = 0 != (dsv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_BLENDABLE);
  10755. info->msaa = 0 != (dsv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET);
  10756. } else {
  10757. info->blend = 0 != (rtv_uav_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_BLENDABLE);
  10758. info->msaa = 0 != (rtv_uav_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET);
  10759. }
  10760. info->depth = depth;
  10761. info->read = info->write = 0 != (rtv_uav_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_TYPED_UNORDERED_ACCESS_VIEW);
  10762. }
  10763. }
  10764. _SOKOL_PRIVATE void _sg_d3d11_setup_backend(const sg_desc* desc) {
  10765. // assume _sg.d3d11 already is zero-initialized
  10766. SOKOL_ASSERT(desc);
  10767. SOKOL_ASSERT(desc->environment.d3d11.device);
  10768. SOKOL_ASSERT(desc->environment.d3d11.device_context);
  10769. _sg.d3d11.valid = true;
  10770. _sg.d3d11.dev = (ID3D11Device*) desc->environment.d3d11.device;
  10771. _sg.d3d11.ctx = (ID3D11DeviceContext*) desc->environment.d3d11.device_context;
  10772. _sg_d3d11_init_caps();
  10773. }
  10774. _SOKOL_PRIVATE void _sg_d3d11_discard_backend(void) {
  10775. SOKOL_ASSERT(_sg.d3d11.valid);
  10776. _sg.d3d11.valid = false;
  10777. }
  10778. _SOKOL_PRIVATE void _sg_d3d11_clear_state(void) {
  10779. // clear all the device context state, so that resource refs don't keep stuck in the d3d device context
  10780. _sg_d3d11_ClearState(_sg.d3d11.ctx);
  10781. }
  10782. _SOKOL_PRIVATE void _sg_d3d11_reset_state_cache(void) {
  10783. // there's currently no state cache in the D3D11 backend, so this is a no-op
  10784. }
  10785. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  10786. SOKOL_ASSERT(buf && desc);
  10787. SOKOL_ASSERT(!buf->d3d11.buf);
  10788. const bool injected = (0 != desc->d3d11_buffer);
  10789. if (injected) {
  10790. buf->d3d11.buf = (ID3D11Buffer*) desc->d3d11_buffer;
  10791. _sg_d3d11_AddRef(buf->d3d11.buf);
  10792. } else {
  10793. D3D11_BUFFER_DESC d3d11_buf_desc;
  10794. _sg_clear(&d3d11_buf_desc, sizeof(d3d11_buf_desc));
  10795. d3d11_buf_desc.ByteWidth = (UINT)buf->cmn.size;
  10796. d3d11_buf_desc.Usage = _sg_d3d11_buffer_usage(&buf->cmn.usage);
  10797. d3d11_buf_desc.BindFlags = _sg_d3d11_buffer_bind_flags(&buf->cmn.usage);
  10798. d3d11_buf_desc.CPUAccessFlags = _sg_d3d11_buffer_cpu_access_flags(&buf->cmn.usage);
  10799. d3d11_buf_desc.MiscFlags = _sg_d3d11_buffer_misc_flags(&buf->cmn.usage);
  10800. D3D11_SUBRESOURCE_DATA* init_data_ptr = 0;
  10801. D3D11_SUBRESOURCE_DATA init_data;
  10802. _sg_clear(&init_data, sizeof(init_data));
  10803. if (desc->data.ptr) {
  10804. init_data.pSysMem = desc->data.ptr;
  10805. init_data_ptr = &init_data;
  10806. }
  10807. HRESULT hr = _sg_d3d11_CreateBuffer(_sg.d3d11.dev, &d3d11_buf_desc, init_data_ptr, &buf->d3d11.buf);
  10808. if (!(SUCCEEDED(hr) && buf->d3d11.buf)) {
  10809. _SG_ERROR(D3D11_CREATE_BUFFER_FAILED);
  10810. return SG_RESOURCESTATE_FAILED;
  10811. }
  10812. // for storage buffers need to create a shader-resource-view
  10813. // for read-only access, and an unordered-access-view for
  10814. // read-write access
  10815. if (buf->cmn.usage.storage_buffer) {
  10816. SOKOL_ASSERT(_sg_multiple_u64((uint64_t)buf->cmn.size, 4));
  10817. D3D11_SHADER_RESOURCE_VIEW_DESC d3d11_srv_desc;
  10818. _sg_clear(&d3d11_srv_desc, sizeof(d3d11_srv_desc));
  10819. d3d11_srv_desc.Format = DXGI_FORMAT_R32_TYPELESS;
  10820. d3d11_srv_desc.ViewDimension = D3D11_SRV_DIMENSION_BUFFEREX;
  10821. d3d11_srv_desc.BufferEx.FirstElement = 0;
  10822. d3d11_srv_desc.BufferEx.NumElements = ((UINT)buf->cmn.size) / 4;
  10823. d3d11_srv_desc.BufferEx.Flags = D3D11_BUFFEREX_SRV_FLAG_RAW;
  10824. hr = _sg_d3d11_CreateShaderResourceView(_sg.d3d11.dev, (ID3D11Resource*)buf->d3d11.buf, &d3d11_srv_desc, &buf->d3d11.srv);
  10825. if (!(SUCCEEDED(hr) && buf->d3d11.srv)) {
  10826. _SG_ERROR(D3D11_CREATE_BUFFER_SRV_FAILED);
  10827. return SG_RESOURCESTATE_FAILED;
  10828. }
  10829. if (buf->cmn.usage.immutable) {
  10830. D3D11_UNORDERED_ACCESS_VIEW_DESC d3d11_uav_desc;
  10831. _sg_clear(&d3d11_uav_desc, sizeof(d3d11_uav_desc));
  10832. d3d11_uav_desc.Format = DXGI_FORMAT_R32_TYPELESS;
  10833. d3d11_uav_desc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
  10834. d3d11_uav_desc.Buffer.FirstElement = 0;
  10835. d3d11_uav_desc.Buffer.NumElements = ((UINT)buf->cmn.size) / 4;
  10836. d3d11_uav_desc.Buffer.Flags = D3D11_BUFFER_UAV_FLAG_RAW;
  10837. hr = _sg_d3d11_CreateUnorderedAccessView(_sg.d3d11.dev, (ID3D11Resource*)buf->d3d11.buf, &d3d11_uav_desc, &buf->d3d11.uav);
  10838. if (!(SUCCEEDED(hr) && buf->d3d11.uav)) {
  10839. _SG_ERROR(D3D11_CREATE_BUFFER_UAV_FAILED);
  10840. return SG_RESOURCESTATE_FAILED;
  10841. }
  10842. }
  10843. }
  10844. _sg_d3d11_setlabel(buf->d3d11.buf, desc->label);
  10845. }
  10846. return SG_RESOURCESTATE_VALID;
  10847. }
  10848. _SOKOL_PRIVATE void _sg_d3d11_discard_buffer(_sg_buffer_t* buf) {
  10849. SOKOL_ASSERT(buf);
  10850. if (buf->d3d11.buf) {
  10851. _sg_d3d11_Release(buf->d3d11.buf);
  10852. }
  10853. if (buf->d3d11.srv) {
  10854. _sg_d3d11_Release(buf->d3d11.srv);
  10855. }
  10856. if (buf->d3d11.uav) {
  10857. _sg_d3d11_Release(buf->d3d11.uav);
  10858. }
  10859. }
  10860. _SOKOL_PRIVATE void _sg_d3d11_fill_subres_data(const _sg_image_t* img, const sg_image_data* data) {
  10861. const int num_faces = (img->cmn.type == SG_IMAGETYPE_CUBE) ? 6:1;
  10862. const int num_slices = (img->cmn.type == SG_IMAGETYPE_ARRAY) ? img->cmn.num_slices:1;
  10863. int subres_index = 0;
  10864. for (int face_index = 0; face_index < num_faces; face_index++) {
  10865. for (int slice_index = 0; slice_index < num_slices; slice_index++) {
  10866. for (int mip_index = 0; mip_index < img->cmn.num_mipmaps; mip_index++, subres_index++) {
  10867. SOKOL_ASSERT(subres_index < (SG_MAX_MIPMAPS * SG_MAX_TEXTUREARRAY_LAYERS));
  10868. D3D11_SUBRESOURCE_DATA* subres_data = &_sg.d3d11.subres_data[subres_index];
  10869. const int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  10870. const int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  10871. const sg_range* subimg_data = &(data->subimage[face_index][mip_index]);
  10872. const size_t slice_size = subimg_data->size / (size_t)num_slices;
  10873. const size_t slice_offset = slice_size * (size_t)slice_index;
  10874. const uint8_t* ptr = (const uint8_t*) subimg_data->ptr;
  10875. subres_data->pSysMem = ptr + slice_offset;
  10876. subres_data->SysMemPitch = (UINT)_sg_row_pitch(img->cmn.pixel_format, mip_width, 1);
  10877. if (img->cmn.type == SG_IMAGETYPE_3D) {
  10878. // FIXME? const int mip_depth = _sg_miplevel_dim(img->depth, mip_index);
  10879. subres_data->SysMemSlicePitch = (UINT)_sg_surface_pitch(img->cmn.pixel_format, mip_width, mip_height, 1);
  10880. } else {
  10881. subres_data->SysMemSlicePitch = 0;
  10882. }
  10883. }
  10884. }
  10885. }
  10886. }
  10887. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  10888. SOKOL_ASSERT(img && desc);
  10889. SOKOL_ASSERT((0 == img->d3d11.tex2d) && (0 == img->d3d11.tex3d) && (0 == img->d3d11.res) && (0 == img->d3d11.srv));
  10890. HRESULT hr;
  10891. const bool injected = (0 != desc->d3d11_texture);
  10892. const bool msaa = (img->cmn.sample_count > 1);
  10893. SOKOL_ASSERT(!(msaa && (img->cmn.type == SG_IMAGETYPE_CUBE)));
  10894. img->d3d11.format = _sg_d3d11_texture_pixel_format(img->cmn.pixel_format);
  10895. if (img->d3d11.format == DXGI_FORMAT_UNKNOWN) {
  10896. _SG_ERROR(D3D11_CREATE_2D_TEXTURE_UNSUPPORTED_PIXEL_FORMAT);
  10897. return SG_RESOURCESTATE_FAILED;
  10898. }
  10899. // prepare initial content pointers
  10900. D3D11_SUBRESOURCE_DATA* init_data = 0;
  10901. if (!injected && desc->data.subimage[0][0].ptr) {
  10902. _sg_d3d11_fill_subres_data(img, &desc->data);
  10903. init_data = _sg.d3d11.subres_data;
  10904. }
  10905. if (img->cmn.type != SG_IMAGETYPE_3D) {
  10906. // 2D-, cube- or array-texture
  10907. // first check for injected texture and/or resource view
  10908. if (injected) {
  10909. img->d3d11.tex2d = (ID3D11Texture2D*) desc->d3d11_texture;
  10910. _sg_d3d11_AddRef(img->d3d11.tex2d);
  10911. img->d3d11.srv = (ID3D11ShaderResourceView*) desc->d3d11_shader_resource_view;
  10912. if (img->d3d11.srv) {
  10913. _sg_d3d11_AddRef(img->d3d11.srv);
  10914. }
  10915. } else {
  10916. // if not injected, create 2D texture
  10917. D3D11_TEXTURE2D_DESC d3d11_tex_desc;
  10918. _sg_clear(&d3d11_tex_desc, sizeof(d3d11_tex_desc));
  10919. d3d11_tex_desc.Width = (UINT)img->cmn.width;
  10920. d3d11_tex_desc.Height = (UINT)img->cmn.height;
  10921. d3d11_tex_desc.MipLevels = (UINT)img->cmn.num_mipmaps;
  10922. switch (img->cmn.type) {
  10923. case SG_IMAGETYPE_ARRAY: d3d11_tex_desc.ArraySize = (UINT)img->cmn.num_slices; break;
  10924. case SG_IMAGETYPE_CUBE: d3d11_tex_desc.ArraySize = 6; break;
  10925. default: d3d11_tex_desc.ArraySize = 1; break;
  10926. }
  10927. d3d11_tex_desc.Format = img->d3d11.format;
  10928. d3d11_tex_desc.BindFlags = _sg_d3d11_image_bind_flags(&img->cmn.usage, img->cmn.pixel_format);
  10929. d3d11_tex_desc.Usage = _sg_d3d11_image_usage(&img->cmn.usage);
  10930. d3d11_tex_desc.CPUAccessFlags = _sg_d3d11_image_cpu_access_flags(&img->cmn.usage);
  10931. d3d11_tex_desc.SampleDesc.Count = (UINT)img->cmn.sample_count;
  10932. d3d11_tex_desc.SampleDesc.Quality = (UINT) (msaa ? D3D11_STANDARD_MULTISAMPLE_PATTERN : 0);
  10933. d3d11_tex_desc.MiscFlags = (img->cmn.type == SG_IMAGETYPE_CUBE) ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0;
  10934. hr = _sg_d3d11_CreateTexture2D(_sg.d3d11.dev, &d3d11_tex_desc, init_data, &img->d3d11.tex2d);
  10935. if (!(SUCCEEDED(hr) && img->d3d11.tex2d)) {
  10936. _SG_ERROR(D3D11_CREATE_2D_TEXTURE_FAILED);
  10937. return SG_RESOURCESTATE_FAILED;
  10938. }
  10939. _sg_d3d11_setlabel(img->d3d11.tex2d, desc->label);
  10940. // create shader-resource-view for 2D texture
  10941. D3D11_SHADER_RESOURCE_VIEW_DESC d3d11_srv_desc;
  10942. _sg_clear(&d3d11_srv_desc, sizeof(d3d11_srv_desc));
  10943. d3d11_srv_desc.Format = _sg_d3d11_srv_pixel_format(img->cmn.pixel_format);
  10944. switch (img->cmn.type) {
  10945. case SG_IMAGETYPE_2D:
  10946. d3d11_srv_desc.ViewDimension = msaa ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D;
  10947. d3d11_srv_desc.Texture2D.MipLevels = (UINT)img->cmn.num_mipmaps;
  10948. break;
  10949. case SG_IMAGETYPE_CUBE:
  10950. d3d11_srv_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
  10951. d3d11_srv_desc.TextureCube.MipLevels = (UINT)img->cmn.num_mipmaps;
  10952. break;
  10953. case SG_IMAGETYPE_ARRAY:
  10954. d3d11_srv_desc.ViewDimension = msaa ? D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY : D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
  10955. d3d11_srv_desc.Texture2DArray.MipLevels = (UINT)img->cmn.num_mipmaps;
  10956. d3d11_srv_desc.Texture2DArray.ArraySize = (UINT)img->cmn.num_slices;
  10957. break;
  10958. default:
  10959. SOKOL_UNREACHABLE; break;
  10960. }
  10961. hr = _sg_d3d11_CreateShaderResourceView(_sg.d3d11.dev, (ID3D11Resource*)img->d3d11.tex2d, &d3d11_srv_desc, &img->d3d11.srv);
  10962. if (!(SUCCEEDED(hr) && img->d3d11.srv)) {
  10963. _SG_ERROR(D3D11_CREATE_2D_SRV_FAILED);
  10964. return SG_RESOURCESTATE_FAILED;
  10965. }
  10966. _sg_d3d11_setlabel(img->d3d11.srv, desc->label);
  10967. }
  10968. SOKOL_ASSERT(img->d3d11.tex2d);
  10969. img->d3d11.res = (ID3D11Resource*)img->d3d11.tex2d;
  10970. _sg_d3d11_AddRef(img->d3d11.res);
  10971. } else {
  10972. // 3D texture - same procedure, first check if injected, than create non-injected
  10973. if (injected) {
  10974. img->d3d11.tex3d = (ID3D11Texture3D*) desc->d3d11_texture;
  10975. _sg_d3d11_AddRef(img->d3d11.tex3d);
  10976. img->d3d11.srv = (ID3D11ShaderResourceView*) desc->d3d11_shader_resource_view;
  10977. if (img->d3d11.srv) {
  10978. _sg_d3d11_AddRef(img->d3d11.srv);
  10979. }
  10980. } else {
  10981. // not injected, create 3d texture
  10982. D3D11_TEXTURE3D_DESC d3d11_tex_desc;
  10983. _sg_clear(&d3d11_tex_desc, sizeof(d3d11_tex_desc));
  10984. d3d11_tex_desc.Width = (UINT)img->cmn.width;
  10985. d3d11_tex_desc.Height = (UINT)img->cmn.height;
  10986. d3d11_tex_desc.Depth = (UINT)img->cmn.num_slices;
  10987. d3d11_tex_desc.MipLevels = (UINT)img->cmn.num_mipmaps;
  10988. d3d11_tex_desc.Format = img->d3d11.format;
  10989. d3d11_tex_desc.BindFlags = _sg_d3d11_image_bind_flags(&img->cmn.usage, img->cmn.pixel_format);
  10990. d3d11_tex_desc.Usage = _sg_d3d11_image_usage(&img->cmn.usage);
  10991. d3d11_tex_desc.CPUAccessFlags = _sg_d3d11_image_cpu_access_flags(&img->cmn.usage);
  10992. if (img->d3d11.format == DXGI_FORMAT_UNKNOWN) {
  10993. _SG_ERROR(D3D11_CREATE_3D_TEXTURE_UNSUPPORTED_PIXEL_FORMAT);
  10994. return SG_RESOURCESTATE_FAILED;
  10995. }
  10996. hr = _sg_d3d11_CreateTexture3D(_sg.d3d11.dev, &d3d11_tex_desc, init_data, &img->d3d11.tex3d);
  10997. if (!(SUCCEEDED(hr) && img->d3d11.tex3d)) {
  10998. _SG_ERROR(D3D11_CREATE_3D_TEXTURE_FAILED);
  10999. return SG_RESOURCESTATE_FAILED;
  11000. }
  11001. _sg_d3d11_setlabel(img->d3d11.tex3d, desc->label);
  11002. // create shader-resource-view for 3D texture
  11003. if (!msaa) {
  11004. D3D11_SHADER_RESOURCE_VIEW_DESC d3d11_srv_desc;
  11005. _sg_clear(&d3d11_srv_desc, sizeof(d3d11_srv_desc));
  11006. d3d11_srv_desc.Format = _sg_d3d11_srv_pixel_format(img->cmn.pixel_format);
  11007. d3d11_srv_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D;
  11008. d3d11_srv_desc.Texture3D.MipLevels = (UINT)img->cmn.num_mipmaps;
  11009. hr = _sg_d3d11_CreateShaderResourceView(_sg.d3d11.dev, (ID3D11Resource*)img->d3d11.tex3d, &d3d11_srv_desc, &img->d3d11.srv);
  11010. if (!(SUCCEEDED(hr) && img->d3d11.srv)) {
  11011. _SG_ERROR(D3D11_CREATE_3D_SRV_FAILED);
  11012. return SG_RESOURCESTATE_FAILED;
  11013. }
  11014. _sg_d3d11_setlabel(img->d3d11.srv, desc->label);
  11015. }
  11016. }
  11017. SOKOL_ASSERT(img->d3d11.tex3d);
  11018. img->d3d11.res = (ID3D11Resource*)img->d3d11.tex3d;
  11019. _sg_d3d11_AddRef(img->d3d11.res);
  11020. }
  11021. return SG_RESOURCESTATE_VALID;
  11022. }
  11023. _SOKOL_PRIVATE void _sg_d3d11_discard_image(_sg_image_t* img) {
  11024. SOKOL_ASSERT(img);
  11025. if (img->d3d11.tex2d) {
  11026. _sg_d3d11_Release(img->d3d11.tex2d);
  11027. }
  11028. if (img->d3d11.tex3d) {
  11029. _sg_d3d11_Release(img->d3d11.tex3d);
  11030. }
  11031. if (img->d3d11.res) {
  11032. _sg_d3d11_Release(img->d3d11.res);
  11033. }
  11034. if (img->d3d11.srv) {
  11035. _sg_d3d11_Release(img->d3d11.srv);
  11036. }
  11037. }
  11038. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  11039. SOKOL_ASSERT(smp && desc);
  11040. SOKOL_ASSERT(0 == smp->d3d11.smp);
  11041. const bool injected = (0 != desc->d3d11_sampler);
  11042. if (injected) {
  11043. smp->d3d11.smp = (ID3D11SamplerState*)desc->d3d11_sampler;
  11044. _sg_d3d11_AddRef(smp->d3d11.smp);
  11045. } else {
  11046. D3D11_SAMPLER_DESC d3d11_smp_desc;
  11047. _sg_clear(&d3d11_smp_desc, sizeof(d3d11_smp_desc));
  11048. d3d11_smp_desc.Filter = _sg_d3d11_filter(desc->min_filter, desc->mag_filter, desc->mipmap_filter, desc->compare != SG_COMPAREFUNC_NEVER, desc->max_anisotropy);
  11049. d3d11_smp_desc.AddressU = _sg_d3d11_address_mode(desc->wrap_u);
  11050. d3d11_smp_desc.AddressV = _sg_d3d11_address_mode(desc->wrap_v);
  11051. d3d11_smp_desc.AddressW = _sg_d3d11_address_mode(desc->wrap_w);
  11052. d3d11_smp_desc.MipLODBias = 0.0f; // FIXME?
  11053. switch (desc->border_color) {
  11054. case SG_BORDERCOLOR_TRANSPARENT_BLACK:
  11055. // all 0.0f
  11056. break;
  11057. case SG_BORDERCOLOR_OPAQUE_WHITE:
  11058. for (int i = 0; i < 4; i++) {
  11059. d3d11_smp_desc.BorderColor[i] = 1.0f;
  11060. }
  11061. break;
  11062. default:
  11063. // opaque black
  11064. d3d11_smp_desc.BorderColor[3] = 1.0f;
  11065. break;
  11066. }
  11067. d3d11_smp_desc.MaxAnisotropy = desc->max_anisotropy;
  11068. d3d11_smp_desc.ComparisonFunc = _sg_d3d11_compare_func(desc->compare);
  11069. d3d11_smp_desc.MinLOD = desc->min_lod;
  11070. d3d11_smp_desc.MaxLOD = desc->max_lod;
  11071. HRESULT hr = _sg_d3d11_CreateSamplerState(_sg.d3d11.dev, &d3d11_smp_desc, &smp->d3d11.smp);
  11072. if (!(SUCCEEDED(hr) && smp->d3d11.smp)) {
  11073. _SG_ERROR(D3D11_CREATE_SAMPLER_STATE_FAILED);
  11074. return SG_RESOURCESTATE_FAILED;
  11075. }
  11076. _sg_d3d11_setlabel(smp->d3d11.smp, desc->label);
  11077. }
  11078. return SG_RESOURCESTATE_VALID;
  11079. }
  11080. _SOKOL_PRIVATE void _sg_d3d11_discard_sampler(_sg_sampler_t* smp) {
  11081. SOKOL_ASSERT(smp);
  11082. if (smp->d3d11.smp) {
  11083. _sg_d3d11_Release(smp->d3d11.smp);
  11084. }
  11085. }
  11086. _SOKOL_PRIVATE bool _sg_d3d11_load_d3dcompiler_dll(void) {
  11087. if ((0 == _sg.d3d11.d3dcompiler_dll) && !_sg.d3d11.d3dcompiler_dll_load_failed) {
  11088. _sg.d3d11.d3dcompiler_dll = LoadLibraryA("d3dcompiler_47.dll");
  11089. if (0 == _sg.d3d11.d3dcompiler_dll) {
  11090. // don't attempt to load missing DLL in the future
  11091. _SG_ERROR(D3D11_LOAD_D3DCOMPILER_47_DLL_FAILED);
  11092. _sg.d3d11.d3dcompiler_dll_load_failed = true;
  11093. return false;
  11094. }
  11095. // look up function pointers
  11096. _sg.d3d11.D3DCompile_func = (pD3DCompile)(void*) GetProcAddress(_sg.d3d11.d3dcompiler_dll, "D3DCompile");
  11097. SOKOL_ASSERT(_sg.d3d11.D3DCompile_func);
  11098. }
  11099. return 0 != _sg.d3d11.d3dcompiler_dll;
  11100. }
  11101. _SOKOL_PRIVATE ID3DBlob* _sg_d3d11_compile_shader(const sg_shader_function* shd_func) {
  11102. if (!_sg_d3d11_load_d3dcompiler_dll()) {
  11103. return NULL;
  11104. }
  11105. SOKOL_ASSERT(shd_func->d3d11_target);
  11106. UINT flags1 = D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR;
  11107. if (_sg.desc.d3d11_shader_debugging) {
  11108. flags1 |= D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
  11109. } else {
  11110. flags1 |= D3DCOMPILE_OPTIMIZATION_LEVEL3;
  11111. }
  11112. ID3DBlob* output = NULL;
  11113. ID3DBlob* errors_or_warnings = NULL;
  11114. HRESULT hr = _sg.d3d11.D3DCompile_func(
  11115. shd_func->source, // pSrcData
  11116. strlen(shd_func->source), // SrcDataSize
  11117. NULL, // pSourceName
  11118. NULL, // pDefines
  11119. NULL, // pInclude
  11120. shd_func->entry ? shd_func->entry : "main", // pEntryPoint
  11121. shd_func->d3d11_target, // pTarget
  11122. flags1, // Flags1
  11123. 0, // Flags2
  11124. &output, // ppCode
  11125. &errors_or_warnings); // ppErrorMsgs
  11126. if (FAILED(hr)) {
  11127. _SG_ERROR(D3D11_SHADER_COMPILATION_FAILED);
  11128. }
  11129. if (errors_or_warnings) {
  11130. _SG_WARN(D3D11_SHADER_COMPILATION_OUTPUT);
  11131. _SG_LOGMSG(D3D11_SHADER_COMPILATION_OUTPUT, (LPCSTR)_sg_d3d11_GetBufferPointer(errors_or_warnings));
  11132. _sg_d3d11_Release(errors_or_warnings); errors_or_warnings = NULL;
  11133. }
  11134. if (FAILED(hr)) {
  11135. // just in case, usually output is NULL here
  11136. if (output) {
  11137. _sg_d3d11_Release(output);
  11138. output = NULL;
  11139. }
  11140. }
  11141. return output;
  11142. }
  11143. // NOTE: this is an out-of-range check for HLSL bindslots that's also active in release mode
  11144. _SOKOL_PRIVATE bool _sg_d3d11_ensure_hlsl_bindslot_ranges(const sg_shader_desc* desc) {
  11145. SOKOL_ASSERT(desc);
  11146. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  11147. if (desc->uniform_blocks[i].hlsl_register_b_n >= _SG_D3D11_MAX_STAGE_UB_BINDINGS) {
  11148. _SG_ERROR(D3D11_UNIFORMBLOCK_HLSL_REGISTER_B_OUT_OF_RANGE);
  11149. return false;
  11150. }
  11151. }
  11152. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  11153. if (desc->storage_buffers[i].hlsl_register_t_n >= _SG_D3D11_MAX_STAGE_SRV_BINDINGS) {
  11154. _SG_ERROR(D3D11_STORAGEBUFFER_HLSL_REGISTER_T_OUT_OF_RANGE);
  11155. return false;
  11156. }
  11157. if (desc->storage_buffers[i].hlsl_register_u_n >= _SG_D3D11_MAX_STAGE_UAV_BINDINGS) {
  11158. _SG_ERROR(D3D11_STORAGEBUFFER_HLSL_REGISTER_U_OUT_OF_RANGE);
  11159. return false;
  11160. }
  11161. }
  11162. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  11163. if (desc->images[i].hlsl_register_t_n >= _SG_D3D11_MAX_STAGE_SRV_BINDINGS) {
  11164. _SG_ERROR(D3D11_IMAGE_HLSL_REGISTER_T_OUT_OF_RANGE);
  11165. return false;
  11166. }
  11167. }
  11168. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  11169. if (desc->samplers[i].hlsl_register_s_n >= _SG_D3D11_MAX_STAGE_SMP_BINDINGS) {
  11170. _SG_ERROR(D3D11_SAMPLER_HLSL_REGISTER_S_OUT_OF_RANGE);
  11171. return false;
  11172. }
  11173. }
  11174. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  11175. if (desc->storage_images[i].hlsl_register_u_n >= _SG_D3D11_MAX_STAGE_UAV_BINDINGS) {
  11176. _SG_ERROR(D3D11_STORAGEIMAGE_HLSL_REGISTER_U_OUT_OF_RANGE);
  11177. return false;
  11178. }
  11179. }
  11180. return true;
  11181. }
  11182. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  11183. SOKOL_ASSERT(shd && desc);
  11184. SOKOL_ASSERT(!shd->d3d11.vs && !shd->d3d11.fs && !shd->d3d11.cs && !shd->d3d11.vs_blob);
  11185. HRESULT hr;
  11186. // perform a range-check on HLSL bindslots that's also active in release
  11187. // mode to avoid potential out-of-bounds array accesses
  11188. if (!_sg_d3d11_ensure_hlsl_bindslot_ranges(desc)) {
  11189. return SG_RESOURCESTATE_FAILED;
  11190. }
  11191. // copy vertex attribute semantic names and indices
  11192. for (size_t i = 0; i < SG_MAX_VERTEX_ATTRIBUTES; i++) {
  11193. _sg_strcpy(&shd->d3d11.attrs[i].sem_name, desc->attrs[i].hlsl_sem_name);
  11194. shd->d3d11.attrs[i].sem_index = desc->attrs[i].hlsl_sem_index;
  11195. }
  11196. // copy HLSL bind slots
  11197. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  11198. shd->d3d11.ub_register_b_n[i] = desc->uniform_blocks[i].hlsl_register_b_n;
  11199. }
  11200. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  11201. shd->d3d11.sbuf_register_t_n[i] = desc->storage_buffers[i].hlsl_register_t_n;
  11202. shd->d3d11.sbuf_register_u_n[i] = desc->storage_buffers[i].hlsl_register_u_n;
  11203. }
  11204. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  11205. shd->d3d11.img_register_t_n[i] = desc->images[i].hlsl_register_t_n;
  11206. }
  11207. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  11208. shd->d3d11.smp_register_s_n[i] = desc->samplers[i].hlsl_register_s_n;
  11209. }
  11210. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  11211. shd->d3d11.simg_register_u_n[i] = desc->storage_images[i].hlsl_register_u_n;
  11212. }
  11213. // create a D3D constant buffer for each uniform block
  11214. for (size_t ub_index = 0; ub_index < SG_MAX_UNIFORMBLOCK_BINDSLOTS; ub_index++) {
  11215. const sg_shader_stage stage = desc->uniform_blocks[ub_index].stage;
  11216. if (stage == SG_SHADERSTAGE_NONE) {
  11217. continue;
  11218. }
  11219. const _sg_shader_uniform_block_t* ub = &shd->cmn.uniform_blocks[ub_index];
  11220. ID3D11Buffer* cbuf = 0;
  11221. D3D11_BUFFER_DESC cb_desc;
  11222. _sg_clear(&cb_desc, sizeof(cb_desc));
  11223. cb_desc.ByteWidth = (UINT)_sg_roundup((int)ub->size, 16);
  11224. cb_desc.Usage = D3D11_USAGE_DEFAULT;
  11225. cb_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  11226. hr = _sg_d3d11_CreateBuffer(_sg.d3d11.dev, &cb_desc, NULL, &cbuf);
  11227. if (!(SUCCEEDED(hr) && cbuf)) {
  11228. _SG_ERROR(D3D11_CREATE_CONSTANT_BUFFER_FAILED);
  11229. return SG_RESOURCESTATE_FAILED;
  11230. }
  11231. _sg_d3d11_setlabel(cbuf, desc->label);
  11232. shd->d3d11.all_cbufs[ub_index] = cbuf;
  11233. const uint8_t d3d11_slot = shd->d3d11.ub_register_b_n[ub_index];
  11234. SOKOL_ASSERT(d3d11_slot < _SG_D3D11_MAX_STAGE_UB_BINDINGS);
  11235. if (stage == SG_SHADERSTAGE_VERTEX) {
  11236. SOKOL_ASSERT(0 == shd->d3d11.vs_cbufs[d3d11_slot]);
  11237. shd->d3d11.vs_cbufs[d3d11_slot] = cbuf;
  11238. } else if (stage == SG_SHADERSTAGE_FRAGMENT) {
  11239. SOKOL_ASSERT(0 == shd->d3d11.fs_cbufs[d3d11_slot]);
  11240. shd->d3d11.fs_cbufs[d3d11_slot] = cbuf;
  11241. } else if (stage == SG_SHADERSTAGE_COMPUTE) {
  11242. SOKOL_ASSERT(0 == shd->d3d11.cs_cbufs[d3d11_slot]);
  11243. shd->d3d11.cs_cbufs[d3d11_slot] = cbuf;
  11244. } else {
  11245. SOKOL_UNREACHABLE;
  11246. }
  11247. }
  11248. // create shader functions
  11249. const bool has_vs = desc->vertex_func.bytecode.ptr || desc->vertex_func.source;
  11250. const bool has_fs = desc->fragment_func.bytecode.ptr || desc->fragment_func.source;
  11251. const bool has_cs = desc->compute_func.bytecode.ptr || desc->compute_func.source;
  11252. bool vs_valid = false; bool fs_valid = false; bool cs_valid = false;
  11253. if (has_vs) {
  11254. const void* vs_ptr = 0; SIZE_T vs_length = 0;
  11255. ID3DBlob* vs_blob = 0;
  11256. if (desc->vertex_func.bytecode.ptr) {
  11257. SOKOL_ASSERT(desc->vertex_func.bytecode.size > 0);
  11258. vs_ptr = desc->vertex_func.bytecode.ptr;
  11259. vs_length = desc->vertex_func.bytecode.size;
  11260. } else {
  11261. SOKOL_ASSERT(desc->vertex_func.source);
  11262. vs_blob = _sg_d3d11_compile_shader(&desc->vertex_func);
  11263. if (vs_blob) {
  11264. vs_ptr = _sg_d3d11_GetBufferPointer(vs_blob);
  11265. vs_length = _sg_d3d11_GetBufferSize(vs_blob);
  11266. }
  11267. }
  11268. if (vs_ptr && (vs_length > 0)) {
  11269. hr = _sg_d3d11_CreateVertexShader(_sg.d3d11.dev, vs_ptr, vs_length, NULL, &shd->d3d11.vs);
  11270. vs_valid = SUCCEEDED(hr) && shd->d3d11.vs;
  11271. }
  11272. // set label, and need to store a copy of the vertex shader blob for the pipeline creation
  11273. if (vs_valid) {
  11274. _sg_d3d11_setlabel(shd->d3d11.vs, desc->label);
  11275. shd->d3d11.vs_blob_length = vs_length;
  11276. shd->d3d11.vs_blob = _sg_malloc((size_t)vs_length);
  11277. SOKOL_ASSERT(shd->d3d11.vs_blob);
  11278. memcpy(shd->d3d11.vs_blob, vs_ptr, vs_length);
  11279. }
  11280. if (vs_blob) {
  11281. _sg_d3d11_Release(vs_blob);
  11282. }
  11283. }
  11284. if (has_fs) {
  11285. const void* fs_ptr = 0; SIZE_T fs_length = 0;
  11286. ID3DBlob* fs_blob = 0;
  11287. if (desc->fragment_func.bytecode.ptr) {
  11288. SOKOL_ASSERT(desc->fragment_func.bytecode.size > 0);
  11289. fs_ptr = desc->fragment_func.bytecode.ptr;
  11290. fs_length = desc->fragment_func.bytecode.size;
  11291. } else {
  11292. SOKOL_ASSERT(desc->fragment_func.source);
  11293. fs_blob = _sg_d3d11_compile_shader(&desc->fragment_func);
  11294. if (fs_blob) {
  11295. fs_ptr = _sg_d3d11_GetBufferPointer(fs_blob);
  11296. fs_length = _sg_d3d11_GetBufferSize(fs_blob);
  11297. }
  11298. }
  11299. if (fs_ptr && (fs_length > 0)) {
  11300. hr = _sg_d3d11_CreatePixelShader(_sg.d3d11.dev, fs_ptr, fs_length, NULL, &shd->d3d11.fs);
  11301. fs_valid = SUCCEEDED(hr) && shd->d3d11.fs;
  11302. }
  11303. if (fs_valid) {
  11304. _sg_d3d11_setlabel(shd->d3d11.fs, desc->label);
  11305. }
  11306. if (fs_blob) {
  11307. _sg_d3d11_Release(fs_blob);
  11308. }
  11309. }
  11310. if (has_cs) {
  11311. const void* cs_ptr = 0; SIZE_T cs_length = 0;
  11312. ID3DBlob* cs_blob = 0;
  11313. if (desc->compute_func.bytecode.ptr) {
  11314. SOKOL_ASSERT(desc->compute_func.bytecode.size > 0);
  11315. cs_ptr = desc->compute_func.bytecode.ptr;
  11316. cs_length = desc->compute_func.bytecode.size;
  11317. } else {
  11318. SOKOL_ASSERT(desc->compute_func.source);
  11319. cs_blob = _sg_d3d11_compile_shader(&desc->compute_func);
  11320. if (cs_blob) {
  11321. cs_ptr = _sg_d3d11_GetBufferPointer(cs_blob);
  11322. cs_length = _sg_d3d11_GetBufferSize(cs_blob);
  11323. }
  11324. }
  11325. if (cs_ptr && (cs_length > 0)) {
  11326. hr = _sg_d3d11_CreateComputeShader(_sg.d3d11.dev, cs_ptr, cs_length, NULL, &shd->d3d11.cs);
  11327. cs_valid = SUCCEEDED(hr) && shd->d3d11.cs;
  11328. }
  11329. if (cs_blob) {
  11330. _sg_d3d11_Release(cs_blob);
  11331. }
  11332. }
  11333. if ((vs_valid && fs_valid) || cs_valid) {
  11334. return SG_RESOURCESTATE_VALID;
  11335. } else {
  11336. return SG_RESOURCESTATE_FAILED;
  11337. }
  11338. }
  11339. _SOKOL_PRIVATE void _sg_d3d11_discard_shader(_sg_shader_t* shd) {
  11340. SOKOL_ASSERT(shd);
  11341. if (shd->d3d11.vs) {
  11342. _sg_d3d11_Release(shd->d3d11.vs);
  11343. }
  11344. if (shd->d3d11.fs) {
  11345. _sg_d3d11_Release(shd->d3d11.fs);
  11346. }
  11347. if (shd->d3d11.cs) {
  11348. _sg_d3d11_Release(shd->d3d11.cs);
  11349. }
  11350. if (shd->d3d11.vs_blob) {
  11351. _sg_free(shd->d3d11.vs_blob);
  11352. }
  11353. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  11354. if (shd->d3d11.all_cbufs[i]) {
  11355. _sg_d3d11_Release(shd->d3d11.all_cbufs[i]);
  11356. }
  11357. }
  11358. }
  11359. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_pipeline(_sg_pipeline_t* pip, _sg_shader_t* shd, const sg_pipeline_desc* desc) {
  11360. SOKOL_ASSERT(pip && shd && desc);
  11361. SOKOL_ASSERT(desc->shader.id == shd->slot.id);
  11362. SOKOL_ASSERT(shd->slot.state == SG_RESOURCESTATE_VALID);
  11363. pip->shader = shd;
  11364. // if this is a compute pipeline, we're done here
  11365. if (pip->cmn.is_compute) {
  11366. return SG_RESOURCESTATE_VALID;
  11367. }
  11368. // a render pipeline...
  11369. SOKOL_ASSERT(shd->d3d11.vs_blob && shd->d3d11.vs_blob_length > 0);
  11370. SOKOL_ASSERT(!pip->d3d11.il && !pip->d3d11.rs && !pip->d3d11.dss && !pip->d3d11.bs);
  11371. pip->d3d11.index_format = _sg_d3d11_index_format(pip->cmn.index_type);
  11372. pip->d3d11.topology = _sg_d3d11_primitive_topology(desc->primitive_type);
  11373. pip->d3d11.stencil_ref = desc->stencil.ref;
  11374. // create input layout object
  11375. HRESULT hr;
  11376. D3D11_INPUT_ELEMENT_DESC d3d11_comps[SG_MAX_VERTEX_ATTRIBUTES];
  11377. _sg_clear(d3d11_comps, sizeof(d3d11_comps));
  11378. size_t attr_index = 0;
  11379. for (; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  11380. const sg_vertex_attr_state* a_state = &desc->layout.attrs[attr_index];
  11381. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  11382. break;
  11383. }
  11384. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  11385. SOKOL_ASSERT(pip->cmn.vertex_buffer_layout_active[a_state->buffer_index]);
  11386. const sg_vertex_buffer_layout_state* l_state = &desc->layout.buffers[a_state->buffer_index];
  11387. const sg_vertex_step step_func = l_state->step_func;
  11388. const int step_rate = l_state->step_rate;
  11389. D3D11_INPUT_ELEMENT_DESC* d3d11_comp = &d3d11_comps[attr_index];
  11390. d3d11_comp->SemanticName = _sg_strptr(&shd->d3d11.attrs[attr_index].sem_name);
  11391. d3d11_comp->SemanticIndex = (UINT)shd->d3d11.attrs[attr_index].sem_index;
  11392. d3d11_comp->Format = _sg_d3d11_vertex_format(a_state->format);
  11393. d3d11_comp->InputSlot = (UINT)a_state->buffer_index;
  11394. d3d11_comp->AlignedByteOffset = (UINT)a_state->offset;
  11395. d3d11_comp->InputSlotClass = _sg_d3d11_input_classification(step_func);
  11396. if (SG_VERTEXSTEP_PER_INSTANCE == step_func) {
  11397. d3d11_comp->InstanceDataStepRate = (UINT)step_rate;
  11398. pip->cmn.use_instanced_draw = true;
  11399. }
  11400. }
  11401. for (size_t layout_index = 0; layout_index < SG_MAX_VERTEXBUFFER_BINDSLOTS; layout_index++) {
  11402. if (pip->cmn.vertex_buffer_layout_active[layout_index]) {
  11403. const sg_vertex_buffer_layout_state* l_state = &desc->layout.buffers[layout_index];
  11404. SOKOL_ASSERT(l_state->stride > 0);
  11405. pip->d3d11.vb_strides[layout_index] = (UINT)l_state->stride;
  11406. } else {
  11407. pip->d3d11.vb_strides[layout_index] = 0;
  11408. }
  11409. }
  11410. if (attr_index > 0) {
  11411. hr = _sg_d3d11_CreateInputLayout(_sg.d3d11.dev,
  11412. d3d11_comps, // pInputElementDesc
  11413. (UINT)attr_index, // NumElements
  11414. shd->d3d11.vs_blob, // pShaderByteCodeWithInputSignature
  11415. shd->d3d11.vs_blob_length, // BytecodeLength
  11416. &pip->d3d11.il);
  11417. if (!(SUCCEEDED(hr) && pip->d3d11.il)) {
  11418. _SG_ERROR(D3D11_CREATE_INPUT_LAYOUT_FAILED);
  11419. return SG_RESOURCESTATE_FAILED;
  11420. }
  11421. _sg_d3d11_setlabel(pip->d3d11.il, desc->label);
  11422. }
  11423. // create rasterizer state
  11424. D3D11_RASTERIZER_DESC rs_desc;
  11425. _sg_clear(&rs_desc, sizeof(rs_desc));
  11426. rs_desc.FillMode = D3D11_FILL_SOLID;
  11427. rs_desc.CullMode = _sg_d3d11_cull_mode(desc->cull_mode);
  11428. rs_desc.FrontCounterClockwise = desc->face_winding == SG_FACEWINDING_CCW;
  11429. rs_desc.DepthBias = (INT) pip->cmn.depth.bias;
  11430. rs_desc.DepthBiasClamp = pip->cmn.depth.bias_clamp;
  11431. rs_desc.SlopeScaledDepthBias = pip->cmn.depth.bias_slope_scale;
  11432. rs_desc.DepthClipEnable = TRUE;
  11433. rs_desc.ScissorEnable = TRUE;
  11434. rs_desc.MultisampleEnable = desc->sample_count > 1;
  11435. rs_desc.AntialiasedLineEnable = FALSE;
  11436. hr = _sg_d3d11_CreateRasterizerState(_sg.d3d11.dev, &rs_desc, &pip->d3d11.rs);
  11437. if (!(SUCCEEDED(hr) && pip->d3d11.rs)) {
  11438. _SG_ERROR(D3D11_CREATE_RASTERIZER_STATE_FAILED);
  11439. return SG_RESOURCESTATE_FAILED;
  11440. }
  11441. _sg_d3d11_setlabel(pip->d3d11.rs, desc->label);
  11442. // create depth-stencil state
  11443. D3D11_DEPTH_STENCIL_DESC dss_desc;
  11444. _sg_clear(&dss_desc, sizeof(dss_desc));
  11445. dss_desc.DepthEnable = TRUE;
  11446. dss_desc.DepthWriteMask = desc->depth.write_enabled ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
  11447. dss_desc.DepthFunc = _sg_d3d11_compare_func(desc->depth.compare);
  11448. dss_desc.StencilEnable = desc->stencil.enabled;
  11449. dss_desc.StencilReadMask = desc->stencil.read_mask;
  11450. dss_desc.StencilWriteMask = desc->stencil.write_mask;
  11451. const sg_stencil_face_state* sf = &desc->stencil.front;
  11452. dss_desc.FrontFace.StencilFailOp = _sg_d3d11_stencil_op(sf->fail_op);
  11453. dss_desc.FrontFace.StencilDepthFailOp = _sg_d3d11_stencil_op(sf->depth_fail_op);
  11454. dss_desc.FrontFace.StencilPassOp = _sg_d3d11_stencil_op(sf->pass_op);
  11455. dss_desc.FrontFace.StencilFunc = _sg_d3d11_compare_func(sf->compare);
  11456. const sg_stencil_face_state* sb = &desc->stencil.back;
  11457. dss_desc.BackFace.StencilFailOp = _sg_d3d11_stencil_op(sb->fail_op);
  11458. dss_desc.BackFace.StencilDepthFailOp = _sg_d3d11_stencil_op(sb->depth_fail_op);
  11459. dss_desc.BackFace.StencilPassOp = _sg_d3d11_stencil_op(sb->pass_op);
  11460. dss_desc.BackFace.StencilFunc = _sg_d3d11_compare_func(sb->compare);
  11461. hr = _sg_d3d11_CreateDepthStencilState(_sg.d3d11.dev, &dss_desc, &pip->d3d11.dss);
  11462. if (!(SUCCEEDED(hr) && pip->d3d11.dss)) {
  11463. _SG_ERROR(D3D11_CREATE_DEPTH_STENCIL_STATE_FAILED);
  11464. return SG_RESOURCESTATE_FAILED;
  11465. }
  11466. _sg_d3d11_setlabel(pip->d3d11.dss, desc->label);
  11467. // create blend state
  11468. D3D11_BLEND_DESC bs_desc;
  11469. _sg_clear(&bs_desc, sizeof(bs_desc));
  11470. bs_desc.AlphaToCoverageEnable = desc->alpha_to_coverage_enabled;
  11471. bs_desc.IndependentBlendEnable = TRUE;
  11472. {
  11473. size_t i = 0;
  11474. for (i = 0; i < (size_t)desc->color_count; i++) {
  11475. const sg_blend_state* src = &desc->colors[i].blend;
  11476. D3D11_RENDER_TARGET_BLEND_DESC* dst = &bs_desc.RenderTarget[i];
  11477. dst->BlendEnable = src->enabled;
  11478. dst->SrcBlend = _sg_d3d11_blend_factor(src->src_factor_rgb);
  11479. dst->DestBlend = _sg_d3d11_blend_factor(src->dst_factor_rgb);
  11480. dst->BlendOp = _sg_d3d11_blend_op(src->op_rgb);
  11481. dst->SrcBlendAlpha = _sg_d3d11_blend_factor(src->src_factor_alpha);
  11482. dst->DestBlendAlpha = _sg_d3d11_blend_factor(src->dst_factor_alpha);
  11483. dst->BlendOpAlpha = _sg_d3d11_blend_op(src->op_alpha);
  11484. dst->RenderTargetWriteMask = _sg_d3d11_color_write_mask(desc->colors[i].write_mask);
  11485. }
  11486. for (; i < 8; i++) {
  11487. D3D11_RENDER_TARGET_BLEND_DESC* dst = &bs_desc.RenderTarget[i];
  11488. dst->BlendEnable = FALSE;
  11489. dst->SrcBlend = dst->SrcBlendAlpha = D3D11_BLEND_ONE;
  11490. dst->DestBlend = dst->DestBlendAlpha = D3D11_BLEND_ZERO;
  11491. dst->BlendOp = dst->BlendOpAlpha = D3D11_BLEND_OP_ADD;
  11492. dst->RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
  11493. }
  11494. }
  11495. hr = _sg_d3d11_CreateBlendState(_sg.d3d11.dev, &bs_desc, &pip->d3d11.bs);
  11496. if (!(SUCCEEDED(hr) && pip->d3d11.bs)) {
  11497. _SG_ERROR(D3D11_CREATE_BLEND_STATE_FAILED);
  11498. return SG_RESOURCESTATE_FAILED;
  11499. }
  11500. _sg_d3d11_setlabel(pip->d3d11.bs, desc->label);
  11501. return SG_RESOURCESTATE_VALID;
  11502. }
  11503. _SOKOL_PRIVATE void _sg_d3d11_discard_pipeline(_sg_pipeline_t* pip) {
  11504. SOKOL_ASSERT(pip);
  11505. if (pip == _sg.d3d11.cur_pipeline) {
  11506. _sg.d3d11.cur_pipeline = 0;
  11507. _sg.d3d11.cur_pipeline_id.id = SG_INVALID_ID;
  11508. }
  11509. if (pip->d3d11.il) {
  11510. _sg_d3d11_Release(pip->d3d11.il);
  11511. }
  11512. if (pip->d3d11.rs) {
  11513. _sg_d3d11_Release(pip->d3d11.rs);
  11514. }
  11515. if (pip->d3d11.dss) {
  11516. _sg_d3d11_Release(pip->d3d11.dss);
  11517. }
  11518. if (pip->d3d11.bs) {
  11519. _sg_d3d11_Release(pip->d3d11.bs);
  11520. }
  11521. }
  11522. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_attachments(_sg_attachments_t* atts, const _sg_attachments_ptrs_t* atts_ptrs, const sg_attachments_desc* desc) {
  11523. SOKOL_ASSERT(atts && atts_ptrs && desc);
  11524. SOKOL_ASSERT(_sg.d3d11.dev);
  11525. // copy image pointers
  11526. for (int i = 0; i < atts->cmn.num_colors; i++) {
  11527. const sg_attachment_desc* color_desc = &desc->colors[i];
  11528. _SOKOL_UNUSED(color_desc);
  11529. SOKOL_ASSERT(color_desc->image.id != SG_INVALID_ID);
  11530. SOKOL_ASSERT(0 == atts->d3d11.colors[i].image);
  11531. SOKOL_ASSERT(atts_ptrs->color_images[i]);
  11532. _sg_image_t* clr_img = atts_ptrs->color_images[i];
  11533. SOKOL_ASSERT(clr_img->slot.id == color_desc->image.id);
  11534. SOKOL_ASSERT(_sg_is_valid_attachment_color_format(clr_img->cmn.pixel_format));
  11535. atts->d3d11.colors[i].image = clr_img;
  11536. const sg_attachment_desc* resolve_desc = &desc->resolves[i];
  11537. if (resolve_desc->image.id != SG_INVALID_ID) {
  11538. SOKOL_ASSERT(0 == atts->d3d11.resolves[i].image);
  11539. SOKOL_ASSERT(atts_ptrs->resolve_images[i]);
  11540. _sg_image_t* rsv_img = atts_ptrs->resolve_images[i];
  11541. SOKOL_ASSERT(rsv_img->slot.id == resolve_desc->image.id);
  11542. SOKOL_ASSERT(clr_img->cmn.pixel_format == rsv_img->cmn.pixel_format);
  11543. atts->d3d11.resolves[i].image = rsv_img;
  11544. }
  11545. }
  11546. SOKOL_ASSERT(0 == atts->d3d11.depth_stencil.image);
  11547. const sg_attachment_desc* ds_desc = &desc->depth_stencil;
  11548. if (ds_desc->image.id != SG_INVALID_ID) {
  11549. SOKOL_ASSERT(atts_ptrs->ds_image);
  11550. _sg_image_t* ds_img = atts_ptrs->ds_image;
  11551. SOKOL_ASSERT(ds_img->slot.id == ds_desc->image.id);
  11552. SOKOL_ASSERT(_sg_is_valid_attachment_depth_format(ds_img->cmn.pixel_format));
  11553. atts->d3d11.depth_stencil.image = ds_img;
  11554. }
  11555. for (int i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  11556. const sg_attachment_desc* storage_desc = &desc->storages[i];
  11557. if (storage_desc->image.id != SG_INVALID_ID) {
  11558. SOKOL_ASSERT(0 == atts->d3d11.storages[i].image);
  11559. SOKOL_ASSERT(atts_ptrs->storage_images[i]);
  11560. _sg_image_t* stg_img = atts_ptrs->storage_images[i];
  11561. SOKOL_ASSERT(stg_img->slot.id == storage_desc->image.id);
  11562. atts->d3d11.storages[i].image = stg_img;
  11563. }
  11564. }
  11565. // create render-target views
  11566. for (int i = 0; i < atts->cmn.num_colors; i++) {
  11567. const _sg_attachment_common_t* cmn_color_att = &atts->cmn.colors[i];
  11568. const _sg_image_t* clr_img = atts_ptrs->color_images[i];
  11569. SOKOL_ASSERT(0 == atts->d3d11.colors[i].view.rtv);
  11570. const bool msaa = clr_img->cmn.sample_count > 1;
  11571. D3D11_RENDER_TARGET_VIEW_DESC d3d11_rtv_desc;
  11572. _sg_clear(&d3d11_rtv_desc, sizeof(d3d11_rtv_desc));
  11573. d3d11_rtv_desc.Format = _sg_d3d11_rtv_uav_pixel_format(clr_img->cmn.pixel_format);
  11574. switch (clr_img->cmn.type) {
  11575. case SG_IMAGETYPE_2D:
  11576. if (msaa) {
  11577. d3d11_rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS;
  11578. } else {
  11579. d3d11_rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
  11580. d3d11_rtv_desc.Texture2D.MipSlice = (UINT)cmn_color_att->mip_level;
  11581. }
  11582. break;
  11583. case SG_IMAGETYPE_CUBE:
  11584. case SG_IMAGETYPE_ARRAY:
  11585. if (msaa) {
  11586. d3d11_rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY;
  11587. d3d11_rtv_desc.Texture2DMSArray.FirstArraySlice = (UINT)cmn_color_att->slice;
  11588. d3d11_rtv_desc.Texture2DMSArray.ArraySize = 1;
  11589. } else {
  11590. d3d11_rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
  11591. d3d11_rtv_desc.Texture2DArray.MipSlice = (UINT)cmn_color_att->mip_level;
  11592. d3d11_rtv_desc.Texture2DArray.FirstArraySlice = (UINT)cmn_color_att->slice;
  11593. d3d11_rtv_desc.Texture2DArray.ArraySize = 1;
  11594. }
  11595. break;
  11596. case SG_IMAGETYPE_3D:
  11597. SOKOL_ASSERT(!msaa);
  11598. d3d11_rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE3D;
  11599. d3d11_rtv_desc.Texture3D.MipSlice = (UINT)cmn_color_att->mip_level;
  11600. d3d11_rtv_desc.Texture3D.FirstWSlice = (UINT)cmn_color_att->slice;
  11601. d3d11_rtv_desc.Texture3D.WSize = 1;
  11602. break;
  11603. default: SOKOL_UNREACHABLE; break;
  11604. }
  11605. SOKOL_ASSERT(clr_img->d3d11.res);
  11606. HRESULT hr = _sg_d3d11_CreateRenderTargetView(_sg.d3d11.dev, clr_img->d3d11.res, &d3d11_rtv_desc, &atts->d3d11.colors[i].view.rtv);
  11607. if (!(SUCCEEDED(hr) && atts->d3d11.colors[i].view.rtv)) {
  11608. _SG_ERROR(D3D11_CREATE_RTV_FAILED);
  11609. return SG_RESOURCESTATE_FAILED;
  11610. }
  11611. _sg_d3d11_setlabel(atts->d3d11.colors[i].view.rtv, desc->label);
  11612. }
  11613. SOKOL_ASSERT(0 == atts->d3d11.depth_stencil.view.dsv);
  11614. if (ds_desc->image.id != SG_INVALID_ID) {
  11615. const _sg_attachment_common_t* cmn_ds_att = &atts->cmn.depth_stencil;
  11616. _sg_image_t* ds_img = atts_ptrs->ds_image;
  11617. const bool msaa = ds_img->cmn.sample_count > 1;
  11618. D3D11_DEPTH_STENCIL_VIEW_DESC d3d11_dsv_desc;
  11619. _sg_clear(&d3d11_dsv_desc, sizeof(d3d11_dsv_desc));
  11620. d3d11_dsv_desc.Format = _sg_d3d11_dsv_pixel_format(ds_img->cmn.pixel_format);
  11621. SOKOL_ASSERT(ds_img && ds_img->cmn.type != SG_IMAGETYPE_3D);
  11622. switch(ds_img->cmn.type) {
  11623. case SG_IMAGETYPE_2D:
  11624. if (msaa) {
  11625. d3d11_dsv_desc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
  11626. } else {
  11627. d3d11_dsv_desc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
  11628. d3d11_dsv_desc.Texture2D.MipSlice = (UINT)cmn_ds_att->mip_level;
  11629. }
  11630. break;
  11631. case SG_IMAGETYPE_CUBE:
  11632. case SG_IMAGETYPE_ARRAY:
  11633. if (msaa) {
  11634. d3d11_dsv_desc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY;
  11635. d3d11_dsv_desc.Texture2DMSArray.FirstArraySlice = (UINT)cmn_ds_att->slice;
  11636. d3d11_dsv_desc.Texture2DMSArray.ArraySize = 1;
  11637. } else {
  11638. d3d11_dsv_desc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DARRAY;
  11639. d3d11_dsv_desc.Texture2DArray.MipSlice = (UINT)cmn_ds_att->mip_level;
  11640. d3d11_dsv_desc.Texture2DArray.FirstArraySlice = (UINT)cmn_ds_att->slice;
  11641. d3d11_dsv_desc.Texture2DArray.ArraySize = 1;
  11642. }
  11643. break;
  11644. default: SOKOL_UNREACHABLE; break;
  11645. }
  11646. SOKOL_ASSERT(ds_img->d3d11.res);
  11647. HRESULT hr = _sg_d3d11_CreateDepthStencilView(_sg.d3d11.dev, ds_img->d3d11.res, &d3d11_dsv_desc, &atts->d3d11.depth_stencil.view.dsv);
  11648. if (!(SUCCEEDED(hr) && atts->d3d11.depth_stencil.view.dsv)) {
  11649. _SG_ERROR(D3D11_CREATE_DSV_FAILED);
  11650. return SG_RESOURCESTATE_FAILED;
  11651. }
  11652. _sg_d3d11_setlabel(atts->d3d11.depth_stencil.view.dsv, desc->label);
  11653. }
  11654. // create storage attachments unordered access views
  11655. for (int i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  11656. const _sg_attachment_common_t* cmn_stg_att = &atts->cmn.storages[i];
  11657. const _sg_image_t* stg_img = atts_ptrs->storage_images[i];
  11658. if (!stg_img) {
  11659. continue;
  11660. }
  11661. SOKOL_ASSERT(stg_img->cmn.sample_count == 1);
  11662. SOKOL_ASSERT(0 == atts->d3d11.storages[i].view.uav);
  11663. D3D11_UNORDERED_ACCESS_VIEW_DESC d3d11_uav_desc;
  11664. _sg_clear(&d3d11_uav_desc, sizeof(d3d11_uav_desc));
  11665. d3d11_uav_desc.Format = _sg_d3d11_rtv_uav_pixel_format(stg_img->cmn.pixel_format);
  11666. switch (stg_img->cmn.type) {
  11667. case SG_IMAGETYPE_2D:
  11668. d3d11_uav_desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D;
  11669. d3d11_uav_desc.Texture2D.MipSlice = (UINT)cmn_stg_att->mip_level;
  11670. break;
  11671. case SG_IMAGETYPE_CUBE:
  11672. case SG_IMAGETYPE_ARRAY:
  11673. d3d11_uav_desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2DARRAY;
  11674. d3d11_uav_desc.Texture2DArray.MipSlice = (UINT)cmn_stg_att->mip_level;
  11675. d3d11_uav_desc.Texture2DArray.FirstArraySlice = (UINT)cmn_stg_att->slice;
  11676. d3d11_uav_desc.Texture2DArray.ArraySize = 1;
  11677. break;
  11678. case SG_IMAGETYPE_3D:
  11679. d3d11_uav_desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE3D;
  11680. d3d11_uav_desc.Texture3D.MipSlice = (UINT)cmn_stg_att->mip_level;
  11681. d3d11_uav_desc.Texture3D.FirstWSlice = (UINT)cmn_stg_att->slice;
  11682. d3d11_uav_desc.Texture3D.WSize = 1;
  11683. break;
  11684. default: SOKOL_UNREACHABLE; break;
  11685. }
  11686. SOKOL_ASSERT(stg_img->d3d11.res);
  11687. HRESULT hr = _sg_d3d11_CreateUnorderedAccessView(_sg.d3d11.dev, stg_img->d3d11.res, &d3d11_uav_desc, &atts->d3d11.storages[i].view.uav);
  11688. if (!(SUCCEEDED(hr) && atts->d3d11.storages[i].view.uav)) {
  11689. _SG_ERROR(D3D11_CREATE_UAV_FAILED);
  11690. return SG_RESOURCESTATE_FAILED;
  11691. }
  11692. _sg_d3d11_setlabel(atts->d3d11.storages[i].view.uav, desc->label);
  11693. }
  11694. return SG_RESOURCESTATE_VALID;
  11695. }
  11696. _SOKOL_PRIVATE void _sg_d3d11_discard_attachments(_sg_attachments_t* atts) {
  11697. SOKOL_ASSERT(atts);
  11698. for (size_t i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  11699. if (atts->d3d11.colors[i].view.rtv) {
  11700. _sg_d3d11_Release(atts->d3d11.colors[i].view.rtv);
  11701. }
  11702. if (atts->d3d11.resolves[i].view.rtv) {
  11703. _sg_d3d11_Release(atts->d3d11.resolves[i].view.rtv);
  11704. }
  11705. }
  11706. if (atts->d3d11.depth_stencil.view.dsv) {
  11707. _sg_d3d11_Release(atts->d3d11.depth_stencil.view.dsv);
  11708. }
  11709. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  11710. if (atts->d3d11.storages[i].view.uav) {
  11711. _sg_d3d11_Release(atts->d3d11.storages[i].view.uav);
  11712. }
  11713. }
  11714. }
  11715. _SOKOL_PRIVATE void _sg_d3d11_begin_pass(const sg_pass* pass) {
  11716. SOKOL_ASSERT(pass);
  11717. if (_sg.cur_pass.is_compute) {
  11718. // nothing to do in compute passes
  11719. return;
  11720. }
  11721. const _sg_attachments_t* atts = _sg.cur_pass.atts;
  11722. const sg_swapchain* swapchain = &pass->swapchain;
  11723. const sg_pass_action* action = &pass->action;
  11724. int num_rtvs = 0;
  11725. ID3D11RenderTargetView* rtvs[SG_MAX_COLOR_ATTACHMENTS] = { 0 };
  11726. ID3D11DepthStencilView* dsv = 0;
  11727. _sg.d3d11.cur_pass.render_view = 0;
  11728. _sg.d3d11.cur_pass.resolve_view = 0;
  11729. if (atts) {
  11730. num_rtvs = atts->cmn.num_colors;
  11731. for (size_t i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  11732. rtvs[i] = atts->d3d11.colors[i].view.rtv;
  11733. }
  11734. dsv = atts->d3d11.depth_stencil.view.dsv;
  11735. } else {
  11736. // NOTE: depth-stencil-view is optional
  11737. SOKOL_ASSERT(swapchain->d3d11.render_view);
  11738. num_rtvs = 1;
  11739. rtvs[0] = (ID3D11RenderTargetView*) swapchain->d3d11.render_view;
  11740. dsv = (ID3D11DepthStencilView*) swapchain->d3d11.depth_stencil_view;
  11741. _sg.d3d11.cur_pass.render_view = (ID3D11RenderTargetView*) swapchain->d3d11.render_view;
  11742. _sg.d3d11.cur_pass.resolve_view = (ID3D11RenderTargetView*) swapchain->d3d11.resolve_view;
  11743. }
  11744. // apply the render-target- and depth-stencil-views
  11745. _sg_d3d11_OMSetRenderTargets(_sg.d3d11.ctx, SG_MAX_COLOR_ATTACHMENTS, rtvs, dsv);
  11746. _sg_stats_add(d3d11.pass.num_om_set_render_targets, 1);
  11747. // set viewport and scissor rect to cover whole screen
  11748. D3D11_VIEWPORT vp;
  11749. _sg_clear(&vp, sizeof(vp));
  11750. vp.Width = (FLOAT) _sg.cur_pass.width;
  11751. vp.Height = (FLOAT) _sg.cur_pass.height;
  11752. vp.MaxDepth = 1.0f;
  11753. _sg_d3d11_RSSetViewports(_sg.d3d11.ctx, 1, &vp);
  11754. D3D11_RECT rect;
  11755. rect.left = 0;
  11756. rect.top = 0;
  11757. rect.right = _sg.cur_pass.width;
  11758. rect.bottom = _sg.cur_pass.height;
  11759. _sg_d3d11_RSSetScissorRects(_sg.d3d11.ctx, 1, &rect);
  11760. // perform clear action
  11761. for (size_t i = 0; i < (size_t)num_rtvs; i++) {
  11762. if (action->colors[i].load_action == SG_LOADACTION_CLEAR) {
  11763. _sg_d3d11_ClearRenderTargetView(_sg.d3d11.ctx, rtvs[i], (float*)&action->colors[i].clear_value);
  11764. _sg_stats_add(d3d11.pass.num_clear_render_target_view, 1);
  11765. }
  11766. }
  11767. UINT ds_flags = 0;
  11768. if (action->depth.load_action == SG_LOADACTION_CLEAR) {
  11769. ds_flags |= D3D11_CLEAR_DEPTH;
  11770. }
  11771. if (action->stencil.load_action == SG_LOADACTION_CLEAR) {
  11772. ds_flags |= D3D11_CLEAR_STENCIL;
  11773. }
  11774. if ((0 != ds_flags) && dsv) {
  11775. _sg_d3d11_ClearDepthStencilView(_sg.d3d11.ctx, dsv, ds_flags, action->depth.clear_value, action->stencil.clear_value);
  11776. _sg_stats_add(d3d11.pass.num_clear_depth_stencil_view, 1);
  11777. }
  11778. }
  11779. // D3D11CalcSubresource only exists for C++
  11780. _SOKOL_PRIVATE UINT _sg_d3d11_calcsubresource(UINT mip_slice, UINT array_slice, UINT mip_levels) {
  11781. return mip_slice + array_slice * mip_levels;
  11782. }
  11783. _SOKOL_PRIVATE void _sg_d3d11_end_pass(void) {
  11784. SOKOL_ASSERT(_sg.d3d11.ctx);
  11785. if (!_sg.cur_pass.is_compute) {
  11786. // need to resolve MSAA render attachments into texture?
  11787. if (_sg.cur_pass.atts_id.id != SG_INVALID_ID) {
  11788. // ...for offscreen pass...
  11789. SOKOL_ASSERT(_sg.cur_pass.atts && _sg.cur_pass.atts->slot.id == _sg.cur_pass.atts_id.id);
  11790. for (size_t i = 0; i < (size_t)_sg.cur_pass.atts->cmn.num_colors; i++) {
  11791. const _sg_image_t* resolve_img = _sg.cur_pass.atts->d3d11.resolves[i].image;
  11792. if (resolve_img) {
  11793. const _sg_image_t* color_img = _sg.cur_pass.atts->d3d11.colors[i].image;
  11794. const _sg_attachment_common_t* cmn_color_att = &_sg.cur_pass.atts->cmn.colors[i];
  11795. const _sg_attachment_common_t* cmn_resolve_att = &_sg.cur_pass.atts->cmn.resolves[i];
  11796. SOKOL_ASSERT(resolve_img->slot.id == cmn_resolve_att->image_id.id);
  11797. SOKOL_ASSERT(color_img && (color_img->slot.id == cmn_color_att->image_id.id));
  11798. SOKOL_ASSERT(color_img->cmn.sample_count > 1);
  11799. SOKOL_ASSERT(resolve_img->cmn.sample_count == 1);
  11800. const UINT src_subres = _sg_d3d11_calcsubresource(
  11801. (UINT)cmn_color_att->mip_level,
  11802. (UINT)cmn_color_att->slice,
  11803. (UINT)color_img->cmn.num_mipmaps);
  11804. const UINT dst_subres = _sg_d3d11_calcsubresource(
  11805. (UINT)cmn_resolve_att->mip_level,
  11806. (UINT)cmn_resolve_att->slice,
  11807. (UINT)resolve_img->cmn.num_mipmaps);
  11808. _sg_d3d11_ResolveSubresource(_sg.d3d11.ctx,
  11809. resolve_img->d3d11.res,
  11810. dst_subres,
  11811. color_img->d3d11.res,
  11812. src_subres,
  11813. color_img->d3d11.format);
  11814. _sg_stats_add(d3d11.pass.num_resolve_subresource, 1);
  11815. }
  11816. }
  11817. } else {
  11818. // ...for swapchain pass...
  11819. if (_sg.d3d11.cur_pass.resolve_view) {
  11820. SOKOL_ASSERT(_sg.d3d11.cur_pass.render_view);
  11821. SOKOL_ASSERT(_sg.cur_pass.swapchain.sample_count > 1);
  11822. SOKOL_ASSERT(_sg.cur_pass.swapchain.color_fmt > SG_PIXELFORMAT_NONE);
  11823. ID3D11Resource* d3d11_render_res = 0;
  11824. ID3D11Resource* d3d11_resolve_res = 0;
  11825. _sg_d3d11_GetResource((ID3D11View*)_sg.d3d11.cur_pass.render_view, &d3d11_render_res);
  11826. _sg_d3d11_GetResource((ID3D11View*)_sg.d3d11.cur_pass.resolve_view, &d3d11_resolve_res);
  11827. SOKOL_ASSERT(d3d11_render_res);
  11828. SOKOL_ASSERT(d3d11_resolve_res);
  11829. const sg_pixel_format color_fmt = _sg.cur_pass.swapchain.color_fmt;
  11830. _sg_d3d11_ResolveSubresource(_sg.d3d11.ctx, d3d11_resolve_res, 0, d3d11_render_res, 0, _sg_d3d11_rtv_uav_pixel_format(color_fmt));
  11831. _sg_d3d11_Release(d3d11_render_res);
  11832. _sg_d3d11_Release(d3d11_resolve_res);
  11833. _sg_stats_add(d3d11.pass.num_resolve_subresource, 1);
  11834. }
  11835. }
  11836. }
  11837. _sg.d3d11.cur_pass.render_view = 0;
  11838. _sg.d3d11.cur_pass.resolve_view = 0;
  11839. _sg.d3d11.cur_pipeline = 0;
  11840. _sg.d3d11.cur_pipeline_id.id = SG_INVALID_ID;
  11841. _sg_d3d11_clear_state();
  11842. }
  11843. _SOKOL_PRIVATE void _sg_d3d11_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  11844. SOKOL_ASSERT(_sg.d3d11.ctx);
  11845. D3D11_VIEWPORT vp;
  11846. vp.TopLeftX = (FLOAT) x;
  11847. vp.TopLeftY = (FLOAT) (origin_top_left ? y : (_sg.cur_pass.height - (y + h)));
  11848. vp.Width = (FLOAT) w;
  11849. vp.Height = (FLOAT) h;
  11850. vp.MinDepth = 0.0f;
  11851. vp.MaxDepth = 1.0f;
  11852. _sg_d3d11_RSSetViewports(_sg.d3d11.ctx, 1, &vp);
  11853. }
  11854. _SOKOL_PRIVATE void _sg_d3d11_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  11855. SOKOL_ASSERT(_sg.d3d11.ctx);
  11856. D3D11_RECT rect;
  11857. rect.left = x;
  11858. rect.top = (origin_top_left ? y : (_sg.cur_pass.height - (y + h)));
  11859. rect.right = x + w;
  11860. rect.bottom = origin_top_left ? (y + h) : (_sg.cur_pass.height - y);
  11861. _sg_d3d11_RSSetScissorRects(_sg.d3d11.ctx, 1, &rect);
  11862. }
  11863. _SOKOL_PRIVATE void _sg_d3d11_populate_storage_attachment_uavs(_sg_pipeline_t* pip, ID3D11UnorderedAccessView** d3d11_cs_uavs) {
  11864. const _sg_attachments_t* atts = _sg.cur_pass.atts;
  11865. SOKOL_ASSERT(atts);
  11866. const _sg_shader_t* shd = pip->shader;
  11867. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  11868. if (shd->cmn.storage_images[i].stage != SG_SHADERSTAGE_COMPUTE) {
  11869. continue;
  11870. }
  11871. SOKOL_ASSERT(shd->d3d11.simg_register_u_n[i] < _SG_D3D11_MAX_STAGE_UAV_BINDINGS);
  11872. SOKOL_ASSERT(atts->d3d11.storages[i].view.uav);
  11873. SOKOL_ASSERT(0 == d3d11_cs_uavs[i]);
  11874. d3d11_cs_uavs[shd->d3d11.simg_register_u_n[i]] = atts->d3d11.storages[i].view.uav;
  11875. }
  11876. }
  11877. _SOKOL_PRIVATE void _sg_d3d11_apply_pipeline(_sg_pipeline_t* pip) {
  11878. SOKOL_ASSERT(pip);
  11879. SOKOL_ASSERT(pip->shader && (pip->cmn.shader_id.id == pip->shader->slot.id));
  11880. SOKOL_ASSERT(_sg.d3d11.ctx);
  11881. _sg.d3d11.cur_pipeline = pip;
  11882. _sg.d3d11.cur_pipeline_id.id = pip->slot.id;
  11883. if (pip->cmn.is_compute) {
  11884. // a compute pipeline
  11885. SOKOL_ASSERT(pip->shader->d3d11.cs);
  11886. _sg_d3d11_CSSetShader(_sg.d3d11.ctx, pip->shader->d3d11.cs, NULL, 0);
  11887. _sg_d3d11_CSSetConstantBuffers(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_UB_BINDINGS, pip->shader->d3d11.cs_cbufs);
  11888. _sg_stats_add(d3d11.pipeline.num_cs_set_shader, 1);
  11889. _sg_stats_add(d3d11.pipeline.num_cs_set_constant_buffers, 1);
  11890. // bind storage attachment UAVs
  11891. if (_sg.cur_pass.atts) {
  11892. ID3D11UnorderedAccessView* d3d11_cs_uavs[_SG_D3D11_MAX_STAGE_UAV_BINDINGS] = {0};
  11893. _sg_d3d11_populate_storage_attachment_uavs(pip, d3d11_cs_uavs);
  11894. _sg_d3d11_CSSetUnorderedAccessViews(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_UAV_BINDINGS, d3d11_cs_uavs, NULL);
  11895. _sg_stats_add(d3d11.bindings.num_cs_set_unordered_access_views, 1);
  11896. }
  11897. } else {
  11898. // a render pipeline
  11899. SOKOL_ASSERT(pip->d3d11.rs && pip->d3d11.bs && pip->d3d11.dss);
  11900. SOKOL_ASSERT(pip->shader->d3d11.vs);
  11901. SOKOL_ASSERT(pip->shader->d3d11.fs);
  11902. _sg.d3d11.use_indexed_draw = (pip->d3d11.index_format != DXGI_FORMAT_UNKNOWN);
  11903. _sg.d3d11.use_instanced_draw = pip->cmn.use_instanced_draw;
  11904. _sg_d3d11_RSSetState(_sg.d3d11.ctx, pip->d3d11.rs);
  11905. _sg_d3d11_OMSetDepthStencilState(_sg.d3d11.ctx, pip->d3d11.dss, pip->d3d11.stencil_ref);
  11906. _sg_d3d11_OMSetBlendState(_sg.d3d11.ctx, pip->d3d11.bs, (float*)&pip->cmn.blend_color, 0xFFFFFFFF);
  11907. _sg_d3d11_IASetPrimitiveTopology(_sg.d3d11.ctx, pip->d3d11.topology);
  11908. _sg_d3d11_IASetInputLayout(_sg.d3d11.ctx, pip->d3d11.il);
  11909. _sg_d3d11_VSSetShader(_sg.d3d11.ctx, pip->shader->d3d11.vs, NULL, 0);
  11910. _sg_d3d11_VSSetConstantBuffers(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_UB_BINDINGS, pip->shader->d3d11.vs_cbufs);
  11911. _sg_d3d11_PSSetShader(_sg.d3d11.ctx, pip->shader->d3d11.fs, NULL, 0);
  11912. _sg_d3d11_PSSetConstantBuffers(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_UB_BINDINGS, pip->shader->d3d11.fs_cbufs);
  11913. _sg_stats_add(d3d11.pipeline.num_rs_set_state, 1);
  11914. _sg_stats_add(d3d11.pipeline.num_om_set_depth_stencil_state, 1);
  11915. _sg_stats_add(d3d11.pipeline.num_om_set_blend_state, 1);
  11916. _sg_stats_add(d3d11.pipeline.num_ia_set_primitive_topology, 1);
  11917. _sg_stats_add(d3d11.pipeline.num_ia_set_input_layout, 1);
  11918. _sg_stats_add(d3d11.pipeline.num_vs_set_shader, 1);
  11919. _sg_stats_add(d3d11.pipeline.num_vs_set_constant_buffers, 1);
  11920. _sg_stats_add(d3d11.pipeline.num_ps_set_shader, 1);
  11921. _sg_stats_add(d3d11.pipeline.num_ps_set_constant_buffers, 1);
  11922. }
  11923. }
  11924. _SOKOL_PRIVATE bool _sg_d3d11_apply_bindings(_sg_bindings_ptrs_t* bnd) {
  11925. SOKOL_ASSERT(bnd);
  11926. SOKOL_ASSERT(bnd->pip && bnd->pip->shader);
  11927. SOKOL_ASSERT(bnd->pip->shader->slot.id == bnd->pip->cmn.shader_id.id);
  11928. SOKOL_ASSERT(_sg.d3d11.ctx);
  11929. const _sg_shader_t* shd = bnd->pip->shader;
  11930. const bool is_compute = bnd->pip->cmn.is_compute;
  11931. // gather all the D3D11 resources into arrays
  11932. ID3D11Buffer* d3d11_ib = bnd->ib ? bnd->ib->d3d11.buf : 0;
  11933. ID3D11Buffer* d3d11_vbs[SG_MAX_VERTEXBUFFER_BINDSLOTS] = {0};
  11934. UINT d3d11_vb_offsets[SG_MAX_VERTEXBUFFER_BINDSLOTS] = {0};
  11935. ID3D11ShaderResourceView* d3d11_vs_srvs[_SG_D3D11_MAX_STAGE_SRV_BINDINGS] = {0};
  11936. ID3D11ShaderResourceView* d3d11_fs_srvs[_SG_D3D11_MAX_STAGE_SRV_BINDINGS] = {0};
  11937. ID3D11ShaderResourceView* d3d11_cs_srvs[_SG_D3D11_MAX_STAGE_SRV_BINDINGS] = {0};
  11938. ID3D11SamplerState* d3d11_vs_smps[_SG_D3D11_MAX_STAGE_SMP_BINDINGS] = {0};
  11939. ID3D11SamplerState* d3d11_fs_smps[_SG_D3D11_MAX_STAGE_SMP_BINDINGS] = {0};
  11940. ID3D11SamplerState* d3d11_cs_smps[_SG_D3D11_MAX_STAGE_SMP_BINDINGS] = {0};
  11941. ID3D11UnorderedAccessView* d3d11_cs_uavs[_SG_D3D11_MAX_STAGE_UAV_BINDINGS] = {0};
  11942. if (!is_compute) {
  11943. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  11944. const _sg_buffer_t* vb = bnd->vbs[i];
  11945. if (vb == 0) {
  11946. continue;
  11947. }
  11948. SOKOL_ASSERT(vb->d3d11.buf);
  11949. d3d11_vbs[i] = vb->d3d11.buf;
  11950. d3d11_vb_offsets[i] = (UINT)bnd->vb_offsets[i];
  11951. }
  11952. }
  11953. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  11954. const _sg_image_t* img = bnd->imgs[i];
  11955. if (img == 0) {
  11956. continue;
  11957. }
  11958. const sg_shader_stage stage = shd->cmn.images[i].stage;
  11959. SOKOL_ASSERT(stage != SG_SHADERSTAGE_NONE);
  11960. const uint8_t d3d11_slot = shd->d3d11.img_register_t_n[i];
  11961. SOKOL_ASSERT(d3d11_slot < _SG_D3D11_MAX_STAGE_SRV_BINDINGS);
  11962. SOKOL_ASSERT(img->d3d11.srv);
  11963. ID3D11ShaderResourceView* d3d11_srv = img->d3d11.srv;
  11964. switch (stage) {
  11965. case SG_SHADERSTAGE_VERTEX: d3d11_vs_srvs[d3d11_slot] = d3d11_srv; break;
  11966. case SG_SHADERSTAGE_FRAGMENT: d3d11_fs_srvs[d3d11_slot] = d3d11_srv; break;
  11967. case SG_SHADERSTAGE_COMPUTE: d3d11_cs_srvs[d3d11_slot] = d3d11_srv; break;
  11968. default: SOKOL_UNREACHABLE;
  11969. }
  11970. }
  11971. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  11972. const _sg_buffer_t* sbuf = bnd->sbufs[i];
  11973. if (sbuf == 0) {
  11974. continue;
  11975. }
  11976. const sg_shader_stage stage = shd->cmn.storage_buffers[i].stage;
  11977. SOKOL_ASSERT(stage != SG_SHADERSTAGE_NONE);
  11978. if (shd->cmn.storage_buffers[i].readonly) {
  11979. SOKOL_ASSERT(sbuf->d3d11.srv);
  11980. const uint8_t d3d11_slot = shd->d3d11.sbuf_register_t_n[i];
  11981. SOKOL_ASSERT(d3d11_slot < _SG_D3D11_MAX_STAGE_SRV_BINDINGS);
  11982. ID3D11ShaderResourceView* d3d11_srv = sbuf->d3d11.srv;
  11983. switch (stage) {
  11984. case SG_SHADERSTAGE_VERTEX: d3d11_vs_srvs[d3d11_slot] = d3d11_srv; break;
  11985. case SG_SHADERSTAGE_FRAGMENT: d3d11_fs_srvs[d3d11_slot] = d3d11_srv; break;
  11986. case SG_SHADERSTAGE_COMPUTE: d3d11_cs_srvs[d3d11_slot] = d3d11_srv; break;
  11987. default: SOKOL_UNREACHABLE;
  11988. }
  11989. } else {
  11990. SOKOL_ASSERT(sbuf->d3d11.uav);
  11991. SOKOL_ASSERT(stage == SG_SHADERSTAGE_COMPUTE);
  11992. const uint8_t d3d11_slot = shd->d3d11.sbuf_register_u_n[i];
  11993. SOKOL_ASSERT(d3d11_slot < _SG_D3D11_MAX_STAGE_UAV_BINDINGS);
  11994. d3d11_cs_uavs[d3d11_slot] = sbuf->d3d11.uav;
  11995. }
  11996. }
  11997. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  11998. const _sg_sampler_t* smp = bnd->smps[i];
  11999. if (smp == 0) {
  12000. continue;
  12001. }
  12002. const sg_shader_stage stage = shd->cmn.samplers[i].stage;
  12003. SOKOL_ASSERT(stage != SG_SHADERSTAGE_NONE);
  12004. const uint8_t d3d11_slot = shd->d3d11.smp_register_s_n[i];
  12005. SOKOL_ASSERT(d3d11_slot < _SG_D3D11_MAX_STAGE_SMP_BINDINGS);
  12006. SOKOL_ASSERT(smp->d3d11.smp);
  12007. ID3D11SamplerState* d3d11_smp = smp->d3d11.smp;
  12008. switch (stage) {
  12009. case SG_SHADERSTAGE_VERTEX: d3d11_vs_smps[d3d11_slot] = d3d11_smp; break;
  12010. case SG_SHADERSTAGE_FRAGMENT: d3d11_fs_smps[d3d11_slot] = d3d11_smp; break;
  12011. case SG_SHADERSTAGE_COMPUTE: d3d11_cs_smps[d3d11_slot] = d3d11_smp; break;
  12012. default: SOKOL_UNREACHABLE;
  12013. }
  12014. }
  12015. if (is_compute) {
  12016. // in a compute pass with storage attachments, also need to rebind the storage attachments
  12017. if (_sg.cur_pass.atts) {
  12018. _sg_d3d11_populate_storage_attachment_uavs(bnd->pip, d3d11_cs_uavs);
  12019. }
  12020. _sg_d3d11_CSSetShaderResources(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_SRV_BINDINGS, d3d11_cs_srvs);
  12021. _sg_d3d11_CSSetSamplers(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_SMP_BINDINGS, d3d11_cs_smps);
  12022. _sg_d3d11_CSSetUnorderedAccessViews(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_UAV_BINDINGS, d3d11_cs_uavs, NULL);
  12023. _sg_stats_add(d3d11.bindings.num_cs_set_shader_resources, 1);
  12024. _sg_stats_add(d3d11.bindings.num_cs_set_samplers, 1);
  12025. _sg_stats_add(d3d11.bindings.num_cs_set_unordered_access_views, 1);
  12026. } else {
  12027. _sg_d3d11_IASetVertexBuffers(_sg.d3d11.ctx, 0, SG_MAX_VERTEXBUFFER_BINDSLOTS, d3d11_vbs, bnd->pip->d3d11.vb_strides, d3d11_vb_offsets);
  12028. _sg_d3d11_IASetIndexBuffer(_sg.d3d11.ctx, d3d11_ib, bnd->pip->d3d11.index_format, (UINT)bnd->ib_offset);
  12029. _sg_d3d11_VSSetShaderResources(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_SRV_BINDINGS, d3d11_vs_srvs);
  12030. _sg_d3d11_PSSetShaderResources(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_SRV_BINDINGS, d3d11_fs_srvs);
  12031. _sg_d3d11_VSSetSamplers(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_SMP_BINDINGS, d3d11_vs_smps);
  12032. _sg_d3d11_PSSetSamplers(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_SMP_BINDINGS, d3d11_fs_smps);
  12033. _sg_stats_add(d3d11.bindings.num_ia_set_vertex_buffers, 1);
  12034. _sg_stats_add(d3d11.bindings.num_ia_set_index_buffer, 1);
  12035. _sg_stats_add(d3d11.bindings.num_vs_set_shader_resources, 1);
  12036. _sg_stats_add(d3d11.bindings.num_ps_set_shader_resources, 1);
  12037. _sg_stats_add(d3d11.bindings.num_vs_set_samplers, 1);
  12038. _sg_stats_add(d3d11.bindings.num_ps_set_samplers, 1);
  12039. }
  12040. return true;
  12041. }
  12042. _SOKOL_PRIVATE void _sg_d3d11_apply_uniforms(int ub_slot, const sg_range* data) {
  12043. SOKOL_ASSERT(_sg.d3d11.ctx);
  12044. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  12045. SOKOL_ASSERT(_sg.d3d11.cur_pipeline && _sg.d3d11.cur_pipeline->slot.id == _sg.d3d11.cur_pipeline_id.id);
  12046. const _sg_shader_t* shd = _sg.d3d11.cur_pipeline->shader;
  12047. SOKOL_ASSERT(shd && (shd->slot.id == _sg.d3d11.cur_pipeline->cmn.shader_id.id));
  12048. SOKOL_ASSERT(data->size == shd->cmn.uniform_blocks[ub_slot].size);
  12049. ID3D11Buffer* cbuf = shd->d3d11.all_cbufs[ub_slot];
  12050. SOKOL_ASSERT(cbuf);
  12051. _sg_d3d11_UpdateSubresource(_sg.d3d11.ctx, (ID3D11Resource*)cbuf, 0, NULL, data->ptr, 0, 0);
  12052. _sg_stats_add(d3d11.uniforms.num_update_subresource, 1);
  12053. }
  12054. _SOKOL_PRIVATE void _sg_d3d11_draw(int base_element, int num_elements, int num_instances) {
  12055. const bool use_instanced_draw = (num_instances > 1) || (_sg.d3d11.use_instanced_draw);
  12056. if (_sg.d3d11.use_indexed_draw) {
  12057. if (use_instanced_draw) {
  12058. _sg_d3d11_DrawIndexedInstanced(_sg.d3d11.ctx, (UINT)num_elements, (UINT)num_instances, (UINT)base_element, 0, 0);
  12059. _sg_stats_add(d3d11.draw.num_draw_indexed_instanced, 1);
  12060. } else {
  12061. _sg_d3d11_DrawIndexed(_sg.d3d11.ctx, (UINT)num_elements, (UINT)base_element, 0);
  12062. _sg_stats_add(d3d11.draw.num_draw_indexed, 1);
  12063. }
  12064. } else {
  12065. if (use_instanced_draw) {
  12066. _sg_d3d11_DrawInstanced(_sg.d3d11.ctx, (UINT)num_elements, (UINT)num_instances, (UINT)base_element, 0);
  12067. _sg_stats_add(d3d11.draw.num_draw_instanced, 1);
  12068. } else {
  12069. _sg_d3d11_Draw(_sg.d3d11.ctx, (UINT)num_elements, (UINT)base_element);
  12070. _sg_stats_add(d3d11.draw.num_draw, 1);
  12071. }
  12072. }
  12073. }
  12074. _SOKOL_PRIVATE void _sg_d3d11_dispatch(int num_groups_x, int num_groups_y, int num_groups_z) {
  12075. _sg_d3d11_Dispatch(_sg.d3d11.ctx, (UINT)num_groups_x, (UINT)num_groups_y, (UINT)num_groups_z);
  12076. }
  12077. _SOKOL_PRIVATE void _sg_d3d11_commit(void) {
  12078. // empty
  12079. }
  12080. _SOKOL_PRIVATE void _sg_d3d11_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  12081. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  12082. SOKOL_ASSERT(_sg.d3d11.ctx);
  12083. SOKOL_ASSERT(buf->d3d11.buf);
  12084. D3D11_MAPPED_SUBRESOURCE d3d11_msr;
  12085. HRESULT hr = _sg_d3d11_Map(_sg.d3d11.ctx, (ID3D11Resource*)buf->d3d11.buf, 0, D3D11_MAP_WRITE_DISCARD, 0, &d3d11_msr);
  12086. _sg_stats_add(d3d11.num_map, 1);
  12087. if (SUCCEEDED(hr)) {
  12088. memcpy(d3d11_msr.pData, data->ptr, data->size);
  12089. _sg_d3d11_Unmap(_sg.d3d11.ctx, (ID3D11Resource*)buf->d3d11.buf, 0);
  12090. _sg_stats_add(d3d11.num_unmap, 1);
  12091. } else {
  12092. _SG_ERROR(D3D11_MAP_FOR_UPDATE_BUFFER_FAILED);
  12093. }
  12094. }
  12095. _SOKOL_PRIVATE void _sg_d3d11_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  12096. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  12097. SOKOL_ASSERT(_sg.d3d11.ctx);
  12098. SOKOL_ASSERT(buf->d3d11.buf);
  12099. D3D11_MAP map_type = new_frame ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE_NO_OVERWRITE;
  12100. D3D11_MAPPED_SUBRESOURCE d3d11_msr;
  12101. HRESULT hr = _sg_d3d11_Map(_sg.d3d11.ctx, (ID3D11Resource*)buf->d3d11.buf, 0, map_type, 0, &d3d11_msr);
  12102. _sg_stats_add(d3d11.num_map, 1);
  12103. if (SUCCEEDED(hr)) {
  12104. uint8_t* dst_ptr = (uint8_t*)d3d11_msr.pData + buf->cmn.append_pos;
  12105. memcpy(dst_ptr, data->ptr, data->size);
  12106. _sg_d3d11_Unmap(_sg.d3d11.ctx, (ID3D11Resource*)buf->d3d11.buf, 0);
  12107. _sg_stats_add(d3d11.num_unmap, 1);
  12108. } else {
  12109. _SG_ERROR(D3D11_MAP_FOR_APPEND_BUFFER_FAILED);
  12110. }
  12111. }
  12112. // see: https://learn.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-resources-subresources
  12113. // also see: https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-d3d11calcsubresource
  12114. _SOKOL_PRIVATE void _sg_d3d11_update_image(_sg_image_t* img, const sg_image_data* data) {
  12115. SOKOL_ASSERT(img && data);
  12116. SOKOL_ASSERT(_sg.d3d11.ctx);
  12117. SOKOL_ASSERT(img->d3d11.res);
  12118. const int num_faces = (img->cmn.type == SG_IMAGETYPE_CUBE) ? 6:1;
  12119. const int num_slices = (img->cmn.type == SG_IMAGETYPE_ARRAY) ? img->cmn.num_slices:1;
  12120. const int num_depth_slices = (img->cmn.type == SG_IMAGETYPE_3D) ? img->cmn.num_slices:1;
  12121. UINT subres_index = 0;
  12122. HRESULT hr;
  12123. D3D11_MAPPED_SUBRESOURCE d3d11_msr;
  12124. for (int face_index = 0; face_index < num_faces; face_index++) {
  12125. for (int slice_index = 0; slice_index < num_slices; slice_index++) {
  12126. for (int mip_index = 0; mip_index < img->cmn.num_mipmaps; mip_index++, subres_index++) {
  12127. SOKOL_ASSERT(subres_index < (SG_MAX_MIPMAPS * SG_MAX_TEXTUREARRAY_LAYERS));
  12128. const int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  12129. const int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  12130. const int src_row_pitch = _sg_row_pitch(img->cmn.pixel_format, mip_width, 1);
  12131. const int src_depth_pitch = _sg_surface_pitch(img->cmn.pixel_format, mip_width, mip_height, 1);
  12132. const sg_range* subimg_data = &(data->subimage[face_index][mip_index]);
  12133. const size_t slice_size = subimg_data->size / (size_t)num_slices;
  12134. SOKOL_ASSERT(slice_size == (size_t)(src_depth_pitch * num_depth_slices));
  12135. const size_t slice_offset = slice_size * (size_t)slice_index;
  12136. const uint8_t* slice_ptr = ((const uint8_t*)subimg_data->ptr) + slice_offset;
  12137. hr = _sg_d3d11_Map(_sg.d3d11.ctx, img->d3d11.res, subres_index, D3D11_MAP_WRITE_DISCARD, 0, &d3d11_msr);
  12138. _sg_stats_add(d3d11.num_map, 1);
  12139. if (SUCCEEDED(hr)) {
  12140. const uint8_t* src_ptr = slice_ptr;
  12141. uint8_t* dst_ptr = (uint8_t*)d3d11_msr.pData;
  12142. for (int depth_index = 0; depth_index < num_depth_slices; depth_index++) {
  12143. if (src_row_pitch == (int)d3d11_msr.RowPitch) {
  12144. const size_t copy_size = slice_size / (size_t)num_depth_slices;
  12145. SOKOL_ASSERT((copy_size * (size_t)num_depth_slices) == slice_size);
  12146. memcpy(dst_ptr, src_ptr, copy_size);
  12147. } else {
  12148. SOKOL_ASSERT(src_row_pitch < (int)d3d11_msr.RowPitch);
  12149. const uint8_t* src_row_ptr = src_ptr;
  12150. uint8_t* dst_row_ptr = dst_ptr;
  12151. for (int row_index = 0; row_index < mip_height; row_index++) {
  12152. memcpy(dst_row_ptr, src_row_ptr, (size_t)src_row_pitch);
  12153. src_row_ptr += src_row_pitch;
  12154. dst_row_ptr += d3d11_msr.RowPitch;
  12155. }
  12156. }
  12157. src_ptr += src_depth_pitch;
  12158. dst_ptr += d3d11_msr.DepthPitch;
  12159. }
  12160. _sg_d3d11_Unmap(_sg.d3d11.ctx, img->d3d11.res, subres_index);
  12161. _sg_stats_add(d3d11.num_unmap, 1);
  12162. } else {
  12163. _SG_ERROR(D3D11_MAP_FOR_UPDATE_IMAGE_FAILED);
  12164. }
  12165. }
  12166. }
  12167. }
  12168. }
  12169. // ███ ███ ███████ ████████ █████ ██ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  12170. // ████ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  12171. // ██ ████ ██ █████ ██ ███████ ██ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  12172. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  12173. // ██ ██ ███████ ██ ██ ██ ███████ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  12174. //
  12175. // >>metal backend
  12176. #elif defined(SOKOL_METAL)
  12177. #if __has_feature(objc_arc)
  12178. #define _SG_OBJC_RETAIN(obj) { }
  12179. #define _SG_OBJC_RELEASE(obj) { obj = nil; }
  12180. #else
  12181. #define _SG_OBJC_RETAIN(obj) { [obj retain]; }
  12182. #define _SG_OBJC_RELEASE(obj) { [obj release]; obj = nil; }
  12183. #endif
  12184. //-- enum translation functions ------------------------------------------------
  12185. _SOKOL_PRIVATE MTLLoadAction _sg_mtl_load_action(sg_load_action a) {
  12186. switch (a) {
  12187. case SG_LOADACTION_CLEAR: return MTLLoadActionClear;
  12188. case SG_LOADACTION_LOAD: return MTLLoadActionLoad;
  12189. case SG_LOADACTION_DONTCARE: return MTLLoadActionDontCare;
  12190. default: SOKOL_UNREACHABLE; return (MTLLoadAction)0;
  12191. }
  12192. }
  12193. _SOKOL_PRIVATE MTLStoreAction _sg_mtl_store_action(sg_store_action a, bool resolve) {
  12194. switch (a) {
  12195. case SG_STOREACTION_STORE:
  12196. if (resolve) {
  12197. return MTLStoreActionStoreAndMultisampleResolve;
  12198. } else {
  12199. return MTLStoreActionStore;
  12200. }
  12201. break;
  12202. case SG_STOREACTION_DONTCARE:
  12203. if (resolve) {
  12204. return MTLStoreActionMultisampleResolve;
  12205. } else {
  12206. return MTLStoreActionDontCare;
  12207. }
  12208. break;
  12209. default: SOKOL_UNREACHABLE; return (MTLStoreAction)0;
  12210. }
  12211. }
  12212. _SOKOL_PRIVATE MTLResourceOptions _sg_mtl_resource_options_storage_mode_managed_or_shared(void) {
  12213. #if defined(_SG_TARGET_MACOS)
  12214. if (_sg.mtl.use_shared_storage_mode) {
  12215. return MTLResourceStorageModeShared;
  12216. } else {
  12217. return MTLResourceStorageModeManaged;
  12218. }
  12219. #else
  12220. // MTLResourceStorageModeManaged is not even defined on iOS SDK
  12221. return MTLResourceStorageModeShared;
  12222. #endif
  12223. }
  12224. _SOKOL_PRIVATE MTLResourceOptions _sg_mtl_buffer_resource_options(const sg_buffer_usage* usage) {
  12225. if (usage->immutable) {
  12226. return _sg_mtl_resource_options_storage_mode_managed_or_shared();
  12227. } else {
  12228. return MTLResourceCPUCacheModeWriteCombined | _sg_mtl_resource_options_storage_mode_managed_or_shared();
  12229. }
  12230. }
  12231. _SOKOL_PRIVATE MTLVertexStepFunction _sg_mtl_step_function(sg_vertex_step step) {
  12232. switch (step) {
  12233. case SG_VERTEXSTEP_PER_VERTEX: return MTLVertexStepFunctionPerVertex;
  12234. case SG_VERTEXSTEP_PER_INSTANCE: return MTLVertexStepFunctionPerInstance;
  12235. default: SOKOL_UNREACHABLE; return (MTLVertexStepFunction)0;
  12236. }
  12237. }
  12238. _SOKOL_PRIVATE MTLVertexFormat _sg_mtl_vertex_format(sg_vertex_format fmt) {
  12239. switch (fmt) {
  12240. case SG_VERTEXFORMAT_FLOAT: return MTLVertexFormatFloat;
  12241. case SG_VERTEXFORMAT_FLOAT2: return MTLVertexFormatFloat2;
  12242. case SG_VERTEXFORMAT_FLOAT3: return MTLVertexFormatFloat3;
  12243. case SG_VERTEXFORMAT_FLOAT4: return MTLVertexFormatFloat4;
  12244. case SG_VERTEXFORMAT_INT: return MTLVertexFormatInt;
  12245. case SG_VERTEXFORMAT_INT2: return MTLVertexFormatInt2;
  12246. case SG_VERTEXFORMAT_INT3: return MTLVertexFormatInt3;
  12247. case SG_VERTEXFORMAT_INT4: return MTLVertexFormatInt4;
  12248. case SG_VERTEXFORMAT_UINT: return MTLVertexFormatUInt;
  12249. case SG_VERTEXFORMAT_UINT2: return MTLVertexFormatUInt2;
  12250. case SG_VERTEXFORMAT_UINT3: return MTLVertexFormatUInt3;
  12251. case SG_VERTEXFORMAT_UINT4: return MTLVertexFormatUInt4;
  12252. case SG_VERTEXFORMAT_BYTE4: return MTLVertexFormatChar4;
  12253. case SG_VERTEXFORMAT_BYTE4N: return MTLVertexFormatChar4Normalized;
  12254. case SG_VERTEXFORMAT_UBYTE4: return MTLVertexFormatUChar4;
  12255. case SG_VERTEXFORMAT_UBYTE4N: return MTLVertexFormatUChar4Normalized;
  12256. case SG_VERTEXFORMAT_SHORT2: return MTLVertexFormatShort2;
  12257. case SG_VERTEXFORMAT_SHORT2N: return MTLVertexFormatShort2Normalized;
  12258. case SG_VERTEXFORMAT_USHORT2: return MTLVertexFormatUShort2;
  12259. case SG_VERTEXFORMAT_USHORT2N: return MTLVertexFormatUShort2Normalized;
  12260. case SG_VERTEXFORMAT_SHORT4: return MTLVertexFormatShort4;
  12261. case SG_VERTEXFORMAT_SHORT4N: return MTLVertexFormatShort4Normalized;
  12262. case SG_VERTEXFORMAT_USHORT4: return MTLVertexFormatUShort4;
  12263. case SG_VERTEXFORMAT_USHORT4N: return MTLVertexFormatUShort4Normalized;
  12264. case SG_VERTEXFORMAT_UINT10_N2: return MTLVertexFormatUInt1010102Normalized;
  12265. case SG_VERTEXFORMAT_HALF2: return MTLVertexFormatHalf2;
  12266. case SG_VERTEXFORMAT_HALF4: return MTLVertexFormatHalf4;
  12267. default: SOKOL_UNREACHABLE; return (MTLVertexFormat)0;
  12268. }
  12269. }
  12270. _SOKOL_PRIVATE MTLPrimitiveType _sg_mtl_primitive_type(sg_primitive_type t) {
  12271. switch (t) {
  12272. case SG_PRIMITIVETYPE_POINTS: return MTLPrimitiveTypePoint;
  12273. case SG_PRIMITIVETYPE_LINES: return MTLPrimitiveTypeLine;
  12274. case SG_PRIMITIVETYPE_LINE_STRIP: return MTLPrimitiveTypeLineStrip;
  12275. case SG_PRIMITIVETYPE_TRIANGLES: return MTLPrimitiveTypeTriangle;
  12276. case SG_PRIMITIVETYPE_TRIANGLE_STRIP: return MTLPrimitiveTypeTriangleStrip;
  12277. default: SOKOL_UNREACHABLE; return (MTLPrimitiveType)0;
  12278. }
  12279. }
  12280. _SOKOL_PRIVATE MTLPixelFormat _sg_mtl_pixel_format(sg_pixel_format fmt) {
  12281. switch (fmt) {
  12282. case SG_PIXELFORMAT_R8: return MTLPixelFormatR8Unorm;
  12283. case SG_PIXELFORMAT_R8SN: return MTLPixelFormatR8Snorm;
  12284. case SG_PIXELFORMAT_R8UI: return MTLPixelFormatR8Uint;
  12285. case SG_PIXELFORMAT_R8SI: return MTLPixelFormatR8Sint;
  12286. case SG_PIXELFORMAT_R16: return MTLPixelFormatR16Unorm;
  12287. case SG_PIXELFORMAT_R16SN: return MTLPixelFormatR16Snorm;
  12288. case SG_PIXELFORMAT_R16UI: return MTLPixelFormatR16Uint;
  12289. case SG_PIXELFORMAT_R16SI: return MTLPixelFormatR16Sint;
  12290. case SG_PIXELFORMAT_R16F: return MTLPixelFormatR16Float;
  12291. case SG_PIXELFORMAT_RG8: return MTLPixelFormatRG8Unorm;
  12292. case SG_PIXELFORMAT_RG8SN: return MTLPixelFormatRG8Snorm;
  12293. case SG_PIXELFORMAT_RG8UI: return MTLPixelFormatRG8Uint;
  12294. case SG_PIXELFORMAT_RG8SI: return MTLPixelFormatRG8Sint;
  12295. case SG_PIXELFORMAT_R32UI: return MTLPixelFormatR32Uint;
  12296. case SG_PIXELFORMAT_R32SI: return MTLPixelFormatR32Sint;
  12297. case SG_PIXELFORMAT_R32F: return MTLPixelFormatR32Float;
  12298. case SG_PIXELFORMAT_RG16: return MTLPixelFormatRG16Unorm;
  12299. case SG_PIXELFORMAT_RG16SN: return MTLPixelFormatRG16Snorm;
  12300. case SG_PIXELFORMAT_RG16UI: return MTLPixelFormatRG16Uint;
  12301. case SG_PIXELFORMAT_RG16SI: return MTLPixelFormatRG16Sint;
  12302. case SG_PIXELFORMAT_RG16F: return MTLPixelFormatRG16Float;
  12303. case SG_PIXELFORMAT_RGBA8: return MTLPixelFormatRGBA8Unorm;
  12304. case SG_PIXELFORMAT_SRGB8A8: return MTLPixelFormatRGBA8Unorm_sRGB;
  12305. case SG_PIXELFORMAT_RGBA8SN: return MTLPixelFormatRGBA8Snorm;
  12306. case SG_PIXELFORMAT_RGBA8UI: return MTLPixelFormatRGBA8Uint;
  12307. case SG_PIXELFORMAT_RGBA8SI: return MTLPixelFormatRGBA8Sint;
  12308. case SG_PIXELFORMAT_BGRA8: return MTLPixelFormatBGRA8Unorm;
  12309. case SG_PIXELFORMAT_RGB10A2: return MTLPixelFormatRGB10A2Unorm;
  12310. case SG_PIXELFORMAT_RG11B10F: return MTLPixelFormatRG11B10Float;
  12311. case SG_PIXELFORMAT_RGB9E5: return MTLPixelFormatRGB9E5Float;
  12312. case SG_PIXELFORMAT_RG32UI: return MTLPixelFormatRG32Uint;
  12313. case SG_PIXELFORMAT_RG32SI: return MTLPixelFormatRG32Sint;
  12314. case SG_PIXELFORMAT_RG32F: return MTLPixelFormatRG32Float;
  12315. case SG_PIXELFORMAT_RGBA16: return MTLPixelFormatRGBA16Unorm;
  12316. case SG_PIXELFORMAT_RGBA16SN: return MTLPixelFormatRGBA16Snorm;
  12317. case SG_PIXELFORMAT_RGBA16UI: return MTLPixelFormatRGBA16Uint;
  12318. case SG_PIXELFORMAT_RGBA16SI: return MTLPixelFormatRGBA16Sint;
  12319. case SG_PIXELFORMAT_RGBA16F: return MTLPixelFormatRGBA16Float;
  12320. case SG_PIXELFORMAT_RGBA32UI: return MTLPixelFormatRGBA32Uint;
  12321. case SG_PIXELFORMAT_RGBA32SI: return MTLPixelFormatRGBA32Sint;
  12322. case SG_PIXELFORMAT_RGBA32F: return MTLPixelFormatRGBA32Float;
  12323. case SG_PIXELFORMAT_DEPTH: return MTLPixelFormatDepth32Float;
  12324. case SG_PIXELFORMAT_DEPTH_STENCIL: return MTLPixelFormatDepth32Float_Stencil8;
  12325. #if defined(_SG_TARGET_MACOS)
  12326. case SG_PIXELFORMAT_BC1_RGBA: return MTLPixelFormatBC1_RGBA;
  12327. case SG_PIXELFORMAT_BC2_RGBA: return MTLPixelFormatBC2_RGBA;
  12328. case SG_PIXELFORMAT_BC3_RGBA: return MTLPixelFormatBC3_RGBA;
  12329. case SG_PIXELFORMAT_BC3_SRGBA: return MTLPixelFormatBC3_RGBA_sRGB;
  12330. case SG_PIXELFORMAT_BC4_R: return MTLPixelFormatBC4_RUnorm;
  12331. case SG_PIXELFORMAT_BC4_RSN: return MTLPixelFormatBC4_RSnorm;
  12332. case SG_PIXELFORMAT_BC5_RG: return MTLPixelFormatBC5_RGUnorm;
  12333. case SG_PIXELFORMAT_BC5_RGSN: return MTLPixelFormatBC5_RGSnorm;
  12334. case SG_PIXELFORMAT_BC6H_RGBF: return MTLPixelFormatBC6H_RGBFloat;
  12335. case SG_PIXELFORMAT_BC6H_RGBUF: return MTLPixelFormatBC6H_RGBUfloat;
  12336. case SG_PIXELFORMAT_BC7_RGBA: return MTLPixelFormatBC7_RGBAUnorm;
  12337. case SG_PIXELFORMAT_BC7_SRGBA: return MTLPixelFormatBC7_RGBAUnorm_sRGB;
  12338. #else
  12339. case SG_PIXELFORMAT_ETC2_RGB8: return MTLPixelFormatETC2_RGB8;
  12340. case SG_PIXELFORMAT_ETC2_SRGB8: return MTLPixelFormatETC2_RGB8_sRGB;
  12341. case SG_PIXELFORMAT_ETC2_RGB8A1: return MTLPixelFormatETC2_RGB8A1;
  12342. case SG_PIXELFORMAT_ETC2_RGBA8: return MTLPixelFormatEAC_RGBA8;
  12343. case SG_PIXELFORMAT_ETC2_SRGB8A8: return MTLPixelFormatEAC_RGBA8_sRGB;
  12344. case SG_PIXELFORMAT_EAC_R11: return MTLPixelFormatEAC_R11Unorm;
  12345. case SG_PIXELFORMAT_EAC_R11SN: return MTLPixelFormatEAC_R11Snorm;
  12346. case SG_PIXELFORMAT_EAC_RG11: return MTLPixelFormatEAC_RG11Unorm;
  12347. case SG_PIXELFORMAT_EAC_RG11SN: return MTLPixelFormatEAC_RG11Snorm;
  12348. case SG_PIXELFORMAT_ASTC_4x4_RGBA: return MTLPixelFormatASTC_4x4_LDR;
  12349. case SG_PIXELFORMAT_ASTC_4x4_SRGBA: return MTLPixelFormatASTC_4x4_sRGB;
  12350. #endif
  12351. default: return MTLPixelFormatInvalid;
  12352. }
  12353. }
  12354. _SOKOL_PRIVATE MTLColorWriteMask _sg_mtl_color_write_mask(sg_color_mask m) {
  12355. MTLColorWriteMask mtl_mask = MTLColorWriteMaskNone;
  12356. if (m & SG_COLORMASK_R) {
  12357. mtl_mask |= MTLColorWriteMaskRed;
  12358. }
  12359. if (m & SG_COLORMASK_G) {
  12360. mtl_mask |= MTLColorWriteMaskGreen;
  12361. }
  12362. if (m & SG_COLORMASK_B) {
  12363. mtl_mask |= MTLColorWriteMaskBlue;
  12364. }
  12365. if (m & SG_COLORMASK_A) {
  12366. mtl_mask |= MTLColorWriteMaskAlpha;
  12367. }
  12368. return mtl_mask;
  12369. }
  12370. _SOKOL_PRIVATE MTLBlendOperation _sg_mtl_blend_op(sg_blend_op op) {
  12371. switch (op) {
  12372. case SG_BLENDOP_ADD: return MTLBlendOperationAdd;
  12373. case SG_BLENDOP_SUBTRACT: return MTLBlendOperationSubtract;
  12374. case SG_BLENDOP_REVERSE_SUBTRACT: return MTLBlendOperationReverseSubtract;
  12375. case SG_BLENDOP_MIN: return MTLBlendOperationMin;
  12376. case SG_BLENDOP_MAX: return MTLBlendOperationMax;
  12377. default: SOKOL_UNREACHABLE; return (MTLBlendOperation)0;
  12378. }
  12379. }
  12380. _SOKOL_PRIVATE MTLBlendFactor _sg_mtl_blend_factor(sg_blend_factor f) {
  12381. switch (f) {
  12382. case SG_BLENDFACTOR_ZERO: return MTLBlendFactorZero;
  12383. case SG_BLENDFACTOR_ONE: return MTLBlendFactorOne;
  12384. case SG_BLENDFACTOR_SRC_COLOR: return MTLBlendFactorSourceColor;
  12385. case SG_BLENDFACTOR_ONE_MINUS_SRC_COLOR: return MTLBlendFactorOneMinusSourceColor;
  12386. case SG_BLENDFACTOR_SRC_ALPHA: return MTLBlendFactorSourceAlpha;
  12387. case SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA: return MTLBlendFactorOneMinusSourceAlpha;
  12388. case SG_BLENDFACTOR_DST_COLOR: return MTLBlendFactorDestinationColor;
  12389. case SG_BLENDFACTOR_ONE_MINUS_DST_COLOR: return MTLBlendFactorOneMinusDestinationColor;
  12390. case SG_BLENDFACTOR_DST_ALPHA: return MTLBlendFactorDestinationAlpha;
  12391. case SG_BLENDFACTOR_ONE_MINUS_DST_ALPHA: return MTLBlendFactorOneMinusDestinationAlpha;
  12392. case SG_BLENDFACTOR_SRC_ALPHA_SATURATED: return MTLBlendFactorSourceAlphaSaturated;
  12393. case SG_BLENDFACTOR_BLEND_COLOR: return MTLBlendFactorBlendColor;
  12394. case SG_BLENDFACTOR_ONE_MINUS_BLEND_COLOR: return MTLBlendFactorOneMinusBlendColor;
  12395. case SG_BLENDFACTOR_BLEND_ALPHA: return MTLBlendFactorBlendAlpha;
  12396. case SG_BLENDFACTOR_ONE_MINUS_BLEND_ALPHA: return MTLBlendFactorOneMinusBlendAlpha;
  12397. default: SOKOL_UNREACHABLE; return (MTLBlendFactor)0;
  12398. }
  12399. }
  12400. _SOKOL_PRIVATE MTLCompareFunction _sg_mtl_compare_func(sg_compare_func f) {
  12401. switch (f) {
  12402. case SG_COMPAREFUNC_NEVER: return MTLCompareFunctionNever;
  12403. case SG_COMPAREFUNC_LESS: return MTLCompareFunctionLess;
  12404. case SG_COMPAREFUNC_EQUAL: return MTLCompareFunctionEqual;
  12405. case SG_COMPAREFUNC_LESS_EQUAL: return MTLCompareFunctionLessEqual;
  12406. case SG_COMPAREFUNC_GREATER: return MTLCompareFunctionGreater;
  12407. case SG_COMPAREFUNC_NOT_EQUAL: return MTLCompareFunctionNotEqual;
  12408. case SG_COMPAREFUNC_GREATER_EQUAL: return MTLCompareFunctionGreaterEqual;
  12409. case SG_COMPAREFUNC_ALWAYS: return MTLCompareFunctionAlways;
  12410. default: SOKOL_UNREACHABLE; return (MTLCompareFunction)0;
  12411. }
  12412. }
  12413. _SOKOL_PRIVATE MTLStencilOperation _sg_mtl_stencil_op(sg_stencil_op op) {
  12414. switch (op) {
  12415. case SG_STENCILOP_KEEP: return MTLStencilOperationKeep;
  12416. case SG_STENCILOP_ZERO: return MTLStencilOperationZero;
  12417. case SG_STENCILOP_REPLACE: return MTLStencilOperationReplace;
  12418. case SG_STENCILOP_INCR_CLAMP: return MTLStencilOperationIncrementClamp;
  12419. case SG_STENCILOP_DECR_CLAMP: return MTLStencilOperationDecrementClamp;
  12420. case SG_STENCILOP_INVERT: return MTLStencilOperationInvert;
  12421. case SG_STENCILOP_INCR_WRAP: return MTLStencilOperationIncrementWrap;
  12422. case SG_STENCILOP_DECR_WRAP: return MTLStencilOperationDecrementWrap;
  12423. default: SOKOL_UNREACHABLE; return (MTLStencilOperation)0;
  12424. }
  12425. }
  12426. _SOKOL_PRIVATE MTLCullMode _sg_mtl_cull_mode(sg_cull_mode m) {
  12427. switch (m) {
  12428. case SG_CULLMODE_NONE: return MTLCullModeNone;
  12429. case SG_CULLMODE_FRONT: return MTLCullModeFront;
  12430. case SG_CULLMODE_BACK: return MTLCullModeBack;
  12431. default: SOKOL_UNREACHABLE; return (MTLCullMode)0;
  12432. }
  12433. }
  12434. _SOKOL_PRIVATE MTLWinding _sg_mtl_winding(sg_face_winding w) {
  12435. switch (w) {
  12436. case SG_FACEWINDING_CW: return MTLWindingClockwise;
  12437. case SG_FACEWINDING_CCW: return MTLWindingCounterClockwise;
  12438. default: SOKOL_UNREACHABLE; return (MTLWinding)0;
  12439. }
  12440. }
  12441. _SOKOL_PRIVATE MTLIndexType _sg_mtl_index_type(sg_index_type t) {
  12442. switch (t) {
  12443. case SG_INDEXTYPE_UINT16: return MTLIndexTypeUInt16;
  12444. case SG_INDEXTYPE_UINT32: return MTLIndexTypeUInt32;
  12445. default: SOKOL_UNREACHABLE; return (MTLIndexType)0;
  12446. }
  12447. }
  12448. _SOKOL_PRIVATE int _sg_mtl_index_size(sg_index_type t) {
  12449. switch (t) {
  12450. case SG_INDEXTYPE_NONE: return 0;
  12451. case SG_INDEXTYPE_UINT16: return 2;
  12452. case SG_INDEXTYPE_UINT32: return 4;
  12453. default: SOKOL_UNREACHABLE; return 0;
  12454. }
  12455. }
  12456. _SOKOL_PRIVATE MTLTextureType _sg_mtl_texture_type(sg_image_type t, bool msaa) {
  12457. switch (t) {
  12458. case SG_IMAGETYPE_2D: return msaa ? MTLTextureType2DMultisample : MTLTextureType2D;
  12459. case SG_IMAGETYPE_CUBE: return MTLTextureTypeCube;
  12460. case SG_IMAGETYPE_3D: return MTLTextureType3D;
  12461. // NOTE: MTLTextureType2DMultisampleArray requires macOS 10.14+, iOS 14.0+
  12462. case SG_IMAGETYPE_ARRAY: return MTLTextureType2DArray;
  12463. default: SOKOL_UNREACHABLE; return (MTLTextureType)0;
  12464. }
  12465. }
  12466. _SOKOL_PRIVATE MTLSamplerAddressMode _sg_mtl_address_mode(sg_wrap w) {
  12467. if (_sg.features.image_clamp_to_border) {
  12468. if (@available(macOS 12.0, iOS 14.0, *)) {
  12469. // border color feature available
  12470. switch (w) {
  12471. case SG_WRAP_REPEAT: return MTLSamplerAddressModeRepeat;
  12472. case SG_WRAP_CLAMP_TO_EDGE: return MTLSamplerAddressModeClampToEdge;
  12473. case SG_WRAP_CLAMP_TO_BORDER: return MTLSamplerAddressModeClampToBorderColor;
  12474. case SG_WRAP_MIRRORED_REPEAT: return MTLSamplerAddressModeMirrorRepeat;
  12475. default: SOKOL_UNREACHABLE; return (MTLSamplerAddressMode)0;
  12476. }
  12477. }
  12478. }
  12479. // fallthrough: clamp to border no supported
  12480. switch (w) {
  12481. case SG_WRAP_REPEAT: return MTLSamplerAddressModeRepeat;
  12482. case SG_WRAP_CLAMP_TO_EDGE: return MTLSamplerAddressModeClampToEdge;
  12483. case SG_WRAP_CLAMP_TO_BORDER: return MTLSamplerAddressModeClampToEdge;
  12484. case SG_WRAP_MIRRORED_REPEAT: return MTLSamplerAddressModeMirrorRepeat;
  12485. default: SOKOL_UNREACHABLE; return (MTLSamplerAddressMode)0;
  12486. }
  12487. }
  12488. _SOKOL_PRIVATE API_AVAILABLE(ios(14.0), macos(12.0)) MTLSamplerBorderColor _sg_mtl_border_color(sg_border_color c) {
  12489. switch (c) {
  12490. case SG_BORDERCOLOR_TRANSPARENT_BLACK: return MTLSamplerBorderColorTransparentBlack;
  12491. case SG_BORDERCOLOR_OPAQUE_BLACK: return MTLSamplerBorderColorOpaqueBlack;
  12492. case SG_BORDERCOLOR_OPAQUE_WHITE: return MTLSamplerBorderColorOpaqueWhite;
  12493. default: SOKOL_UNREACHABLE; return (MTLSamplerBorderColor)0;
  12494. }
  12495. }
  12496. _SOKOL_PRIVATE MTLSamplerMinMagFilter _sg_mtl_minmag_filter(sg_filter f) {
  12497. switch (f) {
  12498. case SG_FILTER_NEAREST:
  12499. return MTLSamplerMinMagFilterNearest;
  12500. case SG_FILTER_LINEAR:
  12501. return MTLSamplerMinMagFilterLinear;
  12502. default:
  12503. SOKOL_UNREACHABLE; return (MTLSamplerMinMagFilter)0;
  12504. }
  12505. }
  12506. _SOKOL_PRIVATE MTLSamplerMipFilter _sg_mtl_mipmap_filter(sg_filter f) {
  12507. switch (f) {
  12508. case SG_FILTER_NEAREST:
  12509. return MTLSamplerMipFilterNearest;
  12510. case SG_FILTER_LINEAR:
  12511. return MTLSamplerMipFilterLinear;
  12512. default:
  12513. SOKOL_UNREACHABLE; return (MTLSamplerMipFilter)0;
  12514. }
  12515. }
  12516. _SOKOL_PRIVATE size_t _sg_mtl_vertexbuffer_bindslot(size_t sokol_bindslot) {
  12517. return sokol_bindslot + _SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS;
  12518. }
  12519. //-- a pool for all Metal resource objects, with deferred release queue ---------
  12520. _SOKOL_PRIVATE void _sg_mtl_init_pool(const sg_desc* desc) {
  12521. _sg.mtl.idpool.num_slots = 2 *
  12522. (
  12523. 2 * desc->buffer_pool_size +
  12524. 4 * desc->image_pool_size +
  12525. 1 * desc->sampler_pool_size +
  12526. 4 * desc->shader_pool_size +
  12527. 2 * desc->pipeline_pool_size +
  12528. desc->attachments_pool_size +
  12529. 128
  12530. );
  12531. _sg.mtl.idpool.pool = [NSMutableArray arrayWithCapacity:(NSUInteger)_sg.mtl.idpool.num_slots];
  12532. _SG_OBJC_RETAIN(_sg.mtl.idpool.pool);
  12533. NSNull* null = [NSNull null];
  12534. for (int i = 0; i < _sg.mtl.idpool.num_slots; i++) {
  12535. [_sg.mtl.idpool.pool addObject:null];
  12536. }
  12537. SOKOL_ASSERT([_sg.mtl.idpool.pool count] == (NSUInteger)_sg.mtl.idpool.num_slots);
  12538. // a queue of currently free slot indices
  12539. _sg.mtl.idpool.free_queue_top = 0;
  12540. _sg.mtl.idpool.free_queue = (int*)_sg_malloc_clear((size_t)_sg.mtl.idpool.num_slots * sizeof(int));
  12541. // pool slot 0 is reserved!
  12542. for (int i = _sg.mtl.idpool.num_slots-1; i >= 1; i--) {
  12543. _sg.mtl.idpool.free_queue[_sg.mtl.idpool.free_queue_top++] = i;
  12544. }
  12545. // a circular queue which holds release items (frame index when a resource is to be released, and the resource's pool index
  12546. _sg.mtl.idpool.release_queue_front = 0;
  12547. _sg.mtl.idpool.release_queue_back = 0;
  12548. _sg.mtl.idpool.release_queue = (_sg_mtl_release_item_t*)_sg_malloc_clear((size_t)_sg.mtl.idpool.num_slots * sizeof(_sg_mtl_release_item_t));
  12549. for (int i = 0; i < _sg.mtl.idpool.num_slots; i++) {
  12550. _sg.mtl.idpool.release_queue[i].frame_index = 0;
  12551. _sg.mtl.idpool.release_queue[i].slot_index = _SG_MTL_INVALID_SLOT_INDEX;
  12552. }
  12553. }
  12554. _SOKOL_PRIVATE void _sg_mtl_destroy_pool(void) {
  12555. _sg_free(_sg.mtl.idpool.release_queue); _sg.mtl.idpool.release_queue = 0;
  12556. _sg_free(_sg.mtl.idpool.free_queue); _sg.mtl.idpool.free_queue = 0;
  12557. _SG_OBJC_RELEASE(_sg.mtl.idpool.pool);
  12558. }
  12559. // get a new free resource pool slot
  12560. _SOKOL_PRIVATE int _sg_mtl_alloc_pool_slot(void) {
  12561. SOKOL_ASSERT(_sg.mtl.idpool.free_queue_top > 0);
  12562. const int slot_index = _sg.mtl.idpool.free_queue[--_sg.mtl.idpool.free_queue_top];
  12563. SOKOL_ASSERT((slot_index > 0) && (slot_index < _sg.mtl.idpool.num_slots));
  12564. return slot_index;
  12565. }
  12566. // put a free resource pool slot back into the free-queue
  12567. _SOKOL_PRIVATE void _sg_mtl_free_pool_slot(int slot_index) {
  12568. SOKOL_ASSERT(_sg.mtl.idpool.free_queue_top < _sg.mtl.idpool.num_slots);
  12569. SOKOL_ASSERT((slot_index > 0) && (slot_index < _sg.mtl.idpool.num_slots));
  12570. _sg.mtl.idpool.free_queue[_sg.mtl.idpool.free_queue_top++] = slot_index;
  12571. }
  12572. // add an MTLResource to the pool, return pool index or 0 if input was 'nil'
  12573. _SOKOL_PRIVATE int _sg_mtl_add_resource(id res) {
  12574. if (nil == res) {
  12575. return _SG_MTL_INVALID_SLOT_INDEX;
  12576. }
  12577. _sg_stats_add(metal.idpool.num_added, 1);
  12578. const int slot_index = _sg_mtl_alloc_pool_slot();
  12579. // NOTE: the NSMutableArray will take ownership of its items
  12580. SOKOL_ASSERT([NSNull null] == _sg.mtl.idpool.pool[(NSUInteger)slot_index]);
  12581. _sg.mtl.idpool.pool[(NSUInteger)slot_index] = res;
  12582. return slot_index;
  12583. }
  12584. /* mark an MTLResource for release, this will put the resource into the
  12585. deferred-release queue, and the resource will then be released N frames later,
  12586. the special pool index 0 will be ignored (this means that a nil
  12587. value was provided to _sg_mtl_add_resource()
  12588. */
  12589. _SOKOL_PRIVATE void _sg_mtl_release_resource(uint32_t frame_index, int slot_index) {
  12590. if (slot_index == _SG_MTL_INVALID_SLOT_INDEX) {
  12591. return;
  12592. }
  12593. _sg_stats_add(metal.idpool.num_released, 1);
  12594. SOKOL_ASSERT((slot_index > 0) && (slot_index < _sg.mtl.idpool.num_slots));
  12595. SOKOL_ASSERT([NSNull null] != _sg.mtl.idpool.pool[(NSUInteger)slot_index]);
  12596. int release_index = _sg.mtl.idpool.release_queue_front++;
  12597. if (_sg.mtl.idpool.release_queue_front >= _sg.mtl.idpool.num_slots) {
  12598. // wrap-around
  12599. _sg.mtl.idpool.release_queue_front = 0;
  12600. }
  12601. // release queue full?
  12602. SOKOL_ASSERT(_sg.mtl.idpool.release_queue_front != _sg.mtl.idpool.release_queue_back);
  12603. SOKOL_ASSERT(0 == _sg.mtl.idpool.release_queue[release_index].frame_index);
  12604. const uint32_t safe_to_release_frame_index = frame_index + SG_NUM_INFLIGHT_FRAMES + 1;
  12605. _sg.mtl.idpool.release_queue[release_index].frame_index = safe_to_release_frame_index;
  12606. _sg.mtl.idpool.release_queue[release_index].slot_index = slot_index;
  12607. }
  12608. // run garbage-collection pass on all resources in the release-queue
  12609. _SOKOL_PRIVATE void _sg_mtl_garbage_collect(uint32_t frame_index) {
  12610. while (_sg.mtl.idpool.release_queue_back != _sg.mtl.idpool.release_queue_front) {
  12611. if (frame_index < _sg.mtl.idpool.release_queue[_sg.mtl.idpool.release_queue_back].frame_index) {
  12612. // don't need to check further, release-items past this are too young
  12613. break;
  12614. }
  12615. _sg_stats_add(metal.idpool.num_garbage_collected, 1);
  12616. // safe to release this resource
  12617. const int slot_index = _sg.mtl.idpool.release_queue[_sg.mtl.idpool.release_queue_back].slot_index;
  12618. SOKOL_ASSERT((slot_index > 0) && (slot_index < _sg.mtl.idpool.num_slots));
  12619. // note: the NSMutableArray takes ownership of its items, assigning an NSNull object will
  12620. // release the object, no matter if using ARC or not
  12621. SOKOL_ASSERT(_sg.mtl.idpool.pool[(NSUInteger)slot_index] != [NSNull null]);
  12622. _sg.mtl.idpool.pool[(NSUInteger)slot_index] = [NSNull null];
  12623. // put the now free pool index back on the free queue
  12624. _sg_mtl_free_pool_slot(slot_index);
  12625. // reset the release queue slot and advance the back index
  12626. _sg.mtl.idpool.release_queue[_sg.mtl.idpool.release_queue_back].frame_index = 0;
  12627. _sg.mtl.idpool.release_queue[_sg.mtl.idpool.release_queue_back].slot_index = _SG_MTL_INVALID_SLOT_INDEX;
  12628. _sg.mtl.idpool.release_queue_back++;
  12629. if (_sg.mtl.idpool.release_queue_back >= _sg.mtl.idpool.num_slots) {
  12630. // wrap-around
  12631. _sg.mtl.idpool.release_queue_back = 0;
  12632. }
  12633. }
  12634. }
  12635. _SOKOL_PRIVATE id _sg_mtl_id(int slot_index) {
  12636. return _sg.mtl.idpool.pool[(NSUInteger)slot_index];
  12637. }
  12638. _SOKOL_PRIVATE void _sg_mtl_clear_state_cache(void) {
  12639. _sg_clear(&_sg.mtl.state_cache, sizeof(_sg.mtl.state_cache));
  12640. }
  12641. // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf
  12642. _SOKOL_PRIVATE void _sg_mtl_init_caps(void) {
  12643. #if defined(_SG_TARGET_MACOS)
  12644. _sg.backend = SG_BACKEND_METAL_MACOS;
  12645. #elif defined(_SG_TARGET_IOS)
  12646. #if defined(_SG_TARGET_IOS_SIMULATOR)
  12647. _sg.backend = SG_BACKEND_METAL_SIMULATOR;
  12648. #else
  12649. _sg.backend = SG_BACKEND_METAL_IOS;
  12650. #endif
  12651. #endif
  12652. _sg.features.origin_top_left = true;
  12653. _sg.features.mrt_independent_blend_state = true;
  12654. _sg.features.mrt_independent_write_mask = true;
  12655. _sg.features.compute = true;
  12656. _sg.features.msaa_image_bindings = true;
  12657. _sg.features.image_clamp_to_border = false;
  12658. #if (MAC_OS_X_VERSION_MAX_ALLOWED >= 120000) || (__IPHONE_OS_VERSION_MAX_ALLOWED >= 140000)
  12659. if (@available(macOS 12.0, iOS 14.0, *)) {
  12660. _sg.features.image_clamp_to_border = [_sg.mtl.device supportsFamily:MTLGPUFamilyApple7]
  12661. || [_sg.mtl.device supportsFamily:MTLGPUFamilyMac2];
  12662. #if (MAC_OS_X_VERSION_MAX_ALLOWED >= 130000) || (__IPHONE_OS_VERSION_MAX_ALLOWED >= 160000)
  12663. if (!_sg.features.image_clamp_to_border) {
  12664. if (@available(macOS 13.0, iOS 16.0, *)) {
  12665. _sg.features.image_clamp_to_border = [_sg.mtl.device supportsFamily:MTLGPUFamilyMetal3];
  12666. }
  12667. }
  12668. #endif
  12669. }
  12670. #endif
  12671. #if defined(_SG_TARGET_MACOS)
  12672. _sg.limits.max_image_size_2d = 16 * 1024;
  12673. _sg.limits.max_image_size_cube = 16 * 1024;
  12674. _sg.limits.max_image_size_3d = 2 * 1024;
  12675. _sg.limits.max_image_size_array = 16 * 1024;
  12676. _sg.limits.max_image_array_layers = 2 * 1024;
  12677. #else
  12678. // FIXME: newer iOS devices support 16k textures
  12679. _sg.limits.max_image_size_2d = 8 * 1024;
  12680. _sg.limits.max_image_size_cube = 8 * 1024;
  12681. _sg.limits.max_image_size_3d = 2 * 1024;
  12682. _sg.limits.max_image_size_array = 8 * 1024;
  12683. _sg.limits.max_image_array_layers = 2 * 1024;
  12684. #endif
  12685. _sg.limits.max_vertex_attrs = SG_MAX_VERTEX_ATTRIBUTES;
  12686. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R8]);
  12687. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R8SN]);
  12688. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R8UI]);
  12689. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R8SI]);
  12690. #if defined(_SG_TARGET_MACOS)
  12691. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16]);
  12692. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16SN]);
  12693. #else
  12694. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_R16]);
  12695. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_R16SN]);
  12696. #endif
  12697. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R16UI]);
  12698. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R16SI]);
  12699. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16F]);
  12700. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG8]);
  12701. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG8SN]);
  12702. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG8UI]);
  12703. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG8SI]);
  12704. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32UI]);
  12705. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32SI]);
  12706. #if defined(_SG_TARGET_MACOS)
  12707. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R32F]);
  12708. #else
  12709. _sg_pixelformat_sbr(&_sg.formats[SG_PIXELFORMAT_R32F]);
  12710. #endif
  12711. #if defined(_SG_TARGET_MACOS)
  12712. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16]);
  12713. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16SN]);
  12714. #else
  12715. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_RG16]);
  12716. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_RG16SN]);
  12717. #endif
  12718. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG16UI]);
  12719. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG16SI]);
  12720. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16F]);
  12721. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA8]);
  12722. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_SRGB8A8]);
  12723. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA8SN]);
  12724. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA8UI]);
  12725. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA8SI]);
  12726. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_BGRA8]);
  12727. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGB10A2]);
  12728. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  12729. #if defined(_SG_TARGET_MACOS)
  12730. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGB9E5]);
  12731. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  12732. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  12733. #else
  12734. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGB9E5]);
  12735. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  12736. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  12737. #endif
  12738. #if defined(_SG_TARGET_MACOS)
  12739. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  12740. #else
  12741. _sg_pixelformat_sbr(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  12742. #endif
  12743. #if defined(_SG_TARGET_MACOS)
  12744. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16]);
  12745. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16SN]);
  12746. #else
  12747. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_RGBA16]);
  12748. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_RGBA16SN]);
  12749. #endif
  12750. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA16UI]);
  12751. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA16SI]);
  12752. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  12753. #if defined(_SG_TARGET_MACOS)
  12754. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  12755. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  12756. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  12757. #else
  12758. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  12759. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  12760. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  12761. #endif
  12762. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH]);
  12763. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH_STENCIL]);
  12764. #if defined(_SG_TARGET_MACOS)
  12765. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC1_RGBA]);
  12766. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC2_RGBA]);
  12767. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_RGBA]);
  12768. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_SRGBA]);
  12769. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_R]);
  12770. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_RSN]);
  12771. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RG]);
  12772. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RGSN]);
  12773. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBF]);
  12774. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBUF]);
  12775. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_RGBA]);
  12776. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_SRGBA]);
  12777. #else
  12778. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8]);
  12779. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8]);
  12780. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8A1]);
  12781. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGBA8]);
  12782. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8A8]);
  12783. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11]);
  12784. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11SN]);
  12785. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11]);
  12786. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11SN]);
  12787. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_RGBA]);
  12788. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_SRGBA]);
  12789. #endif
  12790. // compute shader access (see: https://github.com/gpuweb/gpuweb/issues/513)
  12791. // for now let's use the same conservative set on all backends even though
  12792. // some backends are less restrictive
  12793. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8]);
  12794. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8SN]);
  12795. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8UI]);
  12796. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8SI]);
  12797. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16UI]);
  12798. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16SI]);
  12799. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  12800. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32UI]);
  12801. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32SI]);
  12802. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32F]);
  12803. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  12804. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  12805. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  12806. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  12807. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  12808. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  12809. }
  12810. //-- main Metal backend state and functions ------------------------------------
  12811. _SOKOL_PRIVATE void _sg_mtl_setup_backend(const sg_desc* desc) {
  12812. // assume already zero-initialized
  12813. SOKOL_ASSERT(desc);
  12814. SOKOL_ASSERT(desc->environment.metal.device);
  12815. SOKOL_ASSERT(desc->uniform_buffer_size > 0);
  12816. _sg_mtl_init_pool(desc);
  12817. _sg_mtl_clear_state_cache();
  12818. _sg.mtl.valid = true;
  12819. _sg.mtl.ub_size = desc->uniform_buffer_size;
  12820. _sg.mtl.sem = dispatch_semaphore_create(SG_NUM_INFLIGHT_FRAMES);
  12821. _sg.mtl.device = (__bridge id<MTLDevice>) desc->environment.metal.device;
  12822. _sg.mtl.cmd_queue = [_sg.mtl.device newCommandQueue];
  12823. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  12824. _sg.mtl.uniform_buffers[i] = [_sg.mtl.device
  12825. newBufferWithLength:(NSUInteger)_sg.mtl.ub_size
  12826. options:MTLResourceCPUCacheModeWriteCombined|MTLResourceStorageModeShared
  12827. ];
  12828. #if defined(SOKOL_DEBUG)
  12829. _sg.mtl.uniform_buffers[i].label = [NSString stringWithFormat:@"sg-uniform-buffer.%d", i];
  12830. #endif
  12831. }
  12832. if (desc->mtl_force_managed_storage_mode) {
  12833. _sg.mtl.use_shared_storage_mode = false;
  12834. } else if (@available(macOS 10.15, iOS 13.0, *)) {
  12835. // on Intel Macs, always use managed resources even though the
  12836. // device says it supports unified memory (because of texture restrictions)
  12837. const bool is_apple_gpu = [_sg.mtl.device supportsFamily:MTLGPUFamilyApple1];
  12838. if (!is_apple_gpu) {
  12839. _sg.mtl.use_shared_storage_mode = false;
  12840. } else {
  12841. _sg.mtl.use_shared_storage_mode = true;
  12842. }
  12843. } else {
  12844. #if defined(_SG_TARGET_MACOS)
  12845. _sg.mtl.use_shared_storage_mode = false;
  12846. #else
  12847. _sg.mtl.use_shared_storage_mode = true;
  12848. #endif
  12849. }
  12850. _sg_mtl_init_caps();
  12851. }
  12852. _SOKOL_PRIVATE void _sg_mtl_discard_backend(void) {
  12853. SOKOL_ASSERT(_sg.mtl.valid);
  12854. // wait for the last frame to finish
  12855. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  12856. dispatch_semaphore_wait(_sg.mtl.sem, DISPATCH_TIME_FOREVER);
  12857. }
  12858. // semaphore must be "relinquished" before destruction
  12859. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  12860. dispatch_semaphore_signal(_sg.mtl.sem);
  12861. }
  12862. _sg_mtl_garbage_collect(_sg.frame_index + SG_NUM_INFLIGHT_FRAMES + 2);
  12863. _sg_mtl_destroy_pool();
  12864. _sg.mtl.valid = false;
  12865. _SG_OBJC_RELEASE(_sg.mtl.sem);
  12866. _SG_OBJC_RELEASE(_sg.mtl.device);
  12867. _SG_OBJC_RELEASE(_sg.mtl.cmd_queue);
  12868. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  12869. _SG_OBJC_RELEASE(_sg.mtl.uniform_buffers[i]);
  12870. }
  12871. // NOTE: MTLCommandBuffer, MTLRenderCommandEncoder and MTLComputeCommandEncoder are auto-released
  12872. _sg.mtl.cmd_buffer = nil;
  12873. _sg.mtl.render_cmd_encoder = nil;
  12874. _sg.mtl.compute_cmd_encoder = nil;
  12875. }
  12876. _SOKOL_PRIVATE void _sg_mtl_reset_state_cache(void) {
  12877. _sg_mtl_clear_state_cache();
  12878. }
  12879. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  12880. SOKOL_ASSERT(buf && desc);
  12881. SOKOL_ASSERT(buf->cmn.size > 0);
  12882. const bool injected = (0 != desc->mtl_buffers[0]);
  12883. MTLResourceOptions mtl_options = _sg_mtl_buffer_resource_options(&buf->cmn.usage);
  12884. for (int slot = 0; slot < buf->cmn.num_slots; slot++) {
  12885. id<MTLBuffer> mtl_buf;
  12886. if (injected) {
  12887. SOKOL_ASSERT(desc->mtl_buffers[slot]);
  12888. mtl_buf = (__bridge id<MTLBuffer>) desc->mtl_buffers[slot];
  12889. } else {
  12890. if (desc->data.ptr) {
  12891. SOKOL_ASSERT(desc->data.size > 0);
  12892. mtl_buf = [_sg.mtl.device newBufferWithBytes:desc->data.ptr length:(NSUInteger)buf->cmn.size options:mtl_options];
  12893. } else {
  12894. mtl_buf = [_sg.mtl.device newBufferWithLength:(NSUInteger)buf->cmn.size options:mtl_options];
  12895. }
  12896. if (nil == mtl_buf) {
  12897. _SG_ERROR(METAL_CREATE_BUFFER_FAILED);
  12898. return SG_RESOURCESTATE_FAILED;
  12899. }
  12900. }
  12901. #if defined(SOKOL_DEBUG)
  12902. if (desc->label) {
  12903. mtl_buf.label = [NSString stringWithFormat:@"%s.%d", desc->label, slot];
  12904. }
  12905. #endif
  12906. buf->mtl.buf[slot] = _sg_mtl_add_resource(mtl_buf);
  12907. _SG_OBJC_RELEASE(mtl_buf);
  12908. }
  12909. return SG_RESOURCESTATE_VALID;
  12910. }
  12911. _SOKOL_PRIVATE void _sg_mtl_discard_buffer(_sg_buffer_t* buf) {
  12912. SOKOL_ASSERT(buf);
  12913. for (int slot = 0; slot < buf->cmn.num_slots; slot++) {
  12914. // it's valid to call release resource with '0'
  12915. _sg_mtl_release_resource(_sg.frame_index, buf->mtl.buf[slot]);
  12916. }
  12917. }
  12918. _SOKOL_PRIVATE void _sg_mtl_copy_image_data(const _sg_image_t* img, __unsafe_unretained id<MTLTexture> mtl_tex, const sg_image_data* data) {
  12919. const int num_faces = (img->cmn.type == SG_IMAGETYPE_CUBE) ? 6:1;
  12920. const int num_slices = (img->cmn.type == SG_IMAGETYPE_ARRAY) ? img->cmn.num_slices : 1;
  12921. for (int face_index = 0; face_index < num_faces; face_index++) {
  12922. for (int mip_index = 0; mip_index < img->cmn.num_mipmaps; mip_index++) {
  12923. SOKOL_ASSERT(data->subimage[face_index][mip_index].ptr);
  12924. SOKOL_ASSERT(data->subimage[face_index][mip_index].size > 0);
  12925. const uint8_t* data_ptr = (const uint8_t*)data->subimage[face_index][mip_index].ptr;
  12926. const int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  12927. const int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  12928. int bytes_per_row = _sg_row_pitch(img->cmn.pixel_format, mip_width, 1);
  12929. int bytes_per_slice = _sg_surface_pitch(img->cmn.pixel_format, mip_width, mip_height, 1);
  12930. /* bytesPerImage special case: https://developer.apple.com/documentation/metal/mtltexture/1515679-replaceregion
  12931. "Supply a nonzero value only when you copy data to a MTLTextureType3D type texture"
  12932. */
  12933. MTLRegion region;
  12934. int bytes_per_image;
  12935. if (img->cmn.type == SG_IMAGETYPE_3D) {
  12936. const int mip_depth = _sg_miplevel_dim(img->cmn.num_slices, mip_index);
  12937. region = MTLRegionMake3D(0, 0, 0, (NSUInteger)mip_width, (NSUInteger)mip_height, (NSUInteger)mip_depth);
  12938. bytes_per_image = bytes_per_slice;
  12939. // FIXME: apparently the minimal bytes_per_image size for 3D texture is 4 KByte... somehow need to handle this
  12940. } else {
  12941. region = MTLRegionMake2D(0, 0, (NSUInteger)mip_width, (NSUInteger)mip_height);
  12942. bytes_per_image = 0;
  12943. }
  12944. for (int slice_index = 0; slice_index < num_slices; slice_index++) {
  12945. const int mtl_slice_index = (img->cmn.type == SG_IMAGETYPE_CUBE) ? face_index : slice_index;
  12946. const int slice_offset = slice_index * bytes_per_slice;
  12947. SOKOL_ASSERT((slice_offset + bytes_per_slice) <= (int)data->subimage[face_index][mip_index].size);
  12948. [mtl_tex replaceRegion:region
  12949. mipmapLevel:(NSUInteger)mip_index
  12950. slice:(NSUInteger)mtl_slice_index
  12951. withBytes:data_ptr + slice_offset
  12952. bytesPerRow:(NSUInteger)bytes_per_row
  12953. bytesPerImage:(NSUInteger)bytes_per_image];
  12954. }
  12955. }
  12956. }
  12957. }
  12958. _SOKOL_PRIVATE bool _sg_mtl_init_texdesc(MTLTextureDescriptor* mtl_desc, _sg_image_t* img) {
  12959. mtl_desc.textureType = _sg_mtl_texture_type(img->cmn.type, img->cmn.sample_count > 1);
  12960. mtl_desc.pixelFormat = _sg_mtl_pixel_format(img->cmn.pixel_format);
  12961. if (MTLPixelFormatInvalid == mtl_desc.pixelFormat) {
  12962. _SG_ERROR(METAL_TEXTURE_FORMAT_NOT_SUPPORTED);
  12963. return false;
  12964. }
  12965. mtl_desc.width = (NSUInteger)img->cmn.width;
  12966. mtl_desc.height = (NSUInteger)img->cmn.height;
  12967. if (SG_IMAGETYPE_3D == img->cmn.type) {
  12968. mtl_desc.depth = (NSUInteger)img->cmn.num_slices;
  12969. } else {
  12970. mtl_desc.depth = 1;
  12971. }
  12972. mtl_desc.mipmapLevelCount = (NSUInteger)img->cmn.num_mipmaps;
  12973. if (SG_IMAGETYPE_ARRAY == img->cmn.type) {
  12974. mtl_desc.arrayLength = (NSUInteger)img->cmn.num_slices;
  12975. } else {
  12976. mtl_desc.arrayLength = 1;
  12977. }
  12978. mtl_desc.sampleCount = (NSUInteger)img->cmn.sample_count;
  12979. MTLTextureUsage mtl_tex_usage = MTLTextureUsageShaderRead;
  12980. if (img->cmn.usage.render_attachment) {
  12981. mtl_tex_usage |= MTLTextureUsageRenderTarget;
  12982. } else if (img->cmn.usage.storage_attachment) {
  12983. mtl_tex_usage |= MTLTextureUsageShaderWrite;
  12984. }
  12985. mtl_desc.usage = mtl_tex_usage;
  12986. MTLResourceOptions mtl_res_options = 0;
  12987. if (img->cmn.usage.render_attachment || img->cmn.usage.storage_attachment) {
  12988. mtl_res_options |= MTLResourceStorageModePrivate;
  12989. } else {
  12990. mtl_res_options |= _sg_mtl_resource_options_storage_mode_managed_or_shared();
  12991. if (!img->cmn.usage.immutable) {
  12992. mtl_res_options |= MTLResourceCPUCacheModeWriteCombined;
  12993. }
  12994. }
  12995. mtl_desc.resourceOptions = mtl_res_options;
  12996. return true;
  12997. }
  12998. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  12999. SOKOL_ASSERT(img && desc);
  13000. const bool injected = (0 != desc->mtl_textures[0]);
  13001. // first initialize all Metal resource pool slots to 'empty'
  13002. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  13003. img->mtl.tex[i] = _sg_mtl_add_resource(nil);
  13004. }
  13005. // initialize a Metal texture descriptor
  13006. MTLTextureDescriptor* mtl_desc = [[MTLTextureDescriptor alloc] init];
  13007. if (!_sg_mtl_init_texdesc(mtl_desc, img)) {
  13008. _SG_OBJC_RELEASE(mtl_desc);
  13009. return SG_RESOURCESTATE_FAILED;
  13010. }
  13011. for (int slot = 0; slot < img->cmn.num_slots; slot++) {
  13012. id<MTLTexture> mtl_tex;
  13013. if (injected) {
  13014. SOKOL_ASSERT(desc->mtl_textures[slot]);
  13015. mtl_tex = (__bridge id<MTLTexture>) desc->mtl_textures[slot];
  13016. } else {
  13017. mtl_tex = [_sg.mtl.device newTextureWithDescriptor:mtl_desc];
  13018. if (nil == mtl_tex) {
  13019. _SG_OBJC_RELEASE(mtl_desc);
  13020. _SG_ERROR(METAL_CREATE_TEXTURE_FAILED);
  13021. return SG_RESOURCESTATE_FAILED;
  13022. }
  13023. if (desc->data.subimage[0][0].ptr) {
  13024. _sg_mtl_copy_image_data(img, mtl_tex, &desc->data);
  13025. }
  13026. }
  13027. #if defined(SOKOL_DEBUG)
  13028. if (desc->label) {
  13029. mtl_tex.label = [NSString stringWithFormat:@"%s.%d", desc->label, slot];
  13030. }
  13031. #endif
  13032. img->mtl.tex[slot] = _sg_mtl_add_resource(mtl_tex);
  13033. _SG_OBJC_RELEASE(mtl_tex);
  13034. }
  13035. _SG_OBJC_RELEASE(mtl_desc);
  13036. return SG_RESOURCESTATE_VALID;
  13037. }
  13038. _SOKOL_PRIVATE void _sg_mtl_discard_image(_sg_image_t* img) {
  13039. SOKOL_ASSERT(img);
  13040. // it's valid to call release resource with a 'null resource'
  13041. for (int slot = 0; slot < img->cmn.num_slots; slot++) {
  13042. _sg_mtl_release_resource(_sg.frame_index, img->mtl.tex[slot]);
  13043. }
  13044. }
  13045. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  13046. SOKOL_ASSERT(smp && desc);
  13047. id<MTLSamplerState> mtl_smp;
  13048. const bool injected = (0 != desc->mtl_sampler);
  13049. if (injected) {
  13050. SOKOL_ASSERT(desc->mtl_sampler);
  13051. mtl_smp = (__bridge id<MTLSamplerState>) desc->mtl_sampler;
  13052. } else {
  13053. MTLSamplerDescriptor* mtl_desc = [[MTLSamplerDescriptor alloc] init];
  13054. mtl_desc.sAddressMode = _sg_mtl_address_mode(desc->wrap_u);
  13055. mtl_desc.tAddressMode = _sg_mtl_address_mode(desc->wrap_v);
  13056. mtl_desc.rAddressMode = _sg_mtl_address_mode(desc->wrap_w);
  13057. if (_sg.features.image_clamp_to_border) {
  13058. if (@available(macOS 12.0, iOS 14.0, *)) {
  13059. mtl_desc.borderColor = _sg_mtl_border_color(desc->border_color);
  13060. }
  13061. }
  13062. mtl_desc.minFilter = _sg_mtl_minmag_filter(desc->min_filter);
  13063. mtl_desc.magFilter = _sg_mtl_minmag_filter(desc->mag_filter);
  13064. mtl_desc.mipFilter = _sg_mtl_mipmap_filter(desc->mipmap_filter);
  13065. mtl_desc.lodMinClamp = desc->min_lod;
  13066. mtl_desc.lodMaxClamp = desc->max_lod;
  13067. // FIXME: lodAverage?
  13068. mtl_desc.maxAnisotropy = desc->max_anisotropy;
  13069. mtl_desc.normalizedCoordinates = YES;
  13070. mtl_desc.compareFunction = _sg_mtl_compare_func(desc->compare);
  13071. #if defined(SOKOL_DEBUG)
  13072. if (desc->label) {
  13073. mtl_desc.label = [NSString stringWithUTF8String:desc->label];
  13074. }
  13075. #endif
  13076. mtl_smp = [_sg.mtl.device newSamplerStateWithDescriptor:mtl_desc];
  13077. _SG_OBJC_RELEASE(mtl_desc);
  13078. if (nil == mtl_smp) {
  13079. _SG_ERROR(METAL_CREATE_SAMPLER_FAILED);
  13080. return SG_RESOURCESTATE_FAILED;
  13081. }
  13082. }
  13083. smp->mtl.sampler_state = _sg_mtl_add_resource(mtl_smp);
  13084. _SG_OBJC_RELEASE(mtl_smp);
  13085. return SG_RESOURCESTATE_VALID;
  13086. }
  13087. _SOKOL_PRIVATE void _sg_mtl_discard_sampler(_sg_sampler_t* smp) {
  13088. SOKOL_ASSERT(smp);
  13089. // it's valid to call release resource with a 'null resource'
  13090. _sg_mtl_release_resource(_sg.frame_index, smp->mtl.sampler_state);
  13091. }
  13092. _SOKOL_PRIVATE id<MTLLibrary> _sg_mtl_compile_library(const char* src) {
  13093. NSError* err = NULL;
  13094. id<MTLLibrary> lib = [_sg.mtl.device
  13095. newLibraryWithSource:[NSString stringWithUTF8String:src]
  13096. options:nil
  13097. error:&err
  13098. ];
  13099. if (err) {
  13100. _SG_ERROR(METAL_SHADER_COMPILATION_FAILED);
  13101. _SG_LOGMSG(METAL_SHADER_COMPILATION_OUTPUT, [err.localizedDescription UTF8String]);
  13102. }
  13103. return lib;
  13104. }
  13105. _SOKOL_PRIVATE id<MTLLibrary> _sg_mtl_library_from_bytecode(const void* ptr, size_t num_bytes) {
  13106. NSError* err = NULL;
  13107. dispatch_data_t lib_data = dispatch_data_create(ptr, num_bytes, NULL, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
  13108. id<MTLLibrary> lib = [_sg.mtl.device newLibraryWithData:lib_data error:&err];
  13109. if (err) {
  13110. _SG_ERROR(METAL_SHADER_CREATION_FAILED);
  13111. _SG_LOGMSG(METAL_SHADER_COMPILATION_OUTPUT, [err.localizedDescription UTF8String]);
  13112. }
  13113. _SG_OBJC_RELEASE(lib_data);
  13114. return lib;
  13115. }
  13116. _SOKOL_PRIVATE bool _sg_mtl_create_shader_func(const sg_shader_function* func, const char* label, const char* label_ext, _sg_mtl_shader_func_t* res) {
  13117. SOKOL_ASSERT(res->mtl_lib == _SG_MTL_INVALID_SLOT_INDEX);
  13118. SOKOL_ASSERT(res->mtl_func == _SG_MTL_INVALID_SLOT_INDEX);
  13119. id<MTLLibrary> mtl_lib = nil;
  13120. if (func->bytecode.ptr) {
  13121. SOKOL_ASSERT(func->bytecode.size > 0);
  13122. mtl_lib = _sg_mtl_library_from_bytecode(func->bytecode.ptr, func->bytecode.size);
  13123. } else if (func->source) {
  13124. mtl_lib = _sg_mtl_compile_library(func->source);
  13125. }
  13126. if (mtl_lib == nil) {
  13127. return false;
  13128. }
  13129. #if defined(SOKOL_DEBUG)
  13130. if (label) {
  13131. SOKOL_ASSERT(label_ext);
  13132. mtl_lib.label = [NSString stringWithFormat:@"%s.%s", label, label_ext];
  13133. }
  13134. #else
  13135. _SOKOL_UNUSED(label);
  13136. _SOKOL_UNUSED(label_ext);
  13137. #endif
  13138. SOKOL_ASSERT(func->entry);
  13139. id<MTLFunction> mtl_func = [mtl_lib newFunctionWithName:[NSString stringWithUTF8String:func->entry]];
  13140. if (mtl_func == nil) {
  13141. _SG_ERROR(METAL_SHADER_ENTRY_NOT_FOUND);
  13142. _SG_OBJC_RELEASE(mtl_lib);
  13143. return false;
  13144. }
  13145. res->mtl_lib = _sg_mtl_add_resource(mtl_lib);
  13146. res->mtl_func = _sg_mtl_add_resource(mtl_func);
  13147. _SG_OBJC_RELEASE(mtl_lib);
  13148. _SG_OBJC_RELEASE(mtl_func);
  13149. return true;
  13150. }
  13151. _SOKOL_PRIVATE void _sg_mtl_discard_shader_func(const _sg_mtl_shader_func_t* func) {
  13152. // it is valid to call _sg_mtl_release_resource with a 'null resource'
  13153. _sg_mtl_release_resource(_sg.frame_index, func->mtl_func);
  13154. _sg_mtl_release_resource(_sg.frame_index, func->mtl_lib);
  13155. }
  13156. // NOTE: this is an out-of-range check for MSL bindslots that's also active in release mode
  13157. _SOKOL_PRIVATE bool _sg_mtl_ensure_msl_bindslot_ranges(const sg_shader_desc* desc) {
  13158. SOKOL_ASSERT(desc);
  13159. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  13160. if (desc->uniform_blocks[i].msl_buffer_n >= _SG_MTL_MAX_STAGE_UB_BINDINGS) {
  13161. _SG_ERROR(METAL_UNIFORMBLOCK_MSL_BUFFER_SLOT_OUT_OF_RANGE);
  13162. return false;
  13163. }
  13164. }
  13165. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  13166. if (desc->images[i].msl_texture_n >= _SG_MTL_MAX_STAGE_TEXTURE_BINDINGS) {
  13167. _SG_ERROR(METAL_IMAGE_MSL_TEXTURE_SLOT_OUT_OF_RANGE);
  13168. return false;
  13169. }
  13170. }
  13171. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  13172. if (desc->samplers[i].msl_sampler_n >= _SG_MTL_MAX_STAGE_SAMPLER_BINDINGS) {
  13173. _SG_ERROR(METAL_SAMPLER_MSL_SAMPLER_SLOT_OUT_OF_RANGE);
  13174. return false;
  13175. }
  13176. }
  13177. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  13178. if (desc->storage_buffers[i].msl_buffer_n >= _SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS) {
  13179. _SG_ERROR(METAL_STORAGEBUFFER_MSL_BUFFER_SLOT_OUT_OF_RANGE);
  13180. return false;
  13181. }
  13182. }
  13183. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  13184. if (desc->storage_images[i].msl_texture_n >= _SG_MTL_MAX_STAGE_TEXTURE_BINDINGS) {
  13185. _SG_ERROR(METAL_STORAGEIMAGE_MSL_TEXTURE_SLOT_OUT_OF_RANGE);
  13186. return false;
  13187. }
  13188. }
  13189. return true;
  13190. }
  13191. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  13192. SOKOL_ASSERT(shd && desc);
  13193. // do a MSL bindslot range check also in release mode, and if that fails,
  13194. // also fail shader creation
  13195. if (!_sg_mtl_ensure_msl_bindslot_ranges(desc)) {
  13196. return SG_RESOURCESTATE_FAILED;
  13197. }
  13198. shd->mtl.threads_per_threadgroup = MTLSizeMake(
  13199. (NSUInteger)desc->mtl_threads_per_threadgroup.x,
  13200. (NSUInteger)desc->mtl_threads_per_threadgroup.y,
  13201. (NSUInteger)desc->mtl_threads_per_threadgroup.z);
  13202. // copy resource bindslot mappings
  13203. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  13204. shd->mtl.ub_buffer_n[i] = desc->uniform_blocks[i].msl_buffer_n;
  13205. }
  13206. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  13207. shd->mtl.img_texture_n[i] = desc->images[i].msl_texture_n;
  13208. }
  13209. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  13210. shd->mtl.smp_sampler_n[i] = desc->samplers[i].msl_sampler_n;
  13211. }
  13212. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  13213. shd->mtl.sbuf_buffer_n[i] = desc->storage_buffers[i].msl_buffer_n;
  13214. }
  13215. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  13216. shd->mtl.simg_texture_n[i] = desc->storage_images[i].msl_texture_n;
  13217. }
  13218. // create metal library and function objects
  13219. bool shd_valid = true;
  13220. if (desc->vertex_func.source || desc->vertex_func.bytecode.ptr) {
  13221. shd_valid &= _sg_mtl_create_shader_func(&desc->vertex_func, desc->label, "vs", &shd->mtl.vertex_func);
  13222. }
  13223. if (desc->fragment_func.source || desc->fragment_func.bytecode.ptr) {
  13224. shd_valid &= _sg_mtl_create_shader_func(&desc->fragment_func, desc->label, "fs", &shd->mtl.fragment_func);
  13225. }
  13226. if (desc->compute_func.source || desc->compute_func.bytecode.ptr) {
  13227. shd_valid &= _sg_mtl_create_shader_func(&desc->compute_func, desc->label, "cs", &shd->mtl.compute_func);
  13228. }
  13229. if (!shd_valid) {
  13230. _sg_mtl_discard_shader_func(&shd->mtl.vertex_func);
  13231. _sg_mtl_discard_shader_func(&shd->mtl.fragment_func);
  13232. _sg_mtl_discard_shader_func(&shd->mtl.compute_func);
  13233. }
  13234. return shd_valid ? SG_RESOURCESTATE_VALID : SG_RESOURCESTATE_FAILED;
  13235. }
  13236. _SOKOL_PRIVATE void _sg_mtl_discard_shader(_sg_shader_t* shd) {
  13237. SOKOL_ASSERT(shd);
  13238. _sg_mtl_discard_shader_func(&shd->mtl.vertex_func);
  13239. _sg_mtl_discard_shader_func(&shd->mtl.fragment_func);
  13240. _sg_mtl_discard_shader_func(&shd->mtl.compute_func);
  13241. }
  13242. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_pipeline(_sg_pipeline_t* pip, const sg_pipeline_desc* desc) {
  13243. SOKOL_ASSERT(pip && desc);
  13244. _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  13245. if (pip->cmn.is_compute) {
  13246. NSError* err = NULL;
  13247. MTLComputePipelineDescriptor* cp_desc = [[MTLComputePipelineDescriptor alloc] init];
  13248. cp_desc.computeFunction = _sg_mtl_id(shd->mtl.compute_func.mtl_func);
  13249. cp_desc.threadGroupSizeIsMultipleOfThreadExecutionWidth = true;
  13250. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  13251. const sg_shader_stage stage = shd->cmn.storage_buffers[i].stage;
  13252. SOKOL_ASSERT((stage != SG_SHADERSTAGE_VERTEX) && (stage != SG_SHADERSTAGE_FRAGMENT));
  13253. if ((stage == SG_SHADERSTAGE_COMPUTE) && shd->cmn.storage_buffers[i].readonly) {
  13254. const NSUInteger mtl_slot = shd->mtl.sbuf_buffer_n[i];
  13255. cp_desc.buffers[mtl_slot].mutability = MTLMutabilityImmutable;
  13256. }
  13257. }
  13258. #if defined(SOKOL_DEBUG)
  13259. if (desc->label) {
  13260. cp_desc.label = [NSString stringWithFormat:@"%s", desc->label];
  13261. }
  13262. #endif
  13263. id<MTLComputePipelineState> mtl_cps = [_sg.mtl.device
  13264. newComputePipelineStateWithDescriptor:cp_desc
  13265. options:MTLPipelineOptionNone
  13266. reflection:nil
  13267. error:&err];
  13268. _SG_OBJC_RELEASE(cp_desc);
  13269. if (nil == mtl_cps) {
  13270. SOKOL_ASSERT(err);
  13271. _SG_ERROR(METAL_CREATE_CPS_FAILED);
  13272. _SG_LOGMSG(METAL_CREATE_CPS_OUTPUT, [err.localizedDescription UTF8String]);
  13273. return SG_RESOURCESTATE_FAILED;
  13274. }
  13275. pip->mtl.cps = _sg_mtl_add_resource(mtl_cps);
  13276. _SG_OBJC_RELEASE(mtl_cps);
  13277. pip->mtl.threads_per_threadgroup = shd->mtl.threads_per_threadgroup;
  13278. } else {
  13279. sg_primitive_type prim_type = desc->primitive_type;
  13280. pip->mtl.prim_type = _sg_mtl_primitive_type(prim_type);
  13281. pip->mtl.index_size = _sg_mtl_index_size(pip->cmn.index_type);
  13282. if (SG_INDEXTYPE_NONE != pip->cmn.index_type) {
  13283. pip->mtl.index_type = _sg_mtl_index_type(pip->cmn.index_type);
  13284. }
  13285. pip->mtl.cull_mode = _sg_mtl_cull_mode(desc->cull_mode);
  13286. pip->mtl.winding = _sg_mtl_winding(desc->face_winding);
  13287. pip->mtl.stencil_ref = desc->stencil.ref;
  13288. // create vertex-descriptor
  13289. MTLVertexDescriptor* vtx_desc = [MTLVertexDescriptor vertexDescriptor];
  13290. for (NSUInteger attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  13291. const sg_vertex_attr_state* a_state = &desc->layout.attrs[attr_index];
  13292. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  13293. break;
  13294. }
  13295. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  13296. SOKOL_ASSERT(pip->cmn.vertex_buffer_layout_active[a_state->buffer_index]);
  13297. vtx_desc.attributes[attr_index].format = _sg_mtl_vertex_format(a_state->format);
  13298. vtx_desc.attributes[attr_index].offset = (NSUInteger)a_state->offset;
  13299. vtx_desc.attributes[attr_index].bufferIndex = _sg_mtl_vertexbuffer_bindslot((size_t)a_state->buffer_index);
  13300. }
  13301. for (NSUInteger layout_index = 0; layout_index < SG_MAX_VERTEXBUFFER_BINDSLOTS; layout_index++) {
  13302. if (pip->cmn.vertex_buffer_layout_active[layout_index]) {
  13303. const sg_vertex_buffer_layout_state* l_state = &desc->layout.buffers[layout_index];
  13304. const NSUInteger mtl_vb_slot = _sg_mtl_vertexbuffer_bindslot(layout_index);
  13305. SOKOL_ASSERT(l_state->stride > 0);
  13306. vtx_desc.layouts[mtl_vb_slot].stride = (NSUInteger)l_state->stride;
  13307. vtx_desc.layouts[mtl_vb_slot].stepFunction = _sg_mtl_step_function(l_state->step_func);
  13308. vtx_desc.layouts[mtl_vb_slot].stepRate = (NSUInteger)l_state->step_rate;
  13309. if (SG_VERTEXSTEP_PER_INSTANCE == l_state->step_func) {
  13310. // NOTE: not actually used in _sg_mtl_draw()
  13311. pip->cmn.use_instanced_draw = true;
  13312. }
  13313. }
  13314. }
  13315. // render-pipeline descriptor
  13316. MTLRenderPipelineDescriptor* rp_desc = [[MTLRenderPipelineDescriptor alloc] init];
  13317. rp_desc.vertexDescriptor = vtx_desc;
  13318. SOKOL_ASSERT(shd->mtl.vertex_func.mtl_func != _SG_MTL_INVALID_SLOT_INDEX);
  13319. rp_desc.vertexFunction = _sg_mtl_id(shd->mtl.vertex_func.mtl_func);
  13320. SOKOL_ASSERT(shd->mtl.fragment_func.mtl_func != _SG_MTL_INVALID_SLOT_INDEX);
  13321. rp_desc.fragmentFunction = _sg_mtl_id(shd->mtl.fragment_func.mtl_func);
  13322. rp_desc.rasterSampleCount = (NSUInteger)desc->sample_count;
  13323. rp_desc.alphaToCoverageEnabled = desc->alpha_to_coverage_enabled;
  13324. rp_desc.alphaToOneEnabled = NO;
  13325. rp_desc.rasterizationEnabled = YES;
  13326. rp_desc.depthAttachmentPixelFormat = _sg_mtl_pixel_format(desc->depth.pixel_format);
  13327. if (desc->depth.pixel_format == SG_PIXELFORMAT_DEPTH_STENCIL) {
  13328. rp_desc.stencilAttachmentPixelFormat = _sg_mtl_pixel_format(desc->depth.pixel_format);
  13329. }
  13330. for (NSUInteger i = 0; i < (NSUInteger)desc->color_count; i++) {
  13331. SOKOL_ASSERT(i < SG_MAX_COLOR_ATTACHMENTS);
  13332. const sg_color_target_state* cs = &desc->colors[i];
  13333. rp_desc.colorAttachments[i].pixelFormat = _sg_mtl_pixel_format(cs->pixel_format);
  13334. rp_desc.colorAttachments[i].writeMask = _sg_mtl_color_write_mask(cs->write_mask);
  13335. rp_desc.colorAttachments[i].blendingEnabled = cs->blend.enabled;
  13336. rp_desc.colorAttachments[i].alphaBlendOperation = _sg_mtl_blend_op(cs->blend.op_alpha);
  13337. rp_desc.colorAttachments[i].rgbBlendOperation = _sg_mtl_blend_op(cs->blend.op_rgb);
  13338. rp_desc.colorAttachments[i].destinationAlphaBlendFactor = _sg_mtl_blend_factor(cs->blend.dst_factor_alpha);
  13339. rp_desc.colorAttachments[i].destinationRGBBlendFactor = _sg_mtl_blend_factor(cs->blend.dst_factor_rgb);
  13340. rp_desc.colorAttachments[i].sourceAlphaBlendFactor = _sg_mtl_blend_factor(cs->blend.src_factor_alpha);
  13341. rp_desc.colorAttachments[i].sourceRGBBlendFactor = _sg_mtl_blend_factor(cs->blend.src_factor_rgb);
  13342. }
  13343. // set buffer mutability for all read-only buffers (vertex buffers and read-only storage buffers)
  13344. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  13345. if (pip->cmn.vertex_buffer_layout_active[i]) {
  13346. const NSUInteger mtl_slot = _sg_mtl_vertexbuffer_bindslot(i);
  13347. rp_desc.vertexBuffers[mtl_slot].mutability = MTLMutabilityImmutable;
  13348. }
  13349. }
  13350. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  13351. const NSUInteger mtl_slot = shd->mtl.sbuf_buffer_n[i];
  13352. const sg_shader_stage stage = shd->cmn.storage_buffers[i].stage;
  13353. SOKOL_ASSERT(stage != SG_SHADERSTAGE_COMPUTE);
  13354. if (stage == SG_SHADERSTAGE_VERTEX) {
  13355. SOKOL_ASSERT(shd->cmn.storage_buffers[i].readonly);
  13356. rp_desc.vertexBuffers[mtl_slot].mutability = MTLMutabilityImmutable;
  13357. } else if (stage == SG_SHADERSTAGE_FRAGMENT) {
  13358. SOKOL_ASSERT(shd->cmn.storage_buffers[i].readonly);
  13359. rp_desc.fragmentBuffers[mtl_slot].mutability = MTLMutabilityImmutable;
  13360. }
  13361. }
  13362. #if defined(SOKOL_DEBUG)
  13363. if (desc->label) {
  13364. rp_desc.label = [NSString stringWithFormat:@"%s", desc->label];
  13365. }
  13366. #endif
  13367. NSError* err = NULL;
  13368. id<MTLRenderPipelineState> mtl_rps = [_sg.mtl.device newRenderPipelineStateWithDescriptor:rp_desc error:&err];
  13369. _SG_OBJC_RELEASE(rp_desc);
  13370. if (nil == mtl_rps) {
  13371. SOKOL_ASSERT(err);
  13372. _SG_ERROR(METAL_CREATE_RPS_FAILED);
  13373. _SG_LOGMSG(METAL_CREATE_RPS_OUTPUT, [err.localizedDescription UTF8String]);
  13374. return SG_RESOURCESTATE_FAILED;
  13375. }
  13376. pip->mtl.rps = _sg_mtl_add_resource(mtl_rps);
  13377. _SG_OBJC_RELEASE(mtl_rps);
  13378. // depth-stencil-state
  13379. MTLDepthStencilDescriptor* ds_desc = [[MTLDepthStencilDescriptor alloc] init];
  13380. ds_desc.depthCompareFunction = _sg_mtl_compare_func(desc->depth.compare);
  13381. ds_desc.depthWriteEnabled = desc->depth.write_enabled;
  13382. if (desc->stencil.enabled) {
  13383. const sg_stencil_face_state* sb = &desc->stencil.back;
  13384. ds_desc.backFaceStencil = [[MTLStencilDescriptor alloc] init];
  13385. ds_desc.backFaceStencil.stencilFailureOperation = _sg_mtl_stencil_op(sb->fail_op);
  13386. ds_desc.backFaceStencil.depthFailureOperation = _sg_mtl_stencil_op(sb->depth_fail_op);
  13387. ds_desc.backFaceStencil.depthStencilPassOperation = _sg_mtl_stencil_op(sb->pass_op);
  13388. ds_desc.backFaceStencil.stencilCompareFunction = _sg_mtl_compare_func(sb->compare);
  13389. ds_desc.backFaceStencil.readMask = desc->stencil.read_mask;
  13390. ds_desc.backFaceStencil.writeMask = desc->stencil.write_mask;
  13391. const sg_stencil_face_state* sf = &desc->stencil.front;
  13392. ds_desc.frontFaceStencil = [[MTLStencilDescriptor alloc] init];
  13393. ds_desc.frontFaceStencil.stencilFailureOperation = _sg_mtl_stencil_op(sf->fail_op);
  13394. ds_desc.frontFaceStencil.depthFailureOperation = _sg_mtl_stencil_op(sf->depth_fail_op);
  13395. ds_desc.frontFaceStencil.depthStencilPassOperation = _sg_mtl_stencil_op(sf->pass_op);
  13396. ds_desc.frontFaceStencil.stencilCompareFunction = _sg_mtl_compare_func(sf->compare);
  13397. ds_desc.frontFaceStencil.readMask = desc->stencil.read_mask;
  13398. ds_desc.frontFaceStencil.writeMask = desc->stencil.write_mask;
  13399. }
  13400. #if defined(SOKOL_DEBUG)
  13401. if (desc->label) {
  13402. ds_desc.label = [NSString stringWithFormat:@"%s.dss", desc->label];
  13403. }
  13404. #endif
  13405. id<MTLDepthStencilState> mtl_dss = [_sg.mtl.device newDepthStencilStateWithDescriptor:ds_desc];
  13406. _SG_OBJC_RELEASE(ds_desc);
  13407. if (nil == mtl_dss) {
  13408. _SG_ERROR(METAL_CREATE_DSS_FAILED);
  13409. return SG_RESOURCESTATE_FAILED;
  13410. }
  13411. pip->mtl.dss = _sg_mtl_add_resource(mtl_dss);
  13412. _SG_OBJC_RELEASE(mtl_dss);
  13413. }
  13414. return SG_RESOURCESTATE_VALID;
  13415. }
  13416. _SOKOL_PRIVATE void _sg_mtl_discard_pipeline(_sg_pipeline_t* pip) {
  13417. SOKOL_ASSERT(pip);
  13418. // it's valid to call release resource with a 'null resource'
  13419. _sg_mtl_release_resource(_sg.frame_index, pip->mtl.cps);
  13420. _sg_mtl_release_resource(_sg.frame_index, pip->mtl.rps);
  13421. _sg_mtl_release_resource(_sg.frame_index, pip->mtl.dss);
  13422. }
  13423. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_attachments(_sg_attachments_t* atts, const sg_attachments_desc* desc) {
  13424. SOKOL_ASSERT(atts && desc);
  13425. _SOKOL_UNUSED(desc);
  13426. // create texture views for storage attachments
  13427. for (int i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  13428. const _sg_image_t* stg_img = _sg_image_ref_ptr_or_null(&atts->cmn.storages[i].image);
  13429. if (stg_img) {
  13430. id<MTLTexture> mtl_tex_view = [_sg_mtl_id(stg_img->mtl.tex[0])
  13431. newTextureViewWithPixelFormat: _sg_mtl_pixel_format(stg_img->cmn.pixel_format)
  13432. textureType: _sg_mtl_texture_type(stg_img->cmn.type, false)
  13433. levels: NSMakeRange((NSUInteger)atts->cmn.storages[i].mip_level, 1)
  13434. slices: NSMakeRange((NSUInteger)atts->cmn.storages[i].slice, 1)];
  13435. atts->mtl.storage_views[i] = _sg_mtl_add_resource(mtl_tex_view);
  13436. }
  13437. }
  13438. return SG_RESOURCESTATE_VALID;
  13439. }
  13440. _SOKOL_PRIVATE void _sg_mtl_discard_attachments(_sg_attachments_t* atts) {
  13441. SOKOL_ASSERT(atts);
  13442. _SOKOL_UNUSED(atts);
  13443. for (int i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  13444. // it's valid to call _sg_mtl_release_resource with a null handle
  13445. _sg_mtl_release_resource(_sg.frame_index, atts->mtl.storage_views[i]);
  13446. }
  13447. }
  13448. _SOKOL_PRIVATE void _sg_mtl_bind_uniform_buffers(void) {
  13449. // In the Metal backend, uniform buffer bindings happen once in sg_begin_pass() and
  13450. // remain valid for the entire pass. Only binding offsets will be updated
  13451. // in sg_apply_uniforms()
  13452. if (_sg.cur_pass.is_compute) {
  13453. SOKOL_ASSERT(nil != _sg.mtl.compute_cmd_encoder);
  13454. for (size_t slot = 0; slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS; slot++) {
  13455. [_sg.mtl.compute_cmd_encoder
  13456. setBuffer:_sg.mtl.uniform_buffers[_sg.mtl.cur_frame_rotate_index]
  13457. offset:0
  13458. atIndex:slot];
  13459. }
  13460. } else {
  13461. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13462. for (size_t slot = 0; slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS; slot++) {
  13463. [_sg.mtl.render_cmd_encoder
  13464. setVertexBuffer:_sg.mtl.uniform_buffers[_sg.mtl.cur_frame_rotate_index]
  13465. offset:0
  13466. atIndex:slot];
  13467. [_sg.mtl.render_cmd_encoder
  13468. setFragmentBuffer:_sg.mtl.uniform_buffers[_sg.mtl.cur_frame_rotate_index]
  13469. offset:0
  13470. atIndex:slot];
  13471. }
  13472. }
  13473. }
  13474. _SOKOL_PRIVATE void _sg_mtl_begin_compute_pass(const sg_pass* pass) {
  13475. SOKOL_ASSERT(pass); (void)pass;
  13476. SOKOL_ASSERT(nil != _sg.mtl.cmd_buffer);
  13477. SOKOL_ASSERT(nil == _sg.mtl.compute_cmd_encoder);
  13478. SOKOL_ASSERT(nil == _sg.mtl.render_cmd_encoder);
  13479. _sg.mtl.compute_cmd_encoder = [_sg.mtl.cmd_buffer computeCommandEncoder];
  13480. if (nil == _sg.mtl.compute_cmd_encoder) {
  13481. _sg.cur_pass.valid = false;
  13482. return;
  13483. }
  13484. #if defined(SOKOL_DEBUG)
  13485. if (pass->label) {
  13486. _sg.mtl.compute_cmd_encoder.label = [NSString stringWithUTF8String:pass->label];
  13487. }
  13488. #endif
  13489. }
  13490. _SOKOL_PRIVATE void _sg_mtl_begin_render_pass(const sg_pass* pass) {
  13491. SOKOL_ASSERT(pass);
  13492. SOKOL_ASSERT(nil != _sg.mtl.cmd_buffer);
  13493. SOKOL_ASSERT(nil == _sg.mtl.render_cmd_encoder);
  13494. SOKOL_ASSERT(nil == _sg.mtl.compute_cmd_encoder);
  13495. const sg_swapchain* swapchain = &pass->swapchain;
  13496. const sg_pass_action* action = &pass->action;
  13497. MTLRenderPassDescriptor* pass_desc = [MTLRenderPassDescriptor renderPassDescriptor];
  13498. SOKOL_ASSERT(pass_desc);
  13499. const _sg_attachments_t* atts = _sg_attachments_ref_ptr_or_null(&_sg.cur_pass.atts);
  13500. if (atts) {
  13501. // setup pass descriptor for offscreen rendering
  13502. for (NSUInteger i = 0; i < (NSUInteger)atts->cmn.num_colors; i++) {
  13503. const _sg_attachment_common_t* cmn_color_att = &atts->cmn.colors[i];
  13504. const _sg_image_t* color_att_img = _sg_image_ref_ptr(&cmn_color_att->image);
  13505. const _sg_attachment_common_t* cmn_resolve_att = &atts->cmn.resolves[i];
  13506. const _sg_image_t* resolve_att_img = _sg_image_ref_ptr_or_null(&cmn_resolve_att->image);
  13507. SOKOL_ASSERT(color_att_img->slot.state == SG_RESOURCESTATE_VALID);
  13508. SOKOL_ASSERT(color_att_img->mtl.tex[color_att_img->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  13509. pass_desc.colorAttachments[i].loadAction = _sg_mtl_load_action(action->colors[i].load_action);
  13510. pass_desc.colorAttachments[i].storeAction = _sg_mtl_store_action(action->colors[i].store_action, resolve_att_img != 0);
  13511. sg_color c = action->colors[i].clear_value;
  13512. pass_desc.colorAttachments[i].clearColor = MTLClearColorMake(c.r, c.g, c.b, c.a);
  13513. pass_desc.colorAttachments[i].texture = _sg_mtl_id(color_att_img->mtl.tex[color_att_img->cmn.active_slot]);
  13514. pass_desc.colorAttachments[i].level = (NSUInteger)cmn_color_att->mip_level;
  13515. switch (color_att_img->cmn.type) {
  13516. case SG_IMAGETYPE_CUBE:
  13517. case SG_IMAGETYPE_ARRAY:
  13518. pass_desc.colorAttachments[i].slice = (NSUInteger)cmn_color_att->slice;
  13519. break;
  13520. case SG_IMAGETYPE_3D:
  13521. pass_desc.colorAttachments[i].depthPlane = (NSUInteger)cmn_color_att->slice;
  13522. break;
  13523. default: break;
  13524. }
  13525. if (resolve_att_img) {
  13526. SOKOL_ASSERT(resolve_att_img->slot.state == SG_RESOURCESTATE_VALID);
  13527. SOKOL_ASSERT(resolve_att_img->mtl.tex[resolve_att_img->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  13528. pass_desc.colorAttachments[i].resolveTexture = _sg_mtl_id(resolve_att_img->mtl.tex[resolve_att_img->cmn.active_slot]);
  13529. pass_desc.colorAttachments[i].resolveLevel = (NSUInteger)cmn_resolve_att->mip_level;
  13530. switch (resolve_att_img->cmn.type) {
  13531. case SG_IMAGETYPE_CUBE:
  13532. case SG_IMAGETYPE_ARRAY:
  13533. pass_desc.colorAttachments[i].resolveSlice = (NSUInteger)cmn_resolve_att->slice;
  13534. break;
  13535. case SG_IMAGETYPE_3D:
  13536. pass_desc.colorAttachments[i].resolveDepthPlane = (NSUInteger)cmn_resolve_att->slice;
  13537. break;
  13538. default: break;
  13539. }
  13540. }
  13541. }
  13542. const _sg_image_t* ds_att_img = _sg_image_ref_ptr_or_null(&atts->cmn.depth_stencil.image);
  13543. if (0 != ds_att_img) {
  13544. SOKOL_ASSERT(ds_att_img->slot.state == SG_RESOURCESTATE_VALID);
  13545. SOKOL_ASSERT(ds_att_img->mtl.tex[ds_att_img->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  13546. pass_desc.depthAttachment.texture = _sg_mtl_id(ds_att_img->mtl.tex[ds_att_img->cmn.active_slot]);
  13547. pass_desc.depthAttachment.loadAction = _sg_mtl_load_action(action->depth.load_action);
  13548. pass_desc.depthAttachment.storeAction = _sg_mtl_store_action(action->depth.store_action, false);
  13549. pass_desc.depthAttachment.clearDepth = action->depth.clear_value;
  13550. const _sg_attachment_common_t* cmn_ds_att = &atts->cmn.depth_stencil;
  13551. switch (ds_att_img->cmn.type) {
  13552. case SG_IMAGETYPE_CUBE:
  13553. case SG_IMAGETYPE_ARRAY:
  13554. pass_desc.depthAttachment.slice = (NSUInteger)cmn_ds_att->slice;
  13555. break;
  13556. case SG_IMAGETYPE_3D:
  13557. pass_desc.depthAttachment.resolveDepthPlane = (NSUInteger)cmn_ds_att->slice;
  13558. break;
  13559. default: break;
  13560. }
  13561. if (_sg_is_depth_stencil_format(ds_att_img->cmn.pixel_format)) {
  13562. pass_desc.stencilAttachment.texture = _sg_mtl_id(ds_att_img->mtl.tex[ds_att_img->cmn.active_slot]);
  13563. pass_desc.stencilAttachment.loadAction = _sg_mtl_load_action(action->stencil.load_action);
  13564. pass_desc.stencilAttachment.storeAction = _sg_mtl_store_action(action->depth.store_action, false);
  13565. pass_desc.stencilAttachment.clearStencil = action->stencil.clear_value;
  13566. switch (ds_att_img->cmn.type) {
  13567. case SG_IMAGETYPE_CUBE:
  13568. case SG_IMAGETYPE_ARRAY:
  13569. pass_desc.stencilAttachment.slice = (NSUInteger)cmn_ds_att->slice;
  13570. break;
  13571. case SG_IMAGETYPE_3D:
  13572. pass_desc.stencilAttachment.resolveDepthPlane = (NSUInteger)cmn_ds_att->slice;
  13573. break;
  13574. default: break;
  13575. }
  13576. }
  13577. }
  13578. } else {
  13579. // setup pass descriptor for swapchain rendering
  13580. //
  13581. // NOTE: at least in macOS Sonoma this no longer seems to be the case, the
  13582. // current drawable is also valid in a minimized window
  13583. // ===
  13584. // an MTKView current_drawable will not be valid if window is minimized, don't do any rendering in this case
  13585. if (0 == swapchain->metal.current_drawable) {
  13586. _sg.cur_pass.valid = false;
  13587. return;
  13588. }
  13589. // pin the swapchain resources into memory so that they outlive their command buffer
  13590. // (this is necessary because the command buffer doesn't retain references)
  13591. int pass_desc_ref = _sg_mtl_add_resource(pass_desc);
  13592. _sg_mtl_release_resource(_sg.frame_index, pass_desc_ref);
  13593. _sg.mtl.cur_drawable = (__bridge id<CAMetalDrawable>) swapchain->metal.current_drawable;
  13594. if (swapchain->sample_count > 1) {
  13595. // multi-sampling: render into msaa texture, resolve into drawable texture
  13596. id<MTLTexture> msaa_tex = (__bridge id<MTLTexture>) swapchain->metal.msaa_color_texture;
  13597. SOKOL_ASSERT(msaa_tex != nil);
  13598. pass_desc.colorAttachments[0].texture = msaa_tex;
  13599. pass_desc.colorAttachments[0].resolveTexture = _sg.mtl.cur_drawable.texture;
  13600. pass_desc.colorAttachments[0].storeAction = MTLStoreActionMultisampleResolve;
  13601. } else {
  13602. // non-msaa: render into current_drawable
  13603. pass_desc.colorAttachments[0].texture = _sg.mtl.cur_drawable.texture;
  13604. pass_desc.colorAttachments[0].storeAction = MTLStoreActionStore;
  13605. }
  13606. pass_desc.colorAttachments[0].loadAction = _sg_mtl_load_action(action->colors[0].load_action);
  13607. const sg_color c = action->colors[0].clear_value;
  13608. pass_desc.colorAttachments[0].clearColor = MTLClearColorMake(c.r, c.g, c.b, c.a);
  13609. // optional depth-stencil texture
  13610. if (swapchain->metal.depth_stencil_texture) {
  13611. id<MTLTexture> ds_tex = (__bridge id<MTLTexture>) swapchain->metal.depth_stencil_texture;
  13612. SOKOL_ASSERT(ds_tex != nil);
  13613. pass_desc.depthAttachment.texture = ds_tex;
  13614. pass_desc.depthAttachment.storeAction = MTLStoreActionDontCare;
  13615. pass_desc.depthAttachment.loadAction = _sg_mtl_load_action(action->depth.load_action);
  13616. pass_desc.depthAttachment.clearDepth = action->depth.clear_value;
  13617. if (_sg_is_depth_stencil_format(swapchain->depth_format)) {
  13618. pass_desc.stencilAttachment.texture = ds_tex;
  13619. pass_desc.stencilAttachment.storeAction = MTLStoreActionDontCare;
  13620. pass_desc.stencilAttachment.loadAction = _sg_mtl_load_action(action->stencil.load_action);
  13621. pass_desc.stencilAttachment.clearStencil = action->stencil.clear_value;
  13622. }
  13623. }
  13624. }
  13625. // NOTE: at least in macOS Sonoma, the following is no longer the case, a valid
  13626. // render command encoder is also returned in a minimized window
  13627. // ===
  13628. // create a render command encoder, this might return nil if window is minimized
  13629. _sg.mtl.render_cmd_encoder = [_sg.mtl.cmd_buffer renderCommandEncoderWithDescriptor:pass_desc];
  13630. if (nil == _sg.mtl.render_cmd_encoder) {
  13631. _sg.cur_pass.valid = false;
  13632. return;
  13633. }
  13634. #if defined(SOKOL_DEBUG)
  13635. if (pass->label) {
  13636. _sg.mtl.render_cmd_encoder.label = [NSString stringWithUTF8String:pass->label];
  13637. }
  13638. #endif
  13639. }
  13640. _SOKOL_PRIVATE void _sg_mtl_begin_pass(const sg_pass* pass) {
  13641. SOKOL_ASSERT(pass);
  13642. SOKOL_ASSERT(_sg.mtl.cmd_queue);
  13643. SOKOL_ASSERT(nil == _sg.mtl.compute_cmd_encoder);
  13644. SOKOL_ASSERT(nil == _sg.mtl.render_cmd_encoder);
  13645. SOKOL_ASSERT(nil == _sg.mtl.cur_drawable);
  13646. _sg_mtl_clear_state_cache();
  13647. // if this is the first pass in the frame, create one command buffer and blit-cmd-encoder for the entire frame
  13648. if (nil == _sg.mtl.cmd_buffer) {
  13649. // block until the oldest frame in flight has finished
  13650. dispatch_semaphore_wait(_sg.mtl.sem, DISPATCH_TIME_FOREVER);
  13651. if (_sg.desc.mtl_use_command_buffer_with_retained_references) {
  13652. _sg.mtl.cmd_buffer = [_sg.mtl.cmd_queue commandBuffer];
  13653. } else {
  13654. _sg.mtl.cmd_buffer = [_sg.mtl.cmd_queue commandBufferWithUnretainedReferences];
  13655. }
  13656. [_sg.mtl.cmd_buffer enqueue];
  13657. [_sg.mtl.cmd_buffer addCompletedHandler:^(id<MTLCommandBuffer> cmd_buf) {
  13658. // NOTE: this code is called on a different thread!
  13659. _SOKOL_UNUSED(cmd_buf);
  13660. dispatch_semaphore_signal(_sg.mtl.sem);
  13661. }];
  13662. }
  13663. // if this is first pass in frame, get uniform buffer base pointer
  13664. if (0 == _sg.mtl.cur_ub_base_ptr) {
  13665. _sg.mtl.cur_ub_base_ptr = (uint8_t*)[_sg.mtl.uniform_buffers[_sg.mtl.cur_frame_rotate_index] contents];
  13666. }
  13667. if (pass->compute) {
  13668. _sg_mtl_begin_compute_pass(pass);
  13669. } else {
  13670. _sg_mtl_begin_render_pass(pass);
  13671. }
  13672. // bind uniform buffers, those bindings remain valid for the entire pass
  13673. if (_sg.cur_pass.valid) {
  13674. _sg_mtl_bind_uniform_buffers();
  13675. }
  13676. }
  13677. _SOKOL_PRIVATE void _sg_mtl_end_pass(void) {
  13678. if (nil != _sg.mtl.render_cmd_encoder) {
  13679. [_sg.mtl.render_cmd_encoder endEncoding];
  13680. // NOTE: MTLRenderCommandEncoder is autoreleased
  13681. _sg.mtl.render_cmd_encoder = nil;
  13682. }
  13683. if (nil != _sg.mtl.compute_cmd_encoder) {
  13684. [_sg.mtl.compute_cmd_encoder endEncoding];
  13685. // NOTE: MTLComputeCommandEncoder is autoreleased
  13686. _sg.mtl.compute_cmd_encoder = nil;
  13687. // synchronize any managed resources written by the GPU
  13688. // NOTE: storage attachment images are currently not managed and are not eligible for syncing
  13689. #if defined(_SG_TARGET_MACOS)
  13690. if (_sg_mtl_resource_options_storage_mode_managed_or_shared() == MTLResourceStorageModeManaged) {
  13691. const bool needs_sync = _sg.compute.readwrite_sbufs.cur > 0;
  13692. if (needs_sync) {
  13693. id<MTLBlitCommandEncoder> blit_cmd_encoder = [_sg.mtl.cmd_buffer blitCommandEncoder];
  13694. for (uint32_t i = 0; i < _sg.compute.readwrite_sbufs.cur; i++) {
  13695. _sg_buffer_t* sbuf = _sg_lookup_buffer(_sg.compute.readwrite_sbufs.items[i]);
  13696. if (sbuf) {
  13697. [blit_cmd_encoder synchronizeResource:_sg_mtl_id(sbuf->mtl.buf[sbuf->cmn.active_slot])];
  13698. }
  13699. }
  13700. [blit_cmd_encoder endEncoding];
  13701. }
  13702. }
  13703. #endif
  13704. }
  13705. // if this is a swapchain pass, present the drawable
  13706. if (nil != _sg.mtl.cur_drawable) {
  13707. [_sg.mtl.cmd_buffer presentDrawable:_sg.mtl.cur_drawable];
  13708. _sg.mtl.cur_drawable = nil;
  13709. }
  13710. }
  13711. _SOKOL_PRIVATE void _sg_mtl_commit(void) {
  13712. SOKOL_ASSERT(nil == _sg.mtl.render_cmd_encoder);
  13713. SOKOL_ASSERT(nil == _sg.mtl.compute_cmd_encoder);
  13714. SOKOL_ASSERT(nil != _sg.mtl.cmd_buffer);
  13715. // commit the frame's command buffer
  13716. [_sg.mtl.cmd_buffer commit];
  13717. // garbage-collect resources pending for release
  13718. _sg_mtl_garbage_collect(_sg.frame_index);
  13719. // rotate uniform buffer slot
  13720. if (++_sg.mtl.cur_frame_rotate_index >= SG_NUM_INFLIGHT_FRAMES) {
  13721. _sg.mtl.cur_frame_rotate_index = 0;
  13722. }
  13723. _sg.mtl.cur_ub_offset = 0;
  13724. _sg.mtl.cur_ub_base_ptr = 0;
  13725. // NOTE: MTLCommandBuffer is autoreleased
  13726. _sg.mtl.cmd_buffer = nil;
  13727. }
  13728. _SOKOL_PRIVATE void _sg_mtl_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  13729. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13730. SOKOL_ASSERT(_sg.cur_pass.height > 0);
  13731. MTLViewport vp;
  13732. vp.originX = (double) x;
  13733. vp.originY = (double) (origin_top_left ? y : (_sg.cur_pass.height - (y + h)));
  13734. vp.width = (double) w;
  13735. vp.height = (double) h;
  13736. vp.znear = 0.0;
  13737. vp.zfar = 1.0;
  13738. [_sg.mtl.render_cmd_encoder setViewport:vp];
  13739. }
  13740. _SOKOL_PRIVATE void _sg_mtl_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  13741. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13742. SOKOL_ASSERT(_sg.cur_pass.width > 0);
  13743. SOKOL_ASSERT(_sg.cur_pass.height > 0);
  13744. // clip against framebuffer rect
  13745. const _sg_recti_t clip = _sg_clipi(x, y, w, h, _sg.cur_pass.width, _sg.cur_pass.height);
  13746. MTLScissorRect r;
  13747. r.x = (NSUInteger)clip.x;
  13748. r.y = (NSUInteger) (origin_top_left ? clip.y : (_sg.cur_pass.height - (clip.y + clip.h)));
  13749. r.width = (NSUInteger)clip.w;
  13750. r.height = (NSUInteger)clip.h;
  13751. [_sg.mtl.render_cmd_encoder setScissorRect:r];
  13752. }
  13753. _SOKOL_PRIVATE void _sg_mtl_apply_pipeline(_sg_pipeline_t* pip) {
  13754. SOKOL_ASSERT(pip);
  13755. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_pip, &pip->slot)) {
  13756. _sg.mtl.state_cache.cur_pip = _sg_sref(&pip->slot);
  13757. if (pip->cmn.is_compute) {
  13758. SOKOL_ASSERT(_sg.cur_pass.is_compute);
  13759. SOKOL_ASSERT(nil != _sg.mtl.compute_cmd_encoder);
  13760. SOKOL_ASSERT(pip->mtl.cps != _SG_MTL_INVALID_SLOT_INDEX);
  13761. [_sg.mtl.compute_cmd_encoder setComputePipelineState:_sg_mtl_id(pip->mtl.cps)];
  13762. // apply storage image bindings for writing
  13763. const _sg_attachments_t* atts = _sg_attachments_ref_ptr_or_null(&_sg.cur_pass.atts);
  13764. if (atts) {
  13765. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  13766. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  13767. const sg_shader_stage stage = shd->cmn.storage_images[i].stage;
  13768. if (stage != SG_SHADERSTAGE_COMPUTE) {
  13769. continue;
  13770. }
  13771. const NSUInteger mtl_slot = shd->mtl.simg_texture_n[i];
  13772. SOKOL_ASSERT(mtl_slot < _SG_MTL_MAX_STAGE_TEXTURE_BINDINGS);
  13773. const uint64_t cache_key = ((uint64_t)atts->cmn.storages[i].image.sref.id) << 32;
  13774. SOKOL_ASSERT(cache_key != 0);
  13775. if (_sg.mtl.state_cache.cur_cs_image_ids[mtl_slot] != cache_key) {
  13776. _sg.mtl.state_cache.cur_cs_image_ids[mtl_slot] = cache_key;
  13777. [_sg.mtl.compute_cmd_encoder setTexture:_sg_mtl_id(atts->mtl.storage_views[i]) atIndex:mtl_slot];
  13778. _sg_stats_add(metal.bindings.num_set_compute_texture, 1);
  13779. }
  13780. }
  13781. }
  13782. } else {
  13783. SOKOL_ASSERT(!_sg.cur_pass.is_compute);
  13784. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13785. sg_color c = pip->cmn.blend_color;
  13786. [_sg.mtl.render_cmd_encoder setBlendColorRed:c.r green:c.g blue:c.b alpha:c.a];
  13787. _sg_stats_add(metal.pipeline.num_set_blend_color, 1);
  13788. [_sg.mtl.render_cmd_encoder setCullMode:pip->mtl.cull_mode];
  13789. _sg_stats_add(metal.pipeline.num_set_cull_mode, 1);
  13790. [_sg.mtl.render_cmd_encoder setFrontFacingWinding:pip->mtl.winding];
  13791. _sg_stats_add(metal.pipeline.num_set_front_facing_winding, 1);
  13792. [_sg.mtl.render_cmd_encoder setStencilReferenceValue:pip->mtl.stencil_ref];
  13793. _sg_stats_add(metal.pipeline.num_set_stencil_reference_value, 1);
  13794. [_sg.mtl.render_cmd_encoder setDepthBias:pip->cmn.depth.bias slopeScale:pip->cmn.depth.bias_slope_scale clamp:pip->cmn.depth.bias_clamp];
  13795. _sg_stats_add(metal.pipeline.num_set_depth_bias, 1);
  13796. SOKOL_ASSERT(pip->mtl.rps != _SG_MTL_INVALID_SLOT_INDEX);
  13797. [_sg.mtl.render_cmd_encoder setRenderPipelineState:_sg_mtl_id(pip->mtl.rps)];
  13798. _sg_stats_add(metal.pipeline.num_set_render_pipeline_state, 1);
  13799. SOKOL_ASSERT(pip->mtl.dss != _SG_MTL_INVALID_SLOT_INDEX);
  13800. [_sg.mtl.render_cmd_encoder setDepthStencilState:_sg_mtl_id(pip->mtl.dss)];
  13801. _sg_stats_add(metal.pipeline.num_set_depth_stencil_state, 1);
  13802. }
  13803. }
  13804. }
  13805. _SOKOL_PRIVATE bool _sg_mtl_apply_bindings(_sg_bindings_ptrs_t* bnd) {
  13806. SOKOL_ASSERT(bnd);
  13807. SOKOL_ASSERT(bnd->pip);
  13808. const _sg_shader_t* shd = _sg_shader_ref_ptr(&bnd->pip->cmn.shader);
  13809. // don't set vertex- and index-buffers in compute passes
  13810. if (!_sg.cur_pass.is_compute) {
  13811. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13812. // store index buffer binding, this will be needed later in sg_draw()
  13813. _sg.mtl.state_cache.cur_ibuf = _sg_buffer_ref(bnd->ib);
  13814. if (bnd->ib) {
  13815. SOKOL_ASSERT(bnd->pip->cmn.index_type != SG_INDEXTYPE_NONE);
  13816. } else {
  13817. SOKOL_ASSERT(bnd->pip->cmn.index_type == SG_INDEXTYPE_NONE);
  13818. }
  13819. _sg.mtl.state_cache.cur_ibuf_offset = bnd->ib_offset;
  13820. // apply vertex buffers
  13821. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  13822. const _sg_buffer_t* vb = bnd->vbs[i];
  13823. if (vb == 0) {
  13824. continue;
  13825. }
  13826. const NSUInteger mtl_slot = _sg_mtl_vertexbuffer_bindslot(i);
  13827. SOKOL_ASSERT(mtl_slot < _SG_MTL_MAX_STAGE_BUFFER_BINDINGS);
  13828. const int vb_offset = bnd->vb_offsets[i];
  13829. const bool ref_eql = _sg_sref_eql(&_sg.mtl.state_cache.cur_vsbufs[mtl_slot], &vb->slot);
  13830. if (!ref_eql || (_sg.mtl.state_cache.cur_vs_buffer_offsets[mtl_slot] != vb_offset)) {
  13831. _sg.mtl.state_cache.cur_vs_buffer_offsets[mtl_slot] = vb_offset;
  13832. if (!ref_eql) {
  13833. // vertex buffer has changed
  13834. _sg.mtl.state_cache.cur_vsbufs[mtl_slot] = _sg_sref(&vb->slot);
  13835. SOKOL_ASSERT(vb->mtl.buf[vb->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  13836. [_sg.mtl.render_cmd_encoder setVertexBuffer:_sg_mtl_id(vb->mtl.buf[vb->cmn.active_slot])
  13837. offset:(NSUInteger)vb_offset
  13838. atIndex:mtl_slot];
  13839. } else {
  13840. // only vertex buffer offset has changed
  13841. [_sg.mtl.render_cmd_encoder setVertexBufferOffset:(NSUInteger)vb_offset atIndex:mtl_slot];
  13842. }
  13843. _sg_stats_add(metal.bindings.num_set_vertex_buffer, 1);
  13844. }
  13845. }
  13846. }
  13847. // apply image bindings
  13848. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  13849. const _sg_image_t* img = bnd->imgs[i];
  13850. if (img == 0) {
  13851. continue;
  13852. }
  13853. SOKOL_ASSERT(img->mtl.tex[img->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  13854. const sg_shader_stage stage = shd->cmn.images[i].stage;
  13855. SOKOL_ASSERT((stage == SG_SHADERSTAGE_VERTEX) || (stage == SG_SHADERSTAGE_FRAGMENT) || (stage == SG_SHADERSTAGE_COMPUTE));
  13856. const NSUInteger mtl_slot = shd->mtl.img_texture_n[i];
  13857. SOKOL_ASSERT(mtl_slot < _SG_MTL_MAX_STAGE_TEXTURE_BINDINGS);
  13858. if (stage == SG_SHADERSTAGE_VERTEX) {
  13859. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13860. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_vsimgs[mtl_slot], &img->slot)) {
  13861. _sg.mtl.state_cache.cur_vsimgs[mtl_slot] = _sg_sref(&img->slot);
  13862. [_sg.mtl.render_cmd_encoder setVertexTexture:_sg_mtl_id(img->mtl.tex[img->cmn.active_slot]) atIndex:mtl_slot];
  13863. _sg_stats_add(metal.bindings.num_set_vertex_texture, 1);
  13864. }
  13865. } else if (stage == SG_SHADERSTAGE_FRAGMENT) {
  13866. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13867. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_fsimgs[mtl_slot], &img->slot)) {
  13868. _sg.mtl.state_cache.cur_fsimgs[mtl_slot] = _sg_sref(&img->slot);
  13869. [_sg.mtl.render_cmd_encoder setFragmentTexture:_sg_mtl_id(img->mtl.tex[img->cmn.active_slot]) atIndex:mtl_slot];
  13870. _sg_stats_add(metal.bindings.num_set_fragment_texture, 1);
  13871. }
  13872. } else if (stage == SG_SHADERSTAGE_COMPUTE) {
  13873. SOKOL_ASSERT(nil != _sg.mtl.compute_cmd_encoder);
  13874. if (_sg.mtl.state_cache.cur_cs_image_ids[mtl_slot] != img->slot.id) {
  13875. _sg.mtl.state_cache.cur_cs_image_ids[mtl_slot] = img->slot.id;
  13876. [_sg.mtl.compute_cmd_encoder setTexture:_sg_mtl_id(img->mtl.tex[img->cmn.active_slot]) atIndex:mtl_slot];
  13877. _sg_stats_add(metal.bindings.num_set_compute_texture, 1);
  13878. }
  13879. }
  13880. }
  13881. // apply sampler bindings
  13882. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  13883. const _sg_sampler_t* smp = bnd->smps[i];
  13884. if (smp == 0) {
  13885. continue;
  13886. }
  13887. SOKOL_ASSERT(smp->mtl.sampler_state != _SG_MTL_INVALID_SLOT_INDEX);
  13888. const sg_shader_stage stage = shd->cmn.samplers[i].stage;
  13889. SOKOL_ASSERT((stage == SG_SHADERSTAGE_VERTEX) || (stage == SG_SHADERSTAGE_FRAGMENT) || (stage == SG_SHADERSTAGE_COMPUTE));
  13890. const NSUInteger mtl_slot = shd->mtl.smp_sampler_n[i];
  13891. SOKOL_ASSERT(mtl_slot < _SG_MTL_MAX_STAGE_SAMPLER_BINDINGS);
  13892. if (stage == SG_SHADERSTAGE_VERTEX) {
  13893. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13894. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_vssmps[mtl_slot], &smp->slot)) {
  13895. _sg.mtl.state_cache.cur_vssmps[mtl_slot] = _sg_sref(&smp->slot);
  13896. [_sg.mtl.render_cmd_encoder setVertexSamplerState:_sg_mtl_id(smp->mtl.sampler_state) atIndex:mtl_slot];
  13897. _sg_stats_add(metal.bindings.num_set_vertex_sampler_state, 1);
  13898. }
  13899. } else if (stage == SG_SHADERSTAGE_FRAGMENT) {
  13900. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13901. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_fssmps[mtl_slot], &smp->slot)) {
  13902. _sg.mtl.state_cache.cur_fssmps[mtl_slot] = _sg_sref(&smp->slot);
  13903. [_sg.mtl.render_cmd_encoder setFragmentSamplerState:_sg_mtl_id(smp->mtl.sampler_state) atIndex:mtl_slot];
  13904. _sg_stats_add(metal.bindings.num_set_fragment_sampler_state, 1);
  13905. }
  13906. } else if (stage == SG_SHADERSTAGE_COMPUTE) {
  13907. SOKOL_ASSERT(nil != _sg.mtl.compute_cmd_encoder);
  13908. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_cssmps[mtl_slot], &smp->slot)) {
  13909. _sg.mtl.state_cache.cur_cssmps[mtl_slot] = _sg_sref(&smp->slot);
  13910. [_sg.mtl.compute_cmd_encoder setSamplerState:_sg_mtl_id(smp->mtl.sampler_state) atIndex:mtl_slot];
  13911. _sg_stats_add(metal.bindings.num_set_compute_sampler_state, 1);
  13912. }
  13913. }
  13914. }
  13915. // apply storage buffer bindings
  13916. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  13917. const _sg_buffer_t* sbuf = bnd->sbufs[i];
  13918. if (sbuf == 0) {
  13919. continue;
  13920. }
  13921. SOKOL_ASSERT(sbuf->mtl.buf[sbuf->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  13922. const sg_shader_stage stage = shd->cmn.storage_buffers[i].stage;
  13923. SOKOL_ASSERT((stage == SG_SHADERSTAGE_VERTEX) || (stage == SG_SHADERSTAGE_FRAGMENT) || (stage == SG_SHADERSTAGE_COMPUTE));
  13924. const NSUInteger mtl_slot = shd->mtl.sbuf_buffer_n[i];
  13925. SOKOL_ASSERT(mtl_slot < _SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS);
  13926. if (stage == SG_SHADERSTAGE_VERTEX) {
  13927. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13928. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_vsbufs[mtl_slot], &sbuf->slot)) {
  13929. _sg.mtl.state_cache.cur_vsbufs[mtl_slot] = _sg_sref(&sbuf->slot);
  13930. [_sg.mtl.render_cmd_encoder setVertexBuffer:_sg_mtl_id(sbuf->mtl.buf[sbuf->cmn.active_slot]) offset:0 atIndex:mtl_slot];
  13931. _sg_stats_add(metal.bindings.num_set_vertex_buffer, 1);
  13932. }
  13933. } else if (stage == SG_SHADERSTAGE_FRAGMENT) {
  13934. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13935. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_fsbufs[mtl_slot], &sbuf->slot)) {
  13936. _sg.mtl.state_cache.cur_fsbufs[mtl_slot] = _sg_sref(&sbuf->slot);
  13937. [_sg.mtl.render_cmd_encoder setFragmentBuffer:_sg_mtl_id(sbuf->mtl.buf[sbuf->cmn.active_slot]) offset:0 atIndex:mtl_slot];
  13938. _sg_stats_add(metal.bindings.num_set_fragment_buffer, 1);
  13939. }
  13940. } else if (stage == SG_SHADERSTAGE_COMPUTE) {
  13941. SOKOL_ASSERT(nil != _sg.mtl.compute_cmd_encoder);
  13942. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_csbufs[mtl_slot], &sbuf->slot)) {
  13943. _sg.mtl.state_cache.cur_csbufs[mtl_slot] = _sg_sref(&sbuf->slot);
  13944. [_sg.mtl.compute_cmd_encoder setBuffer:_sg_mtl_id(sbuf->mtl.buf[sbuf->cmn.active_slot]) offset:0 atIndex:mtl_slot];
  13945. _sg_stats_add(metal.bindings.num_set_compute_buffer, 1);
  13946. }
  13947. }
  13948. }
  13949. return true;
  13950. }
  13951. _SOKOL_PRIVATE void _sg_mtl_apply_uniforms(int ub_slot, const sg_range* data) {
  13952. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  13953. SOKOL_ASSERT(((size_t)_sg.mtl.cur_ub_offset + data->size) <= (size_t)_sg.mtl.ub_size);
  13954. SOKOL_ASSERT((_sg.mtl.cur_ub_offset & (_SG_MTL_UB_ALIGN-1)) == 0);
  13955. const _sg_pipeline_t* pip = _sg_pipeline_ref_ptr(&_sg.cur_pip);
  13956. SOKOL_ASSERT(pip);
  13957. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  13958. SOKOL_ASSERT(data->size == shd->cmn.uniform_blocks[ub_slot].size);
  13959. const sg_shader_stage stage = shd->cmn.uniform_blocks[ub_slot].stage;
  13960. const NSUInteger mtl_slot = shd->mtl.ub_buffer_n[ub_slot];
  13961. // copy to global uniform buffer, record offset into cmd encoder, and advance offset
  13962. uint8_t* dst = &_sg.mtl.cur_ub_base_ptr[_sg.mtl.cur_ub_offset];
  13963. memcpy(dst, data->ptr, data->size);
  13964. if (stage == SG_SHADERSTAGE_VERTEX) {
  13965. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13966. [_sg.mtl.render_cmd_encoder setVertexBufferOffset:(NSUInteger)_sg.mtl.cur_ub_offset atIndex:mtl_slot];
  13967. _sg_stats_add(metal.uniforms.num_set_vertex_buffer_offset, 1);
  13968. } else if (stage == SG_SHADERSTAGE_FRAGMENT) {
  13969. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13970. [_sg.mtl.render_cmd_encoder setFragmentBufferOffset:(NSUInteger)_sg.mtl.cur_ub_offset atIndex:mtl_slot];
  13971. _sg_stats_add(metal.uniforms.num_set_fragment_buffer_offset, 1);
  13972. } else if (stage == SG_SHADERSTAGE_COMPUTE) {
  13973. SOKOL_ASSERT(nil != _sg.mtl.compute_cmd_encoder);
  13974. [_sg.mtl.compute_cmd_encoder setBufferOffset:(NSUInteger)_sg.mtl.cur_ub_offset atIndex:mtl_slot];
  13975. _sg_stats_add(metal.uniforms.num_set_compute_buffer_offset, 1);
  13976. } else {
  13977. SOKOL_UNREACHABLE;
  13978. }
  13979. _sg.mtl.cur_ub_offset = _sg_roundup(_sg.mtl.cur_ub_offset + (int)data->size, _SG_MTL_UB_ALIGN);
  13980. }
  13981. _SOKOL_PRIVATE void _sg_mtl_draw(int base_element, int num_elements, int num_instances) {
  13982. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13983. const _sg_pipeline_t* pip = _sg_pipeline_ref_ptr(&_sg.cur_pip);
  13984. SOKOL_ASSERT(pip);
  13985. if (SG_INDEXTYPE_NONE != pip->cmn.index_type) {
  13986. // indexed rendering
  13987. const _sg_buffer_t* ib = _sg_buffer_ref_ptr(&_sg.mtl.state_cache.cur_ibuf);
  13988. SOKOL_ASSERT(ib && (ib->mtl.buf[ib->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX));
  13989. const NSUInteger index_buffer_offset = (NSUInteger) (_sg.mtl.state_cache.cur_ibuf_offset + base_element * pip->mtl.index_size);
  13990. [_sg.mtl.render_cmd_encoder drawIndexedPrimitives:pip->mtl.prim_type
  13991. indexCount:(NSUInteger)num_elements
  13992. indexType:pip->mtl.index_type
  13993. indexBuffer:_sg_mtl_id(ib->mtl.buf[ib->cmn.active_slot])
  13994. indexBufferOffset:index_buffer_offset
  13995. instanceCount:(NSUInteger)num_instances];
  13996. } else {
  13997. // non-indexed rendering
  13998. [_sg.mtl.render_cmd_encoder drawPrimitives:pip->mtl.prim_type
  13999. vertexStart:(NSUInteger)base_element
  14000. vertexCount:(NSUInteger)num_elements
  14001. instanceCount:(NSUInteger)num_instances];
  14002. }
  14003. }
  14004. _SOKOL_PRIVATE void _sg_mtl_dispatch(int num_groups_x, int num_groups_y, int num_groups_z) {
  14005. SOKOL_ASSERT(nil != _sg.mtl.compute_cmd_encoder);
  14006. const _sg_pipeline_t* pip = _sg_pipeline_ref_ptr(&_sg.cur_pip);
  14007. SOKOL_ASSERT(pip);
  14008. const MTLSize thread_groups = MTLSizeMake(
  14009. (NSUInteger)num_groups_x,
  14010. (NSUInteger)num_groups_y,
  14011. (NSUInteger)num_groups_z);
  14012. const MTLSize threads_per_threadgroup = pip->mtl.threads_per_threadgroup;
  14013. [_sg.mtl.compute_cmd_encoder dispatchThreadgroups:thread_groups threadsPerThreadgroup:threads_per_threadgroup];
  14014. }
  14015. _SOKOL_PRIVATE void _sg_mtl_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  14016. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  14017. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  14018. buf->cmn.active_slot = 0;
  14019. }
  14020. __unsafe_unretained id<MTLBuffer> mtl_buf = _sg_mtl_id(buf->mtl.buf[buf->cmn.active_slot]);
  14021. void* dst_ptr = [mtl_buf contents];
  14022. memcpy(dst_ptr, data->ptr, data->size);
  14023. #if defined(_SG_TARGET_MACOS)
  14024. if (_sg_mtl_resource_options_storage_mode_managed_or_shared() == MTLResourceStorageModeManaged) {
  14025. [mtl_buf didModifyRange:NSMakeRange(0, data->size)];
  14026. }
  14027. #endif
  14028. }
  14029. _SOKOL_PRIVATE void _sg_mtl_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  14030. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  14031. if (new_frame) {
  14032. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  14033. buf->cmn.active_slot = 0;
  14034. }
  14035. }
  14036. __unsafe_unretained id<MTLBuffer> mtl_buf = _sg_mtl_id(buf->mtl.buf[buf->cmn.active_slot]);
  14037. uint8_t* dst_ptr = (uint8_t*) [mtl_buf contents];
  14038. dst_ptr += buf->cmn.append_pos;
  14039. memcpy(dst_ptr, data->ptr, data->size);
  14040. #if defined(_SG_TARGET_MACOS)
  14041. if (_sg_mtl_resource_options_storage_mode_managed_or_shared() == MTLResourceStorageModeManaged) {
  14042. [mtl_buf didModifyRange:NSMakeRange((NSUInteger)buf->cmn.append_pos, (NSUInteger)data->size)];
  14043. }
  14044. #endif
  14045. }
  14046. _SOKOL_PRIVATE void _sg_mtl_update_image(_sg_image_t* img, const sg_image_data* data) {
  14047. SOKOL_ASSERT(img && data);
  14048. if (++img->cmn.active_slot >= img->cmn.num_slots) {
  14049. img->cmn.active_slot = 0;
  14050. }
  14051. __unsafe_unretained id<MTLTexture> mtl_tex = _sg_mtl_id(img->mtl.tex[img->cmn.active_slot]);
  14052. _sg_mtl_copy_image_data(img, mtl_tex, data);
  14053. }
  14054. _SOKOL_PRIVATE void _sg_mtl_push_debug_group(const char* name) {
  14055. SOKOL_ASSERT(name);
  14056. if (_sg.mtl.render_cmd_encoder) {
  14057. [_sg.mtl.render_cmd_encoder pushDebugGroup:[NSString stringWithUTF8String:name]];
  14058. } else if (_sg.mtl.compute_cmd_encoder) {
  14059. [_sg.mtl.compute_cmd_encoder pushDebugGroup:[NSString stringWithUTF8String:name]];
  14060. }
  14061. }
  14062. _SOKOL_PRIVATE void _sg_mtl_pop_debug_group(void) {
  14063. if (_sg.mtl.render_cmd_encoder) {
  14064. [_sg.mtl.render_cmd_encoder popDebugGroup];
  14065. } else if (_sg.mtl.compute_cmd_encoder) {
  14066. [_sg.mtl.compute_cmd_encoder popDebugGroup];
  14067. }
  14068. }
  14069. // ██ ██ ███████ ██████ ██████ ██████ ██ ██ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  14070. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  14071. // ██ █ ██ █████ ██████ ██ ███ ██████ ██ ██ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  14072. // ██ ███ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  14073. // ███ ███ ███████ ██████ ██████ ██ ██████ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  14074. //
  14075. // >>webgpu
  14076. // >>wgpu
  14077. #elif defined(SOKOL_WGPU)
  14078. #if !defined(__EMSCRIPTEN__)
  14079. // FIXME: webgpu.h differences between Dawn and Emscripten webgpu.h
  14080. #define wgpuBufferReference wgpuBufferAddRef
  14081. #define wgpuTextureReference wgpuTextureAddRef
  14082. #define wgpuTextureViewReference wgpuTextureViewAddRef
  14083. #define wgpuSamplerReference wgpuSamplerAddRef
  14084. #define WGPUSType_ShaderModuleWGSLDescriptor WGPUSType_ShaderSourceWGSL
  14085. _SOKOL_PRIVATE WGPUStringView _sg_wgpu_stringview(const char* str) {
  14086. WGPUStringView res;
  14087. if (str) {
  14088. res.data = str;
  14089. res.length = strlen(str);
  14090. } else {
  14091. res.data = 0;
  14092. res.length = 0;
  14093. }
  14094. return res;
  14095. }
  14096. _SOKOL_PRIVATE WGPUOptionalBool _sg_wgpu_optional_bool(bool b) {
  14097. return b ? WGPUOptionalBool_True : WGPUOptionalBool_False;
  14098. }
  14099. #else
  14100. #define _sg_wgpu_stringview(str) str
  14101. #define _sg_wgpu_optional_bool(b) (b)
  14102. #endif
  14103. _SOKOL_PRIVATE WGPUBufferUsage _sg_wgpu_buffer_usage(const sg_buffer_usage* usg) {
  14104. int res = 0;
  14105. if (usg->vertex_buffer) {
  14106. res |= WGPUBufferUsage_Vertex;
  14107. }
  14108. if (usg->index_buffer) {
  14109. res |= WGPUBufferUsage_Index;
  14110. }
  14111. if (usg->storage_buffer) {
  14112. res |= WGPUBufferUsage_Storage;
  14113. }
  14114. if (!usg->immutable) {
  14115. res |= WGPUBufferUsage_CopyDst;
  14116. }
  14117. return (WGPUBufferUsage)res;
  14118. }
  14119. _SOKOL_PRIVATE WGPULoadOp _sg_wgpu_load_op(WGPUTextureView view, sg_load_action a) {
  14120. if (0 == view) {
  14121. return WGPULoadOp_Undefined;
  14122. } else switch (a) {
  14123. case SG_LOADACTION_CLEAR:
  14124. case SG_LOADACTION_DONTCARE:
  14125. return WGPULoadOp_Clear;
  14126. case SG_LOADACTION_LOAD:
  14127. return WGPULoadOp_Load;
  14128. default:
  14129. SOKOL_UNREACHABLE;
  14130. return WGPULoadOp_Force32;
  14131. }
  14132. }
  14133. _SOKOL_PRIVATE WGPUStoreOp _sg_wgpu_store_op(WGPUTextureView view, sg_store_action a) {
  14134. if (0 == view) {
  14135. return WGPUStoreOp_Undefined;
  14136. } else switch (a) {
  14137. case SG_STOREACTION_STORE:
  14138. return WGPUStoreOp_Store;
  14139. case SG_STOREACTION_DONTCARE:
  14140. return WGPUStoreOp_Discard;
  14141. default:
  14142. SOKOL_UNREACHABLE;
  14143. return WGPUStoreOp_Force32;
  14144. }
  14145. }
  14146. _SOKOL_PRIVATE WGPUTextureViewDimension _sg_wgpu_texture_view_dimension(sg_image_type t) {
  14147. switch (t) {
  14148. case SG_IMAGETYPE_2D: return WGPUTextureViewDimension_2D;
  14149. case SG_IMAGETYPE_CUBE: return WGPUTextureViewDimension_Cube;
  14150. case SG_IMAGETYPE_3D: return WGPUTextureViewDimension_3D;
  14151. case SG_IMAGETYPE_ARRAY: return WGPUTextureViewDimension_2DArray;
  14152. default: SOKOL_UNREACHABLE; return WGPUTextureViewDimension_Force32;
  14153. }
  14154. }
  14155. _SOKOL_PRIVATE WGPUTextureDimension _sg_wgpu_texture_dimension(sg_image_type t) {
  14156. if (SG_IMAGETYPE_3D == t) {
  14157. return WGPUTextureDimension_3D;
  14158. } else {
  14159. return WGPUTextureDimension_2D;
  14160. }
  14161. }
  14162. _SOKOL_PRIVATE WGPUTextureSampleType _sg_wgpu_texture_sample_type(sg_image_sample_type t, bool msaa) {
  14163. switch (t) {
  14164. case SG_IMAGESAMPLETYPE_FLOAT: return msaa ? WGPUTextureSampleType_UnfilterableFloat : WGPUTextureSampleType_Float;
  14165. case SG_IMAGESAMPLETYPE_DEPTH: return WGPUTextureSampleType_Depth;
  14166. case SG_IMAGESAMPLETYPE_SINT: return WGPUTextureSampleType_Sint;
  14167. case SG_IMAGESAMPLETYPE_UINT: return WGPUTextureSampleType_Uint;
  14168. case SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT: return WGPUTextureSampleType_UnfilterableFloat;
  14169. default: SOKOL_UNREACHABLE; return WGPUTextureSampleType_Force32;
  14170. }
  14171. }
  14172. _SOKOL_PRIVATE WGPUSamplerBindingType _sg_wgpu_sampler_binding_type(sg_sampler_type t) {
  14173. switch (t) {
  14174. case SG_SAMPLERTYPE_FILTERING: return WGPUSamplerBindingType_Filtering;
  14175. case SG_SAMPLERTYPE_COMPARISON: return WGPUSamplerBindingType_Comparison;
  14176. case SG_SAMPLERTYPE_NONFILTERING: return WGPUSamplerBindingType_NonFiltering;
  14177. default: SOKOL_UNREACHABLE; return WGPUSamplerBindingType_Force32;
  14178. }
  14179. }
  14180. _SOKOL_PRIVATE WGPUAddressMode _sg_wgpu_sampler_address_mode(sg_wrap m) {
  14181. switch (m) {
  14182. case SG_WRAP_REPEAT:
  14183. return WGPUAddressMode_Repeat;
  14184. case SG_WRAP_CLAMP_TO_EDGE:
  14185. case SG_WRAP_CLAMP_TO_BORDER:
  14186. return WGPUAddressMode_ClampToEdge;
  14187. case SG_WRAP_MIRRORED_REPEAT:
  14188. return WGPUAddressMode_MirrorRepeat;
  14189. default:
  14190. SOKOL_UNREACHABLE;
  14191. return WGPUAddressMode_Force32;
  14192. }
  14193. }
  14194. _SOKOL_PRIVATE WGPUFilterMode _sg_wgpu_sampler_minmag_filter(sg_filter f) {
  14195. switch (f) {
  14196. case SG_FILTER_NEAREST:
  14197. return WGPUFilterMode_Nearest;
  14198. case SG_FILTER_LINEAR:
  14199. return WGPUFilterMode_Linear;
  14200. default:
  14201. SOKOL_UNREACHABLE;
  14202. return WGPUFilterMode_Force32;
  14203. }
  14204. }
  14205. _SOKOL_PRIVATE WGPUMipmapFilterMode _sg_wgpu_sampler_mipmap_filter(sg_filter f) {
  14206. switch (f) {
  14207. case SG_FILTER_NEAREST:
  14208. return WGPUMipmapFilterMode_Nearest;
  14209. case SG_FILTER_LINEAR:
  14210. return WGPUMipmapFilterMode_Linear;
  14211. default:
  14212. SOKOL_UNREACHABLE;
  14213. return WGPUMipmapFilterMode_Force32;
  14214. }
  14215. }
  14216. _SOKOL_PRIVATE WGPUIndexFormat _sg_wgpu_indexformat(sg_index_type t) {
  14217. // NOTE: there's no WGPUIndexFormat_None
  14218. return (t == SG_INDEXTYPE_UINT16) ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Uint32;
  14219. }
  14220. _SOKOL_PRIVATE WGPUIndexFormat _sg_wgpu_stripindexformat(sg_primitive_type prim_type, sg_index_type idx_type) {
  14221. if (idx_type == SG_INDEXTYPE_NONE) {
  14222. return WGPUIndexFormat_Undefined;
  14223. } else if ((prim_type == SG_PRIMITIVETYPE_LINE_STRIP) || (prim_type == SG_PRIMITIVETYPE_TRIANGLE_STRIP)) {
  14224. return _sg_wgpu_indexformat(idx_type);
  14225. } else {
  14226. return WGPUIndexFormat_Undefined;
  14227. }
  14228. }
  14229. _SOKOL_PRIVATE WGPUVertexStepMode _sg_wgpu_stepmode(sg_vertex_step s) {
  14230. return (s == SG_VERTEXSTEP_PER_VERTEX) ? WGPUVertexStepMode_Vertex : WGPUVertexStepMode_Instance;
  14231. }
  14232. _SOKOL_PRIVATE WGPUVertexFormat _sg_wgpu_vertexformat(sg_vertex_format f) {
  14233. switch (f) {
  14234. case SG_VERTEXFORMAT_FLOAT: return WGPUVertexFormat_Float32;
  14235. case SG_VERTEXFORMAT_FLOAT2: return WGPUVertexFormat_Float32x2;
  14236. case SG_VERTEXFORMAT_FLOAT3: return WGPUVertexFormat_Float32x3;
  14237. case SG_VERTEXFORMAT_FLOAT4: return WGPUVertexFormat_Float32x4;
  14238. case SG_VERTEXFORMAT_INT: return WGPUVertexFormat_Sint32;
  14239. case SG_VERTEXFORMAT_INT2: return WGPUVertexFormat_Sint32x2;
  14240. case SG_VERTEXFORMAT_INT3: return WGPUVertexFormat_Sint32x3;
  14241. case SG_VERTEXFORMAT_INT4: return WGPUVertexFormat_Sint32x4;
  14242. case SG_VERTEXFORMAT_UINT: return WGPUVertexFormat_Uint32;
  14243. case SG_VERTEXFORMAT_UINT2: return WGPUVertexFormat_Uint32x2;
  14244. case SG_VERTEXFORMAT_UINT3: return WGPUVertexFormat_Uint32x3;
  14245. case SG_VERTEXFORMAT_UINT4: return WGPUVertexFormat_Uint32x4;
  14246. case SG_VERTEXFORMAT_BYTE4: return WGPUVertexFormat_Sint8x4;
  14247. case SG_VERTEXFORMAT_BYTE4N: return WGPUVertexFormat_Snorm8x4;
  14248. case SG_VERTEXFORMAT_UBYTE4: return WGPUVertexFormat_Uint8x4;
  14249. case SG_VERTEXFORMAT_UBYTE4N: return WGPUVertexFormat_Unorm8x4;
  14250. case SG_VERTEXFORMAT_SHORT2: return WGPUVertexFormat_Sint16x2;
  14251. case SG_VERTEXFORMAT_SHORT2N: return WGPUVertexFormat_Snorm16x2;
  14252. case SG_VERTEXFORMAT_USHORT2: return WGPUVertexFormat_Uint16x2;
  14253. case SG_VERTEXFORMAT_USHORT2N: return WGPUVertexFormat_Unorm16x2;
  14254. case SG_VERTEXFORMAT_SHORT4: return WGPUVertexFormat_Sint16x4;
  14255. case SG_VERTEXFORMAT_SHORT4N: return WGPUVertexFormat_Snorm16x4;
  14256. case SG_VERTEXFORMAT_USHORT4: return WGPUVertexFormat_Uint16x4;
  14257. case SG_VERTEXFORMAT_USHORT4N: return WGPUVertexFormat_Unorm16x4;
  14258. case SG_VERTEXFORMAT_UINT10_N2: return WGPUVertexFormat_Unorm10_10_10_2;
  14259. case SG_VERTEXFORMAT_HALF2: return WGPUVertexFormat_Float16x2;
  14260. case SG_VERTEXFORMAT_HALF4: return WGPUVertexFormat_Float16x4;
  14261. default:
  14262. SOKOL_UNREACHABLE;
  14263. return WGPUVertexFormat_Force32;
  14264. }
  14265. }
  14266. _SOKOL_PRIVATE WGPUPrimitiveTopology _sg_wgpu_topology(sg_primitive_type t) {
  14267. switch (t) {
  14268. case SG_PRIMITIVETYPE_POINTS: return WGPUPrimitiveTopology_PointList;
  14269. case SG_PRIMITIVETYPE_LINES: return WGPUPrimitiveTopology_LineList;
  14270. case SG_PRIMITIVETYPE_LINE_STRIP: return WGPUPrimitiveTopology_LineStrip;
  14271. case SG_PRIMITIVETYPE_TRIANGLES: return WGPUPrimitiveTopology_TriangleList;
  14272. case SG_PRIMITIVETYPE_TRIANGLE_STRIP: return WGPUPrimitiveTopology_TriangleStrip;
  14273. default:
  14274. SOKOL_UNREACHABLE;
  14275. return WGPUPrimitiveTopology_Force32;
  14276. }
  14277. }
  14278. _SOKOL_PRIVATE WGPUFrontFace _sg_wgpu_frontface(sg_face_winding fw) {
  14279. return (fw == SG_FACEWINDING_CCW) ? WGPUFrontFace_CCW : WGPUFrontFace_CW;
  14280. }
  14281. _SOKOL_PRIVATE WGPUCullMode _sg_wgpu_cullmode(sg_cull_mode cm) {
  14282. switch (cm) {
  14283. case SG_CULLMODE_NONE: return WGPUCullMode_None;
  14284. case SG_CULLMODE_FRONT: return WGPUCullMode_Front;
  14285. case SG_CULLMODE_BACK: return WGPUCullMode_Back;
  14286. default:
  14287. SOKOL_UNREACHABLE;
  14288. return WGPUCullMode_Force32;
  14289. }
  14290. }
  14291. _SOKOL_PRIVATE WGPUTextureFormat _sg_wgpu_textureformat(sg_pixel_format p) {
  14292. switch (p) {
  14293. case SG_PIXELFORMAT_NONE: return WGPUTextureFormat_Undefined;
  14294. case SG_PIXELFORMAT_R8: return WGPUTextureFormat_R8Unorm;
  14295. case SG_PIXELFORMAT_R8SN: return WGPUTextureFormat_R8Snorm;
  14296. case SG_PIXELFORMAT_R8UI: return WGPUTextureFormat_R8Uint;
  14297. case SG_PIXELFORMAT_R8SI: return WGPUTextureFormat_R8Sint;
  14298. case SG_PIXELFORMAT_R16UI: return WGPUTextureFormat_R16Uint;
  14299. case SG_PIXELFORMAT_R16SI: return WGPUTextureFormat_R16Sint;
  14300. case SG_PIXELFORMAT_R16F: return WGPUTextureFormat_R16Float;
  14301. case SG_PIXELFORMAT_RG8: return WGPUTextureFormat_RG8Unorm;
  14302. case SG_PIXELFORMAT_RG8SN: return WGPUTextureFormat_RG8Snorm;
  14303. case SG_PIXELFORMAT_RG8UI: return WGPUTextureFormat_RG8Uint;
  14304. case SG_PIXELFORMAT_RG8SI: return WGPUTextureFormat_RG8Sint;
  14305. case SG_PIXELFORMAT_R32UI: return WGPUTextureFormat_R32Uint;
  14306. case SG_PIXELFORMAT_R32SI: return WGPUTextureFormat_R32Sint;
  14307. case SG_PIXELFORMAT_R32F: return WGPUTextureFormat_R32Float;
  14308. case SG_PIXELFORMAT_RG16UI: return WGPUTextureFormat_RG16Uint;
  14309. case SG_PIXELFORMAT_RG16SI: return WGPUTextureFormat_RG16Sint;
  14310. case SG_PIXELFORMAT_RG16F: return WGPUTextureFormat_RG16Float;
  14311. case SG_PIXELFORMAT_RGBA8: return WGPUTextureFormat_RGBA8Unorm;
  14312. case SG_PIXELFORMAT_SRGB8A8: return WGPUTextureFormat_RGBA8UnormSrgb;
  14313. case SG_PIXELFORMAT_RGBA8SN: return WGPUTextureFormat_RGBA8Snorm;
  14314. case SG_PIXELFORMAT_RGBA8UI: return WGPUTextureFormat_RGBA8Uint;
  14315. case SG_PIXELFORMAT_RGBA8SI: return WGPUTextureFormat_RGBA8Sint;
  14316. case SG_PIXELFORMAT_BGRA8: return WGPUTextureFormat_BGRA8Unorm;
  14317. case SG_PIXELFORMAT_RGB10A2: return WGPUTextureFormat_RGB10A2Unorm;
  14318. case SG_PIXELFORMAT_RG11B10F: return WGPUTextureFormat_RG11B10Ufloat;
  14319. case SG_PIXELFORMAT_RG32UI: return WGPUTextureFormat_RG32Uint;
  14320. case SG_PIXELFORMAT_RG32SI: return WGPUTextureFormat_RG32Sint;
  14321. case SG_PIXELFORMAT_RG32F: return WGPUTextureFormat_RG32Float;
  14322. case SG_PIXELFORMAT_RGBA16UI: return WGPUTextureFormat_RGBA16Uint;
  14323. case SG_PIXELFORMAT_RGBA16SI: return WGPUTextureFormat_RGBA16Sint;
  14324. case SG_PIXELFORMAT_RGBA16F: return WGPUTextureFormat_RGBA16Float;
  14325. case SG_PIXELFORMAT_RGBA32UI: return WGPUTextureFormat_RGBA32Uint;
  14326. case SG_PIXELFORMAT_RGBA32SI: return WGPUTextureFormat_RGBA32Sint;
  14327. case SG_PIXELFORMAT_RGBA32F: return WGPUTextureFormat_RGBA32Float;
  14328. case SG_PIXELFORMAT_DEPTH: return WGPUTextureFormat_Depth32Float;
  14329. case SG_PIXELFORMAT_DEPTH_STENCIL: return WGPUTextureFormat_Depth32FloatStencil8;
  14330. case SG_PIXELFORMAT_BC1_RGBA: return WGPUTextureFormat_BC1RGBAUnorm;
  14331. case SG_PIXELFORMAT_BC2_RGBA: return WGPUTextureFormat_BC2RGBAUnorm;
  14332. case SG_PIXELFORMAT_BC3_RGBA: return WGPUTextureFormat_BC3RGBAUnorm;
  14333. case SG_PIXELFORMAT_BC3_SRGBA: return WGPUTextureFormat_BC3RGBAUnormSrgb;
  14334. case SG_PIXELFORMAT_BC4_R: return WGPUTextureFormat_BC4RUnorm;
  14335. case SG_PIXELFORMAT_BC4_RSN: return WGPUTextureFormat_BC4RSnorm;
  14336. case SG_PIXELFORMAT_BC5_RG: return WGPUTextureFormat_BC5RGUnorm;
  14337. case SG_PIXELFORMAT_BC5_RGSN: return WGPUTextureFormat_BC5RGSnorm;
  14338. case SG_PIXELFORMAT_BC6H_RGBF: return WGPUTextureFormat_BC6HRGBFloat;
  14339. case SG_PIXELFORMAT_BC6H_RGBUF: return WGPUTextureFormat_BC6HRGBUfloat;
  14340. case SG_PIXELFORMAT_BC7_RGBA: return WGPUTextureFormat_BC7RGBAUnorm;
  14341. case SG_PIXELFORMAT_BC7_SRGBA: return WGPUTextureFormat_BC7RGBAUnormSrgb;
  14342. case SG_PIXELFORMAT_ETC2_RGB8: return WGPUTextureFormat_ETC2RGB8Unorm;
  14343. case SG_PIXELFORMAT_ETC2_RGB8A1: return WGPUTextureFormat_ETC2RGB8A1Unorm;
  14344. case SG_PIXELFORMAT_ETC2_RGBA8: return WGPUTextureFormat_ETC2RGBA8Unorm;
  14345. case SG_PIXELFORMAT_ETC2_SRGB8: return WGPUTextureFormat_ETC2RGB8UnormSrgb;
  14346. case SG_PIXELFORMAT_ETC2_SRGB8A8: return WGPUTextureFormat_ETC2RGBA8UnormSrgb;
  14347. case SG_PIXELFORMAT_EAC_R11: return WGPUTextureFormat_EACR11Unorm;
  14348. case SG_PIXELFORMAT_EAC_R11SN: return WGPUTextureFormat_EACR11Snorm;
  14349. case SG_PIXELFORMAT_EAC_RG11: return WGPUTextureFormat_EACRG11Unorm;
  14350. case SG_PIXELFORMAT_EAC_RG11SN: return WGPUTextureFormat_EACRG11Snorm;
  14351. case SG_PIXELFORMAT_RGB9E5: return WGPUTextureFormat_RGB9E5Ufloat;
  14352. case SG_PIXELFORMAT_ASTC_4x4_RGBA: return WGPUTextureFormat_ASTC4x4Unorm;
  14353. case SG_PIXELFORMAT_ASTC_4x4_SRGBA: return WGPUTextureFormat_ASTC4x4UnormSrgb;
  14354. // NOT SUPPORTED
  14355. case SG_PIXELFORMAT_R16:
  14356. case SG_PIXELFORMAT_R16SN:
  14357. case SG_PIXELFORMAT_RG16:
  14358. case SG_PIXELFORMAT_RG16SN:
  14359. case SG_PIXELFORMAT_RGBA16:
  14360. case SG_PIXELFORMAT_RGBA16SN:
  14361. return WGPUTextureFormat_Undefined;
  14362. default:
  14363. SOKOL_UNREACHABLE;
  14364. return WGPUTextureFormat_Force32;
  14365. }
  14366. }
  14367. _SOKOL_PRIVATE WGPUCompareFunction _sg_wgpu_comparefunc(sg_compare_func f) {
  14368. switch (f) {
  14369. case SG_COMPAREFUNC_NEVER: return WGPUCompareFunction_Never;
  14370. case SG_COMPAREFUNC_LESS: return WGPUCompareFunction_Less;
  14371. case SG_COMPAREFUNC_EQUAL: return WGPUCompareFunction_Equal;
  14372. case SG_COMPAREFUNC_LESS_EQUAL: return WGPUCompareFunction_LessEqual;
  14373. case SG_COMPAREFUNC_GREATER: return WGPUCompareFunction_Greater;
  14374. case SG_COMPAREFUNC_NOT_EQUAL: return WGPUCompareFunction_NotEqual;
  14375. case SG_COMPAREFUNC_GREATER_EQUAL: return WGPUCompareFunction_GreaterEqual;
  14376. case SG_COMPAREFUNC_ALWAYS: return WGPUCompareFunction_Always;
  14377. default:
  14378. SOKOL_UNREACHABLE;
  14379. return WGPUCompareFunction_Force32;
  14380. }
  14381. }
  14382. _SOKOL_PRIVATE WGPUStencilOperation _sg_wgpu_stencilop(sg_stencil_op op) {
  14383. switch (op) {
  14384. case SG_STENCILOP_KEEP: return WGPUStencilOperation_Keep;
  14385. case SG_STENCILOP_ZERO: return WGPUStencilOperation_Zero;
  14386. case SG_STENCILOP_REPLACE: return WGPUStencilOperation_Replace;
  14387. case SG_STENCILOP_INCR_CLAMP: return WGPUStencilOperation_IncrementClamp;
  14388. case SG_STENCILOP_DECR_CLAMP: return WGPUStencilOperation_DecrementClamp;
  14389. case SG_STENCILOP_INVERT: return WGPUStencilOperation_Invert;
  14390. case SG_STENCILOP_INCR_WRAP: return WGPUStencilOperation_IncrementWrap;
  14391. case SG_STENCILOP_DECR_WRAP: return WGPUStencilOperation_DecrementWrap;
  14392. default:
  14393. SOKOL_UNREACHABLE;
  14394. return WGPUStencilOperation_Force32;
  14395. }
  14396. }
  14397. _SOKOL_PRIVATE WGPUBlendOperation _sg_wgpu_blendop(sg_blend_op op) {
  14398. switch (op) {
  14399. case SG_BLENDOP_ADD: return WGPUBlendOperation_Add;
  14400. case SG_BLENDOP_SUBTRACT: return WGPUBlendOperation_Subtract;
  14401. case SG_BLENDOP_REVERSE_SUBTRACT: return WGPUBlendOperation_ReverseSubtract;
  14402. case SG_BLENDOP_MIN: return WGPUBlendOperation_Min;
  14403. case SG_BLENDOP_MAX: return WGPUBlendOperation_Max;
  14404. default:
  14405. SOKOL_UNREACHABLE;
  14406. return WGPUBlendOperation_Force32;
  14407. }
  14408. }
  14409. _SOKOL_PRIVATE WGPUBlendFactor _sg_wgpu_blendfactor(sg_blend_factor f) {
  14410. switch (f) {
  14411. case SG_BLENDFACTOR_ZERO: return WGPUBlendFactor_Zero;
  14412. case SG_BLENDFACTOR_ONE: return WGPUBlendFactor_One;
  14413. case SG_BLENDFACTOR_SRC_COLOR: return WGPUBlendFactor_Src;
  14414. case SG_BLENDFACTOR_ONE_MINUS_SRC_COLOR: return WGPUBlendFactor_OneMinusSrc;
  14415. case SG_BLENDFACTOR_SRC_ALPHA: return WGPUBlendFactor_SrcAlpha;
  14416. case SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA: return WGPUBlendFactor_OneMinusSrcAlpha;
  14417. case SG_BLENDFACTOR_DST_COLOR: return WGPUBlendFactor_Dst;
  14418. case SG_BLENDFACTOR_ONE_MINUS_DST_COLOR: return WGPUBlendFactor_OneMinusDst;
  14419. case SG_BLENDFACTOR_DST_ALPHA: return WGPUBlendFactor_DstAlpha;
  14420. case SG_BLENDFACTOR_ONE_MINUS_DST_ALPHA: return WGPUBlendFactor_OneMinusDstAlpha;
  14421. case SG_BLENDFACTOR_SRC_ALPHA_SATURATED: return WGPUBlendFactor_SrcAlphaSaturated;
  14422. case SG_BLENDFACTOR_BLEND_COLOR: return WGPUBlendFactor_Constant;
  14423. case SG_BLENDFACTOR_ONE_MINUS_BLEND_COLOR: return WGPUBlendFactor_OneMinusConstant;
  14424. // FIXME: separate blend alpha value not supported?
  14425. case SG_BLENDFACTOR_BLEND_ALPHA: return WGPUBlendFactor_Constant;
  14426. case SG_BLENDFACTOR_ONE_MINUS_BLEND_ALPHA: return WGPUBlendFactor_OneMinusConstant;
  14427. default:
  14428. SOKOL_UNREACHABLE;
  14429. return WGPUBlendFactor_Force32;
  14430. }
  14431. }
  14432. _SOKOL_PRIVATE WGPUColorWriteMask _sg_wgpu_colorwritemask(uint8_t m) {
  14433. // FIXME: change to WGPUColorWriteMask once Emscripten and Dawn webgpu.h agree
  14434. int res = 0;
  14435. if (0 != (m & SG_COLORMASK_R)) {
  14436. res |= WGPUColorWriteMask_Red;
  14437. }
  14438. if (0 != (m & SG_COLORMASK_G)) {
  14439. res |= WGPUColorWriteMask_Green;
  14440. }
  14441. if (0 != (m & SG_COLORMASK_B)) {
  14442. res |= WGPUColorWriteMask_Blue;
  14443. }
  14444. if (0 != (m & SG_COLORMASK_A)) {
  14445. res |= WGPUColorWriteMask_Alpha;
  14446. }
  14447. return (WGPUColorWriteMask)res;
  14448. }
  14449. _SOKOL_PRIVATE WGPUShaderStage _sg_wgpu_shader_stage(sg_shader_stage stage) {
  14450. switch (stage) {
  14451. case SG_SHADERSTAGE_VERTEX: return WGPUShaderStage_Vertex;
  14452. case SG_SHADERSTAGE_FRAGMENT: return WGPUShaderStage_Fragment;
  14453. case SG_SHADERSTAGE_COMPUTE: return WGPUShaderStage_Compute;
  14454. default: SOKOL_UNREACHABLE; return WGPUShaderStage_None;
  14455. }
  14456. }
  14457. _SOKOL_PRIVATE void _sg_wgpu_init_caps(void) {
  14458. _sg.backend = SG_BACKEND_WGPU;
  14459. _sg.features.origin_top_left = true;
  14460. _sg.features.image_clamp_to_border = false;
  14461. _sg.features.mrt_independent_blend_state = true;
  14462. _sg.features.mrt_independent_write_mask = true;
  14463. _sg.features.compute = true;
  14464. _sg.features.msaa_image_bindings = true;
  14465. wgpuDeviceGetLimits(_sg.wgpu.dev, &_sg.wgpu.limits);
  14466. const WGPULimits* l = &_sg.wgpu.limits.limits;
  14467. _sg.limits.max_image_size_2d = (int) l->maxTextureDimension2D;
  14468. _sg.limits.max_image_size_cube = (int) l->maxTextureDimension2D; // not a bug, see: https://github.com/gpuweb/gpuweb/issues/1327
  14469. _sg.limits.max_image_size_3d = (int) l->maxTextureDimension3D;
  14470. _sg.limits.max_image_size_array = (int) l->maxTextureDimension2D;
  14471. _sg.limits.max_image_array_layers = (int) l->maxTextureArrayLayers;
  14472. _sg.limits.max_vertex_attrs = SG_MAX_VERTEX_ATTRIBUTES;
  14473. // NOTE: no WGPUTextureFormat_R16Unorm
  14474. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R8]);
  14475. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG8]);
  14476. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA8]);
  14477. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_SRGB8A8]);
  14478. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_BGRA8]);
  14479. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16F]);
  14480. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16F]);
  14481. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  14482. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGB10A2]);
  14483. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_R8SN]);
  14484. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG8SN]);
  14485. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGBA8SN]);
  14486. // FIXME: can be made renderable via extension
  14487. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  14488. // NOTE: msaa rendering is possible in WebGPU, but no resolve
  14489. // which is a combination that's not currently supported in sokol-gfx
  14490. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R8UI]);
  14491. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R8SI]);
  14492. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG8UI]);
  14493. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG8SI]);
  14494. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA8UI]);
  14495. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA8SI]);
  14496. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R16UI]);
  14497. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R16SI]);
  14498. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG16UI]);
  14499. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG16SI]);
  14500. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA16UI]);
  14501. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA16SI]);
  14502. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32UI]);
  14503. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32SI]);
  14504. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  14505. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  14506. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  14507. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  14508. if (wgpuDeviceHasFeature(_sg.wgpu.dev, WGPUFeatureName_Float32Filterable)) {
  14509. _sg_pixelformat_sfr(&_sg.formats[SG_PIXELFORMAT_R32F]);
  14510. _sg_pixelformat_sfr(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  14511. _sg_pixelformat_sfr(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  14512. } else {
  14513. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32F]);
  14514. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  14515. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  14516. }
  14517. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH]);
  14518. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH_STENCIL]);
  14519. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGB9E5]);
  14520. if (wgpuDeviceHasFeature(_sg.wgpu.dev, WGPUFeatureName_TextureCompressionBC)) {
  14521. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC1_RGBA]);
  14522. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC2_RGBA]);
  14523. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_RGBA]);
  14524. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_SRGBA]);
  14525. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_R]);
  14526. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_RSN]);
  14527. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RG]);
  14528. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RGSN]);
  14529. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBF]);
  14530. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBUF]);
  14531. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_RGBA]);
  14532. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_SRGBA]);
  14533. }
  14534. if (wgpuDeviceHasFeature(_sg.wgpu.dev, WGPUFeatureName_TextureCompressionETC2)) {
  14535. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8]);
  14536. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8]);
  14537. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8A1]);
  14538. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGBA8]);
  14539. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8A8]);
  14540. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11]);
  14541. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11SN]);
  14542. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11]);
  14543. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11SN]);
  14544. }
  14545. if (wgpuDeviceHasFeature(_sg.wgpu.dev, WGPUFeatureName_TextureCompressionASTC)) {
  14546. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_RGBA]);
  14547. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_SRGBA]);
  14548. }
  14549. // see: https://github.com/gpuweb/gpuweb/issues/513
  14550. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8]);
  14551. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8SN]);
  14552. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8UI]);
  14553. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8SI]);
  14554. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16UI]);
  14555. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16SI]);
  14556. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  14557. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32UI]);
  14558. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32SI]);
  14559. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32F]);
  14560. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  14561. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  14562. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  14563. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  14564. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  14565. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  14566. }
  14567. _SOKOL_PRIVATE void _sg_wgpu_uniform_buffer_init(const sg_desc* desc) {
  14568. SOKOL_ASSERT(0 == _sg.wgpu.uniform.staging);
  14569. SOKOL_ASSERT(0 == _sg.wgpu.uniform.buf);
  14570. // Add the max-uniform-update size (64 KB) to the requested buffer size,
  14571. // this is to prevent validation errors in the WebGPU implementation
  14572. // if the entire buffer size is used per frame. 64 KB is the allowed
  14573. // max uniform update size on NVIDIA
  14574. //
  14575. // FIXME: is this still needed?
  14576. _sg.wgpu.uniform.num_bytes = (uint32_t)(desc->uniform_buffer_size + _SG_WGPU_MAX_UNIFORM_UPDATE_SIZE);
  14577. _sg.wgpu.uniform.staging = (uint8_t*)_sg_malloc(_sg.wgpu.uniform.num_bytes);
  14578. WGPUBufferDescriptor ub_desc;
  14579. _sg_clear(&ub_desc, sizeof(ub_desc));
  14580. ub_desc.size = _sg.wgpu.uniform.num_bytes;
  14581. ub_desc.usage = WGPUBufferUsage_Uniform|WGPUBufferUsage_CopyDst;
  14582. _sg.wgpu.uniform.buf = wgpuDeviceCreateBuffer(_sg.wgpu.dev, &ub_desc);
  14583. SOKOL_ASSERT(_sg.wgpu.uniform.buf);
  14584. }
  14585. _SOKOL_PRIVATE void _sg_wgpu_uniform_buffer_discard(void) {
  14586. if (_sg.wgpu.uniform.buf) {
  14587. wgpuBufferRelease(_sg.wgpu.uniform.buf);
  14588. _sg.wgpu.uniform.buf = 0;
  14589. }
  14590. if (_sg.wgpu.uniform.staging) {
  14591. _sg_free(_sg.wgpu.uniform.staging);
  14592. _sg.wgpu.uniform.staging = 0;
  14593. }
  14594. }
  14595. _SOKOL_PRIVATE void _sg_wgpu_uniform_buffer_on_commit(void) {
  14596. wgpuQueueWriteBuffer(_sg.wgpu.queue, _sg.wgpu.uniform.buf, 0, _sg.wgpu.uniform.staging, _sg.wgpu.uniform.offset);
  14597. _sg_stats_add(wgpu.uniforms.size_write_buffer, _sg.wgpu.uniform.offset);
  14598. _sg.wgpu.uniform.offset = 0;
  14599. _sg_clear(_sg.wgpu.uniform.bind_offsets, sizeof(_sg.wgpu.uniform.bind_offsets));
  14600. }
  14601. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_pool_init(const sg_desc* desc) {
  14602. SOKOL_ASSERT((desc->wgpu_bindgroups_cache_size > 0) && (desc->wgpu_bindgroups_cache_size < _SG_MAX_POOL_SIZE));
  14603. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  14604. SOKOL_ASSERT(0 == p->bindgroups);
  14605. const int pool_size = desc->wgpu_bindgroups_cache_size;
  14606. _sg_pool_init(&p->pool, pool_size);
  14607. size_t pool_byte_size = sizeof(_sg_wgpu_bindgroup_t) * (size_t)p->pool.size;
  14608. p->bindgroups = (_sg_wgpu_bindgroup_t*) _sg_malloc_clear(pool_byte_size);
  14609. }
  14610. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_pool_discard(void) {
  14611. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  14612. SOKOL_ASSERT(p->bindgroups);
  14613. _sg_free(p->bindgroups); p->bindgroups = 0;
  14614. _sg_pool_discard(&p->pool);
  14615. }
  14616. _SOKOL_PRIVATE _sg_wgpu_bindgroup_t* _sg_wgpu_bindgroup_at(uint32_t bg_id) {
  14617. SOKOL_ASSERT(SG_INVALID_ID != bg_id);
  14618. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  14619. int slot_index = _sg_slot_index(bg_id);
  14620. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < p->pool.size));
  14621. return &p->bindgroups[slot_index];
  14622. }
  14623. _SOKOL_PRIVATE _sg_wgpu_bindgroup_t* _sg_wgpu_lookup_bindgroup(uint32_t bg_id) {
  14624. if (SG_INVALID_ID != bg_id) {
  14625. _sg_wgpu_bindgroup_t* bg = _sg_wgpu_bindgroup_at(bg_id);
  14626. if (bg->slot.id == bg_id) {
  14627. return bg;
  14628. }
  14629. }
  14630. return 0;
  14631. }
  14632. _SOKOL_PRIVATE _sg_wgpu_bindgroup_handle_t _sg_wgpu_alloc_bindgroup(void) {
  14633. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  14634. _sg_wgpu_bindgroup_handle_t res;
  14635. int slot_index = _sg_pool_alloc_index(&p->pool);
  14636. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  14637. res.id = _sg_slot_alloc(&p->pool, &p->bindgroups[slot_index].slot, slot_index);
  14638. } else {
  14639. res.id = SG_INVALID_ID;
  14640. _SG_ERROR(WGPU_BINDGROUPS_POOL_EXHAUSTED);
  14641. }
  14642. return res;
  14643. }
  14644. _SOKOL_PRIVATE void _sg_wgpu_dealloc_bindgroup(_sg_wgpu_bindgroup_t* bg) {
  14645. SOKOL_ASSERT(bg && (bg->slot.state == SG_RESOURCESTATE_ALLOC) && (bg->slot.id != SG_INVALID_ID));
  14646. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  14647. _sg_pool_free_index(&p->pool, _sg_slot_index(bg->slot.id));
  14648. _sg_slot_reset(&bg->slot);
  14649. }
  14650. _SOKOL_PRIVATE void _sg_wgpu_reset_bindgroup_to_alloc_state(_sg_wgpu_bindgroup_t* bg) {
  14651. SOKOL_ASSERT(bg);
  14652. _sg_slot_t slot = bg->slot;
  14653. _sg_clear(bg, sizeof(_sg_wgpu_bindgroup_t));
  14654. bg->slot = slot;
  14655. bg->slot.state = SG_RESOURCESTATE_ALLOC;
  14656. }
  14657. // MurmurHash64B (see: https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L142)
  14658. _SOKOL_PRIVATE uint64_t _sg_wgpu_hash(const void* key, int len, uint64_t seed) {
  14659. const uint32_t m = 0x5bd1e995;
  14660. const int r = 24;
  14661. uint32_t h1 = (uint32_t)seed ^ (uint32_t)len;
  14662. uint32_t h2 = (uint32_t)(seed >> 32);
  14663. const uint32_t * data = (const uint32_t *)key;
  14664. while (len >= 8) {
  14665. uint32_t k1 = *data++;
  14666. k1 *= m; k1 ^= k1 >> r; k1 *= m;
  14667. h1 *= m; h1 ^= k1;
  14668. len -= 4;
  14669. uint32_t k2 = *data++;
  14670. k2 *= m; k2 ^= k2 >> r; k2 *= m;
  14671. h2 *= m; h2 ^= k2;
  14672. len -= 4;
  14673. }
  14674. if (len >= 4) {
  14675. uint32_t k1 = *data++;
  14676. k1 *= m; k1 ^= k1 >> r; k1 *= m;
  14677. h1 *= m; h1 ^= k1;
  14678. len -= 4;
  14679. }
  14680. switch(len) {
  14681. case 3: h2 ^= (uint32_t)(((unsigned char*)data)[2] << 16);
  14682. case 2: h2 ^= (uint32_t)(((unsigned char*)data)[1] << 8);
  14683. case 1: h2 ^= ((unsigned char*)data)[0];
  14684. h2 *= m;
  14685. };
  14686. h1 ^= h2 >> 18; h1 *= m;
  14687. h2 ^= h1 >> 22; h2 *= m;
  14688. h1 ^= h2 >> 17; h1 *= m;
  14689. h2 ^= h1 >> 19; h2 *= m;
  14690. uint64_t h = h1;
  14691. h = (h << 32) | h2;
  14692. return h;
  14693. }
  14694. _SOKOL_PRIVATE uint64_t _sg_wgpu_bindgroups_cache_item(_sg_wgpu_bindgroups_cache_item_type_t type, uint8_t wgpu_binding, uint32_t id) {
  14695. // key pattern is bbbbttttiiiiiiii
  14696. const uint64_t bb = (uint64_t)wgpu_binding;
  14697. const uint64_t tttt = (uint64_t)type;
  14698. const uint64_t iiiiiiii = (uint64_t)id;
  14699. return (bb << 56) | (bb << 48) | (tttt << 32) | iiiiiiii;
  14700. }
  14701. _SOKOL_PRIVATE uint64_t _sg_wgpu_bindgroups_cache_pip_item(uint32_t id) {
  14702. return _sg_wgpu_bindgroups_cache_item(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_PIPELINE, 0xFF, id);
  14703. }
  14704. _SOKOL_PRIVATE uint64_t _sg_wgpu_bindgroups_cache_image_item(uint8_t wgpu_binding, uint32_t id) {
  14705. return _sg_wgpu_bindgroups_cache_item(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_IMAGE, wgpu_binding, id);
  14706. }
  14707. _SOKOL_PRIVATE uint64_t _sg_wgpu_bindgroups_cache_sampler_item(uint8_t wgpu_binding, uint32_t id) {
  14708. return _sg_wgpu_bindgroups_cache_item(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_SAMPLER, wgpu_binding, id);
  14709. }
  14710. _SOKOL_PRIVATE uint64_t _sg_wgpu_bindgroups_cache_sbuf_item(uint8_t wgpu_binding, uint32_t id) {
  14711. return _sg_wgpu_bindgroups_cache_item(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_STORAGEBUFFER, wgpu_binding, id);
  14712. }
  14713. _SOKOL_PRIVATE void _sg_wgpu_init_bindgroups_cache_key(_sg_wgpu_bindgroups_cache_key_t* key, const _sg_bindings_ptrs_t* bnd) {
  14714. SOKOL_ASSERT(bnd);
  14715. SOKOL_ASSERT(bnd->pip);
  14716. const _sg_shader_t* shd = bnd->pip->shader;
  14717. SOKOL_ASSERT(shd && shd->slot.id == bnd->pip->cmn.shader_id.id);
  14718. _sg_clear(key->items, sizeof(key->items));
  14719. key->items[0] = _sg_wgpu_bindgroups_cache_pip_item(bnd->pip->slot.id);
  14720. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  14721. if (shd->cmn.images[i].stage == SG_SHADERSTAGE_NONE) {
  14722. continue;
  14723. }
  14724. SOKOL_ASSERT(bnd->imgs[i]);
  14725. const size_t item_idx = i + 1;
  14726. SOKOL_ASSERT(item_idx < _SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS);
  14727. SOKOL_ASSERT(0 == key->items[item_idx]);
  14728. const uint8_t wgpu_binding = shd->wgpu.img_grp1_bnd_n[i];
  14729. const uint32_t id = bnd->imgs[i]->slot.id;
  14730. key->items[item_idx] = _sg_wgpu_bindgroups_cache_image_item(wgpu_binding, id);
  14731. }
  14732. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  14733. if (shd->cmn.samplers[i].stage == SG_SHADERSTAGE_NONE) {
  14734. continue;
  14735. }
  14736. SOKOL_ASSERT(bnd->smps[i]);
  14737. const size_t item_idx = i + 1 + SG_MAX_IMAGE_BINDSLOTS;
  14738. SOKOL_ASSERT(item_idx < _SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS);
  14739. SOKOL_ASSERT(0 == key->items[item_idx]);
  14740. const uint8_t wgpu_binding = shd->wgpu.smp_grp1_bnd_n[i];
  14741. const uint32_t id = bnd->smps[i]->slot.id;
  14742. key->items[item_idx] = _sg_wgpu_bindgroups_cache_sampler_item(wgpu_binding, id);
  14743. }
  14744. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  14745. if (shd->cmn.storage_buffers[i].stage == SG_SHADERSTAGE_NONE) {
  14746. continue;
  14747. }
  14748. SOKOL_ASSERT(bnd->sbufs[i]);
  14749. const size_t item_idx = i + 1 + SG_MAX_IMAGE_BINDSLOTS + SG_MAX_SAMPLER_BINDSLOTS;
  14750. SOKOL_ASSERT(item_idx < _SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS);
  14751. SOKOL_ASSERT(0 == key->items[item_idx]);
  14752. const uint8_t wgpu_binding = shd->wgpu.sbuf_grp1_bnd_n[i];
  14753. const uint32_t id = bnd->sbufs[i]->slot.id;
  14754. key->items[item_idx] = _sg_wgpu_bindgroups_cache_sbuf_item(wgpu_binding, id);
  14755. }
  14756. key->hash = _sg_wgpu_hash(&key->items, (int)sizeof(key->items), 0x1234567887654321);
  14757. }
  14758. _SOKOL_PRIVATE bool _sg_wgpu_compare_bindgroups_cache_key(_sg_wgpu_bindgroups_cache_key_t* k0, _sg_wgpu_bindgroups_cache_key_t* k1) {
  14759. SOKOL_ASSERT(k0 && k1);
  14760. if (k0->hash != k1->hash) {
  14761. return false;
  14762. }
  14763. if (memcmp(&k0->items, &k1->items, sizeof(k0->items)) != 0) {
  14764. _sg_stats_add(wgpu.bindings.num_bindgroup_cache_hash_vs_key_mismatch, 1);
  14765. return false;
  14766. }
  14767. return true;
  14768. }
  14769. _SOKOL_PRIVATE _sg_wgpu_bindgroup_t* _sg_wgpu_create_bindgroup(_sg_bindings_ptrs_t* bnd) {
  14770. SOKOL_ASSERT(_sg.wgpu.dev);
  14771. SOKOL_ASSERT(bnd->pip);
  14772. const _sg_shader_t* shd = bnd->pip->shader;
  14773. SOKOL_ASSERT(shd && (shd->slot.id == bnd->pip->cmn.shader_id.id));
  14774. _sg_stats_add(wgpu.bindings.num_create_bindgroup, 1);
  14775. _sg_wgpu_bindgroup_handle_t bg_id = _sg_wgpu_alloc_bindgroup();
  14776. if (bg_id.id == SG_INVALID_ID) {
  14777. return 0;
  14778. }
  14779. _sg_wgpu_bindgroup_t* bg = _sg_wgpu_bindgroup_at(bg_id.id);
  14780. SOKOL_ASSERT(bg && (bg->slot.state == SG_RESOURCESTATE_ALLOC));
  14781. // create wgpu bindgroup object (also see _sg_wgpu_create_shader())
  14782. WGPUBindGroupLayout bgl = bnd->pip->shader->wgpu.bgl_img_smp_sbuf;
  14783. SOKOL_ASSERT(bgl);
  14784. WGPUBindGroupEntry bg_entries[_SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES];
  14785. _sg_clear(&bg_entries, sizeof(bg_entries));
  14786. size_t bgl_index = 0;
  14787. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  14788. if (shd->cmn.images[i].stage == SG_SHADERSTAGE_NONE) {
  14789. continue;
  14790. }
  14791. SOKOL_ASSERT(bnd->imgs[i]);
  14792. SOKOL_ASSERT(bgl_index < _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES);
  14793. WGPUBindGroupEntry* bg_entry = &bg_entries[bgl_index];
  14794. bg_entry->binding = shd->wgpu.img_grp1_bnd_n[i];
  14795. bg_entry->textureView = bnd->imgs[i]->wgpu.view;
  14796. bgl_index += 1;
  14797. }
  14798. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  14799. if (shd->cmn.samplers[i].stage == SG_SHADERSTAGE_NONE) {
  14800. continue;
  14801. }
  14802. SOKOL_ASSERT(bnd->smps[i]);
  14803. SOKOL_ASSERT(bgl_index < _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES);
  14804. WGPUBindGroupEntry* bg_entry = &bg_entries[bgl_index];
  14805. bg_entry->binding = shd->wgpu.smp_grp1_bnd_n[i];
  14806. bg_entry->sampler = bnd->smps[i]->wgpu.smp;
  14807. bgl_index += 1;
  14808. }
  14809. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  14810. if (shd->cmn.storage_buffers[i].stage == SG_SHADERSTAGE_NONE) {
  14811. continue;
  14812. }
  14813. SOKOL_ASSERT(bnd->sbufs[i]);
  14814. SOKOL_ASSERT(bgl_index < _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES);
  14815. WGPUBindGroupEntry* bg_entry = &bg_entries[bgl_index];
  14816. bg_entry->binding = shd->wgpu.sbuf_grp1_bnd_n[i];
  14817. bg_entry->buffer = bnd->sbufs[i]->wgpu.buf;
  14818. bg_entry->size = (uint64_t) bnd->sbufs[i]->cmn.size;
  14819. bgl_index += 1;
  14820. }
  14821. WGPUBindGroupDescriptor bg_desc;
  14822. _sg_clear(&bg_desc, sizeof(bg_desc));
  14823. bg_desc.layout = bgl;
  14824. bg_desc.entryCount = bgl_index;
  14825. bg_desc.entries = bg_entries;
  14826. bg->bindgroup = wgpuDeviceCreateBindGroup(_sg.wgpu.dev, &bg_desc);
  14827. if (bg->bindgroup == 0) {
  14828. _SG_ERROR(WGPU_CREATEBINDGROUP_FAILED);
  14829. bg->slot.state = SG_RESOURCESTATE_FAILED;
  14830. return bg;
  14831. }
  14832. _sg_wgpu_init_bindgroups_cache_key(&bg->key, bnd);
  14833. bg->slot.state = SG_RESOURCESTATE_VALID;
  14834. return bg;
  14835. }
  14836. _SOKOL_PRIVATE void _sg_wgpu_discard_bindgroup(_sg_wgpu_bindgroup_t* bg) {
  14837. SOKOL_ASSERT(bg);
  14838. _sg_stats_add(wgpu.bindings.num_discard_bindgroup, 1);
  14839. if (bg->slot.state == SG_RESOURCESTATE_VALID) {
  14840. if (bg->bindgroup) {
  14841. wgpuBindGroupRelease(bg->bindgroup);
  14842. bg->bindgroup = 0;
  14843. }
  14844. _sg_wgpu_reset_bindgroup_to_alloc_state(bg);
  14845. SOKOL_ASSERT(bg->slot.state == SG_RESOURCESTATE_ALLOC);
  14846. }
  14847. if (bg->slot.state == SG_RESOURCESTATE_ALLOC) {
  14848. _sg_wgpu_dealloc_bindgroup(bg);
  14849. SOKOL_ASSERT(bg->slot.state == SG_RESOURCESTATE_INITIAL);
  14850. }
  14851. }
  14852. _SOKOL_PRIVATE void _sg_wgpu_discard_all_bindgroups(void) {
  14853. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  14854. for (int i = 0; i < p->pool.size; i++) {
  14855. sg_resource_state state = p->bindgroups[i].slot.state;
  14856. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  14857. _sg_wgpu_discard_bindgroup(&p->bindgroups[i]);
  14858. }
  14859. }
  14860. }
  14861. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_cache_init(const sg_desc* desc) {
  14862. SOKOL_ASSERT(desc);
  14863. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.num == 0);
  14864. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.index_mask == 0);
  14865. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.items == 0);
  14866. const int num = desc->wgpu_bindgroups_cache_size;
  14867. if (num <= 1) {
  14868. _SG_PANIC(WGPU_BINDGROUPSCACHE_SIZE_GREATER_ONE);
  14869. }
  14870. if (!_sg_ispow2(num)) {
  14871. _SG_PANIC(WGPU_BINDGROUPSCACHE_SIZE_POW2);
  14872. }
  14873. _sg.wgpu.bindgroups_cache.num = (uint32_t)desc->wgpu_bindgroups_cache_size;
  14874. _sg.wgpu.bindgroups_cache.index_mask = _sg.wgpu.bindgroups_cache.num - 1;
  14875. size_t size_in_bytes = sizeof(_sg_wgpu_bindgroup_handle_t) * (size_t)num;
  14876. _sg.wgpu.bindgroups_cache.items = (_sg_wgpu_bindgroup_handle_t*)_sg_malloc_clear(size_in_bytes);
  14877. }
  14878. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_cache_discard(void) {
  14879. if (_sg.wgpu.bindgroups_cache.items) {
  14880. _sg_free(_sg.wgpu.bindgroups_cache.items);
  14881. _sg.wgpu.bindgroups_cache.items = 0;
  14882. }
  14883. _sg.wgpu.bindgroups_cache.num = 0;
  14884. _sg.wgpu.bindgroups_cache.index_mask = 0;
  14885. }
  14886. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_cache_set(uint64_t hash, uint32_t bg_id) {
  14887. uint32_t index = hash & _sg.wgpu.bindgroups_cache.index_mask;
  14888. SOKOL_ASSERT(index < _sg.wgpu.bindgroups_cache.num);
  14889. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.items);
  14890. _sg.wgpu.bindgroups_cache.items[index].id = bg_id;
  14891. }
  14892. _SOKOL_PRIVATE uint32_t _sg_wgpu_bindgroups_cache_get(uint64_t hash) {
  14893. uint32_t index = hash & _sg.wgpu.bindgroups_cache.index_mask;
  14894. SOKOL_ASSERT(index < _sg.wgpu.bindgroups_cache.num);
  14895. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.items);
  14896. return _sg.wgpu.bindgroups_cache.items[index].id;
  14897. }
  14898. // called from wgpu resource destroy functions to also invalidate any
  14899. // bindgroups cache slot and bindgroup referencing that resource
  14900. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_cache_invalidate(_sg_wgpu_bindgroups_cache_item_type_t type, uint32_t id) {
  14901. const uint64_t key_mask = 0x0000FFFFFFFFFFFF;
  14902. const uint64_t key_item = _sg_wgpu_bindgroups_cache_item(type, 0, id) & key_mask;
  14903. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.items);
  14904. for (uint32_t cache_item_idx = 0; cache_item_idx < _sg.wgpu.bindgroups_cache.num; cache_item_idx++) {
  14905. const uint32_t bg_id = _sg.wgpu.bindgroups_cache.items[cache_item_idx].id;
  14906. if (bg_id != SG_INVALID_ID) {
  14907. _sg_wgpu_bindgroup_t* bg = _sg_wgpu_lookup_bindgroup(bg_id);
  14908. SOKOL_ASSERT(bg && (bg->slot.state == SG_RESOURCESTATE_VALID));
  14909. // check if resource is in bindgroup, if yes discard bindgroup and invalidate cache slot
  14910. bool invalidate_cache_item = false;
  14911. for (int key_item_idx = 0; key_item_idx < _SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS; key_item_idx++) {
  14912. if ((bg->key.items[key_item_idx] & key_mask) == key_item) {
  14913. invalidate_cache_item = true;
  14914. break;
  14915. }
  14916. }
  14917. if (invalidate_cache_item) {
  14918. _sg_wgpu_discard_bindgroup(bg); bg = 0;
  14919. _sg_wgpu_bindgroups_cache_set(cache_item_idx, SG_INVALID_ID);
  14920. _sg_stats_add(wgpu.bindings.num_bindgroup_cache_invalidates, 1);
  14921. }
  14922. }
  14923. }
  14924. }
  14925. _SOKOL_PRIVATE void _sg_wgpu_bindings_cache_clear(void) {
  14926. memset(&_sg.wgpu.bindings_cache, 0, sizeof(_sg.wgpu.bindings_cache));
  14927. }
  14928. _SOKOL_PRIVATE bool _sg_wgpu_bindings_cache_vb_dirty(size_t index, const _sg_buffer_t* vb, uint64_t offset) {
  14929. SOKOL_ASSERT((index >= 0) && (index < SG_MAX_VERTEXBUFFER_BINDSLOTS));
  14930. if (vb) {
  14931. return (_sg.wgpu.bindings_cache.vbs[index].buffer.id != vb->slot.id)
  14932. || (_sg.wgpu.bindings_cache.vbs[index].offset != offset);
  14933. } else {
  14934. return _sg.wgpu.bindings_cache.vbs[index].buffer.id != SG_INVALID_ID;
  14935. }
  14936. }
  14937. _SOKOL_PRIVATE void _sg_wgpu_bindings_cache_vb_update(size_t index, const _sg_buffer_t* vb, uint64_t offset) {
  14938. SOKOL_ASSERT((index >= 0) && (index < SG_MAX_VERTEXBUFFER_BINDSLOTS));
  14939. if (vb) {
  14940. _sg.wgpu.bindings_cache.vbs[index].buffer.id = vb->slot.id;
  14941. _sg.wgpu.bindings_cache.vbs[index].offset = offset;
  14942. } else {
  14943. _sg.wgpu.bindings_cache.vbs[index].buffer.id = SG_INVALID_ID;
  14944. _sg.wgpu.bindings_cache.vbs[index].offset = 0;
  14945. }
  14946. }
  14947. _SOKOL_PRIVATE bool _sg_wgpu_bindings_cache_ib_dirty(const _sg_buffer_t* ib, uint64_t offset) {
  14948. if (ib) {
  14949. return (_sg.wgpu.bindings_cache.ib.buffer.id != ib->slot.id)
  14950. || (_sg.wgpu.bindings_cache.ib.offset != offset);
  14951. } else {
  14952. return _sg.wgpu.bindings_cache.ib.buffer.id != SG_INVALID_ID;
  14953. }
  14954. }
  14955. _SOKOL_PRIVATE void _sg_wgpu_bindings_cache_ib_update(const _sg_buffer_t* ib, uint64_t offset) {
  14956. if (ib) {
  14957. _sg.wgpu.bindings_cache.ib.buffer.id = ib->slot.id;
  14958. _sg.wgpu.bindings_cache.ib.offset = offset;
  14959. } else {
  14960. _sg.wgpu.bindings_cache.ib.buffer.id = SG_INVALID_ID;
  14961. _sg.wgpu.bindings_cache.ib.offset = 0;
  14962. }
  14963. }
  14964. _SOKOL_PRIVATE bool _sg_wgpu_bindings_cache_bg_dirty(const _sg_wgpu_bindgroup_t* bg) {
  14965. if (bg) {
  14966. return _sg.wgpu.bindings_cache.bg.id != bg->slot.id;
  14967. } else {
  14968. return _sg.wgpu.bindings_cache.bg.id != SG_INVALID_ID;
  14969. }
  14970. }
  14971. _SOKOL_PRIVATE void _sg_wgpu_bindings_cache_bg_update(const _sg_wgpu_bindgroup_t* bg) {
  14972. if (bg) {
  14973. _sg.wgpu.bindings_cache.bg.id = bg->slot.id;
  14974. } else {
  14975. _sg.wgpu.bindings_cache.bg.id = SG_INVALID_ID;
  14976. }
  14977. }
  14978. _SOKOL_PRIVATE void _sg_wgpu_set_bindgroup(size_t bg_idx, _sg_wgpu_bindgroup_t* bg) {
  14979. if (_sg_wgpu_bindings_cache_bg_dirty(bg)) {
  14980. _sg_wgpu_bindings_cache_bg_update(bg);
  14981. _sg_stats_add(wgpu.bindings.num_set_bindgroup, 1);
  14982. if (_sg.cur_pass.is_compute) {
  14983. SOKOL_ASSERT(_sg.wgpu.cpass_enc);
  14984. if (bg) {
  14985. SOKOL_ASSERT(bg->slot.state == SG_RESOURCESTATE_VALID);
  14986. SOKOL_ASSERT(bg->bindgroup);
  14987. wgpuComputePassEncoderSetBindGroup(_sg.wgpu.cpass_enc, bg_idx, bg->bindgroup, 0, 0);
  14988. } else {
  14989. wgpuComputePassEncoderSetBindGroup(_sg.wgpu.cpass_enc, bg_idx, _sg.wgpu.empty_bind_group, 0, 0);
  14990. }
  14991. } else {
  14992. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  14993. if (bg) {
  14994. SOKOL_ASSERT(bg->slot.state == SG_RESOURCESTATE_VALID);
  14995. SOKOL_ASSERT(bg->bindgroup);
  14996. wgpuRenderPassEncoderSetBindGroup(_sg.wgpu.rpass_enc, bg_idx, bg->bindgroup, 0, 0);
  14997. } else {
  14998. wgpuRenderPassEncoderSetBindGroup(_sg.wgpu.rpass_enc, bg_idx, _sg.wgpu.empty_bind_group, 0, 0);
  14999. }
  15000. }
  15001. } else {
  15002. _sg_stats_add(wgpu.bindings.num_skip_redundant_bindgroup, 1);
  15003. }
  15004. }
  15005. _SOKOL_PRIVATE bool _sg_wgpu_apply_bindings_bindgroup(_sg_bindings_ptrs_t* bnd) {
  15006. if (!_sg.desc.wgpu_disable_bindgroups_cache) {
  15007. _sg_wgpu_bindgroup_t* bg = 0;
  15008. _sg_wgpu_bindgroups_cache_key_t key;
  15009. _sg_wgpu_init_bindgroups_cache_key(&key, bnd);
  15010. uint32_t bg_id = _sg_wgpu_bindgroups_cache_get(key.hash);
  15011. if (bg_id != SG_INVALID_ID) {
  15012. // potential cache hit
  15013. bg = _sg_wgpu_lookup_bindgroup(bg_id);
  15014. SOKOL_ASSERT(bg && (bg->slot.state == SG_RESOURCESTATE_VALID));
  15015. if (!_sg_wgpu_compare_bindgroups_cache_key(&key, &bg->key)) {
  15016. // cache collision, need to delete cached bindgroup
  15017. _sg_stats_add(wgpu.bindings.num_bindgroup_cache_collisions, 1);
  15018. _sg_wgpu_discard_bindgroup(bg);
  15019. _sg_wgpu_bindgroups_cache_set(key.hash, SG_INVALID_ID);
  15020. bg = 0;
  15021. } else {
  15022. _sg_stats_add(wgpu.bindings.num_bindgroup_cache_hits, 1);
  15023. }
  15024. } else {
  15025. _sg_stats_add(wgpu.bindings.num_bindgroup_cache_misses, 1);
  15026. }
  15027. if (bg == 0) {
  15028. // either no cache entry yet, or cache collision, create new bindgroup and store in cache
  15029. bg = _sg_wgpu_create_bindgroup(bnd);
  15030. _sg_wgpu_bindgroups_cache_set(key.hash, bg->slot.id);
  15031. }
  15032. if (bg && bg->slot.state == SG_RESOURCESTATE_VALID) {
  15033. _sg_wgpu_set_bindgroup(_SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX, bg);
  15034. } else {
  15035. return false;
  15036. }
  15037. } else {
  15038. // bindgroups cache disabled, create and destroy bindgroup on the fly (expensive!)
  15039. _sg_wgpu_bindgroup_t* bg = _sg_wgpu_create_bindgroup(bnd);
  15040. if (bg) {
  15041. if (bg->slot.state == SG_RESOURCESTATE_VALID) {
  15042. _sg_wgpu_set_bindgroup(_SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX, bg);
  15043. }
  15044. _sg_wgpu_discard_bindgroup(bg);
  15045. } else {
  15046. return false;
  15047. }
  15048. }
  15049. return true;
  15050. }
  15051. _SOKOL_PRIVATE bool _sg_wgpu_apply_index_buffer(_sg_bindings_ptrs_t* bnd) {
  15052. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  15053. const _sg_buffer_t* ib = bnd->ib;
  15054. uint64_t offset = (uint64_t)bnd->ib_offset;
  15055. if (_sg_wgpu_bindings_cache_ib_dirty(ib, offset)) {
  15056. _sg_wgpu_bindings_cache_ib_update(ib, offset);
  15057. if (ib) {
  15058. const WGPUIndexFormat format = _sg_wgpu_indexformat(bnd->pip->cmn.index_type);
  15059. const uint64_t buf_size = (uint64_t)ib->cmn.size;
  15060. SOKOL_ASSERT(buf_size > offset);
  15061. const uint64_t max_bytes = buf_size - offset;
  15062. wgpuRenderPassEncoderSetIndexBuffer(_sg.wgpu.rpass_enc, ib->wgpu.buf, format, offset, max_bytes);
  15063. /* FIXME: the else-pass should actually set a null index buffer, but that doesn't seem to work yet
  15064. } else {
  15065. wgpuRenderPassEncoderSetIndexBuffer(_sg.wgpu.rpass_enc, 0, WGPUIndexFormat_Undefined, 0, 0);
  15066. */
  15067. }
  15068. _sg_stats_add(wgpu.bindings.num_set_index_buffer, 1);
  15069. } else {
  15070. _sg_stats_add(wgpu.bindings.num_skip_redundant_index_buffer, 1);
  15071. }
  15072. return true;
  15073. }
  15074. _SOKOL_PRIVATE bool _sg_wgpu_apply_vertex_buffers(_sg_bindings_ptrs_t* bnd) {
  15075. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  15076. for (uint32_t slot = 0; slot < SG_MAX_VERTEXBUFFER_BINDSLOTS; slot++) {
  15077. const _sg_buffer_t* vb = bnd->vbs[slot];
  15078. const uint64_t offset = (uint64_t)bnd->vb_offsets[slot];
  15079. if (_sg_wgpu_bindings_cache_vb_dirty(slot, vb, offset)) {
  15080. _sg_wgpu_bindings_cache_vb_update(slot, vb, offset);
  15081. if (vb) {
  15082. const uint64_t buf_size = (uint64_t)vb->cmn.size;
  15083. SOKOL_ASSERT(buf_size > offset);
  15084. const uint64_t max_bytes = buf_size - offset;
  15085. wgpuRenderPassEncoderSetVertexBuffer(_sg.wgpu.rpass_enc, slot, vb->wgpu.buf, offset, max_bytes);
  15086. /* FIXME: the else-pass should actually set a null vertex buffer, but that doesn't seem to work yet
  15087. } else {
  15088. wgpuRenderPassEncoderSetVertexBuffer(_sg.wgpu.rpass_enc, slot, 0, 0, 0);
  15089. */
  15090. }
  15091. _sg_stats_add(wgpu.bindings.num_set_vertex_buffer, 1);
  15092. } else {
  15093. _sg_stats_add(wgpu.bindings.num_skip_redundant_vertex_buffer, 1);
  15094. }
  15095. }
  15096. return true;
  15097. }
  15098. _SOKOL_PRIVATE void _sg_wgpu_setup_backend(const sg_desc* desc) {
  15099. SOKOL_ASSERT(desc);
  15100. SOKOL_ASSERT(desc->environment.wgpu.device);
  15101. SOKOL_ASSERT(desc->uniform_buffer_size > 0);
  15102. _sg.backend = SG_BACKEND_WGPU;
  15103. _sg.wgpu.valid = true;
  15104. _sg.wgpu.dev = (WGPUDevice) desc->environment.wgpu.device;
  15105. _sg.wgpu.queue = wgpuDeviceGetQueue(_sg.wgpu.dev);
  15106. SOKOL_ASSERT(_sg.wgpu.queue);
  15107. _sg_wgpu_init_caps();
  15108. _sg_wgpu_uniform_buffer_init(desc);
  15109. _sg_wgpu_bindgroups_pool_init(desc);
  15110. _sg_wgpu_bindgroups_cache_init(desc);
  15111. _sg_wgpu_bindings_cache_clear();
  15112. // create an empty bind group
  15113. WGPUBindGroupLayoutDescriptor bgl_desc;
  15114. _sg_clear(&bgl_desc, sizeof(bgl_desc));
  15115. WGPUBindGroupLayout empty_bgl = wgpuDeviceCreateBindGroupLayout(_sg.wgpu.dev, &bgl_desc);
  15116. SOKOL_ASSERT(empty_bgl);
  15117. WGPUBindGroupDescriptor bg_desc;
  15118. _sg_clear(&bg_desc, sizeof(bg_desc));
  15119. bg_desc.layout = empty_bgl;
  15120. _sg.wgpu.empty_bind_group = wgpuDeviceCreateBindGroup(_sg.wgpu.dev, &bg_desc);
  15121. SOKOL_ASSERT(_sg.wgpu.empty_bind_group);
  15122. wgpuBindGroupLayoutRelease(empty_bgl);
  15123. // create initial per-frame command encoder
  15124. WGPUCommandEncoderDescriptor cmd_enc_desc;
  15125. _sg_clear(&cmd_enc_desc, sizeof(cmd_enc_desc));
  15126. _sg.wgpu.cmd_enc = wgpuDeviceCreateCommandEncoder(_sg.wgpu.dev, &cmd_enc_desc);
  15127. SOKOL_ASSERT(_sg.wgpu.cmd_enc);
  15128. }
  15129. _SOKOL_PRIVATE void _sg_wgpu_discard_backend(void) {
  15130. SOKOL_ASSERT(_sg.wgpu.valid);
  15131. SOKOL_ASSERT(_sg.wgpu.cmd_enc);
  15132. _sg.wgpu.valid = false;
  15133. _sg_wgpu_discard_all_bindgroups();
  15134. _sg_wgpu_bindgroups_cache_discard();
  15135. _sg_wgpu_bindgroups_pool_discard();
  15136. _sg_wgpu_uniform_buffer_discard();
  15137. wgpuBindGroupRelease(_sg.wgpu.empty_bind_group); _sg.wgpu.empty_bind_group = 0;
  15138. wgpuCommandEncoderRelease(_sg.wgpu.cmd_enc); _sg.wgpu.cmd_enc = 0;
  15139. wgpuQueueRelease(_sg.wgpu.queue); _sg.wgpu.queue = 0;
  15140. }
  15141. _SOKOL_PRIVATE void _sg_wgpu_reset_state_cache(void) {
  15142. _sg_wgpu_bindings_cache_clear();
  15143. }
  15144. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  15145. SOKOL_ASSERT(buf && desc);
  15146. SOKOL_ASSERT(buf->cmn.size > 0);
  15147. const bool injected = (0 != desc->wgpu_buffer);
  15148. if (injected) {
  15149. buf->wgpu.buf = (WGPUBuffer) desc->wgpu_buffer;
  15150. wgpuBufferReference(buf->wgpu.buf);
  15151. } else {
  15152. // buffer mapping size must be multiple of 4, so round up buffer size (only a problem
  15153. // with index buffers containing odd number of indices)
  15154. const uint64_t wgpu_buf_size = _sg_roundup_u64((uint64_t)buf->cmn.size, 4);
  15155. const bool map_at_creation = buf->cmn.usage.immutable && (desc->data.ptr);
  15156. WGPUBufferDescriptor wgpu_buf_desc;
  15157. _sg_clear(&wgpu_buf_desc, sizeof(wgpu_buf_desc));
  15158. wgpu_buf_desc.usage = _sg_wgpu_buffer_usage(&buf->cmn.usage);
  15159. wgpu_buf_desc.size = wgpu_buf_size;
  15160. wgpu_buf_desc.mappedAtCreation = map_at_creation;
  15161. wgpu_buf_desc.label = _sg_wgpu_stringview(desc->label);
  15162. buf->wgpu.buf = wgpuDeviceCreateBuffer(_sg.wgpu.dev, &wgpu_buf_desc);
  15163. if (0 == buf->wgpu.buf) {
  15164. _SG_ERROR(WGPU_CREATE_BUFFER_FAILED);
  15165. return SG_RESOURCESTATE_FAILED;
  15166. }
  15167. // NOTE: assume that WebGPU creates zero-initialized buffers
  15168. if (map_at_creation) {
  15169. SOKOL_ASSERT(desc->data.ptr && (desc->data.size > 0));
  15170. SOKOL_ASSERT(desc->data.size <= (size_t)buf->cmn.size);
  15171. // FIXME: inefficient on WASM
  15172. void* ptr = wgpuBufferGetMappedRange(buf->wgpu.buf, 0, wgpu_buf_size);
  15173. SOKOL_ASSERT(ptr);
  15174. memcpy(ptr, desc->data.ptr, desc->data.size);
  15175. wgpuBufferUnmap(buf->wgpu.buf);
  15176. }
  15177. }
  15178. return SG_RESOURCESTATE_VALID;
  15179. }
  15180. _SOKOL_PRIVATE void _sg_wgpu_discard_buffer(_sg_buffer_t* buf) {
  15181. SOKOL_ASSERT(buf);
  15182. if (buf->cmn.usage.storage_buffer) {
  15183. _sg_wgpu_bindgroups_cache_invalidate(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_STORAGEBUFFER, buf->slot.id);
  15184. }
  15185. if (buf->wgpu.buf) {
  15186. wgpuBufferRelease(buf->wgpu.buf);
  15187. }
  15188. }
  15189. _SOKOL_PRIVATE void _sg_wgpu_copy_buffer_data(const _sg_buffer_t* buf, uint64_t offset, const sg_range* data) {
  15190. SOKOL_ASSERT((offset + data->size) <= (size_t)buf->cmn.size);
  15191. // WebGPU's write-buffer requires the size to be a multiple of four, so we may need to split the copy
  15192. // operation into two writeBuffer calls
  15193. uint64_t clamped_size = data->size & ~3UL;
  15194. uint64_t extra_size = data->size & 3UL;
  15195. SOKOL_ASSERT(extra_size < 4);
  15196. wgpuQueueWriteBuffer(_sg.wgpu.queue, buf->wgpu.buf, offset, data->ptr, clamped_size);
  15197. if (extra_size > 0) {
  15198. const uint64_t extra_src_offset = clamped_size;
  15199. const uint64_t extra_dst_offset = offset + clamped_size;
  15200. uint8_t extra_data[4] = { 0 };
  15201. uint8_t* extra_src_ptr = ((uint8_t*)data->ptr) + extra_src_offset;
  15202. for (size_t i = 0; i < extra_size; i++) {
  15203. extra_data[i] = extra_src_ptr[i];
  15204. }
  15205. wgpuQueueWriteBuffer(_sg.wgpu.queue, buf->wgpu.buf, extra_dst_offset, extra_src_ptr, 4);
  15206. }
  15207. }
  15208. _SOKOL_PRIVATE void _sg_wgpu_copy_image_data(const _sg_image_t* img, WGPUTexture wgpu_tex, const sg_image_data* data) {
  15209. WGPUTextureDataLayout wgpu_layout;
  15210. _sg_clear(&wgpu_layout, sizeof(wgpu_layout));
  15211. WGPUImageCopyTexture wgpu_copy_tex;
  15212. _sg_clear(&wgpu_copy_tex, sizeof(wgpu_copy_tex));
  15213. wgpu_copy_tex.texture = wgpu_tex;
  15214. wgpu_copy_tex.aspect = WGPUTextureAspect_All;
  15215. WGPUExtent3D wgpu_extent;
  15216. _sg_clear(&wgpu_extent, sizeof(wgpu_extent));
  15217. const int num_faces = (img->cmn.type == SG_IMAGETYPE_CUBE) ? 6 : 1;
  15218. for (int face_index = 0; face_index < num_faces; face_index++) {
  15219. for (int mip_index = 0; mip_index < img->cmn.num_mipmaps; mip_index++) {
  15220. wgpu_copy_tex.mipLevel = (uint32_t)mip_index;
  15221. wgpu_copy_tex.origin.z = (uint32_t)face_index;
  15222. int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  15223. int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  15224. int mip_slices;
  15225. switch (img->cmn.type) {
  15226. case SG_IMAGETYPE_CUBE:
  15227. mip_slices = 1;
  15228. break;
  15229. case SG_IMAGETYPE_3D:
  15230. mip_slices = _sg_miplevel_dim(img->cmn.num_slices, mip_index);
  15231. break;
  15232. default:
  15233. mip_slices = img->cmn.num_slices;
  15234. break;
  15235. }
  15236. const int row_pitch = _sg_row_pitch(img->cmn.pixel_format, mip_width, 1);
  15237. const int num_rows = _sg_num_rows(img->cmn.pixel_format, mip_height);
  15238. if (_sg_is_compressed_pixel_format(img->cmn.pixel_format)) {
  15239. mip_width = _sg_roundup(mip_width, 4);
  15240. mip_height = _sg_roundup(mip_height, 4);
  15241. }
  15242. wgpu_layout.offset = 0;
  15243. wgpu_layout.bytesPerRow = (uint32_t)row_pitch;
  15244. wgpu_layout.rowsPerImage = (uint32_t)num_rows;
  15245. wgpu_extent.width = (uint32_t)mip_width;
  15246. wgpu_extent.height = (uint32_t)mip_height;
  15247. wgpu_extent.depthOrArrayLayers = (uint32_t)mip_slices;
  15248. const sg_range* mip_data = &data->subimage[face_index][mip_index];
  15249. wgpuQueueWriteTexture(_sg.wgpu.queue, &wgpu_copy_tex, mip_data->ptr, mip_data->size, &wgpu_layout, &wgpu_extent);
  15250. }
  15251. }
  15252. }
  15253. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  15254. SOKOL_ASSERT(img && desc);
  15255. const bool injected = (0 != desc->wgpu_texture);
  15256. if (injected) {
  15257. img->wgpu.tex = (WGPUTexture)desc->wgpu_texture;
  15258. wgpuTextureReference(img->wgpu.tex);
  15259. img->wgpu.view = (WGPUTextureView)desc->wgpu_texture_view;
  15260. if (img->wgpu.view) {
  15261. wgpuTextureViewReference(img->wgpu.view);
  15262. }
  15263. } else {
  15264. WGPUTextureDescriptor wgpu_tex_desc;
  15265. _sg_clear(&wgpu_tex_desc, sizeof(wgpu_tex_desc));
  15266. wgpu_tex_desc.label = _sg_wgpu_stringview(desc->label);
  15267. wgpu_tex_desc.usage = WGPUTextureUsage_TextureBinding|WGPUTextureUsage_CopyDst;
  15268. if (desc->usage.render_attachment) {
  15269. wgpu_tex_desc.usage |= WGPUTextureUsage_RenderAttachment;
  15270. }
  15271. if (desc->usage.storage_attachment) {
  15272. wgpu_tex_desc.usage |= WGPUTextureUsage_StorageBinding;
  15273. }
  15274. wgpu_tex_desc.dimension = _sg_wgpu_texture_dimension(img->cmn.type);
  15275. wgpu_tex_desc.size.width = (uint32_t) img->cmn.width;
  15276. wgpu_tex_desc.size.height = (uint32_t) img->cmn.height;
  15277. if (desc->type == SG_IMAGETYPE_CUBE) {
  15278. wgpu_tex_desc.size.depthOrArrayLayers = 6;
  15279. } else {
  15280. wgpu_tex_desc.size.depthOrArrayLayers = (uint32_t) img->cmn.num_slices;
  15281. }
  15282. wgpu_tex_desc.format = _sg_wgpu_textureformat(img->cmn.pixel_format);
  15283. wgpu_tex_desc.mipLevelCount = (uint32_t) img->cmn.num_mipmaps;
  15284. wgpu_tex_desc.sampleCount = (uint32_t) img->cmn.sample_count;
  15285. img->wgpu.tex = wgpuDeviceCreateTexture(_sg.wgpu.dev, &wgpu_tex_desc);
  15286. if (0 == img->wgpu.tex) {
  15287. _SG_ERROR(WGPU_CREATE_TEXTURE_FAILED);
  15288. return SG_RESOURCESTATE_FAILED;
  15289. }
  15290. if (desc->data.subimage[0][0].ptr) {
  15291. _sg_wgpu_copy_image_data(img, img->wgpu.tex, &desc->data);
  15292. }
  15293. WGPUTextureViewDescriptor wgpu_texview_desc;
  15294. _sg_clear(&wgpu_texview_desc, sizeof(wgpu_texview_desc));
  15295. wgpu_texview_desc.label = _sg_wgpu_stringview(desc->label);
  15296. wgpu_texview_desc.dimension = _sg_wgpu_texture_view_dimension(img->cmn.type);
  15297. wgpu_texview_desc.mipLevelCount = (uint32_t)img->cmn.num_mipmaps;
  15298. if (img->cmn.type == SG_IMAGETYPE_CUBE) {
  15299. wgpu_texview_desc.arrayLayerCount = 6;
  15300. } else if (img->cmn.type == SG_IMAGETYPE_ARRAY) {
  15301. wgpu_texview_desc.arrayLayerCount = (uint32_t)img->cmn.num_slices;
  15302. } else {
  15303. wgpu_texview_desc.arrayLayerCount = 1;
  15304. }
  15305. if (_sg_is_depth_or_depth_stencil_format(img->cmn.pixel_format)) {
  15306. wgpu_texview_desc.aspect = WGPUTextureAspect_DepthOnly;
  15307. } else {
  15308. wgpu_texview_desc.aspect = WGPUTextureAspect_All;
  15309. }
  15310. img->wgpu.view = wgpuTextureCreateView(img->wgpu.tex, &wgpu_texview_desc);
  15311. if (0 == img->wgpu.view) {
  15312. _SG_ERROR(WGPU_CREATE_TEXTURE_VIEW_FAILED);
  15313. return SG_RESOURCESTATE_FAILED;
  15314. }
  15315. }
  15316. return SG_RESOURCESTATE_VALID;
  15317. }
  15318. _SOKOL_PRIVATE void _sg_wgpu_discard_image(_sg_image_t* img) {
  15319. SOKOL_ASSERT(img);
  15320. _sg_wgpu_bindgroups_cache_invalidate(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_IMAGE, img->slot.id);
  15321. if (img->wgpu.view) {
  15322. wgpuTextureViewRelease(img->wgpu.view);
  15323. img->wgpu.view = 0;
  15324. }
  15325. if (img->wgpu.tex) {
  15326. wgpuTextureRelease(img->wgpu.tex);
  15327. img->wgpu.tex = 0;
  15328. }
  15329. }
  15330. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  15331. SOKOL_ASSERT(smp && desc);
  15332. SOKOL_ASSERT(_sg.wgpu.dev);
  15333. const bool injected = (0 != desc->wgpu_sampler);
  15334. if (injected) {
  15335. smp->wgpu.smp = (WGPUSampler) desc->wgpu_sampler;
  15336. wgpuSamplerReference(smp->wgpu.smp);
  15337. } else {
  15338. WGPUSamplerDescriptor wgpu_desc;
  15339. _sg_clear(&wgpu_desc, sizeof(wgpu_desc));
  15340. wgpu_desc.label = _sg_wgpu_stringview(desc->label);
  15341. wgpu_desc.addressModeU = _sg_wgpu_sampler_address_mode(desc->wrap_u);
  15342. wgpu_desc.addressModeV = _sg_wgpu_sampler_address_mode(desc->wrap_v);
  15343. wgpu_desc.addressModeW = _sg_wgpu_sampler_address_mode(desc->wrap_w);
  15344. wgpu_desc.magFilter = _sg_wgpu_sampler_minmag_filter(desc->mag_filter);
  15345. wgpu_desc.minFilter = _sg_wgpu_sampler_minmag_filter(desc->min_filter);
  15346. wgpu_desc.mipmapFilter = _sg_wgpu_sampler_mipmap_filter(desc->mipmap_filter);
  15347. wgpu_desc.lodMinClamp = desc->min_lod;
  15348. wgpu_desc.lodMaxClamp = desc->max_lod;
  15349. wgpu_desc.compare = _sg_wgpu_comparefunc(desc->compare);
  15350. if (wgpu_desc.compare == WGPUCompareFunction_Never) {
  15351. wgpu_desc.compare = WGPUCompareFunction_Undefined;
  15352. }
  15353. wgpu_desc.maxAnisotropy = (uint16_t)desc->max_anisotropy;
  15354. smp->wgpu.smp = wgpuDeviceCreateSampler(_sg.wgpu.dev, &wgpu_desc);
  15355. if (0 == smp->wgpu.smp) {
  15356. _SG_ERROR(WGPU_CREATE_SAMPLER_FAILED);
  15357. return SG_RESOURCESTATE_FAILED;
  15358. }
  15359. }
  15360. return SG_RESOURCESTATE_VALID;
  15361. }
  15362. _SOKOL_PRIVATE void _sg_wgpu_discard_sampler(_sg_sampler_t* smp) {
  15363. SOKOL_ASSERT(smp);
  15364. _sg_wgpu_bindgroups_cache_invalidate(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_SAMPLER, smp->slot.id);
  15365. if (smp->wgpu.smp) {
  15366. wgpuSamplerRelease(smp->wgpu.smp);
  15367. smp->wgpu.smp = 0;
  15368. }
  15369. }
  15370. _SOKOL_PRIVATE _sg_wgpu_shader_func_t _sg_wgpu_create_shader_func(const sg_shader_function* func, const char* label) {
  15371. SOKOL_ASSERT(func);
  15372. SOKOL_ASSERT(func->source);
  15373. SOKOL_ASSERT(func->entry);
  15374. _sg_wgpu_shader_func_t res;
  15375. _sg_clear(&res, sizeof(res));
  15376. _sg_strcpy(&res.entry, func->entry);
  15377. WGPUShaderModuleWGSLDescriptor wgpu_shdmod_wgsl_desc;
  15378. _sg_clear(&wgpu_shdmod_wgsl_desc, sizeof(wgpu_shdmod_wgsl_desc));
  15379. wgpu_shdmod_wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor;
  15380. wgpu_shdmod_wgsl_desc.code = _sg_wgpu_stringview(func->source);
  15381. WGPUShaderModuleDescriptor wgpu_shdmod_desc;
  15382. _sg_clear(&wgpu_shdmod_desc, sizeof(wgpu_shdmod_desc));
  15383. wgpu_shdmod_desc.nextInChain = &wgpu_shdmod_wgsl_desc.chain;
  15384. wgpu_shdmod_desc.label = _sg_wgpu_stringview(label);
  15385. // NOTE: if compilation fails we won't actually find out in this call since
  15386. // it always returns a valid module handle, and the GetCompilationInfo() call
  15387. // is asynchronous
  15388. res.module = wgpuDeviceCreateShaderModule(_sg.wgpu.dev, &wgpu_shdmod_desc);
  15389. if (0 == res.module) {
  15390. _SG_ERROR(WGPU_CREATE_SHADER_MODULE_FAILED);
  15391. }
  15392. return res;
  15393. }
  15394. _SOKOL_PRIVATE void _sg_wgpu_discard_shader_func(_sg_wgpu_shader_func_t* func) {
  15395. if (func->module) {
  15396. wgpuShaderModuleRelease(func->module);
  15397. func->module = 0;
  15398. }
  15399. }
  15400. typedef struct { uint8_t sokol_slot, wgpu_slot; } _sg_wgpu_dynoffset_mapping_t;
  15401. _SOKOL_PRIVATE int _sg_wgpu_dynoffset_cmp(const void* a, const void* b) {
  15402. const _sg_wgpu_dynoffset_mapping_t* aa = (const _sg_wgpu_dynoffset_mapping_t*)a;
  15403. const _sg_wgpu_dynoffset_mapping_t* bb = (const _sg_wgpu_dynoffset_mapping_t*)b;
  15404. if (aa->wgpu_slot < bb->wgpu_slot) return -1;
  15405. else if (aa->wgpu_slot > bb->wgpu_slot) return 1;
  15406. return 0;
  15407. }
  15408. // NOTE: this is an out-of-range check for WGSL bindslots that's also active in release mode
  15409. _SOKOL_PRIVATE bool _sg_wgpu_ensure_wgsl_bindslot_ranges(const sg_shader_desc* desc) {
  15410. SOKOL_ASSERT(desc);
  15411. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  15412. if (desc->uniform_blocks[i].wgsl_group0_binding_n >= _SG_WGPU_MAX_UB_BINDGROUP_BIND_SLOTS) {
  15413. _SG_ERROR(WGPU_UNIFORMBLOCK_WGSL_GROUP0_BINDING_OUT_OF_RANGE);
  15414. return false;
  15415. }
  15416. }
  15417. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  15418. if (desc->storage_buffers[i].wgsl_group1_binding_n >= _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS) {
  15419. _SG_ERROR(WGPU_STORAGEBUFFER_WGSL_GROUP1_BINDING_OUT_OF_RANGE);
  15420. return false;
  15421. }
  15422. }
  15423. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  15424. if (desc->images[i].wgsl_group1_binding_n >= _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS) {
  15425. _SG_ERROR(WGPU_IMAGE_WGSL_GROUP1_BINDING_OUT_OF_RANGE);
  15426. return false;
  15427. }
  15428. }
  15429. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  15430. if (desc->samplers[i].wgsl_group1_binding_n >= _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS) {
  15431. _SG_ERROR(WGPU_SAMPLER_WGSL_GROUP1_BINDING_OUT_OF_RANGE);
  15432. return false;
  15433. }
  15434. }
  15435. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  15436. if (desc->storage_images[i].wgsl_group2_binding_n >= _SG_WGPU_MAX_SIMG_BIND_SLOTS) {
  15437. _SG_ERROR(WGPU_STORAGEIMAGE_WGSL_GROUP2_BINDING_OUT_OF_RANGE);
  15438. }
  15439. }
  15440. return true;
  15441. }
  15442. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  15443. SOKOL_ASSERT(shd && desc);
  15444. SOKOL_ASSERT(shd->wgpu.vertex_func.module == 0);
  15445. SOKOL_ASSERT(shd->wgpu.fragment_func.module == 0);
  15446. SOKOL_ASSERT(shd->wgpu.compute_func.module == 0);
  15447. SOKOL_ASSERT(shd->wgpu.bgl_ub == 0);
  15448. SOKOL_ASSERT(shd->wgpu.bg_ub == 0);
  15449. SOKOL_ASSERT(shd->wgpu.bgl_img_smp_sbuf == 0);
  15450. // do a release-mode bounds-check on wgsl bindslots, even though out-of-range
  15451. // bindslots can't cause out-of-bounds accesses in the wgpu backend, this
  15452. // is done to be consistent with the other backends
  15453. if (!_sg_wgpu_ensure_wgsl_bindslot_ranges(desc)) {
  15454. return SG_RESOURCESTATE_FAILED;
  15455. }
  15456. // build shader modules
  15457. bool shd_valid = true;
  15458. if (desc->vertex_func.source) {
  15459. shd->wgpu.vertex_func = _sg_wgpu_create_shader_func(&desc->vertex_func, desc->label);
  15460. shd_valid &= shd->wgpu.vertex_func.module != 0;
  15461. }
  15462. if (desc->fragment_func.source) {
  15463. shd->wgpu.fragment_func = _sg_wgpu_create_shader_func(&desc->fragment_func, desc->label);
  15464. shd_valid &= shd->wgpu.fragment_func.module != 0;
  15465. }
  15466. if (desc->compute_func.source) {
  15467. shd->wgpu.compute_func = _sg_wgpu_create_shader_func(&desc->compute_func, desc->label);
  15468. shd_valid &= shd->wgpu.compute_func.module != 0;
  15469. }
  15470. if (!shd_valid) {
  15471. _sg_wgpu_discard_shader_func(&shd->wgpu.vertex_func);
  15472. _sg_wgpu_discard_shader_func(&shd->wgpu.fragment_func);
  15473. _sg_wgpu_discard_shader_func(&shd->wgpu.compute_func);
  15474. return SG_RESOURCESTATE_FAILED;
  15475. }
  15476. // create bind group layout and bind group for uniform blocks
  15477. // NOTE also need to create a mapping of sokol ub bind slots to array indices
  15478. // for the dynamic offsets array in the setBindGroup call
  15479. SOKOL_ASSERT(_SG_WGPU_MAX_UB_BINDGROUP_ENTRIES <= _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES);
  15480. SOKOL_ASSERT(_SG_WGPU_MAX_SIMG_BINDGROUP_ENTRIES <= _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES);
  15481. WGPUBindGroupLayoutEntry bgl_entries[_SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES];
  15482. _sg_clear(bgl_entries, sizeof(bgl_entries));
  15483. WGPUBindGroupLayoutDescriptor bgl_desc;
  15484. _sg_clear(&bgl_desc, sizeof(bgl_desc));
  15485. WGPUBindGroupEntry bg_entries[_SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES];
  15486. _sg_clear(&bg_entries, sizeof(bg_entries));
  15487. WGPUBindGroupDescriptor bg_desc;
  15488. _sg_clear(&bg_desc, sizeof(bg_desc));
  15489. _sg_wgpu_dynoffset_mapping_t dynoffset_map[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  15490. _sg_clear(dynoffset_map, sizeof(dynoffset_map));
  15491. size_t bgl_index = 0;
  15492. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  15493. if (shd->cmn.uniform_blocks[i].stage == SG_SHADERSTAGE_NONE) {
  15494. continue;
  15495. }
  15496. shd->wgpu.ub_grp0_bnd_n[i] = desc->uniform_blocks[i].wgsl_group0_binding_n;
  15497. WGPUBindGroupEntry* bg_entry = &bg_entries[bgl_index];
  15498. WGPUBindGroupLayoutEntry* bgl_entry = &bgl_entries[bgl_index];
  15499. bgl_entry->binding = shd->wgpu.ub_grp0_bnd_n[i];
  15500. bgl_entry->visibility = _sg_wgpu_shader_stage(shd->cmn.uniform_blocks[i].stage);
  15501. bgl_entry->buffer.type = WGPUBufferBindingType_Uniform;
  15502. bgl_entry->buffer.hasDynamicOffset = true;
  15503. bg_entry->binding = bgl_entry->binding;
  15504. bg_entry->buffer = _sg.wgpu.uniform.buf;
  15505. bg_entry->size = _SG_WGPU_MAX_UNIFORM_UPDATE_SIZE;
  15506. dynoffset_map[i].sokol_slot = i;
  15507. dynoffset_map[i].wgpu_slot = bgl_entry->binding;
  15508. bgl_index += 1;
  15509. }
  15510. bgl_desc.entryCount = bgl_index;
  15511. bgl_desc.entries = bgl_entries;
  15512. shd->wgpu.bgl_ub = wgpuDeviceCreateBindGroupLayout(_sg.wgpu.dev, &bgl_desc);
  15513. SOKOL_ASSERT(shd->wgpu.bgl_ub);
  15514. bg_desc.layout = shd->wgpu.bgl_ub;
  15515. bg_desc.entryCount = bgl_index;
  15516. bg_desc.entries = bg_entries;
  15517. shd->wgpu.bg_ub = wgpuDeviceCreateBindGroup(_sg.wgpu.dev, &bg_desc);
  15518. SOKOL_ASSERT(shd->wgpu.bg_ub);
  15519. // sort the dynoffset_map by wgpu bindings, this is because the
  15520. // dynamic offsets of the WebGPU setBindGroup call must be in
  15521. // 'binding order', not 'bindgroup entry order'
  15522. qsort(dynoffset_map, bgl_index, sizeof(_sg_wgpu_dynoffset_mapping_t), _sg_wgpu_dynoffset_cmp);
  15523. shd->wgpu.ub_num_dynoffsets = bgl_index;
  15524. for (uint8_t i = 0; i < bgl_index; i++) {
  15525. const uint8_t sokol_slot = dynoffset_map[i].sokol_slot;
  15526. shd->wgpu.ub_dynoffsets[sokol_slot] = i;
  15527. }
  15528. // create bind group layout for images, samplers and storage buffers
  15529. _sg_clear(bgl_entries, sizeof(bgl_entries));
  15530. _sg_clear(&bgl_desc, sizeof(bgl_desc));
  15531. bgl_index = 0;
  15532. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  15533. if (shd->cmn.images[i].stage == SG_SHADERSTAGE_NONE) {
  15534. continue;
  15535. }
  15536. const bool msaa = shd->cmn.images[i].multisampled;
  15537. shd->wgpu.img_grp1_bnd_n[i] = desc->images[i].wgsl_group1_binding_n;
  15538. WGPUBindGroupLayoutEntry* bgl_entry = &bgl_entries[bgl_index];
  15539. bgl_entry->binding = shd->wgpu.img_grp1_bnd_n[i];
  15540. bgl_entry->visibility = _sg_wgpu_shader_stage(shd->cmn.images[i].stage);
  15541. bgl_entry->texture.viewDimension = _sg_wgpu_texture_view_dimension(shd->cmn.images[i].image_type);
  15542. bgl_entry->texture.sampleType = _sg_wgpu_texture_sample_type(shd->cmn.images[i].sample_type, msaa);
  15543. bgl_entry->texture.multisampled = msaa;
  15544. bgl_index += 1;
  15545. }
  15546. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  15547. if (shd->cmn.samplers[i].stage == SG_SHADERSTAGE_NONE) {
  15548. continue;
  15549. }
  15550. shd->wgpu.smp_grp1_bnd_n[i] = desc->samplers[i].wgsl_group1_binding_n;
  15551. WGPUBindGroupLayoutEntry* bgl_entry = &bgl_entries[bgl_index];
  15552. bgl_entry->binding = shd->wgpu.smp_grp1_bnd_n[i];
  15553. bgl_entry->visibility = _sg_wgpu_shader_stage(shd->cmn.samplers[i].stage);
  15554. bgl_entry->sampler.type = _sg_wgpu_sampler_binding_type(shd->cmn.samplers[i].sampler_type);
  15555. bgl_index += 1;
  15556. }
  15557. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  15558. if (shd->cmn.storage_buffers[i].stage == SG_SHADERSTAGE_NONE) {
  15559. continue;
  15560. }
  15561. shd->wgpu.sbuf_grp1_bnd_n[i] = desc->storage_buffers[i].wgsl_group1_binding_n;
  15562. WGPUBindGroupLayoutEntry* bgl_entry = &bgl_entries[bgl_index];
  15563. bgl_entry->binding = shd->wgpu.sbuf_grp1_bnd_n[i];
  15564. bgl_entry->visibility = _sg_wgpu_shader_stage(shd->cmn.storage_buffers[i].stage);
  15565. if (shd->cmn.storage_buffers[i].readonly) {
  15566. bgl_entry->buffer.type = WGPUBufferBindingType_ReadOnlyStorage;
  15567. } else {
  15568. bgl_entry->buffer.type = WGPUBufferBindingType_Storage;
  15569. }
  15570. bgl_index += 1;
  15571. }
  15572. bgl_desc.entryCount = bgl_index;
  15573. bgl_desc.entries = bgl_entries;
  15574. shd->wgpu.bgl_img_smp_sbuf = wgpuDeviceCreateBindGroupLayout(_sg.wgpu.dev, &bgl_desc);
  15575. if (shd->wgpu.bgl_img_smp_sbuf == 0) {
  15576. _SG_ERROR(WGPU_SHADER_CREATE_BINDGROUP_LAYOUT_FAILED);
  15577. return SG_RESOURCESTATE_FAILED;
  15578. }
  15579. // create optional bindgroup layout for storage images (separate bindgroup because
  15580. // those are not applied in sg_apply_bindings() but are defined as pass attachments)
  15581. _sg_clear(bgl_entries, sizeof(bgl_entries));
  15582. _sg_clear(&bgl_desc, sizeof(bgl_desc));
  15583. bgl_index = 0;
  15584. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  15585. if (shd->cmn.storage_images[i].stage == SG_SHADERSTAGE_NONE) {
  15586. continue;
  15587. }
  15588. shd->wgpu.simg_grp2_bnd_n[i] = desc->storage_images[i].wgsl_group2_binding_n;
  15589. WGPUBindGroupLayoutEntry* bgl_entry = &bgl_entries[bgl_index];
  15590. bgl_entry->binding = shd->wgpu.simg_grp2_bnd_n[i];
  15591. bgl_entry->visibility = _sg_wgpu_shader_stage(shd->cmn.storage_images[i].stage);
  15592. if (shd->cmn.storage_images[i].writeonly) {
  15593. bgl_entry->storageTexture.access = WGPUStorageTextureAccess_WriteOnly;
  15594. } else {
  15595. bgl_entry->storageTexture.access = WGPUStorageTextureAccess_ReadWrite;
  15596. }
  15597. bgl_entry->storageTexture.format = _sg_wgpu_textureformat(desc->storage_images[i].access_format);
  15598. bgl_entry->texture.viewDimension = _sg_wgpu_texture_view_dimension(shd->cmn.storage_images[i].image_type);
  15599. bgl_index += 1;
  15600. }
  15601. if (bgl_index > 0) {
  15602. bgl_desc.entryCount = bgl_index;
  15603. bgl_desc.entries = bgl_entries;
  15604. shd->wgpu.bgl_simg = wgpuDeviceCreateBindGroupLayout(_sg.wgpu.dev, &bgl_desc);
  15605. if (shd->wgpu.bgl_simg == 0) {
  15606. _SG_ERROR(WGPU_SHADER_CREATE_BINDGROUP_LAYOUT_FAILED);
  15607. return SG_RESOURCESTATE_FAILED;
  15608. }
  15609. }
  15610. return SG_RESOURCESTATE_VALID;
  15611. }
  15612. _SOKOL_PRIVATE void _sg_wgpu_discard_shader(_sg_shader_t* shd) {
  15613. SOKOL_ASSERT(shd);
  15614. _sg_wgpu_discard_shader_func(&shd->wgpu.vertex_func);
  15615. _sg_wgpu_discard_shader_func(&shd->wgpu.fragment_func);
  15616. _sg_wgpu_discard_shader_func(&shd->wgpu.compute_func);
  15617. if (shd->wgpu.bgl_ub) {
  15618. wgpuBindGroupLayoutRelease(shd->wgpu.bgl_ub);
  15619. shd->wgpu.bgl_ub = 0;
  15620. }
  15621. if (shd->wgpu.bg_ub) {
  15622. wgpuBindGroupRelease(shd->wgpu.bg_ub);
  15623. shd->wgpu.bg_ub = 0;
  15624. }
  15625. if (shd->wgpu.bgl_img_smp_sbuf) {
  15626. wgpuBindGroupLayoutRelease(shd->wgpu.bgl_img_smp_sbuf);
  15627. shd->wgpu.bgl_img_smp_sbuf = 0;
  15628. }
  15629. if (shd->wgpu.bgl_simg) {
  15630. wgpuBindGroupLayoutRelease(shd->wgpu.bgl_simg);
  15631. shd->wgpu.bgl_simg = 0;
  15632. }
  15633. }
  15634. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_pipeline(_sg_pipeline_t* pip, _sg_shader_t* shd, const sg_pipeline_desc* desc) {
  15635. SOKOL_ASSERT(pip && shd && desc);
  15636. SOKOL_ASSERT(desc->shader.id == shd->slot.id);
  15637. SOKOL_ASSERT(shd->wgpu.bgl_ub);
  15638. SOKOL_ASSERT(shd->wgpu.bgl_img_smp_sbuf);
  15639. pip->shader = shd;
  15640. pip->wgpu.blend_color.r = (double) desc->blend_color.r;
  15641. pip->wgpu.blend_color.g = (double) desc->blend_color.g;
  15642. pip->wgpu.blend_color.b = (double) desc->blend_color.b;
  15643. pip->wgpu.blend_color.a = (double) desc->blend_color.a;
  15644. // - @group(0) for uniform blocks
  15645. // - @group(1) for all image, sampler and storagebuffer resources
  15646. // - @group(2) optional: storage image attachments in compute passes
  15647. size_t num_bgls = 2;
  15648. WGPUBindGroupLayout wgpu_bgl[_SG_WGPU_MAX_BINDGROUPS];
  15649. _sg_clear(&wgpu_bgl, sizeof(wgpu_bgl));
  15650. wgpu_bgl[_SG_WGPU_UB_BINDGROUP_INDEX ] = shd->wgpu.bgl_ub;
  15651. wgpu_bgl[_SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX] = shd->wgpu.bgl_img_smp_sbuf;
  15652. if (shd->wgpu.bgl_simg) {
  15653. wgpu_bgl[_SG_WGPU_SIMG_BINDGROUP_INDEX] = shd->wgpu.bgl_simg;
  15654. num_bgls += 1;
  15655. }
  15656. WGPUPipelineLayoutDescriptor wgpu_pl_desc;
  15657. _sg_clear(&wgpu_pl_desc, sizeof(wgpu_pl_desc));
  15658. wgpu_pl_desc.bindGroupLayoutCount = num_bgls;
  15659. wgpu_pl_desc.bindGroupLayouts = &wgpu_bgl[0];
  15660. const WGPUPipelineLayout wgpu_pip_layout = wgpuDeviceCreatePipelineLayout(_sg.wgpu.dev, &wgpu_pl_desc);
  15661. if (0 == wgpu_pip_layout) {
  15662. _SG_ERROR(WGPU_CREATE_PIPELINE_LAYOUT_FAILED);
  15663. return SG_RESOURCESTATE_FAILED;
  15664. }
  15665. SOKOL_ASSERT(wgpu_pip_layout);
  15666. if (pip->cmn.is_compute) {
  15667. WGPUComputePipelineDescriptor wgpu_pip_desc;
  15668. _sg_clear(&wgpu_pip_desc, sizeof(wgpu_pip_desc));
  15669. wgpu_pip_desc.label = _sg_wgpu_stringview(desc->label);
  15670. wgpu_pip_desc.layout = wgpu_pip_layout;
  15671. wgpu_pip_desc.compute.module = shd->wgpu.compute_func.module;
  15672. wgpu_pip_desc.compute.entryPoint = shd->wgpu.compute_func.entry.buf;
  15673. pip->wgpu.cpip = wgpuDeviceCreateComputePipeline(_sg.wgpu.dev, &wgpu_pip_desc);
  15674. wgpuPipelineLayoutRelease(wgpu_pip_layout);
  15675. if (0 == pip->wgpu.cpip) {
  15676. _SG_ERROR(WGPU_CREATE_COMPUTE_PIPELINE_FAILED);
  15677. return SG_RESOURCESTATE_FAILED;
  15678. }
  15679. } else {
  15680. WGPUVertexBufferLayout wgpu_vb_layouts[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  15681. _sg_clear(wgpu_vb_layouts, sizeof(wgpu_vb_layouts));
  15682. WGPUVertexAttribute wgpu_vtx_attrs[SG_MAX_VERTEXBUFFER_BINDSLOTS][SG_MAX_VERTEX_ATTRIBUTES];
  15683. _sg_clear(wgpu_vtx_attrs, sizeof(wgpu_vtx_attrs));
  15684. int wgpu_vb_num = 0;
  15685. for (int vb_idx = 0; vb_idx < SG_MAX_VERTEXBUFFER_BINDSLOTS; vb_idx++, wgpu_vb_num++) {
  15686. const sg_vertex_buffer_layout_state* vbl_state = &desc->layout.buffers[vb_idx];
  15687. if (0 == vbl_state->stride) {
  15688. break;
  15689. }
  15690. wgpu_vb_layouts[vb_idx].arrayStride = (uint64_t)vbl_state->stride;
  15691. wgpu_vb_layouts[vb_idx].stepMode = _sg_wgpu_stepmode(vbl_state->step_func);
  15692. wgpu_vb_layouts[vb_idx].attributes = &wgpu_vtx_attrs[vb_idx][0];
  15693. }
  15694. for (int va_idx = 0; va_idx < SG_MAX_VERTEX_ATTRIBUTES; va_idx++) {
  15695. const sg_vertex_attr_state* va_state = &desc->layout.attrs[va_idx];
  15696. if (SG_VERTEXFORMAT_INVALID == va_state->format) {
  15697. break;
  15698. }
  15699. const int vb_idx = va_state->buffer_index;
  15700. SOKOL_ASSERT(vb_idx < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  15701. SOKOL_ASSERT(pip->cmn.vertex_buffer_layout_active[vb_idx]);
  15702. const size_t wgpu_attr_idx = wgpu_vb_layouts[vb_idx].attributeCount;
  15703. wgpu_vb_layouts[vb_idx].attributeCount += 1;
  15704. wgpu_vtx_attrs[vb_idx][wgpu_attr_idx].format = _sg_wgpu_vertexformat(va_state->format);
  15705. wgpu_vtx_attrs[vb_idx][wgpu_attr_idx].offset = (uint64_t)va_state->offset;
  15706. wgpu_vtx_attrs[vb_idx][wgpu_attr_idx].shaderLocation = (uint32_t)va_idx;
  15707. }
  15708. WGPURenderPipelineDescriptor wgpu_pip_desc;
  15709. _sg_clear(&wgpu_pip_desc, sizeof(wgpu_pip_desc));
  15710. WGPUDepthStencilState wgpu_ds_state;
  15711. _sg_clear(&wgpu_ds_state, sizeof(wgpu_ds_state));
  15712. WGPUFragmentState wgpu_frag_state;
  15713. _sg_clear(&wgpu_frag_state, sizeof(wgpu_frag_state));
  15714. WGPUColorTargetState wgpu_ctgt_state[SG_MAX_COLOR_ATTACHMENTS];
  15715. _sg_clear(&wgpu_ctgt_state, sizeof(wgpu_ctgt_state));
  15716. WGPUBlendState wgpu_blend_state[SG_MAX_COLOR_ATTACHMENTS];
  15717. _sg_clear(&wgpu_blend_state, sizeof(wgpu_blend_state));
  15718. wgpu_pip_desc.label = _sg_wgpu_stringview(desc->label);
  15719. wgpu_pip_desc.layout = wgpu_pip_layout;
  15720. wgpu_pip_desc.vertex.module = shd->wgpu.vertex_func.module;
  15721. wgpu_pip_desc.vertex.entryPoint = shd->wgpu.vertex_func.entry.buf;
  15722. wgpu_pip_desc.vertex.bufferCount = (size_t)wgpu_vb_num;
  15723. wgpu_pip_desc.vertex.buffers = &wgpu_vb_layouts[0];
  15724. wgpu_pip_desc.primitive.topology = _sg_wgpu_topology(desc->primitive_type);
  15725. wgpu_pip_desc.primitive.stripIndexFormat = _sg_wgpu_stripindexformat(desc->primitive_type, desc->index_type);
  15726. wgpu_pip_desc.primitive.frontFace = _sg_wgpu_frontface(desc->face_winding);
  15727. wgpu_pip_desc.primitive.cullMode = _sg_wgpu_cullmode(desc->cull_mode);
  15728. if (SG_PIXELFORMAT_NONE != desc->depth.pixel_format) {
  15729. wgpu_ds_state.format = _sg_wgpu_textureformat(desc->depth.pixel_format);
  15730. wgpu_ds_state.depthWriteEnabled = _sg_wgpu_optional_bool(desc->depth.write_enabled);
  15731. wgpu_ds_state.depthCompare = _sg_wgpu_comparefunc(desc->depth.compare);
  15732. wgpu_ds_state.stencilFront.compare = _sg_wgpu_comparefunc(desc->stencil.front.compare);
  15733. wgpu_ds_state.stencilFront.failOp = _sg_wgpu_stencilop(desc->stencil.front.fail_op);
  15734. wgpu_ds_state.stencilFront.depthFailOp = _sg_wgpu_stencilop(desc->stencil.front.depth_fail_op);
  15735. wgpu_ds_state.stencilFront.passOp = _sg_wgpu_stencilop(desc->stencil.front.pass_op);
  15736. wgpu_ds_state.stencilBack.compare = _sg_wgpu_comparefunc(desc->stencil.back.compare);
  15737. wgpu_ds_state.stencilBack.failOp = _sg_wgpu_stencilop(desc->stencil.back.fail_op);
  15738. wgpu_ds_state.stencilBack.depthFailOp = _sg_wgpu_stencilop(desc->stencil.back.depth_fail_op);
  15739. wgpu_ds_state.stencilBack.passOp = _sg_wgpu_stencilop(desc->stencil.back.pass_op);
  15740. wgpu_ds_state.stencilReadMask = desc->stencil.read_mask;
  15741. wgpu_ds_state.stencilWriteMask = desc->stencil.write_mask;
  15742. wgpu_ds_state.depthBias = (int32_t)desc->depth.bias;
  15743. wgpu_ds_state.depthBiasSlopeScale = desc->depth.bias_slope_scale;
  15744. wgpu_ds_state.depthBiasClamp = desc->depth.bias_clamp;
  15745. wgpu_pip_desc.depthStencil = &wgpu_ds_state;
  15746. }
  15747. wgpu_pip_desc.multisample.count = (uint32_t)desc->sample_count;
  15748. wgpu_pip_desc.multisample.mask = 0xFFFFFFFF;
  15749. wgpu_pip_desc.multisample.alphaToCoverageEnabled = desc->alpha_to_coverage_enabled;
  15750. if (desc->color_count > 0) {
  15751. wgpu_frag_state.module = shd->wgpu.fragment_func.module;
  15752. wgpu_frag_state.entryPoint = shd->wgpu.fragment_func.entry.buf;
  15753. wgpu_frag_state.targetCount = (size_t)desc->color_count;
  15754. wgpu_frag_state.targets = &wgpu_ctgt_state[0];
  15755. for (int i = 0; i < desc->color_count; i++) {
  15756. SOKOL_ASSERT(i < SG_MAX_COLOR_ATTACHMENTS);
  15757. wgpu_ctgt_state[i].format = _sg_wgpu_textureformat(desc->colors[i].pixel_format);
  15758. wgpu_ctgt_state[i].writeMask = _sg_wgpu_colorwritemask(desc->colors[i].write_mask);
  15759. if (desc->colors[i].blend.enabled) {
  15760. wgpu_ctgt_state[i].blend = &wgpu_blend_state[i];
  15761. wgpu_blend_state[i].color.operation = _sg_wgpu_blendop(desc->colors[i].blend.op_rgb);
  15762. wgpu_blend_state[i].color.srcFactor = _sg_wgpu_blendfactor(desc->colors[i].blend.src_factor_rgb);
  15763. wgpu_blend_state[i].color.dstFactor = _sg_wgpu_blendfactor(desc->colors[i].blend.dst_factor_rgb);
  15764. wgpu_blend_state[i].alpha.operation = _sg_wgpu_blendop(desc->colors[i].blend.op_alpha);
  15765. wgpu_blend_state[i].alpha.srcFactor = _sg_wgpu_blendfactor(desc->colors[i].blend.src_factor_alpha);
  15766. wgpu_blend_state[i].alpha.dstFactor = _sg_wgpu_blendfactor(desc->colors[i].blend.dst_factor_alpha);
  15767. }
  15768. }
  15769. wgpu_pip_desc.fragment = &wgpu_frag_state;
  15770. }
  15771. pip->wgpu.rpip = wgpuDeviceCreateRenderPipeline(_sg.wgpu.dev, &wgpu_pip_desc);
  15772. wgpuPipelineLayoutRelease(wgpu_pip_layout);
  15773. if (0 == pip->wgpu.rpip) {
  15774. _SG_ERROR(WGPU_CREATE_RENDER_PIPELINE_FAILED);
  15775. return SG_RESOURCESTATE_FAILED;
  15776. }
  15777. }
  15778. return SG_RESOURCESTATE_VALID;
  15779. }
  15780. _SOKOL_PRIVATE void _sg_wgpu_discard_pipeline(_sg_pipeline_t* pip) {
  15781. SOKOL_ASSERT(pip);
  15782. _sg_wgpu_bindgroups_cache_invalidate(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_PIPELINE, pip->slot.id);
  15783. if (pip == _sg.wgpu.cur_pipeline) {
  15784. _sg.wgpu.cur_pipeline = 0;
  15785. _sg.wgpu.cur_pipeline_id.id = SG_INVALID_ID;
  15786. }
  15787. if (pip->wgpu.rpip) {
  15788. wgpuRenderPipelineRelease(pip->wgpu.rpip);
  15789. pip->wgpu.rpip = 0;
  15790. }
  15791. if (pip->wgpu.cpip) {
  15792. wgpuComputePipelineRelease(pip->wgpu.cpip);
  15793. pip->wgpu.cpip = 0;
  15794. }
  15795. }
  15796. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_attachments(_sg_attachments_t* atts, const _sg_attachments_ptrs_t* atts_ptrs, const sg_attachments_desc* desc) {
  15797. SOKOL_ASSERT(atts && atts_ptrs && desc);
  15798. // copy image pointers and create renderable wgpu texture views
  15799. for (int i = 0; i < atts->cmn.num_colors; i++) {
  15800. const sg_attachment_desc* color_desc = &desc->colors[i];
  15801. _SOKOL_UNUSED(color_desc);
  15802. SOKOL_ASSERT(color_desc->image.id != SG_INVALID_ID);
  15803. SOKOL_ASSERT(0 == atts->wgpu.colors[i].image);
  15804. SOKOL_ASSERT(atts_ptrs->color_images[i]);
  15805. _sg_image_t* clr_img = atts_ptrs->color_images[i];
  15806. SOKOL_ASSERT(clr_img->slot.id == color_desc->image.id);
  15807. SOKOL_ASSERT(_sg_is_valid_attachment_color_format(clr_img->cmn.pixel_format));
  15808. SOKOL_ASSERT(clr_img->wgpu.tex);
  15809. atts->wgpu.colors[i].image = clr_img;
  15810. WGPUTextureViewDescriptor wgpu_color_view_desc;
  15811. _sg_clear(&wgpu_color_view_desc, sizeof(wgpu_color_view_desc));
  15812. wgpu_color_view_desc.baseMipLevel = (uint32_t) color_desc->mip_level;
  15813. wgpu_color_view_desc.mipLevelCount = 1;
  15814. wgpu_color_view_desc.baseArrayLayer = (uint32_t) color_desc->slice;
  15815. wgpu_color_view_desc.arrayLayerCount = 1;
  15816. atts->wgpu.colors[i].view = wgpuTextureCreateView(clr_img->wgpu.tex, &wgpu_color_view_desc);
  15817. if (0 == atts->wgpu.colors[i].view) {
  15818. _SG_ERROR(WGPU_ATTACHMENTS_CREATE_TEXTURE_VIEW_FAILED);
  15819. return SG_RESOURCESTATE_FAILED;
  15820. }
  15821. const sg_attachment_desc* resolve_desc = &desc->resolves[i];
  15822. if (resolve_desc->image.id != SG_INVALID_ID) {
  15823. SOKOL_ASSERT(0 == atts->wgpu.resolves[i].image);
  15824. SOKOL_ASSERT(atts_ptrs->resolve_images[i]);
  15825. _sg_image_t* rsv_img = atts_ptrs->resolve_images[i];
  15826. SOKOL_ASSERT(rsv_img->slot.id == resolve_desc->image.id);
  15827. SOKOL_ASSERT(clr_img->cmn.pixel_format == rsv_img->cmn.pixel_format);
  15828. SOKOL_ASSERT(rsv_img->wgpu.tex);
  15829. atts->wgpu.resolves[i].image = rsv_img;
  15830. WGPUTextureViewDescriptor wgpu_resolve_view_desc;
  15831. _sg_clear(&wgpu_resolve_view_desc, sizeof(wgpu_resolve_view_desc));
  15832. wgpu_resolve_view_desc.baseMipLevel = (uint32_t) resolve_desc->mip_level;
  15833. wgpu_resolve_view_desc.mipLevelCount = 1;
  15834. wgpu_resolve_view_desc.baseArrayLayer = (uint32_t) resolve_desc->slice;
  15835. wgpu_resolve_view_desc.arrayLayerCount = 1;
  15836. atts->wgpu.resolves[i].view = wgpuTextureCreateView(rsv_img->wgpu.tex, &wgpu_resolve_view_desc);
  15837. if (0 == atts->wgpu.resolves[i].view) {
  15838. _SG_ERROR(WGPU_ATTACHMENTS_CREATE_TEXTURE_VIEW_FAILED);
  15839. return SG_RESOURCESTATE_FAILED;
  15840. }
  15841. }
  15842. }
  15843. SOKOL_ASSERT(0 == atts->wgpu.depth_stencil.image);
  15844. const sg_attachment_desc* ds_desc = &desc->depth_stencil;
  15845. if (ds_desc->image.id != SG_INVALID_ID) {
  15846. SOKOL_ASSERT(atts_ptrs->ds_image);
  15847. _sg_image_t* ds_img =atts_ptrs->ds_image;
  15848. SOKOL_ASSERT(ds_img->slot.id == ds_desc->image.id);
  15849. SOKOL_ASSERT(_sg_is_valid_attachment_depth_format(ds_img->cmn.pixel_format));
  15850. SOKOL_ASSERT(ds_img->wgpu.tex);
  15851. atts->wgpu.depth_stencil.image = ds_img;
  15852. WGPUTextureViewDescriptor wgpu_ds_view_desc;
  15853. _sg_clear(&wgpu_ds_view_desc, sizeof(wgpu_ds_view_desc));
  15854. wgpu_ds_view_desc.baseMipLevel = (uint32_t) ds_desc->mip_level;
  15855. wgpu_ds_view_desc.mipLevelCount = 1;
  15856. wgpu_ds_view_desc.baseArrayLayer = (uint32_t) ds_desc->slice;
  15857. wgpu_ds_view_desc.arrayLayerCount = 1;
  15858. atts->wgpu.depth_stencil.view = wgpuTextureCreateView(ds_img->wgpu.tex, &wgpu_ds_view_desc);
  15859. if (0 == atts->wgpu.depth_stencil.view) {
  15860. _SG_ERROR(WGPU_ATTACHMENTS_CREATE_TEXTURE_VIEW_FAILED);
  15861. return SG_RESOURCESTATE_FAILED;
  15862. }
  15863. }
  15864. for (int i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  15865. const sg_attachment_desc* storage_desc = &desc->storages[i];
  15866. if (storage_desc->image.id != SG_INVALID_ID) {
  15867. SOKOL_ASSERT(0 == atts->wgpu.storages[i].image);
  15868. SOKOL_ASSERT(atts_ptrs->storage_images[i]);
  15869. _sg_image_t* stg_img = atts_ptrs->storage_images[i];
  15870. SOKOL_ASSERT(stg_img->slot.id == storage_desc->image.id);
  15871. SOKOL_ASSERT(_sg_is_valid_attachment_storage_format(stg_img->cmn.pixel_format));
  15872. atts->wgpu.storages[i].image = stg_img;
  15873. WGPUTextureViewDescriptor wgpu_storage_view_desc;
  15874. _sg_clear(&wgpu_storage_view_desc, sizeof(wgpu_storage_view_desc));
  15875. wgpu_storage_view_desc.baseMipLevel = (uint32_t) storage_desc->mip_level;
  15876. wgpu_storage_view_desc.mipLevelCount = 1;
  15877. wgpu_storage_view_desc.baseArrayLayer = (uint32_t) storage_desc->slice;
  15878. wgpu_storage_view_desc.arrayLayerCount = 1;
  15879. if (_sg_is_depth_or_depth_stencil_format(stg_img->cmn.pixel_format)) {
  15880. wgpu_storage_view_desc.aspect = WGPUTextureAspect_DepthOnly;
  15881. } else {
  15882. wgpu_storage_view_desc.aspect = WGPUTextureAspect_All;
  15883. }
  15884. atts->wgpu.storages[i].view = wgpuTextureCreateView(stg_img->wgpu.tex, &wgpu_storage_view_desc);
  15885. if (0 == atts->wgpu.storages[i].view) {
  15886. _SG_ERROR(WGPU_ATTACHMENTS_CREATE_TEXTURE_VIEW_FAILED);
  15887. return SG_RESOURCESTATE_FAILED;
  15888. }
  15889. }
  15890. }
  15891. return SG_RESOURCESTATE_VALID;
  15892. }
  15893. _SOKOL_PRIVATE void _sg_wgpu_discard_attachments(_sg_attachments_t* atts) {
  15894. SOKOL_ASSERT(atts);
  15895. for (int i = 0; i < atts->cmn.num_colors; i++) {
  15896. if (atts->wgpu.colors[i].view) {
  15897. wgpuTextureViewRelease(atts->wgpu.colors[i].view);
  15898. atts->wgpu.colors[i].view = 0;
  15899. }
  15900. if (atts->wgpu.resolves[i].view) {
  15901. wgpuTextureViewRelease(atts->wgpu.resolves[i].view);
  15902. atts->wgpu.resolves[i].view = 0;
  15903. }
  15904. }
  15905. if (atts->wgpu.depth_stencil.view) {
  15906. wgpuTextureViewRelease(atts->wgpu.depth_stencil.view);
  15907. atts->wgpu.depth_stencil.view = 0;
  15908. }
  15909. for (int i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  15910. if (atts->wgpu.storages[i].view) {
  15911. wgpuTextureViewRelease(atts->wgpu.storages[i].view);
  15912. atts->wgpu.storages[i].view = 0;
  15913. }
  15914. }
  15915. }
  15916. _SOKOL_PRIVATE void _sg_wgpu_init_color_att(WGPURenderPassColorAttachment* wgpu_att, const sg_color_attachment_action* action, WGPUTextureView color_view, WGPUTextureView resolve_view) {
  15917. wgpu_att->depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
  15918. wgpu_att->view = color_view;
  15919. wgpu_att->resolveTarget = resolve_view;
  15920. wgpu_att->loadOp = _sg_wgpu_load_op(color_view, action->load_action);
  15921. wgpu_att->storeOp = _sg_wgpu_store_op(color_view, action->store_action);
  15922. wgpu_att->clearValue.r = action->clear_value.r;
  15923. wgpu_att->clearValue.g = action->clear_value.g;
  15924. wgpu_att->clearValue.b = action->clear_value.b;
  15925. wgpu_att->clearValue.a = action->clear_value.a;
  15926. }
  15927. _SOKOL_PRIVATE void _sg_wgpu_init_ds_att(WGPURenderPassDepthStencilAttachment* wgpu_att, const sg_pass_action* action, sg_pixel_format fmt, WGPUTextureView view) {
  15928. wgpu_att->view = view;
  15929. wgpu_att->depthLoadOp = _sg_wgpu_load_op(view, action->depth.load_action);
  15930. wgpu_att->depthStoreOp = _sg_wgpu_store_op(view, action->depth.store_action);
  15931. wgpu_att->depthClearValue = action->depth.clear_value;
  15932. wgpu_att->depthReadOnly = false;
  15933. if (_sg_is_depth_stencil_format(fmt)) {
  15934. wgpu_att->stencilLoadOp = _sg_wgpu_load_op(view, action->stencil.load_action);
  15935. wgpu_att->stencilStoreOp = _sg_wgpu_store_op(view, action->stencil.store_action);
  15936. } else {
  15937. wgpu_att->stencilLoadOp = WGPULoadOp_Undefined;
  15938. wgpu_att->stencilStoreOp = WGPUStoreOp_Undefined;
  15939. }
  15940. wgpu_att->stencilClearValue = action->stencil.clear_value;
  15941. wgpu_att->stencilReadOnly = false;
  15942. }
  15943. _SOKOL_PRIVATE void _sg_wgpu_begin_compute_pass(const sg_pass* pass) {
  15944. WGPUComputePassDescriptor wgpu_pass_desc;
  15945. _sg_clear(&wgpu_pass_desc, sizeof(wgpu_pass_desc));
  15946. wgpu_pass_desc.label = _sg_wgpu_stringview(pass->label);
  15947. _sg.wgpu.cpass_enc = wgpuCommandEncoderBeginComputePass(_sg.wgpu.cmd_enc, &wgpu_pass_desc);
  15948. SOKOL_ASSERT(_sg.wgpu.cpass_enc);
  15949. // clear initial bindings
  15950. wgpuComputePassEncoderSetBindGroup(_sg.wgpu.cpass_enc, _SG_WGPU_UB_BINDGROUP_INDEX, _sg.wgpu.empty_bind_group, 0, 0);
  15951. wgpuComputePassEncoderSetBindGroup(_sg.wgpu.cpass_enc, _SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX, _sg.wgpu.empty_bind_group, 0, 0);
  15952. wgpuComputePassEncoderSetBindGroup(_sg.wgpu.cpass_enc, _SG_WGPU_SIMG_BINDGROUP_INDEX, _sg.wgpu.empty_bind_group, 0, 0);
  15953. _sg_stats_add(wgpu.bindings.num_set_bindgroup, 1);
  15954. }
  15955. _SOKOL_PRIVATE void _sg_wgpu_begin_render_pass(const sg_pass* pass) {
  15956. const _sg_attachments_t* atts = _sg.cur_pass.atts;
  15957. const sg_swapchain* swapchain = &pass->swapchain;
  15958. const sg_pass_action* action = &pass->action;
  15959. WGPURenderPassDescriptor wgpu_pass_desc;
  15960. WGPURenderPassColorAttachment wgpu_color_att[SG_MAX_COLOR_ATTACHMENTS];
  15961. WGPURenderPassDepthStencilAttachment wgpu_ds_att;
  15962. _sg_clear(&wgpu_pass_desc, sizeof(wgpu_pass_desc));
  15963. _sg_clear(&wgpu_color_att, sizeof(wgpu_color_att));
  15964. _sg_clear(&wgpu_ds_att, sizeof(wgpu_ds_att));
  15965. wgpu_pass_desc.label = _sg_wgpu_stringview(pass->label);
  15966. if (atts) {
  15967. SOKOL_ASSERT(atts->slot.state == SG_RESOURCESTATE_VALID);
  15968. for (int i = 0; i < atts->cmn.num_colors; i++) {
  15969. _sg_wgpu_init_color_att(&wgpu_color_att[i], &action->colors[i], atts->wgpu.colors[i].view, atts->wgpu.resolves[i].view);
  15970. }
  15971. wgpu_pass_desc.colorAttachmentCount = (size_t)atts->cmn.num_colors;
  15972. wgpu_pass_desc.colorAttachments = &wgpu_color_att[0];
  15973. if (atts->wgpu.depth_stencil.image) {
  15974. _sg_wgpu_init_ds_att(&wgpu_ds_att, action, atts->wgpu.depth_stencil.image->cmn.pixel_format, atts->wgpu.depth_stencil.view);
  15975. wgpu_pass_desc.depthStencilAttachment = &wgpu_ds_att;
  15976. }
  15977. } else {
  15978. WGPUTextureView wgpu_color_view = (WGPUTextureView) swapchain->wgpu.render_view;
  15979. WGPUTextureView wgpu_resolve_view = (WGPUTextureView) swapchain->wgpu.resolve_view;
  15980. WGPUTextureView wgpu_depth_stencil_view = (WGPUTextureView) swapchain->wgpu.depth_stencil_view;
  15981. _sg_wgpu_init_color_att(&wgpu_color_att[0], &action->colors[0], wgpu_color_view, wgpu_resolve_view);
  15982. wgpu_pass_desc.colorAttachmentCount = 1;
  15983. wgpu_pass_desc.colorAttachments = &wgpu_color_att[0];
  15984. if (wgpu_depth_stencil_view) {
  15985. SOKOL_ASSERT(swapchain->depth_format > SG_PIXELFORMAT_NONE);
  15986. _sg_wgpu_init_ds_att(&wgpu_ds_att, action, swapchain->depth_format, wgpu_depth_stencil_view);
  15987. wgpu_pass_desc.depthStencilAttachment = &wgpu_ds_att;
  15988. }
  15989. }
  15990. _sg.wgpu.rpass_enc = wgpuCommandEncoderBeginRenderPass(_sg.wgpu.cmd_enc, &wgpu_pass_desc);
  15991. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  15992. wgpuRenderPassEncoderSetBindGroup(_sg.wgpu.rpass_enc, _SG_WGPU_UB_BINDGROUP_INDEX, _sg.wgpu.empty_bind_group, 0, 0);
  15993. wgpuRenderPassEncoderSetBindGroup(_sg.wgpu.rpass_enc, _SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX, _sg.wgpu.empty_bind_group, 0, 0);
  15994. _sg_stats_add(wgpu.bindings.num_set_bindgroup, 1);
  15995. }
  15996. _SOKOL_PRIVATE void _sg_wgpu_begin_pass(const sg_pass* pass) {
  15997. SOKOL_ASSERT(pass);
  15998. SOKOL_ASSERT(_sg.wgpu.dev);
  15999. SOKOL_ASSERT(_sg.wgpu.cmd_enc);
  16000. SOKOL_ASSERT(0 == _sg.wgpu.rpass_enc);
  16001. SOKOL_ASSERT(0 == _sg.wgpu.cpass_enc);
  16002. _sg.wgpu.cur_pipeline = 0;
  16003. _sg.wgpu.cur_pipeline_id.id = SG_INVALID_ID;
  16004. _sg_wgpu_bindings_cache_clear();
  16005. if (pass->compute) {
  16006. _sg_wgpu_begin_compute_pass(pass);
  16007. } else {
  16008. _sg_wgpu_begin_render_pass(pass);
  16009. }
  16010. }
  16011. _SOKOL_PRIVATE void _sg_wgpu_end_pass(void) {
  16012. if (_sg.wgpu.rpass_enc) {
  16013. wgpuRenderPassEncoderEnd(_sg.wgpu.rpass_enc);
  16014. wgpuRenderPassEncoderRelease(_sg.wgpu.rpass_enc);
  16015. _sg.wgpu.rpass_enc = 0;
  16016. }
  16017. if (_sg.wgpu.cpass_enc) {
  16018. wgpuComputePassEncoderEnd(_sg.wgpu.cpass_enc);
  16019. wgpuComputePassEncoderRelease(_sg.wgpu.cpass_enc);
  16020. _sg.wgpu.cpass_enc = 0;
  16021. }
  16022. }
  16023. _SOKOL_PRIVATE void _sg_wgpu_commit(void) {
  16024. SOKOL_ASSERT(_sg.wgpu.cmd_enc);
  16025. _sg_wgpu_uniform_buffer_on_commit();
  16026. WGPUCommandBufferDescriptor cmd_buf_desc;
  16027. _sg_clear(&cmd_buf_desc, sizeof(cmd_buf_desc));
  16028. WGPUCommandBuffer wgpu_cmd_buf = wgpuCommandEncoderFinish(_sg.wgpu.cmd_enc, &cmd_buf_desc);
  16029. SOKOL_ASSERT(wgpu_cmd_buf);
  16030. wgpuCommandEncoderRelease(_sg.wgpu.cmd_enc);
  16031. _sg.wgpu.cmd_enc = 0;
  16032. wgpuQueueSubmit(_sg.wgpu.queue, 1, &wgpu_cmd_buf);
  16033. wgpuCommandBufferRelease(wgpu_cmd_buf);
  16034. // create a new render-command-encoder for next frame
  16035. WGPUCommandEncoderDescriptor cmd_enc_desc;
  16036. _sg_clear(&cmd_enc_desc, sizeof(cmd_enc_desc));
  16037. _sg.wgpu.cmd_enc = wgpuDeviceCreateCommandEncoder(_sg.wgpu.dev, &cmd_enc_desc);
  16038. }
  16039. _SOKOL_PRIVATE void _sg_wgpu_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  16040. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  16041. // FIXME FIXME FIXME: CLIPPING THE VIEWPORT HERE IS WRONG!!!
  16042. // (but currently required because WebGPU insists that the viewport rectangle must be
  16043. // fully contained inside the framebuffer, but this doesn't make any sense, and also
  16044. // isn't required by the backend APIs)
  16045. const _sg_recti_t clip = _sg_clipi(x, y, w, h, _sg.cur_pass.width, _sg.cur_pass.height);
  16046. float xf = (float) clip.x;
  16047. float yf = (float) (origin_top_left ? clip.y : (_sg.cur_pass.height - (clip.y + clip.h)));
  16048. float wf = (float) clip.w;
  16049. float hf = (float) clip.h;
  16050. wgpuRenderPassEncoderSetViewport(_sg.wgpu.rpass_enc, xf, yf, wf, hf, 0.0f, 1.0f);
  16051. }
  16052. _SOKOL_PRIVATE void _sg_wgpu_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  16053. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  16054. const _sg_recti_t clip = _sg_clipi(x, y, w, h, _sg.cur_pass.width, _sg.cur_pass.height);
  16055. uint32_t sx = (uint32_t) clip.x;
  16056. uint32_t sy = (uint32_t) (origin_top_left ? clip.y : (_sg.cur_pass.height - (clip.y + clip.h)));
  16057. uint32_t sw = (uint32_t) clip.w;
  16058. uint32_t sh = (uint32_t) clip.h;
  16059. wgpuRenderPassEncoderSetScissorRect(_sg.wgpu.rpass_enc, sx, sy, sw, sh);
  16060. }
  16061. _SOKOL_PRIVATE void _sg_wgpu_set_ub_bindgroup(const _sg_shader_t* shd) {
  16062. // NOTE: dynamic offsets must be in binding order, not in BindGroupEntry order
  16063. SOKOL_ASSERT(shd->wgpu.ub_num_dynoffsets < SG_MAX_UNIFORMBLOCK_BINDSLOTS);
  16064. uint32_t dyn_offsets[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  16065. _sg_clear(dyn_offsets, sizeof(dyn_offsets));
  16066. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  16067. if (shd->cmn.uniform_blocks[i].stage == SG_SHADERSTAGE_NONE) {
  16068. continue;
  16069. }
  16070. uint8_t dynoffset_index = shd->wgpu.ub_dynoffsets[i];
  16071. SOKOL_ASSERT(dynoffset_index < shd->wgpu.ub_num_dynoffsets);
  16072. dyn_offsets[dynoffset_index] = _sg.wgpu.uniform.bind_offsets[i];
  16073. }
  16074. if (_sg.cur_pass.is_compute) {
  16075. SOKOL_ASSERT(_sg.wgpu.cpass_enc);
  16076. wgpuComputePassEncoderSetBindGroup(_sg.wgpu.cpass_enc,
  16077. _SG_WGPU_UB_BINDGROUP_INDEX,
  16078. shd->wgpu.bg_ub,
  16079. shd->wgpu.ub_num_dynoffsets,
  16080. dyn_offsets);
  16081. } else {
  16082. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  16083. wgpuRenderPassEncoderSetBindGroup(_sg.wgpu.rpass_enc,
  16084. _SG_WGPU_UB_BINDGROUP_INDEX,
  16085. shd->wgpu.bg_ub,
  16086. shd->wgpu.ub_num_dynoffsets,
  16087. dyn_offsets);
  16088. }
  16089. }
  16090. _SOKOL_PRIVATE void _sg_wgpu_apply_pipeline(_sg_pipeline_t* pip) {
  16091. SOKOL_ASSERT(pip);
  16092. SOKOL_ASSERT(pip->shader && (pip->shader->slot.id == pip->cmn.shader_id.id));
  16093. _sg.wgpu.cur_pipeline = pip;
  16094. _sg.wgpu.cur_pipeline_id.id = pip->slot.id;
  16095. if (pip->cmn.is_compute) {
  16096. SOKOL_ASSERT(_sg.cur_pass.is_compute);
  16097. SOKOL_ASSERT(pip->wgpu.cpip);
  16098. SOKOL_ASSERT(_sg.wgpu.cpass_enc);
  16099. wgpuComputePassEncoderSetPipeline(_sg.wgpu.cpass_enc, pip->wgpu.cpip);
  16100. // adhoc-create a storage attachment bindgroup without going through the bindgroups cache
  16101. // FIXME: the 'resource view update' will get rid of this special case because then storage images
  16102. // will be regular resource bindings
  16103. if (pip->shader->wgpu.bgl_simg) {
  16104. _sg_stats_add(wgpu.bindings.num_create_bindgroup, 1);
  16105. _sg_shader_t* shd = pip->shader;
  16106. SOKOL_ASSERT(shd);
  16107. WGPUBindGroupLayout bgl = shd->wgpu.bgl_simg;
  16108. WGPUBindGroupEntry bg_entries[_SG_WGPU_MAX_SIMG_BINDGROUP_ENTRIES];
  16109. _sg_clear(&bg_entries, sizeof(bg_entries));
  16110. size_t bgl_index = 0;
  16111. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  16112. if (shd->cmn.storage_images[i].stage == SG_SHADERSTAGE_NONE) {
  16113. continue;
  16114. }
  16115. SOKOL_ASSERT(_sg.cur_pass.atts);
  16116. _sg_attachments_t* atts = _sg.cur_pass.atts;
  16117. SOKOL_ASSERT(atts->wgpu.storages[i].view);
  16118. WGPUBindGroupEntry* bg_entry = &bg_entries[bgl_index];
  16119. bg_entry->binding = shd->wgpu.simg_grp2_bnd_n[i];
  16120. bg_entry->textureView = atts->wgpu.storages[i].view;
  16121. bgl_index++;
  16122. }
  16123. SOKOL_ASSERT(bgl_index > 0);
  16124. WGPUBindGroupDescriptor bg_desc;
  16125. _sg_clear(&bg_desc, sizeof(bg_desc));
  16126. bg_desc.layout = bgl;
  16127. bg_desc.entryCount = bgl_index;
  16128. bg_desc.entries = bg_entries;
  16129. WGPUBindGroup bg = wgpuDeviceCreateBindGroup(_sg.wgpu.dev, &bg_desc);
  16130. if (bg) {
  16131. wgpuComputePassEncoderSetBindGroup(_sg.wgpu.cpass_enc, _SG_WGPU_SIMG_BINDGROUP_INDEX, bg, 0, 0);
  16132. wgpuBindGroupRelease(bg);
  16133. } else {
  16134. _SG_ERROR(WGPU_CREATEBINDGROUP_FAILED);
  16135. }
  16136. } else {
  16137. // no storage attachment bindings, clear bindgroup slot
  16138. wgpuComputePassEncoderSetBindGroup(_sg.wgpu.cpass_enc, _SG_WGPU_SIMG_BINDGROUP_INDEX, _sg.wgpu.empty_bind_group, 0, 0);
  16139. }
  16140. } else {
  16141. SOKOL_ASSERT(!_sg.cur_pass.is_compute);
  16142. SOKOL_ASSERT(pip->wgpu.rpip);
  16143. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  16144. _sg.wgpu.use_indexed_draw = (pip->cmn.index_type != SG_INDEXTYPE_NONE);
  16145. wgpuRenderPassEncoderSetPipeline(_sg.wgpu.rpass_enc, pip->wgpu.rpip);
  16146. wgpuRenderPassEncoderSetBlendConstant(_sg.wgpu.rpass_enc, &pip->wgpu.blend_color);
  16147. wgpuRenderPassEncoderSetStencilReference(_sg.wgpu.rpass_enc, pip->cmn.stencil.ref);
  16148. }
  16149. // bind groups must be set because pipelines without uniform blocks or resource bindings
  16150. // will still create 'empty' BindGroupLayouts
  16151. _sg_wgpu_set_ub_bindgroup(pip->shader);
  16152. _sg_wgpu_set_bindgroup(_SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX, 0); // this will set the 'empty bind group'
  16153. }
  16154. _SOKOL_PRIVATE bool _sg_wgpu_apply_bindings(_sg_bindings_ptrs_t* bnd) {
  16155. SOKOL_ASSERT(bnd);
  16156. SOKOL_ASSERT(bnd->pip->shader && (bnd->pip->cmn.shader_id.id == bnd->pip->shader->slot.id));
  16157. bool retval = true;
  16158. if (!_sg.cur_pass.is_compute) {
  16159. retval &= _sg_wgpu_apply_index_buffer(bnd);
  16160. retval &= _sg_wgpu_apply_vertex_buffers(bnd);
  16161. }
  16162. retval &= _sg_wgpu_apply_bindings_bindgroup(bnd);
  16163. return retval;
  16164. }
  16165. _SOKOL_PRIVATE void _sg_wgpu_apply_uniforms(int ub_slot, const sg_range* data) {
  16166. const uint32_t alignment = _sg.wgpu.limits.limits.minUniformBufferOffsetAlignment;
  16167. SOKOL_ASSERT(_sg.wgpu.uniform.staging);
  16168. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  16169. SOKOL_ASSERT((_sg.wgpu.uniform.offset + data->size) <= _sg.wgpu.uniform.num_bytes);
  16170. SOKOL_ASSERT((_sg.wgpu.uniform.offset & (alignment - 1)) == 0);
  16171. const _sg_pipeline_t* pip = _sg.wgpu.cur_pipeline;
  16172. SOKOL_ASSERT(pip && pip->shader);
  16173. SOKOL_ASSERT(pip->slot.id == _sg.wgpu.cur_pipeline_id.id);
  16174. const _sg_shader_t* shd = pip->shader;
  16175. SOKOL_ASSERT(shd->slot.id == pip->cmn.shader_id.id);
  16176. SOKOL_ASSERT(data->size == shd->cmn.uniform_blocks[ub_slot].size);
  16177. SOKOL_ASSERT(data->size <= _SG_WGPU_MAX_UNIFORM_UPDATE_SIZE);
  16178. _sg_stats_add(wgpu.uniforms.num_set_bindgroup, 1);
  16179. memcpy(_sg.wgpu.uniform.staging + _sg.wgpu.uniform.offset, data->ptr, data->size);
  16180. _sg.wgpu.uniform.bind_offsets[ub_slot] = _sg.wgpu.uniform.offset;
  16181. _sg.wgpu.uniform.offset = _sg_roundup_u32(_sg.wgpu.uniform.offset + (uint32_t)data->size, alignment);
  16182. _sg_wgpu_set_ub_bindgroup(shd);
  16183. }
  16184. _SOKOL_PRIVATE void _sg_wgpu_draw(int base_element, int num_elements, int num_instances) {
  16185. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  16186. SOKOL_ASSERT(_sg.wgpu.cur_pipeline && (_sg.wgpu.cur_pipeline->slot.id == _sg.wgpu.cur_pipeline_id.id));
  16187. if (SG_INDEXTYPE_NONE != _sg.wgpu.cur_pipeline->cmn.index_type) {
  16188. wgpuRenderPassEncoderDrawIndexed(_sg.wgpu.rpass_enc, (uint32_t)num_elements, (uint32_t)num_instances, (uint32_t)base_element, 0, 0);
  16189. } else {
  16190. wgpuRenderPassEncoderDraw(_sg.wgpu.rpass_enc, (uint32_t)num_elements, (uint32_t)num_instances, (uint32_t)base_element, 0);
  16191. }
  16192. }
  16193. _SOKOL_PRIVATE void _sg_wgpu_dispatch(int num_groups_x, int num_groups_y, int num_groups_z) {
  16194. SOKOL_ASSERT(_sg.wgpu.cpass_enc);
  16195. wgpuComputePassEncoderDispatchWorkgroups(_sg.wgpu.cpass_enc,
  16196. (uint32_t)num_groups_x,
  16197. (uint32_t)num_groups_y,
  16198. (uint32_t)num_groups_z);
  16199. }
  16200. _SOKOL_PRIVATE void _sg_wgpu_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  16201. SOKOL_ASSERT(data && data->ptr && (data->size > 0));
  16202. SOKOL_ASSERT(buf);
  16203. _sg_wgpu_copy_buffer_data(buf, 0, data);
  16204. }
  16205. _SOKOL_PRIVATE void _sg_wgpu_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  16206. SOKOL_ASSERT(data && data->ptr && (data->size > 0));
  16207. _SOKOL_UNUSED(new_frame);
  16208. _sg_wgpu_copy_buffer_data(buf, (uint64_t)buf->cmn.append_pos, data);
  16209. }
  16210. _SOKOL_PRIVATE void _sg_wgpu_update_image(_sg_image_t* img, const sg_image_data* data) {
  16211. SOKOL_ASSERT(img && data);
  16212. _sg_wgpu_copy_image_data(img, img->wgpu.tex, data);
  16213. }
  16214. #endif
  16215. // ██████ ███████ ███ ██ ███████ ██████ ██ ██████ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  16216. // ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  16217. // ██ ███ █████ ██ ██ ██ █████ ██████ ██ ██ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  16218. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  16219. // ██████ ███████ ██ ████ ███████ ██ ██ ██ ██████ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  16220. //
  16221. // >>generic backend
  16222. static inline void _sg_setup_backend(const sg_desc* desc) {
  16223. #if defined(_SOKOL_ANY_GL)
  16224. _sg_gl_setup_backend(desc);
  16225. #elif defined(SOKOL_METAL)
  16226. _sg_mtl_setup_backend(desc);
  16227. #elif defined(SOKOL_D3D11)
  16228. _sg_d3d11_setup_backend(desc);
  16229. #elif defined(SOKOL_WGPU)
  16230. _sg_wgpu_setup_backend(desc);
  16231. #elif defined(SOKOL_DUMMY_BACKEND)
  16232. _sg_dummy_setup_backend(desc);
  16233. #else
  16234. #error("INVALID BACKEND");
  16235. #endif
  16236. }
  16237. static inline void _sg_discard_backend(void) {
  16238. #if defined(_SOKOL_ANY_GL)
  16239. _sg_gl_discard_backend();
  16240. #elif defined(SOKOL_METAL)
  16241. _sg_mtl_discard_backend();
  16242. #elif defined(SOKOL_D3D11)
  16243. _sg_d3d11_discard_backend();
  16244. #elif defined(SOKOL_WGPU)
  16245. _sg_wgpu_discard_backend();
  16246. #elif defined(SOKOL_DUMMY_BACKEND)
  16247. _sg_dummy_discard_backend();
  16248. #else
  16249. #error("INVALID BACKEND");
  16250. #endif
  16251. }
  16252. static inline void _sg_reset_state_cache(void) {
  16253. #if defined(_SOKOL_ANY_GL)
  16254. _sg_gl_reset_state_cache();
  16255. #elif defined(SOKOL_METAL)
  16256. _sg_mtl_reset_state_cache();
  16257. #elif defined(SOKOL_D3D11)
  16258. _sg_d3d11_reset_state_cache();
  16259. #elif defined(SOKOL_WGPU)
  16260. _sg_wgpu_reset_state_cache();
  16261. #elif defined(SOKOL_DUMMY_BACKEND)
  16262. _sg_dummy_reset_state_cache();
  16263. #else
  16264. #error("INVALID BACKEND");
  16265. #endif
  16266. }
  16267. static inline sg_resource_state _sg_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  16268. #if defined(_SOKOL_ANY_GL)
  16269. return _sg_gl_create_buffer(buf, desc);
  16270. #elif defined(SOKOL_METAL)
  16271. return _sg_mtl_create_buffer(buf, desc);
  16272. #elif defined(SOKOL_D3D11)
  16273. return _sg_d3d11_create_buffer(buf, desc);
  16274. #elif defined(SOKOL_WGPU)
  16275. return _sg_wgpu_create_buffer(buf, desc);
  16276. #elif defined(SOKOL_DUMMY_BACKEND)
  16277. return _sg_dummy_create_buffer(buf, desc);
  16278. #else
  16279. #error("INVALID BACKEND");
  16280. #endif
  16281. }
  16282. static inline void _sg_discard_buffer(_sg_buffer_t* buf) {
  16283. #if defined(_SOKOL_ANY_GL)
  16284. _sg_gl_discard_buffer(buf);
  16285. #elif defined(SOKOL_METAL)
  16286. _sg_mtl_discard_buffer(buf);
  16287. #elif defined(SOKOL_D3D11)
  16288. _sg_d3d11_discard_buffer(buf);
  16289. #elif defined(SOKOL_WGPU)
  16290. _sg_wgpu_discard_buffer(buf);
  16291. #elif defined(SOKOL_DUMMY_BACKEND)
  16292. _sg_dummy_discard_buffer(buf);
  16293. #else
  16294. #error("INVALID BACKEND");
  16295. #endif
  16296. }
  16297. static inline sg_resource_state _sg_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  16298. #if defined(_SOKOL_ANY_GL)
  16299. return _sg_gl_create_image(img, desc);
  16300. #elif defined(SOKOL_METAL)
  16301. return _sg_mtl_create_image(img, desc);
  16302. #elif defined(SOKOL_D3D11)
  16303. return _sg_d3d11_create_image(img, desc);
  16304. #elif defined(SOKOL_WGPU)
  16305. return _sg_wgpu_create_image(img, desc);
  16306. #elif defined(SOKOL_DUMMY_BACKEND)
  16307. return _sg_dummy_create_image(img, desc);
  16308. #else
  16309. #error("INVALID BACKEND");
  16310. #endif
  16311. }
  16312. static inline void _sg_discard_image(_sg_image_t* img) {
  16313. #if defined(_SOKOL_ANY_GL)
  16314. _sg_gl_discard_image(img);
  16315. #elif defined(SOKOL_METAL)
  16316. _sg_mtl_discard_image(img);
  16317. #elif defined(SOKOL_D3D11)
  16318. _sg_d3d11_discard_image(img);
  16319. #elif defined(SOKOL_WGPU)
  16320. _sg_wgpu_discard_image(img);
  16321. #elif defined(SOKOL_DUMMY_BACKEND)
  16322. _sg_dummy_discard_image(img);
  16323. #else
  16324. #error("INVALID BACKEND");
  16325. #endif
  16326. }
  16327. static inline sg_resource_state _sg_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  16328. #if defined(_SOKOL_ANY_GL)
  16329. return _sg_gl_create_sampler(smp, desc);
  16330. #elif defined(SOKOL_METAL)
  16331. return _sg_mtl_create_sampler(smp, desc);
  16332. #elif defined(SOKOL_D3D11)
  16333. return _sg_d3d11_create_sampler(smp, desc);
  16334. #elif defined(SOKOL_WGPU)
  16335. return _sg_wgpu_create_sampler(smp, desc);
  16336. #elif defined(SOKOL_DUMMY_BACKEND)
  16337. return _sg_dummy_create_sampler(smp, desc);
  16338. #else
  16339. #error("INVALID BACKEND");
  16340. #endif
  16341. }
  16342. static inline void _sg_discard_sampler(_sg_sampler_t* smp) {
  16343. #if defined(_SOKOL_ANY_GL)
  16344. _sg_gl_discard_sampler(smp);
  16345. #elif defined(SOKOL_METAL)
  16346. _sg_mtl_discard_sampler(smp);
  16347. #elif defined(SOKOL_D3D11)
  16348. _sg_d3d11_discard_sampler(smp);
  16349. #elif defined(SOKOL_WGPU)
  16350. _sg_wgpu_discard_sampler(smp);
  16351. #elif defined(SOKOL_DUMMY_BACKEND)
  16352. _sg_dummy_discard_sampler(smp);
  16353. #else
  16354. #error("INVALID BACKEND");
  16355. #endif
  16356. }
  16357. static inline sg_resource_state _sg_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  16358. #if defined(_SOKOL_ANY_GL)
  16359. return _sg_gl_create_shader(shd, desc);
  16360. #elif defined(SOKOL_METAL)
  16361. return _sg_mtl_create_shader(shd, desc);
  16362. #elif defined(SOKOL_D3D11)
  16363. return _sg_d3d11_create_shader(shd, desc);
  16364. #elif defined(SOKOL_WGPU)
  16365. return _sg_wgpu_create_shader(shd, desc);
  16366. #elif defined(SOKOL_DUMMY_BACKEND)
  16367. return _sg_dummy_create_shader(shd, desc);
  16368. #else
  16369. #error("INVALID BACKEND");
  16370. #endif
  16371. }
  16372. static inline void _sg_discard_shader(_sg_shader_t* shd) {
  16373. #if defined(_SOKOL_ANY_GL)
  16374. _sg_gl_discard_shader(shd);
  16375. #elif defined(SOKOL_METAL)
  16376. _sg_mtl_discard_shader(shd);
  16377. #elif defined(SOKOL_D3D11)
  16378. _sg_d3d11_discard_shader(shd);
  16379. #elif defined(SOKOL_WGPU)
  16380. _sg_wgpu_discard_shader(shd);
  16381. #elif defined(SOKOL_DUMMY_BACKEND)
  16382. _sg_dummy_discard_shader(shd);
  16383. #else
  16384. #error("INVALID BACKEND");
  16385. #endif
  16386. }
  16387. static inline sg_resource_state _sg_create_pipeline(_sg_pipeline_t* pip, const sg_pipeline_desc* desc) {
  16388. #if defined(_SOKOL_ANY_GL)
  16389. return _sg_gl_create_pipeline(pip, desc);
  16390. #elif defined(SOKOL_METAL)
  16391. return _sg_mtl_create_pipeline(pip, desc);
  16392. #elif defined(SOKOL_D3D11)
  16393. return _sg_d3d11_create_pipeline(pip, desc);
  16394. #elif defined(SOKOL_WGPU)
  16395. return _sg_wgpu_create_pipeline(pip, desc);
  16396. #elif defined(SOKOL_DUMMY_BACKEND)
  16397. return _sg_dummy_create_pipeline(pip, desc);
  16398. #else
  16399. #error("INVALID BACKEND");
  16400. #endif
  16401. }
  16402. static inline void _sg_discard_pipeline(_sg_pipeline_t* pip) {
  16403. #if defined(_SOKOL_ANY_GL)
  16404. _sg_gl_discard_pipeline(pip);
  16405. #elif defined(SOKOL_METAL)
  16406. _sg_mtl_discard_pipeline(pip);
  16407. #elif defined(SOKOL_D3D11)
  16408. _sg_d3d11_discard_pipeline(pip);
  16409. #elif defined(SOKOL_WGPU)
  16410. _sg_wgpu_discard_pipeline(pip);
  16411. #elif defined(SOKOL_DUMMY_BACKEND)
  16412. _sg_dummy_discard_pipeline(pip);
  16413. #else
  16414. #error("INVALID BACKEND");
  16415. #endif
  16416. }
  16417. static inline sg_resource_state _sg_create_attachments(_sg_attachments_t* atts, const sg_attachments_desc* desc) {
  16418. #if defined(_SOKOL_ANY_GL)
  16419. return _sg_gl_create_attachments(atts, desc);
  16420. #elif defined(SOKOL_METAL)
  16421. return _sg_mtl_create_attachments(atts, desc);
  16422. #elif defined(SOKOL_D3D11)
  16423. return _sg_d3d11_create_attachments(atts, desc);
  16424. #elif defined(SOKOL_WGPU)
  16425. return _sg_wgpu_create_attachments(atts, desc);
  16426. #elif defined(SOKOL_DUMMY_BACKEND)
  16427. return _sg_dummy_create_attachments(atts, desc);
  16428. #else
  16429. #error("INVALID BACKEND");
  16430. #endif
  16431. }
  16432. static inline void _sg_discard_attachments(_sg_attachments_t* atts) {
  16433. #if defined(_SOKOL_ANY_GL)
  16434. _sg_gl_discard_attachments(atts);
  16435. #elif defined(SOKOL_METAL)
  16436. _sg_mtl_discard_attachments(atts);
  16437. #elif defined(SOKOL_D3D11)
  16438. _sg_d3d11_discard_attachments(atts);
  16439. #elif defined(SOKOL_WGPU)
  16440. return _sg_wgpu_discard_attachments(atts);
  16441. #elif defined(SOKOL_DUMMY_BACKEND)
  16442. _sg_dummy_discard_attachments(atts);
  16443. #else
  16444. #error("INVALID BACKEND");
  16445. #endif
  16446. }
  16447. static inline void _sg_begin_pass(const sg_pass* pass) {
  16448. #if defined(_SOKOL_ANY_GL)
  16449. _sg_gl_begin_pass(pass);
  16450. #elif defined(SOKOL_METAL)
  16451. _sg_mtl_begin_pass(pass);
  16452. #elif defined(SOKOL_D3D11)
  16453. _sg_d3d11_begin_pass(pass);
  16454. #elif defined(SOKOL_WGPU)
  16455. _sg_wgpu_begin_pass(pass);
  16456. #elif defined(SOKOL_DUMMY_BACKEND)
  16457. _sg_dummy_begin_pass(pass);
  16458. #else
  16459. #error("INVALID BACKEND");
  16460. #endif
  16461. }
  16462. static inline void _sg_end_pass(void) {
  16463. #if defined(_SOKOL_ANY_GL)
  16464. _sg_gl_end_pass();
  16465. #elif defined(SOKOL_METAL)
  16466. _sg_mtl_end_pass();
  16467. #elif defined(SOKOL_D3D11)
  16468. _sg_d3d11_end_pass();
  16469. #elif defined(SOKOL_WGPU)
  16470. _sg_wgpu_end_pass();
  16471. #elif defined(SOKOL_DUMMY_BACKEND)
  16472. _sg_dummy_end_pass();
  16473. #else
  16474. #error("INVALID BACKEND");
  16475. #endif
  16476. }
  16477. static inline void _sg_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  16478. #if defined(_SOKOL_ANY_GL)
  16479. _sg_gl_apply_viewport(x, y, w, h, origin_top_left);
  16480. #elif defined(SOKOL_METAL)
  16481. _sg_mtl_apply_viewport(x, y, w, h, origin_top_left);
  16482. #elif defined(SOKOL_D3D11)
  16483. _sg_d3d11_apply_viewport(x, y, w, h, origin_top_left);
  16484. #elif defined(SOKOL_WGPU)
  16485. _sg_wgpu_apply_viewport(x, y, w, h, origin_top_left);
  16486. #elif defined(SOKOL_DUMMY_BACKEND)
  16487. _sg_dummy_apply_viewport(x, y, w, h, origin_top_left);
  16488. #else
  16489. #error("INVALID BACKEND");
  16490. #endif
  16491. }
  16492. static inline void _sg_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  16493. #if defined(_SOKOL_ANY_GL)
  16494. _sg_gl_apply_scissor_rect(x, y, w, h, origin_top_left);
  16495. #elif defined(SOKOL_METAL)
  16496. _sg_mtl_apply_scissor_rect(x, y, w, h, origin_top_left);
  16497. #elif defined(SOKOL_D3D11)
  16498. _sg_d3d11_apply_scissor_rect(x, y, w, h, origin_top_left);
  16499. #elif defined(SOKOL_WGPU)
  16500. _sg_wgpu_apply_scissor_rect(x, y, w, h, origin_top_left);
  16501. #elif defined(SOKOL_DUMMY_BACKEND)
  16502. _sg_dummy_apply_scissor_rect(x, y, w, h, origin_top_left);
  16503. #else
  16504. #error("INVALID BACKEND");
  16505. #endif
  16506. }
  16507. static inline void _sg_apply_pipeline(_sg_pipeline_t* pip) {
  16508. #if defined(_SOKOL_ANY_GL)
  16509. _sg_gl_apply_pipeline(pip);
  16510. #elif defined(SOKOL_METAL)
  16511. _sg_mtl_apply_pipeline(pip);
  16512. #elif defined(SOKOL_D3D11)
  16513. _sg_d3d11_apply_pipeline(pip);
  16514. #elif defined(SOKOL_WGPU)
  16515. _sg_wgpu_apply_pipeline(pip);
  16516. #elif defined(SOKOL_DUMMY_BACKEND)
  16517. _sg_dummy_apply_pipeline(pip);
  16518. #else
  16519. #error("INVALID BACKEND");
  16520. #endif
  16521. }
  16522. static inline bool _sg_apply_bindings(_sg_bindings_ptrs_t* bnd) {
  16523. #if defined(_SOKOL_ANY_GL)
  16524. return _sg_gl_apply_bindings(bnd);
  16525. #elif defined(SOKOL_METAL)
  16526. return _sg_mtl_apply_bindings(bnd);
  16527. #elif defined(SOKOL_D3D11)
  16528. return _sg_d3d11_apply_bindings(bnd);
  16529. #elif defined(SOKOL_WGPU)
  16530. return _sg_wgpu_apply_bindings(bnd);
  16531. #elif defined(SOKOL_DUMMY_BACKEND)
  16532. return _sg_dummy_apply_bindings(bnd);
  16533. #else
  16534. #error("INVALID BACKEND");
  16535. #endif
  16536. }
  16537. static inline void _sg_apply_uniforms(int ub_slot, const sg_range* data) {
  16538. #if defined(_SOKOL_ANY_GL)
  16539. _sg_gl_apply_uniforms(ub_slot, data);
  16540. #elif defined(SOKOL_METAL)
  16541. _sg_mtl_apply_uniforms(ub_slot, data);
  16542. #elif defined(SOKOL_D3D11)
  16543. _sg_d3d11_apply_uniforms(ub_slot, data);
  16544. #elif defined(SOKOL_WGPU)
  16545. _sg_wgpu_apply_uniforms(ub_slot, data);
  16546. #elif defined(SOKOL_DUMMY_BACKEND)
  16547. _sg_dummy_apply_uniforms(ub_slot, data);
  16548. #else
  16549. #error("INVALID BACKEND");
  16550. #endif
  16551. }
  16552. static inline void _sg_draw(int base_element, int num_elements, int num_instances) {
  16553. #if defined(_SOKOL_ANY_GL)
  16554. _sg_gl_draw(base_element, num_elements, num_instances);
  16555. #elif defined(SOKOL_METAL)
  16556. _sg_mtl_draw(base_element, num_elements, num_instances);
  16557. #elif defined(SOKOL_D3D11)
  16558. _sg_d3d11_draw(base_element, num_elements, num_instances);
  16559. #elif defined(SOKOL_WGPU)
  16560. _sg_wgpu_draw(base_element, num_elements, num_instances);
  16561. #elif defined(SOKOL_DUMMY_BACKEND)
  16562. _sg_dummy_draw(base_element, num_elements, num_instances);
  16563. #else
  16564. #error("INVALID BACKEND");
  16565. #endif
  16566. }
  16567. static inline void _sg_dispatch(int num_groups_x, int num_groups_y, int num_groups_z) {
  16568. #if defined(_SOKOL_ANY_GL)
  16569. _sg_gl_dispatch(num_groups_x, num_groups_y, num_groups_z);
  16570. #elif defined(SOKOL_METAL)
  16571. _sg_mtl_dispatch(num_groups_x, num_groups_y, num_groups_z);
  16572. #elif defined(SOKOL_D3D11)
  16573. _sg_d3d11_dispatch(num_groups_x, num_groups_y, num_groups_z);
  16574. #elif defined(SOKOL_WGPU)
  16575. _sg_wgpu_dispatch(num_groups_x, num_groups_y, num_groups_z);
  16576. #elif defined(SOKOL_DUMMY_BACKEND)
  16577. _sg_dummy_dispatch(num_groups_x, num_groups_y, num_groups_z);
  16578. #else
  16579. #error("INVALID BACKEND");
  16580. #endif
  16581. }
  16582. static inline void _sg_commit(void) {
  16583. #if defined(_SOKOL_ANY_GL)
  16584. _sg_gl_commit();
  16585. #elif defined(SOKOL_METAL)
  16586. _sg_mtl_commit();
  16587. #elif defined(SOKOL_D3D11)
  16588. _sg_d3d11_commit();
  16589. #elif defined(SOKOL_WGPU)
  16590. _sg_wgpu_commit();
  16591. #elif defined(SOKOL_DUMMY_BACKEND)
  16592. _sg_dummy_commit();
  16593. #else
  16594. #error("INVALID BACKEND");
  16595. #endif
  16596. }
  16597. static inline void _sg_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  16598. #if defined(_SOKOL_ANY_GL)
  16599. _sg_gl_update_buffer(buf, data);
  16600. #elif defined(SOKOL_METAL)
  16601. _sg_mtl_update_buffer(buf, data);
  16602. #elif defined(SOKOL_D3D11)
  16603. _sg_d3d11_update_buffer(buf, data);
  16604. #elif defined(SOKOL_WGPU)
  16605. _sg_wgpu_update_buffer(buf, data);
  16606. #elif defined(SOKOL_DUMMY_BACKEND)
  16607. _sg_dummy_update_buffer(buf, data);
  16608. #else
  16609. #error("INVALID BACKEND");
  16610. #endif
  16611. }
  16612. static inline void _sg_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  16613. #if defined(_SOKOL_ANY_GL)
  16614. _sg_gl_append_buffer(buf, data, new_frame);
  16615. #elif defined(SOKOL_METAL)
  16616. _sg_mtl_append_buffer(buf, data, new_frame);
  16617. #elif defined(SOKOL_D3D11)
  16618. _sg_d3d11_append_buffer(buf, data, new_frame);
  16619. #elif defined(SOKOL_WGPU)
  16620. _sg_wgpu_append_buffer(buf, data, new_frame);
  16621. #elif defined(SOKOL_DUMMY_BACKEND)
  16622. _sg_dummy_append_buffer(buf, data, new_frame);
  16623. #else
  16624. #error("INVALID BACKEND");
  16625. #endif
  16626. }
  16627. static inline void _sg_update_image(_sg_image_t* img, const sg_image_data* data) {
  16628. #if defined(_SOKOL_ANY_GL)
  16629. _sg_gl_update_image(img, data);
  16630. #elif defined(SOKOL_METAL)
  16631. _sg_mtl_update_image(img, data);
  16632. #elif defined(SOKOL_D3D11)
  16633. _sg_d3d11_update_image(img, data);
  16634. #elif defined(SOKOL_WGPU)
  16635. _sg_wgpu_update_image(img, data);
  16636. #elif defined(SOKOL_DUMMY_BACKEND)
  16637. _sg_dummy_update_image(img, data);
  16638. #else
  16639. #error("INVALID BACKEND");
  16640. #endif
  16641. }
  16642. static inline void _sg_push_debug_group(const char* name) {
  16643. #if defined(SOKOL_METAL)
  16644. _sg_mtl_push_debug_group(name);
  16645. #else
  16646. _SOKOL_UNUSED(name);
  16647. #endif
  16648. }
  16649. static inline void _sg_pop_debug_group(void) {
  16650. #if defined(SOKOL_METAL)
  16651. _sg_mtl_pop_debug_group();
  16652. #endif
  16653. }
  16654. // ██ ██ █████ ██ ██ ██████ █████ ████████ ██ ██████ ███ ██
  16655. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
  16656. // ██ ██ ███████ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██
  16657. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  16658. // ████ ██ ██ ███████ ██ ██████ ██ ██ ██ ██ ██████ ██ ████
  16659. //
  16660. // >>validation
  16661. #if defined(SOKOL_DEBUG)
  16662. _SOKOL_PRIVATE void _sg_validate_begin(void) {
  16663. _sg.validate_error = SG_LOGITEM_OK;
  16664. }
  16665. _SOKOL_PRIVATE bool _sg_validate_end(void) {
  16666. if (_sg.validate_error != SG_LOGITEM_OK) {
  16667. #if !defined(SOKOL_VALIDATE_NON_FATAL)
  16668. _SG_PANIC(VALIDATION_FAILED);
  16669. return false;
  16670. #else
  16671. return false;
  16672. #endif
  16673. } else {
  16674. return true;
  16675. }
  16676. }
  16677. #endif
  16678. _SOKOL_PRIVATE bool _sg_one(bool b0, bool b1, bool b2) {
  16679. return (b0 && !b1 && !b2) || (!b0 && b1 && !b2) || (!b0 && !b1 && b2);
  16680. }
  16681. _SOKOL_PRIVATE bool _sg_validate_buffer_desc(const sg_buffer_desc* desc) {
  16682. #if !defined(SOKOL_DEBUG)
  16683. _SOKOL_UNUSED(desc);
  16684. return true;
  16685. #else
  16686. if (_sg.desc.disable_validation) {
  16687. return true;
  16688. }
  16689. SOKOL_ASSERT(desc);
  16690. _sg_validate_begin();
  16691. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_BUFFERDESC_CANARY);
  16692. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_BUFFERDESC_CANARY);
  16693. _SG_VALIDATE(desc->size > 0, VALIDATE_BUFFERDESC_EXPECT_NONZERO_SIZE);
  16694. _SG_VALIDATE(_sg_one(desc->usage.immutable, desc->usage.dynamic_update, desc->usage.stream_update), VALIDATE_BUFFERDESC_IMMUTABLE_DYNAMIC_STREAM);
  16695. if (_sg.features.separate_buffer_types) {
  16696. _SG_VALIDATE(_sg_one(desc->usage.vertex_buffer, desc->usage.index_buffer, desc->usage.storage_buffer), VALIDATE_BUFFERDESC_SEPARATE_BUFFER_TYPES);
  16697. }
  16698. bool injected = (0 != desc->gl_buffers[0]) ||
  16699. (0 != desc->mtl_buffers[0]) ||
  16700. (0 != desc->d3d11_buffer) ||
  16701. (0 != desc->wgpu_buffer);
  16702. if (!injected && desc->usage.immutable) {
  16703. if (desc->data.ptr) {
  16704. _SG_VALIDATE(desc->size == desc->data.size, VALIDATE_BUFFERDESC_EXPECT_MATCHING_DATA_SIZE);
  16705. } else {
  16706. _SG_VALIDATE(desc->usage.storage_buffer, VALIDATE_BUFFERDESC_EXPECT_DATA);
  16707. _SG_VALIDATE(desc->data.size == 0, VALIDATE_BUFFERDESC_EXPECT_ZERO_DATA_SIZE);
  16708. }
  16709. } else {
  16710. _SG_VALIDATE(0 == desc->data.ptr, VALIDATE_BUFFERDESC_EXPECT_NO_DATA);
  16711. _SG_VALIDATE(desc->data.size == 0, VALIDATE_BUFFERDESC_EXPECT_ZERO_DATA_SIZE);
  16712. }
  16713. if (desc->usage.storage_buffer) {
  16714. _SG_VALIDATE(_sg.features.compute, VALIDATE_BUFFERDESC_STORAGEBUFFER_SUPPORTED);
  16715. _SG_VALIDATE(_sg_multiple_u64(desc->size, 4), VALIDATE_BUFFERDESC_STORAGEBUFFER_SIZE_MULTIPLE_4);
  16716. }
  16717. return _sg_validate_end();
  16718. #endif
  16719. }
  16720. _SOKOL_PRIVATE void _sg_validate_image_data(const sg_image_data* data, sg_pixel_format fmt, int width, int height, int num_faces, int num_mips, int num_slices) {
  16721. #if !defined(SOKOL_DEBUG)
  16722. _SOKOL_UNUSED(data);
  16723. _SOKOL_UNUSED(fmt);
  16724. _SOKOL_UNUSED(width);
  16725. _SOKOL_UNUSED(height);
  16726. _SOKOL_UNUSED(num_faces);
  16727. _SOKOL_UNUSED(num_mips);
  16728. _SOKOL_UNUSED(num_slices);
  16729. #else
  16730. for (int face_index = 0; face_index < num_faces; face_index++) {
  16731. for (int mip_index = 0; mip_index < num_mips; mip_index++) {
  16732. const bool has_data = data->subimage[face_index][mip_index].ptr != 0;
  16733. const bool has_size = data->subimage[face_index][mip_index].size > 0;
  16734. _SG_VALIDATE(has_data && has_size, VALIDATE_IMAGEDATA_NODATA);
  16735. const int mip_width = _sg_miplevel_dim(width, mip_index);
  16736. const int mip_height = _sg_miplevel_dim(height, mip_index);
  16737. const int bytes_per_slice = _sg_surface_pitch(fmt, mip_width, mip_height, 1);
  16738. const int expected_size = bytes_per_slice * num_slices;
  16739. _SG_VALIDATE(expected_size == (int)data->subimage[face_index][mip_index].size, VALIDATE_IMAGEDATA_DATA_SIZE);
  16740. }
  16741. }
  16742. #endif
  16743. }
  16744. _SOKOL_PRIVATE bool _sg_validate_image_desc(const sg_image_desc* desc) {
  16745. #if !defined(SOKOL_DEBUG)
  16746. _SOKOL_UNUSED(desc);
  16747. return true;
  16748. #else
  16749. if (_sg.desc.disable_validation) {
  16750. return true;
  16751. }
  16752. SOKOL_ASSERT(desc);
  16753. _sg_validate_begin();
  16754. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_IMAGEDESC_CANARY);
  16755. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_IMAGEDESC_CANARY);
  16756. _SG_VALIDATE(_sg_one(desc->usage.immutable, desc->usage.dynamic_update, desc->usage.stream_update), VALIDATE_IMAGEDESC_IMMUTABLE_DYNAMIC_STREAM);
  16757. if (desc->usage.render_attachment || desc->usage.storage_attachment) {
  16758. _SG_VALIDATE(_sg_one(desc->usage.render_attachment, desc->usage.storage_attachment, false), VALIDATE_IMAGEDESC_RENDER_VS_STORAGE_ATTACHMENT);
  16759. }
  16760. _SG_VALIDATE(desc->width > 0, VALIDATE_IMAGEDESC_WIDTH);
  16761. _SG_VALIDATE(desc->height > 0, VALIDATE_IMAGEDESC_HEIGHT);
  16762. const sg_pixel_format fmt = desc->pixel_format;
  16763. const sg_image_usage* usage = &desc->usage;
  16764. const bool injected = (0 != desc->gl_textures[0]) ||
  16765. (0 != desc->mtl_textures[0]) ||
  16766. (0 != desc->d3d11_texture) ||
  16767. (0 != desc->wgpu_texture);
  16768. if (_sg_is_depth_or_depth_stencil_format(fmt)) {
  16769. _SG_VALIDATE(desc->type != SG_IMAGETYPE_3D, VALIDATE_IMAGEDESC_DEPTH_3D_IMAGE);
  16770. }
  16771. if (usage->render_attachment || usage->storage_attachment) {
  16772. SOKOL_ASSERT(((int)fmt >= 0) && ((int)fmt < _SG_PIXELFORMAT_NUM));
  16773. _SG_VALIDATE(usage->immutable, VALIDATE_IMAGEDESC_ATTACHMENT_EXPECT_IMMUTABLE);
  16774. _SG_VALIDATE(desc->data.subimage[0][0].ptr==0, VALIDATE_IMAGEDESC_ATTACHMENT_EXPECT_NO_DATA);
  16775. if (usage->render_attachment) {
  16776. _SG_VALIDATE(_sg.formats[fmt].render, VALIDATE_IMAGEDESC_RENDERATTACHMENT_PIXELFORMAT);
  16777. if (desc->sample_count > 1) {
  16778. _SG_VALIDATE(_sg.formats[fmt].msaa, VALIDATE_IMAGEDESC_RENDERATTACHMENT_NO_MSAA_SUPPORT);
  16779. _SG_VALIDATE(desc->num_mipmaps == 1, VALIDATE_IMAGEDESC_RENDERATTACHMENT_MSAA_NUM_MIPMAPS);
  16780. _SG_VALIDATE(desc->type != SG_IMAGETYPE_ARRAY, VALIDATE_IMAGEDESC_RENDERATTACHMENT_MSAA_ARRAY_IMAGE);
  16781. _SG_VALIDATE(desc->type != SG_IMAGETYPE_3D, VALIDATE_IMAGEDESC_RENDERATTACHMENT_MSAA_3D_IMAGE);
  16782. _SG_VALIDATE(desc->type != SG_IMAGETYPE_CUBE, VALIDATE_IMAGEDESC_RENDERATTACHMENT_MSAA_CUBE_IMAGE);
  16783. }
  16784. } else if (usage->storage_attachment) {
  16785. _SG_VALIDATE(_sg_is_valid_attachment_storage_format(fmt), VALIDATE_IMAGEDESC_STORAGEATTACHMENT_PIXELFORMAT);
  16786. // D3D11 doesn't allow multisampled UAVs (see: https://github.com/gpuweb/gpuweb/issues/513)
  16787. _SG_VALIDATE(desc->sample_count == 1, VALIDATE_IMAGEDESC_STORAGEATTACHMENT_EXPECT_NO_MSAA);
  16788. }
  16789. } else {
  16790. _SG_VALIDATE(desc->sample_count == 1, VALIDATE_IMAGEDESC_MSAA_BUT_NO_ATTACHMENT);
  16791. const bool valid_nonrt_fmt = !_sg_is_valid_attachment_depth_format(fmt);
  16792. _SG_VALIDATE(valid_nonrt_fmt, VALIDATE_IMAGEDESC_NONRT_PIXELFORMAT);
  16793. const bool is_compressed = _sg_is_compressed_pixel_format(desc->pixel_format);
  16794. if (is_compressed) {
  16795. _SG_VALIDATE(usage->immutable, VALIDATE_IMAGEDESC_COMPRESSED_IMMUTABLE);
  16796. }
  16797. if (!injected && usage->immutable) {
  16798. // image desc must have valid data
  16799. _sg_validate_image_data(&desc->data,
  16800. desc->pixel_format,
  16801. desc->width,
  16802. desc->height,
  16803. (desc->type == SG_IMAGETYPE_CUBE) ? 6 : 1,
  16804. desc->num_mipmaps,
  16805. desc->num_slices);
  16806. } else {
  16807. // image desc must not have data
  16808. for (int face_index = 0; face_index < SG_CUBEFACE_NUM; face_index++) {
  16809. for (int mip_index = 0; mip_index < SG_MAX_MIPMAPS; mip_index++) {
  16810. const bool no_data = 0 == desc->data.subimage[face_index][mip_index].ptr;
  16811. const bool no_size = 0 == desc->data.subimage[face_index][mip_index].size;
  16812. if (injected) {
  16813. _SG_VALIDATE(no_data && no_size, VALIDATE_IMAGEDESC_INJECTED_NO_DATA);
  16814. }
  16815. if (!usage->immutable) {
  16816. _SG_VALIDATE(no_data && no_size, VALIDATE_IMAGEDESC_DYNAMIC_NO_DATA);
  16817. }
  16818. }
  16819. }
  16820. }
  16821. }
  16822. return _sg_validate_end();
  16823. #endif
  16824. }
  16825. _SOKOL_PRIVATE bool _sg_validate_sampler_desc(const sg_sampler_desc* desc) {
  16826. #if !defined(SOKOL_DEBUG)
  16827. _SOKOL_UNUSED(desc);
  16828. return true;
  16829. #else
  16830. if (_sg.desc.disable_validation) {
  16831. return true;
  16832. }
  16833. SOKOL_ASSERT(desc);
  16834. _sg_validate_begin();
  16835. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_SAMPLERDESC_CANARY);
  16836. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_SAMPLERDESC_CANARY);
  16837. // restriction from WebGPU: when anisotropy > 1, all filters must be linear
  16838. if (desc->max_anisotropy > 1) {
  16839. _SG_VALIDATE((desc->min_filter == SG_FILTER_LINEAR)
  16840. && (desc->mag_filter == SG_FILTER_LINEAR)
  16841. && (desc->mipmap_filter == SG_FILTER_LINEAR),
  16842. VALIDATE_SAMPLERDESC_ANISTROPIC_REQUIRES_LINEAR_FILTERING);
  16843. }
  16844. return _sg_validate_end();
  16845. #endif
  16846. }
  16847. typedef struct {
  16848. uint64_t lo, hi;
  16849. } _sg_u128_t;
  16850. _SOKOL_PRIVATE _sg_u128_t _sg_u128(void) {
  16851. _sg_u128_t res;
  16852. _sg_clear(&res, sizeof(res));
  16853. return res;
  16854. }
  16855. _SOKOL_PRIVATE _sg_u128_t _sg_validate_set_slot_bit(_sg_u128_t bits, sg_shader_stage stage, uint8_t slot) {
  16856. switch (stage) {
  16857. case SG_SHADERSTAGE_NONE:
  16858. SOKOL_ASSERT(slot < 128);
  16859. if (slot < 64) {
  16860. bits.lo |= 1ULL << slot;
  16861. } else {
  16862. bits.hi |= 1ULL << (slot - 64);
  16863. }
  16864. break;
  16865. case SG_SHADERSTAGE_VERTEX:
  16866. SOKOL_ASSERT(slot < 64);
  16867. bits.lo |= 1ULL << slot;
  16868. break;
  16869. case SG_SHADERSTAGE_FRAGMENT:
  16870. SOKOL_ASSERT(slot < 64);
  16871. bits.hi |= 1ULL << slot;
  16872. break;
  16873. case SG_SHADERSTAGE_COMPUTE:
  16874. SOKOL_ASSERT(slot < 64);
  16875. bits.lo |= 1ULL << slot;
  16876. break;
  16877. default:
  16878. SOKOL_UNREACHABLE;
  16879. break;
  16880. }
  16881. return bits;
  16882. }
  16883. _SOKOL_PRIVATE bool _sg_validate_slot_bits(_sg_u128_t bits, sg_shader_stage stage, uint8_t slot) {
  16884. _sg_u128_t mask = _sg_u128();
  16885. switch (stage) {
  16886. case SG_SHADERSTAGE_NONE:
  16887. SOKOL_ASSERT(slot < 128);
  16888. if (slot < 64) {
  16889. mask.lo = 1ULL << slot;
  16890. } else {
  16891. mask.hi = 1ULL << (slot - 64);
  16892. }
  16893. break;
  16894. case SG_SHADERSTAGE_VERTEX:
  16895. SOKOL_ASSERT(slot < 64);
  16896. mask.lo = 1ULL << slot;
  16897. break;
  16898. case SG_SHADERSTAGE_FRAGMENT:
  16899. SOKOL_ASSERT(slot < 64);
  16900. mask.hi = 1ULL << slot;
  16901. break;
  16902. case SG_SHADERSTAGE_COMPUTE:
  16903. SOKOL_ASSERT(slot < 64);
  16904. mask.lo = 1ULL << slot;
  16905. break;
  16906. default:
  16907. SOKOL_UNREACHABLE;
  16908. break;
  16909. }
  16910. return ((bits.lo & mask.lo) == 0) && ((bits.hi & mask.hi) == 0);
  16911. }
  16912. _SOKOL_PRIVATE bool _sg_validate_shader_desc(const sg_shader_desc* desc) {
  16913. #if !defined(SOKOL_DEBUG)
  16914. _SOKOL_UNUSED(desc);
  16915. return true;
  16916. #else
  16917. if (_sg.desc.disable_validation) {
  16918. return true;
  16919. }
  16920. SOKOL_ASSERT(desc);
  16921. bool is_compute_shader = (desc->compute_func.source != 0) || (desc->compute_func.bytecode.ptr != 0);
  16922. _sg_validate_begin();
  16923. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_SHADERDESC_CANARY);
  16924. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_SHADERDESC_CANARY);
  16925. #if defined(SOKOL_GLCORE) || defined(SOKOL_GLES3) || defined(SOKOL_WGPU)
  16926. // on GL or WebGPU, must provide shader source code
  16927. if (is_compute_shader) {
  16928. _SG_VALIDATE(0 != desc->compute_func.source, VALIDATE_SHADERDESC_COMPUTE_SOURCE);
  16929. } else {
  16930. _SG_VALIDATE(0 != desc->vertex_func.source, VALIDATE_SHADERDESC_VERTEX_SOURCE);
  16931. _SG_VALIDATE(0 != desc->fragment_func.source, VALIDATE_SHADERDESC_FRAGMENT_SOURCE);
  16932. }
  16933. #elif defined(SOKOL_METAL) || defined(SOKOL_D3D11)
  16934. // on Metal or D3D11, must provide shader source code or byte code
  16935. if (is_compute_shader) {
  16936. _SG_VALIDATE((0 != desc->compute_func.source) || (0 != desc->compute_func.bytecode.ptr), VALIDATE_SHADERDESC_COMPUTE_SOURCE_OR_BYTECODE);
  16937. } else {
  16938. _SG_VALIDATE((0 != desc->vertex_func.source)|| (0 != desc->vertex_func.bytecode.ptr), VALIDATE_SHADERDESC_VERTEX_SOURCE_OR_BYTECODE);
  16939. _SG_VALIDATE((0 != desc->fragment_func.source) || (0 != desc->fragment_func.bytecode.ptr), VALIDATE_SHADERDESC_FRAGMENT_SOURCE_OR_BYTECODE);
  16940. }
  16941. #else
  16942. // Dummy Backend, don't require source or bytecode
  16943. #endif
  16944. if (is_compute_shader) {
  16945. _SG_VALIDATE((0 == desc->vertex_func.source) && (0 == desc->vertex_func.bytecode.ptr), VALIDATE_SHADERDESC_INVALID_SHADER_COMBO);
  16946. _SG_VALIDATE((0 == desc->fragment_func.source) && (0 == desc->fragment_func.bytecode.ptr), VALIDATE_SHADERDESC_INVALID_SHADER_COMBO);
  16947. } else {
  16948. _SG_VALIDATE((0 == desc->compute_func.source) && (0 == desc->compute_func.bytecode.ptr), VALIDATE_SHADERDESC_INVALID_SHADER_COMBO);
  16949. }
  16950. #if defined(SOKOL_METAL)
  16951. if (is_compute_shader) {
  16952. _SG_VALIDATE(desc->mtl_threads_per_threadgroup.x > 0, VALIDATE_SHADERDESC_METAL_THREADS_PER_THREADGROUP);
  16953. _SG_VALIDATE(desc->mtl_threads_per_threadgroup.y > 0, VALIDATE_SHADERDESC_METAL_THREADS_PER_THREADGROUP);
  16954. _SG_VALIDATE(desc->mtl_threads_per_threadgroup.z > 0, VALIDATE_SHADERDESC_METAL_THREADS_PER_THREADGROUP);
  16955. }
  16956. #endif
  16957. for (size_t i = 0; i < SG_MAX_VERTEX_ATTRIBUTES; i++) {
  16958. if (desc->attrs[i].glsl_name) {
  16959. _SG_VALIDATE(strlen(desc->attrs[i].glsl_name) < _SG_STRING_SIZE, VALIDATE_SHADERDESC_ATTR_STRING_TOO_LONG);
  16960. }
  16961. if (desc->attrs[i].hlsl_sem_name) {
  16962. _SG_VALIDATE(strlen(desc->attrs[i].hlsl_sem_name) < _SG_STRING_SIZE, VALIDATE_SHADERDESC_ATTR_STRING_TOO_LONG);
  16963. }
  16964. }
  16965. // if shader byte code, the size must also be provided
  16966. if (0 != desc->vertex_func.bytecode.ptr) {
  16967. _SG_VALIDATE(desc->vertex_func.bytecode.size > 0, VALIDATE_SHADERDESC_NO_BYTECODE_SIZE);
  16968. }
  16969. if (0 != desc->fragment_func.bytecode.ptr) {
  16970. _SG_VALIDATE(desc->fragment_func.bytecode.size > 0, VALIDATE_SHADERDESC_NO_BYTECODE_SIZE);
  16971. }
  16972. if (0 != desc->compute_func.bytecode.ptr) {
  16973. _SG_VALIDATE(desc->compute_func.bytecode.size > 0, VALIDATE_SHADERDESC_NO_BYTECODE_SIZE);
  16974. }
  16975. #if defined(SOKOL_METAL)
  16976. _sg_u128_t msl_buf_bits = _sg_u128();
  16977. _sg_u128_t msl_tex_bits = _sg_u128();
  16978. _sg_u128_t msl_smp_bits = _sg_u128();
  16979. #elif defined(SOKOL_D3D11)
  16980. _sg_u128_t hlsl_buf_bits = _sg_u128();
  16981. _sg_u128_t hlsl_srv_bits = _sg_u128();
  16982. _sg_u128_t hlsl_uav_bits = _sg_u128();
  16983. _sg_u128_t hlsl_smp_bits = _sg_u128();
  16984. #elif defined(_SOKOL_ANY_GL)
  16985. _sg_u128_t glsl_sbuf_bnd_bits = _sg_u128();
  16986. _sg_u128_t glsl_simg_bnd_bits = _sg_u128();
  16987. #elif defined(SOKOL_WGPU)
  16988. _sg_u128_t wgsl_group0_bits = _sg_u128();
  16989. _sg_u128_t wgsl_group1_bits = _sg_u128();
  16990. _sg_u128_t wgsl_group2_bits = _sg_u128();
  16991. #endif
  16992. for (size_t ub_idx = 0; ub_idx < SG_MAX_UNIFORMBLOCK_BINDSLOTS; ub_idx++) {
  16993. const sg_shader_uniform_block* ub_desc = &desc->uniform_blocks[ub_idx];
  16994. if (ub_desc->stage == SG_SHADERSTAGE_NONE) {
  16995. continue;
  16996. }
  16997. _SG_VALIDATE(ub_desc->size > 0, VALIDATE_SHADERDESC_UNIFORMBLOCK_SIZE_IS_ZERO);
  16998. #if defined(SOKOL_METAL)
  16999. _SG_VALIDATE(ub_desc->msl_buffer_n < _SG_MTL_MAX_STAGE_UB_BINDINGS, VALIDATE_SHADERDESC_UNIFORMBLOCK_METAL_BUFFER_SLOT_OUT_OF_RANGE);
  17000. _SG_VALIDATE(_sg_validate_slot_bits(msl_buf_bits, ub_desc->stage, ub_desc->msl_buffer_n), VALIDATE_SHADERDESC_UNIFORMBLOCK_METAL_BUFFER_SLOT_COLLISION);
  17001. msl_buf_bits = _sg_validate_set_slot_bit(msl_buf_bits, ub_desc->stage, ub_desc->msl_buffer_n);
  17002. #elif defined(SOKOL_D3D11)
  17003. _SG_VALIDATE(ub_desc->hlsl_register_b_n < _SG_D3D11_MAX_STAGE_UB_BINDINGS, VALIDATE_SHADERDESC_UNIFORMBLOCK_HLSL_REGISTER_B_OUT_OF_RANGE);
  17004. _SG_VALIDATE(_sg_validate_slot_bits(hlsl_buf_bits, ub_desc->stage, ub_desc->hlsl_register_b_n), VALIDATE_SHADERDESC_UNIFORMBLOCK_HLSL_REGISTER_B_COLLISION);
  17005. hlsl_buf_bits = _sg_validate_set_slot_bit(hlsl_buf_bits, ub_desc->stage, ub_desc->hlsl_register_b_n);
  17006. #elif defined(SOKOL_WGPU)
  17007. _SG_VALIDATE(ub_desc->wgsl_group0_binding_n < _SG_WGPU_MAX_UB_BINDGROUP_BIND_SLOTS, VALIDATE_SHADERDESC_UNIFORMBLOCK_WGSL_GROUP0_BINDING_OUT_OF_RANGE);
  17008. _SG_VALIDATE(_sg_validate_slot_bits(wgsl_group0_bits, SG_SHADERSTAGE_NONE, ub_desc->wgsl_group0_binding_n), VALIDATE_SHADERDESC_UNIFORMBLOCK_WGSL_GROUP0_BINDING_COLLISION);
  17009. wgsl_group0_bits = _sg_validate_set_slot_bit(wgsl_group0_bits, SG_SHADERSTAGE_NONE, ub_desc->wgsl_group0_binding_n);
  17010. #endif
  17011. #if defined(_SOKOL_ANY_GL)
  17012. bool uniforms_continuous = true;
  17013. uint32_t uniform_offset = 0;
  17014. int num_uniforms = 0;
  17015. for (size_t u_index = 0; u_index < SG_MAX_UNIFORMBLOCK_MEMBERS; u_index++) {
  17016. const sg_glsl_shader_uniform* u_desc = &ub_desc->glsl_uniforms[u_index];
  17017. if (u_desc->type != SG_UNIFORMTYPE_INVALID) {
  17018. _SG_VALIDATE(uniforms_continuous, VALIDATE_SHADERDESC_UNIFORMBLOCK_NO_CONT_MEMBERS);
  17019. _SG_VALIDATE(u_desc->glsl_name, VALIDATE_SHADERDESC_UNIFORMBLOCK_UNIFORM_GLSL_NAME);
  17020. const int array_count = u_desc->array_count;
  17021. _SG_VALIDATE(array_count > 0, VALIDATE_SHADERDESC_UNIFORMBLOCK_ARRAY_COUNT);
  17022. const uint32_t u_align = _sg_uniform_alignment(u_desc->type, array_count, ub_desc->layout);
  17023. const uint32_t u_size = _sg_uniform_size(u_desc->type, array_count, ub_desc->layout);
  17024. uniform_offset = _sg_align_u32(uniform_offset, u_align);
  17025. uniform_offset += u_size;
  17026. num_uniforms++;
  17027. // with std140, arrays are only allowed for FLOAT4, INT4, MAT4
  17028. if (ub_desc->layout == SG_UNIFORMLAYOUT_STD140) {
  17029. if (array_count > 1) {
  17030. _SG_VALIDATE((u_desc->type == SG_UNIFORMTYPE_FLOAT4) || (u_desc->type == SG_UNIFORMTYPE_INT4) || (u_desc->type == SG_UNIFORMTYPE_MAT4), VALIDATE_SHADERDESC_UNIFORMBLOCK_STD140_ARRAY_TYPE);
  17031. }
  17032. }
  17033. } else {
  17034. uniforms_continuous = false;
  17035. }
  17036. }
  17037. if (ub_desc->layout == SG_UNIFORMLAYOUT_STD140) {
  17038. uniform_offset = _sg_align_u32(uniform_offset, 16);
  17039. }
  17040. _SG_VALIDATE((size_t)uniform_offset == ub_desc->size, VALIDATE_SHADERDESC_UNIFORMBLOCK_SIZE_MISMATCH);
  17041. _SG_VALIDATE(num_uniforms > 0, VALIDATE_SHADERDESC_UNIFORMBLOCK_NO_MEMBERS);
  17042. #endif
  17043. }
  17044. for (size_t sbuf_idx = 0; sbuf_idx < SG_MAX_STORAGEBUFFER_BINDSLOTS; sbuf_idx++) {
  17045. const sg_shader_storage_buffer* sbuf_desc = &desc->storage_buffers[sbuf_idx];
  17046. if (sbuf_desc->stage == SG_SHADERSTAGE_NONE) {
  17047. continue;
  17048. }
  17049. #if defined(SOKOL_METAL)
  17050. _SG_VALIDATE((sbuf_desc->msl_buffer_n >= _SG_MTL_MAX_STAGE_UB_BINDINGS) && (sbuf_desc->msl_buffer_n < _SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS), VALIDATE_SHADERDESC_STORAGEBUFFER_METAL_BUFFER_SLOT_OUT_OF_RANGE);
  17051. _SG_VALIDATE(_sg_validate_slot_bits(msl_buf_bits, sbuf_desc->stage, sbuf_desc->msl_buffer_n), VALIDATE_SHADERDESC_STORAGEBUFFER_METAL_BUFFER_SLOT_COLLISION);
  17052. msl_buf_bits = _sg_validate_set_slot_bit(msl_buf_bits, sbuf_desc->stage, sbuf_desc->msl_buffer_n);
  17053. #elif defined(SOKOL_D3D11)
  17054. if (sbuf_desc->readonly) {
  17055. _SG_VALIDATE(sbuf_desc->hlsl_register_t_n < _SG_D3D11_MAX_STAGE_SRV_BINDINGS, VALIDATE_SHADERDESC_STORAGEBUFFER_HLSL_REGISTER_T_OUT_OF_RANGE);
  17056. _SG_VALIDATE(_sg_validate_slot_bits(hlsl_srv_bits, sbuf_desc->stage, sbuf_desc->hlsl_register_t_n), VALIDATE_SHADERDESC_STORAGEBUFFER_HLSL_REGISTER_T_COLLISION);
  17057. hlsl_srv_bits = _sg_validate_set_slot_bit(hlsl_srv_bits, sbuf_desc->stage, sbuf_desc->hlsl_register_t_n);
  17058. } else {
  17059. _SG_VALIDATE(sbuf_desc->hlsl_register_u_n < _SG_D3D11_MAX_STAGE_UAV_BINDINGS, VALIDATE_SHADERDESC_STORAGEBUFFER_HLSL_REGISTER_U_OUT_OF_RANGE);
  17060. _SG_VALIDATE(_sg_validate_slot_bits(hlsl_uav_bits, sbuf_desc->stage, sbuf_desc->hlsl_register_u_n), VALIDATE_SHADERDESC_STORAGEBUFFER_HLSL_REGISTER_U_COLLISION);
  17061. hlsl_uav_bits = _sg_validate_set_slot_bit(hlsl_uav_bits, sbuf_desc->stage, sbuf_desc->hlsl_register_u_n);
  17062. }
  17063. #elif defined(_SOKOL_ANY_GL)
  17064. _SG_VALIDATE(sbuf_desc->glsl_binding_n < _SG_GL_MAX_SBUF_BINDINGS, VALIDATE_SHADERDESC_STORAGEBUFFER_GLSL_BINDING_OUT_OF_RANGE);
  17065. _SG_VALIDATE(_sg_validate_slot_bits(glsl_sbuf_bnd_bits, SG_SHADERSTAGE_NONE, sbuf_desc->glsl_binding_n), VALIDATE_SHADERDESC_STORAGEBUFFER_GLSL_BINDING_COLLISION);
  17066. glsl_sbuf_bnd_bits = _sg_validate_set_slot_bit(glsl_sbuf_bnd_bits, SG_SHADERSTAGE_NONE, sbuf_desc->glsl_binding_n);
  17067. #elif defined(SOKOL_WGPU)
  17068. _SG_VALIDATE(sbuf_desc->wgsl_group1_binding_n < _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS, VALIDATE_SHADERDESC_STORAGEBUFFER_WGSL_GROUP1_BINDING_OUT_OF_RANGE);
  17069. _SG_VALIDATE(_sg_validate_slot_bits(wgsl_group1_bits, SG_SHADERSTAGE_NONE, sbuf_desc->wgsl_group1_binding_n), VALIDATE_SHADERDESC_STORAGEBUFFER_WGSL_GROUP1_BINDING_COLLISION);
  17070. wgsl_group1_bits = _sg_validate_set_slot_bit(wgsl_group1_bits, SG_SHADERSTAGE_NONE, sbuf_desc->wgsl_group1_binding_n);
  17071. #endif
  17072. }
  17073. for (size_t simg_idx = 0; simg_idx < SG_MAX_STORAGE_ATTACHMENTS; simg_idx++) {
  17074. const sg_shader_storage_image* simg_desc = &desc->storage_images[simg_idx];
  17075. if (simg_desc->stage == SG_SHADERSTAGE_NONE) {
  17076. continue;
  17077. }
  17078. _SG_VALIDATE(simg_desc->stage == SG_SHADERSTAGE_COMPUTE, VALIDATE_SHADERDESC_STORAGEIMAGE_EXPECT_COMPUTE_STAGE);
  17079. #if defined(SOKOL_METAL)
  17080. _SG_VALIDATE(simg_desc->msl_texture_n < _SG_MTL_MAX_STAGE_TEXTURE_BINDINGS, VALIDATE_SHADERDESC_STORAGEIMAGE_METAL_TEXTURE_SLOT_OUT_OF_RANGE);
  17081. _SG_VALIDATE(_sg_validate_slot_bits(msl_tex_bits, simg_desc->stage, simg_desc->msl_texture_n), VALIDATE_SHADERDESC_STORAGEIMAGE_METAL_TEXTURE_SLOT_COLLISION);
  17082. msl_tex_bits = _sg_validate_set_slot_bit(msl_tex_bits, simg_desc->stage, simg_desc->msl_texture_n);
  17083. #elif defined(SOKOL_D3D11)
  17084. _SG_VALIDATE(simg_desc->hlsl_register_u_n < _SG_D3D11_MAX_STAGE_UAV_BINDINGS, VALIDATE_SHADERDESC_STORAGEIMAGE_HLSL_REGISTER_U_OUT_OF_RANGE);
  17085. _SG_VALIDATE(_sg_validate_slot_bits(hlsl_uav_bits, simg_desc->stage, simg_desc->hlsl_register_u_n), VALIDATE_SHADERDESC_STORAGEIMAGE_HLSL_REGISTER_U_COLLISION);
  17086. hlsl_uav_bits = _sg_validate_set_slot_bit(hlsl_uav_bits, simg_desc->stage, simg_desc->hlsl_register_u_n);
  17087. #elif defined(_SOKOL_ANY_GL)
  17088. _SG_VALIDATE(simg_desc->glsl_binding_n < _SG_GL_MAX_SIMG_BINDINGS, VALIDATE_SHADERDESC_STORAGEIMAGE_GLSL_BINDING_OUT_OF_RANGE);
  17089. _SG_VALIDATE(_sg_validate_slot_bits(glsl_simg_bnd_bits, SG_SHADERSTAGE_NONE, simg_desc->glsl_binding_n), VALIDATE_SHADERDESC_STORAGEIMAGE_GLSL_BINDING_COLLISION);
  17090. glsl_simg_bnd_bits = _sg_validate_set_slot_bit(glsl_simg_bnd_bits, SG_SHADERSTAGE_NONE, simg_desc->glsl_binding_n);
  17091. #elif defined(SOKOL_WGPU)
  17092. _SG_VALIDATE(simg_desc->wgsl_group2_binding_n < _SG_WGPU_MAX_SIMG_BIND_SLOTS, VALIDATE_SHADERDESC_STORAGEIMAGE_WGSL_GROUP2_BINDING_OUT_OF_RANGE);
  17093. _SG_VALIDATE(_sg_validate_slot_bits(wgsl_group2_bits, SG_SHADERSTAGE_NONE, simg_desc->wgsl_group2_binding_n), VALIDATE_SHADERDESC_STORAGEIMAGE_WGSL_GROUP2_BINDING_COLLISION);
  17094. wgsl_group2_bits = _sg_validate_set_slot_bit(wgsl_group2_bits, SG_SHADERSTAGE_NONE, simg_desc->wgsl_group2_binding_n);
  17095. #endif
  17096. }
  17097. uint32_t img_slot_mask = 0;
  17098. for (size_t img_idx = 0; img_idx < SG_MAX_IMAGE_BINDSLOTS; img_idx++) {
  17099. const sg_shader_image* img_desc = &desc->images[img_idx];
  17100. if (img_desc->stage == SG_SHADERSTAGE_NONE) {
  17101. continue;
  17102. }
  17103. img_slot_mask |= (1 << img_idx);
  17104. #if defined(SOKOL_METAL)
  17105. _SG_VALIDATE(img_desc->msl_texture_n < _SG_MTL_MAX_STAGE_TEXTURE_BINDINGS, VALIDATE_SHADERDESC_IMAGE_METAL_TEXTURE_SLOT_OUT_OF_RANGE);
  17106. _SG_VALIDATE(_sg_validate_slot_bits(msl_tex_bits, img_desc->stage, img_desc->msl_texture_n), VALIDATE_SHADERDESC_IMAGE_METAL_TEXTURE_SLOT_COLLISION);
  17107. msl_tex_bits = _sg_validate_set_slot_bit(msl_tex_bits, img_desc->stage, img_desc->msl_texture_n);
  17108. #elif defined(SOKOL_D3D11)
  17109. _SG_VALIDATE(img_desc->hlsl_register_t_n < _SG_D3D11_MAX_STAGE_SRV_BINDINGS, VALIDATE_SHADERDESC_IMAGE_HLSL_REGISTER_T_OUT_OF_RANGE);
  17110. _SG_VALIDATE(_sg_validate_slot_bits(hlsl_srv_bits, img_desc->stage, img_desc->hlsl_register_t_n), VALIDATE_SHADERDESC_IMAGE_HLSL_REGISTER_T_COLLISION);
  17111. hlsl_srv_bits = _sg_validate_set_slot_bit(hlsl_srv_bits, img_desc->stage, img_desc->hlsl_register_t_n);
  17112. #elif defined(SOKOL_WGPU)
  17113. _SG_VALIDATE(img_desc->wgsl_group1_binding_n < _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS, VALIDATE_SHADERDESC_IMAGE_WGSL_GROUP1_BINDING_OUT_OF_RANGE);
  17114. _SG_VALIDATE(_sg_validate_slot_bits(wgsl_group1_bits, SG_SHADERSTAGE_NONE, img_desc->wgsl_group1_binding_n), VALIDATE_SHADERDESC_IMAGE_WGSL_GROUP1_BINDING_COLLISION);
  17115. wgsl_group1_bits = _sg_validate_set_slot_bit(wgsl_group1_bits, SG_SHADERSTAGE_NONE, img_desc->wgsl_group1_binding_n);
  17116. #endif
  17117. }
  17118. uint32_t smp_slot_mask = 0;
  17119. for (size_t smp_idx = 0; smp_idx < SG_MAX_SAMPLER_BINDSLOTS; smp_idx++) {
  17120. const sg_shader_sampler* smp_desc = &desc->samplers[smp_idx];
  17121. if (smp_desc->stage == SG_SHADERSTAGE_NONE) {
  17122. continue;
  17123. }
  17124. smp_slot_mask |= (1 << smp_idx);
  17125. #if defined(SOKOL_METAL)
  17126. _SG_VALIDATE(smp_desc->msl_sampler_n < _SG_MTL_MAX_STAGE_SAMPLER_BINDINGS, VALIDATE_SHADERDESC_SAMPLER_METAL_SAMPLER_SLOT_OUT_OF_RANGE);
  17127. _SG_VALIDATE(_sg_validate_slot_bits(msl_smp_bits, smp_desc->stage, smp_desc->msl_sampler_n), VALIDATE_SHADERDESC_SAMPLER_METAL_SAMPLER_SLOT_COLLISION);
  17128. msl_smp_bits = _sg_validate_set_slot_bit(msl_smp_bits, smp_desc->stage, smp_desc->msl_sampler_n);
  17129. #elif defined(SOKOL_D3D11)
  17130. _SG_VALIDATE(smp_desc->hlsl_register_s_n < _SG_D3D11_MAX_STAGE_SMP_BINDINGS, VALIDATE_SHADERDESC_SAMPLER_HLSL_REGISTER_S_OUT_OF_RANGE);
  17131. _SG_VALIDATE(_sg_validate_slot_bits(hlsl_smp_bits, smp_desc->stage, smp_desc->hlsl_register_s_n), VALIDATE_SHADERDESC_SAMPLER_HLSL_REGISTER_S_COLLISION);
  17132. hlsl_smp_bits = _sg_validate_set_slot_bit(hlsl_smp_bits, smp_desc->stage, smp_desc->hlsl_register_s_n);
  17133. #elif defined(SOKOL_WGPU)
  17134. _SG_VALIDATE(smp_desc->wgsl_group1_binding_n < _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS, VALIDATE_SHADERDESC_SAMPLER_WGSL_GROUP1_BINDING_OUT_OF_RANGE);
  17135. _SG_VALIDATE(_sg_validate_slot_bits(wgsl_group1_bits, SG_SHADERSTAGE_NONE, smp_desc->wgsl_group1_binding_n), VALIDATE_SHADERDESC_SAMPLER_WGSL_GROUP1_BINDING_COLLISION);
  17136. wgsl_group1_bits = _sg_validate_set_slot_bit(wgsl_group1_bits, SG_SHADERSTAGE_NONE, smp_desc->wgsl_group1_binding_n);
  17137. #endif
  17138. }
  17139. uint32_t ref_img_slot_mask = 0;
  17140. uint32_t ref_smp_slot_mask = 0;
  17141. for (size_t img_smp_idx = 0; img_smp_idx < SG_MAX_IMAGE_SAMPLER_PAIRS; img_smp_idx++) {
  17142. const sg_shader_image_sampler_pair* img_smp_desc = &desc->image_sampler_pairs[img_smp_idx];
  17143. if (img_smp_desc->stage == SG_SHADERSTAGE_NONE) {
  17144. continue;
  17145. }
  17146. #if defined(_SOKOL_ANY_GL)
  17147. _SG_VALIDATE(img_smp_desc->glsl_name != 0, VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_GLSL_NAME);
  17148. #endif
  17149. const bool img_slot_in_range = img_smp_desc->image_slot < SG_MAX_IMAGE_BINDSLOTS;
  17150. const bool smp_slot_in_range = img_smp_desc->sampler_slot < SG_MAX_SAMPLER_BINDSLOTS;
  17151. _SG_VALIDATE(img_slot_in_range, VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_IMAGE_SLOT_OUT_OF_RANGE);
  17152. _SG_VALIDATE(smp_slot_in_range, VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_SAMPLER_SLOT_OUT_OF_RANGE);
  17153. if (img_slot_in_range && smp_slot_in_range) {
  17154. ref_img_slot_mask |= 1 << img_smp_desc->image_slot;
  17155. ref_smp_slot_mask |= 1 << img_smp_desc->sampler_slot;
  17156. const sg_shader_image* img_desc = &desc->images[img_smp_desc->image_slot];
  17157. const sg_shader_sampler* smp_desc = &desc->samplers[img_smp_desc->sampler_slot];
  17158. _SG_VALIDATE(img_desc->stage == img_smp_desc->stage, VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_IMAGE_STAGE_MISMATCH);
  17159. _SG_VALIDATE(smp_desc->stage == img_smp_desc->stage, VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_SAMPLER_STAGE_MISMATCH);
  17160. const bool needs_nonfiltering = (img_desc->sample_type == SG_IMAGESAMPLETYPE_UINT)
  17161. || (img_desc->sample_type == SG_IMAGESAMPLETYPE_SINT)
  17162. || (img_desc->sample_type == SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT);
  17163. const bool needs_comparison = img_desc->sample_type == SG_IMAGESAMPLETYPE_DEPTH;
  17164. if (needs_nonfiltering) {
  17165. _SG_VALIDATE(needs_nonfiltering && (smp_desc->sampler_type == SG_SAMPLERTYPE_NONFILTERING), VALIDATE_SHADERDESC_NONFILTERING_SAMPLER_REQUIRED);
  17166. }
  17167. if (needs_comparison) {
  17168. _SG_VALIDATE(needs_comparison && (smp_desc->sampler_type == SG_SAMPLERTYPE_COMPARISON), VALIDATE_SHADERDESC_COMPARISON_SAMPLER_REQUIRED);
  17169. }
  17170. }
  17171. }
  17172. // each image and sampler must be referenced by an image sampler
  17173. _SG_VALIDATE(img_slot_mask == ref_img_slot_mask, VALIDATE_SHADERDESC_IMAGE_NOT_REFERENCED_BY_IMAGE_SAMPLER_PAIRS);
  17174. _SG_VALIDATE(smp_slot_mask == ref_smp_slot_mask, VALIDATE_SHADERDESC_SAMPLER_NOT_REFERENCED_BY_IMAGE_SAMPLER_PAIRS);
  17175. return _sg_validate_end();
  17176. #endif
  17177. }
  17178. _SOKOL_PRIVATE bool _sg_validate_pipeline_desc(const sg_pipeline_desc* desc) {
  17179. #if !defined(SOKOL_DEBUG)
  17180. _SOKOL_UNUSED(desc);
  17181. return true;
  17182. #else
  17183. if (_sg.desc.disable_validation) {
  17184. return true;
  17185. }
  17186. SOKOL_ASSERT(desc);
  17187. _sg_validate_begin();
  17188. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_PIPELINEDESC_CANARY);
  17189. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_PIPELINEDESC_CANARY);
  17190. _SG_VALIDATE(desc->shader.id != SG_INVALID_ID, VALIDATE_PIPELINEDESC_SHADER);
  17191. const _sg_shader_t* shd = _sg_lookup_shader(desc->shader.id);
  17192. _SG_VALIDATE(0 != shd, VALIDATE_PIPELINEDESC_SHADER);
  17193. if (shd) {
  17194. _SG_VALIDATE(shd->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_PIPELINEDESC_SHADER);
  17195. if (desc->compute) {
  17196. _SG_VALIDATE(shd->cmn.is_compute, VALIDATE_PIPELINEDESC_COMPUTE_SHADER_EXPECTED);
  17197. } else {
  17198. _SG_VALIDATE(!shd->cmn.is_compute, VALIDATE_PIPELINEDESC_NO_COMPUTE_SHADER_EXPECTED);
  17199. bool attrs_cont = true;
  17200. for (size_t attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  17201. const sg_vertex_attr_state* a_state = &desc->layout.attrs[attr_index];
  17202. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  17203. attrs_cont = false;
  17204. continue;
  17205. }
  17206. _SG_VALIDATE(attrs_cont, VALIDATE_PIPELINEDESC_NO_CONT_ATTRS);
  17207. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  17208. // vertex format must match expected shader attribute base type (if provided)
  17209. if (shd->cmn.attrs[attr_index].base_type != SG_SHADERATTRBASETYPE_UNDEFINED) {
  17210. if (_sg_vertexformat_basetype(a_state->format) != shd->cmn.attrs[attr_index].base_type) {
  17211. _SG_VALIDATE(false, VALIDATE_PIPELINEDESC_ATTR_BASETYPE_MISMATCH);
  17212. _SG_LOGMSG(VALIDATE_PIPELINEDESC_ATTR_BASETYPE_MISMATCH, "attr format:");
  17213. _SG_LOGMSG(VALIDATE_PIPELINEDESC_ATTR_BASETYPE_MISMATCH, _sg_vertexformat_to_string(a_state->format));
  17214. _SG_LOGMSG(VALIDATE_PIPELINEDESC_ATTR_BASETYPE_MISMATCH, "shader attr base type:");
  17215. _SG_LOGMSG(VALIDATE_PIPELINEDESC_ATTR_BASETYPE_MISMATCH, _sg_shaderattrbasetype_to_string(shd->cmn.attrs[attr_index].base_type));
  17216. }
  17217. }
  17218. #if defined(SOKOL_D3D11)
  17219. // on D3D11, semantic names (and semantic indices) must be provided
  17220. _SG_VALIDATE(!_sg_strempty(&shd->d3d11.attrs[attr_index].sem_name), VALIDATE_PIPELINEDESC_ATTR_SEMANTICS);
  17221. #endif
  17222. }
  17223. // must only use readonly storage buffer bindings in render pipelines
  17224. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  17225. if (shd->cmn.storage_buffers[i].stage != SG_SHADERSTAGE_NONE) {
  17226. _SG_VALIDATE(shd->cmn.storage_buffers[i].readonly, VALIDATE_PIPELINEDESC_SHADER_READONLY_STORAGEBUFFERS);
  17227. }
  17228. }
  17229. for (int buf_index = 0; buf_index < SG_MAX_VERTEXBUFFER_BINDSLOTS; buf_index++) {
  17230. const sg_vertex_buffer_layout_state* l_state = &desc->layout.buffers[buf_index];
  17231. if (l_state->stride == 0) {
  17232. continue;
  17233. }
  17234. _SG_VALIDATE(_sg_multiple_u64((uint64_t)l_state->stride, 4), VALIDATE_PIPELINEDESC_LAYOUT_STRIDE4);
  17235. }
  17236. }
  17237. }
  17238. for (size_t color_index = 0; color_index < (size_t)desc->color_count; color_index++) {
  17239. const sg_blend_state* bs = &desc->colors[color_index].blend;
  17240. if ((bs->op_rgb == SG_BLENDOP_MIN) || (bs->op_rgb == SG_BLENDOP_MAX)) {
  17241. _SG_VALIDATE((bs->src_factor_rgb == SG_BLENDFACTOR_ONE) && (bs->dst_factor_rgb == SG_BLENDFACTOR_ONE), VALIDATE_PIPELINEDESC_BLENDOP_MINMAX_REQUIRES_BLENDFACTOR_ONE);
  17242. }
  17243. if ((bs->op_alpha == SG_BLENDOP_MIN) || (bs->op_alpha == SG_BLENDOP_MAX)) {
  17244. _SG_VALIDATE((bs->src_factor_alpha == SG_BLENDFACTOR_ONE) && (bs->dst_factor_alpha == SG_BLENDFACTOR_ONE), VALIDATE_PIPELINEDESC_BLENDOP_MINMAX_REQUIRES_BLENDFACTOR_ONE);
  17245. }
  17246. }
  17247. return _sg_validate_end();
  17248. #endif
  17249. }
  17250. _SOKOL_PRIVATE bool _sg_validate_attachments_desc(const sg_attachments_desc* desc) {
  17251. #if !defined(SOKOL_DEBUG)
  17252. _SOKOL_UNUSED(desc);
  17253. return true;
  17254. #else
  17255. if (_sg.desc.disable_validation) {
  17256. return true;
  17257. }
  17258. SOKOL_ASSERT(desc);
  17259. _sg_validate_begin();
  17260. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_ATTACHMENTSDESC_CANARY);
  17261. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_ATTACHMENTSDESC_CANARY);
  17262. // check color attachments
  17263. bool has_color_atts = false;
  17264. bool has_depth_stencil_att = false;
  17265. {
  17266. bool atts_cont = true;
  17267. int color_width = -1, color_height = -1, color_sample_count = -1;
  17268. for (int att_index = 0; att_index < SG_MAX_COLOR_ATTACHMENTS; att_index++) {
  17269. const sg_attachment_desc* att = &desc->colors[att_index];
  17270. if (att->image.id == SG_INVALID_ID) {
  17271. atts_cont = false;
  17272. continue;
  17273. }
  17274. has_color_atts = true;
  17275. _SG_VALIDATE(atts_cont, VALIDATE_ATTACHMENTSDESC_NO_CONT_COLOR_ATTS);
  17276. const _sg_image_t* img = _sg_lookup_image(att->image.id);
  17277. _SG_VALIDATE(img, VALIDATE_ATTACHMENTSDESC_COLOR_IMAGE);
  17278. if (0 != img) {
  17279. _SG_VALIDATE(img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ATTACHMENTSDESC_COLOR_IMAGE);
  17280. _SG_VALIDATE(img->cmn.usage.render_attachment, VALIDATE_ATTACHMENTSDESC_COLOR_IMAGE_NO_RENDERATTACHMENT);
  17281. _SG_VALIDATE(att->mip_level < img->cmn.num_mipmaps, VALIDATE_ATTACHMENTSDESC_COLOR_MIPLEVEL);
  17282. if (img->cmn.type == SG_IMAGETYPE_CUBE) {
  17283. _SG_VALIDATE(att->slice < 6, VALIDATE_ATTACHMENTSDESC_COLOR_FACE);
  17284. } else if (img->cmn.type == SG_IMAGETYPE_ARRAY) {
  17285. _SG_VALIDATE(att->slice < img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_COLOR_LAYER);
  17286. } else if (img->cmn.type == SG_IMAGETYPE_3D) {
  17287. _SG_VALIDATE(att->slice < img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_COLOR_SLICE);
  17288. }
  17289. if (att_index == 0) {
  17290. color_width = _sg_miplevel_dim(img->cmn.width, att->mip_level);
  17291. color_height = _sg_miplevel_dim(img->cmn.height, att->mip_level);
  17292. color_sample_count = img->cmn.sample_count;
  17293. } else {
  17294. _SG_VALIDATE(color_width == _sg_miplevel_dim(img->cmn.width, att->mip_level), VALIDATE_ATTACHMENTSDESC_IMAGE_SIZES);
  17295. _SG_VALIDATE(color_height == _sg_miplevel_dim(img->cmn.height, att->mip_level), VALIDATE_ATTACHMENTSDESC_IMAGE_SIZES);
  17296. _SG_VALIDATE(color_sample_count == img->cmn.sample_count, VALIDATE_ATTACHMENTSDESC_IMAGE_SAMPLE_COUNTS);
  17297. }
  17298. _SG_VALIDATE(_sg_is_valid_attachment_color_format(img->cmn.pixel_format), VALIDATE_ATTACHMENTSDESC_COLOR_INV_PIXELFORMAT);
  17299. // check resolve attachment
  17300. const sg_attachment_desc* res_att = &desc->resolves[att_index];
  17301. if (res_att->image.id != SG_INVALID_ID) {
  17302. // associated color attachment must be MSAA
  17303. _SG_VALIDATE(img->cmn.sample_count > 1, VALIDATE_ATTACHMENTSDESC_RESOLVE_COLOR_IMAGE_MSAA);
  17304. const _sg_image_t* res_img = _sg_lookup_image(res_att->image.id);
  17305. _SG_VALIDATE(res_img, VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE);
  17306. if (res_img != 0) {
  17307. _SG_VALIDATE(res_img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE);
  17308. _SG_VALIDATE(res_img->cmn.usage.render_attachment, VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_NO_RT);
  17309. _SG_VALIDATE(res_img->cmn.sample_count == 1, VALIDATE_ATTACHMENTSDESC_RESOLVE_SAMPLE_COUNT);
  17310. _SG_VALIDATE(res_att->mip_level < res_img->cmn.num_mipmaps, VALIDATE_ATTACHMENTSDESC_RESOLVE_MIPLEVEL);
  17311. if (res_img->cmn.type == SG_IMAGETYPE_CUBE) {
  17312. _SG_VALIDATE(res_att->slice < SG_CUBEFACE_NUM, VALIDATE_ATTACHMENTSDESC_RESOLVE_FACE);
  17313. } else if (res_img->cmn.type == SG_IMAGETYPE_ARRAY) {
  17314. _SG_VALIDATE(res_att->slice < res_img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_RESOLVE_LAYER);
  17315. } else if (res_img->cmn.type == SG_IMAGETYPE_3D) {
  17316. _SG_VALIDATE(res_att->slice < res_img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_RESOLVE_SLICE);
  17317. }
  17318. _SG_VALIDATE(img->cmn.pixel_format == res_img->cmn.pixel_format, VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_FORMAT);
  17319. _SG_VALIDATE(color_width == _sg_miplevel_dim(res_img->cmn.width, res_att->mip_level), VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_SIZES);
  17320. _SG_VALIDATE(color_height == _sg_miplevel_dim(res_img->cmn.height, res_att->mip_level), VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_SIZES);
  17321. }
  17322. }
  17323. }
  17324. }
  17325. // check depth stencil attachments
  17326. if (desc->depth_stencil.image.id != SG_INVALID_ID) {
  17327. has_depth_stencil_att = true;
  17328. const sg_attachment_desc* att = &desc->depth_stencil;
  17329. const _sg_image_t* img = _sg_lookup_image(att->image.id);
  17330. _SG_VALIDATE(img, VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE);
  17331. if (img) {
  17332. _SG_VALIDATE(img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE);
  17333. _SG_VALIDATE(att->mip_level < img->cmn.num_mipmaps, VALIDATE_ATTACHMENTSDESC_DEPTH_MIPLEVEL);
  17334. if (img->cmn.type == SG_IMAGETYPE_CUBE) {
  17335. _SG_VALIDATE(att->slice < 6, VALIDATE_ATTACHMENTSDESC_DEPTH_FACE);
  17336. } else if (img->cmn.type == SG_IMAGETYPE_ARRAY) {
  17337. _SG_VALIDATE(att->slice < img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_DEPTH_LAYER);
  17338. } else if (img->cmn.type == SG_IMAGETYPE_3D) {
  17339. // NOTE: this can't actually happen because of VALIDATE_IMAGEDESC_DEPTH_3D_IMAGE
  17340. _SG_VALIDATE(att->slice < img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_DEPTH_SLICE);
  17341. }
  17342. _SG_VALIDATE(img->cmn.usage.render_attachment, VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_NO_RENDERATTACHMENT);
  17343. _SG_VALIDATE((color_width == -1) || (color_width == _sg_miplevel_dim(img->cmn.width, att->mip_level)), VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_SIZES);
  17344. _SG_VALIDATE((color_height == -1) || (color_height == _sg_miplevel_dim(img->cmn.height, att->mip_level)), VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_SIZES);
  17345. _SG_VALIDATE((color_sample_count == -1) || (color_sample_count == img->cmn.sample_count), VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_SAMPLE_COUNT);
  17346. _SG_VALIDATE(_sg_is_valid_attachment_depth_format(img->cmn.pixel_format), VALIDATE_ATTACHMENTSDESC_DEPTH_INV_PIXELFORMAT);
  17347. }
  17348. }
  17349. }
  17350. // check storage attachments (note: storage attachments don't need to continuous)
  17351. bool has_storage_atts = false;
  17352. {
  17353. for (int att_index = 0; att_index < SG_MAX_STORAGE_ATTACHMENTS; att_index++) {
  17354. const sg_attachment_desc* att = &desc->storages[att_index];
  17355. if (att->image.id == SG_INVALID_ID) {
  17356. continue;
  17357. }
  17358. has_storage_atts = true;
  17359. const _sg_image_t* img = _sg_lookup_image(att->image.id);
  17360. _SG_VALIDATE(img, VALIDATE_ATTACHMENTSDESC_STORAGE_IMAGE);
  17361. if (0 != img) {
  17362. _SG_VALIDATE(img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ATTACHMENTSDESC_STORAGE_IMAGE);
  17363. _SG_VALIDATE(img->cmn.usage.storage_attachment, VALIDATE_ATTACHMENTSDESC_STORAGE_IMAGE_NO_STORAGEATTACHMENT);
  17364. _SG_VALIDATE(att->mip_level < img->cmn.num_mipmaps, VALIDATE_ATTACHMENTSDESC_STORAGE_MIPLEVEL);
  17365. if (img->cmn.type == SG_IMAGETYPE_CUBE) {
  17366. _SG_VALIDATE(att->slice < 6, VALIDATE_ATTACHMENTSDESC_STORAGE_FACE);
  17367. } else if (img->cmn.type == SG_IMAGETYPE_ARRAY) {
  17368. _SG_VALIDATE(att->slice < img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_STORAGE_LAYER);
  17369. } else if (img->cmn.type == SG_IMAGETYPE_3D) {
  17370. _SG_VALIDATE(att->slice < img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_STORAGE_SLICE);
  17371. }
  17372. _SG_VALIDATE(_sg_is_valid_attachment_storage_format(img->cmn.pixel_format), VALIDATE_ATTACHMENTSDESC_STORAGE_INV_PIXELFORMAT);
  17373. }
  17374. }
  17375. }
  17376. _SG_VALIDATE(has_color_atts || has_depth_stencil_att || has_storage_atts, VALIDATE_ATTACHMENTSDESC_NO_ATTACHMENTS);
  17377. if (has_color_atts || has_depth_stencil_att) {
  17378. _SG_VALIDATE(!has_storage_atts, VALIDATE_ATTACHMENTSDESC_RENDER_VS_STORAGE_ATTACHMENTS);
  17379. }
  17380. if (has_storage_atts) {
  17381. _SG_VALIDATE(!(has_color_atts || has_depth_stencil_att), VALIDATE_ATTACHMENTSDESC_RENDER_VS_STORAGE_ATTACHMENTS);
  17382. }
  17383. return _sg_validate_end();
  17384. #endif
  17385. }
  17386. _SOKOL_PRIVATE bool _sg_validate_begin_pass(const sg_pass* pass) {
  17387. #if !defined(SOKOL_DEBUG)
  17388. _SOKOL_UNUSED(pass);
  17389. return true;
  17390. #else
  17391. if (_sg.desc.disable_validation) {
  17392. return true;
  17393. }
  17394. const bool is_compute_pass = pass->compute;
  17395. const bool is_swapchain_pass = !is_compute_pass && (pass->attachments.id == SG_INVALID_ID);
  17396. const bool is_offscreen_pass = !(is_compute_pass || is_swapchain_pass);
  17397. _sg_validate_begin();
  17398. _SG_VALIDATE(pass->_start_canary == 0, VALIDATE_BEGINPASS_CANARY);
  17399. _SG_VALIDATE(pass->_end_canary == 0, VALIDATE_BEGINPASS_CANARY);
  17400. if (is_compute_pass) {
  17401. // this is a compute pass with optional storage attachments
  17402. if (pass->attachments.id) {
  17403. const _sg_attachments_t* atts = _sg_lookup_attachments(pass->attachments.id);
  17404. if (atts) {
  17405. _SG_VALIDATE(atts->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_BEGINPASS_ATTACHMENTS_VALID);
  17406. _SG_VALIDATE(!atts->cmn.has_render_attachments, VALIDATE_BEGINPASS_COMPUTEPASS_STORAGE_ATTACHMENTS_ONLY);
  17407. for (int i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  17408. const _sg_image_ref_t* storage_img_ref = &atts->cmn.storages[i].image;
  17409. if (!_sg_image_ref_null(storage_img_ref)) {
  17410. _SG_VALIDATE(_sg_image_ref_alive(storage_img_ref), VALIDATE_BEGINPASS_STORAGE_ATTACHMENT_IMAGE);
  17411. _SG_VALIDATE(_sg_image_ref_ptr(storage_img_ref)->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_BEGINPASS_STORAGE_ATTACHMENT_IMAGE);
  17412. }
  17413. }
  17414. } else {
  17415. _SG_VALIDATE(atts != 0, VALIDATE_BEGINPASS_ATTACHMENTS_EXISTS);
  17416. }
  17417. }
  17418. } else if (is_swapchain_pass) {
  17419. // this is a swapchain pass
  17420. _SG_VALIDATE(pass->swapchain.width > 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_WIDTH);
  17421. _SG_VALIDATE(pass->swapchain.height > 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_HEIGHT);
  17422. _SG_VALIDATE(pass->swapchain.sample_count > 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_SAMPLECOUNT);
  17423. _SG_VALIDATE(pass->swapchain.color_format > SG_PIXELFORMAT_NONE, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_COLORFORMAT);
  17424. // NOTE: depth buffer is optional, so depth_format is allowed to be invalid
  17425. // NOTE: the GL framebuffer handle may actually be 0
  17426. #if defined(SOKOL_METAL)
  17427. _SG_VALIDATE(pass->swapchain.metal.current_drawable != 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_CURRENTDRAWABLE);
  17428. if (pass->swapchain.depth_format == SG_PIXELFORMAT_NONE) {
  17429. _SG_VALIDATE(pass->swapchain.metal.depth_stencil_texture == 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_DEPTHSTENCILTEXTURE_NOTSET);
  17430. } else {
  17431. _SG_VALIDATE(pass->swapchain.metal.depth_stencil_texture != 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_DEPTHSTENCILTEXTURE);
  17432. }
  17433. if (pass->swapchain.sample_count > 1) {
  17434. _SG_VALIDATE(pass->swapchain.metal.msaa_color_texture != 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_MSAACOLORTEXTURE);
  17435. } else {
  17436. _SG_VALIDATE(pass->swapchain.metal.msaa_color_texture == 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_MSAACOLORTEXTURE_NOTSET);
  17437. }
  17438. #elif defined(SOKOL_D3D11)
  17439. _SG_VALIDATE(pass->swapchain.d3d11.render_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RENDERVIEW);
  17440. if (pass->swapchain.depth_format == SG_PIXELFORMAT_NONE) {
  17441. _SG_VALIDATE(pass->swapchain.d3d11.depth_stencil_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_DEPTHSTENCILVIEW_NOTSET);
  17442. } else {
  17443. _SG_VALIDATE(pass->swapchain.d3d11.depth_stencil_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_DEPTHSTENCILVIEW);
  17444. }
  17445. if (pass->swapchain.sample_count > 1) {
  17446. _SG_VALIDATE(pass->swapchain.d3d11.resolve_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RESOLVEVIEW);
  17447. } else {
  17448. _SG_VALIDATE(pass->swapchain.d3d11.resolve_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RESOLVEVIEW_NOTSET);
  17449. }
  17450. #elif defined(SOKOL_WGPU)
  17451. _SG_VALIDATE(pass->swapchain.wgpu.render_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RENDERVIEW);
  17452. if (pass->swapchain.depth_format == SG_PIXELFORMAT_NONE) {
  17453. _SG_VALIDATE(pass->swapchain.wgpu.depth_stencil_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_DEPTHSTENCILVIEW_NOTSET);
  17454. } else {
  17455. _SG_VALIDATE(pass->swapchain.wgpu.depth_stencil_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_DEPTHSTENCILVIEW);
  17456. }
  17457. if (pass->swapchain.sample_count > 1) {
  17458. _SG_VALIDATE(pass->swapchain.wgpu.resolve_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RESOLVEVIEW);
  17459. } else {
  17460. _SG_VALIDATE(pass->swapchain.wgpu.resolve_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RESOLVEVIEW_NOTSET);
  17461. }
  17462. #endif
  17463. } else {
  17464. // this is an 'offscreen pass'
  17465. const _sg_attachments_t* atts = _sg_lookup_attachments(pass->attachments.id);
  17466. if (atts) {
  17467. _SG_VALIDATE(atts->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_BEGINPASS_ATTACHMENTS_VALID);
  17468. _SG_VALIDATE(!atts->cmn.has_storage_attachments, VALIDATE_BEGINPASS_RENDERPASS_RENDER_ATTACHMENTS_ONLY);
  17469. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  17470. const _sg_image_ref_t* color_img_ref = &atts->cmn.colors[i].image;
  17471. if (!_sg_image_ref_null(color_img_ref)) {
  17472. _SG_VALIDATE(_sg_image_ref_alive(color_img_ref), VALIDATE_BEGINPASS_COLOR_ATTACHMENT_IMAGE);
  17473. _SG_VALIDATE(_sg_image_ref_ptr(color_img_ref)->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_BEGINPASS_COLOR_ATTACHMENT_IMAGE);
  17474. }
  17475. const _sg_image_ref_t* resolve_img_ref = &atts->cmn.resolves[i].image;
  17476. if (!_sg_image_ref_null(resolve_img_ref)) {
  17477. _SG_VALIDATE(_sg_image_ref_alive(resolve_img_ref), VALIDATE_BEGINPASS_RESOLVE_ATTACHMENT_IMAGE);
  17478. _SG_VALIDATE(_sg_image_ref_ptr(resolve_img_ref)->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_BEGINPASS_RESOLVE_ATTACHMENT_IMAGE);
  17479. }
  17480. }
  17481. const _sg_image_ref_t* ds_img_ref = &atts->cmn.depth_stencil.image;
  17482. if (!_sg_image_ref_null(ds_img_ref)) {
  17483. _SG_VALIDATE(_sg_image_ref_alive(ds_img_ref), VALIDATE_BEGINPASS_DEPTHSTENCIL_ATTACHMENT_IMAGE);
  17484. _SG_VALIDATE(_sg_image_ref_ptr(ds_img_ref)->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_BEGINPASS_DEPTHSTENCIL_ATTACHMENT_IMAGE);
  17485. }
  17486. } else {
  17487. _SG_VALIDATE(atts != 0, VALIDATE_BEGINPASS_ATTACHMENTS_EXISTS);
  17488. }
  17489. }
  17490. if (is_compute_pass || is_offscreen_pass) {
  17491. _SG_VALIDATE(pass->swapchain.width == 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_WIDTH_NOTSET);
  17492. _SG_VALIDATE(pass->swapchain.height == 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_HEIGHT_NOTSET);
  17493. _SG_VALIDATE(pass->swapchain.sample_count == 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_SAMPLECOUNT_NOTSET);
  17494. _SG_VALIDATE(pass->swapchain.color_format == _SG_PIXELFORMAT_DEFAULT, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_COLORFORMAT_NOTSET);
  17495. _SG_VALIDATE(pass->swapchain.depth_format == _SG_PIXELFORMAT_DEFAULT, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_DEPTHFORMAT_NOTSET);
  17496. #if defined(SOKOL_METAL)
  17497. _SG_VALIDATE(pass->swapchain.metal.current_drawable == 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_CURRENTDRAWABLE_NOTSET);
  17498. _SG_VALIDATE(pass->swapchain.metal.depth_stencil_texture == 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_DEPTHSTENCILTEXTURE_NOTSET);
  17499. _SG_VALIDATE(pass->swapchain.metal.msaa_color_texture == 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_MSAACOLORTEXTURE_NOTSET);
  17500. #elif defined(SOKOL_D3D11)
  17501. _SG_VALIDATE(pass->swapchain.d3d11.render_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RENDERVIEW_NOTSET);
  17502. _SG_VALIDATE(pass->swapchain.d3d11.depth_stencil_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_DEPTHSTENCILVIEW_NOTSET);
  17503. _SG_VALIDATE(pass->swapchain.d3d11.resolve_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RESOLVEVIEW_NOTSET);
  17504. #elif defined(SOKOL_WGPU)
  17505. _SG_VALIDATE(pass->swapchain.wgpu.render_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RENDERVIEW_NOTSET);
  17506. _SG_VALIDATE(pass->swapchain.wgpu.depth_stencil_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_DEPTHSTENCILVIEW_NOTSET);
  17507. _SG_VALIDATE(pass->swapchain.wgpu.resolve_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RESOLVEVIEW_NOTSET);
  17508. #elif defined(_SOKOL_ANY_GL)
  17509. _SG_VALIDATE(pass->swapchain.gl.framebuffer == 0, VALIDATE_BEGINPASS_SWAPCHAIN_GL_EXPECT_FRAMEBUFFER_NOTSET);
  17510. #endif
  17511. }
  17512. return _sg_validate_end();
  17513. #endif
  17514. }
  17515. _SOKOL_PRIVATE bool _sg_validate_apply_viewport(int x, int y, int width, int height, bool origin_top_left) {
  17516. _SOKOL_UNUSED(x);
  17517. _SOKOL_UNUSED(y);
  17518. _SOKOL_UNUSED(width);
  17519. _SOKOL_UNUSED(height);
  17520. _SOKOL_UNUSED(origin_top_left);
  17521. #if !defined(SOKOL_DEBUG)
  17522. return true;
  17523. #else
  17524. if (_sg.desc.disable_validation) {
  17525. return true;
  17526. }
  17527. _sg_validate_begin();
  17528. _SG_VALIDATE(_sg.cur_pass.in_pass && !_sg.cur_pass.is_compute, VALIDATE_AVP_RENDERPASS_EXPECTED);
  17529. return _sg_validate_end();
  17530. #endif
  17531. }
  17532. _SOKOL_PRIVATE bool _sg_validate_apply_scissor_rect(int x, int y, int width, int height, bool origin_top_left) {
  17533. _SOKOL_UNUSED(x);
  17534. _SOKOL_UNUSED(y);
  17535. _SOKOL_UNUSED(width);
  17536. _SOKOL_UNUSED(height);
  17537. _SOKOL_UNUSED(origin_top_left);
  17538. #if !defined(SOKOL_DEBUG)
  17539. return true;
  17540. #else
  17541. if (_sg.desc.disable_validation) {
  17542. return true;
  17543. }
  17544. _sg_validate_begin();
  17545. _SG_VALIDATE(_sg.cur_pass.in_pass && !_sg.cur_pass.is_compute, VALIDATE_ASR_RENDERPASS_EXPECTED);
  17546. return _sg_validate_end();
  17547. #endif
  17548. }
  17549. _SOKOL_PRIVATE bool _sg_validate_apply_pipeline(sg_pipeline pip_id) {
  17550. #if !defined(SOKOL_DEBUG)
  17551. _SOKOL_UNUSED(pip_id);
  17552. return true;
  17553. #else
  17554. if (_sg.desc.disable_validation) {
  17555. return true;
  17556. }
  17557. _sg_validate_begin();
  17558. // the pipeline object must be alive and valid
  17559. _SG_VALIDATE(pip_id.id != SG_INVALID_ID, VALIDATE_APIP_PIPELINE_VALID_ID);
  17560. const _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  17561. _SG_VALIDATE(pip != 0, VALIDATE_APIP_PIPELINE_EXISTS);
  17562. if (!pip) {
  17563. return _sg_validate_end();
  17564. }
  17565. _SG_VALIDATE(pip->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_APIP_PIPELINE_VALID);
  17566. // the pipeline's shader must be alive and valid
  17567. _SG_VALIDATE(_sg.cur_pass.in_pass, VALIDATE_APIP_PASS_EXPECTED);
  17568. _SG_VALIDATE(_sg_shader_ref_alive(&pip->cmn.shader), VALIDATE_APIP_PIPELINE_SHADER_ALIVE);
  17569. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  17570. _SG_VALIDATE(shd->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_APIP_PIPELINE_SHADER_VALID);
  17571. // if pass attachments exist, check that the attachment object is still valid
  17572. bool has_attachments = !_sg_attachments_ref_null(&_sg.cur_pass.atts);
  17573. if (has_attachments) {
  17574. _SG_VALIDATE(_sg_attachments_ref_alive(&_sg.cur_pass.atts), VALIDATE_APIP_CURPASS_ATTACHMENTS_ALIVE);
  17575. const _sg_attachments_t* atts = _sg_attachments_ref_ptr(&_sg.cur_pass.atts);
  17576. _SG_VALIDATE(atts->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_APIP_CURPASS_ATTACHMENTS_VALID);
  17577. }
  17578. if (pip->cmn.is_compute) {
  17579. _SG_VALIDATE(_sg.cur_pass.is_compute, VALIDATE_APIP_COMPUTEPASS_EXPECTED);
  17580. if (has_attachments) {
  17581. const _sg_attachments_t* atts = _sg_attachments_ref_ptr(&_sg.cur_pass.atts);
  17582. // a compute pass with storage attachments
  17583. // check that the pass storage attachments match the shader expectations
  17584. for (int i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  17585. if (shd->cmn.storage_images[i].stage != SG_SHADERSTAGE_NONE) {
  17586. const _sg_image_ref_t* img_ref = &atts->cmn.storages[i].image;
  17587. bool img_null = _sg_image_ref_null(img_ref);
  17588. bool img_alive = _sg_image_ref_alive(img_ref);
  17589. _SG_VALIDATE(!img_null, VALIDATE_APIP_EXPECTED_STORAGE_ATTACHMENT_IMAGE);
  17590. if (!img_null) {
  17591. _SG_VALIDATE(img_alive, VALIDATE_APIP_STORAGE_ATTACHMENT_IMAGE_ALIVE);
  17592. if (img_alive) {
  17593. const _sg_image_t* img = _sg_image_ref_ptr(img_ref);
  17594. _SG_VALIDATE(img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_APIP_STORAGE_ATTACHMENT_IMAGE_VALID);
  17595. _SG_VALIDATE(img->cmn.pixel_format == shd->cmn.storage_images[i].access_format, VALIDATE_APIP_STORAGE_ATTACHMENT_PIXELFORMAT);
  17596. _SG_VALIDATE(img->cmn.type == shd->cmn.storage_images[i].image_type, VALIDATE_APIP_STORAGE_ATTACHMENT_IMAGE_TYPE);
  17597. }
  17598. }
  17599. }
  17600. }
  17601. }
  17602. } else {
  17603. _SG_VALIDATE(!_sg.cur_pass.is_compute, VALIDATE_APIP_RENDERPASS_EXPECTED);
  17604. // check that pipeline attributes match current pass attributes
  17605. if (has_attachments) {
  17606. const _sg_attachments_t* atts = _sg_attachments_ref_ptr(&_sg.cur_pass.atts);
  17607. // an offscreen pass
  17608. _SG_VALIDATE(pip->cmn.color_count == atts->cmn.num_colors, VALIDATE_APIP_ATT_COUNT);
  17609. for (int i = 0; i < pip->cmn.color_count; i++) {
  17610. const _sg_image_t* att_img = _sg_image_ref_ptr(&atts->cmn.colors[i].image);
  17611. _SG_VALIDATE(pip->cmn.colors[i].pixel_format == att_img->cmn.pixel_format, VALIDATE_APIP_COLOR_FORMAT);
  17612. _SG_VALIDATE(pip->cmn.sample_count == att_img->cmn.sample_count, VALIDATE_APIP_SAMPLE_COUNT);
  17613. }
  17614. if (!_sg_image_ref_null(&atts->cmn.depth_stencil.image)) {
  17615. _SG_VALIDATE(pip->cmn.depth.pixel_format == _sg_image_ref_ptr(&atts->cmn.depth_stencil.image)->cmn.pixel_format, VALIDATE_APIP_DEPTH_FORMAT);
  17616. } else {
  17617. _SG_VALIDATE(pip->cmn.depth.pixel_format == SG_PIXELFORMAT_NONE, VALIDATE_APIP_DEPTH_FORMAT);
  17618. }
  17619. } else {
  17620. // default pass
  17621. _SG_VALIDATE(pip->cmn.color_count == 1, VALIDATE_APIP_ATT_COUNT);
  17622. _SG_VALIDATE(pip->cmn.colors[0].pixel_format == _sg.cur_pass.swapchain.color_fmt, VALIDATE_APIP_COLOR_FORMAT);
  17623. _SG_VALIDATE(pip->cmn.depth.pixel_format == _sg.cur_pass.swapchain.depth_fmt, VALIDATE_APIP_DEPTH_FORMAT);
  17624. _SG_VALIDATE(pip->cmn.sample_count == _sg.cur_pass.swapchain.sample_count, VALIDATE_APIP_SAMPLE_COUNT);
  17625. }
  17626. }
  17627. return _sg_validate_end();
  17628. #endif
  17629. }
  17630. _SOKOL_PRIVATE bool _sg_validate_apply_bindings(const sg_bindings* bindings) {
  17631. #if !defined(SOKOL_DEBUG)
  17632. _SOKOL_UNUSED(bindings);
  17633. return true;
  17634. #else
  17635. if (_sg.desc.disable_validation) {
  17636. return true;
  17637. }
  17638. _sg_validate_begin();
  17639. // must be called in a pass
  17640. _SG_VALIDATE(_sg.cur_pass.in_pass, VALIDATE_ABND_PASS_EXPECTED);
  17641. // bindings must not be empty
  17642. bool has_any_bindings = bindings->index_buffer.id != SG_INVALID_ID;
  17643. if (!has_any_bindings) for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  17644. has_any_bindings |= bindings->vertex_buffers[i].id != SG_INVALID_ID;
  17645. }
  17646. if (!has_any_bindings) for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  17647. has_any_bindings |= bindings->images[i].id != SG_INVALID_ID;
  17648. }
  17649. if (!has_any_bindings) for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  17650. has_any_bindings |= bindings->samplers[i].id != SG_INVALID_ID;
  17651. }
  17652. if (!has_any_bindings) for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  17653. has_any_bindings |= bindings->storage_buffers[i].id != SG_INVALID_ID;
  17654. }
  17655. _SG_VALIDATE(has_any_bindings, VALIDATE_ABND_EMPTY_BINDINGS);
  17656. // a pipeline object must have been applied
  17657. _SG_VALIDATE(!_sg_pipeline_ref_null(&_sg.cur_pip), VALIDATE_ABND_NO_PIPELINE);
  17658. const bool pip_alive = _sg_pipeline_ref_alive(&_sg.cur_pip);
  17659. _SG_VALIDATE(pip_alive, VALIDATE_ABND_PIPELINE_ALIVE);
  17660. if (!pip_alive) {
  17661. return _sg_validate_end();
  17662. }
  17663. const _sg_pipeline_t* pip = _sg_pipeline_ref_ptr(&_sg.cur_pip);
  17664. _SG_VALIDATE(pip->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ABND_PIPELINE_VALID);
  17665. _SG_VALIDATE(_sg_shader_ref_alive(&pip->cmn.shader), VALIDATE_ABND_PIPELINE_SHADER_ALIVE);
  17666. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  17667. _SG_VALIDATE(shd->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ABND_PIPELINE_SHADER_VALID);
  17668. if (_sg.cur_pass.is_compute) {
  17669. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  17670. _SG_VALIDATE(bindings->vertex_buffers[i].id == SG_INVALID_ID, VALIDATE_ABND_COMPUTE_EXPECTED_NO_VBS);
  17671. }
  17672. } else {
  17673. // has expected vertex buffers, and vertex buffers still exist
  17674. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  17675. if (pip->cmn.vertex_buffer_layout_active[i]) {
  17676. _SG_VALIDATE(bindings->vertex_buffers[i].id != SG_INVALID_ID, VALIDATE_ABND_EXPECTED_VB);
  17677. // buffers in vertex-buffer-slots must have vertex buffer usage
  17678. if (bindings->vertex_buffers[i].id != SG_INVALID_ID) {
  17679. const _sg_buffer_t* buf = _sg_lookup_buffer(bindings->vertex_buffers[i].id);
  17680. _SG_VALIDATE(buf != 0, VALIDATE_ABND_VB_ALIVE);
  17681. if (buf && buf->slot.state == SG_RESOURCESTATE_VALID) {
  17682. _SG_VALIDATE(buf->cmn.usage.vertex_buffer, VALIDATE_ABND_VB_TYPE);
  17683. _SG_VALIDATE(!buf->cmn.append_overflow, VALIDATE_ABND_VB_OVERFLOW);
  17684. }
  17685. }
  17686. }
  17687. }
  17688. }
  17689. if (_sg.cur_pass.is_compute) {
  17690. _SG_VALIDATE(bindings->index_buffer.id == SG_INVALID_ID, VALIDATE_ABND_COMPUTE_EXPECTED_NO_IB);
  17691. } else {
  17692. // index buffer expected or not, and index buffer still exists
  17693. if (pip->cmn.index_type == SG_INDEXTYPE_NONE) {
  17694. // pipeline defines non-indexed rendering, but index buffer provided
  17695. _SG_VALIDATE(bindings->index_buffer.id == SG_INVALID_ID, VALIDATE_ABND_IB);
  17696. } else {
  17697. // pipeline defines indexed rendering, but no index buffer provided
  17698. _SG_VALIDATE(bindings->index_buffer.id != SG_INVALID_ID, VALIDATE_ABND_NO_IB);
  17699. }
  17700. if (bindings->index_buffer.id != SG_INVALID_ID) {
  17701. // buffer in index-buffer-slot must have index buffer usage
  17702. const _sg_buffer_t* buf = _sg_lookup_buffer(bindings->index_buffer.id);
  17703. _SG_VALIDATE(buf != 0, VALIDATE_ABND_IB_ALIVE);
  17704. if (buf && buf->slot.state == SG_RESOURCESTATE_VALID) {
  17705. _SG_VALIDATE(buf->cmn.usage.index_buffer, VALIDATE_ABND_IB_TYPE);
  17706. _SG_VALIDATE(!buf->cmn.append_overflow, VALIDATE_ABND_IB_OVERFLOW);
  17707. }
  17708. }
  17709. }
  17710. // has expected images
  17711. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  17712. if (shd->cmn.images[i].stage != SG_SHADERSTAGE_NONE) {
  17713. _SG_VALIDATE(bindings->images[i].id != SG_INVALID_ID, VALIDATE_ABND_EXPECTED_IMAGE_BINDING);
  17714. if (bindings->images[i].id != SG_INVALID_ID) {
  17715. const _sg_image_t* img = _sg_lookup_image(bindings->images[i].id);
  17716. _SG_VALIDATE(img != 0, VALIDATE_ABND_IMG_ALIVE);
  17717. if (img && img->slot.state == SG_RESOURCESTATE_VALID) {
  17718. _SG_VALIDATE(img->cmn.type == shd->cmn.images[i].image_type, VALIDATE_ABND_IMAGE_TYPE_MISMATCH);
  17719. if (!_sg.features.msaa_image_bindings) {
  17720. _SG_VALIDATE(img->cmn.sample_count == 1, VALIDATE_ABND_IMAGE_MSAA);
  17721. }
  17722. if (shd->cmn.images[i].multisampled) {
  17723. _SG_VALIDATE(img->cmn.sample_count > 1, VALIDATE_ABND_EXPECTED_MULTISAMPLED_IMAGE);
  17724. }
  17725. const _sg_pixelformat_info_t* info = &_sg.formats[img->cmn.pixel_format];
  17726. switch (shd->cmn.images[i].sample_type) {
  17727. case SG_IMAGESAMPLETYPE_FLOAT:
  17728. _SG_VALIDATE(info->filter, VALIDATE_ABND_EXPECTED_FILTERABLE_IMAGE);
  17729. break;
  17730. case SG_IMAGESAMPLETYPE_DEPTH:
  17731. _SG_VALIDATE(info->depth, VALIDATE_ABND_EXPECTED_DEPTH_IMAGE);
  17732. break;
  17733. default:
  17734. break;
  17735. }
  17736. }
  17737. }
  17738. }
  17739. }
  17740. // has expected samplers
  17741. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  17742. if (shd->cmn.samplers[i].stage != SG_SHADERSTAGE_NONE) {
  17743. _SG_VALIDATE(bindings->samplers[i].id != SG_INVALID_ID, VALIDATE_ABND_EXPECTED_SAMPLER_BINDING);
  17744. if (bindings->samplers[i].id != SG_INVALID_ID) {
  17745. const _sg_sampler_t* smp = _sg_lookup_sampler(bindings->samplers[i].id);
  17746. _SG_VALIDATE(smp != 0, VALIDATE_ABND_SMP_ALIVE);
  17747. if (smp) {
  17748. if (shd->cmn.samplers[i].sampler_type == SG_SAMPLERTYPE_COMPARISON) {
  17749. _SG_VALIDATE(smp->cmn.compare != SG_COMPAREFUNC_NEVER, VALIDATE_ABND_UNEXPECTED_SAMPLER_COMPARE_NEVER);
  17750. } else {
  17751. _SG_VALIDATE(smp->cmn.compare == SG_COMPAREFUNC_NEVER, VALIDATE_ABND_EXPECTED_SAMPLER_COMPARE_NEVER);
  17752. }
  17753. if (shd->cmn.samplers[i].sampler_type == SG_SAMPLERTYPE_NONFILTERING) {
  17754. const bool nonfiltering = (smp->cmn.min_filter != SG_FILTER_LINEAR)
  17755. && (smp->cmn.mag_filter != SG_FILTER_LINEAR)
  17756. && (smp->cmn.mipmap_filter != SG_FILTER_LINEAR);
  17757. _SG_VALIDATE(nonfiltering, VALIDATE_ABND_EXPECTED_NONFILTERING_SAMPLER);
  17758. }
  17759. }
  17760. }
  17761. }
  17762. }
  17763. // has expected storage buffers
  17764. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  17765. if (shd->cmn.storage_buffers[i].stage != SG_SHADERSTAGE_NONE) {
  17766. _SG_VALIDATE(bindings->storage_buffers[i].id != SG_INVALID_ID, VALIDATE_ABND_EXPECTED_STORAGEBUFFER_BINDING);
  17767. if (bindings->storage_buffers[i].id != SG_INVALID_ID) {
  17768. const _sg_buffer_t* sbuf = _sg_lookup_buffer(bindings->storage_buffers[i].id);
  17769. _SG_VALIDATE(sbuf != 0, VALIDATE_ABND_STORAGEBUFFER_ALIVE);
  17770. if (sbuf) {
  17771. _SG_VALIDATE(sbuf->cmn.usage.storage_buffer, VALIDATE_ABND_STORAGEBUFFER_BINDING_BUFFERTYPE);
  17772. // read/write bindings are only allowed for immutable buffers
  17773. if (!shd->cmn.storage_buffers[i].readonly) {
  17774. _SG_VALIDATE(sbuf->cmn.usage.immutable, VALIDATE_ABND_STORAGEBUFFER_READWRITE_IMMUTABLE);
  17775. }
  17776. }
  17777. }
  17778. }
  17779. }
  17780. // the same image cannot be bound as texture and pass attachment
  17781. if (!_sg_attachments_ref_null(&_sg.cur_pass.atts)) {
  17782. const _sg_attachments_t* atts = _sg_attachments_ref_ptr(&_sg.cur_pass.atts);
  17783. for (size_t img_idx = 0; img_idx < SG_MAX_IMAGE_BINDSLOTS; img_idx++) {
  17784. if (shd->cmn.images[img_idx].stage != SG_SHADERSTAGE_NONE) {
  17785. const uint32_t img_id = bindings->images[img_idx].id;
  17786. if (img_id == SG_INVALID_ID) {
  17787. continue;
  17788. }
  17789. _SG_VALIDATE(img_id != atts->cmn.depth_stencil.image.sref.id, VALIDATE_ABND_IMAGE_BINDING_VS_DEPTHSTENCIL_ATTACHMENT);
  17790. for (size_t att_idx = 0; att_idx < SG_MAX_COLOR_ATTACHMENTS; att_idx++) {
  17791. _SG_VALIDATE(img_id != atts->cmn.colors[att_idx].image.sref.id, VALIDATE_ABND_IMAGE_BINDING_VS_COLOR_ATTACHMENT);
  17792. _SG_VALIDATE(img_id != atts->cmn.resolves[att_idx].image.sref.id, VALIDATE_ABND_IMAGE_BINDING_VS_RESOLVE_ATTACHMENT);
  17793. }
  17794. for (size_t att_idx = 0; att_idx < SG_MAX_STORAGE_ATTACHMENTS; att_idx++) {
  17795. _SG_VALIDATE(img_id != atts->cmn.storages[att_idx].image.sref.id, VALIDATE_ABND_IMAGE_BINDING_VS_STORAGE_ATTACHMENT);
  17796. }
  17797. }
  17798. }
  17799. }
  17800. return _sg_validate_end();
  17801. #endif
  17802. }
  17803. _SOKOL_PRIVATE bool _sg_validate_apply_uniforms(int ub_slot, const sg_range* data) {
  17804. #if !defined(SOKOL_DEBUG)
  17805. _SOKOL_UNUSED(ub_slot);
  17806. _SOKOL_UNUSED(data);
  17807. return true;
  17808. #else
  17809. if (_sg.desc.disable_validation) {
  17810. return true;
  17811. }
  17812. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  17813. _sg_validate_begin();
  17814. _SG_VALIDATE(_sg.cur_pass.in_pass, VALIDATE_AU_PASS_EXPECTED);
  17815. _SG_VALIDATE(!_sg_pipeline_ref_null(&_sg.cur_pip), VALIDATE_AU_NO_PIPELINE);
  17816. _SG_VALIDATE(_sg_pipeline_ref_alive(&_sg.cur_pip), VALIDATE_AU_PIPELINE_ALIVE);
  17817. const _sg_pipeline_t* pip = _sg_pipeline_ref_ptr(&_sg.cur_pip);
  17818. _SG_VALIDATE(pip->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_AU_PIPELINE_VALID);
  17819. _SG_VALIDATE(_sg_shader_ref_alive(&pip->cmn.shader), VALIDATE_AU_PIPELINE_SHADER_ALIVE);
  17820. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  17821. _SG_VALIDATE(shd->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_AU_PIPELINE_SHADER_VALID);
  17822. _SG_VALIDATE(shd->cmn.uniform_blocks[ub_slot].stage != SG_SHADERSTAGE_NONE, VALIDATE_AU_NO_UNIFORMBLOCK_AT_SLOT);
  17823. _SG_VALIDATE(data->size == shd->cmn.uniform_blocks[ub_slot].size, VALIDATE_AU_SIZE);
  17824. return _sg_validate_end();
  17825. #endif
  17826. }
  17827. _SOKOL_PRIVATE bool _sg_validate_draw(int base_element, int num_elements, int num_instances) {
  17828. #if !defined(SOKOL_DEBUG)
  17829. _SOKOL_UNUSED(base_element);
  17830. _SOKOL_UNUSED(num_elements);
  17831. _SOKOL_UNUSED(num_instances);
  17832. return true;
  17833. #else
  17834. if (_sg.desc.disable_validation) {
  17835. return true;
  17836. }
  17837. _sg_validate_begin();
  17838. _SG_VALIDATE(_sg.cur_pass.in_pass && !_sg.cur_pass.is_compute, VALIDATE_DRAW_RENDERPASS_EXPECTED);
  17839. _SG_VALIDATE(base_element >= 0, VALIDATE_DRAW_BASEELEMENT);
  17840. _SG_VALIDATE(num_elements >= 0, VALIDATE_DRAW_NUMELEMENTS);
  17841. _SG_VALIDATE(num_instances >= 0, VALIDATE_DRAW_NUMINSTANCES);
  17842. _SG_VALIDATE(_sg.required_bindings_and_uniforms == _sg.applied_bindings_and_uniforms, VALIDATE_DRAW_REQUIRED_BINDINGS_OR_UNIFORMS_MISSING);
  17843. return _sg_validate_end();
  17844. #endif
  17845. }
  17846. _SOKOL_PRIVATE bool _sg_validate_dispatch(int num_groups_x, int num_groups_y, int num_groups_z) {
  17847. #if !defined(SOKOL_DEBUG)
  17848. _SOKOL_UNUSED(num_groups_x);
  17849. _SOKOL_UNUSED(num_groups_y);
  17850. _SOKOL_UNUSED(num_groups_z);
  17851. return true;
  17852. #else
  17853. if (_sg.desc.disable_validation) {
  17854. return true;
  17855. }
  17856. _sg_validate_begin();
  17857. _SG_VALIDATE(_sg.cur_pass.in_pass && _sg.cur_pass.is_compute, VALIDATE_DISPATCH_COMPUTEPASS_EXPECTED);
  17858. _SG_VALIDATE((num_groups_x >= 0) && (num_groups_x < (1<<16)), VALIDATE_DISPATCH_NUMGROUPSX);
  17859. _SG_VALIDATE((num_groups_y >= 0) && (num_groups_y < (1<<16)), VALIDATE_DISPATCH_NUMGROUPSY);
  17860. _SG_VALIDATE((num_groups_z >= 0) && (num_groups_z < (1<<16)), VALIDATE_DISPATCH_NUMGROUPSZ);
  17861. _SG_VALIDATE(_sg.required_bindings_and_uniforms == _sg.applied_bindings_and_uniforms, VALIDATE_DRAW_REQUIRED_BINDINGS_OR_UNIFORMS_MISSING);
  17862. return _sg_validate_end();
  17863. #endif
  17864. }
  17865. _SOKOL_PRIVATE bool _sg_validate_update_buffer(const _sg_buffer_t* buf, const sg_range* data) {
  17866. #if !defined(SOKOL_DEBUG)
  17867. _SOKOL_UNUSED(buf);
  17868. _SOKOL_UNUSED(data);
  17869. return true;
  17870. #else
  17871. if (_sg.desc.disable_validation) {
  17872. return true;
  17873. }
  17874. SOKOL_ASSERT(buf && data && data->ptr);
  17875. _sg_validate_begin();
  17876. _SG_VALIDATE(!buf->cmn.usage.immutable, VALIDATE_UPDATEBUF_USAGE);
  17877. _SG_VALIDATE(buf->cmn.size >= (int)data->size, VALIDATE_UPDATEBUF_SIZE);
  17878. _SG_VALIDATE(buf->cmn.update_frame_index != _sg.frame_index, VALIDATE_UPDATEBUF_ONCE);
  17879. _SG_VALIDATE(buf->cmn.append_frame_index != _sg.frame_index, VALIDATE_UPDATEBUF_APPEND);
  17880. return _sg_validate_end();
  17881. #endif
  17882. }
  17883. _SOKOL_PRIVATE bool _sg_validate_append_buffer(const _sg_buffer_t* buf, const sg_range* data) {
  17884. #if !defined(SOKOL_DEBUG)
  17885. _SOKOL_UNUSED(buf);
  17886. _SOKOL_UNUSED(data);
  17887. return true;
  17888. #else
  17889. if (_sg.desc.disable_validation) {
  17890. return true;
  17891. }
  17892. SOKOL_ASSERT(buf && data && data->ptr);
  17893. _sg_validate_begin();
  17894. _SG_VALIDATE(!buf->cmn.usage.immutable, VALIDATE_APPENDBUF_USAGE);
  17895. _SG_VALIDATE(buf->cmn.size >= (buf->cmn.append_pos + (int)data->size), VALIDATE_APPENDBUF_SIZE);
  17896. _SG_VALIDATE(buf->cmn.update_frame_index != _sg.frame_index, VALIDATE_APPENDBUF_UPDATE);
  17897. return _sg_validate_end();
  17898. #endif
  17899. }
  17900. _SOKOL_PRIVATE bool _sg_validate_update_image(const _sg_image_t* img, const sg_image_data* data) {
  17901. #if !defined(SOKOL_DEBUG)
  17902. _SOKOL_UNUSED(img);
  17903. _SOKOL_UNUSED(data);
  17904. return true;
  17905. #else
  17906. if (_sg.desc.disable_validation) {
  17907. return true;
  17908. }
  17909. SOKOL_ASSERT(img && data);
  17910. _sg_validate_begin();
  17911. _SG_VALIDATE(!img->cmn.usage.immutable, VALIDATE_UPDIMG_USAGE);
  17912. _SG_VALIDATE(img->cmn.upd_frame_index != _sg.frame_index, VALIDATE_UPDIMG_ONCE);
  17913. _sg_validate_image_data(data,
  17914. img->cmn.pixel_format,
  17915. img->cmn.width,
  17916. img->cmn.height,
  17917. (img->cmn.type == SG_IMAGETYPE_CUBE) ? 6 : 1,
  17918. img->cmn.num_mipmaps,
  17919. img->cmn.num_slices);
  17920. return _sg_validate_end();
  17921. #endif
  17922. }
  17923. // ██████ ███████ ███████ ██████ ██ ██ ██████ ██████ ███████ ███████
  17924. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  17925. // ██████ █████ ███████ ██ ██ ██ ██ ██████ ██ █████ ███████
  17926. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  17927. // ██ ██ ███████ ███████ ██████ ██████ ██ ██ ██████ ███████ ███████
  17928. //
  17929. // >>resources
  17930. _SOKOL_PRIVATE sg_buffer_usage _sg_buffer_usage_defaults(const sg_buffer_usage* usg) {
  17931. sg_buffer_usage def = *usg;
  17932. if (!(def.vertex_buffer || def.index_buffer || def.storage_buffer)) {
  17933. def.vertex_buffer = true;
  17934. }
  17935. if (!(def.immutable || def.stream_update || def.dynamic_update)) {
  17936. def.immutable = true;
  17937. }
  17938. return def;
  17939. }
  17940. _SOKOL_PRIVATE sg_buffer_desc _sg_buffer_desc_defaults(const sg_buffer_desc* desc) {
  17941. sg_buffer_desc def = *desc;
  17942. def.usage = _sg_buffer_usage_defaults(&def.usage);
  17943. if (def.size == 0) {
  17944. def.size = def.data.size;
  17945. }
  17946. return def;
  17947. }
  17948. _SOKOL_PRIVATE sg_image_usage _sg_image_usage_defaults(const sg_image_usage *usg) {
  17949. sg_image_usage def = *usg;
  17950. if (!(def.immutable || def.stream_update || def.dynamic_update)) {
  17951. def.immutable = true;
  17952. }
  17953. return def;
  17954. }
  17955. _SOKOL_PRIVATE sg_image_desc _sg_image_desc_defaults(const sg_image_desc* desc) {
  17956. sg_image_desc def = *desc;
  17957. def.type = _sg_def(def.type, SG_IMAGETYPE_2D);
  17958. def.usage = _sg_image_usage_defaults(&def.usage);
  17959. def.num_slices = _sg_def(def.num_slices, 1);
  17960. def.num_mipmaps = _sg_def(def.num_mipmaps, 1);
  17961. if (def.usage.render_attachment) {
  17962. def.pixel_format = _sg_def(def.pixel_format, _sg.desc.environment.defaults.color_format);
  17963. def.sample_count = _sg_def(def.sample_count, _sg.desc.environment.defaults.sample_count);
  17964. } else {
  17965. def.pixel_format = _sg_def(def.pixel_format, SG_PIXELFORMAT_RGBA8);
  17966. def.sample_count = _sg_def(def.sample_count, 1);
  17967. }
  17968. return def;
  17969. }
  17970. _SOKOL_PRIVATE sg_sampler_desc _sg_sampler_desc_defaults(const sg_sampler_desc* desc) {
  17971. sg_sampler_desc def = *desc;
  17972. def.min_filter = _sg_def(def.min_filter, SG_FILTER_NEAREST);
  17973. def.mag_filter = _sg_def(def.mag_filter, SG_FILTER_NEAREST);
  17974. def.mipmap_filter = _sg_def(def.mipmap_filter, SG_FILTER_NEAREST);
  17975. def.wrap_u = _sg_def(def.wrap_u, SG_WRAP_REPEAT);
  17976. def.wrap_v = _sg_def(def.wrap_v, SG_WRAP_REPEAT);
  17977. def.wrap_w = _sg_def(def.wrap_w, SG_WRAP_REPEAT);
  17978. def.max_lod = _sg_def_flt(def.max_lod, FLT_MAX);
  17979. def.border_color = _sg_def(def.border_color, SG_BORDERCOLOR_OPAQUE_BLACK);
  17980. def.compare = _sg_def(def.compare, SG_COMPAREFUNC_NEVER);
  17981. def.max_anisotropy = _sg_def(def.max_anisotropy, 1);
  17982. return def;
  17983. }
  17984. _SOKOL_PRIVATE sg_shader_desc _sg_shader_desc_defaults(const sg_shader_desc* desc) {
  17985. sg_shader_desc def = *desc;
  17986. #if defined(SOKOL_METAL)
  17987. def.vertex_func.entry = _sg_def(def.vertex_func.entry, "_main");
  17988. def.fragment_func.entry = _sg_def(def.fragment_func.entry, "_main");
  17989. def.compute_func.entry = _sg_def(def.compute_func.entry, "_main");
  17990. #else
  17991. def.vertex_func.entry = _sg_def(def.vertex_func.entry, "main");
  17992. def.fragment_func.entry = _sg_def(def.fragment_func.entry, "main");
  17993. def.compute_func.entry = _sg_def(def.compute_func.entry, "main");
  17994. #endif
  17995. #if defined(SOKOL_D3D11)
  17996. if (def.vertex_func.source) {
  17997. def.vertex_func.d3d11_target = _sg_def(def.vertex_func.d3d11_target, "vs_4_0");
  17998. }
  17999. if (def.fragment_func.source) {
  18000. def.fragment_func.d3d11_target = _sg_def(def.fragment_func.d3d11_target, "ps_4_0");
  18001. }
  18002. if (def.compute_func.source) {
  18003. def.compute_func.d3d11_target = _sg_def(def.fragment_func.d3d11_target,"cs_5_0");
  18004. }
  18005. #endif
  18006. def.mtl_threads_per_threadgroup.y = _sg_def(desc->mtl_threads_per_threadgroup.y, 1);
  18007. def.mtl_threads_per_threadgroup.z = _sg_def(desc->mtl_threads_per_threadgroup.z, 1);
  18008. for (size_t ub_index = 0; ub_index < SG_MAX_UNIFORMBLOCK_BINDSLOTS; ub_index++) {
  18009. sg_shader_uniform_block* ub_desc = &def.uniform_blocks[ub_index];
  18010. if (ub_desc->stage != SG_SHADERSTAGE_NONE) {
  18011. ub_desc->layout = _sg_def(ub_desc->layout, SG_UNIFORMLAYOUT_NATIVE);
  18012. for (size_t u_index = 0; u_index < SG_MAX_UNIFORMBLOCK_MEMBERS; u_index++) {
  18013. sg_glsl_shader_uniform* u_desc = &ub_desc->glsl_uniforms[u_index];
  18014. if (u_desc->type == SG_UNIFORMTYPE_INVALID) {
  18015. break;
  18016. }
  18017. u_desc->array_count = _sg_def(u_desc->array_count, 1);
  18018. }
  18019. }
  18020. }
  18021. for (size_t img_index = 0; img_index < SG_MAX_IMAGE_BINDSLOTS; img_index++) {
  18022. sg_shader_image* img_desc = &def.images[img_index];
  18023. if (img_desc->stage != SG_SHADERSTAGE_NONE) {
  18024. img_desc->image_type = _sg_def(img_desc->image_type, SG_IMAGETYPE_2D);
  18025. img_desc->sample_type = _sg_def(img_desc->sample_type, SG_IMAGESAMPLETYPE_FLOAT);
  18026. }
  18027. }
  18028. for (size_t smp_index = 0; smp_index < SG_MAX_SAMPLER_BINDSLOTS; smp_index++) {
  18029. sg_shader_sampler* smp_desc = &def.samplers[smp_index];
  18030. if (smp_desc->stage != SG_SHADERSTAGE_NONE) {
  18031. smp_desc->sampler_type = _sg_def(smp_desc->sampler_type, SG_SAMPLERTYPE_FILTERING);
  18032. }
  18033. }
  18034. return def;
  18035. }
  18036. _SOKOL_PRIVATE sg_pipeline_desc _sg_pipeline_desc_defaults(const sg_pipeline_desc* desc) {
  18037. sg_pipeline_desc def = *desc;
  18038. // FIXME: should we actually do all this stuff for a compute pipeline?
  18039. def.primitive_type = _sg_def(def.primitive_type, SG_PRIMITIVETYPE_TRIANGLES);
  18040. def.index_type = _sg_def(def.index_type, SG_INDEXTYPE_NONE);
  18041. def.cull_mode = _sg_def(def.cull_mode, SG_CULLMODE_NONE);
  18042. def.face_winding = _sg_def(def.face_winding, SG_FACEWINDING_CW);
  18043. def.sample_count = _sg_def(def.sample_count, _sg.desc.environment.defaults.sample_count);
  18044. def.stencil.front.compare = _sg_def(def.stencil.front.compare, SG_COMPAREFUNC_ALWAYS);
  18045. def.stencil.front.fail_op = _sg_def(def.stencil.front.fail_op, SG_STENCILOP_KEEP);
  18046. def.stencil.front.depth_fail_op = _sg_def(def.stencil.front.depth_fail_op, SG_STENCILOP_KEEP);
  18047. def.stencil.front.pass_op = _sg_def(def.stencil.front.pass_op, SG_STENCILOP_KEEP);
  18048. def.stencil.back.compare = _sg_def(def.stencil.back.compare, SG_COMPAREFUNC_ALWAYS);
  18049. def.stencil.back.fail_op = _sg_def(def.stencil.back.fail_op, SG_STENCILOP_KEEP);
  18050. def.stencil.back.depth_fail_op = _sg_def(def.stencil.back.depth_fail_op, SG_STENCILOP_KEEP);
  18051. def.stencil.back.pass_op = _sg_def(def.stencil.back.pass_op, SG_STENCILOP_KEEP);
  18052. def.depth.compare = _sg_def(def.depth.compare, SG_COMPAREFUNC_ALWAYS);
  18053. def.depth.pixel_format = _sg_def(def.depth.pixel_format, _sg.desc.environment.defaults.depth_format);
  18054. if (def.colors[0].pixel_format == SG_PIXELFORMAT_NONE) {
  18055. // special case depth-only rendering, enforce a color count of 0
  18056. def.color_count = 0;
  18057. } else {
  18058. def.color_count = _sg_def(def.color_count, 1);
  18059. }
  18060. if (def.color_count > SG_MAX_COLOR_ATTACHMENTS) {
  18061. def.color_count = SG_MAX_COLOR_ATTACHMENTS;
  18062. }
  18063. for (int i = 0; i < def.color_count; i++) {
  18064. sg_color_target_state* cs = &def.colors[i];
  18065. cs->pixel_format = _sg_def(cs->pixel_format, _sg.desc.environment.defaults.color_format);
  18066. cs->write_mask = _sg_def(cs->write_mask, SG_COLORMASK_RGBA);
  18067. sg_blend_state* bs = &def.colors[i].blend;
  18068. bs->op_rgb = _sg_def(bs->op_rgb, SG_BLENDOP_ADD);
  18069. bs->src_factor_rgb = _sg_def(bs->src_factor_rgb, SG_BLENDFACTOR_ONE);
  18070. if ((bs->op_rgb == SG_BLENDOP_MIN) || (bs->op_rgb == SG_BLENDOP_MAX)) {
  18071. bs->dst_factor_rgb = _sg_def(bs->dst_factor_rgb, SG_BLENDFACTOR_ONE);
  18072. } else {
  18073. bs->dst_factor_rgb = _sg_def(bs->dst_factor_rgb, SG_BLENDFACTOR_ZERO);
  18074. }
  18075. bs->op_alpha = _sg_def(bs->op_alpha, SG_BLENDOP_ADD);
  18076. bs->src_factor_alpha = _sg_def(bs->src_factor_alpha, SG_BLENDFACTOR_ONE);
  18077. if ((bs->op_alpha == SG_BLENDOP_MIN) || (bs->op_alpha == SG_BLENDOP_MAX)) {
  18078. bs->dst_factor_alpha = _sg_def(bs->dst_factor_alpha, SG_BLENDFACTOR_ONE);
  18079. } else {
  18080. bs->dst_factor_alpha = _sg_def(bs->dst_factor_alpha, SG_BLENDFACTOR_ZERO);
  18081. }
  18082. }
  18083. for (int attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  18084. sg_vertex_attr_state* a_state = &def.layout.attrs[attr_index];
  18085. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  18086. break;
  18087. }
  18088. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  18089. sg_vertex_buffer_layout_state* l_state = &def.layout.buffers[a_state->buffer_index];
  18090. l_state->step_func = _sg_def(l_state->step_func, SG_VERTEXSTEP_PER_VERTEX);
  18091. l_state->step_rate = _sg_def(l_state->step_rate, 1);
  18092. }
  18093. // resolve vertex layout strides and offsets
  18094. int auto_offset[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  18095. _sg_clear(auto_offset, sizeof(auto_offset));
  18096. bool use_auto_offset = true;
  18097. for (int attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  18098. // to use computed offsets, *all* attr offsets must be 0
  18099. if (def.layout.attrs[attr_index].offset != 0) {
  18100. use_auto_offset = false;
  18101. }
  18102. }
  18103. for (int attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  18104. sg_vertex_attr_state* a_state = &def.layout.attrs[attr_index];
  18105. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  18106. break;
  18107. }
  18108. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  18109. if (use_auto_offset) {
  18110. a_state->offset = auto_offset[a_state->buffer_index];
  18111. }
  18112. auto_offset[a_state->buffer_index] += _sg_vertexformat_bytesize(a_state->format);
  18113. }
  18114. // compute vertex strides if needed
  18115. for (int buf_index = 0; buf_index < SG_MAX_VERTEXBUFFER_BINDSLOTS; buf_index++) {
  18116. sg_vertex_buffer_layout_state* l_state = &def.layout.buffers[buf_index];
  18117. if (l_state->stride == 0) {
  18118. l_state->stride = auto_offset[buf_index];
  18119. }
  18120. }
  18121. return def;
  18122. }
  18123. _SOKOL_PRIVATE sg_attachments_desc _sg_attachments_desc_defaults(const sg_attachments_desc* desc) {
  18124. sg_attachments_desc def = *desc;
  18125. return def;
  18126. }
  18127. _SOKOL_PRIVATE sg_buffer _sg_alloc_buffer(void) {
  18128. sg_buffer res;
  18129. int slot_index = _sg_pool_alloc_index(&_sg.pools.buffer_pool);
  18130. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  18131. res.id = _sg_slot_alloc(&_sg.pools.buffer_pool, &_sg.pools.buffers[slot_index].slot, slot_index);
  18132. } else {
  18133. res.id = SG_INVALID_ID;
  18134. _SG_ERROR(BUFFER_POOL_EXHAUSTED);
  18135. }
  18136. return res;
  18137. }
  18138. _SOKOL_PRIVATE sg_image _sg_alloc_image(void) {
  18139. sg_image res;
  18140. int slot_index = _sg_pool_alloc_index(&_sg.pools.image_pool);
  18141. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  18142. res.id = _sg_slot_alloc(&_sg.pools.image_pool, &_sg.pools.images[slot_index].slot, slot_index);
  18143. } else {
  18144. res.id = SG_INVALID_ID;
  18145. _SG_ERROR(IMAGE_POOL_EXHAUSTED);
  18146. }
  18147. return res;
  18148. }
  18149. _SOKOL_PRIVATE sg_sampler _sg_alloc_sampler(void) {
  18150. sg_sampler res;
  18151. int slot_index = _sg_pool_alloc_index(&_sg.pools.sampler_pool);
  18152. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  18153. res.id = _sg_slot_alloc(&_sg.pools.sampler_pool, &_sg.pools.samplers[slot_index].slot, slot_index);
  18154. } else {
  18155. res.id = SG_INVALID_ID;
  18156. _SG_ERROR(SAMPLER_POOL_EXHAUSTED);
  18157. }
  18158. return res;
  18159. }
  18160. _SOKOL_PRIVATE sg_shader _sg_alloc_shader(void) {
  18161. sg_shader res;
  18162. int slot_index = _sg_pool_alloc_index(&_sg.pools.shader_pool);
  18163. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  18164. res.id = _sg_slot_alloc(&_sg.pools.shader_pool, &_sg.pools.shaders[slot_index].slot, slot_index);
  18165. } else {
  18166. res.id = SG_INVALID_ID;
  18167. _SG_ERROR(SHADER_POOL_EXHAUSTED);
  18168. }
  18169. return res;
  18170. }
  18171. _SOKOL_PRIVATE sg_pipeline _sg_alloc_pipeline(void) {
  18172. sg_pipeline res;
  18173. int slot_index = _sg_pool_alloc_index(&_sg.pools.pipeline_pool);
  18174. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  18175. res.id =_sg_slot_alloc(&_sg.pools.pipeline_pool, &_sg.pools.pipelines[slot_index].slot, slot_index);
  18176. } else {
  18177. res.id = SG_INVALID_ID;
  18178. _SG_ERROR(PIPELINE_POOL_EXHAUSTED);
  18179. }
  18180. return res;
  18181. }
  18182. _SOKOL_PRIVATE sg_attachments _sg_alloc_attachments(void) {
  18183. sg_attachments res;
  18184. int slot_index = _sg_pool_alloc_index(&_sg.pools.attachments_pool);
  18185. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  18186. res.id = _sg_slot_alloc(&_sg.pools.attachments_pool, &_sg.pools.attachments[slot_index].slot, slot_index);
  18187. } else {
  18188. res.id = SG_INVALID_ID;
  18189. _SG_ERROR(PASS_POOL_EXHAUSTED);
  18190. }
  18191. return res;
  18192. }
  18193. _SOKOL_PRIVATE void _sg_dealloc_buffer(_sg_buffer_t* buf) {
  18194. SOKOL_ASSERT(buf && (buf->slot.state == SG_RESOURCESTATE_ALLOC) && (buf->slot.id != SG_INVALID_ID));
  18195. _sg_pool_free_index(&_sg.pools.buffer_pool, _sg_slot_index(buf->slot.id));
  18196. _sg_slot_reset(&buf->slot);
  18197. }
  18198. _SOKOL_PRIVATE void _sg_dealloc_image(_sg_image_t* img) {
  18199. SOKOL_ASSERT(img && (img->slot.state == SG_RESOURCESTATE_ALLOC) && (img->slot.id != SG_INVALID_ID));
  18200. _sg_pool_free_index(&_sg.pools.image_pool, _sg_slot_index(img->slot.id));
  18201. _sg_slot_reset(&img->slot);
  18202. }
  18203. _SOKOL_PRIVATE void _sg_dealloc_sampler(_sg_sampler_t* smp) {
  18204. SOKOL_ASSERT(smp && (smp->slot.state == SG_RESOURCESTATE_ALLOC) && (smp->slot.id != SG_INVALID_ID));
  18205. _sg_pool_free_index(&_sg.pools.sampler_pool, _sg_slot_index(smp->slot.id));
  18206. _sg_slot_reset(&smp->slot);
  18207. }
  18208. _SOKOL_PRIVATE void _sg_dealloc_shader(_sg_shader_t* shd) {
  18209. SOKOL_ASSERT(shd && (shd->slot.state == SG_RESOURCESTATE_ALLOC) && (shd->slot.id != SG_INVALID_ID));
  18210. _sg_pool_free_index(&_sg.pools.shader_pool, _sg_slot_index(shd->slot.id));
  18211. _sg_slot_reset(&shd->slot);
  18212. }
  18213. _SOKOL_PRIVATE void _sg_dealloc_pipeline(_sg_pipeline_t* pip) {
  18214. SOKOL_ASSERT(pip && (pip->slot.state == SG_RESOURCESTATE_ALLOC) && (pip->slot.id != SG_INVALID_ID));
  18215. _sg_pool_free_index(&_sg.pools.pipeline_pool, _sg_slot_index(pip->slot.id));
  18216. _sg_slot_reset(&pip->slot);
  18217. }
  18218. _SOKOL_PRIVATE void _sg_dealloc_attachments(_sg_attachments_t* atts) {
  18219. SOKOL_ASSERT(atts && (atts->slot.state == SG_RESOURCESTATE_ALLOC) && (atts->slot.id != SG_INVALID_ID));
  18220. _sg_pool_free_index(&_sg.pools.attachments_pool, _sg_slot_index(atts->slot.id));
  18221. _sg_slot_reset(&atts->slot);
  18222. }
  18223. _SOKOL_PRIVATE void _sg_init_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  18224. SOKOL_ASSERT(buf && (buf->slot.state == SG_RESOURCESTATE_ALLOC));
  18225. SOKOL_ASSERT(desc);
  18226. if (_sg_validate_buffer_desc(desc)) {
  18227. _sg_buffer_common_init(&buf->cmn, desc);
  18228. buf->slot.state = _sg_create_buffer(buf, desc);
  18229. } else {
  18230. buf->slot.state = SG_RESOURCESTATE_FAILED;
  18231. }
  18232. SOKOL_ASSERT((buf->slot.state == SG_RESOURCESTATE_VALID)||(buf->slot.state == SG_RESOURCESTATE_FAILED));
  18233. }
  18234. _SOKOL_PRIVATE void _sg_init_image(_sg_image_t* img, const sg_image_desc* desc) {
  18235. SOKOL_ASSERT(img && (img->slot.state == SG_RESOURCESTATE_ALLOC));
  18236. SOKOL_ASSERT(desc);
  18237. if (_sg_validate_image_desc(desc)) {
  18238. _sg_image_common_init(&img->cmn, desc);
  18239. img->slot.state = _sg_create_image(img, desc);
  18240. } else {
  18241. img->slot.state = SG_RESOURCESTATE_FAILED;
  18242. }
  18243. SOKOL_ASSERT((img->slot.state == SG_RESOURCESTATE_VALID)||(img->slot.state == SG_RESOURCESTATE_FAILED));
  18244. }
  18245. _SOKOL_PRIVATE void _sg_init_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  18246. SOKOL_ASSERT(smp && (smp->slot.state == SG_RESOURCESTATE_ALLOC));
  18247. SOKOL_ASSERT(desc);
  18248. if (_sg_validate_sampler_desc(desc)) {
  18249. _sg_sampler_common_init(&smp->cmn, desc);
  18250. smp->slot.state = _sg_create_sampler(smp, desc);
  18251. } else {
  18252. smp->slot.state = SG_RESOURCESTATE_FAILED;
  18253. }
  18254. SOKOL_ASSERT((smp->slot.state == SG_RESOURCESTATE_VALID)||(smp->slot.state == SG_RESOURCESTATE_FAILED));
  18255. }
  18256. _SOKOL_PRIVATE void _sg_init_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  18257. SOKOL_ASSERT(shd && (shd->slot.state == SG_RESOURCESTATE_ALLOC));
  18258. SOKOL_ASSERT(desc);
  18259. if (_sg_validate_shader_desc(desc)) {
  18260. _sg_shader_common_init(&shd->cmn, desc);
  18261. shd->slot.state = _sg_create_shader(shd, desc);
  18262. } else {
  18263. shd->slot.state = SG_RESOURCESTATE_FAILED;
  18264. }
  18265. SOKOL_ASSERT((shd->slot.state == SG_RESOURCESTATE_VALID)||(shd->slot.state == SG_RESOURCESTATE_FAILED));
  18266. }
  18267. _SOKOL_PRIVATE void _sg_init_pipeline(_sg_pipeline_t* pip, const sg_pipeline_desc* desc) {
  18268. SOKOL_ASSERT(pip && (pip->slot.state == SG_RESOURCESTATE_ALLOC));
  18269. SOKOL_ASSERT(desc);
  18270. if (_sg_validate_pipeline_desc(desc)) {
  18271. _sg_shader_t* shd = _sg_lookup_shader(desc->shader.id);
  18272. if (shd && (shd->slot.state == SG_RESOURCESTATE_VALID)) {
  18273. _sg_pipeline_common_init(&pip->cmn, desc, shd);
  18274. pip->slot.state = _sg_create_pipeline(pip, desc);
  18275. } else {
  18276. pip->slot.state = SG_RESOURCESTATE_FAILED;
  18277. }
  18278. } else {
  18279. pip->slot.state = SG_RESOURCESTATE_FAILED;
  18280. }
  18281. SOKOL_ASSERT((pip->slot.state == SG_RESOURCESTATE_VALID)||(pip->slot.state == SG_RESOURCESTATE_FAILED));
  18282. }
  18283. _SOKOL_PRIVATE void _sg_init_attachments(_sg_attachments_t* atts, const sg_attachments_desc* desc) {
  18284. SOKOL_ASSERT(atts && atts->slot.state == SG_RESOURCESTATE_ALLOC);
  18285. SOKOL_ASSERT(desc);
  18286. if (_sg_validate_attachments_desc(desc)) {
  18287. // resolve image pointers, track width and height of render attachments,
  18288. // the validation layer already ensured that render attachments have the
  18289. // same width and height (which doesn't matter for storage attachments)
  18290. _sg_attachments_ptrs_t atts_ptrs;
  18291. _sg_clear(&atts_ptrs, sizeof(atts_ptrs));
  18292. int width = 0;
  18293. int height = 0;
  18294. for (size_t i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  18295. if (desc->colors[i].image.id) {
  18296. _sg_image_t* img = _sg_lookup_image(desc->colors[i].image.id);
  18297. if (!(img && img->slot.state == SG_RESOURCESTATE_VALID)) {
  18298. atts->slot.state = SG_RESOURCESTATE_FAILED;
  18299. return;
  18300. }
  18301. const int mip_level = desc->colors[i].mip_level;
  18302. width = _sg_miplevel_dim(img->cmn.width, mip_level);
  18303. height = _sg_miplevel_dim(img->cmn.height, mip_level);
  18304. atts_ptrs.color_images[i] = img;
  18305. }
  18306. if (desc->resolves[i].image.id) {
  18307. _sg_image_t* img = _sg_lookup_image(desc->resolves[i].image.id);
  18308. if (!(img && img->slot.state == SG_RESOURCESTATE_VALID)) {
  18309. atts->slot.state = SG_RESOURCESTATE_FAILED;
  18310. return;
  18311. }
  18312. atts_ptrs.resolve_images[i] = img;
  18313. }
  18314. }
  18315. if (desc->depth_stencil.image.id) {
  18316. _sg_image_t* img = _sg_lookup_image(desc->depth_stencil.image.id);
  18317. if (!(img && img->slot.state == SG_RESOURCESTATE_VALID)) {
  18318. atts->slot.state = SG_RESOURCESTATE_FAILED;
  18319. return;
  18320. }
  18321. const int mip_level = desc->depth_stencil.mip_level;
  18322. width = _sg_miplevel_dim(img->cmn.width, mip_level);
  18323. height = _sg_miplevel_dim(img->cmn.height, mip_level);
  18324. atts_ptrs.ds_image = img;
  18325. }
  18326. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  18327. if (desc->storages[i].image.id) {
  18328. _sg_image_t* img = _sg_lookup_image(desc->storages[i].image.id);
  18329. if (!(img && img->slot.state == SG_RESOURCESTATE_VALID)) {
  18330. atts->slot.state = SG_RESOURCESTATE_FAILED;
  18331. return;
  18332. }
  18333. atts_ptrs.storage_images[i] = img;
  18334. }
  18335. }
  18336. _sg_attachments_common_init(&atts->cmn, desc, &atts_ptrs, width, height);
  18337. atts->slot.state = _sg_create_attachments(atts, desc);
  18338. } else {
  18339. atts->slot.state = SG_RESOURCESTATE_FAILED;
  18340. }
  18341. SOKOL_ASSERT((atts->slot.state == SG_RESOURCESTATE_VALID)||(atts->slot.state == SG_RESOURCESTATE_FAILED));
  18342. }
  18343. _SOKOL_PRIVATE void _sg_uninit_buffer(_sg_buffer_t* buf) {
  18344. SOKOL_ASSERT(buf && ((buf->slot.state == SG_RESOURCESTATE_VALID) || (buf->slot.state == SG_RESOURCESTATE_FAILED)));
  18345. _sg_discard_buffer(buf);
  18346. _sg_reset_buffer_to_alloc_state(buf);
  18347. }
  18348. _SOKOL_PRIVATE void _sg_uninit_image(_sg_image_t* img) {
  18349. SOKOL_ASSERT(img && ((img->slot.state == SG_RESOURCESTATE_VALID) || (img->slot.state == SG_RESOURCESTATE_FAILED)));
  18350. _sg_discard_image(img);
  18351. _sg_reset_image_to_alloc_state(img);
  18352. }
  18353. _SOKOL_PRIVATE void _sg_uninit_sampler(_sg_sampler_t* smp) {
  18354. SOKOL_ASSERT(smp && ((smp->slot.state == SG_RESOURCESTATE_VALID) || (smp->slot.state == SG_RESOURCESTATE_FAILED)));
  18355. _sg_discard_sampler(smp);
  18356. _sg_reset_sampler_to_alloc_state(smp);
  18357. }
  18358. _SOKOL_PRIVATE void _sg_uninit_shader(_sg_shader_t* shd) {
  18359. SOKOL_ASSERT(shd && ((shd->slot.state == SG_RESOURCESTATE_VALID) || (shd->slot.state == SG_RESOURCESTATE_FAILED)));
  18360. _sg_discard_shader(shd);
  18361. _sg_reset_shader_to_alloc_state(shd);
  18362. }
  18363. _SOKOL_PRIVATE void _sg_uninit_pipeline(_sg_pipeline_t* pip) {
  18364. SOKOL_ASSERT(pip && ((pip->slot.state == SG_RESOURCESTATE_VALID) || (pip->slot.state == SG_RESOURCESTATE_FAILED)));
  18365. _sg_discard_pipeline(pip);
  18366. _sg_reset_pipeline_to_alloc_state(pip);
  18367. }
  18368. _SOKOL_PRIVATE void _sg_uninit_attachments(_sg_attachments_t* atts) {
  18369. SOKOL_ASSERT(atts && ((atts->slot.state == SG_RESOURCESTATE_VALID) || (atts->slot.state == SG_RESOURCESTATE_FAILED)));
  18370. _sg_discard_attachments(atts);
  18371. _sg_reset_attachments_to_alloc_state(atts);
  18372. }
  18373. _SOKOL_PRIVATE void _sg_setup_commit_listeners(const sg_desc* desc) {
  18374. SOKOL_ASSERT(desc->max_commit_listeners > 0);
  18375. SOKOL_ASSERT(0 == _sg.commit_listeners.items);
  18376. SOKOL_ASSERT(0 == _sg.commit_listeners.num);
  18377. SOKOL_ASSERT(0 == _sg.commit_listeners.upper);
  18378. _sg.commit_listeners.num = desc->max_commit_listeners;
  18379. const size_t size = (size_t)_sg.commit_listeners.num * sizeof(sg_commit_listener);
  18380. _sg.commit_listeners.items = (sg_commit_listener*)_sg_malloc_clear(size);
  18381. }
  18382. _SOKOL_PRIVATE void _sg_discard_commit_listeners(void) {
  18383. SOKOL_ASSERT(0 != _sg.commit_listeners.items);
  18384. _sg_free(_sg.commit_listeners.items);
  18385. _sg.commit_listeners.items = 0;
  18386. }
  18387. _SOKOL_PRIVATE void _sg_notify_commit_listeners(void) {
  18388. SOKOL_ASSERT(_sg.commit_listeners.items);
  18389. for (int i = 0; i < _sg.commit_listeners.upper; i++) {
  18390. const sg_commit_listener* listener = &_sg.commit_listeners.items[i];
  18391. if (listener->func) {
  18392. listener->func(listener->user_data);
  18393. }
  18394. }
  18395. }
  18396. _SOKOL_PRIVATE bool _sg_add_commit_listener(const sg_commit_listener* new_listener) {
  18397. SOKOL_ASSERT(new_listener && new_listener->func);
  18398. SOKOL_ASSERT(_sg.commit_listeners.items);
  18399. // first check if the listener hadn't been added already
  18400. for (int i = 0; i < _sg.commit_listeners.upper; i++) {
  18401. const sg_commit_listener* slot = &_sg.commit_listeners.items[i];
  18402. if ((slot->func == new_listener->func) && (slot->user_data == new_listener->user_data)) {
  18403. _SG_ERROR(IDENTICAL_COMMIT_LISTENER);
  18404. return false;
  18405. }
  18406. }
  18407. // first try to plug a hole
  18408. sg_commit_listener* slot = 0;
  18409. for (int i = 0; i < _sg.commit_listeners.upper; i++) {
  18410. if (_sg.commit_listeners.items[i].func == 0) {
  18411. slot = &_sg.commit_listeners.items[i];
  18412. break;
  18413. }
  18414. }
  18415. if (!slot) {
  18416. // append to end
  18417. if (_sg.commit_listeners.upper < _sg.commit_listeners.num) {
  18418. slot = &_sg.commit_listeners.items[_sg.commit_listeners.upper++];
  18419. }
  18420. }
  18421. if (!slot) {
  18422. _SG_ERROR(COMMIT_LISTENER_ARRAY_FULL);
  18423. return false;
  18424. }
  18425. *slot = *new_listener;
  18426. return true;
  18427. }
  18428. _SOKOL_PRIVATE bool _sg_remove_commit_listener(const sg_commit_listener* listener) {
  18429. SOKOL_ASSERT(listener && listener->func);
  18430. SOKOL_ASSERT(_sg.commit_listeners.items);
  18431. for (int i = 0; i < _sg.commit_listeners.upper; i++) {
  18432. sg_commit_listener* slot = &_sg.commit_listeners.items[i];
  18433. // both the function pointer and user data must match!
  18434. if ((slot->func == listener->func) && (slot->user_data == listener->user_data)) {
  18435. slot->func = 0;
  18436. slot->user_data = 0;
  18437. // NOTE: since _sg_add_commit_listener() already catches duplicates,
  18438. // we don't need to worry about them here
  18439. return true;
  18440. }
  18441. }
  18442. return false;
  18443. }
  18444. _SOKOL_PRIVATE void _sg_setup_compute(const sg_desc* desc) {
  18445. SOKOL_ASSERT(desc && (desc->max_dispatch_calls_per_pass > 0));
  18446. const uint32_t max_tracked_sbufs = (uint32_t)desc->max_dispatch_calls_per_pass * SG_MAX_STORAGEBUFFER_BINDSLOTS;
  18447. _sg_tracker_init(&_sg.compute.readwrite_sbufs, max_tracked_sbufs);
  18448. }
  18449. _SOKOL_PRIVATE void _sg_discard_compute(void) {
  18450. _sg_tracker_discard(&_sg.compute.readwrite_sbufs);
  18451. }
  18452. _SOKOL_PRIVATE void _sg_compute_pass_track_storage_buffer(_sg_buffer_t* sbuf, bool readonly) {
  18453. SOKOL_ASSERT(sbuf);
  18454. if (!readonly) {
  18455. _sg_tracker_add(&_sg.compute.readwrite_sbufs, sbuf->slot.id);
  18456. }
  18457. }
  18458. _SOKOL_PRIVATE void _sg_compute_on_endpass(void) {
  18459. SOKOL_ASSERT(_sg.cur_pass.in_pass);
  18460. SOKOL_ASSERT(_sg.cur_pass.is_compute);
  18461. _sg_tracker_reset(&_sg.compute.readwrite_sbufs);
  18462. }
  18463. _SOKOL_PRIVATE sg_desc _sg_desc_defaults(const sg_desc* desc) {
  18464. /*
  18465. NOTE: on WebGPU, the default color pixel format MUST be provided,
  18466. cannot be a default compile-time constant.
  18467. */
  18468. sg_desc res = *desc;
  18469. #if defined(SOKOL_WGPU)
  18470. SOKOL_ASSERT(SG_PIXELFORMAT_NONE < res.environment.defaults.color_format);
  18471. #elif defined(SOKOL_METAL) || defined(SOKOL_D3D11)
  18472. res.environment.defaults.color_format = _sg_def(res.environment.defaults.color_format, SG_PIXELFORMAT_BGRA8);
  18473. #else
  18474. res.environment.defaults.color_format = _sg_def(res.environment.defaults.color_format, SG_PIXELFORMAT_RGBA8);
  18475. #endif
  18476. res.environment.defaults.depth_format = _sg_def(res.environment.defaults.depth_format, SG_PIXELFORMAT_DEPTH_STENCIL);
  18477. res.environment.defaults.sample_count = _sg_def(res.environment.defaults.sample_count, 1);
  18478. res.buffer_pool_size = _sg_def(res.buffer_pool_size, _SG_DEFAULT_BUFFER_POOL_SIZE);
  18479. res.image_pool_size = _sg_def(res.image_pool_size, _SG_DEFAULT_IMAGE_POOL_SIZE);
  18480. res.sampler_pool_size = _sg_def(res.sampler_pool_size, _SG_DEFAULT_SAMPLER_POOL_SIZE);
  18481. res.shader_pool_size = _sg_def(res.shader_pool_size, _SG_DEFAULT_SHADER_POOL_SIZE);
  18482. res.pipeline_pool_size = _sg_def(res.pipeline_pool_size, _SG_DEFAULT_PIPELINE_POOL_SIZE);
  18483. res.attachments_pool_size = _sg_def(res.attachments_pool_size, _SG_DEFAULT_ATTACHMENTS_POOL_SIZE);
  18484. res.uniform_buffer_size = _sg_def(res.uniform_buffer_size, _SG_DEFAULT_UB_SIZE);
  18485. res.max_dispatch_calls_per_pass = _sg_def(res.max_dispatch_calls_per_pass, _SG_DEFAULT_MAX_DISPATCH_CALLS_PER_PASS);
  18486. res.max_commit_listeners = _sg_def(res.max_commit_listeners, _SG_DEFAULT_MAX_COMMIT_LISTENERS);
  18487. res.wgpu_bindgroups_cache_size = _sg_def(res.wgpu_bindgroups_cache_size, _SG_DEFAULT_WGPU_BINDGROUP_CACHE_SIZE);
  18488. return res;
  18489. }
  18490. _SOKOL_PRIVATE sg_pass _sg_pass_defaults(const sg_pass* pass) {
  18491. sg_pass res = *pass;
  18492. if (!res.compute) {
  18493. if (res.compute && res.attachments.id == SG_INVALID_ID) {
  18494. // this is a swapchain-pass
  18495. res.swapchain.sample_count = _sg_def(res.swapchain.sample_count, _sg.desc.environment.defaults.sample_count);
  18496. res.swapchain.color_format = _sg_def(res.swapchain.color_format, _sg.desc.environment.defaults.color_format);
  18497. res.swapchain.depth_format = _sg_def(res.swapchain.depth_format, _sg.desc.environment.defaults.depth_format);
  18498. }
  18499. res.action = _sg_pass_action_defaults(&res.action);
  18500. }
  18501. return res;
  18502. }
  18503. _SOKOL_PRIVATE void _sg_discard_all_resources(void) {
  18504. /* this is a bit dumb since it loops over all pool slots to
  18505. find the occupied slots, on the other hand it is only ever
  18506. executed at shutdown
  18507. NOTE: ONLY EXECUTE THIS AT SHUTDOWN
  18508. ...because the free queues will not be reset
  18509. and the resource slots not be cleared!
  18510. */
  18511. for (int i = 1; i < _sg.pools.buffer_pool.size; i++) {
  18512. sg_resource_state state = _sg.pools.buffers[i].slot.state;
  18513. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  18514. _sg_discard_buffer(&_sg.pools.buffers[i]);
  18515. }
  18516. }
  18517. for (int i = 1; i < _sg.pools.image_pool.size; i++) {
  18518. sg_resource_state state = _sg.pools.images[i].slot.state;
  18519. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  18520. _sg_discard_image(&_sg.pools.images[i]);
  18521. }
  18522. }
  18523. for (int i = 1; i < _sg.pools.sampler_pool.size; i++) {
  18524. sg_resource_state state = _sg.pools.samplers[i].slot.state;
  18525. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  18526. _sg_discard_sampler(&_sg.pools.samplers[i]);
  18527. }
  18528. }
  18529. for (int i = 1; i < _sg.pools.shader_pool.size; i++) {
  18530. sg_resource_state state = _sg.pools.shaders[i].slot.state;
  18531. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  18532. _sg_discard_shader(&_sg.pools.shaders[i]);
  18533. }
  18534. }
  18535. for (int i = 1; i < _sg.pools.pipeline_pool.size; i++) {
  18536. sg_resource_state state = _sg.pools.pipelines[i].slot.state;
  18537. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  18538. _sg_discard_pipeline(&_sg.pools.pipelines[i]);
  18539. }
  18540. }
  18541. for (int i = 1; i < _sg.pools.attachments_pool.size; i++) {
  18542. sg_resource_state state = _sg.pools.attachments[i].slot.state;
  18543. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  18544. _sg_discard_attachments(&_sg.pools.attachments[i]);
  18545. }
  18546. }
  18547. }
  18548. // ██████ ██ ██ ██████ ██ ██ ██████
  18549. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  18550. // ██████ ██ ██ ██████ ██ ██ ██
  18551. // ██ ██ ██ ██ ██ ██ ██ ██
  18552. // ██ ██████ ██████ ███████ ██ ██████
  18553. //
  18554. // >>public
  18555. SOKOL_API_IMPL void sg_setup(const sg_desc* desc) {
  18556. SOKOL_ASSERT(desc);
  18557. SOKOL_ASSERT((desc->_start_canary == 0) && (desc->_end_canary == 0));
  18558. SOKOL_ASSERT((desc->allocator.alloc_fn && desc->allocator.free_fn) || (!desc->allocator.alloc_fn && !desc->allocator.free_fn));
  18559. _SG_CLEAR_ARC_STRUCT(_sg_state_t, _sg);
  18560. _sg.desc = _sg_desc_defaults(desc);
  18561. _sg_setup_pools(&_sg.pools, &_sg.desc);
  18562. _sg_setup_compute(&_sg.desc);
  18563. _sg_setup_commit_listeners(&_sg.desc);
  18564. _sg.frame_index = 1;
  18565. _sg.stats_enabled = true;
  18566. _sg_setup_backend(&_sg.desc);
  18567. _sg.valid = true;
  18568. }
  18569. SOKOL_API_IMPL void sg_shutdown(void) {
  18570. _sg_discard_all_resources();
  18571. _sg_discard_backend();
  18572. _sg_discard_commit_listeners();
  18573. _sg_discard_compute();
  18574. _sg_discard_pools(&_sg.pools);
  18575. _SG_CLEAR_ARC_STRUCT(_sg_state_t, _sg);
  18576. }
  18577. SOKOL_API_IMPL bool sg_isvalid(void) {
  18578. return _sg.valid;
  18579. }
  18580. SOKOL_API_IMPL sg_desc sg_query_desc(void) {
  18581. SOKOL_ASSERT(_sg.valid);
  18582. return _sg.desc;
  18583. }
  18584. SOKOL_API_IMPL sg_backend sg_query_backend(void) {
  18585. SOKOL_ASSERT(_sg.valid);
  18586. return _sg.backend;
  18587. }
  18588. SOKOL_API_IMPL sg_features sg_query_features(void) {
  18589. SOKOL_ASSERT(_sg.valid);
  18590. return _sg.features;
  18591. }
  18592. SOKOL_API_IMPL sg_limits sg_query_limits(void) {
  18593. SOKOL_ASSERT(_sg.valid);
  18594. return _sg.limits;
  18595. }
  18596. SOKOL_API_IMPL sg_pixelformat_info sg_query_pixelformat(sg_pixel_format fmt) {
  18597. SOKOL_ASSERT(_sg.valid);
  18598. int fmt_index = (int) fmt;
  18599. SOKOL_ASSERT((fmt_index > SG_PIXELFORMAT_NONE) && (fmt_index < _SG_PIXELFORMAT_NUM));
  18600. const _sg_pixelformat_info_t* src = &_sg.formats[fmt_index];
  18601. sg_pixelformat_info res;
  18602. _sg_clear(&res, sizeof(res));
  18603. res.sample = src->sample;
  18604. res.filter = src->filter;
  18605. res.render = src->render;
  18606. res.blend = src->blend;
  18607. res.msaa = src->msaa;
  18608. res.depth = src->depth;
  18609. res.compressed = _sg_is_compressed_pixel_format(fmt);
  18610. res.read = src->read;
  18611. res.write = src->write;
  18612. if (!res.compressed) {
  18613. res.bytes_per_pixel = _sg_pixelformat_bytesize(fmt);
  18614. }
  18615. return res;
  18616. }
  18617. SOKOL_API_IMPL int sg_query_row_pitch(sg_pixel_format fmt, int width, int row_align_bytes) {
  18618. SOKOL_ASSERT(_sg.valid);
  18619. SOKOL_ASSERT(width > 0);
  18620. SOKOL_ASSERT((row_align_bytes > 0) && _sg_ispow2(row_align_bytes));
  18621. SOKOL_ASSERT(((int)fmt > SG_PIXELFORMAT_NONE) && ((int)fmt < _SG_PIXELFORMAT_NUM));
  18622. return _sg_row_pitch(fmt, width, row_align_bytes);
  18623. }
  18624. SOKOL_API_IMPL int sg_query_surface_pitch(sg_pixel_format fmt, int width, int height, int row_align_bytes) {
  18625. SOKOL_ASSERT(_sg.valid);
  18626. SOKOL_ASSERT((width > 0) && (height > 0));
  18627. SOKOL_ASSERT((row_align_bytes > 0) && _sg_ispow2(row_align_bytes));
  18628. SOKOL_ASSERT(((int)fmt > SG_PIXELFORMAT_NONE) && ((int)fmt < _SG_PIXELFORMAT_NUM));
  18629. return _sg_surface_pitch(fmt, width, height, row_align_bytes);
  18630. }
  18631. SOKOL_API_IMPL sg_frame_stats sg_query_frame_stats(void) {
  18632. SOKOL_ASSERT(_sg.valid);
  18633. return _sg.prev_stats;
  18634. }
  18635. SOKOL_API_IMPL sg_trace_hooks sg_install_trace_hooks(const sg_trace_hooks* trace_hooks) {
  18636. SOKOL_ASSERT(_sg.valid);
  18637. SOKOL_ASSERT(trace_hooks);
  18638. _SOKOL_UNUSED(trace_hooks);
  18639. #if defined(SOKOL_TRACE_HOOKS)
  18640. sg_trace_hooks old_hooks = _sg.hooks;
  18641. _sg.hooks = *trace_hooks;
  18642. #else
  18643. static sg_trace_hooks old_hooks;
  18644. _SG_WARN(TRACE_HOOKS_NOT_ENABLED);
  18645. #endif
  18646. return old_hooks;
  18647. }
  18648. SOKOL_API_IMPL sg_buffer sg_alloc_buffer(void) {
  18649. SOKOL_ASSERT(_sg.valid);
  18650. sg_buffer res = _sg_alloc_buffer();
  18651. _SG_TRACE_ARGS(alloc_buffer, res);
  18652. return res;
  18653. }
  18654. SOKOL_API_IMPL sg_image sg_alloc_image(void) {
  18655. SOKOL_ASSERT(_sg.valid);
  18656. sg_image res = _sg_alloc_image();
  18657. _SG_TRACE_ARGS(alloc_image, res);
  18658. return res;
  18659. }
  18660. SOKOL_API_IMPL sg_sampler sg_alloc_sampler(void) {
  18661. SOKOL_ASSERT(_sg.valid);
  18662. sg_sampler res = _sg_alloc_sampler();
  18663. _SG_TRACE_ARGS(alloc_sampler, res);
  18664. return res;
  18665. }
  18666. SOKOL_API_IMPL sg_shader sg_alloc_shader(void) {
  18667. SOKOL_ASSERT(_sg.valid);
  18668. sg_shader res = _sg_alloc_shader();
  18669. _SG_TRACE_ARGS(alloc_shader, res);
  18670. return res;
  18671. }
  18672. SOKOL_API_IMPL sg_pipeline sg_alloc_pipeline(void) {
  18673. SOKOL_ASSERT(_sg.valid);
  18674. sg_pipeline res = _sg_alloc_pipeline();
  18675. _SG_TRACE_ARGS(alloc_pipeline, res);
  18676. return res;
  18677. }
  18678. SOKOL_API_IMPL sg_attachments sg_alloc_attachments(void) {
  18679. SOKOL_ASSERT(_sg.valid);
  18680. sg_attachments res = _sg_alloc_attachments();
  18681. _SG_TRACE_ARGS(alloc_attachments, res);
  18682. return res;
  18683. }
  18684. SOKOL_API_IMPL void sg_dealloc_buffer(sg_buffer buf_id) {
  18685. SOKOL_ASSERT(_sg.valid);
  18686. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  18687. if (buf) {
  18688. if (buf->slot.state == SG_RESOURCESTATE_ALLOC) {
  18689. _sg_dealloc_buffer(buf);
  18690. } else {
  18691. _SG_ERROR(DEALLOC_BUFFER_INVALID_STATE);
  18692. }
  18693. }
  18694. _SG_TRACE_ARGS(dealloc_buffer, buf_id);
  18695. }
  18696. SOKOL_API_IMPL void sg_dealloc_image(sg_image img_id) {
  18697. SOKOL_ASSERT(_sg.valid);
  18698. _sg_image_t* img = _sg_lookup_image(img_id.id);
  18699. if (img) {
  18700. if (img->slot.state == SG_RESOURCESTATE_ALLOC) {
  18701. _sg_dealloc_image(img);
  18702. } else {
  18703. _SG_ERROR(DEALLOC_IMAGE_INVALID_STATE);
  18704. }
  18705. }
  18706. _SG_TRACE_ARGS(dealloc_image, img_id);
  18707. }
  18708. SOKOL_API_IMPL void sg_dealloc_sampler(sg_sampler smp_id) {
  18709. SOKOL_ASSERT(_sg.valid);
  18710. _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  18711. if (smp) {
  18712. if (smp->slot.state == SG_RESOURCESTATE_ALLOC) {
  18713. _sg_dealloc_sampler(smp);
  18714. } else {
  18715. _SG_ERROR(DEALLOC_SAMPLER_INVALID_STATE);
  18716. }
  18717. }
  18718. _SG_TRACE_ARGS(dealloc_sampler, smp_id);
  18719. }
  18720. SOKOL_API_IMPL void sg_dealloc_shader(sg_shader shd_id) {
  18721. SOKOL_ASSERT(_sg.valid);
  18722. _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  18723. if (shd) {
  18724. if (shd->slot.state == SG_RESOURCESTATE_ALLOC) {
  18725. _sg_dealloc_shader(shd);
  18726. } else {
  18727. _SG_ERROR(DEALLOC_SHADER_INVALID_STATE);
  18728. }
  18729. }
  18730. _SG_TRACE_ARGS(dealloc_shader, shd_id);
  18731. }
  18732. SOKOL_API_IMPL void sg_dealloc_pipeline(sg_pipeline pip_id) {
  18733. SOKOL_ASSERT(_sg.valid);
  18734. _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  18735. if (pip) {
  18736. if (pip->slot.state == SG_RESOURCESTATE_ALLOC) {
  18737. _sg_dealloc_pipeline(pip);
  18738. } else {
  18739. _SG_ERROR(DEALLOC_PIPELINE_INVALID_STATE);
  18740. }
  18741. }
  18742. _SG_TRACE_ARGS(dealloc_pipeline, pip_id);
  18743. }
  18744. SOKOL_API_IMPL void sg_dealloc_attachments(sg_attachments atts_id) {
  18745. SOKOL_ASSERT(_sg.valid);
  18746. _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  18747. if (atts) {
  18748. if (atts->slot.state == SG_RESOURCESTATE_ALLOC) {
  18749. _sg_dealloc_attachments(atts);
  18750. } else {
  18751. _SG_ERROR(DEALLOC_ATTACHMENTS_INVALID_STATE);
  18752. }
  18753. }
  18754. _SG_TRACE_ARGS(dealloc_attachments, atts_id);
  18755. }
  18756. SOKOL_API_IMPL void sg_init_buffer(sg_buffer buf_id, const sg_buffer_desc* desc) {
  18757. SOKOL_ASSERT(_sg.valid);
  18758. sg_buffer_desc desc_def = _sg_buffer_desc_defaults(desc);
  18759. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  18760. if (buf) {
  18761. if (buf->slot.state == SG_RESOURCESTATE_ALLOC) {
  18762. _sg_init_buffer(buf, &desc_def);
  18763. SOKOL_ASSERT((buf->slot.state == SG_RESOURCESTATE_VALID) || (buf->slot.state == SG_RESOURCESTATE_FAILED));
  18764. } else {
  18765. _SG_ERROR(INIT_BUFFER_INVALID_STATE);
  18766. }
  18767. }
  18768. _SG_TRACE_ARGS(init_buffer, buf_id, &desc_def);
  18769. }
  18770. SOKOL_API_IMPL void sg_init_image(sg_image img_id, const sg_image_desc* desc) {
  18771. SOKOL_ASSERT(_sg.valid);
  18772. sg_image_desc desc_def = _sg_image_desc_defaults(desc);
  18773. _sg_image_t* img = _sg_lookup_image(img_id.id);
  18774. if (img) {
  18775. if (img->slot.state == SG_RESOURCESTATE_ALLOC) {
  18776. _sg_init_image(img, &desc_def);
  18777. SOKOL_ASSERT((img->slot.state == SG_RESOURCESTATE_VALID) || (img->slot.state == SG_RESOURCESTATE_FAILED));
  18778. } else {
  18779. _SG_ERROR(INIT_IMAGE_INVALID_STATE);
  18780. }
  18781. }
  18782. _SG_TRACE_ARGS(init_image, img_id, &desc_def);
  18783. }
  18784. SOKOL_API_IMPL void sg_init_sampler(sg_sampler smp_id, const sg_sampler_desc* desc) {
  18785. SOKOL_ASSERT(_sg.valid);
  18786. sg_sampler_desc desc_def = _sg_sampler_desc_defaults(desc);
  18787. _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  18788. if (smp) {
  18789. if (smp->slot.state == SG_RESOURCESTATE_ALLOC) {
  18790. _sg_init_sampler(smp, &desc_def);
  18791. SOKOL_ASSERT((smp->slot.state == SG_RESOURCESTATE_VALID) || (smp->slot.state == SG_RESOURCESTATE_FAILED));
  18792. } else {
  18793. _SG_ERROR(INIT_SAMPLER_INVALID_STATE);
  18794. }
  18795. }
  18796. _SG_TRACE_ARGS(init_sampler, smp_id, &desc_def);
  18797. }
  18798. SOKOL_API_IMPL void sg_init_shader(sg_shader shd_id, const sg_shader_desc* desc) {
  18799. SOKOL_ASSERT(_sg.valid);
  18800. sg_shader_desc desc_def = _sg_shader_desc_defaults(desc);
  18801. _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  18802. if (shd) {
  18803. if (shd->slot.state == SG_RESOURCESTATE_ALLOC) {
  18804. _sg_init_shader(shd, &desc_def);
  18805. SOKOL_ASSERT((shd->slot.state == SG_RESOURCESTATE_VALID) || (shd->slot.state == SG_RESOURCESTATE_FAILED));
  18806. } else {
  18807. _SG_ERROR(INIT_SHADER_INVALID_STATE);
  18808. }
  18809. }
  18810. _SG_TRACE_ARGS(init_shader, shd_id, &desc_def);
  18811. }
  18812. SOKOL_API_IMPL void sg_init_pipeline(sg_pipeline pip_id, const sg_pipeline_desc* desc) {
  18813. SOKOL_ASSERT(_sg.valid);
  18814. sg_pipeline_desc desc_def = _sg_pipeline_desc_defaults(desc);
  18815. _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  18816. if (pip) {
  18817. if (pip->slot.state == SG_RESOURCESTATE_ALLOC) {
  18818. _sg_init_pipeline(pip, &desc_def);
  18819. SOKOL_ASSERT((pip->slot.state == SG_RESOURCESTATE_VALID) || (pip->slot.state == SG_RESOURCESTATE_FAILED));
  18820. } else {
  18821. _SG_ERROR(INIT_PIPELINE_INVALID_STATE);
  18822. }
  18823. }
  18824. _SG_TRACE_ARGS(init_pipeline, pip_id, &desc_def);
  18825. }
  18826. SOKOL_API_IMPL void sg_init_attachments(sg_attachments atts_id, const sg_attachments_desc* desc) {
  18827. SOKOL_ASSERT(_sg.valid);
  18828. sg_attachments_desc desc_def = _sg_attachments_desc_defaults(desc);
  18829. _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  18830. if (atts) {
  18831. if (atts->slot.state == SG_RESOURCESTATE_ALLOC) {
  18832. _sg_init_attachments(atts, &desc_def);
  18833. SOKOL_ASSERT((atts->slot.state == SG_RESOURCESTATE_VALID) || (atts->slot.state == SG_RESOURCESTATE_FAILED));
  18834. } else {
  18835. _SG_ERROR(INIT_ATTACHMENTS_INVALID_STATE);
  18836. }
  18837. }
  18838. _SG_TRACE_ARGS(init_attachments, atts_id, &desc_def);
  18839. }
  18840. SOKOL_API_IMPL void sg_uninit_buffer(sg_buffer buf_id) {
  18841. SOKOL_ASSERT(_sg.valid);
  18842. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  18843. if (buf) {
  18844. if ((buf->slot.state == SG_RESOURCESTATE_VALID) || (buf->slot.state == SG_RESOURCESTATE_FAILED)) {
  18845. _sg_uninit_buffer(buf);
  18846. SOKOL_ASSERT(buf->slot.state == SG_RESOURCESTATE_ALLOC);
  18847. } else {
  18848. _SG_ERROR(UNINIT_BUFFER_INVALID_STATE);
  18849. }
  18850. }
  18851. _SG_TRACE_ARGS(uninit_buffer, buf_id);
  18852. }
  18853. SOKOL_API_IMPL void sg_uninit_image(sg_image img_id) {
  18854. SOKOL_ASSERT(_sg.valid);
  18855. _sg_image_t* img = _sg_lookup_image(img_id.id);
  18856. if (img) {
  18857. if ((img->slot.state == SG_RESOURCESTATE_VALID) || (img->slot.state == SG_RESOURCESTATE_FAILED)) {
  18858. _sg_uninit_image(img);
  18859. SOKOL_ASSERT(img->slot.state == SG_RESOURCESTATE_ALLOC);
  18860. } else {
  18861. _SG_ERROR(UNINIT_IMAGE_INVALID_STATE);
  18862. }
  18863. }
  18864. _SG_TRACE_ARGS(uninit_image, img_id);
  18865. }
  18866. SOKOL_API_IMPL void sg_uninit_sampler(sg_sampler smp_id) {
  18867. SOKOL_ASSERT(_sg.valid);
  18868. _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  18869. if (smp) {
  18870. if ((smp->slot.state == SG_RESOURCESTATE_VALID) || (smp->slot.state == SG_RESOURCESTATE_FAILED)) {
  18871. _sg_uninit_sampler(smp);
  18872. SOKOL_ASSERT(smp->slot.state == SG_RESOURCESTATE_ALLOC);
  18873. } else {
  18874. _SG_ERROR(UNINIT_SAMPLER_INVALID_STATE);
  18875. }
  18876. }
  18877. _SG_TRACE_ARGS(uninit_sampler, smp_id);
  18878. }
  18879. SOKOL_API_IMPL void sg_uninit_shader(sg_shader shd_id) {
  18880. SOKOL_ASSERT(_sg.valid);
  18881. _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  18882. if (shd) {
  18883. if ((shd->slot.state == SG_RESOURCESTATE_VALID) || (shd->slot.state == SG_RESOURCESTATE_FAILED)) {
  18884. _sg_uninit_shader(shd);
  18885. SOKOL_ASSERT(shd->slot.state == SG_RESOURCESTATE_ALLOC);
  18886. } else {
  18887. _SG_ERROR(UNINIT_SHADER_INVALID_STATE);
  18888. }
  18889. }
  18890. _SG_TRACE_ARGS(uninit_shader, shd_id);
  18891. }
  18892. SOKOL_API_IMPL void sg_uninit_pipeline(sg_pipeline pip_id) {
  18893. SOKOL_ASSERT(_sg.valid);
  18894. _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  18895. if (pip) {
  18896. if ((pip->slot.state == SG_RESOURCESTATE_VALID) || (pip->slot.state == SG_RESOURCESTATE_FAILED)) {
  18897. _sg_uninit_pipeline(pip);
  18898. SOKOL_ASSERT(pip->slot.state == SG_RESOURCESTATE_ALLOC);
  18899. } else {
  18900. _SG_ERROR(UNINIT_PIPELINE_INVALID_STATE);
  18901. }
  18902. }
  18903. _SG_TRACE_ARGS(uninit_pipeline, pip_id);
  18904. }
  18905. SOKOL_API_IMPL void sg_uninit_attachments(sg_attachments atts_id) {
  18906. SOKOL_ASSERT(_sg.valid);
  18907. _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  18908. if (atts) {
  18909. if ((atts->slot.state == SG_RESOURCESTATE_VALID) || (atts->slot.state == SG_RESOURCESTATE_FAILED)) {
  18910. _sg_uninit_attachments(atts);
  18911. SOKOL_ASSERT(atts->slot.state == SG_RESOURCESTATE_ALLOC);
  18912. } else {
  18913. _SG_ERROR(UNINIT_ATTACHMENTS_INVALID_STATE);
  18914. }
  18915. }
  18916. _SG_TRACE_ARGS(uninit_attachments, atts_id);
  18917. }
  18918. SOKOL_API_IMPL void sg_fail_buffer(sg_buffer buf_id) {
  18919. SOKOL_ASSERT(_sg.valid);
  18920. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  18921. if (buf) {
  18922. if (buf->slot.state == SG_RESOURCESTATE_ALLOC) {
  18923. buf->slot.state = SG_RESOURCESTATE_FAILED;
  18924. } else {
  18925. _SG_ERROR(FAIL_BUFFER_INVALID_STATE);
  18926. }
  18927. }
  18928. _SG_TRACE_ARGS(fail_buffer, buf_id);
  18929. }
  18930. SOKOL_API_IMPL void sg_fail_image(sg_image img_id) {
  18931. SOKOL_ASSERT(_sg.valid);
  18932. _sg_image_t* img = _sg_lookup_image(img_id.id);
  18933. if (img) {
  18934. if (img->slot.state == SG_RESOURCESTATE_ALLOC) {
  18935. img->slot.state = SG_RESOURCESTATE_FAILED;
  18936. } else {
  18937. _SG_ERROR(FAIL_IMAGE_INVALID_STATE);
  18938. }
  18939. }
  18940. _SG_TRACE_ARGS(fail_image, img_id);
  18941. }
  18942. SOKOL_API_IMPL void sg_fail_sampler(sg_sampler smp_id) {
  18943. SOKOL_ASSERT(_sg.valid);
  18944. _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  18945. if (smp) {
  18946. if (smp->slot.state == SG_RESOURCESTATE_ALLOC) {
  18947. smp->slot.state = SG_RESOURCESTATE_FAILED;
  18948. } else {
  18949. _SG_ERROR(FAIL_SAMPLER_INVALID_STATE);
  18950. }
  18951. }
  18952. _SG_TRACE_ARGS(fail_sampler, smp_id);
  18953. }
  18954. SOKOL_API_IMPL void sg_fail_shader(sg_shader shd_id) {
  18955. SOKOL_ASSERT(_sg.valid);
  18956. _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  18957. if (shd) {
  18958. if (shd->slot.state == SG_RESOURCESTATE_ALLOC) {
  18959. shd->slot.state = SG_RESOURCESTATE_FAILED;
  18960. } else {
  18961. _SG_ERROR(FAIL_SHADER_INVALID_STATE);
  18962. }
  18963. }
  18964. _SG_TRACE_ARGS(fail_shader, shd_id);
  18965. }
  18966. SOKOL_API_IMPL void sg_fail_pipeline(sg_pipeline pip_id) {
  18967. SOKOL_ASSERT(_sg.valid);
  18968. _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  18969. if (pip) {
  18970. if (pip->slot.state == SG_RESOURCESTATE_ALLOC) {
  18971. pip->slot.state = SG_RESOURCESTATE_FAILED;
  18972. } else {
  18973. _SG_ERROR(FAIL_PIPELINE_INVALID_STATE);
  18974. }
  18975. }
  18976. _SG_TRACE_ARGS(fail_pipeline, pip_id);
  18977. }
  18978. SOKOL_API_IMPL void sg_fail_attachments(sg_attachments atts_id) {
  18979. SOKOL_ASSERT(_sg.valid);
  18980. _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  18981. if (atts) {
  18982. if (atts->slot.state == SG_RESOURCESTATE_ALLOC) {
  18983. atts->slot.state = SG_RESOURCESTATE_FAILED;
  18984. } else {
  18985. _SG_ERROR(FAIL_ATTACHMENTS_INVALID_STATE);
  18986. }
  18987. }
  18988. _SG_TRACE_ARGS(fail_attachments, atts_id);
  18989. }
  18990. SOKOL_API_IMPL sg_resource_state sg_query_buffer_state(sg_buffer buf_id) {
  18991. SOKOL_ASSERT(_sg.valid);
  18992. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  18993. sg_resource_state res = buf ? buf->slot.state : SG_RESOURCESTATE_INVALID;
  18994. return res;
  18995. }
  18996. SOKOL_API_IMPL sg_resource_state sg_query_image_state(sg_image img_id) {
  18997. SOKOL_ASSERT(_sg.valid);
  18998. _sg_image_t* img = _sg_lookup_image(img_id.id);
  18999. sg_resource_state res = img ? img->slot.state : SG_RESOURCESTATE_INVALID;
  19000. return res;
  19001. }
  19002. SOKOL_API_IMPL sg_resource_state sg_query_sampler_state(sg_sampler smp_id) {
  19003. SOKOL_ASSERT(_sg.valid);
  19004. _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  19005. sg_resource_state res = smp ? smp->slot.state : SG_RESOURCESTATE_INVALID;
  19006. return res;
  19007. }
  19008. SOKOL_API_IMPL sg_resource_state sg_query_shader_state(sg_shader shd_id) {
  19009. SOKOL_ASSERT(_sg.valid);
  19010. _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  19011. sg_resource_state res = shd ? shd->slot.state : SG_RESOURCESTATE_INVALID;
  19012. return res;
  19013. }
  19014. SOKOL_API_IMPL sg_resource_state sg_query_pipeline_state(sg_pipeline pip_id) {
  19015. SOKOL_ASSERT(_sg.valid);
  19016. _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  19017. sg_resource_state res = pip ? pip->slot.state : SG_RESOURCESTATE_INVALID;
  19018. return res;
  19019. }
  19020. SOKOL_API_IMPL sg_resource_state sg_query_attachments_state(sg_attachments atts_id) {
  19021. SOKOL_ASSERT(_sg.valid);
  19022. _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  19023. sg_resource_state res = atts ? atts->slot.state : SG_RESOURCESTATE_INVALID;
  19024. return res;
  19025. }
  19026. SOKOL_API_IMPL sg_buffer sg_make_buffer(const sg_buffer_desc* desc) {
  19027. SOKOL_ASSERT(_sg.valid);
  19028. SOKOL_ASSERT(desc);
  19029. sg_buffer_desc desc_def = _sg_buffer_desc_defaults(desc);
  19030. sg_buffer buf_id = _sg_alloc_buffer();
  19031. if (buf_id.id != SG_INVALID_ID) {
  19032. _sg_buffer_t* buf = _sg_buffer_at(buf_id.id);
  19033. SOKOL_ASSERT(buf && (buf->slot.state == SG_RESOURCESTATE_ALLOC));
  19034. _sg_init_buffer(buf, &desc_def);
  19035. SOKOL_ASSERT((buf->slot.state == SG_RESOURCESTATE_VALID) || (buf->slot.state == SG_RESOURCESTATE_FAILED));
  19036. }
  19037. _SG_TRACE_ARGS(make_buffer, &desc_def, buf_id);
  19038. return buf_id;
  19039. }
  19040. SOKOL_API_IMPL sg_image sg_make_image(const sg_image_desc* desc) {
  19041. SOKOL_ASSERT(_sg.valid);
  19042. SOKOL_ASSERT(desc);
  19043. sg_image_desc desc_def = _sg_image_desc_defaults(desc);
  19044. sg_image img_id = _sg_alloc_image();
  19045. if (img_id.id != SG_INVALID_ID) {
  19046. _sg_image_t* img = _sg_image_at(img_id.id);
  19047. SOKOL_ASSERT(img && (img->slot.state == SG_RESOURCESTATE_ALLOC));
  19048. _sg_init_image(img, &desc_def);
  19049. SOKOL_ASSERT((img->slot.state == SG_RESOURCESTATE_VALID) || (img->slot.state == SG_RESOURCESTATE_FAILED));
  19050. }
  19051. _SG_TRACE_ARGS(make_image, &desc_def, img_id);
  19052. return img_id;
  19053. }
  19054. SOKOL_API_IMPL sg_sampler sg_make_sampler(const sg_sampler_desc* desc) {
  19055. SOKOL_ASSERT(_sg.valid);
  19056. SOKOL_ASSERT(desc);
  19057. sg_sampler_desc desc_def = _sg_sampler_desc_defaults(desc);
  19058. sg_sampler smp_id = _sg_alloc_sampler();
  19059. if (smp_id.id != SG_INVALID_ID) {
  19060. _sg_sampler_t* smp = _sg_sampler_at(smp_id.id);
  19061. SOKOL_ASSERT(smp && (smp->slot.state == SG_RESOURCESTATE_ALLOC));
  19062. _sg_init_sampler(smp, &desc_def);
  19063. SOKOL_ASSERT((smp->slot.state == SG_RESOURCESTATE_VALID) || (smp->slot.state == SG_RESOURCESTATE_FAILED));
  19064. }
  19065. _SG_TRACE_ARGS(make_sampler, &desc_def, smp_id);
  19066. return smp_id;
  19067. }
  19068. SOKOL_API_IMPL sg_shader sg_make_shader(const sg_shader_desc* desc) {
  19069. SOKOL_ASSERT(_sg.valid);
  19070. SOKOL_ASSERT(desc);
  19071. sg_shader_desc desc_def = _sg_shader_desc_defaults(desc);
  19072. sg_shader shd_id = _sg_alloc_shader();
  19073. if (shd_id.id != SG_INVALID_ID) {
  19074. _sg_shader_t* shd = _sg_shader_at(shd_id.id);
  19075. SOKOL_ASSERT(shd && (shd->slot.state == SG_RESOURCESTATE_ALLOC));
  19076. _sg_init_shader(shd, &desc_def);
  19077. SOKOL_ASSERT((shd->slot.state == SG_RESOURCESTATE_VALID) || (shd->slot.state == SG_RESOURCESTATE_FAILED));
  19078. }
  19079. _SG_TRACE_ARGS(make_shader, &desc_def, shd_id);
  19080. return shd_id;
  19081. }
  19082. SOKOL_API_IMPL sg_pipeline sg_make_pipeline(const sg_pipeline_desc* desc) {
  19083. SOKOL_ASSERT(_sg.valid);
  19084. SOKOL_ASSERT(desc);
  19085. sg_pipeline_desc desc_def = _sg_pipeline_desc_defaults(desc);
  19086. sg_pipeline pip_id = _sg_alloc_pipeline();
  19087. if (pip_id.id != SG_INVALID_ID) {
  19088. _sg_pipeline_t* pip = _sg_pipeline_at(pip_id.id);
  19089. SOKOL_ASSERT(pip && (pip->slot.state == SG_RESOURCESTATE_ALLOC));
  19090. _sg_init_pipeline(pip, &desc_def);
  19091. SOKOL_ASSERT((pip->slot.state == SG_RESOURCESTATE_VALID) || (pip->slot.state == SG_RESOURCESTATE_FAILED));
  19092. }
  19093. _SG_TRACE_ARGS(make_pipeline, &desc_def, pip_id);
  19094. return pip_id;
  19095. }
  19096. SOKOL_API_IMPL sg_attachments sg_make_attachments(const sg_attachments_desc* desc) {
  19097. SOKOL_ASSERT(_sg.valid);
  19098. SOKOL_ASSERT(desc);
  19099. sg_attachments_desc desc_def = _sg_attachments_desc_defaults(desc);
  19100. sg_attachments atts_id = _sg_alloc_attachments();
  19101. if (atts_id.id != SG_INVALID_ID) {
  19102. _sg_attachments_t* atts = _sg_attachments_at(atts_id.id);
  19103. SOKOL_ASSERT(atts && (atts->slot.state == SG_RESOURCESTATE_ALLOC));
  19104. _sg_init_attachments(atts, &desc_def);
  19105. SOKOL_ASSERT((atts->slot.state == SG_RESOURCESTATE_VALID) || (atts->slot.state == SG_RESOURCESTATE_FAILED));
  19106. }
  19107. _SG_TRACE_ARGS(make_attachments, &desc_def, atts_id);
  19108. return atts_id;
  19109. }
  19110. SOKOL_API_IMPL void sg_destroy_buffer(sg_buffer buf_id) {
  19111. SOKOL_ASSERT(_sg.valid);
  19112. _SG_TRACE_ARGS(destroy_buffer, buf_id);
  19113. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19114. if (buf) {
  19115. if ((buf->slot.state == SG_RESOURCESTATE_VALID) || (buf->slot.state == SG_RESOURCESTATE_FAILED)) {
  19116. _sg_uninit_buffer(buf);
  19117. SOKOL_ASSERT(buf->slot.state == SG_RESOURCESTATE_ALLOC);
  19118. }
  19119. if (buf->slot.state == SG_RESOURCESTATE_ALLOC) {
  19120. _sg_dealloc_buffer(buf);
  19121. SOKOL_ASSERT(buf->slot.state == SG_RESOURCESTATE_INITIAL);
  19122. }
  19123. }
  19124. }
  19125. SOKOL_API_IMPL void sg_destroy_image(sg_image img_id) {
  19126. SOKOL_ASSERT(_sg.valid);
  19127. _SG_TRACE_ARGS(destroy_image, img_id);
  19128. _sg_image_t* img = _sg_lookup_image(img_id.id);
  19129. if (img) {
  19130. if ((img->slot.state == SG_RESOURCESTATE_VALID) || (img->slot.state == SG_RESOURCESTATE_FAILED)) {
  19131. _sg_uninit_image(img);
  19132. SOKOL_ASSERT(img->slot.state == SG_RESOURCESTATE_ALLOC);
  19133. }
  19134. if (img->slot.state == SG_RESOURCESTATE_ALLOC) {
  19135. _sg_dealloc_image(img);
  19136. SOKOL_ASSERT(img->slot.state == SG_RESOURCESTATE_INITIAL);
  19137. }
  19138. }
  19139. }
  19140. SOKOL_API_IMPL void sg_destroy_sampler(sg_sampler smp_id) {
  19141. SOKOL_ASSERT(_sg.valid);
  19142. _SG_TRACE_ARGS(destroy_sampler, smp_id);
  19143. _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  19144. if (smp) {
  19145. if ((smp->slot.state == SG_RESOURCESTATE_VALID) || (smp->slot.state == SG_RESOURCESTATE_FAILED)) {
  19146. _sg_uninit_sampler(smp);
  19147. SOKOL_ASSERT(smp->slot.state == SG_RESOURCESTATE_ALLOC);
  19148. }
  19149. if (smp->slot.state == SG_RESOURCESTATE_ALLOC) {
  19150. _sg_dealloc_sampler(smp);
  19151. SOKOL_ASSERT(smp->slot.state == SG_RESOURCESTATE_INITIAL);
  19152. }
  19153. }
  19154. }
  19155. SOKOL_API_IMPL void sg_destroy_shader(sg_shader shd_id) {
  19156. SOKOL_ASSERT(_sg.valid);
  19157. _SG_TRACE_ARGS(destroy_shader, shd_id);
  19158. _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  19159. if (shd) {
  19160. if ((shd->slot.state == SG_RESOURCESTATE_VALID) || (shd->slot.state == SG_RESOURCESTATE_FAILED)) {
  19161. _sg_uninit_shader(shd);
  19162. SOKOL_ASSERT(shd->slot.state == SG_RESOURCESTATE_ALLOC);
  19163. }
  19164. if (shd->slot.state == SG_RESOURCESTATE_ALLOC) {
  19165. _sg_dealloc_shader(shd);
  19166. SOKOL_ASSERT(shd->slot.state == SG_RESOURCESTATE_INITIAL);
  19167. }
  19168. }
  19169. }
  19170. SOKOL_API_IMPL void sg_destroy_pipeline(sg_pipeline pip_id) {
  19171. SOKOL_ASSERT(_sg.valid);
  19172. _SG_TRACE_ARGS(destroy_pipeline, pip_id);
  19173. _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  19174. if (pip) {
  19175. if ((pip->slot.state == SG_RESOURCESTATE_VALID) || (pip->slot.state == SG_RESOURCESTATE_FAILED)) {
  19176. _sg_uninit_pipeline(pip);
  19177. SOKOL_ASSERT(pip->slot.state == SG_RESOURCESTATE_ALLOC);
  19178. }
  19179. if (pip->slot.state == SG_RESOURCESTATE_ALLOC) {
  19180. _sg_dealloc_pipeline(pip);
  19181. SOKOL_ASSERT(pip->slot.state == SG_RESOURCESTATE_INITIAL);
  19182. }
  19183. }
  19184. }
  19185. SOKOL_API_IMPL void sg_destroy_attachments(sg_attachments atts_id) {
  19186. SOKOL_ASSERT(_sg.valid);
  19187. _SG_TRACE_ARGS(destroy_attachments, atts_id);
  19188. _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  19189. if (atts) {
  19190. if ((atts->slot.state == SG_RESOURCESTATE_VALID) || (atts->slot.state == SG_RESOURCESTATE_FAILED)) {
  19191. _sg_uninit_attachments(atts);
  19192. SOKOL_ASSERT(atts->slot.state == SG_RESOURCESTATE_ALLOC);
  19193. }
  19194. if (atts->slot.state == SG_RESOURCESTATE_ALLOC) {
  19195. _sg_dealloc_attachments(atts);
  19196. SOKOL_ASSERT(atts->slot.state == SG_RESOURCESTATE_INITIAL);
  19197. }
  19198. }
  19199. }
  19200. SOKOL_API_IMPL void sg_begin_pass(const sg_pass* pass) {
  19201. SOKOL_ASSERT(_sg.valid);
  19202. SOKOL_ASSERT(!_sg.cur_pass.valid);
  19203. SOKOL_ASSERT(!_sg.cur_pass.in_pass);
  19204. SOKOL_ASSERT(_sg_attachments_ref_null(&_sg.cur_pass.atts));
  19205. SOKOL_ASSERT(pass);
  19206. SOKOL_ASSERT((pass->_start_canary == 0) && (pass->_end_canary == 0));
  19207. const sg_pass pass_def = _sg_pass_defaults(pass);
  19208. if (!_sg_validate_begin_pass(&pass_def)) {
  19209. return;
  19210. }
  19211. _sg.cur_pass.atts = _sg_attachments_ref(0);
  19212. if (pass_def.attachments.id != SG_INVALID_ID) {
  19213. _sg_attachments_t* atts = _sg_lookup_attachments(pass_def.attachments.id);
  19214. if (0 == atts) {
  19215. _SG_ERROR(BEGINPASS_ATTACHMENT_INVALID);
  19216. return;
  19217. }
  19218. SOKOL_ASSERT(atts);
  19219. _sg.cur_pass.atts = _sg_attachments_ref(atts);
  19220. _sg.cur_pass.width = atts->cmn.width;
  19221. _sg.cur_pass.height = atts->cmn.height;
  19222. } else if (!pass_def.compute) {
  19223. // a swapchain pass
  19224. SOKOL_ASSERT(pass_def.swapchain.width > 0);
  19225. SOKOL_ASSERT(pass_def.swapchain.height > 0);
  19226. SOKOL_ASSERT(pass_def.swapchain.color_format > SG_PIXELFORMAT_NONE);
  19227. SOKOL_ASSERT(pass_def.swapchain.sample_count > 0);
  19228. _sg.cur_pass.width = pass_def.swapchain.width;
  19229. _sg.cur_pass.height = pass_def.swapchain.height;
  19230. _sg.cur_pass.swapchain.color_fmt = pass_def.swapchain.color_format;
  19231. _sg.cur_pass.swapchain.depth_fmt = pass_def.swapchain.depth_format;
  19232. _sg.cur_pass.swapchain.sample_count = pass_def.swapchain.sample_count;
  19233. }
  19234. _sg.cur_pass.valid = true; // may be overruled by backend begin-pass functions
  19235. _sg.cur_pass.in_pass = true;
  19236. _sg.cur_pass.is_compute = pass_def.compute;
  19237. _sg_begin_pass(&pass_def);
  19238. _SG_TRACE_ARGS(begin_pass, &pass_def);
  19239. }
  19240. SOKOL_API_IMPL void sg_apply_viewport(int x, int y, int width, int height, bool origin_top_left) {
  19241. SOKOL_ASSERT(_sg.valid);
  19242. #if defined(SOKOL_DEBUG)
  19243. if (!_sg_validate_apply_viewport(x, y, width, height, origin_top_left)) {
  19244. return;
  19245. }
  19246. #endif
  19247. _sg_stats_add(num_apply_viewport, 1);
  19248. if (!_sg.cur_pass.valid) {
  19249. return;
  19250. }
  19251. _sg_apply_viewport(x, y, width, height, origin_top_left);
  19252. _SG_TRACE_ARGS(apply_viewport, x, y, width, height, origin_top_left);
  19253. }
  19254. SOKOL_API_IMPL void sg_apply_viewportf(float x, float y, float width, float height, bool origin_top_left) {
  19255. sg_apply_viewport((int)x, (int)y, (int)width, (int)height, origin_top_left);
  19256. }
  19257. SOKOL_API_IMPL void sg_apply_scissor_rect(int x, int y, int width, int height, bool origin_top_left) {
  19258. SOKOL_ASSERT(_sg.valid);
  19259. #if defined(SOKOL_DEBUG)
  19260. if (!_sg_validate_apply_scissor_rect(x, y, width, height, origin_top_left)) {
  19261. return;
  19262. }
  19263. #endif
  19264. _sg_stats_add(num_apply_scissor_rect, 1);
  19265. if (!_sg.cur_pass.valid) {
  19266. return;
  19267. }
  19268. _sg_apply_scissor_rect(x, y, width, height, origin_top_left);
  19269. _SG_TRACE_ARGS(apply_scissor_rect, x, y, width, height, origin_top_left);
  19270. }
  19271. SOKOL_API_IMPL void sg_apply_scissor_rectf(float x, float y, float width, float height, bool origin_top_left) {
  19272. sg_apply_scissor_rect((int)x, (int)y, (int)width, (int)height, origin_top_left);
  19273. }
  19274. SOKOL_API_IMPL void sg_apply_pipeline(sg_pipeline pip_id) {
  19275. SOKOL_ASSERT(_sg.valid);
  19276. _sg_stats_add(num_apply_pipeline, 1);
  19277. if (!_sg_validate_apply_pipeline(pip_id)) {
  19278. _sg.next_draw_valid = false;
  19279. return;
  19280. }
  19281. if (!_sg.cur_pass.valid) {
  19282. return;
  19283. }
  19284. _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  19285. SOKOL_ASSERT(pip);
  19286. _sg.cur_pip = _sg_pipeline_ref(pip);
  19287. _sg.next_draw_valid = (SG_RESOURCESTATE_VALID == pip->slot.state);
  19288. if (!_sg.next_draw_valid) {
  19289. return;
  19290. }
  19291. _sg_apply_pipeline(pip);
  19292. // set the expected bindings and uniform block flags
  19293. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  19294. _sg.required_bindings_and_uniforms = pip->cmn.required_bindings_and_uniforms | shd->cmn.required_bindings_and_uniforms;
  19295. _sg.applied_bindings_and_uniforms = 0;
  19296. _SG_TRACE_ARGS(apply_pipeline, pip_id);
  19297. }
  19298. SOKOL_API_IMPL void sg_apply_bindings(const sg_bindings* bindings) {
  19299. SOKOL_ASSERT(_sg.valid);
  19300. SOKOL_ASSERT(bindings);
  19301. SOKOL_ASSERT((bindings->_start_canary == 0) && (bindings->_end_canary==0));
  19302. _sg_stats_add(num_apply_bindings, 1);
  19303. _sg.applied_bindings_and_uniforms |= (1 << SG_MAX_UNIFORMBLOCK_BINDSLOTS);
  19304. if (!_sg_validate_apply_bindings(bindings)) {
  19305. _sg.next_draw_valid = false;
  19306. }
  19307. if (!_sg_pipeline_ref_alive(&_sg.cur_pip)) {
  19308. _sg.next_draw_valid = false;
  19309. }
  19310. if (!_sg.cur_pass.valid) {
  19311. return;
  19312. }
  19313. if (!_sg.next_draw_valid) {
  19314. return;
  19315. }
  19316. _sg_bindings_ptrs_t bnd;
  19317. _sg_clear(&bnd, sizeof(bnd));
  19318. bnd.pip = _sg_pipeline_ref_ptr(&_sg.cur_pip);
  19319. const _sg_shader_t* shd = _sg_shader_ref_ptr(&bnd.pip->cmn.shader);
  19320. if (!_sg.cur_pass.is_compute) {
  19321. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  19322. if (bnd.pip->cmn.vertex_buffer_layout_active[i]) {
  19323. SOKOL_ASSERT(bindings->vertex_buffers[i].id != SG_INVALID_ID);
  19324. bnd.vbs[i] = _sg_lookup_buffer(bindings->vertex_buffers[i].id);
  19325. bnd.vb_offsets[i] = bindings->vertex_buffer_offsets[i];
  19326. if (bnd.vbs[i]) {
  19327. _sg.next_draw_valid &= (SG_RESOURCESTATE_VALID == bnd.vbs[i]->slot.state);
  19328. _sg.next_draw_valid &= !bnd.vbs[i]->cmn.append_overflow;
  19329. } else {
  19330. _sg.next_draw_valid = false;
  19331. }
  19332. }
  19333. }
  19334. if (bindings->index_buffer.id) {
  19335. bnd.ib = _sg_lookup_buffer(bindings->index_buffer.id);
  19336. bnd.ib_offset = bindings->index_buffer_offset;
  19337. if (bnd.ib) {
  19338. _sg.next_draw_valid &= (SG_RESOURCESTATE_VALID == bnd.ib->slot.state);
  19339. _sg.next_draw_valid &= !bnd.ib->cmn.append_overflow;
  19340. } else {
  19341. _sg.next_draw_valid = false;
  19342. }
  19343. }
  19344. }
  19345. for (int i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  19346. if (shd->cmn.images[i].stage != SG_SHADERSTAGE_NONE) {
  19347. SOKOL_ASSERT(bindings->images[i].id != SG_INVALID_ID);
  19348. bnd.imgs[i] = _sg_lookup_image(bindings->images[i].id);
  19349. if (bnd.imgs[i]) {
  19350. _sg.next_draw_valid &= (SG_RESOURCESTATE_VALID == bnd.imgs[i]->slot.state);
  19351. } else {
  19352. _sg.next_draw_valid = false;
  19353. }
  19354. }
  19355. }
  19356. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  19357. if (shd->cmn.samplers[i].stage != SG_SHADERSTAGE_NONE) {
  19358. SOKOL_ASSERT(bindings->samplers[i].id != SG_INVALID_ID);
  19359. bnd.smps[i] = _sg_lookup_sampler(bindings->samplers[i].id);
  19360. if (bnd.smps[i]) {
  19361. _sg.next_draw_valid &= (SG_RESOURCESTATE_VALID == bnd.smps[i]->slot.state);
  19362. } else {
  19363. _sg.next_draw_valid = false;
  19364. }
  19365. }
  19366. }
  19367. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  19368. if (shd->cmn.storage_buffers[i].stage != SG_SHADERSTAGE_NONE) {
  19369. SOKOL_ASSERT(bindings->storage_buffers[i].id != SG_INVALID_ID);
  19370. bnd.sbufs[i] = _sg_lookup_buffer(bindings->storage_buffers[i].id);
  19371. if (bnd.sbufs[i]) {
  19372. _sg.next_draw_valid &= (SG_RESOURCESTATE_VALID == bnd.sbufs[i]->slot.state);
  19373. if (_sg.cur_pass.is_compute) {
  19374. _sg_compute_pass_track_storage_buffer(bnd.sbufs[i], shd->cmn.storage_buffers[i].readonly);
  19375. }
  19376. } else {
  19377. _sg.next_draw_valid = false;
  19378. }
  19379. }
  19380. }
  19381. if (_sg.next_draw_valid) {
  19382. _sg.next_draw_valid &= _sg_apply_bindings(&bnd);
  19383. _SG_TRACE_ARGS(apply_bindings, bindings);
  19384. }
  19385. }
  19386. SOKOL_API_IMPL void sg_apply_uniforms(int ub_slot, const sg_range* data) {
  19387. SOKOL_ASSERT(_sg.valid);
  19388. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  19389. SOKOL_ASSERT(data && data->ptr && (data->size > 0));
  19390. _sg_stats_add(num_apply_uniforms, 1);
  19391. _sg_stats_add(size_apply_uniforms, (uint32_t)data->size);
  19392. _sg.applied_bindings_and_uniforms |= 1 << ub_slot;
  19393. if (!_sg_validate_apply_uniforms(ub_slot, data)) {
  19394. _sg.next_draw_valid = false;
  19395. return;
  19396. }
  19397. if (!_sg.cur_pass.valid) {
  19398. return;
  19399. }
  19400. if (!_sg.next_draw_valid) {
  19401. return;
  19402. }
  19403. _sg_apply_uniforms(ub_slot, data);
  19404. _SG_TRACE_ARGS(apply_uniforms, ub_slot, data);
  19405. }
  19406. SOKOL_API_IMPL void sg_draw(int base_element, int num_elements, int num_instances) {
  19407. SOKOL_ASSERT(_sg.valid);
  19408. #if defined(SOKOL_DEBUG)
  19409. if (!_sg_validate_draw(base_element, num_elements, num_instances)) {
  19410. return;
  19411. }
  19412. #endif
  19413. _sg_stats_add(num_draw, 1);
  19414. if (!_sg.cur_pass.valid) {
  19415. return;
  19416. }
  19417. if (!_sg.next_draw_valid) {
  19418. return;
  19419. }
  19420. // skip no-op draws
  19421. if ((0 == num_elements) || (0 == num_instances)) {
  19422. return;
  19423. }
  19424. _sg_draw(base_element, num_elements, num_instances);
  19425. _SG_TRACE_ARGS(draw, base_element, num_elements, num_instances);
  19426. }
  19427. SOKOL_API_IMPL void sg_dispatch(int num_groups_x, int num_groups_y, int num_groups_z) {
  19428. SOKOL_ASSERT(_sg.valid);
  19429. #if defined(SOKOL_DEBUG)
  19430. if (!_sg_validate_dispatch(num_groups_x, num_groups_y, num_groups_z)) {
  19431. return;
  19432. }
  19433. #endif
  19434. _sg_stats_add(num_dispatch, 1);
  19435. if (!_sg.cur_pass.valid) {
  19436. return;
  19437. }
  19438. if (!_sg.next_draw_valid) {
  19439. return;
  19440. }
  19441. // skip no-op dispatches
  19442. if ((0 == num_groups_x) || (0 == num_groups_y) || (0 == num_groups_z)) {
  19443. return;
  19444. }
  19445. _sg_dispatch(num_groups_x, num_groups_y, num_groups_z);
  19446. _SG_TRACE_ARGS(dispatch, num_groups_x, num_groups_y, num_groups_z);
  19447. }
  19448. SOKOL_API_IMPL void sg_end_pass(void) {
  19449. SOKOL_ASSERT(_sg.valid);
  19450. SOKOL_ASSERT(_sg.cur_pass.in_pass);
  19451. _sg_stats_add(num_passes, 1);
  19452. // NOTE: don't exit early if !_sg.cur_pass.valid
  19453. _sg_end_pass();
  19454. _sg.cur_pip = _sg_pipeline_ref(0);
  19455. if (_sg.cur_pass.is_compute) {
  19456. _sg_compute_on_endpass();
  19457. }
  19458. _sg_clear(&_sg.cur_pass, sizeof(_sg.cur_pass));
  19459. _SG_TRACE_NOARGS(end_pass);
  19460. }
  19461. SOKOL_API_IMPL void sg_commit(void) {
  19462. SOKOL_ASSERT(_sg.valid);
  19463. SOKOL_ASSERT(!_sg.cur_pass.valid);
  19464. SOKOL_ASSERT(!_sg.cur_pass.in_pass);
  19465. _sg_commit();
  19466. _sg.stats.frame_index = _sg.frame_index;
  19467. _sg.prev_stats = _sg.stats;
  19468. _sg_clear(&_sg.stats, sizeof(_sg.stats));
  19469. _sg_notify_commit_listeners();
  19470. _SG_TRACE_NOARGS(commit);
  19471. _sg.frame_index++;
  19472. }
  19473. SOKOL_API_IMPL void sg_reset_state_cache(void) {
  19474. SOKOL_ASSERT(_sg.valid);
  19475. _sg_reset_state_cache();
  19476. _SG_TRACE_NOARGS(reset_state_cache);
  19477. }
  19478. SOKOL_API_IMPL void sg_update_buffer(sg_buffer buf_id, const sg_range* data) {
  19479. SOKOL_ASSERT(_sg.valid);
  19480. SOKOL_ASSERT(data && data->ptr && (data->size > 0));
  19481. _sg_stats_add(num_update_buffer, 1);
  19482. _sg_stats_add(size_update_buffer, (uint32_t)data->size);
  19483. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19484. if ((data->size > 0) && buf && (buf->slot.state == SG_RESOURCESTATE_VALID)) {
  19485. if (_sg_validate_update_buffer(buf, data)) {
  19486. SOKOL_ASSERT(data->size <= (size_t)buf->cmn.size);
  19487. // only one update allowed per buffer and frame
  19488. SOKOL_ASSERT(buf->cmn.update_frame_index != _sg.frame_index);
  19489. // update and append on same buffer in same frame not allowed
  19490. SOKOL_ASSERT(buf->cmn.append_frame_index != _sg.frame_index);
  19491. _sg_update_buffer(buf, data);
  19492. buf->cmn.update_frame_index = _sg.frame_index;
  19493. }
  19494. }
  19495. _SG_TRACE_ARGS(update_buffer, buf_id, data);
  19496. }
  19497. SOKOL_API_IMPL int sg_append_buffer(sg_buffer buf_id, const sg_range* data) {
  19498. SOKOL_ASSERT(_sg.valid);
  19499. SOKOL_ASSERT(data && data->ptr);
  19500. _sg_stats_add(num_append_buffer, 1);
  19501. _sg_stats_add(size_append_buffer, (uint32_t)data->size);
  19502. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19503. int result;
  19504. if (buf) {
  19505. // rewind append cursor in a new frame
  19506. if (buf->cmn.append_frame_index != _sg.frame_index) {
  19507. buf->cmn.append_pos = 0;
  19508. buf->cmn.append_overflow = false;
  19509. }
  19510. if (((size_t)buf->cmn.append_pos + data->size) > (size_t)buf->cmn.size) {
  19511. buf->cmn.append_overflow = true;
  19512. }
  19513. const int start_pos = buf->cmn.append_pos;
  19514. // NOTE: the multiple-of-4 requirement for the buffer offset is coming
  19515. // from WebGPU, but we want identical behaviour between backends
  19516. SOKOL_ASSERT(_sg_multiple_u64((uint64_t)start_pos, 4));
  19517. if (buf->slot.state == SG_RESOURCESTATE_VALID) {
  19518. if (_sg_validate_append_buffer(buf, data)) {
  19519. if (!buf->cmn.append_overflow && (data->size > 0)) {
  19520. // update and append on same buffer in same frame not allowed
  19521. SOKOL_ASSERT(buf->cmn.update_frame_index != _sg.frame_index);
  19522. _sg_append_buffer(buf, data, buf->cmn.append_frame_index != _sg.frame_index);
  19523. buf->cmn.append_pos += (int) _sg_roundup_u64(data->size, 4);
  19524. buf->cmn.append_frame_index = _sg.frame_index;
  19525. }
  19526. }
  19527. }
  19528. result = start_pos;
  19529. } else {
  19530. // FIXME: should we return -1 here?
  19531. result = 0;
  19532. }
  19533. _SG_TRACE_ARGS(append_buffer, buf_id, data, result);
  19534. return result;
  19535. }
  19536. SOKOL_API_IMPL bool sg_query_buffer_overflow(sg_buffer buf_id) {
  19537. SOKOL_ASSERT(_sg.valid);
  19538. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19539. bool result = buf ? buf->cmn.append_overflow : false;
  19540. return result;
  19541. }
  19542. SOKOL_API_IMPL bool sg_query_buffer_will_overflow(sg_buffer buf_id, size_t size) {
  19543. SOKOL_ASSERT(_sg.valid);
  19544. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19545. bool result = false;
  19546. if (buf) {
  19547. int append_pos = buf->cmn.append_pos;
  19548. // rewind append cursor in a new frame
  19549. if (buf->cmn.append_frame_index != _sg.frame_index) {
  19550. append_pos = 0;
  19551. }
  19552. if ((append_pos + _sg_roundup((int)size, 4)) > buf->cmn.size) {
  19553. result = true;
  19554. }
  19555. }
  19556. return result;
  19557. }
  19558. SOKOL_API_IMPL void sg_update_image(sg_image img_id, const sg_image_data* data) {
  19559. SOKOL_ASSERT(_sg.valid);
  19560. _sg_stats_add(num_update_image, 1);
  19561. for (int face_index = 0; face_index < SG_CUBEFACE_NUM; face_index++) {
  19562. for (int mip_index = 0; mip_index < SG_MAX_MIPMAPS; mip_index++) {
  19563. if (data->subimage[face_index][mip_index].size == 0) {
  19564. break;
  19565. }
  19566. _sg_stats_add(size_update_image, (uint32_t)data->subimage[face_index][mip_index].size);
  19567. }
  19568. }
  19569. _sg_image_t* img = _sg_lookup_image(img_id.id);
  19570. if (img && img->slot.state == SG_RESOURCESTATE_VALID) {
  19571. if (_sg_validate_update_image(img, data)) {
  19572. SOKOL_ASSERT(img->cmn.upd_frame_index != _sg.frame_index);
  19573. _sg_update_image(img, data);
  19574. img->cmn.upd_frame_index = _sg.frame_index;
  19575. }
  19576. }
  19577. _SG_TRACE_ARGS(update_image, img_id, data);
  19578. }
  19579. SOKOL_API_IMPL void sg_push_debug_group(const char* name) {
  19580. SOKOL_ASSERT(_sg.valid);
  19581. SOKOL_ASSERT(name);
  19582. _sg_push_debug_group(name);
  19583. _SG_TRACE_ARGS(push_debug_group, name);
  19584. }
  19585. SOKOL_API_IMPL void sg_pop_debug_group(void) {
  19586. SOKOL_ASSERT(_sg.valid);
  19587. _sg_pop_debug_group();
  19588. _SG_TRACE_NOARGS(pop_debug_group);
  19589. }
  19590. SOKOL_API_IMPL bool sg_add_commit_listener(sg_commit_listener listener) {
  19591. SOKOL_ASSERT(_sg.valid);
  19592. return _sg_add_commit_listener(&listener);
  19593. }
  19594. SOKOL_API_IMPL bool sg_remove_commit_listener(sg_commit_listener listener) {
  19595. SOKOL_ASSERT(_sg.valid);
  19596. return _sg_remove_commit_listener(&listener);
  19597. }
  19598. SOKOL_API_IMPL void sg_enable_frame_stats(void) {
  19599. SOKOL_ASSERT(_sg.valid);
  19600. _sg.stats_enabled = true;
  19601. }
  19602. SOKOL_API_IMPL void sg_disable_frame_stats(void) {
  19603. SOKOL_ASSERT(_sg.valid);
  19604. _sg.stats_enabled = false;
  19605. }
  19606. SOKOL_API_IMPL bool sg_frame_stats_enabled(void) {
  19607. return _sg.stats_enabled;
  19608. }
  19609. SOKOL_API_IMPL sg_buffer_info sg_query_buffer_info(sg_buffer buf_id) {
  19610. SOKOL_ASSERT(_sg.valid);
  19611. sg_buffer_info info;
  19612. _sg_clear(&info, sizeof(info));
  19613. const _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19614. if (buf) {
  19615. info.slot.state = buf->slot.state;
  19616. info.slot.res_id = buf->slot.id;
  19617. info.slot.uninit_count = buf->slot.uninit_count;
  19618. info.update_frame_index = buf->cmn.update_frame_index;
  19619. info.append_frame_index = buf->cmn.append_frame_index;
  19620. info.append_pos = buf->cmn.append_pos;
  19621. info.append_overflow = buf->cmn.append_overflow;
  19622. #if defined(SOKOL_D3D11)
  19623. info.num_slots = 1;
  19624. info.active_slot = 0;
  19625. #else
  19626. info.num_slots = buf->cmn.num_slots;
  19627. info.active_slot = buf->cmn.active_slot;
  19628. #endif
  19629. }
  19630. return info;
  19631. }
  19632. SOKOL_API_IMPL sg_image_info sg_query_image_info(sg_image img_id) {
  19633. SOKOL_ASSERT(_sg.valid);
  19634. sg_image_info info;
  19635. _sg_clear(&info, sizeof(info));
  19636. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19637. if (img) {
  19638. info.slot.state = img->slot.state;
  19639. info.slot.res_id = img->slot.id;
  19640. info.slot.uninit_count = img->slot.uninit_count;
  19641. info.upd_frame_index = img->cmn.upd_frame_index;
  19642. #if defined(SOKOL_D3D11)
  19643. info.num_slots = 1;
  19644. info.active_slot = 0;
  19645. #else
  19646. info.num_slots = img->cmn.num_slots;
  19647. info.active_slot = img->cmn.active_slot;
  19648. #endif
  19649. }
  19650. return info;
  19651. }
  19652. SOKOL_API_IMPL sg_sampler_info sg_query_sampler_info(sg_sampler smp_id) {
  19653. SOKOL_ASSERT(_sg.valid);
  19654. sg_sampler_info info;
  19655. _sg_clear(&info, sizeof(info));
  19656. const _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  19657. if (smp) {
  19658. info.slot.state = smp->slot.state;
  19659. info.slot.res_id = smp->slot.id;
  19660. info.slot.uninit_count = smp->slot.uninit_count;
  19661. }
  19662. return info;
  19663. }
  19664. SOKOL_API_IMPL sg_shader_info sg_query_shader_info(sg_shader shd_id) {
  19665. SOKOL_ASSERT(_sg.valid);
  19666. sg_shader_info info;
  19667. _sg_clear(&info, sizeof(info));
  19668. const _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  19669. if (shd) {
  19670. info.slot.state = shd->slot.state;
  19671. info.slot.res_id = shd->slot.id;
  19672. info.slot.uninit_count = shd->slot.uninit_count;
  19673. }
  19674. return info;
  19675. }
  19676. SOKOL_API_IMPL sg_pipeline_info sg_query_pipeline_info(sg_pipeline pip_id) {
  19677. SOKOL_ASSERT(_sg.valid);
  19678. sg_pipeline_info info;
  19679. _sg_clear(&info, sizeof(info));
  19680. const _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  19681. if (pip) {
  19682. info.slot.state = pip->slot.state;
  19683. info.slot.res_id = pip->slot.id;
  19684. info.slot.uninit_count = pip->slot.uninit_count;
  19685. }
  19686. return info;
  19687. }
  19688. SOKOL_API_IMPL sg_attachments_info sg_query_attachments_info(sg_attachments atts_id) {
  19689. SOKOL_ASSERT(_sg.valid);
  19690. sg_attachments_info info;
  19691. _sg_clear(&info, sizeof(info));
  19692. const _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  19693. if (atts) {
  19694. info.slot.state = atts->slot.state;
  19695. info.slot.res_id = atts->slot.id;
  19696. info.slot.uninit_count = atts->slot.uninit_count;
  19697. }
  19698. return info;
  19699. }
  19700. SOKOL_API_IMPL sg_buffer_desc sg_query_buffer_desc(sg_buffer buf_id) {
  19701. SOKOL_ASSERT(_sg.valid);
  19702. sg_buffer_desc desc;
  19703. _sg_clear(&desc, sizeof(desc));
  19704. const _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19705. if (buf) {
  19706. desc.size = (size_t)buf->cmn.size;
  19707. desc.usage = buf->cmn.usage;
  19708. }
  19709. return desc;
  19710. }
  19711. SOKOL_API_IMPL size_t sg_query_buffer_size(sg_buffer buf_id) {
  19712. SOKOL_ASSERT(_sg.valid);
  19713. const _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19714. if (buf) {
  19715. return (size_t)buf->cmn.size;
  19716. }
  19717. return 0;
  19718. }
  19719. SOKOL_API_IMPL sg_buffer_usage sg_query_buffer_usage(sg_buffer buf_id) {
  19720. SOKOL_ASSERT(_sg.valid);
  19721. sg_buffer_usage usg;
  19722. _sg_clear(&usg, sizeof(usg));
  19723. const _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19724. if (buf) {
  19725. usg = buf->cmn.usage;
  19726. }
  19727. return usg;
  19728. }
  19729. SOKOL_API_IMPL sg_image_desc sg_query_image_desc(sg_image img_id) {
  19730. SOKOL_ASSERT(_sg.valid);
  19731. sg_image_desc desc;
  19732. _sg_clear(&desc, sizeof(desc));
  19733. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19734. if (img) {
  19735. desc.type = img->cmn.type;
  19736. desc.width = img->cmn.width;
  19737. desc.height = img->cmn.height;
  19738. desc.num_slices = img->cmn.num_slices;
  19739. desc.num_mipmaps = img->cmn.num_mipmaps;
  19740. desc.usage = img->cmn.usage;
  19741. desc.pixel_format = img->cmn.pixel_format;
  19742. desc.sample_count = img->cmn.sample_count;
  19743. }
  19744. return desc;
  19745. }
  19746. SOKOL_API_IMPL sg_image_type sg_query_image_type(sg_image img_id) {
  19747. SOKOL_ASSERT(_sg.valid);
  19748. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19749. if (img) {
  19750. return img->cmn.type;
  19751. }
  19752. return _SG_IMAGETYPE_DEFAULT;
  19753. }
  19754. SOKOL_API_IMPL int sg_query_image_width(sg_image img_id) {
  19755. SOKOL_ASSERT(_sg.valid);
  19756. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19757. if (img) {
  19758. return img->cmn.width;
  19759. }
  19760. return 0;
  19761. }
  19762. SOKOL_API_IMPL int sg_query_image_height(sg_image img_id) {
  19763. SOKOL_ASSERT(_sg.valid);
  19764. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19765. if (img) {
  19766. return img->cmn.height;
  19767. }
  19768. return 0;
  19769. }
  19770. SOKOL_API_IMPL int sg_query_image_num_slices(sg_image img_id) {
  19771. SOKOL_ASSERT(_sg.valid);
  19772. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19773. if (img) {
  19774. return img->cmn.num_slices;
  19775. }
  19776. return 0;
  19777. }
  19778. SOKOL_API_IMPL int sg_query_image_num_mipmaps(sg_image img_id) {
  19779. SOKOL_ASSERT(_sg.valid);
  19780. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19781. if (img) {
  19782. return img->cmn.num_mipmaps;
  19783. }
  19784. return 0;
  19785. }
  19786. SOKOL_API_IMPL sg_pixel_format sg_query_image_pixelformat(sg_image img_id) {
  19787. SOKOL_ASSERT(_sg.valid);
  19788. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19789. if (img) {
  19790. return img->cmn.pixel_format;
  19791. }
  19792. return _SG_PIXELFORMAT_DEFAULT;
  19793. }
  19794. SOKOL_API_IMPL sg_image_usage sg_query_image_usage(sg_image img_id) {
  19795. SOKOL_ASSERT(_sg.valid);
  19796. sg_image_usage usg;
  19797. _sg_clear(&usg, sizeof(usg));
  19798. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19799. if (img) {
  19800. usg = img->cmn.usage;
  19801. }
  19802. return usg;
  19803. }
  19804. SOKOL_API_IMPL int sg_query_image_sample_count(sg_image img_id) {
  19805. SOKOL_ASSERT(_sg.valid);
  19806. SOKOL_ASSERT(_sg.valid);
  19807. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19808. if (img) {
  19809. return img->cmn.sample_count;
  19810. }
  19811. return 0;
  19812. }
  19813. SOKOL_API_IMPL sg_sampler_desc sg_query_sampler_desc(sg_sampler smp_id) {
  19814. SOKOL_ASSERT(_sg.valid);
  19815. sg_sampler_desc desc;
  19816. _sg_clear(&desc, sizeof(desc));
  19817. const _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  19818. if (smp) {
  19819. desc.min_filter = smp->cmn.min_filter;
  19820. desc.mag_filter = smp->cmn.mag_filter;
  19821. desc.mipmap_filter = smp->cmn.mipmap_filter;
  19822. desc.wrap_u = smp->cmn.wrap_u;
  19823. desc.wrap_v = smp->cmn.wrap_v;
  19824. desc.wrap_w = smp->cmn.wrap_w;
  19825. desc.min_lod = smp->cmn.min_lod;
  19826. desc.max_lod = smp->cmn.max_lod;
  19827. desc.border_color = smp->cmn.border_color;
  19828. desc.compare = smp->cmn.compare;
  19829. desc.max_anisotropy = smp->cmn.max_anisotropy;
  19830. }
  19831. return desc;
  19832. }
  19833. SOKOL_API_IMPL sg_shader_desc sg_query_shader_desc(sg_shader shd_id) {
  19834. SOKOL_ASSERT(_sg.valid);
  19835. sg_shader_desc desc;
  19836. _sg_clear(&desc, sizeof(desc));
  19837. const _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  19838. if (shd) {
  19839. for (size_t ub_idx = 0; ub_idx < SG_MAX_UNIFORMBLOCK_BINDSLOTS; ub_idx++) {
  19840. sg_shader_uniform_block* ub_desc = &desc.uniform_blocks[ub_idx];
  19841. const _sg_shader_uniform_block_t* ub = &shd->cmn.uniform_blocks[ub_idx];
  19842. ub_desc->stage = ub->stage;
  19843. ub_desc->size = ub->size;
  19844. }
  19845. for (size_t sbuf_idx = 0; sbuf_idx < SG_MAX_STORAGEBUFFER_BINDSLOTS; sbuf_idx++) {
  19846. sg_shader_storage_buffer* sbuf_desc = &desc.storage_buffers[sbuf_idx];
  19847. const _sg_shader_storage_buffer_t* sbuf = &shd->cmn.storage_buffers[sbuf_idx];
  19848. sbuf_desc->stage = sbuf->stage;
  19849. sbuf_desc->readonly = sbuf->readonly;
  19850. }
  19851. for (size_t simg_idx = 0; simg_idx < SG_MAX_STORAGE_ATTACHMENTS; simg_idx++) {
  19852. sg_shader_storage_image* simg_desc = &desc.storage_images[simg_idx];
  19853. const _sg_shader_storage_image_t* simg = &shd->cmn.storage_images[simg_idx];
  19854. simg_desc->stage = simg->stage;
  19855. simg_desc->access_format = simg->access_format;
  19856. simg_desc->image_type = simg->image_type;
  19857. simg_desc->writeonly = simg->writeonly;
  19858. }
  19859. for (size_t img_idx = 0; img_idx < SG_MAX_IMAGE_BINDSLOTS; img_idx++) {
  19860. sg_shader_image* img_desc = &desc.images[img_idx];
  19861. const _sg_shader_image_t* img = &shd->cmn.images[img_idx];
  19862. img_desc->stage = img->stage;
  19863. img_desc->image_type = img->image_type;
  19864. img_desc->sample_type = img->sample_type;
  19865. img_desc->multisampled = img->multisampled;
  19866. }
  19867. for (size_t smp_idx = 0; smp_idx < SG_MAX_SAMPLER_BINDSLOTS; smp_idx++) {
  19868. sg_shader_sampler* smp_desc = &desc.samplers[smp_idx];
  19869. const _sg_shader_sampler_t* smp = &shd->cmn.samplers[smp_idx];
  19870. smp_desc->stage = smp->stage;
  19871. smp_desc->sampler_type = smp->sampler_type;
  19872. }
  19873. for (size_t img_smp_idx = 0; img_smp_idx < SG_MAX_IMAGE_SAMPLER_PAIRS; img_smp_idx++) {
  19874. sg_shader_image_sampler_pair* img_smp_desc = &desc.image_sampler_pairs[img_smp_idx];
  19875. const _sg_shader_image_sampler_t* img_smp = &shd->cmn.image_samplers[img_smp_idx];
  19876. img_smp_desc->stage = img_smp->stage;
  19877. img_smp_desc->image_slot = img_smp->image_slot;
  19878. img_smp_desc->sampler_slot = img_smp->sampler_slot;
  19879. }
  19880. }
  19881. return desc;
  19882. }
  19883. SOKOL_API_IMPL sg_pipeline_desc sg_query_pipeline_desc(sg_pipeline pip_id) {
  19884. SOKOL_ASSERT(_sg.valid);
  19885. sg_pipeline_desc desc;
  19886. _sg_clear(&desc, sizeof(desc));
  19887. const _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  19888. if (pip) {
  19889. desc.compute = pip->cmn.is_compute;
  19890. desc.shader.id = pip->cmn.shader.sref.id;
  19891. desc.layout = pip->cmn.layout;
  19892. desc.depth = pip->cmn.depth;
  19893. desc.stencil = pip->cmn.stencil;
  19894. desc.color_count = pip->cmn.color_count;
  19895. for (int i = 0; i < pip->cmn.color_count; i++) {
  19896. desc.colors[i] = pip->cmn.colors[i];
  19897. }
  19898. desc.primitive_type = pip->cmn.primitive_type;
  19899. desc.index_type = pip->cmn.index_type;
  19900. desc.cull_mode = pip->cmn.cull_mode;
  19901. desc.face_winding = pip->cmn.face_winding;
  19902. desc.sample_count = pip->cmn.sample_count;
  19903. desc.blend_color = pip->cmn.blend_color;
  19904. desc.alpha_to_coverage_enabled = pip->cmn.alpha_to_coverage_enabled;
  19905. }
  19906. return desc;
  19907. }
  19908. SOKOL_API_IMPL sg_attachments_desc sg_query_attachments_desc(sg_attachments atts_id) {
  19909. SOKOL_ASSERT(_sg.valid);
  19910. sg_attachments_desc desc;
  19911. _sg_clear(&desc, sizeof(desc));
  19912. const _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  19913. if (atts) {
  19914. for (int i = 0; i < atts->cmn.num_colors; i++) {
  19915. desc.colors[i].image.id = atts->cmn.colors[i].image.sref.id;
  19916. desc.colors[i].mip_level = atts->cmn.colors[i].mip_level;
  19917. desc.colors[i].slice = atts->cmn.colors[i].slice;
  19918. }
  19919. desc.depth_stencil.image.id = atts->cmn.depth_stencil.image.sref.id;
  19920. desc.depth_stencil.mip_level = atts->cmn.depth_stencil.mip_level;
  19921. desc.depth_stencil.slice = atts->cmn.depth_stencil.slice;
  19922. }
  19923. return desc;
  19924. }
  19925. SOKOL_API_IMPL sg_buffer_desc sg_query_buffer_defaults(const sg_buffer_desc* desc) {
  19926. SOKOL_ASSERT(_sg.valid && desc);
  19927. return _sg_buffer_desc_defaults(desc);
  19928. }
  19929. SOKOL_API_IMPL sg_image_desc sg_query_image_defaults(const sg_image_desc* desc) {
  19930. SOKOL_ASSERT(_sg.valid && desc);
  19931. return _sg_image_desc_defaults(desc);
  19932. }
  19933. SOKOL_API_IMPL sg_sampler_desc sg_query_sampler_defaults(const sg_sampler_desc* desc) {
  19934. SOKOL_ASSERT(_sg.valid && desc);
  19935. return _sg_sampler_desc_defaults(desc);
  19936. }
  19937. SOKOL_API_IMPL sg_shader_desc sg_query_shader_defaults(const sg_shader_desc* desc) {
  19938. SOKOL_ASSERT(_sg.valid && desc);
  19939. return _sg_shader_desc_defaults(desc);
  19940. }
  19941. SOKOL_API_IMPL sg_pipeline_desc sg_query_pipeline_defaults(const sg_pipeline_desc* desc) {
  19942. SOKOL_ASSERT(_sg.valid && desc);
  19943. return _sg_pipeline_desc_defaults(desc);
  19944. }
  19945. SOKOL_API_IMPL sg_attachments_desc sg_query_attachments_defaults(const sg_attachments_desc* desc) {
  19946. SOKOL_ASSERT(_sg.valid && desc);
  19947. return _sg_attachments_desc_defaults(desc);
  19948. }
  19949. SOKOL_API_IMPL const void* sg_d3d11_device(void) {
  19950. #if defined(SOKOL_D3D11)
  19951. return (const void*) _sg.d3d11.dev;
  19952. #else
  19953. return 0;
  19954. #endif
  19955. }
  19956. SOKOL_API_IMPL const void* sg_d3d11_device_context(void) {
  19957. #if defined(SOKOL_D3D11)
  19958. return (const void*) _sg.d3d11.ctx;
  19959. #else
  19960. return 0;
  19961. #endif
  19962. }
  19963. SOKOL_API_IMPL sg_d3d11_buffer_info sg_d3d11_query_buffer_info(sg_buffer buf_id) {
  19964. SOKOL_ASSERT(_sg.valid);
  19965. sg_d3d11_buffer_info res;
  19966. _sg_clear(&res, sizeof(res));
  19967. #if defined(SOKOL_D3D11)
  19968. const _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19969. if (buf) {
  19970. res.buf = (const void*) buf->d3d11.buf;
  19971. }
  19972. #else
  19973. _SOKOL_UNUSED(buf_id);
  19974. #endif
  19975. return res;
  19976. }
  19977. SOKOL_API_IMPL sg_d3d11_image_info sg_d3d11_query_image_info(sg_image img_id) {
  19978. SOKOL_ASSERT(_sg.valid);
  19979. sg_d3d11_image_info res;
  19980. _sg_clear(&res, sizeof(res));
  19981. #if defined(SOKOL_D3D11)
  19982. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19983. if (img) {
  19984. res.tex2d = (const void*) img->d3d11.tex2d;
  19985. res.tex3d = (const void*) img->d3d11.tex3d;
  19986. res.res = (const void*) img->d3d11.res;
  19987. res.srv = (const void*) img->d3d11.srv;
  19988. }
  19989. #else
  19990. _SOKOL_UNUSED(img_id);
  19991. #endif
  19992. return res;
  19993. }
  19994. SOKOL_API_IMPL sg_d3d11_sampler_info sg_d3d11_query_sampler_info(sg_sampler smp_id) {
  19995. SOKOL_ASSERT(_sg.valid);
  19996. sg_d3d11_sampler_info res;
  19997. _sg_clear(&res, sizeof(res));
  19998. #if defined(SOKOL_D3D11)
  19999. const _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  20000. if (smp) {
  20001. res.smp = (const void*) smp->d3d11.smp;
  20002. }
  20003. #else
  20004. _SOKOL_UNUSED(smp_id);
  20005. #endif
  20006. return res;
  20007. }
  20008. SOKOL_API_IMPL sg_d3d11_shader_info sg_d3d11_query_shader_info(sg_shader shd_id) {
  20009. SOKOL_ASSERT(_sg.valid);
  20010. sg_d3d11_shader_info res;
  20011. _sg_clear(&res, sizeof(res));
  20012. #if defined(SOKOL_D3D11)
  20013. const _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  20014. if (shd) {
  20015. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  20016. res.cbufs[i] = (const void*) shd->d3d11.all_cbufs[i];
  20017. }
  20018. res.vs = (const void*) shd->d3d11.vs;
  20019. res.fs = (const void*) shd->d3d11.fs;
  20020. }
  20021. #else
  20022. _SOKOL_UNUSED(shd_id);
  20023. #endif
  20024. return res;
  20025. }
  20026. SOKOL_API_IMPL sg_d3d11_pipeline_info sg_d3d11_query_pipeline_info(sg_pipeline pip_id) {
  20027. SOKOL_ASSERT(_sg.valid);
  20028. sg_d3d11_pipeline_info res;
  20029. _sg_clear(&res, sizeof(res));
  20030. #if defined(SOKOL_D3D11)
  20031. const _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  20032. if (pip) {
  20033. res.il = (const void*) pip->d3d11.il;
  20034. res.rs = (const void*) pip->d3d11.rs;
  20035. res.dss = (const void*) pip->d3d11.dss;
  20036. res.bs = (const void*) pip->d3d11.bs;
  20037. }
  20038. #else
  20039. _SOKOL_UNUSED(pip_id);
  20040. #endif
  20041. return res;
  20042. }
  20043. SOKOL_API_IMPL sg_d3d11_attachments_info sg_d3d11_query_attachments_info(sg_attachments atts_id) {
  20044. SOKOL_ASSERT(_sg.valid);
  20045. sg_d3d11_attachments_info res;
  20046. _sg_clear(&res, sizeof(res));
  20047. #if defined(SOKOL_D3D11)
  20048. const _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  20049. if (atts) {
  20050. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  20051. res.color_rtv[i] = (const void*) atts->d3d11.colors[i].view.rtv;
  20052. res.resolve_rtv[i] = (const void*) atts->d3d11.resolves[i].view.rtv;
  20053. }
  20054. res.dsv = (const void*) atts->d3d11.depth_stencil.view.dsv;
  20055. }
  20056. #else
  20057. _SOKOL_UNUSED(atts_id);
  20058. #endif
  20059. return res;
  20060. }
  20061. SOKOL_API_IMPL const void* sg_mtl_device(void) {
  20062. #if defined(SOKOL_METAL)
  20063. if (nil != _sg.mtl.device) {
  20064. return (__bridge const void*) _sg.mtl.device;
  20065. } else {
  20066. return 0;
  20067. }
  20068. #else
  20069. return 0;
  20070. #endif
  20071. }
  20072. SOKOL_API_IMPL const void* sg_mtl_render_command_encoder(void) {
  20073. #if defined(SOKOL_METAL)
  20074. if (nil != _sg.mtl.render_cmd_encoder) {
  20075. return (__bridge const void*) _sg.mtl.render_cmd_encoder;
  20076. } else {
  20077. return 0;
  20078. }
  20079. #else
  20080. return 0;
  20081. #endif
  20082. }
  20083. SOKOL_API_IMPL const void* sg_mtl_compute_command_encoder(void) {
  20084. #if defined(SOKOL_METAL)
  20085. if (nil != _sg.mtl.compute_cmd_encoder) {
  20086. return (__bridge const void*) _sg.mtl.compute_cmd_encoder;
  20087. } else {
  20088. return 0;
  20089. }
  20090. #else
  20091. return 0;
  20092. #endif
  20093. }
  20094. SOKOL_API_IMPL sg_mtl_buffer_info sg_mtl_query_buffer_info(sg_buffer buf_id) {
  20095. SOKOL_ASSERT(_sg.valid);
  20096. sg_mtl_buffer_info res;
  20097. _sg_clear(&res, sizeof(res));
  20098. #if defined(SOKOL_METAL)
  20099. const _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  20100. if (buf) {
  20101. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  20102. if (buf->mtl.buf[i] != 0) {
  20103. res.buf[i] = (__bridge void*) _sg_mtl_id(buf->mtl.buf[i]);
  20104. }
  20105. }
  20106. res.active_slot = buf->cmn.active_slot;
  20107. }
  20108. #else
  20109. _SOKOL_UNUSED(buf_id);
  20110. #endif
  20111. return res;
  20112. }
  20113. SOKOL_API_IMPL sg_mtl_image_info sg_mtl_query_image_info(sg_image img_id) {
  20114. SOKOL_ASSERT(_sg.valid);
  20115. sg_mtl_image_info res;
  20116. _sg_clear(&res, sizeof(res));
  20117. #if defined(SOKOL_METAL)
  20118. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  20119. if (img) {
  20120. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  20121. if (img->mtl.tex[i] != 0) {
  20122. res.tex[i] = (__bridge void*) _sg_mtl_id(img->mtl.tex[i]);
  20123. }
  20124. }
  20125. res.active_slot = img->cmn.active_slot;
  20126. }
  20127. #else
  20128. _SOKOL_UNUSED(img_id);
  20129. #endif
  20130. return res;
  20131. }
  20132. SOKOL_API_IMPL sg_mtl_sampler_info sg_mtl_query_sampler_info(sg_sampler smp_id) {
  20133. SOKOL_ASSERT(_sg.valid);
  20134. sg_mtl_sampler_info res;
  20135. _sg_clear(&res, sizeof(res));
  20136. #if defined(SOKOL_METAL)
  20137. const _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  20138. if (smp) {
  20139. if (smp->mtl.sampler_state != 0) {
  20140. res.smp = (__bridge void*) _sg_mtl_id(smp->mtl.sampler_state);
  20141. }
  20142. }
  20143. #else
  20144. _SOKOL_UNUSED(smp_id);
  20145. #endif
  20146. return res;
  20147. }
  20148. SOKOL_API_IMPL sg_mtl_shader_info sg_mtl_query_shader_info(sg_shader shd_id) {
  20149. SOKOL_ASSERT(_sg.valid);
  20150. sg_mtl_shader_info res;
  20151. _sg_clear(&res, sizeof(res));
  20152. #if defined(SOKOL_METAL)
  20153. const _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  20154. if (shd) {
  20155. const int vertex_lib = shd->mtl.vertex_func.mtl_lib;
  20156. const int vertex_func = shd->mtl.vertex_func.mtl_func;
  20157. const int fragment_lib = shd->mtl.fragment_func.mtl_lib;
  20158. const int fragment_func = shd->mtl.fragment_func.mtl_func;
  20159. if (vertex_lib != 0) {
  20160. res.vertex_lib = (__bridge void*) _sg_mtl_id(vertex_lib);
  20161. }
  20162. if (fragment_lib != 0) {
  20163. res.fragment_lib = (__bridge void*) _sg_mtl_id(fragment_lib);
  20164. }
  20165. if (vertex_func != 0) {
  20166. res.vertex_func = (__bridge void*) _sg_mtl_id(vertex_func);
  20167. }
  20168. if (fragment_func != 0) {
  20169. res.fragment_func = (__bridge void*) _sg_mtl_id(fragment_func);
  20170. }
  20171. }
  20172. #else
  20173. _SOKOL_UNUSED(shd_id);
  20174. #endif
  20175. return res;
  20176. }
  20177. SOKOL_API_IMPL sg_mtl_pipeline_info sg_mtl_query_pipeline_info(sg_pipeline pip_id) {
  20178. SOKOL_ASSERT(_sg.valid);
  20179. sg_mtl_pipeline_info res;
  20180. _sg_clear(&res, sizeof(res));
  20181. #if defined(SOKOL_METAL)
  20182. const _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  20183. if (pip) {
  20184. if (pip->mtl.rps != 0) {
  20185. res.rps = (__bridge void*) _sg_mtl_id(pip->mtl.rps);
  20186. }
  20187. if (pip->mtl.dss != 0) {
  20188. res.dss = (__bridge void*) _sg_mtl_id(pip->mtl.dss);
  20189. }
  20190. }
  20191. #else
  20192. _SOKOL_UNUSED(pip_id);
  20193. #endif
  20194. return res;
  20195. }
  20196. SOKOL_API_IMPL const void* sg_wgpu_device(void) {
  20197. #if defined(SOKOL_WGPU)
  20198. return (const void*) _sg.wgpu.dev;
  20199. #else
  20200. return 0;
  20201. #endif
  20202. }
  20203. SOKOL_API_IMPL const void* sg_wgpu_queue(void) {
  20204. #if defined(SOKOL_WGPU)
  20205. return (const void*) _sg.wgpu.queue;
  20206. #else
  20207. return 0;
  20208. #endif
  20209. }
  20210. SOKOL_API_IMPL const void* sg_wgpu_command_encoder(void) {
  20211. #if defined(SOKOL_WGPU)
  20212. return (const void*) _sg.wgpu.cmd_enc;
  20213. #else
  20214. return 0;
  20215. #endif
  20216. }
  20217. SOKOL_API_IMPL const void* sg_wgpu_render_pass_encoder(void) {
  20218. #if defined(SOKOL_WGPU)
  20219. return (const void*) _sg.wgpu.rpass_enc;
  20220. #else
  20221. return 0;
  20222. #endif
  20223. }
  20224. SOKOL_API_IMPL const void* sg_wgpu_compute_pass_encoder(void) {
  20225. #if defined(SOKOL_WGPU)
  20226. return (const void*) _sg.wgpu.cpass_enc;
  20227. #else
  20228. return 0;
  20229. #endif
  20230. }
  20231. SOKOL_API_IMPL sg_wgpu_buffer_info sg_wgpu_query_buffer_info(sg_buffer buf_id) {
  20232. SOKOL_ASSERT(_sg.valid);
  20233. sg_wgpu_buffer_info res;
  20234. _sg_clear(&res, sizeof(res));
  20235. #if defined(SOKOL_WGPU)
  20236. const _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  20237. if (buf) {
  20238. res.buf = (const void*) buf->wgpu.buf;
  20239. }
  20240. #else
  20241. _SOKOL_UNUSED(buf_id);
  20242. #endif
  20243. return res;
  20244. }
  20245. SOKOL_API_IMPL sg_wgpu_image_info sg_wgpu_query_image_info(sg_image img_id) {
  20246. SOKOL_ASSERT(_sg.valid);
  20247. sg_wgpu_image_info res;
  20248. _sg_clear(&res, sizeof(res));
  20249. #if defined(SOKOL_WGPU)
  20250. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  20251. if (img) {
  20252. res.tex = (const void*) img->wgpu.tex;
  20253. res.view = (const void*) img->wgpu.view;
  20254. }
  20255. #else
  20256. _SOKOL_UNUSED(img_id);
  20257. #endif
  20258. return res;
  20259. }
  20260. SOKOL_API_IMPL sg_wgpu_sampler_info sg_wgpu_query_sampler_info(sg_sampler smp_id) {
  20261. SOKOL_ASSERT(_sg.valid);
  20262. sg_wgpu_sampler_info res;
  20263. _sg_clear(&res, sizeof(res));
  20264. #if defined(SOKOL_WGPU)
  20265. const _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  20266. if (smp) {
  20267. res.smp = (const void*) smp->wgpu.smp;
  20268. }
  20269. #else
  20270. _SOKOL_UNUSED(smp_id);
  20271. #endif
  20272. return res;
  20273. }
  20274. SOKOL_API_IMPL sg_wgpu_shader_info sg_wgpu_query_shader_info(sg_shader shd_id) {
  20275. SOKOL_ASSERT(_sg.valid);
  20276. sg_wgpu_shader_info res;
  20277. _sg_clear(&res, sizeof(res));
  20278. #if defined(SOKOL_WGPU)
  20279. const _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  20280. if (shd) {
  20281. res.vs_mod = (const void*) shd->wgpu.vertex_func.module;
  20282. res.fs_mod = (const void*) shd->wgpu.fragment_func.module;
  20283. res.bgl = (const void*) shd->wgpu.bgl_img_smp_sbuf;
  20284. }
  20285. #else
  20286. _SOKOL_UNUSED(shd_id);
  20287. #endif
  20288. return res;
  20289. }
  20290. SOKOL_API_IMPL sg_wgpu_pipeline_info sg_wgpu_query_pipeline_info(sg_pipeline pip_id) {
  20291. SOKOL_ASSERT(_sg.valid);
  20292. sg_wgpu_pipeline_info res;
  20293. _sg_clear(&res, sizeof(res));
  20294. #if defined(SOKOL_WGPU)
  20295. const _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  20296. if (pip) {
  20297. res.render_pipeline = (const void*) pip->wgpu.rpip;
  20298. res.compute_pipeline = (const void*) pip->wgpu.cpip;
  20299. }
  20300. #else
  20301. _SOKOL_UNUSED(pip_id);
  20302. #endif
  20303. return res;
  20304. }
  20305. SOKOL_API_IMPL sg_wgpu_attachments_info sg_wgpu_query_attachments_info(sg_attachments atts_id) {
  20306. SOKOL_ASSERT(_sg.valid);
  20307. sg_wgpu_attachments_info res;
  20308. _sg_clear(&res, sizeof(res));
  20309. #if defined(SOKOL_WGPU)
  20310. const _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  20311. if (atts) {
  20312. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  20313. res.color_view[i] = (const void*) atts->wgpu.colors[i].view;
  20314. res.resolve_view[i] = (const void*) atts->wgpu.resolves[i].view;
  20315. }
  20316. res.ds_view = (const void*) atts->wgpu.depth_stencil.view;
  20317. }
  20318. #else
  20319. _SOKOL_UNUSED(atts_id);
  20320. #endif
  20321. return res;
  20322. }
  20323. SOKOL_API_IMPL sg_gl_buffer_info sg_gl_query_buffer_info(sg_buffer buf_id) {
  20324. SOKOL_ASSERT(_sg.valid);
  20325. sg_gl_buffer_info res;
  20326. _sg_clear(&res, sizeof(res));
  20327. #if defined(_SOKOL_ANY_GL)
  20328. const _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  20329. if (buf) {
  20330. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  20331. res.buf[i] = buf->gl.buf[i];
  20332. }
  20333. res.active_slot = buf->cmn.active_slot;
  20334. }
  20335. #else
  20336. _SOKOL_UNUSED(buf_id);
  20337. #endif
  20338. return res;
  20339. }
  20340. SOKOL_API_IMPL sg_gl_image_info sg_gl_query_image_info(sg_image img_id) {
  20341. SOKOL_ASSERT(_sg.valid);
  20342. sg_gl_image_info res;
  20343. _sg_clear(&res, sizeof(res));
  20344. #if defined(_SOKOL_ANY_GL)
  20345. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  20346. if (img) {
  20347. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  20348. res.tex[i] = img->gl.tex[i];
  20349. }
  20350. res.tex_target = img->gl.target;
  20351. res.msaa_render_buffer = img->gl.msaa_render_buffer;
  20352. res.active_slot = img->cmn.active_slot;
  20353. }
  20354. #else
  20355. _SOKOL_UNUSED(img_id);
  20356. #endif
  20357. return res;
  20358. }
  20359. SOKOL_API_IMPL sg_gl_sampler_info sg_gl_query_sampler_info(sg_sampler smp_id) {
  20360. SOKOL_ASSERT(_sg.valid);
  20361. sg_gl_sampler_info res;
  20362. _sg_clear(&res, sizeof(res));
  20363. #if defined(_SOKOL_ANY_GL)
  20364. const _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  20365. if (smp) {
  20366. res.smp = smp->gl.smp;
  20367. }
  20368. #else
  20369. _SOKOL_UNUSED(smp_id);
  20370. #endif
  20371. return res;
  20372. }
  20373. SOKOL_API_IMPL sg_gl_shader_info sg_gl_query_shader_info(sg_shader shd_id) {
  20374. SOKOL_ASSERT(_sg.valid);
  20375. sg_gl_shader_info res;
  20376. _sg_clear(&res, sizeof(res));
  20377. #if defined(_SOKOL_ANY_GL)
  20378. const _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  20379. if (shd) {
  20380. res.prog = shd->gl.prog;
  20381. }
  20382. #else
  20383. _SOKOL_UNUSED(shd_id);
  20384. #endif
  20385. return res;
  20386. }
  20387. SOKOL_API_IMPL sg_gl_attachments_info sg_gl_query_attachments_info(sg_attachments atts_id) {
  20388. SOKOL_ASSERT(_sg.valid);
  20389. sg_gl_attachments_info res;
  20390. _sg_clear(&res, sizeof(res));
  20391. #if defined(_SOKOL_ANY_GL)
  20392. const _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  20393. if (atts) {
  20394. res.framebuffer = atts->gl.fb;
  20395. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  20396. res.msaa_resolve_framebuffer[i] = atts->gl.msaa_resolve_framebuffer[i];
  20397. }
  20398. }
  20399. #else
  20400. _SOKOL_UNUSED(atts_id);
  20401. #endif
  20402. return res;
  20403. }
  20404. #ifdef _MSC_VER
  20405. #pragma warning(pop)
  20406. #endif
  20407. #endif // SOKOL_GFX_IMPL