sokol_gfx.h 991 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317
  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. Link with the following system libraries (note that sokol_app.h has
  53. additional linker requirements):
  54. - on macOS/iOS with Metal: Metal
  55. - on macOS with GL: OpenGL
  56. - on iOS with GL: OpenGLES
  57. - on Linux with EGL: GL or GLESv2
  58. - on Linux with GLX: GL
  59. - on Android: GLESv3, log, android
  60. - on Windows with the MSVC or Clang toolchains: no action needed, libs are defined in-source via pragma-comment-lib
  61. - on Windows with MINGW/MSYS2 gcc: compile with '-mwin32' so that _WIN32 is defined
  62. - with the D3D11 backend: -ld3d11
  63. On macOS and iOS, the implementation must be compiled as Objective-C.
  64. On Emscripten:
  65. - for WebGL2: add the linker option `-s USE_WEBGL2=1`
  66. - for WebGPU: compile and link with `--use-port=emdawnwebgpu`
  67. (for more exotic situations, read: https://dawn.googlesource.com/dawn/+/refs/heads/main/src/emdawnwebgpu/pkg/README.md)
  68. sokol_gfx DOES NOT:
  69. ===================
  70. - create a window, swapchain or the 3D-API context/device, you must do this
  71. before sokol_gfx is initialized, and pass any required information
  72. (like 3D device pointers) to the sokol_gfx initialization call
  73. - present the rendered frame, how this is done exactly usually depends
  74. on how the window and 3D-API context/device was created
  75. - provide a unified shader language, instead 3D-API-specific shader
  76. source-code or shader-bytecode must be provided (for the "official"
  77. offline shader cross-compiler / code-generator, see here:
  78. https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md)
  79. STEP BY STEP
  80. ============
  81. --- to initialize sokol_gfx, after creating a window and a 3D-API
  82. context/device, call:
  83. sg_setup(const sg_desc*)
  84. Depending on the selected 3D backend, sokol-gfx requires some
  85. information about its runtime environment, like a GPU device pointer,
  86. default swapchain pixel formats and so on. If you are using sokol_app.h
  87. for the window system glue, you can use a helper function provided in
  88. the sokol_glue.h header:
  89. #include "sokol_gfx.h"
  90. #include "sokol_app.h"
  91. #include "sokol_glue.h"
  92. //...
  93. sg_setup(&(sg_desc){
  94. .environment = sglue_environment(),
  95. });
  96. To get any logging output for errors and from the validation layer, you
  97. need to provide a logging callback. Easiest way is through sokol_log.h:
  98. #include "sokol_log.h"
  99. //...
  100. sg_setup(&(sg_desc){
  101. //...
  102. .logger.func = slog_func,
  103. });
  104. --- create resource objects (at least buffers, shaders and pipelines,
  105. and optionally images, samplers and render/compute-pass-attachments):
  106. sg_buffer sg_make_buffer(const sg_buffer_desc*)
  107. sg_image sg_make_image(const sg_image_desc*)
  108. sg_sampler sg_make_sampler(const sg_sampler_desc*)
  109. sg_shader sg_make_shader(const sg_shader_desc*)
  110. sg_pipeline sg_make_pipeline(const sg_pipeline_desc*)
  111. sg_attachments sg_make_attachments(const sg_attachments_desc*)
  112. --- start a render- or compute-pass:
  113. sg_begin_pass(const sg_pass* pass);
  114. Typically, render passes render into an externally provided swapchain which
  115. presents the rendering result on the display. Such a 'swapchain pass'
  116. is started like this:
  117. sg_begin_pass(&(sg_pass){ .action = { ... }, .swapchain = sglue_swapchain() })
  118. ...where .action is an sg_pass_action struct containing actions to be performed
  119. at the start and end of a render pass (such as clearing the render surfaces to
  120. a specific color), and .swapchain is an sg_swapchain struct with all the required
  121. information to render into the swapchain's surfaces.
  122. To start an 'offscreen render pass' into sokol-gfx image objects, an sg_attachment
  123. object handle is required instead of an sg_swapchain struct. An offscreen
  124. pass is started like this (assuming attachments is an sg_attachments handle):
  125. sg_begin_pass(&(sg_pass){ .action = { ... }, .attachments = attachments });
  126. To start a compute-pass, just set the .compute item to true:
  127. sg_begin_pass(&(sg_pass){ .compute = true });
  128. If the compute pass writes into storage images, provide those as
  129. 'storage attachments' via an sg_attachments object:
  130. sg_begin_pass(&(sg_pass){ .compute = true, .attachments = attattachments });
  131. --- set the pipeline state for the next draw call with:
  132. sg_apply_pipeline(sg_pipeline pip)
  133. --- fill an sg_bindings struct with the resource bindings for the next
  134. draw- or dispatch-call (0..N vertex buffers, 0 or 1 index buffer, 0..N images,
  135. samplers and storage-buffers), and call
  136. sg_apply_bindings(const sg_bindings* bindings)
  137. ...to update the resource bindings. Note that in a compute pass, no vertex-
  138. or index-buffer bindings are allowed and will be rejected by the validation
  139. layer.
  140. --- optionally update shader uniform data with:
  141. sg_apply_uniforms(int ub_slot, const sg_range* data)
  142. Read the section 'UNIFORM DATA LAYOUT' to learn about the expected memory layout
  143. of the uniform data passed into sg_apply_uniforms().
  144. --- kick off a draw call with:
  145. sg_draw(int base_element, int num_elements, int num_instances)
  146. The sg_draw() function unifies all the different ways to render primitives
  147. in a single call (indexed vs non-indexed rendering, and instanced vs non-instanced
  148. rendering). In case of indexed rendering, base_element and num_element specify
  149. indices in the currently bound index buffer. In case of non-indexed rendering
  150. base_element and num_elements specify vertices in the currently bound
  151. vertex-buffer(s). To perform instanced rendering, the rendering pipeline
  152. must be setup for instancing (see sg_pipeline_desc below), a separate vertex buffer
  153. containing per-instance data must be bound, and the num_instances parameter
  154. must be > 1.
  155. --- ...or kick of a dispatch call to invoke a compute shader workload:
  156. sg_dispatch(int num_groups_x, int num_groups_y, int num_groups_z)
  157. The dispatch args define the number of 'compute workgroups' processed
  158. by the currently applied compute shader.
  159. --- finish the current pass with:
  160. sg_end_pass()
  161. --- when done with the current frame, call
  162. sg_commit()
  163. --- at the end of your program, shutdown sokol_gfx with:
  164. sg_shutdown()
  165. --- if you need to destroy resources before sg_shutdown(), call:
  166. sg_destroy_buffer(sg_buffer buf)
  167. sg_destroy_image(sg_image img)
  168. sg_destroy_sampler(sg_sampler smp)
  169. sg_destroy_shader(sg_shader shd)
  170. sg_destroy_pipeline(sg_pipeline pip)
  171. sg_destroy_attachments(sg_attachments atts)
  172. --- to set a new viewport rectangle, call:
  173. sg_apply_viewport(int x, int y, int width, int height, bool origin_top_left)
  174. ...or if you want to specify the viewport rectangle with float values:
  175. sg_apply_viewportf(float x, float y, float width, float height, bool origin_top_left)
  176. --- to set a new scissor rect, call:
  177. sg_apply_scissor_rect(int x, int y, int width, int height, bool origin_top_left)
  178. ...or with float values:
  179. sg_apply_scissor_rectf(float x, float y, float width, float height, bool origin_top_left)
  180. Both sg_apply_viewport() and sg_apply_scissor_rect() must be called
  181. inside a rendering pass (e.g. not in a compute pass, or outside a pass)
  182. Note that sg_begin_pass() will reset both the viewport and scissor
  183. rectangles to cover the entire framebuffer.
  184. --- to update (overwrite) the content of buffer and image resources, call:
  185. sg_update_buffer(sg_buffer buf, const sg_range* data)
  186. sg_update_image(sg_image img, const sg_image_data* data)
  187. Buffers and images to be updated must have been created with
  188. sg_buffer_desc.usage.dynamic_update or .stream_update.
  189. Only one update per frame is allowed for buffer and image resources when
  190. using the sg_update_*() functions. The rationale is to have a simple
  191. protection from the CPU scribbling over data the GPU is currently
  192. using, or the CPU having to wait for the GPU
  193. Buffer and image updates can be partial, as long as a rendering
  194. operation only references the valid (updated) data in the
  195. buffer or image.
  196. --- to append a chunk of data to a buffer resource, call:
  197. int sg_append_buffer(sg_buffer buf, const sg_range* data)
  198. The difference to sg_update_buffer() is that sg_append_buffer()
  199. can be called multiple times per frame to append new data to the
  200. buffer piece by piece, optionally interleaved with draw calls referencing
  201. the previously written data.
  202. sg_append_buffer() returns a byte offset to the start of the
  203. written data, this offset can be assigned to
  204. sg_bindings.vertex_buffer_offsets[n] or
  205. sg_bindings.index_buffer_offset
  206. Code example:
  207. for (...) {
  208. const void* data = ...;
  209. const int num_bytes = ...;
  210. int offset = sg_append_buffer(buf, &(sg_range) { .ptr=data, .size=num_bytes });
  211. bindings.vertex_buffer_offsets[0] = offset;
  212. sg_apply_pipeline(pip);
  213. sg_apply_bindings(&bindings);
  214. sg_apply_uniforms(...);
  215. sg_draw(...);
  216. }
  217. A buffer to be used with sg_append_buffer() must have been created
  218. with sg_buffer_desc.usage.dynamic_update or .stream_update.
  219. If the application appends more data to the buffer then fits into
  220. the buffer, the buffer will go into the "overflow" state for the
  221. rest of the frame.
  222. Any draw calls attempting to render an overflown buffer will be
  223. silently dropped (in debug mode this will also result in a
  224. validation error).
  225. You can also check manually if a buffer is in overflow-state by calling
  226. bool sg_query_buffer_overflow(sg_buffer buf)
  227. You can manually check to see if an overflow would occur before adding
  228. any data to a buffer by calling
  229. bool sg_query_buffer_will_overflow(sg_buffer buf, size_t size)
  230. NOTE: Due to restrictions in underlying 3D-APIs, appended chunks of
  231. data will be 4-byte aligned in the destination buffer. This means
  232. that there will be gaps in index buffers containing 16-bit indices
  233. when the number of indices in a call to sg_append_buffer() is
  234. odd. This isn't a problem when each call to sg_append_buffer()
  235. is associated with one draw call, but will be problematic when
  236. a single indexed draw call spans several appended chunks of indices.
  237. --- to check at runtime for optional features, limits and pixelformat support,
  238. call:
  239. sg_features sg_query_features()
  240. sg_limits sg_query_limits()
  241. sg_pixelformat_info sg_query_pixelformat(sg_pixel_format fmt)
  242. --- if you need to call into the underlying 3D-API directly, you must call:
  243. sg_reset_state_cache()
  244. ...before calling sokol_gfx functions again
  245. --- you can inspect the original sg_desc structure handed to sg_setup()
  246. by calling sg_query_desc(). This will return an sg_desc struct with
  247. the default values patched in instead of any zero-initialized values
  248. --- you can get a desc struct matching the creation attributes of a
  249. specific resource object via:
  250. sg_buffer_desc sg_query_buffer_desc(sg_buffer buf)
  251. sg_image_desc sg_query_image_desc(sg_image img)
  252. sg_sampler_desc sg_query_sampler_desc(sg_sampler smp)
  253. sg_shader_desc sq_query_shader_desc(sg_shader shd)
  254. sg_pipeline_desc sg_query_pipeline_desc(sg_pipeline pip)
  255. sg_attachments_desc sg_query_attachments_desc(sg_attachments atts)
  256. ...but NOTE that the returned desc structs may be incomplete, only
  257. creation attributes that are kept around internally after resource
  258. creation will be filled in, and in some cases (like shaders) that's
  259. very little. Any missing attributes will be set to zero. The returned
  260. desc structs might still be useful as partial blueprint for creating
  261. similar resources if filled up with the missing attributes.
  262. Calling the query-desc functions on an invalid resource will return
  263. completely zeroed structs (it makes sense to check the resource state
  264. with sg_query_*_state() first)
  265. --- you can query the default resource creation parameters through the functions
  266. sg_buffer_desc sg_query_buffer_defaults(const sg_buffer_desc* desc)
  267. sg_image_desc sg_query_image_defaults(const sg_image_desc* desc)
  268. sg_sampler_desc sg_query_sampler_defaults(const sg_sampler_desc* desc)
  269. sg_shader_desc sg_query_shader_defaults(const sg_shader_desc* desc)
  270. sg_pipeline_desc sg_query_pipeline_defaults(const sg_pipeline_desc* desc)
  271. sg_attachments_desc sg_query_attachments_defaults(const sg_attachments_desc* desc)
  272. These functions take a pointer to a desc structure which may contain
  273. zero-initialized items for default values. These zero-init values
  274. will be replaced with their concrete values in the returned desc
  275. struct.
  276. --- you can inspect various internal resource runtime values via:
  277. sg_buffer_info sg_query_buffer_info(sg_buffer buf)
  278. sg_image_info sg_query_image_info(sg_image img)
  279. sg_sampler_info sg_query_sampler_info(sg_sampler smp)
  280. sg_shader_info sg_query_shader_info(sg_shader shd)
  281. sg_pipeline_info sg_query_pipeline_info(sg_pipeline pip)
  282. sg_attachments_info sg_query_attachments_info(sg_attachments atts)
  283. ...please note that the returned info-structs are tied quite closely
  284. to sokol_gfx.h internals, and may change more often than other
  285. public API functions and structs.
  286. --- you can query frame stats and control stats collection via:
  287. sg_query_frame_stats()
  288. sg_enable_frame_stats()
  289. sg_disable_frame_stats()
  290. sg_frame_stats_enabled()
  291. --- you can ask at runtime what backend sokol_gfx.h has been compiled for:
  292. sg_backend sg_query_backend(void)
  293. --- call the following helper functions to compute the number of
  294. bytes in a texture row or surface for a specific pixel format.
  295. These functions might be helpful when preparing image data for consumption
  296. by sg_make_image() or sg_update_image():
  297. int sg_query_row_pitch(sg_pixel_format fmt, int width, int int row_align_bytes);
  298. int sg_query_surface_pitch(sg_pixel_format fmt, int width, int height, int row_align_bytes);
  299. Width and height are generally in number pixels, but note that 'row' has different meaning
  300. for uncompressed vs compressed pixel formats: for uncompressed formats, a row is identical
  301. with a single line if pixels, while in compressed formats, one row is a line of *compression blocks*.
  302. This is why calling sg_query_surface_pitch() for a compressed pixel format and height
  303. N, N+1, N+2, ... may return the same result.
  304. The row_align_bytes parameter is for added flexibility. For image data that goes into
  305. the sg_make_image() or sg_update_image() this should generally be 1, because these
  306. functions take tightly packed image data as input no matter what alignment restrictions
  307. exist in the backend 3D APIs.
  308. ON INITIALIZATION:
  309. ==================
  310. When calling sg_setup(), a pointer to an sg_desc struct must be provided
  311. which contains initialization options. These options provide two types
  312. of information to sokol-gfx:
  313. (1) upper bounds and limits needed to allocate various internal
  314. data structures:
  315. - the max number of resources of each type that can
  316. be alive at the same time, this is used for allocating
  317. internal pools
  318. - the max overall size of uniform data that can be
  319. updated per frame, including a worst-case alignment
  320. per uniform update (this worst-case alignment is 256 bytes)
  321. - the max size of all dynamic resource updates (sg_update_buffer,
  322. sg_append_buffer and sg_update_image) per frame
  323. - the max number of compute-dispatch calls in a compute pass
  324. Not all of those limit values are used by all backends, but it is
  325. good practice to provide them none-the-less.
  326. (2) 3D backend "environment information" in a nested sg_environment struct:
  327. - pointers to backend-specific context- or device-objects (for instance
  328. the D3D11, WebGPU or Metal device objects)
  329. - defaults for external swapchain pixel formats and sample counts,
  330. these will be used as default values in image and pipeline objects,
  331. and the sg_swapchain struct passed into sg_begin_pass()
  332. Usually you provide a complete sg_environment struct through
  333. a helper function, as an example look at the sglue_environment()
  334. function in the sokol_glue.h header.
  335. See the documentation block of the sg_desc struct below for more information.
  336. ON RENDER PASSES
  337. ================
  338. Relevant samples:
  339. - https://floooh.github.io/sokol-html5/offscreen-sapp.html
  340. - https://floooh.github.io/sokol-html5/offscreen-msaa-sapp.html
  341. - https://floooh.github.io/sokol-html5/mrt-sapp.html
  342. - https://floooh.github.io/sokol-html5/mrt-pixelformats-sapp.html
  343. A render pass groups rendering commands into a set of render target images
  344. (called 'pass attachments'). Render target images can be used in subsequent
  345. passes as textures (it is invalid to use the same image both as render target
  346. and as texture in the same pass).
  347. The following sokol-gfx functions must only be called inside a render-pass:
  348. sg_apply_viewport[f]
  349. sg_apply_scissor_rect[f]
  350. sg_draw
  351. The following function may be called inside a render- or compute-pass, but
  352. not outside a pass:
  353. sg_apply_pipeline
  354. sg_apply_bindings
  355. sg_apply_uniforms
  356. A frame must have at least one 'swapchain render pass' which renders into an
  357. externally provided swapchain provided as an sg_swapchain struct to the
  358. sg_begin_pass() function. If you use sokol_gfx.h together with sokol_app.h,
  359. just call the sglue_swapchain() helper function in sokol_glue.h to
  360. provide the swapchain information. Otherwise the following information
  361. must be provided:
  362. - the color pixel-format of the swapchain's render surface
  363. - an optional depth/stencil pixel format if the swapchain
  364. has a depth/stencil buffer
  365. - an optional sample-count for MSAA rendering
  366. - NOTE: the above three values can be zero-initialized, in that
  367. case the defaults from the sg_environment struct will be used that
  368. had been passed to the sg_setup() function.
  369. - a number of backend specific objects:
  370. - GL/GLES3: just a GL framebuffer handle
  371. - D3D11:
  372. - an ID3D11RenderTargetView for the rendering surface
  373. - if MSAA is used, an ID3D11RenderTargetView as
  374. MSAA resolve-target
  375. - an optional ID3D11DepthStencilView for the
  376. depth/stencil buffer
  377. - WebGPU
  378. - a WGPUTextureView object for the rendering surface
  379. - if MSAA is used, a WGPUTextureView object as MSAA resolve target
  380. - an optional WGPUTextureView for the
  381. - Metal (NOTE that the roles of provided surfaces is slightly
  382. different in Metal than in D3D11 or WebGPU, notably, the
  383. CAMetalDrawable is either rendered to directly, or serves
  384. as MSAA resolve target):
  385. - a CAMetalDrawable object which is either rendered
  386. into directly, or in case of MSAA rendering, serves
  387. as MSAA-resolve-target
  388. - if MSAA is used, an multisampled MTLTexture where
  389. rendering goes into
  390. - an optional MTLTexture for the depth/stencil buffer
  391. It's recommended that you create a helper function which returns an
  392. initialized sg_swapchain struct by value. This can then be directly plugged
  393. into the sg_begin_pass function like this:
  394. sg_begin_pass(&(sg_pass){ .swapchain = sglue_swapchain() });
  395. As an example for such a helper function check out the function sglue_swapchain()
  396. in the sokol_glue.h header.
  397. For offscreen render passes, the render target images used in a render pass
  398. are baked into an immutable sg_attachments object.
  399. For a simple offscreen scenario with one color-, one depth-stencil-render
  400. target and without multisampling, creating an attachment object looks like this:
  401. First create two render target images, one with a color pixel format,
  402. and one with the depth- or depth-stencil pixel format. Both images
  403. must have the same dimensions:
  404. const sg_image color_img = sg_make_image(&(sg_image_desc){
  405. .render_target = true,
  406. .width = 256,
  407. .height = 256,
  408. .pixel_format = SG_PIXELFORMAT_RGBA8,
  409. .sample_count = 1,
  410. });
  411. const sg_image depth_img = sg_make_image(&(sg_image_desc){
  412. .render_target = true,
  413. .width = 256,
  414. .height = 256,
  415. .pixel_format = SG_PIXELFORMAT_DEPTH,
  416. .sample_count = 1,
  417. });
  418. NOTE: when creating render target images, have in mind that some default values
  419. are aligned with the default environment attributes in the sg_environment struct
  420. that was passed into the sg_setup() call:
  421. - the default value for sg_image_desc.pixel_format is taken from
  422. sg_environment.defaults.color_format
  423. - the default value for sg_image_desc.sample_count is taken from
  424. sg_environment.defaults.sample_count
  425. - the default value for sg_image_desc.num_mipmaps is always 1
  426. Next create an attachments object:
  427. const sg_attachments atts = sg_make_attachments(&(sg_attachments_desc){
  428. .colors[0].image = color_img,
  429. .depth_stencil.image = depth_img,
  430. });
  431. This attachments object is then passed into the sg_begin_pass() function
  432. in place of the swapchain struct:
  433. sg_begin_pass(&(sg_pass){ .attachments = atts });
  434. Swapchain and offscreen passes form dependency trees each with a swapchain
  435. pass at the root, offscreen passes as nodes, and render target images as
  436. dependencies between passes.
  437. sg_pass_action structs are used to define actions that should happen at the
  438. start and end of rendering passes (such as clearing pass attachments to a
  439. specific color or depth-value, or performing an MSAA resolve operation at
  440. the end of a pass).
  441. A typical sg_pass_action object which clears the color attachment to black
  442. might look like this:
  443. const sg_pass_action = {
  444. .colors[0] = {
  445. .load_action = SG_LOADACTION_CLEAR,
  446. .clear_value = { 0.0f, 0.0f, 0.0f, 1.0f }
  447. }
  448. };
  449. This omits the defaults for the color attachment store action, and
  450. the depth-stencil-attachments actions. The same pass action with the
  451. defaults explicitly filled in would look like this:
  452. const sg_pass_action pass_action = {
  453. .colors[0] = {
  454. .load_action = SG_LOADACTION_CLEAR,
  455. .store_action = SG_STOREACTION_STORE,
  456. .clear_value = { 0.0f, 0.0f, 0.0f, 1.0f }
  457. },
  458. .depth = = {
  459. .load_action = SG_LOADACTION_CLEAR,
  460. .store_action = SG_STOREACTION_DONTCARE,
  461. .clear_value = 1.0f,
  462. },
  463. .stencil = {
  464. .load_action = SG_LOADACTION_CLEAR,
  465. .store_action = SG_STOREACTION_DONTCARE,
  466. .clear_value = 0
  467. }
  468. };
  469. With the sg_pass object and sg_pass_action struct in place everything
  470. is ready now for the actual render pass:
  471. Using such this prepared sg_pass_action in a swapchain pass looks like
  472. this:
  473. sg_begin_pass(&(sg_pass){
  474. .action = pass_action,
  475. .swapchain = sglue_swapchain()
  476. });
  477. ...
  478. sg_end_pass();
  479. ...of alternatively in one offscreen pass:
  480. sg_begin_pass(&(sg_pass){
  481. .action = pass_action,
  482. .attachments = attachments,
  483. });
  484. ...
  485. sg_end_pass();
  486. Offscreen rendering can also go into a mipmap, or a slice/face of
  487. a cube-, array- or 3d-image (which some restrictions, for instance
  488. it's not possible to create a 3D image with a depth/stencil pixel format,
  489. these exceptions are generally caught by the sokol-gfx validation layer).
  490. The mipmap/slice selection happens at attachments creation time, for instance
  491. to render into mipmap 2 of slice 3 of an array texture:
  492. const sg_attachments atts = sg_make_attachments(&(sg_attachments_desc){
  493. .colors[0] = {
  494. .image = color_img,
  495. .mip_level = 2,
  496. .slice = 3,
  497. },
  498. .depth_stencil.image = depth_img,
  499. });
  500. If MSAA offscreen rendering is desired, the multi-sample rendering result
  501. must be 'resolved' into a separate 'resolve image', before that image can
  502. be used as texture.
  503. Creating a simple attachments object for multisampled rendering requires
  504. 3 attachment images: the color attachment image which has a sample
  505. count > 1, a resolve attachment image of the same size and pixel format
  506. but a sample count == 1, and a depth/stencil attachment image with
  507. the same size and sample count as the color attachment image:
  508. const sg_image color_img = sg_make_image(&(sg_image_desc){
  509. .render_target = true,
  510. .width = 256,
  511. .height = 256,
  512. .pixel_format = SG_PIXELFORMAT_RGBA8,
  513. .sample_count = 4,
  514. });
  515. const sg_image resolve_img = sg_make_image(&(sg_image_desc){
  516. .render_target = true,
  517. .width = 256,
  518. .height = 256,
  519. .pixel_format = SG_PIXELFORMAT_RGBA8,
  520. .sample_count = 1,
  521. });
  522. const sg_image depth_img = sg_make_image(&(sg_image_desc){
  523. .render_target = true,
  524. .width = 256,
  525. .height = 256,
  526. .pixel_format = SG_PIXELFORMAT_DEPTH,
  527. .sample_count = 4,
  528. });
  529. ...create the attachments object:
  530. const sg_attachments atts = sg_make_attachments(&(sg_attachments_desc){
  531. .colors[0].image = color_img,
  532. .resolves[0].image = resolve_img,
  533. .depth_stencil.image = depth_img,
  534. });
  535. If an attachments object defines a resolve image in a specific resolve attachment slot,
  536. an 'msaa resolve operation' will happen in sg_end_pass().
  537. In this scenario, the content of the MSAA color attachment doesn't need to be
  538. preserved (since it's only needed inside sg_end_pass for the msaa-resolve), so
  539. the .store_action should be set to "don't care":
  540. const sg_pass_action = {
  541. .colors[0] = {
  542. .load_action = SG_LOADACTION_CLEAR,
  543. .store_action = SG_STOREACTION_DONTCARE,
  544. .clear_value = { 0.0f, 0.0f, 0.0f, 1.0f }
  545. }
  546. };
  547. The actual render pass looks as usual:
  548. sg_begin_pass(&(sg_pass){ .action = pass_action, .attachments = atts });
  549. ...
  550. sg_end_pass();
  551. ...after sg_end_pass() the only difference to the non-msaa scenario is that the
  552. rendering result which is going to be used as texture in a followup pass is
  553. in 'resolve_img', not in 'color_img' (in fact, trying to bind color_img as a
  554. texture would result in a validation error).
  555. ON COMPUTE PASSES
  556. =================
  557. Compute passes are used to update the content of storage buffers and
  558. storage images by running compute shader code on
  559. the GPU. Updating storage resources with a compute shader will almost always
  560. be more efficient than computing the same data on the CPU and then uploading
  561. it via `sg_update_buffer()` or `sg_update_image()`.
  562. NOTE: compute passes are only supported on the following platforms and
  563. backends:
  564. - macOS and iOS with Metal
  565. - Windows with D3D11 and OpenGL
  566. - Linux with OpenGL or GLES3.1+
  567. - Web with WebGPU
  568. - Android with GLES3.1+
  569. ...this means compute shaders can't be used on the following platform/backend
  570. combos (the same restrictions apply to using storage buffers without compute
  571. shaders):
  572. - macOS with GL
  573. - iOS with GLES3
  574. - Web with WebGL2
  575. A compute pass which only updates storage buffers is started with:
  576. sg_begin_pass(&(sg_pass){ .compute = true });
  577. ...if the compute pass updates storage images, the images must be 'bound'
  578. via an sg_attachments object:
  579. sg_begin_pass(&(sg_pass){ .compute = true, .attachments = attachments });
  580. Image objects in such a compute pass attachments object must be created with
  581. `storage_attachment` usage:
  582. sg_image storage_image = sg_make_image(&(sg_image_desc){
  583. .usage = {
  584. .storage_attachment = true,
  585. },
  586. // ...
  587. });
  588. ...a compute pass is finished with a regular:
  589. sg_end_pass();
  590. Typically the following functions will be called inside a compute pass:
  591. sg_apply_pipeline()
  592. sg_apply_bindings()
  593. sg_apply_uniforms()
  594. sg_dispatch()
  595. The following functions are disallowed inside a compute pass
  596. and will cause validation layer errors:
  597. sg_apply_viewport[f]()
  598. sg_apply_scissor_rect[f]()
  599. sg_draw()
  600. Only special 'compute shaders' and 'compute pipelines' can be used in
  601. compute passes. A compute shader only has a compute-function instead
  602. of a vertex- and fragment-function pair, and it doesn't accept vertex-
  603. and index-buffers as input, only storage-buffers, textures, non-filtering
  604. samplers and images via storage attachments (more details on compute shaders in
  605. the following section).
  606. A compute pipeline is created by providing a compute shader object,
  607. setting the .compute creation parameter to true and not defining any
  608. 'render state':
  609. sg_pipeline pip = sg_make_pipeline(&(sg_pipeline_desc){
  610. .compute = true,
  611. .shader = compute_shader,
  612. });
  613. The sg_apply_bindings and sg_apply_uniforms calls are the same as in
  614. render passes, with the exception that no vertex- and index-buffers
  615. can be bound in the sg_apply_bindings call.
  616. Finally to kick off a compute workload, call sg_dispatch with the
  617. number of workgroups in the x, y and z-dimension:
  618. sg_dispatch(int num_groups_x, int num_groups_y, int num_groups_z)
  619. Also see the following compute-shader samples:
  620. - https://floooh.github.io/sokol-webgpu/instancing-compute-sapp.html
  621. - https://floooh.github.io/sokol-webgpu/computeboids-sapp.html
  622. - https://floooh.github.io/sokol-webgpu/imageblur-sapp.html
  623. ON SHADER CREATION
  624. ==================
  625. sokol-gfx doesn't come with an integrated shader cross-compiler, instead
  626. backend-specific shader sources or binary blobs need to be provided when
  627. creating a shader object, along with reflection information about the
  628. shader resource binding interface needed to bind sokol-gfx resources to the
  629. proper shader inputs.
  630. The easiest way to provide all this shader creation data is to use the
  631. sokol-shdc shader compiler tool to compile shaders from a common
  632. GLSL syntax into backend-specific sources or binary blobs, along with
  633. shader interface information and uniform blocks and storage buffer array items
  634. mapped to C structs.
  635. To create a shader using a C header which has been code-generated by sokol-shdc:
  636. // include the C header code-generated by sokol-shdc:
  637. #include "myshader.glsl.h"
  638. ...
  639. // create shader using a code-generated helper function from the C header:
  640. sg_shader shd = sg_make_shader(myshader_shader_desc(sg_query_backend()));
  641. The samples in the 'sapp' subdirectory of the sokol-samples project
  642. also use the sokol-shdc approach:
  643. https://github.com/floooh/sokol-samples/tree/master/sapp
  644. If you're planning to use sokol-shdc, you can stop reading here, instead
  645. continue with the sokol-shdc documentation:
  646. https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md
  647. To create shaders with backend-specific shader code or binary blobs,
  648. the sg_make_shader() function requires the following information:
  649. - Shader code or shader binary blobs for the vertex- and fragment-, or the
  650. compute-shader-stage:
  651. - for the desktop GL backend, source code can be provided in '#version 410' or
  652. '#version 430', version 430 is required when using storage buffers and
  653. compute shaders support, but note that this is not available on macOS
  654. - for the GLES3 backend, source code must be provided in '#version 300 es' or
  655. '#version 310 es' syntax (version 310 is required for storage buffer and
  656. compute shader support, but note that this is not supported on WebGL2)
  657. - for the D3D11 backend, shaders can be provided as source or binary
  658. blobs, the source code should be in HLSL4.0 (for compatibility with old
  659. low-end GPUs) or preferably in HLSL5.0 syntax, note that when
  660. shader source code is provided for the D3D11 backend, sokol-gfx will
  661. dynamically load 'd3dcompiler_47.dll'
  662. - for the Metal backends, shaders can be provided as source or binary blobs, the
  663. MSL version should be in 'metal-1.1' (other versions may work but are not tested)
  664. - for the WebGPU backend, shaders must be provided as WGSL source code
  665. - optionally the following shader-code related attributes can be provided:
  666. - an entry function name (only on D3D11 or Metal, but not OpenGL)
  667. - on D3D11 only, a compilation target (default is "vs_4_0" and "ps_4_0")
  668. - Information about the input vertex attributes used by the vertex shader,
  669. most of that backend-specific:
  670. - An optional 'base type' (float, signed-/unsigned-int) for each vertex
  671. attribute. When provided, this used by the validation layer to check
  672. that the CPU-side input vertex format is compatible with the input
  673. vertex declaration of the vertex shader.
  674. - Metal: no location information needed since vertex attributes are always bound
  675. by their attribute location defined in the shader via '[[attribute(N)]]'
  676. - WebGPU: no location information needed since vertex attributes are always
  677. bound by their attribute location defined in the shader via `@location(N)`
  678. - GLSL: vertex attribute names can be optionally provided, in that case their
  679. location will be looked up by name, otherwise, the vertex attribute location
  680. can be defined with 'layout(location = N)'
  681. - D3D11: a 'semantic name' and 'semantic index' must be provided for each vertex
  682. attribute, e.g. if the vertex attribute is defined as 'TEXCOORD1' in the shader,
  683. the semantic name would be 'TEXCOORD', and the semantic index would be '1'
  684. NOTE that vertex attributes currently must not have gaps. This requirement
  685. may be relaxed in the future.
  686. - Specifically for Metal compute shaders, the 'number of threads per threadgroup'
  687. must be provided. Normally this is extracted by sokol-shdc from the GLSL
  688. shader source code. For instance the following statement in the input
  689. GLSL:
  690. layout(local_size_x=64, local_size_y=1, local_size_z=1) in;
  691. ...will be communicated to the sokol-gfx Metal backend in the
  692. code-generated sg_shader_desc struct:
  693. (sg_shader_desc){
  694. .mtl_threads_per_threadgroup = { .x = 64, .y = 1, .z = 1 },
  695. }
  696. - Information about each uniform block binding used in the shader:
  697. - the shader stage of the uniform block (vertex, fragment or compute)
  698. - the size of the uniform block in number of bytes
  699. - a memory layout hint (currently 'native' or 'std140') where 'native' defines a
  700. backend-specific memory layout which shouldn't be used for cross-platform code.
  701. Only std140 guarantees a backend-agnostic memory layout.
  702. - a backend-specific bind slot:
  703. - D3D11/HLSL: the buffer register N (`register(bN)`) where N is 0..7
  704. - Metal/MSL: the buffer bind slot N (`[[buffer(N)]]`) where N is 0..7
  705. - WebGPU: the binding N in `@group(0) @binding(N)` where N is 0..15
  706. - For GLSL only: a description of the internal uniform block layout, which maps
  707. member types and their offsets on the CPU side to uniform variable names
  708. in the GLSL shader
  709. - please also NOTE the documentation sections about UNIFORM DATA LAYOUT
  710. and CROSS-BACKEND COMMON UNIFORM DATA LAYOUT below!
  711. - A description of each storage buffer binding used in the shader:
  712. - the shader stage of the storage buffer
  713. - a boolean 'readonly' flag, this is used for validation and hazard
  714. tracking in some 3D backends. Note that in render passes, only
  715. readonly storage buffer bindings are allowed. In compute passes, any
  716. read/write storage buffer binding is assumed to be written to by the
  717. compute shader.
  718. - a backend-specific bind slot:
  719. - D3D11/HLSL:
  720. - for readonly storage buffer bindings: the texture register N
  721. (`register(tN)`) where N is 0..23 (in HLSL, readonly storage
  722. buffers and textures share the same bind space for
  723. 'shader resource views')
  724. - for read/write storage buffer buffer bindings: the UAV register N
  725. (`register(uN)`) where N is 0..11 (in HLSL, readwrite storage
  726. buffers use their own bind space for 'unordered access views')
  727. - Metal/MSL: the buffer bind slot N (`[[buffer(N)]]`) where N is 8..15
  728. - WebGPU/WGSL: the binding N in `@group(0) @binding(N)` where N is 0..127
  729. - GL/GLSL: the buffer binding N in `layout(binding=N)` where N is 0..7
  730. - note that storage buffer bindings are not supported on all backends
  731. and platforms
  732. - A description of each storage image binding used in the shader (only supported
  733. in compute shaders):
  734. - the shader stage (*must* be compute)
  735. - the expected image type:
  736. - SG_IMAGETYPE_2D
  737. - SG_IMAGETYPE_CUBE
  738. - SG_IMAGETYPE_3D
  739. - SG_IMAGETYPE_ARRAY
  740. - the 'access pixel format', this is currently limited to:
  741. - SG_PIXELFORMAT_RGBA8
  742. - SG_PIXELFORMAT_RGBA8SN/UI/SI
  743. - SG_PIXELFORMAT_RGBA16UI/SI/F
  744. - SG_PIXELFORMAT_R32UIUI/SI/F
  745. - SG_PIXELFORMAT_RG32UI/SI/F
  746. - SG_PIXELFORMAT_RGBA32UI/SI/F
  747. - the access type (readwrite or writeonly)
  748. - a backend-specific bind slot:
  749. - D3D11/HLSL: the UAV register N (`register(uN)` where N is 0..11, the
  750. bind slot must not collide with UAV storage buffer bindings
  751. - Metal/MSL: the texture bind slot N (`[[texture(N)]])` where N is 0..19,
  752. the bind slot must not collide with other texture bindings on the same
  753. stage
  754. - WebGPU/WGSL: the binding N in `@group(2) @binding(N)` where N is 0..3
  755. - GL/GLSL: the buffer binding N in `layout(binding=N)` where N is 0..3
  756. - note that storage image bindings are not supported on all backends and platforms
  757. - A description of each texture binding used in the shader:
  758. - the shader stage of the texture (vertex, fragment or compute)
  759. - the expected image type:
  760. - SG_IMAGETYPE_2D
  761. - SG_IMAGETYPE_CUBE
  762. - SG_IMAGETYPE_3D
  763. - SG_IMAGETYPE_ARRAY
  764. - the expected 'image sample type':
  765. - SG_IMAGESAMPLETYPE_FLOAT
  766. - SG_IMAGESAMPLETYPE_DEPTH
  767. - SG_IMAGESAMPLETYPE_SINT
  768. - SG_IMAGESAMPLETYPE_UINT
  769. - SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT
  770. - a flag whether the texture is expected to be multisampled
  771. - a backend-specific bind slot:
  772. - D3D11/HLSL: the texture register N (`register(tN)`) where N is 0..23
  773. (in HLSL, readonly storage buffers and texture share the same bind space)
  774. - Metal/MSL: the texture bind slot N (`[[texture(N)]]`) where N is 0..19
  775. (the bind slot must not collide with storage image bindings on the same stage)
  776. - WebGPU/WGSL: the binding N in `@group(0) @binding(N)` where N is 0..127
  777. - A description of each sampler used in the shader:
  778. - the shader stage of the sampler (vertex, fragment or compute)
  779. - the expected sampler type:
  780. - SG_SAMPLERTYPE_FILTERING,
  781. - SG_SAMPLERTYPE_NONFILTERING,
  782. - SG_SAMPLERTYPE_COMPARISON,
  783. - a backend-specific bind slot:
  784. - D3D11/HLSL: the sampler register N (`register(sN)`) where N is 0..15
  785. - Metal/MSL: the sampler bind slot N (`[[sampler(N)]]`) where N is 0..15
  786. - WebGPU/WGSL: the binding N in `@group(0) @binding(N)` where N is 0..127
  787. - An array of 'image-sampler-pairs' used by the shader to sample textures,
  788. for D3D11, Metal and WebGPU this is used for validation purposes to check
  789. whether the texture and sampler are compatible with each other (especially
  790. WebGPU is very picky about combining the correct
  791. texture-sample-type with the correct sampler-type). For GLSL an
  792. additional 'combined-image-sampler name' must be provided because 'OpenGL
  793. style GLSL' cannot handle separate texture and sampler objects, but still
  794. groups them into a traditional GLSL 'sampler object'.
  795. Compatibility rules for image-sample-type vs sampler-type are as follows:
  796. - SG_IMAGESAMPLETYPE_FLOAT => (SG_SAMPLERTYPE_FILTERING or SG_SAMPLERTYPE_NONFILTERING)
  797. - SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT => SG_SAMPLERTYPE_NONFILTERING
  798. - SG_IMAGESAMPLETYPE_SINT => SG_SAMPLERTYPE_NONFILTERING
  799. - SG_IMAGESAMPLETYPE_UINT => SG_SAMPLERTYPE_NONFILTERING
  800. - SG_IMAGESAMPLETYPE_DEPTH => SG_SAMPLERTYPE_COMPARISON
  801. Backend-specific bindslot ranges (not relevant when using sokol-shdc):
  802. - D3D11/HLSL:
  803. - separate bindslot space per shader stage
  804. - uniform block bindings (as cbuffer): `register(b0..b7)`
  805. - texture- and readonly storage buffer bindings: `register(t0..t23)`
  806. - read/write storage buffer and storage image bindings: `register(u0..u11)`
  807. - samplers: `register(s0..s15)`
  808. - Metal/MSL:
  809. - separate bindslot space per shader stage
  810. - uniform blocks: `[[buffer(0..7)]]`
  811. - storage buffers: `[[buffer(8..15)]]`
  812. - textures and storage image bindings: `[[texture(0..19)]]`
  813. - samplers: `[[sampler(0..15)]]`
  814. - WebGPU/WGSL:
  815. - common bindslot space across shader stages
  816. - uniform blocks: `@group(0) @binding(0..15)`
  817. - textures, samplers and storage buffers: `@group(1) @binding(0..127)`
  818. - storage image bindings: `@group(2) @binding(0..3)`
  819. - GL/GLSL:
  820. - uniforms and image-samplers are bound by name
  821. - storage buffer bindings: `layout(std430, binding=0..7)` (common
  822. bindslot space across shader stages)
  823. - storage image bindings: `layout(binding=0..3, [access_format])`
  824. For example code of how to create backend-specific shader objects,
  825. please refer to the following samples:
  826. - for D3D11: https://github.com/floooh/sokol-samples/tree/master/d3d11
  827. - for Metal: https://github.com/floooh/sokol-samples/tree/master/metal
  828. - for OpenGL: https://github.com/floooh/sokol-samples/tree/master/glfw
  829. - for GLES3: https://github.com/floooh/sokol-samples/tree/master/html5
  830. - for WebGPU: https://github.com/floooh/sokol-samples/tree/master/wgpu
  831. ON SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT AND SG_SAMPLERTYPE_NONFILTERING
  832. ========================================================================
  833. The WebGPU backend introduces the concept of 'unfilterable-float' textures,
  834. which can only be combined with 'nonfiltering' samplers (this is a restriction
  835. specific to WebGPU, but since the same sokol-gfx code should work across
  836. all backend, the sokol-gfx validation layer also enforces this restriction
  837. - the alternative would be undefined behaviour in some backend APIs on
  838. some devices).
  839. The background is that some mobile devices (most notably iOS devices) can
  840. not perform linear filtering when sampling textures with certain pixel
  841. formats, most notable the 32F formats:
  842. - SG_PIXELFORMAT_R32F
  843. - SG_PIXELFORMAT_RG32F
  844. - SG_PIXELFORMAT_RGBA32F
  845. The information of whether a shader is going to be used with such an
  846. unfilterable-float texture must already be provided in the sg_shader_desc
  847. struct when creating the shader (see the above section "ON SHADER CREATION").
  848. If you are using the sokol-shdc shader compiler, the information whether a
  849. texture/sampler binding expects an 'unfilterable-float/nonfiltering'
  850. texture/sampler combination cannot be inferred from the shader source
  851. alone, you'll need to provide this hint via annotation-tags. For instance
  852. here is an example from the ozz-skin-sapp.c sample shader which samples an
  853. RGBA32F texture with skinning matrices in the vertex shader:
  854. ```glsl
  855. @image_sample_type joint_tex unfilterable_float
  856. uniform texture2D joint_tex;
  857. @sampler_type smp nonfiltering
  858. uniform sampler smp;
  859. ```
  860. This will result in SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT and
  861. SG_SAMPLERTYPE_NONFILTERING being written to the code-generated
  862. sg_shader_desc struct.
  863. ON VERTEX FORMATS
  864. =================
  865. Sokol-gfx implements the same strict mapping rules from CPU-side
  866. vertex component formats to GPU-side vertex input data types:
  867. - float and packed normalized CPU-side formats must be used as
  868. floating point base type in the vertex shader
  869. - packed signed-integer CPU-side formats must be used as signed
  870. integer base type in the vertex shader
  871. - packed unsigned-integer CPU-side formats must be used as unsigned
  872. integer base type in the vertex shader
  873. These mapping rules are enforced by the sokol-gfx validation layer,
  874. but only when sufficient reflection information is provided in
  875. `sg_shader_desc.attrs[].base_type`. This is the case when sokol-shdc
  876. is used, otherwise the default base_type will be SG_SHADERATTRBASETYPE_UNDEFINED
  877. which causes the sokol-gfx validation check to be skipped (of course you
  878. can also provide the per-attribute base type information manually when
  879. not using sokol-shdc).
  880. The detailed mapping rules from SG_VERTEXFORMAT_* to GLSL data types
  881. are as follows:
  882. - FLOAT[*] => float, vec*
  883. - BYTE4N => vec* (scaled to -1.0 .. +1.0)
  884. - UBYTE4N => vec* (scaled to 0.0 .. +1.0)
  885. - SHORT[*]N => vec* (scaled to -1.0 .. +1.0)
  886. - USHORT[*]N => vec* (scaled to 0.0 .. +1.0)
  887. - INT[*] => int, ivec*
  888. - UINT[*] => uint, uvec*
  889. - BYTE4 => int*
  890. - UBYTE4 => uint*
  891. - SHORT[*] => int*
  892. - USHORT[*] => uint*
  893. NOTE that sokol-gfx only provides vertex formats with sizes of a multiple
  894. of 4 (e.g. BYTE4N but not BYTE2N). This is because vertex components must
  895. be 4-byte aligned anyway.
  896. UNIFORM DATA LAYOUT:
  897. ====================
  898. NOTE: if you use the sokol-shdc shader compiler tool, you don't need to worry
  899. about the following details.
  900. The data that's passed into the sg_apply_uniforms() function must adhere to
  901. specific layout rules so that the GPU shader finds the uniform block
  902. items at the right offset.
  903. For the D3D11 and Metal backends, sokol-gfx only cares about the size of uniform
  904. blocks, but not about the internal layout. The data will just be copied into
  905. a uniform/constant buffer in a single operation and it's up you to arrange the
  906. CPU-side layout so that it matches the GPU side layout. This also means that with
  907. the D3D11 and Metal backends you are not limited to a 'cross-platform' subset
  908. of uniform variable types.
  909. If you ever only use one of the D3D11, Metal *or* WebGPU backend, you can stop reading here.
  910. For the GL backends, the internal layout of uniform blocks matters though,
  911. and you are limited to a small number of uniform variable types. This is
  912. because sokol-gfx must be able to locate the uniform block members in order
  913. to upload them to the GPU with glUniformXXX() calls.
  914. To describe the uniform block layout to sokol-gfx, the following information
  915. must be passed to the sg_make_shader() call in the sg_shader_desc struct:
  916. - a hint about the used packing rule (either SG_UNIFORMLAYOUT_NATIVE or
  917. SG_UNIFORMLAYOUT_STD140)
  918. - a list of the uniform block members types in the correct order they
  919. appear on the CPU side
  920. For example if the GLSL shader has the following uniform declarations:
  921. uniform mat4 mvp;
  922. uniform vec2 offset0;
  923. uniform vec2 offset1;
  924. uniform vec2 offset2;
  925. ...and on the CPU side, there's a similar C struct:
  926. typedef struct {
  927. float mvp[16];
  928. float offset0[2];
  929. float offset1[2];
  930. float offset2[2];
  931. } params_t;
  932. ...the uniform block description in the sg_shader_desc must look like this:
  933. sg_shader_desc desc = {
  934. .vs.uniform_blocks[0] = {
  935. .size = sizeof(params_t),
  936. .layout = SG_UNIFORMLAYOUT_NATIVE, // this is the default and can be omitted
  937. .uniforms = {
  938. // order must be the same as in 'params_t':
  939. [0] = { .name = "mvp", .type = SG_UNIFORMTYPE_MAT4 },
  940. [1] = { .name = "offset0", .type = SG_UNIFORMTYPE_VEC2 },
  941. [2] = { .name = "offset1", .type = SG_UNIFORMTYPE_VEC2 },
  942. [3] = { .name = "offset2", .type = SG_UNIFORMTYPE_VEC2 },
  943. }
  944. }
  945. };
  946. With this information sokol-gfx can now compute the correct offsets of the data items
  947. within the uniform block struct.
  948. The SG_UNIFORMLAYOUT_NATIVE packing rule works fine if only the GL backends are used,
  949. but for proper D3D11/Metal/GL a subset of the std140 layout must be used which is
  950. described in the next section:
  951. CROSS-BACKEND COMMON UNIFORM DATA LAYOUT
  952. ========================================
  953. For cross-platform / cross-3D-backend code it is important that the same uniform block
  954. layout on the CPU side can be used for all sokol-gfx backends. To achieve this,
  955. a common subset of the std140 layout must be used:
  956. - The uniform block layout hint in sg_shader_desc must be explicitly set to
  957. SG_UNIFORMLAYOUT_STD140.
  958. - Only the following GLSL uniform types can be used (with their associated sokol-gfx enums):
  959. - float => SG_UNIFORMTYPE_FLOAT
  960. - vec2 => SG_UNIFORMTYPE_FLOAT2
  961. - vec3 => SG_UNIFORMTYPE_FLOAT3
  962. - vec4 => SG_UNIFORMTYPE_FLOAT4
  963. - int => SG_UNIFORMTYPE_INT
  964. - ivec2 => SG_UNIFORMTYPE_INT2
  965. - ivec3 => SG_UNIFORMTYPE_INT3
  966. - ivec4 => SG_UNIFORMTYPE_INT4
  967. - mat4 => SG_UNIFORMTYPE_MAT4
  968. - Alignment for those types must be as follows (in bytes):
  969. - float => 4
  970. - vec2 => 8
  971. - vec3 => 16
  972. - vec4 => 16
  973. - int => 4
  974. - ivec2 => 8
  975. - ivec3 => 16
  976. - ivec4 => 16
  977. - mat4 => 16
  978. - Arrays are only allowed for the following types: vec4, int4, mat4.
  979. Note that the HLSL cbuffer layout rules are slightly different from the
  980. std140 layout rules, this means that the cbuffer declarations in HLSL code
  981. must be tweaked so that the layout is compatible with std140.
  982. The by far easiest way to tackle the common uniform block layout problem is
  983. to use the sokol-shdc shader cross-compiler tool!
  984. ON STORAGE BUFFERS
  985. ==================
  986. The two main purpose of storage buffers are:
  987. - to be populated by compute shaders with dynamically generated data
  988. - for providing random-access data to all shader stages
  989. Storage buffers can be used to pass large amounts of random access structured
  990. data from the CPU side to the shaders. They are similar to data textures, but are
  991. more convenient to use both on the CPU and shader side since they can be accessed
  992. in shaders as as a 1-dimensional array of struct items.
  993. Storage buffers are *NOT* supported on the following platform/backend combos:
  994. - macOS+GL (because storage buffers require GL 4.3, while macOS only goes up to GL 4.1)
  995. - platforms which only support a GLES3.0 context (WebGL2 and iOS)
  996. To use storage buffers, the following steps are required:
  997. - write a shader which uses storage buffers (vertex- and fragment-shaders
  998. can only read from storage buffers, while compute-shaders can both read
  999. and write storage buffers)
  1000. - create one or more storage buffers via sg_make_buffer() with the
  1001. `.usage.storage_buffer = true`
  1002. - when creating a shader via sg_make_shader(), populate the sg_shader_desc
  1003. struct with binding info (when using sokol-shdc, this step will be taken care
  1004. of automatically)
  1005. - which storage buffer bind slots on the vertex-, fragment- or compute-stage
  1006. are occupied
  1007. - whether the storage buffer on that bind slot is readonly (readonly
  1008. bindings are required for vertex- and fragment-shaders, and in compute
  1009. shaders the readonly flag is used to control hazard tracking in some
  1010. 3D backends)
  1011. - when calling sg_apply_bindings(), apply the matching bind slots with the previously
  1012. created storage buffers
  1013. - ...and that's it.
  1014. For more details, see the following backend-agnostic sokol samples:
  1015. - simple vertex pulling from a storage buffer:
  1016. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/vertexpull-sapp.c
  1017. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/vertexpull-sapp.glsl
  1018. - instanced rendering via storage buffers (vertex- and instance-pulling):
  1019. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/instancing-pull-sapp.c
  1020. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/instancing-pull-sapp.glsl
  1021. - storage buffers both on the vertex- and fragment-stage:
  1022. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/sbuftex-sapp.c
  1023. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/sbuftex-sapp.glsl
  1024. - the Ozz animation sample rewritten to pull all rendering data from storage buffers:
  1025. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/ozz-storagebuffer-sapp.cc
  1026. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/ozz-storagebuffer-sapp.glsl
  1027. - the instancing sample modified to use compute shaders:
  1028. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/instancing-compute-sapp.c
  1029. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/instancing-compute-sapp.glsl
  1030. - the Compute Boids sample ported to sokol-gfx:
  1031. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/computeboids-sapp.c
  1032. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/computeboids-sapp.glsl
  1033. ...also see the following backend-specific vertex pulling samples (those also don't use sokol-shdc):
  1034. - D3D11: https://github.com/floooh/sokol-samples/blob/master/d3d11/vertexpulling-d3d11.c
  1035. - desktop GL: https://github.com/floooh/sokol-samples/blob/master/glfw/vertexpulling-glfw.c
  1036. - Metal: https://github.com/floooh/sokol-samples/blob/master/metal/vertexpulling-metal.c
  1037. - WebGPU: https://github.com/floooh/sokol-samples/blob/master/wgpu/vertexpulling-wgpu.c
  1038. ...and the backend specific compute shader samples:
  1039. - D3D11: https://github.com/floooh/sokol-samples/blob/master/d3d11/instancing-compute-d3d11.c
  1040. - desktop GL: https://github.com/floooh/sokol-samples/blob/master/glfw/instancing-compute-glfw.c
  1041. - Metal: https://github.com/floooh/sokol-samples/blob/master/metal/instancing-compute-metal.c
  1042. - WebGPU: https://github.com/floooh/sokol-samples/blob/master/wgpu/instancing-compute-wgpu.c
  1043. Storage buffer shader authoring caveats when using sokol-shdc:
  1044. - declare a read-only storage buffer interface block with `layout(binding=N) readonly buffer [name] { ... }`
  1045. (where 'N' is the index in `sg_bindings.storage_buffers[N]`)
  1046. - ...or a read/write storage buffer interface block with `layout(binding=N) buffer [name] { ... }`
  1047. - declare a struct which describes a single array item in the storage buffer interface block
  1048. - only put a single flexible array member into the storage buffer interface block
  1049. E.g. a complete example in 'sokol-shdc GLSL':
  1050. ```glsl
  1051. @vs
  1052. // declare a struct:
  1053. struct sb_vertex {
  1054. vec3 pos;
  1055. vec4 color;
  1056. }
  1057. // declare a buffer interface block with a single flexible struct array:
  1058. layout(binding=0) readonly buffer vertices {
  1059. sb_vertex vtx[];
  1060. }
  1061. // in the shader function, access the storage buffer like this:
  1062. void main() {
  1063. vec3 pos = vtx[gl_VertexIndex].pos;
  1064. ...
  1065. }
  1066. @end
  1067. ```
  1068. In a compute shader you can read and write the same item in the same
  1069. storage buffer (but you'll have to be careful for random access since
  1070. many threads of the same compute function run in parallel):
  1071. @cs
  1072. struct sb_item {
  1073. vec3 pos;
  1074. vec3 vel;
  1075. }
  1076. layout(binding=0) buffer items_ssbo {
  1077. sb_item items[];
  1078. }
  1079. layout(local_size_x=64, local_size_y=1, local_size_z=1) in;
  1080. void main() {
  1081. uint idx = gl_GlobalInvocationID.x;
  1082. vec3 pos = items[idx].pos;
  1083. ...
  1084. items[idx].pos = pos;
  1085. }
  1086. @end
  1087. Backend-specific storage-buffer caveats (not relevant when using sokol-shdc):
  1088. D3D11:
  1089. - storage buffers are created as 'raw' Byte Address Buffers
  1090. (https://learn.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-resources-intro#raw-views-of-buffers)
  1091. - in HLSL, use a ByteAddressBuffer for readonly access of the buffer content:
  1092. (https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-byteaddressbuffer)
  1093. - ...or RWByteAddressBuffer for read/write access:
  1094. (https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-rwbyteaddressbuffer)
  1095. - readonly-storage buffers and textures are both bound as 'shader-resource-view' and
  1096. share the same bind slots (declared as `register(tN)` in HLSL), where N must be in the range 0..23)
  1097. - read/write storage buffers and storage images are bound as 'unordered-access-view'
  1098. (declared as `register(uN)` in HLSL where N is in the range 0..11)
  1099. Metal:
  1100. - in Metal there is no internal difference between vertex-, uniform- and
  1101. storage-buffers, all are bound to the same 'buffer bind slots' with the
  1102. following reserved ranges:
  1103. - vertex shader stage:
  1104. - uniform buffers: slots 0..7
  1105. - storage buffers: slots 8..15
  1106. - vertex buffers: slots 15..23
  1107. - fragment shader stage:
  1108. - uniform buffers: slots 0..7
  1109. - storage buffers: slots 8..15
  1110. - this means in MSL, storage buffer bindings start at [[buffer(8)]] both in
  1111. the vertex and fragment stage
  1112. GL:
  1113. - the GL backend doesn't use name-lookup to find storage buffer bindings, this
  1114. means you must annotate buffers with `layout(std430, binding=N)` in GLSL
  1115. - ...where N is 0..7 in the vertex shader, and 8..15 in the fragment shader
  1116. WebGPU:
  1117. - in WGSL, textures, samplers and storage buffers all use a shared
  1118. bindspace across all shader stages on bindgroup 1:
  1119. `@group(1) @binding(0..127)
  1120. ON STORAGE IMAGES:
  1121. ==================
  1122. To write pixel data to texture objects in compute shaders, first an image
  1123. object must be created with `storage_attachment usage`:
  1124. sg_image storage_image = sg_make_image(&(sg_image_desc){
  1125. .usage = {
  1126. .storage_attachment = true,
  1127. },
  1128. .width = ...,
  1129. .height = ...,
  1130. .pixel_format = ...,
  1131. });
  1132. ...next the image object must be wrapped in an attachment object, this allows
  1133. to pick a specific mipmap level or slice to be accessed by the compute shader:
  1134. sg_attachments storage_attachment = sg_make_attachment(&(sg_attachments_desc){
  1135. .storages[0] = {
  1136. .image = storage_image,
  1137. .mip_level = ...,
  1138. .slice = ...,
  1139. },
  1140. });
  1141. Finally 'bind' the storage image as pass attachment in the `sg_begin_pass`
  1142. call of a compute pass:
  1143. sg_begin_pass(&(sg_pass){ .compute = true, .attachments = storage_attachments });
  1144. ...
  1145. sg_end_pass();
  1146. Storage attachments should only be accessed as `readwrite` or `writeonly` mode
  1147. in compute shaders because if the limited bind space of up to 4 slots. For
  1148. readonly access, just bind the storage image as regular texture via
  1149. `sg_apply_bindings()`.
  1150. For an example of using storage images in compute shaders see imageblur-sapp:
  1151. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/imageblur-sapp.c
  1152. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/imageblur-sapp.glsl
  1153. NOTE: in the (hopefully not-too-distant) future, working with storage
  1154. images will change by moving the resource binding from pass attachments to
  1155. regular bindings via `sg_apply_bindings()`, but this requires the
  1156. introduction of resource view objects into sokol-gfx (see planning
  1157. ticket: https://github.com/floooh/sokol/issues/1252)
  1158. TRACE HOOKS:
  1159. ============
  1160. sokol_gfx.h optionally allows to install "trace hook" callbacks for
  1161. each public API functions. When a public API function is called, and
  1162. a trace hook callback has been installed for this function, the
  1163. callback will be invoked with the parameters and result of the function.
  1164. This is useful for things like debugging- and profiling-tools, or
  1165. keeping track of resource creation and destruction.
  1166. To use the trace hook feature:
  1167. --- Define SOKOL_TRACE_HOOKS before including the implementation.
  1168. --- Setup an sg_trace_hooks structure with your callback function
  1169. pointers (keep all function pointers you're not interested
  1170. in zero-initialized), optionally set the user_data member
  1171. in the sg_trace_hooks struct.
  1172. --- Install the trace hooks by calling sg_install_trace_hooks(),
  1173. the return value of this function is another sg_trace_hooks
  1174. struct which contains the previously set of trace hooks.
  1175. You should keep this struct around, and call those previous
  1176. functions pointers from your own trace callbacks for proper
  1177. chaining.
  1178. As an example of how trace hooks are used, have a look at the
  1179. imgui/sokol_gfx_imgui.h header which implements a realtime
  1180. debugging UI for sokol_gfx.h on top of Dear ImGui.
  1181. MEMORY ALLOCATION OVERRIDE
  1182. ==========================
  1183. You can override the memory allocation functions at initialization time
  1184. like this:
  1185. void* my_alloc(size_t size, void* user_data) {
  1186. return malloc(size);
  1187. }
  1188. void my_free(void* ptr, void* user_data) {
  1189. free(ptr);
  1190. }
  1191. ...
  1192. sg_setup(&(sg_desc){
  1193. // ...
  1194. .allocator = {
  1195. .alloc_fn = my_alloc,
  1196. .free_fn = my_free,
  1197. .user_data = ...,
  1198. }
  1199. });
  1200. ...
  1201. If no overrides are provided, malloc and free will be used.
  1202. This only affects memory allocation calls done by sokol_gfx.h
  1203. itself though, not any allocations in OS libraries.
  1204. ERROR REPORTING AND LOGGING
  1205. ===========================
  1206. To get any logging information at all you need to provide a logging callback in the setup call
  1207. the easiest way is to use sokol_log.h:
  1208. #include "sokol_log.h"
  1209. sg_setup(&(sg_desc){ .logger.func = slog_func });
  1210. To override logging with your own callback, first write a logging function like this:
  1211. void my_log(const char* tag, // e.g. 'sg'
  1212. uint32_t log_level, // 0=panic, 1=error, 2=warn, 3=info
  1213. uint32_t log_item_id, // SG_LOGITEM_*
  1214. const char* message_or_null, // a message string, may be nullptr in release mode
  1215. uint32_t line_nr, // line number in sokol_gfx.h
  1216. const char* filename_or_null, // source filename, may be nullptr in release mode
  1217. void* user_data)
  1218. {
  1219. ...
  1220. }
  1221. ...and then setup sokol-gfx like this:
  1222. sg_setup(&(sg_desc){
  1223. .logger = {
  1224. .func = my_log,
  1225. .user_data = my_user_data,
  1226. }
  1227. });
  1228. The provided logging function must be reentrant (e.g. be callable from
  1229. different threads).
  1230. If you don't want to provide your own custom logger it is highly recommended to use
  1231. the standard logger in sokol_log.h instead, otherwise you won't see any warnings or
  1232. errors.
  1233. COMMIT LISTENERS
  1234. ================
  1235. It's possible to hook callback functions into sokol-gfx which are called from
  1236. inside sg_commit() in unspecified order. This is mainly useful for libraries
  1237. that build on top of sokol_gfx.h to be notified about the end/start of a frame.
  1238. To add a commit listener, call:
  1239. static void my_commit_listener(void* user_data) {
  1240. ...
  1241. }
  1242. bool success = sg_add_commit_listener((sg_commit_listener){
  1243. .func = my_commit_listener,
  1244. .user_data = ...,
  1245. });
  1246. The function returns false if the internal array of commit listeners is full,
  1247. or the same commit listener had already been added.
  1248. If the function returns true, my_commit_listener() will be called each frame
  1249. from inside sg_commit().
  1250. By default, 1024 distinct commit listeners can be added, but this number
  1251. can be tweaked in the sg_setup() call:
  1252. sg_setup(&(sg_desc){
  1253. .max_commit_listeners = 2048,
  1254. });
  1255. An sg_commit_listener item is equal to another if both the function
  1256. pointer and user_data field are equal.
  1257. To remove a commit listener:
  1258. bool success = sg_remove_commit_listener((sg_commit_listener){
  1259. .func = my_commit_listener,
  1260. .user_data = ...,
  1261. });
  1262. ...where the .func and .user_data field are equal to a previous
  1263. sg_add_commit_listener() call. The function returns true if the commit
  1264. listener item was found and removed, and false otherwise.
  1265. RESOURCE CREATION AND DESTRUCTION IN DETAIL
  1266. ===========================================
  1267. The 'vanilla' way to create resource objects is with the 'make functions':
  1268. sg_buffer sg_make_buffer(const sg_buffer_desc* desc)
  1269. sg_image sg_make_image(const sg_image_desc* desc)
  1270. sg_sampler sg_make_sampler(const sg_sampler_desc* desc)
  1271. sg_shader sg_make_shader(const sg_shader_desc* desc)
  1272. sg_pipeline sg_make_pipeline(const sg_pipeline_desc* desc)
  1273. sg_attachments sg_make_attachments(const sg_attachments_desc* desc)
  1274. This will result in one of three cases:
  1275. 1. The returned handle is invalid. This happens when there are no more
  1276. free slots in the resource pool for this resource type. An invalid
  1277. handle is associated with the INVALID resource state, for instance:
  1278. sg_buffer buf = sg_make_buffer(...)
  1279. if (sg_query_buffer_state(buf) == SG_RESOURCESTATE_INVALID) {
  1280. // buffer pool is exhausted
  1281. }
  1282. 2. The returned handle is valid, but creating the underlying resource
  1283. has failed for some reason. This results in a resource object in the
  1284. FAILED state. The reason *why* resource creation has failed differ
  1285. by resource type. Look for log messages with more details. A failed
  1286. resource state can be checked with:
  1287. sg_buffer buf = sg_make_buffer(...)
  1288. if (sg_query_buffer_state(buf) == SG_RESOURCESTATE_FAILED) {
  1289. // creating the resource has failed
  1290. }
  1291. 3. And finally, if everything goes right, the returned resource is
  1292. in resource state VALID and ready to use. This can be checked
  1293. with:
  1294. sg_buffer buf = sg_make_buffer(...)
  1295. if (sg_query_buffer_state(buf) == SG_RESOURCESTATE_VALID) {
  1296. // creating the resource has failed
  1297. }
  1298. When calling the 'make functions', the created resource goes through a number
  1299. of states:
  1300. - INITIAL: the resource slot associated with the new resource is currently
  1301. free (technically, there is no resource yet, just an empty pool slot)
  1302. - ALLOC: a handle for the new resource has been allocated, this just means
  1303. a pool slot has been reserved.
  1304. - VALID or FAILED: in VALID state any 3D API backend resource objects have
  1305. been successfully created, otherwise if anything went wrong, the resource
  1306. will be in FAILED state.
  1307. Sometimes it makes sense to first grab a handle, but initialize the
  1308. underlying resource at a later time. For instance when loading data
  1309. asynchronously from a slow data source, you may know what buffers and
  1310. textures are needed at an early stage of the loading process, but actually
  1311. loading the buffer or texture content can only be completed at a later time.
  1312. For such situations, sokol-gfx resource objects can be created in two steps.
  1313. You can allocate a handle upfront with one of the 'alloc functions':
  1314. sg_buffer sg_alloc_buffer(void)
  1315. sg_image sg_alloc_image(void)
  1316. sg_sampler sg_alloc_sampler(void)
  1317. sg_shader sg_alloc_shader(void)
  1318. sg_pipeline sg_alloc_pipeline(void)
  1319. sg_attachments sg_alloc_attachments(void)
  1320. This will return a handle with the underlying resource object in the
  1321. ALLOC state:
  1322. sg_image img = sg_alloc_image();
  1323. if (sg_query_image_state(img) == SG_RESOURCESTATE_ALLOC) {
  1324. // allocating an image handle has succeeded, otherwise
  1325. // the image pool is full
  1326. }
  1327. Such an 'incomplete' handle can be used in most sokol-gfx rendering functions
  1328. without doing any harm, sokol-gfx will simply skip any rendering operation
  1329. that involve resources which are not in VALID state.
  1330. At a later time (for instance once the texture has completed loading
  1331. asynchronously), the resource creation can be completed by calling one of
  1332. the 'init functions', those functions take an existing resource handle and
  1333. 'desc struct':
  1334. void sg_init_buffer(sg_buffer buf, const sg_buffer_desc* desc)
  1335. void sg_init_image(sg_image img, const sg_image_desc* desc)
  1336. void sg_init_sampler(sg_sampler smp, const sg_sampler_desc* desc)
  1337. void sg_init_shader(sg_shader shd, const sg_shader_desc* desc)
  1338. void sg_init_pipeline(sg_pipeline pip, const sg_pipeline_desc* desc)
  1339. void sg_init_attachments(sg_attachments atts, const sg_attachments_desc* desc)
  1340. The init functions expect a resource in ALLOC state, and after the function
  1341. returns, the resource will be either in VALID or FAILED state. Calling
  1342. an 'alloc function' followed by the matching 'init function' is fully
  1343. equivalent with calling the 'make function' alone.
  1344. Destruction can also happen as a two-step process. The 'uninit functions'
  1345. will put a resource object from the VALID or FAILED state back into the
  1346. ALLOC state:
  1347. void sg_uninit_buffer(sg_buffer buf)
  1348. void sg_uninit_image(sg_image img)
  1349. void sg_uninit_sampler(sg_sampler smp)
  1350. void sg_uninit_shader(sg_shader shd)
  1351. void sg_uninit_pipeline(sg_pipeline pip)
  1352. void sg_uninit_attachments(sg_attachments pass)
  1353. Calling the 'uninit functions' with a resource that is not in the VALID or
  1354. FAILED state is a no-op.
  1355. To finally free the pool slot for recycling call the 'dealloc functions':
  1356. void sg_dealloc_buffer(sg_buffer buf)
  1357. void sg_dealloc_image(sg_image img)
  1358. void sg_dealloc_sampler(sg_sampler smp)
  1359. void sg_dealloc_shader(sg_shader shd)
  1360. void sg_dealloc_pipeline(sg_pipeline pip)
  1361. void sg_dealloc_attachments(sg_attachments atts)
  1362. Calling the 'dealloc functions' on a resource that's not in ALLOC state is
  1363. a no-op, but will generate a warning log message.
  1364. Calling an 'uninit function' and 'dealloc function' in sequence is equivalent
  1365. with calling the associated 'destroy function':
  1366. void sg_destroy_buffer(sg_buffer buf)
  1367. void sg_destroy_image(sg_image img)
  1368. void sg_destroy_sampler(sg_sampler smp)
  1369. void sg_destroy_shader(sg_shader shd)
  1370. void sg_destroy_pipeline(sg_pipeline pip)
  1371. void sg_destroy_attachments(sg_attachments atts)
  1372. The 'destroy functions' can be called on resources in any state and generally
  1373. do the right thing (for instance if the resource is in ALLOC state, the destroy
  1374. function will be equivalent to the 'dealloc function' and skip the 'uninit part').
  1375. And finally to close the circle, the 'fail functions' can be called to manually
  1376. put a resource in ALLOC state into the FAILED state:
  1377. sg_fail_buffer(sg_buffer buf)
  1378. sg_fail_image(sg_image img)
  1379. sg_fail_sampler(sg_sampler smp)
  1380. sg_fail_shader(sg_shader shd)
  1381. sg_fail_pipeline(sg_pipeline pip)
  1382. sg_fail_attachments(sg_attachments atts)
  1383. This is recommended if anything went wrong outside of sokol-gfx during asynchronous
  1384. resource setup (for instance a file loading operation failed). In this case,
  1385. the 'fail function' should be called instead of the 'init function'.
  1386. Calling a 'fail function' on a resource that's not in ALLOC state is a no-op,
  1387. but will generate a warning log message.
  1388. NOTE: that two-step resource creation usually only makes sense for buffers
  1389. and images, but not for samplers, shaders, pipelines or attachments. Most notably, trying
  1390. to create a pipeline object with a shader that's not in VALID state will
  1391. trigger a validation layer error, or if the validation layer is disabled,
  1392. result in a pipeline object in FAILED state. Same when trying to create
  1393. an attachments object with invalid image objects.
  1394. WEBGPU CAVEATS
  1395. ==============
  1396. For a general overview and design notes of the WebGPU backend see:
  1397. https://floooh.github.io/2023/10/16/sokol-webgpu.html
  1398. In general, don't expect an automatic speedup when switching from the WebGL2
  1399. backend to the WebGPU backend. Some WebGPU functions currently actually
  1400. have a higher CPU overhead than similar WebGL2 functions, leading to the
  1401. paradoxical situation that some WebGPU code may be slower than similar WebGL2
  1402. code.
  1403. - when writing WGSL shader code by hand, a specific bind-slot convention
  1404. must be used:
  1405. All uniform block structs must use `@group(0)` and bindings in the
  1406. range 0..15
  1407. @group(0) @binding(0..15)
  1408. All textures, samplers and storage buffers must use `@group(1)` and
  1409. bindings must be in the range 0..127:
  1410. @group(1) @binding(0..127)
  1411. All storage image attachments must use `@group(2)` and bindings
  1412. must be in the range 0..3:
  1413. @group(2) @binding(0..3)
  1414. Note that the number of texture, sampler and storage buffer bindings
  1415. is still limited despite the large bind range:
  1416. - up to 16 textures and sampler across all shader stages
  1417. - up to 8 storage buffers across all shader stages
  1418. If you use sokol-shdc to generate WGSL shader code, you don't need to worry
  1419. about the above binding conventions since sokol-shdc.
  1420. - The sokol-gfx WebGPU backend uses the sg_desc.uniform_buffer_size item
  1421. to allocate a single per-frame uniform buffer which must be big enough
  1422. to hold all data written by sg_apply_uniforms() during a single frame,
  1423. including a worst-case 256-byte alignment (e.g. each sg_apply_uniform
  1424. call will cost at least 256 bytes of uniform buffer size). The default size
  1425. is 4 MB, which is enough for 16384 sg_apply_uniform() calls per
  1426. frame (assuming the uniform data 'payload' is less than 256 bytes
  1427. per call). These rules are the same as for the Metal backend, so if
  1428. you are already using the Metal backend you'll be fine.
  1429. - sg_apply_bindings(): the sokol-gfx WebGPU backend implements a bindgroup
  1430. cache to prevent excessive creation and destruction of BindGroup objects
  1431. when calling sg_apply_bindings(). The number of slots in the bindgroups
  1432. cache is defined in sg_desc.wgpu_bindgroups_cache_size when calling
  1433. sg_setup. The cache size must be a power-of-2 number, with the default being
  1434. 1024. The bindgroups cache behaviour can be observed by calling the new
  1435. function sg_query_frame_stats(), where the following struct items are
  1436. of interest:
  1437. .wgpu.num_bindgroup_cache_hits
  1438. .wgpu.num_bindgroup_cache_misses
  1439. .wgpu.num_bindgroup_cache_collisions
  1440. .wgpu_num_bindgroup_cache_invalidates
  1441. .wgpu.num_bindgroup_cache_vs_hash_key_mismatch
  1442. The value to pay attention to is `.wgpu.num_bindgroup_cache_collisions`,
  1443. if this number is consistently higher than a few percent of the
  1444. .wgpu.num_set_bindgroup value, it might be a good idea to bump the
  1445. bindgroups cache size to the next power-of-2.
  1446. - sg_apply_viewport(): WebGPU currently has a unique restriction that viewport
  1447. rectangles must be contained entirely within the framebuffer. As a shitty
  1448. workaround sokol_gfx.h will clip incoming viewport rectangles against
  1449. the framebuffer, but this will distort the clipspace-to-screenspace mapping.
  1450. There's no proper way to handle this inside sokol_gfx.h, this must be fixed
  1451. in a future WebGPU update (see: https://github.com/gpuweb/gpuweb/issues/373
  1452. and https://github.com/gpuweb/gpuweb/pull/5025)
  1453. - The sokol shader compiler generally adds `diagnostic(off, derivative_uniformity);`
  1454. into the WGSL output. Currently only the Chrome WebGPU implementation seems
  1455. to recognize this.
  1456. - Likewise, the following sokol-gfx pixel formats are not supported in WebGPU:
  1457. R16, R16SN, RG16, RG16SN, RGBA16, RGBA16SN.
  1458. Unlike unsupported vertex formats, unsupported pixel formats can be queried
  1459. in cross-backend code via sg_query_pixelformat() though.
  1460. - The Emscripten WebGPU shim currently doesn't support the Closure minification
  1461. post-link-step (e.g. currently the emcc argument '--closure 1' or '--closure 2'
  1462. will generate broken Javascript code.
  1463. - sokol-gfx requires the WebGPU device feature `depth32float-stencil8` to be enabled
  1464. (this should be widely supported)
  1465. - sokol-gfx expects that the WebGPU device feature `float32-filterable` to *not* be
  1466. enabled (since this would exclude all iOS devices)
  1467. LICENSE
  1468. =======
  1469. zlib/libpng license
  1470. Copyright (c) 2018 Andre Weissflog
  1471. This software is provided 'as-is', without any express or implied warranty.
  1472. In no event will the authors be held liable for any damages arising from the
  1473. use of this software.
  1474. Permission is granted to anyone to use this software for any purpose,
  1475. including commercial applications, and to alter it and redistribute it
  1476. freely, subject to the following restrictions:
  1477. 1. The origin of this software must not be misrepresented; you must not
  1478. claim that you wrote the original software. If you use this software in a
  1479. product, an acknowledgment in the product documentation would be
  1480. appreciated but is not required.
  1481. 2. Altered source versions must be plainly marked as such, and must not
  1482. be misrepresented as being the original software.
  1483. 3. This notice may not be removed or altered from any source
  1484. distribution.
  1485. */
  1486. #define SOKOL_GFX_INCLUDED (1)
  1487. #include <stddef.h> // size_t
  1488. #include <stdint.h>
  1489. #include <stdbool.h>
  1490. #if defined(SOKOL_API_DECL) && !defined(SOKOL_GFX_API_DECL)
  1491. #define SOKOL_GFX_API_DECL SOKOL_API_DECL
  1492. #endif
  1493. #ifndef SOKOL_GFX_API_DECL
  1494. #if defined(_WIN32) && defined(SOKOL_DLL) && defined(SOKOL_GFX_IMPL)
  1495. #define SOKOL_GFX_API_DECL __declspec(dllexport)
  1496. #elif defined(_WIN32) && defined(SOKOL_DLL)
  1497. #define SOKOL_GFX_API_DECL __declspec(dllimport)
  1498. #else
  1499. #define SOKOL_GFX_API_DECL extern
  1500. #endif
  1501. #endif
  1502. #ifdef __cplusplus
  1503. extern "C" {
  1504. #endif
  1505. /*
  1506. Resource id typedefs:
  1507. sg_buffer: vertex- and index-buffers
  1508. sg_image: images used as textures and render-pass attachments
  1509. sg_sampler sampler objects describing how a texture is sampled in a shader
  1510. sg_shader: vertex- and fragment-shaders and shader interface information
  1511. sg_pipeline: associated shader and vertex-layouts, and render states
  1512. sg_attachments: a baked collection of render pass attachment images
  1513. Instead of pointers, resource creation functions return a 32-bit
  1514. handle which uniquely identifies the resource object.
  1515. The 32-bit resource id is split into a 16-bit pool index in the lower bits,
  1516. and a 16-bit 'generation counter' in the upper bits. The index allows fast
  1517. pool lookups, and combined with the generation-counter it allows to detect
  1518. 'dangling accesses' (trying to use an object which no longer exists, and
  1519. its pool slot has been reused for a new object)
  1520. The resource ids are wrapped into a strongly-typed struct so that
  1521. trying to pass an incompatible resource id is a compile error.
  1522. */
  1523. typedef struct sg_buffer { uint32_t id; } sg_buffer;
  1524. typedef struct sg_image { uint32_t id; } sg_image;
  1525. typedef struct sg_sampler { uint32_t id; } sg_sampler;
  1526. typedef struct sg_shader { uint32_t id; } sg_shader;
  1527. typedef struct sg_pipeline { uint32_t id; } sg_pipeline;
  1528. typedef struct sg_attachments { uint32_t id; } sg_attachments;
  1529. /*
  1530. sg_range is a pointer-size-pair struct used to pass memory blobs into
  1531. sokol-gfx. When initialized from a value type (array or struct), you can
  1532. use the SG_RANGE() macro to build an sg_range struct. For functions which
  1533. take either a sg_range pointer, or a (C++) sg_range reference, use the
  1534. SG_RANGE_REF macro as a solution which compiles both in C and C++.
  1535. */
  1536. typedef struct sg_range {
  1537. const void* ptr;
  1538. size_t size;
  1539. } sg_range;
  1540. // disabling this for every includer isn't great, but the warnings are also quite pointless
  1541. #if defined(_MSC_VER)
  1542. #pragma warning(disable:4221) // /W4 only: nonstandard extension used: 'x': cannot be initialized using address of automatic variable 'y'
  1543. #pragma warning(disable:4204) // VS2015: nonstandard extension used: non-constant aggregate initializer
  1544. #endif
  1545. #if defined(__cplusplus)
  1546. #define SG_RANGE(x) sg_range{ &x, sizeof(x) }
  1547. #define SG_RANGE_REF(x) sg_range{ &x, sizeof(x) }
  1548. #else
  1549. #define SG_RANGE(x) (sg_range){ &x, sizeof(x) }
  1550. #define SG_RANGE_REF(x) &(sg_range){ &x, sizeof(x) }
  1551. #endif
  1552. // various compile-time constants in the public API
  1553. enum {
  1554. SG_INVALID_ID = 0,
  1555. SG_NUM_INFLIGHT_FRAMES = 2,
  1556. SG_MAX_COLOR_ATTACHMENTS = 4,
  1557. SG_MAX_STORAGE_ATTACHMENTS = 4,
  1558. SG_MAX_UNIFORMBLOCK_MEMBERS = 16,
  1559. SG_MAX_VERTEX_ATTRIBUTES = 16,
  1560. SG_MAX_MIPMAPS = 16,
  1561. SG_MAX_TEXTUREARRAY_LAYERS = 128,
  1562. SG_MAX_UNIFORMBLOCK_BINDSLOTS = 8,
  1563. SG_MAX_VERTEXBUFFER_BINDSLOTS = 8,
  1564. SG_MAX_IMAGE_BINDSLOTS = 16,
  1565. SG_MAX_SAMPLER_BINDSLOTS = 16,
  1566. SG_MAX_STORAGEBUFFER_BINDSLOTS = 8,
  1567. SG_MAX_IMAGE_SAMPLER_PAIRS = 16,
  1568. };
  1569. /*
  1570. sg_color
  1571. An RGBA color value.
  1572. */
  1573. typedef struct sg_color { float r, g, b, a; } sg_color;
  1574. /*
  1575. sg_backend
  1576. The active 3D-API backend, use the function sg_query_backend()
  1577. to get the currently active backend.
  1578. */
  1579. typedef enum sg_backend {
  1580. SG_BACKEND_GLCORE,
  1581. SG_BACKEND_GLES3,
  1582. SG_BACKEND_D3D11,
  1583. SG_BACKEND_METAL_IOS,
  1584. SG_BACKEND_METAL_MACOS,
  1585. SG_BACKEND_METAL_SIMULATOR,
  1586. SG_BACKEND_WGPU,
  1587. SG_BACKEND_DUMMY,
  1588. } sg_backend;
  1589. /*
  1590. sg_pixel_format
  1591. sokol_gfx.h basically uses the same pixel formats as WebGPU, since these
  1592. are supported on most newer GPUs.
  1593. A pixelformat name consist of three parts:
  1594. - components (R, RG, RGB or RGBA)
  1595. - bit width per component (8, 16 or 32)
  1596. - component data type:
  1597. - unsigned normalized (no postfix)
  1598. - signed normalized (SN postfix)
  1599. - unsigned integer (UI postfix)
  1600. - signed integer (SI postfix)
  1601. - float (F postfix)
  1602. Not all pixel formats can be used for everything, call sg_query_pixelformat()
  1603. to inspect the capabilities of a given pixelformat. The function returns
  1604. an sg_pixelformat_info struct with the following members:
  1605. - sample: the pixelformat can be sampled as texture at least with
  1606. nearest filtering
  1607. - filter: the pixelformat can be sampled as texture with linear
  1608. filtering
  1609. - render: the pixelformat can be used as render-pass attachment
  1610. - blend: blending is supported when used as render-pass attachment
  1611. - msaa: multisample-antialiasing is supported when used
  1612. as render-pass attachment
  1613. - depth: the pixelformat can be used for depth-stencil attachments
  1614. - compressed: this is a block-compressed format
  1615. - bytes_per_pixel: the numbers of bytes in a pixel (0 for compressed formats)
  1616. The default pixel format for texture images is SG_PIXELFORMAT_RGBA8.
  1617. The default pixel format for render target images is platform-dependent
  1618. and taken from the sg_environment struct passed into sg_setup(). Typically
  1619. the default formats are:
  1620. - for the Metal, D3D11 and WebGPU backends: SG_PIXELFORMAT_BGRA8
  1621. - for GL backends: SG_PIXELFORMAT_RGBA8
  1622. */
  1623. typedef enum sg_pixel_format {
  1624. _SG_PIXELFORMAT_DEFAULT, // value 0 reserved for default-init
  1625. SG_PIXELFORMAT_NONE,
  1626. SG_PIXELFORMAT_R8,
  1627. SG_PIXELFORMAT_R8SN,
  1628. SG_PIXELFORMAT_R8UI,
  1629. SG_PIXELFORMAT_R8SI,
  1630. SG_PIXELFORMAT_R16,
  1631. SG_PIXELFORMAT_R16SN,
  1632. SG_PIXELFORMAT_R16UI,
  1633. SG_PIXELFORMAT_R16SI,
  1634. SG_PIXELFORMAT_R16F,
  1635. SG_PIXELFORMAT_RG8,
  1636. SG_PIXELFORMAT_RG8SN,
  1637. SG_PIXELFORMAT_RG8UI,
  1638. SG_PIXELFORMAT_RG8SI,
  1639. SG_PIXELFORMAT_R32UI,
  1640. SG_PIXELFORMAT_R32SI,
  1641. SG_PIXELFORMAT_R32F,
  1642. SG_PIXELFORMAT_RG16,
  1643. SG_PIXELFORMAT_RG16SN,
  1644. SG_PIXELFORMAT_RG16UI,
  1645. SG_PIXELFORMAT_RG16SI,
  1646. SG_PIXELFORMAT_RG16F,
  1647. SG_PIXELFORMAT_RGBA8,
  1648. SG_PIXELFORMAT_SRGB8A8,
  1649. SG_PIXELFORMAT_RGBA8SN,
  1650. SG_PIXELFORMAT_RGBA8UI,
  1651. SG_PIXELFORMAT_RGBA8SI,
  1652. SG_PIXELFORMAT_BGRA8,
  1653. SG_PIXELFORMAT_RGB10A2,
  1654. SG_PIXELFORMAT_RG11B10F,
  1655. SG_PIXELFORMAT_RGB9E5,
  1656. SG_PIXELFORMAT_RG32UI,
  1657. SG_PIXELFORMAT_RG32SI,
  1658. SG_PIXELFORMAT_RG32F,
  1659. SG_PIXELFORMAT_RGBA16,
  1660. SG_PIXELFORMAT_RGBA16SN,
  1661. SG_PIXELFORMAT_RGBA16UI,
  1662. SG_PIXELFORMAT_RGBA16SI,
  1663. SG_PIXELFORMAT_RGBA16F,
  1664. SG_PIXELFORMAT_RGBA32UI,
  1665. SG_PIXELFORMAT_RGBA32SI,
  1666. SG_PIXELFORMAT_RGBA32F,
  1667. // NOTE: when adding/removing pixel formats before DEPTH, also update sokol_app.h/_SAPP_PIXELFORMAT_*
  1668. SG_PIXELFORMAT_DEPTH,
  1669. SG_PIXELFORMAT_DEPTH_STENCIL,
  1670. // NOTE: don't put any new compressed format in front of here
  1671. SG_PIXELFORMAT_BC1_RGBA,
  1672. SG_PIXELFORMAT_BC2_RGBA,
  1673. SG_PIXELFORMAT_BC3_RGBA,
  1674. SG_PIXELFORMAT_BC3_SRGBA,
  1675. SG_PIXELFORMAT_BC4_R,
  1676. SG_PIXELFORMAT_BC4_RSN,
  1677. SG_PIXELFORMAT_BC5_RG,
  1678. SG_PIXELFORMAT_BC5_RGSN,
  1679. SG_PIXELFORMAT_BC6H_RGBF,
  1680. SG_PIXELFORMAT_BC6H_RGBUF,
  1681. SG_PIXELFORMAT_BC7_RGBA,
  1682. SG_PIXELFORMAT_BC7_SRGBA,
  1683. SG_PIXELFORMAT_ETC2_RGB8,
  1684. SG_PIXELFORMAT_ETC2_SRGB8,
  1685. SG_PIXELFORMAT_ETC2_RGB8A1,
  1686. SG_PIXELFORMAT_ETC2_RGBA8,
  1687. SG_PIXELFORMAT_ETC2_SRGB8A8,
  1688. SG_PIXELFORMAT_EAC_R11,
  1689. SG_PIXELFORMAT_EAC_R11SN,
  1690. SG_PIXELFORMAT_EAC_RG11,
  1691. SG_PIXELFORMAT_EAC_RG11SN,
  1692. SG_PIXELFORMAT_ASTC_4x4_RGBA,
  1693. SG_PIXELFORMAT_ASTC_4x4_SRGBA,
  1694. _SG_PIXELFORMAT_NUM,
  1695. _SG_PIXELFORMAT_FORCE_U32 = 0x7FFFFFFF
  1696. } sg_pixel_format;
  1697. /*
  1698. Runtime information about a pixel format, returned by sg_query_pixelformat().
  1699. */
  1700. typedef struct sg_pixelformat_info {
  1701. bool sample; // pixel format can be sampled in shaders at least with nearest filtering
  1702. bool filter; // pixel format can be sampled with linear filtering
  1703. bool render; // pixel format can be used as render-pass attachment
  1704. bool blend; // pixel format supports alpha-blending when used as render-pass attachment
  1705. bool msaa; // pixel format supports MSAA when used as render-pass attachment
  1706. bool depth; // pixel format is a depth format
  1707. bool compressed; // true if this is a hardware-compressed format
  1708. bool read; // true if format supports compute shader read access
  1709. bool write; // true if format supports compute shader write access
  1710. int bytes_per_pixel; // NOTE: this is 0 for compressed formats, use sg_query_row_pitch() / sg_query_surface_pitch() as alternative
  1711. } sg_pixelformat_info;
  1712. /*
  1713. Runtime information about available optional features, returned by sg_query_features()
  1714. */
  1715. typedef struct sg_features {
  1716. bool origin_top_left; // framebuffer- and texture-origin is in top left corner
  1717. bool image_clamp_to_border; // border color and clamp-to-border uv-wrap mode is supported
  1718. bool mrt_independent_blend_state; // multiple-render-target rendering can use per-render-target blend state
  1719. bool mrt_independent_write_mask; // multiple-render-target rendering can use per-render-target color write masks
  1720. bool compute; // storage buffers and compute shaders are supported
  1721. bool msaa_image_bindings; // if true, multisampled images can be bound as texture resources
  1722. bool separate_buffer_types; // cannot use the same buffer for vertex and indices (onlu WebGL2)
  1723. } sg_features;
  1724. /*
  1725. Runtime information about resource limits, returned by sg_query_limit()
  1726. */
  1727. typedef struct sg_limits {
  1728. int max_image_size_2d; // max width/height of SG_IMAGETYPE_2D images
  1729. int max_image_size_cube; // max width/height of SG_IMAGETYPE_CUBE images
  1730. int max_image_size_3d; // max width/height/depth of SG_IMAGETYPE_3D images
  1731. int max_image_size_array; // max width/height of SG_IMAGETYPE_ARRAY images
  1732. int max_image_array_layers; // max number of layers in SG_IMAGETYPE_ARRAY images
  1733. int max_vertex_attrs; // max number of vertex attributes, clamped to SG_MAX_VERTEX_ATTRIBUTES
  1734. int gl_max_vertex_uniform_components; // <= GL_MAX_VERTEX_UNIFORM_COMPONENTS (only on GL backends)
  1735. int gl_max_combined_texture_image_units; // <= GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS (only on GL backends)
  1736. } sg_limits;
  1737. /*
  1738. sg_resource_state
  1739. The current state of a resource in its resource pool.
  1740. Resources start in the INITIAL state, which means the
  1741. pool slot is unoccupied and can be allocated. When a resource is
  1742. created, first an id is allocated, and the resource pool slot
  1743. is set to state ALLOC. After allocation, the resource is
  1744. initialized, which may result in the VALID or FAILED state. The
  1745. reason why allocation and initialization are separate is because
  1746. some resource types (e.g. buffers and images) might be asynchronously
  1747. initialized by the user application. If a resource which is not
  1748. in the VALID state is attempted to be used for rendering, rendering
  1749. operations will silently be dropped.
  1750. The special INVALID state is returned in sg_query_xxx_state() if no
  1751. resource object exists for the provided resource id.
  1752. */
  1753. typedef enum sg_resource_state {
  1754. SG_RESOURCESTATE_INITIAL,
  1755. SG_RESOURCESTATE_ALLOC,
  1756. SG_RESOURCESTATE_VALID,
  1757. SG_RESOURCESTATE_FAILED,
  1758. SG_RESOURCESTATE_INVALID,
  1759. _SG_RESOURCESTATE_FORCE_U32 = 0x7FFFFFFF
  1760. } sg_resource_state;
  1761. /*
  1762. sg_index_type
  1763. Indicates whether indexed rendering (fetching vertex-indices from an
  1764. index buffer) is used, and if yes, the index data type (16- or 32-bits).
  1765. This is used in the sg_pipeline_desc.index_type member when creating a
  1766. pipeline object.
  1767. The default index type is SG_INDEXTYPE_NONE.
  1768. */
  1769. typedef enum sg_index_type {
  1770. _SG_INDEXTYPE_DEFAULT, // value 0 reserved for default-init
  1771. SG_INDEXTYPE_NONE,
  1772. SG_INDEXTYPE_UINT16,
  1773. SG_INDEXTYPE_UINT32,
  1774. _SG_INDEXTYPE_NUM,
  1775. _SG_INDEXTYPE_FORCE_U32 = 0x7FFFFFFF
  1776. } sg_index_type;
  1777. /*
  1778. sg_image_type
  1779. Indicates the basic type of an image object (2D-texture, cubemap,
  1780. 3D-texture or 2D-array-texture). Used in the sg_image_desc.type member when
  1781. creating an image, and in sg_shader_image_desc to describe a sampled texture
  1782. in the shader (both must match and will be checked in the validation layer
  1783. when calling sg_apply_bindings).
  1784. The default image type when creating an image is SG_IMAGETYPE_2D.
  1785. */
  1786. typedef enum sg_image_type {
  1787. _SG_IMAGETYPE_DEFAULT, // value 0 reserved for default-init
  1788. SG_IMAGETYPE_2D,
  1789. SG_IMAGETYPE_CUBE,
  1790. SG_IMAGETYPE_3D,
  1791. SG_IMAGETYPE_ARRAY,
  1792. _SG_IMAGETYPE_NUM,
  1793. _SG_IMAGETYPE_FORCE_U32 = 0x7FFFFFFF
  1794. } sg_image_type;
  1795. /*
  1796. sg_image_sample_type
  1797. The basic data type of a texture sample as expected by a shader.
  1798. Must be provided in sg_shader_image and used by the validation
  1799. layer in sg_apply_bindings() to check if the provided image object
  1800. is compatible with what the shader expects. Apart from the sokol-gfx
  1801. validation layer, WebGPU is the only backend API which actually requires
  1802. matching texture and sampler type to be provided upfront for validation
  1803. (other 3D APIs treat texture/sampler type mismatches as undefined behaviour).
  1804. NOTE that the following texture pixel formats require the use
  1805. of SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT, combined with a sampler
  1806. of type SG_SAMPLERTYPE_NONFILTERING:
  1807. - SG_PIXELFORMAT_R32F
  1808. - SG_PIXELFORMAT_RG32F
  1809. - SG_PIXELFORMAT_RGBA32F
  1810. (when using sokol-shdc, also check out the meta tags `@image_sample_type`
  1811. and `@sampler_type`)
  1812. */
  1813. typedef enum sg_image_sample_type {
  1814. _SG_IMAGESAMPLETYPE_DEFAULT, // value 0 reserved for default-init
  1815. SG_IMAGESAMPLETYPE_FLOAT,
  1816. SG_IMAGESAMPLETYPE_DEPTH,
  1817. SG_IMAGESAMPLETYPE_SINT,
  1818. SG_IMAGESAMPLETYPE_UINT,
  1819. SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT,
  1820. _SG_IMAGESAMPLETYPE_NUM,
  1821. _SG_IMAGESAMPLETYPE_FORCE_U32 = 0x7FFFFFFF
  1822. } sg_image_sample_type;
  1823. /*
  1824. sg_sampler_type
  1825. The basic type of a texture sampler (sampling vs comparison) as
  1826. defined in a shader. Must be provided in sg_shader_sampler_desc.
  1827. sg_image_sample_type and sg_sampler_type for a texture/sampler
  1828. pair must be compatible with each other, specifically only
  1829. the following pairs are allowed:
  1830. - SG_IMAGESAMPLETYPE_FLOAT => (SG_SAMPLERTYPE_FILTERING or SG_SAMPLERTYPE_NONFILTERING)
  1831. - SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT => SG_SAMPLERTYPE_NONFILTERING
  1832. - SG_IMAGESAMPLETYPE_SINT => SG_SAMPLERTYPE_NONFILTERING
  1833. - SG_IMAGESAMPLETYPE_UINT => SG_SAMPLERTYPE_NONFILTERING
  1834. - SG_IMAGESAMPLETYPE_DEPTH => SG_SAMPLERTYPE_COMPARISON
  1835. */
  1836. typedef enum sg_sampler_type {
  1837. _SG_SAMPLERTYPE_DEFAULT,
  1838. SG_SAMPLERTYPE_FILTERING,
  1839. SG_SAMPLERTYPE_NONFILTERING,
  1840. SG_SAMPLERTYPE_COMPARISON,
  1841. _SG_SAMPLERTYPE_NUM,
  1842. _SG_SAMPLERTYPE_FORCE_U32,
  1843. } sg_sampler_type;
  1844. /*
  1845. sg_cube_face
  1846. The cubemap faces. Use these as indices in the sg_image_desc.content
  1847. array.
  1848. */
  1849. typedef enum sg_cube_face {
  1850. SG_CUBEFACE_POS_X,
  1851. SG_CUBEFACE_NEG_X,
  1852. SG_CUBEFACE_POS_Y,
  1853. SG_CUBEFACE_NEG_Y,
  1854. SG_CUBEFACE_POS_Z,
  1855. SG_CUBEFACE_NEG_Z,
  1856. SG_CUBEFACE_NUM,
  1857. _SG_CUBEFACE_FORCE_U32 = 0x7FFFFFFF
  1858. } sg_cube_face;
  1859. /*
  1860. sg_primitive_type
  1861. This is the common subset of 3D primitive types supported across all 3D
  1862. APIs. This is used in the sg_pipeline_desc.primitive_type member when
  1863. creating a pipeline object.
  1864. The default primitive type is SG_PRIMITIVETYPE_TRIANGLES.
  1865. */
  1866. typedef enum sg_primitive_type {
  1867. _SG_PRIMITIVETYPE_DEFAULT, // value 0 reserved for default-init
  1868. SG_PRIMITIVETYPE_POINTS,
  1869. SG_PRIMITIVETYPE_LINES,
  1870. SG_PRIMITIVETYPE_LINE_STRIP,
  1871. SG_PRIMITIVETYPE_TRIANGLES,
  1872. SG_PRIMITIVETYPE_TRIANGLE_STRIP,
  1873. _SG_PRIMITIVETYPE_NUM,
  1874. _SG_PRIMITIVETYPE_FORCE_U32 = 0x7FFFFFFF
  1875. } sg_primitive_type;
  1876. /*
  1877. sg_filter
  1878. The filtering mode when sampling a texture image. This is
  1879. used in the sg_sampler_desc.min_filter, sg_sampler_desc.mag_filter
  1880. and sg_sampler_desc.mipmap_filter members when creating a sampler object.
  1881. For the default is SG_FILTER_NEAREST.
  1882. */
  1883. typedef enum sg_filter {
  1884. _SG_FILTER_DEFAULT, // value 0 reserved for default-init
  1885. SG_FILTER_NEAREST,
  1886. SG_FILTER_LINEAR,
  1887. _SG_FILTER_NUM,
  1888. _SG_FILTER_FORCE_U32 = 0x7FFFFFFF
  1889. } sg_filter;
  1890. /*
  1891. sg_wrap
  1892. The texture coordinates wrapping mode when sampling a texture
  1893. image. This is used in the sg_image_desc.wrap_u, .wrap_v
  1894. and .wrap_w members when creating an image.
  1895. The default wrap mode is SG_WRAP_REPEAT.
  1896. NOTE: SG_WRAP_CLAMP_TO_BORDER is not supported on all backends
  1897. and platforms. To check for support, call sg_query_features()
  1898. and check the "clamp_to_border" boolean in the returned
  1899. sg_features struct.
  1900. Platforms which don't support SG_WRAP_CLAMP_TO_BORDER will silently fall back
  1901. to SG_WRAP_CLAMP_TO_EDGE without a validation error.
  1902. */
  1903. typedef enum sg_wrap {
  1904. _SG_WRAP_DEFAULT, // value 0 reserved for default-init
  1905. SG_WRAP_REPEAT,
  1906. SG_WRAP_CLAMP_TO_EDGE,
  1907. SG_WRAP_CLAMP_TO_BORDER,
  1908. SG_WRAP_MIRRORED_REPEAT,
  1909. _SG_WRAP_NUM,
  1910. _SG_WRAP_FORCE_U32 = 0x7FFFFFFF
  1911. } sg_wrap;
  1912. /*
  1913. sg_border_color
  1914. The border color to use when sampling a texture, and the UV wrap
  1915. mode is SG_WRAP_CLAMP_TO_BORDER.
  1916. The default border color is SG_BORDERCOLOR_OPAQUE_BLACK
  1917. */
  1918. typedef enum sg_border_color {
  1919. _SG_BORDERCOLOR_DEFAULT, // value 0 reserved for default-init
  1920. SG_BORDERCOLOR_TRANSPARENT_BLACK,
  1921. SG_BORDERCOLOR_OPAQUE_BLACK,
  1922. SG_BORDERCOLOR_OPAQUE_WHITE,
  1923. _SG_BORDERCOLOR_NUM,
  1924. _SG_BORDERCOLOR_FORCE_U32 = 0x7FFFFFFF
  1925. } sg_border_color;
  1926. /*
  1927. sg_vertex_format
  1928. The data type of a vertex component. This is used to describe
  1929. the layout of input vertex data when creating a pipeline object.
  1930. NOTE that specific mapping rules exist from the CPU-side vertex
  1931. formats to the vertex attribute base type in the vertex shader code
  1932. (see doc header section 'ON VERTEX FORMATS').
  1933. */
  1934. typedef enum sg_vertex_format {
  1935. SG_VERTEXFORMAT_INVALID,
  1936. SG_VERTEXFORMAT_FLOAT,
  1937. SG_VERTEXFORMAT_FLOAT2,
  1938. SG_VERTEXFORMAT_FLOAT3,
  1939. SG_VERTEXFORMAT_FLOAT4,
  1940. SG_VERTEXFORMAT_INT,
  1941. SG_VERTEXFORMAT_INT2,
  1942. SG_VERTEXFORMAT_INT3,
  1943. SG_VERTEXFORMAT_INT4,
  1944. SG_VERTEXFORMAT_UINT,
  1945. SG_VERTEXFORMAT_UINT2,
  1946. SG_VERTEXFORMAT_UINT3,
  1947. SG_VERTEXFORMAT_UINT4,
  1948. SG_VERTEXFORMAT_BYTE4,
  1949. SG_VERTEXFORMAT_BYTE4N,
  1950. SG_VERTEXFORMAT_UBYTE4,
  1951. SG_VERTEXFORMAT_UBYTE4N,
  1952. SG_VERTEXFORMAT_SHORT2,
  1953. SG_VERTEXFORMAT_SHORT2N,
  1954. SG_VERTEXFORMAT_USHORT2,
  1955. SG_VERTEXFORMAT_USHORT2N,
  1956. SG_VERTEXFORMAT_SHORT4,
  1957. SG_VERTEXFORMAT_SHORT4N,
  1958. SG_VERTEXFORMAT_USHORT4,
  1959. SG_VERTEXFORMAT_USHORT4N,
  1960. SG_VERTEXFORMAT_UINT10_N2,
  1961. SG_VERTEXFORMAT_HALF2,
  1962. SG_VERTEXFORMAT_HALF4,
  1963. _SG_VERTEXFORMAT_NUM,
  1964. _SG_VERTEXFORMAT_FORCE_U32 = 0x7FFFFFFF
  1965. } sg_vertex_format;
  1966. /*
  1967. sg_vertex_step
  1968. Defines whether the input pointer of a vertex input stream is advanced
  1969. 'per vertex' or 'per instance'. The default step-func is
  1970. SG_VERTEXSTEP_PER_VERTEX. SG_VERTEXSTEP_PER_INSTANCE is used with
  1971. instanced-rendering.
  1972. The vertex-step is part of the vertex-layout definition
  1973. when creating pipeline objects.
  1974. */
  1975. typedef enum sg_vertex_step {
  1976. _SG_VERTEXSTEP_DEFAULT, // value 0 reserved for default-init
  1977. SG_VERTEXSTEP_PER_VERTEX,
  1978. SG_VERTEXSTEP_PER_INSTANCE,
  1979. _SG_VERTEXSTEP_NUM,
  1980. _SG_VERTEXSTEP_FORCE_U32 = 0x7FFFFFFF
  1981. } sg_vertex_step;
  1982. /*
  1983. sg_uniform_type
  1984. The data type of a uniform block member. This is used to
  1985. describe the internal layout of uniform blocks when creating
  1986. a shader object. This is only required for the GL backend, all
  1987. other backends will ignore the interior layout of uniform blocks.
  1988. */
  1989. typedef enum sg_uniform_type {
  1990. SG_UNIFORMTYPE_INVALID,
  1991. SG_UNIFORMTYPE_FLOAT,
  1992. SG_UNIFORMTYPE_FLOAT2,
  1993. SG_UNIFORMTYPE_FLOAT3,
  1994. SG_UNIFORMTYPE_FLOAT4,
  1995. SG_UNIFORMTYPE_INT,
  1996. SG_UNIFORMTYPE_INT2,
  1997. SG_UNIFORMTYPE_INT3,
  1998. SG_UNIFORMTYPE_INT4,
  1999. SG_UNIFORMTYPE_MAT4,
  2000. _SG_UNIFORMTYPE_NUM,
  2001. _SG_UNIFORMTYPE_FORCE_U32 = 0x7FFFFFFF
  2002. } sg_uniform_type;
  2003. /*
  2004. sg_uniform_layout
  2005. A hint for the interior memory layout of uniform blocks. This is
  2006. only relevant for the GL backend where the internal layout
  2007. of uniform blocks must be known to sokol-gfx. For all other backends the
  2008. internal memory layout of uniform blocks doesn't matter, sokol-gfx
  2009. will just pass uniform data as an opaque memory blob to the
  2010. 3D backend.
  2011. SG_UNIFORMLAYOUT_NATIVE (default)
  2012. Native layout means that a 'backend-native' memory layout
  2013. is used. For the GL backend this means that uniforms
  2014. are packed tightly in memory (e.g. there are no padding
  2015. bytes).
  2016. SG_UNIFORMLAYOUT_STD140
  2017. The memory layout is a subset of std140. Arrays are only
  2018. allowed for the FLOAT4, INT4 and MAT4. Alignment is as
  2019. is as follows:
  2020. FLOAT, INT: 4 byte alignment
  2021. FLOAT2, INT2: 8 byte alignment
  2022. FLOAT3, INT3: 16 byte alignment(!)
  2023. FLOAT4, INT4: 16 byte alignment
  2024. MAT4: 16 byte alignment
  2025. FLOAT4[], INT4[]: 16 byte alignment
  2026. The overall size of the uniform block must be a multiple
  2027. of 16.
  2028. For more information search for 'UNIFORM DATA LAYOUT' in the documentation block
  2029. at the start of the header.
  2030. */
  2031. typedef enum sg_uniform_layout {
  2032. _SG_UNIFORMLAYOUT_DEFAULT, // value 0 reserved for default-init
  2033. SG_UNIFORMLAYOUT_NATIVE, // default: layout depends on currently active backend
  2034. SG_UNIFORMLAYOUT_STD140, // std140: memory layout according to std140
  2035. _SG_UNIFORMLAYOUT_NUM,
  2036. _SG_UNIFORMLAYOUT_FORCE_U32 = 0x7FFFFFFF
  2037. } sg_uniform_layout;
  2038. /*
  2039. sg_cull_mode
  2040. The face-culling mode, this is used in the
  2041. sg_pipeline_desc.cull_mode member when creating a
  2042. pipeline object.
  2043. The default cull mode is SG_CULLMODE_NONE
  2044. */
  2045. typedef enum sg_cull_mode {
  2046. _SG_CULLMODE_DEFAULT, // value 0 reserved for default-init
  2047. SG_CULLMODE_NONE,
  2048. SG_CULLMODE_FRONT,
  2049. SG_CULLMODE_BACK,
  2050. _SG_CULLMODE_NUM,
  2051. _SG_CULLMODE_FORCE_U32 = 0x7FFFFFFF
  2052. } sg_cull_mode;
  2053. /*
  2054. sg_face_winding
  2055. The vertex-winding rule that determines a front-facing primitive. This
  2056. is used in the member sg_pipeline_desc.face_winding
  2057. when creating a pipeline object.
  2058. The default winding is SG_FACEWINDING_CW (clockwise)
  2059. */
  2060. typedef enum sg_face_winding {
  2061. _SG_FACEWINDING_DEFAULT, // value 0 reserved for default-init
  2062. SG_FACEWINDING_CCW,
  2063. SG_FACEWINDING_CW,
  2064. _SG_FACEWINDING_NUM,
  2065. _SG_FACEWINDING_FORCE_U32 = 0x7FFFFFFF
  2066. } sg_face_winding;
  2067. /*
  2068. sg_compare_func
  2069. The compare-function for configuring depth- and stencil-ref tests
  2070. in pipeline objects, and for texture samplers which perform a comparison
  2071. instead of regular sampling operation.
  2072. Used in the following structs:
  2073. sg_pipeline_desc
  2074. .depth
  2075. .compare
  2076. .stencil
  2077. .front.compare
  2078. .back.compare
  2079. sg_sampler_desc
  2080. .compare
  2081. The default compare func for depth- and stencil-tests is
  2082. SG_COMPAREFUNC_ALWAYS.
  2083. The default compare func for samplers is SG_COMPAREFUNC_NEVER.
  2084. */
  2085. typedef enum sg_compare_func {
  2086. _SG_COMPAREFUNC_DEFAULT, // value 0 reserved for default-init
  2087. SG_COMPAREFUNC_NEVER,
  2088. SG_COMPAREFUNC_LESS,
  2089. SG_COMPAREFUNC_EQUAL,
  2090. SG_COMPAREFUNC_LESS_EQUAL,
  2091. SG_COMPAREFUNC_GREATER,
  2092. SG_COMPAREFUNC_NOT_EQUAL,
  2093. SG_COMPAREFUNC_GREATER_EQUAL,
  2094. SG_COMPAREFUNC_ALWAYS,
  2095. _SG_COMPAREFUNC_NUM,
  2096. _SG_COMPAREFUNC_FORCE_U32 = 0x7FFFFFFF
  2097. } sg_compare_func;
  2098. /*
  2099. sg_stencil_op
  2100. The operation performed on a currently stored stencil-value when a
  2101. comparison test passes or fails. This is used when creating a pipeline
  2102. object in the following sg_pipeline_desc struct items:
  2103. sg_pipeline_desc
  2104. .stencil
  2105. .front
  2106. .fail_op
  2107. .depth_fail_op
  2108. .pass_op
  2109. .back
  2110. .fail_op
  2111. .depth_fail_op
  2112. .pass_op
  2113. The default value is SG_STENCILOP_KEEP.
  2114. */
  2115. typedef enum sg_stencil_op {
  2116. _SG_STENCILOP_DEFAULT, // value 0 reserved for default-init
  2117. SG_STENCILOP_KEEP,
  2118. SG_STENCILOP_ZERO,
  2119. SG_STENCILOP_REPLACE,
  2120. SG_STENCILOP_INCR_CLAMP,
  2121. SG_STENCILOP_DECR_CLAMP,
  2122. SG_STENCILOP_INVERT,
  2123. SG_STENCILOP_INCR_WRAP,
  2124. SG_STENCILOP_DECR_WRAP,
  2125. _SG_STENCILOP_NUM,
  2126. _SG_STENCILOP_FORCE_U32 = 0x7FFFFFFF
  2127. } sg_stencil_op;
  2128. /*
  2129. sg_blend_factor
  2130. The source and destination factors in blending operations.
  2131. This is used in the following members when creating a pipeline object:
  2132. sg_pipeline_desc
  2133. .colors[i]
  2134. .blend
  2135. .src_factor_rgb
  2136. .dst_factor_rgb
  2137. .src_factor_alpha
  2138. .dst_factor_alpha
  2139. The default value is SG_BLENDFACTOR_ONE for source
  2140. factors, and for the destination SG_BLENDFACTOR_ZERO if the associated
  2141. blend-op is ADD, SUBTRACT or REVERSE_SUBTRACT or SG_BLENDFACTOR_ONE
  2142. if the associated blend-op is MIN or MAX.
  2143. */
  2144. typedef enum sg_blend_factor {
  2145. _SG_BLENDFACTOR_DEFAULT, // value 0 reserved for default-init
  2146. SG_BLENDFACTOR_ZERO,
  2147. SG_BLENDFACTOR_ONE,
  2148. SG_BLENDFACTOR_SRC_COLOR,
  2149. SG_BLENDFACTOR_ONE_MINUS_SRC_COLOR,
  2150. SG_BLENDFACTOR_SRC_ALPHA,
  2151. SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA,
  2152. SG_BLENDFACTOR_DST_COLOR,
  2153. SG_BLENDFACTOR_ONE_MINUS_DST_COLOR,
  2154. SG_BLENDFACTOR_DST_ALPHA,
  2155. SG_BLENDFACTOR_ONE_MINUS_DST_ALPHA,
  2156. SG_BLENDFACTOR_SRC_ALPHA_SATURATED,
  2157. SG_BLENDFACTOR_BLEND_COLOR,
  2158. SG_BLENDFACTOR_ONE_MINUS_BLEND_COLOR,
  2159. SG_BLENDFACTOR_BLEND_ALPHA,
  2160. SG_BLENDFACTOR_ONE_MINUS_BLEND_ALPHA,
  2161. _SG_BLENDFACTOR_NUM,
  2162. _SG_BLENDFACTOR_FORCE_U32 = 0x7FFFFFFF
  2163. } sg_blend_factor;
  2164. /*
  2165. sg_blend_op
  2166. Describes how the source and destination values are combined in the
  2167. fragment blending operation. It is used in the following struct items
  2168. when creating a pipeline object:
  2169. sg_pipeline_desc
  2170. .colors[i]
  2171. .blend
  2172. .op_rgb
  2173. .op_alpha
  2174. The default value is SG_BLENDOP_ADD.
  2175. */
  2176. typedef enum sg_blend_op {
  2177. _SG_BLENDOP_DEFAULT, // value 0 reserved for default-init
  2178. SG_BLENDOP_ADD,
  2179. SG_BLENDOP_SUBTRACT,
  2180. SG_BLENDOP_REVERSE_SUBTRACT,
  2181. SG_BLENDOP_MIN,
  2182. SG_BLENDOP_MAX,
  2183. _SG_BLENDOP_NUM,
  2184. _SG_BLENDOP_FORCE_U32 = 0x7FFFFFFF
  2185. } sg_blend_op;
  2186. /*
  2187. sg_color_mask
  2188. Selects the active color channels when writing a fragment color to the
  2189. framebuffer. This is used in the members
  2190. sg_pipeline_desc.colors[i].write_mask when creating a pipeline object.
  2191. The default colormask is SG_COLORMASK_RGBA (write all colors channels)
  2192. NOTE: since the color mask value 0 is reserved for the default value
  2193. (SG_COLORMASK_RGBA), use SG_COLORMASK_NONE if all color channels
  2194. should be disabled.
  2195. */
  2196. typedef enum sg_color_mask {
  2197. _SG_COLORMASK_DEFAULT = 0, // value 0 reserved for default-init
  2198. SG_COLORMASK_NONE = 0x10, // special value for 'all channels disabled
  2199. SG_COLORMASK_R = 0x1,
  2200. SG_COLORMASK_G = 0x2,
  2201. SG_COLORMASK_RG = 0x3,
  2202. SG_COLORMASK_B = 0x4,
  2203. SG_COLORMASK_RB = 0x5,
  2204. SG_COLORMASK_GB = 0x6,
  2205. SG_COLORMASK_RGB = 0x7,
  2206. SG_COLORMASK_A = 0x8,
  2207. SG_COLORMASK_RA = 0x9,
  2208. SG_COLORMASK_GA = 0xA,
  2209. SG_COLORMASK_RGA = 0xB,
  2210. SG_COLORMASK_BA = 0xC,
  2211. SG_COLORMASK_RBA = 0xD,
  2212. SG_COLORMASK_GBA = 0xE,
  2213. SG_COLORMASK_RGBA = 0xF,
  2214. _SG_COLORMASK_FORCE_U32 = 0x7FFFFFFF
  2215. } sg_color_mask;
  2216. /*
  2217. sg_load_action
  2218. Defines the load action that should be performed at the start of a render pass:
  2219. SG_LOADACTION_CLEAR: clear the render target
  2220. SG_LOADACTION_LOAD: load the previous content of the render target
  2221. SG_LOADACTION_DONTCARE: leave the render target in an undefined state
  2222. This is used in the sg_pass_action structure.
  2223. The default load action for all pass attachments is SG_LOADACTION_CLEAR,
  2224. with the values rgba = { 0.5f, 0.5f, 0.5f, 1.0f }, depth=1.0f and stencil=0.
  2225. If you want to override the default behaviour, it is important to not
  2226. only set the clear color, but the 'action' field as well (as long as this
  2227. is _SG_LOADACTION_DEFAULT, the value fields will be ignored).
  2228. */
  2229. typedef enum sg_load_action {
  2230. _SG_LOADACTION_DEFAULT,
  2231. SG_LOADACTION_CLEAR,
  2232. SG_LOADACTION_LOAD,
  2233. SG_LOADACTION_DONTCARE,
  2234. _SG_LOADACTION_FORCE_U32 = 0x7FFFFFFF
  2235. } sg_load_action;
  2236. /*
  2237. sg_store_action
  2238. Defines the store action that should be performed at the end of a render pass:
  2239. SG_STOREACTION_STORE: store the rendered content to the color attachment image
  2240. SG_STOREACTION_DONTCARE: allows the GPU to discard the rendered content
  2241. */
  2242. typedef enum sg_store_action {
  2243. _SG_STOREACTION_DEFAULT,
  2244. SG_STOREACTION_STORE,
  2245. SG_STOREACTION_DONTCARE,
  2246. _SG_STOREACTION_FORCE_U32 = 0x7FFFFFFF
  2247. } sg_store_action;
  2248. /*
  2249. sg_pass_action
  2250. The sg_pass_action struct defines the actions to be performed
  2251. at the start and end of a render pass.
  2252. - at the start of the pass: whether the render attachments should be cleared,
  2253. loaded with their previous content, or start in an undefined state
  2254. - for clear operations: the clear value (color, depth, or stencil values)
  2255. - at the end of the pass: whether the rendering result should be
  2256. stored back into the render attachment or discarded
  2257. */
  2258. typedef struct sg_color_attachment_action {
  2259. sg_load_action load_action; // default: SG_LOADACTION_CLEAR
  2260. sg_store_action store_action; // default: SG_STOREACTION_STORE
  2261. sg_color clear_value; // default: { 0.5f, 0.5f, 0.5f, 1.0f }
  2262. } sg_color_attachment_action;
  2263. typedef struct sg_depth_attachment_action {
  2264. sg_load_action load_action; // default: SG_LOADACTION_CLEAR
  2265. sg_store_action store_action; // default: SG_STOREACTION_DONTCARE
  2266. float clear_value; // default: 1.0
  2267. } sg_depth_attachment_action;
  2268. typedef struct sg_stencil_attachment_action {
  2269. sg_load_action load_action; // default: SG_LOADACTION_CLEAR
  2270. sg_store_action store_action; // default: SG_STOREACTION_DONTCARE
  2271. uint8_t clear_value; // default: 0
  2272. } sg_stencil_attachment_action;
  2273. typedef struct sg_pass_action {
  2274. sg_color_attachment_action colors[SG_MAX_COLOR_ATTACHMENTS];
  2275. sg_depth_attachment_action depth;
  2276. sg_stencil_attachment_action stencil;
  2277. } sg_pass_action;
  2278. /*
  2279. sg_swapchain
  2280. Used in sg_begin_pass() to provide details about an external swapchain
  2281. (pixel formats, sample count and backend-API specific render surface objects).
  2282. The following information must be provided:
  2283. - the width and height of the swapchain surfaces in number of pixels,
  2284. - the pixel format of the render- and optional msaa-resolve-surface
  2285. - the pixel format of the optional depth- or depth-stencil-surface
  2286. - the MSAA sample count for the render and depth-stencil surface
  2287. If the pixel formats and MSAA sample counts are left zero-initialized,
  2288. their defaults are taken from the sg_environment struct provided in the
  2289. sg_setup() call.
  2290. The width and height *must* be > 0.
  2291. Additionally the following backend API specific objects must be passed in
  2292. as 'type erased' void pointers:
  2293. GL:
  2294. - on all GL backends, a GL framebuffer object must be provided. This
  2295. can be zero for the default framebuffer.
  2296. D3D11:
  2297. - an ID3D11RenderTargetView for the rendering surface, without
  2298. MSAA rendering this surface will also be displayed
  2299. - an optional ID3D11DepthStencilView for the depth- or depth/stencil
  2300. buffer surface
  2301. - when MSAA rendering is used, another ID3D11RenderTargetView
  2302. which serves as MSAA resolve target and will be displayed
  2303. WebGPU (same as D3D11, except different types)
  2304. - a WGPUTextureView for the rendering surface, without
  2305. MSAA rendering this surface will also be displayed
  2306. - an optional WGPUTextureView for the depth- or depth/stencil
  2307. buffer surface
  2308. - when MSAA rendering is used, another WGPUTextureView
  2309. which serves as MSAA resolve target and will be displayed
  2310. Metal (NOTE that the roles of provided surfaces is slightly different
  2311. than on D3D11 or WebGPU in case of MSAA vs non-MSAA rendering):
  2312. - A current CAMetalDrawable (NOT an MTLDrawable!) which will be presented.
  2313. This will either be rendered to directly (if no MSAA is used), or serve
  2314. as MSAA-resolve target.
  2315. - an optional MTLTexture for the depth- or depth-stencil buffer
  2316. - an optional multisampled MTLTexture which serves as intermediate
  2317. rendering surface which will then be resolved into the
  2318. CAMetalDrawable.
  2319. NOTE that for Metal you must use an ObjC __bridge cast to
  2320. properly tunnel the ObjC object id through a C void*, e.g.:
  2321. swapchain.metal.current_drawable = (__bridge const void*) [mtkView currentDrawable];
  2322. On all other backends you shouldn't need to mess with the reference count.
  2323. It's a good practice to write a helper function which returns an initialized
  2324. sg_swapchain structs, which can then be plugged directly into
  2325. sg_pass.swapchain. Look at the function sglue_swapchain() in the sokol_glue.h
  2326. as an example.
  2327. */
  2328. typedef struct sg_metal_swapchain {
  2329. const void* current_drawable; // CAMetalDrawable (NOT MTLDrawable!!!)
  2330. const void* depth_stencil_texture; // MTLTexture
  2331. const void* msaa_color_texture; // MTLTexture
  2332. } sg_metal_swapchain;
  2333. typedef struct sg_d3d11_swapchain {
  2334. const void* render_view; // ID3D11RenderTargetView
  2335. const void* resolve_view; // ID3D11RenderTargetView
  2336. const void* depth_stencil_view; // ID3D11DepthStencilView
  2337. } sg_d3d11_swapchain;
  2338. typedef struct sg_wgpu_swapchain {
  2339. const void* render_view; // WGPUTextureView
  2340. const void* resolve_view; // WGPUTextureView
  2341. const void* depth_stencil_view; // WGPUTextureView
  2342. } sg_wgpu_swapchain;
  2343. typedef struct sg_gl_swapchain {
  2344. uint32_t framebuffer; // GL framebuffer object
  2345. } sg_gl_swapchain;
  2346. typedef struct sg_swapchain {
  2347. int width;
  2348. int height;
  2349. int sample_count;
  2350. sg_pixel_format color_format;
  2351. sg_pixel_format depth_format;
  2352. sg_metal_swapchain metal;
  2353. sg_d3d11_swapchain d3d11;
  2354. sg_wgpu_swapchain wgpu;
  2355. sg_gl_swapchain gl;
  2356. } sg_swapchain;
  2357. /*
  2358. sg_pass
  2359. The sg_pass structure is passed as argument into the sg_begin_pass()
  2360. function.
  2361. For a swapchain render pass, provide an sg_pass_action and sg_swapchain
  2362. struct (for instance via the sglue_swapchain() helper function from
  2363. sokol_glue.h):
  2364. sg_begin_pass(&(sg_pass){
  2365. .action = { ... },
  2366. .swapchain = sglue_swapchain(),
  2367. });
  2368. For an offscreen render pass, provide an sg_pass_action struct and
  2369. an sg_attachments handle:
  2370. sg_begin_pass(&(sg_pass){
  2371. .action = { ... },
  2372. .attachments = attachments,
  2373. });
  2374. You can also omit the .action object to get default pass action behaviour
  2375. (clear to color=grey, depth=1 and stencil=0).
  2376. For a compute pass, just set the sg_pass.compute boolean to true:
  2377. sg_begin_pass(&(sg_pass){ .compute = true });
  2378. */
  2379. typedef struct sg_pass {
  2380. uint32_t _start_canary;
  2381. bool compute;
  2382. sg_pass_action action;
  2383. sg_attachments attachments;
  2384. sg_swapchain swapchain;
  2385. const char* label;
  2386. uint32_t _end_canary;
  2387. } sg_pass;
  2388. /*
  2389. sg_bindings
  2390. The sg_bindings structure defines the buffers, images and
  2391. samplers resource bindings for the next draw call.
  2392. To update the resource bindings, call sg_apply_bindings() with
  2393. a pointer to a populated sg_bindings struct. Note that
  2394. sg_apply_bindings() must be called after sg_apply_pipeline()
  2395. and that bindings are not preserved across sg_apply_pipeline()
  2396. calls, even when the new pipeline uses the same 'bindings layout'.
  2397. A resource binding struct contains:
  2398. - 1..N vertex buffers
  2399. - 0..N vertex buffer offsets
  2400. - 0..1 index buffers
  2401. - 0..1 index buffer offsets
  2402. - 0..N images
  2403. - 0..N samplers
  2404. - 0..N storage buffers
  2405. Where 'N' is defined in the following constants:
  2406. - SG_MAX_VERTEXBUFFER_BINDSLOTS
  2407. - SG_MAX_IMAGE_BINDLOTS
  2408. - SG_MAX_SAMPLER_BINDSLOTS
  2409. - SG_MAX_STORAGEBUFFER_BINDGLOTS
  2410. Note that inside compute passes vertex- and index-buffer-bindings are
  2411. disallowed.
  2412. When using sokol-shdc for shader authoring, the `layout(binding=N)`
  2413. annotation in the shader code directly maps to the slot index for that
  2414. resource type in the bindings struct, for instance the following vertex-
  2415. and fragment-shader interface for sokol-shdc:
  2416. @vs vs
  2417. layout(binding=0) uniform vs_params { ... };
  2418. layout(binding=0) readonly buffer ssbo { ... };
  2419. layout(binding=0) uniform texture2D vs_tex;
  2420. layout(binding=0) uniform sampler vs_smp;
  2421. ...
  2422. @end
  2423. @fs fs
  2424. layout(binding=1) uniform fs_params { ... };
  2425. layout(binding=1) uniform texture2D fs_tex;
  2426. layout(binding=1) uniform sampler fs_smp;
  2427. ...
  2428. @end
  2429. ...would map to the following sg_bindings struct:
  2430. const sg_bindings bnd = {
  2431. .vertex_buffers[0] = ...,
  2432. .images[0] = vs_tex,
  2433. .images[1] = fs_tex,
  2434. .samplers[0] = vs_smp,
  2435. .samplers[1] = fs_smp,
  2436. .storage_buffers[0] = ssbo,
  2437. };
  2438. ...alternatively you can use code-generated slot indices:
  2439. const sg_bindings bnd = {
  2440. .vertex_buffers[0] = ...,
  2441. .images[IMG_vs_tex] = vs_tex,
  2442. .images[IMG_fs_tex] = fs_tex,
  2443. .samplers[SMP_vs_smp] = vs_smp,
  2444. .samplers[SMP_fs_smp] = fs_smp,
  2445. .storage_buffers[SBUF_ssbo] = ssbo,
  2446. };
  2447. Resource bindslots for a specific shader/pipeline may have gaps, and an
  2448. sg_bindings struct may have populated bind slots which are not used by a
  2449. specific shader. This allows to use the same sg_bindings struct across
  2450. different shader variants.
  2451. When not using sokol-shdc, the bindslot indices in the sg_bindings
  2452. struct need to match the per-resource reflection info slot indices
  2453. in the sg_shader_desc struct (for details about that see the
  2454. sg_shader_desc struct documentation).
  2455. The optional buffer offsets can be used to put different unrelated
  2456. chunks of vertex- and/or index-data into the same buffer objects.
  2457. */
  2458. typedef struct sg_bindings {
  2459. uint32_t _start_canary;
  2460. sg_buffer vertex_buffers[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  2461. int vertex_buffer_offsets[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  2462. sg_buffer index_buffer;
  2463. int index_buffer_offset;
  2464. sg_image images[SG_MAX_IMAGE_BINDSLOTS];
  2465. sg_sampler samplers[SG_MAX_SAMPLER_BINDSLOTS];
  2466. sg_buffer storage_buffers[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  2467. uint32_t _end_canary;
  2468. } sg_bindings;
  2469. /*
  2470. sg_buffer_usage
  2471. Describes how a buffer object is going to be used:
  2472. .vertex_buffer (default: true)
  2473. the buffer will bound as vertex buffer via sg_bindings.vertex_buffers[]
  2474. .index_buffer (default: false)
  2475. the buffer will bound as index buffer via sg_bindings.index_buffer
  2476. .storage_buffer (default: false)
  2477. the buffer will bound as storage buffer via sg_bindings.storage_buffers[]
  2478. .immutable (default: true)
  2479. the buffer content will never be updated from the CPU side (but
  2480. may be written to by a compute shader)
  2481. .dynamic_update (default: false)
  2482. the buffer content will be infrequently updated from the CPU side
  2483. .stream_upate (default: false)
  2484. the buffer content will be updated each frame from the CPU side
  2485. */
  2486. typedef struct sg_buffer_usage {
  2487. bool vertex_buffer;
  2488. bool index_buffer;
  2489. bool storage_buffer;
  2490. bool immutable;
  2491. bool dynamic_update;
  2492. bool stream_update;
  2493. } sg_buffer_usage;
  2494. /*
  2495. sg_buffer_desc
  2496. Creation parameters for sg_buffer objects, used in the sg_make_buffer() call.
  2497. The default configuration is:
  2498. .size: 0 (*must* be >0 for buffers without data)
  2499. .usage .vertex_buffer = true, .immutable = true
  2500. .data.ptr 0 (*must* be valid for immutable buffers without storage buffer usage)
  2501. .data.size 0 (*must* be > 0 for immutable buffers without storage buffer usage)
  2502. .label 0 (optional string label)
  2503. For immutable buffers which are initialized with initial data,
  2504. keep the .size item zero-initialized, and set the size together with the
  2505. pointer to the initial data in the .data item.
  2506. For immutable or mutable buffers without initial data, keep the .data item
  2507. zero-initialized, and set the buffer size in the .size item instead.
  2508. You can also set both size values, but currently both size values must
  2509. be identical (this may change in the future when the dynamic resource
  2510. management may become more flexible).
  2511. NOTE: Immutable buffers without storage-buffer-usage *must* be created
  2512. with initial content, this restriction doesn't apply to storage buffer usage,
  2513. because storage buffers may also get their initial content by running
  2514. a compute shader on them.
  2515. NOTE: Buffers without initial data will have undefined content, e.g.
  2516. do *not* expect the buffer to be zero-initialized!
  2517. ADVANCED TOPIC: Injecting native 3D-API buffers:
  2518. The following struct members allow to inject your own GL, Metal
  2519. or D3D11 buffers into sokol_gfx:
  2520. .gl_buffers[SG_NUM_INFLIGHT_FRAMES]
  2521. .mtl_buffers[SG_NUM_INFLIGHT_FRAMES]
  2522. .d3d11_buffer
  2523. You must still provide all other struct items except the .data item, and
  2524. these must match the creation parameters of the native buffers you provide.
  2525. For sg_buffer_desc.usage.immutable buffers, only provide a single native
  2526. 3D-API buffer, otherwise you need to provide SG_NUM_INFLIGHT_FRAMES buffers
  2527. (only for GL and Metal, not D3D11). Providing multiple buffers for GL and
  2528. Metal is necessary because sokol_gfx will rotate through them when calling
  2529. sg_update_buffer() to prevent lock-stalls.
  2530. Note that it is expected that immutable injected buffer have already been
  2531. initialized with content, and the .content member must be 0!
  2532. Also you need to call sg_reset_state_cache() after calling native 3D-API
  2533. functions, and before calling any sokol_gfx function.
  2534. */
  2535. typedef struct sg_buffer_desc {
  2536. uint32_t _start_canary;
  2537. size_t size;
  2538. sg_buffer_usage usage;
  2539. sg_range data;
  2540. const char* label;
  2541. // optionally inject backend-specific resources
  2542. uint32_t gl_buffers[SG_NUM_INFLIGHT_FRAMES];
  2543. const void* mtl_buffers[SG_NUM_INFLIGHT_FRAMES];
  2544. const void* d3d11_buffer;
  2545. const void* wgpu_buffer;
  2546. uint32_t _end_canary;
  2547. } sg_buffer_desc;
  2548. /*
  2549. sg_image_usage
  2550. Describes how the image object is going to be used:
  2551. .render_attachment (default: false)
  2552. the image object is used as color-, resolve- or depth-stencil-
  2553. attachment in a render pass
  2554. .storage_attachment (default: false)
  2555. the image object is used as storage-attachment in a
  2556. compute pass (to be written to by compute shaders)
  2557. .immutable (default: true)
  2558. the image content cannot be updated from the CPU side
  2559. (but may be updated by the GPU in a render- or compute-pass)
  2560. .dynamic_update (default: false)
  2561. the image content is updated infrequently by the CPU
  2562. .stream_update (default: false)
  2563. the image content is updated each frame by the CPU via
  2564. Note that the usage as texture binding is implicit and always allowed.
  2565. */
  2566. typedef struct sg_image_usage {
  2567. bool render_attachment;
  2568. bool storage_attachment;
  2569. bool immutable;
  2570. bool dynamic_update;
  2571. bool stream_update;
  2572. } sg_image_usage;
  2573. /*
  2574. sg_image_data
  2575. Defines the content of an image through a 2D array of sg_range structs.
  2576. The first array dimension is the cubemap face, and the second array
  2577. dimension the mipmap level.
  2578. */
  2579. typedef struct sg_image_data {
  2580. sg_range subimage[SG_CUBEFACE_NUM][SG_MAX_MIPMAPS];
  2581. } sg_image_data;
  2582. /*
  2583. sg_image_desc
  2584. Creation parameters for sg_image objects, used in the sg_make_image() call.
  2585. The default configuration is:
  2586. .type SG_IMAGETYPE_2D
  2587. .usage .immutable = true
  2588. .width 0 (must be set to >0)
  2589. .height 0 (must be set to >0)
  2590. .num_slices 1 (3D textures: depth; array textures: number of layers)
  2591. .num_mipmaps 1
  2592. .pixel_format SG_PIXELFORMAT_RGBA8 for textures, or sg_desc.environment.defaults.color_format for render targets
  2593. .sample_count 1 for textures, or sg_desc.environment.defaults.sample_count for render targets
  2594. .data an sg_image_data struct to define the initial content
  2595. .label 0 (optional string label for trace hooks)
  2596. Q: Why is the default sample_count for render targets identical with the
  2597. "default sample count" from sg_desc.environment.defaults.sample_count?
  2598. A: So that it matches the default sample count in pipeline objects. Even
  2599. though it is a bit strange/confusing that offscreen render targets by default
  2600. get the same sample count as 'default swapchains', but it's better that
  2601. an offscreen render target created with default parameters matches
  2602. a pipeline object created with default parameters.
  2603. NOTE:
  2604. Regular (non-attachment) images with usage.immutable must be fully initialized by
  2605. providing a valid .data member which points to initialization data.
  2606. Images with usage.render_attachment or usage.storage_attachment must
  2607. *not* be created with initial content. Be aware that the initial
  2608. content of render- and storage-attachment images is undefined.
  2609. ADVANCED TOPIC: Injecting native 3D-API textures:
  2610. The following struct members allow to inject your own GL, Metal or D3D11
  2611. textures into sokol_gfx:
  2612. .gl_textures[SG_NUM_INFLIGHT_FRAMES]
  2613. .mtl_textures[SG_NUM_INFLIGHT_FRAMES]
  2614. .d3d11_texture
  2615. .d3d11_shader_resource_view
  2616. .wgpu_texture
  2617. .wgpu_texture_view
  2618. For GL, you can also specify the texture target or leave it empty to use
  2619. the default texture target for the image type (GL_TEXTURE_2D for
  2620. SG_IMAGETYPE_2D etc)
  2621. For D3D11 and WebGPU, either only provide a texture, or both a texture and
  2622. shader-resource-view / texture-view object. If you want to use access the
  2623. injected texture in a shader you *must* provide a shader-resource-view.
  2624. The same rules apply as for injecting native buffers (see sg_buffer_desc
  2625. documentation for more details).
  2626. */
  2627. typedef struct sg_image_desc {
  2628. uint32_t _start_canary;
  2629. sg_image_type type;
  2630. sg_image_usage usage;
  2631. int width;
  2632. int height;
  2633. int num_slices;
  2634. int num_mipmaps;
  2635. sg_pixel_format pixel_format;
  2636. int sample_count;
  2637. sg_image_data data;
  2638. const char* label;
  2639. // optionally inject backend-specific resources
  2640. uint32_t gl_textures[SG_NUM_INFLIGHT_FRAMES];
  2641. uint32_t gl_texture_target;
  2642. const void* mtl_textures[SG_NUM_INFLIGHT_FRAMES];
  2643. const void* d3d11_texture;
  2644. const void* d3d11_shader_resource_view;
  2645. const void* wgpu_texture;
  2646. const void* wgpu_texture_view;
  2647. uint32_t _end_canary;
  2648. } sg_image_desc;
  2649. /*
  2650. sg_sampler_desc
  2651. Creation parameters for sg_sampler objects, used in the sg_make_sampler() call
  2652. .min_filter: SG_FILTER_NEAREST
  2653. .mag_filter: SG_FILTER_NEAREST
  2654. .mipmap_filter SG_FILTER_NEAREST
  2655. .wrap_u: SG_WRAP_REPEAT
  2656. .wrap_v: SG_WRAP_REPEAT
  2657. .wrap_w: SG_WRAP_REPEAT (only SG_IMAGETYPE_3D)
  2658. .min_lod 0.0f
  2659. .max_lod FLT_MAX
  2660. .border_color SG_BORDERCOLOR_OPAQUE_BLACK
  2661. .compare SG_COMPAREFUNC_NEVER
  2662. .max_anisotropy 1 (must be 1..16)
  2663. */
  2664. typedef struct sg_sampler_desc {
  2665. uint32_t _start_canary;
  2666. sg_filter min_filter;
  2667. sg_filter mag_filter;
  2668. sg_filter mipmap_filter;
  2669. sg_wrap wrap_u;
  2670. sg_wrap wrap_v;
  2671. sg_wrap wrap_w;
  2672. float min_lod;
  2673. float max_lod;
  2674. sg_border_color border_color;
  2675. sg_compare_func compare;
  2676. uint32_t max_anisotropy;
  2677. const char* label;
  2678. // optionally inject backend-specific resources
  2679. uint32_t gl_sampler;
  2680. const void* mtl_sampler;
  2681. const void* d3d11_sampler;
  2682. const void* wgpu_sampler;
  2683. uint32_t _end_canary;
  2684. } sg_sampler_desc;
  2685. /*
  2686. sg_shader_desc
  2687. Used as parameter of sg_make_shader() to create a shader object which
  2688. communicates shader source or bytecode and shader interface
  2689. reflection information to sokol-gfx.
  2690. If you use sokol-shdc you can ignore the following information since
  2691. the sg_shader_desc struct will be code-generated.
  2692. Otherwise you need to provide the following information to the
  2693. sg_make_shader() call:
  2694. - a vertex- and fragment-shader function:
  2695. - the shader source or bytecode
  2696. - an optional entry point name
  2697. - for D3D11: an optional compile target when source code is provided
  2698. (the defaults are "vs_4_0" and "ps_4_0")
  2699. - ...or alternatively, a compute function:
  2700. - the shader source or bytecode
  2701. - an optional entry point name
  2702. - for D3D11: an optional compile target when source code is provided
  2703. (the default is "cs_5_0")
  2704. - vertex attributes required by some backends (not for compute shaders):
  2705. - the vertex attribute base type (undefined, float, signed int, unsigned int),
  2706. this information is only used in the validation layer to check that the
  2707. pipeline object vertex formats are compatible with the input vertex attribute
  2708. type used in the vertex shader. NOTE that the default base type
  2709. 'undefined' skips the validation layer check.
  2710. - for the GL backend: optional vertex attribute names used for name lookup
  2711. - for the D3D11 backend: semantic names and indices
  2712. - only for compute shaders on the Metal backend:
  2713. - the workgroup size aka 'threads per thread-group'
  2714. In other 3D APIs this is declared in the shader code:
  2715. - GLSL: `layout(local_size_x=x, local_size_y=y, local_size_y=z) in;`
  2716. - HLSL: `[numthreads(x, y, z)]`
  2717. - WGSL: `@workgroup_size(x, y, z)`
  2718. ...but in Metal the workgroup size is declared on the CPU side
  2719. - reflection information for each uniform block binding used by the shader:
  2720. - the shader stage the uniform block appears in (SG_SHADERSTAGE_*)
  2721. - the size in bytes of the uniform block
  2722. - backend-specific bindslots:
  2723. - HLSL: the constant buffer register `register(b0..7)`
  2724. - MSL: the buffer attribute `[[buffer(0..7)]]`
  2725. - WGSL: the binding in `@group(0) @binding(0..15)`
  2726. - GLSL only: a description of the uniform block interior
  2727. - the memory layout standard (SG_UNIFORMLAYOUT_*)
  2728. - for each member in the uniform block:
  2729. - the member type (SG_UNIFORM_*)
  2730. - if the member is an array, the array count
  2731. - the member name
  2732. - reflection information for each texture binding used by the shader:
  2733. - the shader stage the texture appears in (SG_SHADERSTAGE_*)
  2734. - the image type (SG_IMAGETYPE_*)
  2735. - the image-sample type (SG_IMAGESAMPLETYPE_*)
  2736. - whether the texture is multisampled
  2737. - backend specific bindslots:
  2738. - HLSL: the texture register `register(t0..23)`
  2739. - MSL: the texture attribute `[[texture(0..19)]]`
  2740. - WGSL: the binding in `@group(1) @binding(0..127)`
  2741. - reflection information for each sampler used by the shader:
  2742. - the shader stage the sampler appears in (SG_SHADERSTAGE_*)
  2743. - the sampler type (SG_SAMPLERTYPE_*)
  2744. - backend specific bindslots:
  2745. - HLSL: the sampler register `register(s0..15)`
  2746. - MSL: the sampler attribute `[[sampler(0..15)]]`
  2747. - WGSL: the binding in `@group(0) @binding(0..127)`
  2748. - reflection information for each storage buffer binding used by the shader:
  2749. - the shader stage the storage buffer appears in (SG_SHADERSTAGE_*)
  2750. - whether the storage buffer is readonly
  2751. - backend specific bindslots:
  2752. - HLSL:
  2753. - for readonly storage buffer bindings: `register(t0..23)`
  2754. - for read/write storage buffer bindings: `register(u0..11)`
  2755. - MSL: the buffer attribute `[[buffer(8..15)]]`
  2756. - WGSL: the binding in `@group(1) @binding(0..127)`
  2757. - GL: the binding in `layout(binding=0..7)`
  2758. - reflection information for each storage image binding used by the shader:
  2759. - the shader stage (*must* be SG_SHADERSTAGE_COMPUTE)
  2760. - whether the storage image is writeonly or readwrite (for readonly
  2761. access use a regular texture binding instead)
  2762. - the image type expected by the shader (SG_IMAGETYPE_*)
  2763. - the access pixel format expected by the shader (SG_PIXELFORMAT_*),
  2764. note that only a subset of pixel formats is allowed for storage image
  2765. bindings
  2766. - backend specific bindslots:
  2767. - HLSL: the UAV register `register(u0..u11)`
  2768. - MSL: the texture attribute `[[texture(0..19)]]`
  2769. - WGSL: the binding in `@group(2) @binding(0..3)`
  2770. - GLSL: the binding in `layout(binding=0..3, [access_format])`
  2771. - reflection information for each combined image-sampler object
  2772. used by the shader:
  2773. - the shader stage (SG_SHADERSTAGE_*)
  2774. - the texture's array index in the sg_shader_desc.images[] array
  2775. - the sampler's array index in the sg_shader_desc.samplers[] array
  2776. - GLSL only: the name of the combined image-sampler object
  2777. The number and order of items in the sg_shader_desc.attrs[]
  2778. array corresponds to the items in sg_pipeline_desc.layout.attrs.
  2779. - sg_shader_desc.attrs[N] => sg_pipeline_desc.layout.attrs[N]
  2780. NOTE that vertex attribute indices currently cannot have gaps.
  2781. The items index in the sg_shader_desc.uniform_blocks[] array corresponds
  2782. to the ub_slot arg in sg_apply_uniforms():
  2783. - sg_shader_desc.uniform_blocks[N] => sg_apply_uniforms(N, ...)
  2784. The items in the shader_desc images, samplers and storage_buffers
  2785. arrays correspond to the same array items in the sg_bindings struct:
  2786. - sg_shader_desc.images[N] => sg_bindings.images[N]
  2787. - sg_shader_desc.samplers[N] => sg_bindings.samplers[N]
  2788. - sg_shader_desc.storage_buffers[N] => sg_bindings.storage_buffers[N]
  2789. For all GL backends, shader source-code must be provided. For D3D11 and Metal,
  2790. either shader source-code or byte-code can be provided.
  2791. NOTE that the uniform block, image, sampler, storage_buffer and
  2792. storage_image arrays may have gaps. This allows to use the same sg_bindings
  2793. struct for different related shader variants.
  2794. For D3D11, if source code is provided, the d3dcompiler_47.dll will be loaded
  2795. on demand. If this fails, shader creation will fail. When compiling HLSL
  2796. source code, you can provide an optional target string via
  2797. sg_shader_stage_desc.d3d11_target, the default target is "vs_4_0" for the
  2798. vertex shader stage and "ps_4_0" for the pixel shader stage.
  2799. You may optionally provide the file path to enable the default #include handler
  2800. behavior when compiling source code.
  2801. */
  2802. typedef enum sg_shader_stage {
  2803. SG_SHADERSTAGE_NONE,
  2804. SG_SHADERSTAGE_VERTEX,
  2805. SG_SHADERSTAGE_FRAGMENT,
  2806. SG_SHADERSTAGE_COMPUTE,
  2807. _SG_SHADERSTAGE_FORCE_U32 = 0x7FFFFFFF,
  2808. } sg_shader_stage;
  2809. typedef struct sg_shader_function {
  2810. const char* source;
  2811. sg_range bytecode;
  2812. const char* entry;
  2813. const char* d3d11_target; // default: "vs_4_0" or "ps_4_0"
  2814. const char* d3d11_filepath;
  2815. } sg_shader_function;
  2816. typedef enum sg_shader_attr_base_type {
  2817. SG_SHADERATTRBASETYPE_UNDEFINED,
  2818. SG_SHADERATTRBASETYPE_FLOAT,
  2819. SG_SHADERATTRBASETYPE_SINT,
  2820. SG_SHADERATTRBASETYPE_UINT,
  2821. _SG_SHADERATTRBASETYPE_FORCE_U32 = 0x7FFFFFFF,
  2822. } sg_shader_attr_base_type;
  2823. typedef struct sg_shader_vertex_attr {
  2824. sg_shader_attr_base_type base_type; // default: UNDEFINED (disables validation)
  2825. const char* glsl_name; // [optional] GLSL attribute name
  2826. const char* hlsl_sem_name; // HLSL semantic name
  2827. uint8_t hlsl_sem_index; // HLSL semantic index
  2828. } sg_shader_vertex_attr;
  2829. typedef struct sg_glsl_shader_uniform {
  2830. sg_uniform_type type;
  2831. uint16_t array_count; // 0 or 1 for scalars, >1 for arrays
  2832. const char* glsl_name; // glsl name binding is required on GL 4.1 and WebGL2
  2833. } sg_glsl_shader_uniform;
  2834. typedef struct sg_shader_uniform_block {
  2835. sg_shader_stage stage;
  2836. uint32_t size;
  2837. uint8_t hlsl_register_b_n; // HLSL register(bn)
  2838. uint8_t msl_buffer_n; // MSL [[buffer(n)]]
  2839. uint8_t wgsl_group0_binding_n; // WGSL @group(0) @binding(n)
  2840. sg_uniform_layout layout;
  2841. sg_glsl_shader_uniform glsl_uniforms[SG_MAX_UNIFORMBLOCK_MEMBERS];
  2842. } sg_shader_uniform_block;
  2843. typedef struct sg_shader_image {
  2844. sg_shader_stage stage;
  2845. sg_image_type image_type;
  2846. sg_image_sample_type sample_type;
  2847. bool multisampled;
  2848. uint8_t hlsl_register_t_n; // HLSL register(tn) bind slot
  2849. uint8_t msl_texture_n; // MSL [[texture(n)]] bind slot
  2850. uint8_t wgsl_group1_binding_n; // WGSL @group(1) @binding(n) bind slot
  2851. } sg_shader_image;
  2852. typedef struct sg_shader_sampler {
  2853. sg_shader_stage stage;
  2854. sg_sampler_type sampler_type;
  2855. uint8_t hlsl_register_s_n; // HLSL register(sn) bind slot
  2856. uint8_t msl_sampler_n; // MSL [[sampler(n)]] bind slot
  2857. uint8_t wgsl_group1_binding_n; // WGSL @group(1) @binding(n) bind slot
  2858. } sg_shader_sampler;
  2859. typedef struct sg_shader_storage_buffer {
  2860. sg_shader_stage stage;
  2861. bool readonly;
  2862. uint8_t hlsl_register_t_n; // HLSL register(tn) bind slot (for readonly access)
  2863. uint8_t hlsl_register_u_n; // HLSL register(un) bind slot (for read/write access)
  2864. uint8_t msl_buffer_n; // MSL [[buffer(n)]] bind slot
  2865. uint8_t wgsl_group1_binding_n; // WGSL @group(1) @binding(n) bind slot
  2866. uint8_t glsl_binding_n; // GLSL layout(binding=n)
  2867. } sg_shader_storage_buffer;
  2868. typedef struct sg_shader_storage_image {
  2869. sg_shader_stage stage; // must be NONE or COMPUTE
  2870. sg_image_type image_type;
  2871. sg_pixel_format access_format; // shader-access pixel format
  2872. bool writeonly; // false means read/write access
  2873. uint8_t hlsl_register_u_n; // HLSL register(un) bind slot
  2874. uint8_t msl_texture_n; // MSL [[texture(n)]] bind slot
  2875. uint8_t wgsl_group2_binding_n; // WGSL @group(2) @binding(n) bind slot
  2876. uint8_t glsl_binding_n; // GLSL layout(binding=n)
  2877. } sg_shader_storage_image;
  2878. typedef struct sg_shader_image_sampler_pair {
  2879. sg_shader_stage stage;
  2880. uint8_t image_slot;
  2881. uint8_t sampler_slot;
  2882. const char* glsl_name; // glsl name binding required because of GL 4.1 and WebGL2
  2883. } sg_shader_image_sampler_pair;
  2884. typedef struct sg_mtl_shader_threads_per_threadgroup {
  2885. int x, y, z;
  2886. } sg_mtl_shader_threads_per_threadgroup;
  2887. typedef struct sg_shader_desc {
  2888. uint32_t _start_canary;
  2889. sg_shader_function vertex_func;
  2890. sg_shader_function fragment_func;
  2891. sg_shader_function compute_func;
  2892. sg_shader_vertex_attr attrs[SG_MAX_VERTEX_ATTRIBUTES];
  2893. sg_shader_uniform_block uniform_blocks[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  2894. sg_shader_storage_buffer storage_buffers[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  2895. sg_shader_image images[SG_MAX_IMAGE_BINDSLOTS];
  2896. sg_shader_sampler samplers[SG_MAX_SAMPLER_BINDSLOTS];
  2897. sg_shader_image_sampler_pair image_sampler_pairs[SG_MAX_IMAGE_SAMPLER_PAIRS];
  2898. sg_shader_storage_image storage_images[SG_MAX_STORAGE_ATTACHMENTS];
  2899. sg_mtl_shader_threads_per_threadgroup mtl_threads_per_threadgroup;
  2900. const char* label;
  2901. uint32_t _end_canary;
  2902. } sg_shader_desc;
  2903. /*
  2904. sg_pipeline_desc
  2905. The sg_pipeline_desc struct defines all creation parameters for an
  2906. sg_pipeline object, used as argument to the sg_make_pipeline() function:
  2907. Pipeline objects come in two flavours:
  2908. - render pipelines for use in render passes
  2909. - compute pipelines for use in compute passes
  2910. A compute pipeline only requires a compute shader object but no
  2911. 'render state', while a render pipeline requires a vertex/fragment shader
  2912. object and additional render state declarations:
  2913. - the vertex layout for all input vertex buffers
  2914. - a shader object
  2915. - the 3D primitive type (points, lines, triangles, ...)
  2916. - the index type (none, 16- or 32-bit)
  2917. - all the fixed-function-pipeline state (depth-, stencil-, blend-state, etc...)
  2918. If the vertex data has no gaps between vertex components, you can omit
  2919. the .layout.buffers[].stride and layout.attrs[].offset items (leave them
  2920. default-initialized to 0), sokol-gfx will then compute the offsets and
  2921. strides from the vertex component formats (.layout.attrs[].format).
  2922. Please note that ALL vertex attribute offsets must be 0 in order for the
  2923. automatic offset computation to kick in.
  2924. Note that if you use vertex-pulling from storage buffers instead of
  2925. fixed-function vertex input you can simply omit the entire nested .layout
  2926. struct.
  2927. The default configuration is as follows:
  2928. .compute: false (must be set to true for a compute pipeline)
  2929. .shader: 0 (must be initialized with a valid sg_shader id!)
  2930. .layout:
  2931. .buffers[]: vertex buffer layouts
  2932. .stride: 0 (if no stride is given it will be computed)
  2933. .step_func SG_VERTEXSTEP_PER_VERTEX
  2934. .step_rate 1
  2935. .attrs[]: vertex attribute declarations
  2936. .buffer_index 0 the vertex buffer bind slot
  2937. .offset 0 (offsets can be omitted if the vertex layout has no gaps)
  2938. .format SG_VERTEXFORMAT_INVALID (must be initialized!)
  2939. .depth:
  2940. .pixel_format: sg_desc.context.depth_format
  2941. .compare: SG_COMPAREFUNC_ALWAYS
  2942. .write_enabled: false
  2943. .bias: 0.0f
  2944. .bias_slope_scale: 0.0f
  2945. .bias_clamp: 0.0f
  2946. .stencil:
  2947. .enabled: false
  2948. .front/back:
  2949. .compare: SG_COMPAREFUNC_ALWAYS
  2950. .fail_op: SG_STENCILOP_KEEP
  2951. .depth_fail_op: SG_STENCILOP_KEEP
  2952. .pass_op: SG_STENCILOP_KEEP
  2953. .read_mask: 0
  2954. .write_mask: 0
  2955. .ref: 0
  2956. .color_count 1
  2957. .colors[0..color_count]
  2958. .pixel_format sg_desc.context.color_format
  2959. .write_mask: SG_COLORMASK_RGBA
  2960. .blend:
  2961. .enabled: false
  2962. .src_factor_rgb: SG_BLENDFACTOR_ONE
  2963. .dst_factor_rgb: SG_BLENDFACTOR_ZERO
  2964. .op_rgb: SG_BLENDOP_ADD
  2965. .src_factor_alpha: SG_BLENDFACTOR_ONE
  2966. .dst_factor_alpha: SG_BLENDFACTOR_ZERO
  2967. .op_alpha: SG_BLENDOP_ADD
  2968. .primitive_type: SG_PRIMITIVETYPE_TRIANGLES
  2969. .index_type: SG_INDEXTYPE_NONE
  2970. .cull_mode: SG_CULLMODE_NONE
  2971. .face_winding: SG_FACEWINDING_CW
  2972. .sample_count: sg_desc.context.sample_count
  2973. .blend_color: (sg_color) { 0.0f, 0.0f, 0.0f, 0.0f }
  2974. .alpha_to_coverage_enabled: false
  2975. .label 0 (optional string label for trace hooks)
  2976. */
  2977. typedef struct sg_vertex_buffer_layout_state {
  2978. int stride;
  2979. sg_vertex_step step_func;
  2980. int step_rate;
  2981. } sg_vertex_buffer_layout_state;
  2982. typedef struct sg_vertex_attr_state {
  2983. int buffer_index;
  2984. int offset;
  2985. sg_vertex_format format;
  2986. } sg_vertex_attr_state;
  2987. typedef struct sg_vertex_layout_state {
  2988. sg_vertex_buffer_layout_state buffers[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  2989. sg_vertex_attr_state attrs[SG_MAX_VERTEX_ATTRIBUTES];
  2990. } sg_vertex_layout_state;
  2991. typedef struct sg_stencil_face_state {
  2992. sg_compare_func compare;
  2993. sg_stencil_op fail_op;
  2994. sg_stencil_op depth_fail_op;
  2995. sg_stencil_op pass_op;
  2996. } sg_stencil_face_state;
  2997. typedef struct sg_stencil_state {
  2998. bool enabled;
  2999. sg_stencil_face_state front;
  3000. sg_stencil_face_state back;
  3001. uint8_t read_mask;
  3002. uint8_t write_mask;
  3003. uint8_t ref;
  3004. } sg_stencil_state;
  3005. typedef struct sg_depth_state {
  3006. sg_pixel_format pixel_format;
  3007. sg_compare_func compare;
  3008. bool write_enabled;
  3009. float bias;
  3010. float bias_slope_scale;
  3011. float bias_clamp;
  3012. } sg_depth_state;
  3013. typedef struct sg_blend_state {
  3014. bool enabled;
  3015. sg_blend_factor src_factor_rgb;
  3016. sg_blend_factor dst_factor_rgb;
  3017. sg_blend_op op_rgb;
  3018. sg_blend_factor src_factor_alpha;
  3019. sg_blend_factor dst_factor_alpha;
  3020. sg_blend_op op_alpha;
  3021. } sg_blend_state;
  3022. typedef struct sg_color_target_state {
  3023. sg_pixel_format pixel_format;
  3024. sg_color_mask write_mask;
  3025. sg_blend_state blend;
  3026. } sg_color_target_state;
  3027. typedef struct sg_pipeline_desc {
  3028. uint32_t _start_canary;
  3029. bool compute;
  3030. sg_shader shader;
  3031. sg_vertex_layout_state layout;
  3032. sg_depth_state depth;
  3033. sg_stencil_state stencil;
  3034. int color_count;
  3035. sg_color_target_state colors[SG_MAX_COLOR_ATTACHMENTS];
  3036. sg_primitive_type primitive_type;
  3037. sg_index_type index_type;
  3038. sg_cull_mode cull_mode;
  3039. sg_face_winding face_winding;
  3040. int sample_count;
  3041. sg_color blend_color;
  3042. bool alpha_to_coverage_enabled;
  3043. const char* label;
  3044. uint32_t _end_canary;
  3045. } sg_pipeline_desc;
  3046. /*
  3047. sg_attachments_desc
  3048. Creation parameters for an sg_attachments object, used as argument to the
  3049. sg_make_attachments() function.
  3050. An attachments object bundles either bundles 'render attachments' for
  3051. a render pass, or 'storage attachments' for a compute pass which writes
  3052. to storage images.
  3053. Render attachments are:
  3054. - 0..4 color attachment images
  3055. - 0..4 msaa-resolve attachment images
  3056. - 0 or one depth-stencil attachment image
  3057. Note that all types of render attachment images must be created with
  3058. `sg_image_desc.usage.render_attachment = true`. At least one color-attachment
  3059. or depth-stencil-attachment image must be provided in a render pass
  3060. (only providing a depth-stencil-attachment is useful for depth-only passes).
  3061. Alternatively provide 1..4 storage attachment images which must be created
  3062. with `sg_image_desc.usage.storage_attachment = true`.
  3063. An sg_attachments object cannot have both render- and storage-attachments.
  3064. Each attachment definition consists of an image object, and two additional indices
  3065. describing which subimage the pass will render into: one mipmap index, and if the image
  3066. is a cubemap, array-texture or 3D-texture, the face-index, array-layer or
  3067. depth-slice.
  3068. All attachments must have the same width and height.
  3069. All color attachments and the depth-stencil attachment must have the
  3070. same sample count.
  3071. If a resolve attachment is set, an MSAA-resolve operation from the
  3072. associated color attachment image into the resolve attachment image will take
  3073. place in the sg_end_pass() function. In this case, the color attachment
  3074. must have a (sample_count>1), and the resolve attachment a
  3075. (sample_count==1). The resolve attachment also must have the same pixel
  3076. format as the color attachment.
  3077. NOTE that MSAA depth-stencil attachments cannot be msaa-resolved!
  3078. */
  3079. typedef struct sg_attachment_desc {
  3080. sg_image image;
  3081. int mip_level;
  3082. int slice; // cube texture: face; array texture: layer; 3D texture: slice
  3083. } sg_attachment_desc;
  3084. typedef struct sg_attachments_desc {
  3085. uint32_t _start_canary;
  3086. sg_attachment_desc colors[SG_MAX_COLOR_ATTACHMENTS];
  3087. sg_attachment_desc resolves[SG_MAX_COLOR_ATTACHMENTS];
  3088. sg_attachment_desc depth_stencil;
  3089. sg_attachment_desc storages[SG_MAX_STORAGE_ATTACHMENTS];
  3090. const char* label;
  3091. uint32_t _end_canary;
  3092. } sg_attachments_desc;
  3093. /*
  3094. sg_trace_hooks
  3095. Installable callback functions to keep track of the sokol-gfx calls,
  3096. this is useful for debugging, or keeping track of resource creation
  3097. and destruction.
  3098. Trace hooks are installed with sg_install_trace_hooks(), this returns
  3099. another sg_trace_hooks struct with the previous set of
  3100. trace hook function pointers. These should be invoked by the
  3101. new trace hooks to form a proper call chain.
  3102. */
  3103. typedef struct sg_trace_hooks {
  3104. void* user_data;
  3105. void (*reset_state_cache)(void* user_data);
  3106. void (*make_buffer)(const sg_buffer_desc* desc, sg_buffer result, void* user_data);
  3107. void (*make_image)(const sg_image_desc* desc, sg_image result, void* user_data);
  3108. void (*make_sampler)(const sg_sampler_desc* desc, sg_sampler result, void* user_data);
  3109. void (*make_shader)(const sg_shader_desc* desc, sg_shader result, void* user_data);
  3110. void (*make_pipeline)(const sg_pipeline_desc* desc, sg_pipeline result, void* user_data);
  3111. void (*make_attachments)(const sg_attachments_desc* desc, sg_attachments result, void* user_data);
  3112. void (*destroy_buffer)(sg_buffer buf, void* user_data);
  3113. void (*destroy_image)(sg_image img, void* user_data);
  3114. void (*destroy_sampler)(sg_sampler smp, void* user_data);
  3115. void (*destroy_shader)(sg_shader shd, void* user_data);
  3116. void (*destroy_pipeline)(sg_pipeline pip, void* user_data);
  3117. void (*destroy_attachments)(sg_attachments atts, void* user_data);
  3118. void (*update_buffer)(sg_buffer buf, const sg_range* data, void* user_data);
  3119. void (*update_image)(sg_image img, const sg_image_data* data, void* user_data);
  3120. void (*append_buffer)(sg_buffer buf, const sg_range* data, int result, void* user_data);
  3121. void (*begin_pass)(const sg_pass* pass, void* user_data);
  3122. void (*apply_viewport)(int x, int y, int width, int height, bool origin_top_left, void* user_data);
  3123. void (*apply_scissor_rect)(int x, int y, int width, int height, bool origin_top_left, void* user_data);
  3124. void (*apply_pipeline)(sg_pipeline pip, void* user_data);
  3125. void (*apply_bindings)(const sg_bindings* bindings, void* user_data);
  3126. void (*apply_uniforms)(int ub_index, const sg_range* data, void* user_data);
  3127. void (*draw)(int base_element, int num_elements, int num_instances, void* user_data);
  3128. void (*dispatch)(int num_groups_x, int num_groups_y, int num_groups_z, void* user_data);
  3129. void (*end_pass)(void* user_data);
  3130. void (*commit)(void* user_data);
  3131. void (*alloc_buffer)(sg_buffer result, void* user_data);
  3132. void (*alloc_image)(sg_image result, void* user_data);
  3133. void (*alloc_sampler)(sg_sampler result, void* user_data);
  3134. void (*alloc_shader)(sg_shader result, void* user_data);
  3135. void (*alloc_pipeline)(sg_pipeline result, void* user_data);
  3136. void (*alloc_attachments)(sg_attachments result, void* user_data);
  3137. void (*dealloc_buffer)(sg_buffer buf_id, void* user_data);
  3138. void (*dealloc_image)(sg_image img_id, void* user_data);
  3139. void (*dealloc_sampler)(sg_sampler smp_id, void* user_data);
  3140. void (*dealloc_shader)(sg_shader shd_id, void* user_data);
  3141. void (*dealloc_pipeline)(sg_pipeline pip_id, void* user_data);
  3142. void (*dealloc_attachments)(sg_attachments atts_id, void* user_data);
  3143. void (*init_buffer)(sg_buffer buf_id, const sg_buffer_desc* desc, void* user_data);
  3144. void (*init_image)(sg_image img_id, const sg_image_desc* desc, void* user_data);
  3145. void (*init_sampler)(sg_sampler smp_id, const sg_sampler_desc* desc, void* user_data);
  3146. void (*init_shader)(sg_shader shd_id, const sg_shader_desc* desc, void* user_data);
  3147. void (*init_pipeline)(sg_pipeline pip_id, const sg_pipeline_desc* desc, void* user_data);
  3148. void (*init_attachments)(sg_attachments atts_id, const sg_attachments_desc* desc, void* user_data);
  3149. void (*uninit_buffer)(sg_buffer buf_id, void* user_data);
  3150. void (*uninit_image)(sg_image img_id, void* user_data);
  3151. void (*uninit_sampler)(sg_sampler smp_id, void* user_data);
  3152. void (*uninit_shader)(sg_shader shd_id, void* user_data);
  3153. void (*uninit_pipeline)(sg_pipeline pip_id, void* user_data);
  3154. void (*uninit_attachments)(sg_attachments atts_id, void* user_data);
  3155. void (*fail_buffer)(sg_buffer buf_id, void* user_data);
  3156. void (*fail_image)(sg_image img_id, void* user_data);
  3157. void (*fail_sampler)(sg_sampler smp_id, void* user_data);
  3158. void (*fail_shader)(sg_shader shd_id, void* user_data);
  3159. void (*fail_pipeline)(sg_pipeline pip_id, void* user_data);
  3160. void (*fail_attachments)(sg_attachments atts_id, void* user_data);
  3161. void (*push_debug_group)(const char* name, void* user_data);
  3162. void (*pop_debug_group)(void* user_data);
  3163. } sg_trace_hooks;
  3164. /*
  3165. sg_buffer_info
  3166. sg_image_info
  3167. sg_sampler_info
  3168. sg_shader_info
  3169. sg_pipeline_info
  3170. sg_attachments_info
  3171. These structs contain various internal resource attributes which
  3172. might be useful for debug-inspection. Please don't rely on the
  3173. actual content of those structs too much, as they are quite closely
  3174. tied to sokol_gfx.h internals and may change more frequently than
  3175. the other public API elements.
  3176. The *_info structs are used as the return values of the following functions:
  3177. sg_query_buffer_info()
  3178. sg_query_image_info()
  3179. sg_query_sampler_info()
  3180. sg_query_shader_info()
  3181. sg_query_pipeline_info()
  3182. sg_query_attachments_info()
  3183. */
  3184. typedef struct sg_slot_info {
  3185. sg_resource_state state; // the current state of this resource slot
  3186. uint32_t res_id; // type-neutral resource if (e.g. sg_buffer.id)
  3187. uint32_t uninit_count;
  3188. } sg_slot_info;
  3189. typedef struct sg_buffer_info {
  3190. sg_slot_info slot; // resource pool slot info
  3191. uint32_t update_frame_index; // frame index of last sg_update_buffer()
  3192. uint32_t append_frame_index; // frame index of last sg_append_buffer()
  3193. int append_pos; // current position in buffer for sg_append_buffer()
  3194. bool append_overflow; // is buffer in overflow state (due to sg_append_buffer)
  3195. int num_slots; // number of renaming-slots for dynamically updated buffers
  3196. int active_slot; // currently active write-slot for dynamically updated buffers
  3197. } sg_buffer_info;
  3198. typedef struct sg_image_info {
  3199. sg_slot_info slot; // resource pool slot info
  3200. uint32_t upd_frame_index; // frame index of last sg_update_image()
  3201. int num_slots; // number of renaming-slots for dynamically updated images
  3202. int active_slot; // currently active write-slot for dynamically updated images
  3203. } sg_image_info;
  3204. typedef struct sg_sampler_info {
  3205. sg_slot_info slot; // resource pool slot info
  3206. } sg_sampler_info;
  3207. typedef struct sg_shader_info {
  3208. sg_slot_info slot; // resource pool slot info
  3209. } sg_shader_info;
  3210. typedef struct sg_pipeline_info {
  3211. sg_slot_info slot; // resource pool slot info
  3212. } sg_pipeline_info;
  3213. typedef struct sg_attachments_info {
  3214. sg_slot_info slot; // resource pool slot info
  3215. } sg_attachments_info;
  3216. /*
  3217. sg_frame_stats
  3218. Allows to track generic and backend-specific stats about a
  3219. render frame. Obtained by calling sg_query_frame_stats(). The returned
  3220. struct contains information about the *previous* frame.
  3221. */
  3222. typedef struct sg_frame_stats_gl {
  3223. uint32_t num_bind_buffer;
  3224. uint32_t num_active_texture;
  3225. uint32_t num_bind_texture;
  3226. uint32_t num_bind_sampler;
  3227. uint32_t num_use_program;
  3228. uint32_t num_render_state;
  3229. uint32_t num_vertex_attrib_pointer;
  3230. uint32_t num_vertex_attrib_divisor;
  3231. uint32_t num_enable_vertex_attrib_array;
  3232. uint32_t num_disable_vertex_attrib_array;
  3233. uint32_t num_uniform;
  3234. uint32_t num_memory_barriers;
  3235. } sg_frame_stats_gl;
  3236. typedef struct sg_frame_stats_d3d11_pass {
  3237. uint32_t num_om_set_render_targets;
  3238. uint32_t num_clear_render_target_view;
  3239. uint32_t num_clear_depth_stencil_view;
  3240. uint32_t num_resolve_subresource;
  3241. } sg_frame_stats_d3d11_pass;
  3242. typedef struct sg_frame_stats_d3d11_pipeline {
  3243. uint32_t num_rs_set_state;
  3244. uint32_t num_om_set_depth_stencil_state;
  3245. uint32_t num_om_set_blend_state;
  3246. uint32_t num_ia_set_primitive_topology;
  3247. uint32_t num_ia_set_input_layout;
  3248. uint32_t num_vs_set_shader;
  3249. uint32_t num_vs_set_constant_buffers;
  3250. uint32_t num_ps_set_shader;
  3251. uint32_t num_ps_set_constant_buffers;
  3252. uint32_t num_cs_set_shader;
  3253. uint32_t num_cs_set_constant_buffers;
  3254. } sg_frame_stats_d3d11_pipeline;
  3255. typedef struct sg_frame_stats_d3d11_bindings {
  3256. uint32_t num_ia_set_vertex_buffers;
  3257. uint32_t num_ia_set_index_buffer;
  3258. uint32_t num_vs_set_shader_resources;
  3259. uint32_t num_vs_set_samplers;
  3260. uint32_t num_ps_set_shader_resources;
  3261. uint32_t num_ps_set_samplers;
  3262. uint32_t num_cs_set_shader_resources;
  3263. uint32_t num_cs_set_samplers;
  3264. uint32_t num_cs_set_unordered_access_views;
  3265. } sg_frame_stats_d3d11_bindings;
  3266. typedef struct sg_frame_stats_d3d11_uniforms {
  3267. uint32_t num_update_subresource;
  3268. } sg_frame_stats_d3d11_uniforms;
  3269. typedef struct sg_frame_stats_d3d11_draw {
  3270. uint32_t num_draw_indexed_instanced;
  3271. uint32_t num_draw_indexed;
  3272. uint32_t num_draw_instanced;
  3273. uint32_t num_draw;
  3274. } sg_frame_stats_d3d11_draw;
  3275. typedef struct sg_frame_stats_d3d11 {
  3276. sg_frame_stats_d3d11_pass pass;
  3277. sg_frame_stats_d3d11_pipeline pipeline;
  3278. sg_frame_stats_d3d11_bindings bindings;
  3279. sg_frame_stats_d3d11_uniforms uniforms;
  3280. sg_frame_stats_d3d11_draw draw;
  3281. uint32_t num_map;
  3282. uint32_t num_unmap;
  3283. } sg_frame_stats_d3d11;
  3284. typedef struct sg_frame_stats_metal_idpool {
  3285. uint32_t num_added;
  3286. uint32_t num_released;
  3287. uint32_t num_garbage_collected;
  3288. } sg_frame_stats_metal_idpool;
  3289. typedef struct sg_frame_stats_metal_pipeline {
  3290. uint32_t num_set_blend_color;
  3291. uint32_t num_set_cull_mode;
  3292. uint32_t num_set_front_facing_winding;
  3293. uint32_t num_set_stencil_reference_value;
  3294. uint32_t num_set_depth_bias;
  3295. uint32_t num_set_render_pipeline_state;
  3296. uint32_t num_set_depth_stencil_state;
  3297. } sg_frame_stats_metal_pipeline;
  3298. typedef struct sg_frame_stats_metal_bindings {
  3299. uint32_t num_set_vertex_buffer;
  3300. uint32_t num_set_vertex_texture;
  3301. uint32_t num_set_vertex_sampler_state;
  3302. uint32_t num_set_fragment_buffer;
  3303. uint32_t num_set_fragment_texture;
  3304. uint32_t num_set_fragment_sampler_state;
  3305. uint32_t num_set_compute_buffer;
  3306. uint32_t num_set_compute_texture;
  3307. uint32_t num_set_compute_sampler_state;
  3308. } sg_frame_stats_metal_bindings;
  3309. typedef struct sg_frame_stats_metal_uniforms {
  3310. uint32_t num_set_vertex_buffer_offset;
  3311. uint32_t num_set_fragment_buffer_offset;
  3312. uint32_t num_set_compute_buffer_offset;
  3313. } sg_frame_stats_metal_uniforms;
  3314. typedef struct sg_frame_stats_metal {
  3315. sg_frame_stats_metal_idpool idpool;
  3316. sg_frame_stats_metal_pipeline pipeline;
  3317. sg_frame_stats_metal_bindings bindings;
  3318. sg_frame_stats_metal_uniforms uniforms;
  3319. } sg_frame_stats_metal;
  3320. typedef struct sg_frame_stats_wgpu_uniforms {
  3321. uint32_t num_set_bindgroup;
  3322. uint32_t size_write_buffer;
  3323. } sg_frame_stats_wgpu_uniforms;
  3324. typedef struct sg_frame_stats_wgpu_bindings {
  3325. uint32_t num_set_vertex_buffer;
  3326. uint32_t num_skip_redundant_vertex_buffer;
  3327. uint32_t num_set_index_buffer;
  3328. uint32_t num_skip_redundant_index_buffer;
  3329. uint32_t num_create_bindgroup;
  3330. uint32_t num_discard_bindgroup;
  3331. uint32_t num_set_bindgroup;
  3332. uint32_t num_skip_redundant_bindgroup;
  3333. uint32_t num_bindgroup_cache_hits;
  3334. uint32_t num_bindgroup_cache_misses;
  3335. uint32_t num_bindgroup_cache_collisions;
  3336. uint32_t num_bindgroup_cache_invalidates;
  3337. uint32_t num_bindgroup_cache_hash_vs_key_mismatch;
  3338. } sg_frame_stats_wgpu_bindings;
  3339. typedef struct sg_frame_stats_wgpu {
  3340. sg_frame_stats_wgpu_uniforms uniforms;
  3341. sg_frame_stats_wgpu_bindings bindings;
  3342. } sg_frame_stats_wgpu;
  3343. typedef struct sg_frame_stats {
  3344. uint32_t frame_index; // current frame counter, starts at 0
  3345. uint32_t num_passes;
  3346. uint32_t num_apply_viewport;
  3347. uint32_t num_apply_scissor_rect;
  3348. uint32_t num_apply_pipeline;
  3349. uint32_t num_apply_bindings;
  3350. uint32_t num_apply_uniforms;
  3351. uint32_t num_draw;
  3352. uint32_t num_dispatch;
  3353. uint32_t num_update_buffer;
  3354. uint32_t num_append_buffer;
  3355. uint32_t num_update_image;
  3356. uint32_t size_apply_uniforms;
  3357. uint32_t size_update_buffer;
  3358. uint32_t size_append_buffer;
  3359. uint32_t size_update_image;
  3360. sg_frame_stats_gl gl;
  3361. sg_frame_stats_d3d11 d3d11;
  3362. sg_frame_stats_metal metal;
  3363. sg_frame_stats_wgpu wgpu;
  3364. } sg_frame_stats;
  3365. /*
  3366. sg_log_item
  3367. An enum with a unique item for each log message, warning, error
  3368. and validation layer message. Note that these messages are only
  3369. visible when a logger function is installed in the sg_setup() call.
  3370. */
  3371. #define _SG_LOG_ITEMS \
  3372. _SG_LOGITEM_XMACRO(OK, "Ok") \
  3373. _SG_LOGITEM_XMACRO(MALLOC_FAILED, "memory allocation failed") \
  3374. _SG_LOGITEM_XMACRO(GL_TEXTURE_FORMAT_NOT_SUPPORTED, "pixel format not supported for texture (gl)") \
  3375. _SG_LOGITEM_XMACRO(GL_3D_TEXTURES_NOT_SUPPORTED, "3d textures not supported (gl)") \
  3376. _SG_LOGITEM_XMACRO(GL_ARRAY_TEXTURES_NOT_SUPPORTED, "array textures not supported (gl)") \
  3377. _SG_LOGITEM_XMACRO(GL_STORAGEBUFFER_GLSL_BINDING_OUT_OF_RANGE, "GLSL storage buffer bindslot is out of range (must be 0..7) (gl)") \
  3378. _SG_LOGITEM_XMACRO(GL_STORAGEIMAGE_GLSL_BINDING_OUT_OF_RANGE, "GLSL storage image bindslot is out of range (must be 0..3) (gl)") \
  3379. _SG_LOGITEM_XMACRO(GL_SHADER_COMPILATION_FAILED, "shader compilation failed (gl)") \
  3380. _SG_LOGITEM_XMACRO(GL_SHADER_LINKING_FAILED, "shader linking failed (gl)") \
  3381. _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") \
  3382. _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") \
  3383. _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") \
  3384. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_UNDEFINED, "framebuffer completeness check failed with GL_FRAMEBUFFER_UNDEFINED (gl)") \
  3385. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_INCOMPLETE_ATTACHMENT, "framebuffer completeness check failed with GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT (gl)") \
  3386. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MISSING_ATTACHMENT, "framebuffer completeness check failed with GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT (gl)") \
  3387. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_UNSUPPORTED, "framebuffer completeness check failed with GL_FRAMEBUFFER_UNSUPPORTED (gl)") \
  3388. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MULTISAMPLE, "framebuffer completeness check failed with GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE (gl)") \
  3389. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_UNKNOWN, "framebuffer completeness check failed (unknown reason) (gl)") \
  3390. _SG_LOGITEM_XMACRO(D3D11_CREATE_BUFFER_FAILED, "CreateBuffer() failed (d3d11)") \
  3391. _SG_LOGITEM_XMACRO(D3D11_CREATE_BUFFER_SRV_FAILED, "CreateShaderResourceView() failed for storage buffer (d3d11)") \
  3392. _SG_LOGITEM_XMACRO(D3D11_CREATE_BUFFER_UAV_FAILED, "CreateUnorderedAccessView() failed for storage buffer (d3d11)") \
  3393. _SG_LOGITEM_XMACRO(D3D11_CREATE_DEPTH_TEXTURE_UNSUPPORTED_PIXEL_FORMAT, "pixel format not supported for depth-stencil texture (d3d11)") \
  3394. _SG_LOGITEM_XMACRO(D3D11_CREATE_DEPTH_TEXTURE_FAILED, "CreateTexture2D() failed for depth-stencil texture (d3d11)") \
  3395. _SG_LOGITEM_XMACRO(D3D11_CREATE_2D_TEXTURE_UNSUPPORTED_PIXEL_FORMAT, "pixel format not supported for 2d-, cube- or array-texture (d3d11)") \
  3396. _SG_LOGITEM_XMACRO(D3D11_CREATE_2D_TEXTURE_FAILED, "CreateTexture2D() failed for 2d-, cube- or array-texture (d3d11)") \
  3397. _SG_LOGITEM_XMACRO(D3D11_CREATE_2D_SRV_FAILED, "CreateShaderResourceView() failed for 2d-, cube- or array-texture (d3d11)") \
  3398. _SG_LOGITEM_XMACRO(D3D11_CREATE_3D_TEXTURE_UNSUPPORTED_PIXEL_FORMAT, "pixel format not supported for 3D texture (d3d11)") \
  3399. _SG_LOGITEM_XMACRO(D3D11_CREATE_3D_TEXTURE_FAILED, "CreateTexture3D() failed (d3d11)") \
  3400. _SG_LOGITEM_XMACRO(D3D11_CREATE_3D_SRV_FAILED, "CreateShaderResourceView() failed for 3d texture (d3d11)") \
  3401. _SG_LOGITEM_XMACRO(D3D11_CREATE_MSAA_TEXTURE_FAILED, "CreateTexture2D() failed for MSAA render target texture (d3d11)") \
  3402. _SG_LOGITEM_XMACRO(D3D11_CREATE_SAMPLER_STATE_FAILED, "CreateSamplerState() failed (d3d11)") \
  3403. _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)") \
  3404. _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)") \
  3405. _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)") \
  3406. _SG_LOGITEM_XMACRO(D3D11_IMAGE_HLSL_REGISTER_T_OUT_OF_RANGE, "image 'hlsl_register_t_n' is out of range (must be 0..23)") \
  3407. _SG_LOGITEM_XMACRO(D3D11_SAMPLER_HLSL_REGISTER_S_OUT_OF_RANGE, "sampler 'hlsl_register_s_n' is out of rang (must be 0..15)") \
  3408. _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)") \
  3409. _SG_LOGITEM_XMACRO(D3D11_LOAD_D3DCOMPILER_47_DLL_FAILED, "loading d3dcompiler_47.dll failed (d3d11)") \
  3410. _SG_LOGITEM_XMACRO(D3D11_SHADER_COMPILATION_FAILED, "shader compilation failed (d3d11)") \
  3411. _SG_LOGITEM_XMACRO(D3D11_SHADER_COMPILATION_OUTPUT, "") \
  3412. _SG_LOGITEM_XMACRO(D3D11_CREATE_CONSTANT_BUFFER_FAILED, "CreateBuffer() failed for uniform constant buffer (d3d11)") \
  3413. _SG_LOGITEM_XMACRO(D3D11_CREATE_INPUT_LAYOUT_FAILED, "CreateInputLayout() failed (d3d11)") \
  3414. _SG_LOGITEM_XMACRO(D3D11_CREATE_RASTERIZER_STATE_FAILED, "CreateRasterizerState() failed (d3d11)") \
  3415. _SG_LOGITEM_XMACRO(D3D11_CREATE_DEPTH_STENCIL_STATE_FAILED, "CreateDepthStencilState() failed (d3d11)") \
  3416. _SG_LOGITEM_XMACRO(D3D11_CREATE_BLEND_STATE_FAILED, "CreateBlendState() failed (d3d11)") \
  3417. _SG_LOGITEM_XMACRO(D3D11_CREATE_RTV_FAILED, "CreateRenderTargetView() failed (d3d11)") \
  3418. _SG_LOGITEM_XMACRO(D3D11_CREATE_DSV_FAILED, "CreateDepthStencilView() failed (d3d11)") \
  3419. _SG_LOGITEM_XMACRO(D3D11_CREATE_UAV_FAILED, "CreateUnorderedAccessView() failed (d3d11)") \
  3420. _SG_LOGITEM_XMACRO(D3D11_MAP_FOR_UPDATE_BUFFER_FAILED, "Map() failed when updating buffer (d3d11)") \
  3421. _SG_LOGITEM_XMACRO(D3D11_MAP_FOR_APPEND_BUFFER_FAILED, "Map() failed when appending to buffer (d3d11)") \
  3422. _SG_LOGITEM_XMACRO(D3D11_MAP_FOR_UPDATE_IMAGE_FAILED, "Map() failed when updating image (d3d11)") \
  3423. _SG_LOGITEM_XMACRO(METAL_CREATE_BUFFER_FAILED, "failed to create buffer object (metal)") \
  3424. _SG_LOGITEM_XMACRO(METAL_TEXTURE_FORMAT_NOT_SUPPORTED, "pixel format not supported for texture (metal)") \
  3425. _SG_LOGITEM_XMACRO(METAL_CREATE_TEXTURE_FAILED, "failed to create texture object (metal)") \
  3426. _SG_LOGITEM_XMACRO(METAL_CREATE_SAMPLER_FAILED, "failed to create sampler object (metal)") \
  3427. _SG_LOGITEM_XMACRO(METAL_SHADER_COMPILATION_FAILED, "shader compilation failed (metal)") \
  3428. _SG_LOGITEM_XMACRO(METAL_SHADER_CREATION_FAILED, "shader creation failed (metal)") \
  3429. _SG_LOGITEM_XMACRO(METAL_SHADER_COMPILATION_OUTPUT, "") \
  3430. _SG_LOGITEM_XMACRO(METAL_SHADER_ENTRY_NOT_FOUND, "shader entry function not found (metal)") \
  3431. _SG_LOGITEM_XMACRO(METAL_UNIFORMBLOCK_MSL_BUFFER_SLOT_OUT_OF_RANGE, "uniform block 'msl_buffer_n' is out of range (must be 0..7)") \
  3432. _SG_LOGITEM_XMACRO(METAL_STORAGEBUFFER_MSL_BUFFER_SLOT_OUT_OF_RANGE, "storage buffer 'msl_buffer_n' is out of range (must be 8..15)") \
  3433. _SG_LOGITEM_XMACRO(METAL_STORAGEIMAGE_MSL_TEXTURE_SLOT_OUT_OF_RANGE, "storage image 'msl_texture_n' is out of range (must be 0..19)") \
  3434. _SG_LOGITEM_XMACRO(METAL_IMAGE_MSL_TEXTURE_SLOT_OUT_OF_RANGE, "image 'msl_texture_n' is out of range (must be 0..19)") \
  3435. _SG_LOGITEM_XMACRO(METAL_SAMPLER_MSL_SAMPLER_SLOT_OUT_OF_RANGE, "sampler 'msl_sampler_n' is out of range (must be 0..15)") \
  3436. _SG_LOGITEM_XMACRO(METAL_CREATE_CPS_FAILED, "failed to create compute pipeline state (metal)") \
  3437. _SG_LOGITEM_XMACRO(METAL_CREATE_CPS_OUTPUT, "") \
  3438. _SG_LOGITEM_XMACRO(METAL_CREATE_RPS_FAILED, "failed to create render pipeline state (metal)") \
  3439. _SG_LOGITEM_XMACRO(METAL_CREATE_RPS_OUTPUT, "") \
  3440. _SG_LOGITEM_XMACRO(METAL_CREATE_DSS_FAILED, "failed to create depth stencil state (metal)") \
  3441. _SG_LOGITEM_XMACRO(WGPU_BINDGROUPS_POOL_EXHAUSTED, "bindgroups pool exhausted (increase sg_desc.bindgroups_cache_size) (wgpu)") \
  3442. _SG_LOGITEM_XMACRO(WGPU_BINDGROUPSCACHE_SIZE_GREATER_ONE, "sg_desc.wgpu_bindgroups_cache_size must be > 1 (wgpu)") \
  3443. _SG_LOGITEM_XMACRO(WGPU_BINDGROUPSCACHE_SIZE_POW2, "sg_desc.wgpu_bindgroups_cache_size must be a power of 2 (wgpu)") \
  3444. _SG_LOGITEM_XMACRO(WGPU_CREATEBINDGROUP_FAILED, "wgpuDeviceCreateBindGroup failed") \
  3445. _SG_LOGITEM_XMACRO(WGPU_CREATE_BUFFER_FAILED, "wgpuDeviceCreateBuffer() failed") \
  3446. _SG_LOGITEM_XMACRO(WGPU_CREATE_TEXTURE_FAILED, "wgpuDeviceCreateTexture() failed") \
  3447. _SG_LOGITEM_XMACRO(WGPU_CREATE_TEXTURE_VIEW_FAILED, "wgpuTextureCreateView() failed") \
  3448. _SG_LOGITEM_XMACRO(WGPU_CREATE_SAMPLER_FAILED, "wgpuDeviceCreateSampler() failed") \
  3449. _SG_LOGITEM_XMACRO(WGPU_CREATE_SHADER_MODULE_FAILED, "wgpuDeviceCreateShaderModule() failed") \
  3450. _SG_LOGITEM_XMACRO(WGPU_SHADER_CREATE_BINDGROUP_LAYOUT_FAILED, "wgpuDeviceCreateBindGroupLayout() for shader stage failed") \
  3451. _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)") \
  3452. _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)") \
  3453. _SG_LOGITEM_XMACRO(WGPU_IMAGE_WGSL_GROUP1_BINDING_OUT_OF_RANGE, "image 'wgsl_group1_binding_n' is out of range (must be 0..127)") \
  3454. _SG_LOGITEM_XMACRO(WGPU_SAMPLER_WGSL_GROUP1_BINDING_OUT_OF_RANGE, "sampler 'wgsl_group1_binding_n' is out of range (must be 0..127)") \
  3455. _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)") \
  3456. _SG_LOGITEM_XMACRO(WGPU_CREATE_PIPELINE_LAYOUT_FAILED, "wgpuDeviceCreatePipelineLayout() failed") \
  3457. _SG_LOGITEM_XMACRO(WGPU_CREATE_RENDER_PIPELINE_FAILED, "wgpuDeviceCreateRenderPipeline() failed") \
  3458. _SG_LOGITEM_XMACRO(WGPU_CREATE_COMPUTE_PIPELINE_FAILED, "wgpuDeviceCreateComputePipeline() failed") \
  3459. _SG_LOGITEM_XMACRO(WGPU_ATTACHMENTS_CREATE_TEXTURE_VIEW_FAILED, "wgpuTextureCreateView() failed in create attachments") \
  3460. _SG_LOGITEM_XMACRO(IDENTICAL_COMMIT_LISTENER, "attempting to add identical commit listener") \
  3461. _SG_LOGITEM_XMACRO(COMMIT_LISTENER_ARRAY_FULL, "commit listener array full") \
  3462. _SG_LOGITEM_XMACRO(TRACE_HOOKS_NOT_ENABLED, "sg_install_trace_hooks() called, but SOKOL_TRACE_HOOKS is not defined") \
  3463. _SG_LOGITEM_XMACRO(DEALLOC_BUFFER_INVALID_STATE, "sg_dealloc_buffer(): buffer must be in ALLOC state") \
  3464. _SG_LOGITEM_XMACRO(DEALLOC_IMAGE_INVALID_STATE, "sg_dealloc_image(): image must be in alloc state") \
  3465. _SG_LOGITEM_XMACRO(DEALLOC_SAMPLER_INVALID_STATE, "sg_dealloc_sampler(): sampler must be in alloc state") \
  3466. _SG_LOGITEM_XMACRO(DEALLOC_SHADER_INVALID_STATE, "sg_dealloc_shader(): shader must be in ALLOC state") \
  3467. _SG_LOGITEM_XMACRO(DEALLOC_PIPELINE_INVALID_STATE, "sg_dealloc_pipeline(): pipeline must be in ALLOC state") \
  3468. _SG_LOGITEM_XMACRO(DEALLOC_ATTACHMENTS_INVALID_STATE, "sg_dealloc_attachments(): attachments must be in ALLOC state") \
  3469. _SG_LOGITEM_XMACRO(INIT_BUFFER_INVALID_STATE, "sg_init_buffer(): buffer must be in ALLOC state") \
  3470. _SG_LOGITEM_XMACRO(INIT_IMAGE_INVALID_STATE, "sg_init_image(): image must be in ALLOC state") \
  3471. _SG_LOGITEM_XMACRO(INIT_SAMPLER_INVALID_STATE, "sg_init_sampler(): sampler must be in ALLOC state") \
  3472. _SG_LOGITEM_XMACRO(INIT_SHADER_INVALID_STATE, "sg_init_shader(): shader must be in ALLOC state") \
  3473. _SG_LOGITEM_XMACRO(INIT_PIPELINE_INVALID_STATE, "sg_init_pipeline(): pipeline must be in ALLOC state") \
  3474. _SG_LOGITEM_XMACRO(INIT_ATTACHMENTS_INVALID_STATE, "sg_init_attachments(): pass must be in ALLOC state") \
  3475. _SG_LOGITEM_XMACRO(UNINIT_BUFFER_INVALID_STATE, "sg_uninit_buffer(): buffer must be in VALID or FAILED state") \
  3476. _SG_LOGITEM_XMACRO(UNINIT_IMAGE_INVALID_STATE, "sg_uninit_image(): image must be in VALID or FAILED state") \
  3477. _SG_LOGITEM_XMACRO(UNINIT_SAMPLER_INVALID_STATE, "sg_uninit_sampler(): sampler must be in VALID or FAILED state") \
  3478. _SG_LOGITEM_XMACRO(UNINIT_SHADER_INVALID_STATE, "sg_uninit_shader(): shader must be in VALID or FAILED state") \
  3479. _SG_LOGITEM_XMACRO(UNINIT_PIPELINE_INVALID_STATE, "sg_uninit_pipeline(): pipeline must be in VALID or FAILED state") \
  3480. _SG_LOGITEM_XMACRO(UNINIT_ATTACHMENTS_INVALID_STATE, "sg_uninit_attachments(): attachments must be in VALID or FAILED state") \
  3481. _SG_LOGITEM_XMACRO(FAIL_BUFFER_INVALID_STATE, "sg_fail_buffer(): buffer must be in ALLOC state") \
  3482. _SG_LOGITEM_XMACRO(FAIL_IMAGE_INVALID_STATE, "sg_fail_image(): image must be in ALLOC state") \
  3483. _SG_LOGITEM_XMACRO(FAIL_SAMPLER_INVALID_STATE, "sg_fail_sampler(): sampler must be in ALLOC state") \
  3484. _SG_LOGITEM_XMACRO(FAIL_SHADER_INVALID_STATE, "sg_fail_shader(): shader must be in ALLOC state") \
  3485. _SG_LOGITEM_XMACRO(FAIL_PIPELINE_INVALID_STATE, "sg_fail_pipeline(): pipeline must be in ALLOC state") \
  3486. _SG_LOGITEM_XMACRO(FAIL_ATTACHMENTS_INVALID_STATE, "sg_fail_attachments(): attachments must be in ALLOC state") \
  3487. _SG_LOGITEM_XMACRO(BUFFER_POOL_EXHAUSTED, "buffer pool exhausted") \
  3488. _SG_LOGITEM_XMACRO(IMAGE_POOL_EXHAUSTED, "image pool exhausted") \
  3489. _SG_LOGITEM_XMACRO(SAMPLER_POOL_EXHAUSTED, "sampler pool exhausted") \
  3490. _SG_LOGITEM_XMACRO(SHADER_POOL_EXHAUSTED, "shader pool exhausted") \
  3491. _SG_LOGITEM_XMACRO(PIPELINE_POOL_EXHAUSTED, "pipeline pool exhausted") \
  3492. _SG_LOGITEM_XMACRO(PASS_POOL_EXHAUSTED, "pass pool exhausted") \
  3493. _SG_LOGITEM_XMACRO(BEGINPASS_ATTACHMENT_INVALID, "sg_begin_pass: an attachment was provided that no longer exists") \
  3494. _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") \
  3495. _SG_LOGITEM_XMACRO(DRAW_WITHOUT_BINDINGS, "attempting to draw without resource bindings") \
  3496. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_CANARY, "sg_buffer_desc not initialized") \
  3497. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_IMMUTABLE_DYNAMIC_STREAM, "sg_buffer_desc.usage: only one of .immutable, .dynamic_update, .stream_update can be true") \
  3498. _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)") \
  3499. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_EXPECT_NONZERO_SIZE, "sg_buffer_desc.size must be greater zero") \
  3500. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_EXPECT_MATCHING_DATA_SIZE, "sg_buffer_desc.size and .data.size must be equal") \
  3501. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_EXPECT_ZERO_DATA_SIZE, "sg_buffer_desc.data.size expected to be zero") \
  3502. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_EXPECT_NO_DATA, "sg_buffer_desc.data.ptr must be null for dynamic/stream buffers") \
  3503. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_EXPECT_DATA, "sg_buffer_desc: initial content data must be provided for immutable buffers without storage buffer usage") \
  3504. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_STORAGEBUFFER_SUPPORTED, "storage buffers not supported by the backend 3D API (requires OpenGL >= 4.3)") \
  3505. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_STORAGEBUFFER_SIZE_MULTIPLE_4, "size of storage buffers must be a multiple of 4") \
  3506. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDATA_NODATA, "sg_image_data: no data (.ptr and/or .size is zero)") \
  3507. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDATA_DATA_SIZE, "sg_image_data: data size doesn't match expected surface size") \
  3508. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_CANARY, "sg_image_desc not initialized") \
  3509. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_IMMUTABLE_DYNAMIC_STREAM, "sg_image_desc.usage: only one of .immutable, .dynamic_update, .stream_update can be true") \
  3510. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RENDER_VS_STORAGE_ATTACHMENT, "sg_image_desc.usage: only one of .render_attachment or .storage_attachment can be true") \
  3511. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_WIDTH, "sg_image_desc.width must be > 0") \
  3512. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_HEIGHT, "sg_image_desc.height must be > 0") \
  3513. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_NONRT_PIXELFORMAT, "invalid pixel format for non-render-target image") \
  3514. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_MSAA_BUT_NO_ATTACHMENT, "non-attachment images cannot be multisampled") \
  3515. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_DEPTH_3D_IMAGE, "3D images cannot have a depth/stencil image format") \
  3516. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_ATTACHMENT_EXPECT_IMMUTABLE, "render/storage attachment images must be sg_image_usage.immutable") \
  3517. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_ATTACHMENT_EXPECT_NO_DATA, "render/storage attachment images cannot be initialized with data") \
  3518. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RENDERATTACHMENT_NO_MSAA_SUPPORT, "multisampling not supported for this pixel format") \
  3519. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RENDERATTACHMENT_MSAA_NUM_MIPMAPS, "multisample images must have num_mipmaps == 1") \
  3520. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RENDERATTACHMENT_MSAA_3D_IMAGE, "3D images cannot have a sample_count > 1") \
  3521. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RENDERATTACHMENT_MSAA_CUBE_IMAGE, "cube images cannot have sample_count > 1") \
  3522. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RENDERATTACHMENT_MSAA_ARRAY_IMAGE, "array images cannot have sample_count > 1") \
  3523. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RENDERATTACHMENT_PIXELFORMAT, "invalid pixel format for render attachment image") \
  3524. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_STORAGEATTACHMENT_PIXELFORMAT, "invalid pixel format for storage attachment image") \
  3525. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_STORAGEATTACHMENT_EXPECT_NO_MSAA, "storage attachment images cannot be multisampled") \
  3526. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_INJECTED_NO_DATA, "images with injected textures cannot be initialized with data") \
  3527. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_DYNAMIC_NO_DATA, "dynamic/stream-update images cannot be initialized with data") \
  3528. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_COMPRESSED_IMMUTABLE, "compressed images must be immutable") \
  3529. _SG_LOGITEM_XMACRO(VALIDATE_SAMPLERDESC_CANARY, "sg_sampler_desc not initialized") \
  3530. _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") \
  3531. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_CANARY, "sg_shader_desc not initialized") \
  3532. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_VERTEX_SOURCE, "vertex shader source code expected") \
  3533. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_FRAGMENT_SOURCE, "fragment shader source code expected") \
  3534. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_COMPUTE_SOURCE, "compute shader source code expected") \
  3535. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_VERTEX_SOURCE_OR_BYTECODE, "vertex shader source or byte code expected") \
  3536. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_FRAGMENT_SOURCE_OR_BYTECODE, "fragment shader source or byte code expected") \
  3537. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_COMPUTE_SOURCE_OR_BYTECODE, "compute shader source or byte code expected") \
  3538. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_INVALID_SHADER_COMBO, "cannot combine compute shaders with vertex or fragment shaders") \
  3539. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_NO_BYTECODE_SIZE, "shader byte code length (in bytes) required") \
  3540. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_METAL_THREADS_PER_THREADGROUP, "sg_shader_desc.mtl_threads_per_threadgroup must be initialized for compute shaders (metal)") \
  3541. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_NO_CONT_MEMBERS, "uniform block members must occupy continuous slots") \
  3542. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_SIZE_IS_ZERO, "bound uniform block size cannot be zero") \
  3543. _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)") \
  3544. _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") \
  3545. _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)") \
  3546. _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") \
  3547. _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)") \
  3548. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_WGSL_GROUP0_BINDING_COLLISION, "uniform block 'wgsl_group0_binding_n' must be unique across all uniform blocks") \
  3549. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_NO_MEMBERS, "GL backend requires uniform block member declarations") \
  3550. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_UNIFORM_GLSL_NAME, "uniform block member 'glsl_name' missing") \
  3551. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_SIZE_MISMATCH, "size of uniform block members doesn't match uniform block size") \
  3552. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_ARRAY_COUNT, "uniform array count must be >= 1") \
  3553. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_STD140_ARRAY_TYPE, "uniform arrays only allowed for FLOAT4, INT4, MAT4 in std140 layout") \
  3554. _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)") \
  3555. _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") \
  3556. _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)") \
  3557. _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") \
  3558. _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)") \
  3559. _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") \
  3560. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_GLSL_BINDING_OUT_OF_RANGE, "storage buffer 'glsl_binding_n' is out of range (must be 0..7)") \
  3561. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_GLSL_BINDING_COLLISION, "storage buffer 'glsl_binding_n' must be unique across shader stages") \
  3562. _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)") \
  3563. _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") \
  3564. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEIMAGE_EXPECT_COMPUTE_STAGE, "storage images are only allowed on the compute stage") \
  3565. _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") \
  3566. _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") \
  3567. _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)") \
  3568. _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") \
  3569. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEIMAGE_GLSL_BINDING_OUT_OF_RANGE, "storage image 'glsl_binding_n' is out of range (must be 0..4)") \
  3570. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEIMAGE_GLSL_BINDING_COLLISION, "storage image 'glsl_binding_n' must be unique across shader stages") \
  3571. _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)") \
  3572. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEIMAGE_WGSL_GROUP2_BINDING_COLLISION, "storage image 'wgsl_group2_binding_n' must be unique in same shader stage") \
  3573. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_METAL_TEXTURE_SLOT_OUT_OF_RANGE, "image 'msl_texture_n' is out of range (must be 0..19)") \
  3574. _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") \
  3575. _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)") \
  3576. _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") \
  3577. _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)") \
  3578. _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") \
  3579. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_METAL_SAMPLER_SLOT_OUT_OF_RANGE, "sampler 'msl_sampler_n' is out of range (must be 0..15)") \
  3580. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_METAL_SAMPLER_SLOT_COLLISION, "sampler 'msl_sampler_n' must be unique in same shader stage") \
  3581. _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)") \
  3582. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_HLSL_REGISTER_S_COLLISION, "sampler 'hlsl_register_s_n' must be unique in same shader stage") \
  3583. _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)") \
  3584. _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") \
  3585. _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)") \
  3586. _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)") \
  3587. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_IMAGE_STAGE_MISMATCH, "image-sampler-pair stage doesn't match referenced image stage") \
  3588. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_SAMPLER_STAGE_MISMATCH, "image-sampler-pair stage doesn't match referenced sampler stage") \
  3589. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_GLSL_NAME, "image-sampler-pair 'glsl_name' missing") \
  3590. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_NONFILTERING_SAMPLER_REQUIRED, "image sample type UNFILTERABLE_FLOAT, UINT, SINT can only be used with NONFILTERING sampler") \
  3591. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_COMPARISON_SAMPLER_REQUIRED, "image sample type DEPTH can only be used with COMPARISON sampler") \
  3592. _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)") \
  3593. _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)") \
  3594. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_ATTR_STRING_TOO_LONG, "vertex attribute name/semantic string too long (max len 16)") \
  3595. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_CANARY, "sg_pipeline_desc not initialized") \
  3596. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_SHADER, "sg_pipeline_desc.shader missing or invalid") \
  3597. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_COMPUTE_SHADER_EXPECTED, "sg_pipeline_desc.shader must be a compute shader") \
  3598. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_NO_COMPUTE_SHADER_EXPECTED, "sg_pipeline_desc.compute is false, but shader is a compute shader") \
  3599. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_NO_CONT_ATTRS, "sg_pipeline_desc.layout.attrs is not continuous") \
  3600. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_ATTR_BASETYPE_MISMATCH, "sg_pipeline_desc.layout.attrs[].format is incompatible with sg_shader_desc.attrs[].base_type") \
  3601. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_LAYOUT_STRIDE4, "sg_pipeline_desc.layout.buffers[].stride must be multiple of 4") \
  3602. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_ATTR_SEMANTICS, "D3D11 missing vertex attribute semantics in shader") \
  3603. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_SHADER_READONLY_STORAGEBUFFERS, "sg_pipeline_desc.shader: only readonly storage buffer bindings allowed in render pipelines") \
  3604. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_BLENDOP_MINMAX_REQUIRES_BLENDFACTOR_ONE, "SG_BLENDOP_MIN/MAX requires all blend factors to be SG_BLENDFACTOR_ONE") \
  3605. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_CANARY, "sg_attachments_desc not initialized") \
  3606. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_NO_ATTACHMENTS, "sg_attachments_desc no color, depth-stencil or storage attachments") \
  3607. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_NO_CONT_COLOR_ATTS, "color attachments must occupy continuous slots") \
  3608. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_COLOR_IMAGE, "color attachment image is not valid") \
  3609. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_COLOR_MIPLEVEL, "color attachment mip level is higher than number of mipmaps in image") \
  3610. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_COLOR_FACE, "color attachment image is cubemap, but face index is too big") \
  3611. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_COLOR_LAYER, "color attachment image is array texture, but layer index is too big") \
  3612. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_COLOR_SLICE, "color attachment image is 3d texture, but slice value is too big") \
  3613. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_COLOR_IMAGE_NO_RENDERATTACHMENT, "color attachment images must be sg_image_desc.usage.render_attachment=true") \
  3614. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_COLOR_INV_PIXELFORMAT, "color attachment images must be renderable color pixel format") \
  3615. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_IMAGE_SIZES, "all color and depth attachment images must have the same size") \
  3616. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_IMAGE_SAMPLE_COUNTS, "all color and depth attachment images must have the same sample count") \
  3617. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_COLOR_IMAGE_MSAA, "resolve attachments must have a color attachment image with sample count > 1") \
  3618. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE, "resolve attachment image not valid") \
  3619. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_SAMPLE_COUNT, "pass resolve attachment image sample count must be 1") \
  3620. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_MIPLEVEL, "resolve attachment mip level is higher than number of mipmaps in image") \
  3621. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_FACE, "resolve attachment is cubemap, but face index is too big") \
  3622. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_LAYER, "resolve attachment is array texture, but layer index is too big") \
  3623. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_SLICE, "resolve attachment is 3d texture, but slice value is too big") \
  3624. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_NO_RT, "resolve attachment image must have render_target=true") \
  3625. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_SIZES, "resolve attachment size must match color attachment image size") \
  3626. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_FORMAT, "resolve attachment pixel format must match color attachment pixel format") \
  3627. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_INV_PIXELFORMAT, "depth attachment image must be depth or depth-stencil pixel format") \
  3628. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE, "depth attachment image is not valid") \
  3629. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_MIPLEVEL, "depth attachment mip level is higher than number of mipmaps in image") \
  3630. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_FACE, "depth attachment image is cubemap, but face index is too big") \
  3631. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_LAYER, "depth attachment image is array texture, but layer index is too big") \
  3632. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_SLICE, "depth attachment image is 3d texture, but slice value is too big") \
  3633. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_NO_RENDERATTACHMENT, "depth attachment image must be sg_image_desc.usage.render_attachment=true") \
  3634. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_SIZES, "depth attachment image size must match color attachment image size") \
  3635. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_SAMPLE_COUNT, "depth attachment sample count must match color attachment sample count") \
  3636. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_STORAGE_IMAGE, "storage attachment image is not valid") \
  3637. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_STORAGE_MIPLEVEL, "storage attachment mip level is higher than number of mipmaps in image") \
  3638. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_STORAGE_FACE, "storage attachment image is cubemap, but face index is too big") \
  3639. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_STORAGE_LAYER, "storage attachment image is array texture, but layer index is too big") \
  3640. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_STORAGE_SLICE, "storage attachment image is 3d texture, but slice value is too big") \
  3641. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_STORAGE_IMAGE_NO_STORAGEATTACHMENT, "storage attachment images must be sg_image_desc.usage.storage_attachment=true") \
  3642. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_STORAGE_INV_PIXELFORMAT, "storage attachment pixel format must have .compute_readwrite or .compute_writeonly capabilities") \
  3643. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RENDER_VS_STORAGE_ATTACHMENTS, "cannot use color/depth and storage attachment images on the same sg_attachments object") \
  3644. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_CANARY, "sg_begin_pass: pass struct not initialized") \
  3645. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_ATTACHMENTS_EXISTS, "sg_begin_pass: attachments object no longer alive") \
  3646. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_ATTACHMENTS_VALID, "sg_begin_pass: attachments object not in resource state VALID") \
  3647. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_COMPUTEPASS_STORAGE_ATTACHMENTS_ONLY, "sg_begin_pass: only storage attachments allowed on compute pass") \
  3648. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_RENDERPASS_RENDER_ATTACHMENTS_ONLY, "sg_begin_pass: a render pass cannot have storage attachments") \
  3649. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_COLOR_ATTACHMENT_IMAGE_ALIVE, "sg_begin_pass: one or more color attachment images are no longer alive") \
  3650. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_COLOR_ATTACHMENT_IMAGE_VALID, "sg_begin_pass: one or more color attachment images are not in valid state") \
  3651. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_RESOLVE_ATTACHMENT_IMAGE_ALIVE, "sg_begin_pass: one or more resolve attachment images are no longer alive") \
  3652. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_RESOLVE_ATTACHMENT_IMAGE_VALID, "sg_begin_pass: one or more resolve attachment images are not in valid state") \
  3653. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_DEPTHSTENCIL_ATTACHMENT_IMAGE_ALIVE, "sg_begin_pass: one or more depth-stencil attachment images are no longer alive") \
  3654. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_DEPTHSTENCIL_ATTACHMENT_IMAGE_VALID, "sg_begin_pass: one or more depth-stencil attachment images are not in valid state") \
  3655. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_STORAGE_ATTACHMENT_IMAGE_ALIVE, "sg_begin_pass: one or more storage attachment images is no longer alive") \
  3656. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_STORAGE_ATTACHMENT_IMAGE_VALID, "sg_begin_pass: one or more storage attachment images is not in valid state") \
  3657. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_WIDTH, "sg_begin_pass: expected pass.swapchain.width > 0") \
  3658. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_WIDTH_NOTSET, "sg_begin_pass: expected pass.swapchain.width == 0") \
  3659. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_HEIGHT, "sg_begin_pass: expected pass.swapchain.height > 0") \
  3660. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_HEIGHT_NOTSET, "sg_begin_pass: expected pass.swapchain.height == 0") \
  3661. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_SAMPLECOUNT, "sg_begin_pass: expected pass.swapchain.sample_count > 0") \
  3662. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_SAMPLECOUNT_NOTSET, "sg_begin_pass: expected pass.swapchain.sample_count == 0") \
  3663. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_COLORFORMAT, "sg_begin_pass: expected pass.swapchain.color_format to be valid") \
  3664. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_COLORFORMAT_NOTSET, "sg_begin_pass: expected pass.swapchain.color_format to be unset") \
  3665. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_DEPTHFORMAT_NOTSET, "sg_begin_pass: expected pass.swapchain.depth_format to be unset") \
  3666. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_CURRENTDRAWABLE, "sg_begin_pass: expected pass.swapchain.metal.current_drawable != 0") \
  3667. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_CURRENTDRAWABLE_NOTSET, "sg_begin_pass: expected pass.swapchain.metal.current_drawable == 0") \
  3668. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_DEPTHSTENCILTEXTURE, "sg_begin_pass: expected pass.swapchain.metal.depth_stencil_texture != 0") \
  3669. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_DEPTHSTENCILTEXTURE_NOTSET, "sg_begin_pass: expected pass.swapchain.metal.depth_stencil_texture == 0") \
  3670. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_MSAACOLORTEXTURE, "sg_begin_pass: expected pass.swapchain.metal.msaa_color_texture != 0") \
  3671. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_MSAACOLORTEXTURE_NOTSET, "sg_begin_pass: expected pass.swapchain.metal.msaa_color_texture == 0") \
  3672. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RENDERVIEW, "sg_begin_pass: expected pass.swapchain.d3d11.render_view != 0") \
  3673. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RENDERVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.d3d11.render_view == 0") \
  3674. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RESOLVEVIEW, "sg_begin_pass: expected pass.swapchain.d3d11.resolve_view != 0") \
  3675. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RESOLVEVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.d3d11.resolve_view == 0") \
  3676. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_DEPTHSTENCILVIEW, "sg_begin_pass: expected pass.swapchain.d3d11.depth_stencil_view != 0") \
  3677. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_DEPTHSTENCILVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.d3d11.depth_stencil_view == 0") \
  3678. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RENDERVIEW, "sg_begin_pass: expected pass.swapchain.wgpu.render_view != 0") \
  3679. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RENDERVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.wgpu.render_view == 0") \
  3680. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RESOLVEVIEW, "sg_begin_pass: expected pass.swapchain.wgpu.resolve_view != 0") \
  3681. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RESOLVEVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.wgpu.resolve_view == 0") \
  3682. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_DEPTHSTENCILVIEW, "sg_begin_pass: expected pass.swapchain.wgpu.depth_stencil_view != 0") \
  3683. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_DEPTHSTENCILVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.wgpu.depth_stencil_view == 0") \
  3684. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_GL_EXPECT_FRAMEBUFFER_NOTSET, "sg_begin_pass: expected pass.swapchain.gl.framebuffer == 0") \
  3685. _SG_LOGITEM_XMACRO(VALIDATE_AVP_RENDERPASS_EXPECTED, "sg_apply_viewport: must be called in a render pass") \
  3686. _SG_LOGITEM_XMACRO(VALIDATE_ASR_RENDERPASS_EXPECTED, "sg_apply_scissor_rect: must be called in a render pass") \
  3687. _SG_LOGITEM_XMACRO(VALIDATE_APIP_PIPELINE_VALID_ID, "sg_apply_pipeline: invalid pipeline id provided") \
  3688. _SG_LOGITEM_XMACRO(VALIDATE_APIP_PIPELINE_EXISTS, "sg_apply_pipeline: pipeline object no longer alive") \
  3689. _SG_LOGITEM_XMACRO(VALIDATE_APIP_PIPELINE_VALID, "sg_apply_pipeline: pipeline object not in valid state") \
  3690. _SG_LOGITEM_XMACRO(VALIDATE_APIP_PASS_EXPECTED, "sg_apply_pipeline: must be called in a pass") \
  3691. _SG_LOGITEM_XMACRO(VALIDATE_APIP_PIPELINE_SHADER_ALIVE, "sg_apply_pipeline: shader object associated with pipeline no longer alive") \
  3692. _SG_LOGITEM_XMACRO(VALIDATE_APIP_PIPELINE_SHADER_VALID, "sg_apply_pipeline: shader object associated with pipeline not in valid state") \
  3693. _SG_LOGITEM_XMACRO(VALIDATE_APIP_COMPUTEPASS_EXPECTED, "sg_apply_pipeline: trying to apply compute pipeline in render pass") \
  3694. _SG_LOGITEM_XMACRO(VALIDATE_APIP_RENDERPASS_EXPECTED, "sg_apply_pipeline: trying to apply render pipeline in compute pass") \
  3695. _SG_LOGITEM_XMACRO(VALIDATE_APIP_CURPASS_ATTACHMENTS_ALIVE, "sg_apply_pipeline: current pass attachments no longer alive") \
  3696. _SG_LOGITEM_XMACRO(VALIDATE_APIP_CURPASS_ATTACHMENTS_VALID, "sg_apply_pipeline: current pass attachments not in valid state") \
  3697. _SG_LOGITEM_XMACRO(VALIDATE_APIP_ATT_COUNT, "sg_apply_pipeline: number of pipeline color attachments doesn't match number of pass color attachments") \
  3698. _SG_LOGITEM_XMACRO(VALIDATE_APIP_COLOR_ATTACHMENT_IMAGE_ALIVE, "sg_apply_pipeline: one or more pass color attachments images are no longer alive") \
  3699. _SG_LOGITEM_XMACRO(VALIDATE_APIP_COLOR_ATTACHMENT_IMAGE_VALID, "sg_apply_pipeline: one or more pass color attachments images are not in valid state") \
  3700. _SG_LOGITEM_XMACRO(VALIDATE_APIP_DEPTHSTENCIL_ATTACHMENT_IMAGE_ALIVE, "sg_apply_pipeline: pass depth-stencil attachment image no longer alive") \
  3701. _SG_LOGITEM_XMACRO(VALIDATE_APIP_DEPTHSTENCIL_ATTACHMENT_IMAGE_VALID, "sg_apply_pipeline: pass depth-stencil attachment image not in valid state") \
  3702. _SG_LOGITEM_XMACRO(VALIDATE_APIP_COLOR_FORMAT, "sg_apply_pipeline: pipeline color attachment pixel format doesn't match pass color attachment pixel format") \
  3703. _SG_LOGITEM_XMACRO(VALIDATE_APIP_DEPTH_FORMAT, "sg_apply_pipeline: pipeline depth pixel_format doesn't match pass depth attachment pixel format") \
  3704. _SG_LOGITEM_XMACRO(VALIDATE_APIP_SAMPLE_COUNT, "sg_apply_pipeline: pipeline MSAA sample count doesn't match render pass attachment sample count") \
  3705. _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") \
  3706. _SG_LOGITEM_XMACRO(VALIDATE_APIP_STORAGE_ATTACHMENT_IMAGE_ALIVE, "sg_apply_pipeline: compute pass storage image attachment no longer exists") \
  3707. _SG_LOGITEM_XMACRO(VALIDATE_APIP_STORAGE_ATTACHMENT_IMAGE_VALID, "sg_apply_pipeline: compute pass storage image attachment is not in valid state") \
  3708. _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") \
  3709. _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") \
  3710. _SG_LOGITEM_XMACRO(VALIDATE_ABND_PASS_EXPECTED, "sg_apply_bindings: must be called in a pass") \
  3711. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EMPTY_BINDINGS, "sg_apply_bindings: the provided sg_bindings struct is empty") \
  3712. _SG_LOGITEM_XMACRO(VALIDATE_ABND_NO_PIPELINE, "sg_apply_bindings: must be called after sg_apply_pipeline") \
  3713. _SG_LOGITEM_XMACRO(VALIDATE_ABND_PIPELINE_ALIVE, "sg_apply_bindings: currently applied pipeline object no longer alive") \
  3714. _SG_LOGITEM_XMACRO(VALIDATE_ABND_PIPELINE_VALID, "sg_apply_bindings: currently applied pipeline object not in valid state") \
  3715. _SG_LOGITEM_XMACRO(VALIDATE_ABND_PIPELINE_SHADER_ALIVE, "sg_apply_bindings: shader associated with currently applied pipeline is no longer alive") \
  3716. _SG_LOGITEM_XMACRO(VALIDATE_ABND_PIPELINE_SHADER_VALID, "sg_apply_bindings: shader associated with currently applied pipeline is not in valid state") \
  3717. _SG_LOGITEM_XMACRO(VALIDATE_ABND_COMPUTE_EXPECTED_NO_VBS, "sg_apply_bindings: vertex buffer bindings not allowed in a compute pass") \
  3718. _SG_LOGITEM_XMACRO(VALIDATE_ABND_COMPUTE_EXPECTED_NO_IB, "sg_apply_bindings: index buffer binding not allowed in compute pass") \
  3719. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_VB, "sg_apply_bindings: vertex buffer binding is missing or buffer handle is invalid") \
  3720. _SG_LOGITEM_XMACRO(VALIDATE_ABND_VB_ALIVE, "sg_apply_bindings: vertex buffer no longer alive") \
  3721. _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)") \
  3722. _SG_LOGITEM_XMACRO(VALIDATE_ABND_VB_OVERFLOW, "sg_apply_bindings: buffer in vertex buffer slot is overflown") \
  3723. _SG_LOGITEM_XMACRO(VALIDATE_ABND_NO_IB, "sg_apply_bindings: pipeline object defines indexed rendering, but no index buffer provided") \
  3724. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IB, "sg_apply_bindings: pipeline object defines non-indexed rendering, but index buffer provided") \
  3725. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IB_ALIVE, "sg_apply_bindings: index buffer no longer alive") \
  3726. _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)") \
  3727. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IB_OVERFLOW, "sg_apply_bindings: buffer in index buffer slot is overflown") \
  3728. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_IMAGE_BINDING, "sg_apply_bindings: image binding is missing or the image handle is invalid") \
  3729. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IMG_ALIVE, "sg_apply_bindings: bound image no longer alive") \
  3730. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IMAGE_TYPE_MISMATCH, "sg_apply_bindings: type of bound image doesn't match shader desc") \
  3731. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_MULTISAMPLED_IMAGE, "sg_apply_bindings: expected image with sample_count > 1") \
  3732. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IMAGE_MSAA, "sg_apply_bindings: cannot bind image with sample_count>1") \
  3733. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_FILTERABLE_IMAGE, "sg_apply_bindings: filterable image expected") \
  3734. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_DEPTH_IMAGE, "sg_apply_bindings: depth image expected") \
  3735. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_SAMPLER_BINDING, "sg_apply_bindings: sampler binding is missing or the sampler handle is invalid") \
  3736. _SG_LOGITEM_XMACRO(VALIDATE_ABND_UNEXPECTED_SAMPLER_COMPARE_NEVER, "sg_apply_bindings: shader expects SG_SAMPLERTYPE_COMPARISON but sampler has SG_COMPAREFUNC_NEVER") \
  3737. _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") \
  3738. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_NONFILTERING_SAMPLER, "sg_apply_bindings: shader expected SG_SAMPLERTYPE_NONFILTERING, but sampler has SG_FILTER_LINEAR filters") \
  3739. _SG_LOGITEM_XMACRO(VALIDATE_ABND_SMP_ALIVE, "sg_apply_bindings: bound sampler no longer alive") \
  3740. _SG_LOGITEM_XMACRO(VALIDATE_ABND_SMP_VALID, "sg_apply_bindings: bound sampler not in valid state") \
  3741. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_STORAGEBUFFER_BINDING, "sg_apply_bindings: storage buffer binding is missing or the buffer handle is invalid") \
  3742. _SG_LOGITEM_XMACRO(VALIDATE_ABND_STORAGEBUFFER_ALIVE, "sg_apply_bindings: bound storage buffer no longer alive") \
  3743. _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)") \
  3744. _SG_LOGITEM_XMACRO(VALIDATE_ABND_STORAGEBUFFER_READWRITE_IMMUTABLE, "sg_apply_bindings: storage buffers bound as read/write must have usage immutable") \
  3745. _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") \
  3746. _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") \
  3747. _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") \
  3748. _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") \
  3749. _SG_LOGITEM_XMACRO(VALIDATE_AU_PASS_EXPECTED, "sg_apply_uniforms: must be called in a pass") \
  3750. _SG_LOGITEM_XMACRO(VALIDATE_AU_NO_PIPELINE, "sg_apply_uniforms: must be called after sg_apply_pipeline()") \
  3751. _SG_LOGITEM_XMACRO(VALIDATE_AU_PIPELINE_ALIVE, "sg_apply_uniforms: currently applied pipeline object no longer alive") \
  3752. _SG_LOGITEM_XMACRO(VALIDATE_AU_PIPELINE_VALID, "sg_apply_uniforms: currently applied pipeline object not in valid state") \
  3753. _SG_LOGITEM_XMACRO(VALIDATE_AU_PIPELINE_SHADER_ALIVE, "sg_apply_uniforms: shader associated with currently applied pipeline is no longer alive") \
  3754. _SG_LOGITEM_XMACRO(VALIDATE_AU_PIPELINE_SHADER_VALID, "sg_apply_uniforms: shader associated with currently applied pipeline is not in valid state") \
  3755. _SG_LOGITEM_XMACRO(VALIDATE_AU_NO_UNIFORMBLOCK_AT_SLOT, "sg_apply_uniforms: no uniform block declaration at this shader stage UB slot") \
  3756. _SG_LOGITEM_XMACRO(VALIDATE_AU_SIZE, "sg_apply_uniforms: data size doesn't match declared uniform block size") \
  3757. _SG_LOGITEM_XMACRO(VALIDATE_DRAW_RENDERPASS_EXPECTED, "sg_draw: must be called in a render pass") \
  3758. _SG_LOGITEM_XMACRO(VALIDATE_DRAW_BASEELEMENT, "sg_draw: base_element cannot be < 0") \
  3759. _SG_LOGITEM_XMACRO(VALIDATE_DRAW_NUMELEMENTS, "sg_draw: num_elements cannot be < 0") \
  3760. _SG_LOGITEM_XMACRO(VALIDATE_DRAW_NUMINSTANCES, "sg_draw: num_instances cannot be < 0") \
  3761. _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()") \
  3762. _SG_LOGITEM_XMACRO(VALIDATE_DISPATCH_COMPUTEPASS_EXPECTED, "sg_dispatch: must be called in a compute pass") \
  3763. _SG_LOGITEM_XMACRO(VALIDATE_DISPATCH_NUMGROUPSX, "sg_dispatch: num_groups_x must be >=0 and <65536") \
  3764. _SG_LOGITEM_XMACRO(VALIDATE_DISPATCH_NUMGROUPSY, "sg_dispatch: num_groups_y must be >=0 and <65536") \
  3765. _SG_LOGITEM_XMACRO(VALIDATE_DISPATCH_NUMGROUPSZ, "sg_dispatch: num_groups_z must be >=0 and <65536") \
  3766. _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()") \
  3767. _SG_LOGITEM_XMACRO(VALIDATE_UPDATEBUF_USAGE, "sg_update_buffer: cannot update immutable buffer") \
  3768. _SG_LOGITEM_XMACRO(VALIDATE_UPDATEBUF_SIZE, "sg_update_buffer: update size is bigger than buffer size") \
  3769. _SG_LOGITEM_XMACRO(VALIDATE_UPDATEBUF_ONCE, "sg_update_buffer: only one update allowed per buffer and frame") \
  3770. _SG_LOGITEM_XMACRO(VALIDATE_UPDATEBUF_APPEND, "sg_update_buffer: cannot call sg_update_buffer and sg_append_buffer in same frame") \
  3771. _SG_LOGITEM_XMACRO(VALIDATE_APPENDBUF_USAGE, "sg_append_buffer: cannot append to immutable buffer") \
  3772. _SG_LOGITEM_XMACRO(VALIDATE_APPENDBUF_SIZE, "sg_append_buffer: overall appended size is bigger than buffer size") \
  3773. _SG_LOGITEM_XMACRO(VALIDATE_APPENDBUF_UPDATE, "sg_append_buffer: cannot call sg_append_buffer and sg_update_buffer in same frame") \
  3774. _SG_LOGITEM_XMACRO(VALIDATE_UPDIMG_USAGE, "sg_update_image: cannot update immutable image") \
  3775. _SG_LOGITEM_XMACRO(VALIDATE_UPDIMG_ONCE, "sg_update_image: only one update allowed per image and frame") \
  3776. _SG_LOGITEM_XMACRO(VALIDATION_FAILED, "validation layer checks failed") \
  3777. #define _SG_LOGITEM_XMACRO(item,msg) SG_LOGITEM_##item,
  3778. typedef enum sg_log_item {
  3779. _SG_LOG_ITEMS
  3780. } sg_log_item;
  3781. #undef _SG_LOGITEM_XMACRO
  3782. /*
  3783. sg_desc
  3784. The sg_desc struct contains configuration values for sokol_gfx,
  3785. it is used as parameter to the sg_setup() call.
  3786. The default configuration is:
  3787. .buffer_pool_size 128
  3788. .image_pool_size 128
  3789. .sampler_pool_size 64
  3790. .shader_pool_size 32
  3791. .pipeline_pool_size 64
  3792. .attachments_pool_size 16
  3793. .uniform_buffer_size 4 MB (4*1024*1024)
  3794. .max_dispatch_calls_per_pass 1024
  3795. .max_commit_listeners 1024
  3796. .disable_validation false
  3797. .mtl_force_managed_storage_mode false
  3798. .wgpu_disable_bindgroups_cache false
  3799. .wgpu_bindgroups_cache_size 1024
  3800. .allocator.alloc_fn 0 (in this case, malloc() will be called)
  3801. .allocator.free_fn 0 (in this case, free() will be called)
  3802. .allocator.user_data 0
  3803. .environment.defaults.color_format: default value depends on selected backend:
  3804. all GL backends: SG_PIXELFORMAT_RGBA8
  3805. Metal and D3D11: SG_PIXELFORMAT_BGRA8
  3806. WebGPU: *no default* (must be queried from WebGPU swapchain object)
  3807. .environment.defaults.depth_format: SG_PIXELFORMAT_DEPTH_STENCIL
  3808. .environment.defaults.sample_count: 1
  3809. Metal specific:
  3810. (NOTE: All Objective-C object references are transferred through
  3811. a bridged cast (__bridge const void*) to sokol_gfx, which will use an
  3812. unretained bridged cast (__bridge id<xxx>) to retrieve the Objective-C
  3813. references back. Since the bridge cast is unretained, the caller
  3814. must hold a strong reference to the Objective-C object until sg_setup()
  3815. returns.
  3816. .mtl_force_managed_storage_mode
  3817. when enabled, Metal buffers and texture resources are created in managed storage
  3818. mode, otherwise sokol-gfx will decide whether to create buffers and
  3819. textures in managed or shared storage mode (this is mainly a debugging option)
  3820. .mtl_use_command_buffer_with_retained_references
  3821. when true, the sokol-gfx Metal backend will use Metal command buffers which
  3822. bump the reference count of resource objects as long as they are inflight,
  3823. this is slower than the default command-buffer-with-unretained-references
  3824. method, this may be a workaround when confronted with lifetime validation
  3825. errors from the Metal validation layer until a proper fix has been implemented
  3826. .environment.metal.device
  3827. a pointer to the MTLDevice object
  3828. D3D11 specific:
  3829. .environment.d3d11.device
  3830. a pointer to the ID3D11Device object, this must have been created
  3831. before sg_setup() is called
  3832. .environment.d3d11.device_context
  3833. a pointer to the ID3D11DeviceContext object
  3834. .d3d11_shader_debugging
  3835. set this to true to compile shaders which are provided as HLSL source
  3836. code with debug information and without optimization, this allows
  3837. shader debugging in tools like RenderDoc, to output source code
  3838. instead of byte code from sokol-shdc, omit the `--binary` cmdline
  3839. option
  3840. WebGPU specific:
  3841. .wgpu_disable_bindgroups_cache
  3842. When this is true, the WebGPU backend will create and immediately
  3843. release a BindGroup object in the sg_apply_bindings() call, only
  3844. use this for debugging purposes.
  3845. .wgpu_bindgroups_cache_size
  3846. The size of the bindgroups cache for re-using BindGroup objects
  3847. between sg_apply_bindings() calls. The smaller the cache size,
  3848. the more likely are cache slot collisions which will cause
  3849. a BindGroups object to be destroyed and a new one created.
  3850. Use the information returned by sg_query_stats() to check
  3851. if this is a frequent occurrence, and increase the cache size as
  3852. needed (the default is 1024).
  3853. NOTE: wgpu_bindgroups_cache_size must be a power-of-2 number!
  3854. .environment.wgpu.device
  3855. a WGPUDevice handle
  3856. When using sokol_gfx.h and sokol_app.h together, consider using the
  3857. helper function sglue_environment() in the sokol_glue.h header to
  3858. initialize the sg_desc.environment nested struct. sglue_environment() returns
  3859. a completely initialized sg_environment struct with information
  3860. provided by sokol_app.h.
  3861. */
  3862. typedef struct sg_environment_defaults {
  3863. sg_pixel_format color_format;
  3864. sg_pixel_format depth_format;
  3865. int sample_count;
  3866. } sg_environment_defaults;
  3867. typedef struct sg_metal_environment {
  3868. const void* device;
  3869. } sg_metal_environment;
  3870. typedef struct sg_d3d11_environment {
  3871. const void* device;
  3872. const void* device_context;
  3873. } sg_d3d11_environment;
  3874. typedef struct sg_wgpu_environment {
  3875. const void* device;
  3876. } sg_wgpu_environment;
  3877. typedef struct sg_environment {
  3878. sg_environment_defaults defaults;
  3879. sg_metal_environment metal;
  3880. sg_d3d11_environment d3d11;
  3881. sg_wgpu_environment wgpu;
  3882. } sg_environment;
  3883. /*
  3884. sg_commit_listener
  3885. Used with function sg_add_commit_listener() to add a callback
  3886. which will be called in sg_commit(). This is useful for libraries
  3887. building on top of sokol-gfx to be notified about when a frame
  3888. ends (instead of having to guess, or add a manual 'new-frame'
  3889. function.
  3890. */
  3891. typedef struct sg_commit_listener {
  3892. void (*func)(void* user_data);
  3893. void* user_data;
  3894. } sg_commit_listener;
  3895. /*
  3896. sg_allocator
  3897. Used in sg_desc to provide custom memory-alloc and -free functions
  3898. to sokol_gfx.h. If memory management should be overridden, both the
  3899. alloc_fn and free_fn function must be provided (e.g. it's not valid to
  3900. override one function but not the other).
  3901. */
  3902. typedef struct sg_allocator {
  3903. void* (*alloc_fn)(size_t size, void* user_data);
  3904. void (*free_fn)(void* ptr, void* user_data);
  3905. void* user_data;
  3906. } sg_allocator;
  3907. /*
  3908. sg_logger
  3909. Used in sg_desc to provide a logging function. Please be aware
  3910. that without logging function, sokol-gfx will be completely
  3911. silent, e.g. it will not report errors, warnings and
  3912. validation layer messages. For maximum error verbosity,
  3913. compile in debug mode (e.g. NDEBUG *not* defined) and provide a
  3914. compatible logger function in the sg_setup() call
  3915. (for instance the standard logging function from sokol_log.h).
  3916. */
  3917. typedef struct sg_logger {
  3918. void (*func)(
  3919. const char* tag, // always "sg"
  3920. uint32_t log_level, // 0=panic, 1=error, 2=warning, 3=info
  3921. uint32_t log_item_id, // SG_LOGITEM_*
  3922. const char* message_or_null, // a message string, may be nullptr in release mode
  3923. uint32_t line_nr, // line number in sokol_gfx.h
  3924. const char* filename_or_null, // source filename, may be nullptr in release mode
  3925. void* user_data);
  3926. void* user_data;
  3927. } sg_logger;
  3928. typedef struct sg_desc {
  3929. uint32_t _start_canary;
  3930. int buffer_pool_size;
  3931. int image_pool_size;
  3932. int sampler_pool_size;
  3933. int shader_pool_size;
  3934. int pipeline_pool_size;
  3935. int attachments_pool_size;
  3936. int uniform_buffer_size;
  3937. int max_dispatch_calls_per_pass; // max expected number of dispatch calls per pass (default: 1024)
  3938. int max_commit_listeners;
  3939. bool disable_validation; // disable validation layer even in debug mode, useful for tests
  3940. bool d3d11_shader_debugging; // if true, HLSL shaders are compiled with D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION
  3941. bool mtl_force_managed_storage_mode; // for debugging: use Metal managed storage mode for resources even with UMA
  3942. bool mtl_use_command_buffer_with_retained_references; // Metal: use a managed MTLCommandBuffer which ref-counts used resources
  3943. bool wgpu_disable_bindgroups_cache; // set to true to disable the WebGPU backend BindGroup cache
  3944. int wgpu_bindgroups_cache_size; // number of slots in the WebGPU bindgroup cache (must be 2^N)
  3945. sg_allocator allocator;
  3946. sg_logger logger; // optional log function override
  3947. sg_environment environment;
  3948. uint32_t _end_canary;
  3949. } sg_desc;
  3950. // setup and misc functions
  3951. SOKOL_GFX_API_DECL void sg_setup(const sg_desc* desc);
  3952. SOKOL_GFX_API_DECL void sg_shutdown(void);
  3953. SOKOL_GFX_API_DECL bool sg_isvalid(void);
  3954. SOKOL_GFX_API_DECL void sg_reset_state_cache(void);
  3955. SOKOL_GFX_API_DECL sg_trace_hooks sg_install_trace_hooks(const sg_trace_hooks* trace_hooks);
  3956. SOKOL_GFX_API_DECL void sg_push_debug_group(const char* name);
  3957. SOKOL_GFX_API_DECL void sg_pop_debug_group(void);
  3958. SOKOL_GFX_API_DECL bool sg_add_commit_listener(sg_commit_listener listener);
  3959. SOKOL_GFX_API_DECL bool sg_remove_commit_listener(sg_commit_listener listener);
  3960. // resource creation, destruction and updating
  3961. SOKOL_GFX_API_DECL sg_buffer sg_make_buffer(const sg_buffer_desc* desc);
  3962. SOKOL_GFX_API_DECL sg_image sg_make_image(const sg_image_desc* desc);
  3963. SOKOL_GFX_API_DECL sg_sampler sg_make_sampler(const sg_sampler_desc* desc);
  3964. SOKOL_GFX_API_DECL sg_shader sg_make_shader(const sg_shader_desc* desc);
  3965. SOKOL_GFX_API_DECL sg_pipeline sg_make_pipeline(const sg_pipeline_desc* desc);
  3966. SOKOL_GFX_API_DECL sg_attachments sg_make_attachments(const sg_attachments_desc* desc);
  3967. SOKOL_GFX_API_DECL void sg_destroy_buffer(sg_buffer buf);
  3968. SOKOL_GFX_API_DECL void sg_destroy_image(sg_image img);
  3969. SOKOL_GFX_API_DECL void sg_destroy_sampler(sg_sampler smp);
  3970. SOKOL_GFX_API_DECL void sg_destroy_shader(sg_shader shd);
  3971. SOKOL_GFX_API_DECL void sg_destroy_pipeline(sg_pipeline pip);
  3972. SOKOL_GFX_API_DECL void sg_destroy_attachments(sg_attachments atts);
  3973. SOKOL_GFX_API_DECL void sg_update_buffer(sg_buffer buf, const sg_range* data);
  3974. SOKOL_GFX_API_DECL void sg_update_image(sg_image img, const sg_image_data* data);
  3975. SOKOL_GFX_API_DECL int sg_append_buffer(sg_buffer buf, const sg_range* data);
  3976. SOKOL_GFX_API_DECL bool sg_query_buffer_overflow(sg_buffer buf);
  3977. SOKOL_GFX_API_DECL bool sg_query_buffer_will_overflow(sg_buffer buf, size_t size);
  3978. // render and compute functions
  3979. SOKOL_GFX_API_DECL void sg_begin_pass(const sg_pass* pass);
  3980. SOKOL_GFX_API_DECL void sg_apply_viewport(int x, int y, int width, int height, bool origin_top_left);
  3981. SOKOL_GFX_API_DECL void sg_apply_viewportf(float x, float y, float width, float height, bool origin_top_left);
  3982. SOKOL_GFX_API_DECL void sg_apply_scissor_rect(int x, int y, int width, int height, bool origin_top_left);
  3983. SOKOL_GFX_API_DECL void sg_apply_scissor_rectf(float x, float y, float width, float height, bool origin_top_left);
  3984. SOKOL_GFX_API_DECL void sg_apply_pipeline(sg_pipeline pip);
  3985. SOKOL_GFX_API_DECL void sg_apply_bindings(const sg_bindings* bindings);
  3986. SOKOL_GFX_API_DECL void sg_apply_uniforms(int ub_slot, const sg_range* data);
  3987. SOKOL_GFX_API_DECL void sg_draw(int base_element, int num_elements, int num_instances);
  3988. SOKOL_GFX_API_DECL void sg_dispatch(int num_groups_x, int num_groups_y, int num_groups_z);
  3989. SOKOL_GFX_API_DECL void sg_end_pass(void);
  3990. SOKOL_GFX_API_DECL void sg_commit(void);
  3991. // getting information
  3992. SOKOL_GFX_API_DECL sg_desc sg_query_desc(void);
  3993. SOKOL_GFX_API_DECL sg_backend sg_query_backend(void);
  3994. SOKOL_GFX_API_DECL sg_features sg_query_features(void);
  3995. SOKOL_GFX_API_DECL sg_limits sg_query_limits(void);
  3996. SOKOL_GFX_API_DECL sg_pixelformat_info sg_query_pixelformat(sg_pixel_format fmt);
  3997. SOKOL_GFX_API_DECL int sg_query_row_pitch(sg_pixel_format fmt, int width, int row_align_bytes);
  3998. SOKOL_GFX_API_DECL int sg_query_surface_pitch(sg_pixel_format fmt, int width, int height, int row_align_bytes);
  3999. // get current state of a resource (INITIAL, ALLOC, VALID, FAILED, INVALID)
  4000. SOKOL_GFX_API_DECL sg_resource_state sg_query_buffer_state(sg_buffer buf);
  4001. SOKOL_GFX_API_DECL sg_resource_state sg_query_image_state(sg_image img);
  4002. SOKOL_GFX_API_DECL sg_resource_state sg_query_sampler_state(sg_sampler smp);
  4003. SOKOL_GFX_API_DECL sg_resource_state sg_query_shader_state(sg_shader shd);
  4004. SOKOL_GFX_API_DECL sg_resource_state sg_query_pipeline_state(sg_pipeline pip);
  4005. SOKOL_GFX_API_DECL sg_resource_state sg_query_attachments_state(sg_attachments atts);
  4006. // get runtime information about a resource
  4007. SOKOL_GFX_API_DECL sg_buffer_info sg_query_buffer_info(sg_buffer buf);
  4008. SOKOL_GFX_API_DECL sg_image_info sg_query_image_info(sg_image img);
  4009. SOKOL_GFX_API_DECL sg_sampler_info sg_query_sampler_info(sg_sampler smp);
  4010. SOKOL_GFX_API_DECL sg_shader_info sg_query_shader_info(sg_shader shd);
  4011. SOKOL_GFX_API_DECL sg_pipeline_info sg_query_pipeline_info(sg_pipeline pip);
  4012. SOKOL_GFX_API_DECL sg_attachments_info sg_query_attachments_info(sg_attachments atts);
  4013. // get desc structs matching a specific resource (NOTE that not all creation attributes may be provided)
  4014. SOKOL_GFX_API_DECL sg_buffer_desc sg_query_buffer_desc(sg_buffer buf);
  4015. SOKOL_GFX_API_DECL sg_image_desc sg_query_image_desc(sg_image img);
  4016. SOKOL_GFX_API_DECL sg_sampler_desc sg_query_sampler_desc(sg_sampler smp);
  4017. SOKOL_GFX_API_DECL sg_shader_desc sg_query_shader_desc(sg_shader shd);
  4018. SOKOL_GFX_API_DECL sg_pipeline_desc sg_query_pipeline_desc(sg_pipeline pip);
  4019. SOKOL_GFX_API_DECL sg_attachments_desc sg_query_attachments_desc(sg_attachments atts);
  4020. // get resource creation desc struct with their default values replaced
  4021. SOKOL_GFX_API_DECL sg_buffer_desc sg_query_buffer_defaults(const sg_buffer_desc* desc);
  4022. SOKOL_GFX_API_DECL sg_image_desc sg_query_image_defaults(const sg_image_desc* desc);
  4023. SOKOL_GFX_API_DECL sg_sampler_desc sg_query_sampler_defaults(const sg_sampler_desc* desc);
  4024. SOKOL_GFX_API_DECL sg_shader_desc sg_query_shader_defaults(const sg_shader_desc* desc);
  4025. SOKOL_GFX_API_DECL sg_pipeline_desc sg_query_pipeline_defaults(const sg_pipeline_desc* desc);
  4026. SOKOL_GFX_API_DECL sg_attachments_desc sg_query_attachments_defaults(const sg_attachments_desc* desc);
  4027. // assorted query functions
  4028. SOKOL_GFX_API_DECL size_t sg_query_buffer_size(sg_buffer buf);
  4029. SOKOL_GFX_API_DECL sg_buffer_usage sg_query_buffer_usage(sg_buffer buf);
  4030. SOKOL_GFX_API_DECL sg_image_type sg_query_image_type(sg_image img);
  4031. SOKOL_GFX_API_DECL int sg_query_image_width(sg_image img);
  4032. SOKOL_GFX_API_DECL int sg_query_image_height(sg_image img);
  4033. SOKOL_GFX_API_DECL int sg_query_image_num_slices(sg_image img);
  4034. SOKOL_GFX_API_DECL int sg_query_image_num_mipmaps(sg_image img);
  4035. SOKOL_GFX_API_DECL sg_pixel_format sg_query_image_pixelformat(sg_image img);
  4036. SOKOL_GFX_API_DECL sg_image_usage sg_query_image_usage(sg_image img);
  4037. SOKOL_GFX_API_DECL int sg_query_image_sample_count(sg_image img);
  4038. // separate resource allocation and initialization (for async setup)
  4039. SOKOL_GFX_API_DECL sg_buffer sg_alloc_buffer(void);
  4040. SOKOL_GFX_API_DECL sg_image sg_alloc_image(void);
  4041. SOKOL_GFX_API_DECL sg_sampler sg_alloc_sampler(void);
  4042. SOKOL_GFX_API_DECL sg_shader sg_alloc_shader(void);
  4043. SOKOL_GFX_API_DECL sg_pipeline sg_alloc_pipeline(void);
  4044. SOKOL_GFX_API_DECL sg_attachments sg_alloc_attachments(void);
  4045. SOKOL_GFX_API_DECL void sg_dealloc_buffer(sg_buffer buf);
  4046. SOKOL_GFX_API_DECL void sg_dealloc_image(sg_image img);
  4047. SOKOL_GFX_API_DECL void sg_dealloc_sampler(sg_sampler smp);
  4048. SOKOL_GFX_API_DECL void sg_dealloc_shader(sg_shader shd);
  4049. SOKOL_GFX_API_DECL void sg_dealloc_pipeline(sg_pipeline pip);
  4050. SOKOL_GFX_API_DECL void sg_dealloc_attachments(sg_attachments attachments);
  4051. SOKOL_GFX_API_DECL void sg_init_buffer(sg_buffer buf, const sg_buffer_desc* desc);
  4052. SOKOL_GFX_API_DECL void sg_init_image(sg_image img, const sg_image_desc* desc);
  4053. SOKOL_GFX_API_DECL void sg_init_sampler(sg_sampler smg, const sg_sampler_desc* desc);
  4054. SOKOL_GFX_API_DECL void sg_init_shader(sg_shader shd, const sg_shader_desc* desc);
  4055. SOKOL_GFX_API_DECL void sg_init_pipeline(sg_pipeline pip, const sg_pipeline_desc* desc);
  4056. SOKOL_GFX_API_DECL void sg_init_attachments(sg_attachments attachments, const sg_attachments_desc* desc);
  4057. SOKOL_GFX_API_DECL void sg_uninit_buffer(sg_buffer buf);
  4058. SOKOL_GFX_API_DECL void sg_uninit_image(sg_image img);
  4059. SOKOL_GFX_API_DECL void sg_uninit_sampler(sg_sampler smp);
  4060. SOKOL_GFX_API_DECL void sg_uninit_shader(sg_shader shd);
  4061. SOKOL_GFX_API_DECL void sg_uninit_pipeline(sg_pipeline pip);
  4062. SOKOL_GFX_API_DECL void sg_uninit_attachments(sg_attachments atts);
  4063. SOKOL_GFX_API_DECL void sg_fail_buffer(sg_buffer buf);
  4064. SOKOL_GFX_API_DECL void sg_fail_image(sg_image img);
  4065. SOKOL_GFX_API_DECL void sg_fail_sampler(sg_sampler smp);
  4066. SOKOL_GFX_API_DECL void sg_fail_shader(sg_shader shd);
  4067. SOKOL_GFX_API_DECL void sg_fail_pipeline(sg_pipeline pip);
  4068. SOKOL_GFX_API_DECL void sg_fail_attachments(sg_attachments atts);
  4069. // frame stats
  4070. SOKOL_GFX_API_DECL void sg_enable_frame_stats(void);
  4071. SOKOL_GFX_API_DECL void sg_disable_frame_stats(void);
  4072. SOKOL_GFX_API_DECL bool sg_frame_stats_enabled(void);
  4073. SOKOL_GFX_API_DECL sg_frame_stats sg_query_frame_stats(void);
  4074. /* Backend-specific structs and functions, these may come in handy for mixing
  4075. sokol-gfx rendering with 'native backend' rendering functions.
  4076. This group of functions will be expanded as needed.
  4077. */
  4078. typedef struct sg_d3d11_buffer_info {
  4079. const void* buf; // ID3D11Buffer*
  4080. } sg_d3d11_buffer_info;
  4081. typedef struct sg_d3d11_image_info {
  4082. const void* tex2d; // ID3D11Texture2D*
  4083. const void* tex3d; // ID3D11Texture3D*
  4084. const void* res; // ID3D11Resource* (either tex2d or tex3d)
  4085. const void* srv; // ID3D11ShaderResourceView*
  4086. } sg_d3d11_image_info;
  4087. typedef struct sg_d3d11_sampler_info {
  4088. const void* smp; // ID3D11SamplerState*
  4089. } sg_d3d11_sampler_info;
  4090. typedef struct sg_d3d11_shader_info {
  4091. const void* cbufs[SG_MAX_UNIFORMBLOCK_BINDSLOTS]; // ID3D11Buffer* (constant buffers by bind slot)
  4092. const void* vs; // ID3D11VertexShader*
  4093. const void* fs; // ID3D11PixelShader*
  4094. } sg_d3d11_shader_info;
  4095. typedef struct sg_d3d11_pipeline_info {
  4096. const void* il; // ID3D11InputLayout*
  4097. const void* rs; // ID3D11RasterizerState*
  4098. const void* dss; // ID3D11DepthStencilState*
  4099. const void* bs; // ID3D11BlendState*
  4100. } sg_d3d11_pipeline_info;
  4101. typedef struct sg_d3d11_attachments_info {
  4102. const void* color_rtv[SG_MAX_COLOR_ATTACHMENTS]; // ID3D11RenderTargetView
  4103. const void* dsv; // ID3D11DepthStencilView
  4104. } sg_d3d11_attachments_info;
  4105. typedef struct sg_mtl_buffer_info {
  4106. const void* buf[SG_NUM_INFLIGHT_FRAMES]; // id<MTLBuffer>
  4107. int active_slot;
  4108. } sg_mtl_buffer_info;
  4109. typedef struct sg_mtl_image_info {
  4110. const void* tex[SG_NUM_INFLIGHT_FRAMES]; // id<MTLTexture>
  4111. int active_slot;
  4112. } sg_mtl_image_info;
  4113. typedef struct sg_mtl_sampler_info {
  4114. const void* smp; // id<MTLSamplerState>
  4115. } sg_mtl_sampler_info;
  4116. typedef struct sg_mtl_shader_info {
  4117. const void* vertex_lib; // id<MTLLibrary>
  4118. const void* fragment_lib; // id<MTLLibrary>
  4119. const void* vertex_func; // id<MTLFunction>
  4120. const void* fragment_func; // id<MTLFunction>
  4121. } sg_mtl_shader_info;
  4122. typedef struct sg_mtl_pipeline_info {
  4123. const void* rps; // id<MTLRenderPipelineState>
  4124. const void* dss; // id<MTLDepthStencilState>
  4125. } sg_mtl_pipeline_info;
  4126. typedef struct sg_wgpu_buffer_info {
  4127. const void* buf; // WGPUBuffer
  4128. } sg_wgpu_buffer_info;
  4129. typedef struct sg_wgpu_image_info {
  4130. const void* tex; // WGPUTexture
  4131. const void* view; // WGPUTextureView
  4132. } sg_wgpu_image_info;
  4133. typedef struct sg_wgpu_sampler_info {
  4134. const void* smp; // WGPUSampler
  4135. } sg_wgpu_sampler_info;
  4136. typedef struct sg_wgpu_shader_info {
  4137. const void* vs_mod; // WGPUShaderModule
  4138. const void* fs_mod; // WGPUShaderModule
  4139. const void* bgl; // WGPUBindGroupLayout;
  4140. } sg_wgpu_shader_info;
  4141. typedef struct sg_wgpu_pipeline_info {
  4142. const void* render_pipeline; // WGPURenderPipeline
  4143. const void* compute_pipeline; // WGPUComputePipeline
  4144. } sg_wgpu_pipeline_info;
  4145. typedef struct sg_wgpu_attachments_info {
  4146. const void* color_view[SG_MAX_COLOR_ATTACHMENTS]; // WGPUTextureView
  4147. const void* resolve_view[SG_MAX_COLOR_ATTACHMENTS]; // WGPUTextureView
  4148. const void* ds_view; // WGPUTextureView
  4149. } sg_wgpu_attachments_info;
  4150. typedef struct sg_gl_buffer_info {
  4151. uint32_t buf[SG_NUM_INFLIGHT_FRAMES];
  4152. int active_slot;
  4153. } sg_gl_buffer_info;
  4154. typedef struct sg_gl_image_info {
  4155. uint32_t tex[SG_NUM_INFLIGHT_FRAMES];
  4156. uint32_t tex_target;
  4157. uint32_t msaa_render_buffer;
  4158. int active_slot;
  4159. } sg_gl_image_info;
  4160. typedef struct sg_gl_sampler_info {
  4161. uint32_t smp;
  4162. } sg_gl_sampler_info;
  4163. typedef struct sg_gl_shader_info {
  4164. uint32_t prog;
  4165. } sg_gl_shader_info;
  4166. typedef struct sg_gl_attachments_info {
  4167. uint32_t framebuffer;
  4168. uint32_t msaa_resolve_framebuffer[SG_MAX_COLOR_ATTACHMENTS];
  4169. } sg_gl_attachments_info;
  4170. // D3D11: return ID3D11Device
  4171. SOKOL_GFX_API_DECL const void* sg_d3d11_device(void);
  4172. // D3D11: return ID3D11DeviceContext
  4173. SOKOL_GFX_API_DECL const void* sg_d3d11_device_context(void);
  4174. // D3D11: get internal buffer resource objects
  4175. SOKOL_GFX_API_DECL sg_d3d11_buffer_info sg_d3d11_query_buffer_info(sg_buffer buf);
  4176. // D3D11: get internal image resource objects
  4177. SOKOL_GFX_API_DECL sg_d3d11_image_info sg_d3d11_query_image_info(sg_image img);
  4178. // D3D11: get internal sampler resource objects
  4179. SOKOL_GFX_API_DECL sg_d3d11_sampler_info sg_d3d11_query_sampler_info(sg_sampler smp);
  4180. // D3D11: get internal shader resource objects
  4181. SOKOL_GFX_API_DECL sg_d3d11_shader_info sg_d3d11_query_shader_info(sg_shader shd);
  4182. // D3D11: get internal pipeline resource objects
  4183. SOKOL_GFX_API_DECL sg_d3d11_pipeline_info sg_d3d11_query_pipeline_info(sg_pipeline pip);
  4184. // D3D11: get internal pass resource objects
  4185. SOKOL_GFX_API_DECL sg_d3d11_attachments_info sg_d3d11_query_attachments_info(sg_attachments atts);
  4186. // Metal: return __bridge-casted MTLDevice
  4187. SOKOL_GFX_API_DECL const void* sg_mtl_device(void);
  4188. // Metal: return __bridge-casted MTLRenderCommandEncoder when inside render pass (otherwise zero)
  4189. SOKOL_GFX_API_DECL const void* sg_mtl_render_command_encoder(void);
  4190. // Metal: return __bridge-casted MTLComputeCommandEncoder when inside compute pass (otherwise zero)
  4191. SOKOL_GFX_API_DECL const void* sg_mtl_compute_command_encoder(void);
  4192. // Metal: get internal __bridge-casted buffer resource objects
  4193. SOKOL_GFX_API_DECL sg_mtl_buffer_info sg_mtl_query_buffer_info(sg_buffer buf);
  4194. // Metal: get internal __bridge-casted image resource objects
  4195. SOKOL_GFX_API_DECL sg_mtl_image_info sg_mtl_query_image_info(sg_image img);
  4196. // Metal: get internal __bridge-casted sampler resource objects
  4197. SOKOL_GFX_API_DECL sg_mtl_sampler_info sg_mtl_query_sampler_info(sg_sampler smp);
  4198. // Metal: get internal __bridge-casted shader resource objects
  4199. SOKOL_GFX_API_DECL sg_mtl_shader_info sg_mtl_query_shader_info(sg_shader shd);
  4200. // Metal: get internal __bridge-casted pipeline resource objects
  4201. SOKOL_GFX_API_DECL sg_mtl_pipeline_info sg_mtl_query_pipeline_info(sg_pipeline pip);
  4202. // WebGPU: return WGPUDevice object
  4203. SOKOL_GFX_API_DECL const void* sg_wgpu_device(void);
  4204. // WebGPU: return WGPUQueue object
  4205. SOKOL_GFX_API_DECL const void* sg_wgpu_queue(void);
  4206. // WebGPU: return this frame's WGPUCommandEncoder
  4207. SOKOL_GFX_API_DECL const void* sg_wgpu_command_encoder(void);
  4208. // WebGPU: return WGPURenderPassEncoder of current pass (returns 0 when outside pass or in a compute pass)
  4209. SOKOL_GFX_API_DECL const void* sg_wgpu_render_pass_encoder(void);
  4210. // WebGPU: return WGPUComputePassEncoder of current pass (returns 0 when outside pass or in a render pass)
  4211. SOKOL_GFX_API_DECL const void* sg_wgpu_compute_pass_encoder(void);
  4212. // WebGPU: get internal buffer resource objects
  4213. SOKOL_GFX_API_DECL sg_wgpu_buffer_info sg_wgpu_query_buffer_info(sg_buffer buf);
  4214. // WebGPU: get internal image resource objects
  4215. SOKOL_GFX_API_DECL sg_wgpu_image_info sg_wgpu_query_image_info(sg_image img);
  4216. // WebGPU: get internal sampler resource objects
  4217. SOKOL_GFX_API_DECL sg_wgpu_sampler_info sg_wgpu_query_sampler_info(sg_sampler smp);
  4218. // WebGPU: get internal shader resource objects
  4219. SOKOL_GFX_API_DECL sg_wgpu_shader_info sg_wgpu_query_shader_info(sg_shader shd);
  4220. // WebGPU: get internal pipeline resource objects
  4221. SOKOL_GFX_API_DECL sg_wgpu_pipeline_info sg_wgpu_query_pipeline_info(sg_pipeline pip);
  4222. // WebGPU: get internal pass resource objects
  4223. SOKOL_GFX_API_DECL sg_wgpu_attachments_info sg_wgpu_query_attachments_info(sg_attachments atts);
  4224. // GL: get internal buffer resource objects
  4225. SOKOL_GFX_API_DECL sg_gl_buffer_info sg_gl_query_buffer_info(sg_buffer buf);
  4226. // GL: get internal image resource objects
  4227. SOKOL_GFX_API_DECL sg_gl_image_info sg_gl_query_image_info(sg_image img);
  4228. // GL: get internal sampler resource objects
  4229. SOKOL_GFX_API_DECL sg_gl_sampler_info sg_gl_query_sampler_info(sg_sampler smp);
  4230. // GL: get internal shader resource objects
  4231. SOKOL_GFX_API_DECL sg_gl_shader_info sg_gl_query_shader_info(sg_shader shd);
  4232. // GL: get internal pass resource objects
  4233. SOKOL_GFX_API_DECL sg_gl_attachments_info sg_gl_query_attachments_info(sg_attachments atts);
  4234. #ifdef __cplusplus
  4235. } // extern "C"
  4236. // reference-based equivalents for c++
  4237. inline void sg_setup(const sg_desc& desc) { return sg_setup(&desc); }
  4238. inline sg_buffer sg_make_buffer(const sg_buffer_desc& desc) { return sg_make_buffer(&desc); }
  4239. inline sg_image sg_make_image(const sg_image_desc& desc) { return sg_make_image(&desc); }
  4240. inline sg_sampler sg_make_sampler(const sg_sampler_desc& desc) { return sg_make_sampler(&desc); }
  4241. inline sg_shader sg_make_shader(const sg_shader_desc& desc) { return sg_make_shader(&desc); }
  4242. inline sg_pipeline sg_make_pipeline(const sg_pipeline_desc& desc) { return sg_make_pipeline(&desc); }
  4243. inline sg_attachments sg_make_attachments(const sg_attachments_desc& desc) { return sg_make_attachments(&desc); }
  4244. inline void sg_update_image(sg_image img, const sg_image_data& data) { return sg_update_image(img, &data); }
  4245. inline void sg_begin_pass(const sg_pass& pass) { return sg_begin_pass(&pass); }
  4246. inline void sg_apply_bindings(const sg_bindings& bindings) { return sg_apply_bindings(&bindings); }
  4247. inline void sg_apply_uniforms(int ub_slot, const sg_range& data) { return sg_apply_uniforms(ub_slot, &data); }
  4248. inline sg_buffer_desc sg_query_buffer_defaults(const sg_buffer_desc& desc) { return sg_query_buffer_defaults(&desc); }
  4249. inline sg_image_desc sg_query_image_defaults(const sg_image_desc& desc) { return sg_query_image_defaults(&desc); }
  4250. inline sg_sampler_desc sg_query_sampler_defaults(const sg_sampler_desc& desc) { return sg_query_sampler_defaults(&desc); }
  4251. inline sg_shader_desc sg_query_shader_defaults(const sg_shader_desc& desc) { return sg_query_shader_defaults(&desc); }
  4252. inline sg_pipeline_desc sg_query_pipeline_defaults(const sg_pipeline_desc& desc) { return sg_query_pipeline_defaults(&desc); }
  4253. inline sg_attachments_desc sg_query_attachments_defaults(const sg_attachments_desc& desc) { return sg_query_attachments_defaults(&desc); }
  4254. inline void sg_init_buffer(sg_buffer buf, const sg_buffer_desc& desc) { return sg_init_buffer(buf, &desc); }
  4255. inline void sg_init_image(sg_image img, const sg_image_desc& desc) { return sg_init_image(img, &desc); }
  4256. inline void sg_init_sampler(sg_sampler smp, const sg_sampler_desc& desc) { return sg_init_sampler(smp, &desc); }
  4257. inline void sg_init_shader(sg_shader shd, const sg_shader_desc& desc) { return sg_init_shader(shd, &desc); }
  4258. inline void sg_init_pipeline(sg_pipeline pip, const sg_pipeline_desc& desc) { return sg_init_pipeline(pip, &desc); }
  4259. inline void sg_init_attachments(sg_attachments atts, const sg_attachments_desc& desc) { return sg_init_attachments(atts, &desc); }
  4260. inline void sg_update_buffer(sg_buffer buf_id, const sg_range& data) { return sg_update_buffer(buf_id, &data); }
  4261. inline int sg_append_buffer(sg_buffer buf_id, const sg_range& data) { return sg_append_buffer(buf_id, &data); }
  4262. #endif
  4263. #endif // SOKOL_GFX_INCLUDED
  4264. // ██ ███ ███ ██████ ██ ███████ ███ ███ ███████ ███ ██ ████████ █████ ████████ ██ ██████ ███ ██
  4265. // ██ ████ ████ ██ ██ ██ ██ ████ ████ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
  4266. // ██ ██ ████ ██ ██████ ██ █████ ██ ████ ██ █████ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██
  4267. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  4268. // ██ ██ ██ ██ ███████ ███████ ██ ██ ███████ ██ ████ ██ ██ ██ ██ ██ ██████ ██ ████
  4269. //
  4270. // >>implementation
  4271. #ifdef SOKOL_GFX_IMPL
  4272. #define SOKOL_GFX_IMPL_INCLUDED (1)
  4273. #if !(defined(SOKOL_GLCORE)||defined(SOKOL_GLES3)||defined(SOKOL_D3D11)||defined(SOKOL_METAL)||defined(SOKOL_WGPU)||defined(SOKOL_DUMMY_BACKEND))
  4274. #error "Please select a backend with SOKOL_GLCORE, SOKOL_GLES3, SOKOL_D3D11, SOKOL_METAL, SOKOL_WGPU or SOKOL_DUMMY_BACKEND"
  4275. #endif
  4276. #if defined(SOKOL_MALLOC) || defined(SOKOL_CALLOC) || defined(SOKOL_FREE)
  4277. #error "SOKOL_MALLOC/CALLOC/FREE macros are no longer supported, please use sg_desc.allocator to override memory allocation functions"
  4278. #endif
  4279. #include <stdlib.h> // malloc, free, qsort
  4280. #include <string.h> // memset
  4281. #include <float.h> // FLT_MAX
  4282. #ifndef SOKOL_API_IMPL
  4283. #define SOKOL_API_IMPL
  4284. #endif
  4285. #ifndef SOKOL_DEBUG
  4286. #ifndef NDEBUG
  4287. #define SOKOL_DEBUG
  4288. #endif
  4289. #endif
  4290. #ifndef SOKOL_ASSERT
  4291. #include <assert.h>
  4292. #define SOKOL_ASSERT(c) assert(c)
  4293. #endif
  4294. #ifndef SOKOL_UNREACHABLE
  4295. #define SOKOL_UNREACHABLE SOKOL_ASSERT(false)
  4296. #endif
  4297. #ifndef _SOKOL_PRIVATE
  4298. #if defined(__GNUC__) || defined(__clang__)
  4299. #define _SOKOL_PRIVATE __attribute__((unused)) static
  4300. #else
  4301. #define _SOKOL_PRIVATE static
  4302. #endif
  4303. #endif
  4304. #ifndef _SOKOL_UNUSED
  4305. #define _SOKOL_UNUSED(x) (void)(x)
  4306. #endif
  4307. #if defined(SOKOL_TRACE_HOOKS)
  4308. #define _SG_TRACE_ARGS(fn, ...) if (_sg.hooks.fn) { _sg.hooks.fn(__VA_ARGS__, _sg.hooks.user_data); }
  4309. #define _SG_TRACE_NOARGS(fn) if (_sg.hooks.fn) { _sg.hooks.fn(_sg.hooks.user_data); }
  4310. #else
  4311. #define _SG_TRACE_ARGS(fn, ...)
  4312. #define _SG_TRACE_NOARGS(fn)
  4313. #endif
  4314. // default clear values
  4315. #ifndef SG_DEFAULT_CLEAR_RED
  4316. #define SG_DEFAULT_CLEAR_RED (0.5f)
  4317. #endif
  4318. #ifndef SG_DEFAULT_CLEAR_GREEN
  4319. #define SG_DEFAULT_CLEAR_GREEN (0.5f)
  4320. #endif
  4321. #ifndef SG_DEFAULT_CLEAR_BLUE
  4322. #define SG_DEFAULT_CLEAR_BLUE (0.5f)
  4323. #endif
  4324. #ifndef SG_DEFAULT_CLEAR_ALPHA
  4325. #define SG_DEFAULT_CLEAR_ALPHA (1.0f)
  4326. #endif
  4327. #ifndef SG_DEFAULT_CLEAR_DEPTH
  4328. #define SG_DEFAULT_CLEAR_DEPTH (1.0f)
  4329. #endif
  4330. #ifndef SG_DEFAULT_CLEAR_STENCIL
  4331. #define SG_DEFAULT_CLEAR_STENCIL (0)
  4332. #endif
  4333. #ifdef _MSC_VER
  4334. #pragma warning(push)
  4335. #pragma warning(disable:4115) // named type definition in parentheses
  4336. #pragma warning(disable:4505) // unreferenced local function has been removed
  4337. #pragma warning(disable:4201) // nonstandard extension used: nameless struct/union (needed by d3d11.h)
  4338. #pragma warning(disable:4054) // 'type cast': from function pointer
  4339. #pragma warning(disable:4055) // 'type cast': from data pointer
  4340. #endif
  4341. #if defined(SOKOL_D3D11)
  4342. #ifndef D3D11_NO_HELPERS
  4343. #define D3D11_NO_HELPERS
  4344. #endif
  4345. #ifndef WIN32_LEAN_AND_MEAN
  4346. #define WIN32_LEAN_AND_MEAN
  4347. #endif
  4348. #ifndef NOMINMAX
  4349. #define NOMINMAX
  4350. #endif
  4351. #include <d3d11.h>
  4352. #include <d3dcompiler.h>
  4353. #ifdef _MSC_VER
  4354. #pragma comment (lib, "kernel32")
  4355. #pragma comment (lib, "user32")
  4356. #pragma comment (lib, "dxgi")
  4357. #pragma comment (lib, "d3d11")
  4358. #endif
  4359. #elif defined(SOKOL_METAL)
  4360. // see https://clang.llvm.org/docs/LanguageExtensions.html#automatic-reference-counting
  4361. #if !defined(__cplusplus)
  4362. #if __has_feature(objc_arc) && !__has_feature(objc_arc_fields)
  4363. #error "sokol_gfx.h requires __has_feature(objc_arc_field) if ARC is enabled (use a more recent compiler version)"
  4364. #endif
  4365. #endif
  4366. #include <TargetConditionals.h>
  4367. #include <AvailabilityMacros.h>
  4368. #if defined(TARGET_OS_IPHONE) && !TARGET_OS_IPHONE
  4369. #define _SG_TARGET_MACOS (1)
  4370. #else
  4371. #define _SG_TARGET_IOS (1)
  4372. #if defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR
  4373. #define _SG_TARGET_IOS_SIMULATOR (1)
  4374. #endif
  4375. #endif
  4376. #import <Metal/Metal.h>
  4377. #import <QuartzCore/CoreAnimation.h> // needed for CAMetalDrawable
  4378. #elif defined(SOKOL_WGPU)
  4379. #include <webgpu/webgpu.h>
  4380. #if defined(__EMSCRIPTEN__)
  4381. #include <emscripten/emscripten.h>
  4382. #endif
  4383. #elif defined(SOKOL_GLCORE) || defined(SOKOL_GLES3)
  4384. #define _SOKOL_ANY_GL (1)
  4385. // include platform specific GL headers (or on Win32: use an embedded GL loader)
  4386. #if !defined(SOKOL_EXTERNAL_GL_LOADER)
  4387. #if defined(_WIN32)
  4388. #if defined(SOKOL_GLCORE)
  4389. #define _SOKOL_USE_WIN32_GL_LOADER (1)
  4390. #ifndef WIN32_LEAN_AND_MEAN
  4391. #define WIN32_LEAN_AND_MEAN
  4392. #endif
  4393. #ifndef NOMINMAX
  4394. #define NOMINMAX
  4395. #endif
  4396. #include <windows.h>
  4397. #pragma comment (lib, "kernel32") // GetProcAddress()
  4398. #define _SOKOL_GL_HAS_COMPUTE (1)
  4399. #define _SOKOL_GL_HAS_TEXSTORAGE (1)
  4400. #endif
  4401. #elif defined(__APPLE__)
  4402. #include <TargetConditionals.h>
  4403. #ifndef GL_SILENCE_DEPRECATION
  4404. #define GL_SILENCE_DEPRECATION
  4405. #endif
  4406. #if defined(TARGET_OS_IPHONE) && !TARGET_OS_IPHONE
  4407. #include <OpenGL/gl3.h>
  4408. #else
  4409. #include <OpenGLES/ES3/gl.h>
  4410. #include <OpenGLES/ES3/glext.h>
  4411. #define _SOKOL_GL_HAS_TEXSTORAGE (1)
  4412. #endif
  4413. #elif defined(__EMSCRIPTEN__)
  4414. #if defined(SOKOL_GLES3)
  4415. #include <GLES3/gl3.h>
  4416. #define _SOKOL_GL_HAS_TEXSTORAGE (1)
  4417. #endif
  4418. #elif defined(__ANDROID__)
  4419. #include <GLES3/gl31.h>
  4420. #define _SOKOL_GL_HAS_COMPUTE (1)
  4421. #define _SOKOL_GL_HAS_TEXSTORAGE (1)
  4422. #elif defined(__linux__) || defined(__unix__)
  4423. #if defined(SOKOL_GLCORE)
  4424. #define GL_GLEXT_PROTOTYPES
  4425. #include <GL/gl.h>
  4426. #else
  4427. #include <GLES3/gl31.h>
  4428. #include <GLES3/gl3ext.h>
  4429. #endif
  4430. #define _SOKOL_GL_HAS_COMPUTE (1)
  4431. #define _SOKOL_GL_HAS_TEXSTORAGE (1)
  4432. #endif
  4433. #endif
  4434. // optional GL loader definitions (only on Win32)
  4435. #if defined(_SOKOL_USE_WIN32_GL_LOADER)
  4436. #define __gl_h_ 1
  4437. #define __gl32_h_ 1
  4438. #define __gl31_h_ 1
  4439. #define __GL_H__ 1
  4440. #define __glext_h_ 1
  4441. #define __GLEXT_H_ 1
  4442. #define __gltypes_h_ 1
  4443. #define __glcorearb_h_ 1
  4444. #define __gl_glcorearb_h_ 1
  4445. #define GL_APIENTRY APIENTRY
  4446. typedef unsigned int GLenum;
  4447. typedef unsigned int GLuint;
  4448. typedef int GLsizei;
  4449. typedef char GLchar;
  4450. typedef ptrdiff_t GLintptr;
  4451. typedef ptrdiff_t GLsizeiptr;
  4452. typedef double GLclampd;
  4453. typedef unsigned short GLushort;
  4454. typedef unsigned char GLubyte;
  4455. typedef unsigned char GLboolean;
  4456. typedef uint64_t GLuint64;
  4457. typedef double GLdouble;
  4458. typedef unsigned short GLhalf;
  4459. typedef float GLclampf;
  4460. typedef unsigned int GLbitfield;
  4461. typedef signed char GLbyte;
  4462. typedef short GLshort;
  4463. typedef void GLvoid;
  4464. typedef int64_t GLint64;
  4465. typedef float GLfloat;
  4466. typedef int GLint;
  4467. #define GL_INT_2_10_10_10_REV 0x8D9F
  4468. #define GL_R32F 0x822E
  4469. #define GL_PROGRAM_POINT_SIZE 0x8642
  4470. #define GL_DEPTH_ATTACHMENT 0x8D00
  4471. #define GL_DEPTH_STENCIL_ATTACHMENT 0x821A
  4472. #define GL_COLOR_ATTACHMENT2 0x8CE2
  4473. #define GL_COLOR_ATTACHMENT0 0x8CE0
  4474. #define GL_R16F 0x822D
  4475. #define GL_COLOR_ATTACHMENT22 0x8CF6
  4476. #define GL_DRAW_FRAMEBUFFER 0x8CA9
  4477. #define GL_FRAMEBUFFER_COMPLETE 0x8CD5
  4478. #define GL_NUM_EXTENSIONS 0x821D
  4479. #define GL_INFO_LOG_LENGTH 0x8B84
  4480. #define GL_VERTEX_SHADER 0x8B31
  4481. #define GL_INCR 0x1E02
  4482. #define GL_DYNAMIC_DRAW 0x88E8
  4483. #define GL_STATIC_DRAW 0x88E4
  4484. #define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519
  4485. #define GL_TEXTURE_CUBE_MAP 0x8513
  4486. #define GL_FUNC_SUBTRACT 0x800A
  4487. #define GL_FUNC_REVERSE_SUBTRACT 0x800B
  4488. #define GL_CONSTANT_COLOR 0x8001
  4489. #define GL_DECR_WRAP 0x8508
  4490. #define GL_R8 0x8229
  4491. #define GL_LINEAR_MIPMAP_LINEAR 0x2703
  4492. #define GL_ELEMENT_ARRAY_BUFFER 0x8893
  4493. #define GL_SHORT 0x1402
  4494. #define GL_DEPTH_TEST 0x0B71
  4495. #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518
  4496. #define GL_LINK_STATUS 0x8B82
  4497. #define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517
  4498. #define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E
  4499. #define GL_RGBA16F 0x881A
  4500. #define GL_CONSTANT_ALPHA 0x8003
  4501. #define GL_READ_FRAMEBUFFER 0x8CA8
  4502. #define GL_TEXTURE0 0x84C0
  4503. #define GL_TEXTURE_MIN_LOD 0x813A
  4504. #define GL_CLAMP_TO_EDGE 0x812F
  4505. #define GL_UNSIGNED_SHORT_5_6_5 0x8363
  4506. #define GL_TEXTURE_WRAP_R 0x8072
  4507. #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034
  4508. #define GL_NEAREST_MIPMAP_NEAREST 0x2700
  4509. #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033
  4510. #define GL_SRC_ALPHA_SATURATE 0x0308
  4511. #define GL_STREAM_DRAW 0x88E0
  4512. #define GL_ONE 1
  4513. #define GL_NEAREST_MIPMAP_LINEAR 0x2702
  4514. #define GL_RGB10_A2 0x8059
  4515. #define GL_RGBA8 0x8058
  4516. #define GL_SRGB8_ALPHA8 0x8C43
  4517. #define GL_COLOR_ATTACHMENT1 0x8CE1
  4518. #define GL_RGBA4 0x8056
  4519. #define GL_RGB8 0x8051
  4520. #define GL_ARRAY_BUFFER 0x8892
  4521. #define GL_STENCIL 0x1802
  4522. #define GL_TEXTURE_2D 0x0DE1
  4523. #define GL_DEPTH 0x1801
  4524. #define GL_FRONT 0x0404
  4525. #define GL_STENCIL_BUFFER_BIT 0x00000400
  4526. #define GL_REPEAT 0x2901
  4527. #define GL_RGBA 0x1908
  4528. #define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515
  4529. #define GL_DECR 0x1E03
  4530. #define GL_FRAGMENT_SHADER 0x8B30
  4531. #define GL_COMPUTE_SHADER 0x91B9
  4532. #define GL_FLOAT 0x1406
  4533. #define GL_TEXTURE_MAX_LOD 0x813B
  4534. #define GL_DEPTH_COMPONENT 0x1902
  4535. #define GL_ONE_MINUS_DST_ALPHA 0x0305
  4536. #define GL_COLOR 0x1800
  4537. #define GL_TEXTURE_2D_ARRAY 0x8C1A
  4538. #define GL_TRIANGLES 0x0004
  4539. #define GL_UNSIGNED_BYTE 0x1401
  4540. #define GL_TEXTURE_MAG_FILTER 0x2800
  4541. #define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004
  4542. #define GL_NONE 0
  4543. #define GL_SRC_COLOR 0x0300
  4544. #define GL_BYTE 0x1400
  4545. #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A
  4546. #define GL_LINE_STRIP 0x0003
  4547. #define GL_TEXTURE_3D 0x806F
  4548. #define GL_CW 0x0900
  4549. #define GL_LINEAR 0x2601
  4550. #define GL_RENDERBUFFER 0x8D41
  4551. #define GL_GEQUAL 0x0206
  4552. #define GL_COLOR_BUFFER_BIT 0x00004000
  4553. #define GL_RGBA32F 0x8814
  4554. #define GL_BLEND 0x0BE2
  4555. #define GL_ONE_MINUS_SRC_ALPHA 0x0303
  4556. #define GL_ONE_MINUS_CONSTANT_COLOR 0x8002
  4557. #define GL_TEXTURE_WRAP_T 0x2803
  4558. #define GL_TEXTURE_WRAP_S 0x2802
  4559. #define GL_TEXTURE_MIN_FILTER 0x2801
  4560. #define GL_LINEAR_MIPMAP_NEAREST 0x2701
  4561. #define GL_EXTENSIONS 0x1F03
  4562. #define GL_NO_ERROR 0
  4563. #define GL_REPLACE 0x1E01
  4564. #define GL_KEEP 0x1E00
  4565. #define GL_CCW 0x0901
  4566. #define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516
  4567. #define GL_RGB 0x1907
  4568. #define GL_TRIANGLE_STRIP 0x0005
  4569. #define GL_FALSE 0
  4570. #define GL_ZERO 0
  4571. #define GL_CULL_FACE 0x0B44
  4572. #define GL_INVERT 0x150A
  4573. #define GL_INT 0x1404
  4574. #define GL_UNSIGNED_INT 0x1405
  4575. #define GL_UNSIGNED_SHORT 0x1403
  4576. #define GL_NEAREST 0x2600
  4577. #define GL_SCISSOR_TEST 0x0C11
  4578. #define GL_LEQUAL 0x0203
  4579. #define GL_STENCIL_TEST 0x0B90
  4580. #define GL_DITHER 0x0BD0
  4581. #define GL_DEPTH_COMPONENT32F 0x8CAC
  4582. #define GL_EQUAL 0x0202
  4583. #define GL_FRAMEBUFFER 0x8D40
  4584. #define GL_RGB5 0x8050
  4585. #define GL_LINES 0x0001
  4586. #define GL_DEPTH_BUFFER_BIT 0x00000100
  4587. #define GL_SRC_ALPHA 0x0302
  4588. #define GL_INCR_WRAP 0x8507
  4589. #define GL_LESS 0x0201
  4590. #define GL_MULTISAMPLE 0x809D
  4591. #define GL_FRAMEBUFFER_BINDING 0x8CA6
  4592. #define GL_BACK 0x0405
  4593. #define GL_ALWAYS 0x0207
  4594. #define GL_FUNC_ADD 0x8006
  4595. #define GL_ONE_MINUS_DST_COLOR 0x0307
  4596. #define GL_NOTEQUAL 0x0205
  4597. #define GL_DST_COLOR 0x0306
  4598. #define GL_COMPILE_STATUS 0x8B81
  4599. #define GL_RED 0x1903
  4600. #define GL_COLOR_ATTACHMENT3 0x8CE3
  4601. #define GL_DST_ALPHA 0x0304
  4602. #define GL_RGB5_A1 0x8057
  4603. #define GL_GREATER 0x0204
  4604. #define GL_POLYGON_OFFSET_FILL 0x8037
  4605. #define GL_TRUE 1
  4606. #define GL_NEVER 0x0200
  4607. #define GL_POINTS 0x0000
  4608. #define GL_ONE_MINUS_SRC_COLOR 0x0301
  4609. #define GL_MIRRORED_REPEAT 0x8370
  4610. #define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D
  4611. #define GL_R11F_G11F_B10F 0x8C3A
  4612. #define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B
  4613. #define GL_RGB9_E5 0x8C3D
  4614. #define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E
  4615. #define GL_RGBA32UI 0x8D70
  4616. #define GL_RGB32UI 0x8D71
  4617. #define GL_RGBA16UI 0x8D76
  4618. #define GL_RGB16UI 0x8D77
  4619. #define GL_RGBA8UI 0x8D7C
  4620. #define GL_RGB8UI 0x8D7D
  4621. #define GL_RGBA32I 0x8D82
  4622. #define GL_RGB32I 0x8D83
  4623. #define GL_RGBA16I 0x8D88
  4624. #define GL_RGB16I 0x8D89
  4625. #define GL_RGBA8I 0x8D8E
  4626. #define GL_RGB8I 0x8D8F
  4627. #define GL_RED_INTEGER 0x8D94
  4628. #define GL_RG 0x8227
  4629. #define GL_RG_INTEGER 0x8228
  4630. #define GL_R8 0x8229
  4631. #define GL_R16 0x822A
  4632. #define GL_RG8 0x822B
  4633. #define GL_RG16 0x822C
  4634. #define GL_R16F 0x822D
  4635. #define GL_R32F 0x822E
  4636. #define GL_RG16F 0x822F
  4637. #define GL_RG32F 0x8230
  4638. #define GL_R8I 0x8231
  4639. #define GL_R8UI 0x8232
  4640. #define GL_R16I 0x8233
  4641. #define GL_R16UI 0x8234
  4642. #define GL_R32I 0x8235
  4643. #define GL_R32UI 0x8236
  4644. #define GL_RG8I 0x8237
  4645. #define GL_RG8UI 0x8238
  4646. #define GL_RG16I 0x8239
  4647. #define GL_RG16UI 0x823A
  4648. #define GL_RG32I 0x823B
  4649. #define GL_RG32UI 0x823C
  4650. #define GL_RGBA_INTEGER 0x8D99
  4651. #define GL_R8_SNORM 0x8F94
  4652. #define GL_RG8_SNORM 0x8F95
  4653. #define GL_RGB8_SNORM 0x8F96
  4654. #define GL_RGBA8_SNORM 0x8F97
  4655. #define GL_R16_SNORM 0x8F98
  4656. #define GL_RG16_SNORM 0x8F99
  4657. #define GL_RGB16_SNORM 0x8F9A
  4658. #define GL_RGBA16_SNORM 0x8F9B
  4659. #define GL_RGBA16 0x805B
  4660. #define GL_MAX_TEXTURE_SIZE 0x0D33
  4661. #define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C
  4662. #define GL_MAX_3D_TEXTURE_SIZE 0x8073
  4663. #define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF
  4664. #define GL_MAX_VERTEX_ATTRIBS 0x8869
  4665. #define GL_CLAMP_TO_BORDER 0x812D
  4666. #define GL_TEXTURE_BORDER_COLOR 0x1004
  4667. #define GL_CURRENT_PROGRAM 0x8B8D
  4668. #define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A
  4669. #define GL_UNPACK_ALIGNMENT 0x0CF5
  4670. #define GL_FRAMEBUFFER_SRGB 0x8DB9
  4671. #define GL_TEXTURE_COMPARE_MODE 0x884C
  4672. #define GL_TEXTURE_COMPARE_FUNC 0x884D
  4673. #define GL_COMPARE_REF_TO_TEXTURE 0x884E
  4674. #define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F
  4675. #define GL_TEXTURE_MAX_LEVEL 0x813D
  4676. #define GL_FRAMEBUFFER_UNDEFINED 0x8219
  4677. #define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6
  4678. #define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7
  4679. #define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD
  4680. #define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56
  4681. #define GL_MAJOR_VERSION 0x821B
  4682. #define GL_MINOR_VERSION 0x821C
  4683. #define GL_TEXTURE_2D_MULTISAMPLE 0x9100
  4684. #define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102
  4685. #define GL_SHADER_STORAGE_BARRIER_BIT 0x2000
  4686. #define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001
  4687. #define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002
  4688. #define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008
  4689. #define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020
  4690. #define GL_MIN 0x8007
  4691. #define GL_MAX 0x8008
  4692. #define GL_WRITE_ONLY 0x88B9
  4693. #define GL_READ_WRITE 0x88BA
  4694. #endif
  4695. #ifndef GL_UNSIGNED_INT_2_10_10_10_REV
  4696. #define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368
  4697. #endif
  4698. #ifndef GL_UNSIGNED_INT_24_8
  4699. #define GL_UNSIGNED_INT_24_8 0x84FA
  4700. #endif
  4701. #ifndef GL_TEXTURE_MAX_ANISOTROPY_EXT
  4702. #define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
  4703. #endif
  4704. #ifndef GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT
  4705. #define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
  4706. #endif
  4707. #ifndef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
  4708. #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
  4709. #endif
  4710. #ifndef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
  4711. #define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
  4712. #endif
  4713. #ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
  4714. #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
  4715. #endif
  4716. #ifndef GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT
  4717. #define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT 0x8C4F
  4718. #endif
  4719. #ifndef GL_COMPRESSED_RED_RGTC1
  4720. #define GL_COMPRESSED_RED_RGTC1 0x8DBB
  4721. #endif
  4722. #ifndef GL_COMPRESSED_SIGNED_RED_RGTC1
  4723. #define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC
  4724. #endif
  4725. #ifndef GL_COMPRESSED_RED_GREEN_RGTC2
  4726. #define GL_COMPRESSED_RED_GREEN_RGTC2 0x8DBD
  4727. #endif
  4728. #ifndef GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2
  4729. #define GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2 0x8DBE
  4730. #endif
  4731. #ifndef GL_COMPRESSED_RGBA_BPTC_UNORM_ARB
  4732. #define GL_COMPRESSED_RGBA_BPTC_UNORM_ARB 0x8E8C
  4733. #endif
  4734. #ifndef GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB
  4735. #define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB 0x8E8D
  4736. #endif
  4737. #ifndef GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB
  4738. #define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB 0x8E8E
  4739. #endif
  4740. #ifndef GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB
  4741. #define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB 0x8E8F
  4742. #endif
  4743. #ifndef GL_COMPRESSED_RGB8_ETC2
  4744. #define GL_COMPRESSED_RGB8_ETC2 0x9274
  4745. #endif
  4746. #ifndef GL_COMPRESSED_SRGB8_ETC2
  4747. #define GL_COMPRESSED_SRGB8_ETC2 0x9275
  4748. #endif
  4749. #ifndef GL_COMPRESSED_RGBA8_ETC2_EAC
  4750. #define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278
  4751. #endif
  4752. #ifndef GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC
  4753. #define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279
  4754. #endif
  4755. #ifndef GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2
  4756. #define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276
  4757. #endif
  4758. #ifndef GL_COMPRESSED_R11_EAC
  4759. #define GL_COMPRESSED_R11_EAC 0x9270
  4760. #endif
  4761. #ifndef GL_COMPRESSED_SIGNED_R11_EAC
  4762. #define GL_COMPRESSED_SIGNED_R11_EAC 0x9271
  4763. #endif
  4764. #ifndef GL_COMPRESSED_RG11_EAC
  4765. #define GL_COMPRESSED_RG11_EAC 0x9272
  4766. #endif
  4767. #ifndef GL_COMPRESSED_SIGNED_RG11_EAC
  4768. #define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273
  4769. #endif
  4770. #ifndef GL_COMPRESSED_RGBA_ASTC_4x4_KHR
  4771. #define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93B0
  4772. #endif
  4773. #ifndef GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR
  4774. #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 0x93D0
  4775. #endif
  4776. #ifndef GL_DEPTH24_STENCIL8
  4777. #define GL_DEPTH24_STENCIL8 0x88F0
  4778. #endif
  4779. #ifndef GL_HALF_FLOAT
  4780. #define GL_HALF_FLOAT 0x140B
  4781. #endif
  4782. #ifndef GL_DEPTH_STENCIL
  4783. #define GL_DEPTH_STENCIL 0x84F9
  4784. #endif
  4785. #ifndef GL_LUMINANCE
  4786. #define GL_LUMINANCE 0x1909
  4787. #endif
  4788. #ifndef GL_COMPUTE_SHADER
  4789. #define GL_COMPUTE_SHADER 0x91B9
  4790. #endif
  4791. #ifndef _SG_GL_CHECK_ERROR
  4792. #define _SG_GL_CHECK_ERROR() { SOKOL_ASSERT(glGetError() == GL_NO_ERROR); }
  4793. #endif
  4794. // make some GL constants generally available to simplify compilation,
  4795. // use of those constants will be filtered by runtime flags
  4796. #ifndef GL_SHADER_STORAGE_BUFFER
  4797. #define GL_SHADER_STORAGE_BUFFER 0x90D2
  4798. #endif
  4799. #endif
  4800. #if defined(SOKOL_GLES3)
  4801. // on WebGL2, GL_FRAMEBUFFER_UNDEFINED technically doesn't exist (it is defined
  4802. // in the Emscripten headers, but may not exist in other WebGL2 shims)
  4803. // see: https://github.com/floooh/sokol/pull/933
  4804. #ifndef GL_FRAMEBUFFER_UNDEFINED
  4805. #define GL_FRAMEBUFFER_UNDEFINED 0x8219
  4806. #endif
  4807. #endif
  4808. // ███████ ████████ ██████ ██ ██ ██████ ████████ ███████
  4809. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  4810. // ███████ ██ ██████ ██ ██ ██ ██ ███████
  4811. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  4812. // ███████ ██ ██ ██ ██████ ██████ ██ ███████
  4813. //
  4814. // >>structs
  4815. // resource pool slots
  4816. typedef struct {
  4817. uint32_t id;
  4818. uint32_t uninit_count;
  4819. sg_resource_state state;
  4820. } _sg_slot_t;
  4821. // resource pool housekeeping struct
  4822. typedef struct {
  4823. int size;
  4824. int queue_top;
  4825. uint32_t* gen_ctrs;
  4826. int* free_queue;
  4827. } _sg_pool_t;
  4828. // resource func forward decls
  4829. struct _sg_buffer_s;
  4830. struct _sg_image_s;
  4831. struct _sg_sampler_s;
  4832. struct _sg_shader_s;
  4833. struct _sg_pipeline_s;
  4834. struct _sg_attachments_s;
  4835. // a general resource slot reference useful for caches
  4836. typedef struct _sg_sref_s {
  4837. uint32_t id;
  4838. uint32_t uninit_count;
  4839. } _sg_sref_t;
  4840. // safe (in debug mode) internal resource references
  4841. typedef struct _sg_buffer_ref_s {
  4842. struct _sg_buffer_s* ptr;
  4843. _sg_sref_t sref;
  4844. } _sg_buffer_ref_t;
  4845. typedef struct _sg_image_ref_s {
  4846. struct _sg_image_s* ptr;
  4847. _sg_sref_t sref;
  4848. } _sg_image_ref_t;
  4849. typedef struct _sg_sampler_ref_t {
  4850. struct _sg_sampler_s* ptr;
  4851. _sg_sref_t sref;
  4852. } _sg_sampler_ref_t;
  4853. typedef struct _sg_shader_ref_s {
  4854. struct _sg_shader_s* ptr;
  4855. _sg_sref_t sref;
  4856. } _sg_shader_ref_t;
  4857. typedef struct _sg_pipeline_ref_s {
  4858. struct _sg_pipeline_s* ptr;
  4859. _sg_sref_t sref;
  4860. } _sg_pipeline_ref_t;
  4861. typedef struct _sg_attachments_ref_s {
  4862. struct _sg_attachments_s* ptr;
  4863. _sg_sref_t sref;
  4864. } _sg_attachments_ref_t;
  4865. // resource tracking (for keeping track of gpu-written storage resources
  4866. typedef struct {
  4867. uint32_t size;
  4868. uint32_t cur;
  4869. uint32_t* items;
  4870. } _sg_tracker_t;
  4871. // constants
  4872. enum {
  4873. _SG_STRING_SIZE = 32,
  4874. _SG_SLOT_SHIFT = 16,
  4875. _SG_SLOT_MASK = (1<<_SG_SLOT_SHIFT)-1,
  4876. _SG_MAX_POOL_SIZE = (1<<_SG_SLOT_SHIFT),
  4877. _SG_DEFAULT_BUFFER_POOL_SIZE = 128,
  4878. _SG_DEFAULT_IMAGE_POOL_SIZE = 128,
  4879. _SG_DEFAULT_SAMPLER_POOL_SIZE = 64,
  4880. _SG_DEFAULT_SHADER_POOL_SIZE = 32,
  4881. _SG_DEFAULT_PIPELINE_POOL_SIZE = 64,
  4882. _SG_DEFAULT_ATTACHMENTS_POOL_SIZE = 16,
  4883. _SG_DEFAULT_UB_SIZE = 4 * 1024 * 1024,
  4884. _SG_DEFAULT_MAX_DISPATCH_CALLS_PER_PASS = 1024,
  4885. _SG_DEFAULT_MAX_COMMIT_LISTENERS = 1024,
  4886. _SG_DEFAULT_WGPU_BINDGROUP_CACHE_SIZE = 1024,
  4887. };
  4888. // fixed-size string
  4889. typedef struct {
  4890. char buf[_SG_STRING_SIZE];
  4891. } _sg_str_t;
  4892. typedef struct {
  4893. int size;
  4894. int append_pos;
  4895. bool append_overflow;
  4896. uint32_t update_frame_index;
  4897. uint32_t append_frame_index;
  4898. int num_slots;
  4899. int active_slot;
  4900. sg_buffer_usage usage;
  4901. } _sg_buffer_common_t;
  4902. typedef struct {
  4903. uint32_t upd_frame_index;
  4904. int num_slots;
  4905. int active_slot;
  4906. sg_image_type type;
  4907. int width;
  4908. int height;
  4909. int num_slices;
  4910. int num_mipmaps;
  4911. sg_image_usage usage;
  4912. sg_pixel_format pixel_format;
  4913. int sample_count;
  4914. } _sg_image_common_t;
  4915. typedef struct {
  4916. sg_filter min_filter;
  4917. sg_filter mag_filter;
  4918. sg_filter mipmap_filter;
  4919. sg_wrap wrap_u;
  4920. sg_wrap wrap_v;
  4921. sg_wrap wrap_w;
  4922. float min_lod;
  4923. float max_lod;
  4924. sg_border_color border_color;
  4925. sg_compare_func compare;
  4926. uint32_t max_anisotropy;
  4927. } _sg_sampler_common_t;
  4928. typedef struct {
  4929. sg_shader_attr_base_type base_type;
  4930. } _sg_shader_attr_t;
  4931. typedef struct {
  4932. sg_shader_stage stage;
  4933. uint32_t size;
  4934. } _sg_shader_uniform_block_t;
  4935. typedef struct {
  4936. sg_shader_stage stage;
  4937. bool readonly;
  4938. } _sg_shader_storage_buffer_t;
  4939. typedef struct {
  4940. sg_shader_stage stage;
  4941. sg_image_type image_type;
  4942. sg_pixel_format access_format;
  4943. bool writeonly;
  4944. } _sg_shader_storage_image_t;
  4945. typedef struct {
  4946. sg_shader_stage stage;
  4947. sg_image_type image_type;
  4948. sg_image_sample_type sample_type;
  4949. bool multisampled;
  4950. } _sg_shader_image_t;
  4951. typedef struct {
  4952. sg_shader_stage stage;
  4953. sg_sampler_type sampler_type;
  4954. } _sg_shader_sampler_t;
  4955. typedef struct {
  4956. sg_shader_stage stage;
  4957. uint8_t image_slot;
  4958. uint8_t sampler_slot;
  4959. } _sg_shader_image_sampler_t;
  4960. typedef struct {
  4961. uint32_t required_bindings_and_uniforms;
  4962. bool is_compute;
  4963. _sg_shader_attr_t attrs[SG_MAX_VERTEX_ATTRIBUTES];
  4964. _sg_shader_uniform_block_t uniform_blocks[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  4965. _sg_shader_storage_buffer_t storage_buffers[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  4966. _sg_shader_image_t images[SG_MAX_IMAGE_BINDSLOTS];
  4967. _sg_shader_sampler_t samplers[SG_MAX_SAMPLER_BINDSLOTS];
  4968. _sg_shader_image_sampler_t image_samplers[SG_MAX_IMAGE_SAMPLER_PAIRS];
  4969. _sg_shader_storage_image_t storage_images[SG_MAX_STORAGE_ATTACHMENTS];
  4970. } _sg_shader_common_t;
  4971. typedef struct {
  4972. bool vertex_buffer_layout_active[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  4973. bool use_instanced_draw;
  4974. bool is_compute;
  4975. uint32_t required_bindings_and_uniforms;
  4976. _sg_shader_ref_t shader;
  4977. sg_vertex_layout_state layout;
  4978. sg_depth_state depth;
  4979. sg_stencil_state stencil;
  4980. int color_count;
  4981. sg_color_target_state colors[SG_MAX_COLOR_ATTACHMENTS];
  4982. sg_primitive_type primitive_type;
  4983. sg_index_type index_type;
  4984. sg_cull_mode cull_mode;
  4985. sg_face_winding face_winding;
  4986. int sample_count;
  4987. sg_color blend_color;
  4988. bool alpha_to_coverage_enabled;
  4989. } _sg_pipeline_common_t;
  4990. typedef struct {
  4991. _sg_image_ref_t image;
  4992. int mip_level;
  4993. int slice;
  4994. } _sg_attachment_common_t;
  4995. typedef struct {
  4996. int width;
  4997. int height;
  4998. int num_colors;
  4999. bool has_render_attachments;
  5000. bool has_storage_attachments;
  5001. _sg_attachment_common_t colors[SG_MAX_COLOR_ATTACHMENTS];
  5002. _sg_attachment_common_t resolves[SG_MAX_COLOR_ATTACHMENTS];
  5003. _sg_attachment_common_t depth_stencil;
  5004. _sg_attachment_common_t storages[SG_MAX_STORAGE_ATTACHMENTS];
  5005. } _sg_attachments_common_t;
  5006. #if defined(SOKOL_DUMMY_BACKEND)
  5007. typedef struct _sg_buffer_s {
  5008. _sg_slot_t slot;
  5009. _sg_buffer_common_t cmn;
  5010. } _sg_dummy_buffer_t;
  5011. typedef _sg_dummy_buffer_t _sg_buffer_t;
  5012. typedef struct _sg_image_s {
  5013. _sg_slot_t slot;
  5014. _sg_image_common_t cmn;
  5015. } _sg_dummy_image_t;
  5016. typedef _sg_dummy_image_t _sg_image_t;
  5017. typedef struct _sg_sampler_s {
  5018. _sg_slot_t slot;
  5019. _sg_sampler_common_t cmn;
  5020. } _sg_dummy_sampler_t;
  5021. typedef _sg_dummy_sampler_t _sg_sampler_t;
  5022. typedef struct _sg_shader_s {
  5023. _sg_slot_t slot;
  5024. _sg_shader_common_t cmn;
  5025. } _sg_dummy_shader_t;
  5026. typedef _sg_dummy_shader_t _sg_shader_t;
  5027. typedef struct _sg_pipeline_s {
  5028. _sg_slot_t slot;
  5029. _sg_pipeline_common_t cmn;
  5030. } _sg_dummy_pipeline_t;
  5031. typedef _sg_dummy_pipeline_t _sg_pipeline_t;
  5032. typedef struct _sg_attachments_s {
  5033. _sg_slot_t slot;
  5034. _sg_attachments_common_t cmn;
  5035. } _sg_dummy_attachments_t;
  5036. typedef _sg_dummy_attachments_t _sg_attachments_t;
  5037. #elif defined(_SOKOL_ANY_GL)
  5038. typedef enum {
  5039. _SG_GL_GPUDIRTY_VERTEXBUFFER = (1<<0),
  5040. _SG_GL_GPUDIRTY_INDEXBUFFER = (1<<1),
  5041. _SG_GL_GPUDIRTY_STORAGEBUFFER = (1<<2),
  5042. _SG_GL_GPUDIRTY_BUFFER_ALL = _SG_GL_GPUDIRTY_VERTEXBUFFER | _SG_GL_GPUDIRTY_INDEXBUFFER | _SG_GL_GPUDIRTY_STORAGEBUFFER,
  5043. } _sg_gl_gpudirty_t;
  5044. typedef struct _sg_buffer_s {
  5045. _sg_slot_t slot;
  5046. _sg_buffer_common_t cmn;
  5047. struct {
  5048. GLuint buf[SG_NUM_INFLIGHT_FRAMES];
  5049. bool injected; // if true, external buffers were injected with sg_buffer_desc.gl_buffers
  5050. uint8_t gpu_dirty_flags; // combination of _sg_gl_gpudirty_t flags
  5051. } gl;
  5052. } _sg_gl_buffer_t;
  5053. typedef _sg_gl_buffer_t _sg_buffer_t;
  5054. typedef struct _sg_image_s {
  5055. _sg_slot_t slot;
  5056. _sg_image_common_t cmn;
  5057. struct {
  5058. GLenum target;
  5059. GLuint msaa_render_buffer;
  5060. GLuint tex[SG_NUM_INFLIGHT_FRAMES];
  5061. bool injected; // if true, external textures were injected with sg_image_desc.gl_textures
  5062. } gl;
  5063. } _sg_gl_image_t;
  5064. typedef _sg_gl_image_t _sg_image_t;
  5065. typedef struct _sg_sampler_s {
  5066. _sg_slot_t slot;
  5067. _sg_sampler_common_t cmn;
  5068. struct {
  5069. GLuint smp;
  5070. bool injected; // true if external sampler was injects in sg_sampler_desc.gl_sampler
  5071. } gl;
  5072. } _sg_gl_sampler_t;
  5073. typedef _sg_gl_sampler_t _sg_sampler_t;
  5074. typedef struct {
  5075. GLint gl_loc;
  5076. sg_uniform_type type;
  5077. uint16_t count;
  5078. uint16_t offset;
  5079. } _sg_gl_uniform_t;
  5080. typedef struct {
  5081. int num_uniforms;
  5082. _sg_gl_uniform_t uniforms[SG_MAX_UNIFORMBLOCK_MEMBERS];
  5083. } _sg_gl_uniform_block_t;
  5084. typedef struct {
  5085. _sg_str_t name;
  5086. } _sg_gl_shader_attr_t;
  5087. typedef struct _sg_shader_s {
  5088. _sg_slot_t slot;
  5089. _sg_shader_common_t cmn;
  5090. struct {
  5091. GLuint prog;
  5092. _sg_gl_shader_attr_t attrs[SG_MAX_VERTEX_ATTRIBUTES];
  5093. _sg_gl_uniform_block_t uniform_blocks[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  5094. uint8_t sbuf_binding[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  5095. uint8_t simg_binding[SG_MAX_STORAGE_ATTACHMENTS];
  5096. int8_t tex_slot[SG_MAX_IMAGE_SAMPLER_PAIRS]; // GL texture unit index
  5097. } gl;
  5098. } _sg_gl_shader_t;
  5099. typedef _sg_gl_shader_t _sg_shader_t;
  5100. typedef struct {
  5101. int8_t vb_index; // -1 if attr is not enabled
  5102. int8_t divisor; // -1 if not initialized
  5103. uint8_t stride;
  5104. uint8_t size;
  5105. uint8_t normalized;
  5106. int offset;
  5107. GLenum type;
  5108. sg_shader_attr_base_type base_type;
  5109. } _sg_gl_attr_t;
  5110. typedef struct _sg_pipeline_s {
  5111. _sg_slot_t slot;
  5112. _sg_pipeline_common_t cmn;
  5113. struct {
  5114. _sg_gl_attr_t attrs[SG_MAX_VERTEX_ATTRIBUTES];
  5115. sg_depth_state depth;
  5116. sg_stencil_state stencil;
  5117. sg_primitive_type primitive_type;
  5118. sg_blend_state blend;
  5119. sg_color_mask color_write_mask[SG_MAX_COLOR_ATTACHMENTS];
  5120. sg_cull_mode cull_mode;
  5121. sg_face_winding face_winding;
  5122. int sample_count;
  5123. bool alpha_to_coverage_enabled;
  5124. } gl;
  5125. } _sg_gl_pipeline_t;
  5126. typedef _sg_gl_pipeline_t _sg_pipeline_t;
  5127. typedef struct _sg_attachments_s {
  5128. _sg_slot_t slot;
  5129. _sg_attachments_common_t cmn;
  5130. struct {
  5131. GLuint fb;
  5132. GLuint msaa_resolve_framebuffer[SG_MAX_COLOR_ATTACHMENTS];
  5133. } gl;
  5134. } _sg_gl_attachments_t;
  5135. typedef _sg_gl_attachments_t _sg_attachments_t;
  5136. typedef struct {
  5137. _sg_gl_attr_t gl_attr;
  5138. GLuint gl_vbuf;
  5139. } _sg_gl_cache_attr_t;
  5140. typedef struct {
  5141. GLenum target;
  5142. GLuint texture;
  5143. GLuint sampler;
  5144. } _sg_gl_cache_texture_sampler_bind_slot;
  5145. #define _SG_GL_MAX_SBUF_BINDINGS (SG_MAX_STORAGEBUFFER_BINDSLOTS)
  5146. #define _SG_GL_MAX_SIMG_BINDINGS (SG_MAX_STORAGE_ATTACHMENTS)
  5147. #define _SG_GL_MAX_IMG_SMP_BINDINGS (SG_MAX_IMAGE_SAMPLER_PAIRS)
  5148. typedef struct {
  5149. sg_depth_state depth;
  5150. sg_stencil_state stencil;
  5151. sg_blend_state blend;
  5152. sg_color_mask color_write_mask[SG_MAX_COLOR_ATTACHMENTS];
  5153. sg_cull_mode cull_mode;
  5154. sg_face_winding face_winding;
  5155. bool polygon_offset_enabled;
  5156. int sample_count;
  5157. sg_color blend_color;
  5158. bool alpha_to_coverage_enabled;
  5159. _sg_gl_cache_attr_t attrs[SG_MAX_VERTEX_ATTRIBUTES];
  5160. GLuint vertex_buffer;
  5161. GLuint index_buffer;
  5162. GLuint storage_buffer; // general bind point
  5163. GLuint storage_buffers[_SG_GL_MAX_SBUF_BINDINGS];
  5164. GLuint stored_vertex_buffer;
  5165. GLuint stored_index_buffer;
  5166. GLuint stored_storage_buffer;
  5167. GLuint prog;
  5168. _sg_gl_cache_texture_sampler_bind_slot texture_samplers[_SG_GL_MAX_IMG_SMP_BINDINGS];
  5169. _sg_gl_cache_texture_sampler_bind_slot stored_texture_sampler;
  5170. int cur_ib_offset;
  5171. GLenum cur_primitive_type;
  5172. GLenum cur_index_type;
  5173. GLenum cur_active_texture;
  5174. _sg_sref_t cur_pip;
  5175. } _sg_gl_state_cache_t;
  5176. typedef struct {
  5177. bool valid;
  5178. GLuint vao;
  5179. _sg_gl_state_cache_t cache;
  5180. bool ext_anisotropic;
  5181. GLint max_anisotropy;
  5182. sg_store_action color_store_actions[SG_MAX_COLOR_ATTACHMENTS];
  5183. sg_store_action depth_store_action;
  5184. sg_store_action stencil_store_action;
  5185. #if _SOKOL_USE_WIN32_GL_LOADER
  5186. HINSTANCE opengl32_dll;
  5187. #endif
  5188. } _sg_gl_backend_t;
  5189. #elif defined(SOKOL_D3D11)
  5190. typedef struct _sg_buffer_s {
  5191. _sg_slot_t slot;
  5192. _sg_buffer_common_t cmn;
  5193. struct {
  5194. ID3D11Buffer* buf;
  5195. ID3D11ShaderResourceView* srv;
  5196. ID3D11UnorderedAccessView* uav;
  5197. } d3d11;
  5198. } _sg_d3d11_buffer_t;
  5199. typedef _sg_d3d11_buffer_t _sg_buffer_t;
  5200. typedef struct _sg_image_s {
  5201. _sg_slot_t slot;
  5202. _sg_image_common_t cmn;
  5203. struct {
  5204. DXGI_FORMAT format;
  5205. ID3D11Texture2D* tex2d;
  5206. ID3D11Texture3D* tex3d;
  5207. ID3D11Resource* res; // either tex2d or tex3d
  5208. ID3D11ShaderResourceView* srv;
  5209. } d3d11;
  5210. } _sg_d3d11_image_t;
  5211. typedef _sg_d3d11_image_t _sg_image_t;
  5212. typedef struct _sg_sampler_s {
  5213. _sg_slot_t slot;
  5214. _sg_sampler_common_t cmn;
  5215. struct {
  5216. ID3D11SamplerState* smp;
  5217. } d3d11;
  5218. } _sg_d3d11_sampler_t;
  5219. typedef _sg_d3d11_sampler_t _sg_sampler_t;
  5220. typedef struct {
  5221. _sg_str_t sem_name;
  5222. int sem_index;
  5223. } _sg_d3d11_shader_attr_t;
  5224. #define _SG_D3D11_MAX_STAGE_UB_BINDINGS (SG_MAX_UNIFORMBLOCK_BINDSLOTS)
  5225. #define _SG_D3D11_MAX_STAGE_SRV_BINDINGS (SG_MAX_IMAGE_BINDSLOTS + SG_MAX_STORAGEBUFFER_BINDSLOTS)
  5226. #define _SG_D3D11_MAX_STAGE_UAV_BINDINGS (SG_MAX_STORAGEBUFFER_BINDSLOTS + SG_MAX_STORAGE_ATTACHMENTS)
  5227. #define _SG_D3D11_MAX_STAGE_SMP_BINDINGS (SG_MAX_SAMPLER_BINDSLOTS)
  5228. typedef struct _sg_shader_s {
  5229. _sg_slot_t slot;
  5230. _sg_shader_common_t cmn;
  5231. struct {
  5232. _sg_d3d11_shader_attr_t attrs[SG_MAX_VERTEX_ATTRIBUTES];
  5233. ID3D11VertexShader* vs;
  5234. ID3D11PixelShader* fs;
  5235. ID3D11ComputeShader* cs;
  5236. void* vs_blob;
  5237. size_t vs_blob_length;
  5238. uint8_t ub_register_b_n[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  5239. uint8_t img_register_t_n[SG_MAX_IMAGE_BINDSLOTS];
  5240. uint8_t smp_register_s_n[SG_MAX_SAMPLER_BINDSLOTS];
  5241. uint8_t sbuf_register_t_n[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  5242. uint8_t sbuf_register_u_n[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  5243. uint8_t simg_register_u_n[SG_MAX_STORAGE_ATTACHMENTS];
  5244. ID3D11Buffer* all_cbufs[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  5245. ID3D11Buffer* vs_cbufs[_SG_D3D11_MAX_STAGE_UB_BINDINGS];
  5246. ID3D11Buffer* fs_cbufs[_SG_D3D11_MAX_STAGE_UB_BINDINGS];
  5247. ID3D11Buffer* cs_cbufs[_SG_D3D11_MAX_STAGE_UB_BINDINGS];
  5248. } d3d11;
  5249. } _sg_d3d11_shader_t;
  5250. typedef _sg_d3d11_shader_t _sg_shader_t;
  5251. typedef struct _sg_pipeline_s {
  5252. _sg_slot_t slot;
  5253. _sg_pipeline_common_t cmn;
  5254. struct {
  5255. UINT stencil_ref;
  5256. UINT vb_strides[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  5257. D3D_PRIMITIVE_TOPOLOGY topology;
  5258. DXGI_FORMAT index_format;
  5259. ID3D11InputLayout* il;
  5260. ID3D11RasterizerState* rs;
  5261. ID3D11DepthStencilState* dss;
  5262. ID3D11BlendState* bs;
  5263. } d3d11;
  5264. } _sg_d3d11_pipeline_t;
  5265. typedef _sg_d3d11_pipeline_t _sg_pipeline_t;
  5266. typedef struct {
  5267. union {
  5268. ID3D11RenderTargetView* rtv;
  5269. ID3D11DepthStencilView* dsv;
  5270. ID3D11UnorderedAccessView* uav;
  5271. } view;
  5272. } _sg_d3d11_attachment_t;
  5273. typedef struct _sg_attachments_s {
  5274. _sg_slot_t slot;
  5275. _sg_attachments_common_t cmn;
  5276. struct {
  5277. _sg_d3d11_attachment_t colors[SG_MAX_COLOR_ATTACHMENTS];
  5278. _sg_d3d11_attachment_t depth_stencil;
  5279. _sg_d3d11_attachment_t storages[SG_MAX_STORAGE_ATTACHMENTS];
  5280. } d3d11;
  5281. } _sg_d3d11_attachments_t;
  5282. typedef _sg_d3d11_attachments_t _sg_attachments_t;
  5283. typedef struct {
  5284. bool valid;
  5285. ID3D11Device* dev;
  5286. ID3D11DeviceContext* ctx;
  5287. bool use_indexed_draw;
  5288. bool use_instanced_draw;
  5289. struct {
  5290. ID3D11RenderTargetView* render_view;
  5291. ID3D11RenderTargetView* resolve_view;
  5292. } cur_pass;
  5293. // on-demand loaded d3dcompiler_47.dll handles
  5294. HINSTANCE d3dcompiler_dll;
  5295. bool d3dcompiler_dll_load_failed;
  5296. pD3DCompile D3DCompile_func;
  5297. // global subresourcedata array for texture updates
  5298. D3D11_SUBRESOURCE_DATA subres_data[SG_MAX_MIPMAPS * SG_MAX_TEXTUREARRAY_LAYERS];
  5299. } _sg_d3d11_backend_t;
  5300. #elif defined(SOKOL_METAL)
  5301. #if defined(_SG_TARGET_MACOS) || defined(_SG_TARGET_IOS_SIMULATOR)
  5302. #define _SG_MTL_UB_ALIGN (256)
  5303. #else
  5304. #define _SG_MTL_UB_ALIGN (16)
  5305. #endif
  5306. #define _SG_MTL_INVALID_SLOT_INDEX (0)
  5307. typedef struct {
  5308. uint32_t frame_index; // frame index at which it is safe to release this resource
  5309. int slot_index;
  5310. } _sg_mtl_release_item_t;
  5311. typedef struct {
  5312. NSMutableArray* pool;
  5313. int num_slots;
  5314. int free_queue_top;
  5315. int* free_queue;
  5316. int release_queue_front;
  5317. int release_queue_back;
  5318. _sg_mtl_release_item_t* release_queue;
  5319. } _sg_mtl_idpool_t;
  5320. typedef struct _sg_buffer_s {
  5321. _sg_slot_t slot;
  5322. _sg_buffer_common_t cmn;
  5323. struct {
  5324. int buf[SG_NUM_INFLIGHT_FRAMES]; // index into _sg_mtl_pool
  5325. } mtl;
  5326. } _sg_mtl_buffer_t;
  5327. typedef _sg_mtl_buffer_t _sg_buffer_t;
  5328. typedef struct _sg_image_s {
  5329. _sg_slot_t slot;
  5330. _sg_image_common_t cmn;
  5331. struct {
  5332. int tex[SG_NUM_INFLIGHT_FRAMES];
  5333. } mtl;
  5334. } _sg_mtl_image_t;
  5335. typedef _sg_mtl_image_t _sg_image_t;
  5336. typedef struct _sg_sampler_s {
  5337. _sg_slot_t slot;
  5338. _sg_sampler_common_t cmn;
  5339. struct {
  5340. int sampler_state;
  5341. } mtl;
  5342. } _sg_mtl_sampler_t;
  5343. typedef _sg_mtl_sampler_t _sg_sampler_t;
  5344. typedef struct {
  5345. int mtl_lib;
  5346. int mtl_func;
  5347. } _sg_mtl_shader_func_t;
  5348. typedef struct _sg_shader_s {
  5349. _sg_slot_t slot;
  5350. _sg_shader_common_t cmn;
  5351. struct {
  5352. _sg_mtl_shader_func_t vertex_func;
  5353. _sg_mtl_shader_func_t fragment_func;
  5354. _sg_mtl_shader_func_t compute_func;
  5355. MTLSize threads_per_threadgroup;
  5356. uint8_t ub_buffer_n[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  5357. uint8_t img_texture_n[SG_MAX_IMAGE_BINDSLOTS];
  5358. uint8_t smp_sampler_n[SG_MAX_SAMPLER_BINDSLOTS];
  5359. uint8_t sbuf_buffer_n[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  5360. uint8_t simg_texture_n[SG_MAX_STORAGE_ATTACHMENTS];
  5361. } mtl;
  5362. } _sg_mtl_shader_t;
  5363. typedef _sg_mtl_shader_t _sg_shader_t;
  5364. typedef struct _sg_pipeline_s {
  5365. _sg_slot_t slot;
  5366. _sg_pipeline_common_t cmn;
  5367. struct {
  5368. MTLPrimitiveType prim_type;
  5369. int index_size;
  5370. MTLIndexType index_type;
  5371. MTLCullMode cull_mode;
  5372. MTLWinding winding;
  5373. uint32_t stencil_ref;
  5374. MTLSize threads_per_threadgroup;
  5375. int cps; // MTLComputePipelineState
  5376. int rps; // MTLRenderPipelineState
  5377. int dss; // MTLDepthStencilState
  5378. } mtl;
  5379. } _sg_mtl_pipeline_t;
  5380. typedef _sg_mtl_pipeline_t _sg_pipeline_t;
  5381. typedef struct _sg_attachments_s {
  5382. _sg_slot_t slot;
  5383. _sg_attachments_common_t cmn;
  5384. struct {
  5385. int storage_views[SG_MAX_STORAGE_ATTACHMENTS];
  5386. } mtl;
  5387. } _sg_mtl_attachments_t;
  5388. typedef _sg_mtl_attachments_t _sg_attachments_t;
  5389. // resource binding state cache
  5390. #define _SG_MTL_MAX_STAGE_UB_BINDINGS (SG_MAX_UNIFORMBLOCK_BINDSLOTS)
  5391. #define _SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS (_SG_MTL_MAX_STAGE_UB_BINDINGS + SG_MAX_STORAGEBUFFER_BINDSLOTS)
  5392. #define _SG_MTL_MAX_STAGE_BUFFER_BINDINGS (_SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS + SG_MAX_VERTEXBUFFER_BINDSLOTS)
  5393. #define _SG_MTL_MAX_STAGE_TEXTURE_BINDINGS (SG_MAX_IMAGE_BINDSLOTS + SG_MAX_STORAGE_ATTACHMENTS)
  5394. #define _SG_MTL_MAX_STAGE_SAMPLER_BINDINGS (SG_MAX_SAMPLER_BINDSLOTS)
  5395. typedef struct {
  5396. _sg_sref_t cur_pip;
  5397. _sg_buffer_ref_t cur_ibuf;
  5398. int cur_ibuf_offset;
  5399. int cur_vs_buffer_offsets[_SG_MTL_MAX_STAGE_BUFFER_BINDINGS];
  5400. _sg_sref_t cur_vsbufs[_SG_MTL_MAX_STAGE_BUFFER_BINDINGS];
  5401. _sg_sref_t cur_fsbufs[_SG_MTL_MAX_STAGE_BUFFER_BINDINGS];
  5402. _sg_sref_t cur_csbufs[_SG_MTL_MAX_STAGE_BUFFER_BINDINGS];
  5403. _sg_sref_t cur_vsimgs[_SG_MTL_MAX_STAGE_TEXTURE_BINDINGS];
  5404. _sg_sref_t cur_fsimgs[_SG_MTL_MAX_STAGE_TEXTURE_BINDINGS];
  5405. _sg_sref_t cur_vssmps[_SG_MTL_MAX_STAGE_SAMPLER_BINDINGS];
  5406. _sg_sref_t cur_fssmps[_SG_MTL_MAX_STAGE_SAMPLER_BINDINGS];
  5407. _sg_sref_t cur_cssmps[_SG_MTL_MAX_STAGE_SAMPLER_BINDINGS];
  5408. // NOTE: special case: uint64_t for storage images, because we need
  5409. // to differentiate between storage pass attachments and regular
  5410. // textures bound to compute stages (but both binding types live
  5411. // in the texture bind space in Metal)
  5412. // This special case will be removed in the view update!
  5413. uint64_t cur_cs_image_ids[_SG_MTL_MAX_STAGE_TEXTURE_BINDINGS];
  5414. } _sg_mtl_state_cache_t;
  5415. typedef struct {
  5416. bool valid;
  5417. bool use_shared_storage_mode;
  5418. uint32_t cur_frame_rotate_index;
  5419. int ub_size;
  5420. int cur_ub_offset;
  5421. uint8_t* cur_ub_base_ptr;
  5422. _sg_mtl_state_cache_t state_cache;
  5423. _sg_mtl_idpool_t idpool;
  5424. dispatch_semaphore_t sem;
  5425. id<MTLDevice> device;
  5426. id<MTLCommandQueue> cmd_queue;
  5427. id<MTLCommandBuffer> cmd_buffer;
  5428. id<MTLRenderCommandEncoder> render_cmd_encoder;
  5429. id<MTLComputeCommandEncoder> compute_cmd_encoder;
  5430. id<CAMetalDrawable> cur_drawable;
  5431. id<MTLBuffer> uniform_buffers[SG_NUM_INFLIGHT_FRAMES];
  5432. } _sg_mtl_backend_t;
  5433. #elif defined(SOKOL_WGPU)
  5434. #define _SG_WGPU_ROWPITCH_ALIGN (256)
  5435. #define _SG_WGPU_MAX_UNIFORM_UPDATE_SIZE (1<<16) // also see WGPULimits.maxUniformBufferBindingSize
  5436. #define _SG_WGPU_MAX_BINDGROUPS (3) // 0: uniforms, 1: images, samplers, storage buffers, 2: storage images (only in compute passes)
  5437. #define _SG_WGPU_UB_BINDGROUP_INDEX (0)
  5438. #define _SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX (1)
  5439. #define _SG_WGPU_SIMG_BINDGROUP_INDEX (2)
  5440. #define _SG_WGPU_MAX_UB_BINDGROUP_ENTRIES (SG_MAX_UNIFORMBLOCK_BINDSLOTS)
  5441. #define _SG_WGPU_MAX_UB_BINDGROUP_BIND_SLOTS (2 * SG_MAX_UNIFORMBLOCK_BINDSLOTS)
  5442. #define _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES (SG_MAX_IMAGE_BINDSLOTS + SG_MAX_SAMPLER_BINDSLOTS + SG_MAX_STORAGEBUFFER_BINDSLOTS)
  5443. #define _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS (128)
  5444. #define _SG_WGPU_MAX_SIMG_BIND_SLOTS (SG_MAX_STORAGE_ATTACHMENTS)
  5445. #define _SG_WGPU_MAX_SIMG_BINDGROUP_ENTRIES (SG_MAX_STORAGE_ATTACHMENTS)
  5446. typedef struct _sg_buffer_s {
  5447. _sg_slot_t slot;
  5448. _sg_buffer_common_t cmn;
  5449. struct {
  5450. WGPUBuffer buf;
  5451. } wgpu;
  5452. } _sg_wgpu_buffer_t;
  5453. typedef _sg_wgpu_buffer_t _sg_buffer_t;
  5454. typedef struct _sg_image_s {
  5455. _sg_slot_t slot;
  5456. _sg_image_common_t cmn;
  5457. struct {
  5458. WGPUTexture tex;
  5459. WGPUTextureView view;
  5460. } wgpu;
  5461. } _sg_wgpu_image_t;
  5462. typedef _sg_wgpu_image_t _sg_image_t;
  5463. typedef struct _sg_sampler_s {
  5464. _sg_slot_t slot;
  5465. _sg_sampler_common_t cmn;
  5466. struct {
  5467. WGPUSampler smp;
  5468. } wgpu;
  5469. } _sg_wgpu_sampler_t;
  5470. typedef _sg_wgpu_sampler_t _sg_sampler_t;
  5471. typedef struct {
  5472. WGPUShaderModule module;
  5473. _sg_str_t entry;
  5474. } _sg_wgpu_shader_func_t;
  5475. typedef struct _sg_shader_s {
  5476. _sg_slot_t slot;
  5477. _sg_shader_common_t cmn;
  5478. struct {
  5479. _sg_wgpu_shader_func_t vertex_func;
  5480. _sg_wgpu_shader_func_t fragment_func;
  5481. _sg_wgpu_shader_func_t compute_func;
  5482. WGPUBindGroupLayout bgl_ub;
  5483. WGPUBindGroup bg_ub;
  5484. WGPUBindGroupLayout bgl_img_smp_sbuf;
  5485. WGPUBindGroupLayout bgl_simg;
  5486. // a mapping of sokol-gfx bind slots to setBindGroup dynamic-offset-array indices
  5487. uint8_t ub_num_dynoffsets;
  5488. uint8_t ub_dynoffsets[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  5489. // indexed by sokol-gfx bind slot:
  5490. uint8_t ub_grp0_bnd_n[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  5491. uint8_t img_grp1_bnd_n[SG_MAX_IMAGE_BINDSLOTS];
  5492. uint8_t smp_grp1_bnd_n[SG_MAX_SAMPLER_BINDSLOTS];
  5493. uint8_t sbuf_grp1_bnd_n[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  5494. uint8_t simg_grp2_bnd_n[SG_MAX_STORAGE_ATTACHMENTS];
  5495. } wgpu;
  5496. } _sg_wgpu_shader_t;
  5497. typedef _sg_wgpu_shader_t _sg_shader_t;
  5498. typedef struct _sg_pipeline_s {
  5499. _sg_slot_t slot;
  5500. _sg_pipeline_common_t cmn;
  5501. struct {
  5502. WGPURenderPipeline rpip;
  5503. WGPUComputePipeline cpip;
  5504. WGPUColor blend_color;
  5505. } wgpu;
  5506. } _sg_wgpu_pipeline_t;
  5507. typedef _sg_wgpu_pipeline_t _sg_pipeline_t;
  5508. typedef struct {
  5509. WGPUTextureView view;
  5510. } _sg_wgpu_attachment_t;
  5511. typedef struct _sg_attachments_s {
  5512. _sg_slot_t slot;
  5513. _sg_attachments_common_t cmn;
  5514. struct {
  5515. _sg_wgpu_attachment_t colors[SG_MAX_COLOR_ATTACHMENTS];
  5516. _sg_wgpu_attachment_t resolves[SG_MAX_COLOR_ATTACHMENTS];
  5517. _sg_wgpu_attachment_t depth_stencil;
  5518. _sg_wgpu_attachment_t storages[SG_MAX_STORAGE_ATTACHMENTS];
  5519. } wgpu;
  5520. } _sg_wgpu_attachments_t;
  5521. typedef _sg_wgpu_attachments_t _sg_attachments_t;
  5522. // a pool of per-frame uniform buffers
  5523. typedef struct {
  5524. uint32_t num_bytes;
  5525. uint32_t offset; // current offset into buf
  5526. uint8_t* staging; // intermediate buffer for uniform data updates
  5527. WGPUBuffer buf; // the GPU-side uniform buffer
  5528. uint32_t bind_offsets[SG_MAX_UNIFORMBLOCK_BINDSLOTS]; // NOTE: index is sokol-gfx ub slot index!
  5529. } _sg_wgpu_uniform_buffer_t;
  5530. typedef struct {
  5531. uint32_t id;
  5532. } _sg_wgpu_bindgroup_handle_t;
  5533. typedef enum {
  5534. _SG_WGPU_BINDGROUPSCACHEITEMTYPE_NONE = 0,
  5535. _SG_WGPU_BINDGROUPSCACHEITEMTYPE_IMAGE = 1,
  5536. _SG_WGPU_BINDGROUPSCACHEITEMTYPE_SAMPLER = 2,
  5537. _SG_WGPU_BINDGROUPSCACHEITEMTYPE_STORAGEBUFFER = 3,
  5538. _SG_WGPU_BINDGROUPSCACHEITEMTYPE_PIPELINE = 4,
  5539. } _sg_wgpu_bindgroups_cache_item_type_t;
  5540. #define _SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS (1 + _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES)
  5541. typedef struct {
  5542. uint64_t hash;
  5543. // the format of cache key items is BBTCCCCCIIIIIIII
  5544. // where
  5545. // - BB: 8 bits WGPU binding
  5546. // - T: 3 bits _sg_wgpu_bindgroups_cache_item_type_t
  5547. // - CCCCC: 21 bits slot.uninit_count
  5548. // - IIIIIIII: 32 bits slot.id
  5549. //
  5550. // where the item type is a per-resource-type bit pattern
  5551. uint64_t items[_SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS];
  5552. } _sg_wgpu_bindgroups_cache_key_t;
  5553. typedef struct {
  5554. uint32_t num; // must be 2^n
  5555. uint32_t index_mask; // mask to turn hash into valid index
  5556. _sg_wgpu_bindgroup_handle_t* items;
  5557. } _sg_wgpu_bindgroups_cache_t;
  5558. typedef struct {
  5559. _sg_slot_t slot;
  5560. WGPUBindGroup bindgroup;
  5561. _sg_wgpu_bindgroups_cache_key_t key;
  5562. } _sg_wgpu_bindgroup_t;
  5563. typedef struct {
  5564. _sg_pool_t pool;
  5565. _sg_wgpu_bindgroup_t* bindgroups;
  5566. } _sg_wgpu_bindgroups_pool_t;
  5567. typedef struct {
  5568. struct {
  5569. sg_buffer buffer;
  5570. uint64_t offset;
  5571. } vbs[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  5572. struct {
  5573. sg_buffer buffer;
  5574. uint64_t offset;
  5575. } ib;
  5576. _sg_wgpu_bindgroup_handle_t bg;
  5577. } _sg_wgpu_bindings_cache_t;
  5578. // the WGPU backend state
  5579. typedef struct {
  5580. bool valid;
  5581. bool use_indexed_draw;
  5582. WGPUDevice dev;
  5583. WGPULimits limits;
  5584. WGPUQueue queue;
  5585. WGPUCommandEncoder cmd_enc;
  5586. WGPURenderPassEncoder rpass_enc;
  5587. WGPUComputePassEncoder cpass_enc;
  5588. WGPUBindGroup empty_bind_group;
  5589. _sg_wgpu_uniform_buffer_t uniform;
  5590. _sg_wgpu_bindings_cache_t bindings_cache;
  5591. _sg_wgpu_bindgroups_cache_t bindgroups_cache;
  5592. _sg_wgpu_bindgroups_pool_t bindgroups_pool;
  5593. } _sg_wgpu_backend_t;
  5594. #endif
  5595. // this *MUST* remain 0
  5596. #define _SG_INVALID_SLOT_INDEX (0)
  5597. typedef struct _sg_pools_s {
  5598. _sg_pool_t buffer_pool;
  5599. _sg_pool_t image_pool;
  5600. _sg_pool_t sampler_pool;
  5601. _sg_pool_t shader_pool;
  5602. _sg_pool_t pipeline_pool;
  5603. _sg_pool_t attachments_pool;
  5604. _sg_buffer_t* buffers;
  5605. _sg_image_t* images;
  5606. _sg_sampler_t* samplers;
  5607. _sg_shader_t* shaders;
  5608. _sg_pipeline_t* pipelines;
  5609. _sg_attachments_t* attachments;
  5610. } _sg_pools_t;
  5611. typedef struct {
  5612. int num; // number of allocated commit listener items
  5613. int upper; // the current upper index (no valid items past this point)
  5614. sg_commit_listener* items;
  5615. } _sg_commit_listeners_t;
  5616. // resolved pass attachments struct
  5617. typedef struct {
  5618. _sg_image_t* color_images[SG_MAX_COLOR_ATTACHMENTS];
  5619. _sg_image_t* resolve_images[SG_MAX_COLOR_ATTACHMENTS];
  5620. _sg_image_t* ds_image;
  5621. _sg_image_t* storage_images[SG_MAX_STORAGE_ATTACHMENTS];
  5622. } _sg_attachments_ptrs_t;
  5623. // resolved resource bindings struct
  5624. typedef struct {
  5625. _sg_pipeline_t* pip;
  5626. int vb_offsets[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  5627. int ib_offset;
  5628. _sg_buffer_t* vbs[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  5629. _sg_buffer_t* ib;
  5630. _sg_image_t* imgs[SG_MAX_IMAGE_BINDSLOTS];
  5631. _sg_sampler_t* smps[SG_MAX_SAMPLER_BINDSLOTS];
  5632. _sg_buffer_t* sbufs[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  5633. _sg_image_t* simgs[SG_MAX_STORAGE_ATTACHMENTS];
  5634. } _sg_bindings_ptrs_t;
  5635. typedef struct {
  5636. bool sample;
  5637. bool filter;
  5638. bool render;
  5639. bool blend;
  5640. bool msaa;
  5641. bool depth;
  5642. bool read;
  5643. bool write;
  5644. } _sg_pixelformat_info_t;
  5645. typedef struct {
  5646. bool valid;
  5647. sg_desc desc; // original desc with default values patched in
  5648. uint32_t frame_index;
  5649. struct {
  5650. bool valid;
  5651. bool in_pass;
  5652. bool is_compute;
  5653. _sg_attachments_ref_t atts; // null in a swapchain pass
  5654. int width;
  5655. int height;
  5656. struct {
  5657. sg_pixel_format color_fmt;
  5658. sg_pixel_format depth_fmt;
  5659. int sample_count;
  5660. } swapchain;
  5661. } cur_pass;
  5662. _sg_pipeline_ref_t cur_pip;
  5663. bool next_draw_valid;
  5664. uint32_t required_bindings_and_uniforms; // used to check that bindings and uniforms are applied after applying pipeline
  5665. uint32_t applied_bindings_and_uniforms; // bits 0..7: uniform blocks, bit 8: bindings
  5666. #if defined(SOKOL_DEBUG)
  5667. sg_log_item validate_error;
  5668. #endif
  5669. struct {
  5670. _sg_tracker_t readwrite_sbufs; // tracks read/write storage buffers used in compute pass
  5671. } compute;
  5672. _sg_pools_t pools;
  5673. sg_backend backend;
  5674. sg_features features;
  5675. sg_limits limits;
  5676. _sg_pixelformat_info_t formats[_SG_PIXELFORMAT_NUM];
  5677. bool stats_enabled;
  5678. sg_frame_stats stats;
  5679. sg_frame_stats prev_stats;
  5680. #if defined(_SOKOL_ANY_GL)
  5681. _sg_gl_backend_t gl;
  5682. #elif defined(SOKOL_METAL)
  5683. _sg_mtl_backend_t mtl;
  5684. #elif defined(SOKOL_D3D11)
  5685. _sg_d3d11_backend_t d3d11;
  5686. #elif defined(SOKOL_WGPU)
  5687. _sg_wgpu_backend_t wgpu;
  5688. #endif
  5689. #if defined(SOKOL_TRACE_HOOKS)
  5690. sg_trace_hooks hooks;
  5691. #endif
  5692. _sg_commit_listeners_t commit_listeners;
  5693. } _sg_state_t;
  5694. static _sg_state_t _sg;
  5695. // ██ ██████ ██████ ██████ ██ ███ ██ ██████
  5696. // ██ ██ ██ ██ ██ ██ ████ ██ ██
  5697. // ██ ██ ██ ██ ███ ██ ███ ██ ██ ██ ██ ██ ███
  5698. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  5699. // ███████ ██████ ██████ ██████ ██ ██ ████ ██████
  5700. //
  5701. // >>logging
  5702. #if defined(SOKOL_DEBUG)
  5703. #define _SG_LOGITEM_XMACRO(item,msg) #item ": " msg,
  5704. static const char* _sg_log_messages[] = {
  5705. _SG_LOG_ITEMS
  5706. };
  5707. #undef _SG_LOGITEM_XMACRO
  5708. #endif // SOKOL_DEBUG
  5709. #define _SG_PANIC(code) _sg_log(SG_LOGITEM_ ##code, 0, 0, __LINE__)
  5710. #define _SG_ERROR(code) _sg_log(SG_LOGITEM_ ##code, 1, 0, __LINE__)
  5711. #define _SG_WARN(code) _sg_log(SG_LOGITEM_ ##code, 2, 0, __LINE__)
  5712. #define _SG_INFO(code) _sg_log(SG_LOGITEM_ ##code, 3, 0, __LINE__)
  5713. #define _SG_LOGMSG(code,msg) _sg_log(SG_LOGITEM_ ##code, 3, msg, __LINE__)
  5714. #define _SG_VALIDATE(cond,code) if (!(cond)){ _sg.validate_error = SG_LOGITEM_ ##code; _sg_log(SG_LOGITEM_ ##code, 1, 0, __LINE__); }
  5715. static void _sg_log(sg_log_item log_item, uint32_t log_level, const char* msg, uint32_t line_nr) {
  5716. if (_sg.desc.logger.func) {
  5717. const char* filename = 0;
  5718. #if defined(SOKOL_DEBUG)
  5719. filename = __FILE__;
  5720. if (0 == msg) {
  5721. msg = _sg_log_messages[log_item];
  5722. }
  5723. #endif
  5724. _sg.desc.logger.func("sg", log_level, (uint32_t)log_item, msg, line_nr, filename, _sg.desc.logger.user_data);
  5725. } else {
  5726. // for log level PANIC it would be 'undefined behaviour' to continue
  5727. if (log_level == 0) {
  5728. abort();
  5729. }
  5730. }
  5731. }
  5732. // ███ ███ ███████ ███ ███ ██████ ██████ ██ ██
  5733. // ████ ████ ██ ████ ████ ██ ██ ██ ██ ██ ██
  5734. // ██ ████ ██ █████ ██ ████ ██ ██ ██ ██████ ████
  5735. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  5736. // ██ ██ ███████ ██ ██ ██████ ██ ██ ██
  5737. //
  5738. // >>memory
  5739. // a helper macro to clear a struct with potentially ARC'ed ObjC references
  5740. #if defined(SOKOL_METAL)
  5741. #if defined(__cplusplus)
  5742. #define _SG_CLEAR_ARC_STRUCT(type, item) { item = type(); }
  5743. #else
  5744. #define _SG_CLEAR_ARC_STRUCT(type, item) { item = (type) { 0 }; }
  5745. #endif
  5746. #else
  5747. #define _SG_CLEAR_ARC_STRUCT(type, item) { _sg_clear(&item, sizeof(item)); }
  5748. #endif
  5749. _SOKOL_PRIVATE void _sg_clear(void* ptr, size_t size) {
  5750. SOKOL_ASSERT(ptr && (size > 0));
  5751. memset(ptr, 0, size);
  5752. }
  5753. _SOKOL_PRIVATE void* _sg_malloc(size_t size) {
  5754. SOKOL_ASSERT(size > 0);
  5755. void* ptr;
  5756. if (_sg.desc.allocator.alloc_fn) {
  5757. ptr = _sg.desc.allocator.alloc_fn(size, _sg.desc.allocator.user_data);
  5758. } else {
  5759. ptr = malloc(size);
  5760. }
  5761. if (0 == ptr) {
  5762. _SG_PANIC(MALLOC_FAILED);
  5763. }
  5764. return ptr;
  5765. }
  5766. _SOKOL_PRIVATE void* _sg_malloc_clear(size_t size) {
  5767. void* ptr = _sg_malloc(size);
  5768. _sg_clear(ptr, size);
  5769. return ptr;
  5770. }
  5771. _SOKOL_PRIVATE void _sg_free(void* ptr) {
  5772. if (_sg.desc.allocator.free_fn) {
  5773. _sg.desc.allocator.free_fn(ptr, _sg.desc.allocator.user_data);
  5774. } else {
  5775. free(ptr);
  5776. }
  5777. }
  5778. _SOKOL_PRIVATE bool _sg_strempty(const _sg_str_t* str) {
  5779. return 0 == str->buf[0];
  5780. }
  5781. _SOKOL_PRIVATE const char* _sg_strptr(const _sg_str_t* str) {
  5782. return &str->buf[0];
  5783. }
  5784. _SOKOL_PRIVATE void _sg_strcpy(_sg_str_t* dst, const char* src) {
  5785. SOKOL_ASSERT(dst);
  5786. if (src) {
  5787. #if defined(_MSC_VER)
  5788. strncpy_s(dst->buf, _SG_STRING_SIZE, src, (_SG_STRING_SIZE-1));
  5789. #else
  5790. strncpy(dst->buf, src, _SG_STRING_SIZE);
  5791. #endif
  5792. dst->buf[_SG_STRING_SIZE-1] = 0;
  5793. } else {
  5794. _sg_clear(dst->buf, _SG_STRING_SIZE);
  5795. }
  5796. }
  5797. // ██████ ██████ ██████ ██
  5798. // ██ ██ ██ ██ ██ ██ ██
  5799. // ██████ ██ ██ ██ ██ ██
  5800. // ██ ██ ██ ██ ██ ██
  5801. // ██ ██████ ██████ ███████
  5802. //
  5803. // >>pool
  5804. _SOKOL_PRIVATE void _sg_pool_init(_sg_pool_t* pool, int num) {
  5805. SOKOL_ASSERT(pool && (num >= 1));
  5806. // slot 0 is reserved for the 'invalid id', so bump the pool size by 1
  5807. pool->size = num + 1;
  5808. pool->queue_top = 0;
  5809. // generation counters indexable by pool slot index, slot 0 is reserved
  5810. size_t gen_ctrs_size = sizeof(uint32_t) * (size_t)pool->size;
  5811. pool->gen_ctrs = (uint32_t*)_sg_malloc_clear(gen_ctrs_size);
  5812. // it's not a bug to only reserve 'num' here
  5813. pool->free_queue = (int*) _sg_malloc_clear(sizeof(int) * (size_t)num);
  5814. // never allocate the zero-th pool item since the invalid id is 0
  5815. for (int i = pool->size-1; i >= 1; i--) {
  5816. pool->free_queue[pool->queue_top++] = i;
  5817. }
  5818. }
  5819. _SOKOL_PRIVATE void _sg_pool_discard(_sg_pool_t* pool) {
  5820. SOKOL_ASSERT(pool);
  5821. SOKOL_ASSERT(pool->free_queue);
  5822. _sg_free(pool->free_queue);
  5823. pool->free_queue = 0;
  5824. SOKOL_ASSERT(pool->gen_ctrs);
  5825. _sg_free(pool->gen_ctrs);
  5826. pool->gen_ctrs = 0;
  5827. pool->size = 0;
  5828. pool->queue_top = 0;
  5829. }
  5830. _SOKOL_PRIVATE int _sg_pool_alloc_index(_sg_pool_t* pool) {
  5831. SOKOL_ASSERT(pool);
  5832. SOKOL_ASSERT(pool->free_queue);
  5833. if (pool->queue_top > 0) {
  5834. int slot_index = pool->free_queue[--pool->queue_top];
  5835. SOKOL_ASSERT((slot_index > 0) && (slot_index < pool->size));
  5836. return slot_index;
  5837. } else {
  5838. // pool exhausted
  5839. return _SG_INVALID_SLOT_INDEX;
  5840. }
  5841. }
  5842. _SOKOL_PRIVATE void _sg_pool_free_index(_sg_pool_t* pool, int slot_index) {
  5843. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < pool->size));
  5844. SOKOL_ASSERT(pool);
  5845. SOKOL_ASSERT(pool->free_queue);
  5846. SOKOL_ASSERT(pool->queue_top < pool->size);
  5847. #ifdef SOKOL_DEBUG
  5848. // debug check against double-free
  5849. for (int i = 0; i < pool->queue_top; i++) {
  5850. SOKOL_ASSERT(pool->free_queue[i] != slot_index);
  5851. }
  5852. #endif
  5853. pool->free_queue[pool->queue_top++] = slot_index;
  5854. SOKOL_ASSERT(pool->queue_top <= (pool->size-1));
  5855. }
  5856. _SOKOL_PRIVATE void _sg_slot_reset(_sg_slot_t* slot) {
  5857. SOKOL_ASSERT(slot);
  5858. _sg_clear(slot, sizeof(_sg_slot_t));
  5859. }
  5860. _SOKOL_PRIVATE void _sg_reset_buffer_to_alloc_state(_sg_buffer_t* buf) {
  5861. SOKOL_ASSERT(buf);
  5862. _sg_slot_t slot = buf->slot;
  5863. _sg_clear(buf, sizeof(*buf));
  5864. buf->slot = slot;
  5865. buf->slot.uninit_count += 1;
  5866. buf->slot.state = SG_RESOURCESTATE_ALLOC;
  5867. }
  5868. _SOKOL_PRIVATE void _sg_reset_image_to_alloc_state(_sg_image_t* img) {
  5869. SOKOL_ASSERT(img);
  5870. _sg_slot_t slot = img->slot;
  5871. _sg_clear(img, sizeof(*img));
  5872. img->slot = slot;
  5873. img->slot.uninit_count += 1;
  5874. img->slot.state = SG_RESOURCESTATE_ALLOC;
  5875. }
  5876. _SOKOL_PRIVATE void _sg_reset_sampler_to_alloc_state(_sg_sampler_t* smp) {
  5877. SOKOL_ASSERT(smp);
  5878. _sg_slot_t slot = smp->slot;
  5879. _sg_clear(smp, sizeof(*smp));
  5880. smp->slot = slot;
  5881. smp->slot.uninit_count += 1;
  5882. smp->slot.state = SG_RESOURCESTATE_ALLOC;
  5883. }
  5884. _SOKOL_PRIVATE void _sg_reset_shader_to_alloc_state(_sg_shader_t* shd) {
  5885. SOKOL_ASSERT(shd);
  5886. _sg_slot_t slot = shd->slot;
  5887. _sg_clear(shd, sizeof(*shd));
  5888. shd->slot = slot;
  5889. shd->slot.uninit_count += 1;
  5890. shd->slot.state = SG_RESOURCESTATE_ALLOC;
  5891. }
  5892. _SOKOL_PRIVATE void _sg_reset_pipeline_to_alloc_state(_sg_pipeline_t* pip) {
  5893. SOKOL_ASSERT(pip);
  5894. _sg_slot_t slot = pip->slot;
  5895. _sg_clear(pip, sizeof(*pip));
  5896. pip->slot = slot;
  5897. pip->slot.uninit_count += 1;
  5898. pip->slot.state = SG_RESOURCESTATE_ALLOC;
  5899. }
  5900. _SOKOL_PRIVATE void _sg_reset_attachments_to_alloc_state(_sg_attachments_t* atts) {
  5901. SOKOL_ASSERT(atts);
  5902. _sg_slot_t slot = atts->slot;
  5903. _sg_clear(atts, sizeof(*atts));
  5904. atts->slot = slot;
  5905. atts->slot.uninit_count += 1;
  5906. atts->slot.state = SG_RESOURCESTATE_ALLOC;
  5907. }
  5908. _SOKOL_PRIVATE void _sg_setup_pools(_sg_pools_t* p, const sg_desc* desc) {
  5909. SOKOL_ASSERT(p);
  5910. SOKOL_ASSERT(desc);
  5911. // note: the pools here will have an additional item, since slot 0 is reserved
  5912. SOKOL_ASSERT((desc->buffer_pool_size > 0) && (desc->buffer_pool_size < _SG_MAX_POOL_SIZE));
  5913. _sg_pool_init(&p->buffer_pool, desc->buffer_pool_size);
  5914. size_t buffer_pool_byte_size = sizeof(_sg_buffer_t) * (size_t)p->buffer_pool.size;
  5915. p->buffers = (_sg_buffer_t*) _sg_malloc_clear(buffer_pool_byte_size);
  5916. SOKOL_ASSERT((desc->image_pool_size > 0) && (desc->image_pool_size < _SG_MAX_POOL_SIZE));
  5917. _sg_pool_init(&p->image_pool, desc->image_pool_size);
  5918. size_t image_pool_byte_size = sizeof(_sg_image_t) * (size_t)p->image_pool.size;
  5919. p->images = (_sg_image_t*) _sg_malloc_clear(image_pool_byte_size);
  5920. SOKOL_ASSERT((desc->sampler_pool_size > 0) && (desc->sampler_pool_size < _SG_MAX_POOL_SIZE));
  5921. _sg_pool_init(&p->sampler_pool, desc->sampler_pool_size);
  5922. size_t sampler_pool_byte_size = sizeof(_sg_sampler_t) * (size_t)p->sampler_pool.size;
  5923. p->samplers = (_sg_sampler_t*) _sg_malloc_clear(sampler_pool_byte_size);
  5924. SOKOL_ASSERT((desc->shader_pool_size > 0) && (desc->shader_pool_size < _SG_MAX_POOL_SIZE));
  5925. _sg_pool_init(&p->shader_pool, desc->shader_pool_size);
  5926. size_t shader_pool_byte_size = sizeof(_sg_shader_t) * (size_t)p->shader_pool.size;
  5927. p->shaders = (_sg_shader_t*) _sg_malloc_clear(shader_pool_byte_size);
  5928. SOKOL_ASSERT((desc->pipeline_pool_size > 0) && (desc->pipeline_pool_size < _SG_MAX_POOL_SIZE));
  5929. _sg_pool_init(&p->pipeline_pool, desc->pipeline_pool_size);
  5930. size_t pipeline_pool_byte_size = sizeof(_sg_pipeline_t) * (size_t)p->pipeline_pool.size;
  5931. p->pipelines = (_sg_pipeline_t*) _sg_malloc_clear(pipeline_pool_byte_size);
  5932. SOKOL_ASSERT((desc->attachments_pool_size > 0) && (desc->attachments_pool_size < _SG_MAX_POOL_SIZE));
  5933. _sg_pool_init(&p->attachments_pool, desc->attachments_pool_size);
  5934. size_t attachments_pool_byte_size = sizeof(_sg_attachments_t) * (size_t)p->attachments_pool.size;
  5935. p->attachments = (_sg_attachments_t*) _sg_malloc_clear(attachments_pool_byte_size);
  5936. }
  5937. _SOKOL_PRIVATE void _sg_discard_pools(_sg_pools_t* p) {
  5938. SOKOL_ASSERT(p);
  5939. _sg_free(p->attachments); p->attachments = 0;
  5940. _sg_free(p->pipelines); p->pipelines = 0;
  5941. _sg_free(p->shaders); p->shaders = 0;
  5942. _sg_free(p->samplers); p->samplers = 0;
  5943. _sg_free(p->images); p->images = 0;
  5944. _sg_free(p->buffers); p->buffers = 0;
  5945. _sg_pool_discard(&p->attachments_pool);
  5946. _sg_pool_discard(&p->pipeline_pool);
  5947. _sg_pool_discard(&p->shader_pool);
  5948. _sg_pool_discard(&p->sampler_pool);
  5949. _sg_pool_discard(&p->image_pool);
  5950. _sg_pool_discard(&p->buffer_pool);
  5951. }
  5952. /* allocate the slot at slot_index:
  5953. - bump the slot's generation counter
  5954. - create a resource id from the generation counter and slot index
  5955. - set the slot's id to this id
  5956. - set the slot's state to ALLOC
  5957. - return the resource id
  5958. */
  5959. _SOKOL_PRIVATE uint32_t _sg_slot_alloc(_sg_pool_t* pool, _sg_slot_t* slot, int slot_index) {
  5960. /* FIXME: add handling for an overflowing generation counter,
  5961. for now, just overflow (another option is to disable
  5962. the slot)
  5963. */
  5964. SOKOL_ASSERT(pool && pool->gen_ctrs);
  5965. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < pool->size));
  5966. SOKOL_ASSERT(slot->id == SG_INVALID_ID);
  5967. SOKOL_ASSERT(slot->state == SG_RESOURCESTATE_INITIAL);
  5968. uint32_t ctr = ++pool->gen_ctrs[slot_index];
  5969. slot->id = (ctr<<_SG_SLOT_SHIFT)|(slot_index & _SG_SLOT_MASK);
  5970. slot->state = SG_RESOURCESTATE_ALLOC;
  5971. return slot->id;
  5972. }
  5973. // extract slot index from id
  5974. _SOKOL_PRIVATE int _sg_slot_index(uint32_t id) {
  5975. int slot_index = (int) (id & _SG_SLOT_MASK);
  5976. SOKOL_ASSERT(_SG_INVALID_SLOT_INDEX != slot_index);
  5977. return slot_index;
  5978. }
  5979. // returns pointer to resource by id without matching id check
  5980. _SOKOL_PRIVATE _sg_buffer_t* _sg_buffer_at(uint32_t buf_id) {
  5981. SOKOL_ASSERT(SG_INVALID_ID != buf_id);
  5982. int slot_index = _sg_slot_index(buf_id);
  5983. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < _sg.pools.buffer_pool.size));
  5984. return &_sg.pools.buffers[slot_index];
  5985. }
  5986. _SOKOL_PRIVATE _sg_image_t* _sg_image_at(uint32_t img_id) {
  5987. SOKOL_ASSERT(SG_INVALID_ID != img_id);
  5988. int slot_index = _sg_slot_index(img_id);
  5989. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < _sg.pools.image_pool.size));
  5990. return &_sg.pools.images[slot_index];
  5991. }
  5992. _SOKOL_PRIVATE _sg_sampler_t* _sg_sampler_at(uint32_t smp_id) {
  5993. SOKOL_ASSERT(SG_INVALID_ID != smp_id);
  5994. int slot_index = _sg_slot_index(smp_id);
  5995. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < _sg.pools.sampler_pool.size));
  5996. return &_sg.pools.samplers[slot_index];
  5997. }
  5998. _SOKOL_PRIVATE _sg_shader_t* _sg_shader_at(uint32_t shd_id) {
  5999. SOKOL_ASSERT(SG_INVALID_ID != shd_id);
  6000. int slot_index = _sg_slot_index(shd_id);
  6001. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < _sg.pools.shader_pool.size));
  6002. return &_sg.pools.shaders[slot_index];
  6003. }
  6004. _SOKOL_PRIVATE _sg_pipeline_t* _sg_pipeline_at(uint32_t pip_id) {
  6005. SOKOL_ASSERT(SG_INVALID_ID != pip_id);
  6006. int slot_index = _sg_slot_index(pip_id);
  6007. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < _sg.pools.pipeline_pool.size));
  6008. return &_sg.pools.pipelines[slot_index];
  6009. }
  6010. _SOKOL_PRIVATE _sg_attachments_t* _sg_attachments_at(uint32_t atts_id) {
  6011. SOKOL_ASSERT(SG_INVALID_ID != atts_id);
  6012. int slot_index = _sg_slot_index(atts_id);
  6013. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < _sg.pools.attachments_pool.size));
  6014. return &_sg.pools.attachments[slot_index];
  6015. }
  6016. // returns pointer to resource with matching id check, may return 0
  6017. _SOKOL_PRIVATE _sg_buffer_t* _sg_lookup_buffer(uint32_t buf_id) {
  6018. if (SG_INVALID_ID != buf_id) {
  6019. _sg_buffer_t* buf = _sg_buffer_at(buf_id);
  6020. if (buf->slot.id == buf_id) {
  6021. return buf;
  6022. }
  6023. }
  6024. return 0;
  6025. }
  6026. _SOKOL_PRIVATE _sg_image_t* _sg_lookup_image(uint32_t img_id) {
  6027. if (SG_INVALID_ID != img_id) {
  6028. _sg_image_t* img = _sg_image_at(img_id);
  6029. if (img->slot.id == img_id) {
  6030. return img;
  6031. }
  6032. }
  6033. return 0;
  6034. }
  6035. _SOKOL_PRIVATE _sg_sampler_t* _sg_lookup_sampler(uint32_t smp_id) {
  6036. if (SG_INVALID_ID != smp_id) {
  6037. _sg_sampler_t* smp = _sg_sampler_at(smp_id);
  6038. if (smp->slot.id == smp_id) {
  6039. return smp;
  6040. }
  6041. }
  6042. return 0;
  6043. }
  6044. _SOKOL_PRIVATE _sg_shader_t* _sg_lookup_shader(uint32_t shd_id) {
  6045. if (SG_INVALID_ID != shd_id) {
  6046. _sg_shader_t* shd = _sg_shader_at(shd_id);
  6047. if (shd->slot.id == shd_id) {
  6048. return shd;
  6049. }
  6050. }
  6051. return 0;
  6052. }
  6053. _SOKOL_PRIVATE _sg_pipeline_t* _sg_lookup_pipeline(uint32_t pip_id) {
  6054. if (SG_INVALID_ID != pip_id) {
  6055. _sg_pipeline_t* pip = _sg_pipeline_at(pip_id);
  6056. if (pip->slot.id == pip_id) {
  6057. return pip;
  6058. }
  6059. }
  6060. return 0;
  6061. }
  6062. _SOKOL_PRIVATE _sg_attachments_t* _sg_lookup_attachments(uint32_t atts_id) {
  6063. if (SG_INVALID_ID != atts_id) {
  6064. _sg_attachments_t* atts = _sg_attachments_at(atts_id);
  6065. if (atts->slot.id == atts_id) {
  6066. return atts;
  6067. }
  6068. }
  6069. return 0;
  6070. }
  6071. // ██████ ███████ ███████ ███████
  6072. // ██ ██ ██ ██ ██
  6073. // ██████ █████ █████ ███████
  6074. // ██ ██ ██ ██ ██
  6075. // ██ ██ ███████ ██ ███████
  6076. //
  6077. // >>refs
  6078. _SOKOL_PRIVATE _sg_sref_t _sg_sref(const _sg_slot_t* slot) {
  6079. _sg_sref_t sref; _sg_clear(&sref, sizeof(sref));
  6080. if (slot) {
  6081. sref.id = slot->id;
  6082. sref.uninit_count = slot->uninit_count;
  6083. }
  6084. return sref;
  6085. }
  6086. _SOKOL_PRIVATE bool _sg_sref_eql(const _sg_sref_t* sref, const _sg_slot_t* slot) {
  6087. SOKOL_ASSERT(sref && slot);
  6088. return (sref->id == slot->id) && (sref->uninit_count == slot->uninit_count);
  6089. }
  6090. _SOKOL_PRIVATE _sg_buffer_ref_t _sg_buffer_ref(_sg_buffer_t* buf_or_null) {
  6091. _sg_buffer_ref_t ref; _sg_clear(&ref, sizeof(ref));
  6092. if (buf_or_null) {
  6093. _sg_buffer_t* buf = buf_or_null;
  6094. SOKOL_ASSERT(buf->slot.id != SG_INVALID_ID);
  6095. ref.ptr = buf;
  6096. ref.sref = _sg_sref(&buf->slot);
  6097. }
  6098. return ref;
  6099. }
  6100. _SOKOL_PRIVATE _sg_image_ref_t _sg_image_ref(_sg_image_t* img_or_null) {
  6101. _sg_image_ref_t ref; _sg_clear(&ref, sizeof(ref));
  6102. if (img_or_null) {
  6103. _sg_image_t* img = img_or_null;
  6104. SOKOL_ASSERT(img->slot.id != SG_INVALID_ID);
  6105. ref.ptr = img;
  6106. ref.sref = _sg_sref(&img->slot);
  6107. }
  6108. return ref;
  6109. }
  6110. _SOKOL_PRIVATE _sg_sampler_ref_t _sg_sampler_ref(_sg_sampler_t* smp_or_null) {
  6111. _sg_sampler_ref_t ref; _sg_clear(&ref, sizeof(ref));
  6112. if (smp_or_null) {
  6113. _sg_sampler_t* smp = smp_or_null;
  6114. SOKOL_ASSERT(smp->slot.id != SG_INVALID_ID);
  6115. ref.ptr = smp;
  6116. ref.sref = _sg_sref(&smp->slot);
  6117. }
  6118. return ref;
  6119. }
  6120. _SOKOL_PRIVATE _sg_shader_ref_t _sg_shader_ref(_sg_shader_t* shd_or_null) {
  6121. _sg_shader_ref_t ref; _sg_clear(&ref, sizeof(ref));
  6122. if (shd_or_null) {
  6123. _sg_shader_t* shd = shd_or_null;
  6124. SOKOL_ASSERT(shd->slot.id != SG_INVALID_ID);
  6125. ref.ptr = shd;
  6126. ref.sref = _sg_sref(&shd->slot);
  6127. }
  6128. return ref;
  6129. }
  6130. _SOKOL_PRIVATE _sg_pipeline_ref_t _sg_pipeline_ref(_sg_pipeline_t* pip_or_null) {
  6131. _sg_pipeline_ref_t ref; _sg_clear(&ref, sizeof(ref));
  6132. if (pip_or_null) {
  6133. _sg_pipeline_t* pip = pip_or_null;
  6134. SOKOL_ASSERT(pip->slot.id != SG_INVALID_ID);
  6135. ref.ptr = pip;
  6136. ref.sref = _sg_sref(&pip->slot);
  6137. }
  6138. return ref;
  6139. }
  6140. _SOKOL_PRIVATE _sg_attachments_ref_t _sg_attachments_ref(_sg_attachments_t* atts_or_null) {
  6141. _sg_attachments_ref_t ref; _sg_clear(&ref, sizeof(ref));
  6142. if (atts_or_null) {
  6143. _sg_attachments_t* atts = atts_or_null;
  6144. SOKOL_ASSERT(atts->slot.id != SG_INVALID_ID);
  6145. ref.ptr = atts;
  6146. ref.sref = _sg_sref(&atts->slot);
  6147. }
  6148. return ref;
  6149. }
  6150. #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); }
  6151. _SG_IMPL_RES_EQL(_sg_buffer_ref_eql, _sg_buffer_ref_t, _sg_buffer_t)
  6152. _SG_IMPL_RES_EQL(_sg_image_ref_eql, _sg_image_ref_t, _sg_image_t)
  6153. _SG_IMPL_RES_EQL(_sg_sampler_ref_eql, _sg_sampler_ref_t, _sg_sampler_t)
  6154. _SG_IMPL_RES_EQL(_sg_shader_ref_eql, _sg_shader_ref_t, _sg_shader_t)
  6155. _SG_IMPL_RES_EQL(_sg_pipeline_ref_eql, _sg_pipeline_ref_t, _sg_pipeline_t)
  6156. _SG_IMPL_RES_EQL(_sg_attachments_ref_eql, _sg_attachments_ref_t, _sg_attachments_t)
  6157. #define _SG_IMPL_RES_NULL(NAME,REF) _SOKOL_PRIVATE bool NAME(const REF* ref) { SOKOL_ASSERT(ref); return SG_INVALID_ID == ref->sref.id; }
  6158. _SG_IMPL_RES_NULL(_sg_buffer_ref_null, _sg_buffer_ref_t)
  6159. _SG_IMPL_RES_NULL(_sg_image_ref_null, _sg_image_ref_t)
  6160. _SG_IMPL_RES_NULL(_sg_sampler_ref_null, _sg_sampler_ref_t)
  6161. _SG_IMPL_RES_NULL(_sg_shader_ref_null, _sg_shader_ref_t)
  6162. _SG_IMPL_RES_NULL(_sg_pipeline_ref_null, _sg_pipeline_ref_t)
  6163. _SG_IMPL_RES_NULL(_sg_attachments_ref_null, _sg_attachments_ref_t)
  6164. #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); }
  6165. _SG_IMPL_RES_ALIVE(_sg_buffer_ref_alive, _sg_buffer_ref_t)
  6166. _SG_IMPL_RES_ALIVE(_sg_image_ref_alive, _sg_image_ref_t)
  6167. _SG_IMPL_RES_ALIVE(_sg_sampler_ref_alive, _sg_sampler_ref_t)
  6168. _SG_IMPL_RES_ALIVE(_sg_shader_ref_alive, _sg_shader_ref_t)
  6169. _SG_IMPL_RES_ALIVE(_sg_pipeline_ref_alive, _sg_pipeline_ref_t)
  6170. _SG_IMPL_RES_ALIVE(_sg_attachments_ref_alive, _sg_attachments_ref_t)
  6171. #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; }
  6172. _SG_IMPL_RES_PTR(_sg_buffer_ref_ptr, _sg_buffer_ref_t, _sg_buffer_t)
  6173. _SG_IMPL_RES_PTR(_sg_image_ref_ptr, _sg_image_ref_t, _sg_image_t)
  6174. _SG_IMPL_RES_PTR(_sg_sampler_ref_ptr, _sg_sampler_ref_t, _sg_sampler_t)
  6175. _SG_IMPL_RES_PTR(_sg_shader_ref_ptr, _sg_shader_ref_t, _sg_shader_t)
  6176. _SG_IMPL_RES_PTR(_sg_pipeline_ref_ptr, _sg_pipeline_ref_t, _sg_pipeline_t)
  6177. _SG_IMPL_RES_PTR(_sg_attachments_ref_ptr, _sg_attachments_ref_t, _sg_attachments_t)
  6178. #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; } }
  6179. _SG_IMPL_RES_PTR_OR_NULL(_sg_buffer_ref_ptr_or_null, _sg_buffer_ref_t, _sg_buffer_t)
  6180. _SG_IMPL_RES_PTR_OR_NULL(_sg_image_ref_ptr_or_null, _sg_image_ref_t, _sg_image_t)
  6181. _SG_IMPL_RES_PTR_OR_NULL(_sg_sampler_ref_ptr_or_null, _sg_sampler_ref_t, _sg_sampler_t)
  6182. _SG_IMPL_RES_PTR_OR_NULL(_sg_shader_ref_ptr_or_null, _sg_shader_ref_t, _sg_shader_t)
  6183. _SG_IMPL_RES_PTR_OR_NULL(_sg_pipeline_ref_ptr_or_null, _sg_pipeline_ref_t, _sg_pipeline_t)
  6184. _SG_IMPL_RES_PTR_OR_NULL(_sg_attachments_ref_ptr_or_null, _sg_attachments_ref_t, _sg_attachments_t)
  6185. // ████████ ██████ █████ ██████ ██ ██ ███████ ██████
  6186. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  6187. // ██ ██████ ███████ ██ █████ █████ ██████
  6188. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  6189. // ██ ██ ██ ██ ██ ██████ ██ ██ ███████ ██ ██
  6190. //
  6191. // >>tracker
  6192. _SOKOL_PRIVATE void _sg_tracker_init(_sg_tracker_t* tracker, uint32_t num) {
  6193. SOKOL_ASSERT(tracker);
  6194. SOKOL_ASSERT(num > 0);
  6195. SOKOL_ASSERT(0 == tracker->size);
  6196. SOKOL_ASSERT(0 == tracker->cur);
  6197. SOKOL_ASSERT(0 == tracker->items);
  6198. tracker->size = (uint32_t)num;
  6199. tracker->items = (uint32_t*)_sg_malloc_clear(num * sizeof(uint32_t));
  6200. }
  6201. _SOKOL_PRIVATE void _sg_tracker_discard(_sg_tracker_t* tracker) {
  6202. SOKOL_ASSERT(tracker);
  6203. if (tracker->items) {
  6204. _sg_free(tracker->items);
  6205. }
  6206. tracker->size = 0;
  6207. tracker->cur = 0;
  6208. tracker->items = 0;
  6209. }
  6210. _SOKOL_PRIVATE void _sg_tracker_reset(_sg_tracker_t* tracker) {
  6211. SOKOL_ASSERT(tracker && tracker->items);
  6212. tracker->cur = 0;
  6213. }
  6214. _SOKOL_PRIVATE bool _sg_tracker_add(_sg_tracker_t* tracker, uint32_t res_id) {
  6215. SOKOL_ASSERT(tracker && tracker->items);
  6216. if (tracker->cur < tracker->size) {
  6217. tracker->items[tracker->cur++] = res_id;
  6218. return true;
  6219. } else {
  6220. return false;
  6221. }
  6222. }
  6223. // ██ ██ ███████ ██ ██████ ███████ ██████ ███████
  6224. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  6225. // ███████ █████ ██ ██████ █████ ██████ ███████
  6226. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  6227. // ██ ██ ███████ ███████ ██ ███████ ██ ██ ███████
  6228. //
  6229. // >>helpers
  6230. // helper macros
  6231. #define _sg_def(val, def) (((val) == 0) ? (def) : (val))
  6232. #define _sg_def_flt(val, def) (((val) == 0.0f) ? (def) : (val))
  6233. #define _sg_min(a,b) (((a)<(b))?(a):(b))
  6234. #define _sg_max(a,b) (((a)>(b))?(a):(b))
  6235. #define _sg_clamp(v,v0,v1) (((v)<(v0))?(v0):(((v)>(v1))?(v1):(v)))
  6236. #define _sg_fequal(val,cmp,delta) ((((val)-(cmp))> -(delta))&&(((val)-(cmp))<(delta)))
  6237. #define _sg_ispow2(val) ((val&(val-1))==0)
  6238. #define _sg_stats_add(key,val) {if(_sg.stats_enabled){ _sg.stats.key+=val;}}
  6239. _SOKOL_PRIVATE uint32_t _sg_align_u32(uint32_t val, uint32_t align) {
  6240. SOKOL_ASSERT((align > 0) && ((align & (align - 1)) == 0));
  6241. return (val + (align - 1)) & ~(align - 1);
  6242. }
  6243. typedef struct { int x, y, w, h; } _sg_recti_t;
  6244. _SOKOL_PRIVATE _sg_recti_t _sg_clipi(int x, int y, int w, int h, int clip_width, int clip_height) {
  6245. x = _sg_min(_sg_max(0, x), clip_width-1);
  6246. y = _sg_min(_sg_max(0, y), clip_height-1);
  6247. if ((x + w) > clip_width) {
  6248. w = clip_width - x;
  6249. }
  6250. if ((y + h) > clip_height) {
  6251. h = clip_height - y;
  6252. }
  6253. w = _sg_max(w, 1);
  6254. h = _sg_max(h, 1);
  6255. const _sg_recti_t res = { x, y, w, h };
  6256. return res;
  6257. }
  6258. _SOKOL_PRIVATE void _sg_buffer_common_init(_sg_buffer_common_t* cmn, const sg_buffer_desc* desc) {
  6259. cmn->size = (int)desc->size;
  6260. cmn->append_pos = 0;
  6261. cmn->append_overflow = false;
  6262. cmn->update_frame_index = 0;
  6263. cmn->append_frame_index = 0;
  6264. cmn->num_slots = desc->usage.immutable ? 1 : SG_NUM_INFLIGHT_FRAMES;
  6265. cmn->active_slot = 0;
  6266. cmn->usage = desc->usage;
  6267. }
  6268. _SOKOL_PRIVATE void _sg_image_common_init(_sg_image_common_t* cmn, const sg_image_desc* desc) {
  6269. cmn->upd_frame_index = 0;
  6270. cmn->num_slots = desc->usage.immutable ? 1 : SG_NUM_INFLIGHT_FRAMES;
  6271. cmn->active_slot = 0;
  6272. cmn->type = desc->type;
  6273. cmn->width = desc->width;
  6274. cmn->height = desc->height;
  6275. cmn->num_slices = desc->num_slices;
  6276. cmn->num_mipmaps = desc->num_mipmaps;
  6277. cmn->usage = desc->usage;
  6278. cmn->pixel_format = desc->pixel_format;
  6279. cmn->sample_count = desc->sample_count;
  6280. }
  6281. _SOKOL_PRIVATE void _sg_sampler_common_init(_sg_sampler_common_t* cmn, const sg_sampler_desc* desc) {
  6282. cmn->min_filter = desc->min_filter;
  6283. cmn->mag_filter = desc->mag_filter;
  6284. cmn->mipmap_filter = desc->mipmap_filter;
  6285. cmn->wrap_u = desc->wrap_u;
  6286. cmn->wrap_v = desc->wrap_v;
  6287. cmn->wrap_w = desc->wrap_w;
  6288. cmn->min_lod = desc->min_lod;
  6289. cmn->max_lod = desc->max_lod;
  6290. cmn->border_color = desc->border_color;
  6291. cmn->compare = desc->compare;
  6292. cmn->max_anisotropy = desc->max_anisotropy;
  6293. }
  6294. _SOKOL_PRIVATE void _sg_shader_common_init(_sg_shader_common_t* cmn, const sg_shader_desc* desc) {
  6295. cmn->is_compute = desc->compute_func.source || desc->compute_func.bytecode.ptr;
  6296. for (size_t i = 0; i < SG_MAX_VERTEX_ATTRIBUTES; i++) {
  6297. cmn->attrs[i].base_type = desc->attrs[i].base_type;
  6298. }
  6299. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  6300. const sg_shader_uniform_block* src = &desc->uniform_blocks[i];
  6301. _sg_shader_uniform_block_t* dst = &cmn->uniform_blocks[i];
  6302. if (src->stage != SG_SHADERSTAGE_NONE) {
  6303. cmn->required_bindings_and_uniforms |= (1 << i);
  6304. dst->stage = src->stage;
  6305. dst->size = src->size;
  6306. }
  6307. }
  6308. const uint32_t required_bindings_flag = (1 << SG_MAX_UNIFORMBLOCK_BINDSLOTS);
  6309. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  6310. const sg_shader_storage_buffer* src = &desc->storage_buffers[i];
  6311. _sg_shader_storage_buffer_t* dst = &cmn->storage_buffers[i];
  6312. if (src->stage != SG_SHADERSTAGE_NONE) {
  6313. cmn->required_bindings_and_uniforms |= required_bindings_flag;
  6314. dst->stage = src->stage;
  6315. dst->readonly = src->readonly;
  6316. }
  6317. }
  6318. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  6319. const sg_shader_image* src = &desc->images[i];
  6320. _sg_shader_image_t* dst = &cmn->images[i];
  6321. if (src->stage != SG_SHADERSTAGE_NONE) {
  6322. cmn->required_bindings_and_uniforms |= required_bindings_flag;
  6323. dst->stage = src->stage;
  6324. dst->image_type = src->image_type;
  6325. dst->sample_type = src->sample_type;
  6326. dst->multisampled = src->multisampled;
  6327. }
  6328. }
  6329. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  6330. const sg_shader_sampler* src = &desc->samplers[i];
  6331. _sg_shader_sampler_t* dst = &cmn->samplers[i];
  6332. if (src->stage != SG_SHADERSTAGE_NONE) {
  6333. cmn->required_bindings_and_uniforms |= required_bindings_flag;
  6334. dst->stage = src->stage;
  6335. dst->sampler_type = src->sampler_type;
  6336. }
  6337. }
  6338. for (size_t i = 0; i < SG_MAX_IMAGE_SAMPLER_PAIRS; i++) {
  6339. const sg_shader_image_sampler_pair* src = &desc->image_sampler_pairs[i];
  6340. _sg_shader_image_sampler_t* dst = &cmn->image_samplers[i];
  6341. if (src->stage != SG_SHADERSTAGE_NONE) {
  6342. dst->stage = src->stage;
  6343. SOKOL_ASSERT((src->image_slot >= 0) && (src->image_slot < SG_MAX_IMAGE_BINDSLOTS));
  6344. SOKOL_ASSERT(desc->images[src->image_slot].stage == src->stage);
  6345. dst->image_slot = src->image_slot;
  6346. SOKOL_ASSERT((src->sampler_slot >= 0) && (src->sampler_slot < SG_MAX_SAMPLER_BINDSLOTS));
  6347. SOKOL_ASSERT(desc->samplers[src->sampler_slot].stage == src->stage);
  6348. dst->sampler_slot = src->sampler_slot;
  6349. }
  6350. }
  6351. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  6352. const sg_shader_storage_image* src = &desc->storage_images[i];
  6353. _sg_shader_storage_image_t* dst = &cmn->storage_images[i];
  6354. if (src->stage != SG_SHADERSTAGE_NONE) {
  6355. dst->stage = src->stage;
  6356. dst->image_type = src->image_type;
  6357. dst->access_format = src->access_format;
  6358. dst->writeonly = src->writeonly;
  6359. }
  6360. }
  6361. }
  6362. _SOKOL_PRIVATE void _sg_pipeline_common_init(_sg_pipeline_common_t* cmn, const sg_pipeline_desc* desc, _sg_shader_t* shd) {
  6363. SOKOL_ASSERT((desc->color_count >= 0) && (desc->color_count <= SG_MAX_COLOR_ATTACHMENTS));
  6364. // FIXME: most of this isn't needed for compute pipelines
  6365. const uint32_t required_bindings_flag = (1 << SG_MAX_UNIFORMBLOCK_BINDSLOTS);
  6366. for (int i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  6367. const sg_vertex_attr_state* a_state = &desc->layout.attrs[i];
  6368. if (a_state->format != SG_VERTEXFORMAT_INVALID) {
  6369. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  6370. cmn->vertex_buffer_layout_active[a_state->buffer_index] = true;
  6371. cmn->required_bindings_and_uniforms |= required_bindings_flag;
  6372. }
  6373. }
  6374. cmn->is_compute = desc->compute;
  6375. cmn->use_instanced_draw = false;
  6376. cmn->shader = _sg_shader_ref(shd);
  6377. cmn->layout = desc->layout;
  6378. cmn->depth = desc->depth;
  6379. cmn->stencil = desc->stencil;
  6380. cmn->color_count = desc->color_count;
  6381. for (int i = 0; i < desc->color_count; i++) {
  6382. cmn->colors[i] = desc->colors[i];
  6383. }
  6384. cmn->primitive_type = desc->primitive_type;
  6385. cmn->index_type = desc->index_type;
  6386. if (cmn->index_type != SG_INDEXTYPE_NONE) {
  6387. cmn->required_bindings_and_uniforms |= required_bindings_flag;
  6388. }
  6389. cmn->cull_mode = desc->cull_mode;
  6390. cmn->face_winding = desc->face_winding;
  6391. cmn->sample_count = desc->sample_count;
  6392. cmn->blend_color = desc->blend_color;
  6393. cmn->alpha_to_coverage_enabled = desc->alpha_to_coverage_enabled;
  6394. }
  6395. _SOKOL_PRIVATE void _sg_attachment_common_init(_sg_attachment_common_t* cmn, const sg_attachment_desc* desc, _sg_image_t* img) {
  6396. cmn->image = _sg_image_ref(img);
  6397. cmn->mip_level = desc->mip_level;
  6398. cmn->slice = desc->slice;
  6399. }
  6400. _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) {
  6401. // NOTE: width/height will be 0 for storage image attachments
  6402. cmn->width = width;
  6403. cmn->height = height;
  6404. for (size_t i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  6405. if (desc->colors[i].image.id != SG_INVALID_ID) {
  6406. cmn->num_colors++;
  6407. _sg_attachment_common_init(&cmn->colors[i], &desc->colors[i], ptrs->color_images[i]);
  6408. _sg_attachment_common_init(&cmn->resolves[i], &desc->resolves[i], ptrs->resolve_images[i]);
  6409. cmn->has_render_attachments = true;
  6410. }
  6411. }
  6412. if (desc->depth_stencil.image.id != SG_INVALID_ID) {
  6413. _sg_attachment_common_init(&cmn->depth_stencil, &desc->depth_stencil, ptrs->ds_image);
  6414. cmn->has_render_attachments = true;
  6415. }
  6416. // NOTE: storage attachment slots may be non-continuous,
  6417. // so a 'num_storages' doesn't make sense
  6418. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  6419. if (desc->storages[i].image.id != SG_INVALID_ID) {
  6420. cmn->has_storage_attachments = true;
  6421. _sg_attachment_common_init(&cmn->storages[i], &desc->storages[i], ptrs->storage_images[i]);
  6422. }
  6423. }
  6424. }
  6425. _SOKOL_PRIVATE int _sg_vertexformat_bytesize(sg_vertex_format fmt) {
  6426. switch (fmt) {
  6427. case SG_VERTEXFORMAT_FLOAT: return 4;
  6428. case SG_VERTEXFORMAT_FLOAT2: return 8;
  6429. case SG_VERTEXFORMAT_FLOAT3: return 12;
  6430. case SG_VERTEXFORMAT_FLOAT4: return 16;
  6431. case SG_VERTEXFORMAT_INT: return 4;
  6432. case SG_VERTEXFORMAT_INT2: return 8;
  6433. case SG_VERTEXFORMAT_INT3: return 12;
  6434. case SG_VERTEXFORMAT_INT4: return 16;
  6435. case SG_VERTEXFORMAT_UINT: return 4;
  6436. case SG_VERTEXFORMAT_UINT2: return 8;
  6437. case SG_VERTEXFORMAT_UINT3: return 12;
  6438. case SG_VERTEXFORMAT_UINT4: return 16;
  6439. case SG_VERTEXFORMAT_BYTE4: return 4;
  6440. case SG_VERTEXFORMAT_BYTE4N: return 4;
  6441. case SG_VERTEXFORMAT_UBYTE4: return 4;
  6442. case SG_VERTEXFORMAT_UBYTE4N: return 4;
  6443. case SG_VERTEXFORMAT_SHORT2: return 4;
  6444. case SG_VERTEXFORMAT_SHORT2N: return 4;
  6445. case SG_VERTEXFORMAT_USHORT2: return 4;
  6446. case SG_VERTEXFORMAT_USHORT2N: return 4;
  6447. case SG_VERTEXFORMAT_SHORT4: return 8;
  6448. case SG_VERTEXFORMAT_SHORT4N: return 8;
  6449. case SG_VERTEXFORMAT_USHORT4: return 8;
  6450. case SG_VERTEXFORMAT_USHORT4N: return 8;
  6451. case SG_VERTEXFORMAT_UINT10_N2: return 4;
  6452. case SG_VERTEXFORMAT_HALF2: return 4;
  6453. case SG_VERTEXFORMAT_HALF4: return 8;
  6454. case SG_VERTEXFORMAT_INVALID: return 0;
  6455. default:
  6456. SOKOL_UNREACHABLE;
  6457. return -1;
  6458. }
  6459. }
  6460. _SOKOL_PRIVATE const char* _sg_vertexformat_to_string(sg_vertex_format fmt) {
  6461. switch (fmt) {
  6462. case SG_VERTEXFORMAT_FLOAT: return "FLOAT";
  6463. case SG_VERTEXFORMAT_FLOAT2: return "FLOAT2";
  6464. case SG_VERTEXFORMAT_FLOAT3: return "FLOAT3";
  6465. case SG_VERTEXFORMAT_FLOAT4: return "FLOAT4";
  6466. case SG_VERTEXFORMAT_INT: return "INT";
  6467. case SG_VERTEXFORMAT_INT2: return "INT2";
  6468. case SG_VERTEXFORMAT_INT3: return "INT3";
  6469. case SG_VERTEXFORMAT_INT4: return "INT4";
  6470. case SG_VERTEXFORMAT_UINT: return "UINT";
  6471. case SG_VERTEXFORMAT_UINT2: return "UINT2";
  6472. case SG_VERTEXFORMAT_UINT3: return "UINT3";
  6473. case SG_VERTEXFORMAT_UINT4: return "UINT4";
  6474. case SG_VERTEXFORMAT_BYTE4: return "BYTE4";
  6475. case SG_VERTEXFORMAT_BYTE4N: return "BYTE4N";
  6476. case SG_VERTEXFORMAT_UBYTE4: return "UBYTE4";
  6477. case SG_VERTEXFORMAT_UBYTE4N: return "UBYTE4N";
  6478. case SG_VERTEXFORMAT_SHORT2: return "SHORT2";
  6479. case SG_VERTEXFORMAT_SHORT2N: return "SHORT2N";
  6480. case SG_VERTEXFORMAT_USHORT2: return "USHORT2";
  6481. case SG_VERTEXFORMAT_USHORT2N: return "USHORT2N";
  6482. case SG_VERTEXFORMAT_SHORT4: return "SHORT4";
  6483. case SG_VERTEXFORMAT_SHORT4N: return "SHORT4N";
  6484. case SG_VERTEXFORMAT_USHORT4: return "USHORT4";
  6485. case SG_VERTEXFORMAT_USHORT4N: return "USHORT4N";
  6486. case SG_VERTEXFORMAT_UINT10_N2: return "UINT10_N2";
  6487. case SG_VERTEXFORMAT_HALF2: return "HALF2";
  6488. case SG_VERTEXFORMAT_HALF4: return "HALF4";
  6489. default:
  6490. SOKOL_UNREACHABLE;
  6491. return "INVALID";
  6492. }
  6493. }
  6494. _SOKOL_PRIVATE const char* _sg_shaderattrbasetype_to_string(sg_shader_attr_base_type b) {
  6495. switch (b) {
  6496. case SG_SHADERATTRBASETYPE_UNDEFINED: return "UNDEFINED";
  6497. case SG_SHADERATTRBASETYPE_FLOAT: return "FLOAT";
  6498. case SG_SHADERATTRBASETYPE_SINT: return "SINT";
  6499. case SG_SHADERATTRBASETYPE_UINT: return "UINT";
  6500. default:
  6501. SOKOL_UNREACHABLE;
  6502. return "INVALID";
  6503. }
  6504. }
  6505. _SOKOL_PRIVATE sg_shader_attr_base_type _sg_vertexformat_basetype(sg_vertex_format fmt) {
  6506. switch (fmt) {
  6507. case SG_VERTEXFORMAT_FLOAT:
  6508. case SG_VERTEXFORMAT_FLOAT2:
  6509. case SG_VERTEXFORMAT_FLOAT3:
  6510. case SG_VERTEXFORMAT_FLOAT4:
  6511. case SG_VERTEXFORMAT_HALF2:
  6512. case SG_VERTEXFORMAT_HALF4:
  6513. case SG_VERTEXFORMAT_BYTE4N:
  6514. case SG_VERTEXFORMAT_UBYTE4N:
  6515. case SG_VERTEXFORMAT_SHORT2N:
  6516. case SG_VERTEXFORMAT_USHORT2N:
  6517. case SG_VERTEXFORMAT_SHORT4N:
  6518. case SG_VERTEXFORMAT_USHORT4N:
  6519. case SG_VERTEXFORMAT_UINT10_N2:
  6520. return SG_SHADERATTRBASETYPE_FLOAT;
  6521. case SG_VERTEXFORMAT_INT:
  6522. case SG_VERTEXFORMAT_INT2:
  6523. case SG_VERTEXFORMAT_INT3:
  6524. case SG_VERTEXFORMAT_INT4:
  6525. case SG_VERTEXFORMAT_BYTE4:
  6526. case SG_VERTEXFORMAT_SHORT2:
  6527. case SG_VERTEXFORMAT_SHORT4:
  6528. return SG_SHADERATTRBASETYPE_SINT;
  6529. case SG_VERTEXFORMAT_UINT:
  6530. case SG_VERTEXFORMAT_UINT2:
  6531. case SG_VERTEXFORMAT_UINT3:
  6532. case SG_VERTEXFORMAT_UINT4:
  6533. case SG_VERTEXFORMAT_UBYTE4:
  6534. case SG_VERTEXFORMAT_USHORT2:
  6535. case SG_VERTEXFORMAT_USHORT4:
  6536. return SG_SHADERATTRBASETYPE_UINT;
  6537. default:
  6538. SOKOL_UNREACHABLE;
  6539. return SG_SHADERATTRBASETYPE_UNDEFINED;
  6540. }
  6541. }
  6542. _SOKOL_PRIVATE uint32_t _sg_uniform_alignment(sg_uniform_type type, int array_count, sg_uniform_layout ub_layout) {
  6543. if (ub_layout == SG_UNIFORMLAYOUT_NATIVE) {
  6544. return 1;
  6545. } else {
  6546. SOKOL_ASSERT(array_count > 0);
  6547. if (array_count == 1) {
  6548. switch (type) {
  6549. case SG_UNIFORMTYPE_FLOAT:
  6550. case SG_UNIFORMTYPE_INT:
  6551. return 4;
  6552. case SG_UNIFORMTYPE_FLOAT2:
  6553. case SG_UNIFORMTYPE_INT2:
  6554. return 8;
  6555. case SG_UNIFORMTYPE_FLOAT3:
  6556. case SG_UNIFORMTYPE_FLOAT4:
  6557. case SG_UNIFORMTYPE_INT3:
  6558. case SG_UNIFORMTYPE_INT4:
  6559. return 16;
  6560. case SG_UNIFORMTYPE_MAT4:
  6561. return 16;
  6562. default:
  6563. SOKOL_UNREACHABLE;
  6564. return 1;
  6565. }
  6566. } else {
  6567. return 16;
  6568. }
  6569. }
  6570. }
  6571. _SOKOL_PRIVATE uint32_t _sg_uniform_size(sg_uniform_type type, int array_count, sg_uniform_layout ub_layout) {
  6572. SOKOL_ASSERT(array_count > 0);
  6573. if (array_count == 1) {
  6574. switch (type) {
  6575. case SG_UNIFORMTYPE_FLOAT:
  6576. case SG_UNIFORMTYPE_INT:
  6577. return 4;
  6578. case SG_UNIFORMTYPE_FLOAT2:
  6579. case SG_UNIFORMTYPE_INT2:
  6580. return 8;
  6581. case SG_UNIFORMTYPE_FLOAT3:
  6582. case SG_UNIFORMTYPE_INT3:
  6583. return 12;
  6584. case SG_UNIFORMTYPE_FLOAT4:
  6585. case SG_UNIFORMTYPE_INT4:
  6586. return 16;
  6587. case SG_UNIFORMTYPE_MAT4:
  6588. return 64;
  6589. default:
  6590. SOKOL_UNREACHABLE;
  6591. return 0;
  6592. }
  6593. } else {
  6594. if (ub_layout == SG_UNIFORMLAYOUT_NATIVE) {
  6595. switch (type) {
  6596. case SG_UNIFORMTYPE_FLOAT:
  6597. case SG_UNIFORMTYPE_INT:
  6598. return 4 * (uint32_t)array_count;
  6599. case SG_UNIFORMTYPE_FLOAT2:
  6600. case SG_UNIFORMTYPE_INT2:
  6601. return 8 * (uint32_t)array_count;
  6602. case SG_UNIFORMTYPE_FLOAT3:
  6603. case SG_UNIFORMTYPE_INT3:
  6604. return 12 * (uint32_t)array_count;
  6605. case SG_UNIFORMTYPE_FLOAT4:
  6606. case SG_UNIFORMTYPE_INT4:
  6607. return 16 * (uint32_t)array_count;
  6608. case SG_UNIFORMTYPE_MAT4:
  6609. return 64 * (uint32_t)array_count;
  6610. default:
  6611. SOKOL_UNREACHABLE;
  6612. return 0;
  6613. }
  6614. } else {
  6615. switch (type) {
  6616. case SG_UNIFORMTYPE_FLOAT:
  6617. case SG_UNIFORMTYPE_FLOAT2:
  6618. case SG_UNIFORMTYPE_FLOAT3:
  6619. case SG_UNIFORMTYPE_FLOAT4:
  6620. case SG_UNIFORMTYPE_INT:
  6621. case SG_UNIFORMTYPE_INT2:
  6622. case SG_UNIFORMTYPE_INT3:
  6623. case SG_UNIFORMTYPE_INT4:
  6624. return 16 * (uint32_t)array_count;
  6625. case SG_UNIFORMTYPE_MAT4:
  6626. return 64 * (uint32_t)array_count;
  6627. default:
  6628. SOKOL_UNREACHABLE;
  6629. return 0;
  6630. }
  6631. }
  6632. }
  6633. }
  6634. _SOKOL_PRIVATE bool _sg_is_compressed_pixel_format(sg_pixel_format fmt) {
  6635. switch (fmt) {
  6636. case SG_PIXELFORMAT_BC1_RGBA:
  6637. case SG_PIXELFORMAT_BC2_RGBA:
  6638. case SG_PIXELFORMAT_BC3_RGBA:
  6639. case SG_PIXELFORMAT_BC3_SRGBA:
  6640. case SG_PIXELFORMAT_BC4_R:
  6641. case SG_PIXELFORMAT_BC4_RSN:
  6642. case SG_PIXELFORMAT_BC5_RG:
  6643. case SG_PIXELFORMAT_BC5_RGSN:
  6644. case SG_PIXELFORMAT_BC6H_RGBF:
  6645. case SG_PIXELFORMAT_BC6H_RGBUF:
  6646. case SG_PIXELFORMAT_BC7_RGBA:
  6647. case SG_PIXELFORMAT_BC7_SRGBA:
  6648. case SG_PIXELFORMAT_ETC2_RGB8:
  6649. case SG_PIXELFORMAT_ETC2_SRGB8:
  6650. case SG_PIXELFORMAT_ETC2_RGB8A1:
  6651. case SG_PIXELFORMAT_ETC2_RGBA8:
  6652. case SG_PIXELFORMAT_ETC2_SRGB8A8:
  6653. case SG_PIXELFORMAT_EAC_R11:
  6654. case SG_PIXELFORMAT_EAC_R11SN:
  6655. case SG_PIXELFORMAT_EAC_RG11:
  6656. case SG_PIXELFORMAT_EAC_RG11SN:
  6657. case SG_PIXELFORMAT_ASTC_4x4_RGBA:
  6658. case SG_PIXELFORMAT_ASTC_4x4_SRGBA:
  6659. return true;
  6660. default:
  6661. return false;
  6662. }
  6663. }
  6664. _SOKOL_PRIVATE bool _sg_is_valid_attachment_color_format(sg_pixel_format fmt) {
  6665. const int fmt_index = (int) fmt;
  6666. SOKOL_ASSERT((fmt_index >= 0) && (fmt_index < _SG_PIXELFORMAT_NUM));
  6667. return _sg.formats[fmt_index].render && !_sg.formats[fmt_index].depth;
  6668. }
  6669. _SOKOL_PRIVATE bool _sg_is_valid_attachment_depth_format(sg_pixel_format fmt) {
  6670. const int fmt_index = (int) fmt;
  6671. SOKOL_ASSERT((fmt_index >= 0) && (fmt_index < _SG_PIXELFORMAT_NUM));
  6672. return _sg.formats[fmt_index].render && _sg.formats[fmt_index].depth;
  6673. }
  6674. _SOKOL_PRIVATE bool _sg_is_valid_attachment_storage_format(sg_pixel_format fmt) {
  6675. const int fmt_index = (int) fmt;
  6676. SOKOL_ASSERT((fmt_index >= 0) && (fmt_index < _SG_PIXELFORMAT_NUM));
  6677. return _sg.formats[fmt_index].read || _sg.formats[fmt_index].write;
  6678. }
  6679. _SOKOL_PRIVATE bool _sg_is_depth_or_depth_stencil_format(sg_pixel_format fmt) {
  6680. return (SG_PIXELFORMAT_DEPTH == fmt) || (SG_PIXELFORMAT_DEPTH_STENCIL == fmt);
  6681. }
  6682. _SOKOL_PRIVATE bool _sg_is_depth_stencil_format(sg_pixel_format fmt) {
  6683. return (SG_PIXELFORMAT_DEPTH_STENCIL == fmt);
  6684. }
  6685. _SOKOL_PRIVATE int _sg_pixelformat_bytesize(sg_pixel_format fmt) {
  6686. switch (fmt) {
  6687. case SG_PIXELFORMAT_R8:
  6688. case SG_PIXELFORMAT_R8SN:
  6689. case SG_PIXELFORMAT_R8UI:
  6690. case SG_PIXELFORMAT_R8SI:
  6691. return 1;
  6692. case SG_PIXELFORMAT_R16:
  6693. case SG_PIXELFORMAT_R16SN:
  6694. case SG_PIXELFORMAT_R16UI:
  6695. case SG_PIXELFORMAT_R16SI:
  6696. case SG_PIXELFORMAT_R16F:
  6697. case SG_PIXELFORMAT_RG8:
  6698. case SG_PIXELFORMAT_RG8SN:
  6699. case SG_PIXELFORMAT_RG8UI:
  6700. case SG_PIXELFORMAT_RG8SI:
  6701. return 2;
  6702. case SG_PIXELFORMAT_R32UI:
  6703. case SG_PIXELFORMAT_R32SI:
  6704. case SG_PIXELFORMAT_R32F:
  6705. case SG_PIXELFORMAT_RG16:
  6706. case SG_PIXELFORMAT_RG16SN:
  6707. case SG_PIXELFORMAT_RG16UI:
  6708. case SG_PIXELFORMAT_RG16SI:
  6709. case SG_PIXELFORMAT_RG16F:
  6710. case SG_PIXELFORMAT_RGBA8:
  6711. case SG_PIXELFORMAT_SRGB8A8:
  6712. case SG_PIXELFORMAT_RGBA8SN:
  6713. case SG_PIXELFORMAT_RGBA8UI:
  6714. case SG_PIXELFORMAT_RGBA8SI:
  6715. case SG_PIXELFORMAT_BGRA8:
  6716. case SG_PIXELFORMAT_RGB10A2:
  6717. case SG_PIXELFORMAT_RG11B10F:
  6718. case SG_PIXELFORMAT_RGB9E5:
  6719. return 4;
  6720. case SG_PIXELFORMAT_RG32UI:
  6721. case SG_PIXELFORMAT_RG32SI:
  6722. case SG_PIXELFORMAT_RG32F:
  6723. case SG_PIXELFORMAT_RGBA16:
  6724. case SG_PIXELFORMAT_RGBA16SN:
  6725. case SG_PIXELFORMAT_RGBA16UI:
  6726. case SG_PIXELFORMAT_RGBA16SI:
  6727. case SG_PIXELFORMAT_RGBA16F:
  6728. return 8;
  6729. case SG_PIXELFORMAT_RGBA32UI:
  6730. case SG_PIXELFORMAT_RGBA32SI:
  6731. case SG_PIXELFORMAT_RGBA32F:
  6732. return 16;
  6733. case SG_PIXELFORMAT_DEPTH:
  6734. case SG_PIXELFORMAT_DEPTH_STENCIL:
  6735. return 4;
  6736. default:
  6737. SOKOL_UNREACHABLE;
  6738. return 0;
  6739. }
  6740. }
  6741. _SOKOL_PRIVATE int _sg_roundup(int val, int round_to) {
  6742. return (val+(round_to-1)) & ~(round_to-1);
  6743. }
  6744. _SOKOL_PRIVATE uint32_t _sg_roundup_u32(uint32_t val, uint32_t round_to) {
  6745. return (val+(round_to-1)) & ~(round_to-1);
  6746. }
  6747. _SOKOL_PRIVATE uint64_t _sg_roundup_u64(uint64_t val, uint64_t round_to) {
  6748. return (val+(round_to-1)) & ~(round_to-1);
  6749. }
  6750. _SOKOL_PRIVATE bool _sg_multiple_u64(uint64_t val, uint64_t of) {
  6751. return (val & (of-1)) == 0;
  6752. }
  6753. /* return row pitch for an image
  6754. see ComputePitch in https://github.com/microsoft/DirectXTex/blob/master/DirectXTex/DirectXTexUtil.cpp
  6755. */
  6756. _SOKOL_PRIVATE int _sg_row_pitch(sg_pixel_format fmt, int width, int row_align) {
  6757. int pitch;
  6758. switch (fmt) {
  6759. case SG_PIXELFORMAT_BC1_RGBA:
  6760. case SG_PIXELFORMAT_BC4_R:
  6761. case SG_PIXELFORMAT_BC4_RSN:
  6762. case SG_PIXELFORMAT_ETC2_RGB8:
  6763. case SG_PIXELFORMAT_ETC2_SRGB8:
  6764. case SG_PIXELFORMAT_ETC2_RGB8A1:
  6765. case SG_PIXELFORMAT_EAC_R11:
  6766. case SG_PIXELFORMAT_EAC_R11SN:
  6767. pitch = ((width + 3) / 4) * 8;
  6768. pitch = pitch < 8 ? 8 : pitch;
  6769. break;
  6770. case SG_PIXELFORMAT_BC2_RGBA:
  6771. case SG_PIXELFORMAT_BC3_RGBA:
  6772. case SG_PIXELFORMAT_BC3_SRGBA:
  6773. case SG_PIXELFORMAT_BC5_RG:
  6774. case SG_PIXELFORMAT_BC5_RGSN:
  6775. case SG_PIXELFORMAT_BC6H_RGBF:
  6776. case SG_PIXELFORMAT_BC6H_RGBUF:
  6777. case SG_PIXELFORMAT_BC7_RGBA:
  6778. case SG_PIXELFORMAT_BC7_SRGBA:
  6779. case SG_PIXELFORMAT_ETC2_RGBA8:
  6780. case SG_PIXELFORMAT_ETC2_SRGB8A8:
  6781. case SG_PIXELFORMAT_EAC_RG11:
  6782. case SG_PIXELFORMAT_EAC_RG11SN:
  6783. case SG_PIXELFORMAT_ASTC_4x4_RGBA:
  6784. case SG_PIXELFORMAT_ASTC_4x4_SRGBA:
  6785. pitch = ((width + 3) / 4) * 16;
  6786. pitch = pitch < 16 ? 16 : pitch;
  6787. break;
  6788. default:
  6789. pitch = width * _sg_pixelformat_bytesize(fmt);
  6790. break;
  6791. }
  6792. pitch = _sg_roundup(pitch, row_align);
  6793. return pitch;
  6794. }
  6795. // compute the number of rows in a surface depending on pixel format
  6796. _SOKOL_PRIVATE int _sg_num_rows(sg_pixel_format fmt, int height) {
  6797. int num_rows;
  6798. switch (fmt) {
  6799. case SG_PIXELFORMAT_BC1_RGBA:
  6800. case SG_PIXELFORMAT_BC4_R:
  6801. case SG_PIXELFORMAT_BC4_RSN:
  6802. case SG_PIXELFORMAT_ETC2_RGB8:
  6803. case SG_PIXELFORMAT_ETC2_SRGB8:
  6804. case SG_PIXELFORMAT_ETC2_RGB8A1:
  6805. case SG_PIXELFORMAT_ETC2_RGBA8:
  6806. case SG_PIXELFORMAT_ETC2_SRGB8A8:
  6807. case SG_PIXELFORMAT_EAC_R11:
  6808. case SG_PIXELFORMAT_EAC_R11SN:
  6809. case SG_PIXELFORMAT_EAC_RG11:
  6810. case SG_PIXELFORMAT_EAC_RG11SN:
  6811. case SG_PIXELFORMAT_BC2_RGBA:
  6812. case SG_PIXELFORMAT_BC3_RGBA:
  6813. case SG_PIXELFORMAT_BC3_SRGBA:
  6814. case SG_PIXELFORMAT_BC5_RG:
  6815. case SG_PIXELFORMAT_BC5_RGSN:
  6816. case SG_PIXELFORMAT_BC6H_RGBF:
  6817. case SG_PIXELFORMAT_BC6H_RGBUF:
  6818. case SG_PIXELFORMAT_BC7_RGBA:
  6819. case SG_PIXELFORMAT_BC7_SRGBA:
  6820. case SG_PIXELFORMAT_ASTC_4x4_RGBA:
  6821. case SG_PIXELFORMAT_ASTC_4x4_SRGBA:
  6822. num_rows = ((height + 3) / 4);
  6823. break;
  6824. default:
  6825. num_rows = height;
  6826. break;
  6827. }
  6828. if (num_rows < 1) {
  6829. num_rows = 1;
  6830. }
  6831. return num_rows;
  6832. }
  6833. // return size of a mipmap level
  6834. _SOKOL_PRIVATE int _sg_miplevel_dim(int base_dim, int mip_level) {
  6835. return _sg_max(base_dim >> mip_level, 1);
  6836. }
  6837. /* return pitch of a 2D subimage / texture slice
  6838. see ComputePitch in https://github.com/microsoft/DirectXTex/blob/master/DirectXTex/DirectXTexUtil.cpp
  6839. */
  6840. _SOKOL_PRIVATE int _sg_surface_pitch(sg_pixel_format fmt, int width, int height, int row_align) {
  6841. int num_rows = _sg_num_rows(fmt, height);
  6842. return num_rows * _sg_row_pitch(fmt, width, row_align);
  6843. }
  6844. // capability table pixel format helper functions
  6845. _SOKOL_PRIVATE void _sg_pixelformat_all(_sg_pixelformat_info_t* pfi) {
  6846. pfi->sample = true;
  6847. pfi->filter = true;
  6848. pfi->blend = true;
  6849. pfi->render = true;
  6850. pfi->msaa = true;
  6851. }
  6852. _SOKOL_PRIVATE void _sg_pixelformat_s(_sg_pixelformat_info_t* pfi) {
  6853. pfi->sample = true;
  6854. }
  6855. _SOKOL_PRIVATE void _sg_pixelformat_sf(_sg_pixelformat_info_t* pfi) {
  6856. pfi->sample = true;
  6857. pfi->filter = true;
  6858. }
  6859. _SOKOL_PRIVATE void _sg_pixelformat_sr(_sg_pixelformat_info_t* pfi) {
  6860. pfi->sample = true;
  6861. pfi->render = true;
  6862. }
  6863. _SOKOL_PRIVATE void _sg_pixelformat_sfr(_sg_pixelformat_info_t* pfi) {
  6864. pfi->sample = true;
  6865. pfi->filter = true;
  6866. pfi->render = true;
  6867. }
  6868. _SOKOL_PRIVATE void _sg_pixelformat_srmd(_sg_pixelformat_info_t* pfi) {
  6869. pfi->sample = true;
  6870. pfi->render = true;
  6871. pfi->msaa = true;
  6872. pfi->depth = true;
  6873. }
  6874. _SOKOL_PRIVATE void _sg_pixelformat_srm(_sg_pixelformat_info_t* pfi) {
  6875. pfi->sample = true;
  6876. pfi->render = true;
  6877. pfi->msaa = true;
  6878. }
  6879. _SOKOL_PRIVATE void _sg_pixelformat_sfrm(_sg_pixelformat_info_t* pfi) {
  6880. pfi->sample = true;
  6881. pfi->filter = true;
  6882. pfi->render = true;
  6883. pfi->msaa = true;
  6884. }
  6885. _SOKOL_PRIVATE void _sg_pixelformat_sbrm(_sg_pixelformat_info_t* pfi) {
  6886. pfi->sample = true;
  6887. pfi->blend = true;
  6888. pfi->render = true;
  6889. pfi->msaa = true;
  6890. }
  6891. _SOKOL_PRIVATE void _sg_pixelformat_sbr(_sg_pixelformat_info_t* pfi) {
  6892. pfi->sample = true;
  6893. pfi->blend = true;
  6894. pfi->render = true;
  6895. }
  6896. _SOKOL_PRIVATE void _sg_pixelformat_sfbr(_sg_pixelformat_info_t* pfi) {
  6897. pfi->sample = true;
  6898. pfi->filter = true;
  6899. pfi->blend = true;
  6900. pfi->render = true;
  6901. }
  6902. _SOKOL_PRIVATE void _sg_pixelformat_compute_all(_sg_pixelformat_info_t* pfi) {
  6903. pfi->read = true;
  6904. pfi->write = true;
  6905. }
  6906. _SOKOL_PRIVATE void _sg_pixelformat_compute_writeonly(_sg_pixelformat_info_t* pfi) {
  6907. pfi->read = false;
  6908. pfi->write = true;
  6909. }
  6910. _SOKOL_PRIVATE sg_pass_action _sg_pass_action_defaults(const sg_pass_action* action) {
  6911. SOKOL_ASSERT(action);
  6912. sg_pass_action res = *action;
  6913. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  6914. if (res.colors[i].load_action == _SG_LOADACTION_DEFAULT) {
  6915. res.colors[i].load_action = SG_LOADACTION_CLEAR;
  6916. res.colors[i].clear_value.r = SG_DEFAULT_CLEAR_RED;
  6917. res.colors[i].clear_value.g = SG_DEFAULT_CLEAR_GREEN;
  6918. res.colors[i].clear_value.b = SG_DEFAULT_CLEAR_BLUE;
  6919. res.colors[i].clear_value.a = SG_DEFAULT_CLEAR_ALPHA;
  6920. }
  6921. if (res.colors[i].store_action == _SG_STOREACTION_DEFAULT) {
  6922. res.colors[i].store_action = SG_STOREACTION_STORE;
  6923. }
  6924. }
  6925. if (res.depth.load_action == _SG_LOADACTION_DEFAULT) {
  6926. res.depth.load_action = SG_LOADACTION_CLEAR;
  6927. res.depth.clear_value = SG_DEFAULT_CLEAR_DEPTH;
  6928. }
  6929. if (res.depth.store_action == _SG_STOREACTION_DEFAULT) {
  6930. res.depth.store_action = SG_STOREACTION_DONTCARE;
  6931. }
  6932. if (res.stencil.load_action == _SG_LOADACTION_DEFAULT) {
  6933. res.stencil.load_action = SG_LOADACTION_CLEAR;
  6934. res.stencil.clear_value = SG_DEFAULT_CLEAR_STENCIL;
  6935. }
  6936. if (res.stencil.store_action == _SG_STOREACTION_DEFAULT) {
  6937. res.stencil.store_action = SG_STOREACTION_DONTCARE;
  6938. }
  6939. return res;
  6940. }
  6941. // ██████ ██ ██ ███ ███ ███ ███ ██ ██ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  6942. // ██ ██ ██ ██ ████ ████ ████ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  6943. // ██ ██ ██ ██ ██ ████ ██ ██ ████ ██ ████ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  6944. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  6945. // ██████ ██████ ██ ██ ██ ██ ██ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  6946. //
  6947. // >>dummy backend
  6948. #if defined(SOKOL_DUMMY_BACKEND)
  6949. _SOKOL_PRIVATE void _sg_dummy_setup_backend(const sg_desc* desc) {
  6950. SOKOL_ASSERT(desc);
  6951. _SOKOL_UNUSED(desc);
  6952. _sg.backend = SG_BACKEND_DUMMY;
  6953. for (int i = SG_PIXELFORMAT_R8; i < SG_PIXELFORMAT_BC1_RGBA; i++) {
  6954. _sg.formats[i].sample = true;
  6955. _sg.formats[i].filter = true;
  6956. _sg.formats[i].render = true;
  6957. _sg.formats[i].blend = true;
  6958. _sg.formats[i].msaa = true;
  6959. }
  6960. _sg.formats[SG_PIXELFORMAT_DEPTH].depth = true;
  6961. _sg.formats[SG_PIXELFORMAT_DEPTH_STENCIL].depth = true;
  6962. }
  6963. _SOKOL_PRIVATE void _sg_dummy_discard_backend(void) {
  6964. // empty
  6965. }
  6966. _SOKOL_PRIVATE void _sg_dummy_reset_state_cache(void) {
  6967. // empty
  6968. }
  6969. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  6970. SOKOL_ASSERT(buf && desc);
  6971. _SOKOL_UNUSED(buf);
  6972. _SOKOL_UNUSED(desc);
  6973. return SG_RESOURCESTATE_VALID;
  6974. }
  6975. _SOKOL_PRIVATE void _sg_dummy_discard_buffer(_sg_buffer_t* buf) {
  6976. SOKOL_ASSERT(buf);
  6977. _SOKOL_UNUSED(buf);
  6978. }
  6979. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  6980. SOKOL_ASSERT(img && desc);
  6981. _SOKOL_UNUSED(img);
  6982. _SOKOL_UNUSED(desc);
  6983. return SG_RESOURCESTATE_VALID;
  6984. }
  6985. _SOKOL_PRIVATE void _sg_dummy_discard_image(_sg_image_t* img) {
  6986. SOKOL_ASSERT(img);
  6987. _SOKOL_UNUSED(img);
  6988. }
  6989. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  6990. SOKOL_ASSERT(smp && desc);
  6991. _SOKOL_UNUSED(smp);
  6992. _SOKOL_UNUSED(desc);
  6993. return SG_RESOURCESTATE_VALID;
  6994. }
  6995. _SOKOL_PRIVATE void _sg_dummy_discard_sampler(_sg_sampler_t* smp) {
  6996. SOKOL_ASSERT(smp);
  6997. _SOKOL_UNUSED(smp);
  6998. }
  6999. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  7000. SOKOL_ASSERT(shd && desc);
  7001. _SOKOL_UNUSED(shd);
  7002. _SOKOL_UNUSED(desc);
  7003. return SG_RESOURCESTATE_VALID;
  7004. }
  7005. _SOKOL_PRIVATE void _sg_dummy_discard_shader(_sg_shader_t* shd) {
  7006. SOKOL_ASSERT(shd);
  7007. _SOKOL_UNUSED(shd);
  7008. }
  7009. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_pipeline(_sg_pipeline_t* pip, const sg_pipeline_desc* desc) {
  7010. SOKOL_ASSERT(pip && desc);
  7011. _SOKOL_UNUSED(pip);
  7012. _SOKOL_UNUSED(desc);
  7013. return SG_RESOURCESTATE_VALID;
  7014. }
  7015. _SOKOL_PRIVATE void _sg_dummy_discard_pipeline(_sg_pipeline_t* pip) {
  7016. SOKOL_ASSERT(pip);
  7017. _SOKOL_UNUSED(pip);
  7018. }
  7019. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_attachments(_sg_attachments_t* atts, const sg_attachments_desc* desc) {
  7020. SOKOL_ASSERT(atts && desc);
  7021. _SOKOL_UNUSED(atts);
  7022. _SOKOL_UNUSED(desc);
  7023. return SG_RESOURCESTATE_VALID;
  7024. }
  7025. _SOKOL_PRIVATE void _sg_dummy_discard_attachments(_sg_attachments_t* atts) {
  7026. SOKOL_ASSERT(atts);
  7027. _SOKOL_UNUSED(atts);
  7028. }
  7029. _SOKOL_PRIVATE void _sg_dummy_begin_pass(const sg_pass* pass) {
  7030. SOKOL_ASSERT(pass);
  7031. _SOKOL_UNUSED(pass);
  7032. }
  7033. _SOKOL_PRIVATE void _sg_dummy_end_pass(void) {
  7034. // empty
  7035. }
  7036. _SOKOL_PRIVATE void _sg_dummy_commit(void) {
  7037. // empty
  7038. }
  7039. _SOKOL_PRIVATE void _sg_dummy_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  7040. _SOKOL_UNUSED(x);
  7041. _SOKOL_UNUSED(y);
  7042. _SOKOL_UNUSED(w);
  7043. _SOKOL_UNUSED(h);
  7044. _SOKOL_UNUSED(origin_top_left);
  7045. }
  7046. _SOKOL_PRIVATE void _sg_dummy_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  7047. _SOKOL_UNUSED(x);
  7048. _SOKOL_UNUSED(y);
  7049. _SOKOL_UNUSED(w);
  7050. _SOKOL_UNUSED(h);
  7051. _SOKOL_UNUSED(origin_top_left);
  7052. }
  7053. _SOKOL_PRIVATE void _sg_dummy_apply_pipeline(_sg_pipeline_t* pip) {
  7054. SOKOL_ASSERT(pip);
  7055. _SOKOL_UNUSED(pip);
  7056. }
  7057. _SOKOL_PRIVATE bool _sg_dummy_apply_bindings(_sg_bindings_ptrs_t* bnd) {
  7058. SOKOL_ASSERT(bnd);
  7059. SOKOL_ASSERT(bnd->pip);
  7060. _SOKOL_UNUSED(bnd);
  7061. return true;
  7062. }
  7063. _SOKOL_PRIVATE void _sg_dummy_apply_uniforms(int ub_slot, const sg_range* data) {
  7064. _SOKOL_UNUSED(ub_slot);
  7065. _SOKOL_UNUSED(data);
  7066. }
  7067. _SOKOL_PRIVATE void _sg_dummy_draw(int base_element, int num_elements, int num_instances) {
  7068. _SOKOL_UNUSED(base_element);
  7069. _SOKOL_UNUSED(num_elements);
  7070. _SOKOL_UNUSED(num_instances);
  7071. }
  7072. _SOKOL_PRIVATE void _sg_dummy_dispatch(int num_groups_x, int num_groups_y, int num_groups_z) {
  7073. _SOKOL_UNUSED(num_groups_x);
  7074. _SOKOL_UNUSED(num_groups_y);
  7075. _SOKOL_UNUSED(num_groups_z);
  7076. }
  7077. _SOKOL_PRIVATE void _sg_dummy_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  7078. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  7079. _SOKOL_UNUSED(data);
  7080. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  7081. buf->cmn.active_slot = 0;
  7082. }
  7083. }
  7084. _SOKOL_PRIVATE bool _sg_dummy_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  7085. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  7086. _SOKOL_UNUSED(data);
  7087. if (new_frame) {
  7088. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  7089. buf->cmn.active_slot = 0;
  7090. }
  7091. }
  7092. return true;
  7093. }
  7094. _SOKOL_PRIVATE void _sg_dummy_update_image(_sg_image_t* img, const sg_image_data* data) {
  7095. SOKOL_ASSERT(img && data);
  7096. _SOKOL_UNUSED(data);
  7097. if (++img->cmn.active_slot >= img->cmn.num_slots) {
  7098. img->cmn.active_slot = 0;
  7099. }
  7100. }
  7101. // ██████ ██████ ███████ ███ ██ ██████ ██ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  7102. // ██ ██ ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  7103. // ██ ██ ██████ █████ ██ ██ ██ ██ ███ ██ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  7104. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  7105. // ██████ ██ ███████ ██ ████ ██████ ███████ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  7106. //
  7107. // >>opengl backend
  7108. #elif defined(_SOKOL_ANY_GL)
  7109. // optional GL loader for win32
  7110. #if defined(_SOKOL_USE_WIN32_GL_LOADER)
  7111. #ifndef SG_GL_FUNCS_EXT
  7112. #define SG_GL_FUNCS_EXT
  7113. #endif
  7114. // X Macro list of GL function names and signatures
  7115. #define _SG_GL_FUNCS \
  7116. SG_GL_FUNCS_EXT \
  7117. _SG_XMACRO(glBindVertexArray, void, (GLuint array)) \
  7118. _SG_XMACRO(glFramebufferTextureLayer, void, (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer)) \
  7119. _SG_XMACRO(glGenFramebuffers, void, (GLsizei n, GLuint * framebuffers)) \
  7120. _SG_XMACRO(glBindFramebuffer, void, (GLenum target, GLuint framebuffer)) \
  7121. _SG_XMACRO(glBindRenderbuffer, void, (GLenum target, GLuint renderbuffer)) \
  7122. _SG_XMACRO(glGetStringi, const GLubyte *, (GLenum name, GLuint index)) \
  7123. _SG_XMACRO(glClearBufferfi, void, (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil)) \
  7124. _SG_XMACRO(glClearBufferfv, void, (GLenum buffer, GLint drawbuffer, const GLfloat * value)) \
  7125. _SG_XMACRO(glClearBufferuiv, void, (GLenum buffer, GLint drawbuffer, const GLuint * value)) \
  7126. _SG_XMACRO(glClearBufferiv, void, (GLenum buffer, GLint drawbuffer, const GLint * value)) \
  7127. _SG_XMACRO(glDeleteRenderbuffers, void, (GLsizei n, const GLuint * renderbuffers)) \
  7128. _SG_XMACRO(glUniform1fv, void, (GLint location, GLsizei count, const GLfloat * value)) \
  7129. _SG_XMACRO(glUniform2fv, void, (GLint location, GLsizei count, const GLfloat * value)) \
  7130. _SG_XMACRO(glUniform3fv, void, (GLint location, GLsizei count, const GLfloat * value)) \
  7131. _SG_XMACRO(glUniform4fv, void, (GLint location, GLsizei count, const GLfloat * value)) \
  7132. _SG_XMACRO(glUniform1iv, void, (GLint location, GLsizei count, const GLint * value)) \
  7133. _SG_XMACRO(glUniform2iv, void, (GLint location, GLsizei count, const GLint * value)) \
  7134. _SG_XMACRO(glUniform3iv, void, (GLint location, GLsizei count, const GLint * value)) \
  7135. _SG_XMACRO(glUniform4iv, void, (GLint location, GLsizei count, const GLint * value)) \
  7136. _SG_XMACRO(glUniformMatrix4fv, void, (GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)) \
  7137. _SG_XMACRO(glUseProgram, void, (GLuint program)) \
  7138. _SG_XMACRO(glShaderSource, void, (GLuint shader, GLsizei count, const GLchar *const* string, const GLint * length)) \
  7139. _SG_XMACRO(glLinkProgram, void, (GLuint program)) \
  7140. _SG_XMACRO(glGetUniformLocation, GLint, (GLuint program, const GLchar * name)) \
  7141. _SG_XMACRO(glGetShaderiv, void, (GLuint shader, GLenum pname, GLint * params)) \
  7142. _SG_XMACRO(glGetProgramInfoLog, void, (GLuint program, GLsizei bufSize, GLsizei * length, GLchar * infoLog)) \
  7143. _SG_XMACRO(glGetAttribLocation, GLint, (GLuint program, const GLchar * name)) \
  7144. _SG_XMACRO(glDisableVertexAttribArray, void, (GLuint index)) \
  7145. _SG_XMACRO(glDeleteShader, void, (GLuint shader)) \
  7146. _SG_XMACRO(glDeleteProgram, void, (GLuint program)) \
  7147. _SG_XMACRO(glCompileShader, void, (GLuint shader)) \
  7148. _SG_XMACRO(glStencilFuncSeparate, void, (GLenum face, GLenum func, GLint ref, GLuint mask)) \
  7149. _SG_XMACRO(glStencilOpSeparate, void, (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass)) \
  7150. _SG_XMACRO(glRenderbufferStorageMultisample, void, (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height)) \
  7151. _SG_XMACRO(glDrawBuffers, void, (GLsizei n, const GLenum * bufs)) \
  7152. _SG_XMACRO(glVertexAttribDivisor, void, (GLuint index, GLuint divisor)) \
  7153. _SG_XMACRO(glBufferSubData, void, (GLenum target, GLintptr offset, GLsizeiptr size, const void * data)) \
  7154. _SG_XMACRO(glGenBuffers, void, (GLsizei n, GLuint * buffers)) \
  7155. _SG_XMACRO(glCheckFramebufferStatus, GLenum, (GLenum target)) \
  7156. _SG_XMACRO(glFramebufferRenderbuffer, void, (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)) \
  7157. _SG_XMACRO(glCompressedTexImage2D, void, (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void * data)) \
  7158. _SG_XMACRO(glCompressedTexImage3D, void, (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void * data)) \
  7159. _SG_XMACRO(glActiveTexture, void, (GLenum texture)) \
  7160. _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)) \
  7161. _SG_XMACRO(glRenderbufferStorage, void, (GLenum target, GLenum internalformat, GLsizei width, GLsizei height)) \
  7162. _SG_XMACRO(glGenTextures, void, (GLsizei n, GLuint * textures)) \
  7163. _SG_XMACRO(glPolygonOffset, void, (GLfloat factor, GLfloat units)) \
  7164. _SG_XMACRO(glDrawElements, void, (GLenum mode, GLsizei count, GLenum type, const void * indices)) \
  7165. _SG_XMACRO(glDeleteFramebuffers, void, (GLsizei n, const GLuint * framebuffers)) \
  7166. _SG_XMACRO(glBlendEquationSeparate, void, (GLenum modeRGB, GLenum modeAlpha)) \
  7167. _SG_XMACRO(glDeleteTextures, void, (GLsizei n, const GLuint * textures)) \
  7168. _SG_XMACRO(glGetProgramiv, void, (GLuint program, GLenum pname, GLint * params)) \
  7169. _SG_XMACRO(glBindTexture, void, (GLenum target, GLuint texture)) \
  7170. _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)) \
  7171. _SG_XMACRO(glCreateShader, GLuint, (GLenum type)) \
  7172. _SG_XMACRO(glTexSubImage2D, void, (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void * pixels)) \
  7173. _SG_XMACRO(glFramebufferTexture2D, void, (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)) \
  7174. _SG_XMACRO(glCreateProgram, GLuint, (void)) \
  7175. _SG_XMACRO(glViewport, void, (GLint x, GLint y, GLsizei width, GLsizei height)) \
  7176. _SG_XMACRO(glDeleteBuffers, void, (GLsizei n, const GLuint * buffers)) \
  7177. _SG_XMACRO(glDrawArrays, void, (GLenum mode, GLint first, GLsizei count)) \
  7178. _SG_XMACRO(glDrawElementsInstanced, void, (GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount)) \
  7179. _SG_XMACRO(glVertexAttribPointer, void, (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void * pointer)) \
  7180. _SG_XMACRO(glVertexAttribIPointer, void, (GLuint index, GLint size, GLenum type, GLsizei stride, const void * pointer)) \
  7181. _SG_XMACRO(glUniform1i, void, (GLint location, GLint v0)) \
  7182. _SG_XMACRO(glDisable, void, (GLenum cap)) \
  7183. _SG_XMACRO(glColorMask, void, (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)) \
  7184. _SG_XMACRO(glColorMaski, void, (GLuint buf, GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)) \
  7185. _SG_XMACRO(glBindBuffer, void, (GLenum target, GLuint buffer)) \
  7186. _SG_XMACRO(glDeleteVertexArrays, void, (GLsizei n, const GLuint * arrays)) \
  7187. _SG_XMACRO(glDepthMask, void, (GLboolean flag)) \
  7188. _SG_XMACRO(glDrawArraysInstanced, void, (GLenum mode, GLint first, GLsizei count, GLsizei instancecount)) \
  7189. _SG_XMACRO(glScissor, void, (GLint x, GLint y, GLsizei width, GLsizei height)) \
  7190. _SG_XMACRO(glGenRenderbuffers, void, (GLsizei n, GLuint * renderbuffers)) \
  7191. _SG_XMACRO(glBufferData, void, (GLenum target, GLsizeiptr size, const void * data, GLenum usage)) \
  7192. _SG_XMACRO(glBlendFuncSeparate, void, (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha)) \
  7193. _SG_XMACRO(glTexParameteri, void, (GLenum target, GLenum pname, GLint param)) \
  7194. _SG_XMACRO(glGetIntegerv, void, (GLenum pname, GLint * data)) \
  7195. _SG_XMACRO(glEnable, void, (GLenum cap)) \
  7196. _SG_XMACRO(glBlitFramebuffer, void, (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter)) \
  7197. _SG_XMACRO(glStencilMask, void, (GLuint mask)) \
  7198. _SG_XMACRO(glAttachShader, void, (GLuint program, GLuint shader)) \
  7199. _SG_XMACRO(glGetError, GLenum, (void)) \
  7200. _SG_XMACRO(glBlendColor, void, (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)) \
  7201. _SG_XMACRO(glTexParameterf, void, (GLenum target, GLenum pname, GLfloat param)) \
  7202. _SG_XMACRO(glTexParameterfv, void, (GLenum target, GLenum pname, const GLfloat* params)) \
  7203. _SG_XMACRO(glGetShaderInfoLog, void, (GLuint shader, GLsizei bufSize, GLsizei * length, GLchar * infoLog)) \
  7204. _SG_XMACRO(glDepthFunc, void, (GLenum func)) \
  7205. _SG_XMACRO(glStencilOp , void, (GLenum fail, GLenum zfail, GLenum zpass)) \
  7206. _SG_XMACRO(glStencilFunc, void, (GLenum func, GLint ref, GLuint mask)) \
  7207. _SG_XMACRO(glEnableVertexAttribArray, void, (GLuint index)) \
  7208. _SG_XMACRO(glBlendFunc, void, (GLenum sfactor, GLenum dfactor)) \
  7209. _SG_XMACRO(glReadBuffer, void, (GLenum src)) \
  7210. _SG_XMACRO(glTexImage2D, void, (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void * pixels)) \
  7211. _SG_XMACRO(glGenVertexArrays, void, (GLsizei n, GLuint * arrays)) \
  7212. _SG_XMACRO(glFrontFace, void, (GLenum mode)) \
  7213. _SG_XMACRO(glCullFace, void, (GLenum mode)) \
  7214. _SG_XMACRO(glPixelStorei, void, (GLenum pname, GLint param)) \
  7215. _SG_XMACRO(glBindSampler, void, (GLuint unit, GLuint sampler)) \
  7216. _SG_XMACRO(glGenSamplers, void, (GLsizei n, GLuint* samplers)) \
  7217. _SG_XMACRO(glSamplerParameteri, void, (GLuint sampler, GLenum pname, GLint param)) \
  7218. _SG_XMACRO(glSamplerParameterf, void, (GLuint sampler, GLenum pname, GLfloat param)) \
  7219. _SG_XMACRO(glSamplerParameterfv, void, (GLuint sampler, GLenum pname, const GLfloat* params)) \
  7220. _SG_XMACRO(glDeleteSamplers, void, (GLsizei n, const GLuint* samplers)) \
  7221. _SG_XMACRO(glBindBufferBase, void, (GLenum target, GLuint index, GLuint buffer)) \
  7222. _SG_XMACRO(glTexImage2DMultisample, void, (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations)) \
  7223. _SG_XMACRO(glTexImage3DMultisample, void, (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations)) \
  7224. _SG_XMACRO(glDispatchCompute, void, (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z)) \
  7225. _SG_XMACRO(glMemoryBarrier, void, (GLbitfield barriers)) \
  7226. _SG_XMACRO(glBindImageTexture, void, (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format)) \
  7227. _SG_XMACRO(glTexStorage2DMultisample, void, (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations)) \
  7228. _SG_XMACRO(glTexStorage2D, void, (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height)) \
  7229. _SG_XMACRO(glTexStorage3DMultisample, void, (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations)) \
  7230. _SG_XMACRO(glTexStorage3D, void, (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth)) \
  7231. _SG_XMACRO(glCompressedTexSubImage2D, void, (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data)) \
  7232. _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))
  7233. // generate GL function pointer typedefs
  7234. #define _SG_XMACRO(name, ret, args) typedef ret (GL_APIENTRY* PFN_ ## name) args;
  7235. _SG_GL_FUNCS
  7236. #undef _SG_XMACRO
  7237. // generate GL function pointers
  7238. #define _SG_XMACRO(name, ret, args) static PFN_ ## name name;
  7239. _SG_GL_FUNCS
  7240. #undef _SG_XMACRO
  7241. // helper function to lookup GL functions in GL DLL
  7242. typedef PROC (WINAPI * _sg_wglGetProcAddress)(LPCSTR);
  7243. _SOKOL_PRIVATE void* _sg_gl_getprocaddr(const char* name, _sg_wglGetProcAddress wgl_getprocaddress) {
  7244. void* proc_addr = (void*) wgl_getprocaddress(name);
  7245. if (0 == proc_addr) {
  7246. proc_addr = (void*) GetProcAddress(_sg.gl.opengl32_dll, name);
  7247. }
  7248. SOKOL_ASSERT(proc_addr);
  7249. return proc_addr;
  7250. }
  7251. // populate GL function pointers
  7252. _SOKOL_PRIVATE void _sg_gl_load_opengl(void) {
  7253. SOKOL_ASSERT(0 == _sg.gl.opengl32_dll);
  7254. _sg.gl.opengl32_dll = LoadLibraryA("opengl32.dll");
  7255. SOKOL_ASSERT(_sg.gl.opengl32_dll);
  7256. _sg_wglGetProcAddress wgl_getprocaddress = (_sg_wglGetProcAddress) GetProcAddress(_sg.gl.opengl32_dll, "wglGetProcAddress");
  7257. SOKOL_ASSERT(wgl_getprocaddress);
  7258. #define _SG_XMACRO(name, ret, args) name = (PFN_ ## name) _sg_gl_getprocaddr(#name, wgl_getprocaddress);
  7259. _SG_GL_FUNCS
  7260. #undef _SG_XMACRO
  7261. }
  7262. _SOKOL_PRIVATE void _sg_gl_unload_opengl(void) {
  7263. SOKOL_ASSERT(_sg.gl.opengl32_dll);
  7264. FreeLibrary(_sg.gl.opengl32_dll);
  7265. _sg.gl.opengl32_dll = 0;
  7266. }
  7267. #endif // _SOKOL_USE_WIN32_GL_LOADER
  7268. //-- type translation ----------------------------------------------------------
  7269. _SOKOL_PRIVATE GLenum _sg_gl_buffer_target(const sg_buffer_usage* usg) {
  7270. // NOTE: the buffer target returned here is only used for the bind point
  7271. // to copy data into the buffer, expect for WebGL2, the bind point doesn't
  7272. // need to match the later usage of the buffer (but because of the WebGL2
  7273. // restriction we cannot simply select a random bind point, because in WebGL2
  7274. // a buffer cannot 'switch' bind points later.
  7275. if (usg->vertex_buffer) {
  7276. return GL_ARRAY_BUFFER;
  7277. } else if (usg->index_buffer) {
  7278. return GL_ELEMENT_ARRAY_BUFFER;
  7279. } else if (usg->storage_buffer) {
  7280. return GL_SHADER_STORAGE_BUFFER;
  7281. } else {
  7282. SOKOL_UNREACHABLE; return 0;
  7283. }
  7284. }
  7285. _SOKOL_PRIVATE GLenum _sg_gl_texture_target(sg_image_type t, int sample_count) {
  7286. #if defined(SOKOL_GLCORE)
  7287. const bool msaa = sample_count > 1;
  7288. if (msaa) {
  7289. switch (t) {
  7290. case SG_IMAGETYPE_2D: return GL_TEXTURE_2D_MULTISAMPLE;
  7291. case SG_IMAGETYPE_ARRAY: return GL_TEXTURE_2D_MULTISAMPLE_ARRAY;
  7292. default: SOKOL_UNREACHABLE; return 0;
  7293. }
  7294. } else {
  7295. switch (t) {
  7296. case SG_IMAGETYPE_2D: return GL_TEXTURE_2D;
  7297. case SG_IMAGETYPE_CUBE: return GL_TEXTURE_CUBE_MAP;
  7298. case SG_IMAGETYPE_3D: return GL_TEXTURE_3D;
  7299. case SG_IMAGETYPE_ARRAY: return GL_TEXTURE_2D_ARRAY;
  7300. default: SOKOL_UNREACHABLE; return 0;
  7301. }
  7302. }
  7303. #else
  7304. SOKOL_ASSERT(sample_count == 1); _SOKOL_UNUSED(sample_count);
  7305. switch (t) {
  7306. case SG_IMAGETYPE_2D: return GL_TEXTURE_2D;
  7307. case SG_IMAGETYPE_CUBE: return GL_TEXTURE_CUBE_MAP;
  7308. case SG_IMAGETYPE_3D: return GL_TEXTURE_3D;
  7309. case SG_IMAGETYPE_ARRAY: return GL_TEXTURE_2D_ARRAY;
  7310. default: SOKOL_UNREACHABLE; return 0;
  7311. }
  7312. #endif
  7313. }
  7314. _SOKOL_PRIVATE GLenum _sg_gl_buffer_usage(const sg_buffer_usage* usg) {
  7315. if (usg->immutable) {
  7316. return GL_STATIC_DRAW;
  7317. } else if (usg->dynamic_update) {
  7318. return GL_DYNAMIC_DRAW;
  7319. } else if (usg->stream_update) {
  7320. return GL_STREAM_DRAW;
  7321. } else {
  7322. SOKOL_UNREACHABLE; return 0;
  7323. }
  7324. }
  7325. _SOKOL_PRIVATE GLenum _sg_gl_shader_stage(sg_shader_stage stage) {
  7326. switch (stage) {
  7327. case SG_SHADERSTAGE_VERTEX: return GL_VERTEX_SHADER;
  7328. case SG_SHADERSTAGE_FRAGMENT: return GL_FRAGMENT_SHADER;
  7329. case SG_SHADERSTAGE_COMPUTE: return GL_COMPUTE_SHADER;
  7330. default: SOKOL_UNREACHABLE; return 0;
  7331. }
  7332. }
  7333. _SOKOL_PRIVATE GLint _sg_gl_vertexformat_size(sg_vertex_format fmt) {
  7334. switch (fmt) {
  7335. case SG_VERTEXFORMAT_FLOAT: return 1;
  7336. case SG_VERTEXFORMAT_FLOAT2: return 2;
  7337. case SG_VERTEXFORMAT_FLOAT3: return 3;
  7338. case SG_VERTEXFORMAT_FLOAT4: return 4;
  7339. case SG_VERTEXFORMAT_INT: return 1;
  7340. case SG_VERTEXFORMAT_INT2: return 2;
  7341. case SG_VERTEXFORMAT_INT3: return 3;
  7342. case SG_VERTEXFORMAT_INT4: return 4;
  7343. case SG_VERTEXFORMAT_UINT: return 1;
  7344. case SG_VERTEXFORMAT_UINT2: return 2;
  7345. case SG_VERTEXFORMAT_UINT3: return 3;
  7346. case SG_VERTEXFORMAT_UINT4: return 4;
  7347. case SG_VERTEXFORMAT_BYTE4: return 4;
  7348. case SG_VERTEXFORMAT_BYTE4N: return 4;
  7349. case SG_VERTEXFORMAT_UBYTE4: return 4;
  7350. case SG_VERTEXFORMAT_UBYTE4N: return 4;
  7351. case SG_VERTEXFORMAT_SHORT2: return 2;
  7352. case SG_VERTEXFORMAT_SHORT2N: return 2;
  7353. case SG_VERTEXFORMAT_USHORT2: return 2;
  7354. case SG_VERTEXFORMAT_USHORT2N: return 2;
  7355. case SG_VERTEXFORMAT_SHORT4: return 4;
  7356. case SG_VERTEXFORMAT_SHORT4N: return 4;
  7357. case SG_VERTEXFORMAT_USHORT4: return 4;
  7358. case SG_VERTEXFORMAT_USHORT4N: return 4;
  7359. case SG_VERTEXFORMAT_UINT10_N2: return 4;
  7360. case SG_VERTEXFORMAT_HALF2: return 2;
  7361. case SG_VERTEXFORMAT_HALF4: return 4;
  7362. default: SOKOL_UNREACHABLE; return 0;
  7363. }
  7364. }
  7365. _SOKOL_PRIVATE GLenum _sg_gl_vertexformat_type(sg_vertex_format fmt) {
  7366. switch (fmt) {
  7367. case SG_VERTEXFORMAT_FLOAT:
  7368. case SG_VERTEXFORMAT_FLOAT2:
  7369. case SG_VERTEXFORMAT_FLOAT3:
  7370. case SG_VERTEXFORMAT_FLOAT4:
  7371. return GL_FLOAT;
  7372. case SG_VERTEXFORMAT_INT:
  7373. case SG_VERTEXFORMAT_INT2:
  7374. case SG_VERTEXFORMAT_INT3:
  7375. case SG_VERTEXFORMAT_INT4:
  7376. return GL_INT;
  7377. case SG_VERTEXFORMAT_UINT:
  7378. case SG_VERTEXFORMAT_UINT2:
  7379. case SG_VERTEXFORMAT_UINT3:
  7380. case SG_VERTEXFORMAT_UINT4:
  7381. return GL_UNSIGNED_INT;
  7382. case SG_VERTEXFORMAT_BYTE4:
  7383. case SG_VERTEXFORMAT_BYTE4N:
  7384. return GL_BYTE;
  7385. case SG_VERTEXFORMAT_UBYTE4:
  7386. case SG_VERTEXFORMAT_UBYTE4N:
  7387. return GL_UNSIGNED_BYTE;
  7388. case SG_VERTEXFORMAT_SHORT2:
  7389. case SG_VERTEXFORMAT_SHORT2N:
  7390. case SG_VERTEXFORMAT_SHORT4:
  7391. case SG_VERTEXFORMAT_SHORT4N:
  7392. return GL_SHORT;
  7393. case SG_VERTEXFORMAT_USHORT2:
  7394. case SG_VERTEXFORMAT_USHORT2N:
  7395. case SG_VERTEXFORMAT_USHORT4:
  7396. case SG_VERTEXFORMAT_USHORT4N:
  7397. return GL_UNSIGNED_SHORT;
  7398. case SG_VERTEXFORMAT_UINT10_N2:
  7399. return GL_UNSIGNED_INT_2_10_10_10_REV;
  7400. case SG_VERTEXFORMAT_HALF2:
  7401. case SG_VERTEXFORMAT_HALF4:
  7402. return GL_HALF_FLOAT;
  7403. default:
  7404. SOKOL_UNREACHABLE; return 0;
  7405. }
  7406. }
  7407. _SOKOL_PRIVATE GLboolean _sg_gl_vertexformat_normalized(sg_vertex_format fmt) {
  7408. switch (fmt) {
  7409. case SG_VERTEXFORMAT_BYTE4N:
  7410. case SG_VERTEXFORMAT_UBYTE4N:
  7411. case SG_VERTEXFORMAT_SHORT2N:
  7412. case SG_VERTEXFORMAT_USHORT2N:
  7413. case SG_VERTEXFORMAT_SHORT4N:
  7414. case SG_VERTEXFORMAT_USHORT4N:
  7415. case SG_VERTEXFORMAT_UINT10_N2:
  7416. return GL_TRUE;
  7417. default:
  7418. return GL_FALSE;
  7419. }
  7420. }
  7421. _SOKOL_PRIVATE GLenum _sg_gl_primitive_type(sg_primitive_type t) {
  7422. switch (t) {
  7423. case SG_PRIMITIVETYPE_POINTS: return GL_POINTS;
  7424. case SG_PRIMITIVETYPE_LINES: return GL_LINES;
  7425. case SG_PRIMITIVETYPE_LINE_STRIP: return GL_LINE_STRIP;
  7426. case SG_PRIMITIVETYPE_TRIANGLES: return GL_TRIANGLES;
  7427. case SG_PRIMITIVETYPE_TRIANGLE_STRIP: return GL_TRIANGLE_STRIP;
  7428. default: SOKOL_UNREACHABLE; return 0;
  7429. }
  7430. }
  7431. _SOKOL_PRIVATE GLenum _sg_gl_index_type(sg_index_type t) {
  7432. switch (t) {
  7433. case SG_INDEXTYPE_NONE: return 0;
  7434. case SG_INDEXTYPE_UINT16: return GL_UNSIGNED_SHORT;
  7435. case SG_INDEXTYPE_UINT32: return GL_UNSIGNED_INT;
  7436. default: SOKOL_UNREACHABLE; return 0;
  7437. }
  7438. }
  7439. _SOKOL_PRIVATE GLenum _sg_gl_compare_func(sg_compare_func cmp) {
  7440. switch (cmp) {
  7441. case SG_COMPAREFUNC_NEVER: return GL_NEVER;
  7442. case SG_COMPAREFUNC_LESS: return GL_LESS;
  7443. case SG_COMPAREFUNC_EQUAL: return GL_EQUAL;
  7444. case SG_COMPAREFUNC_LESS_EQUAL: return GL_LEQUAL;
  7445. case SG_COMPAREFUNC_GREATER: return GL_GREATER;
  7446. case SG_COMPAREFUNC_NOT_EQUAL: return GL_NOTEQUAL;
  7447. case SG_COMPAREFUNC_GREATER_EQUAL: return GL_GEQUAL;
  7448. case SG_COMPAREFUNC_ALWAYS: return GL_ALWAYS;
  7449. default: SOKOL_UNREACHABLE; return 0;
  7450. }
  7451. }
  7452. _SOKOL_PRIVATE GLenum _sg_gl_stencil_op(sg_stencil_op op) {
  7453. switch (op) {
  7454. case SG_STENCILOP_KEEP: return GL_KEEP;
  7455. case SG_STENCILOP_ZERO: return GL_ZERO;
  7456. case SG_STENCILOP_REPLACE: return GL_REPLACE;
  7457. case SG_STENCILOP_INCR_CLAMP: return GL_INCR;
  7458. case SG_STENCILOP_DECR_CLAMP: return GL_DECR;
  7459. case SG_STENCILOP_INVERT: return GL_INVERT;
  7460. case SG_STENCILOP_INCR_WRAP: return GL_INCR_WRAP;
  7461. case SG_STENCILOP_DECR_WRAP: return GL_DECR_WRAP;
  7462. default: SOKOL_UNREACHABLE; return 0;
  7463. }
  7464. }
  7465. _SOKOL_PRIVATE GLenum _sg_gl_blend_factor(sg_blend_factor f) {
  7466. switch (f) {
  7467. case SG_BLENDFACTOR_ZERO: return GL_ZERO;
  7468. case SG_BLENDFACTOR_ONE: return GL_ONE;
  7469. case SG_BLENDFACTOR_SRC_COLOR: return GL_SRC_COLOR;
  7470. case SG_BLENDFACTOR_ONE_MINUS_SRC_COLOR: return GL_ONE_MINUS_SRC_COLOR;
  7471. case SG_BLENDFACTOR_SRC_ALPHA: return GL_SRC_ALPHA;
  7472. case SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA: return GL_ONE_MINUS_SRC_ALPHA;
  7473. case SG_BLENDFACTOR_DST_COLOR: return GL_DST_COLOR;
  7474. case SG_BLENDFACTOR_ONE_MINUS_DST_COLOR: return GL_ONE_MINUS_DST_COLOR;
  7475. case SG_BLENDFACTOR_DST_ALPHA: return GL_DST_ALPHA;
  7476. case SG_BLENDFACTOR_ONE_MINUS_DST_ALPHA: return GL_ONE_MINUS_DST_ALPHA;
  7477. case SG_BLENDFACTOR_SRC_ALPHA_SATURATED: return GL_SRC_ALPHA_SATURATE;
  7478. case SG_BLENDFACTOR_BLEND_COLOR: return GL_CONSTANT_COLOR;
  7479. case SG_BLENDFACTOR_ONE_MINUS_BLEND_COLOR: return GL_ONE_MINUS_CONSTANT_COLOR;
  7480. case SG_BLENDFACTOR_BLEND_ALPHA: return GL_CONSTANT_ALPHA;
  7481. case SG_BLENDFACTOR_ONE_MINUS_BLEND_ALPHA: return GL_ONE_MINUS_CONSTANT_ALPHA;
  7482. default: SOKOL_UNREACHABLE; return 0;
  7483. }
  7484. }
  7485. _SOKOL_PRIVATE GLenum _sg_gl_blend_op(sg_blend_op op) {
  7486. switch (op) {
  7487. case SG_BLENDOP_ADD: return GL_FUNC_ADD;
  7488. case SG_BLENDOP_SUBTRACT: return GL_FUNC_SUBTRACT;
  7489. case SG_BLENDOP_REVERSE_SUBTRACT: return GL_FUNC_REVERSE_SUBTRACT;
  7490. case SG_BLENDOP_MIN: return GL_MIN;
  7491. case SG_BLENDOP_MAX: return GL_MAX;
  7492. default: SOKOL_UNREACHABLE; return 0;
  7493. }
  7494. }
  7495. _SOKOL_PRIVATE GLenum _sg_gl_min_filter(sg_filter min_f, sg_filter mipmap_f) {
  7496. if (min_f == SG_FILTER_NEAREST) {
  7497. switch (mipmap_f) {
  7498. case SG_FILTER_NEAREST: return GL_NEAREST_MIPMAP_NEAREST;
  7499. case SG_FILTER_LINEAR: return GL_NEAREST_MIPMAP_LINEAR;
  7500. default: SOKOL_UNREACHABLE; return (GLenum)0;
  7501. }
  7502. } else if (min_f == SG_FILTER_LINEAR) {
  7503. switch (mipmap_f) {
  7504. case SG_FILTER_NEAREST: return GL_LINEAR_MIPMAP_NEAREST;
  7505. case SG_FILTER_LINEAR: return GL_LINEAR_MIPMAP_LINEAR;
  7506. default: SOKOL_UNREACHABLE; return (GLenum)0;
  7507. }
  7508. } else {
  7509. SOKOL_UNREACHABLE; return (GLenum)0;
  7510. }
  7511. }
  7512. _SOKOL_PRIVATE GLenum _sg_gl_mag_filter(sg_filter mag_f) {
  7513. if (mag_f == SG_FILTER_NEAREST) {
  7514. return GL_NEAREST;
  7515. } else {
  7516. return GL_LINEAR;
  7517. }
  7518. }
  7519. _SOKOL_PRIVATE GLenum _sg_gl_wrap(sg_wrap w) {
  7520. switch (w) {
  7521. case SG_WRAP_CLAMP_TO_EDGE: return GL_CLAMP_TO_EDGE;
  7522. #if defined(SOKOL_GLCORE)
  7523. case SG_WRAP_CLAMP_TO_BORDER: return GL_CLAMP_TO_BORDER;
  7524. #else
  7525. case SG_WRAP_CLAMP_TO_BORDER: return GL_CLAMP_TO_EDGE;
  7526. #endif
  7527. case SG_WRAP_REPEAT: return GL_REPEAT;
  7528. case SG_WRAP_MIRRORED_REPEAT: return GL_MIRRORED_REPEAT;
  7529. default: SOKOL_UNREACHABLE; return 0;
  7530. }
  7531. }
  7532. _SOKOL_PRIVATE GLenum _sg_gl_teximage_type(sg_pixel_format fmt) {
  7533. switch (fmt) {
  7534. case SG_PIXELFORMAT_R8:
  7535. case SG_PIXELFORMAT_R8UI:
  7536. case SG_PIXELFORMAT_RG8:
  7537. case SG_PIXELFORMAT_RG8UI:
  7538. case SG_PIXELFORMAT_RGBA8:
  7539. case SG_PIXELFORMAT_SRGB8A8:
  7540. case SG_PIXELFORMAT_RGBA8UI:
  7541. case SG_PIXELFORMAT_BGRA8:
  7542. return GL_UNSIGNED_BYTE;
  7543. case SG_PIXELFORMAT_R8SN:
  7544. case SG_PIXELFORMAT_R8SI:
  7545. case SG_PIXELFORMAT_RG8SN:
  7546. case SG_PIXELFORMAT_RG8SI:
  7547. case SG_PIXELFORMAT_RGBA8SN:
  7548. case SG_PIXELFORMAT_RGBA8SI:
  7549. return GL_BYTE;
  7550. case SG_PIXELFORMAT_R16:
  7551. case SG_PIXELFORMAT_R16UI:
  7552. case SG_PIXELFORMAT_RG16:
  7553. case SG_PIXELFORMAT_RG16UI:
  7554. case SG_PIXELFORMAT_RGBA16:
  7555. case SG_PIXELFORMAT_RGBA16UI:
  7556. return GL_UNSIGNED_SHORT;
  7557. case SG_PIXELFORMAT_R16SN:
  7558. case SG_PIXELFORMAT_R16SI:
  7559. case SG_PIXELFORMAT_RG16SN:
  7560. case SG_PIXELFORMAT_RG16SI:
  7561. case SG_PIXELFORMAT_RGBA16SN:
  7562. case SG_PIXELFORMAT_RGBA16SI:
  7563. return GL_SHORT;
  7564. case SG_PIXELFORMAT_R16F:
  7565. case SG_PIXELFORMAT_RG16F:
  7566. case SG_PIXELFORMAT_RGBA16F:
  7567. return GL_HALF_FLOAT;
  7568. case SG_PIXELFORMAT_R32UI:
  7569. case SG_PIXELFORMAT_RG32UI:
  7570. case SG_PIXELFORMAT_RGBA32UI:
  7571. return GL_UNSIGNED_INT;
  7572. case SG_PIXELFORMAT_R32SI:
  7573. case SG_PIXELFORMAT_RG32SI:
  7574. case SG_PIXELFORMAT_RGBA32SI:
  7575. return GL_INT;
  7576. case SG_PIXELFORMAT_R32F:
  7577. case SG_PIXELFORMAT_RG32F:
  7578. case SG_PIXELFORMAT_RGBA32F:
  7579. return GL_FLOAT;
  7580. case SG_PIXELFORMAT_RGB10A2:
  7581. return GL_UNSIGNED_INT_2_10_10_10_REV;
  7582. case SG_PIXELFORMAT_RG11B10F:
  7583. return GL_UNSIGNED_INT_10F_11F_11F_REV;
  7584. case SG_PIXELFORMAT_RGB9E5:
  7585. return GL_UNSIGNED_INT_5_9_9_9_REV;
  7586. case SG_PIXELFORMAT_DEPTH:
  7587. return GL_FLOAT;
  7588. case SG_PIXELFORMAT_DEPTH_STENCIL:
  7589. return GL_UNSIGNED_INT_24_8;
  7590. default:
  7591. SOKOL_UNREACHABLE; return 0;
  7592. }
  7593. }
  7594. _SOKOL_PRIVATE GLenum _sg_gl_teximage_format(sg_pixel_format fmt) {
  7595. switch (fmt) {
  7596. case SG_PIXELFORMAT_R8:
  7597. case SG_PIXELFORMAT_R8SN:
  7598. case SG_PIXELFORMAT_R16:
  7599. case SG_PIXELFORMAT_R16SN:
  7600. case SG_PIXELFORMAT_R16F:
  7601. case SG_PIXELFORMAT_R32F:
  7602. return GL_RED;
  7603. case SG_PIXELFORMAT_R8UI:
  7604. case SG_PIXELFORMAT_R8SI:
  7605. case SG_PIXELFORMAT_R16UI:
  7606. case SG_PIXELFORMAT_R16SI:
  7607. case SG_PIXELFORMAT_R32UI:
  7608. case SG_PIXELFORMAT_R32SI:
  7609. return GL_RED_INTEGER;
  7610. case SG_PIXELFORMAT_RG8:
  7611. case SG_PIXELFORMAT_RG8SN:
  7612. case SG_PIXELFORMAT_RG16:
  7613. case SG_PIXELFORMAT_RG16SN:
  7614. case SG_PIXELFORMAT_RG16F:
  7615. case SG_PIXELFORMAT_RG32F:
  7616. return GL_RG;
  7617. case SG_PIXELFORMAT_RG8UI:
  7618. case SG_PIXELFORMAT_RG8SI:
  7619. case SG_PIXELFORMAT_RG16UI:
  7620. case SG_PIXELFORMAT_RG16SI:
  7621. case SG_PIXELFORMAT_RG32UI:
  7622. case SG_PIXELFORMAT_RG32SI:
  7623. return GL_RG_INTEGER;
  7624. case SG_PIXELFORMAT_RGBA8:
  7625. case SG_PIXELFORMAT_SRGB8A8:
  7626. case SG_PIXELFORMAT_RGBA8SN:
  7627. case SG_PIXELFORMAT_RGBA16:
  7628. case SG_PIXELFORMAT_RGBA16SN:
  7629. case SG_PIXELFORMAT_RGBA16F:
  7630. case SG_PIXELFORMAT_RGBA32F:
  7631. case SG_PIXELFORMAT_RGB10A2:
  7632. return GL_RGBA;
  7633. case SG_PIXELFORMAT_RGBA8UI:
  7634. case SG_PIXELFORMAT_RGBA8SI:
  7635. case SG_PIXELFORMAT_RGBA16UI:
  7636. case SG_PIXELFORMAT_RGBA16SI:
  7637. case SG_PIXELFORMAT_RGBA32UI:
  7638. case SG_PIXELFORMAT_RGBA32SI:
  7639. return GL_RGBA_INTEGER;
  7640. case SG_PIXELFORMAT_RG11B10F:
  7641. case SG_PIXELFORMAT_RGB9E5:
  7642. return GL_RGB;
  7643. case SG_PIXELFORMAT_DEPTH:
  7644. return GL_DEPTH_COMPONENT;
  7645. case SG_PIXELFORMAT_DEPTH_STENCIL:
  7646. return GL_DEPTH_STENCIL;
  7647. case SG_PIXELFORMAT_BC1_RGBA:
  7648. return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
  7649. case SG_PIXELFORMAT_BC2_RGBA:
  7650. return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
  7651. case SG_PIXELFORMAT_BC3_RGBA:
  7652. return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
  7653. case SG_PIXELFORMAT_BC3_SRGBA:
  7654. return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  7655. case SG_PIXELFORMAT_BC4_R:
  7656. return GL_COMPRESSED_RED_RGTC1;
  7657. case SG_PIXELFORMAT_BC4_RSN:
  7658. return GL_COMPRESSED_SIGNED_RED_RGTC1;
  7659. case SG_PIXELFORMAT_BC5_RG:
  7660. return GL_COMPRESSED_RED_GREEN_RGTC2;
  7661. case SG_PIXELFORMAT_BC5_RGSN:
  7662. return GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2;
  7663. case SG_PIXELFORMAT_BC6H_RGBF:
  7664. return GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB;
  7665. case SG_PIXELFORMAT_BC6H_RGBUF:
  7666. return GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB;
  7667. case SG_PIXELFORMAT_BC7_RGBA:
  7668. return GL_COMPRESSED_RGBA_BPTC_UNORM_ARB;
  7669. case SG_PIXELFORMAT_BC7_SRGBA:
  7670. return GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB;
  7671. case SG_PIXELFORMAT_ETC2_RGB8:
  7672. return GL_COMPRESSED_RGB8_ETC2;
  7673. case SG_PIXELFORMAT_ETC2_SRGB8:
  7674. return GL_COMPRESSED_SRGB8_ETC2;
  7675. case SG_PIXELFORMAT_ETC2_RGB8A1:
  7676. return GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
  7677. case SG_PIXELFORMAT_ETC2_RGBA8:
  7678. return GL_COMPRESSED_RGBA8_ETC2_EAC;
  7679. case SG_PIXELFORMAT_ETC2_SRGB8A8:
  7680. return GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
  7681. case SG_PIXELFORMAT_EAC_R11:
  7682. return GL_COMPRESSED_R11_EAC;
  7683. case SG_PIXELFORMAT_EAC_R11SN:
  7684. return GL_COMPRESSED_SIGNED_R11_EAC;
  7685. case SG_PIXELFORMAT_EAC_RG11:
  7686. return GL_COMPRESSED_RG11_EAC;
  7687. case SG_PIXELFORMAT_EAC_RG11SN:
  7688. return GL_COMPRESSED_SIGNED_RG11_EAC;
  7689. case SG_PIXELFORMAT_ASTC_4x4_RGBA:
  7690. return GL_COMPRESSED_RGBA_ASTC_4x4_KHR;
  7691. case SG_PIXELFORMAT_ASTC_4x4_SRGBA:
  7692. return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
  7693. default:
  7694. SOKOL_UNREACHABLE; return 0;
  7695. }
  7696. }
  7697. _SOKOL_PRIVATE GLenum _sg_gl_teximage_internal_format(sg_pixel_format fmt) {
  7698. switch (fmt) {
  7699. case SG_PIXELFORMAT_R8: return GL_R8;
  7700. case SG_PIXELFORMAT_R8SN: return GL_R8_SNORM;
  7701. case SG_PIXELFORMAT_R8UI: return GL_R8UI;
  7702. case SG_PIXELFORMAT_R8SI: return GL_R8I;
  7703. #if !defined(SOKOL_GLES3)
  7704. case SG_PIXELFORMAT_R16: return GL_R16;
  7705. case SG_PIXELFORMAT_R16SN: return GL_R16_SNORM;
  7706. #endif
  7707. case SG_PIXELFORMAT_R16UI: return GL_R16UI;
  7708. case SG_PIXELFORMAT_R16SI: return GL_R16I;
  7709. case SG_PIXELFORMAT_R16F: return GL_R16F;
  7710. case SG_PIXELFORMAT_RG8: return GL_RG8;
  7711. case SG_PIXELFORMAT_RG8SN: return GL_RG8_SNORM;
  7712. case SG_PIXELFORMAT_RG8UI: return GL_RG8UI;
  7713. case SG_PIXELFORMAT_RG8SI: return GL_RG8I;
  7714. case SG_PIXELFORMAT_R32UI: return GL_R32UI;
  7715. case SG_PIXELFORMAT_R32SI: return GL_R32I;
  7716. case SG_PIXELFORMAT_R32F: return GL_R32F;
  7717. #if !defined(SOKOL_GLES3)
  7718. case SG_PIXELFORMAT_RG16: return GL_RG16;
  7719. case SG_PIXELFORMAT_RG16SN: return GL_RG16_SNORM;
  7720. #endif
  7721. case SG_PIXELFORMAT_RG16UI: return GL_RG16UI;
  7722. case SG_PIXELFORMAT_RG16SI: return GL_RG16I;
  7723. case SG_PIXELFORMAT_RG16F: return GL_RG16F;
  7724. case SG_PIXELFORMAT_RGBA8: return GL_RGBA8;
  7725. case SG_PIXELFORMAT_SRGB8A8: return GL_SRGB8_ALPHA8;
  7726. case SG_PIXELFORMAT_RGBA8SN: return GL_RGBA8_SNORM;
  7727. case SG_PIXELFORMAT_RGBA8UI: return GL_RGBA8UI;
  7728. case SG_PIXELFORMAT_RGBA8SI: return GL_RGBA8I;
  7729. case SG_PIXELFORMAT_RGB10A2: return GL_RGB10_A2;
  7730. case SG_PIXELFORMAT_RG11B10F: return GL_R11F_G11F_B10F;
  7731. case SG_PIXELFORMAT_RGB9E5: return GL_RGB9_E5;
  7732. case SG_PIXELFORMAT_RG32UI: return GL_RG32UI;
  7733. case SG_PIXELFORMAT_RG32SI: return GL_RG32I;
  7734. case SG_PIXELFORMAT_RG32F: return GL_RG32F;
  7735. #if !defined(SOKOL_GLES3)
  7736. case SG_PIXELFORMAT_RGBA16: return GL_RGBA16;
  7737. case SG_PIXELFORMAT_RGBA16SN: return GL_RGBA16_SNORM;
  7738. #endif
  7739. case SG_PIXELFORMAT_RGBA16UI: return GL_RGBA16UI;
  7740. case SG_PIXELFORMAT_RGBA16SI: return GL_RGBA16I;
  7741. case SG_PIXELFORMAT_RGBA16F: return GL_RGBA16F;
  7742. case SG_PIXELFORMAT_RGBA32UI: return GL_RGBA32UI;
  7743. case SG_PIXELFORMAT_RGBA32SI: return GL_RGBA32I;
  7744. case SG_PIXELFORMAT_RGBA32F: return GL_RGBA32F;
  7745. case SG_PIXELFORMAT_DEPTH: return GL_DEPTH_COMPONENT32F;
  7746. case SG_PIXELFORMAT_DEPTH_STENCIL: return GL_DEPTH24_STENCIL8;
  7747. case SG_PIXELFORMAT_BC1_RGBA: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
  7748. case SG_PIXELFORMAT_BC2_RGBA: return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
  7749. case SG_PIXELFORMAT_BC3_RGBA: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
  7750. case SG_PIXELFORMAT_BC3_SRGBA: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  7751. case SG_PIXELFORMAT_BC4_R: return GL_COMPRESSED_RED_RGTC1;
  7752. case SG_PIXELFORMAT_BC4_RSN: return GL_COMPRESSED_SIGNED_RED_RGTC1;
  7753. case SG_PIXELFORMAT_BC5_RG: return GL_COMPRESSED_RED_GREEN_RGTC2;
  7754. case SG_PIXELFORMAT_BC5_RGSN: return GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2;
  7755. case SG_PIXELFORMAT_BC6H_RGBF: return GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB;
  7756. case SG_PIXELFORMAT_BC6H_RGBUF: return GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB;
  7757. case SG_PIXELFORMAT_BC7_RGBA: return GL_COMPRESSED_RGBA_BPTC_UNORM_ARB;
  7758. case SG_PIXELFORMAT_BC7_SRGBA: return GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB;
  7759. case SG_PIXELFORMAT_ETC2_RGB8: return GL_COMPRESSED_RGB8_ETC2;
  7760. case SG_PIXELFORMAT_ETC2_SRGB8: return GL_COMPRESSED_SRGB8_ETC2;
  7761. case SG_PIXELFORMAT_ETC2_RGB8A1: return GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
  7762. case SG_PIXELFORMAT_ETC2_RGBA8: return GL_COMPRESSED_RGBA8_ETC2_EAC;
  7763. case SG_PIXELFORMAT_ETC2_SRGB8A8: return GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
  7764. case SG_PIXELFORMAT_EAC_R11: return GL_COMPRESSED_R11_EAC;
  7765. case SG_PIXELFORMAT_EAC_R11SN: return GL_COMPRESSED_SIGNED_R11_EAC;
  7766. case SG_PIXELFORMAT_EAC_RG11: return GL_COMPRESSED_RG11_EAC;
  7767. case SG_PIXELFORMAT_EAC_RG11SN: return GL_COMPRESSED_SIGNED_RG11_EAC;
  7768. case SG_PIXELFORMAT_ASTC_4x4_RGBA: return GL_COMPRESSED_RGBA_ASTC_4x4_KHR;
  7769. case SG_PIXELFORMAT_ASTC_4x4_SRGBA: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
  7770. default: SOKOL_UNREACHABLE; return 0;
  7771. }
  7772. }
  7773. _SOKOL_PRIVATE GLenum _sg_gl_cubeface_target(int face_index) {
  7774. switch (face_index) {
  7775. case 0: return GL_TEXTURE_CUBE_MAP_POSITIVE_X;
  7776. case 1: return GL_TEXTURE_CUBE_MAP_NEGATIVE_X;
  7777. case 2: return GL_TEXTURE_CUBE_MAP_POSITIVE_Y;
  7778. case 3: return GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;
  7779. case 4: return GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
  7780. case 5: return GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
  7781. default: SOKOL_UNREACHABLE; return 0;
  7782. }
  7783. }
  7784. // see: https://www.khronos.org/registry/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  7785. _SOKOL_PRIVATE void _sg_gl_init_pixelformats(bool has_bgra) {
  7786. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R8]);
  7787. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_R8SN]);
  7788. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R8UI]);
  7789. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R8SI]);
  7790. #if !defined(SOKOL_GLES3)
  7791. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16]);
  7792. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16SN]);
  7793. #endif
  7794. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R16UI]);
  7795. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R16SI]);
  7796. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG8]);
  7797. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG8SN]);
  7798. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG8UI]);
  7799. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG8SI]);
  7800. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32UI]);
  7801. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32SI]);
  7802. #if !defined(SOKOL_GLES3)
  7803. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16]);
  7804. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16SN]);
  7805. #endif
  7806. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG16UI]);
  7807. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG16SI]);
  7808. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA8]);
  7809. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_SRGB8A8]);
  7810. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGBA8SN]);
  7811. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA8UI]);
  7812. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA8SI]);
  7813. if (has_bgra) {
  7814. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_BGRA8]);
  7815. }
  7816. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGB10A2]);
  7817. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGB9E5]);
  7818. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  7819. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  7820. #if !defined(SOKOL_GLES3)
  7821. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16]);
  7822. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16SN]);
  7823. #endif
  7824. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA16UI]);
  7825. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA16SI]);
  7826. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  7827. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  7828. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH]);
  7829. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH_STENCIL]);
  7830. }
  7831. // FIXME: OES_half_float_blend
  7832. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_half_float(bool has_colorbuffer_half_float) {
  7833. if (has_colorbuffer_half_float) {
  7834. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16F]);
  7835. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16F]);
  7836. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  7837. } else {
  7838. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_R16F]);
  7839. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG16F]);
  7840. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  7841. }
  7842. }
  7843. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_float(bool has_colorbuffer_float, bool has_texture_float_linear, bool has_float_blend) {
  7844. if (has_texture_float_linear) {
  7845. if (has_colorbuffer_float) {
  7846. if (has_float_blend) {
  7847. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R32F]);
  7848. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  7849. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  7850. } else {
  7851. _sg_pixelformat_sfrm(&_sg.formats[SG_PIXELFORMAT_R32F]);
  7852. _sg_pixelformat_sfrm(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  7853. _sg_pixelformat_sfrm(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  7854. }
  7855. _sg_pixelformat_sfrm(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  7856. } else {
  7857. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_R32F]);
  7858. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  7859. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  7860. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  7861. }
  7862. } else {
  7863. if (has_colorbuffer_float) {
  7864. _sg_pixelformat_sbrm(&_sg.formats[SG_PIXELFORMAT_R32F]);
  7865. _sg_pixelformat_sbrm(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  7866. _sg_pixelformat_sbrm(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  7867. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  7868. } else {
  7869. _sg_pixelformat_s(&_sg.formats[SG_PIXELFORMAT_R32F]);
  7870. _sg_pixelformat_s(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  7871. _sg_pixelformat_s(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  7872. _sg_pixelformat_s(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  7873. }
  7874. }
  7875. }
  7876. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_s3tc(void) {
  7877. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC1_RGBA]);
  7878. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC2_RGBA]);
  7879. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_RGBA]);
  7880. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_SRGBA]);
  7881. }
  7882. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_rgtc(void) {
  7883. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_R]);
  7884. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_RSN]);
  7885. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RG]);
  7886. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RGSN]);
  7887. }
  7888. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_bptc(void) {
  7889. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBF]);
  7890. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBUF]);
  7891. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_RGBA]);
  7892. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_SRGBA]);
  7893. }
  7894. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_etc2(void) {
  7895. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8]);
  7896. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8]);
  7897. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8A1]);
  7898. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGBA8]);
  7899. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8A8]);
  7900. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11]);
  7901. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11SN]);
  7902. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11]);
  7903. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11SN]);
  7904. }
  7905. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_astc(void) {
  7906. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_RGBA]);
  7907. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_SRGBA]);
  7908. }
  7909. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_compute(void) {
  7910. // using Vulkan's conservative default caps (see: https://github.com/gpuweb/gpuweb/issues/513)
  7911. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8]);
  7912. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8SN]);
  7913. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8UI]);
  7914. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8SI]);
  7915. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16UI]);
  7916. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16SI]);
  7917. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  7918. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32UI]);
  7919. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32SI]);
  7920. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32F]);
  7921. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  7922. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  7923. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  7924. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  7925. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  7926. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  7927. }
  7928. _SOKOL_PRIVATE void _sg_gl_init_limits(void) {
  7929. _SG_GL_CHECK_ERROR();
  7930. GLint gl_int;
  7931. glGetIntegerv(GL_MAX_TEXTURE_SIZE, &gl_int);
  7932. _SG_GL_CHECK_ERROR();
  7933. _sg.limits.max_image_size_2d = gl_int;
  7934. _sg.limits.max_image_size_array = gl_int;
  7935. glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &gl_int);
  7936. _SG_GL_CHECK_ERROR();
  7937. _sg.limits.max_image_size_cube = gl_int;
  7938. glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &gl_int);
  7939. _SG_GL_CHECK_ERROR();
  7940. if (gl_int > SG_MAX_VERTEX_ATTRIBUTES) {
  7941. gl_int = SG_MAX_VERTEX_ATTRIBUTES;
  7942. }
  7943. _sg.limits.max_vertex_attrs = gl_int;
  7944. glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, &gl_int);
  7945. _SG_GL_CHECK_ERROR();
  7946. _sg.limits.gl_max_vertex_uniform_components = gl_int;
  7947. glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE, &gl_int);
  7948. _SG_GL_CHECK_ERROR();
  7949. _sg.limits.max_image_size_3d = gl_int;
  7950. glGetIntegerv(GL_MAX_ARRAY_TEXTURE_LAYERS, &gl_int);
  7951. _SG_GL_CHECK_ERROR();
  7952. _sg.limits.max_image_array_layers = gl_int;
  7953. if (_sg.gl.ext_anisotropic) {
  7954. glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &gl_int);
  7955. _SG_GL_CHECK_ERROR();
  7956. _sg.gl.max_anisotropy = gl_int;
  7957. } else {
  7958. _sg.gl.max_anisotropy = 1;
  7959. }
  7960. glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &gl_int);
  7961. _SG_GL_CHECK_ERROR();
  7962. _sg.limits.gl_max_combined_texture_image_units = gl_int;
  7963. }
  7964. #if defined(SOKOL_GLCORE)
  7965. _SOKOL_PRIVATE void _sg_gl_init_caps_glcore(void) {
  7966. _sg.backend = SG_BACKEND_GLCORE;
  7967. GLint major_version = 0;
  7968. GLint minor_version = 0;
  7969. glGetIntegerv(GL_MAJOR_VERSION, &major_version);
  7970. glGetIntegerv(GL_MINOR_VERSION, &minor_version);
  7971. const int version = major_version * 100 + minor_version * 10;
  7972. _sg.features.origin_top_left = false;
  7973. _sg.features.image_clamp_to_border = true;
  7974. _sg.features.mrt_independent_blend_state = false;
  7975. _sg.features.mrt_independent_write_mask = true;
  7976. _sg.features.compute = version >= 430;
  7977. #if defined(__APPLE__)
  7978. _sg.features.msaa_image_bindings = false;
  7979. #else
  7980. _sg.features.msaa_image_bindings = true;
  7981. #endif
  7982. // scan extensions
  7983. bool has_s3tc = false; // BC1..BC3
  7984. bool has_rgtc = false; // BC4 and BC5
  7985. bool has_bptc = false; // BC6H and BC7
  7986. bool has_etc2 = false;
  7987. bool has_astc = false;
  7988. GLint num_ext = 0;
  7989. glGetIntegerv(GL_NUM_EXTENSIONS, &num_ext);
  7990. for (int i = 0; i < num_ext; i++) {
  7991. const char* ext = (const char*) glGetStringi(GL_EXTENSIONS, (GLuint)i);
  7992. if (ext) {
  7993. if (strstr(ext, "_texture_compression_s3tc")) {
  7994. has_s3tc = true;
  7995. } else if (strstr(ext, "_texture_compression_rgtc")) {
  7996. has_rgtc = true;
  7997. } else if (strstr(ext, "_texture_compression_bptc")) {
  7998. has_bptc = true;
  7999. } else if (strstr(ext, "_ES3_compatibility")) {
  8000. has_etc2 = true;
  8001. } else if (strstr(ext, "_texture_filter_anisotropic")) {
  8002. _sg.gl.ext_anisotropic = true;
  8003. } else if (strstr(ext, "_texture_compression_astc_ldr")) {
  8004. has_astc = true;
  8005. }
  8006. }
  8007. }
  8008. // limits
  8009. _sg_gl_init_limits();
  8010. // pixel formats
  8011. const bool has_bgra = false; // not a bug
  8012. const bool has_colorbuffer_float = true;
  8013. const bool has_colorbuffer_half_float = true;
  8014. const bool has_texture_float_linear = true; // FIXME???
  8015. const bool has_float_blend = true;
  8016. _sg_gl_init_pixelformats(has_bgra);
  8017. _sg_gl_init_pixelformats_float(has_colorbuffer_float, has_texture_float_linear, has_float_blend);
  8018. _sg_gl_init_pixelformats_half_float(has_colorbuffer_half_float);
  8019. if (has_s3tc) {
  8020. _sg_gl_init_pixelformats_s3tc();
  8021. }
  8022. if (has_rgtc) {
  8023. _sg_gl_init_pixelformats_rgtc();
  8024. }
  8025. if (has_bptc) {
  8026. _sg_gl_init_pixelformats_bptc();
  8027. }
  8028. if (has_etc2) {
  8029. _sg_gl_init_pixelformats_etc2();
  8030. }
  8031. if (has_astc) {
  8032. _sg_gl_init_pixelformats_astc();
  8033. }
  8034. if (_sg.features.compute) {
  8035. _sg_gl_init_pixelformats_compute();
  8036. }
  8037. }
  8038. #endif
  8039. #if defined(SOKOL_GLES3)
  8040. _SOKOL_PRIVATE void _sg_gl_init_caps_gles3(void) {
  8041. _sg.backend = SG_BACKEND_GLES3;
  8042. GLint major_version = 0;
  8043. GLint minor_version = 0;
  8044. glGetIntegerv(GL_MAJOR_VERSION, &major_version);
  8045. glGetIntegerv(GL_MINOR_VERSION, &minor_version);
  8046. const int version = major_version * 100 + minor_version * 10;
  8047. _sg.features.origin_top_left = false;
  8048. _sg.features.image_clamp_to_border = false;
  8049. _sg.features.mrt_independent_blend_state = false;
  8050. _sg.features.mrt_independent_write_mask = false;
  8051. _sg.features.compute = version >= 310;
  8052. _sg.features.msaa_image_bindings = false;
  8053. #if defined(__EMSCRIPTEN__)
  8054. _sg.features.separate_buffer_types = true;
  8055. #else
  8056. _sg.features.separate_buffer_types = false;
  8057. #endif
  8058. bool has_s3tc = false; // BC1..BC3
  8059. bool has_rgtc = false; // BC4 and BC5
  8060. bool has_bptc = false; // BC6H and BC7
  8061. #if defined(__EMSCRIPTEN__)
  8062. bool has_etc2 = false;
  8063. #else
  8064. bool has_etc2 = true;
  8065. #endif
  8066. bool has_astc = false;
  8067. bool has_colorbuffer_float = false;
  8068. bool has_colorbuffer_half_float = false;
  8069. bool has_texture_float_linear = false;
  8070. bool has_float_blend = false;
  8071. GLint num_ext = 0;
  8072. glGetIntegerv(GL_NUM_EXTENSIONS, &num_ext);
  8073. for (int i = 0; i < num_ext; i++) {
  8074. const char* ext = (const char*) glGetStringi(GL_EXTENSIONS, (GLuint)i);
  8075. if (ext) {
  8076. if (strstr(ext, "_texture_compression_s3tc")) {
  8077. has_s3tc = true;
  8078. } else if (strstr(ext, "_compressed_texture_s3tc")) {
  8079. has_s3tc = true;
  8080. } else if (strstr(ext, "_texture_compression_rgtc")) {
  8081. has_rgtc = true;
  8082. } else if (strstr(ext, "_texture_compression_bptc")) {
  8083. has_bptc = true;
  8084. } else if (strstr(ext, "_compressed_texture_etc")) {
  8085. has_etc2 = true;
  8086. } else if (strstr(ext, "_compressed_texture_astc")) {
  8087. has_astc = true;
  8088. } else if (strstr(ext, "_color_buffer_float")) {
  8089. has_colorbuffer_float = true;
  8090. } else if (strstr(ext, "_color_buffer_half_float")) {
  8091. has_colorbuffer_half_float = true;
  8092. } else if (strstr(ext, "_texture_float_linear")) {
  8093. has_texture_float_linear = true;
  8094. } else if (strstr(ext, "_float_blend")) {
  8095. has_float_blend = true;
  8096. } else if (strstr(ext, "_texture_filter_anisotropic")) {
  8097. _sg.gl.ext_anisotropic = true;
  8098. }
  8099. }
  8100. }
  8101. /* on WebGL2, color_buffer_float also includes 16-bit formats
  8102. see: https://developer.mozilla.org/en-US/docs/Web/API/EXT_color_buffer_float
  8103. */
  8104. #if defined(__EMSCRIPTEN__)
  8105. if (!has_colorbuffer_half_float && has_colorbuffer_float) {
  8106. has_colorbuffer_half_float = has_colorbuffer_float;
  8107. }
  8108. #endif
  8109. // limits
  8110. _sg_gl_init_limits();
  8111. // pixel formats
  8112. const bool has_bgra = false; // not a bug
  8113. _sg_gl_init_pixelformats(has_bgra);
  8114. _sg_gl_init_pixelformats_float(has_colorbuffer_float, has_texture_float_linear, has_float_blend);
  8115. _sg_gl_init_pixelformats_half_float(has_colorbuffer_half_float);
  8116. if (has_s3tc) {
  8117. _sg_gl_init_pixelformats_s3tc();
  8118. }
  8119. if (has_rgtc) {
  8120. _sg_gl_init_pixelformats_rgtc();
  8121. }
  8122. if (has_bptc) {
  8123. _sg_gl_init_pixelformats_bptc();
  8124. }
  8125. if (has_etc2) {
  8126. _sg_gl_init_pixelformats_etc2();
  8127. }
  8128. if (has_astc) {
  8129. _sg_gl_init_pixelformats_astc();
  8130. }
  8131. if (_sg.features.compute) {
  8132. _sg_gl_init_pixelformats_compute();
  8133. }
  8134. }
  8135. #endif
  8136. //-- state cache implementation ------------------------------------------------
  8137. _SOKOL_PRIVATE void _sg_gl_cache_clear_buffer_bindings(bool force) {
  8138. if (force || (_sg.gl.cache.vertex_buffer != 0)) {
  8139. glBindBuffer(GL_ARRAY_BUFFER, 0);
  8140. _sg.gl.cache.vertex_buffer = 0;
  8141. _sg_stats_add(gl.num_bind_buffer, 1);
  8142. }
  8143. if (force || (_sg.gl.cache.index_buffer != 0)) {
  8144. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  8145. _sg.gl.cache.index_buffer = 0;
  8146. _sg_stats_add(gl.num_bind_buffer, 1);
  8147. }
  8148. if (force || (_sg.gl.cache.storage_buffer != 0)) {
  8149. if (_sg.features.compute) {
  8150. glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
  8151. }
  8152. _sg.gl.cache.storage_buffer = 0;
  8153. _sg_stats_add(gl.num_bind_buffer, 1);
  8154. }
  8155. for (size_t i = 0; i < _SG_GL_MAX_SBUF_BINDINGS; i++) {
  8156. if (force || (_sg.gl.cache.storage_buffers[i] != 0)) {
  8157. if (_sg.features.compute) {
  8158. glBindBufferBase(GL_SHADER_STORAGE_BUFFER, (GLuint)i, 0);
  8159. }
  8160. _sg.gl.cache.storage_buffers[i] = 0;
  8161. _sg_stats_add(gl.num_bind_buffer, 1);
  8162. }
  8163. }
  8164. }
  8165. _SOKOL_PRIVATE void _sg_gl_cache_bind_buffer(GLenum target, GLuint buffer) {
  8166. SOKOL_ASSERT((GL_ARRAY_BUFFER == target) || (GL_ELEMENT_ARRAY_BUFFER == target) || (GL_SHADER_STORAGE_BUFFER == target));
  8167. if (target == GL_ARRAY_BUFFER) {
  8168. if (_sg.gl.cache.vertex_buffer != buffer) {
  8169. _sg.gl.cache.vertex_buffer = buffer;
  8170. glBindBuffer(target, buffer);
  8171. _sg_stats_add(gl.num_bind_buffer, 1);
  8172. }
  8173. } else if (target == GL_ELEMENT_ARRAY_BUFFER) {
  8174. if (_sg.gl.cache.index_buffer != buffer) {
  8175. _sg.gl.cache.index_buffer = buffer;
  8176. glBindBuffer(target, buffer);
  8177. _sg_stats_add(gl.num_bind_buffer, 1);
  8178. }
  8179. } else if (target == GL_SHADER_STORAGE_BUFFER) {
  8180. if (_sg.gl.cache.storage_buffer != buffer) {
  8181. _sg.gl.cache.storage_buffer = buffer;
  8182. if (_sg.features.compute) {
  8183. glBindBuffer(target, buffer);
  8184. }
  8185. _sg_stats_add(gl.num_bind_buffer, 1);
  8186. }
  8187. } else {
  8188. SOKOL_UNREACHABLE;
  8189. }
  8190. }
  8191. _SOKOL_PRIVATE void _sg_gl_cache_bind_storage_buffer(uint8_t glsl_binding_n, GLuint buffer) {
  8192. SOKOL_ASSERT(glsl_binding_n < _SG_GL_MAX_SBUF_BINDINGS);
  8193. if (_sg.gl.cache.storage_buffers[glsl_binding_n] != buffer) {
  8194. _sg.gl.cache.storage_buffers[glsl_binding_n] = buffer;
  8195. _sg.gl.cache.storage_buffer = buffer; // not a bug
  8196. if (_sg.features.compute) {
  8197. glBindBufferBase(GL_SHADER_STORAGE_BUFFER, glsl_binding_n, buffer);
  8198. }
  8199. _sg_stats_add(gl.num_bind_buffer, 1);
  8200. }
  8201. }
  8202. _SOKOL_PRIVATE void _sg_gl_cache_store_buffer_binding(GLenum target) {
  8203. if (target == GL_ARRAY_BUFFER) {
  8204. _sg.gl.cache.stored_vertex_buffer = _sg.gl.cache.vertex_buffer;
  8205. } else if (target == GL_ELEMENT_ARRAY_BUFFER) {
  8206. _sg.gl.cache.stored_index_buffer = _sg.gl.cache.index_buffer;
  8207. } else if (target == GL_SHADER_STORAGE_BUFFER) {
  8208. _sg.gl.cache.stored_storage_buffer = _sg.gl.cache.storage_buffer;
  8209. } else {
  8210. SOKOL_UNREACHABLE;
  8211. }
  8212. }
  8213. _SOKOL_PRIVATE void _sg_gl_cache_restore_buffer_binding(GLenum target) {
  8214. if (target == GL_ARRAY_BUFFER) {
  8215. if (_sg.gl.cache.stored_vertex_buffer != 0) {
  8216. // we only care about restoring valid ids
  8217. _sg_gl_cache_bind_buffer(target, _sg.gl.cache.stored_vertex_buffer);
  8218. _sg.gl.cache.stored_vertex_buffer = 0;
  8219. }
  8220. } else if (target == GL_ELEMENT_ARRAY_BUFFER) {
  8221. if (_sg.gl.cache.stored_index_buffer != 0) {
  8222. // we only care about restoring valid ids
  8223. _sg_gl_cache_bind_buffer(target, _sg.gl.cache.stored_index_buffer);
  8224. _sg.gl.cache.stored_index_buffer = 0;
  8225. }
  8226. } else if (target == GL_SHADER_STORAGE_BUFFER) {
  8227. if (_sg.gl.cache.stored_storage_buffer != 0) {
  8228. // we only care about restoring valid ids
  8229. _sg_gl_cache_bind_buffer(target, _sg.gl.cache.stored_storage_buffer);
  8230. _sg.gl.cache.stored_storage_buffer = 0;
  8231. }
  8232. } else {
  8233. SOKOL_UNREACHABLE;
  8234. }
  8235. }
  8236. // called from _sg_gl_discard_buffer()
  8237. _SOKOL_PRIVATE void _sg_gl_cache_invalidate_buffer(GLuint buf) {
  8238. if (buf == _sg.gl.cache.vertex_buffer) {
  8239. _sg.gl.cache.vertex_buffer = 0;
  8240. glBindBuffer(GL_ARRAY_BUFFER, 0);
  8241. _sg_stats_add(gl.num_bind_buffer, 1);
  8242. }
  8243. if (buf == _sg.gl.cache.index_buffer) {
  8244. _sg.gl.cache.index_buffer = 0;
  8245. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  8246. _sg_stats_add(gl.num_bind_buffer, 1);
  8247. }
  8248. if (buf == _sg.gl.cache.storage_buffer) {
  8249. _sg.gl.cache.storage_buffer = 0;
  8250. glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
  8251. _sg_stats_add(gl.num_bind_buffer, 1);
  8252. }
  8253. for (size_t i = 0; i < _SG_GL_MAX_SBUF_BINDINGS; i++) {
  8254. if (buf == _sg.gl.cache.storage_buffers[i]) {
  8255. _sg.gl.cache.storage_buffers[i] = 0;
  8256. _sg.gl.cache.storage_buffer = 0; // not a bug!
  8257. glBindBufferBase(GL_SHADER_STORAGE_BUFFER, (GLuint)i, 0);
  8258. _sg_stats_add(gl.num_bind_buffer, 1);
  8259. }
  8260. }
  8261. if (buf == _sg.gl.cache.stored_vertex_buffer) {
  8262. _sg.gl.cache.stored_vertex_buffer = 0;
  8263. }
  8264. if (buf == _sg.gl.cache.stored_index_buffer) {
  8265. _sg.gl.cache.stored_index_buffer = 0;
  8266. }
  8267. if (buf == _sg.gl.cache.stored_storage_buffer) {
  8268. _sg.gl.cache.stored_storage_buffer = 0;
  8269. }
  8270. for (int i = 0; i < SG_MAX_VERTEX_ATTRIBUTES; i++) {
  8271. if (buf == _sg.gl.cache.attrs[i].gl_vbuf) {
  8272. _sg.gl.cache.attrs[i].gl_vbuf = 0;
  8273. }
  8274. }
  8275. }
  8276. _SOKOL_PRIVATE void _sg_gl_cache_active_texture(GLenum texture) {
  8277. _SG_GL_CHECK_ERROR();
  8278. if (_sg.gl.cache.cur_active_texture != texture) {
  8279. _sg.gl.cache.cur_active_texture = texture;
  8280. glActiveTexture(texture);
  8281. _sg_stats_add(gl.num_active_texture, 1);
  8282. }
  8283. _SG_GL_CHECK_ERROR();
  8284. }
  8285. _SOKOL_PRIVATE void _sg_gl_cache_clear_texture_sampler_bindings(bool force) {
  8286. _SG_GL_CHECK_ERROR();
  8287. for (int i = 0; (i < _SG_GL_MAX_IMG_SMP_BINDINGS) && (i < _sg.limits.gl_max_combined_texture_image_units); i++) {
  8288. if (force || (_sg.gl.cache.texture_samplers[i].texture != 0)) {
  8289. GLenum gl_texture_unit = (GLenum) (GL_TEXTURE0 + i);
  8290. glActiveTexture(gl_texture_unit);
  8291. _sg_stats_add(gl.num_active_texture, 1);
  8292. glBindTexture(GL_TEXTURE_2D, 0);
  8293. glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
  8294. glBindTexture(GL_TEXTURE_3D, 0);
  8295. glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
  8296. _sg_stats_add(gl.num_bind_texture, 4);
  8297. glBindSampler((GLuint)i, 0);
  8298. _sg_stats_add(gl.num_bind_sampler, 1);
  8299. _sg.gl.cache.texture_samplers[i].target = 0;
  8300. _sg.gl.cache.texture_samplers[i].texture = 0;
  8301. _sg.gl.cache.texture_samplers[i].sampler = 0;
  8302. _sg.gl.cache.cur_active_texture = gl_texture_unit;
  8303. }
  8304. }
  8305. _SG_GL_CHECK_ERROR();
  8306. }
  8307. _SOKOL_PRIVATE void _sg_gl_cache_bind_texture_sampler(int8_t gl_tex_slot, GLenum target, GLuint texture, GLuint sampler) {
  8308. /* it's valid to call this function with target=0 and/or texture=0
  8309. target=0 will unbind the previous binding, texture=0 will clear
  8310. the new binding
  8311. */
  8312. SOKOL_ASSERT((gl_tex_slot >= 0) && (gl_tex_slot < _SG_GL_MAX_IMG_SMP_BINDINGS));
  8313. if (gl_tex_slot >= _sg.limits.gl_max_combined_texture_image_units) {
  8314. return;
  8315. }
  8316. _SG_GL_CHECK_ERROR();
  8317. _sg_gl_cache_texture_sampler_bind_slot* slot = &_sg.gl.cache.texture_samplers[gl_tex_slot];
  8318. if ((slot->target != target) || (slot->texture != texture) || (slot->sampler != sampler)) {
  8319. _sg_gl_cache_active_texture((GLenum)(GL_TEXTURE0 + gl_tex_slot));
  8320. // if the target has changed, clear the previous binding on that target
  8321. if ((target != slot->target) && (slot->target != 0)) {
  8322. glBindTexture(slot->target, 0);
  8323. _SG_GL_CHECK_ERROR();
  8324. _sg_stats_add(gl.num_bind_texture, 1);
  8325. }
  8326. // apply new binding (can be 0 to unbind)
  8327. if (target != 0) {
  8328. glBindTexture(target, texture);
  8329. _SG_GL_CHECK_ERROR();
  8330. _sg_stats_add(gl.num_bind_texture, 1);
  8331. }
  8332. // apply new sampler (can be 0 to unbind)
  8333. glBindSampler((GLuint)gl_tex_slot, sampler);
  8334. _SG_GL_CHECK_ERROR();
  8335. _sg_stats_add(gl.num_bind_sampler, 1);
  8336. slot->target = target;
  8337. slot->texture = texture;
  8338. slot->sampler = sampler;
  8339. }
  8340. }
  8341. _SOKOL_PRIVATE void _sg_gl_cache_store_texture_sampler_binding(int8_t gl_tex_slot) {
  8342. SOKOL_ASSERT((gl_tex_slot >= 0) && (gl_tex_slot < _SG_GL_MAX_IMG_SMP_BINDINGS));
  8343. _sg.gl.cache.stored_texture_sampler = _sg.gl.cache.texture_samplers[gl_tex_slot];
  8344. }
  8345. _SOKOL_PRIVATE void _sg_gl_cache_restore_texture_sampler_binding(int8_t gl_tex_slot) {
  8346. SOKOL_ASSERT((gl_tex_slot >= 0) && (gl_tex_slot < _SG_GL_MAX_IMG_SMP_BINDINGS));
  8347. _sg_gl_cache_texture_sampler_bind_slot* slot = &_sg.gl.cache.stored_texture_sampler;
  8348. if (slot->texture != 0) {
  8349. // we only care about restoring valid ids
  8350. SOKOL_ASSERT(slot->target != 0);
  8351. _sg_gl_cache_bind_texture_sampler(gl_tex_slot, slot->target, slot->texture, slot->sampler);
  8352. slot->target = 0;
  8353. slot->texture = 0;
  8354. slot->sampler = 0;
  8355. }
  8356. }
  8357. // called from _sg_gl_discard_texture() and _sg_gl_discard_sampler()
  8358. _SOKOL_PRIVATE void _sg_gl_cache_invalidate_texture_sampler(GLuint tex, GLuint smp) {
  8359. _SG_GL_CHECK_ERROR();
  8360. for (size_t i = 0; i < _SG_GL_MAX_IMG_SMP_BINDINGS; i++) {
  8361. _sg_gl_cache_texture_sampler_bind_slot* slot = &_sg.gl.cache.texture_samplers[i];
  8362. if ((0 != slot->target) && ((tex == slot->texture) || (smp == slot->sampler))) {
  8363. _sg_gl_cache_active_texture((GLenum)(GL_TEXTURE0 + i));
  8364. glBindTexture(slot->target, 0);
  8365. _SG_GL_CHECK_ERROR();
  8366. _sg_stats_add(gl.num_bind_texture, 1);
  8367. glBindSampler((GLuint)i, 0);
  8368. _SG_GL_CHECK_ERROR();
  8369. _sg_stats_add(gl.num_bind_sampler, 1);
  8370. slot->target = 0;
  8371. slot->texture = 0;
  8372. slot->sampler = 0;
  8373. }
  8374. }
  8375. if ((tex == _sg.gl.cache.stored_texture_sampler.texture) || (smp == _sg.gl.cache.stored_texture_sampler.sampler)) {
  8376. _sg.gl.cache.stored_texture_sampler.target = 0;
  8377. _sg.gl.cache.stored_texture_sampler.texture = 0;
  8378. _sg.gl.cache.stored_texture_sampler.sampler = 0;
  8379. }
  8380. }
  8381. // called from _sg_gl_discard_shader()
  8382. _SOKOL_PRIVATE void _sg_gl_cache_invalidate_program(GLuint prog) {
  8383. if (prog == _sg.gl.cache.prog) {
  8384. _sg.gl.cache.prog = 0;
  8385. glUseProgram(0);
  8386. _sg_stats_add(gl.num_use_program, 1);
  8387. }
  8388. }
  8389. // called from _sg_gl_discard_pipeline()
  8390. _SOKOL_PRIVATE void _sg_gl_cache_invalidate_pipeline(_sg_pipeline_t* pip) {
  8391. if (_sg_sref_eql(&_sg.gl.cache.cur_pip, &pip->slot)) {
  8392. _sg.gl.cache.cur_pip = _sg_sref(0);
  8393. }
  8394. }
  8395. _SOKOL_PRIVATE void _sg_gl_reset_state_cache(void) {
  8396. _SG_GL_CHECK_ERROR();
  8397. glBindVertexArray(_sg.gl.vao);
  8398. _SG_GL_CHECK_ERROR();
  8399. _sg_clear(&_sg.gl.cache, sizeof(_sg.gl.cache));
  8400. _sg_gl_cache_clear_buffer_bindings(true);
  8401. _SG_GL_CHECK_ERROR();
  8402. _sg_gl_cache_clear_texture_sampler_bindings(true);
  8403. _SG_GL_CHECK_ERROR();
  8404. for (int i = 0; i < _sg.limits.max_vertex_attrs; i++) {
  8405. _sg_gl_attr_t* attr = &_sg.gl.cache.attrs[i].gl_attr;
  8406. attr->vb_index = -1;
  8407. attr->divisor = -1;
  8408. glDisableVertexAttribArray((GLuint)i);
  8409. _SG_GL_CHECK_ERROR();
  8410. _sg_stats_add(gl.num_disable_vertex_attrib_array, 1);
  8411. }
  8412. _sg.gl.cache.cur_primitive_type = GL_TRIANGLES;
  8413. // shader program
  8414. glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&_sg.gl.cache.prog);
  8415. _SG_GL_CHECK_ERROR();
  8416. // depth and stencil state
  8417. _sg.gl.cache.depth.compare = SG_COMPAREFUNC_ALWAYS;
  8418. _sg.gl.cache.stencil.front.compare = SG_COMPAREFUNC_ALWAYS;
  8419. _sg.gl.cache.stencil.front.fail_op = SG_STENCILOP_KEEP;
  8420. _sg.gl.cache.stencil.front.depth_fail_op = SG_STENCILOP_KEEP;
  8421. _sg.gl.cache.stencil.front.pass_op = SG_STENCILOP_KEEP;
  8422. _sg.gl.cache.stencil.back.compare = SG_COMPAREFUNC_ALWAYS;
  8423. _sg.gl.cache.stencil.back.fail_op = SG_STENCILOP_KEEP;
  8424. _sg.gl.cache.stencil.back.depth_fail_op = SG_STENCILOP_KEEP;
  8425. _sg.gl.cache.stencil.back.pass_op = SG_STENCILOP_KEEP;
  8426. glEnable(GL_DEPTH_TEST);
  8427. glDepthFunc(GL_ALWAYS);
  8428. glDepthMask(GL_FALSE);
  8429. glDisable(GL_STENCIL_TEST);
  8430. glStencilFunc(GL_ALWAYS, 0, 0);
  8431. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  8432. glStencilMask(0);
  8433. _sg_stats_add(gl.num_render_state, 7);
  8434. // blend state
  8435. _sg.gl.cache.blend.src_factor_rgb = SG_BLENDFACTOR_ONE;
  8436. _sg.gl.cache.blend.dst_factor_rgb = SG_BLENDFACTOR_ZERO;
  8437. _sg.gl.cache.blend.op_rgb = SG_BLENDOP_ADD;
  8438. _sg.gl.cache.blend.src_factor_alpha = SG_BLENDFACTOR_ONE;
  8439. _sg.gl.cache.blend.dst_factor_alpha = SG_BLENDFACTOR_ZERO;
  8440. _sg.gl.cache.blend.op_alpha = SG_BLENDOP_ADD;
  8441. glDisable(GL_BLEND);
  8442. glBlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_ZERO);
  8443. glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
  8444. glBlendColor(0.0f, 0.0f, 0.0f, 0.0f);
  8445. _sg_stats_add(gl.num_render_state, 4);
  8446. // standalone state
  8447. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  8448. _sg.gl.cache.color_write_mask[i] = SG_COLORMASK_RGBA;
  8449. }
  8450. _sg.gl.cache.cull_mode = SG_CULLMODE_NONE;
  8451. _sg.gl.cache.face_winding = SG_FACEWINDING_CW;
  8452. _sg.gl.cache.sample_count = 1;
  8453. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  8454. glPolygonOffset(0.0f, 0.0f);
  8455. glDisable(GL_POLYGON_OFFSET_FILL);
  8456. glDisable(GL_CULL_FACE);
  8457. glFrontFace(GL_CW);
  8458. glCullFace(GL_BACK);
  8459. glEnable(GL_SCISSOR_TEST);
  8460. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  8461. glEnable(GL_DITHER);
  8462. glDisable(GL_POLYGON_OFFSET_FILL);
  8463. _sg_stats_add(gl.num_render_state, 10);
  8464. #if defined(SOKOL_GLCORE)
  8465. glEnable(GL_MULTISAMPLE);
  8466. glEnable(GL_PROGRAM_POINT_SIZE);
  8467. _sg_stats_add(gl.num_render_state, 2);
  8468. #endif
  8469. }
  8470. _SOKOL_PRIVATE void _sg_gl_setup_backend(const sg_desc* desc) {
  8471. _SOKOL_UNUSED(desc);
  8472. // assumes that _sg.gl is already zero-initialized
  8473. _sg.gl.valid = true;
  8474. #if defined(_SOKOL_USE_WIN32_GL_LOADER)
  8475. _sg_gl_load_opengl();
  8476. #endif
  8477. // clear initial GL error state
  8478. #if defined(SOKOL_DEBUG)
  8479. while (glGetError() != GL_NO_ERROR);
  8480. #endif
  8481. #if defined(SOKOL_GLCORE)
  8482. _sg_gl_init_caps_glcore();
  8483. #elif defined(SOKOL_GLES3)
  8484. _sg_gl_init_caps_gles3();
  8485. #endif
  8486. glGenVertexArrays(1, &_sg.gl.vao);
  8487. glBindVertexArray(_sg.gl.vao);
  8488. _SG_GL_CHECK_ERROR();
  8489. // incoming texture data is generally expected to be packed tightly
  8490. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  8491. #if defined(SOKOL_GLCORE)
  8492. // enable seamless cubemap sampling (only desktop GL)
  8493. glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
  8494. #endif
  8495. _sg_gl_reset_state_cache();
  8496. }
  8497. _SOKOL_PRIVATE void _sg_gl_discard_backend(void) {
  8498. SOKOL_ASSERT(_sg.gl.valid);
  8499. if (_sg.gl.vao) {
  8500. glDeleteVertexArrays(1, &_sg.gl.vao);
  8501. }
  8502. #if defined(_SOKOL_USE_WIN32_GL_LOADER)
  8503. _sg_gl_unload_opengl();
  8504. #endif
  8505. _sg.gl.valid = false;
  8506. }
  8507. //-- GL backend resource creation and destruction ------------------------------
  8508. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  8509. SOKOL_ASSERT(buf && desc);
  8510. _SG_GL_CHECK_ERROR();
  8511. buf->gl.injected = (0 != desc->gl_buffers[0]);
  8512. const GLenum gl_target = _sg_gl_buffer_target(&buf->cmn.usage);
  8513. const GLenum gl_usage = _sg_gl_buffer_usage(&buf->cmn.usage);
  8514. for (int slot = 0; slot < buf->cmn.num_slots; slot++) {
  8515. GLuint gl_buf = 0;
  8516. if (buf->gl.injected) {
  8517. SOKOL_ASSERT(desc->gl_buffers[slot]);
  8518. gl_buf = desc->gl_buffers[slot];
  8519. } else {
  8520. glGenBuffers(1, &gl_buf);
  8521. SOKOL_ASSERT(gl_buf);
  8522. _sg_gl_cache_store_buffer_binding(gl_target);
  8523. _sg_gl_cache_bind_buffer(gl_target, gl_buf);
  8524. glBufferData(gl_target, buf->cmn.size, 0, gl_usage);
  8525. if (desc->data.ptr) {
  8526. glBufferSubData(gl_target, 0, buf->cmn.size, desc->data.ptr);
  8527. }
  8528. _sg_gl_cache_restore_buffer_binding(gl_target);
  8529. }
  8530. buf->gl.buf[slot] = gl_buf;
  8531. }
  8532. _SG_GL_CHECK_ERROR();
  8533. return SG_RESOURCESTATE_VALID;
  8534. }
  8535. _SOKOL_PRIVATE void _sg_gl_discard_buffer(_sg_buffer_t* buf) {
  8536. SOKOL_ASSERT(buf);
  8537. _SG_GL_CHECK_ERROR();
  8538. for (int slot = 0; slot < buf->cmn.num_slots; slot++) {
  8539. if (buf->gl.buf[slot]) {
  8540. _sg_gl_cache_invalidate_buffer(buf->gl.buf[slot]);
  8541. if (!buf->gl.injected) {
  8542. glDeleteBuffers(1, &buf->gl.buf[slot]);
  8543. }
  8544. }
  8545. }
  8546. _SG_GL_CHECK_ERROR();
  8547. }
  8548. _SOKOL_PRIVATE bool _sg_gl_supported_texture_format(sg_pixel_format fmt) {
  8549. const int fmt_index = (int) fmt;
  8550. SOKOL_ASSERT((fmt_index > SG_PIXELFORMAT_NONE) && (fmt_index < _SG_PIXELFORMAT_NUM));
  8551. return _sg.formats[fmt_index].sample;
  8552. }
  8553. _SOKOL_PRIVATE void _sg_gl_texstorage(const _sg_image_t* img) {
  8554. const GLenum tgt = img->gl.target;
  8555. const int num_mips = img->cmn.num_mipmaps;
  8556. #if defined(_SOKOL_GL_HAS_TEXSTORAGE)
  8557. const GLenum ifmt = _sg_gl_teximage_internal_format(img->cmn.pixel_format);
  8558. const bool msaa = img->cmn.sample_count > 1;
  8559. const int w = img->cmn.width;
  8560. const int h = img->cmn.height;
  8561. if ((SG_IMAGETYPE_2D == img->cmn.type) || (SG_IMAGETYPE_CUBE == img->cmn.type)) {
  8562. #if defined(SOKOL_GLCORE)
  8563. if (msaa) {
  8564. glTexStorage2DMultisample(tgt, img->cmn.sample_count, ifmt, w, h, GL_TRUE);
  8565. } else {
  8566. glTexStorage2D(tgt, num_mips, ifmt, w, h);
  8567. }
  8568. #else
  8569. SOKOL_ASSERT(!msaa); _SOKOL_UNUSED(msaa);
  8570. glTexStorage2D(tgt, num_mips, ifmt, w, h);
  8571. #endif
  8572. } else if ((SG_IMAGETYPE_3D == img->cmn.type) || (SG_IMAGETYPE_ARRAY == img->cmn.type)) {
  8573. const int depth = img->cmn.num_slices;
  8574. #if defined(SOKOL_GLCORE)
  8575. if (msaa) {
  8576. // NOTE: MSAA works only for array textures, not 3D textures
  8577. glTexStorage3DMultisample(tgt, img->cmn.sample_count, ifmt, w, h, depth, GL_TRUE);
  8578. } else {
  8579. glTexStorage3D(tgt, num_mips, ifmt, w, h, depth);
  8580. }
  8581. #else
  8582. SOKOL_ASSERT(!msaa); _SOKOL_UNUSED(msaa);
  8583. glTexStorage3D(tgt, num_mips, ifmt, w, h, depth);
  8584. #endif
  8585. }
  8586. #else
  8587. glTexParameteri(tgt, GL_TEXTURE_MAX_LEVEL, num_mips - 1);
  8588. #endif
  8589. _SG_GL_CHECK_ERROR();
  8590. }
  8591. _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) {
  8592. const bool compressed = _sg_is_compressed_pixel_format(img->cmn.pixel_format);
  8593. #if defined(_SOKOL_GL_HAS_TEXSTORAGE)
  8594. if (data_ptr == 0) {
  8595. return;
  8596. }
  8597. SOKOL_ASSERT(img->cmn.sample_count == 1);
  8598. if ((SG_IMAGETYPE_2D == img->cmn.type) || (SG_IMAGETYPE_CUBE == img->cmn.type)) {
  8599. if (compressed) {
  8600. const GLenum ifmt = _sg_gl_teximage_internal_format(img->cmn.pixel_format);
  8601. glCompressedTexSubImage2D(tgt, mip_index, 0, 0, w, h, ifmt, data_size, data_ptr);
  8602. } else {
  8603. const GLenum type = _sg_gl_teximage_type(img->cmn.pixel_format);
  8604. const GLenum fmt = _sg_gl_teximage_format(img->cmn.pixel_format);
  8605. glTexSubImage2D(tgt, mip_index, 0, 0, w, h, fmt, type, data_ptr);
  8606. }
  8607. } else if ((SG_IMAGETYPE_3D == img->cmn.type) || (SG_IMAGETYPE_ARRAY == img->cmn.type)) {
  8608. if (compressed) {
  8609. const GLenum ifmt = _sg_gl_teximage_internal_format(img->cmn.pixel_format);
  8610. glCompressedTexSubImage3D(tgt, mip_index, 0, 0, 0, w, h, depth, ifmt, data_size, data_ptr);
  8611. } else {
  8612. const GLenum type = _sg_gl_teximage_type(img->cmn.pixel_format);
  8613. const GLenum fmt = _sg_gl_teximage_format(img->cmn.pixel_format);
  8614. glTexSubImage3D(tgt, mip_index, 0, 0, 0, w, h, depth, fmt, type, data_ptr);
  8615. }
  8616. }
  8617. #else
  8618. const GLenum ifmt = _sg_gl_teximage_internal_format(img->cmn.pixel_format);
  8619. const bool msaa = img->cmn.sample_count > 1;
  8620. if ((SG_IMAGETYPE_2D == img->cmn.type) || (SG_IMAGETYPE_CUBE == img->cmn.type)) {
  8621. if (compressed) {
  8622. SOKOL_ASSERT(!msaa); _SOKOL_UNUSED(msaa);
  8623. glCompressedTexImage2D(tgt, mip_index, ifmt, w, h, 0, data_size, data_ptr);
  8624. } else {
  8625. const GLenum type = _sg_gl_teximage_type(img->cmn.pixel_format);
  8626. const GLenum fmt = _sg_gl_teximage_format(img->cmn.pixel_format);
  8627. #if defined(SOKOL_GLCORE)
  8628. if (msaa) {
  8629. glTexImage2DMultisample(tgt, img->cmn.sample_count, (GLint)ifmt, w, h, GL_TRUE);
  8630. } else {
  8631. glTexImage2D(tgt, mip_index, (GLint)ifmt, w, h, 0, fmt, type, data_ptr);
  8632. }
  8633. #else
  8634. SOKOL_ASSERT(!msaa); _SOKOL_UNUSED(msaa);
  8635. glTexImage2D(tgt, mip_index, (GLint)ifmt, w, h, 0, fmt, type, data_ptr);
  8636. #endif
  8637. }
  8638. } else if ((SG_IMAGETYPE_3D == img->cmn.type) || (SG_IMAGETYPE_ARRAY == img->cmn.type)) {
  8639. if (compressed) {
  8640. SOKOL_ASSERT(!msaa); _SOKOL_UNUSED(msaa);
  8641. glCompressedTexImage3D(tgt, mip_index, ifmt, w, h, depth, 0, data_size, data_ptr);
  8642. } else {
  8643. const GLenum type = _sg_gl_teximage_type(img->cmn.pixel_format);
  8644. const GLenum fmt = _sg_gl_teximage_format(img->cmn.pixel_format);
  8645. #if defined(SOKOL_GLCORE)
  8646. if (msaa) {
  8647. // NOTE: MSAA works only for array textures, not 3D textures
  8648. glTexImage3DMultisample(tgt, img->cmn.sample_count, (GLint)ifmt, w, h, depth, GL_TRUE);
  8649. } else {
  8650. glTexImage3D(tgt, mip_index, (GLint)ifmt, w, h, depth, 0, fmt, type, data_ptr);
  8651. }
  8652. #else
  8653. SOKOL_ASSERT(!msaa); _SOKOL_UNUSED(msaa);
  8654. glTexImage3D(tgt, mip_index, (GLint)ifmt, w, h, depth, 0, fmt, type, data_ptr);
  8655. #endif
  8656. }
  8657. }
  8658. #endif
  8659. _SG_GL_CHECK_ERROR();
  8660. }
  8661. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  8662. SOKOL_ASSERT(img && desc);
  8663. _SG_GL_CHECK_ERROR();
  8664. img->gl.injected = (0 != desc->gl_textures[0]);
  8665. // check if texture format is support
  8666. if (!_sg_gl_supported_texture_format(img->cmn.pixel_format)) {
  8667. _SG_ERROR(GL_TEXTURE_FORMAT_NOT_SUPPORTED);
  8668. return SG_RESOURCESTATE_FAILED;
  8669. }
  8670. // GLES3/WebGL2/macOS doesn't have support for multisampled textures, so create a render buffer object instead
  8671. const bool msaa = img->cmn.sample_count > 1;
  8672. if (!_sg.features.msaa_image_bindings && img->cmn.usage.render_attachment && msaa) {
  8673. const GLenum gl_internal_format = _sg_gl_teximage_internal_format(img->cmn.pixel_format);
  8674. glGenRenderbuffers(1, &img->gl.msaa_render_buffer);
  8675. glBindRenderbuffer(GL_RENDERBUFFER, img->gl.msaa_render_buffer);
  8676. glRenderbufferStorageMultisample(GL_RENDERBUFFER, img->cmn.sample_count, gl_internal_format, img->cmn.width, img->cmn.height);
  8677. } else if (img->gl.injected) {
  8678. img->gl.target = _sg_gl_texture_target(img->cmn.type, img->cmn.sample_count);
  8679. // inject externally GL textures
  8680. for (int slot = 0; slot < img->cmn.num_slots; slot++) {
  8681. SOKOL_ASSERT(desc->gl_textures[slot]);
  8682. img->gl.tex[slot] = desc->gl_textures[slot];
  8683. }
  8684. if (desc->gl_texture_target) {
  8685. img->gl.target = (GLenum)desc->gl_texture_target;
  8686. }
  8687. } else {
  8688. // create our own GL texture(s)
  8689. img->gl.target = _sg_gl_texture_target(img->cmn.type, img->cmn.sample_count);
  8690. for (int slot = 0; slot < img->cmn.num_slots; slot++) {
  8691. glGenTextures(1, &img->gl.tex[slot]);
  8692. SOKOL_ASSERT(img->gl.tex[slot]);
  8693. _sg_gl_cache_store_texture_sampler_binding(0);
  8694. _sg_gl_cache_bind_texture_sampler(0, img->gl.target, img->gl.tex[slot], 0);
  8695. _sg_gl_texstorage(img);
  8696. const int num_faces = img->cmn.type == SG_IMAGETYPE_CUBE ? 6 : 1;
  8697. for (int face_index = 0; face_index < num_faces; face_index++) {
  8698. for (int mip_index = 0; mip_index < img->cmn.num_mipmaps; mip_index++) {
  8699. GLenum gl_img_target = img->gl.target;
  8700. if (SG_IMAGETYPE_CUBE == img->cmn.type) {
  8701. gl_img_target = _sg_gl_cubeface_target(face_index);
  8702. }
  8703. const GLvoid* data_ptr = desc->data.subimage[face_index][mip_index].ptr;
  8704. const GLsizei data_size = (GLsizei)desc->data.subimage[face_index][mip_index].size;
  8705. const int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  8706. const int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  8707. const int mip_depth = (SG_IMAGETYPE_3D == img->cmn.type) ? _sg_miplevel_dim(img->cmn.num_slices, mip_index) : img->cmn.num_slices;
  8708. _sg_gl_teximage(img, gl_img_target, mip_index, mip_width, mip_height, mip_depth, data_ptr, data_size);
  8709. }
  8710. }
  8711. _sg_gl_cache_restore_texture_sampler_binding(0);
  8712. }
  8713. }
  8714. _SG_GL_CHECK_ERROR();
  8715. return SG_RESOURCESTATE_VALID;
  8716. }
  8717. _SOKOL_PRIVATE void _sg_gl_discard_image(_sg_image_t* img) {
  8718. SOKOL_ASSERT(img);
  8719. _SG_GL_CHECK_ERROR();
  8720. for (int slot = 0; slot < img->cmn.num_slots; slot++) {
  8721. if (img->gl.tex[slot]) {
  8722. _sg_gl_cache_invalidate_texture_sampler(img->gl.tex[slot], 0);
  8723. if (!img->gl.injected) {
  8724. glDeleteTextures(1, &img->gl.tex[slot]);
  8725. }
  8726. }
  8727. }
  8728. if (img->gl.msaa_render_buffer) {
  8729. glDeleteRenderbuffers(1, &img->gl.msaa_render_buffer);
  8730. }
  8731. _SG_GL_CHECK_ERROR();
  8732. }
  8733. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  8734. SOKOL_ASSERT(smp && desc);
  8735. _SG_GL_CHECK_ERROR();
  8736. smp->gl.injected = (0 != desc->gl_sampler);
  8737. if (smp->gl.injected) {
  8738. smp->gl.smp = (GLuint) desc->gl_sampler;
  8739. } else {
  8740. glGenSamplers(1, &smp->gl.smp);
  8741. SOKOL_ASSERT(smp->gl.smp);
  8742. const GLenum gl_min_filter = _sg_gl_min_filter(smp->cmn.min_filter, smp->cmn.mipmap_filter);
  8743. const GLenum gl_mag_filter = _sg_gl_mag_filter(smp->cmn.mag_filter);
  8744. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_MIN_FILTER, (GLint)gl_min_filter);
  8745. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_MAG_FILTER, (GLint)gl_mag_filter);
  8746. // GL spec has strange defaults for mipmap min/max lod: -1000 to +1000
  8747. const float min_lod = _sg_clamp(desc->min_lod, 0.0f, 1000.0f);
  8748. const float max_lod = _sg_clamp(desc->max_lod, 0.0f, 1000.0f);
  8749. glSamplerParameterf(smp->gl.smp, GL_TEXTURE_MIN_LOD, min_lod);
  8750. glSamplerParameterf(smp->gl.smp, GL_TEXTURE_MAX_LOD, max_lod);
  8751. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_WRAP_S, (GLint)_sg_gl_wrap(smp->cmn.wrap_u));
  8752. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_WRAP_T, (GLint)_sg_gl_wrap(smp->cmn.wrap_v));
  8753. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_WRAP_R, (GLint)_sg_gl_wrap(smp->cmn.wrap_w));
  8754. #if defined(SOKOL_GLCORE)
  8755. float border[4];
  8756. switch (smp->cmn.border_color) {
  8757. case SG_BORDERCOLOR_TRANSPARENT_BLACK:
  8758. border[0] = 0.0f; border[1] = 0.0f; border[2] = 0.0f; border[3] = 0.0f;
  8759. break;
  8760. case SG_BORDERCOLOR_OPAQUE_WHITE:
  8761. border[0] = 1.0f; border[1] = 1.0f; border[2] = 1.0f; border[3] = 1.0f;
  8762. break;
  8763. default:
  8764. border[0] = 0.0f; border[1] = 0.0f; border[2] = 0.0f; border[3] = 1.0f;
  8765. break;
  8766. }
  8767. glSamplerParameterfv(smp->gl.smp, GL_TEXTURE_BORDER_COLOR, border);
  8768. #endif
  8769. if (smp->cmn.compare != SG_COMPAREFUNC_NEVER) {
  8770. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  8771. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_COMPARE_FUNC, (GLint)_sg_gl_compare_func(smp->cmn.compare));
  8772. } else {
  8773. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  8774. }
  8775. if (_sg.gl.ext_anisotropic && (smp->cmn.max_anisotropy > 1)) {
  8776. GLint max_aniso = (GLint) smp->cmn.max_anisotropy;
  8777. if (max_aniso > _sg.gl.max_anisotropy) {
  8778. max_aniso = _sg.gl.max_anisotropy;
  8779. }
  8780. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_MAX_ANISOTROPY_EXT, max_aniso);
  8781. }
  8782. }
  8783. _SG_GL_CHECK_ERROR();
  8784. return SG_RESOURCESTATE_VALID;
  8785. }
  8786. _SOKOL_PRIVATE void _sg_gl_discard_sampler(_sg_sampler_t* smp) {
  8787. SOKOL_ASSERT(smp);
  8788. _SG_GL_CHECK_ERROR();
  8789. _sg_gl_cache_invalidate_texture_sampler(0, smp->gl.smp);
  8790. if (!smp->gl.injected) {
  8791. glDeleteSamplers(1, &smp->gl.smp);
  8792. }
  8793. _SG_GL_CHECK_ERROR();
  8794. }
  8795. _SOKOL_PRIVATE GLuint _sg_gl_compile_shader(sg_shader_stage stage, const char* src) {
  8796. SOKOL_ASSERT(src);
  8797. _SG_GL_CHECK_ERROR();
  8798. GLuint gl_shd = glCreateShader(_sg_gl_shader_stage(stage));
  8799. glShaderSource(gl_shd, 1, &src, 0);
  8800. glCompileShader(gl_shd);
  8801. GLint compile_status = 0;
  8802. glGetShaderiv(gl_shd, GL_COMPILE_STATUS, &compile_status);
  8803. if (!compile_status) {
  8804. // compilation failed, log error and delete shader
  8805. GLint log_len = 0;
  8806. glGetShaderiv(gl_shd, GL_INFO_LOG_LENGTH, &log_len);
  8807. if (log_len > 0) {
  8808. GLchar* log_buf = (GLchar*) _sg_malloc((size_t)log_len);
  8809. glGetShaderInfoLog(gl_shd, log_len, &log_len, log_buf);
  8810. _SG_ERROR(GL_SHADER_COMPILATION_FAILED);
  8811. _SG_LOGMSG(GL_SHADER_COMPILATION_FAILED, log_buf);
  8812. _sg_free(log_buf);
  8813. }
  8814. glDeleteShader(gl_shd);
  8815. gl_shd = 0;
  8816. }
  8817. _SG_GL_CHECK_ERROR();
  8818. return gl_shd;
  8819. }
  8820. // NOTE: this is an out-of-range check for GLSL bindslots that's also active in release mode
  8821. _SOKOL_PRIVATE bool _sg_gl_ensure_glsl_bindslot_ranges(const sg_shader_desc* desc) {
  8822. SOKOL_ASSERT(desc);
  8823. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  8824. if (desc->storage_buffers[i].glsl_binding_n >= _SG_GL_MAX_SBUF_BINDINGS) {
  8825. _SG_ERROR(GL_STORAGEBUFFER_GLSL_BINDING_OUT_OF_RANGE);
  8826. return false;
  8827. }
  8828. }
  8829. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  8830. if (desc->storage_images[i].glsl_binding_n >= _SG_GL_MAX_SIMG_BINDINGS) {
  8831. _SG_ERROR(GL_STORAGEIMAGE_GLSL_BINDING_OUT_OF_RANGE);
  8832. return false;
  8833. }
  8834. }
  8835. return true;
  8836. }
  8837. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  8838. SOKOL_ASSERT(shd && desc);
  8839. SOKOL_ASSERT(!shd->gl.prog);
  8840. _SG_GL_CHECK_ERROR();
  8841. // perform a fatal range-check on GLSL bindslots that's also active
  8842. // in release mode to avoid potential out-of-bounds array accesses
  8843. if (!_sg_gl_ensure_glsl_bindslot_ranges(desc)) {
  8844. return SG_RESOURCESTATE_FAILED;
  8845. }
  8846. // copy the optional vertex attribute names over
  8847. for (int i = 0; i < SG_MAX_VERTEX_ATTRIBUTES; i++) {
  8848. _sg_strcpy(&shd->gl.attrs[i].name, desc->attrs[i].glsl_name);
  8849. }
  8850. const bool has_vs = desc->vertex_func.source;
  8851. const bool has_fs = desc->fragment_func.source;
  8852. const bool has_cs = desc->compute_func.source;
  8853. SOKOL_ASSERT((has_vs && has_fs) || has_cs);
  8854. GLuint gl_prog = glCreateProgram();
  8855. if (has_vs && has_fs) {
  8856. GLuint gl_vs = _sg_gl_compile_shader(SG_SHADERSTAGE_VERTEX, desc->vertex_func.source);
  8857. GLuint gl_fs = _sg_gl_compile_shader(SG_SHADERSTAGE_FRAGMENT, desc->fragment_func.source);
  8858. if (!(gl_vs && gl_fs)) {
  8859. glDeleteProgram(gl_prog);
  8860. if (gl_vs) { glDeleteShader(gl_vs); }
  8861. if (gl_fs) { glDeleteShader(gl_fs); }
  8862. return SG_RESOURCESTATE_FAILED;
  8863. }
  8864. glAttachShader(gl_prog, gl_vs);
  8865. glAttachShader(gl_prog, gl_fs);
  8866. glLinkProgram(gl_prog);
  8867. glDeleteShader(gl_vs);
  8868. glDeleteShader(gl_fs);
  8869. _SG_GL_CHECK_ERROR();
  8870. } else if (has_cs) {
  8871. GLuint gl_cs = _sg_gl_compile_shader(SG_SHADERSTAGE_COMPUTE, desc->compute_func.source);
  8872. if (!gl_cs) {
  8873. glDeleteProgram(gl_prog);
  8874. return SG_RESOURCESTATE_FAILED;
  8875. }
  8876. glAttachShader(gl_prog, gl_cs);
  8877. glLinkProgram(gl_prog);
  8878. glDeleteShader(gl_cs);
  8879. _SG_GL_CHECK_ERROR();
  8880. } else {
  8881. SOKOL_UNREACHABLE;
  8882. }
  8883. GLint link_status;
  8884. glGetProgramiv(gl_prog, GL_LINK_STATUS, &link_status);
  8885. if (!link_status) {
  8886. GLint log_len = 0;
  8887. glGetProgramiv(gl_prog, GL_INFO_LOG_LENGTH, &log_len);
  8888. if (log_len > 0) {
  8889. GLchar* log_buf = (GLchar*) _sg_malloc((size_t)log_len);
  8890. glGetProgramInfoLog(gl_prog, log_len, &log_len, log_buf);
  8891. _SG_ERROR(GL_SHADER_LINKING_FAILED);
  8892. _SG_LOGMSG(GL_SHADER_LINKING_FAILED, log_buf);
  8893. _sg_free(log_buf);
  8894. }
  8895. glDeleteProgram(gl_prog);
  8896. return SG_RESOURCESTATE_FAILED;
  8897. }
  8898. shd->gl.prog = gl_prog;
  8899. // resolve uniforms
  8900. _SG_GL_CHECK_ERROR();
  8901. for (size_t ub_index = 0; ub_index < SG_MAX_UNIFORMBLOCK_BINDSLOTS; ub_index++) {
  8902. const sg_shader_uniform_block* ub_desc = &desc->uniform_blocks[ub_index];
  8903. if (ub_desc->stage == SG_SHADERSTAGE_NONE) {
  8904. continue;
  8905. }
  8906. SOKOL_ASSERT(ub_desc->size > 0);
  8907. _sg_gl_uniform_block_t* ub = &shd->gl.uniform_blocks[ub_index];
  8908. SOKOL_ASSERT(ub->num_uniforms == 0);
  8909. uint32_t cur_uniform_offset = 0;
  8910. for (int u_index = 0; u_index < SG_MAX_UNIFORMBLOCK_MEMBERS; u_index++) {
  8911. const sg_glsl_shader_uniform* u_desc = &ub_desc->glsl_uniforms[u_index];
  8912. if (u_desc->type == SG_UNIFORMTYPE_INVALID) {
  8913. break;
  8914. }
  8915. const uint32_t u_align = _sg_uniform_alignment(u_desc->type, u_desc->array_count, ub_desc->layout);
  8916. const uint32_t u_size = _sg_uniform_size(u_desc->type, u_desc->array_count, ub_desc->layout);
  8917. cur_uniform_offset = _sg_align_u32(cur_uniform_offset, u_align);
  8918. _sg_gl_uniform_t* u = &ub->uniforms[u_index];
  8919. u->type = u_desc->type;
  8920. u->count = (uint16_t) u_desc->array_count;
  8921. u->offset = (uint16_t) cur_uniform_offset;
  8922. SOKOL_ASSERT(u_desc->glsl_name);
  8923. u->gl_loc = glGetUniformLocation(gl_prog, u_desc->glsl_name);
  8924. if (u->gl_loc == -1) {
  8925. _SG_WARN(GL_UNIFORMBLOCK_NAME_NOT_FOUND_IN_SHADER);
  8926. _SG_LOGMSG(GL_UNIFORMBLOCK_NAME_NOT_FOUND_IN_SHADER, u_desc->glsl_name);
  8927. }
  8928. cur_uniform_offset += u_size;
  8929. ub->num_uniforms++;
  8930. }
  8931. if (ub_desc->layout == SG_UNIFORMLAYOUT_STD140) {
  8932. cur_uniform_offset = _sg_align_u32(cur_uniform_offset, 16);
  8933. }
  8934. SOKOL_ASSERT(ub_desc->size == (size_t)cur_uniform_offset);
  8935. _SOKOL_UNUSED(cur_uniform_offset);
  8936. }
  8937. // copy storage buffer bind slots
  8938. for (size_t sbuf_index = 0; sbuf_index < SG_MAX_STORAGEBUFFER_BINDSLOTS; sbuf_index++) {
  8939. const sg_shader_storage_buffer* sbuf_desc = &desc->storage_buffers[sbuf_index];
  8940. if (sbuf_desc->stage == SG_SHADERSTAGE_NONE) {
  8941. continue;
  8942. }
  8943. SOKOL_ASSERT(sbuf_desc->glsl_binding_n < _SG_GL_MAX_SBUF_BINDINGS);
  8944. shd->gl.sbuf_binding[sbuf_index] = sbuf_desc->glsl_binding_n;
  8945. }
  8946. // copy storage image bind slots
  8947. for (size_t simg_index = 0; simg_index < SG_MAX_STORAGE_ATTACHMENTS; simg_index++) {
  8948. const sg_shader_storage_image* simg_desc = &desc->storage_images[simg_index];
  8949. if (simg_desc->stage == SG_SHADERSTAGE_NONE) {
  8950. continue;
  8951. }
  8952. SOKOL_ASSERT(simg_desc->glsl_binding_n < _SG_GL_MAX_SIMG_BINDINGS);
  8953. shd->gl.simg_binding[simg_index] = simg_desc->glsl_binding_n;
  8954. }
  8955. // record image sampler location in shader program
  8956. _SG_GL_CHECK_ERROR();
  8957. GLuint cur_prog = 0;
  8958. glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&cur_prog);
  8959. glUseProgram(gl_prog);
  8960. GLint gl_tex_slot = 0;
  8961. for (size_t img_smp_index = 0; img_smp_index < SG_MAX_IMAGE_SAMPLER_PAIRS; img_smp_index++) {
  8962. const sg_shader_image_sampler_pair* img_smp_desc = &desc->image_sampler_pairs[img_smp_index];
  8963. if (img_smp_desc->stage == SG_SHADERSTAGE_NONE) {
  8964. continue;
  8965. }
  8966. SOKOL_ASSERT(img_smp_desc->glsl_name);
  8967. GLint gl_loc = glGetUniformLocation(gl_prog, img_smp_desc->glsl_name);
  8968. if (gl_loc != -1) {
  8969. glUniform1i(gl_loc, gl_tex_slot);
  8970. shd->gl.tex_slot[img_smp_index] = (int8_t)gl_tex_slot++;
  8971. } else {
  8972. shd->gl.tex_slot[img_smp_index] = -1;
  8973. _SG_WARN(GL_IMAGE_SAMPLER_NAME_NOT_FOUND_IN_SHADER);
  8974. _SG_LOGMSG(GL_IMAGE_SAMPLER_NAME_NOT_FOUND_IN_SHADER, img_smp_desc->glsl_name);
  8975. }
  8976. }
  8977. // it's legal to call glUseProgram with 0
  8978. glUseProgram(cur_prog);
  8979. _SG_GL_CHECK_ERROR();
  8980. return SG_RESOURCESTATE_VALID;
  8981. }
  8982. _SOKOL_PRIVATE void _sg_gl_discard_shader(_sg_shader_t* shd) {
  8983. SOKOL_ASSERT(shd);
  8984. _SG_GL_CHECK_ERROR();
  8985. if (shd->gl.prog) {
  8986. _sg_gl_cache_invalidate_program(shd->gl.prog);
  8987. glDeleteProgram(shd->gl.prog);
  8988. }
  8989. _SG_GL_CHECK_ERROR();
  8990. }
  8991. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_pipeline(_sg_pipeline_t* pip, const sg_pipeline_desc* desc) {
  8992. SOKOL_ASSERT(pip && desc);
  8993. SOKOL_ASSERT(_sg.limits.max_vertex_attrs <= SG_MAX_VERTEX_ATTRIBUTES);
  8994. if (pip->cmn.is_compute) {
  8995. // shortcut for compute pipelines
  8996. return SG_RESOURCESTATE_VALID;
  8997. }
  8998. pip->gl.primitive_type = desc->primitive_type;
  8999. pip->gl.depth = desc->depth;
  9000. pip->gl.stencil = desc->stencil;
  9001. // FIXME: blend color and write mask per draw-buffer-attachment (requires GL4)
  9002. pip->gl.blend = desc->colors[0].blend;
  9003. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  9004. pip->gl.color_write_mask[i] = desc->colors[i].write_mask;
  9005. }
  9006. pip->gl.cull_mode = desc->cull_mode;
  9007. pip->gl.face_winding = desc->face_winding;
  9008. pip->gl.sample_count = desc->sample_count;
  9009. pip->gl.alpha_to_coverage_enabled = desc->alpha_to_coverage_enabled;
  9010. // NOTE: GLSL compilers may remove unused vertex attributes so we can't rely
  9011. // on the 'prepopulated' vertex_buffer_layout_active[] state and need to
  9012. // fill this array from scratch with the actual info after GLSL compilation
  9013. for (int i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  9014. pip->cmn.vertex_buffer_layout_active[i] = false;
  9015. }
  9016. // resolve vertex attributes
  9017. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  9018. SOKOL_ASSERT(shd->gl.prog);
  9019. for (int attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  9020. pip->gl.attrs[attr_index].vb_index = -1;
  9021. }
  9022. for (int attr_index = 0; attr_index < _sg.limits.max_vertex_attrs; attr_index++) {
  9023. const sg_vertex_attr_state* a_state = &desc->layout.attrs[attr_index];
  9024. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  9025. break;
  9026. }
  9027. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  9028. const sg_vertex_buffer_layout_state* l_state = &desc->layout.buffers[a_state->buffer_index];
  9029. const sg_vertex_step step_func = l_state->step_func;
  9030. const int step_rate = l_state->step_rate;
  9031. GLint attr_loc = attr_index;
  9032. if (!_sg_strempty(&shd->gl.attrs[attr_index].name)) {
  9033. attr_loc = glGetAttribLocation(shd->gl.prog, _sg_strptr(&shd->gl.attrs[attr_index].name));
  9034. }
  9035. if (attr_loc != -1) {
  9036. SOKOL_ASSERT(attr_loc < (GLint)_sg.limits.max_vertex_attrs);
  9037. _sg_gl_attr_t* gl_attr = &pip->gl.attrs[attr_loc];
  9038. SOKOL_ASSERT(gl_attr->vb_index == -1);
  9039. gl_attr->vb_index = (int8_t) a_state->buffer_index;
  9040. if (step_func == SG_VERTEXSTEP_PER_VERTEX) {
  9041. gl_attr->divisor = 0;
  9042. } else {
  9043. gl_attr->divisor = (int8_t) step_rate;
  9044. pip->cmn.use_instanced_draw = true;
  9045. }
  9046. SOKOL_ASSERT(l_state->stride > 0);
  9047. gl_attr->stride = (uint8_t) l_state->stride;
  9048. gl_attr->offset = a_state->offset;
  9049. gl_attr->size = (uint8_t) _sg_gl_vertexformat_size(a_state->format);
  9050. gl_attr->type = _sg_gl_vertexformat_type(a_state->format);
  9051. gl_attr->normalized = _sg_gl_vertexformat_normalized(a_state->format);
  9052. gl_attr->base_type = _sg_vertexformat_basetype(a_state->format);
  9053. pip->cmn.vertex_buffer_layout_active[a_state->buffer_index] = true;
  9054. } else {
  9055. _SG_WARN(GL_VERTEX_ATTRIBUTE_NOT_FOUND_IN_SHADER);
  9056. _SG_LOGMSG(GL_VERTEX_ATTRIBUTE_NOT_FOUND_IN_SHADER, _sg_strptr(&shd->gl.attrs[attr_index].name));
  9057. }
  9058. }
  9059. return SG_RESOURCESTATE_VALID;
  9060. }
  9061. _SOKOL_PRIVATE void _sg_gl_discard_pipeline(_sg_pipeline_t* pip) {
  9062. SOKOL_ASSERT(pip);
  9063. _sg_gl_cache_invalidate_pipeline(pip);
  9064. }
  9065. _SOKOL_PRIVATE void _sg_gl_fb_attach_texture(const _sg_attachment_common_t* att, GLenum gl_att_type) {
  9066. const _sg_image_t* img = _sg_image_ref_ptr(&att->image);
  9067. const GLuint gl_tex = img->gl.tex[0];
  9068. SOKOL_ASSERT(gl_tex);
  9069. const GLuint gl_target = img->gl.target;
  9070. SOKOL_ASSERT(gl_target);
  9071. const int mip_level = att->mip_level;
  9072. const int slice = att->slice;
  9073. switch (img->cmn.type) {
  9074. case SG_IMAGETYPE_2D:
  9075. glFramebufferTexture2D(GL_FRAMEBUFFER, gl_att_type, gl_target, gl_tex, mip_level);
  9076. break;
  9077. case SG_IMAGETYPE_CUBE:
  9078. glFramebufferTexture2D(GL_FRAMEBUFFER, gl_att_type, _sg_gl_cubeface_target(slice), gl_tex, mip_level);
  9079. break;
  9080. default:
  9081. glFramebufferTextureLayer(GL_FRAMEBUFFER, gl_att_type, gl_tex, mip_level, slice);
  9082. break;
  9083. }
  9084. }
  9085. _SOKOL_PRIVATE GLenum _sg_gl_depth_stencil_attachment_type(const _sg_image_t* ds_img) {
  9086. if (_sg_is_depth_stencil_format(ds_img->cmn.pixel_format)) {
  9087. return GL_DEPTH_STENCIL_ATTACHMENT;
  9088. } else {
  9089. return GL_DEPTH_ATTACHMENT;
  9090. }
  9091. }
  9092. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_attachments(_sg_attachments_t* atts, const sg_attachments_desc* desc) {
  9093. SOKOL_ASSERT(atts && desc);
  9094. _SOKOL_UNUSED(desc);
  9095. _SG_GL_CHECK_ERROR();
  9096. // if this is a compute pass attachment we're done here
  9097. if (atts->cmn.has_storage_attachments) {
  9098. SOKOL_ASSERT(!atts->cmn.has_render_attachments);
  9099. return SG_RESOURCESTATE_VALID;
  9100. }
  9101. // store current framebuffer binding (restored at end of function)
  9102. GLuint gl_orig_fb;
  9103. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&gl_orig_fb);
  9104. // create a framebuffer object
  9105. glGenFramebuffers(1, &atts->gl.fb);
  9106. glBindFramebuffer(GL_FRAMEBUFFER, atts->gl.fb);
  9107. // attach color attachments to framebuffer
  9108. for (int i = 0; i < atts->cmn.num_colors; i++) {
  9109. const _sg_image_t* color_img = _sg_image_ref_ptr(&atts->cmn.colors[i].image);
  9110. const GLuint gl_msaa_render_buffer = color_img->gl.msaa_render_buffer;
  9111. if (gl_msaa_render_buffer) {
  9112. glFramebufferRenderbuffer(GL_FRAMEBUFFER, (GLenum)(GL_COLOR_ATTACHMENT0+i), GL_RENDERBUFFER, gl_msaa_render_buffer);
  9113. } else {
  9114. const GLenum gl_att_type = (GLenum)(GL_COLOR_ATTACHMENT0 + i);
  9115. _sg_gl_fb_attach_texture(&atts->cmn.colors[i], gl_att_type);
  9116. }
  9117. }
  9118. // attach depth-stencil attachment
  9119. if (!_sg_image_ref_null(&atts->cmn.depth_stencil.image)) {
  9120. const _sg_image_t* ds_img = _sg_image_ref_ptr(&atts->cmn.depth_stencil.image);
  9121. const GLenum gl_att_type = _sg_gl_depth_stencil_attachment_type(ds_img);
  9122. const GLuint gl_msaa_render_buffer = ds_img->gl.msaa_render_buffer;
  9123. if (gl_msaa_render_buffer) {
  9124. glFramebufferRenderbuffer(GL_FRAMEBUFFER, gl_att_type, GL_RENDERBUFFER, gl_msaa_render_buffer);
  9125. } else {
  9126. _sg_gl_fb_attach_texture(&atts->cmn.depth_stencil, gl_att_type);
  9127. }
  9128. }
  9129. // check if framebuffer is complete
  9130. {
  9131. const GLenum fb_status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  9132. if (fb_status != GL_FRAMEBUFFER_COMPLETE) {
  9133. switch (fb_status) {
  9134. case GL_FRAMEBUFFER_UNDEFINED:
  9135. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNDEFINED);
  9136. break;
  9137. case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  9138. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_ATTACHMENT);
  9139. break;
  9140. case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  9141. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MISSING_ATTACHMENT);
  9142. break;
  9143. case GL_FRAMEBUFFER_UNSUPPORTED:
  9144. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNSUPPORTED);
  9145. break;
  9146. case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
  9147. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MULTISAMPLE);
  9148. break;
  9149. default:
  9150. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNKNOWN);
  9151. break;
  9152. }
  9153. return SG_RESOURCESTATE_FAILED;
  9154. }
  9155. }
  9156. // setup color attachments for the framebuffer
  9157. static const GLenum gl_draw_bufs[SG_MAX_COLOR_ATTACHMENTS] = {
  9158. GL_COLOR_ATTACHMENT0,
  9159. GL_COLOR_ATTACHMENT1,
  9160. GL_COLOR_ATTACHMENT2,
  9161. GL_COLOR_ATTACHMENT3
  9162. };
  9163. glDrawBuffers(atts->cmn.num_colors, gl_draw_bufs);
  9164. // create MSAA resolve framebuffers if necessary
  9165. for (int i = 0; i < atts->cmn.num_colors; i++) {
  9166. _sg_attachment_common_t* cmn_resolve_att = &atts->cmn.resolves[i];
  9167. if (!_sg_image_ref_null(&cmn_resolve_att->image)) {
  9168. SOKOL_ASSERT(0 == atts->gl.msaa_resolve_framebuffer[i]);
  9169. glGenFramebuffers(1, &atts->gl.msaa_resolve_framebuffer[i]);
  9170. glBindFramebuffer(GL_FRAMEBUFFER, atts->gl.msaa_resolve_framebuffer[i]);
  9171. _sg_gl_fb_attach_texture(cmn_resolve_att, GL_COLOR_ATTACHMENT0);
  9172. // check if framebuffer is complete
  9173. const GLenum fb_status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  9174. if (fb_status != GL_FRAMEBUFFER_COMPLETE) {
  9175. switch (fb_status) {
  9176. case GL_FRAMEBUFFER_UNDEFINED:
  9177. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNDEFINED);
  9178. break;
  9179. case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  9180. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_ATTACHMENT);
  9181. break;
  9182. case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  9183. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MISSING_ATTACHMENT);
  9184. break;
  9185. case GL_FRAMEBUFFER_UNSUPPORTED:
  9186. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNSUPPORTED);
  9187. break;
  9188. case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
  9189. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MULTISAMPLE);
  9190. break;
  9191. default:
  9192. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNKNOWN);
  9193. break;
  9194. }
  9195. return SG_RESOURCESTATE_FAILED;
  9196. }
  9197. // setup color attachments for the framebuffer
  9198. glDrawBuffers(1, &gl_draw_bufs[0]);
  9199. }
  9200. }
  9201. // restore original framebuffer binding
  9202. glBindFramebuffer(GL_FRAMEBUFFER, gl_orig_fb);
  9203. _SG_GL_CHECK_ERROR();
  9204. return SG_RESOURCESTATE_VALID;
  9205. }
  9206. _SOKOL_PRIVATE void _sg_gl_discard_attachments(_sg_attachments_t* atts) {
  9207. SOKOL_ASSERT(atts);
  9208. _SG_GL_CHECK_ERROR();
  9209. if (0 != atts->gl.fb) {
  9210. glDeleteFramebuffers(1, &atts->gl.fb);
  9211. }
  9212. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  9213. if (atts->gl.msaa_resolve_framebuffer[i]) {
  9214. glDeleteFramebuffers(1, &atts->gl.msaa_resolve_framebuffer[i]);
  9215. }
  9216. }
  9217. _SG_GL_CHECK_ERROR();
  9218. }
  9219. _SOKOL_PRIVATE void _sg_gl_begin_pass(const sg_pass* pass) {
  9220. // FIXME: what if a texture used as render target is still bound, should we
  9221. // unbind all currently bound textures in begin pass?
  9222. SOKOL_ASSERT(pass);
  9223. _SG_GL_CHECK_ERROR();
  9224. const _sg_attachments_t* atts = _sg_attachments_ref_ptr_or_null(&_sg.cur_pass.atts);
  9225. // early out if this a compute pass
  9226. if (pass->compute) {
  9227. // first pipeline in pass needs to re-apply storage attachments
  9228. if (atts && atts->cmn.has_storage_attachments) {
  9229. _sg.gl.cache.cur_pip = _sg_sref(0);
  9230. }
  9231. return;
  9232. }
  9233. const sg_swapchain* swapchain = &pass->swapchain;
  9234. const sg_pass_action* action = &pass->action;
  9235. // bind the render pass framebuffer
  9236. //
  9237. // FIXME: Disabling SRGB conversion for the default framebuffer is
  9238. // a crude hack to make behaviour for sRGB render target textures
  9239. // identical with the Metal and D3D11 swapchains created by sokol-app.
  9240. //
  9241. // This will need a cleaner solution (e.g. allowing to configure
  9242. // sokol_app.h with an sRGB or RGB framebuffer.
  9243. if (atts) {
  9244. // offscreen pass
  9245. SOKOL_ASSERT(atts->gl.fb);
  9246. #if defined(SOKOL_GLCORE)
  9247. glEnable(GL_FRAMEBUFFER_SRGB);
  9248. #endif
  9249. glBindFramebuffer(GL_FRAMEBUFFER, atts->gl.fb);
  9250. } else {
  9251. // default pass
  9252. #if defined(SOKOL_GLCORE)
  9253. glDisable(GL_FRAMEBUFFER_SRGB);
  9254. #endif
  9255. // NOTE: on some platforms, the default framebuffer of a context
  9256. // is null, so we can't actually assert here that the
  9257. // framebuffer has been provided
  9258. glBindFramebuffer(GL_FRAMEBUFFER, swapchain->gl.framebuffer);
  9259. }
  9260. glViewport(0, 0, _sg.cur_pass.width, _sg.cur_pass.height);
  9261. glScissor(0, 0, _sg.cur_pass.width, _sg.cur_pass.height);
  9262. // number of color attachments
  9263. const int num_color_atts = atts ? atts->cmn.num_colors : 1;
  9264. // clear color and depth-stencil attachments if needed
  9265. bool clear_any_color = false;
  9266. for (int i = 0; i < num_color_atts; i++) {
  9267. if (SG_LOADACTION_CLEAR == action->colors[i].load_action) {
  9268. clear_any_color = true;
  9269. break;
  9270. }
  9271. }
  9272. const bool clear_depth = (action->depth.load_action == SG_LOADACTION_CLEAR);
  9273. const bool clear_stencil = (action->stencil.load_action == SG_LOADACTION_CLEAR);
  9274. bool need_pip_cache_flush = false;
  9275. if (clear_any_color) {
  9276. bool need_color_mask_flush = false;
  9277. // NOTE: not a bug to iterate over all possible color attachments
  9278. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  9279. if (SG_COLORMASK_RGBA != _sg.gl.cache.color_write_mask[i]) {
  9280. need_pip_cache_flush = true;
  9281. need_color_mask_flush = true;
  9282. _sg.gl.cache.color_write_mask[i] = SG_COLORMASK_RGBA;
  9283. }
  9284. }
  9285. if (need_color_mask_flush) {
  9286. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  9287. }
  9288. }
  9289. if (clear_depth) {
  9290. if (!_sg.gl.cache.depth.write_enabled) {
  9291. need_pip_cache_flush = true;
  9292. _sg.gl.cache.depth.write_enabled = true;
  9293. glDepthMask(GL_TRUE);
  9294. }
  9295. if (_sg.gl.cache.depth.compare != SG_COMPAREFUNC_ALWAYS) {
  9296. need_pip_cache_flush = true;
  9297. _sg.gl.cache.depth.compare = SG_COMPAREFUNC_ALWAYS;
  9298. glDepthFunc(GL_ALWAYS);
  9299. }
  9300. }
  9301. if (clear_stencil) {
  9302. if (_sg.gl.cache.stencil.write_mask != 0xFF) {
  9303. need_pip_cache_flush = true;
  9304. _sg.gl.cache.stencil.write_mask = 0xFF;
  9305. glStencilMask(0xFF);
  9306. }
  9307. }
  9308. if (need_pip_cache_flush) {
  9309. // we messed with the state cache directly, need to clear cached
  9310. // pipeline to force re-evaluation in next sg_apply_pipeline()
  9311. _sg.gl.cache.cur_pip = _sg_sref(0);
  9312. }
  9313. for (int i = 0; i < num_color_atts; i++) {
  9314. if (action->colors[i].load_action == SG_LOADACTION_CLEAR) {
  9315. glClearBufferfv(GL_COLOR, i, &action->colors[i].clear_value.r);
  9316. }
  9317. }
  9318. if ((atts == 0) || !_sg_image_ref_null(&atts->cmn.depth_stencil.image)) {
  9319. if (clear_depth && clear_stencil) {
  9320. glClearBufferfi(GL_DEPTH_STENCIL, 0, action->depth.clear_value, action->stencil.clear_value);
  9321. } else if (clear_depth) {
  9322. glClearBufferfv(GL_DEPTH, 0, &action->depth.clear_value);
  9323. } else if (clear_stencil) {
  9324. GLint val = (GLint) action->stencil.clear_value;
  9325. glClearBufferiv(GL_STENCIL, 0, &val);
  9326. }
  9327. }
  9328. // keep store actions for end-pass
  9329. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  9330. _sg.gl.color_store_actions[i] = action->colors[i].store_action;
  9331. }
  9332. _sg.gl.depth_store_action = action->depth.store_action;
  9333. _sg.gl.stencil_store_action = action->stencil.store_action;
  9334. _SG_GL_CHECK_ERROR();
  9335. }
  9336. _SOKOL_PRIVATE void _sg_gl_end_render_pass(void) {
  9337. const _sg_attachments_t* atts = _sg_attachments_ref_ptr_or_null(&_sg.cur_pass.atts);
  9338. if (atts) {
  9339. bool fb_read_bound = false;
  9340. bool fb_draw_bound = false;
  9341. const int num_color_atts = atts->cmn.num_colors;
  9342. for (int i = 0; i < num_color_atts; i++) {
  9343. // perform MSAA resolve if needed
  9344. if (atts->gl.msaa_resolve_framebuffer[i] != 0) {
  9345. if (!fb_read_bound) {
  9346. SOKOL_ASSERT(atts->gl.fb);
  9347. glBindFramebuffer(GL_READ_FRAMEBUFFER, atts->gl.fb);
  9348. fb_read_bound = true;
  9349. }
  9350. const _sg_image_t* img = _sg_image_ref_ptr(&atts->cmn.colors[i].image);
  9351. const int w = img->cmn.width;
  9352. const int h = img->cmn.height;
  9353. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, atts->gl.msaa_resolve_framebuffer[i]);
  9354. glReadBuffer((GLenum)(GL_COLOR_ATTACHMENT0 + i));
  9355. glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  9356. fb_draw_bound = true;
  9357. }
  9358. }
  9359. // invalidate framebuffers
  9360. _SOKOL_UNUSED(fb_draw_bound);
  9361. #if defined(SOKOL_GLES3)
  9362. // need to restore framebuffer binding before invalidate if the MSAA resolve had changed the binding
  9363. if (fb_draw_bound) {
  9364. glBindFramebuffer(GL_FRAMEBUFFER, atts->gl.fb);
  9365. }
  9366. GLenum invalidate_atts[SG_MAX_COLOR_ATTACHMENTS + 2] = { 0 };
  9367. int att_index = 0;
  9368. for (int i = 0; i < num_color_atts; i++) {
  9369. if (_sg.gl.color_store_actions[i] == SG_STOREACTION_DONTCARE) {
  9370. invalidate_atts[att_index++] = (GLenum)(GL_COLOR_ATTACHMENT0 + i);
  9371. }
  9372. }
  9373. if (!_sg_image_ref_null(&atts->cmn.depth_stencil.image)) {
  9374. if (_sg.gl.depth_store_action == SG_STOREACTION_DONTCARE) {
  9375. invalidate_atts[att_index++] = GL_DEPTH_ATTACHMENT;
  9376. }
  9377. if (_sg.gl.stencil_store_action == SG_STOREACTION_DONTCARE) {
  9378. invalidate_atts[att_index++] = GL_STENCIL_ATTACHMENT;
  9379. }
  9380. }
  9381. if (att_index > 0) {
  9382. glInvalidateFramebuffer(GL_DRAW_FRAMEBUFFER, att_index, invalidate_atts);
  9383. }
  9384. #endif
  9385. }
  9386. }
  9387. _SOKOL_PRIVATE void _sg_gl_end_compute_pass(void) {
  9388. #if defined(_SOKOL_GL_HAS_COMPUTE)
  9389. const _sg_attachments_t* atts = _sg_attachments_ref_ptr_or_null(&_sg.cur_pass.atts);
  9390. if (atts && atts->cmn.has_storage_attachments) {
  9391. glMemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT|GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
  9392. }
  9393. #endif
  9394. }
  9395. _SOKOL_PRIVATE void _sg_gl_end_pass(void) {
  9396. _SG_GL_CHECK_ERROR();
  9397. if (_sg.cur_pass.is_compute) {
  9398. _sg_gl_end_compute_pass();
  9399. } else {
  9400. _sg_gl_end_render_pass();
  9401. }
  9402. _SG_GL_CHECK_ERROR();
  9403. }
  9404. _SOKOL_PRIVATE void _sg_gl_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  9405. y = origin_top_left ? (_sg.cur_pass.height - (y+h)) : y;
  9406. glViewport(x, y, w, h);
  9407. }
  9408. _SOKOL_PRIVATE void _sg_gl_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  9409. y = origin_top_left ? (_sg.cur_pass.height - (y+h)) : y;
  9410. glScissor(x, y, w, h);
  9411. }
  9412. _SOKOL_PRIVATE void _sg_gl_apply_render_pipeline_state(_sg_pipeline_t* pip) {
  9413. // update render pipeline state
  9414. _sg.gl.cache.cur_primitive_type = _sg_gl_primitive_type(pip->gl.primitive_type);
  9415. _sg.gl.cache.cur_index_type = _sg_gl_index_type(pip->cmn.index_type);
  9416. // update depth state
  9417. {
  9418. const sg_depth_state* state_ds = &pip->gl.depth;
  9419. sg_depth_state* cache_ds = &_sg.gl.cache.depth;
  9420. if (state_ds->compare != cache_ds->compare) {
  9421. cache_ds->compare = state_ds->compare;
  9422. glDepthFunc(_sg_gl_compare_func(state_ds->compare));
  9423. _sg_stats_add(gl.num_render_state, 1);
  9424. }
  9425. if (state_ds->write_enabled != cache_ds->write_enabled) {
  9426. cache_ds->write_enabled = state_ds->write_enabled;
  9427. glDepthMask(state_ds->write_enabled);
  9428. _sg_stats_add(gl.num_render_state, 1);
  9429. }
  9430. if (!_sg_fequal(state_ds->bias, cache_ds->bias, 0.000001f) ||
  9431. !_sg_fequal(state_ds->bias_slope_scale, cache_ds->bias_slope_scale, 0.000001f))
  9432. {
  9433. /* according to ANGLE's D3D11 backend:
  9434. D3D11 SlopeScaledDepthBias ==> GL polygonOffsetFactor
  9435. D3D11 DepthBias ==> GL polygonOffsetUnits
  9436. DepthBiasClamp has no meaning on GL
  9437. */
  9438. cache_ds->bias = state_ds->bias;
  9439. cache_ds->bias_slope_scale = state_ds->bias_slope_scale;
  9440. glPolygonOffset(state_ds->bias_slope_scale, state_ds->bias);
  9441. _sg_stats_add(gl.num_render_state, 1);
  9442. bool po_enabled = true;
  9443. if (_sg_fequal(state_ds->bias, 0.0f, 0.000001f) &&
  9444. _sg_fequal(state_ds->bias_slope_scale, 0.0f, 0.000001f))
  9445. {
  9446. po_enabled = false;
  9447. }
  9448. if (po_enabled != _sg.gl.cache.polygon_offset_enabled) {
  9449. _sg.gl.cache.polygon_offset_enabled = po_enabled;
  9450. if (po_enabled) {
  9451. glEnable(GL_POLYGON_OFFSET_FILL);
  9452. } else {
  9453. glDisable(GL_POLYGON_OFFSET_FILL);
  9454. }
  9455. _sg_stats_add(gl.num_render_state, 1);
  9456. }
  9457. }
  9458. }
  9459. // update stencil state
  9460. {
  9461. const sg_stencil_state* state_ss = &pip->gl.stencil;
  9462. sg_stencil_state* cache_ss = &_sg.gl.cache.stencil;
  9463. if (state_ss->enabled != cache_ss->enabled) {
  9464. cache_ss->enabled = state_ss->enabled;
  9465. if (state_ss->enabled) {
  9466. glEnable(GL_STENCIL_TEST);
  9467. } else {
  9468. glDisable(GL_STENCIL_TEST);
  9469. }
  9470. _sg_stats_add(gl.num_render_state, 1);
  9471. }
  9472. if (state_ss->write_mask != cache_ss->write_mask) {
  9473. cache_ss->write_mask = state_ss->write_mask;
  9474. glStencilMask(state_ss->write_mask);
  9475. _sg_stats_add(gl.num_render_state, 1);
  9476. }
  9477. for (int i = 0; i < 2; i++) {
  9478. const sg_stencil_face_state* state_sfs = (i==0)? &state_ss->front : &state_ss->back;
  9479. sg_stencil_face_state* cache_sfs = (i==0)? &cache_ss->front : &cache_ss->back;
  9480. GLenum gl_face = (i==0)? GL_FRONT : GL_BACK;
  9481. if ((state_sfs->compare != cache_sfs->compare) ||
  9482. (state_ss->read_mask != cache_ss->read_mask) ||
  9483. (state_ss->ref != cache_ss->ref))
  9484. {
  9485. cache_sfs->compare = state_sfs->compare;
  9486. glStencilFuncSeparate(gl_face,
  9487. _sg_gl_compare_func(state_sfs->compare),
  9488. state_ss->ref,
  9489. state_ss->read_mask);
  9490. _sg_stats_add(gl.num_render_state, 1);
  9491. }
  9492. if ((state_sfs->fail_op != cache_sfs->fail_op) ||
  9493. (state_sfs->depth_fail_op != cache_sfs->depth_fail_op) ||
  9494. (state_sfs->pass_op != cache_sfs->pass_op))
  9495. {
  9496. cache_sfs->fail_op = state_sfs->fail_op;
  9497. cache_sfs->depth_fail_op = state_sfs->depth_fail_op;
  9498. cache_sfs->pass_op = state_sfs->pass_op;
  9499. glStencilOpSeparate(gl_face,
  9500. _sg_gl_stencil_op(state_sfs->fail_op),
  9501. _sg_gl_stencil_op(state_sfs->depth_fail_op),
  9502. _sg_gl_stencil_op(state_sfs->pass_op));
  9503. _sg_stats_add(gl.num_render_state, 1);
  9504. }
  9505. }
  9506. cache_ss->read_mask = state_ss->read_mask;
  9507. cache_ss->ref = state_ss->ref;
  9508. }
  9509. if (pip->cmn.color_count > 0) {
  9510. // update blend state
  9511. // FIXME: separate blend state per color attachment
  9512. const sg_blend_state* state_bs = &pip->gl.blend;
  9513. sg_blend_state* cache_bs = &_sg.gl.cache.blend;
  9514. if (state_bs->enabled != cache_bs->enabled) {
  9515. cache_bs->enabled = state_bs->enabled;
  9516. if (state_bs->enabled) {
  9517. glEnable(GL_BLEND);
  9518. } else {
  9519. glDisable(GL_BLEND);
  9520. }
  9521. _sg_stats_add(gl.num_render_state, 1);
  9522. }
  9523. if ((state_bs->src_factor_rgb != cache_bs->src_factor_rgb) ||
  9524. (state_bs->dst_factor_rgb != cache_bs->dst_factor_rgb) ||
  9525. (state_bs->src_factor_alpha != cache_bs->src_factor_alpha) ||
  9526. (state_bs->dst_factor_alpha != cache_bs->dst_factor_alpha))
  9527. {
  9528. cache_bs->src_factor_rgb = state_bs->src_factor_rgb;
  9529. cache_bs->dst_factor_rgb = state_bs->dst_factor_rgb;
  9530. cache_bs->src_factor_alpha = state_bs->src_factor_alpha;
  9531. cache_bs->dst_factor_alpha = state_bs->dst_factor_alpha;
  9532. glBlendFuncSeparate(_sg_gl_blend_factor(state_bs->src_factor_rgb),
  9533. _sg_gl_blend_factor(state_bs->dst_factor_rgb),
  9534. _sg_gl_blend_factor(state_bs->src_factor_alpha),
  9535. _sg_gl_blend_factor(state_bs->dst_factor_alpha));
  9536. _sg_stats_add(gl.num_render_state, 1);
  9537. }
  9538. if ((state_bs->op_rgb != cache_bs->op_rgb) || (state_bs->op_alpha != cache_bs->op_alpha)) {
  9539. cache_bs->op_rgb = state_bs->op_rgb;
  9540. cache_bs->op_alpha = state_bs->op_alpha;
  9541. glBlendEquationSeparate(_sg_gl_blend_op(state_bs->op_rgb), _sg_gl_blend_op(state_bs->op_alpha));
  9542. _sg_stats_add(gl.num_render_state, 1);
  9543. }
  9544. // standalone color target state
  9545. for (GLuint i = 0; i < (GLuint)pip->cmn.color_count; i++) {
  9546. if (pip->gl.color_write_mask[i] != _sg.gl.cache.color_write_mask[i]) {
  9547. const sg_color_mask cm = pip->gl.color_write_mask[i];
  9548. _sg.gl.cache.color_write_mask[i] = cm;
  9549. #ifdef SOKOL_GLCORE
  9550. glColorMaski(i,
  9551. (cm & SG_COLORMASK_R) != 0,
  9552. (cm & SG_COLORMASK_G) != 0,
  9553. (cm & SG_COLORMASK_B) != 0,
  9554. (cm & SG_COLORMASK_A) != 0);
  9555. #else
  9556. if (0 == i) {
  9557. glColorMask((cm & SG_COLORMASK_R) != 0,
  9558. (cm & SG_COLORMASK_G) != 0,
  9559. (cm & SG_COLORMASK_B) != 0,
  9560. (cm & SG_COLORMASK_A) != 0);
  9561. }
  9562. #endif
  9563. _sg_stats_add(gl.num_render_state, 1);
  9564. }
  9565. }
  9566. if (!_sg_fequal(pip->cmn.blend_color.r, _sg.gl.cache.blend_color.r, 0.0001f) ||
  9567. !_sg_fequal(pip->cmn.blend_color.g, _sg.gl.cache.blend_color.g, 0.0001f) ||
  9568. !_sg_fequal(pip->cmn.blend_color.b, _sg.gl.cache.blend_color.b, 0.0001f) ||
  9569. !_sg_fequal(pip->cmn.blend_color.a, _sg.gl.cache.blend_color.a, 0.0001f))
  9570. {
  9571. sg_color c = pip->cmn.blend_color;
  9572. _sg.gl.cache.blend_color = c;
  9573. glBlendColor(c.r, c.g, c.b, c.a);
  9574. _sg_stats_add(gl.num_render_state, 1);
  9575. }
  9576. } // pip->cmn.color_count > 0
  9577. if (pip->gl.cull_mode != _sg.gl.cache.cull_mode) {
  9578. _sg.gl.cache.cull_mode = pip->gl.cull_mode;
  9579. if (SG_CULLMODE_NONE == pip->gl.cull_mode) {
  9580. glDisable(GL_CULL_FACE);
  9581. _sg_stats_add(gl.num_render_state, 1);
  9582. } else {
  9583. glEnable(GL_CULL_FACE);
  9584. GLenum gl_mode = (SG_CULLMODE_FRONT == pip->gl.cull_mode) ? GL_FRONT : GL_BACK;
  9585. glCullFace(gl_mode);
  9586. _sg_stats_add(gl.num_render_state, 2);
  9587. }
  9588. }
  9589. if (pip->gl.face_winding != _sg.gl.cache.face_winding) {
  9590. _sg.gl.cache.face_winding = pip->gl.face_winding;
  9591. GLenum gl_winding = (SG_FACEWINDING_CW == pip->gl.face_winding) ? GL_CW : GL_CCW;
  9592. glFrontFace(gl_winding);
  9593. _sg_stats_add(gl.num_render_state, 1);
  9594. }
  9595. if (pip->gl.alpha_to_coverage_enabled != _sg.gl.cache.alpha_to_coverage_enabled) {
  9596. _sg.gl.cache.alpha_to_coverage_enabled = pip->gl.alpha_to_coverage_enabled;
  9597. if (pip->gl.alpha_to_coverage_enabled) {
  9598. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  9599. } else {
  9600. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  9601. }
  9602. _sg_stats_add(gl.num_render_state, 1);
  9603. }
  9604. #ifdef SOKOL_GLCORE
  9605. if (pip->gl.sample_count != _sg.gl.cache.sample_count) {
  9606. _sg.gl.cache.sample_count = pip->gl.sample_count;
  9607. if (pip->gl.sample_count > 1) {
  9608. glEnable(GL_MULTISAMPLE);
  9609. } else {
  9610. glDisable(GL_MULTISAMPLE);
  9611. }
  9612. _sg_stats_add(gl.num_render_state, 1);
  9613. }
  9614. #endif
  9615. }
  9616. _SOKOL_PRIVATE void _sg_gl_apply_compute_pipeline_state(_sg_pipeline_t* pip) {
  9617. #if defined(_SOKOL_GL_HAS_COMPUTE)
  9618. // apply storage attachment images (if any)
  9619. const _sg_attachments_t* atts = _sg_attachments_ref_ptr_or_null(&_sg.cur_pass.atts);
  9620. if (atts) {
  9621. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  9622. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  9623. if (shd->cmn.storage_images[i].stage == SG_SHADERSTAGE_NONE) {
  9624. continue;
  9625. }
  9626. SOKOL_ASSERT(shd->cmn.storage_images[i].stage == SG_SHADERSTAGE_COMPUTE);
  9627. SOKOL_ASSERT(shd->gl.simg_binding[i] < _SG_GL_MAX_SIMG_BINDINGS);
  9628. _sg_image_t* img = _sg_image_ref_ptr(&atts->cmn.storages[i].image);
  9629. GLuint gl_unit = shd->gl.simg_binding[i];
  9630. GLuint gl_tex = img->gl.tex[img->cmn.active_slot];
  9631. GLint level = atts->cmn.storages[i].mip_level;
  9632. GLint layer = atts->cmn.storages[i].slice;
  9633. GLboolean layered = shd->cmn.storage_images[i].image_type != SG_IMAGETYPE_2D;
  9634. GLenum access = shd->cmn.storage_images[i].writeonly ? GL_WRITE_ONLY : GL_READ_WRITE;
  9635. GLenum format = _sg_gl_teximage_internal_format(shd->cmn.storage_images[i].access_format);
  9636. // FIXME: go through state cache, use attachment id as key
  9637. glBindImageTexture(gl_unit, gl_tex, level, layered, layer, access, format);
  9638. _SG_GL_CHECK_ERROR();
  9639. }
  9640. }
  9641. #else
  9642. _SOKOL_UNUSED(pip);
  9643. #endif
  9644. }
  9645. _SOKOL_PRIVATE void _sg_gl_apply_pipeline(_sg_pipeline_t* pip) {
  9646. SOKOL_ASSERT(pip);
  9647. _SG_GL_CHECK_ERROR();
  9648. if (!_sg_sref_eql(&_sg.gl.cache.cur_pip, &pip->slot)) {
  9649. _sg.gl.cache.cur_pip = _sg_sref(&pip->slot);
  9650. // bind shader program
  9651. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  9652. if (shd->gl.prog != _sg.gl.cache.prog) {
  9653. _sg.gl.cache.prog = shd->gl.prog;
  9654. glUseProgram(shd->gl.prog);
  9655. _sg_stats_add(gl.num_use_program, 1);
  9656. }
  9657. if (pip->cmn.is_compute) {
  9658. _sg_gl_apply_compute_pipeline_state(pip);
  9659. } else {
  9660. _sg_gl_apply_render_pipeline_state(pip);
  9661. }
  9662. }
  9663. _SG_GL_CHECK_ERROR();
  9664. }
  9665. #if defined(_SOKOL_GL_HAS_COMPUTE)
  9666. _SOKOL_PRIVATE void _sg_gl_handle_memory_barriers(const _sg_shader_t* shd, const _sg_bindings_ptrs_t* bnd) {
  9667. if (!_sg.features.compute) {
  9668. return;
  9669. }
  9670. GLbitfield gl_barrier_bits = 0;
  9671. // if vertex-, index- or storage-buffer bindings have been written
  9672. // by a compute shader before, a barrier must be issued
  9673. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  9674. _sg_buffer_t* buf = bnd->vbs[i];
  9675. if (!buf) {
  9676. continue;
  9677. }
  9678. if (buf->gl.gpu_dirty_flags & _SG_GL_GPUDIRTY_VERTEXBUFFER) {
  9679. gl_barrier_bits |= GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT;
  9680. buf->gl.gpu_dirty_flags &= (uint8_t)~_SG_GL_GPUDIRTY_VERTEXBUFFER;
  9681. }
  9682. }
  9683. if (bnd->ib) {
  9684. _sg_buffer_t* buf = bnd->ib;
  9685. if (buf->gl.gpu_dirty_flags & _SG_GL_GPUDIRTY_INDEXBUFFER) {
  9686. gl_barrier_bits |= GL_ELEMENT_ARRAY_BARRIER_BIT;
  9687. buf->gl.gpu_dirty_flags &= (uint8_t)~_SG_GL_GPUDIRTY_INDEXBUFFER;
  9688. }
  9689. }
  9690. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  9691. _sg_buffer_t* buf = bnd->sbufs[i];
  9692. if (!buf) {
  9693. continue;
  9694. }
  9695. SOKOL_ASSERT(shd->cmn.storage_buffers[i].stage != SG_SHADERSTAGE_NONE);
  9696. if (buf->gl.gpu_dirty_flags & _SG_GL_GPUDIRTY_STORAGEBUFFER) {
  9697. gl_barrier_bits |= GL_SHADER_STORAGE_BARRIER_BIT;
  9698. buf->gl.gpu_dirty_flags &= (uint8_t)~_SG_GL_GPUDIRTY_STORAGEBUFFER;
  9699. }
  9700. }
  9701. // mark storage buffers as dirty which will be written by compute shaders
  9702. // (don't merge this into the above loop, this would mess up the dirty
  9703. // dirty flags if the same buffer is bound multiple times)
  9704. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  9705. _sg_buffer_t* buf = bnd->sbufs[i];
  9706. if (!buf) {
  9707. continue;
  9708. }
  9709. if (!shd->cmn.storage_buffers[i].readonly) {
  9710. buf->gl.gpu_dirty_flags = _SG_GL_GPUDIRTY_BUFFER_ALL;
  9711. }
  9712. }
  9713. if (0 != gl_barrier_bits) {
  9714. glMemoryBarrier(gl_barrier_bits);
  9715. _sg_stats_add(gl.num_memory_barriers, 1);
  9716. }
  9717. }
  9718. #endif
  9719. _SOKOL_PRIVATE bool _sg_gl_apply_bindings(_sg_bindings_ptrs_t* bnd) {
  9720. SOKOL_ASSERT(bnd);
  9721. SOKOL_ASSERT(bnd->pip);
  9722. _SG_GL_CHECK_ERROR();
  9723. const _sg_shader_t* shd = _sg_shader_ref_ptr(&bnd->pip->cmn.shader);
  9724. // bind combined image-samplers
  9725. _SG_GL_CHECK_ERROR();
  9726. for (size_t img_smp_index = 0; img_smp_index < SG_MAX_IMAGE_SAMPLER_PAIRS; img_smp_index++) {
  9727. const _sg_shader_image_sampler_t* img_smp = &shd->cmn.image_samplers[img_smp_index];
  9728. if (img_smp->stage == SG_SHADERSTAGE_NONE) {
  9729. continue;
  9730. }
  9731. const int8_t gl_tex_slot = (GLint)shd->gl.tex_slot[img_smp_index];
  9732. if (gl_tex_slot != -1) {
  9733. SOKOL_ASSERT(img_smp->image_slot < SG_MAX_IMAGE_BINDSLOTS);
  9734. SOKOL_ASSERT(img_smp->sampler_slot < SG_MAX_SAMPLER_BINDSLOTS);
  9735. const _sg_image_t* img = bnd->imgs[img_smp->image_slot];
  9736. const _sg_sampler_t* smp = bnd->smps[img_smp->sampler_slot];
  9737. SOKOL_ASSERT(img);
  9738. SOKOL_ASSERT(smp);
  9739. const GLenum gl_tgt = img->gl.target;
  9740. const GLuint gl_tex = img->gl.tex[img->cmn.active_slot];
  9741. const GLuint gl_smp = smp->gl.smp;
  9742. _sg_gl_cache_bind_texture_sampler(gl_tex_slot, gl_tgt, gl_tex, gl_smp);
  9743. }
  9744. }
  9745. _SG_GL_CHECK_ERROR();
  9746. // bind storage buffers
  9747. for (size_t sbuf_index = 0; sbuf_index < SG_MAX_STORAGEBUFFER_BINDSLOTS; sbuf_index++) {
  9748. if (shd->cmn.storage_buffers[sbuf_index].stage == SG_SHADERSTAGE_NONE) {
  9749. continue;
  9750. }
  9751. const _sg_buffer_t* sbuf = bnd->sbufs[sbuf_index];
  9752. const uint8_t binding = shd->gl.sbuf_binding[sbuf_index];
  9753. GLuint gl_sbuf = sbuf->gl.buf[sbuf->cmn.active_slot];
  9754. _sg_gl_cache_bind_storage_buffer(binding, gl_sbuf);
  9755. }
  9756. _SG_GL_CHECK_ERROR();
  9757. if (!bnd->pip->cmn.is_compute) {
  9758. // index buffer (can be 0)
  9759. const GLuint gl_ib = bnd->ib ? bnd->ib->gl.buf[bnd->ib->cmn.active_slot] : 0;
  9760. _sg_gl_cache_bind_buffer(GL_ELEMENT_ARRAY_BUFFER, gl_ib);
  9761. _sg.gl.cache.cur_ib_offset = bnd->ib_offset;
  9762. // vertex attributes
  9763. for (GLuint attr_index = 0; attr_index < (GLuint)_sg.limits.max_vertex_attrs; attr_index++) {
  9764. _sg_gl_attr_t* attr = &bnd->pip->gl.attrs[attr_index];
  9765. _sg_gl_cache_attr_t* cache_attr = &_sg.gl.cache.attrs[attr_index];
  9766. bool cache_attr_dirty = false;
  9767. int vb_offset = 0;
  9768. GLuint gl_vb = 0;
  9769. if (attr->vb_index >= 0) {
  9770. // attribute is enabled
  9771. SOKOL_ASSERT(attr->vb_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  9772. _sg_buffer_t* vb = bnd->vbs[attr->vb_index];
  9773. SOKOL_ASSERT(vb);
  9774. gl_vb = vb->gl.buf[vb->cmn.active_slot];
  9775. vb_offset = bnd->vb_offsets[attr->vb_index] + attr->offset;
  9776. if ((gl_vb != cache_attr->gl_vbuf) ||
  9777. (attr->size != cache_attr->gl_attr.size) ||
  9778. (attr->type != cache_attr->gl_attr.type) ||
  9779. (attr->normalized != cache_attr->gl_attr.normalized) ||
  9780. (attr->base_type != cache_attr->gl_attr.base_type) ||
  9781. (attr->stride != cache_attr->gl_attr.stride) ||
  9782. (vb_offset != cache_attr->gl_attr.offset) ||
  9783. (cache_attr->gl_attr.divisor != attr->divisor))
  9784. {
  9785. _sg_gl_cache_bind_buffer(GL_ARRAY_BUFFER, gl_vb);
  9786. if (attr->base_type == SG_SHADERATTRBASETYPE_FLOAT) {
  9787. glVertexAttribPointer(attr_index, attr->size, attr->type, attr->normalized, attr->stride, (const GLvoid*)(GLintptr)vb_offset);
  9788. } else {
  9789. glVertexAttribIPointer(attr_index, attr->size, attr->type, attr->stride, (const GLvoid*)(GLintptr)vb_offset);
  9790. }
  9791. _sg_stats_add(gl.num_vertex_attrib_pointer, 1);
  9792. glVertexAttribDivisor(attr_index, (GLuint)attr->divisor);
  9793. _sg_stats_add(gl.num_vertex_attrib_divisor, 1);
  9794. cache_attr_dirty = true;
  9795. }
  9796. if (cache_attr->gl_attr.vb_index == -1) {
  9797. glEnableVertexAttribArray(attr_index);
  9798. _sg_stats_add(gl.num_enable_vertex_attrib_array, 1);
  9799. cache_attr_dirty = true;
  9800. }
  9801. } else {
  9802. // attribute is disabled
  9803. if (cache_attr->gl_attr.vb_index != -1) {
  9804. glDisableVertexAttribArray(attr_index);
  9805. _sg_stats_add(gl.num_disable_vertex_attrib_array, 1);
  9806. cache_attr_dirty = true;
  9807. }
  9808. }
  9809. if (cache_attr_dirty) {
  9810. cache_attr->gl_attr = *attr;
  9811. cache_attr->gl_attr.offset = vb_offset;
  9812. cache_attr->gl_vbuf = gl_vb;
  9813. }
  9814. }
  9815. _SG_GL_CHECK_ERROR();
  9816. }
  9817. // take care of storage buffer memory barriers (this needs to happen after the bindings are set)
  9818. #if defined(_SOKOL_GL_HAS_COMPUTE)
  9819. _sg_gl_handle_memory_barriers(shd, bnd);
  9820. _SG_GL_CHECK_ERROR();
  9821. #endif
  9822. return true;
  9823. }
  9824. _SOKOL_PRIVATE void _sg_gl_apply_uniforms(int ub_slot, const sg_range* data) {
  9825. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  9826. const _sg_pipeline_t* pip = _sg_pipeline_ref_ptr(&_sg.cur_pip);
  9827. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  9828. SOKOL_ASSERT(SG_SHADERSTAGE_NONE != shd->cmn.uniform_blocks[ub_slot].stage);
  9829. SOKOL_ASSERT(data->size == shd->cmn.uniform_blocks[ub_slot].size);
  9830. const _sg_gl_uniform_block_t* gl_ub = &shd->gl.uniform_blocks[ub_slot];
  9831. for (int u_index = 0; u_index < gl_ub->num_uniforms; u_index++) {
  9832. const _sg_gl_uniform_t* u = &gl_ub->uniforms[u_index];
  9833. SOKOL_ASSERT(u->type != SG_UNIFORMTYPE_INVALID);
  9834. if (u->gl_loc == -1) {
  9835. continue;
  9836. }
  9837. _sg_stats_add(gl.num_uniform, 1);
  9838. GLfloat* fptr = (GLfloat*) (((uint8_t*)data->ptr) + u->offset);
  9839. GLint* iptr = (GLint*) (((uint8_t*)data->ptr) + u->offset);
  9840. switch (u->type) {
  9841. case SG_UNIFORMTYPE_INVALID:
  9842. break;
  9843. case SG_UNIFORMTYPE_FLOAT:
  9844. glUniform1fv(u->gl_loc, u->count, fptr);
  9845. break;
  9846. case SG_UNIFORMTYPE_FLOAT2:
  9847. glUniform2fv(u->gl_loc, u->count, fptr);
  9848. break;
  9849. case SG_UNIFORMTYPE_FLOAT3:
  9850. glUniform3fv(u->gl_loc, u->count, fptr);
  9851. break;
  9852. case SG_UNIFORMTYPE_FLOAT4:
  9853. glUniform4fv(u->gl_loc, u->count, fptr);
  9854. break;
  9855. case SG_UNIFORMTYPE_INT:
  9856. glUniform1iv(u->gl_loc, u->count, iptr);
  9857. break;
  9858. case SG_UNIFORMTYPE_INT2:
  9859. glUniform2iv(u->gl_loc, u->count, iptr);
  9860. break;
  9861. case SG_UNIFORMTYPE_INT3:
  9862. glUniform3iv(u->gl_loc, u->count, iptr);
  9863. break;
  9864. case SG_UNIFORMTYPE_INT4:
  9865. glUniform4iv(u->gl_loc, u->count, iptr);
  9866. break;
  9867. case SG_UNIFORMTYPE_MAT4:
  9868. glUniformMatrix4fv(u->gl_loc, u->count, GL_FALSE, fptr);
  9869. break;
  9870. default:
  9871. SOKOL_UNREACHABLE;
  9872. break;
  9873. }
  9874. }
  9875. }
  9876. _SOKOL_PRIVATE void _sg_gl_draw(int base_element, int num_elements, int num_instances) {
  9877. const GLenum i_type = _sg.gl.cache.cur_index_type;
  9878. const GLenum p_type = _sg.gl.cache.cur_primitive_type;
  9879. const bool use_instanced_draw = (num_instances > 1) || _sg_pipeline_ref_ptr(&_sg.cur_pip)->cmn.use_instanced_draw;
  9880. if (0 != i_type) {
  9881. // indexed rendering
  9882. const int i_size = (i_type == GL_UNSIGNED_SHORT) ? 2 : 4;
  9883. const int ib_offset = _sg.gl.cache.cur_ib_offset;
  9884. const GLvoid* indices = (const GLvoid*)(GLintptr)(base_element*i_size+ib_offset);
  9885. if (use_instanced_draw) {
  9886. glDrawElementsInstanced(p_type, num_elements, i_type, indices, num_instances);
  9887. } else {
  9888. glDrawElements(p_type, num_elements, i_type, indices);
  9889. }
  9890. } else {
  9891. // non-indexed rendering
  9892. if (use_instanced_draw) {
  9893. glDrawArraysInstanced(p_type, base_element, num_elements, num_instances);
  9894. } else {
  9895. glDrawArrays(p_type, base_element, num_elements);
  9896. }
  9897. }
  9898. }
  9899. _SOKOL_PRIVATE void _sg_gl_dispatch(int num_groups_x, int num_groups_y, int num_groups_z) {
  9900. #if defined(_SOKOL_GL_HAS_COMPUTE)
  9901. if (!_sg.features.compute) {
  9902. return;
  9903. }
  9904. glDispatchCompute((GLuint)num_groups_x, (GLuint)num_groups_y, (GLuint)num_groups_z);
  9905. #else
  9906. (void)num_groups_x; (void)num_groups_y; (void)num_groups_z;
  9907. #endif
  9908. }
  9909. _SOKOL_PRIVATE void _sg_gl_commit(void) {
  9910. // "soft" clear bindings (only those that are actually bound)
  9911. _sg_gl_cache_clear_buffer_bindings(false);
  9912. _sg_gl_cache_clear_texture_sampler_bindings(false);
  9913. }
  9914. _SOKOL_PRIVATE void _sg_gl_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  9915. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  9916. // only one update per buffer per frame allowed
  9917. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  9918. buf->cmn.active_slot = 0;
  9919. }
  9920. GLenum gl_tgt = _sg_gl_buffer_target(&buf->cmn.usage);
  9921. SOKOL_ASSERT(buf->cmn.active_slot < SG_NUM_INFLIGHT_FRAMES);
  9922. GLuint gl_buf = buf->gl.buf[buf->cmn.active_slot];
  9923. SOKOL_ASSERT(gl_buf);
  9924. _SG_GL_CHECK_ERROR();
  9925. _sg_gl_cache_store_buffer_binding(gl_tgt);
  9926. _sg_gl_cache_bind_buffer(gl_tgt, gl_buf);
  9927. glBufferSubData(gl_tgt, 0, (GLsizeiptr)data->size, data->ptr);
  9928. _sg_gl_cache_restore_buffer_binding(gl_tgt);
  9929. _SG_GL_CHECK_ERROR();
  9930. }
  9931. _SOKOL_PRIVATE void _sg_gl_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  9932. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  9933. if (new_frame) {
  9934. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  9935. buf->cmn.active_slot = 0;
  9936. }
  9937. }
  9938. GLenum gl_tgt = _sg_gl_buffer_target(&buf->cmn.usage);
  9939. SOKOL_ASSERT(buf->cmn.active_slot < SG_NUM_INFLIGHT_FRAMES);
  9940. GLuint gl_buf = buf->gl.buf[buf->cmn.active_slot];
  9941. SOKOL_ASSERT(gl_buf);
  9942. _SG_GL_CHECK_ERROR();
  9943. _sg_gl_cache_store_buffer_binding(gl_tgt);
  9944. _sg_gl_cache_bind_buffer(gl_tgt, gl_buf);
  9945. glBufferSubData(gl_tgt, buf->cmn.append_pos, (GLsizeiptr)data->size, data->ptr);
  9946. _sg_gl_cache_restore_buffer_binding(gl_tgt);
  9947. _SG_GL_CHECK_ERROR();
  9948. }
  9949. _SOKOL_PRIVATE void _sg_gl_update_image(_sg_image_t* img, const sg_image_data* data) {
  9950. SOKOL_ASSERT(img && data);
  9951. // only one update per image per frame allowed
  9952. if (++img->cmn.active_slot >= img->cmn.num_slots) {
  9953. img->cmn.active_slot = 0;
  9954. }
  9955. SOKOL_ASSERT(img->cmn.active_slot < SG_NUM_INFLIGHT_FRAMES);
  9956. SOKOL_ASSERT(0 != img->gl.tex[img->cmn.active_slot]);
  9957. _sg_gl_cache_store_texture_sampler_binding(0);
  9958. _sg_gl_cache_bind_texture_sampler(0, img->gl.target, img->gl.tex[img->cmn.active_slot], 0);
  9959. const GLenum gl_img_format = _sg_gl_teximage_format(img->cmn.pixel_format);
  9960. const GLenum gl_img_type = _sg_gl_teximage_type(img->cmn.pixel_format);
  9961. const int num_faces = img->cmn.type == SG_IMAGETYPE_CUBE ? 6 : 1;
  9962. const int num_mips = img->cmn.num_mipmaps;
  9963. for (int face_index = 0; face_index < num_faces; face_index++) {
  9964. for (int mip_index = 0; mip_index < num_mips; mip_index++) {
  9965. GLenum gl_img_target = img->gl.target;
  9966. if (SG_IMAGETYPE_CUBE == img->cmn.type) {
  9967. gl_img_target = _sg_gl_cubeface_target(face_index);
  9968. }
  9969. const GLvoid* data_ptr = data->subimage[face_index][mip_index].ptr;
  9970. int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  9971. int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  9972. if ((SG_IMAGETYPE_2D == img->cmn.type) || (SG_IMAGETYPE_CUBE == img->cmn.type)) {
  9973. glTexSubImage2D(gl_img_target, mip_index,
  9974. 0, 0,
  9975. mip_width, mip_height,
  9976. gl_img_format, gl_img_type,
  9977. data_ptr);
  9978. } else if ((SG_IMAGETYPE_3D == img->cmn.type) || (SG_IMAGETYPE_ARRAY == img->cmn.type)) {
  9979. int mip_depth = img->cmn.num_slices;
  9980. if (SG_IMAGETYPE_3D == img->cmn.type) {
  9981. mip_depth = _sg_miplevel_dim(img->cmn.num_slices, mip_index);
  9982. }
  9983. glTexSubImage3D(gl_img_target, mip_index,
  9984. 0, 0, 0,
  9985. mip_width, mip_height, mip_depth,
  9986. gl_img_format, gl_img_type,
  9987. data_ptr);
  9988. }
  9989. }
  9990. }
  9991. _sg_gl_cache_restore_texture_sampler_binding(0);
  9992. }
  9993. // ██████ ██████ ██████ ██ ██ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  9994. // ██ ██ ██ ██ ██ ███ ███ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  9995. // ██ ██ █████ ██ ██ ██ ██ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  9996. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  9997. // ██████ ██████ ██████ ██ ██ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  9998. //
  9999. // >>d3d11 backend
  10000. #elif defined(SOKOL_D3D11)
  10001. #if defined(__cplusplus)
  10002. #define _sg_d3d11_AddRef(self) (self)->AddRef()
  10003. #else
  10004. #define _sg_d3d11_AddRef(self) (self)->lpVtbl->AddRef(self)
  10005. #endif
  10006. #if defined(__cplusplus)
  10007. #define _sg_d3d11_Release(self) (self)->Release()
  10008. #else
  10009. #define _sg_d3d11_Release(self) (self)->lpVtbl->Release(self)
  10010. #endif
  10011. // NOTE: This needs to be a macro since we can't use the polymorphism in C. It's called on many kinds of resources.
  10012. // NOTE: Based on microsoft docs, it's fine to call this with pData=NULL if DataSize is also zero.
  10013. #if defined(__cplusplus)
  10014. #define _sg_d3d11_SetPrivateData(self, guid, DataSize, pData) (self)->SetPrivateData(guid, DataSize, pData)
  10015. #else
  10016. #define _sg_d3d11_SetPrivateData(self, guid, DataSize, pData) (self)->lpVtbl->SetPrivateData(self, guid, DataSize, pData)
  10017. #endif
  10018. #if defined(__cplusplus)
  10019. #define _sg_win32_refguid(guid) guid
  10020. #else
  10021. #define _sg_win32_refguid(guid) &guid
  10022. #endif
  10023. static const GUID _sg_d3d11_WKPDID_D3DDebugObjectName = { 0x429b8c22,0x9188,0x4b0c, {0x87,0x42,0xac,0xb0,0xbf,0x85,0xc2,0x00} };
  10024. #if defined(SOKOL_DEBUG)
  10025. #define _sg_d3d11_setlabel(self, label) _sg_d3d11_SetPrivateData(self, _sg_win32_refguid(_sg_d3d11_WKPDID_D3DDebugObjectName), label ? (UINT)strlen(label) : 0, label)
  10026. #else
  10027. #define _sg_d3d11_setlabel(self, label)
  10028. #endif
  10029. //-- D3D11 C/C++ wrappers ------------------------------------------------------
  10030. static inline HRESULT _sg_d3d11_CheckFormatSupport(ID3D11Device* self, DXGI_FORMAT Format, UINT* pFormatSupport) {
  10031. #if defined(__cplusplus)
  10032. return self->CheckFormatSupport(Format, pFormatSupport);
  10033. #else
  10034. return self->lpVtbl->CheckFormatSupport(self, Format, pFormatSupport);
  10035. #endif
  10036. }
  10037. static inline void _sg_d3d11_OMSetRenderTargets(ID3D11DeviceContext* self, UINT NumViews, ID3D11RenderTargetView* const* ppRenderTargetViews, ID3D11DepthStencilView *pDepthStencilView) {
  10038. #if defined(__cplusplus)
  10039. self->OMSetRenderTargets(NumViews, ppRenderTargetViews, pDepthStencilView);
  10040. #else
  10041. self->lpVtbl->OMSetRenderTargets(self, NumViews, ppRenderTargetViews, pDepthStencilView);
  10042. #endif
  10043. }
  10044. static inline void _sg_d3d11_RSSetState(ID3D11DeviceContext* self, ID3D11RasterizerState* pRasterizerState) {
  10045. #if defined(__cplusplus)
  10046. self->RSSetState(pRasterizerState);
  10047. #else
  10048. self->lpVtbl->RSSetState(self, pRasterizerState);
  10049. #endif
  10050. }
  10051. static inline void _sg_d3d11_OMSetDepthStencilState(ID3D11DeviceContext* self, ID3D11DepthStencilState* pDepthStencilState, UINT StencilRef) {
  10052. #if defined(__cplusplus)
  10053. self->OMSetDepthStencilState(pDepthStencilState, StencilRef);
  10054. #else
  10055. self->lpVtbl->OMSetDepthStencilState(self, pDepthStencilState, StencilRef);
  10056. #endif
  10057. }
  10058. static inline void _sg_d3d11_OMSetBlendState(ID3D11DeviceContext* self, ID3D11BlendState* pBlendState, const FLOAT BlendFactor[4], UINT SampleMask) {
  10059. #if defined(__cplusplus)
  10060. self->OMSetBlendState(pBlendState, BlendFactor, SampleMask);
  10061. #else
  10062. self->lpVtbl->OMSetBlendState(self, pBlendState, BlendFactor, SampleMask);
  10063. #endif
  10064. }
  10065. static inline void _sg_d3d11_IASetVertexBuffers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppVertexBuffers, const UINT* pStrides, const UINT* pOffsets) {
  10066. #if defined(__cplusplus)
  10067. self->IASetVertexBuffers(StartSlot, NumBuffers, ppVertexBuffers, pStrides, pOffsets);
  10068. #else
  10069. self->lpVtbl->IASetVertexBuffers(self, StartSlot, NumBuffers, ppVertexBuffers, pStrides, pOffsets);
  10070. #endif
  10071. }
  10072. static inline void _sg_d3d11_IASetIndexBuffer(ID3D11DeviceContext* self, ID3D11Buffer* pIndexBuffer, DXGI_FORMAT Format, UINT Offset) {
  10073. #if defined(__cplusplus)
  10074. self->IASetIndexBuffer(pIndexBuffer, Format, Offset);
  10075. #else
  10076. self->lpVtbl->IASetIndexBuffer(self, pIndexBuffer, Format, Offset);
  10077. #endif
  10078. }
  10079. static inline void _sg_d3d11_IASetInputLayout(ID3D11DeviceContext* self, ID3D11InputLayout* pInputLayout) {
  10080. #if defined(__cplusplus)
  10081. self->IASetInputLayout(pInputLayout);
  10082. #else
  10083. self->lpVtbl->IASetInputLayout(self, pInputLayout);
  10084. #endif
  10085. }
  10086. static inline void _sg_d3d11_VSSetShader(ID3D11DeviceContext* self, ID3D11VertexShader* pVertexShader, ID3D11ClassInstance* const* ppClassInstances, UINT NumClassInstances) {
  10087. #if defined(__cplusplus)
  10088. self->VSSetShader(pVertexShader, ppClassInstances, NumClassInstances);
  10089. #else
  10090. self->lpVtbl->VSSetShader(self, pVertexShader, ppClassInstances, NumClassInstances);
  10091. #endif
  10092. }
  10093. static inline void _sg_d3d11_PSSetShader(ID3D11DeviceContext* self, ID3D11PixelShader* pPixelShader, ID3D11ClassInstance* const* ppClassInstances, UINT NumClassInstances) {
  10094. #if defined(__cplusplus)
  10095. self->PSSetShader(pPixelShader, ppClassInstances, NumClassInstances);
  10096. #else
  10097. self->lpVtbl->PSSetShader(self, pPixelShader, ppClassInstances, NumClassInstances);
  10098. #endif
  10099. }
  10100. static inline void _sg_d3d11_CSSetShader(ID3D11DeviceContext* self, ID3D11ComputeShader* pComputeShader, ID3D11ClassInstance* const* ppClassInstances, UINT NumClassInstances) {
  10101. #if defined(__cplusplus)
  10102. self->CSSetShader(pComputeShader, ppClassInstances, NumClassInstances);
  10103. #else
  10104. self->lpVtbl->CSSetShader(self, pComputeShader, ppClassInstances, NumClassInstances);
  10105. #endif
  10106. }
  10107. static inline void _sg_d3d11_VSSetConstantBuffers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppConstantBuffers) {
  10108. #if defined(__cplusplus)
  10109. self->VSSetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers);
  10110. #else
  10111. self->lpVtbl->VSSetConstantBuffers(self, StartSlot, NumBuffers, ppConstantBuffers);
  10112. #endif
  10113. }
  10114. static inline void _sg_d3d11_PSSetConstantBuffers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppConstantBuffers) {
  10115. #if defined(__cplusplus)
  10116. self->PSSetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers);
  10117. #else
  10118. self->lpVtbl->PSSetConstantBuffers(self, StartSlot, NumBuffers, ppConstantBuffers);
  10119. #endif
  10120. }
  10121. static inline void _sg_d3d11_CSSetConstantBuffers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppConstantBuffers) {
  10122. #if defined(__cplusplus)
  10123. self->CSSetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers);
  10124. #else
  10125. self->lpVtbl->CSSetConstantBuffers(self, StartSlot, NumBuffers, ppConstantBuffers);
  10126. #endif
  10127. }
  10128. static inline void _sg_d3d11_VSSetShaderResources(ID3D11DeviceContext* self, UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView* const* ppShaderResourceViews) {
  10129. #if defined(__cplusplus)
  10130. self->VSSetShaderResources(StartSlot, NumViews, ppShaderResourceViews);
  10131. #else
  10132. self->lpVtbl->VSSetShaderResources(self, StartSlot, NumViews, ppShaderResourceViews);
  10133. #endif
  10134. }
  10135. static inline void _sg_d3d11_PSSetShaderResources(ID3D11DeviceContext* self, UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView* const* ppShaderResourceViews) {
  10136. #if defined(__cplusplus)
  10137. self->PSSetShaderResources(StartSlot, NumViews, ppShaderResourceViews);
  10138. #else
  10139. self->lpVtbl->PSSetShaderResources(self, StartSlot, NumViews, ppShaderResourceViews);
  10140. #endif
  10141. }
  10142. static inline void _sg_d3d11_CSSetShaderResources(ID3D11DeviceContext* self, UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView* const* ppShaderResourceViews) {
  10143. #if defined(__cplusplus)
  10144. self->CSSetShaderResources(StartSlot, NumViews, ppShaderResourceViews);
  10145. #else
  10146. self->lpVtbl->CSSetShaderResources(self, StartSlot, NumViews, ppShaderResourceViews);
  10147. #endif
  10148. }
  10149. static inline void _sg_d3d11_VSSetSamplers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumSamplers, ID3D11SamplerState* const* ppSamplers) {
  10150. #if defined(__cplusplus)
  10151. self->VSSetSamplers(StartSlot, NumSamplers, ppSamplers);
  10152. #else
  10153. self->lpVtbl->VSSetSamplers(self, StartSlot, NumSamplers, ppSamplers);
  10154. #endif
  10155. }
  10156. static inline void _sg_d3d11_PSSetSamplers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumSamplers, ID3D11SamplerState* const* ppSamplers) {
  10157. #if defined(__cplusplus)
  10158. self->PSSetSamplers(StartSlot, NumSamplers, ppSamplers);
  10159. #else
  10160. self->lpVtbl->PSSetSamplers(self, StartSlot, NumSamplers, ppSamplers);
  10161. #endif
  10162. }
  10163. static inline void _sg_d3d11_CSSetSamplers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumSamplers, ID3D11SamplerState* const* ppSamplers) {
  10164. #if defined(__cplusplus)
  10165. self->CSSetSamplers(StartSlot, NumSamplers, ppSamplers);
  10166. #else
  10167. self->lpVtbl->CSSetSamplers(self, StartSlot, NumSamplers, ppSamplers);
  10168. #endif
  10169. }
  10170. static inline void _sg_d3d11_CSSetUnorderedAccessViews(ID3D11DeviceContext* self, UINT StartSlot, UINT NumUAVs, ID3D11UnorderedAccessView* const* ppUnorderedAccessViews, const UINT* pUAVInitialCounts) {
  10171. #if defined(__cplusplus)
  10172. self->CSSetUnorderedAccessViews(StartSlot, NumUAVs, ppUnorderedAccessViews, pUAVInitialCounts);
  10173. #else
  10174. self->lpVtbl->CSSetUnorderedAccessViews(self, StartSlot, NumUAVs, ppUnorderedAccessViews, pUAVInitialCounts);
  10175. #endif
  10176. }
  10177. static inline HRESULT _sg_d3d11_CreateBuffer(ID3D11Device* self, const D3D11_BUFFER_DESC* pDesc, const D3D11_SUBRESOURCE_DATA* pInitialData, ID3D11Buffer** ppBuffer) {
  10178. #if defined(__cplusplus)
  10179. return self->CreateBuffer(pDesc, pInitialData, ppBuffer);
  10180. #else
  10181. return self->lpVtbl->CreateBuffer(self, pDesc, pInitialData, ppBuffer);
  10182. #endif
  10183. }
  10184. static inline HRESULT _sg_d3d11_CreateTexture2D(ID3D11Device* self, const D3D11_TEXTURE2D_DESC* pDesc, const D3D11_SUBRESOURCE_DATA* pInitialData, ID3D11Texture2D** ppTexture2D) {
  10185. #if defined(__cplusplus)
  10186. return self->CreateTexture2D(pDesc, pInitialData, ppTexture2D);
  10187. #else
  10188. return self->lpVtbl->CreateTexture2D(self, pDesc, pInitialData, ppTexture2D);
  10189. #endif
  10190. }
  10191. static inline HRESULT _sg_d3d11_CreateShaderResourceView(ID3D11Device* self, ID3D11Resource* pResource, const D3D11_SHADER_RESOURCE_VIEW_DESC* pDesc, ID3D11ShaderResourceView** ppSRView) {
  10192. #if defined(__cplusplus)
  10193. return self->CreateShaderResourceView(pResource, pDesc, ppSRView);
  10194. #else
  10195. return self->lpVtbl->CreateShaderResourceView(self, pResource, pDesc, ppSRView);
  10196. #endif
  10197. }
  10198. static inline HRESULT _sg_d3d11_CreateUnorderedAccessView(ID3D11Device* self, ID3D11Resource* pResource, const D3D11_UNORDERED_ACCESS_VIEW_DESC* pDesc, ID3D11UnorderedAccessView** ppUAVView) {
  10199. #if defined(__cplusplus)
  10200. return self->CreateUnorderedAccessView(pResource, pDesc, ppUAVView);
  10201. #else
  10202. return self->lpVtbl->CreateUnorderedAccessView(self, pResource, pDesc, ppUAVView);
  10203. #endif
  10204. }
  10205. static inline void _sg_d3d11_GetResource(ID3D11View* self, ID3D11Resource** ppResource) {
  10206. #if defined(__cplusplus)
  10207. self->GetResource(ppResource);
  10208. #else
  10209. self->lpVtbl->GetResource(self, ppResource);
  10210. #endif
  10211. }
  10212. static inline HRESULT _sg_d3d11_CreateTexture3D(ID3D11Device* self, const D3D11_TEXTURE3D_DESC* pDesc, const D3D11_SUBRESOURCE_DATA* pInitialData, ID3D11Texture3D** ppTexture3D) {
  10213. #if defined(__cplusplus)
  10214. return self->CreateTexture3D(pDesc, pInitialData, ppTexture3D);
  10215. #else
  10216. return self->lpVtbl->CreateTexture3D(self, pDesc, pInitialData, ppTexture3D);
  10217. #endif
  10218. }
  10219. static inline HRESULT _sg_d3d11_CreateSamplerState(ID3D11Device* self, const D3D11_SAMPLER_DESC* pSamplerDesc, ID3D11SamplerState** ppSamplerState) {
  10220. #if defined(__cplusplus)
  10221. return self->CreateSamplerState(pSamplerDesc, ppSamplerState);
  10222. #else
  10223. return self->lpVtbl->CreateSamplerState(self, pSamplerDesc, ppSamplerState);
  10224. #endif
  10225. }
  10226. static inline LPVOID _sg_d3d11_GetBufferPointer(ID3D10Blob* self) {
  10227. #if defined(__cplusplus)
  10228. return self->GetBufferPointer();
  10229. #else
  10230. return self->lpVtbl->GetBufferPointer(self);
  10231. #endif
  10232. }
  10233. static inline SIZE_T _sg_d3d11_GetBufferSize(ID3D10Blob* self) {
  10234. #if defined(__cplusplus)
  10235. return self->GetBufferSize();
  10236. #else
  10237. return self->lpVtbl->GetBufferSize(self);
  10238. #endif
  10239. }
  10240. static inline HRESULT _sg_d3d11_CreateVertexShader(ID3D11Device* self, const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage, ID3D11VertexShader** ppVertexShader) {
  10241. #if defined(__cplusplus)
  10242. return self->CreateVertexShader(pShaderBytecode, BytecodeLength, pClassLinkage, ppVertexShader);
  10243. #else
  10244. return self->lpVtbl->CreateVertexShader(self, pShaderBytecode, BytecodeLength, pClassLinkage, ppVertexShader);
  10245. #endif
  10246. }
  10247. static inline HRESULT _sg_d3d11_CreatePixelShader(ID3D11Device* self, const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage, ID3D11PixelShader** ppPixelShader) {
  10248. #if defined(__cplusplus)
  10249. return self->CreatePixelShader(pShaderBytecode, BytecodeLength, pClassLinkage, ppPixelShader);
  10250. #else
  10251. return self->lpVtbl->CreatePixelShader(self, pShaderBytecode, BytecodeLength, pClassLinkage, ppPixelShader);
  10252. #endif
  10253. }
  10254. static inline HRESULT _sg_d3d11_CreateComputeShader(ID3D11Device* self, const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage, ID3D11ComputeShader** ppComputeShader) {
  10255. #if defined(__cplusplus)
  10256. return self->CreateComputeShader(pShaderBytecode, BytecodeLength, pClassLinkage, ppComputeShader);
  10257. #else
  10258. return self->lpVtbl->CreateComputeShader(self, pShaderBytecode, BytecodeLength, pClassLinkage, ppComputeShader);
  10259. #endif
  10260. }
  10261. static inline HRESULT _sg_d3d11_CreateInputLayout(ID3D11Device* self, const D3D11_INPUT_ELEMENT_DESC* pInputElementDescs, UINT NumElements, const void* pShaderBytecodeWithInputSignature, SIZE_T BytecodeLength, ID3D11InputLayout **ppInputLayout) {
  10262. #if defined(__cplusplus)
  10263. return self->CreateInputLayout(pInputElementDescs, NumElements, pShaderBytecodeWithInputSignature, BytecodeLength, ppInputLayout);
  10264. #else
  10265. return self->lpVtbl->CreateInputLayout(self, pInputElementDescs, NumElements, pShaderBytecodeWithInputSignature, BytecodeLength, ppInputLayout);
  10266. #endif
  10267. }
  10268. static inline HRESULT _sg_d3d11_CreateRasterizerState(ID3D11Device* self, const D3D11_RASTERIZER_DESC* pRasterizerDesc, ID3D11RasterizerState** ppRasterizerState) {
  10269. #if defined(__cplusplus)
  10270. return self->CreateRasterizerState(pRasterizerDesc, ppRasterizerState);
  10271. #else
  10272. return self->lpVtbl->CreateRasterizerState(self, pRasterizerDesc, ppRasterizerState);
  10273. #endif
  10274. }
  10275. static inline HRESULT _sg_d3d11_CreateDepthStencilState(ID3D11Device* self, const D3D11_DEPTH_STENCIL_DESC* pDepthStencilDesc, ID3D11DepthStencilState** ppDepthStencilState) {
  10276. #if defined(__cplusplus)
  10277. return self->CreateDepthStencilState(pDepthStencilDesc, ppDepthStencilState);
  10278. #else
  10279. return self->lpVtbl->CreateDepthStencilState(self, pDepthStencilDesc, ppDepthStencilState);
  10280. #endif
  10281. }
  10282. static inline HRESULT _sg_d3d11_CreateBlendState(ID3D11Device* self, const D3D11_BLEND_DESC* pBlendStateDesc, ID3D11BlendState** ppBlendState) {
  10283. #if defined(__cplusplus)
  10284. return self->CreateBlendState(pBlendStateDesc, ppBlendState);
  10285. #else
  10286. return self->lpVtbl->CreateBlendState(self, pBlendStateDesc, ppBlendState);
  10287. #endif
  10288. }
  10289. static inline HRESULT _sg_d3d11_CreateRenderTargetView(ID3D11Device* self, ID3D11Resource *pResource, const D3D11_RENDER_TARGET_VIEW_DESC* pDesc, ID3D11RenderTargetView** ppRTView) {
  10290. #if defined(__cplusplus)
  10291. return self->CreateRenderTargetView(pResource, pDesc, ppRTView);
  10292. #else
  10293. return self->lpVtbl->CreateRenderTargetView(self, pResource, pDesc, ppRTView);
  10294. #endif
  10295. }
  10296. static inline HRESULT _sg_d3d11_CreateDepthStencilView(ID3D11Device* self, ID3D11Resource* pResource, const D3D11_DEPTH_STENCIL_VIEW_DESC* pDesc, ID3D11DepthStencilView** ppDepthStencilView) {
  10297. #if defined(__cplusplus)
  10298. return self->CreateDepthStencilView(pResource, pDesc, ppDepthStencilView);
  10299. #else
  10300. return self->lpVtbl->CreateDepthStencilView(self, pResource, pDesc, ppDepthStencilView);
  10301. #endif
  10302. }
  10303. static inline void _sg_d3d11_RSSetViewports(ID3D11DeviceContext* self, UINT NumViewports, const D3D11_VIEWPORT* pViewports) {
  10304. #if defined(__cplusplus)
  10305. self->RSSetViewports(NumViewports, pViewports);
  10306. #else
  10307. self->lpVtbl->RSSetViewports(self, NumViewports, pViewports);
  10308. #endif
  10309. }
  10310. static inline void _sg_d3d11_RSSetScissorRects(ID3D11DeviceContext* self, UINT NumRects, const D3D11_RECT* pRects) {
  10311. #if defined(__cplusplus)
  10312. self->RSSetScissorRects(NumRects, pRects);
  10313. #else
  10314. self->lpVtbl->RSSetScissorRects(self, NumRects, pRects);
  10315. #endif
  10316. }
  10317. static inline void _sg_d3d11_ClearRenderTargetView(ID3D11DeviceContext* self, ID3D11RenderTargetView* pRenderTargetView, const FLOAT ColorRGBA[4]) {
  10318. #if defined(__cplusplus)
  10319. self->ClearRenderTargetView(pRenderTargetView, ColorRGBA);
  10320. #else
  10321. self->lpVtbl->ClearRenderTargetView(self, pRenderTargetView, ColorRGBA);
  10322. #endif
  10323. }
  10324. static inline void _sg_d3d11_ClearDepthStencilView(ID3D11DeviceContext* self, ID3D11DepthStencilView* pDepthStencilView, UINT ClearFlags, FLOAT Depth, UINT8 Stencil) {
  10325. #if defined(__cplusplus)
  10326. self->ClearDepthStencilView(pDepthStencilView, ClearFlags, Depth, Stencil);
  10327. #else
  10328. self->lpVtbl->ClearDepthStencilView(self, pDepthStencilView, ClearFlags, Depth, Stencil);
  10329. #endif
  10330. }
  10331. static inline void _sg_d3d11_ResolveSubresource(ID3D11DeviceContext* self, ID3D11Resource* pDstResource, UINT DstSubresource, ID3D11Resource* pSrcResource, UINT SrcSubresource, DXGI_FORMAT Format) {
  10332. #if defined(__cplusplus)
  10333. self->ResolveSubresource(pDstResource, DstSubresource, pSrcResource, SrcSubresource, Format);
  10334. #else
  10335. self->lpVtbl->ResolveSubresource(self, pDstResource, DstSubresource, pSrcResource, SrcSubresource, Format);
  10336. #endif
  10337. }
  10338. static inline void _sg_d3d11_IASetPrimitiveTopology(ID3D11DeviceContext* self, D3D11_PRIMITIVE_TOPOLOGY Topology) {
  10339. #if defined(__cplusplus)
  10340. self->IASetPrimitiveTopology(Topology);
  10341. #else
  10342. self->lpVtbl->IASetPrimitiveTopology(self, Topology);
  10343. #endif
  10344. }
  10345. static inline void _sg_d3d11_UpdateSubresource(ID3D11DeviceContext* self, ID3D11Resource* pDstResource, UINT DstSubresource, const D3D11_BOX* pDstBox, const void* pSrcData, UINT SrcRowPitch, UINT SrcDepthPitch) {
  10346. #if defined(__cplusplus)
  10347. self->UpdateSubresource(pDstResource, DstSubresource, pDstBox, pSrcData, SrcRowPitch, SrcDepthPitch);
  10348. #else
  10349. self->lpVtbl->UpdateSubresource(self, pDstResource, DstSubresource, pDstBox, pSrcData, SrcRowPitch, SrcDepthPitch);
  10350. #endif
  10351. }
  10352. static inline void _sg_d3d11_DrawIndexed(ID3D11DeviceContext* self, UINT IndexCount, UINT StartIndexLocation, INT BaseVertexLocation) {
  10353. #if defined(__cplusplus)
  10354. self->DrawIndexed(IndexCount, StartIndexLocation, BaseVertexLocation);
  10355. #else
  10356. self->lpVtbl->DrawIndexed(self, IndexCount, StartIndexLocation, BaseVertexLocation);
  10357. #endif
  10358. }
  10359. static inline void _sg_d3d11_DrawIndexedInstanced(ID3D11DeviceContext* self, UINT IndexCountPerInstance, UINT InstanceCount, UINT StartIndexLocation, INT BaseVertexLocation, UINT StartInstanceLocation) {
  10360. #if defined(__cplusplus)
  10361. self->DrawIndexedInstanced(IndexCountPerInstance, InstanceCount, StartIndexLocation, BaseVertexLocation, StartInstanceLocation);
  10362. #else
  10363. self->lpVtbl->DrawIndexedInstanced(self, IndexCountPerInstance, InstanceCount, StartIndexLocation, BaseVertexLocation, StartInstanceLocation);
  10364. #endif
  10365. }
  10366. static inline void _sg_d3d11_Draw(ID3D11DeviceContext* self, UINT VertexCount, UINT StartVertexLocation) {
  10367. #if defined(__cplusplus)
  10368. self->Draw(VertexCount, StartVertexLocation);
  10369. #else
  10370. self->lpVtbl->Draw(self, VertexCount, StartVertexLocation);
  10371. #endif
  10372. }
  10373. static inline void _sg_d3d11_DrawInstanced(ID3D11DeviceContext* self, UINT VertexCountPerInstance, UINT InstanceCount, UINT StartVertexLocation, UINT StartInstanceLocation) {
  10374. #if defined(__cplusplus)
  10375. self->DrawInstanced(VertexCountPerInstance, InstanceCount, StartVertexLocation, StartInstanceLocation);
  10376. #else
  10377. self->lpVtbl->DrawInstanced(self, VertexCountPerInstance, InstanceCount, StartVertexLocation, StartInstanceLocation);
  10378. #endif
  10379. }
  10380. static inline void _sg_d3d11_Dispatch(ID3D11DeviceContext* self, UINT ThreadGroupCountX, UINT ThreadGroupCountY, UINT ThreadGroupCountZ) {
  10381. #if defined(__cplusplus)
  10382. self->Dispatch(ThreadGroupCountX, ThreadGroupCountY, ThreadGroupCountZ);
  10383. #else
  10384. self->lpVtbl->Dispatch(self, ThreadGroupCountX, ThreadGroupCountY, ThreadGroupCountZ);
  10385. #endif
  10386. }
  10387. static inline HRESULT _sg_d3d11_Map(ID3D11DeviceContext* self, ID3D11Resource* pResource, UINT Subresource, D3D11_MAP MapType, UINT MapFlags, D3D11_MAPPED_SUBRESOURCE* pMappedResource) {
  10388. #if defined(__cplusplus)
  10389. return self->Map(pResource, Subresource, MapType, MapFlags, pMappedResource);
  10390. #else
  10391. return self->lpVtbl->Map(self, pResource, Subresource, MapType, MapFlags, pMappedResource);
  10392. #endif
  10393. }
  10394. static inline void _sg_d3d11_Unmap(ID3D11DeviceContext* self, ID3D11Resource* pResource, UINT Subresource) {
  10395. #if defined(__cplusplus)
  10396. self->Unmap(pResource, Subresource);
  10397. #else
  10398. self->lpVtbl->Unmap(self, pResource, Subresource);
  10399. #endif
  10400. }
  10401. static inline void _sg_d3d11_ClearState(ID3D11DeviceContext* self) {
  10402. #if defined(__cplusplus)
  10403. self->ClearState();
  10404. #else
  10405. self->lpVtbl->ClearState(self);
  10406. #endif
  10407. }
  10408. //-- enum translation functions ------------------------------------------------
  10409. _SOKOL_PRIVATE D3D11_USAGE _sg_d3d11_image_usage(const sg_image_usage* usg) {
  10410. if (usg->immutable) {
  10411. if (usg->render_attachment || usg->storage_attachment) {
  10412. return D3D11_USAGE_DEFAULT;
  10413. } else {
  10414. return D3D11_USAGE_IMMUTABLE;
  10415. }
  10416. } else {
  10417. return D3D11_USAGE_DYNAMIC;
  10418. }
  10419. }
  10420. _SOKOL_PRIVATE UINT _sg_d3d11_image_bind_flags(const sg_image_usage* usg, sg_pixel_format fmt) {
  10421. UINT res = D3D11_BIND_SHADER_RESOURCE;
  10422. if (usg->render_attachment) {
  10423. if (_sg_is_depth_or_depth_stencil_format(fmt)) {
  10424. res |= D3D11_BIND_DEPTH_STENCIL;
  10425. } else {
  10426. res |= D3D11_BIND_RENDER_TARGET;
  10427. }
  10428. } else if (usg->storage_attachment) {
  10429. res |= D3D11_BIND_UNORDERED_ACCESS;
  10430. }
  10431. return res;
  10432. }
  10433. _SOKOL_PRIVATE UINT _sg_d3d11_image_cpu_access_flags(const sg_image_usage* usg) {
  10434. if (usg->render_attachment || usg->storage_attachment || usg->immutable) {
  10435. return 0;
  10436. } else {
  10437. return D3D11_CPU_ACCESS_WRITE;
  10438. }
  10439. }
  10440. _SOKOL_PRIVATE D3D11_USAGE _sg_d3d11_buffer_usage(const sg_buffer_usage* usg) {
  10441. if (usg->immutable) {
  10442. return usg->storage_buffer ? D3D11_USAGE_DEFAULT : D3D11_USAGE_IMMUTABLE;
  10443. } else {
  10444. return D3D11_USAGE_DYNAMIC;
  10445. }
  10446. }
  10447. _SOKOL_PRIVATE UINT _sg_d3d11_buffer_bind_flags(const sg_buffer_usage* usg) {
  10448. UINT res = 0;
  10449. if (usg->vertex_buffer) {
  10450. res |= D3D11_BIND_VERTEX_BUFFER;
  10451. }
  10452. if (usg->index_buffer) {
  10453. res |= D3D11_BIND_INDEX_BUFFER;
  10454. }
  10455. if (usg->storage_buffer) {
  10456. if (usg->immutable) {
  10457. res |= D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS;
  10458. } else {
  10459. res |= D3D11_BIND_SHADER_RESOURCE;
  10460. }
  10461. }
  10462. return res;
  10463. }
  10464. _SOKOL_PRIVATE UINT _sg_d3d11_buffer_misc_flags(const sg_buffer_usage* usg) {
  10465. return usg->storage_buffer ? D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS : 0;
  10466. }
  10467. _SOKOL_PRIVATE UINT _sg_d3d11_buffer_cpu_access_flags(const sg_buffer_usage* usg) {
  10468. return usg->immutable ? 0 : D3D11_CPU_ACCESS_WRITE;
  10469. }
  10470. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_texture_pixel_format(sg_pixel_format fmt) {
  10471. switch (fmt) {
  10472. case SG_PIXELFORMAT_R8: return DXGI_FORMAT_R8_UNORM;
  10473. case SG_PIXELFORMAT_R8SN: return DXGI_FORMAT_R8_SNORM;
  10474. case SG_PIXELFORMAT_R8UI: return DXGI_FORMAT_R8_UINT;
  10475. case SG_PIXELFORMAT_R8SI: return DXGI_FORMAT_R8_SINT;
  10476. case SG_PIXELFORMAT_R16: return DXGI_FORMAT_R16_UNORM;
  10477. case SG_PIXELFORMAT_R16SN: return DXGI_FORMAT_R16_SNORM;
  10478. case SG_PIXELFORMAT_R16UI: return DXGI_FORMAT_R16_UINT;
  10479. case SG_PIXELFORMAT_R16SI: return DXGI_FORMAT_R16_SINT;
  10480. case SG_PIXELFORMAT_R16F: return DXGI_FORMAT_R16_FLOAT;
  10481. case SG_PIXELFORMAT_RG8: return DXGI_FORMAT_R8G8_UNORM;
  10482. case SG_PIXELFORMAT_RG8SN: return DXGI_FORMAT_R8G8_SNORM;
  10483. case SG_PIXELFORMAT_RG8UI: return DXGI_FORMAT_R8G8_UINT;
  10484. case SG_PIXELFORMAT_RG8SI: return DXGI_FORMAT_R8G8_SINT;
  10485. case SG_PIXELFORMAT_R32UI: return DXGI_FORMAT_R32_UINT;
  10486. case SG_PIXELFORMAT_R32SI: return DXGI_FORMAT_R32_SINT;
  10487. case SG_PIXELFORMAT_R32F: return DXGI_FORMAT_R32_FLOAT;
  10488. case SG_PIXELFORMAT_RG16: return DXGI_FORMAT_R16G16_UNORM;
  10489. case SG_PIXELFORMAT_RG16SN: return DXGI_FORMAT_R16G16_SNORM;
  10490. case SG_PIXELFORMAT_RG16UI: return DXGI_FORMAT_R16G16_UINT;
  10491. case SG_PIXELFORMAT_RG16SI: return DXGI_FORMAT_R16G16_SINT;
  10492. case SG_PIXELFORMAT_RG16F: return DXGI_FORMAT_R16G16_FLOAT;
  10493. case SG_PIXELFORMAT_RGBA8: return DXGI_FORMAT_R8G8B8A8_UNORM;
  10494. case SG_PIXELFORMAT_SRGB8A8: return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
  10495. case SG_PIXELFORMAT_RGBA8SN: return DXGI_FORMAT_R8G8B8A8_SNORM;
  10496. case SG_PIXELFORMAT_RGBA8UI: return DXGI_FORMAT_R8G8B8A8_UINT;
  10497. case SG_PIXELFORMAT_RGBA8SI: return DXGI_FORMAT_R8G8B8A8_SINT;
  10498. case SG_PIXELFORMAT_BGRA8: return DXGI_FORMAT_B8G8R8A8_UNORM;
  10499. case SG_PIXELFORMAT_RGB10A2: return DXGI_FORMAT_R10G10B10A2_UNORM;
  10500. case SG_PIXELFORMAT_RG11B10F: return DXGI_FORMAT_R11G11B10_FLOAT;
  10501. case SG_PIXELFORMAT_RGB9E5: return DXGI_FORMAT_R9G9B9E5_SHAREDEXP;
  10502. case SG_PIXELFORMAT_RG32UI: return DXGI_FORMAT_R32G32_UINT;
  10503. case SG_PIXELFORMAT_RG32SI: return DXGI_FORMAT_R32G32_SINT;
  10504. case SG_PIXELFORMAT_RG32F: return DXGI_FORMAT_R32G32_FLOAT;
  10505. case SG_PIXELFORMAT_RGBA16: return DXGI_FORMAT_R16G16B16A16_UNORM;
  10506. case SG_PIXELFORMAT_RGBA16SN: return DXGI_FORMAT_R16G16B16A16_SNORM;
  10507. case SG_PIXELFORMAT_RGBA16UI: return DXGI_FORMAT_R16G16B16A16_UINT;
  10508. case SG_PIXELFORMAT_RGBA16SI: return DXGI_FORMAT_R16G16B16A16_SINT;
  10509. case SG_PIXELFORMAT_RGBA16F: return DXGI_FORMAT_R16G16B16A16_FLOAT;
  10510. case SG_PIXELFORMAT_RGBA32UI: return DXGI_FORMAT_R32G32B32A32_UINT;
  10511. case SG_PIXELFORMAT_RGBA32SI: return DXGI_FORMAT_R32G32B32A32_SINT;
  10512. case SG_PIXELFORMAT_RGBA32F: return DXGI_FORMAT_R32G32B32A32_FLOAT;
  10513. case SG_PIXELFORMAT_DEPTH: return DXGI_FORMAT_R32_TYPELESS;
  10514. case SG_PIXELFORMAT_DEPTH_STENCIL: return DXGI_FORMAT_R24G8_TYPELESS;
  10515. case SG_PIXELFORMAT_BC1_RGBA: return DXGI_FORMAT_BC1_UNORM;
  10516. case SG_PIXELFORMAT_BC2_RGBA: return DXGI_FORMAT_BC2_UNORM;
  10517. case SG_PIXELFORMAT_BC3_RGBA: return DXGI_FORMAT_BC3_UNORM;
  10518. case SG_PIXELFORMAT_BC3_SRGBA: return DXGI_FORMAT_BC3_UNORM_SRGB;
  10519. case SG_PIXELFORMAT_BC4_R: return DXGI_FORMAT_BC4_UNORM;
  10520. case SG_PIXELFORMAT_BC4_RSN: return DXGI_FORMAT_BC4_SNORM;
  10521. case SG_PIXELFORMAT_BC5_RG: return DXGI_FORMAT_BC5_UNORM;
  10522. case SG_PIXELFORMAT_BC5_RGSN: return DXGI_FORMAT_BC5_SNORM;
  10523. case SG_PIXELFORMAT_BC6H_RGBF: return DXGI_FORMAT_BC6H_SF16;
  10524. case SG_PIXELFORMAT_BC6H_RGBUF: return DXGI_FORMAT_BC6H_UF16;
  10525. case SG_PIXELFORMAT_BC7_RGBA: return DXGI_FORMAT_BC7_UNORM;
  10526. case SG_PIXELFORMAT_BC7_SRGBA: return DXGI_FORMAT_BC7_UNORM_SRGB;
  10527. default: return DXGI_FORMAT_UNKNOWN;
  10528. };
  10529. }
  10530. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_srv_pixel_format(sg_pixel_format fmt) {
  10531. if (fmt == SG_PIXELFORMAT_DEPTH) {
  10532. return DXGI_FORMAT_R32_FLOAT;
  10533. } else if (fmt == SG_PIXELFORMAT_DEPTH_STENCIL) {
  10534. return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
  10535. } else {
  10536. return _sg_d3d11_texture_pixel_format(fmt);
  10537. }
  10538. }
  10539. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_dsv_pixel_format(sg_pixel_format fmt) {
  10540. if (fmt == SG_PIXELFORMAT_DEPTH) {
  10541. return DXGI_FORMAT_D32_FLOAT;
  10542. } else if (fmt == SG_PIXELFORMAT_DEPTH_STENCIL) {
  10543. return DXGI_FORMAT_D24_UNORM_S8_UINT;
  10544. } else {
  10545. return _sg_d3d11_texture_pixel_format(fmt);
  10546. }
  10547. }
  10548. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_rtv_uav_pixel_format(sg_pixel_format fmt) {
  10549. if (fmt == SG_PIXELFORMAT_DEPTH) {
  10550. return DXGI_FORMAT_R32_FLOAT;
  10551. } else if (fmt == SG_PIXELFORMAT_DEPTH_STENCIL) {
  10552. return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
  10553. } else {
  10554. return _sg_d3d11_texture_pixel_format(fmt);
  10555. }
  10556. }
  10557. _SOKOL_PRIVATE D3D11_PRIMITIVE_TOPOLOGY _sg_d3d11_primitive_topology(sg_primitive_type prim_type) {
  10558. switch (prim_type) {
  10559. case SG_PRIMITIVETYPE_POINTS: return D3D11_PRIMITIVE_TOPOLOGY_POINTLIST;
  10560. case SG_PRIMITIVETYPE_LINES: return D3D11_PRIMITIVE_TOPOLOGY_LINELIST;
  10561. case SG_PRIMITIVETYPE_LINE_STRIP: return D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP;
  10562. case SG_PRIMITIVETYPE_TRIANGLES: return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  10563. case SG_PRIMITIVETYPE_TRIANGLE_STRIP: return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
  10564. default: SOKOL_UNREACHABLE; return (D3D11_PRIMITIVE_TOPOLOGY) 0;
  10565. }
  10566. }
  10567. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_index_format(sg_index_type index_type) {
  10568. switch (index_type) {
  10569. case SG_INDEXTYPE_NONE: return DXGI_FORMAT_UNKNOWN;
  10570. case SG_INDEXTYPE_UINT16: return DXGI_FORMAT_R16_UINT;
  10571. case SG_INDEXTYPE_UINT32: return DXGI_FORMAT_R32_UINT;
  10572. default: SOKOL_UNREACHABLE; return (DXGI_FORMAT) 0;
  10573. }
  10574. }
  10575. _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) {
  10576. uint32_t d3d11_filter = 0;
  10577. if (max_anisotropy > 1) {
  10578. // D3D11_FILTER_ANISOTROPIC = 0x55,
  10579. d3d11_filter |= 0x55;
  10580. } else {
  10581. // D3D11_FILTER_MIN_MAG_MIP_POINT = 0,
  10582. // D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR = 0x1,
  10583. // D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x4,
  10584. // D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR = 0x5,
  10585. // D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT = 0x10,
  10586. // D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x11,
  10587. // D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT = 0x14,
  10588. // D3D11_FILTER_MIN_MAG_MIP_LINEAR = 0x15,
  10589. if (mipmap_f == SG_FILTER_LINEAR) {
  10590. d3d11_filter |= 0x01;
  10591. }
  10592. if (mag_f == SG_FILTER_LINEAR) {
  10593. d3d11_filter |= 0x04;
  10594. }
  10595. if (min_f == SG_FILTER_LINEAR) {
  10596. d3d11_filter |= 0x10;
  10597. }
  10598. }
  10599. // D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT = 0x80,
  10600. // D3D11_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR = 0x81,
  10601. // D3D11_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x84,
  10602. // D3D11_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR = 0x85,
  10603. // D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT = 0x90,
  10604. // D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x91,
  10605. // D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT = 0x94,
  10606. // D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR = 0x95,
  10607. // D3D11_FILTER_COMPARISON_ANISOTROPIC = 0xd5,
  10608. if (comparison) {
  10609. d3d11_filter |= 0x80;
  10610. }
  10611. return (D3D11_FILTER)d3d11_filter;
  10612. }
  10613. _SOKOL_PRIVATE D3D11_TEXTURE_ADDRESS_MODE _sg_d3d11_address_mode(sg_wrap m) {
  10614. switch (m) {
  10615. case SG_WRAP_REPEAT: return D3D11_TEXTURE_ADDRESS_WRAP;
  10616. case SG_WRAP_CLAMP_TO_EDGE: return D3D11_TEXTURE_ADDRESS_CLAMP;
  10617. case SG_WRAP_CLAMP_TO_BORDER: return D3D11_TEXTURE_ADDRESS_BORDER;
  10618. case SG_WRAP_MIRRORED_REPEAT: return D3D11_TEXTURE_ADDRESS_MIRROR;
  10619. default: SOKOL_UNREACHABLE; return (D3D11_TEXTURE_ADDRESS_MODE) 0;
  10620. }
  10621. }
  10622. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_vertex_format(sg_vertex_format fmt) {
  10623. switch (fmt) {
  10624. case SG_VERTEXFORMAT_FLOAT: return DXGI_FORMAT_R32_FLOAT;
  10625. case SG_VERTEXFORMAT_FLOAT2: return DXGI_FORMAT_R32G32_FLOAT;
  10626. case SG_VERTEXFORMAT_FLOAT3: return DXGI_FORMAT_R32G32B32_FLOAT;
  10627. case SG_VERTEXFORMAT_FLOAT4: return DXGI_FORMAT_R32G32B32A32_FLOAT;
  10628. case SG_VERTEXFORMAT_INT: return DXGI_FORMAT_R32_SINT;
  10629. case SG_VERTEXFORMAT_INT2: return DXGI_FORMAT_R32G32_SINT;
  10630. case SG_VERTEXFORMAT_INT3: return DXGI_FORMAT_R32G32B32_SINT;
  10631. case SG_VERTEXFORMAT_INT4: return DXGI_FORMAT_R32G32B32A32_SINT;
  10632. case SG_VERTEXFORMAT_UINT: return DXGI_FORMAT_R32_UINT;
  10633. case SG_VERTEXFORMAT_UINT2: return DXGI_FORMAT_R32G32_UINT;
  10634. case SG_VERTEXFORMAT_UINT3: return DXGI_FORMAT_R32G32B32_UINT;
  10635. case SG_VERTEXFORMAT_UINT4: return DXGI_FORMAT_R32G32B32A32_UINT;
  10636. case SG_VERTEXFORMAT_BYTE4: return DXGI_FORMAT_R8G8B8A8_SINT;
  10637. case SG_VERTEXFORMAT_BYTE4N: return DXGI_FORMAT_R8G8B8A8_SNORM;
  10638. case SG_VERTEXFORMAT_UBYTE4: return DXGI_FORMAT_R8G8B8A8_UINT;
  10639. case SG_VERTEXFORMAT_UBYTE4N: return DXGI_FORMAT_R8G8B8A8_UNORM;
  10640. case SG_VERTEXFORMAT_SHORT2: return DXGI_FORMAT_R16G16_SINT;
  10641. case SG_VERTEXFORMAT_SHORT2N: return DXGI_FORMAT_R16G16_SNORM;
  10642. case SG_VERTEXFORMAT_USHORT2: return DXGI_FORMAT_R16G16_UINT;
  10643. case SG_VERTEXFORMAT_USHORT2N: return DXGI_FORMAT_R16G16_UNORM;
  10644. case SG_VERTEXFORMAT_SHORT4: return DXGI_FORMAT_R16G16B16A16_SINT;
  10645. case SG_VERTEXFORMAT_SHORT4N: return DXGI_FORMAT_R16G16B16A16_SNORM;
  10646. case SG_VERTEXFORMAT_USHORT4: return DXGI_FORMAT_R16G16B16A16_UINT;
  10647. case SG_VERTEXFORMAT_USHORT4N: return DXGI_FORMAT_R16G16B16A16_UNORM;
  10648. case SG_VERTEXFORMAT_UINT10_N2: return DXGI_FORMAT_R10G10B10A2_UNORM;
  10649. case SG_VERTEXFORMAT_HALF2: return DXGI_FORMAT_R16G16_FLOAT;
  10650. case SG_VERTEXFORMAT_HALF4: return DXGI_FORMAT_R16G16B16A16_FLOAT;
  10651. default: SOKOL_UNREACHABLE; return (DXGI_FORMAT) 0;
  10652. }
  10653. }
  10654. _SOKOL_PRIVATE D3D11_INPUT_CLASSIFICATION _sg_d3d11_input_classification(sg_vertex_step step) {
  10655. switch (step) {
  10656. case SG_VERTEXSTEP_PER_VERTEX: return D3D11_INPUT_PER_VERTEX_DATA;
  10657. case SG_VERTEXSTEP_PER_INSTANCE: return D3D11_INPUT_PER_INSTANCE_DATA;
  10658. default: SOKOL_UNREACHABLE; return (D3D11_INPUT_CLASSIFICATION) 0;
  10659. }
  10660. }
  10661. _SOKOL_PRIVATE D3D11_CULL_MODE _sg_d3d11_cull_mode(sg_cull_mode m) {
  10662. switch (m) {
  10663. case SG_CULLMODE_NONE: return D3D11_CULL_NONE;
  10664. case SG_CULLMODE_FRONT: return D3D11_CULL_FRONT;
  10665. case SG_CULLMODE_BACK: return D3D11_CULL_BACK;
  10666. default: SOKOL_UNREACHABLE; return (D3D11_CULL_MODE) 0;
  10667. }
  10668. }
  10669. _SOKOL_PRIVATE D3D11_COMPARISON_FUNC _sg_d3d11_compare_func(sg_compare_func f) {
  10670. switch (f) {
  10671. case SG_COMPAREFUNC_NEVER: return D3D11_COMPARISON_NEVER;
  10672. case SG_COMPAREFUNC_LESS: return D3D11_COMPARISON_LESS;
  10673. case SG_COMPAREFUNC_EQUAL: return D3D11_COMPARISON_EQUAL;
  10674. case SG_COMPAREFUNC_LESS_EQUAL: return D3D11_COMPARISON_LESS_EQUAL;
  10675. case SG_COMPAREFUNC_GREATER: return D3D11_COMPARISON_GREATER;
  10676. case SG_COMPAREFUNC_NOT_EQUAL: return D3D11_COMPARISON_NOT_EQUAL;
  10677. case SG_COMPAREFUNC_GREATER_EQUAL: return D3D11_COMPARISON_GREATER_EQUAL;
  10678. case SG_COMPAREFUNC_ALWAYS: return D3D11_COMPARISON_ALWAYS;
  10679. default: SOKOL_UNREACHABLE; return (D3D11_COMPARISON_FUNC) 0;
  10680. }
  10681. }
  10682. _SOKOL_PRIVATE D3D11_STENCIL_OP _sg_d3d11_stencil_op(sg_stencil_op op) {
  10683. switch (op) {
  10684. case SG_STENCILOP_KEEP: return D3D11_STENCIL_OP_KEEP;
  10685. case SG_STENCILOP_ZERO: return D3D11_STENCIL_OP_ZERO;
  10686. case SG_STENCILOP_REPLACE: return D3D11_STENCIL_OP_REPLACE;
  10687. case SG_STENCILOP_INCR_CLAMP: return D3D11_STENCIL_OP_INCR_SAT;
  10688. case SG_STENCILOP_DECR_CLAMP: return D3D11_STENCIL_OP_DECR_SAT;
  10689. case SG_STENCILOP_INVERT: return D3D11_STENCIL_OP_INVERT;
  10690. case SG_STENCILOP_INCR_WRAP: return D3D11_STENCIL_OP_INCR;
  10691. case SG_STENCILOP_DECR_WRAP: return D3D11_STENCIL_OP_DECR;
  10692. default: SOKOL_UNREACHABLE; return (D3D11_STENCIL_OP) 0;
  10693. }
  10694. }
  10695. _SOKOL_PRIVATE D3D11_BLEND _sg_d3d11_blend_factor(sg_blend_factor f) {
  10696. switch (f) {
  10697. case SG_BLENDFACTOR_ZERO: return D3D11_BLEND_ZERO;
  10698. case SG_BLENDFACTOR_ONE: return D3D11_BLEND_ONE;
  10699. case SG_BLENDFACTOR_SRC_COLOR: return D3D11_BLEND_SRC_COLOR;
  10700. case SG_BLENDFACTOR_ONE_MINUS_SRC_COLOR: return D3D11_BLEND_INV_SRC_COLOR;
  10701. case SG_BLENDFACTOR_SRC_ALPHA: return D3D11_BLEND_SRC_ALPHA;
  10702. case SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA: return D3D11_BLEND_INV_SRC_ALPHA;
  10703. case SG_BLENDFACTOR_DST_COLOR: return D3D11_BLEND_DEST_COLOR;
  10704. case SG_BLENDFACTOR_ONE_MINUS_DST_COLOR: return D3D11_BLEND_INV_DEST_COLOR;
  10705. case SG_BLENDFACTOR_DST_ALPHA: return D3D11_BLEND_DEST_ALPHA;
  10706. case SG_BLENDFACTOR_ONE_MINUS_DST_ALPHA: return D3D11_BLEND_INV_DEST_ALPHA;
  10707. case SG_BLENDFACTOR_SRC_ALPHA_SATURATED: return D3D11_BLEND_SRC_ALPHA_SAT;
  10708. case SG_BLENDFACTOR_BLEND_COLOR: return D3D11_BLEND_BLEND_FACTOR;
  10709. case SG_BLENDFACTOR_ONE_MINUS_BLEND_COLOR: return D3D11_BLEND_INV_BLEND_FACTOR;
  10710. case SG_BLENDFACTOR_BLEND_ALPHA: return D3D11_BLEND_BLEND_FACTOR;
  10711. case SG_BLENDFACTOR_ONE_MINUS_BLEND_ALPHA: return D3D11_BLEND_INV_BLEND_FACTOR;
  10712. default: SOKOL_UNREACHABLE; return (D3D11_BLEND) 0;
  10713. }
  10714. }
  10715. _SOKOL_PRIVATE D3D11_BLEND_OP _sg_d3d11_blend_op(sg_blend_op op) {
  10716. switch (op) {
  10717. case SG_BLENDOP_ADD: return D3D11_BLEND_OP_ADD;
  10718. case SG_BLENDOP_SUBTRACT: return D3D11_BLEND_OP_SUBTRACT;
  10719. case SG_BLENDOP_REVERSE_SUBTRACT: return D3D11_BLEND_OP_REV_SUBTRACT;
  10720. case SG_BLENDOP_MIN: return D3D11_BLEND_OP_MIN;
  10721. case SG_BLENDOP_MAX: return D3D11_BLEND_OP_MAX;
  10722. default: SOKOL_UNREACHABLE; return (D3D11_BLEND_OP) 0;
  10723. }
  10724. }
  10725. _SOKOL_PRIVATE UINT8 _sg_d3d11_color_write_mask(sg_color_mask m) {
  10726. UINT8 res = 0;
  10727. if (m & SG_COLORMASK_R) {
  10728. res |= D3D11_COLOR_WRITE_ENABLE_RED;
  10729. }
  10730. if (m & SG_COLORMASK_G) {
  10731. res |= D3D11_COLOR_WRITE_ENABLE_GREEN;
  10732. }
  10733. if (m & SG_COLORMASK_B) {
  10734. res |= D3D11_COLOR_WRITE_ENABLE_BLUE;
  10735. }
  10736. if (m & SG_COLORMASK_A) {
  10737. res |= D3D11_COLOR_WRITE_ENABLE_ALPHA;
  10738. }
  10739. return res;
  10740. }
  10741. _SOKOL_PRIVATE UINT _sg_d3d11_dxgi_fmt_caps(DXGI_FORMAT dxgi_fmt) {
  10742. UINT dxgi_fmt_caps = 0;
  10743. if (dxgi_fmt != DXGI_FORMAT_UNKNOWN) {
  10744. HRESULT hr = _sg_d3d11_CheckFormatSupport(_sg.d3d11.dev, dxgi_fmt, &dxgi_fmt_caps);
  10745. SOKOL_ASSERT(SUCCEEDED(hr) || (E_FAIL == hr));
  10746. if (!SUCCEEDED(hr)) {
  10747. dxgi_fmt_caps = 0;
  10748. }
  10749. }
  10750. return dxgi_fmt_caps;
  10751. }
  10752. // see: https://docs.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-resources-limits#resource-limits-for-feature-level-11-hardware
  10753. _SOKOL_PRIVATE void _sg_d3d11_init_caps(void) {
  10754. _sg.backend = SG_BACKEND_D3D11;
  10755. _sg.features.origin_top_left = true;
  10756. _sg.features.image_clamp_to_border = true;
  10757. _sg.features.mrt_independent_blend_state = true;
  10758. _sg.features.mrt_independent_write_mask = true;
  10759. _sg.features.compute = true;
  10760. _sg.features.msaa_image_bindings = true;
  10761. _sg.limits.max_image_size_2d = 16 * 1024;
  10762. _sg.limits.max_image_size_cube = 16 * 1024;
  10763. _sg.limits.max_image_size_3d = 2 * 1024;
  10764. _sg.limits.max_image_size_array = 16 * 1024;
  10765. _sg.limits.max_image_array_layers = 2 * 1024;
  10766. _sg.limits.max_vertex_attrs = SG_MAX_VERTEX_ATTRIBUTES;
  10767. // see: https://docs.microsoft.com/en-us/windows/win32/api/d3d11/ne-d3d11-d3d11_format_support
  10768. for (int fmt = (SG_PIXELFORMAT_NONE+1); fmt < _SG_PIXELFORMAT_NUM; fmt++) {
  10769. const UINT srv_dxgi_fmt_caps = _sg_d3d11_dxgi_fmt_caps(_sg_d3d11_srv_pixel_format((sg_pixel_format)fmt));
  10770. const UINT rtv_uav_dxgi_fmt_caps = _sg_d3d11_dxgi_fmt_caps(_sg_d3d11_rtv_uav_pixel_format((sg_pixel_format)fmt));
  10771. const UINT dsv_dxgi_fmt_caps = _sg_d3d11_dxgi_fmt_caps(_sg_d3d11_dsv_pixel_format((sg_pixel_format)fmt));
  10772. _sg_pixelformat_info_t* info = &_sg.formats[fmt];
  10773. const bool render = 0 != (rtv_uav_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_RENDER_TARGET);
  10774. const bool depth = 0 != (dsv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_DEPTH_STENCIL);
  10775. info->sample = 0 != (srv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_TEXTURE2D);
  10776. info->filter = 0 != (srv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_SHADER_SAMPLE);
  10777. info->render = render || depth;
  10778. if (depth) {
  10779. info->blend = 0 != (dsv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_BLENDABLE);
  10780. info->msaa = 0 != (dsv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET);
  10781. } else {
  10782. info->blend = 0 != (rtv_uav_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_BLENDABLE);
  10783. info->msaa = 0 != (rtv_uav_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET);
  10784. }
  10785. info->depth = depth;
  10786. info->read = info->write = 0 != (rtv_uav_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_TYPED_UNORDERED_ACCESS_VIEW);
  10787. }
  10788. }
  10789. _SOKOL_PRIVATE void _sg_d3d11_setup_backend(const sg_desc* desc) {
  10790. // assume _sg.d3d11 already is zero-initialized
  10791. SOKOL_ASSERT(desc);
  10792. SOKOL_ASSERT(desc->environment.d3d11.device);
  10793. SOKOL_ASSERT(desc->environment.d3d11.device_context);
  10794. _sg.d3d11.valid = true;
  10795. _sg.d3d11.dev = (ID3D11Device*) desc->environment.d3d11.device;
  10796. _sg.d3d11.ctx = (ID3D11DeviceContext*) desc->environment.d3d11.device_context;
  10797. _sg_d3d11_init_caps();
  10798. }
  10799. _SOKOL_PRIVATE void _sg_d3d11_discard_backend(void) {
  10800. SOKOL_ASSERT(_sg.d3d11.valid);
  10801. _sg.d3d11.valid = false;
  10802. }
  10803. _SOKOL_PRIVATE void _sg_d3d11_clear_state(void) {
  10804. // clear all the device context state, so that resource refs don't keep stuck in the d3d device context
  10805. _sg_d3d11_ClearState(_sg.d3d11.ctx);
  10806. }
  10807. _SOKOL_PRIVATE void _sg_d3d11_reset_state_cache(void) {
  10808. // there's currently no state cache in the D3D11 backend, so this is a no-op
  10809. }
  10810. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  10811. SOKOL_ASSERT(buf && desc);
  10812. SOKOL_ASSERT(!buf->d3d11.buf);
  10813. const bool injected = (0 != desc->d3d11_buffer);
  10814. if (injected) {
  10815. buf->d3d11.buf = (ID3D11Buffer*) desc->d3d11_buffer;
  10816. _sg_d3d11_AddRef(buf->d3d11.buf);
  10817. } else {
  10818. D3D11_BUFFER_DESC d3d11_buf_desc;
  10819. _sg_clear(&d3d11_buf_desc, sizeof(d3d11_buf_desc));
  10820. d3d11_buf_desc.ByteWidth = (UINT)buf->cmn.size;
  10821. d3d11_buf_desc.Usage = _sg_d3d11_buffer_usage(&buf->cmn.usage);
  10822. d3d11_buf_desc.BindFlags = _sg_d3d11_buffer_bind_flags(&buf->cmn.usage);
  10823. d3d11_buf_desc.CPUAccessFlags = _sg_d3d11_buffer_cpu_access_flags(&buf->cmn.usage);
  10824. d3d11_buf_desc.MiscFlags = _sg_d3d11_buffer_misc_flags(&buf->cmn.usage);
  10825. D3D11_SUBRESOURCE_DATA* init_data_ptr = 0;
  10826. D3D11_SUBRESOURCE_DATA init_data;
  10827. _sg_clear(&init_data, sizeof(init_data));
  10828. if (desc->data.ptr) {
  10829. init_data.pSysMem = desc->data.ptr;
  10830. init_data_ptr = &init_data;
  10831. }
  10832. HRESULT hr = _sg_d3d11_CreateBuffer(_sg.d3d11.dev, &d3d11_buf_desc, init_data_ptr, &buf->d3d11.buf);
  10833. if (!(SUCCEEDED(hr) && buf->d3d11.buf)) {
  10834. _SG_ERROR(D3D11_CREATE_BUFFER_FAILED);
  10835. return SG_RESOURCESTATE_FAILED;
  10836. }
  10837. // for storage buffers need to create a shader-resource-view
  10838. // for read-only access, and an unordered-access-view for
  10839. // read-write access
  10840. if (buf->cmn.usage.storage_buffer) {
  10841. SOKOL_ASSERT(_sg_multiple_u64((uint64_t)buf->cmn.size, 4));
  10842. D3D11_SHADER_RESOURCE_VIEW_DESC d3d11_srv_desc;
  10843. _sg_clear(&d3d11_srv_desc, sizeof(d3d11_srv_desc));
  10844. d3d11_srv_desc.Format = DXGI_FORMAT_R32_TYPELESS;
  10845. d3d11_srv_desc.ViewDimension = D3D11_SRV_DIMENSION_BUFFEREX;
  10846. d3d11_srv_desc.BufferEx.FirstElement = 0;
  10847. d3d11_srv_desc.BufferEx.NumElements = ((UINT)buf->cmn.size) / 4;
  10848. d3d11_srv_desc.BufferEx.Flags = D3D11_BUFFEREX_SRV_FLAG_RAW;
  10849. hr = _sg_d3d11_CreateShaderResourceView(_sg.d3d11.dev, (ID3D11Resource*)buf->d3d11.buf, &d3d11_srv_desc, &buf->d3d11.srv);
  10850. if (!(SUCCEEDED(hr) && buf->d3d11.srv)) {
  10851. _SG_ERROR(D3D11_CREATE_BUFFER_SRV_FAILED);
  10852. return SG_RESOURCESTATE_FAILED;
  10853. }
  10854. if (buf->cmn.usage.immutable) {
  10855. D3D11_UNORDERED_ACCESS_VIEW_DESC d3d11_uav_desc;
  10856. _sg_clear(&d3d11_uav_desc, sizeof(d3d11_uav_desc));
  10857. d3d11_uav_desc.Format = DXGI_FORMAT_R32_TYPELESS;
  10858. d3d11_uav_desc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
  10859. d3d11_uav_desc.Buffer.FirstElement = 0;
  10860. d3d11_uav_desc.Buffer.NumElements = ((UINT)buf->cmn.size) / 4;
  10861. d3d11_uav_desc.Buffer.Flags = D3D11_BUFFER_UAV_FLAG_RAW;
  10862. hr = _sg_d3d11_CreateUnorderedAccessView(_sg.d3d11.dev, (ID3D11Resource*)buf->d3d11.buf, &d3d11_uav_desc, &buf->d3d11.uav);
  10863. if (!(SUCCEEDED(hr) && buf->d3d11.uav)) {
  10864. _SG_ERROR(D3D11_CREATE_BUFFER_UAV_FAILED);
  10865. return SG_RESOURCESTATE_FAILED;
  10866. }
  10867. }
  10868. }
  10869. _sg_d3d11_setlabel(buf->d3d11.buf, desc->label);
  10870. }
  10871. return SG_RESOURCESTATE_VALID;
  10872. }
  10873. _SOKOL_PRIVATE void _sg_d3d11_discard_buffer(_sg_buffer_t* buf) {
  10874. SOKOL_ASSERT(buf);
  10875. if (buf->d3d11.buf) {
  10876. _sg_d3d11_Release(buf->d3d11.buf);
  10877. }
  10878. if (buf->d3d11.srv) {
  10879. _sg_d3d11_Release(buf->d3d11.srv);
  10880. }
  10881. if (buf->d3d11.uav) {
  10882. _sg_d3d11_Release(buf->d3d11.uav);
  10883. }
  10884. }
  10885. _SOKOL_PRIVATE void _sg_d3d11_fill_subres_data(const _sg_image_t* img, const sg_image_data* data) {
  10886. const int num_faces = (img->cmn.type == SG_IMAGETYPE_CUBE) ? 6:1;
  10887. const int num_slices = (img->cmn.type == SG_IMAGETYPE_ARRAY) ? img->cmn.num_slices:1;
  10888. int subres_index = 0;
  10889. for (int face_index = 0; face_index < num_faces; face_index++) {
  10890. for (int slice_index = 0; slice_index < num_slices; slice_index++) {
  10891. for (int mip_index = 0; mip_index < img->cmn.num_mipmaps; mip_index++, subres_index++) {
  10892. SOKOL_ASSERT(subres_index < (SG_MAX_MIPMAPS * SG_MAX_TEXTUREARRAY_LAYERS));
  10893. D3D11_SUBRESOURCE_DATA* subres_data = &_sg.d3d11.subres_data[subres_index];
  10894. const int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  10895. const int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  10896. const sg_range* subimg_data = &(data->subimage[face_index][mip_index]);
  10897. const size_t slice_size = subimg_data->size / (size_t)num_slices;
  10898. const size_t slice_offset = slice_size * (size_t)slice_index;
  10899. const uint8_t* ptr = (const uint8_t*) subimg_data->ptr;
  10900. subres_data->pSysMem = ptr + slice_offset;
  10901. subres_data->SysMemPitch = (UINT)_sg_row_pitch(img->cmn.pixel_format, mip_width, 1);
  10902. if (img->cmn.type == SG_IMAGETYPE_3D) {
  10903. // FIXME? const int mip_depth = _sg_miplevel_dim(img->depth, mip_index);
  10904. subres_data->SysMemSlicePitch = (UINT)_sg_surface_pitch(img->cmn.pixel_format, mip_width, mip_height, 1);
  10905. } else {
  10906. subres_data->SysMemSlicePitch = 0;
  10907. }
  10908. }
  10909. }
  10910. }
  10911. }
  10912. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  10913. SOKOL_ASSERT(img && desc);
  10914. SOKOL_ASSERT((0 == img->d3d11.tex2d) && (0 == img->d3d11.tex3d) && (0 == img->d3d11.res) && (0 == img->d3d11.srv));
  10915. HRESULT hr;
  10916. const bool injected = (0 != desc->d3d11_texture);
  10917. const bool msaa = (img->cmn.sample_count > 1);
  10918. SOKOL_ASSERT(!(msaa && (img->cmn.type == SG_IMAGETYPE_CUBE)));
  10919. img->d3d11.format = _sg_d3d11_texture_pixel_format(img->cmn.pixel_format);
  10920. if (img->d3d11.format == DXGI_FORMAT_UNKNOWN) {
  10921. _SG_ERROR(D3D11_CREATE_2D_TEXTURE_UNSUPPORTED_PIXEL_FORMAT);
  10922. return SG_RESOURCESTATE_FAILED;
  10923. }
  10924. // prepare initial content pointers
  10925. D3D11_SUBRESOURCE_DATA* init_data = 0;
  10926. if (!injected && desc->data.subimage[0][0].ptr) {
  10927. _sg_d3d11_fill_subres_data(img, &desc->data);
  10928. init_data = _sg.d3d11.subres_data;
  10929. }
  10930. if (img->cmn.type != SG_IMAGETYPE_3D) {
  10931. // 2D-, cube- or array-texture
  10932. // first check for injected texture and/or resource view
  10933. if (injected) {
  10934. img->d3d11.tex2d = (ID3D11Texture2D*) desc->d3d11_texture;
  10935. _sg_d3d11_AddRef(img->d3d11.tex2d);
  10936. img->d3d11.srv = (ID3D11ShaderResourceView*) desc->d3d11_shader_resource_view;
  10937. if (img->d3d11.srv) {
  10938. _sg_d3d11_AddRef(img->d3d11.srv);
  10939. }
  10940. } else {
  10941. // if not injected, create 2D texture
  10942. D3D11_TEXTURE2D_DESC d3d11_tex_desc;
  10943. _sg_clear(&d3d11_tex_desc, sizeof(d3d11_tex_desc));
  10944. d3d11_tex_desc.Width = (UINT)img->cmn.width;
  10945. d3d11_tex_desc.Height = (UINT)img->cmn.height;
  10946. d3d11_tex_desc.MipLevels = (UINT)img->cmn.num_mipmaps;
  10947. switch (img->cmn.type) {
  10948. case SG_IMAGETYPE_ARRAY: d3d11_tex_desc.ArraySize = (UINT)img->cmn.num_slices; break;
  10949. case SG_IMAGETYPE_CUBE: d3d11_tex_desc.ArraySize = 6; break;
  10950. default: d3d11_tex_desc.ArraySize = 1; break;
  10951. }
  10952. d3d11_tex_desc.Format = img->d3d11.format;
  10953. d3d11_tex_desc.BindFlags = _sg_d3d11_image_bind_flags(&img->cmn.usage, img->cmn.pixel_format);
  10954. d3d11_tex_desc.Usage = _sg_d3d11_image_usage(&img->cmn.usage);
  10955. d3d11_tex_desc.CPUAccessFlags = _sg_d3d11_image_cpu_access_flags(&img->cmn.usage);
  10956. d3d11_tex_desc.SampleDesc.Count = (UINT)img->cmn.sample_count;
  10957. d3d11_tex_desc.SampleDesc.Quality = (UINT) (msaa ? D3D11_STANDARD_MULTISAMPLE_PATTERN : 0);
  10958. d3d11_tex_desc.MiscFlags = (img->cmn.type == SG_IMAGETYPE_CUBE) ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0;
  10959. hr = _sg_d3d11_CreateTexture2D(_sg.d3d11.dev, &d3d11_tex_desc, init_data, &img->d3d11.tex2d);
  10960. if (!(SUCCEEDED(hr) && img->d3d11.tex2d)) {
  10961. _SG_ERROR(D3D11_CREATE_2D_TEXTURE_FAILED);
  10962. return SG_RESOURCESTATE_FAILED;
  10963. }
  10964. _sg_d3d11_setlabel(img->d3d11.tex2d, desc->label);
  10965. // create shader-resource-view for 2D texture
  10966. D3D11_SHADER_RESOURCE_VIEW_DESC d3d11_srv_desc;
  10967. _sg_clear(&d3d11_srv_desc, sizeof(d3d11_srv_desc));
  10968. d3d11_srv_desc.Format = _sg_d3d11_srv_pixel_format(img->cmn.pixel_format);
  10969. switch (img->cmn.type) {
  10970. case SG_IMAGETYPE_2D:
  10971. d3d11_srv_desc.ViewDimension = msaa ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D;
  10972. d3d11_srv_desc.Texture2D.MipLevels = (UINT)img->cmn.num_mipmaps;
  10973. break;
  10974. case SG_IMAGETYPE_CUBE:
  10975. d3d11_srv_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
  10976. d3d11_srv_desc.TextureCube.MipLevels = (UINT)img->cmn.num_mipmaps;
  10977. break;
  10978. case SG_IMAGETYPE_ARRAY:
  10979. d3d11_srv_desc.ViewDimension = msaa ? D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY : D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
  10980. d3d11_srv_desc.Texture2DArray.MipLevels = (UINT)img->cmn.num_mipmaps;
  10981. d3d11_srv_desc.Texture2DArray.ArraySize = (UINT)img->cmn.num_slices;
  10982. break;
  10983. default:
  10984. SOKOL_UNREACHABLE; break;
  10985. }
  10986. hr = _sg_d3d11_CreateShaderResourceView(_sg.d3d11.dev, (ID3D11Resource*)img->d3d11.tex2d, &d3d11_srv_desc, &img->d3d11.srv);
  10987. if (!(SUCCEEDED(hr) && img->d3d11.srv)) {
  10988. _SG_ERROR(D3D11_CREATE_2D_SRV_FAILED);
  10989. return SG_RESOURCESTATE_FAILED;
  10990. }
  10991. _sg_d3d11_setlabel(img->d3d11.srv, desc->label);
  10992. }
  10993. SOKOL_ASSERT(img->d3d11.tex2d);
  10994. img->d3d11.res = (ID3D11Resource*)img->d3d11.tex2d;
  10995. _sg_d3d11_AddRef(img->d3d11.res);
  10996. } else {
  10997. // 3D texture - same procedure, first check if injected, than create non-injected
  10998. if (injected) {
  10999. img->d3d11.tex3d = (ID3D11Texture3D*) desc->d3d11_texture;
  11000. _sg_d3d11_AddRef(img->d3d11.tex3d);
  11001. img->d3d11.srv = (ID3D11ShaderResourceView*) desc->d3d11_shader_resource_view;
  11002. if (img->d3d11.srv) {
  11003. _sg_d3d11_AddRef(img->d3d11.srv);
  11004. }
  11005. } else {
  11006. // not injected, create 3d texture
  11007. D3D11_TEXTURE3D_DESC d3d11_tex_desc;
  11008. _sg_clear(&d3d11_tex_desc, sizeof(d3d11_tex_desc));
  11009. d3d11_tex_desc.Width = (UINT)img->cmn.width;
  11010. d3d11_tex_desc.Height = (UINT)img->cmn.height;
  11011. d3d11_tex_desc.Depth = (UINT)img->cmn.num_slices;
  11012. d3d11_tex_desc.MipLevels = (UINT)img->cmn.num_mipmaps;
  11013. d3d11_tex_desc.Format = img->d3d11.format;
  11014. d3d11_tex_desc.BindFlags = _sg_d3d11_image_bind_flags(&img->cmn.usage, img->cmn.pixel_format);
  11015. d3d11_tex_desc.Usage = _sg_d3d11_image_usage(&img->cmn.usage);
  11016. d3d11_tex_desc.CPUAccessFlags = _sg_d3d11_image_cpu_access_flags(&img->cmn.usage);
  11017. if (img->d3d11.format == DXGI_FORMAT_UNKNOWN) {
  11018. _SG_ERROR(D3D11_CREATE_3D_TEXTURE_UNSUPPORTED_PIXEL_FORMAT);
  11019. return SG_RESOURCESTATE_FAILED;
  11020. }
  11021. hr = _sg_d3d11_CreateTexture3D(_sg.d3d11.dev, &d3d11_tex_desc, init_data, &img->d3d11.tex3d);
  11022. if (!(SUCCEEDED(hr) && img->d3d11.tex3d)) {
  11023. _SG_ERROR(D3D11_CREATE_3D_TEXTURE_FAILED);
  11024. return SG_RESOURCESTATE_FAILED;
  11025. }
  11026. _sg_d3d11_setlabel(img->d3d11.tex3d, desc->label);
  11027. // create shader-resource-view for 3D texture
  11028. if (!msaa) {
  11029. D3D11_SHADER_RESOURCE_VIEW_DESC d3d11_srv_desc;
  11030. _sg_clear(&d3d11_srv_desc, sizeof(d3d11_srv_desc));
  11031. d3d11_srv_desc.Format = _sg_d3d11_srv_pixel_format(img->cmn.pixel_format);
  11032. d3d11_srv_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D;
  11033. d3d11_srv_desc.Texture3D.MipLevels = (UINT)img->cmn.num_mipmaps;
  11034. hr = _sg_d3d11_CreateShaderResourceView(_sg.d3d11.dev, (ID3D11Resource*)img->d3d11.tex3d, &d3d11_srv_desc, &img->d3d11.srv);
  11035. if (!(SUCCEEDED(hr) && img->d3d11.srv)) {
  11036. _SG_ERROR(D3D11_CREATE_3D_SRV_FAILED);
  11037. return SG_RESOURCESTATE_FAILED;
  11038. }
  11039. _sg_d3d11_setlabel(img->d3d11.srv, desc->label);
  11040. }
  11041. }
  11042. SOKOL_ASSERT(img->d3d11.tex3d);
  11043. img->d3d11.res = (ID3D11Resource*)img->d3d11.tex3d;
  11044. _sg_d3d11_AddRef(img->d3d11.res);
  11045. }
  11046. return SG_RESOURCESTATE_VALID;
  11047. }
  11048. _SOKOL_PRIVATE void _sg_d3d11_discard_image(_sg_image_t* img) {
  11049. SOKOL_ASSERT(img);
  11050. if (img->d3d11.tex2d) {
  11051. _sg_d3d11_Release(img->d3d11.tex2d);
  11052. }
  11053. if (img->d3d11.tex3d) {
  11054. _sg_d3d11_Release(img->d3d11.tex3d);
  11055. }
  11056. if (img->d3d11.res) {
  11057. _sg_d3d11_Release(img->d3d11.res);
  11058. }
  11059. if (img->d3d11.srv) {
  11060. _sg_d3d11_Release(img->d3d11.srv);
  11061. }
  11062. }
  11063. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  11064. SOKOL_ASSERT(smp && desc);
  11065. SOKOL_ASSERT(0 == smp->d3d11.smp);
  11066. const bool injected = (0 != desc->d3d11_sampler);
  11067. if (injected) {
  11068. smp->d3d11.smp = (ID3D11SamplerState*)desc->d3d11_sampler;
  11069. _sg_d3d11_AddRef(smp->d3d11.smp);
  11070. } else {
  11071. D3D11_SAMPLER_DESC d3d11_smp_desc;
  11072. _sg_clear(&d3d11_smp_desc, sizeof(d3d11_smp_desc));
  11073. d3d11_smp_desc.Filter = _sg_d3d11_filter(desc->min_filter, desc->mag_filter, desc->mipmap_filter, desc->compare != SG_COMPAREFUNC_NEVER, desc->max_anisotropy);
  11074. d3d11_smp_desc.AddressU = _sg_d3d11_address_mode(desc->wrap_u);
  11075. d3d11_smp_desc.AddressV = _sg_d3d11_address_mode(desc->wrap_v);
  11076. d3d11_smp_desc.AddressW = _sg_d3d11_address_mode(desc->wrap_w);
  11077. d3d11_smp_desc.MipLODBias = 0.0f; // FIXME?
  11078. switch (desc->border_color) {
  11079. case SG_BORDERCOLOR_TRANSPARENT_BLACK:
  11080. // all 0.0f
  11081. break;
  11082. case SG_BORDERCOLOR_OPAQUE_WHITE:
  11083. for (int i = 0; i < 4; i++) {
  11084. d3d11_smp_desc.BorderColor[i] = 1.0f;
  11085. }
  11086. break;
  11087. default:
  11088. // opaque black
  11089. d3d11_smp_desc.BorderColor[3] = 1.0f;
  11090. break;
  11091. }
  11092. d3d11_smp_desc.MaxAnisotropy = desc->max_anisotropy;
  11093. d3d11_smp_desc.ComparisonFunc = _sg_d3d11_compare_func(desc->compare);
  11094. d3d11_smp_desc.MinLOD = desc->min_lod;
  11095. d3d11_smp_desc.MaxLOD = desc->max_lod;
  11096. HRESULT hr = _sg_d3d11_CreateSamplerState(_sg.d3d11.dev, &d3d11_smp_desc, &smp->d3d11.smp);
  11097. if (!(SUCCEEDED(hr) && smp->d3d11.smp)) {
  11098. _SG_ERROR(D3D11_CREATE_SAMPLER_STATE_FAILED);
  11099. return SG_RESOURCESTATE_FAILED;
  11100. }
  11101. _sg_d3d11_setlabel(smp->d3d11.smp, desc->label);
  11102. }
  11103. return SG_RESOURCESTATE_VALID;
  11104. }
  11105. _SOKOL_PRIVATE void _sg_d3d11_discard_sampler(_sg_sampler_t* smp) {
  11106. SOKOL_ASSERT(smp);
  11107. if (smp->d3d11.smp) {
  11108. _sg_d3d11_Release(smp->d3d11.smp);
  11109. }
  11110. }
  11111. _SOKOL_PRIVATE bool _sg_d3d11_load_d3dcompiler_dll(void) {
  11112. if ((0 == _sg.d3d11.d3dcompiler_dll) && !_sg.d3d11.d3dcompiler_dll_load_failed) {
  11113. _sg.d3d11.d3dcompiler_dll = LoadLibraryA("d3dcompiler_47.dll");
  11114. if (0 == _sg.d3d11.d3dcompiler_dll) {
  11115. // don't attempt to load missing DLL in the future
  11116. _SG_ERROR(D3D11_LOAD_D3DCOMPILER_47_DLL_FAILED);
  11117. _sg.d3d11.d3dcompiler_dll_load_failed = true;
  11118. return false;
  11119. }
  11120. // look up function pointers
  11121. _sg.d3d11.D3DCompile_func = (pD3DCompile)(void*) GetProcAddress(_sg.d3d11.d3dcompiler_dll, "D3DCompile");
  11122. SOKOL_ASSERT(_sg.d3d11.D3DCompile_func);
  11123. }
  11124. return 0 != _sg.d3d11.d3dcompiler_dll;
  11125. }
  11126. _SOKOL_PRIVATE ID3DBlob* _sg_d3d11_compile_shader(const sg_shader_function* shd_func) {
  11127. if (!_sg_d3d11_load_d3dcompiler_dll()) {
  11128. return NULL;
  11129. }
  11130. SOKOL_ASSERT(shd_func->d3d11_target);
  11131. UINT flags1 = D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR;
  11132. if (_sg.desc.d3d11_shader_debugging) {
  11133. flags1 |= D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
  11134. } else {
  11135. flags1 |= D3DCOMPILE_OPTIMIZATION_LEVEL3;
  11136. }
  11137. ID3DBlob* output = NULL;
  11138. ID3DBlob* errors_or_warnings = NULL;
  11139. HRESULT hr = _sg.d3d11.D3DCompile_func(
  11140. shd_func->source, // pSrcData
  11141. strlen(shd_func->source), // SrcDataSize
  11142. shd_func->d3d11_filepath, // pSourceName
  11143. NULL, // pDefines
  11144. D3D_COMPILE_STANDARD_FILE_INCLUDE, // pInclude
  11145. shd_func->entry ? shd_func->entry : "main", // pEntryPoint
  11146. shd_func->d3d11_target, // pTarget
  11147. flags1, // Flags1
  11148. 0, // Flags2
  11149. &output, // ppCode
  11150. &errors_or_warnings); // ppErrorMsgs
  11151. if (FAILED(hr)) {
  11152. _SG_ERROR(D3D11_SHADER_COMPILATION_FAILED);
  11153. }
  11154. if (errors_or_warnings) {
  11155. _SG_WARN(D3D11_SHADER_COMPILATION_OUTPUT);
  11156. _SG_LOGMSG(D3D11_SHADER_COMPILATION_OUTPUT, (LPCSTR)_sg_d3d11_GetBufferPointer(errors_or_warnings));
  11157. _sg_d3d11_Release(errors_or_warnings); errors_or_warnings = NULL;
  11158. }
  11159. if (FAILED(hr)) {
  11160. // just in case, usually output is NULL here
  11161. if (output) {
  11162. _sg_d3d11_Release(output);
  11163. output = NULL;
  11164. }
  11165. }
  11166. return output;
  11167. }
  11168. // NOTE: this is an out-of-range check for HLSL bindslots that's also active in release mode
  11169. _SOKOL_PRIVATE bool _sg_d3d11_ensure_hlsl_bindslot_ranges(const sg_shader_desc* desc) {
  11170. SOKOL_ASSERT(desc);
  11171. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  11172. if (desc->uniform_blocks[i].hlsl_register_b_n >= _SG_D3D11_MAX_STAGE_UB_BINDINGS) {
  11173. _SG_ERROR(D3D11_UNIFORMBLOCK_HLSL_REGISTER_B_OUT_OF_RANGE);
  11174. return false;
  11175. }
  11176. }
  11177. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  11178. if (desc->storage_buffers[i].hlsl_register_t_n >= _SG_D3D11_MAX_STAGE_SRV_BINDINGS) {
  11179. _SG_ERROR(D3D11_STORAGEBUFFER_HLSL_REGISTER_T_OUT_OF_RANGE);
  11180. return false;
  11181. }
  11182. if (desc->storage_buffers[i].hlsl_register_u_n >= _SG_D3D11_MAX_STAGE_UAV_BINDINGS) {
  11183. _SG_ERROR(D3D11_STORAGEBUFFER_HLSL_REGISTER_U_OUT_OF_RANGE);
  11184. return false;
  11185. }
  11186. }
  11187. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  11188. if (desc->images[i].hlsl_register_t_n >= _SG_D3D11_MAX_STAGE_SRV_BINDINGS) {
  11189. _SG_ERROR(D3D11_IMAGE_HLSL_REGISTER_T_OUT_OF_RANGE);
  11190. return false;
  11191. }
  11192. }
  11193. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  11194. if (desc->samplers[i].hlsl_register_s_n >= _SG_D3D11_MAX_STAGE_SMP_BINDINGS) {
  11195. _SG_ERROR(D3D11_SAMPLER_HLSL_REGISTER_S_OUT_OF_RANGE);
  11196. return false;
  11197. }
  11198. }
  11199. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  11200. if (desc->storage_images[i].hlsl_register_u_n >= _SG_D3D11_MAX_STAGE_UAV_BINDINGS) {
  11201. _SG_ERROR(D3D11_STORAGEIMAGE_HLSL_REGISTER_U_OUT_OF_RANGE);
  11202. return false;
  11203. }
  11204. }
  11205. return true;
  11206. }
  11207. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  11208. SOKOL_ASSERT(shd && desc);
  11209. SOKOL_ASSERT(!shd->d3d11.vs && !shd->d3d11.fs && !shd->d3d11.cs && !shd->d3d11.vs_blob);
  11210. HRESULT hr;
  11211. // perform a range-check on HLSL bindslots that's also active in release
  11212. // mode to avoid potential out-of-bounds array accesses
  11213. if (!_sg_d3d11_ensure_hlsl_bindslot_ranges(desc)) {
  11214. return SG_RESOURCESTATE_FAILED;
  11215. }
  11216. // copy vertex attribute semantic names and indices
  11217. for (size_t i = 0; i < SG_MAX_VERTEX_ATTRIBUTES; i++) {
  11218. _sg_strcpy(&shd->d3d11.attrs[i].sem_name, desc->attrs[i].hlsl_sem_name);
  11219. shd->d3d11.attrs[i].sem_index = desc->attrs[i].hlsl_sem_index;
  11220. }
  11221. // copy HLSL bind slots
  11222. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  11223. shd->d3d11.ub_register_b_n[i] = desc->uniform_blocks[i].hlsl_register_b_n;
  11224. }
  11225. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  11226. shd->d3d11.sbuf_register_t_n[i] = desc->storage_buffers[i].hlsl_register_t_n;
  11227. shd->d3d11.sbuf_register_u_n[i] = desc->storage_buffers[i].hlsl_register_u_n;
  11228. }
  11229. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  11230. shd->d3d11.img_register_t_n[i] = desc->images[i].hlsl_register_t_n;
  11231. }
  11232. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  11233. shd->d3d11.smp_register_s_n[i] = desc->samplers[i].hlsl_register_s_n;
  11234. }
  11235. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  11236. shd->d3d11.simg_register_u_n[i] = desc->storage_images[i].hlsl_register_u_n;
  11237. }
  11238. // create a D3D constant buffer for each uniform block
  11239. for (size_t ub_index = 0; ub_index < SG_MAX_UNIFORMBLOCK_BINDSLOTS; ub_index++) {
  11240. const sg_shader_stage stage = desc->uniform_blocks[ub_index].stage;
  11241. if (stage == SG_SHADERSTAGE_NONE) {
  11242. continue;
  11243. }
  11244. const _sg_shader_uniform_block_t* ub = &shd->cmn.uniform_blocks[ub_index];
  11245. ID3D11Buffer* cbuf = 0;
  11246. D3D11_BUFFER_DESC cb_desc;
  11247. _sg_clear(&cb_desc, sizeof(cb_desc));
  11248. cb_desc.ByteWidth = (UINT)_sg_roundup((int)ub->size, 16);
  11249. cb_desc.Usage = D3D11_USAGE_DEFAULT;
  11250. cb_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  11251. hr = _sg_d3d11_CreateBuffer(_sg.d3d11.dev, &cb_desc, NULL, &cbuf);
  11252. if (!(SUCCEEDED(hr) && cbuf)) {
  11253. _SG_ERROR(D3D11_CREATE_CONSTANT_BUFFER_FAILED);
  11254. return SG_RESOURCESTATE_FAILED;
  11255. }
  11256. _sg_d3d11_setlabel(cbuf, desc->label);
  11257. shd->d3d11.all_cbufs[ub_index] = cbuf;
  11258. const uint8_t d3d11_slot = shd->d3d11.ub_register_b_n[ub_index];
  11259. SOKOL_ASSERT(d3d11_slot < _SG_D3D11_MAX_STAGE_UB_BINDINGS);
  11260. if (stage == SG_SHADERSTAGE_VERTEX) {
  11261. SOKOL_ASSERT(0 == shd->d3d11.vs_cbufs[d3d11_slot]);
  11262. shd->d3d11.vs_cbufs[d3d11_slot] = cbuf;
  11263. } else if (stage == SG_SHADERSTAGE_FRAGMENT) {
  11264. SOKOL_ASSERT(0 == shd->d3d11.fs_cbufs[d3d11_slot]);
  11265. shd->d3d11.fs_cbufs[d3d11_slot] = cbuf;
  11266. } else if (stage == SG_SHADERSTAGE_COMPUTE) {
  11267. SOKOL_ASSERT(0 == shd->d3d11.cs_cbufs[d3d11_slot]);
  11268. shd->d3d11.cs_cbufs[d3d11_slot] = cbuf;
  11269. } else {
  11270. SOKOL_UNREACHABLE;
  11271. }
  11272. }
  11273. // create shader functions
  11274. const bool has_vs = desc->vertex_func.bytecode.ptr || desc->vertex_func.source;
  11275. const bool has_fs = desc->fragment_func.bytecode.ptr || desc->fragment_func.source;
  11276. const bool has_cs = desc->compute_func.bytecode.ptr || desc->compute_func.source;
  11277. bool vs_valid = false; bool fs_valid = false; bool cs_valid = false;
  11278. if (has_vs) {
  11279. const void* vs_ptr = 0; SIZE_T vs_length = 0;
  11280. ID3DBlob* vs_blob = 0;
  11281. if (desc->vertex_func.bytecode.ptr) {
  11282. SOKOL_ASSERT(desc->vertex_func.bytecode.size > 0);
  11283. vs_ptr = desc->vertex_func.bytecode.ptr;
  11284. vs_length = desc->vertex_func.bytecode.size;
  11285. } else {
  11286. SOKOL_ASSERT(desc->vertex_func.source);
  11287. vs_blob = _sg_d3d11_compile_shader(&desc->vertex_func);
  11288. if (vs_blob) {
  11289. vs_ptr = _sg_d3d11_GetBufferPointer(vs_blob);
  11290. vs_length = _sg_d3d11_GetBufferSize(vs_blob);
  11291. }
  11292. }
  11293. if (vs_ptr && (vs_length > 0)) {
  11294. hr = _sg_d3d11_CreateVertexShader(_sg.d3d11.dev, vs_ptr, vs_length, NULL, &shd->d3d11.vs);
  11295. vs_valid = SUCCEEDED(hr) && shd->d3d11.vs;
  11296. }
  11297. // set label, and need to store a copy of the vertex shader blob for the pipeline creation
  11298. if (vs_valid) {
  11299. _sg_d3d11_setlabel(shd->d3d11.vs, desc->label);
  11300. shd->d3d11.vs_blob_length = vs_length;
  11301. shd->d3d11.vs_blob = _sg_malloc((size_t)vs_length);
  11302. SOKOL_ASSERT(shd->d3d11.vs_blob);
  11303. memcpy(shd->d3d11.vs_blob, vs_ptr, vs_length);
  11304. }
  11305. if (vs_blob) {
  11306. _sg_d3d11_Release(vs_blob);
  11307. }
  11308. }
  11309. if (has_fs) {
  11310. const void* fs_ptr = 0; SIZE_T fs_length = 0;
  11311. ID3DBlob* fs_blob = 0;
  11312. if (desc->fragment_func.bytecode.ptr) {
  11313. SOKOL_ASSERT(desc->fragment_func.bytecode.size > 0);
  11314. fs_ptr = desc->fragment_func.bytecode.ptr;
  11315. fs_length = desc->fragment_func.bytecode.size;
  11316. } else {
  11317. SOKOL_ASSERT(desc->fragment_func.source);
  11318. fs_blob = _sg_d3d11_compile_shader(&desc->fragment_func);
  11319. if (fs_blob) {
  11320. fs_ptr = _sg_d3d11_GetBufferPointer(fs_blob);
  11321. fs_length = _sg_d3d11_GetBufferSize(fs_blob);
  11322. }
  11323. }
  11324. if (fs_ptr && (fs_length > 0)) {
  11325. hr = _sg_d3d11_CreatePixelShader(_sg.d3d11.dev, fs_ptr, fs_length, NULL, &shd->d3d11.fs);
  11326. fs_valid = SUCCEEDED(hr) && shd->d3d11.fs;
  11327. }
  11328. if (fs_valid) {
  11329. _sg_d3d11_setlabel(shd->d3d11.fs, desc->label);
  11330. }
  11331. if (fs_blob) {
  11332. _sg_d3d11_Release(fs_blob);
  11333. }
  11334. }
  11335. if (has_cs) {
  11336. const void* cs_ptr = 0; SIZE_T cs_length = 0;
  11337. ID3DBlob* cs_blob = 0;
  11338. if (desc->compute_func.bytecode.ptr) {
  11339. SOKOL_ASSERT(desc->compute_func.bytecode.size > 0);
  11340. cs_ptr = desc->compute_func.bytecode.ptr;
  11341. cs_length = desc->compute_func.bytecode.size;
  11342. } else {
  11343. SOKOL_ASSERT(desc->compute_func.source);
  11344. cs_blob = _sg_d3d11_compile_shader(&desc->compute_func);
  11345. if (cs_blob) {
  11346. cs_ptr = _sg_d3d11_GetBufferPointer(cs_blob);
  11347. cs_length = _sg_d3d11_GetBufferSize(cs_blob);
  11348. }
  11349. }
  11350. if (cs_ptr && (cs_length > 0)) {
  11351. hr = _sg_d3d11_CreateComputeShader(_sg.d3d11.dev, cs_ptr, cs_length, NULL, &shd->d3d11.cs);
  11352. cs_valid = SUCCEEDED(hr) && shd->d3d11.cs;
  11353. }
  11354. if (cs_blob) {
  11355. _sg_d3d11_Release(cs_blob);
  11356. }
  11357. }
  11358. if ((vs_valid && fs_valid) || cs_valid) {
  11359. return SG_RESOURCESTATE_VALID;
  11360. } else {
  11361. return SG_RESOURCESTATE_FAILED;
  11362. }
  11363. }
  11364. _SOKOL_PRIVATE void _sg_d3d11_discard_shader(_sg_shader_t* shd) {
  11365. SOKOL_ASSERT(shd);
  11366. if (shd->d3d11.vs) {
  11367. _sg_d3d11_Release(shd->d3d11.vs);
  11368. }
  11369. if (shd->d3d11.fs) {
  11370. _sg_d3d11_Release(shd->d3d11.fs);
  11371. }
  11372. if (shd->d3d11.cs) {
  11373. _sg_d3d11_Release(shd->d3d11.cs);
  11374. }
  11375. if (shd->d3d11.vs_blob) {
  11376. _sg_free(shd->d3d11.vs_blob);
  11377. }
  11378. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  11379. if (shd->d3d11.all_cbufs[i]) {
  11380. _sg_d3d11_Release(shd->d3d11.all_cbufs[i]);
  11381. }
  11382. }
  11383. }
  11384. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_pipeline(_sg_pipeline_t* pip, const sg_pipeline_desc* desc) {
  11385. SOKOL_ASSERT(pip && desc);
  11386. _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  11387. // if this is a compute pipeline, we're done here
  11388. if (pip->cmn.is_compute) {
  11389. return SG_RESOURCESTATE_VALID;
  11390. }
  11391. // a render pipeline...
  11392. SOKOL_ASSERT(shd->d3d11.vs_blob && shd->d3d11.vs_blob_length > 0);
  11393. SOKOL_ASSERT(!pip->d3d11.il && !pip->d3d11.rs && !pip->d3d11.dss && !pip->d3d11.bs);
  11394. pip->d3d11.index_format = _sg_d3d11_index_format(pip->cmn.index_type);
  11395. pip->d3d11.topology = _sg_d3d11_primitive_topology(desc->primitive_type);
  11396. pip->d3d11.stencil_ref = desc->stencil.ref;
  11397. // create input layout object
  11398. HRESULT hr;
  11399. D3D11_INPUT_ELEMENT_DESC d3d11_comps[SG_MAX_VERTEX_ATTRIBUTES];
  11400. _sg_clear(d3d11_comps, sizeof(d3d11_comps));
  11401. size_t attr_index = 0;
  11402. for (; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  11403. const sg_vertex_attr_state* a_state = &desc->layout.attrs[attr_index];
  11404. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  11405. break;
  11406. }
  11407. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  11408. SOKOL_ASSERT(pip->cmn.vertex_buffer_layout_active[a_state->buffer_index]);
  11409. const sg_vertex_buffer_layout_state* l_state = &desc->layout.buffers[a_state->buffer_index];
  11410. const sg_vertex_step step_func = l_state->step_func;
  11411. const int step_rate = l_state->step_rate;
  11412. D3D11_INPUT_ELEMENT_DESC* d3d11_comp = &d3d11_comps[attr_index];
  11413. d3d11_comp->SemanticName = _sg_strptr(&shd->d3d11.attrs[attr_index].sem_name);
  11414. d3d11_comp->SemanticIndex = (UINT)shd->d3d11.attrs[attr_index].sem_index;
  11415. d3d11_comp->Format = _sg_d3d11_vertex_format(a_state->format);
  11416. d3d11_comp->InputSlot = (UINT)a_state->buffer_index;
  11417. d3d11_comp->AlignedByteOffset = (UINT)a_state->offset;
  11418. d3d11_comp->InputSlotClass = _sg_d3d11_input_classification(step_func);
  11419. if (SG_VERTEXSTEP_PER_INSTANCE == step_func) {
  11420. d3d11_comp->InstanceDataStepRate = (UINT)step_rate;
  11421. pip->cmn.use_instanced_draw = true;
  11422. }
  11423. }
  11424. for (size_t layout_index = 0; layout_index < SG_MAX_VERTEXBUFFER_BINDSLOTS; layout_index++) {
  11425. if (pip->cmn.vertex_buffer_layout_active[layout_index]) {
  11426. const sg_vertex_buffer_layout_state* l_state = &desc->layout.buffers[layout_index];
  11427. SOKOL_ASSERT(l_state->stride > 0);
  11428. pip->d3d11.vb_strides[layout_index] = (UINT)l_state->stride;
  11429. } else {
  11430. pip->d3d11.vb_strides[layout_index] = 0;
  11431. }
  11432. }
  11433. if (attr_index > 0) {
  11434. hr = _sg_d3d11_CreateInputLayout(_sg.d3d11.dev,
  11435. d3d11_comps, // pInputElementDesc
  11436. (UINT)attr_index, // NumElements
  11437. shd->d3d11.vs_blob, // pShaderByteCodeWithInputSignature
  11438. shd->d3d11.vs_blob_length, // BytecodeLength
  11439. &pip->d3d11.il);
  11440. if (!(SUCCEEDED(hr) && pip->d3d11.il)) {
  11441. _SG_ERROR(D3D11_CREATE_INPUT_LAYOUT_FAILED);
  11442. return SG_RESOURCESTATE_FAILED;
  11443. }
  11444. _sg_d3d11_setlabel(pip->d3d11.il, desc->label);
  11445. }
  11446. // create rasterizer state
  11447. D3D11_RASTERIZER_DESC rs_desc;
  11448. _sg_clear(&rs_desc, sizeof(rs_desc));
  11449. rs_desc.FillMode = D3D11_FILL_SOLID;
  11450. rs_desc.CullMode = _sg_d3d11_cull_mode(desc->cull_mode);
  11451. rs_desc.FrontCounterClockwise = desc->face_winding == SG_FACEWINDING_CCW;
  11452. rs_desc.DepthBias = (INT) pip->cmn.depth.bias;
  11453. rs_desc.DepthBiasClamp = pip->cmn.depth.bias_clamp;
  11454. rs_desc.SlopeScaledDepthBias = pip->cmn.depth.bias_slope_scale;
  11455. rs_desc.DepthClipEnable = TRUE;
  11456. rs_desc.ScissorEnable = TRUE;
  11457. rs_desc.MultisampleEnable = desc->sample_count > 1;
  11458. rs_desc.AntialiasedLineEnable = FALSE;
  11459. hr = _sg_d3d11_CreateRasterizerState(_sg.d3d11.dev, &rs_desc, &pip->d3d11.rs);
  11460. if (!(SUCCEEDED(hr) && pip->d3d11.rs)) {
  11461. _SG_ERROR(D3D11_CREATE_RASTERIZER_STATE_FAILED);
  11462. return SG_RESOURCESTATE_FAILED;
  11463. }
  11464. _sg_d3d11_setlabel(pip->d3d11.rs, desc->label);
  11465. // create depth-stencil state
  11466. D3D11_DEPTH_STENCIL_DESC dss_desc;
  11467. _sg_clear(&dss_desc, sizeof(dss_desc));
  11468. dss_desc.DepthEnable = TRUE;
  11469. dss_desc.DepthWriteMask = desc->depth.write_enabled ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
  11470. dss_desc.DepthFunc = _sg_d3d11_compare_func(desc->depth.compare);
  11471. dss_desc.StencilEnable = desc->stencil.enabled;
  11472. dss_desc.StencilReadMask = desc->stencil.read_mask;
  11473. dss_desc.StencilWriteMask = desc->stencil.write_mask;
  11474. const sg_stencil_face_state* sf = &desc->stencil.front;
  11475. dss_desc.FrontFace.StencilFailOp = _sg_d3d11_stencil_op(sf->fail_op);
  11476. dss_desc.FrontFace.StencilDepthFailOp = _sg_d3d11_stencil_op(sf->depth_fail_op);
  11477. dss_desc.FrontFace.StencilPassOp = _sg_d3d11_stencil_op(sf->pass_op);
  11478. dss_desc.FrontFace.StencilFunc = _sg_d3d11_compare_func(sf->compare);
  11479. const sg_stencil_face_state* sb = &desc->stencil.back;
  11480. dss_desc.BackFace.StencilFailOp = _sg_d3d11_stencil_op(sb->fail_op);
  11481. dss_desc.BackFace.StencilDepthFailOp = _sg_d3d11_stencil_op(sb->depth_fail_op);
  11482. dss_desc.BackFace.StencilPassOp = _sg_d3d11_stencil_op(sb->pass_op);
  11483. dss_desc.BackFace.StencilFunc = _sg_d3d11_compare_func(sb->compare);
  11484. hr = _sg_d3d11_CreateDepthStencilState(_sg.d3d11.dev, &dss_desc, &pip->d3d11.dss);
  11485. if (!(SUCCEEDED(hr) && pip->d3d11.dss)) {
  11486. _SG_ERROR(D3D11_CREATE_DEPTH_STENCIL_STATE_FAILED);
  11487. return SG_RESOURCESTATE_FAILED;
  11488. }
  11489. _sg_d3d11_setlabel(pip->d3d11.dss, desc->label);
  11490. // create blend state
  11491. D3D11_BLEND_DESC bs_desc;
  11492. _sg_clear(&bs_desc, sizeof(bs_desc));
  11493. bs_desc.AlphaToCoverageEnable = desc->alpha_to_coverage_enabled;
  11494. bs_desc.IndependentBlendEnable = TRUE;
  11495. {
  11496. size_t i = 0;
  11497. for (i = 0; i < (size_t)desc->color_count; i++) {
  11498. const sg_blend_state* src = &desc->colors[i].blend;
  11499. D3D11_RENDER_TARGET_BLEND_DESC* dst = &bs_desc.RenderTarget[i];
  11500. dst->BlendEnable = src->enabled;
  11501. dst->SrcBlend = _sg_d3d11_blend_factor(src->src_factor_rgb);
  11502. dst->DestBlend = _sg_d3d11_blend_factor(src->dst_factor_rgb);
  11503. dst->BlendOp = _sg_d3d11_blend_op(src->op_rgb);
  11504. dst->SrcBlendAlpha = _sg_d3d11_blend_factor(src->src_factor_alpha);
  11505. dst->DestBlendAlpha = _sg_d3d11_blend_factor(src->dst_factor_alpha);
  11506. dst->BlendOpAlpha = _sg_d3d11_blend_op(src->op_alpha);
  11507. dst->RenderTargetWriteMask = _sg_d3d11_color_write_mask(desc->colors[i].write_mask);
  11508. }
  11509. for (; i < 8; i++) {
  11510. D3D11_RENDER_TARGET_BLEND_DESC* dst = &bs_desc.RenderTarget[i];
  11511. dst->BlendEnable = FALSE;
  11512. dst->SrcBlend = dst->SrcBlendAlpha = D3D11_BLEND_ONE;
  11513. dst->DestBlend = dst->DestBlendAlpha = D3D11_BLEND_ZERO;
  11514. dst->BlendOp = dst->BlendOpAlpha = D3D11_BLEND_OP_ADD;
  11515. dst->RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
  11516. }
  11517. }
  11518. hr = _sg_d3d11_CreateBlendState(_sg.d3d11.dev, &bs_desc, &pip->d3d11.bs);
  11519. if (!(SUCCEEDED(hr) && pip->d3d11.bs)) {
  11520. _SG_ERROR(D3D11_CREATE_BLEND_STATE_FAILED);
  11521. return SG_RESOURCESTATE_FAILED;
  11522. }
  11523. _sg_d3d11_setlabel(pip->d3d11.bs, desc->label);
  11524. return SG_RESOURCESTATE_VALID;
  11525. }
  11526. _SOKOL_PRIVATE void _sg_d3d11_discard_pipeline(_sg_pipeline_t* pip) {
  11527. SOKOL_ASSERT(pip);
  11528. if (pip->d3d11.il) {
  11529. _sg_d3d11_Release(pip->d3d11.il);
  11530. }
  11531. if (pip->d3d11.rs) {
  11532. _sg_d3d11_Release(pip->d3d11.rs);
  11533. }
  11534. if (pip->d3d11.dss) {
  11535. _sg_d3d11_Release(pip->d3d11.dss);
  11536. }
  11537. if (pip->d3d11.bs) {
  11538. _sg_d3d11_Release(pip->d3d11.bs);
  11539. }
  11540. }
  11541. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_attachments(_sg_attachments_t* atts, const sg_attachments_desc* desc) {
  11542. SOKOL_ASSERT(atts && desc);
  11543. SOKOL_ASSERT(_sg.d3d11.dev);
  11544. _SOKOL_UNUSED(desc);
  11545. // create render-target views
  11546. for (int i = 0; i < atts->cmn.num_colors; i++) {
  11547. const _sg_attachment_common_t* cmn_color_att = &atts->cmn.colors[i];
  11548. const _sg_image_t* clr_img = _sg_image_ref_ptr(&atts->cmn.colors[i].image);
  11549. SOKOL_ASSERT(0 == atts->d3d11.colors[i].view.rtv);
  11550. const bool msaa = clr_img->cmn.sample_count > 1;
  11551. D3D11_RENDER_TARGET_VIEW_DESC d3d11_rtv_desc;
  11552. _sg_clear(&d3d11_rtv_desc, sizeof(d3d11_rtv_desc));
  11553. d3d11_rtv_desc.Format = _sg_d3d11_rtv_uav_pixel_format(clr_img->cmn.pixel_format);
  11554. switch (clr_img->cmn.type) {
  11555. case SG_IMAGETYPE_2D:
  11556. if (msaa) {
  11557. d3d11_rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS;
  11558. } else {
  11559. d3d11_rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
  11560. d3d11_rtv_desc.Texture2D.MipSlice = (UINT)cmn_color_att->mip_level;
  11561. }
  11562. break;
  11563. case SG_IMAGETYPE_CUBE:
  11564. case SG_IMAGETYPE_ARRAY:
  11565. if (msaa) {
  11566. d3d11_rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY;
  11567. d3d11_rtv_desc.Texture2DMSArray.FirstArraySlice = (UINT)cmn_color_att->slice;
  11568. d3d11_rtv_desc.Texture2DMSArray.ArraySize = 1;
  11569. } else {
  11570. d3d11_rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
  11571. d3d11_rtv_desc.Texture2DArray.MipSlice = (UINT)cmn_color_att->mip_level;
  11572. d3d11_rtv_desc.Texture2DArray.FirstArraySlice = (UINT)cmn_color_att->slice;
  11573. d3d11_rtv_desc.Texture2DArray.ArraySize = 1;
  11574. }
  11575. break;
  11576. case SG_IMAGETYPE_3D:
  11577. SOKOL_ASSERT(!msaa);
  11578. d3d11_rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE3D;
  11579. d3d11_rtv_desc.Texture3D.MipSlice = (UINT)cmn_color_att->mip_level;
  11580. d3d11_rtv_desc.Texture3D.FirstWSlice = (UINT)cmn_color_att->slice;
  11581. d3d11_rtv_desc.Texture3D.WSize = 1;
  11582. break;
  11583. default: SOKOL_UNREACHABLE; break;
  11584. }
  11585. SOKOL_ASSERT(clr_img->d3d11.res);
  11586. HRESULT hr = _sg_d3d11_CreateRenderTargetView(_sg.d3d11.dev, clr_img->d3d11.res, &d3d11_rtv_desc, &atts->d3d11.colors[i].view.rtv);
  11587. if (!(SUCCEEDED(hr) && atts->d3d11.colors[i].view.rtv)) {
  11588. _SG_ERROR(D3D11_CREATE_RTV_FAILED);
  11589. return SG_RESOURCESTATE_FAILED;
  11590. }
  11591. _sg_d3d11_setlabel(atts->d3d11.colors[i].view.rtv, desc->label);
  11592. }
  11593. SOKOL_ASSERT(0 == atts->d3d11.depth_stencil.view.dsv);
  11594. if (!_sg_image_ref_null(&atts->cmn.depth_stencil.image)) {
  11595. const _sg_attachment_common_t* cmn_ds_att = &atts->cmn.depth_stencil;
  11596. const _sg_image_t* ds_img = _sg_image_ref_ptr(&atts->cmn.depth_stencil.image);
  11597. const bool msaa = ds_img->cmn.sample_count > 1;
  11598. D3D11_DEPTH_STENCIL_VIEW_DESC d3d11_dsv_desc;
  11599. _sg_clear(&d3d11_dsv_desc, sizeof(d3d11_dsv_desc));
  11600. d3d11_dsv_desc.Format = _sg_d3d11_dsv_pixel_format(ds_img->cmn.pixel_format);
  11601. SOKOL_ASSERT(ds_img && ds_img->cmn.type != SG_IMAGETYPE_3D);
  11602. switch(ds_img->cmn.type) {
  11603. case SG_IMAGETYPE_2D:
  11604. if (msaa) {
  11605. d3d11_dsv_desc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
  11606. } else {
  11607. d3d11_dsv_desc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
  11608. d3d11_dsv_desc.Texture2D.MipSlice = (UINT)cmn_ds_att->mip_level;
  11609. }
  11610. break;
  11611. case SG_IMAGETYPE_CUBE:
  11612. case SG_IMAGETYPE_ARRAY:
  11613. if (msaa) {
  11614. d3d11_dsv_desc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY;
  11615. d3d11_dsv_desc.Texture2DMSArray.FirstArraySlice = (UINT)cmn_ds_att->slice;
  11616. d3d11_dsv_desc.Texture2DMSArray.ArraySize = 1;
  11617. } else {
  11618. d3d11_dsv_desc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DARRAY;
  11619. d3d11_dsv_desc.Texture2DArray.MipSlice = (UINT)cmn_ds_att->mip_level;
  11620. d3d11_dsv_desc.Texture2DArray.FirstArraySlice = (UINT)cmn_ds_att->slice;
  11621. d3d11_dsv_desc.Texture2DArray.ArraySize = 1;
  11622. }
  11623. break;
  11624. default: SOKOL_UNREACHABLE; break;
  11625. }
  11626. SOKOL_ASSERT(ds_img->d3d11.res);
  11627. HRESULT hr = _sg_d3d11_CreateDepthStencilView(_sg.d3d11.dev, ds_img->d3d11.res, &d3d11_dsv_desc, &atts->d3d11.depth_stencil.view.dsv);
  11628. if (!(SUCCEEDED(hr) && atts->d3d11.depth_stencil.view.dsv)) {
  11629. _SG_ERROR(D3D11_CREATE_DSV_FAILED);
  11630. return SG_RESOURCESTATE_FAILED;
  11631. }
  11632. _sg_d3d11_setlabel(atts->d3d11.depth_stencil.view.dsv, desc->label);
  11633. }
  11634. // create storage attachments unordered access views
  11635. for (int i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  11636. const _sg_attachment_common_t* cmn_stg_att = &atts->cmn.storages[i];
  11637. const _sg_image_t* stg_img = _sg_image_ref_ptr_or_null(&atts->cmn.storages[i].image);
  11638. if (!stg_img) {
  11639. continue;
  11640. }
  11641. SOKOL_ASSERT(stg_img->cmn.sample_count == 1);
  11642. SOKOL_ASSERT(0 == atts->d3d11.storages[i].view.uav);
  11643. D3D11_UNORDERED_ACCESS_VIEW_DESC d3d11_uav_desc;
  11644. _sg_clear(&d3d11_uav_desc, sizeof(d3d11_uav_desc));
  11645. d3d11_uav_desc.Format = _sg_d3d11_rtv_uav_pixel_format(stg_img->cmn.pixel_format);
  11646. switch (stg_img->cmn.type) {
  11647. case SG_IMAGETYPE_2D:
  11648. d3d11_uav_desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D;
  11649. d3d11_uav_desc.Texture2D.MipSlice = (UINT)cmn_stg_att->mip_level;
  11650. break;
  11651. case SG_IMAGETYPE_CUBE:
  11652. case SG_IMAGETYPE_ARRAY:
  11653. d3d11_uav_desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2DARRAY;
  11654. d3d11_uav_desc.Texture2DArray.MipSlice = (UINT)cmn_stg_att->mip_level;
  11655. d3d11_uav_desc.Texture2DArray.FirstArraySlice = (UINT)cmn_stg_att->slice;
  11656. d3d11_uav_desc.Texture2DArray.ArraySize = 1;
  11657. break;
  11658. case SG_IMAGETYPE_3D:
  11659. d3d11_uav_desc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE3D;
  11660. d3d11_uav_desc.Texture3D.MipSlice = (UINT)cmn_stg_att->mip_level;
  11661. d3d11_uav_desc.Texture3D.FirstWSlice = (UINT)cmn_stg_att->slice;
  11662. d3d11_uav_desc.Texture3D.WSize = 1;
  11663. break;
  11664. default: SOKOL_UNREACHABLE; break;
  11665. }
  11666. SOKOL_ASSERT(stg_img->d3d11.res);
  11667. HRESULT hr = _sg_d3d11_CreateUnorderedAccessView(_sg.d3d11.dev, stg_img->d3d11.res, &d3d11_uav_desc, &atts->d3d11.storages[i].view.uav);
  11668. if (!(SUCCEEDED(hr) && atts->d3d11.storages[i].view.uav)) {
  11669. _SG_ERROR(D3D11_CREATE_UAV_FAILED);
  11670. return SG_RESOURCESTATE_FAILED;
  11671. }
  11672. _sg_d3d11_setlabel(atts->d3d11.storages[i].view.uav, desc->label);
  11673. }
  11674. return SG_RESOURCESTATE_VALID;
  11675. }
  11676. _SOKOL_PRIVATE void _sg_d3d11_discard_attachments(_sg_attachments_t* atts) {
  11677. SOKOL_ASSERT(atts);
  11678. for (size_t i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  11679. if (atts->d3d11.colors[i].view.rtv) {
  11680. _sg_d3d11_Release(atts->d3d11.colors[i].view.rtv);
  11681. }
  11682. }
  11683. if (atts->d3d11.depth_stencil.view.dsv) {
  11684. _sg_d3d11_Release(atts->d3d11.depth_stencil.view.dsv);
  11685. }
  11686. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  11687. if (atts->d3d11.storages[i].view.uav) {
  11688. _sg_d3d11_Release(atts->d3d11.storages[i].view.uav);
  11689. }
  11690. }
  11691. }
  11692. _SOKOL_PRIVATE void _sg_d3d11_begin_pass(const sg_pass* pass) {
  11693. SOKOL_ASSERT(pass);
  11694. if (_sg.cur_pass.is_compute) {
  11695. // nothing to do in compute passes
  11696. return;
  11697. }
  11698. const _sg_attachments_t* atts = _sg_attachments_ref_ptr_or_null(&_sg.cur_pass.atts);
  11699. const sg_swapchain* swapchain = &pass->swapchain;
  11700. const sg_pass_action* action = &pass->action;
  11701. int num_rtvs = 0;
  11702. ID3D11RenderTargetView* rtvs[SG_MAX_COLOR_ATTACHMENTS] = { 0 };
  11703. ID3D11DepthStencilView* dsv = 0;
  11704. _sg.d3d11.cur_pass.render_view = 0;
  11705. _sg.d3d11.cur_pass.resolve_view = 0;
  11706. if (atts) {
  11707. num_rtvs = atts->cmn.num_colors;
  11708. for (size_t i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  11709. rtvs[i] = atts->d3d11.colors[i].view.rtv;
  11710. }
  11711. dsv = atts->d3d11.depth_stencil.view.dsv;
  11712. } else {
  11713. // NOTE: depth-stencil-view is optional
  11714. SOKOL_ASSERT(swapchain->d3d11.render_view);
  11715. num_rtvs = 1;
  11716. rtvs[0] = (ID3D11RenderTargetView*) swapchain->d3d11.render_view;
  11717. dsv = (ID3D11DepthStencilView*) swapchain->d3d11.depth_stencil_view;
  11718. _sg.d3d11.cur_pass.render_view = (ID3D11RenderTargetView*) swapchain->d3d11.render_view;
  11719. _sg.d3d11.cur_pass.resolve_view = (ID3D11RenderTargetView*) swapchain->d3d11.resolve_view;
  11720. }
  11721. // apply the render-target- and depth-stencil-views
  11722. _sg_d3d11_OMSetRenderTargets(_sg.d3d11.ctx, SG_MAX_COLOR_ATTACHMENTS, rtvs, dsv);
  11723. _sg_stats_add(d3d11.pass.num_om_set_render_targets, 1);
  11724. // set viewport and scissor rect to cover whole screen
  11725. D3D11_VIEWPORT vp;
  11726. _sg_clear(&vp, sizeof(vp));
  11727. vp.Width = (FLOAT) _sg.cur_pass.width;
  11728. vp.Height = (FLOAT) _sg.cur_pass.height;
  11729. vp.MaxDepth = 1.0f;
  11730. _sg_d3d11_RSSetViewports(_sg.d3d11.ctx, 1, &vp);
  11731. D3D11_RECT rect;
  11732. rect.left = 0;
  11733. rect.top = 0;
  11734. rect.right = _sg.cur_pass.width;
  11735. rect.bottom = _sg.cur_pass.height;
  11736. _sg_d3d11_RSSetScissorRects(_sg.d3d11.ctx, 1, &rect);
  11737. // perform clear action
  11738. for (size_t i = 0; i < (size_t)num_rtvs; i++) {
  11739. if (action->colors[i].load_action == SG_LOADACTION_CLEAR) {
  11740. _sg_d3d11_ClearRenderTargetView(_sg.d3d11.ctx, rtvs[i], (float*)&action->colors[i].clear_value);
  11741. _sg_stats_add(d3d11.pass.num_clear_render_target_view, 1);
  11742. }
  11743. }
  11744. UINT ds_flags = 0;
  11745. if (action->depth.load_action == SG_LOADACTION_CLEAR) {
  11746. ds_flags |= D3D11_CLEAR_DEPTH;
  11747. }
  11748. if (action->stencil.load_action == SG_LOADACTION_CLEAR) {
  11749. ds_flags |= D3D11_CLEAR_STENCIL;
  11750. }
  11751. if ((0 != ds_flags) && dsv) {
  11752. _sg_d3d11_ClearDepthStencilView(_sg.d3d11.ctx, dsv, ds_flags, action->depth.clear_value, action->stencil.clear_value);
  11753. _sg_stats_add(d3d11.pass.num_clear_depth_stencil_view, 1);
  11754. }
  11755. }
  11756. // D3D11CalcSubresource only exists for C++
  11757. _SOKOL_PRIVATE UINT _sg_d3d11_calcsubresource(UINT mip_slice, UINT array_slice, UINT mip_levels) {
  11758. return mip_slice + array_slice * mip_levels;
  11759. }
  11760. _SOKOL_PRIVATE void _sg_d3d11_end_pass(void) {
  11761. SOKOL_ASSERT(_sg.d3d11.ctx);
  11762. const _sg_attachments_t* atts = _sg_attachments_ref_ptr_or_null(&_sg.cur_pass.atts);
  11763. if (!_sg.cur_pass.is_compute) {
  11764. // need to resolve MSAA render attachments into texture?
  11765. if (atts) {
  11766. // ...for offscreen pass...
  11767. for (size_t i = 0; i < (size_t)atts->cmn.num_colors; i++) {
  11768. const _sg_image_t* resolve_img = _sg_image_ref_ptr_or_null(&atts->cmn.resolves[i].image);
  11769. if (resolve_img) {
  11770. const _sg_image_t* color_img = _sg_image_ref_ptr(&atts->cmn.colors[i].image);
  11771. const _sg_attachment_common_t* cmn_color_att = &atts->cmn.colors[i];
  11772. const _sg_attachment_common_t* cmn_resolve_att = &atts->cmn.resolves[i];
  11773. SOKOL_ASSERT(color_img->cmn.sample_count > 1);
  11774. SOKOL_ASSERT(resolve_img->cmn.sample_count == 1);
  11775. const UINT src_subres = _sg_d3d11_calcsubresource(
  11776. (UINT)cmn_color_att->mip_level,
  11777. (UINT)cmn_color_att->slice,
  11778. (UINT)color_img->cmn.num_mipmaps);
  11779. const UINT dst_subres = _sg_d3d11_calcsubresource(
  11780. (UINT)cmn_resolve_att->mip_level,
  11781. (UINT)cmn_resolve_att->slice,
  11782. (UINT)resolve_img->cmn.num_mipmaps);
  11783. _sg_d3d11_ResolveSubresource(_sg.d3d11.ctx,
  11784. resolve_img->d3d11.res,
  11785. dst_subres,
  11786. color_img->d3d11.res,
  11787. src_subres,
  11788. color_img->d3d11.format);
  11789. _sg_stats_add(d3d11.pass.num_resolve_subresource, 1);
  11790. }
  11791. }
  11792. } else {
  11793. // ...for swapchain pass...
  11794. if (_sg.d3d11.cur_pass.resolve_view) {
  11795. SOKOL_ASSERT(_sg.d3d11.cur_pass.render_view);
  11796. SOKOL_ASSERT(_sg.cur_pass.swapchain.sample_count > 1);
  11797. SOKOL_ASSERT(_sg.cur_pass.swapchain.color_fmt > SG_PIXELFORMAT_NONE);
  11798. ID3D11Resource* d3d11_render_res = 0;
  11799. ID3D11Resource* d3d11_resolve_res = 0;
  11800. _sg_d3d11_GetResource((ID3D11View*)_sg.d3d11.cur_pass.render_view, &d3d11_render_res);
  11801. _sg_d3d11_GetResource((ID3D11View*)_sg.d3d11.cur_pass.resolve_view, &d3d11_resolve_res);
  11802. SOKOL_ASSERT(d3d11_render_res);
  11803. SOKOL_ASSERT(d3d11_resolve_res);
  11804. const sg_pixel_format color_fmt = _sg.cur_pass.swapchain.color_fmt;
  11805. _sg_d3d11_ResolveSubresource(_sg.d3d11.ctx, d3d11_resolve_res, 0, d3d11_render_res, 0, _sg_d3d11_rtv_uav_pixel_format(color_fmt));
  11806. _sg_d3d11_Release(d3d11_render_res);
  11807. _sg_d3d11_Release(d3d11_resolve_res);
  11808. _sg_stats_add(d3d11.pass.num_resolve_subresource, 1);
  11809. }
  11810. }
  11811. }
  11812. _sg.d3d11.cur_pass.render_view = 0;
  11813. _sg.d3d11.cur_pass.resolve_view = 0;
  11814. _sg_d3d11_clear_state();
  11815. }
  11816. _SOKOL_PRIVATE void _sg_d3d11_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  11817. SOKOL_ASSERT(_sg.d3d11.ctx);
  11818. D3D11_VIEWPORT vp;
  11819. vp.TopLeftX = (FLOAT) x;
  11820. vp.TopLeftY = (FLOAT) (origin_top_left ? y : (_sg.cur_pass.height - (y + h)));
  11821. vp.Width = (FLOAT) w;
  11822. vp.Height = (FLOAT) h;
  11823. vp.MinDepth = 0.0f;
  11824. vp.MaxDepth = 1.0f;
  11825. _sg_d3d11_RSSetViewports(_sg.d3d11.ctx, 1, &vp);
  11826. }
  11827. _SOKOL_PRIVATE void _sg_d3d11_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  11828. SOKOL_ASSERT(_sg.d3d11.ctx);
  11829. D3D11_RECT rect;
  11830. rect.left = x;
  11831. rect.top = (origin_top_left ? y : (_sg.cur_pass.height - (y + h)));
  11832. rect.right = x + w;
  11833. rect.bottom = origin_top_left ? (y + h) : (_sg.cur_pass.height - y);
  11834. _sg_d3d11_RSSetScissorRects(_sg.d3d11.ctx, 1, &rect);
  11835. }
  11836. _SOKOL_PRIVATE void _sg_d3d11_populate_storage_attachment_uavs(_sg_pipeline_t* pip, ID3D11UnorderedAccessView** d3d11_cs_uavs) {
  11837. const _sg_attachments_t* atts = _sg_attachments_ref_ptr(&_sg.cur_pass.atts);
  11838. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  11839. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  11840. if (shd->cmn.storage_images[i].stage != SG_SHADERSTAGE_COMPUTE) {
  11841. continue;
  11842. }
  11843. SOKOL_ASSERT(shd->d3d11.simg_register_u_n[i] < _SG_D3D11_MAX_STAGE_UAV_BINDINGS);
  11844. SOKOL_ASSERT(atts->d3d11.storages[i].view.uav);
  11845. SOKOL_ASSERT(0 == d3d11_cs_uavs[i]);
  11846. d3d11_cs_uavs[shd->d3d11.simg_register_u_n[i]] = atts->d3d11.storages[i].view.uav;
  11847. }
  11848. }
  11849. _SOKOL_PRIVATE void _sg_d3d11_apply_pipeline(_sg_pipeline_t* pip) {
  11850. SOKOL_ASSERT(pip);
  11851. SOKOL_ASSERT(_sg.d3d11.ctx);
  11852. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  11853. if (pip->cmn.is_compute) {
  11854. // a compute pipeline
  11855. SOKOL_ASSERT(shd->d3d11.cs);
  11856. _sg_d3d11_CSSetShader(_sg.d3d11.ctx, shd->d3d11.cs, NULL, 0);
  11857. _sg_d3d11_CSSetConstantBuffers(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_UB_BINDINGS, shd->d3d11.cs_cbufs);
  11858. _sg_stats_add(d3d11.pipeline.num_cs_set_shader, 1);
  11859. _sg_stats_add(d3d11.pipeline.num_cs_set_constant_buffers, 1);
  11860. // bind storage attachment UAVs
  11861. if (!_sg_attachments_ref_null(&_sg.cur_pass.atts)) {
  11862. ID3D11UnorderedAccessView* d3d11_cs_uavs[_SG_D3D11_MAX_STAGE_UAV_BINDINGS] = {0};
  11863. _sg_d3d11_populate_storage_attachment_uavs(pip, d3d11_cs_uavs);
  11864. _sg_d3d11_CSSetUnorderedAccessViews(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_UAV_BINDINGS, d3d11_cs_uavs, NULL);
  11865. _sg_stats_add(d3d11.bindings.num_cs_set_unordered_access_views, 1);
  11866. }
  11867. } else {
  11868. // a render pipeline
  11869. SOKOL_ASSERT(pip->d3d11.rs && pip->d3d11.bs && pip->d3d11.dss);
  11870. SOKOL_ASSERT(shd->d3d11.vs);
  11871. SOKOL_ASSERT(shd->d3d11.fs);
  11872. _sg.d3d11.use_indexed_draw = (pip->d3d11.index_format != DXGI_FORMAT_UNKNOWN);
  11873. _sg.d3d11.use_instanced_draw = pip->cmn.use_instanced_draw;
  11874. _sg_d3d11_RSSetState(_sg.d3d11.ctx, pip->d3d11.rs);
  11875. _sg_d3d11_OMSetDepthStencilState(_sg.d3d11.ctx, pip->d3d11.dss, pip->d3d11.stencil_ref);
  11876. _sg_d3d11_OMSetBlendState(_sg.d3d11.ctx, pip->d3d11.bs, (float*)&pip->cmn.blend_color, 0xFFFFFFFF);
  11877. _sg_d3d11_IASetPrimitiveTopology(_sg.d3d11.ctx, pip->d3d11.topology);
  11878. _sg_d3d11_IASetInputLayout(_sg.d3d11.ctx, pip->d3d11.il);
  11879. _sg_d3d11_VSSetShader(_sg.d3d11.ctx, shd->d3d11.vs, NULL, 0);
  11880. _sg_d3d11_VSSetConstantBuffers(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_UB_BINDINGS, shd->d3d11.vs_cbufs);
  11881. _sg_d3d11_PSSetShader(_sg.d3d11.ctx, shd->d3d11.fs, NULL, 0);
  11882. _sg_d3d11_PSSetConstantBuffers(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_UB_BINDINGS, shd->d3d11.fs_cbufs);
  11883. _sg_stats_add(d3d11.pipeline.num_rs_set_state, 1);
  11884. _sg_stats_add(d3d11.pipeline.num_om_set_depth_stencil_state, 1);
  11885. _sg_stats_add(d3d11.pipeline.num_om_set_blend_state, 1);
  11886. _sg_stats_add(d3d11.pipeline.num_ia_set_primitive_topology, 1);
  11887. _sg_stats_add(d3d11.pipeline.num_ia_set_input_layout, 1);
  11888. _sg_stats_add(d3d11.pipeline.num_vs_set_shader, 1);
  11889. _sg_stats_add(d3d11.pipeline.num_vs_set_constant_buffers, 1);
  11890. _sg_stats_add(d3d11.pipeline.num_ps_set_shader, 1);
  11891. _sg_stats_add(d3d11.pipeline.num_ps_set_constant_buffers, 1);
  11892. }
  11893. }
  11894. _SOKOL_PRIVATE bool _sg_d3d11_apply_bindings(_sg_bindings_ptrs_t* bnd) {
  11895. SOKOL_ASSERT(bnd);
  11896. SOKOL_ASSERT(bnd->pip);
  11897. SOKOL_ASSERT(_sg.d3d11.ctx);
  11898. const _sg_shader_t* shd = _sg_shader_ref_ptr(&bnd->pip->cmn.shader);
  11899. const bool is_compute = bnd->pip->cmn.is_compute;
  11900. // gather all the D3D11 resources into arrays
  11901. ID3D11Buffer* d3d11_ib = bnd->ib ? bnd->ib->d3d11.buf : 0;
  11902. ID3D11Buffer* d3d11_vbs[SG_MAX_VERTEXBUFFER_BINDSLOTS] = {0};
  11903. UINT d3d11_vb_offsets[SG_MAX_VERTEXBUFFER_BINDSLOTS] = {0};
  11904. ID3D11ShaderResourceView* d3d11_vs_srvs[_SG_D3D11_MAX_STAGE_SRV_BINDINGS] = {0};
  11905. ID3D11ShaderResourceView* d3d11_fs_srvs[_SG_D3D11_MAX_STAGE_SRV_BINDINGS] = {0};
  11906. ID3D11ShaderResourceView* d3d11_cs_srvs[_SG_D3D11_MAX_STAGE_SRV_BINDINGS] = {0};
  11907. ID3D11SamplerState* d3d11_vs_smps[_SG_D3D11_MAX_STAGE_SMP_BINDINGS] = {0};
  11908. ID3D11SamplerState* d3d11_fs_smps[_SG_D3D11_MAX_STAGE_SMP_BINDINGS] = {0};
  11909. ID3D11SamplerState* d3d11_cs_smps[_SG_D3D11_MAX_STAGE_SMP_BINDINGS] = {0};
  11910. ID3D11UnorderedAccessView* d3d11_cs_uavs[_SG_D3D11_MAX_STAGE_UAV_BINDINGS] = {0};
  11911. if (!is_compute) {
  11912. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  11913. const _sg_buffer_t* vb = bnd->vbs[i];
  11914. if (vb == 0) {
  11915. continue;
  11916. }
  11917. SOKOL_ASSERT(vb->d3d11.buf);
  11918. d3d11_vbs[i] = vb->d3d11.buf;
  11919. d3d11_vb_offsets[i] = (UINT)bnd->vb_offsets[i];
  11920. }
  11921. }
  11922. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  11923. const _sg_image_t* img = bnd->imgs[i];
  11924. if (img == 0) {
  11925. continue;
  11926. }
  11927. const sg_shader_stage stage = shd->cmn.images[i].stage;
  11928. SOKOL_ASSERT(stage != SG_SHADERSTAGE_NONE);
  11929. const uint8_t d3d11_slot = shd->d3d11.img_register_t_n[i];
  11930. SOKOL_ASSERT(d3d11_slot < _SG_D3D11_MAX_STAGE_SRV_BINDINGS);
  11931. SOKOL_ASSERT(img->d3d11.srv);
  11932. ID3D11ShaderResourceView* d3d11_srv = img->d3d11.srv;
  11933. switch (stage) {
  11934. case SG_SHADERSTAGE_VERTEX: d3d11_vs_srvs[d3d11_slot] = d3d11_srv; break;
  11935. case SG_SHADERSTAGE_FRAGMENT: d3d11_fs_srvs[d3d11_slot] = d3d11_srv; break;
  11936. case SG_SHADERSTAGE_COMPUTE: d3d11_cs_srvs[d3d11_slot] = d3d11_srv; break;
  11937. default: SOKOL_UNREACHABLE;
  11938. }
  11939. }
  11940. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  11941. const _sg_buffer_t* sbuf = bnd->sbufs[i];
  11942. if (sbuf == 0) {
  11943. continue;
  11944. }
  11945. const sg_shader_stage stage = shd->cmn.storage_buffers[i].stage;
  11946. SOKOL_ASSERT(stage != SG_SHADERSTAGE_NONE);
  11947. if (shd->cmn.storage_buffers[i].readonly) {
  11948. SOKOL_ASSERT(sbuf->d3d11.srv);
  11949. const uint8_t d3d11_slot = shd->d3d11.sbuf_register_t_n[i];
  11950. SOKOL_ASSERT(d3d11_slot < _SG_D3D11_MAX_STAGE_SRV_BINDINGS);
  11951. ID3D11ShaderResourceView* d3d11_srv = sbuf->d3d11.srv;
  11952. switch (stage) {
  11953. case SG_SHADERSTAGE_VERTEX: d3d11_vs_srvs[d3d11_slot] = d3d11_srv; break;
  11954. case SG_SHADERSTAGE_FRAGMENT: d3d11_fs_srvs[d3d11_slot] = d3d11_srv; break;
  11955. case SG_SHADERSTAGE_COMPUTE: d3d11_cs_srvs[d3d11_slot] = d3d11_srv; break;
  11956. default: SOKOL_UNREACHABLE;
  11957. }
  11958. } else {
  11959. SOKOL_ASSERT(sbuf->d3d11.uav);
  11960. SOKOL_ASSERT(stage == SG_SHADERSTAGE_COMPUTE);
  11961. const uint8_t d3d11_slot = shd->d3d11.sbuf_register_u_n[i];
  11962. SOKOL_ASSERT(d3d11_slot < _SG_D3D11_MAX_STAGE_UAV_BINDINGS);
  11963. d3d11_cs_uavs[d3d11_slot] = sbuf->d3d11.uav;
  11964. }
  11965. }
  11966. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  11967. const _sg_sampler_t* smp = bnd->smps[i];
  11968. if (smp == 0) {
  11969. continue;
  11970. }
  11971. const sg_shader_stage stage = shd->cmn.samplers[i].stage;
  11972. SOKOL_ASSERT(stage != SG_SHADERSTAGE_NONE);
  11973. const uint8_t d3d11_slot = shd->d3d11.smp_register_s_n[i];
  11974. SOKOL_ASSERT(d3d11_slot < _SG_D3D11_MAX_STAGE_SMP_BINDINGS);
  11975. SOKOL_ASSERT(smp->d3d11.smp);
  11976. ID3D11SamplerState* d3d11_smp = smp->d3d11.smp;
  11977. switch (stage) {
  11978. case SG_SHADERSTAGE_VERTEX: d3d11_vs_smps[d3d11_slot] = d3d11_smp; break;
  11979. case SG_SHADERSTAGE_FRAGMENT: d3d11_fs_smps[d3d11_slot] = d3d11_smp; break;
  11980. case SG_SHADERSTAGE_COMPUTE: d3d11_cs_smps[d3d11_slot] = d3d11_smp; break;
  11981. default: SOKOL_UNREACHABLE;
  11982. }
  11983. }
  11984. if (is_compute) {
  11985. // in a compute pass with storage attachments, also need to rebind the storage attachments
  11986. if (!_sg_attachments_ref_null(&_sg.cur_pass.atts)) {
  11987. _sg_d3d11_populate_storage_attachment_uavs(bnd->pip, d3d11_cs_uavs);
  11988. }
  11989. _sg_d3d11_CSSetShaderResources(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_SRV_BINDINGS, d3d11_cs_srvs);
  11990. _sg_d3d11_CSSetSamplers(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_SMP_BINDINGS, d3d11_cs_smps);
  11991. _sg_d3d11_CSSetUnorderedAccessViews(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_UAV_BINDINGS, d3d11_cs_uavs, NULL);
  11992. _sg_stats_add(d3d11.bindings.num_cs_set_shader_resources, 1);
  11993. _sg_stats_add(d3d11.bindings.num_cs_set_samplers, 1);
  11994. _sg_stats_add(d3d11.bindings.num_cs_set_unordered_access_views, 1);
  11995. } else {
  11996. _sg_d3d11_IASetVertexBuffers(_sg.d3d11.ctx, 0, SG_MAX_VERTEXBUFFER_BINDSLOTS, d3d11_vbs, bnd->pip->d3d11.vb_strides, d3d11_vb_offsets);
  11997. _sg_d3d11_IASetIndexBuffer(_sg.d3d11.ctx, d3d11_ib, bnd->pip->d3d11.index_format, (UINT)bnd->ib_offset);
  11998. _sg_d3d11_VSSetShaderResources(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_SRV_BINDINGS, d3d11_vs_srvs);
  11999. _sg_d3d11_PSSetShaderResources(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_SRV_BINDINGS, d3d11_fs_srvs);
  12000. _sg_d3d11_VSSetSamplers(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_SMP_BINDINGS, d3d11_vs_smps);
  12001. _sg_d3d11_PSSetSamplers(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_SMP_BINDINGS, d3d11_fs_smps);
  12002. _sg_stats_add(d3d11.bindings.num_ia_set_vertex_buffers, 1);
  12003. _sg_stats_add(d3d11.bindings.num_ia_set_index_buffer, 1);
  12004. _sg_stats_add(d3d11.bindings.num_vs_set_shader_resources, 1);
  12005. _sg_stats_add(d3d11.bindings.num_ps_set_shader_resources, 1);
  12006. _sg_stats_add(d3d11.bindings.num_vs_set_samplers, 1);
  12007. _sg_stats_add(d3d11.bindings.num_ps_set_samplers, 1);
  12008. }
  12009. return true;
  12010. }
  12011. _SOKOL_PRIVATE void _sg_d3d11_apply_uniforms(int ub_slot, const sg_range* data) {
  12012. SOKOL_ASSERT(_sg.d3d11.ctx);
  12013. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  12014. const _sg_pipeline_t* pip = _sg_pipeline_ref_ptr(&_sg.cur_pip);
  12015. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  12016. SOKOL_ASSERT(data->size == shd->cmn.uniform_blocks[ub_slot].size);
  12017. ID3D11Buffer* cbuf = shd->d3d11.all_cbufs[ub_slot];
  12018. SOKOL_ASSERT(cbuf);
  12019. _sg_d3d11_UpdateSubresource(_sg.d3d11.ctx, (ID3D11Resource*)cbuf, 0, NULL, data->ptr, 0, 0);
  12020. _sg_stats_add(d3d11.uniforms.num_update_subresource, 1);
  12021. }
  12022. _SOKOL_PRIVATE void _sg_d3d11_draw(int base_element, int num_elements, int num_instances) {
  12023. const bool use_instanced_draw = (num_instances > 1) || (_sg.d3d11.use_instanced_draw);
  12024. if (_sg.d3d11.use_indexed_draw) {
  12025. if (use_instanced_draw) {
  12026. _sg_d3d11_DrawIndexedInstanced(_sg.d3d11.ctx, (UINT)num_elements, (UINT)num_instances, (UINT)base_element, 0, 0);
  12027. _sg_stats_add(d3d11.draw.num_draw_indexed_instanced, 1);
  12028. } else {
  12029. _sg_d3d11_DrawIndexed(_sg.d3d11.ctx, (UINT)num_elements, (UINT)base_element, 0);
  12030. _sg_stats_add(d3d11.draw.num_draw_indexed, 1);
  12031. }
  12032. } else {
  12033. if (use_instanced_draw) {
  12034. _sg_d3d11_DrawInstanced(_sg.d3d11.ctx, (UINT)num_elements, (UINT)num_instances, (UINT)base_element, 0);
  12035. _sg_stats_add(d3d11.draw.num_draw_instanced, 1);
  12036. } else {
  12037. _sg_d3d11_Draw(_sg.d3d11.ctx, (UINT)num_elements, (UINT)base_element);
  12038. _sg_stats_add(d3d11.draw.num_draw, 1);
  12039. }
  12040. }
  12041. }
  12042. _SOKOL_PRIVATE void _sg_d3d11_dispatch(int num_groups_x, int num_groups_y, int num_groups_z) {
  12043. _sg_d3d11_Dispatch(_sg.d3d11.ctx, (UINT)num_groups_x, (UINT)num_groups_y, (UINT)num_groups_z);
  12044. }
  12045. _SOKOL_PRIVATE void _sg_d3d11_commit(void) {
  12046. // empty
  12047. }
  12048. _SOKOL_PRIVATE void _sg_d3d11_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  12049. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  12050. SOKOL_ASSERT(_sg.d3d11.ctx);
  12051. SOKOL_ASSERT(buf->d3d11.buf);
  12052. D3D11_MAPPED_SUBRESOURCE d3d11_msr;
  12053. HRESULT hr = _sg_d3d11_Map(_sg.d3d11.ctx, (ID3D11Resource*)buf->d3d11.buf, 0, D3D11_MAP_WRITE_DISCARD, 0, &d3d11_msr);
  12054. _sg_stats_add(d3d11.num_map, 1);
  12055. if (SUCCEEDED(hr)) {
  12056. memcpy(d3d11_msr.pData, data->ptr, data->size);
  12057. _sg_d3d11_Unmap(_sg.d3d11.ctx, (ID3D11Resource*)buf->d3d11.buf, 0);
  12058. _sg_stats_add(d3d11.num_unmap, 1);
  12059. } else {
  12060. _SG_ERROR(D3D11_MAP_FOR_UPDATE_BUFFER_FAILED);
  12061. }
  12062. }
  12063. _SOKOL_PRIVATE void _sg_d3d11_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  12064. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  12065. SOKOL_ASSERT(_sg.d3d11.ctx);
  12066. SOKOL_ASSERT(buf->d3d11.buf);
  12067. D3D11_MAP map_type = new_frame ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE_NO_OVERWRITE;
  12068. D3D11_MAPPED_SUBRESOURCE d3d11_msr;
  12069. HRESULT hr = _sg_d3d11_Map(_sg.d3d11.ctx, (ID3D11Resource*)buf->d3d11.buf, 0, map_type, 0, &d3d11_msr);
  12070. _sg_stats_add(d3d11.num_map, 1);
  12071. if (SUCCEEDED(hr)) {
  12072. uint8_t* dst_ptr = (uint8_t*)d3d11_msr.pData + buf->cmn.append_pos;
  12073. memcpy(dst_ptr, data->ptr, data->size);
  12074. _sg_d3d11_Unmap(_sg.d3d11.ctx, (ID3D11Resource*)buf->d3d11.buf, 0);
  12075. _sg_stats_add(d3d11.num_unmap, 1);
  12076. } else {
  12077. _SG_ERROR(D3D11_MAP_FOR_APPEND_BUFFER_FAILED);
  12078. }
  12079. }
  12080. // see: https://learn.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-resources-subresources
  12081. // also see: https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-d3d11calcsubresource
  12082. _SOKOL_PRIVATE void _sg_d3d11_update_image(_sg_image_t* img, const sg_image_data* data) {
  12083. SOKOL_ASSERT(img && data);
  12084. SOKOL_ASSERT(_sg.d3d11.ctx);
  12085. SOKOL_ASSERT(img->d3d11.res);
  12086. const int num_faces = (img->cmn.type == SG_IMAGETYPE_CUBE) ? 6:1;
  12087. const int num_slices = (img->cmn.type == SG_IMAGETYPE_ARRAY) ? img->cmn.num_slices:1;
  12088. const int num_depth_slices = (img->cmn.type == SG_IMAGETYPE_3D) ? img->cmn.num_slices:1;
  12089. UINT subres_index = 0;
  12090. HRESULT hr;
  12091. D3D11_MAPPED_SUBRESOURCE d3d11_msr;
  12092. for (int face_index = 0; face_index < num_faces; face_index++) {
  12093. for (int slice_index = 0; slice_index < num_slices; slice_index++) {
  12094. for (int mip_index = 0; mip_index < img->cmn.num_mipmaps; mip_index++, subres_index++) {
  12095. SOKOL_ASSERT(subres_index < (SG_MAX_MIPMAPS * SG_MAX_TEXTUREARRAY_LAYERS));
  12096. const int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  12097. const int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  12098. const int src_row_pitch = _sg_row_pitch(img->cmn.pixel_format, mip_width, 1);
  12099. const int src_depth_pitch = _sg_surface_pitch(img->cmn.pixel_format, mip_width, mip_height, 1);
  12100. const sg_range* subimg_data = &(data->subimage[face_index][mip_index]);
  12101. const size_t slice_size = subimg_data->size / (size_t)num_slices;
  12102. SOKOL_ASSERT(slice_size == (size_t)(src_depth_pitch * num_depth_slices));
  12103. const size_t slice_offset = slice_size * (size_t)slice_index;
  12104. const uint8_t* slice_ptr = ((const uint8_t*)subimg_data->ptr) + slice_offset;
  12105. hr = _sg_d3d11_Map(_sg.d3d11.ctx, img->d3d11.res, subres_index, D3D11_MAP_WRITE_DISCARD, 0, &d3d11_msr);
  12106. _sg_stats_add(d3d11.num_map, 1);
  12107. if (SUCCEEDED(hr)) {
  12108. const uint8_t* src_ptr = slice_ptr;
  12109. uint8_t* dst_ptr = (uint8_t*)d3d11_msr.pData;
  12110. for (int depth_index = 0; depth_index < num_depth_slices; depth_index++) {
  12111. if (src_row_pitch == (int)d3d11_msr.RowPitch) {
  12112. const size_t copy_size = slice_size / (size_t)num_depth_slices;
  12113. SOKOL_ASSERT((copy_size * (size_t)num_depth_slices) == slice_size);
  12114. memcpy(dst_ptr, src_ptr, copy_size);
  12115. } else {
  12116. SOKOL_ASSERT(src_row_pitch < (int)d3d11_msr.RowPitch);
  12117. const uint8_t* src_row_ptr = src_ptr;
  12118. uint8_t* dst_row_ptr = dst_ptr;
  12119. for (int row_index = 0; row_index < mip_height; row_index++) {
  12120. memcpy(dst_row_ptr, src_row_ptr, (size_t)src_row_pitch);
  12121. src_row_ptr += src_row_pitch;
  12122. dst_row_ptr += d3d11_msr.RowPitch;
  12123. }
  12124. }
  12125. src_ptr += src_depth_pitch;
  12126. dst_ptr += d3d11_msr.DepthPitch;
  12127. }
  12128. _sg_d3d11_Unmap(_sg.d3d11.ctx, img->d3d11.res, subres_index);
  12129. _sg_stats_add(d3d11.num_unmap, 1);
  12130. } else {
  12131. _SG_ERROR(D3D11_MAP_FOR_UPDATE_IMAGE_FAILED);
  12132. }
  12133. }
  12134. }
  12135. }
  12136. }
  12137. // ███ ███ ███████ ████████ █████ ██ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  12138. // ████ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  12139. // ██ ████ ██ █████ ██ ███████ ██ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  12140. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  12141. // ██ ██ ███████ ██ ██ ██ ███████ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  12142. //
  12143. // >>metal backend
  12144. #elif defined(SOKOL_METAL)
  12145. #if __has_feature(objc_arc)
  12146. #define _SG_OBJC_RETAIN(obj) { }
  12147. #define _SG_OBJC_RELEASE(obj) { obj = nil; }
  12148. #else
  12149. #define _SG_OBJC_RETAIN(obj) { [obj retain]; }
  12150. #define _SG_OBJC_RELEASE(obj) { [obj release]; obj = nil; }
  12151. #endif
  12152. //-- enum translation functions ------------------------------------------------
  12153. _SOKOL_PRIVATE MTLLoadAction _sg_mtl_load_action(sg_load_action a) {
  12154. switch (a) {
  12155. case SG_LOADACTION_CLEAR: return MTLLoadActionClear;
  12156. case SG_LOADACTION_LOAD: return MTLLoadActionLoad;
  12157. case SG_LOADACTION_DONTCARE: return MTLLoadActionDontCare;
  12158. default: SOKOL_UNREACHABLE; return (MTLLoadAction)0;
  12159. }
  12160. }
  12161. _SOKOL_PRIVATE MTLStoreAction _sg_mtl_store_action(sg_store_action a, bool resolve) {
  12162. switch (a) {
  12163. case SG_STOREACTION_STORE:
  12164. if (resolve) {
  12165. return MTLStoreActionStoreAndMultisampleResolve;
  12166. } else {
  12167. return MTLStoreActionStore;
  12168. }
  12169. break;
  12170. case SG_STOREACTION_DONTCARE:
  12171. if (resolve) {
  12172. return MTLStoreActionMultisampleResolve;
  12173. } else {
  12174. return MTLStoreActionDontCare;
  12175. }
  12176. break;
  12177. default: SOKOL_UNREACHABLE; return (MTLStoreAction)0;
  12178. }
  12179. }
  12180. _SOKOL_PRIVATE MTLResourceOptions _sg_mtl_resource_options_storage_mode_managed_or_shared(void) {
  12181. #if defined(_SG_TARGET_MACOS)
  12182. if (_sg.mtl.use_shared_storage_mode) {
  12183. return MTLResourceStorageModeShared;
  12184. } else {
  12185. return MTLResourceStorageModeManaged;
  12186. }
  12187. #else
  12188. // MTLResourceStorageModeManaged is not even defined on iOS SDK
  12189. return MTLResourceStorageModeShared;
  12190. #endif
  12191. }
  12192. _SOKOL_PRIVATE MTLResourceOptions _sg_mtl_buffer_resource_options(const sg_buffer_usage* usage) {
  12193. if (usage->immutable) {
  12194. return _sg_mtl_resource_options_storage_mode_managed_or_shared();
  12195. } else {
  12196. return MTLResourceCPUCacheModeWriteCombined | _sg_mtl_resource_options_storage_mode_managed_or_shared();
  12197. }
  12198. }
  12199. _SOKOL_PRIVATE MTLVertexStepFunction _sg_mtl_step_function(sg_vertex_step step) {
  12200. switch (step) {
  12201. case SG_VERTEXSTEP_PER_VERTEX: return MTLVertexStepFunctionPerVertex;
  12202. case SG_VERTEXSTEP_PER_INSTANCE: return MTLVertexStepFunctionPerInstance;
  12203. default: SOKOL_UNREACHABLE; return (MTLVertexStepFunction)0;
  12204. }
  12205. }
  12206. _SOKOL_PRIVATE MTLVertexFormat _sg_mtl_vertex_format(sg_vertex_format fmt) {
  12207. switch (fmt) {
  12208. case SG_VERTEXFORMAT_FLOAT: return MTLVertexFormatFloat;
  12209. case SG_VERTEXFORMAT_FLOAT2: return MTLVertexFormatFloat2;
  12210. case SG_VERTEXFORMAT_FLOAT3: return MTLVertexFormatFloat3;
  12211. case SG_VERTEXFORMAT_FLOAT4: return MTLVertexFormatFloat4;
  12212. case SG_VERTEXFORMAT_INT: return MTLVertexFormatInt;
  12213. case SG_VERTEXFORMAT_INT2: return MTLVertexFormatInt2;
  12214. case SG_VERTEXFORMAT_INT3: return MTLVertexFormatInt3;
  12215. case SG_VERTEXFORMAT_INT4: return MTLVertexFormatInt4;
  12216. case SG_VERTEXFORMAT_UINT: return MTLVertexFormatUInt;
  12217. case SG_VERTEXFORMAT_UINT2: return MTLVertexFormatUInt2;
  12218. case SG_VERTEXFORMAT_UINT3: return MTLVertexFormatUInt3;
  12219. case SG_VERTEXFORMAT_UINT4: return MTLVertexFormatUInt4;
  12220. case SG_VERTEXFORMAT_BYTE4: return MTLVertexFormatChar4;
  12221. case SG_VERTEXFORMAT_BYTE4N: return MTLVertexFormatChar4Normalized;
  12222. case SG_VERTEXFORMAT_UBYTE4: return MTLVertexFormatUChar4;
  12223. case SG_VERTEXFORMAT_UBYTE4N: return MTLVertexFormatUChar4Normalized;
  12224. case SG_VERTEXFORMAT_SHORT2: return MTLVertexFormatShort2;
  12225. case SG_VERTEXFORMAT_SHORT2N: return MTLVertexFormatShort2Normalized;
  12226. case SG_VERTEXFORMAT_USHORT2: return MTLVertexFormatUShort2;
  12227. case SG_VERTEXFORMAT_USHORT2N: return MTLVertexFormatUShort2Normalized;
  12228. case SG_VERTEXFORMAT_SHORT4: return MTLVertexFormatShort4;
  12229. case SG_VERTEXFORMAT_SHORT4N: return MTLVertexFormatShort4Normalized;
  12230. case SG_VERTEXFORMAT_USHORT4: return MTLVertexFormatUShort4;
  12231. case SG_VERTEXFORMAT_USHORT4N: return MTLVertexFormatUShort4Normalized;
  12232. case SG_VERTEXFORMAT_UINT10_N2: return MTLVertexFormatUInt1010102Normalized;
  12233. case SG_VERTEXFORMAT_HALF2: return MTLVertexFormatHalf2;
  12234. case SG_VERTEXFORMAT_HALF4: return MTLVertexFormatHalf4;
  12235. default: SOKOL_UNREACHABLE; return (MTLVertexFormat)0;
  12236. }
  12237. }
  12238. _SOKOL_PRIVATE MTLPrimitiveType _sg_mtl_primitive_type(sg_primitive_type t) {
  12239. switch (t) {
  12240. case SG_PRIMITIVETYPE_POINTS: return MTLPrimitiveTypePoint;
  12241. case SG_PRIMITIVETYPE_LINES: return MTLPrimitiveTypeLine;
  12242. case SG_PRIMITIVETYPE_LINE_STRIP: return MTLPrimitiveTypeLineStrip;
  12243. case SG_PRIMITIVETYPE_TRIANGLES: return MTLPrimitiveTypeTriangle;
  12244. case SG_PRIMITIVETYPE_TRIANGLE_STRIP: return MTLPrimitiveTypeTriangleStrip;
  12245. default: SOKOL_UNREACHABLE; return (MTLPrimitiveType)0;
  12246. }
  12247. }
  12248. _SOKOL_PRIVATE MTLPixelFormat _sg_mtl_pixel_format(sg_pixel_format fmt) {
  12249. switch (fmt) {
  12250. case SG_PIXELFORMAT_R8: return MTLPixelFormatR8Unorm;
  12251. case SG_PIXELFORMAT_R8SN: return MTLPixelFormatR8Snorm;
  12252. case SG_PIXELFORMAT_R8UI: return MTLPixelFormatR8Uint;
  12253. case SG_PIXELFORMAT_R8SI: return MTLPixelFormatR8Sint;
  12254. case SG_PIXELFORMAT_R16: return MTLPixelFormatR16Unorm;
  12255. case SG_PIXELFORMAT_R16SN: return MTLPixelFormatR16Snorm;
  12256. case SG_PIXELFORMAT_R16UI: return MTLPixelFormatR16Uint;
  12257. case SG_PIXELFORMAT_R16SI: return MTLPixelFormatR16Sint;
  12258. case SG_PIXELFORMAT_R16F: return MTLPixelFormatR16Float;
  12259. case SG_PIXELFORMAT_RG8: return MTLPixelFormatRG8Unorm;
  12260. case SG_PIXELFORMAT_RG8SN: return MTLPixelFormatRG8Snorm;
  12261. case SG_PIXELFORMAT_RG8UI: return MTLPixelFormatRG8Uint;
  12262. case SG_PIXELFORMAT_RG8SI: return MTLPixelFormatRG8Sint;
  12263. case SG_PIXELFORMAT_R32UI: return MTLPixelFormatR32Uint;
  12264. case SG_PIXELFORMAT_R32SI: return MTLPixelFormatR32Sint;
  12265. case SG_PIXELFORMAT_R32F: return MTLPixelFormatR32Float;
  12266. case SG_PIXELFORMAT_RG16: return MTLPixelFormatRG16Unorm;
  12267. case SG_PIXELFORMAT_RG16SN: return MTLPixelFormatRG16Snorm;
  12268. case SG_PIXELFORMAT_RG16UI: return MTLPixelFormatRG16Uint;
  12269. case SG_PIXELFORMAT_RG16SI: return MTLPixelFormatRG16Sint;
  12270. case SG_PIXELFORMAT_RG16F: return MTLPixelFormatRG16Float;
  12271. case SG_PIXELFORMAT_RGBA8: return MTLPixelFormatRGBA8Unorm;
  12272. case SG_PIXELFORMAT_SRGB8A8: return MTLPixelFormatRGBA8Unorm_sRGB;
  12273. case SG_PIXELFORMAT_RGBA8SN: return MTLPixelFormatRGBA8Snorm;
  12274. case SG_PIXELFORMAT_RGBA8UI: return MTLPixelFormatRGBA8Uint;
  12275. case SG_PIXELFORMAT_RGBA8SI: return MTLPixelFormatRGBA8Sint;
  12276. case SG_PIXELFORMAT_BGRA8: return MTLPixelFormatBGRA8Unorm;
  12277. case SG_PIXELFORMAT_RGB10A2: return MTLPixelFormatRGB10A2Unorm;
  12278. case SG_PIXELFORMAT_RG11B10F: return MTLPixelFormatRG11B10Float;
  12279. case SG_PIXELFORMAT_RGB9E5: return MTLPixelFormatRGB9E5Float;
  12280. case SG_PIXELFORMAT_RG32UI: return MTLPixelFormatRG32Uint;
  12281. case SG_PIXELFORMAT_RG32SI: return MTLPixelFormatRG32Sint;
  12282. case SG_PIXELFORMAT_RG32F: return MTLPixelFormatRG32Float;
  12283. case SG_PIXELFORMAT_RGBA16: return MTLPixelFormatRGBA16Unorm;
  12284. case SG_PIXELFORMAT_RGBA16SN: return MTLPixelFormatRGBA16Snorm;
  12285. case SG_PIXELFORMAT_RGBA16UI: return MTLPixelFormatRGBA16Uint;
  12286. case SG_PIXELFORMAT_RGBA16SI: return MTLPixelFormatRGBA16Sint;
  12287. case SG_PIXELFORMAT_RGBA16F: return MTLPixelFormatRGBA16Float;
  12288. case SG_PIXELFORMAT_RGBA32UI: return MTLPixelFormatRGBA32Uint;
  12289. case SG_PIXELFORMAT_RGBA32SI: return MTLPixelFormatRGBA32Sint;
  12290. case SG_PIXELFORMAT_RGBA32F: return MTLPixelFormatRGBA32Float;
  12291. case SG_PIXELFORMAT_DEPTH: return MTLPixelFormatDepth32Float;
  12292. case SG_PIXELFORMAT_DEPTH_STENCIL: return MTLPixelFormatDepth32Float_Stencil8;
  12293. #if defined(_SG_TARGET_MACOS)
  12294. case SG_PIXELFORMAT_BC1_RGBA: return MTLPixelFormatBC1_RGBA;
  12295. case SG_PIXELFORMAT_BC2_RGBA: return MTLPixelFormatBC2_RGBA;
  12296. case SG_PIXELFORMAT_BC3_RGBA: return MTLPixelFormatBC3_RGBA;
  12297. case SG_PIXELFORMAT_BC3_SRGBA: return MTLPixelFormatBC3_RGBA_sRGB;
  12298. case SG_PIXELFORMAT_BC4_R: return MTLPixelFormatBC4_RUnorm;
  12299. case SG_PIXELFORMAT_BC4_RSN: return MTLPixelFormatBC4_RSnorm;
  12300. case SG_PIXELFORMAT_BC5_RG: return MTLPixelFormatBC5_RGUnorm;
  12301. case SG_PIXELFORMAT_BC5_RGSN: return MTLPixelFormatBC5_RGSnorm;
  12302. case SG_PIXELFORMAT_BC6H_RGBF: return MTLPixelFormatBC6H_RGBFloat;
  12303. case SG_PIXELFORMAT_BC6H_RGBUF: return MTLPixelFormatBC6H_RGBUfloat;
  12304. case SG_PIXELFORMAT_BC7_RGBA: return MTLPixelFormatBC7_RGBAUnorm;
  12305. case SG_PIXELFORMAT_BC7_SRGBA: return MTLPixelFormatBC7_RGBAUnorm_sRGB;
  12306. #else
  12307. case SG_PIXELFORMAT_ETC2_RGB8: return MTLPixelFormatETC2_RGB8;
  12308. case SG_PIXELFORMAT_ETC2_SRGB8: return MTLPixelFormatETC2_RGB8_sRGB;
  12309. case SG_PIXELFORMAT_ETC2_RGB8A1: return MTLPixelFormatETC2_RGB8A1;
  12310. case SG_PIXELFORMAT_ETC2_RGBA8: return MTLPixelFormatEAC_RGBA8;
  12311. case SG_PIXELFORMAT_ETC2_SRGB8A8: return MTLPixelFormatEAC_RGBA8_sRGB;
  12312. case SG_PIXELFORMAT_EAC_R11: return MTLPixelFormatEAC_R11Unorm;
  12313. case SG_PIXELFORMAT_EAC_R11SN: return MTLPixelFormatEAC_R11Snorm;
  12314. case SG_PIXELFORMAT_EAC_RG11: return MTLPixelFormatEAC_RG11Unorm;
  12315. case SG_PIXELFORMAT_EAC_RG11SN: return MTLPixelFormatEAC_RG11Snorm;
  12316. case SG_PIXELFORMAT_ASTC_4x4_RGBA: return MTLPixelFormatASTC_4x4_LDR;
  12317. case SG_PIXELFORMAT_ASTC_4x4_SRGBA: return MTLPixelFormatASTC_4x4_sRGB;
  12318. #endif
  12319. default: return MTLPixelFormatInvalid;
  12320. }
  12321. }
  12322. _SOKOL_PRIVATE MTLColorWriteMask _sg_mtl_color_write_mask(sg_color_mask m) {
  12323. MTLColorWriteMask mtl_mask = MTLColorWriteMaskNone;
  12324. if (m & SG_COLORMASK_R) {
  12325. mtl_mask |= MTLColorWriteMaskRed;
  12326. }
  12327. if (m & SG_COLORMASK_G) {
  12328. mtl_mask |= MTLColorWriteMaskGreen;
  12329. }
  12330. if (m & SG_COLORMASK_B) {
  12331. mtl_mask |= MTLColorWriteMaskBlue;
  12332. }
  12333. if (m & SG_COLORMASK_A) {
  12334. mtl_mask |= MTLColorWriteMaskAlpha;
  12335. }
  12336. return mtl_mask;
  12337. }
  12338. _SOKOL_PRIVATE MTLBlendOperation _sg_mtl_blend_op(sg_blend_op op) {
  12339. switch (op) {
  12340. case SG_BLENDOP_ADD: return MTLBlendOperationAdd;
  12341. case SG_BLENDOP_SUBTRACT: return MTLBlendOperationSubtract;
  12342. case SG_BLENDOP_REVERSE_SUBTRACT: return MTLBlendOperationReverseSubtract;
  12343. case SG_BLENDOP_MIN: return MTLBlendOperationMin;
  12344. case SG_BLENDOP_MAX: return MTLBlendOperationMax;
  12345. default: SOKOL_UNREACHABLE; return (MTLBlendOperation)0;
  12346. }
  12347. }
  12348. _SOKOL_PRIVATE MTLBlendFactor _sg_mtl_blend_factor(sg_blend_factor f) {
  12349. switch (f) {
  12350. case SG_BLENDFACTOR_ZERO: return MTLBlendFactorZero;
  12351. case SG_BLENDFACTOR_ONE: return MTLBlendFactorOne;
  12352. case SG_BLENDFACTOR_SRC_COLOR: return MTLBlendFactorSourceColor;
  12353. case SG_BLENDFACTOR_ONE_MINUS_SRC_COLOR: return MTLBlendFactorOneMinusSourceColor;
  12354. case SG_BLENDFACTOR_SRC_ALPHA: return MTLBlendFactorSourceAlpha;
  12355. case SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA: return MTLBlendFactorOneMinusSourceAlpha;
  12356. case SG_BLENDFACTOR_DST_COLOR: return MTLBlendFactorDestinationColor;
  12357. case SG_BLENDFACTOR_ONE_MINUS_DST_COLOR: return MTLBlendFactorOneMinusDestinationColor;
  12358. case SG_BLENDFACTOR_DST_ALPHA: return MTLBlendFactorDestinationAlpha;
  12359. case SG_BLENDFACTOR_ONE_MINUS_DST_ALPHA: return MTLBlendFactorOneMinusDestinationAlpha;
  12360. case SG_BLENDFACTOR_SRC_ALPHA_SATURATED: return MTLBlendFactorSourceAlphaSaturated;
  12361. case SG_BLENDFACTOR_BLEND_COLOR: return MTLBlendFactorBlendColor;
  12362. case SG_BLENDFACTOR_ONE_MINUS_BLEND_COLOR: return MTLBlendFactorOneMinusBlendColor;
  12363. case SG_BLENDFACTOR_BLEND_ALPHA: return MTLBlendFactorBlendAlpha;
  12364. case SG_BLENDFACTOR_ONE_MINUS_BLEND_ALPHA: return MTLBlendFactorOneMinusBlendAlpha;
  12365. default: SOKOL_UNREACHABLE; return (MTLBlendFactor)0;
  12366. }
  12367. }
  12368. _SOKOL_PRIVATE MTLCompareFunction _sg_mtl_compare_func(sg_compare_func f) {
  12369. switch (f) {
  12370. case SG_COMPAREFUNC_NEVER: return MTLCompareFunctionNever;
  12371. case SG_COMPAREFUNC_LESS: return MTLCompareFunctionLess;
  12372. case SG_COMPAREFUNC_EQUAL: return MTLCompareFunctionEqual;
  12373. case SG_COMPAREFUNC_LESS_EQUAL: return MTLCompareFunctionLessEqual;
  12374. case SG_COMPAREFUNC_GREATER: return MTLCompareFunctionGreater;
  12375. case SG_COMPAREFUNC_NOT_EQUAL: return MTLCompareFunctionNotEqual;
  12376. case SG_COMPAREFUNC_GREATER_EQUAL: return MTLCompareFunctionGreaterEqual;
  12377. case SG_COMPAREFUNC_ALWAYS: return MTLCompareFunctionAlways;
  12378. default: SOKOL_UNREACHABLE; return (MTLCompareFunction)0;
  12379. }
  12380. }
  12381. _SOKOL_PRIVATE MTLStencilOperation _sg_mtl_stencil_op(sg_stencil_op op) {
  12382. switch (op) {
  12383. case SG_STENCILOP_KEEP: return MTLStencilOperationKeep;
  12384. case SG_STENCILOP_ZERO: return MTLStencilOperationZero;
  12385. case SG_STENCILOP_REPLACE: return MTLStencilOperationReplace;
  12386. case SG_STENCILOP_INCR_CLAMP: return MTLStencilOperationIncrementClamp;
  12387. case SG_STENCILOP_DECR_CLAMP: return MTLStencilOperationDecrementClamp;
  12388. case SG_STENCILOP_INVERT: return MTLStencilOperationInvert;
  12389. case SG_STENCILOP_INCR_WRAP: return MTLStencilOperationIncrementWrap;
  12390. case SG_STENCILOP_DECR_WRAP: return MTLStencilOperationDecrementWrap;
  12391. default: SOKOL_UNREACHABLE; return (MTLStencilOperation)0;
  12392. }
  12393. }
  12394. _SOKOL_PRIVATE MTLCullMode _sg_mtl_cull_mode(sg_cull_mode m) {
  12395. switch (m) {
  12396. case SG_CULLMODE_NONE: return MTLCullModeNone;
  12397. case SG_CULLMODE_FRONT: return MTLCullModeFront;
  12398. case SG_CULLMODE_BACK: return MTLCullModeBack;
  12399. default: SOKOL_UNREACHABLE; return (MTLCullMode)0;
  12400. }
  12401. }
  12402. _SOKOL_PRIVATE MTLWinding _sg_mtl_winding(sg_face_winding w) {
  12403. switch (w) {
  12404. case SG_FACEWINDING_CW: return MTLWindingClockwise;
  12405. case SG_FACEWINDING_CCW: return MTLWindingCounterClockwise;
  12406. default: SOKOL_UNREACHABLE; return (MTLWinding)0;
  12407. }
  12408. }
  12409. _SOKOL_PRIVATE MTLIndexType _sg_mtl_index_type(sg_index_type t) {
  12410. switch (t) {
  12411. case SG_INDEXTYPE_UINT16: return MTLIndexTypeUInt16;
  12412. case SG_INDEXTYPE_UINT32: return MTLIndexTypeUInt32;
  12413. default: SOKOL_UNREACHABLE; return (MTLIndexType)0;
  12414. }
  12415. }
  12416. _SOKOL_PRIVATE int _sg_mtl_index_size(sg_index_type t) {
  12417. switch (t) {
  12418. case SG_INDEXTYPE_NONE: return 0;
  12419. case SG_INDEXTYPE_UINT16: return 2;
  12420. case SG_INDEXTYPE_UINT32: return 4;
  12421. default: SOKOL_UNREACHABLE; return 0;
  12422. }
  12423. }
  12424. _SOKOL_PRIVATE MTLTextureType _sg_mtl_texture_type(sg_image_type t, bool msaa) {
  12425. switch (t) {
  12426. case SG_IMAGETYPE_2D: return msaa ? MTLTextureType2DMultisample : MTLTextureType2D;
  12427. case SG_IMAGETYPE_CUBE: return MTLTextureTypeCube;
  12428. case SG_IMAGETYPE_3D: return MTLTextureType3D;
  12429. // NOTE: MTLTextureType2DMultisampleArray requires macOS 10.14+, iOS 14.0+
  12430. case SG_IMAGETYPE_ARRAY: return MTLTextureType2DArray;
  12431. default: SOKOL_UNREACHABLE; return (MTLTextureType)0;
  12432. }
  12433. }
  12434. _SOKOL_PRIVATE MTLSamplerAddressMode _sg_mtl_address_mode(sg_wrap w) {
  12435. if (_sg.features.image_clamp_to_border) {
  12436. if (@available(macOS 12.0, iOS 14.0, *)) {
  12437. // border color feature available
  12438. switch (w) {
  12439. case SG_WRAP_REPEAT: return MTLSamplerAddressModeRepeat;
  12440. case SG_WRAP_CLAMP_TO_EDGE: return MTLSamplerAddressModeClampToEdge;
  12441. case SG_WRAP_CLAMP_TO_BORDER: return MTLSamplerAddressModeClampToBorderColor;
  12442. case SG_WRAP_MIRRORED_REPEAT: return MTLSamplerAddressModeMirrorRepeat;
  12443. default: SOKOL_UNREACHABLE; return (MTLSamplerAddressMode)0;
  12444. }
  12445. }
  12446. }
  12447. // fallthrough: clamp to border no supported
  12448. switch (w) {
  12449. case SG_WRAP_REPEAT: return MTLSamplerAddressModeRepeat;
  12450. case SG_WRAP_CLAMP_TO_EDGE: return MTLSamplerAddressModeClampToEdge;
  12451. case SG_WRAP_CLAMP_TO_BORDER: return MTLSamplerAddressModeClampToEdge;
  12452. case SG_WRAP_MIRRORED_REPEAT: return MTLSamplerAddressModeMirrorRepeat;
  12453. default: SOKOL_UNREACHABLE; return (MTLSamplerAddressMode)0;
  12454. }
  12455. }
  12456. _SOKOL_PRIVATE API_AVAILABLE(ios(14.0), macos(12.0)) MTLSamplerBorderColor _sg_mtl_border_color(sg_border_color c) {
  12457. switch (c) {
  12458. case SG_BORDERCOLOR_TRANSPARENT_BLACK: return MTLSamplerBorderColorTransparentBlack;
  12459. case SG_BORDERCOLOR_OPAQUE_BLACK: return MTLSamplerBorderColorOpaqueBlack;
  12460. case SG_BORDERCOLOR_OPAQUE_WHITE: return MTLSamplerBorderColorOpaqueWhite;
  12461. default: SOKOL_UNREACHABLE; return (MTLSamplerBorderColor)0;
  12462. }
  12463. }
  12464. _SOKOL_PRIVATE MTLSamplerMinMagFilter _sg_mtl_minmag_filter(sg_filter f) {
  12465. switch (f) {
  12466. case SG_FILTER_NEAREST:
  12467. return MTLSamplerMinMagFilterNearest;
  12468. case SG_FILTER_LINEAR:
  12469. return MTLSamplerMinMagFilterLinear;
  12470. default:
  12471. SOKOL_UNREACHABLE; return (MTLSamplerMinMagFilter)0;
  12472. }
  12473. }
  12474. _SOKOL_PRIVATE MTLSamplerMipFilter _sg_mtl_mipmap_filter(sg_filter f) {
  12475. switch (f) {
  12476. case SG_FILTER_NEAREST:
  12477. return MTLSamplerMipFilterNearest;
  12478. case SG_FILTER_LINEAR:
  12479. return MTLSamplerMipFilterLinear;
  12480. default:
  12481. SOKOL_UNREACHABLE; return (MTLSamplerMipFilter)0;
  12482. }
  12483. }
  12484. _SOKOL_PRIVATE size_t _sg_mtl_vertexbuffer_bindslot(size_t sokol_bindslot) {
  12485. return sokol_bindslot + _SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS;
  12486. }
  12487. //-- a pool for all Metal resource objects, with deferred release queue ---------
  12488. _SOKOL_PRIVATE void _sg_mtl_init_pool(const sg_desc* desc) {
  12489. _sg.mtl.idpool.num_slots = 2 *
  12490. (
  12491. 2 * desc->buffer_pool_size +
  12492. 4 * desc->image_pool_size +
  12493. 1 * desc->sampler_pool_size +
  12494. 4 * desc->shader_pool_size +
  12495. 2 * desc->pipeline_pool_size +
  12496. desc->attachments_pool_size +
  12497. 128
  12498. );
  12499. _sg.mtl.idpool.pool = [NSMutableArray arrayWithCapacity:(NSUInteger)_sg.mtl.idpool.num_slots];
  12500. _SG_OBJC_RETAIN(_sg.mtl.idpool.pool);
  12501. NSNull* null = [NSNull null];
  12502. for (int i = 0; i < _sg.mtl.idpool.num_slots; i++) {
  12503. [_sg.mtl.idpool.pool addObject:null];
  12504. }
  12505. SOKOL_ASSERT([_sg.mtl.idpool.pool count] == (NSUInteger)_sg.mtl.idpool.num_slots);
  12506. // a queue of currently free slot indices
  12507. _sg.mtl.idpool.free_queue_top = 0;
  12508. _sg.mtl.idpool.free_queue = (int*)_sg_malloc_clear((size_t)_sg.mtl.idpool.num_slots * sizeof(int));
  12509. // pool slot 0 is reserved!
  12510. for (int i = _sg.mtl.idpool.num_slots-1; i >= 1; i--) {
  12511. _sg.mtl.idpool.free_queue[_sg.mtl.idpool.free_queue_top++] = i;
  12512. }
  12513. // a circular queue which holds release items (frame index when a resource is to be released, and the resource's pool index
  12514. _sg.mtl.idpool.release_queue_front = 0;
  12515. _sg.mtl.idpool.release_queue_back = 0;
  12516. _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));
  12517. for (int i = 0; i < _sg.mtl.idpool.num_slots; i++) {
  12518. _sg.mtl.idpool.release_queue[i].frame_index = 0;
  12519. _sg.mtl.idpool.release_queue[i].slot_index = _SG_MTL_INVALID_SLOT_INDEX;
  12520. }
  12521. }
  12522. _SOKOL_PRIVATE void _sg_mtl_destroy_pool(void) {
  12523. _sg_free(_sg.mtl.idpool.release_queue); _sg.mtl.idpool.release_queue = 0;
  12524. _sg_free(_sg.mtl.idpool.free_queue); _sg.mtl.idpool.free_queue = 0;
  12525. _SG_OBJC_RELEASE(_sg.mtl.idpool.pool);
  12526. }
  12527. // get a new free resource pool slot
  12528. _SOKOL_PRIVATE int _sg_mtl_alloc_pool_slot(void) {
  12529. SOKOL_ASSERT(_sg.mtl.idpool.free_queue_top > 0);
  12530. const int slot_index = _sg.mtl.idpool.free_queue[--_sg.mtl.idpool.free_queue_top];
  12531. SOKOL_ASSERT((slot_index > 0) && (slot_index < _sg.mtl.idpool.num_slots));
  12532. return slot_index;
  12533. }
  12534. // put a free resource pool slot back into the free-queue
  12535. _SOKOL_PRIVATE void _sg_mtl_free_pool_slot(int slot_index) {
  12536. SOKOL_ASSERT(_sg.mtl.idpool.free_queue_top < _sg.mtl.idpool.num_slots);
  12537. SOKOL_ASSERT((slot_index > 0) && (slot_index < _sg.mtl.idpool.num_slots));
  12538. _sg.mtl.idpool.free_queue[_sg.mtl.idpool.free_queue_top++] = slot_index;
  12539. }
  12540. // add an MTLResource to the pool, return pool index or 0 if input was 'nil'
  12541. _SOKOL_PRIVATE int _sg_mtl_add_resource(id res) {
  12542. if (nil == res) {
  12543. return _SG_MTL_INVALID_SLOT_INDEX;
  12544. }
  12545. _sg_stats_add(metal.idpool.num_added, 1);
  12546. const int slot_index = _sg_mtl_alloc_pool_slot();
  12547. // NOTE: the NSMutableArray will take ownership of its items
  12548. SOKOL_ASSERT([NSNull null] == _sg.mtl.idpool.pool[(NSUInteger)slot_index]);
  12549. _sg.mtl.idpool.pool[(NSUInteger)slot_index] = res;
  12550. return slot_index;
  12551. }
  12552. /* mark an MTLResource for release, this will put the resource into the
  12553. deferred-release queue, and the resource will then be released N frames later,
  12554. the special pool index 0 will be ignored (this means that a nil
  12555. value was provided to _sg_mtl_add_resource()
  12556. */
  12557. _SOKOL_PRIVATE void _sg_mtl_release_resource(uint32_t frame_index, int slot_index) {
  12558. if (slot_index == _SG_MTL_INVALID_SLOT_INDEX) {
  12559. return;
  12560. }
  12561. _sg_stats_add(metal.idpool.num_released, 1);
  12562. SOKOL_ASSERT((slot_index > 0) && (slot_index < _sg.mtl.idpool.num_slots));
  12563. SOKOL_ASSERT([NSNull null] != _sg.mtl.idpool.pool[(NSUInteger)slot_index]);
  12564. int release_index = _sg.mtl.idpool.release_queue_front++;
  12565. if (_sg.mtl.idpool.release_queue_front >= _sg.mtl.idpool.num_slots) {
  12566. // wrap-around
  12567. _sg.mtl.idpool.release_queue_front = 0;
  12568. }
  12569. // release queue full?
  12570. SOKOL_ASSERT(_sg.mtl.idpool.release_queue_front != _sg.mtl.idpool.release_queue_back);
  12571. SOKOL_ASSERT(0 == _sg.mtl.idpool.release_queue[release_index].frame_index);
  12572. const uint32_t safe_to_release_frame_index = frame_index + SG_NUM_INFLIGHT_FRAMES + 1;
  12573. _sg.mtl.idpool.release_queue[release_index].frame_index = safe_to_release_frame_index;
  12574. _sg.mtl.idpool.release_queue[release_index].slot_index = slot_index;
  12575. }
  12576. // run garbage-collection pass on all resources in the release-queue
  12577. _SOKOL_PRIVATE void _sg_mtl_garbage_collect(uint32_t frame_index) {
  12578. while (_sg.mtl.idpool.release_queue_back != _sg.mtl.idpool.release_queue_front) {
  12579. if (frame_index < _sg.mtl.idpool.release_queue[_sg.mtl.idpool.release_queue_back].frame_index) {
  12580. // don't need to check further, release-items past this are too young
  12581. break;
  12582. }
  12583. _sg_stats_add(metal.idpool.num_garbage_collected, 1);
  12584. // safe to release this resource
  12585. const int slot_index = _sg.mtl.idpool.release_queue[_sg.mtl.idpool.release_queue_back].slot_index;
  12586. SOKOL_ASSERT((slot_index > 0) && (slot_index < _sg.mtl.idpool.num_slots));
  12587. // note: the NSMutableArray takes ownership of its items, assigning an NSNull object will
  12588. // release the object, no matter if using ARC or not
  12589. SOKOL_ASSERT(_sg.mtl.idpool.pool[(NSUInteger)slot_index] != [NSNull null]);
  12590. _sg.mtl.idpool.pool[(NSUInteger)slot_index] = [NSNull null];
  12591. // put the now free pool index back on the free queue
  12592. _sg_mtl_free_pool_slot(slot_index);
  12593. // reset the release queue slot and advance the back index
  12594. _sg.mtl.idpool.release_queue[_sg.mtl.idpool.release_queue_back].frame_index = 0;
  12595. _sg.mtl.idpool.release_queue[_sg.mtl.idpool.release_queue_back].slot_index = _SG_MTL_INVALID_SLOT_INDEX;
  12596. _sg.mtl.idpool.release_queue_back++;
  12597. if (_sg.mtl.idpool.release_queue_back >= _sg.mtl.idpool.num_slots) {
  12598. // wrap-around
  12599. _sg.mtl.idpool.release_queue_back = 0;
  12600. }
  12601. }
  12602. }
  12603. _SOKOL_PRIVATE id _sg_mtl_id(int slot_index) {
  12604. return _sg.mtl.idpool.pool[(NSUInteger)slot_index];
  12605. }
  12606. _SOKOL_PRIVATE void _sg_mtl_clear_state_cache(void) {
  12607. _sg_clear(&_sg.mtl.state_cache, sizeof(_sg.mtl.state_cache));
  12608. }
  12609. // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf
  12610. _SOKOL_PRIVATE void _sg_mtl_init_caps(void) {
  12611. #if defined(_SG_TARGET_MACOS)
  12612. _sg.backend = SG_BACKEND_METAL_MACOS;
  12613. #elif defined(_SG_TARGET_IOS)
  12614. #if defined(_SG_TARGET_IOS_SIMULATOR)
  12615. _sg.backend = SG_BACKEND_METAL_SIMULATOR;
  12616. #else
  12617. _sg.backend = SG_BACKEND_METAL_IOS;
  12618. #endif
  12619. #endif
  12620. _sg.features.origin_top_left = true;
  12621. _sg.features.mrt_independent_blend_state = true;
  12622. _sg.features.mrt_independent_write_mask = true;
  12623. _sg.features.compute = true;
  12624. _sg.features.msaa_image_bindings = true;
  12625. _sg.features.image_clamp_to_border = false;
  12626. #if (MAC_OS_X_VERSION_MAX_ALLOWED >= 120000) || (__IPHONE_OS_VERSION_MAX_ALLOWED >= 140000)
  12627. if (@available(macOS 12.0, iOS 14.0, *)) {
  12628. _sg.features.image_clamp_to_border = [_sg.mtl.device supportsFamily:MTLGPUFamilyApple7]
  12629. || [_sg.mtl.device supportsFamily:MTLGPUFamilyMac2];
  12630. #if (MAC_OS_X_VERSION_MAX_ALLOWED >= 130000) || (__IPHONE_OS_VERSION_MAX_ALLOWED >= 160000)
  12631. if (!_sg.features.image_clamp_to_border) {
  12632. if (@available(macOS 13.0, iOS 16.0, *)) {
  12633. _sg.features.image_clamp_to_border = [_sg.mtl.device supportsFamily:MTLGPUFamilyMetal3];
  12634. }
  12635. }
  12636. #endif
  12637. }
  12638. #endif
  12639. #if defined(_SG_TARGET_MACOS)
  12640. _sg.limits.max_image_size_2d = 16 * 1024;
  12641. _sg.limits.max_image_size_cube = 16 * 1024;
  12642. _sg.limits.max_image_size_3d = 2 * 1024;
  12643. _sg.limits.max_image_size_array = 16 * 1024;
  12644. _sg.limits.max_image_array_layers = 2 * 1024;
  12645. #else
  12646. // FIXME: newer iOS devices support 16k textures
  12647. _sg.limits.max_image_size_2d = 8 * 1024;
  12648. _sg.limits.max_image_size_cube = 8 * 1024;
  12649. _sg.limits.max_image_size_3d = 2 * 1024;
  12650. _sg.limits.max_image_size_array = 8 * 1024;
  12651. _sg.limits.max_image_array_layers = 2 * 1024;
  12652. #endif
  12653. _sg.limits.max_vertex_attrs = SG_MAX_VERTEX_ATTRIBUTES;
  12654. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R8]);
  12655. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R8SN]);
  12656. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R8UI]);
  12657. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R8SI]);
  12658. #if defined(_SG_TARGET_MACOS)
  12659. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16]);
  12660. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16SN]);
  12661. #else
  12662. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_R16]);
  12663. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_R16SN]);
  12664. #endif
  12665. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R16UI]);
  12666. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R16SI]);
  12667. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16F]);
  12668. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG8]);
  12669. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG8SN]);
  12670. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG8UI]);
  12671. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG8SI]);
  12672. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32UI]);
  12673. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32SI]);
  12674. #if defined(_SG_TARGET_MACOS)
  12675. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R32F]);
  12676. #else
  12677. _sg_pixelformat_sbr(&_sg.formats[SG_PIXELFORMAT_R32F]);
  12678. #endif
  12679. #if defined(_SG_TARGET_MACOS)
  12680. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16]);
  12681. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16SN]);
  12682. #else
  12683. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_RG16]);
  12684. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_RG16SN]);
  12685. #endif
  12686. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG16UI]);
  12687. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG16SI]);
  12688. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16F]);
  12689. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA8]);
  12690. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_SRGB8A8]);
  12691. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA8SN]);
  12692. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA8UI]);
  12693. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA8SI]);
  12694. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_BGRA8]);
  12695. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGB10A2]);
  12696. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  12697. #if defined(_SG_TARGET_MACOS)
  12698. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGB9E5]);
  12699. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  12700. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  12701. #else
  12702. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGB9E5]);
  12703. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  12704. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  12705. #endif
  12706. #if defined(_SG_TARGET_MACOS)
  12707. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  12708. #else
  12709. _sg_pixelformat_sbr(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  12710. #endif
  12711. #if defined(_SG_TARGET_MACOS)
  12712. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16]);
  12713. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16SN]);
  12714. #else
  12715. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_RGBA16]);
  12716. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_RGBA16SN]);
  12717. #endif
  12718. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA16UI]);
  12719. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA16SI]);
  12720. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  12721. #if defined(_SG_TARGET_MACOS)
  12722. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  12723. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  12724. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  12725. #else
  12726. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  12727. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  12728. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  12729. #endif
  12730. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH]);
  12731. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH_STENCIL]);
  12732. #if defined(_SG_TARGET_MACOS)
  12733. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC1_RGBA]);
  12734. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC2_RGBA]);
  12735. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_RGBA]);
  12736. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_SRGBA]);
  12737. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_R]);
  12738. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_RSN]);
  12739. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RG]);
  12740. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RGSN]);
  12741. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBF]);
  12742. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBUF]);
  12743. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_RGBA]);
  12744. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_SRGBA]);
  12745. #else
  12746. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8]);
  12747. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8]);
  12748. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8A1]);
  12749. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGBA8]);
  12750. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8A8]);
  12751. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11]);
  12752. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11SN]);
  12753. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11]);
  12754. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11SN]);
  12755. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_RGBA]);
  12756. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_SRGBA]);
  12757. #endif
  12758. // compute shader access (see: https://github.com/gpuweb/gpuweb/issues/513)
  12759. // for now let's use the same conservative set on all backends even though
  12760. // some backends are less restrictive
  12761. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8]);
  12762. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8SN]);
  12763. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8UI]);
  12764. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8SI]);
  12765. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16UI]);
  12766. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16SI]);
  12767. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  12768. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32UI]);
  12769. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32SI]);
  12770. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32F]);
  12771. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  12772. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  12773. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  12774. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  12775. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  12776. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  12777. }
  12778. //-- main Metal backend state and functions ------------------------------------
  12779. _SOKOL_PRIVATE void _sg_mtl_setup_backend(const sg_desc* desc) {
  12780. // assume already zero-initialized
  12781. SOKOL_ASSERT(desc);
  12782. SOKOL_ASSERT(desc->environment.metal.device);
  12783. SOKOL_ASSERT(desc->uniform_buffer_size > 0);
  12784. _sg_mtl_init_pool(desc);
  12785. _sg_mtl_clear_state_cache();
  12786. _sg.mtl.valid = true;
  12787. _sg.mtl.ub_size = desc->uniform_buffer_size;
  12788. _sg.mtl.sem = dispatch_semaphore_create(SG_NUM_INFLIGHT_FRAMES);
  12789. _sg.mtl.device = (__bridge id<MTLDevice>) desc->environment.metal.device;
  12790. _sg.mtl.cmd_queue = [_sg.mtl.device newCommandQueue];
  12791. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  12792. _sg.mtl.uniform_buffers[i] = [_sg.mtl.device
  12793. newBufferWithLength:(NSUInteger)_sg.mtl.ub_size
  12794. options:MTLResourceCPUCacheModeWriteCombined|MTLResourceStorageModeShared
  12795. ];
  12796. #if defined(SOKOL_DEBUG)
  12797. _sg.mtl.uniform_buffers[i].label = [NSString stringWithFormat:@"sg-uniform-buffer.%d", i];
  12798. #endif
  12799. }
  12800. if (desc->mtl_force_managed_storage_mode) {
  12801. _sg.mtl.use_shared_storage_mode = false;
  12802. } else if (@available(macOS 10.15, iOS 13.0, *)) {
  12803. // on Intel Macs, always use managed resources even though the
  12804. // device says it supports unified memory (because of texture restrictions)
  12805. const bool is_apple_gpu = [_sg.mtl.device supportsFamily:MTLGPUFamilyApple1];
  12806. if (!is_apple_gpu) {
  12807. _sg.mtl.use_shared_storage_mode = false;
  12808. } else {
  12809. _sg.mtl.use_shared_storage_mode = true;
  12810. }
  12811. } else {
  12812. #if defined(_SG_TARGET_MACOS)
  12813. _sg.mtl.use_shared_storage_mode = false;
  12814. #else
  12815. _sg.mtl.use_shared_storage_mode = true;
  12816. #endif
  12817. }
  12818. _sg_mtl_init_caps();
  12819. }
  12820. _SOKOL_PRIVATE void _sg_mtl_discard_backend(void) {
  12821. SOKOL_ASSERT(_sg.mtl.valid);
  12822. // wait for the last frame to finish
  12823. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  12824. dispatch_semaphore_wait(_sg.mtl.sem, DISPATCH_TIME_FOREVER);
  12825. }
  12826. // semaphore must be "relinquished" before destruction
  12827. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  12828. dispatch_semaphore_signal(_sg.mtl.sem);
  12829. }
  12830. _sg_mtl_garbage_collect(_sg.frame_index + SG_NUM_INFLIGHT_FRAMES + 2);
  12831. _sg_mtl_destroy_pool();
  12832. _sg.mtl.valid = false;
  12833. _SG_OBJC_RELEASE(_sg.mtl.sem);
  12834. _SG_OBJC_RELEASE(_sg.mtl.device);
  12835. _SG_OBJC_RELEASE(_sg.mtl.cmd_queue);
  12836. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  12837. _SG_OBJC_RELEASE(_sg.mtl.uniform_buffers[i]);
  12838. }
  12839. // NOTE: MTLCommandBuffer, MTLRenderCommandEncoder and MTLComputeCommandEncoder are auto-released
  12840. _sg.mtl.cmd_buffer = nil;
  12841. _sg.mtl.render_cmd_encoder = nil;
  12842. _sg.mtl.compute_cmd_encoder = nil;
  12843. }
  12844. _SOKOL_PRIVATE void _sg_mtl_reset_state_cache(void) {
  12845. _sg_mtl_clear_state_cache();
  12846. }
  12847. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  12848. SOKOL_ASSERT(buf && desc);
  12849. SOKOL_ASSERT(buf->cmn.size > 0);
  12850. const bool injected = (0 != desc->mtl_buffers[0]);
  12851. MTLResourceOptions mtl_options = _sg_mtl_buffer_resource_options(&buf->cmn.usage);
  12852. for (int slot = 0; slot < buf->cmn.num_slots; slot++) {
  12853. id<MTLBuffer> mtl_buf;
  12854. if (injected) {
  12855. SOKOL_ASSERT(desc->mtl_buffers[slot]);
  12856. mtl_buf = (__bridge id<MTLBuffer>) desc->mtl_buffers[slot];
  12857. } else {
  12858. if (desc->data.ptr) {
  12859. SOKOL_ASSERT(desc->data.size > 0);
  12860. mtl_buf = [_sg.mtl.device newBufferWithBytes:desc->data.ptr length:(NSUInteger)buf->cmn.size options:mtl_options];
  12861. } else {
  12862. mtl_buf = [_sg.mtl.device newBufferWithLength:(NSUInteger)buf->cmn.size options:mtl_options];
  12863. }
  12864. if (nil == mtl_buf) {
  12865. _SG_ERROR(METAL_CREATE_BUFFER_FAILED);
  12866. return SG_RESOURCESTATE_FAILED;
  12867. }
  12868. }
  12869. #if defined(SOKOL_DEBUG)
  12870. if (desc->label) {
  12871. mtl_buf.label = [NSString stringWithFormat:@"%s.%d", desc->label, slot];
  12872. }
  12873. #endif
  12874. buf->mtl.buf[slot] = _sg_mtl_add_resource(mtl_buf);
  12875. _SG_OBJC_RELEASE(mtl_buf);
  12876. }
  12877. return SG_RESOURCESTATE_VALID;
  12878. }
  12879. _SOKOL_PRIVATE void _sg_mtl_discard_buffer(_sg_buffer_t* buf) {
  12880. SOKOL_ASSERT(buf);
  12881. for (int slot = 0; slot < buf->cmn.num_slots; slot++) {
  12882. // it's valid to call release resource with '0'
  12883. _sg_mtl_release_resource(_sg.frame_index, buf->mtl.buf[slot]);
  12884. }
  12885. }
  12886. _SOKOL_PRIVATE void _sg_mtl_copy_image_data(const _sg_image_t* img, __unsafe_unretained id<MTLTexture> mtl_tex, const sg_image_data* data) {
  12887. const int num_faces = (img->cmn.type == SG_IMAGETYPE_CUBE) ? 6:1;
  12888. const int num_slices = (img->cmn.type == SG_IMAGETYPE_ARRAY) ? img->cmn.num_slices : 1;
  12889. for (int face_index = 0; face_index < num_faces; face_index++) {
  12890. for (int mip_index = 0; mip_index < img->cmn.num_mipmaps; mip_index++) {
  12891. SOKOL_ASSERT(data->subimage[face_index][mip_index].ptr);
  12892. SOKOL_ASSERT(data->subimage[face_index][mip_index].size > 0);
  12893. const uint8_t* data_ptr = (const uint8_t*)data->subimage[face_index][mip_index].ptr;
  12894. const int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  12895. const int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  12896. int bytes_per_row = _sg_row_pitch(img->cmn.pixel_format, mip_width, 1);
  12897. int bytes_per_slice = _sg_surface_pitch(img->cmn.pixel_format, mip_width, mip_height, 1);
  12898. /* bytesPerImage special case: https://developer.apple.com/documentation/metal/mtltexture/1515679-replaceregion
  12899. "Supply a nonzero value only when you copy data to a MTLTextureType3D type texture"
  12900. */
  12901. MTLRegion region;
  12902. int bytes_per_image;
  12903. if (img->cmn.type == SG_IMAGETYPE_3D) {
  12904. const int mip_depth = _sg_miplevel_dim(img->cmn.num_slices, mip_index);
  12905. region = MTLRegionMake3D(0, 0, 0, (NSUInteger)mip_width, (NSUInteger)mip_height, (NSUInteger)mip_depth);
  12906. bytes_per_image = bytes_per_slice;
  12907. // FIXME: apparently the minimal bytes_per_image size for 3D texture is 4 KByte... somehow need to handle this
  12908. } else {
  12909. region = MTLRegionMake2D(0, 0, (NSUInteger)mip_width, (NSUInteger)mip_height);
  12910. bytes_per_image = 0;
  12911. }
  12912. for (int slice_index = 0; slice_index < num_slices; slice_index++) {
  12913. const int mtl_slice_index = (img->cmn.type == SG_IMAGETYPE_CUBE) ? face_index : slice_index;
  12914. const int slice_offset = slice_index * bytes_per_slice;
  12915. SOKOL_ASSERT((slice_offset + bytes_per_slice) <= (int)data->subimage[face_index][mip_index].size);
  12916. [mtl_tex replaceRegion:region
  12917. mipmapLevel:(NSUInteger)mip_index
  12918. slice:(NSUInteger)mtl_slice_index
  12919. withBytes:data_ptr + slice_offset
  12920. bytesPerRow:(NSUInteger)bytes_per_row
  12921. bytesPerImage:(NSUInteger)bytes_per_image];
  12922. }
  12923. }
  12924. }
  12925. }
  12926. _SOKOL_PRIVATE bool _sg_mtl_init_texdesc(MTLTextureDescriptor* mtl_desc, _sg_image_t* img) {
  12927. mtl_desc.textureType = _sg_mtl_texture_type(img->cmn.type, img->cmn.sample_count > 1);
  12928. mtl_desc.pixelFormat = _sg_mtl_pixel_format(img->cmn.pixel_format);
  12929. if (MTLPixelFormatInvalid == mtl_desc.pixelFormat) {
  12930. _SG_ERROR(METAL_TEXTURE_FORMAT_NOT_SUPPORTED);
  12931. return false;
  12932. }
  12933. mtl_desc.width = (NSUInteger)img->cmn.width;
  12934. mtl_desc.height = (NSUInteger)img->cmn.height;
  12935. if (SG_IMAGETYPE_3D == img->cmn.type) {
  12936. mtl_desc.depth = (NSUInteger)img->cmn.num_slices;
  12937. } else {
  12938. mtl_desc.depth = 1;
  12939. }
  12940. mtl_desc.mipmapLevelCount = (NSUInteger)img->cmn.num_mipmaps;
  12941. if (SG_IMAGETYPE_ARRAY == img->cmn.type) {
  12942. mtl_desc.arrayLength = (NSUInteger)img->cmn.num_slices;
  12943. } else {
  12944. mtl_desc.arrayLength = 1;
  12945. }
  12946. mtl_desc.sampleCount = (NSUInteger)img->cmn.sample_count;
  12947. MTLTextureUsage mtl_tex_usage = MTLTextureUsageShaderRead;
  12948. if (img->cmn.usage.render_attachment) {
  12949. mtl_tex_usage |= MTLTextureUsageRenderTarget;
  12950. } else if (img->cmn.usage.storage_attachment) {
  12951. mtl_tex_usage |= MTLTextureUsageShaderWrite;
  12952. }
  12953. mtl_desc.usage = mtl_tex_usage;
  12954. MTLResourceOptions mtl_res_options = 0;
  12955. if (img->cmn.usage.render_attachment || img->cmn.usage.storage_attachment) {
  12956. mtl_res_options |= MTLResourceStorageModePrivate;
  12957. } else {
  12958. mtl_res_options |= _sg_mtl_resource_options_storage_mode_managed_or_shared();
  12959. if (!img->cmn.usage.immutable) {
  12960. mtl_res_options |= MTLResourceCPUCacheModeWriteCombined;
  12961. }
  12962. }
  12963. mtl_desc.resourceOptions = mtl_res_options;
  12964. return true;
  12965. }
  12966. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  12967. SOKOL_ASSERT(img && desc);
  12968. const bool injected = (0 != desc->mtl_textures[0]);
  12969. // first initialize all Metal resource pool slots to 'empty'
  12970. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  12971. img->mtl.tex[i] = _sg_mtl_add_resource(nil);
  12972. }
  12973. // initialize a Metal texture descriptor
  12974. MTLTextureDescriptor* mtl_desc = [[MTLTextureDescriptor alloc] init];
  12975. if (!_sg_mtl_init_texdesc(mtl_desc, img)) {
  12976. _SG_OBJC_RELEASE(mtl_desc);
  12977. return SG_RESOURCESTATE_FAILED;
  12978. }
  12979. for (int slot = 0; slot < img->cmn.num_slots; slot++) {
  12980. id<MTLTexture> mtl_tex;
  12981. if (injected) {
  12982. SOKOL_ASSERT(desc->mtl_textures[slot]);
  12983. mtl_tex = (__bridge id<MTLTexture>) desc->mtl_textures[slot];
  12984. } else {
  12985. mtl_tex = [_sg.mtl.device newTextureWithDescriptor:mtl_desc];
  12986. if (nil == mtl_tex) {
  12987. _SG_OBJC_RELEASE(mtl_desc);
  12988. _SG_ERROR(METAL_CREATE_TEXTURE_FAILED);
  12989. return SG_RESOURCESTATE_FAILED;
  12990. }
  12991. if (desc->data.subimage[0][0].ptr) {
  12992. _sg_mtl_copy_image_data(img, mtl_tex, &desc->data);
  12993. }
  12994. }
  12995. #if defined(SOKOL_DEBUG)
  12996. if (desc->label) {
  12997. mtl_tex.label = [NSString stringWithFormat:@"%s.%d", desc->label, slot];
  12998. }
  12999. #endif
  13000. img->mtl.tex[slot] = _sg_mtl_add_resource(mtl_tex);
  13001. _SG_OBJC_RELEASE(mtl_tex);
  13002. }
  13003. _SG_OBJC_RELEASE(mtl_desc);
  13004. return SG_RESOURCESTATE_VALID;
  13005. }
  13006. _SOKOL_PRIVATE void _sg_mtl_discard_image(_sg_image_t* img) {
  13007. SOKOL_ASSERT(img);
  13008. // it's valid to call release resource with a 'null resource'
  13009. for (int slot = 0; slot < img->cmn.num_slots; slot++) {
  13010. _sg_mtl_release_resource(_sg.frame_index, img->mtl.tex[slot]);
  13011. }
  13012. }
  13013. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  13014. SOKOL_ASSERT(smp && desc);
  13015. id<MTLSamplerState> mtl_smp;
  13016. const bool injected = (0 != desc->mtl_sampler);
  13017. if (injected) {
  13018. SOKOL_ASSERT(desc->mtl_sampler);
  13019. mtl_smp = (__bridge id<MTLSamplerState>) desc->mtl_sampler;
  13020. } else {
  13021. MTLSamplerDescriptor* mtl_desc = [[MTLSamplerDescriptor alloc] init];
  13022. mtl_desc.sAddressMode = _sg_mtl_address_mode(desc->wrap_u);
  13023. mtl_desc.tAddressMode = _sg_mtl_address_mode(desc->wrap_v);
  13024. mtl_desc.rAddressMode = _sg_mtl_address_mode(desc->wrap_w);
  13025. if (_sg.features.image_clamp_to_border) {
  13026. if (@available(macOS 12.0, iOS 14.0, *)) {
  13027. mtl_desc.borderColor = _sg_mtl_border_color(desc->border_color);
  13028. }
  13029. }
  13030. mtl_desc.minFilter = _sg_mtl_minmag_filter(desc->min_filter);
  13031. mtl_desc.magFilter = _sg_mtl_minmag_filter(desc->mag_filter);
  13032. mtl_desc.mipFilter = _sg_mtl_mipmap_filter(desc->mipmap_filter);
  13033. mtl_desc.lodMinClamp = desc->min_lod;
  13034. mtl_desc.lodMaxClamp = desc->max_lod;
  13035. // FIXME: lodAverage?
  13036. mtl_desc.maxAnisotropy = desc->max_anisotropy;
  13037. mtl_desc.normalizedCoordinates = YES;
  13038. mtl_desc.compareFunction = _sg_mtl_compare_func(desc->compare);
  13039. #if defined(SOKOL_DEBUG)
  13040. if (desc->label) {
  13041. mtl_desc.label = [NSString stringWithUTF8String:desc->label];
  13042. }
  13043. #endif
  13044. mtl_smp = [_sg.mtl.device newSamplerStateWithDescriptor:mtl_desc];
  13045. _SG_OBJC_RELEASE(mtl_desc);
  13046. if (nil == mtl_smp) {
  13047. _SG_ERROR(METAL_CREATE_SAMPLER_FAILED);
  13048. return SG_RESOURCESTATE_FAILED;
  13049. }
  13050. }
  13051. smp->mtl.sampler_state = _sg_mtl_add_resource(mtl_smp);
  13052. _SG_OBJC_RELEASE(mtl_smp);
  13053. return SG_RESOURCESTATE_VALID;
  13054. }
  13055. _SOKOL_PRIVATE void _sg_mtl_discard_sampler(_sg_sampler_t* smp) {
  13056. SOKOL_ASSERT(smp);
  13057. // it's valid to call release resource with a 'null resource'
  13058. _sg_mtl_release_resource(_sg.frame_index, smp->mtl.sampler_state);
  13059. }
  13060. _SOKOL_PRIVATE id<MTLLibrary> _sg_mtl_compile_library(const char* src) {
  13061. NSError* err = NULL;
  13062. id<MTLLibrary> lib = [_sg.mtl.device
  13063. newLibraryWithSource:[NSString stringWithUTF8String:src]
  13064. options:nil
  13065. error:&err
  13066. ];
  13067. if (err) {
  13068. _SG_ERROR(METAL_SHADER_COMPILATION_FAILED);
  13069. _SG_LOGMSG(METAL_SHADER_COMPILATION_OUTPUT, [err.localizedDescription UTF8String]);
  13070. }
  13071. return lib;
  13072. }
  13073. _SOKOL_PRIVATE id<MTLLibrary> _sg_mtl_library_from_bytecode(const void* ptr, size_t num_bytes) {
  13074. NSError* err = NULL;
  13075. dispatch_data_t lib_data = dispatch_data_create(ptr, num_bytes, NULL, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
  13076. id<MTLLibrary> lib = [_sg.mtl.device newLibraryWithData:lib_data error:&err];
  13077. if (err) {
  13078. _SG_ERROR(METAL_SHADER_CREATION_FAILED);
  13079. _SG_LOGMSG(METAL_SHADER_COMPILATION_OUTPUT, [err.localizedDescription UTF8String]);
  13080. }
  13081. _SG_OBJC_RELEASE(lib_data);
  13082. return lib;
  13083. }
  13084. _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) {
  13085. SOKOL_ASSERT(res->mtl_lib == _SG_MTL_INVALID_SLOT_INDEX);
  13086. SOKOL_ASSERT(res->mtl_func == _SG_MTL_INVALID_SLOT_INDEX);
  13087. id<MTLLibrary> mtl_lib = nil;
  13088. if (func->bytecode.ptr) {
  13089. SOKOL_ASSERT(func->bytecode.size > 0);
  13090. mtl_lib = _sg_mtl_library_from_bytecode(func->bytecode.ptr, func->bytecode.size);
  13091. } else if (func->source) {
  13092. mtl_lib = _sg_mtl_compile_library(func->source);
  13093. }
  13094. if (mtl_lib == nil) {
  13095. return false;
  13096. }
  13097. #if defined(SOKOL_DEBUG)
  13098. if (label) {
  13099. SOKOL_ASSERT(label_ext);
  13100. mtl_lib.label = [NSString stringWithFormat:@"%s.%s", label, label_ext];
  13101. }
  13102. #else
  13103. _SOKOL_UNUSED(label);
  13104. _SOKOL_UNUSED(label_ext);
  13105. #endif
  13106. SOKOL_ASSERT(func->entry);
  13107. id<MTLFunction> mtl_func = [mtl_lib newFunctionWithName:[NSString stringWithUTF8String:func->entry]];
  13108. if (mtl_func == nil) {
  13109. _SG_ERROR(METAL_SHADER_ENTRY_NOT_FOUND);
  13110. _SG_OBJC_RELEASE(mtl_lib);
  13111. return false;
  13112. }
  13113. res->mtl_lib = _sg_mtl_add_resource(mtl_lib);
  13114. res->mtl_func = _sg_mtl_add_resource(mtl_func);
  13115. _SG_OBJC_RELEASE(mtl_lib);
  13116. _SG_OBJC_RELEASE(mtl_func);
  13117. return true;
  13118. }
  13119. _SOKOL_PRIVATE void _sg_mtl_discard_shader_func(const _sg_mtl_shader_func_t* func) {
  13120. // it is valid to call _sg_mtl_release_resource with a 'null resource'
  13121. _sg_mtl_release_resource(_sg.frame_index, func->mtl_func);
  13122. _sg_mtl_release_resource(_sg.frame_index, func->mtl_lib);
  13123. }
  13124. // NOTE: this is an out-of-range check for MSL bindslots that's also active in release mode
  13125. _SOKOL_PRIVATE bool _sg_mtl_ensure_msl_bindslot_ranges(const sg_shader_desc* desc) {
  13126. SOKOL_ASSERT(desc);
  13127. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  13128. if (desc->uniform_blocks[i].msl_buffer_n >= _SG_MTL_MAX_STAGE_UB_BINDINGS) {
  13129. _SG_ERROR(METAL_UNIFORMBLOCK_MSL_BUFFER_SLOT_OUT_OF_RANGE);
  13130. return false;
  13131. }
  13132. }
  13133. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  13134. if (desc->images[i].msl_texture_n >= _SG_MTL_MAX_STAGE_TEXTURE_BINDINGS) {
  13135. _SG_ERROR(METAL_IMAGE_MSL_TEXTURE_SLOT_OUT_OF_RANGE);
  13136. return false;
  13137. }
  13138. }
  13139. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  13140. if (desc->samplers[i].msl_sampler_n >= _SG_MTL_MAX_STAGE_SAMPLER_BINDINGS) {
  13141. _SG_ERROR(METAL_SAMPLER_MSL_SAMPLER_SLOT_OUT_OF_RANGE);
  13142. return false;
  13143. }
  13144. }
  13145. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  13146. if (desc->storage_buffers[i].msl_buffer_n >= _SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS) {
  13147. _SG_ERROR(METAL_STORAGEBUFFER_MSL_BUFFER_SLOT_OUT_OF_RANGE);
  13148. return false;
  13149. }
  13150. }
  13151. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  13152. if (desc->storage_images[i].msl_texture_n >= _SG_MTL_MAX_STAGE_TEXTURE_BINDINGS) {
  13153. _SG_ERROR(METAL_STORAGEIMAGE_MSL_TEXTURE_SLOT_OUT_OF_RANGE);
  13154. return false;
  13155. }
  13156. }
  13157. return true;
  13158. }
  13159. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  13160. SOKOL_ASSERT(shd && desc);
  13161. // do a MSL bindslot range check also in release mode, and if that fails,
  13162. // also fail shader creation
  13163. if (!_sg_mtl_ensure_msl_bindslot_ranges(desc)) {
  13164. return SG_RESOURCESTATE_FAILED;
  13165. }
  13166. shd->mtl.threads_per_threadgroup = MTLSizeMake(
  13167. (NSUInteger)desc->mtl_threads_per_threadgroup.x,
  13168. (NSUInteger)desc->mtl_threads_per_threadgroup.y,
  13169. (NSUInteger)desc->mtl_threads_per_threadgroup.z);
  13170. // copy resource bindslot mappings
  13171. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  13172. shd->mtl.ub_buffer_n[i] = desc->uniform_blocks[i].msl_buffer_n;
  13173. }
  13174. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  13175. shd->mtl.img_texture_n[i] = desc->images[i].msl_texture_n;
  13176. }
  13177. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  13178. shd->mtl.smp_sampler_n[i] = desc->samplers[i].msl_sampler_n;
  13179. }
  13180. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  13181. shd->mtl.sbuf_buffer_n[i] = desc->storage_buffers[i].msl_buffer_n;
  13182. }
  13183. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  13184. shd->mtl.simg_texture_n[i] = desc->storage_images[i].msl_texture_n;
  13185. }
  13186. // create metal library and function objects
  13187. bool shd_valid = true;
  13188. if (desc->vertex_func.source || desc->vertex_func.bytecode.ptr) {
  13189. shd_valid &= _sg_mtl_create_shader_func(&desc->vertex_func, desc->label, "vs", &shd->mtl.vertex_func);
  13190. }
  13191. if (desc->fragment_func.source || desc->fragment_func.bytecode.ptr) {
  13192. shd_valid &= _sg_mtl_create_shader_func(&desc->fragment_func, desc->label, "fs", &shd->mtl.fragment_func);
  13193. }
  13194. if (desc->compute_func.source || desc->compute_func.bytecode.ptr) {
  13195. shd_valid &= _sg_mtl_create_shader_func(&desc->compute_func, desc->label, "cs", &shd->mtl.compute_func);
  13196. }
  13197. if (!shd_valid) {
  13198. _sg_mtl_discard_shader_func(&shd->mtl.vertex_func);
  13199. _sg_mtl_discard_shader_func(&shd->mtl.fragment_func);
  13200. _sg_mtl_discard_shader_func(&shd->mtl.compute_func);
  13201. }
  13202. return shd_valid ? SG_RESOURCESTATE_VALID : SG_RESOURCESTATE_FAILED;
  13203. }
  13204. _SOKOL_PRIVATE void _sg_mtl_discard_shader(_sg_shader_t* shd) {
  13205. SOKOL_ASSERT(shd);
  13206. _sg_mtl_discard_shader_func(&shd->mtl.vertex_func);
  13207. _sg_mtl_discard_shader_func(&shd->mtl.fragment_func);
  13208. _sg_mtl_discard_shader_func(&shd->mtl.compute_func);
  13209. }
  13210. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_pipeline(_sg_pipeline_t* pip, const sg_pipeline_desc* desc) {
  13211. SOKOL_ASSERT(pip && desc);
  13212. _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  13213. if (pip->cmn.is_compute) {
  13214. NSError* err = NULL;
  13215. MTLComputePipelineDescriptor* cp_desc = [[MTLComputePipelineDescriptor alloc] init];
  13216. cp_desc.computeFunction = _sg_mtl_id(shd->mtl.compute_func.mtl_func);
  13217. cp_desc.threadGroupSizeIsMultipleOfThreadExecutionWidth = true;
  13218. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  13219. const sg_shader_stage stage = shd->cmn.storage_buffers[i].stage;
  13220. SOKOL_ASSERT((stage != SG_SHADERSTAGE_VERTEX) && (stage != SG_SHADERSTAGE_FRAGMENT));
  13221. if ((stage == SG_SHADERSTAGE_COMPUTE) && shd->cmn.storage_buffers[i].readonly) {
  13222. const NSUInteger mtl_slot = shd->mtl.sbuf_buffer_n[i];
  13223. cp_desc.buffers[mtl_slot].mutability = MTLMutabilityImmutable;
  13224. }
  13225. }
  13226. #if defined(SOKOL_DEBUG)
  13227. if (desc->label) {
  13228. cp_desc.label = [NSString stringWithFormat:@"%s", desc->label];
  13229. }
  13230. #endif
  13231. id<MTLComputePipelineState> mtl_cps = [_sg.mtl.device
  13232. newComputePipelineStateWithDescriptor:cp_desc
  13233. options:MTLPipelineOptionNone
  13234. reflection:nil
  13235. error:&err];
  13236. _SG_OBJC_RELEASE(cp_desc);
  13237. if (nil == mtl_cps) {
  13238. SOKOL_ASSERT(err);
  13239. _SG_ERROR(METAL_CREATE_CPS_FAILED);
  13240. _SG_LOGMSG(METAL_CREATE_CPS_OUTPUT, [err.localizedDescription UTF8String]);
  13241. return SG_RESOURCESTATE_FAILED;
  13242. }
  13243. pip->mtl.cps = _sg_mtl_add_resource(mtl_cps);
  13244. _SG_OBJC_RELEASE(mtl_cps);
  13245. pip->mtl.threads_per_threadgroup = shd->mtl.threads_per_threadgroup;
  13246. } else {
  13247. sg_primitive_type prim_type = desc->primitive_type;
  13248. pip->mtl.prim_type = _sg_mtl_primitive_type(prim_type);
  13249. pip->mtl.index_size = _sg_mtl_index_size(pip->cmn.index_type);
  13250. if (SG_INDEXTYPE_NONE != pip->cmn.index_type) {
  13251. pip->mtl.index_type = _sg_mtl_index_type(pip->cmn.index_type);
  13252. }
  13253. pip->mtl.cull_mode = _sg_mtl_cull_mode(desc->cull_mode);
  13254. pip->mtl.winding = _sg_mtl_winding(desc->face_winding);
  13255. pip->mtl.stencil_ref = desc->stencil.ref;
  13256. // create vertex-descriptor
  13257. MTLVertexDescriptor* vtx_desc = [MTLVertexDescriptor vertexDescriptor];
  13258. for (NSUInteger attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  13259. const sg_vertex_attr_state* a_state = &desc->layout.attrs[attr_index];
  13260. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  13261. break;
  13262. }
  13263. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  13264. SOKOL_ASSERT(pip->cmn.vertex_buffer_layout_active[a_state->buffer_index]);
  13265. vtx_desc.attributes[attr_index].format = _sg_mtl_vertex_format(a_state->format);
  13266. vtx_desc.attributes[attr_index].offset = (NSUInteger)a_state->offset;
  13267. vtx_desc.attributes[attr_index].bufferIndex = _sg_mtl_vertexbuffer_bindslot((size_t)a_state->buffer_index);
  13268. }
  13269. for (NSUInteger layout_index = 0; layout_index < SG_MAX_VERTEXBUFFER_BINDSLOTS; layout_index++) {
  13270. if (pip->cmn.vertex_buffer_layout_active[layout_index]) {
  13271. const sg_vertex_buffer_layout_state* l_state = &desc->layout.buffers[layout_index];
  13272. const NSUInteger mtl_vb_slot = _sg_mtl_vertexbuffer_bindslot(layout_index);
  13273. SOKOL_ASSERT(l_state->stride > 0);
  13274. vtx_desc.layouts[mtl_vb_slot].stride = (NSUInteger)l_state->stride;
  13275. vtx_desc.layouts[mtl_vb_slot].stepFunction = _sg_mtl_step_function(l_state->step_func);
  13276. vtx_desc.layouts[mtl_vb_slot].stepRate = (NSUInteger)l_state->step_rate;
  13277. if (SG_VERTEXSTEP_PER_INSTANCE == l_state->step_func) {
  13278. // NOTE: not actually used in _sg_mtl_draw()
  13279. pip->cmn.use_instanced_draw = true;
  13280. }
  13281. }
  13282. }
  13283. // render-pipeline descriptor
  13284. MTLRenderPipelineDescriptor* rp_desc = [[MTLRenderPipelineDescriptor alloc] init];
  13285. rp_desc.vertexDescriptor = vtx_desc;
  13286. SOKOL_ASSERT(shd->mtl.vertex_func.mtl_func != _SG_MTL_INVALID_SLOT_INDEX);
  13287. rp_desc.vertexFunction = _sg_mtl_id(shd->mtl.vertex_func.mtl_func);
  13288. SOKOL_ASSERT(shd->mtl.fragment_func.mtl_func != _SG_MTL_INVALID_SLOT_INDEX);
  13289. rp_desc.fragmentFunction = _sg_mtl_id(shd->mtl.fragment_func.mtl_func);
  13290. rp_desc.rasterSampleCount = (NSUInteger)desc->sample_count;
  13291. rp_desc.alphaToCoverageEnabled = desc->alpha_to_coverage_enabled;
  13292. rp_desc.alphaToOneEnabled = NO;
  13293. rp_desc.rasterizationEnabled = YES;
  13294. rp_desc.depthAttachmentPixelFormat = _sg_mtl_pixel_format(desc->depth.pixel_format);
  13295. if (desc->depth.pixel_format == SG_PIXELFORMAT_DEPTH_STENCIL) {
  13296. rp_desc.stencilAttachmentPixelFormat = _sg_mtl_pixel_format(desc->depth.pixel_format);
  13297. }
  13298. for (NSUInteger i = 0; i < (NSUInteger)desc->color_count; i++) {
  13299. SOKOL_ASSERT(i < SG_MAX_COLOR_ATTACHMENTS);
  13300. const sg_color_target_state* cs = &desc->colors[i];
  13301. rp_desc.colorAttachments[i].pixelFormat = _sg_mtl_pixel_format(cs->pixel_format);
  13302. rp_desc.colorAttachments[i].writeMask = _sg_mtl_color_write_mask(cs->write_mask);
  13303. rp_desc.colorAttachments[i].blendingEnabled = cs->blend.enabled;
  13304. rp_desc.colorAttachments[i].alphaBlendOperation = _sg_mtl_blend_op(cs->blend.op_alpha);
  13305. rp_desc.colorAttachments[i].rgbBlendOperation = _sg_mtl_blend_op(cs->blend.op_rgb);
  13306. rp_desc.colorAttachments[i].destinationAlphaBlendFactor = _sg_mtl_blend_factor(cs->blend.dst_factor_alpha);
  13307. rp_desc.colorAttachments[i].destinationRGBBlendFactor = _sg_mtl_blend_factor(cs->blend.dst_factor_rgb);
  13308. rp_desc.colorAttachments[i].sourceAlphaBlendFactor = _sg_mtl_blend_factor(cs->blend.src_factor_alpha);
  13309. rp_desc.colorAttachments[i].sourceRGBBlendFactor = _sg_mtl_blend_factor(cs->blend.src_factor_rgb);
  13310. }
  13311. // set buffer mutability for all read-only buffers (vertex buffers and read-only storage buffers)
  13312. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  13313. if (pip->cmn.vertex_buffer_layout_active[i]) {
  13314. const NSUInteger mtl_slot = _sg_mtl_vertexbuffer_bindslot(i);
  13315. rp_desc.vertexBuffers[mtl_slot].mutability = MTLMutabilityImmutable;
  13316. }
  13317. }
  13318. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  13319. const NSUInteger mtl_slot = shd->mtl.sbuf_buffer_n[i];
  13320. const sg_shader_stage stage = shd->cmn.storage_buffers[i].stage;
  13321. SOKOL_ASSERT(stage != SG_SHADERSTAGE_COMPUTE);
  13322. if (stage == SG_SHADERSTAGE_VERTEX) {
  13323. SOKOL_ASSERT(shd->cmn.storage_buffers[i].readonly);
  13324. rp_desc.vertexBuffers[mtl_slot].mutability = MTLMutabilityImmutable;
  13325. } else if (stage == SG_SHADERSTAGE_FRAGMENT) {
  13326. SOKOL_ASSERT(shd->cmn.storage_buffers[i].readonly);
  13327. rp_desc.fragmentBuffers[mtl_slot].mutability = MTLMutabilityImmutable;
  13328. }
  13329. }
  13330. #if defined(SOKOL_DEBUG)
  13331. if (desc->label) {
  13332. rp_desc.label = [NSString stringWithFormat:@"%s", desc->label];
  13333. }
  13334. #endif
  13335. NSError* err = NULL;
  13336. id<MTLRenderPipelineState> mtl_rps = [_sg.mtl.device newRenderPipelineStateWithDescriptor:rp_desc error:&err];
  13337. _SG_OBJC_RELEASE(rp_desc);
  13338. if (nil == mtl_rps) {
  13339. SOKOL_ASSERT(err);
  13340. _SG_ERROR(METAL_CREATE_RPS_FAILED);
  13341. _SG_LOGMSG(METAL_CREATE_RPS_OUTPUT, [err.localizedDescription UTF8String]);
  13342. return SG_RESOURCESTATE_FAILED;
  13343. }
  13344. pip->mtl.rps = _sg_mtl_add_resource(mtl_rps);
  13345. _SG_OBJC_RELEASE(mtl_rps);
  13346. // depth-stencil-state
  13347. MTLDepthStencilDescriptor* ds_desc = [[MTLDepthStencilDescriptor alloc] init];
  13348. ds_desc.depthCompareFunction = _sg_mtl_compare_func(desc->depth.compare);
  13349. ds_desc.depthWriteEnabled = desc->depth.write_enabled;
  13350. if (desc->stencil.enabled) {
  13351. const sg_stencil_face_state* sb = &desc->stencil.back;
  13352. ds_desc.backFaceStencil = [[MTLStencilDescriptor alloc] init];
  13353. ds_desc.backFaceStencil.stencilFailureOperation = _sg_mtl_stencil_op(sb->fail_op);
  13354. ds_desc.backFaceStencil.depthFailureOperation = _sg_mtl_stencil_op(sb->depth_fail_op);
  13355. ds_desc.backFaceStencil.depthStencilPassOperation = _sg_mtl_stencil_op(sb->pass_op);
  13356. ds_desc.backFaceStencil.stencilCompareFunction = _sg_mtl_compare_func(sb->compare);
  13357. ds_desc.backFaceStencil.readMask = desc->stencil.read_mask;
  13358. ds_desc.backFaceStencil.writeMask = desc->stencil.write_mask;
  13359. const sg_stencil_face_state* sf = &desc->stencil.front;
  13360. ds_desc.frontFaceStencil = [[MTLStencilDescriptor alloc] init];
  13361. ds_desc.frontFaceStencil.stencilFailureOperation = _sg_mtl_stencil_op(sf->fail_op);
  13362. ds_desc.frontFaceStencil.depthFailureOperation = _sg_mtl_stencil_op(sf->depth_fail_op);
  13363. ds_desc.frontFaceStencil.depthStencilPassOperation = _sg_mtl_stencil_op(sf->pass_op);
  13364. ds_desc.frontFaceStencil.stencilCompareFunction = _sg_mtl_compare_func(sf->compare);
  13365. ds_desc.frontFaceStencil.readMask = desc->stencil.read_mask;
  13366. ds_desc.frontFaceStencil.writeMask = desc->stencil.write_mask;
  13367. }
  13368. #if defined(SOKOL_DEBUG)
  13369. if (desc->label) {
  13370. ds_desc.label = [NSString stringWithFormat:@"%s.dss", desc->label];
  13371. }
  13372. #endif
  13373. id<MTLDepthStencilState> mtl_dss = [_sg.mtl.device newDepthStencilStateWithDescriptor:ds_desc];
  13374. _SG_OBJC_RELEASE(ds_desc);
  13375. if (nil == mtl_dss) {
  13376. _SG_ERROR(METAL_CREATE_DSS_FAILED);
  13377. return SG_RESOURCESTATE_FAILED;
  13378. }
  13379. pip->mtl.dss = _sg_mtl_add_resource(mtl_dss);
  13380. _SG_OBJC_RELEASE(mtl_dss);
  13381. }
  13382. return SG_RESOURCESTATE_VALID;
  13383. }
  13384. _SOKOL_PRIVATE void _sg_mtl_discard_pipeline(_sg_pipeline_t* pip) {
  13385. SOKOL_ASSERT(pip);
  13386. // it's valid to call release resource with a 'null resource'
  13387. _sg_mtl_release_resource(_sg.frame_index, pip->mtl.cps);
  13388. _sg_mtl_release_resource(_sg.frame_index, pip->mtl.rps);
  13389. _sg_mtl_release_resource(_sg.frame_index, pip->mtl.dss);
  13390. }
  13391. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_attachments(_sg_attachments_t* atts, const sg_attachments_desc* desc) {
  13392. SOKOL_ASSERT(atts && desc);
  13393. _SOKOL_UNUSED(desc);
  13394. // create texture views for storage attachments
  13395. for (int i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  13396. const _sg_image_t* stg_img = _sg_image_ref_ptr_or_null(&atts->cmn.storages[i].image);
  13397. if (stg_img) {
  13398. id<MTLTexture> mtl_tex_view = [_sg_mtl_id(stg_img->mtl.tex[0])
  13399. newTextureViewWithPixelFormat: _sg_mtl_pixel_format(stg_img->cmn.pixel_format)
  13400. textureType: _sg_mtl_texture_type(stg_img->cmn.type, false)
  13401. levels: NSMakeRange((NSUInteger)atts->cmn.storages[i].mip_level, 1)
  13402. slices: NSMakeRange((NSUInteger)atts->cmn.storages[i].slice, 1)];
  13403. atts->mtl.storage_views[i] = _sg_mtl_add_resource(mtl_tex_view);
  13404. }
  13405. }
  13406. return SG_RESOURCESTATE_VALID;
  13407. }
  13408. _SOKOL_PRIVATE void _sg_mtl_discard_attachments(_sg_attachments_t* atts) {
  13409. SOKOL_ASSERT(atts);
  13410. _SOKOL_UNUSED(atts);
  13411. for (int i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  13412. // it's valid to call _sg_mtl_release_resource with a null handle
  13413. _sg_mtl_release_resource(_sg.frame_index, atts->mtl.storage_views[i]);
  13414. }
  13415. }
  13416. _SOKOL_PRIVATE void _sg_mtl_bind_uniform_buffers(void) {
  13417. // In the Metal backend, uniform buffer bindings happen once in sg_begin_pass() and
  13418. // remain valid for the entire pass. Only binding offsets will be updated
  13419. // in sg_apply_uniforms()
  13420. if (_sg.cur_pass.is_compute) {
  13421. SOKOL_ASSERT(nil != _sg.mtl.compute_cmd_encoder);
  13422. for (size_t slot = 0; slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS; slot++) {
  13423. [_sg.mtl.compute_cmd_encoder
  13424. setBuffer:_sg.mtl.uniform_buffers[_sg.mtl.cur_frame_rotate_index]
  13425. offset:0
  13426. atIndex:slot];
  13427. }
  13428. } else {
  13429. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13430. for (size_t slot = 0; slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS; slot++) {
  13431. [_sg.mtl.render_cmd_encoder
  13432. setVertexBuffer:_sg.mtl.uniform_buffers[_sg.mtl.cur_frame_rotate_index]
  13433. offset:0
  13434. atIndex:slot];
  13435. [_sg.mtl.render_cmd_encoder
  13436. setFragmentBuffer:_sg.mtl.uniform_buffers[_sg.mtl.cur_frame_rotate_index]
  13437. offset:0
  13438. atIndex:slot];
  13439. }
  13440. }
  13441. }
  13442. _SOKOL_PRIVATE void _sg_mtl_begin_compute_pass(const sg_pass* pass) {
  13443. SOKOL_ASSERT(pass); (void)pass;
  13444. SOKOL_ASSERT(nil != _sg.mtl.cmd_buffer);
  13445. SOKOL_ASSERT(nil == _sg.mtl.compute_cmd_encoder);
  13446. SOKOL_ASSERT(nil == _sg.mtl.render_cmd_encoder);
  13447. _sg.mtl.compute_cmd_encoder = [_sg.mtl.cmd_buffer computeCommandEncoder];
  13448. if (nil == _sg.mtl.compute_cmd_encoder) {
  13449. _sg.cur_pass.valid = false;
  13450. return;
  13451. }
  13452. #if defined(SOKOL_DEBUG)
  13453. if (pass->label) {
  13454. _sg.mtl.compute_cmd_encoder.label = [NSString stringWithUTF8String:pass->label];
  13455. }
  13456. #endif
  13457. }
  13458. _SOKOL_PRIVATE void _sg_mtl_begin_render_pass(const sg_pass* pass) {
  13459. SOKOL_ASSERT(pass);
  13460. SOKOL_ASSERT(nil != _sg.mtl.cmd_buffer);
  13461. SOKOL_ASSERT(nil == _sg.mtl.render_cmd_encoder);
  13462. SOKOL_ASSERT(nil == _sg.mtl.compute_cmd_encoder);
  13463. const sg_swapchain* swapchain = &pass->swapchain;
  13464. const sg_pass_action* action = &pass->action;
  13465. MTLRenderPassDescriptor* pass_desc = [MTLRenderPassDescriptor renderPassDescriptor];
  13466. SOKOL_ASSERT(pass_desc);
  13467. const _sg_attachments_t* atts = _sg_attachments_ref_ptr_or_null(&_sg.cur_pass.atts);
  13468. if (atts) {
  13469. // setup pass descriptor for offscreen rendering
  13470. for (NSUInteger i = 0; i < (NSUInteger)atts->cmn.num_colors; i++) {
  13471. const _sg_attachment_common_t* cmn_color_att = &atts->cmn.colors[i];
  13472. const _sg_image_t* color_att_img = _sg_image_ref_ptr(&cmn_color_att->image);
  13473. const _sg_attachment_common_t* cmn_resolve_att = &atts->cmn.resolves[i];
  13474. const _sg_image_t* resolve_att_img = _sg_image_ref_ptr_or_null(&cmn_resolve_att->image);
  13475. SOKOL_ASSERT(color_att_img->slot.state == SG_RESOURCESTATE_VALID);
  13476. SOKOL_ASSERT(color_att_img->mtl.tex[color_att_img->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  13477. pass_desc.colorAttachments[i].loadAction = _sg_mtl_load_action(action->colors[i].load_action);
  13478. pass_desc.colorAttachments[i].storeAction = _sg_mtl_store_action(action->colors[i].store_action, resolve_att_img != 0);
  13479. sg_color c = action->colors[i].clear_value;
  13480. pass_desc.colorAttachments[i].clearColor = MTLClearColorMake(c.r, c.g, c.b, c.a);
  13481. pass_desc.colorAttachments[i].texture = _sg_mtl_id(color_att_img->mtl.tex[color_att_img->cmn.active_slot]);
  13482. pass_desc.colorAttachments[i].level = (NSUInteger)cmn_color_att->mip_level;
  13483. switch (color_att_img->cmn.type) {
  13484. case SG_IMAGETYPE_CUBE:
  13485. case SG_IMAGETYPE_ARRAY:
  13486. pass_desc.colorAttachments[i].slice = (NSUInteger)cmn_color_att->slice;
  13487. break;
  13488. case SG_IMAGETYPE_3D:
  13489. pass_desc.colorAttachments[i].depthPlane = (NSUInteger)cmn_color_att->slice;
  13490. break;
  13491. default: break;
  13492. }
  13493. if (resolve_att_img) {
  13494. SOKOL_ASSERT(resolve_att_img->slot.state == SG_RESOURCESTATE_VALID);
  13495. SOKOL_ASSERT(resolve_att_img->mtl.tex[resolve_att_img->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  13496. pass_desc.colorAttachments[i].resolveTexture = _sg_mtl_id(resolve_att_img->mtl.tex[resolve_att_img->cmn.active_slot]);
  13497. pass_desc.colorAttachments[i].resolveLevel = (NSUInteger)cmn_resolve_att->mip_level;
  13498. switch (resolve_att_img->cmn.type) {
  13499. case SG_IMAGETYPE_CUBE:
  13500. case SG_IMAGETYPE_ARRAY:
  13501. pass_desc.colorAttachments[i].resolveSlice = (NSUInteger)cmn_resolve_att->slice;
  13502. break;
  13503. case SG_IMAGETYPE_3D:
  13504. pass_desc.colorAttachments[i].resolveDepthPlane = (NSUInteger)cmn_resolve_att->slice;
  13505. break;
  13506. default: break;
  13507. }
  13508. }
  13509. }
  13510. const _sg_image_t* ds_att_img = _sg_image_ref_ptr_or_null(&atts->cmn.depth_stencil.image);
  13511. if (0 != ds_att_img) {
  13512. SOKOL_ASSERT(ds_att_img->slot.state == SG_RESOURCESTATE_VALID);
  13513. SOKOL_ASSERT(ds_att_img->mtl.tex[ds_att_img->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  13514. pass_desc.depthAttachment.texture = _sg_mtl_id(ds_att_img->mtl.tex[ds_att_img->cmn.active_slot]);
  13515. pass_desc.depthAttachment.loadAction = _sg_mtl_load_action(action->depth.load_action);
  13516. pass_desc.depthAttachment.storeAction = _sg_mtl_store_action(action->depth.store_action, false);
  13517. pass_desc.depthAttachment.clearDepth = action->depth.clear_value;
  13518. const _sg_attachment_common_t* cmn_ds_att = &atts->cmn.depth_stencil;
  13519. switch (ds_att_img->cmn.type) {
  13520. case SG_IMAGETYPE_CUBE:
  13521. case SG_IMAGETYPE_ARRAY:
  13522. pass_desc.depthAttachment.slice = (NSUInteger)cmn_ds_att->slice;
  13523. break;
  13524. case SG_IMAGETYPE_3D:
  13525. pass_desc.depthAttachment.resolveDepthPlane = (NSUInteger)cmn_ds_att->slice;
  13526. break;
  13527. default: break;
  13528. }
  13529. if (_sg_is_depth_stencil_format(ds_att_img->cmn.pixel_format)) {
  13530. pass_desc.stencilAttachment.texture = _sg_mtl_id(ds_att_img->mtl.tex[ds_att_img->cmn.active_slot]);
  13531. pass_desc.stencilAttachment.loadAction = _sg_mtl_load_action(action->stencil.load_action);
  13532. pass_desc.stencilAttachment.storeAction = _sg_mtl_store_action(action->depth.store_action, false);
  13533. pass_desc.stencilAttachment.clearStencil = action->stencil.clear_value;
  13534. switch (ds_att_img->cmn.type) {
  13535. case SG_IMAGETYPE_CUBE:
  13536. case SG_IMAGETYPE_ARRAY:
  13537. pass_desc.stencilAttachment.slice = (NSUInteger)cmn_ds_att->slice;
  13538. break;
  13539. case SG_IMAGETYPE_3D:
  13540. pass_desc.stencilAttachment.resolveDepthPlane = (NSUInteger)cmn_ds_att->slice;
  13541. break;
  13542. default: break;
  13543. }
  13544. }
  13545. }
  13546. } else {
  13547. // setup pass descriptor for swapchain rendering
  13548. //
  13549. // NOTE: at least in macOS Sonoma this no longer seems to be the case, the
  13550. // current drawable is also valid in a minimized window
  13551. // ===
  13552. // an MTKView current_drawable will not be valid if window is minimized, don't do any rendering in this case
  13553. if (0 == swapchain->metal.current_drawable) {
  13554. _sg.cur_pass.valid = false;
  13555. return;
  13556. }
  13557. // pin the swapchain resources into memory so that they outlive their command buffer
  13558. // (this is necessary because the command buffer doesn't retain references)
  13559. int pass_desc_ref = _sg_mtl_add_resource(pass_desc);
  13560. _sg_mtl_release_resource(_sg.frame_index, pass_desc_ref);
  13561. _sg.mtl.cur_drawable = (__bridge id<CAMetalDrawable>) swapchain->metal.current_drawable;
  13562. if (swapchain->sample_count > 1) {
  13563. // multi-sampling: render into msaa texture, resolve into drawable texture
  13564. id<MTLTexture> msaa_tex = (__bridge id<MTLTexture>) swapchain->metal.msaa_color_texture;
  13565. SOKOL_ASSERT(msaa_tex != nil);
  13566. pass_desc.colorAttachments[0].texture = msaa_tex;
  13567. pass_desc.colorAttachments[0].resolveTexture = _sg.mtl.cur_drawable.texture;
  13568. pass_desc.colorAttachments[0].storeAction = MTLStoreActionMultisampleResolve;
  13569. } else {
  13570. // non-msaa: render into current_drawable
  13571. pass_desc.colorAttachments[0].texture = _sg.mtl.cur_drawable.texture;
  13572. pass_desc.colorAttachments[0].storeAction = MTLStoreActionStore;
  13573. }
  13574. pass_desc.colorAttachments[0].loadAction = _sg_mtl_load_action(action->colors[0].load_action);
  13575. const sg_color c = action->colors[0].clear_value;
  13576. pass_desc.colorAttachments[0].clearColor = MTLClearColorMake(c.r, c.g, c.b, c.a);
  13577. // optional depth-stencil texture
  13578. if (swapchain->metal.depth_stencil_texture) {
  13579. id<MTLTexture> ds_tex = (__bridge id<MTLTexture>) swapchain->metal.depth_stencil_texture;
  13580. SOKOL_ASSERT(ds_tex != nil);
  13581. pass_desc.depthAttachment.texture = ds_tex;
  13582. pass_desc.depthAttachment.storeAction = MTLStoreActionDontCare;
  13583. pass_desc.depthAttachment.loadAction = _sg_mtl_load_action(action->depth.load_action);
  13584. pass_desc.depthAttachment.clearDepth = action->depth.clear_value;
  13585. if (_sg_is_depth_stencil_format(swapchain->depth_format)) {
  13586. pass_desc.stencilAttachment.texture = ds_tex;
  13587. pass_desc.stencilAttachment.storeAction = MTLStoreActionDontCare;
  13588. pass_desc.stencilAttachment.loadAction = _sg_mtl_load_action(action->stencil.load_action);
  13589. pass_desc.stencilAttachment.clearStencil = action->stencil.clear_value;
  13590. }
  13591. }
  13592. }
  13593. // NOTE: at least in macOS Sonoma, the following is no longer the case, a valid
  13594. // render command encoder is also returned in a minimized window
  13595. // ===
  13596. // create a render command encoder, this might return nil if window is minimized
  13597. _sg.mtl.render_cmd_encoder = [_sg.mtl.cmd_buffer renderCommandEncoderWithDescriptor:pass_desc];
  13598. if (nil == _sg.mtl.render_cmd_encoder) {
  13599. _sg.cur_pass.valid = false;
  13600. return;
  13601. }
  13602. #if defined(SOKOL_DEBUG)
  13603. if (pass->label) {
  13604. _sg.mtl.render_cmd_encoder.label = [NSString stringWithUTF8String:pass->label];
  13605. }
  13606. #endif
  13607. }
  13608. _SOKOL_PRIVATE void _sg_mtl_begin_pass(const sg_pass* pass) {
  13609. SOKOL_ASSERT(pass);
  13610. SOKOL_ASSERT(_sg.mtl.cmd_queue);
  13611. SOKOL_ASSERT(nil == _sg.mtl.compute_cmd_encoder);
  13612. SOKOL_ASSERT(nil == _sg.mtl.render_cmd_encoder);
  13613. SOKOL_ASSERT(nil == _sg.mtl.cur_drawable);
  13614. _sg_mtl_clear_state_cache();
  13615. // if this is the first pass in the frame, create one command buffer and blit-cmd-encoder for the entire frame
  13616. if (nil == _sg.mtl.cmd_buffer) {
  13617. // block until the oldest frame in flight has finished
  13618. dispatch_semaphore_wait(_sg.mtl.sem, DISPATCH_TIME_FOREVER);
  13619. if (_sg.desc.mtl_use_command_buffer_with_retained_references) {
  13620. _sg.mtl.cmd_buffer = [_sg.mtl.cmd_queue commandBuffer];
  13621. } else {
  13622. _sg.mtl.cmd_buffer = [_sg.mtl.cmd_queue commandBufferWithUnretainedReferences];
  13623. }
  13624. [_sg.mtl.cmd_buffer enqueue];
  13625. [_sg.mtl.cmd_buffer addCompletedHandler:^(id<MTLCommandBuffer> cmd_buf) {
  13626. // NOTE: this code is called on a different thread!
  13627. _SOKOL_UNUSED(cmd_buf);
  13628. dispatch_semaphore_signal(_sg.mtl.sem);
  13629. }];
  13630. }
  13631. // if this is first pass in frame, get uniform buffer base pointer
  13632. if (0 == _sg.mtl.cur_ub_base_ptr) {
  13633. _sg.mtl.cur_ub_base_ptr = (uint8_t*)[_sg.mtl.uniform_buffers[_sg.mtl.cur_frame_rotate_index] contents];
  13634. }
  13635. if (pass->compute) {
  13636. _sg_mtl_begin_compute_pass(pass);
  13637. } else {
  13638. _sg_mtl_begin_render_pass(pass);
  13639. }
  13640. // bind uniform buffers, those bindings remain valid for the entire pass
  13641. if (_sg.cur_pass.valid) {
  13642. _sg_mtl_bind_uniform_buffers();
  13643. }
  13644. }
  13645. _SOKOL_PRIVATE void _sg_mtl_end_pass(void) {
  13646. if (nil != _sg.mtl.render_cmd_encoder) {
  13647. [_sg.mtl.render_cmd_encoder endEncoding];
  13648. // NOTE: MTLRenderCommandEncoder is autoreleased
  13649. _sg.mtl.render_cmd_encoder = nil;
  13650. }
  13651. if (nil != _sg.mtl.compute_cmd_encoder) {
  13652. [_sg.mtl.compute_cmd_encoder endEncoding];
  13653. // NOTE: MTLComputeCommandEncoder is autoreleased
  13654. _sg.mtl.compute_cmd_encoder = nil;
  13655. // synchronize any managed resources written by the GPU
  13656. // NOTE: storage attachment images are currently not managed and are not eligible for syncing
  13657. #if defined(_SG_TARGET_MACOS)
  13658. if (_sg_mtl_resource_options_storage_mode_managed_or_shared() == MTLResourceStorageModeManaged) {
  13659. const bool needs_sync = _sg.compute.readwrite_sbufs.cur > 0;
  13660. if (needs_sync) {
  13661. id<MTLBlitCommandEncoder> blit_cmd_encoder = [_sg.mtl.cmd_buffer blitCommandEncoder];
  13662. for (uint32_t i = 0; i < _sg.compute.readwrite_sbufs.cur; i++) {
  13663. _sg_buffer_t* sbuf = _sg_lookup_buffer(_sg.compute.readwrite_sbufs.items[i]);
  13664. if (sbuf) {
  13665. [blit_cmd_encoder synchronizeResource:_sg_mtl_id(sbuf->mtl.buf[sbuf->cmn.active_slot])];
  13666. }
  13667. }
  13668. [blit_cmd_encoder endEncoding];
  13669. }
  13670. }
  13671. #endif
  13672. }
  13673. // if this is a swapchain pass, present the drawable
  13674. if (nil != _sg.mtl.cur_drawable) {
  13675. [_sg.mtl.cmd_buffer presentDrawable:_sg.mtl.cur_drawable];
  13676. _sg.mtl.cur_drawable = nil;
  13677. }
  13678. }
  13679. _SOKOL_PRIVATE void _sg_mtl_commit(void) {
  13680. SOKOL_ASSERT(nil == _sg.mtl.render_cmd_encoder);
  13681. SOKOL_ASSERT(nil == _sg.mtl.compute_cmd_encoder);
  13682. SOKOL_ASSERT(nil != _sg.mtl.cmd_buffer);
  13683. // commit the frame's command buffer
  13684. [_sg.mtl.cmd_buffer commit];
  13685. // garbage-collect resources pending for release
  13686. _sg_mtl_garbage_collect(_sg.frame_index);
  13687. // rotate uniform buffer slot
  13688. if (++_sg.mtl.cur_frame_rotate_index >= SG_NUM_INFLIGHT_FRAMES) {
  13689. _sg.mtl.cur_frame_rotate_index = 0;
  13690. }
  13691. _sg.mtl.cur_ub_offset = 0;
  13692. _sg.mtl.cur_ub_base_ptr = 0;
  13693. // NOTE: MTLCommandBuffer is autoreleased
  13694. _sg.mtl.cmd_buffer = nil;
  13695. }
  13696. _SOKOL_PRIVATE void _sg_mtl_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  13697. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13698. SOKOL_ASSERT(_sg.cur_pass.height > 0);
  13699. MTLViewport vp;
  13700. vp.originX = (double) x;
  13701. vp.originY = (double) (origin_top_left ? y : (_sg.cur_pass.height - (y + h)));
  13702. vp.width = (double) w;
  13703. vp.height = (double) h;
  13704. vp.znear = 0.0;
  13705. vp.zfar = 1.0;
  13706. [_sg.mtl.render_cmd_encoder setViewport:vp];
  13707. }
  13708. _SOKOL_PRIVATE void _sg_mtl_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  13709. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13710. SOKOL_ASSERT(_sg.cur_pass.width > 0);
  13711. SOKOL_ASSERT(_sg.cur_pass.height > 0);
  13712. // clip against framebuffer rect
  13713. const _sg_recti_t clip = _sg_clipi(x, y, w, h, _sg.cur_pass.width, _sg.cur_pass.height);
  13714. MTLScissorRect r;
  13715. r.x = (NSUInteger)clip.x;
  13716. r.y = (NSUInteger) (origin_top_left ? clip.y : (_sg.cur_pass.height - (clip.y + clip.h)));
  13717. r.width = (NSUInteger)clip.w;
  13718. r.height = (NSUInteger)clip.h;
  13719. [_sg.mtl.render_cmd_encoder setScissorRect:r];
  13720. }
  13721. _SOKOL_PRIVATE void _sg_mtl_apply_pipeline(_sg_pipeline_t* pip) {
  13722. SOKOL_ASSERT(pip);
  13723. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_pip, &pip->slot)) {
  13724. _sg.mtl.state_cache.cur_pip = _sg_sref(&pip->slot);
  13725. if (pip->cmn.is_compute) {
  13726. SOKOL_ASSERT(_sg.cur_pass.is_compute);
  13727. SOKOL_ASSERT(nil != _sg.mtl.compute_cmd_encoder);
  13728. SOKOL_ASSERT(pip->mtl.cps != _SG_MTL_INVALID_SLOT_INDEX);
  13729. [_sg.mtl.compute_cmd_encoder setComputePipelineState:_sg_mtl_id(pip->mtl.cps)];
  13730. // apply storage image bindings for writing
  13731. const _sg_attachments_t* atts = _sg_attachments_ref_ptr_or_null(&_sg.cur_pass.atts);
  13732. if (atts) {
  13733. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  13734. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  13735. const sg_shader_stage stage = shd->cmn.storage_images[i].stage;
  13736. if (stage != SG_SHADERSTAGE_COMPUTE) {
  13737. continue;
  13738. }
  13739. const NSUInteger mtl_slot = shd->mtl.simg_texture_n[i];
  13740. SOKOL_ASSERT(mtl_slot < _SG_MTL_MAX_STAGE_TEXTURE_BINDINGS);
  13741. const uint64_t cache_key = ((uint64_t)atts->cmn.storages[i].image.sref.id) << 32;
  13742. SOKOL_ASSERT(cache_key != 0);
  13743. if (_sg.mtl.state_cache.cur_cs_image_ids[mtl_slot] != cache_key) {
  13744. _sg.mtl.state_cache.cur_cs_image_ids[mtl_slot] = cache_key;
  13745. [_sg.mtl.compute_cmd_encoder setTexture:_sg_mtl_id(atts->mtl.storage_views[i]) atIndex:mtl_slot];
  13746. _sg_stats_add(metal.bindings.num_set_compute_texture, 1);
  13747. }
  13748. }
  13749. }
  13750. } else {
  13751. SOKOL_ASSERT(!_sg.cur_pass.is_compute);
  13752. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13753. sg_color c = pip->cmn.blend_color;
  13754. [_sg.mtl.render_cmd_encoder setBlendColorRed:c.r green:c.g blue:c.b alpha:c.a];
  13755. _sg_stats_add(metal.pipeline.num_set_blend_color, 1);
  13756. [_sg.mtl.render_cmd_encoder setCullMode:pip->mtl.cull_mode];
  13757. _sg_stats_add(metal.pipeline.num_set_cull_mode, 1);
  13758. [_sg.mtl.render_cmd_encoder setFrontFacingWinding:pip->mtl.winding];
  13759. _sg_stats_add(metal.pipeline.num_set_front_facing_winding, 1);
  13760. [_sg.mtl.render_cmd_encoder setStencilReferenceValue:pip->mtl.stencil_ref];
  13761. _sg_stats_add(metal.pipeline.num_set_stencil_reference_value, 1);
  13762. [_sg.mtl.render_cmd_encoder setDepthBias:pip->cmn.depth.bias slopeScale:pip->cmn.depth.bias_slope_scale clamp:pip->cmn.depth.bias_clamp];
  13763. _sg_stats_add(metal.pipeline.num_set_depth_bias, 1);
  13764. SOKOL_ASSERT(pip->mtl.rps != _SG_MTL_INVALID_SLOT_INDEX);
  13765. [_sg.mtl.render_cmd_encoder setRenderPipelineState:_sg_mtl_id(pip->mtl.rps)];
  13766. _sg_stats_add(metal.pipeline.num_set_render_pipeline_state, 1);
  13767. SOKOL_ASSERT(pip->mtl.dss != _SG_MTL_INVALID_SLOT_INDEX);
  13768. [_sg.mtl.render_cmd_encoder setDepthStencilState:_sg_mtl_id(pip->mtl.dss)];
  13769. _sg_stats_add(metal.pipeline.num_set_depth_stencil_state, 1);
  13770. }
  13771. }
  13772. }
  13773. _SOKOL_PRIVATE bool _sg_mtl_apply_bindings(_sg_bindings_ptrs_t* bnd) {
  13774. SOKOL_ASSERT(bnd);
  13775. SOKOL_ASSERT(bnd->pip);
  13776. const _sg_shader_t* shd = _sg_shader_ref_ptr(&bnd->pip->cmn.shader);
  13777. // don't set vertex- and index-buffers in compute passes
  13778. if (!_sg.cur_pass.is_compute) {
  13779. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13780. // store index buffer binding, this will be needed later in sg_draw()
  13781. _sg.mtl.state_cache.cur_ibuf = _sg_buffer_ref(bnd->ib);
  13782. if (bnd->ib) {
  13783. SOKOL_ASSERT(bnd->pip->cmn.index_type != SG_INDEXTYPE_NONE);
  13784. } else {
  13785. SOKOL_ASSERT(bnd->pip->cmn.index_type == SG_INDEXTYPE_NONE);
  13786. }
  13787. _sg.mtl.state_cache.cur_ibuf_offset = bnd->ib_offset;
  13788. // apply vertex buffers
  13789. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  13790. const _sg_buffer_t* vb = bnd->vbs[i];
  13791. if (vb == 0) {
  13792. continue;
  13793. }
  13794. const NSUInteger mtl_slot = _sg_mtl_vertexbuffer_bindslot(i);
  13795. SOKOL_ASSERT(mtl_slot < _SG_MTL_MAX_STAGE_BUFFER_BINDINGS);
  13796. const int vb_offset = bnd->vb_offsets[i];
  13797. const bool ref_eql = _sg_sref_eql(&_sg.mtl.state_cache.cur_vsbufs[mtl_slot], &vb->slot);
  13798. if (!ref_eql || (_sg.mtl.state_cache.cur_vs_buffer_offsets[mtl_slot] != vb_offset)) {
  13799. _sg.mtl.state_cache.cur_vs_buffer_offsets[mtl_slot] = vb_offset;
  13800. if (!ref_eql) {
  13801. // vertex buffer has changed
  13802. _sg.mtl.state_cache.cur_vsbufs[mtl_slot] = _sg_sref(&vb->slot);
  13803. SOKOL_ASSERT(vb->mtl.buf[vb->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  13804. [_sg.mtl.render_cmd_encoder setVertexBuffer:_sg_mtl_id(vb->mtl.buf[vb->cmn.active_slot])
  13805. offset:(NSUInteger)vb_offset
  13806. atIndex:mtl_slot];
  13807. } else {
  13808. // only vertex buffer offset has changed
  13809. [_sg.mtl.render_cmd_encoder setVertexBufferOffset:(NSUInteger)vb_offset atIndex:mtl_slot];
  13810. }
  13811. _sg_stats_add(metal.bindings.num_set_vertex_buffer, 1);
  13812. }
  13813. }
  13814. }
  13815. // apply image bindings
  13816. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  13817. const _sg_image_t* img = bnd->imgs[i];
  13818. if (img == 0) {
  13819. continue;
  13820. }
  13821. SOKOL_ASSERT(img->mtl.tex[img->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  13822. const sg_shader_stage stage = shd->cmn.images[i].stage;
  13823. SOKOL_ASSERT((stage == SG_SHADERSTAGE_VERTEX) || (stage == SG_SHADERSTAGE_FRAGMENT) || (stage == SG_SHADERSTAGE_COMPUTE));
  13824. const NSUInteger mtl_slot = shd->mtl.img_texture_n[i];
  13825. SOKOL_ASSERT(mtl_slot < _SG_MTL_MAX_STAGE_TEXTURE_BINDINGS);
  13826. if (stage == SG_SHADERSTAGE_VERTEX) {
  13827. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13828. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_vsimgs[mtl_slot], &img->slot)) {
  13829. _sg.mtl.state_cache.cur_vsimgs[mtl_slot] = _sg_sref(&img->slot);
  13830. [_sg.mtl.render_cmd_encoder setVertexTexture:_sg_mtl_id(img->mtl.tex[img->cmn.active_slot]) atIndex:mtl_slot];
  13831. _sg_stats_add(metal.bindings.num_set_vertex_texture, 1);
  13832. }
  13833. } else if (stage == SG_SHADERSTAGE_FRAGMENT) {
  13834. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13835. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_fsimgs[mtl_slot], &img->slot)) {
  13836. _sg.mtl.state_cache.cur_fsimgs[mtl_slot] = _sg_sref(&img->slot);
  13837. [_sg.mtl.render_cmd_encoder setFragmentTexture:_sg_mtl_id(img->mtl.tex[img->cmn.active_slot]) atIndex:mtl_slot];
  13838. _sg_stats_add(metal.bindings.num_set_fragment_texture, 1);
  13839. }
  13840. } else if (stage == SG_SHADERSTAGE_COMPUTE) {
  13841. SOKOL_ASSERT(nil != _sg.mtl.compute_cmd_encoder);
  13842. if (_sg.mtl.state_cache.cur_cs_image_ids[mtl_slot] != img->slot.id) {
  13843. _sg.mtl.state_cache.cur_cs_image_ids[mtl_slot] = img->slot.id;
  13844. [_sg.mtl.compute_cmd_encoder setTexture:_sg_mtl_id(img->mtl.tex[img->cmn.active_slot]) atIndex:mtl_slot];
  13845. _sg_stats_add(metal.bindings.num_set_compute_texture, 1);
  13846. }
  13847. }
  13848. }
  13849. // apply sampler bindings
  13850. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  13851. const _sg_sampler_t* smp = bnd->smps[i];
  13852. if (smp == 0) {
  13853. continue;
  13854. }
  13855. SOKOL_ASSERT(smp->mtl.sampler_state != _SG_MTL_INVALID_SLOT_INDEX);
  13856. const sg_shader_stage stage = shd->cmn.samplers[i].stage;
  13857. SOKOL_ASSERT((stage == SG_SHADERSTAGE_VERTEX) || (stage == SG_SHADERSTAGE_FRAGMENT) || (stage == SG_SHADERSTAGE_COMPUTE));
  13858. const NSUInteger mtl_slot = shd->mtl.smp_sampler_n[i];
  13859. SOKOL_ASSERT(mtl_slot < _SG_MTL_MAX_STAGE_SAMPLER_BINDINGS);
  13860. if (stage == SG_SHADERSTAGE_VERTEX) {
  13861. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13862. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_vssmps[mtl_slot], &smp->slot)) {
  13863. _sg.mtl.state_cache.cur_vssmps[mtl_slot] = _sg_sref(&smp->slot);
  13864. [_sg.mtl.render_cmd_encoder setVertexSamplerState:_sg_mtl_id(smp->mtl.sampler_state) atIndex:mtl_slot];
  13865. _sg_stats_add(metal.bindings.num_set_vertex_sampler_state, 1);
  13866. }
  13867. } else if (stage == SG_SHADERSTAGE_FRAGMENT) {
  13868. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13869. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_fssmps[mtl_slot], &smp->slot)) {
  13870. _sg.mtl.state_cache.cur_fssmps[mtl_slot] = _sg_sref(&smp->slot);
  13871. [_sg.mtl.render_cmd_encoder setFragmentSamplerState:_sg_mtl_id(smp->mtl.sampler_state) atIndex:mtl_slot];
  13872. _sg_stats_add(metal.bindings.num_set_fragment_sampler_state, 1);
  13873. }
  13874. } else if (stage == SG_SHADERSTAGE_COMPUTE) {
  13875. SOKOL_ASSERT(nil != _sg.mtl.compute_cmd_encoder);
  13876. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_cssmps[mtl_slot], &smp->slot)) {
  13877. _sg.mtl.state_cache.cur_cssmps[mtl_slot] = _sg_sref(&smp->slot);
  13878. [_sg.mtl.compute_cmd_encoder setSamplerState:_sg_mtl_id(smp->mtl.sampler_state) atIndex:mtl_slot];
  13879. _sg_stats_add(metal.bindings.num_set_compute_sampler_state, 1);
  13880. }
  13881. }
  13882. }
  13883. // apply storage buffer bindings
  13884. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  13885. const _sg_buffer_t* sbuf = bnd->sbufs[i];
  13886. if (sbuf == 0) {
  13887. continue;
  13888. }
  13889. SOKOL_ASSERT(sbuf->mtl.buf[sbuf->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  13890. const sg_shader_stage stage = shd->cmn.storage_buffers[i].stage;
  13891. SOKOL_ASSERT((stage == SG_SHADERSTAGE_VERTEX) || (stage == SG_SHADERSTAGE_FRAGMENT) || (stage == SG_SHADERSTAGE_COMPUTE));
  13892. const NSUInteger mtl_slot = shd->mtl.sbuf_buffer_n[i];
  13893. SOKOL_ASSERT(mtl_slot < _SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS);
  13894. if (stage == SG_SHADERSTAGE_VERTEX) {
  13895. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13896. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_vsbufs[mtl_slot], &sbuf->slot)) {
  13897. _sg.mtl.state_cache.cur_vsbufs[mtl_slot] = _sg_sref(&sbuf->slot);
  13898. [_sg.mtl.render_cmd_encoder setVertexBuffer:_sg_mtl_id(sbuf->mtl.buf[sbuf->cmn.active_slot]) offset:0 atIndex:mtl_slot];
  13899. _sg_stats_add(metal.bindings.num_set_vertex_buffer, 1);
  13900. }
  13901. } else if (stage == SG_SHADERSTAGE_FRAGMENT) {
  13902. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13903. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_fsbufs[mtl_slot], &sbuf->slot)) {
  13904. _sg.mtl.state_cache.cur_fsbufs[mtl_slot] = _sg_sref(&sbuf->slot);
  13905. [_sg.mtl.render_cmd_encoder setFragmentBuffer:_sg_mtl_id(sbuf->mtl.buf[sbuf->cmn.active_slot]) offset:0 atIndex:mtl_slot];
  13906. _sg_stats_add(metal.bindings.num_set_fragment_buffer, 1);
  13907. }
  13908. } else if (stage == SG_SHADERSTAGE_COMPUTE) {
  13909. SOKOL_ASSERT(nil != _sg.mtl.compute_cmd_encoder);
  13910. if (!_sg_sref_eql(&_sg.mtl.state_cache.cur_csbufs[mtl_slot], &sbuf->slot)) {
  13911. _sg.mtl.state_cache.cur_csbufs[mtl_slot] = _sg_sref(&sbuf->slot);
  13912. [_sg.mtl.compute_cmd_encoder setBuffer:_sg_mtl_id(sbuf->mtl.buf[sbuf->cmn.active_slot]) offset:0 atIndex:mtl_slot];
  13913. _sg_stats_add(metal.bindings.num_set_compute_buffer, 1);
  13914. }
  13915. }
  13916. }
  13917. return true;
  13918. }
  13919. _SOKOL_PRIVATE void _sg_mtl_apply_uniforms(int ub_slot, const sg_range* data) {
  13920. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  13921. SOKOL_ASSERT(((size_t)_sg.mtl.cur_ub_offset + data->size) <= (size_t)_sg.mtl.ub_size);
  13922. SOKOL_ASSERT((_sg.mtl.cur_ub_offset & (_SG_MTL_UB_ALIGN-1)) == 0);
  13923. const _sg_pipeline_t* pip = _sg_pipeline_ref_ptr(&_sg.cur_pip);
  13924. SOKOL_ASSERT(pip);
  13925. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  13926. SOKOL_ASSERT(data->size == shd->cmn.uniform_blocks[ub_slot].size);
  13927. const sg_shader_stage stage = shd->cmn.uniform_blocks[ub_slot].stage;
  13928. const NSUInteger mtl_slot = shd->mtl.ub_buffer_n[ub_slot];
  13929. // copy to global uniform buffer, record offset into cmd encoder, and advance offset
  13930. uint8_t* dst = &_sg.mtl.cur_ub_base_ptr[_sg.mtl.cur_ub_offset];
  13931. memcpy(dst, data->ptr, data->size);
  13932. if (stage == SG_SHADERSTAGE_VERTEX) {
  13933. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13934. [_sg.mtl.render_cmd_encoder setVertexBufferOffset:(NSUInteger)_sg.mtl.cur_ub_offset atIndex:mtl_slot];
  13935. _sg_stats_add(metal.uniforms.num_set_vertex_buffer_offset, 1);
  13936. } else if (stage == SG_SHADERSTAGE_FRAGMENT) {
  13937. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13938. [_sg.mtl.render_cmd_encoder setFragmentBufferOffset:(NSUInteger)_sg.mtl.cur_ub_offset atIndex:mtl_slot];
  13939. _sg_stats_add(metal.uniforms.num_set_fragment_buffer_offset, 1);
  13940. } else if (stage == SG_SHADERSTAGE_COMPUTE) {
  13941. SOKOL_ASSERT(nil != _sg.mtl.compute_cmd_encoder);
  13942. [_sg.mtl.compute_cmd_encoder setBufferOffset:(NSUInteger)_sg.mtl.cur_ub_offset atIndex:mtl_slot];
  13943. _sg_stats_add(metal.uniforms.num_set_compute_buffer_offset, 1);
  13944. } else {
  13945. SOKOL_UNREACHABLE;
  13946. }
  13947. _sg.mtl.cur_ub_offset = _sg_roundup(_sg.mtl.cur_ub_offset + (int)data->size, _SG_MTL_UB_ALIGN);
  13948. }
  13949. _SOKOL_PRIVATE void _sg_mtl_draw(int base_element, int num_elements, int num_instances) {
  13950. SOKOL_ASSERT(nil != _sg.mtl.render_cmd_encoder);
  13951. const _sg_pipeline_t* pip = _sg_pipeline_ref_ptr(&_sg.cur_pip);
  13952. SOKOL_ASSERT(pip);
  13953. if (SG_INDEXTYPE_NONE != pip->cmn.index_type) {
  13954. // indexed rendering
  13955. const _sg_buffer_t* ib = _sg_buffer_ref_ptr(&_sg.mtl.state_cache.cur_ibuf);
  13956. SOKOL_ASSERT(ib && (ib->mtl.buf[ib->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX));
  13957. const NSUInteger index_buffer_offset = (NSUInteger) (_sg.mtl.state_cache.cur_ibuf_offset + base_element * pip->mtl.index_size);
  13958. [_sg.mtl.render_cmd_encoder drawIndexedPrimitives:pip->mtl.prim_type
  13959. indexCount:(NSUInteger)num_elements
  13960. indexType:pip->mtl.index_type
  13961. indexBuffer:_sg_mtl_id(ib->mtl.buf[ib->cmn.active_slot])
  13962. indexBufferOffset:index_buffer_offset
  13963. instanceCount:(NSUInteger)num_instances];
  13964. } else {
  13965. // non-indexed rendering
  13966. [_sg.mtl.render_cmd_encoder drawPrimitives:pip->mtl.prim_type
  13967. vertexStart:(NSUInteger)base_element
  13968. vertexCount:(NSUInteger)num_elements
  13969. instanceCount:(NSUInteger)num_instances];
  13970. }
  13971. }
  13972. _SOKOL_PRIVATE void _sg_mtl_dispatch(int num_groups_x, int num_groups_y, int num_groups_z) {
  13973. SOKOL_ASSERT(nil != _sg.mtl.compute_cmd_encoder);
  13974. const _sg_pipeline_t* pip = _sg_pipeline_ref_ptr(&_sg.cur_pip);
  13975. SOKOL_ASSERT(pip);
  13976. const MTLSize thread_groups = MTLSizeMake(
  13977. (NSUInteger)num_groups_x,
  13978. (NSUInteger)num_groups_y,
  13979. (NSUInteger)num_groups_z);
  13980. const MTLSize threads_per_threadgroup = pip->mtl.threads_per_threadgroup;
  13981. [_sg.mtl.compute_cmd_encoder dispatchThreadgroups:thread_groups threadsPerThreadgroup:threads_per_threadgroup];
  13982. }
  13983. _SOKOL_PRIVATE void _sg_mtl_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  13984. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  13985. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  13986. buf->cmn.active_slot = 0;
  13987. }
  13988. __unsafe_unretained id<MTLBuffer> mtl_buf = _sg_mtl_id(buf->mtl.buf[buf->cmn.active_slot]);
  13989. void* dst_ptr = [mtl_buf contents];
  13990. memcpy(dst_ptr, data->ptr, data->size);
  13991. #if defined(_SG_TARGET_MACOS)
  13992. if (_sg_mtl_resource_options_storage_mode_managed_or_shared() == MTLResourceStorageModeManaged) {
  13993. [mtl_buf didModifyRange:NSMakeRange(0, data->size)];
  13994. }
  13995. #endif
  13996. }
  13997. _SOKOL_PRIVATE void _sg_mtl_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  13998. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  13999. if (new_frame) {
  14000. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  14001. buf->cmn.active_slot = 0;
  14002. }
  14003. }
  14004. __unsafe_unretained id<MTLBuffer> mtl_buf = _sg_mtl_id(buf->mtl.buf[buf->cmn.active_slot]);
  14005. uint8_t* dst_ptr = (uint8_t*) [mtl_buf contents];
  14006. dst_ptr += buf->cmn.append_pos;
  14007. memcpy(dst_ptr, data->ptr, data->size);
  14008. #if defined(_SG_TARGET_MACOS)
  14009. if (_sg_mtl_resource_options_storage_mode_managed_or_shared() == MTLResourceStorageModeManaged) {
  14010. [mtl_buf didModifyRange:NSMakeRange((NSUInteger)buf->cmn.append_pos, (NSUInteger)data->size)];
  14011. }
  14012. #endif
  14013. }
  14014. _SOKOL_PRIVATE void _sg_mtl_update_image(_sg_image_t* img, const sg_image_data* data) {
  14015. SOKOL_ASSERT(img && data);
  14016. if (++img->cmn.active_slot >= img->cmn.num_slots) {
  14017. img->cmn.active_slot = 0;
  14018. }
  14019. __unsafe_unretained id<MTLTexture> mtl_tex = _sg_mtl_id(img->mtl.tex[img->cmn.active_slot]);
  14020. _sg_mtl_copy_image_data(img, mtl_tex, data);
  14021. }
  14022. _SOKOL_PRIVATE void _sg_mtl_push_debug_group(const char* name) {
  14023. SOKOL_ASSERT(name);
  14024. if (_sg.mtl.render_cmd_encoder) {
  14025. [_sg.mtl.render_cmd_encoder pushDebugGroup:[NSString stringWithUTF8String:name]];
  14026. } else if (_sg.mtl.compute_cmd_encoder) {
  14027. [_sg.mtl.compute_cmd_encoder pushDebugGroup:[NSString stringWithUTF8String:name]];
  14028. }
  14029. }
  14030. _SOKOL_PRIVATE void _sg_mtl_pop_debug_group(void) {
  14031. if (_sg.mtl.render_cmd_encoder) {
  14032. [_sg.mtl.render_cmd_encoder popDebugGroup];
  14033. } else if (_sg.mtl.compute_cmd_encoder) {
  14034. [_sg.mtl.compute_cmd_encoder popDebugGroup];
  14035. }
  14036. }
  14037. // ██ ██ ███████ ██████ ██████ ██████ ██ ██ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  14038. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  14039. // ██ █ ██ █████ ██████ ██ ███ ██████ ██ ██ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  14040. // ██ ███ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  14041. // ███ ███ ███████ ██████ ██████ ██ ██████ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  14042. //
  14043. // >>webgpu
  14044. // >>wgpu
  14045. #elif defined(SOKOL_WGPU)
  14046. #define WGPUSType_ShaderModuleWGSLDescriptor WGPUSType_ShaderSourceWGSL
  14047. _SOKOL_PRIVATE WGPUStringView _sg_wgpu_stringview(const char* str) {
  14048. WGPUStringView res;
  14049. if (str) {
  14050. res.data = str;
  14051. res.length = strlen(str);
  14052. } else {
  14053. res.data = 0;
  14054. res.length = 0;
  14055. }
  14056. return res;
  14057. }
  14058. _SOKOL_PRIVATE WGPUOptionalBool _sg_wgpu_optional_bool(bool b) {
  14059. return b ? WGPUOptionalBool_True : WGPUOptionalBool_False;
  14060. }
  14061. _SOKOL_PRIVATE WGPUBufferUsage _sg_wgpu_buffer_usage(const sg_buffer_usage* usg) {
  14062. int res = 0;
  14063. if (usg->vertex_buffer) {
  14064. res |= WGPUBufferUsage_Vertex;
  14065. }
  14066. if (usg->index_buffer) {
  14067. res |= WGPUBufferUsage_Index;
  14068. }
  14069. if (usg->storage_buffer) {
  14070. res |= WGPUBufferUsage_Storage;
  14071. }
  14072. if (!usg->immutable) {
  14073. res |= WGPUBufferUsage_CopyDst;
  14074. }
  14075. return (WGPUBufferUsage)res;
  14076. }
  14077. _SOKOL_PRIVATE WGPULoadOp _sg_wgpu_load_op(WGPUTextureView view, sg_load_action a) {
  14078. if (0 == view) {
  14079. return WGPULoadOp_Undefined;
  14080. } else switch (a) {
  14081. case SG_LOADACTION_CLEAR:
  14082. case SG_LOADACTION_DONTCARE:
  14083. return WGPULoadOp_Clear;
  14084. case SG_LOADACTION_LOAD:
  14085. return WGPULoadOp_Load;
  14086. default:
  14087. SOKOL_UNREACHABLE;
  14088. return WGPULoadOp_Force32;
  14089. }
  14090. }
  14091. _SOKOL_PRIVATE WGPUStoreOp _sg_wgpu_store_op(WGPUTextureView view, sg_store_action a) {
  14092. if (0 == view) {
  14093. return WGPUStoreOp_Undefined;
  14094. } else switch (a) {
  14095. case SG_STOREACTION_STORE:
  14096. return WGPUStoreOp_Store;
  14097. case SG_STOREACTION_DONTCARE:
  14098. return WGPUStoreOp_Discard;
  14099. default:
  14100. SOKOL_UNREACHABLE;
  14101. return WGPUStoreOp_Force32;
  14102. }
  14103. }
  14104. _SOKOL_PRIVATE WGPUTextureViewDimension _sg_wgpu_texture_view_dimension(sg_image_type t) {
  14105. switch (t) {
  14106. case SG_IMAGETYPE_2D: return WGPUTextureViewDimension_2D;
  14107. case SG_IMAGETYPE_CUBE: return WGPUTextureViewDimension_Cube;
  14108. case SG_IMAGETYPE_3D: return WGPUTextureViewDimension_3D;
  14109. case SG_IMAGETYPE_ARRAY: return WGPUTextureViewDimension_2DArray;
  14110. default: SOKOL_UNREACHABLE; return WGPUTextureViewDimension_Force32;
  14111. }
  14112. }
  14113. _SOKOL_PRIVATE WGPUTextureDimension _sg_wgpu_texture_dimension(sg_image_type t) {
  14114. if (SG_IMAGETYPE_3D == t) {
  14115. return WGPUTextureDimension_3D;
  14116. } else {
  14117. return WGPUTextureDimension_2D;
  14118. }
  14119. }
  14120. _SOKOL_PRIVATE WGPUTextureSampleType _sg_wgpu_texture_sample_type(sg_image_sample_type t, bool msaa) {
  14121. switch (t) {
  14122. case SG_IMAGESAMPLETYPE_FLOAT: return msaa ? WGPUTextureSampleType_UnfilterableFloat : WGPUTextureSampleType_Float;
  14123. case SG_IMAGESAMPLETYPE_DEPTH: return WGPUTextureSampleType_Depth;
  14124. case SG_IMAGESAMPLETYPE_SINT: return WGPUTextureSampleType_Sint;
  14125. case SG_IMAGESAMPLETYPE_UINT: return WGPUTextureSampleType_Uint;
  14126. case SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT: return WGPUTextureSampleType_UnfilterableFloat;
  14127. default: SOKOL_UNREACHABLE; return WGPUTextureSampleType_Force32;
  14128. }
  14129. }
  14130. _SOKOL_PRIVATE WGPUSamplerBindingType _sg_wgpu_sampler_binding_type(sg_sampler_type t) {
  14131. switch (t) {
  14132. case SG_SAMPLERTYPE_FILTERING: return WGPUSamplerBindingType_Filtering;
  14133. case SG_SAMPLERTYPE_COMPARISON: return WGPUSamplerBindingType_Comparison;
  14134. case SG_SAMPLERTYPE_NONFILTERING: return WGPUSamplerBindingType_NonFiltering;
  14135. default: SOKOL_UNREACHABLE; return WGPUSamplerBindingType_Force32;
  14136. }
  14137. }
  14138. _SOKOL_PRIVATE WGPUAddressMode _sg_wgpu_sampler_address_mode(sg_wrap m) {
  14139. switch (m) {
  14140. case SG_WRAP_REPEAT:
  14141. return WGPUAddressMode_Repeat;
  14142. case SG_WRAP_CLAMP_TO_EDGE:
  14143. case SG_WRAP_CLAMP_TO_BORDER:
  14144. return WGPUAddressMode_ClampToEdge;
  14145. case SG_WRAP_MIRRORED_REPEAT:
  14146. return WGPUAddressMode_MirrorRepeat;
  14147. default:
  14148. SOKOL_UNREACHABLE;
  14149. return WGPUAddressMode_Force32;
  14150. }
  14151. }
  14152. _SOKOL_PRIVATE WGPUFilterMode _sg_wgpu_sampler_minmag_filter(sg_filter f) {
  14153. switch (f) {
  14154. case SG_FILTER_NEAREST:
  14155. return WGPUFilterMode_Nearest;
  14156. case SG_FILTER_LINEAR:
  14157. return WGPUFilterMode_Linear;
  14158. default:
  14159. SOKOL_UNREACHABLE;
  14160. return WGPUFilterMode_Force32;
  14161. }
  14162. }
  14163. _SOKOL_PRIVATE WGPUMipmapFilterMode _sg_wgpu_sampler_mipmap_filter(sg_filter f) {
  14164. switch (f) {
  14165. case SG_FILTER_NEAREST:
  14166. return WGPUMipmapFilterMode_Nearest;
  14167. case SG_FILTER_LINEAR:
  14168. return WGPUMipmapFilterMode_Linear;
  14169. default:
  14170. SOKOL_UNREACHABLE;
  14171. return WGPUMipmapFilterMode_Force32;
  14172. }
  14173. }
  14174. _SOKOL_PRIVATE WGPUIndexFormat _sg_wgpu_indexformat(sg_index_type t) {
  14175. // NOTE: there's no WGPUIndexFormat_None
  14176. return (t == SG_INDEXTYPE_UINT16) ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Uint32;
  14177. }
  14178. _SOKOL_PRIVATE WGPUIndexFormat _sg_wgpu_stripindexformat(sg_primitive_type prim_type, sg_index_type idx_type) {
  14179. if (idx_type == SG_INDEXTYPE_NONE) {
  14180. return WGPUIndexFormat_Undefined;
  14181. } else if ((prim_type == SG_PRIMITIVETYPE_LINE_STRIP) || (prim_type == SG_PRIMITIVETYPE_TRIANGLE_STRIP)) {
  14182. return _sg_wgpu_indexformat(idx_type);
  14183. } else {
  14184. return WGPUIndexFormat_Undefined;
  14185. }
  14186. }
  14187. _SOKOL_PRIVATE WGPUVertexStepMode _sg_wgpu_stepmode(sg_vertex_step s) {
  14188. return (s == SG_VERTEXSTEP_PER_VERTEX) ? WGPUVertexStepMode_Vertex : WGPUVertexStepMode_Instance;
  14189. }
  14190. _SOKOL_PRIVATE WGPUVertexFormat _sg_wgpu_vertexformat(sg_vertex_format f) {
  14191. switch (f) {
  14192. case SG_VERTEXFORMAT_FLOAT: return WGPUVertexFormat_Float32;
  14193. case SG_VERTEXFORMAT_FLOAT2: return WGPUVertexFormat_Float32x2;
  14194. case SG_VERTEXFORMAT_FLOAT3: return WGPUVertexFormat_Float32x3;
  14195. case SG_VERTEXFORMAT_FLOAT4: return WGPUVertexFormat_Float32x4;
  14196. case SG_VERTEXFORMAT_INT: return WGPUVertexFormat_Sint32;
  14197. case SG_VERTEXFORMAT_INT2: return WGPUVertexFormat_Sint32x2;
  14198. case SG_VERTEXFORMAT_INT3: return WGPUVertexFormat_Sint32x3;
  14199. case SG_VERTEXFORMAT_INT4: return WGPUVertexFormat_Sint32x4;
  14200. case SG_VERTEXFORMAT_UINT: return WGPUVertexFormat_Uint32;
  14201. case SG_VERTEXFORMAT_UINT2: return WGPUVertexFormat_Uint32x2;
  14202. case SG_VERTEXFORMAT_UINT3: return WGPUVertexFormat_Uint32x3;
  14203. case SG_VERTEXFORMAT_UINT4: return WGPUVertexFormat_Uint32x4;
  14204. case SG_VERTEXFORMAT_BYTE4: return WGPUVertexFormat_Sint8x4;
  14205. case SG_VERTEXFORMAT_BYTE4N: return WGPUVertexFormat_Snorm8x4;
  14206. case SG_VERTEXFORMAT_UBYTE4: return WGPUVertexFormat_Uint8x4;
  14207. case SG_VERTEXFORMAT_UBYTE4N: return WGPUVertexFormat_Unorm8x4;
  14208. case SG_VERTEXFORMAT_SHORT2: return WGPUVertexFormat_Sint16x2;
  14209. case SG_VERTEXFORMAT_SHORT2N: return WGPUVertexFormat_Snorm16x2;
  14210. case SG_VERTEXFORMAT_USHORT2: return WGPUVertexFormat_Uint16x2;
  14211. case SG_VERTEXFORMAT_USHORT2N: return WGPUVertexFormat_Unorm16x2;
  14212. case SG_VERTEXFORMAT_SHORT4: return WGPUVertexFormat_Sint16x4;
  14213. case SG_VERTEXFORMAT_SHORT4N: return WGPUVertexFormat_Snorm16x4;
  14214. case SG_VERTEXFORMAT_USHORT4: return WGPUVertexFormat_Uint16x4;
  14215. case SG_VERTEXFORMAT_USHORT4N: return WGPUVertexFormat_Unorm16x4;
  14216. case SG_VERTEXFORMAT_UINT10_N2: return WGPUVertexFormat_Unorm10_10_10_2;
  14217. case SG_VERTEXFORMAT_HALF2: return WGPUVertexFormat_Float16x2;
  14218. case SG_VERTEXFORMAT_HALF4: return WGPUVertexFormat_Float16x4;
  14219. default:
  14220. SOKOL_UNREACHABLE;
  14221. return WGPUVertexFormat_Force32;
  14222. }
  14223. }
  14224. _SOKOL_PRIVATE WGPUPrimitiveTopology _sg_wgpu_topology(sg_primitive_type t) {
  14225. switch (t) {
  14226. case SG_PRIMITIVETYPE_POINTS: return WGPUPrimitiveTopology_PointList;
  14227. case SG_PRIMITIVETYPE_LINES: return WGPUPrimitiveTopology_LineList;
  14228. case SG_PRIMITIVETYPE_LINE_STRIP: return WGPUPrimitiveTopology_LineStrip;
  14229. case SG_PRIMITIVETYPE_TRIANGLES: return WGPUPrimitiveTopology_TriangleList;
  14230. case SG_PRIMITIVETYPE_TRIANGLE_STRIP: return WGPUPrimitiveTopology_TriangleStrip;
  14231. default:
  14232. SOKOL_UNREACHABLE;
  14233. return WGPUPrimitiveTopology_Force32;
  14234. }
  14235. }
  14236. _SOKOL_PRIVATE WGPUFrontFace _sg_wgpu_frontface(sg_face_winding fw) {
  14237. return (fw == SG_FACEWINDING_CCW) ? WGPUFrontFace_CCW : WGPUFrontFace_CW;
  14238. }
  14239. _SOKOL_PRIVATE WGPUCullMode _sg_wgpu_cullmode(sg_cull_mode cm) {
  14240. switch (cm) {
  14241. case SG_CULLMODE_NONE: return WGPUCullMode_None;
  14242. case SG_CULLMODE_FRONT: return WGPUCullMode_Front;
  14243. case SG_CULLMODE_BACK: return WGPUCullMode_Back;
  14244. default:
  14245. SOKOL_UNREACHABLE;
  14246. return WGPUCullMode_Force32;
  14247. }
  14248. }
  14249. _SOKOL_PRIVATE WGPUTextureFormat _sg_wgpu_textureformat(sg_pixel_format p) {
  14250. switch (p) {
  14251. case SG_PIXELFORMAT_NONE: return WGPUTextureFormat_Undefined;
  14252. case SG_PIXELFORMAT_R8: return WGPUTextureFormat_R8Unorm;
  14253. case SG_PIXELFORMAT_R8SN: return WGPUTextureFormat_R8Snorm;
  14254. case SG_PIXELFORMAT_R8UI: return WGPUTextureFormat_R8Uint;
  14255. case SG_PIXELFORMAT_R8SI: return WGPUTextureFormat_R8Sint;
  14256. case SG_PIXELFORMAT_R16UI: return WGPUTextureFormat_R16Uint;
  14257. case SG_PIXELFORMAT_R16SI: return WGPUTextureFormat_R16Sint;
  14258. case SG_PIXELFORMAT_R16F: return WGPUTextureFormat_R16Float;
  14259. case SG_PIXELFORMAT_RG8: return WGPUTextureFormat_RG8Unorm;
  14260. case SG_PIXELFORMAT_RG8SN: return WGPUTextureFormat_RG8Snorm;
  14261. case SG_PIXELFORMAT_RG8UI: return WGPUTextureFormat_RG8Uint;
  14262. case SG_PIXELFORMAT_RG8SI: return WGPUTextureFormat_RG8Sint;
  14263. case SG_PIXELFORMAT_R32UI: return WGPUTextureFormat_R32Uint;
  14264. case SG_PIXELFORMAT_R32SI: return WGPUTextureFormat_R32Sint;
  14265. case SG_PIXELFORMAT_R32F: return WGPUTextureFormat_R32Float;
  14266. case SG_PIXELFORMAT_RG16UI: return WGPUTextureFormat_RG16Uint;
  14267. case SG_PIXELFORMAT_RG16SI: return WGPUTextureFormat_RG16Sint;
  14268. case SG_PIXELFORMAT_RG16F: return WGPUTextureFormat_RG16Float;
  14269. case SG_PIXELFORMAT_RGBA8: return WGPUTextureFormat_RGBA8Unorm;
  14270. case SG_PIXELFORMAT_SRGB8A8: return WGPUTextureFormat_RGBA8UnormSrgb;
  14271. case SG_PIXELFORMAT_RGBA8SN: return WGPUTextureFormat_RGBA8Snorm;
  14272. case SG_PIXELFORMAT_RGBA8UI: return WGPUTextureFormat_RGBA8Uint;
  14273. case SG_PIXELFORMAT_RGBA8SI: return WGPUTextureFormat_RGBA8Sint;
  14274. case SG_PIXELFORMAT_BGRA8: return WGPUTextureFormat_BGRA8Unorm;
  14275. case SG_PIXELFORMAT_RGB10A2: return WGPUTextureFormat_RGB10A2Unorm;
  14276. case SG_PIXELFORMAT_RG11B10F: return WGPUTextureFormat_RG11B10Ufloat;
  14277. case SG_PIXELFORMAT_RG32UI: return WGPUTextureFormat_RG32Uint;
  14278. case SG_PIXELFORMAT_RG32SI: return WGPUTextureFormat_RG32Sint;
  14279. case SG_PIXELFORMAT_RG32F: return WGPUTextureFormat_RG32Float;
  14280. case SG_PIXELFORMAT_RGBA16UI: return WGPUTextureFormat_RGBA16Uint;
  14281. case SG_PIXELFORMAT_RGBA16SI: return WGPUTextureFormat_RGBA16Sint;
  14282. case SG_PIXELFORMAT_RGBA16F: return WGPUTextureFormat_RGBA16Float;
  14283. case SG_PIXELFORMAT_RGBA32UI: return WGPUTextureFormat_RGBA32Uint;
  14284. case SG_PIXELFORMAT_RGBA32SI: return WGPUTextureFormat_RGBA32Sint;
  14285. case SG_PIXELFORMAT_RGBA32F: return WGPUTextureFormat_RGBA32Float;
  14286. case SG_PIXELFORMAT_DEPTH: return WGPUTextureFormat_Depth32Float;
  14287. case SG_PIXELFORMAT_DEPTH_STENCIL: return WGPUTextureFormat_Depth32FloatStencil8;
  14288. case SG_PIXELFORMAT_BC1_RGBA: return WGPUTextureFormat_BC1RGBAUnorm;
  14289. case SG_PIXELFORMAT_BC2_RGBA: return WGPUTextureFormat_BC2RGBAUnorm;
  14290. case SG_PIXELFORMAT_BC3_RGBA: return WGPUTextureFormat_BC3RGBAUnorm;
  14291. case SG_PIXELFORMAT_BC3_SRGBA: return WGPUTextureFormat_BC3RGBAUnormSrgb;
  14292. case SG_PIXELFORMAT_BC4_R: return WGPUTextureFormat_BC4RUnorm;
  14293. case SG_PIXELFORMAT_BC4_RSN: return WGPUTextureFormat_BC4RSnorm;
  14294. case SG_PIXELFORMAT_BC5_RG: return WGPUTextureFormat_BC5RGUnorm;
  14295. case SG_PIXELFORMAT_BC5_RGSN: return WGPUTextureFormat_BC5RGSnorm;
  14296. case SG_PIXELFORMAT_BC6H_RGBF: return WGPUTextureFormat_BC6HRGBFloat;
  14297. case SG_PIXELFORMAT_BC6H_RGBUF: return WGPUTextureFormat_BC6HRGBUfloat;
  14298. case SG_PIXELFORMAT_BC7_RGBA: return WGPUTextureFormat_BC7RGBAUnorm;
  14299. case SG_PIXELFORMAT_BC7_SRGBA: return WGPUTextureFormat_BC7RGBAUnormSrgb;
  14300. case SG_PIXELFORMAT_ETC2_RGB8: return WGPUTextureFormat_ETC2RGB8Unorm;
  14301. case SG_PIXELFORMAT_ETC2_RGB8A1: return WGPUTextureFormat_ETC2RGB8A1Unorm;
  14302. case SG_PIXELFORMAT_ETC2_RGBA8: return WGPUTextureFormat_ETC2RGBA8Unorm;
  14303. case SG_PIXELFORMAT_ETC2_SRGB8: return WGPUTextureFormat_ETC2RGB8UnormSrgb;
  14304. case SG_PIXELFORMAT_ETC2_SRGB8A8: return WGPUTextureFormat_ETC2RGBA8UnormSrgb;
  14305. case SG_PIXELFORMAT_EAC_R11: return WGPUTextureFormat_EACR11Unorm;
  14306. case SG_PIXELFORMAT_EAC_R11SN: return WGPUTextureFormat_EACR11Snorm;
  14307. case SG_PIXELFORMAT_EAC_RG11: return WGPUTextureFormat_EACRG11Unorm;
  14308. case SG_PIXELFORMAT_EAC_RG11SN: return WGPUTextureFormat_EACRG11Snorm;
  14309. case SG_PIXELFORMAT_RGB9E5: return WGPUTextureFormat_RGB9E5Ufloat;
  14310. case SG_PIXELFORMAT_ASTC_4x4_RGBA: return WGPUTextureFormat_ASTC4x4Unorm;
  14311. case SG_PIXELFORMAT_ASTC_4x4_SRGBA: return WGPUTextureFormat_ASTC4x4UnormSrgb;
  14312. // NOT SUPPORTED
  14313. case SG_PIXELFORMAT_R16:
  14314. case SG_PIXELFORMAT_R16SN:
  14315. case SG_PIXELFORMAT_RG16:
  14316. case SG_PIXELFORMAT_RG16SN:
  14317. case SG_PIXELFORMAT_RGBA16:
  14318. case SG_PIXELFORMAT_RGBA16SN:
  14319. return WGPUTextureFormat_Undefined;
  14320. default:
  14321. SOKOL_UNREACHABLE;
  14322. return WGPUTextureFormat_Force32;
  14323. }
  14324. }
  14325. _SOKOL_PRIVATE WGPUCompareFunction _sg_wgpu_comparefunc(sg_compare_func f) {
  14326. switch (f) {
  14327. case SG_COMPAREFUNC_NEVER: return WGPUCompareFunction_Never;
  14328. case SG_COMPAREFUNC_LESS: return WGPUCompareFunction_Less;
  14329. case SG_COMPAREFUNC_EQUAL: return WGPUCompareFunction_Equal;
  14330. case SG_COMPAREFUNC_LESS_EQUAL: return WGPUCompareFunction_LessEqual;
  14331. case SG_COMPAREFUNC_GREATER: return WGPUCompareFunction_Greater;
  14332. case SG_COMPAREFUNC_NOT_EQUAL: return WGPUCompareFunction_NotEqual;
  14333. case SG_COMPAREFUNC_GREATER_EQUAL: return WGPUCompareFunction_GreaterEqual;
  14334. case SG_COMPAREFUNC_ALWAYS: return WGPUCompareFunction_Always;
  14335. default:
  14336. SOKOL_UNREACHABLE;
  14337. return WGPUCompareFunction_Force32;
  14338. }
  14339. }
  14340. _SOKOL_PRIVATE WGPUStencilOperation _sg_wgpu_stencilop(sg_stencil_op op) {
  14341. switch (op) {
  14342. case SG_STENCILOP_KEEP: return WGPUStencilOperation_Keep;
  14343. case SG_STENCILOP_ZERO: return WGPUStencilOperation_Zero;
  14344. case SG_STENCILOP_REPLACE: return WGPUStencilOperation_Replace;
  14345. case SG_STENCILOP_INCR_CLAMP: return WGPUStencilOperation_IncrementClamp;
  14346. case SG_STENCILOP_DECR_CLAMP: return WGPUStencilOperation_DecrementClamp;
  14347. case SG_STENCILOP_INVERT: return WGPUStencilOperation_Invert;
  14348. case SG_STENCILOP_INCR_WRAP: return WGPUStencilOperation_IncrementWrap;
  14349. case SG_STENCILOP_DECR_WRAP: return WGPUStencilOperation_DecrementWrap;
  14350. default:
  14351. SOKOL_UNREACHABLE;
  14352. return WGPUStencilOperation_Force32;
  14353. }
  14354. }
  14355. _SOKOL_PRIVATE WGPUBlendOperation _sg_wgpu_blendop(sg_blend_op op) {
  14356. switch (op) {
  14357. case SG_BLENDOP_ADD: return WGPUBlendOperation_Add;
  14358. case SG_BLENDOP_SUBTRACT: return WGPUBlendOperation_Subtract;
  14359. case SG_BLENDOP_REVERSE_SUBTRACT: return WGPUBlendOperation_ReverseSubtract;
  14360. case SG_BLENDOP_MIN: return WGPUBlendOperation_Min;
  14361. case SG_BLENDOP_MAX: return WGPUBlendOperation_Max;
  14362. default:
  14363. SOKOL_UNREACHABLE;
  14364. return WGPUBlendOperation_Force32;
  14365. }
  14366. }
  14367. _SOKOL_PRIVATE WGPUBlendFactor _sg_wgpu_blendfactor(sg_blend_factor f) {
  14368. switch (f) {
  14369. case SG_BLENDFACTOR_ZERO: return WGPUBlendFactor_Zero;
  14370. case SG_BLENDFACTOR_ONE: return WGPUBlendFactor_One;
  14371. case SG_BLENDFACTOR_SRC_COLOR: return WGPUBlendFactor_Src;
  14372. case SG_BLENDFACTOR_ONE_MINUS_SRC_COLOR: return WGPUBlendFactor_OneMinusSrc;
  14373. case SG_BLENDFACTOR_SRC_ALPHA: return WGPUBlendFactor_SrcAlpha;
  14374. case SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA: return WGPUBlendFactor_OneMinusSrcAlpha;
  14375. case SG_BLENDFACTOR_DST_COLOR: return WGPUBlendFactor_Dst;
  14376. case SG_BLENDFACTOR_ONE_MINUS_DST_COLOR: return WGPUBlendFactor_OneMinusDst;
  14377. case SG_BLENDFACTOR_DST_ALPHA: return WGPUBlendFactor_DstAlpha;
  14378. case SG_BLENDFACTOR_ONE_MINUS_DST_ALPHA: return WGPUBlendFactor_OneMinusDstAlpha;
  14379. case SG_BLENDFACTOR_SRC_ALPHA_SATURATED: return WGPUBlendFactor_SrcAlphaSaturated;
  14380. case SG_BLENDFACTOR_BLEND_COLOR: return WGPUBlendFactor_Constant;
  14381. case SG_BLENDFACTOR_ONE_MINUS_BLEND_COLOR: return WGPUBlendFactor_OneMinusConstant;
  14382. // FIXME: separate blend alpha value not supported?
  14383. case SG_BLENDFACTOR_BLEND_ALPHA: return WGPUBlendFactor_Constant;
  14384. case SG_BLENDFACTOR_ONE_MINUS_BLEND_ALPHA: return WGPUBlendFactor_OneMinusConstant;
  14385. default:
  14386. SOKOL_UNREACHABLE;
  14387. return WGPUBlendFactor_Force32;
  14388. }
  14389. }
  14390. _SOKOL_PRIVATE WGPUColorWriteMask _sg_wgpu_colorwritemask(uint8_t m) {
  14391. // FIXME: change to WGPUColorWriteMask once Emscripten and Dawn webgpu.h agree
  14392. int res = 0;
  14393. if (0 != (m & SG_COLORMASK_R)) {
  14394. res |= WGPUColorWriteMask_Red;
  14395. }
  14396. if (0 != (m & SG_COLORMASK_G)) {
  14397. res |= WGPUColorWriteMask_Green;
  14398. }
  14399. if (0 != (m & SG_COLORMASK_B)) {
  14400. res |= WGPUColorWriteMask_Blue;
  14401. }
  14402. if (0 != (m & SG_COLORMASK_A)) {
  14403. res |= WGPUColorWriteMask_Alpha;
  14404. }
  14405. return (WGPUColorWriteMask)res;
  14406. }
  14407. _SOKOL_PRIVATE WGPUShaderStage _sg_wgpu_shader_stage(sg_shader_stage stage) {
  14408. switch (stage) {
  14409. case SG_SHADERSTAGE_VERTEX: return WGPUShaderStage_Vertex;
  14410. case SG_SHADERSTAGE_FRAGMENT: return WGPUShaderStage_Fragment;
  14411. case SG_SHADERSTAGE_COMPUTE: return WGPUShaderStage_Compute;
  14412. default: SOKOL_UNREACHABLE; return WGPUShaderStage_None;
  14413. }
  14414. }
  14415. _SOKOL_PRIVATE void _sg_wgpu_init_caps(void) {
  14416. _sg.backend = SG_BACKEND_WGPU;
  14417. _sg.features.origin_top_left = true;
  14418. _sg.features.image_clamp_to_border = false;
  14419. _sg.features.mrt_independent_blend_state = true;
  14420. _sg.features.mrt_independent_write_mask = true;
  14421. _sg.features.compute = true;
  14422. _sg.features.msaa_image_bindings = true;
  14423. wgpuDeviceGetLimits(_sg.wgpu.dev, &_sg.wgpu.limits);
  14424. const WGPULimits* l = &_sg.wgpu.limits;
  14425. _sg.limits.max_image_size_2d = (int) l->maxTextureDimension2D;
  14426. _sg.limits.max_image_size_cube = (int) l->maxTextureDimension2D; // not a bug, see: https://github.com/gpuweb/gpuweb/issues/1327
  14427. _sg.limits.max_image_size_3d = (int) l->maxTextureDimension3D;
  14428. _sg.limits.max_image_size_array = (int) l->maxTextureDimension2D;
  14429. _sg.limits.max_image_array_layers = (int) l->maxTextureArrayLayers;
  14430. _sg.limits.max_vertex_attrs = SG_MAX_VERTEX_ATTRIBUTES;
  14431. // NOTE: no WGPUTextureFormat_R16Unorm
  14432. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R8]);
  14433. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG8]);
  14434. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA8]);
  14435. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_SRGB8A8]);
  14436. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_BGRA8]);
  14437. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16F]);
  14438. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16F]);
  14439. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  14440. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGB10A2]);
  14441. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_R8SN]);
  14442. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG8SN]);
  14443. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGBA8SN]);
  14444. // FIXME: can be made renderable via extension
  14445. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  14446. // NOTE: msaa rendering is possible in WebGPU, but no resolve
  14447. // which is a combination that's not currently supported in sokol-gfx
  14448. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R8UI]);
  14449. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R8SI]);
  14450. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG8UI]);
  14451. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG8SI]);
  14452. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA8UI]);
  14453. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA8SI]);
  14454. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R16UI]);
  14455. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R16SI]);
  14456. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG16UI]);
  14457. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG16SI]);
  14458. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA16UI]);
  14459. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA16SI]);
  14460. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32UI]);
  14461. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32SI]);
  14462. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  14463. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  14464. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  14465. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  14466. if (wgpuDeviceHasFeature(_sg.wgpu.dev, WGPUFeatureName_Float32Filterable)) {
  14467. _sg_pixelformat_sfr(&_sg.formats[SG_PIXELFORMAT_R32F]);
  14468. _sg_pixelformat_sfr(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  14469. _sg_pixelformat_sfr(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  14470. } else {
  14471. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32F]);
  14472. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  14473. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  14474. }
  14475. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH]);
  14476. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH_STENCIL]);
  14477. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGB9E5]);
  14478. if (wgpuDeviceHasFeature(_sg.wgpu.dev, WGPUFeatureName_TextureCompressionBC)) {
  14479. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC1_RGBA]);
  14480. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC2_RGBA]);
  14481. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_RGBA]);
  14482. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_SRGBA]);
  14483. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_R]);
  14484. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_RSN]);
  14485. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RG]);
  14486. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RGSN]);
  14487. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBF]);
  14488. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBUF]);
  14489. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_RGBA]);
  14490. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_SRGBA]);
  14491. }
  14492. if (wgpuDeviceHasFeature(_sg.wgpu.dev, WGPUFeatureName_TextureCompressionETC2)) {
  14493. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8]);
  14494. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8]);
  14495. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8A1]);
  14496. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGBA8]);
  14497. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8A8]);
  14498. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11]);
  14499. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11SN]);
  14500. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11]);
  14501. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11SN]);
  14502. }
  14503. if (wgpuDeviceHasFeature(_sg.wgpu.dev, WGPUFeatureName_TextureCompressionASTC)) {
  14504. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_RGBA]);
  14505. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_SRGBA]);
  14506. }
  14507. // see: https://github.com/gpuweb/gpuweb/issues/513
  14508. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8]);
  14509. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8SN]);
  14510. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8UI]);
  14511. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA8SI]);
  14512. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16UI]);
  14513. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16SI]);
  14514. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  14515. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32UI]);
  14516. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32SI]);
  14517. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_R32F]);
  14518. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  14519. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  14520. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  14521. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  14522. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  14523. _sg_pixelformat_compute_all(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  14524. }
  14525. _SOKOL_PRIVATE void _sg_wgpu_uniform_buffer_init(const sg_desc* desc) {
  14526. SOKOL_ASSERT(0 == _sg.wgpu.uniform.staging);
  14527. SOKOL_ASSERT(0 == _sg.wgpu.uniform.buf);
  14528. // Add the max-uniform-update size (64 KB) to the requested buffer size,
  14529. // this is to prevent validation errors in the WebGPU implementation
  14530. // if the entire buffer size is used per frame. 64 KB is the allowed
  14531. // max uniform update size on NVIDIA
  14532. //
  14533. // FIXME: is this still needed?
  14534. _sg.wgpu.uniform.num_bytes = (uint32_t)(desc->uniform_buffer_size + _SG_WGPU_MAX_UNIFORM_UPDATE_SIZE);
  14535. _sg.wgpu.uniform.staging = (uint8_t*)_sg_malloc(_sg.wgpu.uniform.num_bytes);
  14536. WGPUBufferDescriptor ub_desc;
  14537. _sg_clear(&ub_desc, sizeof(ub_desc));
  14538. ub_desc.size = _sg.wgpu.uniform.num_bytes;
  14539. ub_desc.usage = WGPUBufferUsage_Uniform|WGPUBufferUsage_CopyDst;
  14540. _sg.wgpu.uniform.buf = wgpuDeviceCreateBuffer(_sg.wgpu.dev, &ub_desc);
  14541. SOKOL_ASSERT(_sg.wgpu.uniform.buf);
  14542. }
  14543. _SOKOL_PRIVATE void _sg_wgpu_uniform_buffer_discard(void) {
  14544. if (_sg.wgpu.uniform.buf) {
  14545. wgpuBufferRelease(_sg.wgpu.uniform.buf);
  14546. _sg.wgpu.uniform.buf = 0;
  14547. }
  14548. if (_sg.wgpu.uniform.staging) {
  14549. _sg_free(_sg.wgpu.uniform.staging);
  14550. _sg.wgpu.uniform.staging = 0;
  14551. }
  14552. }
  14553. _SOKOL_PRIVATE void _sg_wgpu_uniform_buffer_on_commit(void) {
  14554. wgpuQueueWriteBuffer(_sg.wgpu.queue, _sg.wgpu.uniform.buf, 0, _sg.wgpu.uniform.staging, _sg.wgpu.uniform.offset);
  14555. _sg_stats_add(wgpu.uniforms.size_write_buffer, _sg.wgpu.uniform.offset);
  14556. _sg.wgpu.uniform.offset = 0;
  14557. _sg_clear(_sg.wgpu.uniform.bind_offsets, sizeof(_sg.wgpu.uniform.bind_offsets));
  14558. }
  14559. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_pool_init(const sg_desc* desc) {
  14560. SOKOL_ASSERT((desc->wgpu_bindgroups_cache_size > 0) && (desc->wgpu_bindgroups_cache_size < _SG_MAX_POOL_SIZE));
  14561. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  14562. SOKOL_ASSERT(0 == p->bindgroups);
  14563. const int pool_size = desc->wgpu_bindgroups_cache_size;
  14564. _sg_pool_init(&p->pool, pool_size);
  14565. size_t pool_byte_size = sizeof(_sg_wgpu_bindgroup_t) * (size_t)p->pool.size;
  14566. p->bindgroups = (_sg_wgpu_bindgroup_t*) _sg_malloc_clear(pool_byte_size);
  14567. }
  14568. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_pool_discard(void) {
  14569. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  14570. SOKOL_ASSERT(p->bindgroups);
  14571. _sg_free(p->bindgroups); p->bindgroups = 0;
  14572. _sg_pool_discard(&p->pool);
  14573. }
  14574. _SOKOL_PRIVATE _sg_wgpu_bindgroup_t* _sg_wgpu_bindgroup_at(uint32_t bg_id) {
  14575. SOKOL_ASSERT(SG_INVALID_ID != bg_id);
  14576. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  14577. int slot_index = _sg_slot_index(bg_id);
  14578. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < p->pool.size));
  14579. return &p->bindgroups[slot_index];
  14580. }
  14581. _SOKOL_PRIVATE _sg_wgpu_bindgroup_t* _sg_wgpu_lookup_bindgroup(uint32_t bg_id) {
  14582. if (SG_INVALID_ID != bg_id) {
  14583. _sg_wgpu_bindgroup_t* bg = _sg_wgpu_bindgroup_at(bg_id);
  14584. if (bg->slot.id == bg_id) {
  14585. return bg;
  14586. }
  14587. }
  14588. return 0;
  14589. }
  14590. _SOKOL_PRIVATE _sg_wgpu_bindgroup_handle_t _sg_wgpu_alloc_bindgroup(void) {
  14591. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  14592. _sg_wgpu_bindgroup_handle_t res;
  14593. int slot_index = _sg_pool_alloc_index(&p->pool);
  14594. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  14595. res.id = _sg_slot_alloc(&p->pool, &p->bindgroups[slot_index].slot, slot_index);
  14596. } else {
  14597. res.id = SG_INVALID_ID;
  14598. _SG_ERROR(WGPU_BINDGROUPS_POOL_EXHAUSTED);
  14599. }
  14600. return res;
  14601. }
  14602. _SOKOL_PRIVATE void _sg_wgpu_dealloc_bindgroup(_sg_wgpu_bindgroup_t* bg) {
  14603. SOKOL_ASSERT(bg && (bg->slot.state == SG_RESOURCESTATE_ALLOC) && (bg->slot.id != SG_INVALID_ID));
  14604. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  14605. _sg_pool_free_index(&p->pool, _sg_slot_index(bg->slot.id));
  14606. _sg_slot_reset(&bg->slot);
  14607. }
  14608. _SOKOL_PRIVATE void _sg_wgpu_reset_bindgroup_to_alloc_state(_sg_wgpu_bindgroup_t* bg) {
  14609. SOKOL_ASSERT(bg);
  14610. _sg_slot_t slot = bg->slot;
  14611. _sg_clear(bg, sizeof(_sg_wgpu_bindgroup_t));
  14612. bg->slot = slot;
  14613. bg->slot.state = SG_RESOURCESTATE_ALLOC;
  14614. }
  14615. // MurmurHash64B (see: https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L142)
  14616. _SOKOL_PRIVATE uint64_t _sg_wgpu_hash(const void* key, int len, uint64_t seed) {
  14617. const uint32_t m = 0x5bd1e995;
  14618. const int r = 24;
  14619. uint32_t h1 = (uint32_t)seed ^ (uint32_t)len;
  14620. uint32_t h2 = (uint32_t)(seed >> 32);
  14621. const uint32_t * data = (const uint32_t *)key;
  14622. while (len >= 8) {
  14623. uint32_t k1 = *data++;
  14624. k1 *= m; k1 ^= k1 >> r; k1 *= m;
  14625. h1 *= m; h1 ^= k1;
  14626. len -= 4;
  14627. uint32_t k2 = *data++;
  14628. k2 *= m; k2 ^= k2 >> r; k2 *= m;
  14629. h2 *= m; h2 ^= k2;
  14630. len -= 4;
  14631. }
  14632. if (len >= 4) {
  14633. uint32_t k1 = *data++;
  14634. k1 *= m; k1 ^= k1 >> r; k1 *= m;
  14635. h1 *= m; h1 ^= k1;
  14636. len -= 4;
  14637. }
  14638. switch(len) {
  14639. case 3: h2 ^= (uint32_t)(((unsigned char*)data)[2] << 16);
  14640. case 2: h2 ^= (uint32_t)(((unsigned char*)data)[1] << 8);
  14641. case 1: h2 ^= ((unsigned char*)data)[0];
  14642. h2 *= m;
  14643. };
  14644. h1 ^= h2 >> 18; h1 *= m;
  14645. h2 ^= h1 >> 22; h2 *= m;
  14646. h1 ^= h2 >> 17; h1 *= m;
  14647. h2 ^= h1 >> 19; h2 *= m;
  14648. uint64_t h = h1;
  14649. h = (h << 32) | h2;
  14650. return h;
  14651. }
  14652. _SOKOL_PRIVATE uint64_t _sg_wgpu_bindgroups_cache_item(_sg_wgpu_bindgroups_cache_item_type_t type, uint8_t wgpu_binding, uint32_t id, uint32_t uninit_count) {
  14653. const uint64_t bb = wgpu_binding;
  14654. const uint64_t t = type & 7;
  14655. const uint64_t ccccc = uninit_count & ((1 << 21) - 1);
  14656. const uint64_t iiiiiiii = id;
  14657. return (bb << 56) | (t << 53) | (ccccc << 32) | iiiiiiii;
  14658. }
  14659. _SOKOL_PRIVATE uint64_t _sg_wgpu_bindgroups_cache_pip_item(const _sg_slot_t* slot) {
  14660. return _sg_wgpu_bindgroups_cache_item(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_PIPELINE, 0xFF, slot->id, slot->uninit_count);
  14661. }
  14662. _SOKOL_PRIVATE uint64_t _sg_wgpu_bindgroups_cache_image_item(uint8_t wgpu_binding, const _sg_slot_t* slot) {
  14663. return _sg_wgpu_bindgroups_cache_item(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_IMAGE, wgpu_binding, slot->id, slot->uninit_count);
  14664. }
  14665. _SOKOL_PRIVATE uint64_t _sg_wgpu_bindgroups_cache_sampler_item(uint8_t wgpu_binding, const _sg_slot_t* slot) {
  14666. return _sg_wgpu_bindgroups_cache_item(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_SAMPLER, wgpu_binding, slot->id, slot->uninit_count);
  14667. }
  14668. _SOKOL_PRIVATE uint64_t _sg_wgpu_bindgroups_cache_sbuf_item(uint8_t wgpu_binding, const _sg_slot_t* slot) {
  14669. return _sg_wgpu_bindgroups_cache_item(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_STORAGEBUFFER, wgpu_binding, slot->id, slot->uninit_count);
  14670. }
  14671. _SOKOL_PRIVATE void _sg_wgpu_init_bindgroups_cache_key(_sg_wgpu_bindgroups_cache_key_t* key, const _sg_bindings_ptrs_t* bnd) {
  14672. SOKOL_ASSERT(bnd);
  14673. SOKOL_ASSERT(bnd->pip);
  14674. const _sg_shader_t* shd = _sg_shader_ref_ptr(&bnd->pip->cmn.shader);
  14675. _sg_clear(key->items, sizeof(key->items));
  14676. key->items[0] = _sg_wgpu_bindgroups_cache_pip_item(&bnd->pip->slot);
  14677. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  14678. if (shd->cmn.images[i].stage == SG_SHADERSTAGE_NONE) {
  14679. continue;
  14680. }
  14681. SOKOL_ASSERT(bnd->imgs[i]);
  14682. const size_t item_idx = i + 1;
  14683. SOKOL_ASSERT(item_idx < _SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS);
  14684. SOKOL_ASSERT(0 == key->items[item_idx]);
  14685. const uint8_t wgpu_binding = shd->wgpu.img_grp1_bnd_n[i];
  14686. key->items[item_idx] = _sg_wgpu_bindgroups_cache_image_item(wgpu_binding, &bnd->imgs[i]->slot);
  14687. }
  14688. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  14689. if (shd->cmn.samplers[i].stage == SG_SHADERSTAGE_NONE) {
  14690. continue;
  14691. }
  14692. SOKOL_ASSERT(bnd->smps[i]);
  14693. const size_t item_idx = i + 1 + SG_MAX_IMAGE_BINDSLOTS;
  14694. SOKOL_ASSERT(item_idx < _SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS);
  14695. SOKOL_ASSERT(0 == key->items[item_idx]);
  14696. const uint8_t wgpu_binding = shd->wgpu.smp_grp1_bnd_n[i];
  14697. key->items[item_idx] = _sg_wgpu_bindgroups_cache_sampler_item(wgpu_binding, &bnd->smps[i]->slot);
  14698. }
  14699. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  14700. if (shd->cmn.storage_buffers[i].stage == SG_SHADERSTAGE_NONE) {
  14701. continue;
  14702. }
  14703. SOKOL_ASSERT(bnd->sbufs[i]);
  14704. const size_t item_idx = i + 1 + SG_MAX_IMAGE_BINDSLOTS + SG_MAX_SAMPLER_BINDSLOTS;
  14705. SOKOL_ASSERT(item_idx < _SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS);
  14706. SOKOL_ASSERT(0 == key->items[item_idx]);
  14707. const uint8_t wgpu_binding = shd->wgpu.sbuf_grp1_bnd_n[i];
  14708. key->items[item_idx] = _sg_wgpu_bindgroups_cache_sbuf_item(wgpu_binding, &bnd->sbufs[i]->slot);
  14709. }
  14710. key->hash = _sg_wgpu_hash(&key->items, (int)sizeof(key->items), 0x1234567887654321);
  14711. }
  14712. _SOKOL_PRIVATE bool _sg_wgpu_compare_bindgroups_cache_key(_sg_wgpu_bindgroups_cache_key_t* k0, _sg_wgpu_bindgroups_cache_key_t* k1) {
  14713. SOKOL_ASSERT(k0 && k1);
  14714. if (k0->hash != k1->hash) {
  14715. return false;
  14716. }
  14717. if (memcmp(&k0->items, &k1->items, sizeof(k0->items)) != 0) {
  14718. _sg_stats_add(wgpu.bindings.num_bindgroup_cache_hash_vs_key_mismatch, 1);
  14719. return false;
  14720. }
  14721. return true;
  14722. }
  14723. _SOKOL_PRIVATE _sg_wgpu_bindgroup_t* _sg_wgpu_create_bindgroup(_sg_bindings_ptrs_t* bnd) {
  14724. SOKOL_ASSERT(_sg.wgpu.dev);
  14725. SOKOL_ASSERT(bnd->pip);
  14726. const _sg_shader_t* shd = _sg_shader_ref_ptr(&bnd->pip->cmn.shader);
  14727. _sg_stats_add(wgpu.bindings.num_create_bindgroup, 1);
  14728. _sg_wgpu_bindgroup_handle_t bg_id = _sg_wgpu_alloc_bindgroup();
  14729. if (bg_id.id == SG_INVALID_ID) {
  14730. return 0;
  14731. }
  14732. _sg_wgpu_bindgroup_t* bg = _sg_wgpu_bindgroup_at(bg_id.id);
  14733. SOKOL_ASSERT(bg && (bg->slot.state == SG_RESOURCESTATE_ALLOC));
  14734. // create wgpu bindgroup object (also see _sg_wgpu_create_shader())
  14735. WGPUBindGroupLayout bgl = shd->wgpu.bgl_img_smp_sbuf;
  14736. SOKOL_ASSERT(bgl);
  14737. WGPUBindGroupEntry bg_entries[_SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES];
  14738. _sg_clear(&bg_entries, sizeof(bg_entries));
  14739. size_t bgl_index = 0;
  14740. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  14741. if (shd->cmn.images[i].stage == SG_SHADERSTAGE_NONE) {
  14742. continue;
  14743. }
  14744. SOKOL_ASSERT(bnd->imgs[i]);
  14745. SOKOL_ASSERT(bgl_index < _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES);
  14746. WGPUBindGroupEntry* bg_entry = &bg_entries[bgl_index];
  14747. bg_entry->binding = shd->wgpu.img_grp1_bnd_n[i];
  14748. bg_entry->textureView = bnd->imgs[i]->wgpu.view;
  14749. bgl_index += 1;
  14750. }
  14751. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  14752. if (shd->cmn.samplers[i].stage == SG_SHADERSTAGE_NONE) {
  14753. continue;
  14754. }
  14755. SOKOL_ASSERT(bnd->smps[i]);
  14756. SOKOL_ASSERT(bgl_index < _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES);
  14757. WGPUBindGroupEntry* bg_entry = &bg_entries[bgl_index];
  14758. bg_entry->binding = shd->wgpu.smp_grp1_bnd_n[i];
  14759. bg_entry->sampler = bnd->smps[i]->wgpu.smp;
  14760. bgl_index += 1;
  14761. }
  14762. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  14763. if (shd->cmn.storage_buffers[i].stage == SG_SHADERSTAGE_NONE) {
  14764. continue;
  14765. }
  14766. SOKOL_ASSERT(bnd->sbufs[i]);
  14767. SOKOL_ASSERT(bgl_index < _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES);
  14768. WGPUBindGroupEntry* bg_entry = &bg_entries[bgl_index];
  14769. bg_entry->binding = shd->wgpu.sbuf_grp1_bnd_n[i];
  14770. bg_entry->buffer = bnd->sbufs[i]->wgpu.buf;
  14771. bg_entry->size = (uint64_t) bnd->sbufs[i]->cmn.size;
  14772. bgl_index += 1;
  14773. }
  14774. WGPUBindGroupDescriptor bg_desc;
  14775. _sg_clear(&bg_desc, sizeof(bg_desc));
  14776. bg_desc.layout = bgl;
  14777. bg_desc.entryCount = bgl_index;
  14778. bg_desc.entries = bg_entries;
  14779. bg->bindgroup = wgpuDeviceCreateBindGroup(_sg.wgpu.dev, &bg_desc);
  14780. if (bg->bindgroup == 0) {
  14781. _SG_ERROR(WGPU_CREATEBINDGROUP_FAILED);
  14782. bg->slot.state = SG_RESOURCESTATE_FAILED;
  14783. return bg;
  14784. }
  14785. _sg_wgpu_init_bindgroups_cache_key(&bg->key, bnd);
  14786. bg->slot.state = SG_RESOURCESTATE_VALID;
  14787. return bg;
  14788. }
  14789. _SOKOL_PRIVATE void _sg_wgpu_discard_bindgroup(_sg_wgpu_bindgroup_t* bg) {
  14790. SOKOL_ASSERT(bg);
  14791. _sg_stats_add(wgpu.bindings.num_discard_bindgroup, 1);
  14792. if (bg->slot.state == SG_RESOURCESTATE_VALID) {
  14793. if (bg->bindgroup) {
  14794. wgpuBindGroupRelease(bg->bindgroup);
  14795. bg->bindgroup = 0;
  14796. }
  14797. _sg_wgpu_reset_bindgroup_to_alloc_state(bg);
  14798. SOKOL_ASSERT(bg->slot.state == SG_RESOURCESTATE_ALLOC);
  14799. }
  14800. if (bg->slot.state == SG_RESOURCESTATE_ALLOC) {
  14801. _sg_wgpu_dealloc_bindgroup(bg);
  14802. SOKOL_ASSERT(bg->slot.state == SG_RESOURCESTATE_INITIAL);
  14803. }
  14804. }
  14805. _SOKOL_PRIVATE void _sg_wgpu_discard_all_bindgroups(void) {
  14806. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  14807. for (int i = 0; i < p->pool.size; i++) {
  14808. sg_resource_state state = p->bindgroups[i].slot.state;
  14809. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  14810. _sg_wgpu_discard_bindgroup(&p->bindgroups[i]);
  14811. }
  14812. }
  14813. }
  14814. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_cache_init(const sg_desc* desc) {
  14815. SOKOL_ASSERT(desc);
  14816. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.num == 0);
  14817. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.index_mask == 0);
  14818. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.items == 0);
  14819. const int num = desc->wgpu_bindgroups_cache_size;
  14820. if (num <= 1) {
  14821. _SG_PANIC(WGPU_BINDGROUPSCACHE_SIZE_GREATER_ONE);
  14822. }
  14823. if (!_sg_ispow2(num)) {
  14824. _SG_PANIC(WGPU_BINDGROUPSCACHE_SIZE_POW2);
  14825. }
  14826. _sg.wgpu.bindgroups_cache.num = (uint32_t)desc->wgpu_bindgroups_cache_size;
  14827. _sg.wgpu.bindgroups_cache.index_mask = _sg.wgpu.bindgroups_cache.num - 1;
  14828. size_t size_in_bytes = sizeof(_sg_wgpu_bindgroup_handle_t) * (size_t)num;
  14829. _sg.wgpu.bindgroups_cache.items = (_sg_wgpu_bindgroup_handle_t*)_sg_malloc_clear(size_in_bytes);
  14830. }
  14831. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_cache_discard(void) {
  14832. if (_sg.wgpu.bindgroups_cache.items) {
  14833. _sg_free(_sg.wgpu.bindgroups_cache.items);
  14834. _sg.wgpu.bindgroups_cache.items = 0;
  14835. }
  14836. _sg.wgpu.bindgroups_cache.num = 0;
  14837. _sg.wgpu.bindgroups_cache.index_mask = 0;
  14838. }
  14839. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_cache_set(uint64_t hash, uint32_t bg_id) {
  14840. uint32_t index = hash & _sg.wgpu.bindgroups_cache.index_mask;
  14841. SOKOL_ASSERT(index < _sg.wgpu.bindgroups_cache.num);
  14842. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.items);
  14843. _sg.wgpu.bindgroups_cache.items[index].id = bg_id;
  14844. }
  14845. _SOKOL_PRIVATE uint32_t _sg_wgpu_bindgroups_cache_get(uint64_t hash) {
  14846. uint32_t index = hash & _sg.wgpu.bindgroups_cache.index_mask;
  14847. SOKOL_ASSERT(index < _sg.wgpu.bindgroups_cache.num);
  14848. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.items);
  14849. return _sg.wgpu.bindgroups_cache.items[index].id;
  14850. }
  14851. // called from wgpu resource destroy functions to also invalidate any
  14852. // bindgroups cache slot and bindgroup referencing that resource
  14853. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_cache_invalidate(_sg_wgpu_bindgroups_cache_item_type_t type, const _sg_slot_t* slot) {
  14854. const uint64_t key_mask = _sg_wgpu_bindgroups_cache_item(type, 0xFF, 0xFFFFFFFF, 0xFFFFFFFF);
  14855. const uint64_t key_item = _sg_wgpu_bindgroups_cache_item(type, 0, slot->id, slot->uninit_count) & key_mask;
  14856. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.items);
  14857. for (uint32_t cache_item_idx = 0; cache_item_idx < _sg.wgpu.bindgroups_cache.num; cache_item_idx++) {
  14858. const uint32_t bg_id = _sg.wgpu.bindgroups_cache.items[cache_item_idx].id;
  14859. if (bg_id != SG_INVALID_ID) {
  14860. _sg_wgpu_bindgroup_t* bg = _sg_wgpu_lookup_bindgroup(bg_id);
  14861. SOKOL_ASSERT(bg && (bg->slot.state == SG_RESOURCESTATE_VALID));
  14862. // check if resource is in bindgroup, if yes discard bindgroup and invalidate cache slot
  14863. bool invalidate_cache_item = false;
  14864. for (int key_item_idx = 0; key_item_idx < _SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS; key_item_idx++) {
  14865. if ((bg->key.items[key_item_idx] & key_mask) == key_item) {
  14866. invalidate_cache_item = true;
  14867. break;
  14868. }
  14869. }
  14870. if (invalidate_cache_item) {
  14871. _sg_wgpu_discard_bindgroup(bg); bg = 0;
  14872. _sg_wgpu_bindgroups_cache_set(cache_item_idx, SG_INVALID_ID);
  14873. _sg_stats_add(wgpu.bindings.num_bindgroup_cache_invalidates, 1);
  14874. }
  14875. }
  14876. }
  14877. }
  14878. _SOKOL_PRIVATE void _sg_wgpu_bindings_cache_clear(void) {
  14879. memset(&_sg.wgpu.bindings_cache, 0, sizeof(_sg.wgpu.bindings_cache));
  14880. }
  14881. _SOKOL_PRIVATE bool _sg_wgpu_bindings_cache_vb_dirty(size_t index, const _sg_buffer_t* vb, uint64_t offset) {
  14882. SOKOL_ASSERT((index >= 0) && (index < SG_MAX_VERTEXBUFFER_BINDSLOTS));
  14883. if (vb) {
  14884. return (_sg.wgpu.bindings_cache.vbs[index].buffer.id != vb->slot.id)
  14885. || (_sg.wgpu.bindings_cache.vbs[index].offset != offset);
  14886. } else {
  14887. return _sg.wgpu.bindings_cache.vbs[index].buffer.id != SG_INVALID_ID;
  14888. }
  14889. }
  14890. _SOKOL_PRIVATE void _sg_wgpu_bindings_cache_vb_update(size_t index, const _sg_buffer_t* vb, uint64_t offset) {
  14891. SOKOL_ASSERT((index >= 0) && (index < SG_MAX_VERTEXBUFFER_BINDSLOTS));
  14892. if (vb) {
  14893. _sg.wgpu.bindings_cache.vbs[index].buffer.id = vb->slot.id;
  14894. _sg.wgpu.bindings_cache.vbs[index].offset = offset;
  14895. } else {
  14896. _sg.wgpu.bindings_cache.vbs[index].buffer.id = SG_INVALID_ID;
  14897. _sg.wgpu.bindings_cache.vbs[index].offset = 0;
  14898. }
  14899. }
  14900. _SOKOL_PRIVATE bool _sg_wgpu_bindings_cache_ib_dirty(const _sg_buffer_t* ib, uint64_t offset) {
  14901. if (ib) {
  14902. return (_sg.wgpu.bindings_cache.ib.buffer.id != ib->slot.id)
  14903. || (_sg.wgpu.bindings_cache.ib.offset != offset);
  14904. } else {
  14905. return _sg.wgpu.bindings_cache.ib.buffer.id != SG_INVALID_ID;
  14906. }
  14907. }
  14908. _SOKOL_PRIVATE void _sg_wgpu_bindings_cache_ib_update(const _sg_buffer_t* ib, uint64_t offset) {
  14909. if (ib) {
  14910. _sg.wgpu.bindings_cache.ib.buffer.id = ib->slot.id;
  14911. _sg.wgpu.bindings_cache.ib.offset = offset;
  14912. } else {
  14913. _sg.wgpu.bindings_cache.ib.buffer.id = SG_INVALID_ID;
  14914. _sg.wgpu.bindings_cache.ib.offset = 0;
  14915. }
  14916. }
  14917. _SOKOL_PRIVATE bool _sg_wgpu_bindings_cache_bg_dirty(const _sg_wgpu_bindgroup_t* bg) {
  14918. if (bg) {
  14919. return _sg.wgpu.bindings_cache.bg.id != bg->slot.id;
  14920. } else {
  14921. return _sg.wgpu.bindings_cache.bg.id != SG_INVALID_ID;
  14922. }
  14923. }
  14924. _SOKOL_PRIVATE void _sg_wgpu_bindings_cache_bg_update(const _sg_wgpu_bindgroup_t* bg) {
  14925. if (bg) {
  14926. _sg.wgpu.bindings_cache.bg.id = bg->slot.id;
  14927. } else {
  14928. _sg.wgpu.bindings_cache.bg.id = SG_INVALID_ID;
  14929. }
  14930. }
  14931. _SOKOL_PRIVATE void _sg_wgpu_set_bindgroup(size_t bg_idx, _sg_wgpu_bindgroup_t* bg) {
  14932. if (_sg_wgpu_bindings_cache_bg_dirty(bg)) {
  14933. _sg_wgpu_bindings_cache_bg_update(bg);
  14934. _sg_stats_add(wgpu.bindings.num_set_bindgroup, 1);
  14935. if (_sg.cur_pass.is_compute) {
  14936. SOKOL_ASSERT(_sg.wgpu.cpass_enc);
  14937. if (bg) {
  14938. SOKOL_ASSERT(bg->slot.state == SG_RESOURCESTATE_VALID);
  14939. SOKOL_ASSERT(bg->bindgroup);
  14940. wgpuComputePassEncoderSetBindGroup(_sg.wgpu.cpass_enc, bg_idx, bg->bindgroup, 0, 0);
  14941. } else {
  14942. wgpuComputePassEncoderSetBindGroup(_sg.wgpu.cpass_enc, bg_idx, _sg.wgpu.empty_bind_group, 0, 0);
  14943. }
  14944. } else {
  14945. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  14946. if (bg) {
  14947. SOKOL_ASSERT(bg->slot.state == SG_RESOURCESTATE_VALID);
  14948. SOKOL_ASSERT(bg->bindgroup);
  14949. wgpuRenderPassEncoderSetBindGroup(_sg.wgpu.rpass_enc, bg_idx, bg->bindgroup, 0, 0);
  14950. } else {
  14951. wgpuRenderPassEncoderSetBindGroup(_sg.wgpu.rpass_enc, bg_idx, _sg.wgpu.empty_bind_group, 0, 0);
  14952. }
  14953. }
  14954. } else {
  14955. _sg_stats_add(wgpu.bindings.num_skip_redundant_bindgroup, 1);
  14956. }
  14957. }
  14958. _SOKOL_PRIVATE bool _sg_wgpu_apply_bindings_bindgroup(_sg_bindings_ptrs_t* bnd) {
  14959. if (!_sg.desc.wgpu_disable_bindgroups_cache) {
  14960. _sg_wgpu_bindgroup_t* bg = 0;
  14961. _sg_wgpu_bindgroups_cache_key_t key;
  14962. _sg_wgpu_init_bindgroups_cache_key(&key, bnd);
  14963. uint32_t bg_id = _sg_wgpu_bindgroups_cache_get(key.hash);
  14964. if (bg_id != SG_INVALID_ID) {
  14965. // potential cache hit
  14966. bg = _sg_wgpu_lookup_bindgroup(bg_id);
  14967. SOKOL_ASSERT(bg && (bg->slot.state == SG_RESOURCESTATE_VALID));
  14968. if (!_sg_wgpu_compare_bindgroups_cache_key(&key, &bg->key)) {
  14969. // cache collision, need to delete cached bindgroup
  14970. _sg_stats_add(wgpu.bindings.num_bindgroup_cache_collisions, 1);
  14971. _sg_wgpu_discard_bindgroup(bg);
  14972. _sg_wgpu_bindgroups_cache_set(key.hash, SG_INVALID_ID);
  14973. bg = 0;
  14974. } else {
  14975. _sg_stats_add(wgpu.bindings.num_bindgroup_cache_hits, 1);
  14976. }
  14977. } else {
  14978. _sg_stats_add(wgpu.bindings.num_bindgroup_cache_misses, 1);
  14979. }
  14980. if (bg == 0) {
  14981. // either no cache entry yet, or cache collision, create new bindgroup and store in cache
  14982. bg = _sg_wgpu_create_bindgroup(bnd);
  14983. _sg_wgpu_bindgroups_cache_set(key.hash, bg->slot.id);
  14984. }
  14985. if (bg && bg->slot.state == SG_RESOURCESTATE_VALID) {
  14986. _sg_wgpu_set_bindgroup(_SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX, bg);
  14987. } else {
  14988. return false;
  14989. }
  14990. } else {
  14991. // bindgroups cache disabled, create and destroy bindgroup on the fly (expensive!)
  14992. _sg_wgpu_bindgroup_t* bg = _sg_wgpu_create_bindgroup(bnd);
  14993. if (bg) {
  14994. if (bg->slot.state == SG_RESOURCESTATE_VALID) {
  14995. _sg_wgpu_set_bindgroup(_SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX, bg);
  14996. }
  14997. _sg_wgpu_discard_bindgroup(bg);
  14998. } else {
  14999. return false;
  15000. }
  15001. }
  15002. return true;
  15003. }
  15004. _SOKOL_PRIVATE bool _sg_wgpu_apply_index_buffer(_sg_bindings_ptrs_t* bnd) {
  15005. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  15006. const _sg_buffer_t* ib = bnd->ib;
  15007. uint64_t offset = (uint64_t)bnd->ib_offset;
  15008. if (_sg_wgpu_bindings_cache_ib_dirty(ib, offset)) {
  15009. _sg_wgpu_bindings_cache_ib_update(ib, offset);
  15010. if (ib) {
  15011. const WGPUIndexFormat format = _sg_wgpu_indexformat(bnd->pip->cmn.index_type);
  15012. const uint64_t buf_size = (uint64_t)ib->cmn.size;
  15013. SOKOL_ASSERT(buf_size > offset);
  15014. const uint64_t max_bytes = buf_size - offset;
  15015. wgpuRenderPassEncoderSetIndexBuffer(_sg.wgpu.rpass_enc, ib->wgpu.buf, format, offset, max_bytes);
  15016. /* FIXME: the else-pass should actually set a null index buffer, but that doesn't seem to work yet
  15017. } else {
  15018. wgpuRenderPassEncoderSetIndexBuffer(_sg.wgpu.rpass_enc, 0, WGPUIndexFormat_Undefined, 0, 0);
  15019. */
  15020. }
  15021. _sg_stats_add(wgpu.bindings.num_set_index_buffer, 1);
  15022. } else {
  15023. _sg_stats_add(wgpu.bindings.num_skip_redundant_index_buffer, 1);
  15024. }
  15025. return true;
  15026. }
  15027. _SOKOL_PRIVATE bool _sg_wgpu_apply_vertex_buffers(_sg_bindings_ptrs_t* bnd) {
  15028. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  15029. for (uint32_t slot = 0; slot < SG_MAX_VERTEXBUFFER_BINDSLOTS; slot++) {
  15030. const _sg_buffer_t* vb = bnd->vbs[slot];
  15031. const uint64_t offset = (uint64_t)bnd->vb_offsets[slot];
  15032. if (_sg_wgpu_bindings_cache_vb_dirty(slot, vb, offset)) {
  15033. _sg_wgpu_bindings_cache_vb_update(slot, vb, offset);
  15034. if (vb) {
  15035. const uint64_t buf_size = (uint64_t)vb->cmn.size;
  15036. SOKOL_ASSERT(buf_size > offset);
  15037. const uint64_t max_bytes = buf_size - offset;
  15038. wgpuRenderPassEncoderSetVertexBuffer(_sg.wgpu.rpass_enc, slot, vb->wgpu.buf, offset, max_bytes);
  15039. /* FIXME: the else-pass should actually set a null vertex buffer, but that doesn't seem to work yet
  15040. } else {
  15041. wgpuRenderPassEncoderSetVertexBuffer(_sg.wgpu.rpass_enc, slot, 0, 0, 0);
  15042. */
  15043. }
  15044. _sg_stats_add(wgpu.bindings.num_set_vertex_buffer, 1);
  15045. } else {
  15046. _sg_stats_add(wgpu.bindings.num_skip_redundant_vertex_buffer, 1);
  15047. }
  15048. }
  15049. return true;
  15050. }
  15051. _SOKOL_PRIVATE void _sg_wgpu_setup_backend(const sg_desc* desc) {
  15052. SOKOL_ASSERT(desc);
  15053. SOKOL_ASSERT(desc->environment.wgpu.device);
  15054. SOKOL_ASSERT(desc->uniform_buffer_size > 0);
  15055. _sg.backend = SG_BACKEND_WGPU;
  15056. _sg.wgpu.valid = true;
  15057. _sg.wgpu.dev = (WGPUDevice) desc->environment.wgpu.device;
  15058. _sg.wgpu.queue = wgpuDeviceGetQueue(_sg.wgpu.dev);
  15059. SOKOL_ASSERT(_sg.wgpu.queue);
  15060. _sg_wgpu_init_caps();
  15061. _sg_wgpu_uniform_buffer_init(desc);
  15062. _sg_wgpu_bindgroups_pool_init(desc);
  15063. _sg_wgpu_bindgroups_cache_init(desc);
  15064. _sg_wgpu_bindings_cache_clear();
  15065. // create an empty bind group
  15066. WGPUBindGroupLayoutDescriptor bgl_desc;
  15067. _sg_clear(&bgl_desc, sizeof(bgl_desc));
  15068. WGPUBindGroupLayout empty_bgl = wgpuDeviceCreateBindGroupLayout(_sg.wgpu.dev, &bgl_desc);
  15069. SOKOL_ASSERT(empty_bgl);
  15070. WGPUBindGroupDescriptor bg_desc;
  15071. _sg_clear(&bg_desc, sizeof(bg_desc));
  15072. bg_desc.layout = empty_bgl;
  15073. _sg.wgpu.empty_bind_group = wgpuDeviceCreateBindGroup(_sg.wgpu.dev, &bg_desc);
  15074. SOKOL_ASSERT(_sg.wgpu.empty_bind_group);
  15075. wgpuBindGroupLayoutRelease(empty_bgl);
  15076. // create initial per-frame command encoder
  15077. WGPUCommandEncoderDescriptor cmd_enc_desc;
  15078. _sg_clear(&cmd_enc_desc, sizeof(cmd_enc_desc));
  15079. _sg.wgpu.cmd_enc = wgpuDeviceCreateCommandEncoder(_sg.wgpu.dev, &cmd_enc_desc);
  15080. SOKOL_ASSERT(_sg.wgpu.cmd_enc);
  15081. }
  15082. _SOKOL_PRIVATE void _sg_wgpu_discard_backend(void) {
  15083. SOKOL_ASSERT(_sg.wgpu.valid);
  15084. SOKOL_ASSERT(_sg.wgpu.cmd_enc);
  15085. _sg.wgpu.valid = false;
  15086. _sg_wgpu_discard_all_bindgroups();
  15087. _sg_wgpu_bindgroups_cache_discard();
  15088. _sg_wgpu_bindgroups_pool_discard();
  15089. _sg_wgpu_uniform_buffer_discard();
  15090. wgpuBindGroupRelease(_sg.wgpu.empty_bind_group); _sg.wgpu.empty_bind_group = 0;
  15091. wgpuCommandEncoderRelease(_sg.wgpu.cmd_enc); _sg.wgpu.cmd_enc = 0;
  15092. wgpuQueueRelease(_sg.wgpu.queue); _sg.wgpu.queue = 0;
  15093. }
  15094. _SOKOL_PRIVATE void _sg_wgpu_reset_state_cache(void) {
  15095. _sg_wgpu_bindings_cache_clear();
  15096. }
  15097. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  15098. SOKOL_ASSERT(buf && desc);
  15099. SOKOL_ASSERT(buf->cmn.size > 0);
  15100. const bool injected = (0 != desc->wgpu_buffer);
  15101. if (injected) {
  15102. buf->wgpu.buf = (WGPUBuffer) desc->wgpu_buffer;
  15103. wgpuBufferAddRef(buf->wgpu.buf);
  15104. } else {
  15105. // buffer mapping size must be multiple of 4, so round up buffer size (only a problem
  15106. // with index buffers containing odd number of indices)
  15107. const uint64_t wgpu_buf_size = _sg_roundup_u64((uint64_t)buf->cmn.size, 4);
  15108. const bool map_at_creation = buf->cmn.usage.immutable && (desc->data.ptr);
  15109. WGPUBufferDescriptor wgpu_buf_desc;
  15110. _sg_clear(&wgpu_buf_desc, sizeof(wgpu_buf_desc));
  15111. wgpu_buf_desc.usage = _sg_wgpu_buffer_usage(&buf->cmn.usage);
  15112. wgpu_buf_desc.size = wgpu_buf_size;
  15113. wgpu_buf_desc.mappedAtCreation = map_at_creation;
  15114. wgpu_buf_desc.label = _sg_wgpu_stringview(desc->label);
  15115. buf->wgpu.buf = wgpuDeviceCreateBuffer(_sg.wgpu.dev, &wgpu_buf_desc);
  15116. if (0 == buf->wgpu.buf) {
  15117. _SG_ERROR(WGPU_CREATE_BUFFER_FAILED);
  15118. return SG_RESOURCESTATE_FAILED;
  15119. }
  15120. // NOTE: assume that WebGPU creates zero-initialized buffers
  15121. if (map_at_creation) {
  15122. SOKOL_ASSERT(desc->data.ptr && (desc->data.size > 0));
  15123. SOKOL_ASSERT(desc->data.size <= (size_t)buf->cmn.size);
  15124. // FIXME: inefficient on WASM
  15125. void* ptr = wgpuBufferGetMappedRange(buf->wgpu.buf, 0, wgpu_buf_size);
  15126. SOKOL_ASSERT(ptr);
  15127. memcpy(ptr, desc->data.ptr, desc->data.size);
  15128. wgpuBufferUnmap(buf->wgpu.buf);
  15129. }
  15130. }
  15131. return SG_RESOURCESTATE_VALID;
  15132. }
  15133. _SOKOL_PRIVATE void _sg_wgpu_discard_buffer(_sg_buffer_t* buf) {
  15134. SOKOL_ASSERT(buf);
  15135. if (buf->cmn.usage.storage_buffer) {
  15136. _sg_wgpu_bindgroups_cache_invalidate(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_STORAGEBUFFER, &buf->slot);
  15137. }
  15138. if (buf->wgpu.buf) {
  15139. wgpuBufferRelease(buf->wgpu.buf);
  15140. }
  15141. }
  15142. _SOKOL_PRIVATE void _sg_wgpu_copy_buffer_data(const _sg_buffer_t* buf, uint64_t offset, const sg_range* data) {
  15143. SOKOL_ASSERT((offset + data->size) <= (size_t)buf->cmn.size);
  15144. // WebGPU's write-buffer requires the size to be a multiple of four, so we may need to split the copy
  15145. // operation into two writeBuffer calls
  15146. uint64_t clamped_size = data->size & ~3UL;
  15147. uint64_t extra_size = data->size & 3UL;
  15148. SOKOL_ASSERT(extra_size < 4);
  15149. wgpuQueueWriteBuffer(_sg.wgpu.queue, buf->wgpu.buf, offset, data->ptr, clamped_size);
  15150. if (extra_size > 0) {
  15151. const uint64_t extra_src_offset = clamped_size;
  15152. const uint64_t extra_dst_offset = offset + clamped_size;
  15153. uint8_t extra_data[4] = { 0 };
  15154. uint8_t* extra_src_ptr = ((uint8_t*)data->ptr) + extra_src_offset;
  15155. for (size_t i = 0; i < extra_size; i++) {
  15156. extra_data[i] = extra_src_ptr[i];
  15157. }
  15158. wgpuQueueWriteBuffer(_sg.wgpu.queue, buf->wgpu.buf, extra_dst_offset, extra_src_ptr, 4);
  15159. }
  15160. }
  15161. _SOKOL_PRIVATE void _sg_wgpu_copy_image_data(const _sg_image_t* img, WGPUTexture wgpu_tex, const sg_image_data* data) {
  15162. WGPUTexelCopyBufferLayout wgpu_layout;
  15163. _sg_clear(&wgpu_layout, sizeof(wgpu_layout));
  15164. WGPUTexelCopyTextureInfo wgpu_copy_tex;
  15165. _sg_clear(&wgpu_copy_tex, sizeof(wgpu_copy_tex));
  15166. wgpu_copy_tex.texture = wgpu_tex;
  15167. wgpu_copy_tex.aspect = WGPUTextureAspect_All;
  15168. WGPUExtent3D wgpu_extent;
  15169. _sg_clear(&wgpu_extent, sizeof(wgpu_extent));
  15170. const int num_faces = (img->cmn.type == SG_IMAGETYPE_CUBE) ? 6 : 1;
  15171. for (int face_index = 0; face_index < num_faces; face_index++) {
  15172. for (int mip_index = 0; mip_index < img->cmn.num_mipmaps; mip_index++) {
  15173. wgpu_copy_tex.mipLevel = (uint32_t)mip_index;
  15174. wgpu_copy_tex.origin.z = (uint32_t)face_index;
  15175. int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  15176. int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  15177. int mip_slices;
  15178. switch (img->cmn.type) {
  15179. case SG_IMAGETYPE_CUBE:
  15180. mip_slices = 1;
  15181. break;
  15182. case SG_IMAGETYPE_3D:
  15183. mip_slices = _sg_miplevel_dim(img->cmn.num_slices, mip_index);
  15184. break;
  15185. default:
  15186. mip_slices = img->cmn.num_slices;
  15187. break;
  15188. }
  15189. const int row_pitch = _sg_row_pitch(img->cmn.pixel_format, mip_width, 1);
  15190. const int num_rows = _sg_num_rows(img->cmn.pixel_format, mip_height);
  15191. if (_sg_is_compressed_pixel_format(img->cmn.pixel_format)) {
  15192. mip_width = _sg_roundup(mip_width, 4);
  15193. mip_height = _sg_roundup(mip_height, 4);
  15194. }
  15195. wgpu_layout.offset = 0;
  15196. wgpu_layout.bytesPerRow = (uint32_t)row_pitch;
  15197. wgpu_layout.rowsPerImage = (uint32_t)num_rows;
  15198. wgpu_extent.width = (uint32_t)mip_width;
  15199. wgpu_extent.height = (uint32_t)mip_height;
  15200. wgpu_extent.depthOrArrayLayers = (uint32_t)mip_slices;
  15201. const sg_range* mip_data = &data->subimage[face_index][mip_index];
  15202. wgpuQueueWriteTexture(_sg.wgpu.queue, &wgpu_copy_tex, mip_data->ptr, mip_data->size, &wgpu_layout, &wgpu_extent);
  15203. }
  15204. }
  15205. }
  15206. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  15207. SOKOL_ASSERT(img && desc);
  15208. const bool injected = (0 != desc->wgpu_texture);
  15209. if (injected) {
  15210. img->wgpu.tex = (WGPUTexture)desc->wgpu_texture;
  15211. wgpuTextureAddRef(img->wgpu.tex);
  15212. img->wgpu.view = (WGPUTextureView)desc->wgpu_texture_view;
  15213. if (img->wgpu.view) {
  15214. wgpuTextureViewAddRef(img->wgpu.view);
  15215. }
  15216. } else {
  15217. WGPUTextureDescriptor wgpu_tex_desc;
  15218. _sg_clear(&wgpu_tex_desc, sizeof(wgpu_tex_desc));
  15219. wgpu_tex_desc.label = _sg_wgpu_stringview(desc->label);
  15220. wgpu_tex_desc.usage = WGPUTextureUsage_TextureBinding|WGPUTextureUsage_CopyDst;
  15221. if (desc->usage.render_attachment) {
  15222. wgpu_tex_desc.usage |= WGPUTextureUsage_RenderAttachment;
  15223. }
  15224. if (desc->usage.storage_attachment) {
  15225. wgpu_tex_desc.usage |= WGPUTextureUsage_StorageBinding;
  15226. }
  15227. wgpu_tex_desc.dimension = _sg_wgpu_texture_dimension(img->cmn.type);
  15228. wgpu_tex_desc.size.width = (uint32_t) img->cmn.width;
  15229. wgpu_tex_desc.size.height = (uint32_t) img->cmn.height;
  15230. if (desc->type == SG_IMAGETYPE_CUBE) {
  15231. wgpu_tex_desc.size.depthOrArrayLayers = 6;
  15232. } else {
  15233. wgpu_tex_desc.size.depthOrArrayLayers = (uint32_t) img->cmn.num_slices;
  15234. }
  15235. wgpu_tex_desc.format = _sg_wgpu_textureformat(img->cmn.pixel_format);
  15236. wgpu_tex_desc.mipLevelCount = (uint32_t) img->cmn.num_mipmaps;
  15237. wgpu_tex_desc.sampleCount = (uint32_t) img->cmn.sample_count;
  15238. img->wgpu.tex = wgpuDeviceCreateTexture(_sg.wgpu.dev, &wgpu_tex_desc);
  15239. if (0 == img->wgpu.tex) {
  15240. _SG_ERROR(WGPU_CREATE_TEXTURE_FAILED);
  15241. return SG_RESOURCESTATE_FAILED;
  15242. }
  15243. if (desc->data.subimage[0][0].ptr) {
  15244. _sg_wgpu_copy_image_data(img, img->wgpu.tex, &desc->data);
  15245. }
  15246. WGPUTextureViewDescriptor wgpu_texview_desc;
  15247. _sg_clear(&wgpu_texview_desc, sizeof(wgpu_texview_desc));
  15248. wgpu_texview_desc.label = _sg_wgpu_stringview(desc->label);
  15249. wgpu_texview_desc.dimension = _sg_wgpu_texture_view_dimension(img->cmn.type);
  15250. wgpu_texview_desc.mipLevelCount = (uint32_t)img->cmn.num_mipmaps;
  15251. if (img->cmn.type == SG_IMAGETYPE_CUBE) {
  15252. wgpu_texview_desc.arrayLayerCount = 6;
  15253. } else if (img->cmn.type == SG_IMAGETYPE_ARRAY) {
  15254. wgpu_texview_desc.arrayLayerCount = (uint32_t)img->cmn.num_slices;
  15255. } else {
  15256. wgpu_texview_desc.arrayLayerCount = 1;
  15257. }
  15258. if (_sg_is_depth_or_depth_stencil_format(img->cmn.pixel_format)) {
  15259. wgpu_texview_desc.aspect = WGPUTextureAspect_DepthOnly;
  15260. } else {
  15261. wgpu_texview_desc.aspect = WGPUTextureAspect_All;
  15262. }
  15263. img->wgpu.view = wgpuTextureCreateView(img->wgpu.tex, &wgpu_texview_desc);
  15264. if (0 == img->wgpu.view) {
  15265. _SG_ERROR(WGPU_CREATE_TEXTURE_VIEW_FAILED);
  15266. return SG_RESOURCESTATE_FAILED;
  15267. }
  15268. }
  15269. return SG_RESOURCESTATE_VALID;
  15270. }
  15271. _SOKOL_PRIVATE void _sg_wgpu_discard_image(_sg_image_t* img) {
  15272. SOKOL_ASSERT(img);
  15273. _sg_wgpu_bindgroups_cache_invalidate(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_IMAGE, &img->slot);
  15274. if (img->wgpu.view) {
  15275. wgpuTextureViewRelease(img->wgpu.view);
  15276. img->wgpu.view = 0;
  15277. }
  15278. if (img->wgpu.tex) {
  15279. wgpuTextureRelease(img->wgpu.tex);
  15280. img->wgpu.tex = 0;
  15281. }
  15282. }
  15283. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  15284. SOKOL_ASSERT(smp && desc);
  15285. SOKOL_ASSERT(_sg.wgpu.dev);
  15286. const bool injected = (0 != desc->wgpu_sampler);
  15287. if (injected) {
  15288. smp->wgpu.smp = (WGPUSampler) desc->wgpu_sampler;
  15289. wgpuSamplerAddRef(smp->wgpu.smp);
  15290. } else {
  15291. WGPUSamplerDescriptor wgpu_desc;
  15292. _sg_clear(&wgpu_desc, sizeof(wgpu_desc));
  15293. wgpu_desc.label = _sg_wgpu_stringview(desc->label);
  15294. wgpu_desc.addressModeU = _sg_wgpu_sampler_address_mode(desc->wrap_u);
  15295. wgpu_desc.addressModeV = _sg_wgpu_sampler_address_mode(desc->wrap_v);
  15296. wgpu_desc.addressModeW = _sg_wgpu_sampler_address_mode(desc->wrap_w);
  15297. wgpu_desc.magFilter = _sg_wgpu_sampler_minmag_filter(desc->mag_filter);
  15298. wgpu_desc.minFilter = _sg_wgpu_sampler_minmag_filter(desc->min_filter);
  15299. wgpu_desc.mipmapFilter = _sg_wgpu_sampler_mipmap_filter(desc->mipmap_filter);
  15300. wgpu_desc.lodMinClamp = desc->min_lod;
  15301. wgpu_desc.lodMaxClamp = desc->max_lod;
  15302. wgpu_desc.compare = _sg_wgpu_comparefunc(desc->compare);
  15303. if (wgpu_desc.compare == WGPUCompareFunction_Never) {
  15304. wgpu_desc.compare = WGPUCompareFunction_Undefined;
  15305. }
  15306. wgpu_desc.maxAnisotropy = (uint16_t)desc->max_anisotropy;
  15307. smp->wgpu.smp = wgpuDeviceCreateSampler(_sg.wgpu.dev, &wgpu_desc);
  15308. if (0 == smp->wgpu.smp) {
  15309. _SG_ERROR(WGPU_CREATE_SAMPLER_FAILED);
  15310. return SG_RESOURCESTATE_FAILED;
  15311. }
  15312. }
  15313. return SG_RESOURCESTATE_VALID;
  15314. }
  15315. _SOKOL_PRIVATE void _sg_wgpu_discard_sampler(_sg_sampler_t* smp) {
  15316. SOKOL_ASSERT(smp);
  15317. _sg_wgpu_bindgroups_cache_invalidate(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_SAMPLER, &smp->slot);
  15318. if (smp->wgpu.smp) {
  15319. wgpuSamplerRelease(smp->wgpu.smp);
  15320. smp->wgpu.smp = 0;
  15321. }
  15322. }
  15323. _SOKOL_PRIVATE _sg_wgpu_shader_func_t _sg_wgpu_create_shader_func(const sg_shader_function* func, const char* label) {
  15324. SOKOL_ASSERT(func);
  15325. SOKOL_ASSERT(func->source);
  15326. SOKOL_ASSERT(func->entry);
  15327. _sg_wgpu_shader_func_t res;
  15328. _sg_clear(&res, sizeof(res));
  15329. _sg_strcpy(&res.entry, func->entry);
  15330. WGPUShaderModuleWGSLDescriptor wgpu_shdmod_wgsl_desc;
  15331. _sg_clear(&wgpu_shdmod_wgsl_desc, sizeof(wgpu_shdmod_wgsl_desc));
  15332. wgpu_shdmod_wgsl_desc.chain.sType = WGPUSType_ShaderSourceWGSL;
  15333. wgpu_shdmod_wgsl_desc.code = _sg_wgpu_stringview(func->source);
  15334. WGPUShaderModuleDescriptor wgpu_shdmod_desc;
  15335. _sg_clear(&wgpu_shdmod_desc, sizeof(wgpu_shdmod_desc));
  15336. wgpu_shdmod_desc.nextInChain = &wgpu_shdmod_wgsl_desc.chain;
  15337. wgpu_shdmod_desc.label = _sg_wgpu_stringview(label);
  15338. // NOTE: if compilation fails we won't actually find out in this call since
  15339. // it always returns a valid module handle, and the GetCompilationInfo() call
  15340. // is asynchronous
  15341. res.module = wgpuDeviceCreateShaderModule(_sg.wgpu.dev, &wgpu_shdmod_desc);
  15342. if (0 == res.module) {
  15343. _SG_ERROR(WGPU_CREATE_SHADER_MODULE_FAILED);
  15344. }
  15345. return res;
  15346. }
  15347. _SOKOL_PRIVATE void _sg_wgpu_discard_shader_func(_sg_wgpu_shader_func_t* func) {
  15348. if (func->module) {
  15349. wgpuShaderModuleRelease(func->module);
  15350. func->module = 0;
  15351. }
  15352. }
  15353. typedef struct { uint8_t sokol_slot, wgpu_slot; } _sg_wgpu_dynoffset_mapping_t;
  15354. _SOKOL_PRIVATE int _sg_wgpu_dynoffset_cmp(const void* a, const void* b) {
  15355. const _sg_wgpu_dynoffset_mapping_t* aa = (const _sg_wgpu_dynoffset_mapping_t*)a;
  15356. const _sg_wgpu_dynoffset_mapping_t* bb = (const _sg_wgpu_dynoffset_mapping_t*)b;
  15357. if (aa->wgpu_slot < bb->wgpu_slot) return -1;
  15358. else if (aa->wgpu_slot > bb->wgpu_slot) return 1;
  15359. return 0;
  15360. }
  15361. // NOTE: this is an out-of-range check for WGSL bindslots that's also active in release mode
  15362. _SOKOL_PRIVATE bool _sg_wgpu_ensure_wgsl_bindslot_ranges(const sg_shader_desc* desc) {
  15363. SOKOL_ASSERT(desc);
  15364. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  15365. if (desc->uniform_blocks[i].wgsl_group0_binding_n >= _SG_WGPU_MAX_UB_BINDGROUP_BIND_SLOTS) {
  15366. _SG_ERROR(WGPU_UNIFORMBLOCK_WGSL_GROUP0_BINDING_OUT_OF_RANGE);
  15367. return false;
  15368. }
  15369. }
  15370. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  15371. if (desc->storage_buffers[i].wgsl_group1_binding_n >= _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS) {
  15372. _SG_ERROR(WGPU_STORAGEBUFFER_WGSL_GROUP1_BINDING_OUT_OF_RANGE);
  15373. return false;
  15374. }
  15375. }
  15376. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  15377. if (desc->images[i].wgsl_group1_binding_n >= _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS) {
  15378. _SG_ERROR(WGPU_IMAGE_WGSL_GROUP1_BINDING_OUT_OF_RANGE);
  15379. return false;
  15380. }
  15381. }
  15382. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  15383. if (desc->samplers[i].wgsl_group1_binding_n >= _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS) {
  15384. _SG_ERROR(WGPU_SAMPLER_WGSL_GROUP1_BINDING_OUT_OF_RANGE);
  15385. return false;
  15386. }
  15387. }
  15388. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  15389. if (desc->storage_images[i].wgsl_group2_binding_n >= _SG_WGPU_MAX_SIMG_BIND_SLOTS) {
  15390. _SG_ERROR(WGPU_STORAGEIMAGE_WGSL_GROUP2_BINDING_OUT_OF_RANGE);
  15391. }
  15392. }
  15393. return true;
  15394. }
  15395. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  15396. SOKOL_ASSERT(shd && desc);
  15397. SOKOL_ASSERT(shd->wgpu.vertex_func.module == 0);
  15398. SOKOL_ASSERT(shd->wgpu.fragment_func.module == 0);
  15399. SOKOL_ASSERT(shd->wgpu.compute_func.module == 0);
  15400. SOKOL_ASSERT(shd->wgpu.bgl_ub == 0);
  15401. SOKOL_ASSERT(shd->wgpu.bg_ub == 0);
  15402. SOKOL_ASSERT(shd->wgpu.bgl_img_smp_sbuf == 0);
  15403. // do a release-mode bounds-check on wgsl bindslots, even though out-of-range
  15404. // bindslots can't cause out-of-bounds accesses in the wgpu backend, this
  15405. // is done to be consistent with the other backends
  15406. if (!_sg_wgpu_ensure_wgsl_bindslot_ranges(desc)) {
  15407. return SG_RESOURCESTATE_FAILED;
  15408. }
  15409. // build shader modules
  15410. bool shd_valid = true;
  15411. if (desc->vertex_func.source) {
  15412. shd->wgpu.vertex_func = _sg_wgpu_create_shader_func(&desc->vertex_func, desc->label);
  15413. shd_valid &= shd->wgpu.vertex_func.module != 0;
  15414. }
  15415. if (desc->fragment_func.source) {
  15416. shd->wgpu.fragment_func = _sg_wgpu_create_shader_func(&desc->fragment_func, desc->label);
  15417. shd_valid &= shd->wgpu.fragment_func.module != 0;
  15418. }
  15419. if (desc->compute_func.source) {
  15420. shd->wgpu.compute_func = _sg_wgpu_create_shader_func(&desc->compute_func, desc->label);
  15421. shd_valid &= shd->wgpu.compute_func.module != 0;
  15422. }
  15423. if (!shd_valid) {
  15424. _sg_wgpu_discard_shader_func(&shd->wgpu.vertex_func);
  15425. _sg_wgpu_discard_shader_func(&shd->wgpu.fragment_func);
  15426. _sg_wgpu_discard_shader_func(&shd->wgpu.compute_func);
  15427. return SG_RESOURCESTATE_FAILED;
  15428. }
  15429. // create bind group layout and bind group for uniform blocks
  15430. // NOTE also need to create a mapping of sokol ub bind slots to array indices
  15431. // for the dynamic offsets array in the setBindGroup call
  15432. SOKOL_ASSERT(_SG_WGPU_MAX_UB_BINDGROUP_ENTRIES <= _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES);
  15433. SOKOL_ASSERT(_SG_WGPU_MAX_SIMG_BINDGROUP_ENTRIES <= _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES);
  15434. WGPUBindGroupLayoutEntry bgl_entries[_SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES];
  15435. _sg_clear(bgl_entries, sizeof(bgl_entries));
  15436. WGPUBindGroupLayoutDescriptor bgl_desc;
  15437. _sg_clear(&bgl_desc, sizeof(bgl_desc));
  15438. WGPUBindGroupEntry bg_entries[_SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES];
  15439. _sg_clear(&bg_entries, sizeof(bg_entries));
  15440. WGPUBindGroupDescriptor bg_desc;
  15441. _sg_clear(&bg_desc, sizeof(bg_desc));
  15442. _sg_wgpu_dynoffset_mapping_t dynoffset_map[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  15443. _sg_clear(dynoffset_map, sizeof(dynoffset_map));
  15444. size_t bgl_index = 0;
  15445. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  15446. if (shd->cmn.uniform_blocks[i].stage == SG_SHADERSTAGE_NONE) {
  15447. continue;
  15448. }
  15449. shd->wgpu.ub_grp0_bnd_n[i] = desc->uniform_blocks[i].wgsl_group0_binding_n;
  15450. WGPUBindGroupEntry* bg_entry = &bg_entries[bgl_index];
  15451. WGPUBindGroupLayoutEntry* bgl_entry = &bgl_entries[bgl_index];
  15452. bgl_entry->binding = shd->wgpu.ub_grp0_bnd_n[i];
  15453. bgl_entry->visibility = _sg_wgpu_shader_stage(shd->cmn.uniform_blocks[i].stage);
  15454. bgl_entry->buffer.type = WGPUBufferBindingType_Uniform;
  15455. bgl_entry->buffer.hasDynamicOffset = true;
  15456. bg_entry->binding = bgl_entry->binding;
  15457. bg_entry->buffer = _sg.wgpu.uniform.buf;
  15458. bg_entry->size = _SG_WGPU_MAX_UNIFORM_UPDATE_SIZE;
  15459. dynoffset_map[i].sokol_slot = i;
  15460. dynoffset_map[i].wgpu_slot = bgl_entry->binding;
  15461. bgl_index += 1;
  15462. }
  15463. bgl_desc.entryCount = bgl_index;
  15464. bgl_desc.entries = bgl_entries;
  15465. shd->wgpu.bgl_ub = wgpuDeviceCreateBindGroupLayout(_sg.wgpu.dev, &bgl_desc);
  15466. SOKOL_ASSERT(shd->wgpu.bgl_ub);
  15467. bg_desc.layout = shd->wgpu.bgl_ub;
  15468. bg_desc.entryCount = bgl_index;
  15469. bg_desc.entries = bg_entries;
  15470. shd->wgpu.bg_ub = wgpuDeviceCreateBindGroup(_sg.wgpu.dev, &bg_desc);
  15471. SOKOL_ASSERT(shd->wgpu.bg_ub);
  15472. // sort the dynoffset_map by wgpu bindings, this is because the
  15473. // dynamic offsets of the WebGPU setBindGroup call must be in
  15474. // 'binding order', not 'bindgroup entry order'
  15475. qsort(dynoffset_map, bgl_index, sizeof(_sg_wgpu_dynoffset_mapping_t), _sg_wgpu_dynoffset_cmp);
  15476. shd->wgpu.ub_num_dynoffsets = bgl_index;
  15477. for (uint8_t i = 0; i < bgl_index; i++) {
  15478. const uint8_t sokol_slot = dynoffset_map[i].sokol_slot;
  15479. shd->wgpu.ub_dynoffsets[sokol_slot] = i;
  15480. }
  15481. // create bind group layout for images, samplers and storage buffers
  15482. _sg_clear(bgl_entries, sizeof(bgl_entries));
  15483. _sg_clear(&bgl_desc, sizeof(bgl_desc));
  15484. bgl_index = 0;
  15485. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  15486. if (shd->cmn.images[i].stage == SG_SHADERSTAGE_NONE) {
  15487. continue;
  15488. }
  15489. const bool msaa = shd->cmn.images[i].multisampled;
  15490. shd->wgpu.img_grp1_bnd_n[i] = desc->images[i].wgsl_group1_binding_n;
  15491. WGPUBindGroupLayoutEntry* bgl_entry = &bgl_entries[bgl_index];
  15492. bgl_entry->binding = shd->wgpu.img_grp1_bnd_n[i];
  15493. bgl_entry->visibility = _sg_wgpu_shader_stage(shd->cmn.images[i].stage);
  15494. bgl_entry->texture.viewDimension = _sg_wgpu_texture_view_dimension(shd->cmn.images[i].image_type);
  15495. bgl_entry->texture.sampleType = _sg_wgpu_texture_sample_type(shd->cmn.images[i].sample_type, msaa);
  15496. bgl_entry->texture.multisampled = msaa;
  15497. bgl_index += 1;
  15498. }
  15499. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  15500. if (shd->cmn.samplers[i].stage == SG_SHADERSTAGE_NONE) {
  15501. continue;
  15502. }
  15503. shd->wgpu.smp_grp1_bnd_n[i] = desc->samplers[i].wgsl_group1_binding_n;
  15504. WGPUBindGroupLayoutEntry* bgl_entry = &bgl_entries[bgl_index];
  15505. bgl_entry->binding = shd->wgpu.smp_grp1_bnd_n[i];
  15506. bgl_entry->visibility = _sg_wgpu_shader_stage(shd->cmn.samplers[i].stage);
  15507. bgl_entry->sampler.type = _sg_wgpu_sampler_binding_type(shd->cmn.samplers[i].sampler_type);
  15508. bgl_index += 1;
  15509. }
  15510. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  15511. if (shd->cmn.storage_buffers[i].stage == SG_SHADERSTAGE_NONE) {
  15512. continue;
  15513. }
  15514. shd->wgpu.sbuf_grp1_bnd_n[i] = desc->storage_buffers[i].wgsl_group1_binding_n;
  15515. WGPUBindGroupLayoutEntry* bgl_entry = &bgl_entries[bgl_index];
  15516. bgl_entry->binding = shd->wgpu.sbuf_grp1_bnd_n[i];
  15517. bgl_entry->visibility = _sg_wgpu_shader_stage(shd->cmn.storage_buffers[i].stage);
  15518. if (shd->cmn.storage_buffers[i].readonly) {
  15519. bgl_entry->buffer.type = WGPUBufferBindingType_ReadOnlyStorage;
  15520. } else {
  15521. bgl_entry->buffer.type = WGPUBufferBindingType_Storage;
  15522. }
  15523. bgl_index += 1;
  15524. }
  15525. bgl_desc.entryCount = bgl_index;
  15526. bgl_desc.entries = bgl_entries;
  15527. shd->wgpu.bgl_img_smp_sbuf = wgpuDeviceCreateBindGroupLayout(_sg.wgpu.dev, &bgl_desc);
  15528. if (shd->wgpu.bgl_img_smp_sbuf == 0) {
  15529. _SG_ERROR(WGPU_SHADER_CREATE_BINDGROUP_LAYOUT_FAILED);
  15530. return SG_RESOURCESTATE_FAILED;
  15531. }
  15532. // create optional bindgroup layout for storage images (separate bindgroup because
  15533. // those are not applied in sg_apply_bindings() but are defined as pass attachments)
  15534. _sg_clear(bgl_entries, sizeof(bgl_entries));
  15535. _sg_clear(&bgl_desc, sizeof(bgl_desc));
  15536. bgl_index = 0;
  15537. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  15538. if (shd->cmn.storage_images[i].stage == SG_SHADERSTAGE_NONE) {
  15539. continue;
  15540. }
  15541. shd->wgpu.simg_grp2_bnd_n[i] = desc->storage_images[i].wgsl_group2_binding_n;
  15542. WGPUBindGroupLayoutEntry* bgl_entry = &bgl_entries[bgl_index];
  15543. bgl_entry->binding = shd->wgpu.simg_grp2_bnd_n[i];
  15544. bgl_entry->visibility = _sg_wgpu_shader_stage(shd->cmn.storage_images[i].stage);
  15545. if (shd->cmn.storage_images[i].writeonly) {
  15546. bgl_entry->storageTexture.access = WGPUStorageTextureAccess_WriteOnly;
  15547. } else {
  15548. bgl_entry->storageTexture.access = WGPUStorageTextureAccess_ReadWrite;
  15549. }
  15550. bgl_entry->storageTexture.format = _sg_wgpu_textureformat(desc->storage_images[i].access_format);
  15551. bgl_entry->texture.viewDimension = _sg_wgpu_texture_view_dimension(shd->cmn.storage_images[i].image_type);
  15552. bgl_index += 1;
  15553. }
  15554. if (bgl_index > 0) {
  15555. bgl_desc.entryCount = bgl_index;
  15556. bgl_desc.entries = bgl_entries;
  15557. shd->wgpu.bgl_simg = wgpuDeviceCreateBindGroupLayout(_sg.wgpu.dev, &bgl_desc);
  15558. if (shd->wgpu.bgl_simg == 0) {
  15559. _SG_ERROR(WGPU_SHADER_CREATE_BINDGROUP_LAYOUT_FAILED);
  15560. return SG_RESOURCESTATE_FAILED;
  15561. }
  15562. }
  15563. return SG_RESOURCESTATE_VALID;
  15564. }
  15565. _SOKOL_PRIVATE void _sg_wgpu_discard_shader(_sg_shader_t* shd) {
  15566. SOKOL_ASSERT(shd);
  15567. _sg_wgpu_discard_shader_func(&shd->wgpu.vertex_func);
  15568. _sg_wgpu_discard_shader_func(&shd->wgpu.fragment_func);
  15569. _sg_wgpu_discard_shader_func(&shd->wgpu.compute_func);
  15570. if (shd->wgpu.bgl_ub) {
  15571. wgpuBindGroupLayoutRelease(shd->wgpu.bgl_ub);
  15572. shd->wgpu.bgl_ub = 0;
  15573. }
  15574. if (shd->wgpu.bg_ub) {
  15575. wgpuBindGroupRelease(shd->wgpu.bg_ub);
  15576. shd->wgpu.bg_ub = 0;
  15577. }
  15578. if (shd->wgpu.bgl_img_smp_sbuf) {
  15579. wgpuBindGroupLayoutRelease(shd->wgpu.bgl_img_smp_sbuf);
  15580. shd->wgpu.bgl_img_smp_sbuf = 0;
  15581. }
  15582. if (shd->wgpu.bgl_simg) {
  15583. wgpuBindGroupLayoutRelease(shd->wgpu.bgl_simg);
  15584. shd->wgpu.bgl_simg = 0;
  15585. }
  15586. }
  15587. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_pipeline(_sg_pipeline_t* pip, const sg_pipeline_desc* desc) {
  15588. SOKOL_ASSERT(pip && desc);
  15589. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  15590. SOKOL_ASSERT(shd->wgpu.bgl_ub);
  15591. SOKOL_ASSERT(shd->wgpu.bgl_img_smp_sbuf);
  15592. pip->wgpu.blend_color.r = (double) desc->blend_color.r;
  15593. pip->wgpu.blend_color.g = (double) desc->blend_color.g;
  15594. pip->wgpu.blend_color.b = (double) desc->blend_color.b;
  15595. pip->wgpu.blend_color.a = (double) desc->blend_color.a;
  15596. // - @group(0) for uniform blocks
  15597. // - @group(1) for all image, sampler and storagebuffer resources
  15598. // - @group(2) optional: storage image attachments in compute passes
  15599. size_t num_bgls = 2;
  15600. WGPUBindGroupLayout wgpu_bgl[_SG_WGPU_MAX_BINDGROUPS];
  15601. _sg_clear(&wgpu_bgl, sizeof(wgpu_bgl));
  15602. wgpu_bgl[_SG_WGPU_UB_BINDGROUP_INDEX ] = shd->wgpu.bgl_ub;
  15603. wgpu_bgl[_SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX] = shd->wgpu.bgl_img_smp_sbuf;
  15604. if (shd->wgpu.bgl_simg) {
  15605. wgpu_bgl[_SG_WGPU_SIMG_BINDGROUP_INDEX] = shd->wgpu.bgl_simg;
  15606. num_bgls += 1;
  15607. }
  15608. WGPUPipelineLayoutDescriptor wgpu_pl_desc;
  15609. _sg_clear(&wgpu_pl_desc, sizeof(wgpu_pl_desc));
  15610. wgpu_pl_desc.bindGroupLayoutCount = num_bgls;
  15611. wgpu_pl_desc.bindGroupLayouts = &wgpu_bgl[0];
  15612. const WGPUPipelineLayout wgpu_pip_layout = wgpuDeviceCreatePipelineLayout(_sg.wgpu.dev, &wgpu_pl_desc);
  15613. if (0 == wgpu_pip_layout) {
  15614. _SG_ERROR(WGPU_CREATE_PIPELINE_LAYOUT_FAILED);
  15615. return SG_RESOURCESTATE_FAILED;
  15616. }
  15617. SOKOL_ASSERT(wgpu_pip_layout);
  15618. if (pip->cmn.is_compute) {
  15619. WGPUComputePipelineDescriptor wgpu_pip_desc;
  15620. _sg_clear(&wgpu_pip_desc, sizeof(wgpu_pip_desc));
  15621. wgpu_pip_desc.label = _sg_wgpu_stringview(desc->label);
  15622. wgpu_pip_desc.layout = wgpu_pip_layout;
  15623. wgpu_pip_desc.compute.module = shd->wgpu.compute_func.module;
  15624. wgpu_pip_desc.compute.entryPoint = _sg_wgpu_stringview(shd->wgpu.compute_func.entry.buf);
  15625. pip->wgpu.cpip = wgpuDeviceCreateComputePipeline(_sg.wgpu.dev, &wgpu_pip_desc);
  15626. wgpuPipelineLayoutRelease(wgpu_pip_layout);
  15627. if (0 == pip->wgpu.cpip) {
  15628. _SG_ERROR(WGPU_CREATE_COMPUTE_PIPELINE_FAILED);
  15629. return SG_RESOURCESTATE_FAILED;
  15630. }
  15631. } else {
  15632. WGPUVertexBufferLayout wgpu_vb_layouts[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  15633. _sg_clear(wgpu_vb_layouts, sizeof(wgpu_vb_layouts));
  15634. WGPUVertexAttribute wgpu_vtx_attrs[SG_MAX_VERTEXBUFFER_BINDSLOTS][SG_MAX_VERTEX_ATTRIBUTES];
  15635. _sg_clear(wgpu_vtx_attrs, sizeof(wgpu_vtx_attrs));
  15636. int wgpu_vb_num = 0;
  15637. for (int vb_idx = 0; vb_idx < SG_MAX_VERTEXBUFFER_BINDSLOTS; vb_idx++, wgpu_vb_num++) {
  15638. const sg_vertex_buffer_layout_state* vbl_state = &desc->layout.buffers[vb_idx];
  15639. if (0 == vbl_state->stride) {
  15640. break;
  15641. }
  15642. wgpu_vb_layouts[vb_idx].arrayStride = (uint64_t)vbl_state->stride;
  15643. wgpu_vb_layouts[vb_idx].stepMode = _sg_wgpu_stepmode(vbl_state->step_func);
  15644. wgpu_vb_layouts[vb_idx].attributes = &wgpu_vtx_attrs[vb_idx][0];
  15645. }
  15646. for (int va_idx = 0; va_idx < SG_MAX_VERTEX_ATTRIBUTES; va_idx++) {
  15647. const sg_vertex_attr_state* va_state = &desc->layout.attrs[va_idx];
  15648. if (SG_VERTEXFORMAT_INVALID == va_state->format) {
  15649. break;
  15650. }
  15651. const int vb_idx = va_state->buffer_index;
  15652. SOKOL_ASSERT(vb_idx < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  15653. SOKOL_ASSERT(pip->cmn.vertex_buffer_layout_active[vb_idx]);
  15654. const size_t wgpu_attr_idx = wgpu_vb_layouts[vb_idx].attributeCount;
  15655. wgpu_vb_layouts[vb_idx].attributeCount += 1;
  15656. wgpu_vtx_attrs[vb_idx][wgpu_attr_idx].format = _sg_wgpu_vertexformat(va_state->format);
  15657. wgpu_vtx_attrs[vb_idx][wgpu_attr_idx].offset = (uint64_t)va_state->offset;
  15658. wgpu_vtx_attrs[vb_idx][wgpu_attr_idx].shaderLocation = (uint32_t)va_idx;
  15659. }
  15660. WGPURenderPipelineDescriptor wgpu_pip_desc;
  15661. _sg_clear(&wgpu_pip_desc, sizeof(wgpu_pip_desc));
  15662. WGPUDepthStencilState wgpu_ds_state;
  15663. _sg_clear(&wgpu_ds_state, sizeof(wgpu_ds_state));
  15664. WGPUFragmentState wgpu_frag_state;
  15665. _sg_clear(&wgpu_frag_state, sizeof(wgpu_frag_state));
  15666. WGPUColorTargetState wgpu_ctgt_state[SG_MAX_COLOR_ATTACHMENTS];
  15667. _sg_clear(&wgpu_ctgt_state, sizeof(wgpu_ctgt_state));
  15668. WGPUBlendState wgpu_blend_state[SG_MAX_COLOR_ATTACHMENTS];
  15669. _sg_clear(&wgpu_blend_state, sizeof(wgpu_blend_state));
  15670. wgpu_pip_desc.label = _sg_wgpu_stringview(desc->label);
  15671. wgpu_pip_desc.layout = wgpu_pip_layout;
  15672. wgpu_pip_desc.vertex.module = shd->wgpu.vertex_func.module;
  15673. wgpu_pip_desc.vertex.entryPoint = _sg_wgpu_stringview(shd->wgpu.vertex_func.entry.buf);
  15674. wgpu_pip_desc.vertex.bufferCount = (size_t)wgpu_vb_num;
  15675. wgpu_pip_desc.vertex.buffers = &wgpu_vb_layouts[0];
  15676. wgpu_pip_desc.primitive.topology = _sg_wgpu_topology(desc->primitive_type);
  15677. wgpu_pip_desc.primitive.stripIndexFormat = _sg_wgpu_stripindexformat(desc->primitive_type, desc->index_type);
  15678. wgpu_pip_desc.primitive.frontFace = _sg_wgpu_frontface(desc->face_winding);
  15679. wgpu_pip_desc.primitive.cullMode = _sg_wgpu_cullmode(desc->cull_mode);
  15680. if (SG_PIXELFORMAT_NONE != desc->depth.pixel_format) {
  15681. wgpu_ds_state.format = _sg_wgpu_textureformat(desc->depth.pixel_format);
  15682. wgpu_ds_state.depthWriteEnabled = _sg_wgpu_optional_bool(desc->depth.write_enabled);
  15683. wgpu_ds_state.depthCompare = _sg_wgpu_comparefunc(desc->depth.compare);
  15684. wgpu_ds_state.stencilFront.compare = _sg_wgpu_comparefunc(desc->stencil.front.compare);
  15685. wgpu_ds_state.stencilFront.failOp = _sg_wgpu_stencilop(desc->stencil.front.fail_op);
  15686. wgpu_ds_state.stencilFront.depthFailOp = _sg_wgpu_stencilop(desc->stencil.front.depth_fail_op);
  15687. wgpu_ds_state.stencilFront.passOp = _sg_wgpu_stencilop(desc->stencil.front.pass_op);
  15688. wgpu_ds_state.stencilBack.compare = _sg_wgpu_comparefunc(desc->stencil.back.compare);
  15689. wgpu_ds_state.stencilBack.failOp = _sg_wgpu_stencilop(desc->stencil.back.fail_op);
  15690. wgpu_ds_state.stencilBack.depthFailOp = _sg_wgpu_stencilop(desc->stencil.back.depth_fail_op);
  15691. wgpu_ds_state.stencilBack.passOp = _sg_wgpu_stencilop(desc->stencil.back.pass_op);
  15692. wgpu_ds_state.stencilReadMask = desc->stencil.read_mask;
  15693. wgpu_ds_state.stencilWriteMask = desc->stencil.write_mask;
  15694. wgpu_ds_state.depthBias = (int32_t)desc->depth.bias;
  15695. wgpu_ds_state.depthBiasSlopeScale = desc->depth.bias_slope_scale;
  15696. wgpu_ds_state.depthBiasClamp = desc->depth.bias_clamp;
  15697. wgpu_pip_desc.depthStencil = &wgpu_ds_state;
  15698. }
  15699. wgpu_pip_desc.multisample.count = (uint32_t)desc->sample_count;
  15700. wgpu_pip_desc.multisample.mask = 0xFFFFFFFF;
  15701. wgpu_pip_desc.multisample.alphaToCoverageEnabled = desc->alpha_to_coverage_enabled;
  15702. if (desc->color_count > 0) {
  15703. wgpu_frag_state.module = shd->wgpu.fragment_func.module;
  15704. wgpu_frag_state.entryPoint = _sg_wgpu_stringview(shd->wgpu.fragment_func.entry.buf);
  15705. wgpu_frag_state.targetCount = (size_t)desc->color_count;
  15706. wgpu_frag_state.targets = &wgpu_ctgt_state[0];
  15707. for (int i = 0; i < desc->color_count; i++) {
  15708. SOKOL_ASSERT(i < SG_MAX_COLOR_ATTACHMENTS);
  15709. wgpu_ctgt_state[i].format = _sg_wgpu_textureformat(desc->colors[i].pixel_format);
  15710. wgpu_ctgt_state[i].writeMask = _sg_wgpu_colorwritemask(desc->colors[i].write_mask);
  15711. if (desc->colors[i].blend.enabled) {
  15712. wgpu_ctgt_state[i].blend = &wgpu_blend_state[i];
  15713. wgpu_blend_state[i].color.operation = _sg_wgpu_blendop(desc->colors[i].blend.op_rgb);
  15714. wgpu_blend_state[i].color.srcFactor = _sg_wgpu_blendfactor(desc->colors[i].blend.src_factor_rgb);
  15715. wgpu_blend_state[i].color.dstFactor = _sg_wgpu_blendfactor(desc->colors[i].blend.dst_factor_rgb);
  15716. wgpu_blend_state[i].alpha.operation = _sg_wgpu_blendop(desc->colors[i].blend.op_alpha);
  15717. wgpu_blend_state[i].alpha.srcFactor = _sg_wgpu_blendfactor(desc->colors[i].blend.src_factor_alpha);
  15718. wgpu_blend_state[i].alpha.dstFactor = _sg_wgpu_blendfactor(desc->colors[i].blend.dst_factor_alpha);
  15719. }
  15720. }
  15721. wgpu_pip_desc.fragment = &wgpu_frag_state;
  15722. }
  15723. pip->wgpu.rpip = wgpuDeviceCreateRenderPipeline(_sg.wgpu.dev, &wgpu_pip_desc);
  15724. wgpuPipelineLayoutRelease(wgpu_pip_layout);
  15725. if (0 == pip->wgpu.rpip) {
  15726. _SG_ERROR(WGPU_CREATE_RENDER_PIPELINE_FAILED);
  15727. return SG_RESOURCESTATE_FAILED;
  15728. }
  15729. }
  15730. return SG_RESOURCESTATE_VALID;
  15731. }
  15732. _SOKOL_PRIVATE void _sg_wgpu_discard_pipeline(_sg_pipeline_t* pip) {
  15733. SOKOL_ASSERT(pip);
  15734. _sg_wgpu_bindgroups_cache_invalidate(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_PIPELINE, &pip->slot);
  15735. if (pip->wgpu.rpip) {
  15736. wgpuRenderPipelineRelease(pip->wgpu.rpip);
  15737. pip->wgpu.rpip = 0;
  15738. }
  15739. if (pip->wgpu.cpip) {
  15740. wgpuComputePipelineRelease(pip->wgpu.cpip);
  15741. pip->wgpu.cpip = 0;
  15742. }
  15743. }
  15744. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_attachments(_sg_attachments_t* atts, const sg_attachments_desc* desc) {
  15745. SOKOL_ASSERT(atts && desc);
  15746. // create texture views
  15747. for (int i = 0; i < atts->cmn.num_colors; i++) {
  15748. const sg_attachment_desc* color_desc = &desc->colors[i];
  15749. _sg_image_t* clr_img = _sg_image_ref_ptr(&atts->cmn.colors[i].image);
  15750. SOKOL_ASSERT(_sg_is_valid_attachment_color_format(clr_img->cmn.pixel_format));
  15751. SOKOL_ASSERT(clr_img->wgpu.tex);
  15752. WGPUTextureViewDescriptor wgpu_color_view_desc;
  15753. _sg_clear(&wgpu_color_view_desc, sizeof(wgpu_color_view_desc));
  15754. wgpu_color_view_desc.baseMipLevel = (uint32_t) color_desc->mip_level;
  15755. wgpu_color_view_desc.mipLevelCount = 1;
  15756. wgpu_color_view_desc.baseArrayLayer = (uint32_t) color_desc->slice;
  15757. wgpu_color_view_desc.arrayLayerCount = 1;
  15758. atts->wgpu.colors[i].view = wgpuTextureCreateView(clr_img->wgpu.tex, &wgpu_color_view_desc);
  15759. if (0 == atts->wgpu.colors[i].view) {
  15760. _SG_ERROR(WGPU_ATTACHMENTS_CREATE_TEXTURE_VIEW_FAILED);
  15761. return SG_RESOURCESTATE_FAILED;
  15762. }
  15763. const sg_attachment_desc* resolve_desc = &desc->resolves[i];
  15764. if (resolve_desc->image.id != SG_INVALID_ID) {
  15765. _sg_image_t* rsv_img = _sg_image_ref_ptr(&atts->cmn.resolves[i].image);
  15766. SOKOL_ASSERT(clr_img->cmn.pixel_format == rsv_img->cmn.pixel_format);
  15767. SOKOL_ASSERT(rsv_img->wgpu.tex);
  15768. WGPUTextureViewDescriptor wgpu_resolve_view_desc;
  15769. _sg_clear(&wgpu_resolve_view_desc, sizeof(wgpu_resolve_view_desc));
  15770. wgpu_resolve_view_desc.baseMipLevel = (uint32_t) resolve_desc->mip_level;
  15771. wgpu_resolve_view_desc.mipLevelCount = 1;
  15772. wgpu_resolve_view_desc.baseArrayLayer = (uint32_t) resolve_desc->slice;
  15773. wgpu_resolve_view_desc.arrayLayerCount = 1;
  15774. atts->wgpu.resolves[i].view = wgpuTextureCreateView(rsv_img->wgpu.tex, &wgpu_resolve_view_desc);
  15775. if (0 == atts->wgpu.resolves[i].view) {
  15776. _SG_ERROR(WGPU_ATTACHMENTS_CREATE_TEXTURE_VIEW_FAILED);
  15777. return SG_RESOURCESTATE_FAILED;
  15778. }
  15779. }
  15780. }
  15781. const sg_attachment_desc* ds_desc = &desc->depth_stencil;
  15782. if (ds_desc->image.id != SG_INVALID_ID) {
  15783. _sg_image_t* ds_img = _sg_image_ref_ptr(&atts->cmn.depth_stencil.image);
  15784. SOKOL_ASSERT(_sg_is_valid_attachment_depth_format(ds_img->cmn.pixel_format));
  15785. SOKOL_ASSERT(ds_img->wgpu.tex);
  15786. WGPUTextureViewDescriptor wgpu_ds_view_desc;
  15787. _sg_clear(&wgpu_ds_view_desc, sizeof(wgpu_ds_view_desc));
  15788. wgpu_ds_view_desc.baseMipLevel = (uint32_t) ds_desc->mip_level;
  15789. wgpu_ds_view_desc.mipLevelCount = 1;
  15790. wgpu_ds_view_desc.baseArrayLayer = (uint32_t) ds_desc->slice;
  15791. wgpu_ds_view_desc.arrayLayerCount = 1;
  15792. atts->wgpu.depth_stencil.view = wgpuTextureCreateView(ds_img->wgpu.tex, &wgpu_ds_view_desc);
  15793. if (0 == atts->wgpu.depth_stencil.view) {
  15794. _SG_ERROR(WGPU_ATTACHMENTS_CREATE_TEXTURE_VIEW_FAILED);
  15795. return SG_RESOURCESTATE_FAILED;
  15796. }
  15797. }
  15798. for (int i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  15799. const sg_attachment_desc* storage_desc = &desc->storages[i];
  15800. if (storage_desc->image.id != SG_INVALID_ID) {
  15801. _sg_image_t* stg_img = _sg_image_ref_ptr(&atts->cmn.storages[i].image);
  15802. SOKOL_ASSERT(_sg_is_valid_attachment_storage_format(stg_img->cmn.pixel_format));
  15803. WGPUTextureViewDescriptor wgpu_storage_view_desc;
  15804. _sg_clear(&wgpu_storage_view_desc, sizeof(wgpu_storage_view_desc));
  15805. wgpu_storage_view_desc.baseMipLevel = (uint32_t) storage_desc->mip_level;
  15806. wgpu_storage_view_desc.mipLevelCount = 1;
  15807. wgpu_storage_view_desc.baseArrayLayer = (uint32_t) storage_desc->slice;
  15808. wgpu_storage_view_desc.arrayLayerCount = 1;
  15809. if (_sg_is_depth_or_depth_stencil_format(stg_img->cmn.pixel_format)) {
  15810. wgpu_storage_view_desc.aspect = WGPUTextureAspect_DepthOnly;
  15811. } else {
  15812. wgpu_storage_view_desc.aspect = WGPUTextureAspect_All;
  15813. }
  15814. atts->wgpu.storages[i].view = wgpuTextureCreateView(stg_img->wgpu.tex, &wgpu_storage_view_desc);
  15815. if (0 == atts->wgpu.storages[i].view) {
  15816. _SG_ERROR(WGPU_ATTACHMENTS_CREATE_TEXTURE_VIEW_FAILED);
  15817. return SG_RESOURCESTATE_FAILED;
  15818. }
  15819. }
  15820. }
  15821. return SG_RESOURCESTATE_VALID;
  15822. }
  15823. _SOKOL_PRIVATE void _sg_wgpu_discard_attachments(_sg_attachments_t* atts) {
  15824. SOKOL_ASSERT(atts);
  15825. for (int i = 0; i < atts->cmn.num_colors; i++) {
  15826. if (atts->wgpu.colors[i].view) {
  15827. wgpuTextureViewRelease(atts->wgpu.colors[i].view);
  15828. atts->wgpu.colors[i].view = 0;
  15829. }
  15830. if (atts->wgpu.resolves[i].view) {
  15831. wgpuTextureViewRelease(atts->wgpu.resolves[i].view);
  15832. atts->wgpu.resolves[i].view = 0;
  15833. }
  15834. }
  15835. if (atts->wgpu.depth_stencil.view) {
  15836. wgpuTextureViewRelease(atts->wgpu.depth_stencil.view);
  15837. atts->wgpu.depth_stencil.view = 0;
  15838. }
  15839. for (int i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  15840. if (atts->wgpu.storages[i].view) {
  15841. wgpuTextureViewRelease(atts->wgpu.storages[i].view);
  15842. atts->wgpu.storages[i].view = 0;
  15843. }
  15844. }
  15845. }
  15846. _SOKOL_PRIVATE void _sg_wgpu_init_color_att(WGPURenderPassColorAttachment* wgpu_att, const sg_color_attachment_action* action, WGPUTextureView color_view, WGPUTextureView resolve_view) {
  15847. wgpu_att->depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
  15848. wgpu_att->view = color_view;
  15849. wgpu_att->resolveTarget = resolve_view;
  15850. wgpu_att->loadOp = _sg_wgpu_load_op(color_view, action->load_action);
  15851. wgpu_att->storeOp = _sg_wgpu_store_op(color_view, action->store_action);
  15852. wgpu_att->clearValue.r = action->clear_value.r;
  15853. wgpu_att->clearValue.g = action->clear_value.g;
  15854. wgpu_att->clearValue.b = action->clear_value.b;
  15855. wgpu_att->clearValue.a = action->clear_value.a;
  15856. }
  15857. _SOKOL_PRIVATE void _sg_wgpu_init_ds_att(WGPURenderPassDepthStencilAttachment* wgpu_att, const sg_pass_action* action, sg_pixel_format fmt, WGPUTextureView view) {
  15858. wgpu_att->view = view;
  15859. wgpu_att->depthLoadOp = _sg_wgpu_load_op(view, action->depth.load_action);
  15860. wgpu_att->depthStoreOp = _sg_wgpu_store_op(view, action->depth.store_action);
  15861. wgpu_att->depthClearValue = action->depth.clear_value;
  15862. wgpu_att->depthReadOnly = false;
  15863. if (_sg_is_depth_stencil_format(fmt)) {
  15864. wgpu_att->stencilLoadOp = _sg_wgpu_load_op(view, action->stencil.load_action);
  15865. wgpu_att->stencilStoreOp = _sg_wgpu_store_op(view, action->stencil.store_action);
  15866. } else {
  15867. wgpu_att->stencilLoadOp = WGPULoadOp_Undefined;
  15868. wgpu_att->stencilStoreOp = WGPUStoreOp_Undefined;
  15869. }
  15870. wgpu_att->stencilClearValue = action->stencil.clear_value;
  15871. wgpu_att->stencilReadOnly = false;
  15872. }
  15873. _SOKOL_PRIVATE void _sg_wgpu_begin_compute_pass(const sg_pass* pass) {
  15874. WGPUComputePassDescriptor wgpu_pass_desc;
  15875. _sg_clear(&wgpu_pass_desc, sizeof(wgpu_pass_desc));
  15876. wgpu_pass_desc.label = _sg_wgpu_stringview(pass->label);
  15877. _sg.wgpu.cpass_enc = wgpuCommandEncoderBeginComputePass(_sg.wgpu.cmd_enc, &wgpu_pass_desc);
  15878. SOKOL_ASSERT(_sg.wgpu.cpass_enc);
  15879. // clear initial bindings
  15880. wgpuComputePassEncoderSetBindGroup(_sg.wgpu.cpass_enc, _SG_WGPU_UB_BINDGROUP_INDEX, _sg.wgpu.empty_bind_group, 0, 0);
  15881. wgpuComputePassEncoderSetBindGroup(_sg.wgpu.cpass_enc, _SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX, _sg.wgpu.empty_bind_group, 0, 0);
  15882. wgpuComputePassEncoderSetBindGroup(_sg.wgpu.cpass_enc, _SG_WGPU_SIMG_BINDGROUP_INDEX, _sg.wgpu.empty_bind_group, 0, 0);
  15883. _sg_stats_add(wgpu.bindings.num_set_bindgroup, 1);
  15884. }
  15885. _SOKOL_PRIVATE void _sg_wgpu_begin_render_pass(const sg_pass* pass) {
  15886. const sg_swapchain* swapchain = &pass->swapchain;
  15887. const sg_pass_action* action = &pass->action;
  15888. const _sg_attachments_t* atts = _sg_attachments_ref_ptr_or_null(&_sg.cur_pass.atts);
  15889. WGPURenderPassDescriptor wgpu_pass_desc;
  15890. WGPURenderPassColorAttachment wgpu_color_att[SG_MAX_COLOR_ATTACHMENTS];
  15891. WGPURenderPassDepthStencilAttachment wgpu_ds_att;
  15892. _sg_clear(&wgpu_pass_desc, sizeof(wgpu_pass_desc));
  15893. _sg_clear(&wgpu_color_att, sizeof(wgpu_color_att));
  15894. _sg_clear(&wgpu_ds_att, sizeof(wgpu_ds_att));
  15895. wgpu_pass_desc.label = _sg_wgpu_stringview(pass->label);
  15896. if (atts) {
  15897. SOKOL_ASSERT(atts->slot.state == SG_RESOURCESTATE_VALID);
  15898. for (int i = 0; i < atts->cmn.num_colors; i++) {
  15899. _sg_wgpu_init_color_att(&wgpu_color_att[i], &action->colors[i], atts->wgpu.colors[i].view, atts->wgpu.resolves[i].view);
  15900. }
  15901. wgpu_pass_desc.colorAttachmentCount = (size_t)atts->cmn.num_colors;
  15902. wgpu_pass_desc.colorAttachments = &wgpu_color_att[0];
  15903. const _sg_image_t* ds_img = _sg_image_ref_ptr_or_null(&atts->cmn.depth_stencil.image);
  15904. if (ds_img) {
  15905. _sg_wgpu_init_ds_att(&wgpu_ds_att, action, ds_img->cmn.pixel_format, atts->wgpu.depth_stencil.view);
  15906. wgpu_pass_desc.depthStencilAttachment = &wgpu_ds_att;
  15907. }
  15908. } else {
  15909. WGPUTextureView wgpu_color_view = (WGPUTextureView) swapchain->wgpu.render_view;
  15910. WGPUTextureView wgpu_resolve_view = (WGPUTextureView) swapchain->wgpu.resolve_view;
  15911. WGPUTextureView wgpu_depth_stencil_view = (WGPUTextureView) swapchain->wgpu.depth_stencil_view;
  15912. _sg_wgpu_init_color_att(&wgpu_color_att[0], &action->colors[0], wgpu_color_view, wgpu_resolve_view);
  15913. wgpu_pass_desc.colorAttachmentCount = 1;
  15914. wgpu_pass_desc.colorAttachments = &wgpu_color_att[0];
  15915. if (wgpu_depth_stencil_view) {
  15916. SOKOL_ASSERT(swapchain->depth_format > SG_PIXELFORMAT_NONE);
  15917. _sg_wgpu_init_ds_att(&wgpu_ds_att, action, swapchain->depth_format, wgpu_depth_stencil_view);
  15918. wgpu_pass_desc.depthStencilAttachment = &wgpu_ds_att;
  15919. }
  15920. }
  15921. _sg.wgpu.rpass_enc = wgpuCommandEncoderBeginRenderPass(_sg.wgpu.cmd_enc, &wgpu_pass_desc);
  15922. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  15923. wgpuRenderPassEncoderSetBindGroup(_sg.wgpu.rpass_enc, _SG_WGPU_UB_BINDGROUP_INDEX, _sg.wgpu.empty_bind_group, 0, 0);
  15924. wgpuRenderPassEncoderSetBindGroup(_sg.wgpu.rpass_enc, _SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX, _sg.wgpu.empty_bind_group, 0, 0);
  15925. _sg_stats_add(wgpu.bindings.num_set_bindgroup, 1);
  15926. }
  15927. _SOKOL_PRIVATE void _sg_wgpu_begin_pass(const sg_pass* pass) {
  15928. SOKOL_ASSERT(pass);
  15929. SOKOL_ASSERT(_sg.wgpu.dev);
  15930. SOKOL_ASSERT(_sg.wgpu.cmd_enc);
  15931. SOKOL_ASSERT(0 == _sg.wgpu.rpass_enc);
  15932. SOKOL_ASSERT(0 == _sg.wgpu.cpass_enc);
  15933. _sg_wgpu_bindings_cache_clear();
  15934. if (pass->compute) {
  15935. _sg_wgpu_begin_compute_pass(pass);
  15936. } else {
  15937. _sg_wgpu_begin_render_pass(pass);
  15938. }
  15939. }
  15940. _SOKOL_PRIVATE void _sg_wgpu_end_pass(void) {
  15941. if (_sg.wgpu.rpass_enc) {
  15942. wgpuRenderPassEncoderEnd(_sg.wgpu.rpass_enc);
  15943. wgpuRenderPassEncoderRelease(_sg.wgpu.rpass_enc);
  15944. _sg.wgpu.rpass_enc = 0;
  15945. }
  15946. if (_sg.wgpu.cpass_enc) {
  15947. wgpuComputePassEncoderEnd(_sg.wgpu.cpass_enc);
  15948. wgpuComputePassEncoderRelease(_sg.wgpu.cpass_enc);
  15949. _sg.wgpu.cpass_enc = 0;
  15950. }
  15951. }
  15952. _SOKOL_PRIVATE void _sg_wgpu_commit(void) {
  15953. SOKOL_ASSERT(_sg.wgpu.cmd_enc);
  15954. _sg_wgpu_uniform_buffer_on_commit();
  15955. WGPUCommandBufferDescriptor cmd_buf_desc;
  15956. _sg_clear(&cmd_buf_desc, sizeof(cmd_buf_desc));
  15957. WGPUCommandBuffer wgpu_cmd_buf = wgpuCommandEncoderFinish(_sg.wgpu.cmd_enc, &cmd_buf_desc);
  15958. SOKOL_ASSERT(wgpu_cmd_buf);
  15959. wgpuCommandEncoderRelease(_sg.wgpu.cmd_enc);
  15960. _sg.wgpu.cmd_enc = 0;
  15961. wgpuQueueSubmit(_sg.wgpu.queue, 1, &wgpu_cmd_buf);
  15962. wgpuCommandBufferRelease(wgpu_cmd_buf);
  15963. // create a new render-command-encoder for next frame
  15964. WGPUCommandEncoderDescriptor cmd_enc_desc;
  15965. _sg_clear(&cmd_enc_desc, sizeof(cmd_enc_desc));
  15966. _sg.wgpu.cmd_enc = wgpuDeviceCreateCommandEncoder(_sg.wgpu.dev, &cmd_enc_desc);
  15967. }
  15968. _SOKOL_PRIVATE void _sg_wgpu_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  15969. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  15970. // FIXME FIXME FIXME: CLIPPING THE VIEWPORT HERE IS WRONG!!!
  15971. // (but currently required because WebGPU insists that the viewport rectangle must be
  15972. // fully contained inside the framebuffer, but this doesn't make any sense, and also
  15973. // isn't required by the backend APIs)
  15974. const _sg_recti_t clip = _sg_clipi(x, y, w, h, _sg.cur_pass.width, _sg.cur_pass.height);
  15975. float xf = (float) clip.x;
  15976. float yf = (float) (origin_top_left ? clip.y : (_sg.cur_pass.height - (clip.y + clip.h)));
  15977. float wf = (float) clip.w;
  15978. float hf = (float) clip.h;
  15979. wgpuRenderPassEncoderSetViewport(_sg.wgpu.rpass_enc, xf, yf, wf, hf, 0.0f, 1.0f);
  15980. }
  15981. _SOKOL_PRIVATE void _sg_wgpu_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  15982. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  15983. const _sg_recti_t clip = _sg_clipi(x, y, w, h, _sg.cur_pass.width, _sg.cur_pass.height);
  15984. uint32_t sx = (uint32_t) clip.x;
  15985. uint32_t sy = (uint32_t) (origin_top_left ? clip.y : (_sg.cur_pass.height - (clip.y + clip.h)));
  15986. uint32_t sw = (uint32_t) clip.w;
  15987. uint32_t sh = (uint32_t) clip.h;
  15988. wgpuRenderPassEncoderSetScissorRect(_sg.wgpu.rpass_enc, sx, sy, sw, sh);
  15989. }
  15990. _SOKOL_PRIVATE void _sg_wgpu_set_ub_bindgroup(const _sg_shader_t* shd) {
  15991. // NOTE: dynamic offsets must be in binding order, not in BindGroupEntry order
  15992. SOKOL_ASSERT(shd->wgpu.ub_num_dynoffsets < SG_MAX_UNIFORMBLOCK_BINDSLOTS);
  15993. uint32_t dyn_offsets[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  15994. _sg_clear(dyn_offsets, sizeof(dyn_offsets));
  15995. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  15996. if (shd->cmn.uniform_blocks[i].stage == SG_SHADERSTAGE_NONE) {
  15997. continue;
  15998. }
  15999. uint8_t dynoffset_index = shd->wgpu.ub_dynoffsets[i];
  16000. SOKOL_ASSERT(dynoffset_index < shd->wgpu.ub_num_dynoffsets);
  16001. dyn_offsets[dynoffset_index] = _sg.wgpu.uniform.bind_offsets[i];
  16002. }
  16003. if (_sg.cur_pass.is_compute) {
  16004. SOKOL_ASSERT(_sg.wgpu.cpass_enc);
  16005. wgpuComputePassEncoderSetBindGroup(_sg.wgpu.cpass_enc,
  16006. _SG_WGPU_UB_BINDGROUP_INDEX,
  16007. shd->wgpu.bg_ub,
  16008. shd->wgpu.ub_num_dynoffsets,
  16009. dyn_offsets);
  16010. } else {
  16011. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  16012. wgpuRenderPassEncoderSetBindGroup(_sg.wgpu.rpass_enc,
  16013. _SG_WGPU_UB_BINDGROUP_INDEX,
  16014. shd->wgpu.bg_ub,
  16015. shd->wgpu.ub_num_dynoffsets,
  16016. dyn_offsets);
  16017. }
  16018. }
  16019. _SOKOL_PRIVATE void _sg_wgpu_apply_pipeline(_sg_pipeline_t* pip) {
  16020. SOKOL_ASSERT(pip);
  16021. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  16022. if (pip->cmn.is_compute) {
  16023. SOKOL_ASSERT(_sg.cur_pass.is_compute);
  16024. SOKOL_ASSERT(pip->wgpu.cpip);
  16025. SOKOL_ASSERT(_sg.wgpu.cpass_enc);
  16026. wgpuComputePassEncoderSetPipeline(_sg.wgpu.cpass_enc, pip->wgpu.cpip);
  16027. // adhoc-create a storage attachment bindgroup without going through the bindgroups cache
  16028. // FIXME: the 'resource view update' will get rid of this special case because then storage images
  16029. // will be regular resource bindings
  16030. if (shd->wgpu.bgl_simg) {
  16031. _sg_stats_add(wgpu.bindings.num_create_bindgroup, 1);
  16032. SOKOL_ASSERT(shd);
  16033. WGPUBindGroupLayout bgl = shd->wgpu.bgl_simg;
  16034. WGPUBindGroupEntry bg_entries[_SG_WGPU_MAX_SIMG_BINDGROUP_ENTRIES];
  16035. _sg_clear(&bg_entries, sizeof(bg_entries));
  16036. size_t bgl_index = 0;
  16037. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  16038. if (shd->cmn.storage_images[i].stage == SG_SHADERSTAGE_NONE) {
  16039. continue;
  16040. }
  16041. _sg_attachments_t* atts = _sg_attachments_ref_ptr(&_sg.cur_pass.atts);
  16042. SOKOL_ASSERT(atts->wgpu.storages[i].view);
  16043. WGPUBindGroupEntry* bg_entry = &bg_entries[bgl_index];
  16044. bg_entry->binding = shd->wgpu.simg_grp2_bnd_n[i];
  16045. bg_entry->textureView = atts->wgpu.storages[i].view;
  16046. bgl_index++;
  16047. }
  16048. SOKOL_ASSERT(bgl_index > 0);
  16049. WGPUBindGroupDescriptor bg_desc;
  16050. _sg_clear(&bg_desc, sizeof(bg_desc));
  16051. bg_desc.layout = bgl;
  16052. bg_desc.entryCount = bgl_index;
  16053. bg_desc.entries = bg_entries;
  16054. WGPUBindGroup bg = wgpuDeviceCreateBindGroup(_sg.wgpu.dev, &bg_desc);
  16055. if (bg) {
  16056. wgpuComputePassEncoderSetBindGroup(_sg.wgpu.cpass_enc, _SG_WGPU_SIMG_BINDGROUP_INDEX, bg, 0, 0);
  16057. wgpuBindGroupRelease(bg);
  16058. } else {
  16059. _SG_ERROR(WGPU_CREATEBINDGROUP_FAILED);
  16060. }
  16061. } else {
  16062. // no storage attachment bindings, clear bindgroup slot
  16063. wgpuComputePassEncoderSetBindGroup(_sg.wgpu.cpass_enc, _SG_WGPU_SIMG_BINDGROUP_INDEX, _sg.wgpu.empty_bind_group, 0, 0);
  16064. }
  16065. } else {
  16066. SOKOL_ASSERT(!_sg.cur_pass.is_compute);
  16067. SOKOL_ASSERT(pip->wgpu.rpip);
  16068. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  16069. _sg.wgpu.use_indexed_draw = (pip->cmn.index_type != SG_INDEXTYPE_NONE);
  16070. wgpuRenderPassEncoderSetPipeline(_sg.wgpu.rpass_enc, pip->wgpu.rpip);
  16071. wgpuRenderPassEncoderSetBlendConstant(_sg.wgpu.rpass_enc, &pip->wgpu.blend_color);
  16072. wgpuRenderPassEncoderSetStencilReference(_sg.wgpu.rpass_enc, pip->cmn.stencil.ref);
  16073. }
  16074. // bind groups must be set because pipelines without uniform blocks or resource bindings
  16075. // will still create 'empty' BindGroupLayouts
  16076. _sg_wgpu_set_ub_bindgroup(shd);
  16077. _sg_wgpu_set_bindgroup(_SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX, 0); // this will set the 'empty bind group'
  16078. }
  16079. _SOKOL_PRIVATE bool _sg_wgpu_apply_bindings(_sg_bindings_ptrs_t* bnd) {
  16080. SOKOL_ASSERT(bnd);
  16081. bool retval = true;
  16082. if (!_sg.cur_pass.is_compute) {
  16083. retval &= _sg_wgpu_apply_index_buffer(bnd);
  16084. retval &= _sg_wgpu_apply_vertex_buffers(bnd);
  16085. }
  16086. retval &= _sg_wgpu_apply_bindings_bindgroup(bnd);
  16087. return retval;
  16088. }
  16089. _SOKOL_PRIVATE void _sg_wgpu_apply_uniforms(int ub_slot, const sg_range* data) {
  16090. const uint32_t alignment = _sg.wgpu.limits.minUniformBufferOffsetAlignment;
  16091. SOKOL_ASSERT(_sg.wgpu.uniform.staging);
  16092. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  16093. SOKOL_ASSERT((_sg.wgpu.uniform.offset + data->size) <= _sg.wgpu.uniform.num_bytes);
  16094. SOKOL_ASSERT((_sg.wgpu.uniform.offset & (alignment - 1)) == 0);
  16095. const _sg_pipeline_t* pip = _sg_pipeline_ref_ptr(&_sg.cur_pip);
  16096. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  16097. SOKOL_ASSERT(data->size == shd->cmn.uniform_blocks[ub_slot].size);
  16098. SOKOL_ASSERT(data->size <= _SG_WGPU_MAX_UNIFORM_UPDATE_SIZE);
  16099. _sg_stats_add(wgpu.uniforms.num_set_bindgroup, 1);
  16100. memcpy(_sg.wgpu.uniform.staging + _sg.wgpu.uniform.offset, data->ptr, data->size);
  16101. _sg.wgpu.uniform.bind_offsets[ub_slot] = _sg.wgpu.uniform.offset;
  16102. _sg.wgpu.uniform.offset = _sg_roundup_u32(_sg.wgpu.uniform.offset + (uint32_t)data->size, alignment);
  16103. _sg_wgpu_set_ub_bindgroup(shd);
  16104. }
  16105. _SOKOL_PRIVATE void _sg_wgpu_draw(int base_element, int num_elements, int num_instances) {
  16106. SOKOL_ASSERT(_sg.wgpu.rpass_enc);
  16107. const _sg_pipeline_t* pip = _sg_pipeline_ref_ptr(&_sg.cur_pip);
  16108. if (SG_INDEXTYPE_NONE != pip->cmn.index_type) {
  16109. wgpuRenderPassEncoderDrawIndexed(_sg.wgpu.rpass_enc, (uint32_t)num_elements, (uint32_t)num_instances, (uint32_t)base_element, 0, 0);
  16110. } else {
  16111. wgpuRenderPassEncoderDraw(_sg.wgpu.rpass_enc, (uint32_t)num_elements, (uint32_t)num_instances, (uint32_t)base_element, 0);
  16112. }
  16113. }
  16114. _SOKOL_PRIVATE void _sg_wgpu_dispatch(int num_groups_x, int num_groups_y, int num_groups_z) {
  16115. SOKOL_ASSERT(_sg.wgpu.cpass_enc);
  16116. wgpuComputePassEncoderDispatchWorkgroups(_sg.wgpu.cpass_enc,
  16117. (uint32_t)num_groups_x,
  16118. (uint32_t)num_groups_y,
  16119. (uint32_t)num_groups_z);
  16120. }
  16121. _SOKOL_PRIVATE void _sg_wgpu_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  16122. SOKOL_ASSERT(data && data->ptr && (data->size > 0));
  16123. SOKOL_ASSERT(buf);
  16124. _sg_wgpu_copy_buffer_data(buf, 0, data);
  16125. }
  16126. _SOKOL_PRIVATE void _sg_wgpu_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  16127. SOKOL_ASSERT(data && data->ptr && (data->size > 0));
  16128. _SOKOL_UNUSED(new_frame);
  16129. _sg_wgpu_copy_buffer_data(buf, (uint64_t)buf->cmn.append_pos, data);
  16130. }
  16131. _SOKOL_PRIVATE void _sg_wgpu_update_image(_sg_image_t* img, const sg_image_data* data) {
  16132. SOKOL_ASSERT(img && data);
  16133. _sg_wgpu_copy_image_data(img, img->wgpu.tex, data);
  16134. }
  16135. #endif
  16136. // ██████ ███████ ███ ██ ███████ ██████ ██ ██████ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  16137. // ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  16138. // ██ ███ █████ ██ ██ ██ █████ ██████ ██ ██ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  16139. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  16140. // ██████ ███████ ██ ████ ███████ ██ ██ ██ ██████ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  16141. //
  16142. // >>generic backend
  16143. static inline void _sg_setup_backend(const sg_desc* desc) {
  16144. #if defined(_SOKOL_ANY_GL)
  16145. _sg_gl_setup_backend(desc);
  16146. #elif defined(SOKOL_METAL)
  16147. _sg_mtl_setup_backend(desc);
  16148. #elif defined(SOKOL_D3D11)
  16149. _sg_d3d11_setup_backend(desc);
  16150. #elif defined(SOKOL_WGPU)
  16151. _sg_wgpu_setup_backend(desc);
  16152. #elif defined(SOKOL_DUMMY_BACKEND)
  16153. _sg_dummy_setup_backend(desc);
  16154. #else
  16155. #error("INVALID BACKEND");
  16156. #endif
  16157. }
  16158. static inline void _sg_discard_backend(void) {
  16159. #if defined(_SOKOL_ANY_GL)
  16160. _sg_gl_discard_backend();
  16161. #elif defined(SOKOL_METAL)
  16162. _sg_mtl_discard_backend();
  16163. #elif defined(SOKOL_D3D11)
  16164. _sg_d3d11_discard_backend();
  16165. #elif defined(SOKOL_WGPU)
  16166. _sg_wgpu_discard_backend();
  16167. #elif defined(SOKOL_DUMMY_BACKEND)
  16168. _sg_dummy_discard_backend();
  16169. #else
  16170. #error("INVALID BACKEND");
  16171. #endif
  16172. }
  16173. static inline void _sg_reset_state_cache(void) {
  16174. #if defined(_SOKOL_ANY_GL)
  16175. _sg_gl_reset_state_cache();
  16176. #elif defined(SOKOL_METAL)
  16177. _sg_mtl_reset_state_cache();
  16178. #elif defined(SOKOL_D3D11)
  16179. _sg_d3d11_reset_state_cache();
  16180. #elif defined(SOKOL_WGPU)
  16181. _sg_wgpu_reset_state_cache();
  16182. #elif defined(SOKOL_DUMMY_BACKEND)
  16183. _sg_dummy_reset_state_cache();
  16184. #else
  16185. #error("INVALID BACKEND");
  16186. #endif
  16187. }
  16188. static inline sg_resource_state _sg_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  16189. #if defined(_SOKOL_ANY_GL)
  16190. return _sg_gl_create_buffer(buf, desc);
  16191. #elif defined(SOKOL_METAL)
  16192. return _sg_mtl_create_buffer(buf, desc);
  16193. #elif defined(SOKOL_D3D11)
  16194. return _sg_d3d11_create_buffer(buf, desc);
  16195. #elif defined(SOKOL_WGPU)
  16196. return _sg_wgpu_create_buffer(buf, desc);
  16197. #elif defined(SOKOL_DUMMY_BACKEND)
  16198. return _sg_dummy_create_buffer(buf, desc);
  16199. #else
  16200. #error("INVALID BACKEND");
  16201. #endif
  16202. }
  16203. static inline void _sg_discard_buffer(_sg_buffer_t* buf) {
  16204. #if defined(_SOKOL_ANY_GL)
  16205. _sg_gl_discard_buffer(buf);
  16206. #elif defined(SOKOL_METAL)
  16207. _sg_mtl_discard_buffer(buf);
  16208. #elif defined(SOKOL_D3D11)
  16209. _sg_d3d11_discard_buffer(buf);
  16210. #elif defined(SOKOL_WGPU)
  16211. _sg_wgpu_discard_buffer(buf);
  16212. #elif defined(SOKOL_DUMMY_BACKEND)
  16213. _sg_dummy_discard_buffer(buf);
  16214. #else
  16215. #error("INVALID BACKEND");
  16216. #endif
  16217. }
  16218. static inline sg_resource_state _sg_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  16219. #if defined(_SOKOL_ANY_GL)
  16220. return _sg_gl_create_image(img, desc);
  16221. #elif defined(SOKOL_METAL)
  16222. return _sg_mtl_create_image(img, desc);
  16223. #elif defined(SOKOL_D3D11)
  16224. return _sg_d3d11_create_image(img, desc);
  16225. #elif defined(SOKOL_WGPU)
  16226. return _sg_wgpu_create_image(img, desc);
  16227. #elif defined(SOKOL_DUMMY_BACKEND)
  16228. return _sg_dummy_create_image(img, desc);
  16229. #else
  16230. #error("INVALID BACKEND");
  16231. #endif
  16232. }
  16233. static inline void _sg_discard_image(_sg_image_t* img) {
  16234. #if defined(_SOKOL_ANY_GL)
  16235. _sg_gl_discard_image(img);
  16236. #elif defined(SOKOL_METAL)
  16237. _sg_mtl_discard_image(img);
  16238. #elif defined(SOKOL_D3D11)
  16239. _sg_d3d11_discard_image(img);
  16240. #elif defined(SOKOL_WGPU)
  16241. _sg_wgpu_discard_image(img);
  16242. #elif defined(SOKOL_DUMMY_BACKEND)
  16243. _sg_dummy_discard_image(img);
  16244. #else
  16245. #error("INVALID BACKEND");
  16246. #endif
  16247. }
  16248. static inline sg_resource_state _sg_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  16249. #if defined(_SOKOL_ANY_GL)
  16250. return _sg_gl_create_sampler(smp, desc);
  16251. #elif defined(SOKOL_METAL)
  16252. return _sg_mtl_create_sampler(smp, desc);
  16253. #elif defined(SOKOL_D3D11)
  16254. return _sg_d3d11_create_sampler(smp, desc);
  16255. #elif defined(SOKOL_WGPU)
  16256. return _sg_wgpu_create_sampler(smp, desc);
  16257. #elif defined(SOKOL_DUMMY_BACKEND)
  16258. return _sg_dummy_create_sampler(smp, desc);
  16259. #else
  16260. #error("INVALID BACKEND");
  16261. #endif
  16262. }
  16263. static inline void _sg_discard_sampler(_sg_sampler_t* smp) {
  16264. #if defined(_SOKOL_ANY_GL)
  16265. _sg_gl_discard_sampler(smp);
  16266. #elif defined(SOKOL_METAL)
  16267. _sg_mtl_discard_sampler(smp);
  16268. #elif defined(SOKOL_D3D11)
  16269. _sg_d3d11_discard_sampler(smp);
  16270. #elif defined(SOKOL_WGPU)
  16271. _sg_wgpu_discard_sampler(smp);
  16272. #elif defined(SOKOL_DUMMY_BACKEND)
  16273. _sg_dummy_discard_sampler(smp);
  16274. #else
  16275. #error("INVALID BACKEND");
  16276. #endif
  16277. }
  16278. static inline sg_resource_state _sg_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  16279. #if defined(_SOKOL_ANY_GL)
  16280. return _sg_gl_create_shader(shd, desc);
  16281. #elif defined(SOKOL_METAL)
  16282. return _sg_mtl_create_shader(shd, desc);
  16283. #elif defined(SOKOL_D3D11)
  16284. return _sg_d3d11_create_shader(shd, desc);
  16285. #elif defined(SOKOL_WGPU)
  16286. return _sg_wgpu_create_shader(shd, desc);
  16287. #elif defined(SOKOL_DUMMY_BACKEND)
  16288. return _sg_dummy_create_shader(shd, desc);
  16289. #else
  16290. #error("INVALID BACKEND");
  16291. #endif
  16292. }
  16293. static inline void _sg_discard_shader(_sg_shader_t* shd) {
  16294. #if defined(_SOKOL_ANY_GL)
  16295. _sg_gl_discard_shader(shd);
  16296. #elif defined(SOKOL_METAL)
  16297. _sg_mtl_discard_shader(shd);
  16298. #elif defined(SOKOL_D3D11)
  16299. _sg_d3d11_discard_shader(shd);
  16300. #elif defined(SOKOL_WGPU)
  16301. _sg_wgpu_discard_shader(shd);
  16302. #elif defined(SOKOL_DUMMY_BACKEND)
  16303. _sg_dummy_discard_shader(shd);
  16304. #else
  16305. #error("INVALID BACKEND");
  16306. #endif
  16307. }
  16308. static inline sg_resource_state _sg_create_pipeline(_sg_pipeline_t* pip, const sg_pipeline_desc* desc) {
  16309. #if defined(_SOKOL_ANY_GL)
  16310. return _sg_gl_create_pipeline(pip, desc);
  16311. #elif defined(SOKOL_METAL)
  16312. return _sg_mtl_create_pipeline(pip, desc);
  16313. #elif defined(SOKOL_D3D11)
  16314. return _sg_d3d11_create_pipeline(pip, desc);
  16315. #elif defined(SOKOL_WGPU)
  16316. return _sg_wgpu_create_pipeline(pip, desc);
  16317. #elif defined(SOKOL_DUMMY_BACKEND)
  16318. return _sg_dummy_create_pipeline(pip, desc);
  16319. #else
  16320. #error("INVALID BACKEND");
  16321. #endif
  16322. }
  16323. static inline void _sg_discard_pipeline(_sg_pipeline_t* pip) {
  16324. #if defined(_SOKOL_ANY_GL)
  16325. _sg_gl_discard_pipeline(pip);
  16326. #elif defined(SOKOL_METAL)
  16327. _sg_mtl_discard_pipeline(pip);
  16328. #elif defined(SOKOL_D3D11)
  16329. _sg_d3d11_discard_pipeline(pip);
  16330. #elif defined(SOKOL_WGPU)
  16331. _sg_wgpu_discard_pipeline(pip);
  16332. #elif defined(SOKOL_DUMMY_BACKEND)
  16333. _sg_dummy_discard_pipeline(pip);
  16334. #else
  16335. #error("INVALID BACKEND");
  16336. #endif
  16337. }
  16338. static inline sg_resource_state _sg_create_attachments(_sg_attachments_t* atts, const sg_attachments_desc* desc) {
  16339. #if defined(_SOKOL_ANY_GL)
  16340. return _sg_gl_create_attachments(atts, desc);
  16341. #elif defined(SOKOL_METAL)
  16342. return _sg_mtl_create_attachments(atts, desc);
  16343. #elif defined(SOKOL_D3D11)
  16344. return _sg_d3d11_create_attachments(atts, desc);
  16345. #elif defined(SOKOL_WGPU)
  16346. return _sg_wgpu_create_attachments(atts, desc);
  16347. #elif defined(SOKOL_DUMMY_BACKEND)
  16348. return _sg_dummy_create_attachments(atts, desc);
  16349. #else
  16350. #error("INVALID BACKEND");
  16351. #endif
  16352. }
  16353. static inline void _sg_discard_attachments(_sg_attachments_t* atts) {
  16354. #if defined(_SOKOL_ANY_GL)
  16355. _sg_gl_discard_attachments(atts);
  16356. #elif defined(SOKOL_METAL)
  16357. _sg_mtl_discard_attachments(atts);
  16358. #elif defined(SOKOL_D3D11)
  16359. _sg_d3d11_discard_attachments(atts);
  16360. #elif defined(SOKOL_WGPU)
  16361. return _sg_wgpu_discard_attachments(atts);
  16362. #elif defined(SOKOL_DUMMY_BACKEND)
  16363. _sg_dummy_discard_attachments(atts);
  16364. #else
  16365. #error("INVALID BACKEND");
  16366. #endif
  16367. }
  16368. static inline void _sg_begin_pass(const sg_pass* pass) {
  16369. #if defined(_SOKOL_ANY_GL)
  16370. _sg_gl_begin_pass(pass);
  16371. #elif defined(SOKOL_METAL)
  16372. _sg_mtl_begin_pass(pass);
  16373. #elif defined(SOKOL_D3D11)
  16374. _sg_d3d11_begin_pass(pass);
  16375. #elif defined(SOKOL_WGPU)
  16376. _sg_wgpu_begin_pass(pass);
  16377. #elif defined(SOKOL_DUMMY_BACKEND)
  16378. _sg_dummy_begin_pass(pass);
  16379. #else
  16380. #error("INVALID BACKEND");
  16381. #endif
  16382. }
  16383. static inline void _sg_end_pass(void) {
  16384. #if defined(_SOKOL_ANY_GL)
  16385. _sg_gl_end_pass();
  16386. #elif defined(SOKOL_METAL)
  16387. _sg_mtl_end_pass();
  16388. #elif defined(SOKOL_D3D11)
  16389. _sg_d3d11_end_pass();
  16390. #elif defined(SOKOL_WGPU)
  16391. _sg_wgpu_end_pass();
  16392. #elif defined(SOKOL_DUMMY_BACKEND)
  16393. _sg_dummy_end_pass();
  16394. #else
  16395. #error("INVALID BACKEND");
  16396. #endif
  16397. }
  16398. static inline void _sg_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  16399. #if defined(_SOKOL_ANY_GL)
  16400. _sg_gl_apply_viewport(x, y, w, h, origin_top_left);
  16401. #elif defined(SOKOL_METAL)
  16402. _sg_mtl_apply_viewport(x, y, w, h, origin_top_left);
  16403. #elif defined(SOKOL_D3D11)
  16404. _sg_d3d11_apply_viewport(x, y, w, h, origin_top_left);
  16405. #elif defined(SOKOL_WGPU)
  16406. _sg_wgpu_apply_viewport(x, y, w, h, origin_top_left);
  16407. #elif defined(SOKOL_DUMMY_BACKEND)
  16408. _sg_dummy_apply_viewport(x, y, w, h, origin_top_left);
  16409. #else
  16410. #error("INVALID BACKEND");
  16411. #endif
  16412. }
  16413. static inline void _sg_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  16414. #if defined(_SOKOL_ANY_GL)
  16415. _sg_gl_apply_scissor_rect(x, y, w, h, origin_top_left);
  16416. #elif defined(SOKOL_METAL)
  16417. _sg_mtl_apply_scissor_rect(x, y, w, h, origin_top_left);
  16418. #elif defined(SOKOL_D3D11)
  16419. _sg_d3d11_apply_scissor_rect(x, y, w, h, origin_top_left);
  16420. #elif defined(SOKOL_WGPU)
  16421. _sg_wgpu_apply_scissor_rect(x, y, w, h, origin_top_left);
  16422. #elif defined(SOKOL_DUMMY_BACKEND)
  16423. _sg_dummy_apply_scissor_rect(x, y, w, h, origin_top_left);
  16424. #else
  16425. #error("INVALID BACKEND");
  16426. #endif
  16427. }
  16428. static inline void _sg_apply_pipeline(_sg_pipeline_t* pip) {
  16429. #if defined(_SOKOL_ANY_GL)
  16430. _sg_gl_apply_pipeline(pip);
  16431. #elif defined(SOKOL_METAL)
  16432. _sg_mtl_apply_pipeline(pip);
  16433. #elif defined(SOKOL_D3D11)
  16434. _sg_d3d11_apply_pipeline(pip);
  16435. #elif defined(SOKOL_WGPU)
  16436. _sg_wgpu_apply_pipeline(pip);
  16437. #elif defined(SOKOL_DUMMY_BACKEND)
  16438. _sg_dummy_apply_pipeline(pip);
  16439. #else
  16440. #error("INVALID BACKEND");
  16441. #endif
  16442. }
  16443. static inline bool _sg_apply_bindings(_sg_bindings_ptrs_t* bnd) {
  16444. #if defined(_SOKOL_ANY_GL)
  16445. return _sg_gl_apply_bindings(bnd);
  16446. #elif defined(SOKOL_METAL)
  16447. return _sg_mtl_apply_bindings(bnd);
  16448. #elif defined(SOKOL_D3D11)
  16449. return _sg_d3d11_apply_bindings(bnd);
  16450. #elif defined(SOKOL_WGPU)
  16451. return _sg_wgpu_apply_bindings(bnd);
  16452. #elif defined(SOKOL_DUMMY_BACKEND)
  16453. return _sg_dummy_apply_bindings(bnd);
  16454. #else
  16455. #error("INVALID BACKEND");
  16456. #endif
  16457. }
  16458. static inline void _sg_apply_uniforms(int ub_slot, const sg_range* data) {
  16459. #if defined(_SOKOL_ANY_GL)
  16460. _sg_gl_apply_uniforms(ub_slot, data);
  16461. #elif defined(SOKOL_METAL)
  16462. _sg_mtl_apply_uniforms(ub_slot, data);
  16463. #elif defined(SOKOL_D3D11)
  16464. _sg_d3d11_apply_uniforms(ub_slot, data);
  16465. #elif defined(SOKOL_WGPU)
  16466. _sg_wgpu_apply_uniforms(ub_slot, data);
  16467. #elif defined(SOKOL_DUMMY_BACKEND)
  16468. _sg_dummy_apply_uniforms(ub_slot, data);
  16469. #else
  16470. #error("INVALID BACKEND");
  16471. #endif
  16472. }
  16473. static inline void _sg_draw(int base_element, int num_elements, int num_instances) {
  16474. #if defined(_SOKOL_ANY_GL)
  16475. _sg_gl_draw(base_element, num_elements, num_instances);
  16476. #elif defined(SOKOL_METAL)
  16477. _sg_mtl_draw(base_element, num_elements, num_instances);
  16478. #elif defined(SOKOL_D3D11)
  16479. _sg_d3d11_draw(base_element, num_elements, num_instances);
  16480. #elif defined(SOKOL_WGPU)
  16481. _sg_wgpu_draw(base_element, num_elements, num_instances);
  16482. #elif defined(SOKOL_DUMMY_BACKEND)
  16483. _sg_dummy_draw(base_element, num_elements, num_instances);
  16484. #else
  16485. #error("INVALID BACKEND");
  16486. #endif
  16487. }
  16488. static inline void _sg_dispatch(int num_groups_x, int num_groups_y, int num_groups_z) {
  16489. #if defined(_SOKOL_ANY_GL)
  16490. _sg_gl_dispatch(num_groups_x, num_groups_y, num_groups_z);
  16491. #elif defined(SOKOL_METAL)
  16492. _sg_mtl_dispatch(num_groups_x, num_groups_y, num_groups_z);
  16493. #elif defined(SOKOL_D3D11)
  16494. _sg_d3d11_dispatch(num_groups_x, num_groups_y, num_groups_z);
  16495. #elif defined(SOKOL_WGPU)
  16496. _sg_wgpu_dispatch(num_groups_x, num_groups_y, num_groups_z);
  16497. #elif defined(SOKOL_DUMMY_BACKEND)
  16498. _sg_dummy_dispatch(num_groups_x, num_groups_y, num_groups_z);
  16499. #else
  16500. #error("INVALID BACKEND");
  16501. #endif
  16502. }
  16503. static inline void _sg_commit(void) {
  16504. #if defined(_SOKOL_ANY_GL)
  16505. _sg_gl_commit();
  16506. #elif defined(SOKOL_METAL)
  16507. _sg_mtl_commit();
  16508. #elif defined(SOKOL_D3D11)
  16509. _sg_d3d11_commit();
  16510. #elif defined(SOKOL_WGPU)
  16511. _sg_wgpu_commit();
  16512. #elif defined(SOKOL_DUMMY_BACKEND)
  16513. _sg_dummy_commit();
  16514. #else
  16515. #error("INVALID BACKEND");
  16516. #endif
  16517. }
  16518. static inline void _sg_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  16519. #if defined(_SOKOL_ANY_GL)
  16520. _sg_gl_update_buffer(buf, data);
  16521. #elif defined(SOKOL_METAL)
  16522. _sg_mtl_update_buffer(buf, data);
  16523. #elif defined(SOKOL_D3D11)
  16524. _sg_d3d11_update_buffer(buf, data);
  16525. #elif defined(SOKOL_WGPU)
  16526. _sg_wgpu_update_buffer(buf, data);
  16527. #elif defined(SOKOL_DUMMY_BACKEND)
  16528. _sg_dummy_update_buffer(buf, data);
  16529. #else
  16530. #error("INVALID BACKEND");
  16531. #endif
  16532. }
  16533. static inline void _sg_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  16534. #if defined(_SOKOL_ANY_GL)
  16535. _sg_gl_append_buffer(buf, data, new_frame);
  16536. #elif defined(SOKOL_METAL)
  16537. _sg_mtl_append_buffer(buf, data, new_frame);
  16538. #elif defined(SOKOL_D3D11)
  16539. _sg_d3d11_append_buffer(buf, data, new_frame);
  16540. #elif defined(SOKOL_WGPU)
  16541. _sg_wgpu_append_buffer(buf, data, new_frame);
  16542. #elif defined(SOKOL_DUMMY_BACKEND)
  16543. _sg_dummy_append_buffer(buf, data, new_frame);
  16544. #else
  16545. #error("INVALID BACKEND");
  16546. #endif
  16547. }
  16548. static inline void _sg_update_image(_sg_image_t* img, const sg_image_data* data) {
  16549. #if defined(_SOKOL_ANY_GL)
  16550. _sg_gl_update_image(img, data);
  16551. #elif defined(SOKOL_METAL)
  16552. _sg_mtl_update_image(img, data);
  16553. #elif defined(SOKOL_D3D11)
  16554. _sg_d3d11_update_image(img, data);
  16555. #elif defined(SOKOL_WGPU)
  16556. _sg_wgpu_update_image(img, data);
  16557. #elif defined(SOKOL_DUMMY_BACKEND)
  16558. _sg_dummy_update_image(img, data);
  16559. #else
  16560. #error("INVALID BACKEND");
  16561. #endif
  16562. }
  16563. static inline void _sg_push_debug_group(const char* name) {
  16564. #if defined(SOKOL_METAL)
  16565. _sg_mtl_push_debug_group(name);
  16566. #else
  16567. _SOKOL_UNUSED(name);
  16568. #endif
  16569. }
  16570. static inline void _sg_pop_debug_group(void) {
  16571. #if defined(SOKOL_METAL)
  16572. _sg_mtl_pop_debug_group();
  16573. #endif
  16574. }
  16575. // ██ ██ █████ ██ ██ ██████ █████ ████████ ██ ██████ ███ ██
  16576. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
  16577. // ██ ██ ███████ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██
  16578. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  16579. // ████ ██ ██ ███████ ██ ██████ ██ ██ ██ ██ ██████ ██ ████
  16580. //
  16581. // >>validation
  16582. #if defined(SOKOL_DEBUG)
  16583. _SOKOL_PRIVATE void _sg_validate_begin(void) {
  16584. _sg.validate_error = SG_LOGITEM_OK;
  16585. }
  16586. _SOKOL_PRIVATE bool _sg_validate_end(void) {
  16587. if (_sg.validate_error != SG_LOGITEM_OK) {
  16588. #if !defined(SOKOL_VALIDATE_NON_FATAL)
  16589. _SG_PANIC(VALIDATION_FAILED);
  16590. return false;
  16591. #else
  16592. return false;
  16593. #endif
  16594. } else {
  16595. return true;
  16596. }
  16597. }
  16598. #endif
  16599. _SOKOL_PRIVATE bool _sg_one(bool b0, bool b1, bool b2) {
  16600. return (b0 && !b1 && !b2) || (!b0 && b1 && !b2) || (!b0 && !b1 && b2);
  16601. }
  16602. _SOKOL_PRIVATE bool _sg_validate_buffer_desc(const sg_buffer_desc* desc) {
  16603. #if !defined(SOKOL_DEBUG)
  16604. _SOKOL_UNUSED(desc);
  16605. return true;
  16606. #else
  16607. if (_sg.desc.disable_validation) {
  16608. return true;
  16609. }
  16610. SOKOL_ASSERT(desc);
  16611. _sg_validate_begin();
  16612. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_BUFFERDESC_CANARY);
  16613. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_BUFFERDESC_CANARY);
  16614. _SG_VALIDATE(desc->size > 0, VALIDATE_BUFFERDESC_EXPECT_NONZERO_SIZE);
  16615. _SG_VALIDATE(_sg_one(desc->usage.immutable, desc->usage.dynamic_update, desc->usage.stream_update), VALIDATE_BUFFERDESC_IMMUTABLE_DYNAMIC_STREAM);
  16616. if (_sg.features.separate_buffer_types) {
  16617. _SG_VALIDATE(_sg_one(desc->usage.vertex_buffer, desc->usage.index_buffer, desc->usage.storage_buffer), VALIDATE_BUFFERDESC_SEPARATE_BUFFER_TYPES);
  16618. }
  16619. bool injected = (0 != desc->gl_buffers[0]) ||
  16620. (0 != desc->mtl_buffers[0]) ||
  16621. (0 != desc->d3d11_buffer) ||
  16622. (0 != desc->wgpu_buffer);
  16623. if (!injected && desc->usage.immutable) {
  16624. if (desc->data.ptr) {
  16625. _SG_VALIDATE(desc->size == desc->data.size, VALIDATE_BUFFERDESC_EXPECT_MATCHING_DATA_SIZE);
  16626. } else {
  16627. _SG_VALIDATE(desc->usage.storage_buffer, VALIDATE_BUFFERDESC_EXPECT_DATA);
  16628. _SG_VALIDATE(desc->data.size == 0, VALIDATE_BUFFERDESC_EXPECT_ZERO_DATA_SIZE);
  16629. }
  16630. } else {
  16631. _SG_VALIDATE(0 == desc->data.ptr, VALIDATE_BUFFERDESC_EXPECT_NO_DATA);
  16632. _SG_VALIDATE(desc->data.size == 0, VALIDATE_BUFFERDESC_EXPECT_ZERO_DATA_SIZE);
  16633. }
  16634. if (desc->usage.storage_buffer) {
  16635. _SG_VALIDATE(_sg.features.compute, VALIDATE_BUFFERDESC_STORAGEBUFFER_SUPPORTED);
  16636. _SG_VALIDATE(_sg_multiple_u64(desc->size, 4), VALIDATE_BUFFERDESC_STORAGEBUFFER_SIZE_MULTIPLE_4);
  16637. }
  16638. return _sg_validate_end();
  16639. #endif
  16640. }
  16641. _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) {
  16642. #if !defined(SOKOL_DEBUG)
  16643. _SOKOL_UNUSED(data);
  16644. _SOKOL_UNUSED(fmt);
  16645. _SOKOL_UNUSED(width);
  16646. _SOKOL_UNUSED(height);
  16647. _SOKOL_UNUSED(num_faces);
  16648. _SOKOL_UNUSED(num_mips);
  16649. _SOKOL_UNUSED(num_slices);
  16650. #else
  16651. for (int face_index = 0; face_index < num_faces; face_index++) {
  16652. for (int mip_index = 0; mip_index < num_mips; mip_index++) {
  16653. const bool has_data = data->subimage[face_index][mip_index].ptr != 0;
  16654. const bool has_size = data->subimage[face_index][mip_index].size > 0;
  16655. _SG_VALIDATE(has_data && has_size, VALIDATE_IMAGEDATA_NODATA);
  16656. const int mip_width = _sg_miplevel_dim(width, mip_index);
  16657. const int mip_height = _sg_miplevel_dim(height, mip_index);
  16658. const int bytes_per_slice = _sg_surface_pitch(fmt, mip_width, mip_height, 1);
  16659. const int expected_size = bytes_per_slice * num_slices;
  16660. _SG_VALIDATE(expected_size == (int)data->subimage[face_index][mip_index].size, VALIDATE_IMAGEDATA_DATA_SIZE);
  16661. }
  16662. }
  16663. #endif
  16664. }
  16665. _SOKOL_PRIVATE bool _sg_validate_image_desc(const sg_image_desc* desc) {
  16666. #if !defined(SOKOL_DEBUG)
  16667. _SOKOL_UNUSED(desc);
  16668. return true;
  16669. #else
  16670. if (_sg.desc.disable_validation) {
  16671. return true;
  16672. }
  16673. SOKOL_ASSERT(desc);
  16674. _sg_validate_begin();
  16675. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_IMAGEDESC_CANARY);
  16676. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_IMAGEDESC_CANARY);
  16677. _SG_VALIDATE(_sg_one(desc->usage.immutable, desc->usage.dynamic_update, desc->usage.stream_update), VALIDATE_IMAGEDESC_IMMUTABLE_DYNAMIC_STREAM);
  16678. if (desc->usage.render_attachment || desc->usage.storage_attachment) {
  16679. _SG_VALIDATE(_sg_one(desc->usage.render_attachment, desc->usage.storage_attachment, false), VALIDATE_IMAGEDESC_RENDER_VS_STORAGE_ATTACHMENT);
  16680. }
  16681. _SG_VALIDATE(desc->width > 0, VALIDATE_IMAGEDESC_WIDTH);
  16682. _SG_VALIDATE(desc->height > 0, VALIDATE_IMAGEDESC_HEIGHT);
  16683. const sg_pixel_format fmt = desc->pixel_format;
  16684. const sg_image_usage* usage = &desc->usage;
  16685. const bool injected = (0 != desc->gl_textures[0]) ||
  16686. (0 != desc->mtl_textures[0]) ||
  16687. (0 != desc->d3d11_texture) ||
  16688. (0 != desc->wgpu_texture);
  16689. if (_sg_is_depth_or_depth_stencil_format(fmt)) {
  16690. _SG_VALIDATE(desc->type != SG_IMAGETYPE_3D, VALIDATE_IMAGEDESC_DEPTH_3D_IMAGE);
  16691. }
  16692. if (usage->render_attachment || usage->storage_attachment) {
  16693. SOKOL_ASSERT(((int)fmt >= 0) && ((int)fmt < _SG_PIXELFORMAT_NUM));
  16694. _SG_VALIDATE(usage->immutable, VALIDATE_IMAGEDESC_ATTACHMENT_EXPECT_IMMUTABLE);
  16695. _SG_VALIDATE(desc->data.subimage[0][0].ptr==0, VALIDATE_IMAGEDESC_ATTACHMENT_EXPECT_NO_DATA);
  16696. if (usage->render_attachment) {
  16697. _SG_VALIDATE(_sg.formats[fmt].render, VALIDATE_IMAGEDESC_RENDERATTACHMENT_PIXELFORMAT);
  16698. if (desc->sample_count > 1) {
  16699. _SG_VALIDATE(_sg.formats[fmt].msaa, VALIDATE_IMAGEDESC_RENDERATTACHMENT_NO_MSAA_SUPPORT);
  16700. _SG_VALIDATE(desc->num_mipmaps == 1, VALIDATE_IMAGEDESC_RENDERATTACHMENT_MSAA_NUM_MIPMAPS);
  16701. _SG_VALIDATE(desc->type != SG_IMAGETYPE_ARRAY, VALIDATE_IMAGEDESC_RENDERATTACHMENT_MSAA_ARRAY_IMAGE);
  16702. _SG_VALIDATE(desc->type != SG_IMAGETYPE_3D, VALIDATE_IMAGEDESC_RENDERATTACHMENT_MSAA_3D_IMAGE);
  16703. _SG_VALIDATE(desc->type != SG_IMAGETYPE_CUBE, VALIDATE_IMAGEDESC_RENDERATTACHMENT_MSAA_CUBE_IMAGE);
  16704. }
  16705. } else if (usage->storage_attachment) {
  16706. _SG_VALIDATE(_sg_is_valid_attachment_storage_format(fmt), VALIDATE_IMAGEDESC_STORAGEATTACHMENT_PIXELFORMAT);
  16707. // D3D11 doesn't allow multisampled UAVs (see: https://github.com/gpuweb/gpuweb/issues/513)
  16708. _SG_VALIDATE(desc->sample_count == 1, VALIDATE_IMAGEDESC_STORAGEATTACHMENT_EXPECT_NO_MSAA);
  16709. }
  16710. } else {
  16711. _SG_VALIDATE(desc->sample_count == 1, VALIDATE_IMAGEDESC_MSAA_BUT_NO_ATTACHMENT);
  16712. const bool valid_nonrt_fmt = !_sg_is_valid_attachment_depth_format(fmt);
  16713. _SG_VALIDATE(valid_nonrt_fmt, VALIDATE_IMAGEDESC_NONRT_PIXELFORMAT);
  16714. const bool is_compressed = _sg_is_compressed_pixel_format(desc->pixel_format);
  16715. if (is_compressed) {
  16716. _SG_VALIDATE(usage->immutable, VALIDATE_IMAGEDESC_COMPRESSED_IMMUTABLE);
  16717. }
  16718. if (!injected && usage->immutable) {
  16719. // image desc must have valid data
  16720. _sg_validate_image_data(&desc->data,
  16721. desc->pixel_format,
  16722. desc->width,
  16723. desc->height,
  16724. (desc->type == SG_IMAGETYPE_CUBE) ? 6 : 1,
  16725. desc->num_mipmaps,
  16726. desc->num_slices);
  16727. } else {
  16728. // image desc must not have data
  16729. for (int face_index = 0; face_index < SG_CUBEFACE_NUM; face_index++) {
  16730. for (int mip_index = 0; mip_index < SG_MAX_MIPMAPS; mip_index++) {
  16731. const bool no_data = 0 == desc->data.subimage[face_index][mip_index].ptr;
  16732. const bool no_size = 0 == desc->data.subimage[face_index][mip_index].size;
  16733. if (injected) {
  16734. _SG_VALIDATE(no_data && no_size, VALIDATE_IMAGEDESC_INJECTED_NO_DATA);
  16735. }
  16736. if (!usage->immutable) {
  16737. _SG_VALIDATE(no_data && no_size, VALIDATE_IMAGEDESC_DYNAMIC_NO_DATA);
  16738. }
  16739. }
  16740. }
  16741. }
  16742. }
  16743. return _sg_validate_end();
  16744. #endif
  16745. }
  16746. _SOKOL_PRIVATE bool _sg_validate_sampler_desc(const sg_sampler_desc* desc) {
  16747. #if !defined(SOKOL_DEBUG)
  16748. _SOKOL_UNUSED(desc);
  16749. return true;
  16750. #else
  16751. if (_sg.desc.disable_validation) {
  16752. return true;
  16753. }
  16754. SOKOL_ASSERT(desc);
  16755. _sg_validate_begin();
  16756. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_SAMPLERDESC_CANARY);
  16757. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_SAMPLERDESC_CANARY);
  16758. // restriction from WebGPU: when anisotropy > 1, all filters must be linear
  16759. if (desc->max_anisotropy > 1) {
  16760. _SG_VALIDATE((desc->min_filter == SG_FILTER_LINEAR)
  16761. && (desc->mag_filter == SG_FILTER_LINEAR)
  16762. && (desc->mipmap_filter == SG_FILTER_LINEAR),
  16763. VALIDATE_SAMPLERDESC_ANISTROPIC_REQUIRES_LINEAR_FILTERING);
  16764. }
  16765. return _sg_validate_end();
  16766. #endif
  16767. }
  16768. typedef struct {
  16769. uint64_t lo, hi;
  16770. } _sg_u128_t;
  16771. _SOKOL_PRIVATE _sg_u128_t _sg_u128(void) {
  16772. _sg_u128_t res;
  16773. _sg_clear(&res, sizeof(res));
  16774. return res;
  16775. }
  16776. _SOKOL_PRIVATE _sg_u128_t _sg_validate_set_slot_bit(_sg_u128_t bits, sg_shader_stage stage, uint8_t slot) {
  16777. switch (stage) {
  16778. case SG_SHADERSTAGE_NONE:
  16779. SOKOL_ASSERT(slot < 128);
  16780. if (slot < 64) {
  16781. bits.lo |= 1ULL << slot;
  16782. } else {
  16783. bits.hi |= 1ULL << (slot - 64);
  16784. }
  16785. break;
  16786. case SG_SHADERSTAGE_VERTEX:
  16787. SOKOL_ASSERT(slot < 64);
  16788. bits.lo |= 1ULL << slot;
  16789. break;
  16790. case SG_SHADERSTAGE_FRAGMENT:
  16791. SOKOL_ASSERT(slot < 64);
  16792. bits.hi |= 1ULL << slot;
  16793. break;
  16794. case SG_SHADERSTAGE_COMPUTE:
  16795. SOKOL_ASSERT(slot < 64);
  16796. bits.lo |= 1ULL << slot;
  16797. break;
  16798. default:
  16799. SOKOL_UNREACHABLE;
  16800. break;
  16801. }
  16802. return bits;
  16803. }
  16804. _SOKOL_PRIVATE bool _sg_validate_slot_bits(_sg_u128_t bits, sg_shader_stage stage, uint8_t slot) {
  16805. _sg_u128_t mask = _sg_u128();
  16806. switch (stage) {
  16807. case SG_SHADERSTAGE_NONE:
  16808. SOKOL_ASSERT(slot < 128);
  16809. if (slot < 64) {
  16810. mask.lo = 1ULL << slot;
  16811. } else {
  16812. mask.hi = 1ULL << (slot - 64);
  16813. }
  16814. break;
  16815. case SG_SHADERSTAGE_VERTEX:
  16816. SOKOL_ASSERT(slot < 64);
  16817. mask.lo = 1ULL << slot;
  16818. break;
  16819. case SG_SHADERSTAGE_FRAGMENT:
  16820. SOKOL_ASSERT(slot < 64);
  16821. mask.hi = 1ULL << slot;
  16822. break;
  16823. case SG_SHADERSTAGE_COMPUTE:
  16824. SOKOL_ASSERT(slot < 64);
  16825. mask.lo = 1ULL << slot;
  16826. break;
  16827. default:
  16828. SOKOL_UNREACHABLE;
  16829. break;
  16830. }
  16831. return ((bits.lo & mask.lo) == 0) && ((bits.hi & mask.hi) == 0);
  16832. }
  16833. _SOKOL_PRIVATE bool _sg_validate_shader_desc(const sg_shader_desc* desc) {
  16834. #if !defined(SOKOL_DEBUG)
  16835. _SOKOL_UNUSED(desc);
  16836. return true;
  16837. #else
  16838. if (_sg.desc.disable_validation) {
  16839. return true;
  16840. }
  16841. SOKOL_ASSERT(desc);
  16842. bool is_compute_shader = (desc->compute_func.source != 0) || (desc->compute_func.bytecode.ptr != 0);
  16843. _sg_validate_begin();
  16844. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_SHADERDESC_CANARY);
  16845. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_SHADERDESC_CANARY);
  16846. #if defined(SOKOL_GLCORE) || defined(SOKOL_GLES3) || defined(SOKOL_WGPU)
  16847. // on GL or WebGPU, must provide shader source code
  16848. if (is_compute_shader) {
  16849. _SG_VALIDATE(0 != desc->compute_func.source, VALIDATE_SHADERDESC_COMPUTE_SOURCE);
  16850. } else {
  16851. _SG_VALIDATE(0 != desc->vertex_func.source, VALIDATE_SHADERDESC_VERTEX_SOURCE);
  16852. _SG_VALIDATE(0 != desc->fragment_func.source, VALIDATE_SHADERDESC_FRAGMENT_SOURCE);
  16853. }
  16854. #elif defined(SOKOL_METAL) || defined(SOKOL_D3D11)
  16855. // on Metal or D3D11, must provide shader source code or byte code
  16856. if (is_compute_shader) {
  16857. _SG_VALIDATE((0 != desc->compute_func.source) || (0 != desc->compute_func.bytecode.ptr), VALIDATE_SHADERDESC_COMPUTE_SOURCE_OR_BYTECODE);
  16858. } else {
  16859. _SG_VALIDATE((0 != desc->vertex_func.source)|| (0 != desc->vertex_func.bytecode.ptr), VALIDATE_SHADERDESC_VERTEX_SOURCE_OR_BYTECODE);
  16860. _SG_VALIDATE((0 != desc->fragment_func.source) || (0 != desc->fragment_func.bytecode.ptr), VALIDATE_SHADERDESC_FRAGMENT_SOURCE_OR_BYTECODE);
  16861. }
  16862. #else
  16863. // Dummy Backend, don't require source or bytecode
  16864. #endif
  16865. if (is_compute_shader) {
  16866. _SG_VALIDATE((0 == desc->vertex_func.source) && (0 == desc->vertex_func.bytecode.ptr), VALIDATE_SHADERDESC_INVALID_SHADER_COMBO);
  16867. _SG_VALIDATE((0 == desc->fragment_func.source) && (0 == desc->fragment_func.bytecode.ptr), VALIDATE_SHADERDESC_INVALID_SHADER_COMBO);
  16868. } else {
  16869. _SG_VALIDATE((0 == desc->compute_func.source) && (0 == desc->compute_func.bytecode.ptr), VALIDATE_SHADERDESC_INVALID_SHADER_COMBO);
  16870. }
  16871. #if defined(SOKOL_METAL)
  16872. if (is_compute_shader) {
  16873. _SG_VALIDATE(desc->mtl_threads_per_threadgroup.x > 0, VALIDATE_SHADERDESC_METAL_THREADS_PER_THREADGROUP);
  16874. _SG_VALIDATE(desc->mtl_threads_per_threadgroup.y > 0, VALIDATE_SHADERDESC_METAL_THREADS_PER_THREADGROUP);
  16875. _SG_VALIDATE(desc->mtl_threads_per_threadgroup.z > 0, VALIDATE_SHADERDESC_METAL_THREADS_PER_THREADGROUP);
  16876. }
  16877. #endif
  16878. for (size_t i = 0; i < SG_MAX_VERTEX_ATTRIBUTES; i++) {
  16879. if (desc->attrs[i].glsl_name) {
  16880. _SG_VALIDATE(strlen(desc->attrs[i].glsl_name) < _SG_STRING_SIZE, VALIDATE_SHADERDESC_ATTR_STRING_TOO_LONG);
  16881. }
  16882. if (desc->attrs[i].hlsl_sem_name) {
  16883. _SG_VALIDATE(strlen(desc->attrs[i].hlsl_sem_name) < _SG_STRING_SIZE, VALIDATE_SHADERDESC_ATTR_STRING_TOO_LONG);
  16884. }
  16885. }
  16886. // if shader byte code, the size must also be provided
  16887. if (0 != desc->vertex_func.bytecode.ptr) {
  16888. _SG_VALIDATE(desc->vertex_func.bytecode.size > 0, VALIDATE_SHADERDESC_NO_BYTECODE_SIZE);
  16889. }
  16890. if (0 != desc->fragment_func.bytecode.ptr) {
  16891. _SG_VALIDATE(desc->fragment_func.bytecode.size > 0, VALIDATE_SHADERDESC_NO_BYTECODE_SIZE);
  16892. }
  16893. if (0 != desc->compute_func.bytecode.ptr) {
  16894. _SG_VALIDATE(desc->compute_func.bytecode.size > 0, VALIDATE_SHADERDESC_NO_BYTECODE_SIZE);
  16895. }
  16896. #if defined(SOKOL_METAL)
  16897. _sg_u128_t msl_buf_bits = _sg_u128();
  16898. _sg_u128_t msl_tex_bits = _sg_u128();
  16899. _sg_u128_t msl_smp_bits = _sg_u128();
  16900. #elif defined(SOKOL_D3D11)
  16901. _sg_u128_t hlsl_buf_bits = _sg_u128();
  16902. _sg_u128_t hlsl_srv_bits = _sg_u128();
  16903. _sg_u128_t hlsl_uav_bits = _sg_u128();
  16904. _sg_u128_t hlsl_smp_bits = _sg_u128();
  16905. #elif defined(_SOKOL_ANY_GL)
  16906. _sg_u128_t glsl_sbuf_bnd_bits = _sg_u128();
  16907. _sg_u128_t glsl_simg_bnd_bits = _sg_u128();
  16908. #elif defined(SOKOL_WGPU)
  16909. _sg_u128_t wgsl_group0_bits = _sg_u128();
  16910. _sg_u128_t wgsl_group1_bits = _sg_u128();
  16911. _sg_u128_t wgsl_group2_bits = _sg_u128();
  16912. #endif
  16913. for (size_t ub_idx = 0; ub_idx < SG_MAX_UNIFORMBLOCK_BINDSLOTS; ub_idx++) {
  16914. const sg_shader_uniform_block* ub_desc = &desc->uniform_blocks[ub_idx];
  16915. if (ub_desc->stage == SG_SHADERSTAGE_NONE) {
  16916. continue;
  16917. }
  16918. _SG_VALIDATE(ub_desc->size > 0, VALIDATE_SHADERDESC_UNIFORMBLOCK_SIZE_IS_ZERO);
  16919. #if defined(SOKOL_METAL)
  16920. _SG_VALIDATE(ub_desc->msl_buffer_n < _SG_MTL_MAX_STAGE_UB_BINDINGS, VALIDATE_SHADERDESC_UNIFORMBLOCK_METAL_BUFFER_SLOT_OUT_OF_RANGE);
  16921. _SG_VALIDATE(_sg_validate_slot_bits(msl_buf_bits, ub_desc->stage, ub_desc->msl_buffer_n), VALIDATE_SHADERDESC_UNIFORMBLOCK_METAL_BUFFER_SLOT_COLLISION);
  16922. msl_buf_bits = _sg_validate_set_slot_bit(msl_buf_bits, ub_desc->stage, ub_desc->msl_buffer_n);
  16923. #elif defined(SOKOL_D3D11)
  16924. _SG_VALIDATE(ub_desc->hlsl_register_b_n < _SG_D3D11_MAX_STAGE_UB_BINDINGS, VALIDATE_SHADERDESC_UNIFORMBLOCK_HLSL_REGISTER_B_OUT_OF_RANGE);
  16925. _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);
  16926. hlsl_buf_bits = _sg_validate_set_slot_bit(hlsl_buf_bits, ub_desc->stage, ub_desc->hlsl_register_b_n);
  16927. #elif defined(SOKOL_WGPU)
  16928. _SG_VALIDATE(ub_desc->wgsl_group0_binding_n < _SG_WGPU_MAX_UB_BINDGROUP_BIND_SLOTS, VALIDATE_SHADERDESC_UNIFORMBLOCK_WGSL_GROUP0_BINDING_OUT_OF_RANGE);
  16929. _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);
  16930. wgsl_group0_bits = _sg_validate_set_slot_bit(wgsl_group0_bits, SG_SHADERSTAGE_NONE, ub_desc->wgsl_group0_binding_n);
  16931. #endif
  16932. #if defined(_SOKOL_ANY_GL)
  16933. bool uniforms_continuous = true;
  16934. uint32_t uniform_offset = 0;
  16935. int num_uniforms = 0;
  16936. for (size_t u_index = 0; u_index < SG_MAX_UNIFORMBLOCK_MEMBERS; u_index++) {
  16937. const sg_glsl_shader_uniform* u_desc = &ub_desc->glsl_uniforms[u_index];
  16938. if (u_desc->type != SG_UNIFORMTYPE_INVALID) {
  16939. _SG_VALIDATE(uniforms_continuous, VALIDATE_SHADERDESC_UNIFORMBLOCK_NO_CONT_MEMBERS);
  16940. _SG_VALIDATE(u_desc->glsl_name, VALIDATE_SHADERDESC_UNIFORMBLOCK_UNIFORM_GLSL_NAME);
  16941. const int array_count = u_desc->array_count;
  16942. _SG_VALIDATE(array_count > 0, VALIDATE_SHADERDESC_UNIFORMBLOCK_ARRAY_COUNT);
  16943. const uint32_t u_align = _sg_uniform_alignment(u_desc->type, array_count, ub_desc->layout);
  16944. const uint32_t u_size = _sg_uniform_size(u_desc->type, array_count, ub_desc->layout);
  16945. uniform_offset = _sg_align_u32(uniform_offset, u_align);
  16946. uniform_offset += u_size;
  16947. num_uniforms++;
  16948. // with std140, arrays are only allowed for FLOAT4, INT4, MAT4
  16949. if (ub_desc->layout == SG_UNIFORMLAYOUT_STD140) {
  16950. if (array_count > 1) {
  16951. _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);
  16952. }
  16953. }
  16954. } else {
  16955. uniforms_continuous = false;
  16956. }
  16957. }
  16958. if (ub_desc->layout == SG_UNIFORMLAYOUT_STD140) {
  16959. uniform_offset = _sg_align_u32(uniform_offset, 16);
  16960. }
  16961. _SG_VALIDATE((size_t)uniform_offset == ub_desc->size, VALIDATE_SHADERDESC_UNIFORMBLOCK_SIZE_MISMATCH);
  16962. _SG_VALIDATE(num_uniforms > 0, VALIDATE_SHADERDESC_UNIFORMBLOCK_NO_MEMBERS);
  16963. #endif
  16964. }
  16965. for (size_t sbuf_idx = 0; sbuf_idx < SG_MAX_STORAGEBUFFER_BINDSLOTS; sbuf_idx++) {
  16966. const sg_shader_storage_buffer* sbuf_desc = &desc->storage_buffers[sbuf_idx];
  16967. if (sbuf_desc->stage == SG_SHADERSTAGE_NONE) {
  16968. continue;
  16969. }
  16970. #if defined(SOKOL_METAL)
  16971. _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);
  16972. _SG_VALIDATE(_sg_validate_slot_bits(msl_buf_bits, sbuf_desc->stage, sbuf_desc->msl_buffer_n), VALIDATE_SHADERDESC_STORAGEBUFFER_METAL_BUFFER_SLOT_COLLISION);
  16973. msl_buf_bits = _sg_validate_set_slot_bit(msl_buf_bits, sbuf_desc->stage, sbuf_desc->msl_buffer_n);
  16974. #elif defined(SOKOL_D3D11)
  16975. if (sbuf_desc->readonly) {
  16976. _SG_VALIDATE(sbuf_desc->hlsl_register_t_n < _SG_D3D11_MAX_STAGE_SRV_BINDINGS, VALIDATE_SHADERDESC_STORAGEBUFFER_HLSL_REGISTER_T_OUT_OF_RANGE);
  16977. _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);
  16978. hlsl_srv_bits = _sg_validate_set_slot_bit(hlsl_srv_bits, sbuf_desc->stage, sbuf_desc->hlsl_register_t_n);
  16979. } else {
  16980. _SG_VALIDATE(sbuf_desc->hlsl_register_u_n < _SG_D3D11_MAX_STAGE_UAV_BINDINGS, VALIDATE_SHADERDESC_STORAGEBUFFER_HLSL_REGISTER_U_OUT_OF_RANGE);
  16981. _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);
  16982. hlsl_uav_bits = _sg_validate_set_slot_bit(hlsl_uav_bits, sbuf_desc->stage, sbuf_desc->hlsl_register_u_n);
  16983. }
  16984. #elif defined(_SOKOL_ANY_GL)
  16985. _SG_VALIDATE(sbuf_desc->glsl_binding_n < _SG_GL_MAX_SBUF_BINDINGS, VALIDATE_SHADERDESC_STORAGEBUFFER_GLSL_BINDING_OUT_OF_RANGE);
  16986. _SG_VALIDATE(_sg_validate_slot_bits(glsl_sbuf_bnd_bits, SG_SHADERSTAGE_NONE, sbuf_desc->glsl_binding_n), VALIDATE_SHADERDESC_STORAGEBUFFER_GLSL_BINDING_COLLISION);
  16987. glsl_sbuf_bnd_bits = _sg_validate_set_slot_bit(glsl_sbuf_bnd_bits, SG_SHADERSTAGE_NONE, sbuf_desc->glsl_binding_n);
  16988. #elif defined(SOKOL_WGPU)
  16989. _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);
  16990. _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);
  16991. wgsl_group1_bits = _sg_validate_set_slot_bit(wgsl_group1_bits, SG_SHADERSTAGE_NONE, sbuf_desc->wgsl_group1_binding_n);
  16992. #endif
  16993. }
  16994. for (size_t simg_idx = 0; simg_idx < SG_MAX_STORAGE_ATTACHMENTS; simg_idx++) {
  16995. const sg_shader_storage_image* simg_desc = &desc->storage_images[simg_idx];
  16996. if (simg_desc->stage == SG_SHADERSTAGE_NONE) {
  16997. continue;
  16998. }
  16999. _SG_VALIDATE(simg_desc->stage == SG_SHADERSTAGE_COMPUTE, VALIDATE_SHADERDESC_STORAGEIMAGE_EXPECT_COMPUTE_STAGE);
  17000. #if defined(SOKOL_METAL)
  17001. _SG_VALIDATE(simg_desc->msl_texture_n < _SG_MTL_MAX_STAGE_TEXTURE_BINDINGS, VALIDATE_SHADERDESC_STORAGEIMAGE_METAL_TEXTURE_SLOT_OUT_OF_RANGE);
  17002. _SG_VALIDATE(_sg_validate_slot_bits(msl_tex_bits, simg_desc->stage, simg_desc->msl_texture_n), VALIDATE_SHADERDESC_STORAGEIMAGE_METAL_TEXTURE_SLOT_COLLISION);
  17003. msl_tex_bits = _sg_validate_set_slot_bit(msl_tex_bits, simg_desc->stage, simg_desc->msl_texture_n);
  17004. #elif defined(SOKOL_D3D11)
  17005. _SG_VALIDATE(simg_desc->hlsl_register_u_n < _SG_D3D11_MAX_STAGE_UAV_BINDINGS, VALIDATE_SHADERDESC_STORAGEIMAGE_HLSL_REGISTER_U_OUT_OF_RANGE);
  17006. _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);
  17007. hlsl_uav_bits = _sg_validate_set_slot_bit(hlsl_uav_bits, simg_desc->stage, simg_desc->hlsl_register_u_n);
  17008. #elif defined(_SOKOL_ANY_GL)
  17009. _SG_VALIDATE(simg_desc->glsl_binding_n < _SG_GL_MAX_SIMG_BINDINGS, VALIDATE_SHADERDESC_STORAGEIMAGE_GLSL_BINDING_OUT_OF_RANGE);
  17010. _SG_VALIDATE(_sg_validate_slot_bits(glsl_simg_bnd_bits, SG_SHADERSTAGE_NONE, simg_desc->glsl_binding_n), VALIDATE_SHADERDESC_STORAGEIMAGE_GLSL_BINDING_COLLISION);
  17011. glsl_simg_bnd_bits = _sg_validate_set_slot_bit(glsl_simg_bnd_bits, SG_SHADERSTAGE_NONE, simg_desc->glsl_binding_n);
  17012. #elif defined(SOKOL_WGPU)
  17013. _SG_VALIDATE(simg_desc->wgsl_group2_binding_n < _SG_WGPU_MAX_SIMG_BIND_SLOTS, VALIDATE_SHADERDESC_STORAGEIMAGE_WGSL_GROUP2_BINDING_OUT_OF_RANGE);
  17014. _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);
  17015. wgsl_group2_bits = _sg_validate_set_slot_bit(wgsl_group2_bits, SG_SHADERSTAGE_NONE, simg_desc->wgsl_group2_binding_n);
  17016. #endif
  17017. }
  17018. uint32_t img_slot_mask = 0;
  17019. for (size_t img_idx = 0; img_idx < SG_MAX_IMAGE_BINDSLOTS; img_idx++) {
  17020. const sg_shader_image* img_desc = &desc->images[img_idx];
  17021. if (img_desc->stage == SG_SHADERSTAGE_NONE) {
  17022. continue;
  17023. }
  17024. img_slot_mask |= (1 << img_idx);
  17025. #if defined(SOKOL_METAL)
  17026. _SG_VALIDATE(img_desc->msl_texture_n < _SG_MTL_MAX_STAGE_TEXTURE_BINDINGS, VALIDATE_SHADERDESC_IMAGE_METAL_TEXTURE_SLOT_OUT_OF_RANGE);
  17027. _SG_VALIDATE(_sg_validate_slot_bits(msl_tex_bits, img_desc->stage, img_desc->msl_texture_n), VALIDATE_SHADERDESC_IMAGE_METAL_TEXTURE_SLOT_COLLISION);
  17028. msl_tex_bits = _sg_validate_set_slot_bit(msl_tex_bits, img_desc->stage, img_desc->msl_texture_n);
  17029. #elif defined(SOKOL_D3D11)
  17030. _SG_VALIDATE(img_desc->hlsl_register_t_n < _SG_D3D11_MAX_STAGE_SRV_BINDINGS, VALIDATE_SHADERDESC_IMAGE_HLSL_REGISTER_T_OUT_OF_RANGE);
  17031. _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);
  17032. hlsl_srv_bits = _sg_validate_set_slot_bit(hlsl_srv_bits, img_desc->stage, img_desc->hlsl_register_t_n);
  17033. #elif defined(SOKOL_WGPU)
  17034. _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);
  17035. _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);
  17036. wgsl_group1_bits = _sg_validate_set_slot_bit(wgsl_group1_bits, SG_SHADERSTAGE_NONE, img_desc->wgsl_group1_binding_n);
  17037. #endif
  17038. }
  17039. uint32_t smp_slot_mask = 0;
  17040. for (size_t smp_idx = 0; smp_idx < SG_MAX_SAMPLER_BINDSLOTS; smp_idx++) {
  17041. const sg_shader_sampler* smp_desc = &desc->samplers[smp_idx];
  17042. if (smp_desc->stage == SG_SHADERSTAGE_NONE) {
  17043. continue;
  17044. }
  17045. smp_slot_mask |= (1 << smp_idx);
  17046. #if defined(SOKOL_METAL)
  17047. _SG_VALIDATE(smp_desc->msl_sampler_n < _SG_MTL_MAX_STAGE_SAMPLER_BINDINGS, VALIDATE_SHADERDESC_SAMPLER_METAL_SAMPLER_SLOT_OUT_OF_RANGE);
  17048. _SG_VALIDATE(_sg_validate_slot_bits(msl_smp_bits, smp_desc->stage, smp_desc->msl_sampler_n), VALIDATE_SHADERDESC_SAMPLER_METAL_SAMPLER_SLOT_COLLISION);
  17049. msl_smp_bits = _sg_validate_set_slot_bit(msl_smp_bits, smp_desc->stage, smp_desc->msl_sampler_n);
  17050. #elif defined(SOKOL_D3D11)
  17051. _SG_VALIDATE(smp_desc->hlsl_register_s_n < _SG_D3D11_MAX_STAGE_SMP_BINDINGS, VALIDATE_SHADERDESC_SAMPLER_HLSL_REGISTER_S_OUT_OF_RANGE);
  17052. _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);
  17053. hlsl_smp_bits = _sg_validate_set_slot_bit(hlsl_smp_bits, smp_desc->stage, smp_desc->hlsl_register_s_n);
  17054. #elif defined(SOKOL_WGPU)
  17055. _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);
  17056. _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);
  17057. wgsl_group1_bits = _sg_validate_set_slot_bit(wgsl_group1_bits, SG_SHADERSTAGE_NONE, smp_desc->wgsl_group1_binding_n);
  17058. #endif
  17059. }
  17060. uint32_t ref_img_slot_mask = 0;
  17061. uint32_t ref_smp_slot_mask = 0;
  17062. for (size_t img_smp_idx = 0; img_smp_idx < SG_MAX_IMAGE_SAMPLER_PAIRS; img_smp_idx++) {
  17063. const sg_shader_image_sampler_pair* img_smp_desc = &desc->image_sampler_pairs[img_smp_idx];
  17064. if (img_smp_desc->stage == SG_SHADERSTAGE_NONE) {
  17065. continue;
  17066. }
  17067. #if defined(_SOKOL_ANY_GL)
  17068. _SG_VALIDATE(img_smp_desc->glsl_name != 0, VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_GLSL_NAME);
  17069. #endif
  17070. const bool img_slot_in_range = img_smp_desc->image_slot < SG_MAX_IMAGE_BINDSLOTS;
  17071. const bool smp_slot_in_range = img_smp_desc->sampler_slot < SG_MAX_SAMPLER_BINDSLOTS;
  17072. _SG_VALIDATE(img_slot_in_range, VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_IMAGE_SLOT_OUT_OF_RANGE);
  17073. _SG_VALIDATE(smp_slot_in_range, VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_SAMPLER_SLOT_OUT_OF_RANGE);
  17074. if (img_slot_in_range && smp_slot_in_range) {
  17075. ref_img_slot_mask |= 1 << img_smp_desc->image_slot;
  17076. ref_smp_slot_mask |= 1 << img_smp_desc->sampler_slot;
  17077. const sg_shader_image* img_desc = &desc->images[img_smp_desc->image_slot];
  17078. const sg_shader_sampler* smp_desc = &desc->samplers[img_smp_desc->sampler_slot];
  17079. _SG_VALIDATE(img_desc->stage == img_smp_desc->stage, VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_IMAGE_STAGE_MISMATCH);
  17080. _SG_VALIDATE(smp_desc->stage == img_smp_desc->stage, VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_SAMPLER_STAGE_MISMATCH);
  17081. const bool needs_nonfiltering = (img_desc->sample_type == SG_IMAGESAMPLETYPE_UINT)
  17082. || (img_desc->sample_type == SG_IMAGESAMPLETYPE_SINT)
  17083. || (img_desc->sample_type == SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT);
  17084. const bool needs_comparison = img_desc->sample_type == SG_IMAGESAMPLETYPE_DEPTH;
  17085. if (needs_nonfiltering) {
  17086. _SG_VALIDATE(needs_nonfiltering && (smp_desc->sampler_type == SG_SAMPLERTYPE_NONFILTERING), VALIDATE_SHADERDESC_NONFILTERING_SAMPLER_REQUIRED);
  17087. }
  17088. if (needs_comparison) {
  17089. _SG_VALIDATE(needs_comparison && (smp_desc->sampler_type == SG_SAMPLERTYPE_COMPARISON), VALIDATE_SHADERDESC_COMPARISON_SAMPLER_REQUIRED);
  17090. }
  17091. }
  17092. }
  17093. // each image and sampler must be referenced by an image sampler
  17094. _SG_VALIDATE(img_slot_mask == ref_img_slot_mask, VALIDATE_SHADERDESC_IMAGE_NOT_REFERENCED_BY_IMAGE_SAMPLER_PAIRS);
  17095. _SG_VALIDATE(smp_slot_mask == ref_smp_slot_mask, VALIDATE_SHADERDESC_SAMPLER_NOT_REFERENCED_BY_IMAGE_SAMPLER_PAIRS);
  17096. return _sg_validate_end();
  17097. #endif
  17098. }
  17099. _SOKOL_PRIVATE bool _sg_validate_pipeline_desc(const sg_pipeline_desc* desc) {
  17100. #if !defined(SOKOL_DEBUG)
  17101. _SOKOL_UNUSED(desc);
  17102. return true;
  17103. #else
  17104. if (_sg.desc.disable_validation) {
  17105. return true;
  17106. }
  17107. SOKOL_ASSERT(desc);
  17108. _sg_validate_begin();
  17109. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_PIPELINEDESC_CANARY);
  17110. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_PIPELINEDESC_CANARY);
  17111. _SG_VALIDATE(desc->shader.id != SG_INVALID_ID, VALIDATE_PIPELINEDESC_SHADER);
  17112. const _sg_shader_t* shd = _sg_lookup_shader(desc->shader.id);
  17113. _SG_VALIDATE(0 != shd, VALIDATE_PIPELINEDESC_SHADER);
  17114. if (shd) {
  17115. _SG_VALIDATE(shd->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_PIPELINEDESC_SHADER);
  17116. if (desc->compute) {
  17117. _SG_VALIDATE(shd->cmn.is_compute, VALIDATE_PIPELINEDESC_COMPUTE_SHADER_EXPECTED);
  17118. } else {
  17119. _SG_VALIDATE(!shd->cmn.is_compute, VALIDATE_PIPELINEDESC_NO_COMPUTE_SHADER_EXPECTED);
  17120. bool attrs_cont = true;
  17121. for (size_t attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  17122. const sg_vertex_attr_state* a_state = &desc->layout.attrs[attr_index];
  17123. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  17124. attrs_cont = false;
  17125. continue;
  17126. }
  17127. _SG_VALIDATE(attrs_cont, VALIDATE_PIPELINEDESC_NO_CONT_ATTRS);
  17128. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  17129. // vertex format must match expected shader attribute base type (if provided)
  17130. if (shd->cmn.attrs[attr_index].base_type != SG_SHADERATTRBASETYPE_UNDEFINED) {
  17131. if (_sg_vertexformat_basetype(a_state->format) != shd->cmn.attrs[attr_index].base_type) {
  17132. _SG_VALIDATE(false, VALIDATE_PIPELINEDESC_ATTR_BASETYPE_MISMATCH);
  17133. _SG_LOGMSG(VALIDATE_PIPELINEDESC_ATTR_BASETYPE_MISMATCH, "attr format:");
  17134. _SG_LOGMSG(VALIDATE_PIPELINEDESC_ATTR_BASETYPE_MISMATCH, _sg_vertexformat_to_string(a_state->format));
  17135. _SG_LOGMSG(VALIDATE_PIPELINEDESC_ATTR_BASETYPE_MISMATCH, "shader attr base type:");
  17136. _SG_LOGMSG(VALIDATE_PIPELINEDESC_ATTR_BASETYPE_MISMATCH, _sg_shaderattrbasetype_to_string(shd->cmn.attrs[attr_index].base_type));
  17137. }
  17138. }
  17139. #if defined(SOKOL_D3D11)
  17140. // on D3D11, semantic names (and semantic indices) must be provided
  17141. _SG_VALIDATE(!_sg_strempty(&shd->d3d11.attrs[attr_index].sem_name), VALIDATE_PIPELINEDESC_ATTR_SEMANTICS);
  17142. #endif
  17143. }
  17144. // must only use readonly storage buffer bindings in render pipelines
  17145. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  17146. if (shd->cmn.storage_buffers[i].stage != SG_SHADERSTAGE_NONE) {
  17147. _SG_VALIDATE(shd->cmn.storage_buffers[i].readonly, VALIDATE_PIPELINEDESC_SHADER_READONLY_STORAGEBUFFERS);
  17148. }
  17149. }
  17150. for (int buf_index = 0; buf_index < SG_MAX_VERTEXBUFFER_BINDSLOTS; buf_index++) {
  17151. const sg_vertex_buffer_layout_state* l_state = &desc->layout.buffers[buf_index];
  17152. if (l_state->stride == 0) {
  17153. continue;
  17154. }
  17155. _SG_VALIDATE(_sg_multiple_u64((uint64_t)l_state->stride, 4), VALIDATE_PIPELINEDESC_LAYOUT_STRIDE4);
  17156. }
  17157. }
  17158. }
  17159. for (size_t color_index = 0; color_index < (size_t)desc->color_count; color_index++) {
  17160. const sg_blend_state* bs = &desc->colors[color_index].blend;
  17161. if ((bs->op_rgb == SG_BLENDOP_MIN) || (bs->op_rgb == SG_BLENDOP_MAX)) {
  17162. _SG_VALIDATE((bs->src_factor_rgb == SG_BLENDFACTOR_ONE) && (bs->dst_factor_rgb == SG_BLENDFACTOR_ONE), VALIDATE_PIPELINEDESC_BLENDOP_MINMAX_REQUIRES_BLENDFACTOR_ONE);
  17163. }
  17164. if ((bs->op_alpha == SG_BLENDOP_MIN) || (bs->op_alpha == SG_BLENDOP_MAX)) {
  17165. _SG_VALIDATE((bs->src_factor_alpha == SG_BLENDFACTOR_ONE) && (bs->dst_factor_alpha == SG_BLENDFACTOR_ONE), VALIDATE_PIPELINEDESC_BLENDOP_MINMAX_REQUIRES_BLENDFACTOR_ONE);
  17166. }
  17167. }
  17168. return _sg_validate_end();
  17169. #endif
  17170. }
  17171. _SOKOL_PRIVATE bool _sg_validate_attachments_desc(const sg_attachments_desc* desc) {
  17172. #if !defined(SOKOL_DEBUG)
  17173. _SOKOL_UNUSED(desc);
  17174. return true;
  17175. #else
  17176. if (_sg.desc.disable_validation) {
  17177. return true;
  17178. }
  17179. SOKOL_ASSERT(desc);
  17180. _sg_validate_begin();
  17181. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_ATTACHMENTSDESC_CANARY);
  17182. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_ATTACHMENTSDESC_CANARY);
  17183. // check color attachments
  17184. bool has_color_atts = false;
  17185. bool has_depth_stencil_att = false;
  17186. {
  17187. bool atts_cont = true;
  17188. int color_width = -1, color_height = -1, color_sample_count = -1;
  17189. for (int att_index = 0; att_index < SG_MAX_COLOR_ATTACHMENTS; att_index++) {
  17190. const sg_attachment_desc* att = &desc->colors[att_index];
  17191. if (att->image.id == SG_INVALID_ID) {
  17192. atts_cont = false;
  17193. continue;
  17194. }
  17195. has_color_atts = true;
  17196. _SG_VALIDATE(atts_cont, VALIDATE_ATTACHMENTSDESC_NO_CONT_COLOR_ATTS);
  17197. const _sg_image_t* img = _sg_lookup_image(att->image.id);
  17198. _SG_VALIDATE(img, VALIDATE_ATTACHMENTSDESC_COLOR_IMAGE);
  17199. if (img) {
  17200. _SG_VALIDATE(img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ATTACHMENTSDESC_COLOR_IMAGE);
  17201. _SG_VALIDATE(img->cmn.usage.render_attachment, VALIDATE_ATTACHMENTSDESC_COLOR_IMAGE_NO_RENDERATTACHMENT);
  17202. _SG_VALIDATE(att->mip_level < img->cmn.num_mipmaps, VALIDATE_ATTACHMENTSDESC_COLOR_MIPLEVEL);
  17203. if (img->cmn.type == SG_IMAGETYPE_CUBE) {
  17204. _SG_VALIDATE(att->slice < 6, VALIDATE_ATTACHMENTSDESC_COLOR_FACE);
  17205. } else if (img->cmn.type == SG_IMAGETYPE_ARRAY) {
  17206. _SG_VALIDATE(att->slice < img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_COLOR_LAYER);
  17207. } else if (img->cmn.type == SG_IMAGETYPE_3D) {
  17208. _SG_VALIDATE(att->slice < img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_COLOR_SLICE);
  17209. }
  17210. if (att_index == 0) {
  17211. color_width = _sg_miplevel_dim(img->cmn.width, att->mip_level);
  17212. color_height = _sg_miplevel_dim(img->cmn.height, att->mip_level);
  17213. color_sample_count = img->cmn.sample_count;
  17214. } else {
  17215. _SG_VALIDATE(color_width == _sg_miplevel_dim(img->cmn.width, att->mip_level), VALIDATE_ATTACHMENTSDESC_IMAGE_SIZES);
  17216. _SG_VALIDATE(color_height == _sg_miplevel_dim(img->cmn.height, att->mip_level), VALIDATE_ATTACHMENTSDESC_IMAGE_SIZES);
  17217. _SG_VALIDATE(color_sample_count == img->cmn.sample_count, VALIDATE_ATTACHMENTSDESC_IMAGE_SAMPLE_COUNTS);
  17218. }
  17219. _SG_VALIDATE(_sg_is_valid_attachment_color_format(img->cmn.pixel_format), VALIDATE_ATTACHMENTSDESC_COLOR_INV_PIXELFORMAT);
  17220. // check resolve attachment
  17221. const sg_attachment_desc* res_att = &desc->resolves[att_index];
  17222. if (res_att->image.id != SG_INVALID_ID) {
  17223. // associated color attachment must be MSAA
  17224. _SG_VALIDATE(img->cmn.sample_count > 1, VALIDATE_ATTACHMENTSDESC_RESOLVE_COLOR_IMAGE_MSAA);
  17225. const _sg_image_t* res_img = _sg_lookup_image(res_att->image.id);
  17226. _SG_VALIDATE(res_img, VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE);
  17227. if (res_img) {
  17228. _SG_VALIDATE(res_img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE);
  17229. _SG_VALIDATE(res_img->cmn.usage.render_attachment, VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_NO_RT);
  17230. _SG_VALIDATE(res_img->cmn.sample_count == 1, VALIDATE_ATTACHMENTSDESC_RESOLVE_SAMPLE_COUNT);
  17231. _SG_VALIDATE(res_att->mip_level < res_img->cmn.num_mipmaps, VALIDATE_ATTACHMENTSDESC_RESOLVE_MIPLEVEL);
  17232. if (res_img->cmn.type == SG_IMAGETYPE_CUBE) {
  17233. _SG_VALIDATE(res_att->slice < SG_CUBEFACE_NUM, VALIDATE_ATTACHMENTSDESC_RESOLVE_FACE);
  17234. } else if (res_img->cmn.type == SG_IMAGETYPE_ARRAY) {
  17235. _SG_VALIDATE(res_att->slice < res_img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_RESOLVE_LAYER);
  17236. } else if (res_img->cmn.type == SG_IMAGETYPE_3D) {
  17237. _SG_VALIDATE(res_att->slice < res_img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_RESOLVE_SLICE);
  17238. }
  17239. _SG_VALIDATE(img->cmn.pixel_format == res_img->cmn.pixel_format, VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_FORMAT);
  17240. _SG_VALIDATE(color_width == _sg_miplevel_dim(res_img->cmn.width, res_att->mip_level), VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_SIZES);
  17241. _SG_VALIDATE(color_height == _sg_miplevel_dim(res_img->cmn.height, res_att->mip_level), VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_SIZES);
  17242. }
  17243. }
  17244. }
  17245. }
  17246. // check depth stencil attachments
  17247. if (desc->depth_stencil.image.id != SG_INVALID_ID) {
  17248. has_depth_stencil_att = true;
  17249. const sg_attachment_desc* att = &desc->depth_stencil;
  17250. const _sg_image_t* img = _sg_lookup_image(att->image.id);
  17251. _SG_VALIDATE(img, VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE);
  17252. if (img) {
  17253. _SG_VALIDATE(img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE);
  17254. _SG_VALIDATE(att->mip_level < img->cmn.num_mipmaps, VALIDATE_ATTACHMENTSDESC_DEPTH_MIPLEVEL);
  17255. if (img->cmn.type == SG_IMAGETYPE_CUBE) {
  17256. _SG_VALIDATE(att->slice < 6, VALIDATE_ATTACHMENTSDESC_DEPTH_FACE);
  17257. } else if (img->cmn.type == SG_IMAGETYPE_ARRAY) {
  17258. _SG_VALIDATE(att->slice < img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_DEPTH_LAYER);
  17259. } else if (img->cmn.type == SG_IMAGETYPE_3D) {
  17260. // NOTE: this can't actually happen because of VALIDATE_IMAGEDESC_DEPTH_3D_IMAGE
  17261. _SG_VALIDATE(att->slice < img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_DEPTH_SLICE);
  17262. }
  17263. _SG_VALIDATE(img->cmn.usage.render_attachment, VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_NO_RENDERATTACHMENT);
  17264. _SG_VALIDATE((color_width == -1) || (color_width == _sg_miplevel_dim(img->cmn.width, att->mip_level)), VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_SIZES);
  17265. _SG_VALIDATE((color_height == -1) || (color_height == _sg_miplevel_dim(img->cmn.height, att->mip_level)), VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_SIZES);
  17266. _SG_VALIDATE((color_sample_count == -1) || (color_sample_count == img->cmn.sample_count), VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_SAMPLE_COUNT);
  17267. _SG_VALIDATE(_sg_is_valid_attachment_depth_format(img->cmn.pixel_format), VALIDATE_ATTACHMENTSDESC_DEPTH_INV_PIXELFORMAT);
  17268. }
  17269. }
  17270. }
  17271. // check storage attachments (note: storage attachments don't need to continuous)
  17272. bool has_storage_atts = false;
  17273. {
  17274. for (int att_index = 0; att_index < SG_MAX_STORAGE_ATTACHMENTS; att_index++) {
  17275. const sg_attachment_desc* att = &desc->storages[att_index];
  17276. if (att->image.id == SG_INVALID_ID) {
  17277. continue;
  17278. }
  17279. has_storage_atts = true;
  17280. const _sg_image_t* img = _sg_lookup_image(att->image.id);
  17281. _SG_VALIDATE(img, VALIDATE_ATTACHMENTSDESC_STORAGE_IMAGE);
  17282. if (img) {
  17283. _SG_VALIDATE(img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ATTACHMENTSDESC_STORAGE_IMAGE);
  17284. _SG_VALIDATE(img->cmn.usage.storage_attachment, VALIDATE_ATTACHMENTSDESC_STORAGE_IMAGE_NO_STORAGEATTACHMENT);
  17285. _SG_VALIDATE(att->mip_level < img->cmn.num_mipmaps, VALIDATE_ATTACHMENTSDESC_STORAGE_MIPLEVEL);
  17286. if (img->cmn.type == SG_IMAGETYPE_CUBE) {
  17287. _SG_VALIDATE(att->slice < 6, VALIDATE_ATTACHMENTSDESC_STORAGE_FACE);
  17288. } else if (img->cmn.type == SG_IMAGETYPE_ARRAY) {
  17289. _SG_VALIDATE(att->slice < img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_STORAGE_LAYER);
  17290. } else if (img->cmn.type == SG_IMAGETYPE_3D) {
  17291. _SG_VALIDATE(att->slice < img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_STORAGE_SLICE);
  17292. }
  17293. _SG_VALIDATE(_sg_is_valid_attachment_storage_format(img->cmn.pixel_format), VALIDATE_ATTACHMENTSDESC_STORAGE_INV_PIXELFORMAT);
  17294. }
  17295. }
  17296. }
  17297. _SG_VALIDATE(has_color_atts || has_depth_stencil_att || has_storage_atts, VALIDATE_ATTACHMENTSDESC_NO_ATTACHMENTS);
  17298. if (has_color_atts || has_depth_stencil_att) {
  17299. _SG_VALIDATE(!has_storage_atts, VALIDATE_ATTACHMENTSDESC_RENDER_VS_STORAGE_ATTACHMENTS);
  17300. }
  17301. if (has_storage_atts) {
  17302. _SG_VALIDATE(!(has_color_atts || has_depth_stencil_att), VALIDATE_ATTACHMENTSDESC_RENDER_VS_STORAGE_ATTACHMENTS);
  17303. }
  17304. return _sg_validate_end();
  17305. #endif
  17306. }
  17307. _SOKOL_PRIVATE bool _sg_validate_begin_pass(const sg_pass* pass) {
  17308. #if !defined(SOKOL_DEBUG)
  17309. _SOKOL_UNUSED(pass);
  17310. return true;
  17311. #else
  17312. if (_sg.desc.disable_validation) {
  17313. return true;
  17314. }
  17315. const bool is_compute_pass = pass->compute;
  17316. const bool is_swapchain_pass = !is_compute_pass && (pass->attachments.id == SG_INVALID_ID);
  17317. const bool is_offscreen_pass = !(is_compute_pass || is_swapchain_pass);
  17318. _sg_validate_begin();
  17319. _SG_VALIDATE(pass->_start_canary == 0, VALIDATE_BEGINPASS_CANARY);
  17320. _SG_VALIDATE(pass->_end_canary == 0, VALIDATE_BEGINPASS_CANARY);
  17321. if (is_compute_pass) {
  17322. // this is a compute pass with optional storage attachments
  17323. if (pass->attachments.id != SG_INVALID_ID) {
  17324. const _sg_attachments_t* atts = _sg_lookup_attachments(pass->attachments.id);
  17325. if (atts) {
  17326. _SG_VALIDATE(atts->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_BEGINPASS_ATTACHMENTS_VALID);
  17327. _SG_VALIDATE(!atts->cmn.has_render_attachments, VALIDATE_BEGINPASS_COMPUTEPASS_STORAGE_ATTACHMENTS_ONLY);
  17328. for (int i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  17329. const _sg_image_ref_t* img_ref = &atts->cmn.storages[i].image;
  17330. const bool img_null = _sg_image_ref_null(img_ref);
  17331. const bool img_alive = _sg_image_ref_alive(img_ref);
  17332. if (!img_null) {
  17333. _SG_VALIDATE(img_alive, VALIDATE_BEGINPASS_STORAGE_ATTACHMENT_IMAGE_ALIVE);
  17334. if (img_alive) {
  17335. _SG_VALIDATE(_sg_image_ref_ptr(img_ref)->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_BEGINPASS_STORAGE_ATTACHMENT_IMAGE_VALID);
  17336. }
  17337. }
  17338. }
  17339. } else {
  17340. _SG_VALIDATE(atts != 0, VALIDATE_BEGINPASS_ATTACHMENTS_EXISTS);
  17341. }
  17342. }
  17343. } else if (is_swapchain_pass) {
  17344. // this is a swapchain pass
  17345. _SG_VALIDATE(pass->swapchain.width > 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_WIDTH);
  17346. _SG_VALIDATE(pass->swapchain.height > 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_HEIGHT);
  17347. _SG_VALIDATE(pass->swapchain.sample_count > 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_SAMPLECOUNT);
  17348. _SG_VALIDATE(pass->swapchain.color_format > SG_PIXELFORMAT_NONE, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_COLORFORMAT);
  17349. // NOTE: depth buffer is optional, so depth_format is allowed to be invalid
  17350. // NOTE: the GL framebuffer handle may actually be 0
  17351. #if defined(SOKOL_METAL)
  17352. _SG_VALIDATE(pass->swapchain.metal.current_drawable != 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_CURRENTDRAWABLE);
  17353. if (pass->swapchain.depth_format == SG_PIXELFORMAT_NONE) {
  17354. _SG_VALIDATE(pass->swapchain.metal.depth_stencil_texture == 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_DEPTHSTENCILTEXTURE_NOTSET);
  17355. } else {
  17356. _SG_VALIDATE(pass->swapchain.metal.depth_stencil_texture != 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_DEPTHSTENCILTEXTURE);
  17357. }
  17358. if (pass->swapchain.sample_count > 1) {
  17359. _SG_VALIDATE(pass->swapchain.metal.msaa_color_texture != 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_MSAACOLORTEXTURE);
  17360. } else {
  17361. _SG_VALIDATE(pass->swapchain.metal.msaa_color_texture == 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_MSAACOLORTEXTURE_NOTSET);
  17362. }
  17363. #elif defined(SOKOL_D3D11)
  17364. _SG_VALIDATE(pass->swapchain.d3d11.render_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RENDERVIEW);
  17365. if (pass->swapchain.depth_format == SG_PIXELFORMAT_NONE) {
  17366. _SG_VALIDATE(pass->swapchain.d3d11.depth_stencil_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_DEPTHSTENCILVIEW_NOTSET);
  17367. } else {
  17368. _SG_VALIDATE(pass->swapchain.d3d11.depth_stencil_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_DEPTHSTENCILVIEW);
  17369. }
  17370. if (pass->swapchain.sample_count > 1) {
  17371. _SG_VALIDATE(pass->swapchain.d3d11.resolve_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RESOLVEVIEW);
  17372. } else {
  17373. _SG_VALIDATE(pass->swapchain.d3d11.resolve_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RESOLVEVIEW_NOTSET);
  17374. }
  17375. #elif defined(SOKOL_WGPU)
  17376. _SG_VALIDATE(pass->swapchain.wgpu.render_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RENDERVIEW);
  17377. if (pass->swapchain.depth_format == SG_PIXELFORMAT_NONE) {
  17378. _SG_VALIDATE(pass->swapchain.wgpu.depth_stencil_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_DEPTHSTENCILVIEW_NOTSET);
  17379. } else {
  17380. _SG_VALIDATE(pass->swapchain.wgpu.depth_stencil_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_DEPTHSTENCILVIEW);
  17381. }
  17382. if (pass->swapchain.sample_count > 1) {
  17383. _SG_VALIDATE(pass->swapchain.wgpu.resolve_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RESOLVEVIEW);
  17384. } else {
  17385. _SG_VALIDATE(pass->swapchain.wgpu.resolve_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RESOLVEVIEW_NOTSET);
  17386. }
  17387. #endif
  17388. } else {
  17389. // this is an 'offscreen pass'
  17390. const _sg_attachments_t* atts = _sg_lookup_attachments(pass->attachments.id);
  17391. if (atts) {
  17392. _SG_VALIDATE(atts->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_BEGINPASS_ATTACHMENTS_VALID);
  17393. _SG_VALIDATE(!atts->cmn.has_storage_attachments, VALIDATE_BEGINPASS_RENDERPASS_RENDER_ATTACHMENTS_ONLY);
  17394. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  17395. {
  17396. const _sg_image_ref_t* img_ref = &atts->cmn.colors[i].image;
  17397. const bool img_null = _sg_image_ref_null(img_ref);
  17398. const bool img_alive = _sg_image_ref_alive(img_ref);
  17399. if (!img_null) {
  17400. _SG_VALIDATE(img_alive, VALIDATE_BEGINPASS_COLOR_ATTACHMENT_IMAGE_ALIVE);
  17401. if (img_alive) {
  17402. _SG_VALIDATE(_sg_image_ref_ptr(img_ref)->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_BEGINPASS_COLOR_ATTACHMENT_IMAGE_VALID);
  17403. }
  17404. }
  17405. }
  17406. {
  17407. const _sg_image_ref_t* img_ref = &atts->cmn.resolves[i].image;
  17408. const bool img_null = _sg_image_ref_null(img_ref);
  17409. const bool img_alive = _sg_image_ref_alive(img_ref);
  17410. if (!img_null) {
  17411. _SG_VALIDATE(img_alive, VALIDATE_BEGINPASS_RESOLVE_ATTACHMENT_IMAGE_ALIVE);
  17412. if (img_alive) {
  17413. _SG_VALIDATE(_sg_image_ref_ptr(img_ref)->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_BEGINPASS_RESOLVE_ATTACHMENT_IMAGE_VALID);
  17414. }
  17415. }
  17416. }
  17417. }
  17418. {
  17419. const _sg_image_ref_t* img_ref = &atts->cmn.depth_stencil.image;
  17420. const bool img_null = _sg_image_ref_null(img_ref);
  17421. const bool img_alive = _sg_image_ref_alive(img_ref);
  17422. if (!img_null) {
  17423. _SG_VALIDATE(img_alive, VALIDATE_BEGINPASS_DEPTHSTENCIL_ATTACHMENT_IMAGE_ALIVE);
  17424. if (img_alive) {
  17425. _SG_VALIDATE(_sg_image_ref_ptr(img_ref)->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_BEGINPASS_DEPTHSTENCIL_ATTACHMENT_IMAGE_VALID);
  17426. }
  17427. }
  17428. }
  17429. } else {
  17430. _SG_VALIDATE(atts != 0, VALIDATE_BEGINPASS_ATTACHMENTS_EXISTS);
  17431. }
  17432. }
  17433. if (is_compute_pass || is_offscreen_pass) {
  17434. _SG_VALIDATE(pass->swapchain.width == 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_WIDTH_NOTSET);
  17435. _SG_VALIDATE(pass->swapchain.height == 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_HEIGHT_NOTSET);
  17436. _SG_VALIDATE(pass->swapchain.sample_count == 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_SAMPLECOUNT_NOTSET);
  17437. _SG_VALIDATE(pass->swapchain.color_format == _SG_PIXELFORMAT_DEFAULT, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_COLORFORMAT_NOTSET);
  17438. _SG_VALIDATE(pass->swapchain.depth_format == _SG_PIXELFORMAT_DEFAULT, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_DEPTHFORMAT_NOTSET);
  17439. #if defined(SOKOL_METAL)
  17440. _SG_VALIDATE(pass->swapchain.metal.current_drawable == 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_CURRENTDRAWABLE_NOTSET);
  17441. _SG_VALIDATE(pass->swapchain.metal.depth_stencil_texture == 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_DEPTHSTENCILTEXTURE_NOTSET);
  17442. _SG_VALIDATE(pass->swapchain.metal.msaa_color_texture == 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_MSAACOLORTEXTURE_NOTSET);
  17443. #elif defined(SOKOL_D3D11)
  17444. _SG_VALIDATE(pass->swapchain.d3d11.render_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RENDERVIEW_NOTSET);
  17445. _SG_VALIDATE(pass->swapchain.d3d11.depth_stencil_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_DEPTHSTENCILVIEW_NOTSET);
  17446. _SG_VALIDATE(pass->swapchain.d3d11.resolve_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RESOLVEVIEW_NOTSET);
  17447. #elif defined(SOKOL_WGPU)
  17448. _SG_VALIDATE(pass->swapchain.wgpu.render_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RENDERVIEW_NOTSET);
  17449. _SG_VALIDATE(pass->swapchain.wgpu.depth_stencil_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_DEPTHSTENCILVIEW_NOTSET);
  17450. _SG_VALIDATE(pass->swapchain.wgpu.resolve_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RESOLVEVIEW_NOTSET);
  17451. #elif defined(_SOKOL_ANY_GL)
  17452. _SG_VALIDATE(pass->swapchain.gl.framebuffer == 0, VALIDATE_BEGINPASS_SWAPCHAIN_GL_EXPECT_FRAMEBUFFER_NOTSET);
  17453. #endif
  17454. }
  17455. return _sg_validate_end();
  17456. #endif
  17457. }
  17458. _SOKOL_PRIVATE bool _sg_validate_apply_viewport(int x, int y, int width, int height, bool origin_top_left) {
  17459. _SOKOL_UNUSED(x);
  17460. _SOKOL_UNUSED(y);
  17461. _SOKOL_UNUSED(width);
  17462. _SOKOL_UNUSED(height);
  17463. _SOKOL_UNUSED(origin_top_left);
  17464. #if !defined(SOKOL_DEBUG)
  17465. return true;
  17466. #else
  17467. if (_sg.desc.disable_validation) {
  17468. return true;
  17469. }
  17470. _sg_validate_begin();
  17471. _SG_VALIDATE(_sg.cur_pass.in_pass && !_sg.cur_pass.is_compute, VALIDATE_AVP_RENDERPASS_EXPECTED);
  17472. return _sg_validate_end();
  17473. #endif
  17474. }
  17475. _SOKOL_PRIVATE bool _sg_validate_apply_scissor_rect(int x, int y, int width, int height, bool origin_top_left) {
  17476. _SOKOL_UNUSED(x);
  17477. _SOKOL_UNUSED(y);
  17478. _SOKOL_UNUSED(width);
  17479. _SOKOL_UNUSED(height);
  17480. _SOKOL_UNUSED(origin_top_left);
  17481. #if !defined(SOKOL_DEBUG)
  17482. return true;
  17483. #else
  17484. if (_sg.desc.disable_validation) {
  17485. return true;
  17486. }
  17487. _sg_validate_begin();
  17488. _SG_VALIDATE(_sg.cur_pass.in_pass && !_sg.cur_pass.is_compute, VALIDATE_ASR_RENDERPASS_EXPECTED);
  17489. return _sg_validate_end();
  17490. #endif
  17491. }
  17492. _SOKOL_PRIVATE bool _sg_validate_apply_pipeline(sg_pipeline pip_id) {
  17493. #if !defined(SOKOL_DEBUG)
  17494. _SOKOL_UNUSED(pip_id);
  17495. return true;
  17496. #else
  17497. if (_sg.desc.disable_validation) {
  17498. return true;
  17499. }
  17500. _sg_validate_begin();
  17501. // the pipeline object must be alive and valid
  17502. _SG_VALIDATE(pip_id.id != SG_INVALID_ID, VALIDATE_APIP_PIPELINE_VALID_ID);
  17503. const _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  17504. _SG_VALIDATE(pip != 0, VALIDATE_APIP_PIPELINE_EXISTS);
  17505. if (!pip) {
  17506. return _sg_validate_end();
  17507. }
  17508. _SG_VALIDATE(pip->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_APIP_PIPELINE_VALID);
  17509. // the pipeline's shader must be alive and valid
  17510. _SG_VALIDATE(_sg.cur_pass.in_pass, VALIDATE_APIP_PASS_EXPECTED);
  17511. const bool shd_alive = _sg_shader_ref_alive(&pip->cmn.shader);
  17512. const _sg_shader_t* shd = shd_alive ? _sg_shader_ref_ptr(&pip->cmn.shader) : 0;
  17513. _SG_VALIDATE(shd_alive, VALIDATE_APIP_PIPELINE_SHADER_ALIVE);
  17514. if (shd_alive) {
  17515. _SG_VALIDATE(shd->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_APIP_PIPELINE_SHADER_VALID);
  17516. } else {
  17517. return _sg_validate_end();
  17518. }
  17519. // if pass attachments exist, check that the attachment object is still valid
  17520. bool atts_null = _sg_attachments_ref_null(&_sg.cur_pass.atts);
  17521. bool atts_alive = _sg_attachments_ref_alive(&_sg.cur_pass.atts);
  17522. const _sg_attachments_t* atts = atts_alive ? _sg_attachments_ref_ptr(&_sg.cur_pass.atts) : 0;
  17523. if (!atts_null) {
  17524. _SG_VALIDATE(atts_alive, VALIDATE_APIP_CURPASS_ATTACHMENTS_ALIVE);
  17525. if (atts) {
  17526. _SG_VALIDATE(atts->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_APIP_CURPASS_ATTACHMENTS_VALID);
  17527. }
  17528. }
  17529. if (pip->cmn.is_compute) {
  17530. _SG_VALIDATE(_sg.cur_pass.is_compute, VALIDATE_APIP_COMPUTEPASS_EXPECTED);
  17531. if (atts) {
  17532. // a compute pass with storage attachments
  17533. // check that the pass storage attachments match the shader expectations
  17534. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  17535. if (shd->cmn.storage_images[i].stage != SG_SHADERSTAGE_NONE) {
  17536. const _sg_image_ref_t* img_ref = &atts->cmn.storages[i].image;
  17537. const bool img_null = _sg_image_ref_null(img_ref);
  17538. const bool img_alive = _sg_image_ref_alive(img_ref);
  17539. _SG_VALIDATE(!img_null, VALIDATE_APIP_EXPECTED_STORAGE_ATTACHMENT_IMAGE);
  17540. if (!img_null) {
  17541. _SG_VALIDATE(img_alive, VALIDATE_APIP_STORAGE_ATTACHMENT_IMAGE_ALIVE);
  17542. if (img_alive) {
  17543. const _sg_image_t* img = _sg_image_ref_ptr(img_ref);
  17544. _SG_VALIDATE(img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_APIP_STORAGE_ATTACHMENT_IMAGE_VALID);
  17545. _SG_VALIDATE(img->cmn.pixel_format == shd->cmn.storage_images[i].access_format, VALIDATE_APIP_STORAGE_ATTACHMENT_PIXELFORMAT);
  17546. _SG_VALIDATE(img->cmn.type == shd->cmn.storage_images[i].image_type, VALIDATE_APIP_STORAGE_ATTACHMENT_IMAGE_TYPE);
  17547. }
  17548. }
  17549. }
  17550. }
  17551. }
  17552. } else {
  17553. _SG_VALIDATE(!_sg.cur_pass.is_compute, VALIDATE_APIP_RENDERPASS_EXPECTED);
  17554. // check that pipeline attributes match current pass attributes
  17555. if (!atts_null) {
  17556. if (atts) {
  17557. // an offscreen pass
  17558. _SG_VALIDATE(pip->cmn.color_count == atts->cmn.num_colors, VALIDATE_APIP_ATT_COUNT);
  17559. for (int i = 0; i < pip->cmn.color_count; i++) {
  17560. const _sg_image_ref_t* img_ref = &atts->cmn.colors[i].image;
  17561. const bool img_null = _sg_image_ref_null(img_ref);
  17562. const bool img_alive = _sg_image_ref_alive(img_ref);
  17563. if (!img_null) {
  17564. _SG_VALIDATE(img_alive, VALIDATE_APIP_COLOR_ATTACHMENT_IMAGE_ALIVE);
  17565. if (img_alive) {
  17566. const _sg_image_t* img = _sg_image_ref_ptr(img_ref);
  17567. _SG_VALIDATE(img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_APIP_COLOR_ATTACHMENT_IMAGE_VALID);
  17568. _SG_VALIDATE(pip->cmn.colors[i].pixel_format == img->cmn.pixel_format, VALIDATE_APIP_COLOR_FORMAT);
  17569. _SG_VALIDATE(pip->cmn.sample_count == img->cmn.sample_count, VALIDATE_APIP_SAMPLE_COUNT);
  17570. }
  17571. }
  17572. }
  17573. {
  17574. const _sg_image_ref_t* img_ref = &atts->cmn.depth_stencil.image;
  17575. const bool img_null = _sg_image_ref_null(img_ref);
  17576. const bool img_alive = _sg_image_ref_alive(img_ref);
  17577. if (!img_null) {
  17578. _SG_VALIDATE(img_alive, VALIDATE_APIP_DEPTHSTENCIL_ATTACHMENT_IMAGE_ALIVE);
  17579. if (img_alive) {
  17580. const _sg_image_t* img = _sg_image_ref_ptr(img_ref);
  17581. _SG_VALIDATE(img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_APIP_DEPTHSTENCIL_ATTACHMENT_IMAGE_VALID);
  17582. _SG_VALIDATE(pip->cmn.depth.pixel_format == img->cmn.pixel_format, VALIDATE_APIP_DEPTH_FORMAT);
  17583. }
  17584. } else {
  17585. _SG_VALIDATE(pip->cmn.depth.pixel_format == SG_PIXELFORMAT_NONE, VALIDATE_APIP_DEPTH_FORMAT);
  17586. }
  17587. }
  17588. }
  17589. } else {
  17590. // default pass
  17591. _SG_VALIDATE(pip->cmn.color_count == 1, VALIDATE_APIP_ATT_COUNT);
  17592. _SG_VALIDATE(pip->cmn.colors[0].pixel_format == _sg.cur_pass.swapchain.color_fmt, VALIDATE_APIP_COLOR_FORMAT);
  17593. _SG_VALIDATE(pip->cmn.depth.pixel_format == _sg.cur_pass.swapchain.depth_fmt, VALIDATE_APIP_DEPTH_FORMAT);
  17594. _SG_VALIDATE(pip->cmn.sample_count == _sg.cur_pass.swapchain.sample_count, VALIDATE_APIP_SAMPLE_COUNT);
  17595. }
  17596. }
  17597. return _sg_validate_end();
  17598. #endif
  17599. }
  17600. _SOKOL_PRIVATE bool _sg_validate_apply_bindings(const sg_bindings* bindings) {
  17601. #if !defined(SOKOL_DEBUG)
  17602. _SOKOL_UNUSED(bindings);
  17603. return true;
  17604. #else
  17605. if (_sg.desc.disable_validation) {
  17606. return true;
  17607. }
  17608. _sg_validate_begin();
  17609. // must be called in a pass
  17610. _SG_VALIDATE(_sg.cur_pass.in_pass, VALIDATE_ABND_PASS_EXPECTED);
  17611. // bindings must not be empty
  17612. bool has_any_bindings = bindings->index_buffer.id != SG_INVALID_ID;
  17613. if (!has_any_bindings) for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  17614. has_any_bindings |= bindings->vertex_buffers[i].id != SG_INVALID_ID;
  17615. }
  17616. if (!has_any_bindings) for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  17617. has_any_bindings |= bindings->images[i].id != SG_INVALID_ID;
  17618. }
  17619. if (!has_any_bindings) for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  17620. has_any_bindings |= bindings->samplers[i].id != SG_INVALID_ID;
  17621. }
  17622. if (!has_any_bindings) for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  17623. has_any_bindings |= bindings->storage_buffers[i].id != SG_INVALID_ID;
  17624. }
  17625. _SG_VALIDATE(has_any_bindings, VALIDATE_ABND_EMPTY_BINDINGS);
  17626. // a pipeline object must have been applied
  17627. const bool pip_null = _sg_pipeline_ref_null(&_sg.cur_pip);
  17628. const bool pip_alive = _sg_pipeline_ref_alive(&_sg.cur_pip);
  17629. _SG_VALIDATE(!pip_null, VALIDATE_ABND_NO_PIPELINE);
  17630. _SG_VALIDATE(pip_alive, VALIDATE_ABND_PIPELINE_ALIVE);
  17631. if (!pip_alive) {
  17632. return _sg_validate_end();
  17633. }
  17634. const _sg_pipeline_t* pip = _sg_pipeline_ref_ptr(&_sg.cur_pip);
  17635. _SG_VALIDATE(pip->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ABND_PIPELINE_VALID);
  17636. const bool shd_alive = _sg_shader_ref_alive(&pip->cmn.shader);
  17637. _SG_VALIDATE(shd_alive, VALIDATE_ABND_PIPELINE_SHADER_ALIVE);
  17638. if (!shd_alive) {
  17639. return _sg_validate_end();
  17640. }
  17641. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  17642. _SG_VALIDATE(shd->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ABND_PIPELINE_SHADER_VALID);
  17643. if (_sg.cur_pass.is_compute) {
  17644. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  17645. _SG_VALIDATE(bindings->vertex_buffers[i].id == SG_INVALID_ID, VALIDATE_ABND_COMPUTE_EXPECTED_NO_VBS);
  17646. }
  17647. } else {
  17648. // has expected vertex buffers, and vertex buffers still exist
  17649. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  17650. if (pip->cmn.vertex_buffer_layout_active[i]) {
  17651. _SG_VALIDATE(bindings->vertex_buffers[i].id != SG_INVALID_ID, VALIDATE_ABND_EXPECTED_VB);
  17652. // buffers in vertex-buffer-slots must have vertex buffer usage
  17653. if (bindings->vertex_buffers[i].id != SG_INVALID_ID) {
  17654. const _sg_buffer_t* buf = _sg_lookup_buffer(bindings->vertex_buffers[i].id);
  17655. _SG_VALIDATE(buf != 0, VALIDATE_ABND_VB_ALIVE);
  17656. // NOTE: state != VALID is legal and skips rendering!
  17657. if (buf && buf->slot.state == SG_RESOURCESTATE_VALID) {
  17658. _SG_VALIDATE(buf->cmn.usage.vertex_buffer, VALIDATE_ABND_VB_TYPE);
  17659. _SG_VALIDATE(!buf->cmn.append_overflow, VALIDATE_ABND_VB_OVERFLOW);
  17660. }
  17661. }
  17662. }
  17663. }
  17664. }
  17665. if (_sg.cur_pass.is_compute) {
  17666. _SG_VALIDATE(bindings->index_buffer.id == SG_INVALID_ID, VALIDATE_ABND_COMPUTE_EXPECTED_NO_IB);
  17667. } else {
  17668. // index buffer expected or not, and index buffer still exists
  17669. if (pip->cmn.index_type == SG_INDEXTYPE_NONE) {
  17670. // pipeline defines non-indexed rendering, but index buffer provided
  17671. _SG_VALIDATE(bindings->index_buffer.id == SG_INVALID_ID, VALIDATE_ABND_IB);
  17672. } else {
  17673. // pipeline defines indexed rendering, but no index buffer provided
  17674. _SG_VALIDATE(bindings->index_buffer.id != SG_INVALID_ID, VALIDATE_ABND_NO_IB);
  17675. }
  17676. if (bindings->index_buffer.id != SG_INVALID_ID) {
  17677. // buffer in index-buffer-slot must have index buffer usage
  17678. const _sg_buffer_t* buf = _sg_lookup_buffer(bindings->index_buffer.id);
  17679. _SG_VALIDATE(buf != 0, VALIDATE_ABND_IB_ALIVE);
  17680. // NOTE: state != VALID is legal and skips rendering!
  17681. if (buf && buf->slot.state == SG_RESOURCESTATE_VALID) {
  17682. _SG_VALIDATE(buf->cmn.usage.index_buffer, VALIDATE_ABND_IB_TYPE);
  17683. _SG_VALIDATE(!buf->cmn.append_overflow, VALIDATE_ABND_IB_OVERFLOW);
  17684. }
  17685. }
  17686. }
  17687. // has expected images
  17688. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  17689. if (shd->cmn.images[i].stage != SG_SHADERSTAGE_NONE) {
  17690. _SG_VALIDATE(bindings->images[i].id != SG_INVALID_ID, VALIDATE_ABND_EXPECTED_IMAGE_BINDING);
  17691. if (bindings->images[i].id != SG_INVALID_ID) {
  17692. const _sg_image_t* img = _sg_lookup_image(bindings->images[i].id);
  17693. _SG_VALIDATE(img != 0, VALIDATE_ABND_IMG_ALIVE);
  17694. // NOTE: state != VALID is legal and skips rendering!
  17695. if (img && img->slot.state == SG_RESOURCESTATE_VALID) {
  17696. _SG_VALIDATE(img->cmn.type == shd->cmn.images[i].image_type, VALIDATE_ABND_IMAGE_TYPE_MISMATCH);
  17697. if (!_sg.features.msaa_image_bindings) {
  17698. _SG_VALIDATE(img->cmn.sample_count == 1, VALIDATE_ABND_IMAGE_MSAA);
  17699. }
  17700. if (shd->cmn.images[i].multisampled) {
  17701. _SG_VALIDATE(img->cmn.sample_count > 1, VALIDATE_ABND_EXPECTED_MULTISAMPLED_IMAGE);
  17702. }
  17703. const _sg_pixelformat_info_t* info = &_sg.formats[img->cmn.pixel_format];
  17704. switch (shd->cmn.images[i].sample_type) {
  17705. case SG_IMAGESAMPLETYPE_FLOAT:
  17706. _SG_VALIDATE(info->filter, VALIDATE_ABND_EXPECTED_FILTERABLE_IMAGE);
  17707. break;
  17708. case SG_IMAGESAMPLETYPE_DEPTH:
  17709. _SG_VALIDATE(info->depth, VALIDATE_ABND_EXPECTED_DEPTH_IMAGE);
  17710. break;
  17711. default:
  17712. break;
  17713. }
  17714. }
  17715. }
  17716. }
  17717. }
  17718. // has expected samplers
  17719. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  17720. if (shd->cmn.samplers[i].stage != SG_SHADERSTAGE_NONE) {
  17721. _SG_VALIDATE(bindings->samplers[i].id != SG_INVALID_ID, VALIDATE_ABND_EXPECTED_SAMPLER_BINDING);
  17722. if (bindings->samplers[i].id != SG_INVALID_ID) {
  17723. const _sg_sampler_t* smp = _sg_lookup_sampler(bindings->samplers[i].id);
  17724. _SG_VALIDATE(smp != 0, VALIDATE_ABND_SMP_ALIVE);
  17725. if (smp) {
  17726. // NOTE: for samplers we're specifically checking that they are in valid state
  17727. // (technically an invalid sample skips rendering, but an invalid sampler is
  17728. // most likely an oversight)
  17729. _SG_VALIDATE(smp->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ABND_SMP_VALID);
  17730. if (shd->cmn.samplers[i].sampler_type == SG_SAMPLERTYPE_COMPARISON) {
  17731. _SG_VALIDATE(smp->cmn.compare != SG_COMPAREFUNC_NEVER, VALIDATE_ABND_UNEXPECTED_SAMPLER_COMPARE_NEVER);
  17732. } else {
  17733. _SG_VALIDATE(smp->cmn.compare == SG_COMPAREFUNC_NEVER, VALIDATE_ABND_EXPECTED_SAMPLER_COMPARE_NEVER);
  17734. }
  17735. if (shd->cmn.samplers[i].sampler_type == SG_SAMPLERTYPE_NONFILTERING) {
  17736. const bool nonfiltering = (smp->cmn.min_filter != SG_FILTER_LINEAR)
  17737. && (smp->cmn.mag_filter != SG_FILTER_LINEAR)
  17738. && (smp->cmn.mipmap_filter != SG_FILTER_LINEAR);
  17739. _SG_VALIDATE(nonfiltering, VALIDATE_ABND_EXPECTED_NONFILTERING_SAMPLER);
  17740. }
  17741. }
  17742. }
  17743. }
  17744. }
  17745. // has expected storage buffers
  17746. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  17747. if (shd->cmn.storage_buffers[i].stage != SG_SHADERSTAGE_NONE) {
  17748. _SG_VALIDATE(bindings->storage_buffers[i].id != SG_INVALID_ID, VALIDATE_ABND_EXPECTED_STORAGEBUFFER_BINDING);
  17749. if (bindings->storage_buffers[i].id != SG_INVALID_ID) {
  17750. const _sg_buffer_t* sbuf = _sg_lookup_buffer(bindings->storage_buffers[i].id);
  17751. _SG_VALIDATE(sbuf != 0, VALIDATE_ABND_STORAGEBUFFER_ALIVE);
  17752. // NOTE: state != VALID is legal and skips rendering!
  17753. if (sbuf && sbuf->slot.state == SG_RESOURCESTATE_VALID) {
  17754. _SG_VALIDATE(sbuf->cmn.usage.storage_buffer, VALIDATE_ABND_STORAGEBUFFER_BINDING_BUFFERTYPE);
  17755. // read/write bindings are only allowed for immutable buffers
  17756. if (!shd->cmn.storage_buffers[i].readonly) {
  17757. _SG_VALIDATE(sbuf->cmn.usage.immutable, VALIDATE_ABND_STORAGEBUFFER_READWRITE_IMMUTABLE);
  17758. }
  17759. }
  17760. }
  17761. }
  17762. }
  17763. // the same image cannot be bound as texture and pass attachment
  17764. if (!_sg_attachments_ref_null(&_sg.cur_pass.atts)) {
  17765. const _sg_attachments_t* atts = _sg_attachments_ref_ptr(&_sg.cur_pass.atts);
  17766. for (size_t img_idx = 0; img_idx < SG_MAX_IMAGE_BINDSLOTS; img_idx++) {
  17767. if (shd->cmn.images[img_idx].stage != SG_SHADERSTAGE_NONE) {
  17768. const uint32_t img_id = bindings->images[img_idx].id;
  17769. if (img_id == SG_INVALID_ID) {
  17770. continue;
  17771. }
  17772. _SG_VALIDATE(img_id != atts->cmn.depth_stencil.image.sref.id, VALIDATE_ABND_IMAGE_BINDING_VS_DEPTHSTENCIL_ATTACHMENT);
  17773. for (size_t att_idx = 0; att_idx < SG_MAX_COLOR_ATTACHMENTS; att_idx++) {
  17774. _SG_VALIDATE(img_id != atts->cmn.colors[att_idx].image.sref.id, VALIDATE_ABND_IMAGE_BINDING_VS_COLOR_ATTACHMENT);
  17775. _SG_VALIDATE(img_id != atts->cmn.resolves[att_idx].image.sref.id, VALIDATE_ABND_IMAGE_BINDING_VS_RESOLVE_ATTACHMENT);
  17776. }
  17777. for (size_t att_idx = 0; att_idx < SG_MAX_STORAGE_ATTACHMENTS; att_idx++) {
  17778. _SG_VALIDATE(img_id != atts->cmn.storages[att_idx].image.sref.id, VALIDATE_ABND_IMAGE_BINDING_VS_STORAGE_ATTACHMENT);
  17779. }
  17780. }
  17781. }
  17782. }
  17783. return _sg_validate_end();
  17784. #endif
  17785. }
  17786. _SOKOL_PRIVATE bool _sg_validate_apply_uniforms(int ub_slot, const sg_range* data) {
  17787. #if !defined(SOKOL_DEBUG)
  17788. _SOKOL_UNUSED(ub_slot);
  17789. _SOKOL_UNUSED(data);
  17790. return true;
  17791. #else
  17792. if (_sg.desc.disable_validation) {
  17793. return true;
  17794. }
  17795. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  17796. _sg_validate_begin();
  17797. _SG_VALIDATE(_sg.cur_pass.in_pass, VALIDATE_AU_PASS_EXPECTED);
  17798. const _sg_pipeline_ref_t* pip_ref = &_sg.cur_pip;
  17799. const bool pip_null = _sg_pipeline_ref_null(pip_ref);
  17800. const bool pip_alive = _sg_pipeline_ref_alive(pip_ref);
  17801. _SG_VALIDATE(!pip_null, VALIDATE_AU_NO_PIPELINE);
  17802. _SG_VALIDATE(pip_alive, VALIDATE_AU_PIPELINE_ALIVE);
  17803. if (pip_alive) {
  17804. const _sg_pipeline_t* pip = _sg_pipeline_ref_ptr(pip_ref);
  17805. _SG_VALIDATE(pip->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_AU_PIPELINE_VALID);
  17806. const _sg_shader_ref_t* shd_ref = &pip->cmn.shader;
  17807. const bool shd_alive = _sg_shader_ref_alive(shd_ref);
  17808. _SG_VALIDATE(shd_alive, VALIDATE_AU_PIPELINE_SHADER_ALIVE);
  17809. if (shd_alive) {
  17810. const _sg_shader_t* shd = _sg_shader_ref_ptr(shd_ref);
  17811. _SG_VALIDATE(shd->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_AU_PIPELINE_SHADER_VALID);
  17812. _SG_VALIDATE(shd->cmn.uniform_blocks[ub_slot].stage != SG_SHADERSTAGE_NONE, VALIDATE_AU_NO_UNIFORMBLOCK_AT_SLOT);
  17813. _SG_VALIDATE(data->size == shd->cmn.uniform_blocks[ub_slot].size, VALIDATE_AU_SIZE);
  17814. }
  17815. }
  17816. return _sg_validate_end();
  17817. #endif
  17818. }
  17819. _SOKOL_PRIVATE bool _sg_validate_draw(int base_element, int num_elements, int num_instances) {
  17820. #if !defined(SOKOL_DEBUG)
  17821. _SOKOL_UNUSED(base_element);
  17822. _SOKOL_UNUSED(num_elements);
  17823. _SOKOL_UNUSED(num_instances);
  17824. return true;
  17825. #else
  17826. if (_sg.desc.disable_validation) {
  17827. return true;
  17828. }
  17829. _sg_validate_begin();
  17830. _SG_VALIDATE(_sg.cur_pass.in_pass && !_sg.cur_pass.is_compute, VALIDATE_DRAW_RENDERPASS_EXPECTED);
  17831. _SG_VALIDATE(base_element >= 0, VALIDATE_DRAW_BASEELEMENT);
  17832. _SG_VALIDATE(num_elements >= 0, VALIDATE_DRAW_NUMELEMENTS);
  17833. _SG_VALIDATE(num_instances >= 0, VALIDATE_DRAW_NUMINSTANCES);
  17834. _SG_VALIDATE(_sg.required_bindings_and_uniforms == _sg.applied_bindings_and_uniforms, VALIDATE_DRAW_REQUIRED_BINDINGS_OR_UNIFORMS_MISSING);
  17835. return _sg_validate_end();
  17836. #endif
  17837. }
  17838. _SOKOL_PRIVATE bool _sg_validate_dispatch(int num_groups_x, int num_groups_y, int num_groups_z) {
  17839. #if !defined(SOKOL_DEBUG)
  17840. _SOKOL_UNUSED(num_groups_x);
  17841. _SOKOL_UNUSED(num_groups_y);
  17842. _SOKOL_UNUSED(num_groups_z);
  17843. return true;
  17844. #else
  17845. if (_sg.desc.disable_validation) {
  17846. return true;
  17847. }
  17848. _sg_validate_begin();
  17849. _SG_VALIDATE(_sg.cur_pass.in_pass && _sg.cur_pass.is_compute, VALIDATE_DISPATCH_COMPUTEPASS_EXPECTED);
  17850. _SG_VALIDATE((num_groups_x >= 0) && (num_groups_x < (1<<16)), VALIDATE_DISPATCH_NUMGROUPSX);
  17851. _SG_VALIDATE((num_groups_y >= 0) && (num_groups_y < (1<<16)), VALIDATE_DISPATCH_NUMGROUPSY);
  17852. _SG_VALIDATE((num_groups_z >= 0) && (num_groups_z < (1<<16)), VALIDATE_DISPATCH_NUMGROUPSZ);
  17853. _SG_VALIDATE(_sg.required_bindings_and_uniforms == _sg.applied_bindings_and_uniforms, VALIDATE_DRAW_REQUIRED_BINDINGS_OR_UNIFORMS_MISSING);
  17854. return _sg_validate_end();
  17855. #endif
  17856. }
  17857. _SOKOL_PRIVATE bool _sg_validate_update_buffer(const _sg_buffer_t* buf, const sg_range* data) {
  17858. #if !defined(SOKOL_DEBUG)
  17859. _SOKOL_UNUSED(buf);
  17860. _SOKOL_UNUSED(data);
  17861. return true;
  17862. #else
  17863. if (_sg.desc.disable_validation) {
  17864. return true;
  17865. }
  17866. SOKOL_ASSERT(buf && data && data->ptr);
  17867. _sg_validate_begin();
  17868. _SG_VALIDATE(!buf->cmn.usage.immutable, VALIDATE_UPDATEBUF_USAGE);
  17869. _SG_VALIDATE(buf->cmn.size >= (int)data->size, VALIDATE_UPDATEBUF_SIZE);
  17870. _SG_VALIDATE(buf->cmn.update_frame_index != _sg.frame_index, VALIDATE_UPDATEBUF_ONCE);
  17871. _SG_VALIDATE(buf->cmn.append_frame_index != _sg.frame_index, VALIDATE_UPDATEBUF_APPEND);
  17872. return _sg_validate_end();
  17873. #endif
  17874. }
  17875. _SOKOL_PRIVATE bool _sg_validate_append_buffer(const _sg_buffer_t* buf, const sg_range* data) {
  17876. #if !defined(SOKOL_DEBUG)
  17877. _SOKOL_UNUSED(buf);
  17878. _SOKOL_UNUSED(data);
  17879. return true;
  17880. #else
  17881. if (_sg.desc.disable_validation) {
  17882. return true;
  17883. }
  17884. SOKOL_ASSERT(buf && data && data->ptr);
  17885. _sg_validate_begin();
  17886. _SG_VALIDATE(!buf->cmn.usage.immutable, VALIDATE_APPENDBUF_USAGE);
  17887. _SG_VALIDATE(buf->cmn.size >= (buf->cmn.append_pos + (int)data->size), VALIDATE_APPENDBUF_SIZE);
  17888. _SG_VALIDATE(buf->cmn.update_frame_index != _sg.frame_index, VALIDATE_APPENDBUF_UPDATE);
  17889. return _sg_validate_end();
  17890. #endif
  17891. }
  17892. _SOKOL_PRIVATE bool _sg_validate_update_image(const _sg_image_t* img, const sg_image_data* data) {
  17893. #if !defined(SOKOL_DEBUG)
  17894. _SOKOL_UNUSED(img);
  17895. _SOKOL_UNUSED(data);
  17896. return true;
  17897. #else
  17898. if (_sg.desc.disable_validation) {
  17899. return true;
  17900. }
  17901. SOKOL_ASSERT(img && data);
  17902. _sg_validate_begin();
  17903. _SG_VALIDATE(!img->cmn.usage.immutable, VALIDATE_UPDIMG_USAGE);
  17904. _SG_VALIDATE(img->cmn.upd_frame_index != _sg.frame_index, VALIDATE_UPDIMG_ONCE);
  17905. _sg_validate_image_data(data,
  17906. img->cmn.pixel_format,
  17907. img->cmn.width,
  17908. img->cmn.height,
  17909. (img->cmn.type == SG_IMAGETYPE_CUBE) ? 6 : 1,
  17910. img->cmn.num_mipmaps,
  17911. img->cmn.num_slices);
  17912. return _sg_validate_end();
  17913. #endif
  17914. }
  17915. // ██████ ███████ ███████ ██████ ██ ██ ██████ ██████ ███████ ███████
  17916. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  17917. // ██████ █████ ███████ ██ ██ ██ ██ ██████ ██ █████ ███████
  17918. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  17919. // ██ ██ ███████ ███████ ██████ ██████ ██ ██ ██████ ███████ ███████
  17920. //
  17921. // >>resources
  17922. _SOKOL_PRIVATE sg_buffer_usage _sg_buffer_usage_defaults(const sg_buffer_usage* usg) {
  17923. sg_buffer_usage def = *usg;
  17924. if (!(def.vertex_buffer || def.index_buffer || def.storage_buffer)) {
  17925. def.vertex_buffer = true;
  17926. }
  17927. if (!(def.immutable || def.stream_update || def.dynamic_update)) {
  17928. def.immutable = true;
  17929. }
  17930. return def;
  17931. }
  17932. _SOKOL_PRIVATE sg_buffer_desc _sg_buffer_desc_defaults(const sg_buffer_desc* desc) {
  17933. sg_buffer_desc def = *desc;
  17934. def.usage = _sg_buffer_usage_defaults(&def.usage);
  17935. if (def.size == 0) {
  17936. def.size = def.data.size;
  17937. }
  17938. return def;
  17939. }
  17940. _SOKOL_PRIVATE sg_image_usage _sg_image_usage_defaults(const sg_image_usage *usg) {
  17941. sg_image_usage def = *usg;
  17942. if (!(def.immutable || def.stream_update || def.dynamic_update)) {
  17943. def.immutable = true;
  17944. }
  17945. return def;
  17946. }
  17947. _SOKOL_PRIVATE sg_image_desc _sg_image_desc_defaults(const sg_image_desc* desc) {
  17948. sg_image_desc def = *desc;
  17949. def.type = _sg_def(def.type, SG_IMAGETYPE_2D);
  17950. def.usage = _sg_image_usage_defaults(&def.usage);
  17951. def.num_slices = _sg_def(def.num_slices, 1);
  17952. def.num_mipmaps = _sg_def(def.num_mipmaps, 1);
  17953. if (def.usage.render_attachment) {
  17954. def.pixel_format = _sg_def(def.pixel_format, _sg.desc.environment.defaults.color_format);
  17955. def.sample_count = _sg_def(def.sample_count, _sg.desc.environment.defaults.sample_count);
  17956. } else {
  17957. def.pixel_format = _sg_def(def.pixel_format, SG_PIXELFORMAT_RGBA8);
  17958. def.sample_count = _sg_def(def.sample_count, 1);
  17959. }
  17960. return def;
  17961. }
  17962. _SOKOL_PRIVATE sg_sampler_desc _sg_sampler_desc_defaults(const sg_sampler_desc* desc) {
  17963. sg_sampler_desc def = *desc;
  17964. def.min_filter = _sg_def(def.min_filter, SG_FILTER_NEAREST);
  17965. def.mag_filter = _sg_def(def.mag_filter, SG_FILTER_NEAREST);
  17966. def.mipmap_filter = _sg_def(def.mipmap_filter, SG_FILTER_NEAREST);
  17967. def.wrap_u = _sg_def(def.wrap_u, SG_WRAP_REPEAT);
  17968. def.wrap_v = _sg_def(def.wrap_v, SG_WRAP_REPEAT);
  17969. def.wrap_w = _sg_def(def.wrap_w, SG_WRAP_REPEAT);
  17970. def.max_lod = _sg_def_flt(def.max_lod, FLT_MAX);
  17971. def.border_color = _sg_def(def.border_color, SG_BORDERCOLOR_OPAQUE_BLACK);
  17972. def.compare = _sg_def(def.compare, SG_COMPAREFUNC_NEVER);
  17973. def.max_anisotropy = _sg_def(def.max_anisotropy, 1);
  17974. return def;
  17975. }
  17976. _SOKOL_PRIVATE sg_shader_desc _sg_shader_desc_defaults(const sg_shader_desc* desc) {
  17977. sg_shader_desc def = *desc;
  17978. #if defined(SOKOL_METAL)
  17979. def.vertex_func.entry = _sg_def(def.vertex_func.entry, "_main");
  17980. def.fragment_func.entry = _sg_def(def.fragment_func.entry, "_main");
  17981. def.compute_func.entry = _sg_def(def.compute_func.entry, "_main");
  17982. #else
  17983. def.vertex_func.entry = _sg_def(def.vertex_func.entry, "main");
  17984. def.fragment_func.entry = _sg_def(def.fragment_func.entry, "main");
  17985. def.compute_func.entry = _sg_def(def.compute_func.entry, "main");
  17986. #endif
  17987. #if defined(SOKOL_D3D11)
  17988. if (def.vertex_func.source) {
  17989. def.vertex_func.d3d11_target = _sg_def(def.vertex_func.d3d11_target, "vs_4_0");
  17990. }
  17991. if (def.fragment_func.source) {
  17992. def.fragment_func.d3d11_target = _sg_def(def.fragment_func.d3d11_target, "ps_4_0");
  17993. }
  17994. if (def.compute_func.source) {
  17995. def.compute_func.d3d11_target = _sg_def(def.fragment_func.d3d11_target,"cs_5_0");
  17996. }
  17997. #endif
  17998. def.mtl_threads_per_threadgroup.y = _sg_def(desc->mtl_threads_per_threadgroup.y, 1);
  17999. def.mtl_threads_per_threadgroup.z = _sg_def(desc->mtl_threads_per_threadgroup.z, 1);
  18000. for (size_t ub_index = 0; ub_index < SG_MAX_UNIFORMBLOCK_BINDSLOTS; ub_index++) {
  18001. sg_shader_uniform_block* ub_desc = &def.uniform_blocks[ub_index];
  18002. if (ub_desc->stage != SG_SHADERSTAGE_NONE) {
  18003. ub_desc->layout = _sg_def(ub_desc->layout, SG_UNIFORMLAYOUT_NATIVE);
  18004. for (size_t u_index = 0; u_index < SG_MAX_UNIFORMBLOCK_MEMBERS; u_index++) {
  18005. sg_glsl_shader_uniform* u_desc = &ub_desc->glsl_uniforms[u_index];
  18006. if (u_desc->type == SG_UNIFORMTYPE_INVALID) {
  18007. break;
  18008. }
  18009. u_desc->array_count = _sg_def(u_desc->array_count, 1);
  18010. }
  18011. }
  18012. }
  18013. for (size_t img_index = 0; img_index < SG_MAX_IMAGE_BINDSLOTS; img_index++) {
  18014. sg_shader_image* img_desc = &def.images[img_index];
  18015. if (img_desc->stage != SG_SHADERSTAGE_NONE) {
  18016. img_desc->image_type = _sg_def(img_desc->image_type, SG_IMAGETYPE_2D);
  18017. img_desc->sample_type = _sg_def(img_desc->sample_type, SG_IMAGESAMPLETYPE_FLOAT);
  18018. }
  18019. }
  18020. for (size_t smp_index = 0; smp_index < SG_MAX_SAMPLER_BINDSLOTS; smp_index++) {
  18021. sg_shader_sampler* smp_desc = &def.samplers[smp_index];
  18022. if (smp_desc->stage != SG_SHADERSTAGE_NONE) {
  18023. smp_desc->sampler_type = _sg_def(smp_desc->sampler_type, SG_SAMPLERTYPE_FILTERING);
  18024. }
  18025. }
  18026. return def;
  18027. }
  18028. _SOKOL_PRIVATE sg_pipeline_desc _sg_pipeline_desc_defaults(const sg_pipeline_desc* desc) {
  18029. sg_pipeline_desc def = *desc;
  18030. // FIXME: should we actually do all this stuff for a compute pipeline?
  18031. def.primitive_type = _sg_def(def.primitive_type, SG_PRIMITIVETYPE_TRIANGLES);
  18032. def.index_type = _sg_def(def.index_type, SG_INDEXTYPE_NONE);
  18033. def.cull_mode = _sg_def(def.cull_mode, SG_CULLMODE_NONE);
  18034. def.face_winding = _sg_def(def.face_winding, SG_FACEWINDING_CW);
  18035. def.sample_count = _sg_def(def.sample_count, _sg.desc.environment.defaults.sample_count);
  18036. def.stencil.front.compare = _sg_def(def.stencil.front.compare, SG_COMPAREFUNC_ALWAYS);
  18037. def.stencil.front.fail_op = _sg_def(def.stencil.front.fail_op, SG_STENCILOP_KEEP);
  18038. def.stencil.front.depth_fail_op = _sg_def(def.stencil.front.depth_fail_op, SG_STENCILOP_KEEP);
  18039. def.stencil.front.pass_op = _sg_def(def.stencil.front.pass_op, SG_STENCILOP_KEEP);
  18040. def.stencil.back.compare = _sg_def(def.stencil.back.compare, SG_COMPAREFUNC_ALWAYS);
  18041. def.stencil.back.fail_op = _sg_def(def.stencil.back.fail_op, SG_STENCILOP_KEEP);
  18042. def.stencil.back.depth_fail_op = _sg_def(def.stencil.back.depth_fail_op, SG_STENCILOP_KEEP);
  18043. def.stencil.back.pass_op = _sg_def(def.stencil.back.pass_op, SG_STENCILOP_KEEP);
  18044. def.depth.compare = _sg_def(def.depth.compare, SG_COMPAREFUNC_ALWAYS);
  18045. def.depth.pixel_format = _sg_def(def.depth.pixel_format, _sg.desc.environment.defaults.depth_format);
  18046. if (def.colors[0].pixel_format == SG_PIXELFORMAT_NONE) {
  18047. // special case depth-only rendering, enforce a color count of 0
  18048. def.color_count = 0;
  18049. } else {
  18050. def.color_count = _sg_def(def.color_count, 1);
  18051. }
  18052. if (def.color_count > SG_MAX_COLOR_ATTACHMENTS) {
  18053. def.color_count = SG_MAX_COLOR_ATTACHMENTS;
  18054. }
  18055. for (int i = 0; i < def.color_count; i++) {
  18056. sg_color_target_state* cs = &def.colors[i];
  18057. cs->pixel_format = _sg_def(cs->pixel_format, _sg.desc.environment.defaults.color_format);
  18058. cs->write_mask = _sg_def(cs->write_mask, SG_COLORMASK_RGBA);
  18059. sg_blend_state* bs = &def.colors[i].blend;
  18060. bs->op_rgb = _sg_def(bs->op_rgb, SG_BLENDOP_ADD);
  18061. bs->src_factor_rgb = _sg_def(bs->src_factor_rgb, SG_BLENDFACTOR_ONE);
  18062. if ((bs->op_rgb == SG_BLENDOP_MIN) || (bs->op_rgb == SG_BLENDOP_MAX)) {
  18063. bs->dst_factor_rgb = _sg_def(bs->dst_factor_rgb, SG_BLENDFACTOR_ONE);
  18064. } else {
  18065. bs->dst_factor_rgb = _sg_def(bs->dst_factor_rgb, SG_BLENDFACTOR_ZERO);
  18066. }
  18067. bs->op_alpha = _sg_def(bs->op_alpha, SG_BLENDOP_ADD);
  18068. bs->src_factor_alpha = _sg_def(bs->src_factor_alpha, SG_BLENDFACTOR_ONE);
  18069. if ((bs->op_alpha == SG_BLENDOP_MIN) || (bs->op_alpha == SG_BLENDOP_MAX)) {
  18070. bs->dst_factor_alpha = _sg_def(bs->dst_factor_alpha, SG_BLENDFACTOR_ONE);
  18071. } else {
  18072. bs->dst_factor_alpha = _sg_def(bs->dst_factor_alpha, SG_BLENDFACTOR_ZERO);
  18073. }
  18074. }
  18075. for (int attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  18076. sg_vertex_attr_state* a_state = &def.layout.attrs[attr_index];
  18077. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  18078. break;
  18079. }
  18080. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  18081. sg_vertex_buffer_layout_state* l_state = &def.layout.buffers[a_state->buffer_index];
  18082. l_state->step_func = _sg_def(l_state->step_func, SG_VERTEXSTEP_PER_VERTEX);
  18083. l_state->step_rate = _sg_def(l_state->step_rate, 1);
  18084. }
  18085. // resolve vertex layout strides and offsets
  18086. int auto_offset[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  18087. _sg_clear(auto_offset, sizeof(auto_offset));
  18088. bool use_auto_offset = true;
  18089. for (int attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  18090. // to use computed offsets, *all* attr offsets must be 0
  18091. if (def.layout.attrs[attr_index].offset != 0) {
  18092. use_auto_offset = false;
  18093. }
  18094. }
  18095. for (int attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  18096. sg_vertex_attr_state* a_state = &def.layout.attrs[attr_index];
  18097. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  18098. break;
  18099. }
  18100. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  18101. if (use_auto_offset) {
  18102. a_state->offset = auto_offset[a_state->buffer_index];
  18103. }
  18104. auto_offset[a_state->buffer_index] += _sg_vertexformat_bytesize(a_state->format);
  18105. }
  18106. // compute vertex strides if needed
  18107. for (int buf_index = 0; buf_index < SG_MAX_VERTEXBUFFER_BINDSLOTS; buf_index++) {
  18108. sg_vertex_buffer_layout_state* l_state = &def.layout.buffers[buf_index];
  18109. if (l_state->stride == 0) {
  18110. l_state->stride = auto_offset[buf_index];
  18111. }
  18112. }
  18113. return def;
  18114. }
  18115. _SOKOL_PRIVATE sg_attachments_desc _sg_attachments_desc_defaults(const sg_attachments_desc* desc) {
  18116. sg_attachments_desc def = *desc;
  18117. return def;
  18118. }
  18119. _SOKOL_PRIVATE sg_buffer _sg_alloc_buffer(void) {
  18120. sg_buffer res;
  18121. int slot_index = _sg_pool_alloc_index(&_sg.pools.buffer_pool);
  18122. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  18123. res.id = _sg_slot_alloc(&_sg.pools.buffer_pool, &_sg.pools.buffers[slot_index].slot, slot_index);
  18124. } else {
  18125. res.id = SG_INVALID_ID;
  18126. _SG_ERROR(BUFFER_POOL_EXHAUSTED);
  18127. }
  18128. return res;
  18129. }
  18130. _SOKOL_PRIVATE sg_image _sg_alloc_image(void) {
  18131. sg_image res;
  18132. int slot_index = _sg_pool_alloc_index(&_sg.pools.image_pool);
  18133. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  18134. res.id = _sg_slot_alloc(&_sg.pools.image_pool, &_sg.pools.images[slot_index].slot, slot_index);
  18135. } else {
  18136. res.id = SG_INVALID_ID;
  18137. _SG_ERROR(IMAGE_POOL_EXHAUSTED);
  18138. }
  18139. return res;
  18140. }
  18141. _SOKOL_PRIVATE sg_sampler _sg_alloc_sampler(void) {
  18142. sg_sampler res;
  18143. int slot_index = _sg_pool_alloc_index(&_sg.pools.sampler_pool);
  18144. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  18145. res.id = _sg_slot_alloc(&_sg.pools.sampler_pool, &_sg.pools.samplers[slot_index].slot, slot_index);
  18146. } else {
  18147. res.id = SG_INVALID_ID;
  18148. _SG_ERROR(SAMPLER_POOL_EXHAUSTED);
  18149. }
  18150. return res;
  18151. }
  18152. _SOKOL_PRIVATE sg_shader _sg_alloc_shader(void) {
  18153. sg_shader res;
  18154. int slot_index = _sg_pool_alloc_index(&_sg.pools.shader_pool);
  18155. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  18156. res.id = _sg_slot_alloc(&_sg.pools.shader_pool, &_sg.pools.shaders[slot_index].slot, slot_index);
  18157. } else {
  18158. res.id = SG_INVALID_ID;
  18159. _SG_ERROR(SHADER_POOL_EXHAUSTED);
  18160. }
  18161. return res;
  18162. }
  18163. _SOKOL_PRIVATE sg_pipeline _sg_alloc_pipeline(void) {
  18164. sg_pipeline res;
  18165. int slot_index = _sg_pool_alloc_index(&_sg.pools.pipeline_pool);
  18166. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  18167. res.id =_sg_slot_alloc(&_sg.pools.pipeline_pool, &_sg.pools.pipelines[slot_index].slot, slot_index);
  18168. } else {
  18169. res.id = SG_INVALID_ID;
  18170. _SG_ERROR(PIPELINE_POOL_EXHAUSTED);
  18171. }
  18172. return res;
  18173. }
  18174. _SOKOL_PRIVATE sg_attachments _sg_alloc_attachments(void) {
  18175. sg_attachments res;
  18176. int slot_index = _sg_pool_alloc_index(&_sg.pools.attachments_pool);
  18177. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  18178. res.id = _sg_slot_alloc(&_sg.pools.attachments_pool, &_sg.pools.attachments[slot_index].slot, slot_index);
  18179. } else {
  18180. res.id = SG_INVALID_ID;
  18181. _SG_ERROR(PASS_POOL_EXHAUSTED);
  18182. }
  18183. return res;
  18184. }
  18185. _SOKOL_PRIVATE void _sg_dealloc_buffer(_sg_buffer_t* buf) {
  18186. SOKOL_ASSERT(buf && (buf->slot.state == SG_RESOURCESTATE_ALLOC) && (buf->slot.id != SG_INVALID_ID));
  18187. _sg_pool_free_index(&_sg.pools.buffer_pool, _sg_slot_index(buf->slot.id));
  18188. _sg_slot_reset(&buf->slot);
  18189. }
  18190. _SOKOL_PRIVATE void _sg_dealloc_image(_sg_image_t* img) {
  18191. SOKOL_ASSERT(img && (img->slot.state == SG_RESOURCESTATE_ALLOC) && (img->slot.id != SG_INVALID_ID));
  18192. _sg_pool_free_index(&_sg.pools.image_pool, _sg_slot_index(img->slot.id));
  18193. _sg_slot_reset(&img->slot);
  18194. }
  18195. _SOKOL_PRIVATE void _sg_dealloc_sampler(_sg_sampler_t* smp) {
  18196. SOKOL_ASSERT(smp && (smp->slot.state == SG_RESOURCESTATE_ALLOC) && (smp->slot.id != SG_INVALID_ID));
  18197. _sg_pool_free_index(&_sg.pools.sampler_pool, _sg_slot_index(smp->slot.id));
  18198. _sg_slot_reset(&smp->slot);
  18199. }
  18200. _SOKOL_PRIVATE void _sg_dealloc_shader(_sg_shader_t* shd) {
  18201. SOKOL_ASSERT(shd && (shd->slot.state == SG_RESOURCESTATE_ALLOC) && (shd->slot.id != SG_INVALID_ID));
  18202. _sg_pool_free_index(&_sg.pools.shader_pool, _sg_slot_index(shd->slot.id));
  18203. _sg_slot_reset(&shd->slot);
  18204. }
  18205. _SOKOL_PRIVATE void _sg_dealloc_pipeline(_sg_pipeline_t* pip) {
  18206. SOKOL_ASSERT(pip && (pip->slot.state == SG_RESOURCESTATE_ALLOC) && (pip->slot.id != SG_INVALID_ID));
  18207. _sg_pool_free_index(&_sg.pools.pipeline_pool, _sg_slot_index(pip->slot.id));
  18208. _sg_slot_reset(&pip->slot);
  18209. }
  18210. _SOKOL_PRIVATE void _sg_dealloc_attachments(_sg_attachments_t* atts) {
  18211. SOKOL_ASSERT(atts && (atts->slot.state == SG_RESOURCESTATE_ALLOC) && (atts->slot.id != SG_INVALID_ID));
  18212. _sg_pool_free_index(&_sg.pools.attachments_pool, _sg_slot_index(atts->slot.id));
  18213. _sg_slot_reset(&atts->slot);
  18214. }
  18215. _SOKOL_PRIVATE void _sg_init_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  18216. SOKOL_ASSERT(buf && (buf->slot.state == SG_RESOURCESTATE_ALLOC));
  18217. SOKOL_ASSERT(desc);
  18218. if (_sg_validate_buffer_desc(desc)) {
  18219. _sg_buffer_common_init(&buf->cmn, desc);
  18220. buf->slot.state = _sg_create_buffer(buf, desc);
  18221. } else {
  18222. buf->slot.state = SG_RESOURCESTATE_FAILED;
  18223. }
  18224. SOKOL_ASSERT((buf->slot.state == SG_RESOURCESTATE_VALID)||(buf->slot.state == SG_RESOURCESTATE_FAILED));
  18225. }
  18226. _SOKOL_PRIVATE void _sg_init_image(_sg_image_t* img, const sg_image_desc* desc) {
  18227. SOKOL_ASSERT(img && (img->slot.state == SG_RESOURCESTATE_ALLOC));
  18228. SOKOL_ASSERT(desc);
  18229. if (_sg_validate_image_desc(desc)) {
  18230. _sg_image_common_init(&img->cmn, desc);
  18231. img->slot.state = _sg_create_image(img, desc);
  18232. } else {
  18233. img->slot.state = SG_RESOURCESTATE_FAILED;
  18234. }
  18235. SOKOL_ASSERT((img->slot.state == SG_RESOURCESTATE_VALID)||(img->slot.state == SG_RESOURCESTATE_FAILED));
  18236. }
  18237. _SOKOL_PRIVATE void _sg_init_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  18238. SOKOL_ASSERT(smp && (smp->slot.state == SG_RESOURCESTATE_ALLOC));
  18239. SOKOL_ASSERT(desc);
  18240. if (_sg_validate_sampler_desc(desc)) {
  18241. _sg_sampler_common_init(&smp->cmn, desc);
  18242. smp->slot.state = _sg_create_sampler(smp, desc);
  18243. } else {
  18244. smp->slot.state = SG_RESOURCESTATE_FAILED;
  18245. }
  18246. SOKOL_ASSERT((smp->slot.state == SG_RESOURCESTATE_VALID)||(smp->slot.state == SG_RESOURCESTATE_FAILED));
  18247. }
  18248. _SOKOL_PRIVATE void _sg_init_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  18249. SOKOL_ASSERT(shd && (shd->slot.state == SG_RESOURCESTATE_ALLOC));
  18250. SOKOL_ASSERT(desc);
  18251. if (_sg_validate_shader_desc(desc)) {
  18252. _sg_shader_common_init(&shd->cmn, desc);
  18253. shd->slot.state = _sg_create_shader(shd, desc);
  18254. } else {
  18255. shd->slot.state = SG_RESOURCESTATE_FAILED;
  18256. }
  18257. SOKOL_ASSERT((shd->slot.state == SG_RESOURCESTATE_VALID)||(shd->slot.state == SG_RESOURCESTATE_FAILED));
  18258. }
  18259. _SOKOL_PRIVATE void _sg_init_pipeline(_sg_pipeline_t* pip, const sg_pipeline_desc* desc) {
  18260. SOKOL_ASSERT(pip && (pip->slot.state == SG_RESOURCESTATE_ALLOC));
  18261. SOKOL_ASSERT(desc);
  18262. if (_sg_validate_pipeline_desc(desc)) {
  18263. _sg_shader_t* shd = _sg_lookup_shader(desc->shader.id);
  18264. if (shd && (shd->slot.state == SG_RESOURCESTATE_VALID)) {
  18265. _sg_pipeline_common_init(&pip->cmn, desc, shd);
  18266. pip->slot.state = _sg_create_pipeline(pip, desc);
  18267. } else {
  18268. pip->slot.state = SG_RESOURCESTATE_FAILED;
  18269. }
  18270. } else {
  18271. pip->slot.state = SG_RESOURCESTATE_FAILED;
  18272. }
  18273. SOKOL_ASSERT((pip->slot.state == SG_RESOURCESTATE_VALID)||(pip->slot.state == SG_RESOURCESTATE_FAILED));
  18274. }
  18275. _SOKOL_PRIVATE void _sg_init_attachments(_sg_attachments_t* atts, const sg_attachments_desc* desc) {
  18276. SOKOL_ASSERT(atts && atts->slot.state == SG_RESOURCESTATE_ALLOC);
  18277. SOKOL_ASSERT(desc);
  18278. if (_sg_validate_attachments_desc(desc)) {
  18279. // resolve image pointers, track width and height of render attachments,
  18280. // the validation layer already ensured that render attachments have the
  18281. // same width and height (which doesn't matter for storage attachments)
  18282. _sg_attachments_ptrs_t atts_ptrs;
  18283. _sg_clear(&atts_ptrs, sizeof(atts_ptrs));
  18284. int width = 0;
  18285. int height = 0;
  18286. for (size_t i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  18287. if (desc->colors[i].image.id) {
  18288. _sg_image_t* img = _sg_lookup_image(desc->colors[i].image.id);
  18289. if (!(img && img->slot.state == SG_RESOURCESTATE_VALID)) {
  18290. atts->slot.state = SG_RESOURCESTATE_FAILED;
  18291. return;
  18292. }
  18293. const int mip_level = desc->colors[i].mip_level;
  18294. width = _sg_miplevel_dim(img->cmn.width, mip_level);
  18295. height = _sg_miplevel_dim(img->cmn.height, mip_level);
  18296. atts_ptrs.color_images[i] = img;
  18297. }
  18298. if (desc->resolves[i].image.id) {
  18299. _sg_image_t* img = _sg_lookup_image(desc->resolves[i].image.id);
  18300. if (!(img && img->slot.state == SG_RESOURCESTATE_VALID)) {
  18301. atts->slot.state = SG_RESOURCESTATE_FAILED;
  18302. return;
  18303. }
  18304. atts_ptrs.resolve_images[i] = img;
  18305. }
  18306. }
  18307. if (desc->depth_stencil.image.id) {
  18308. _sg_image_t* img = _sg_lookup_image(desc->depth_stencil.image.id);
  18309. if (!(img && img->slot.state == SG_RESOURCESTATE_VALID)) {
  18310. atts->slot.state = SG_RESOURCESTATE_FAILED;
  18311. return;
  18312. }
  18313. const int mip_level = desc->depth_stencil.mip_level;
  18314. width = _sg_miplevel_dim(img->cmn.width, mip_level);
  18315. height = _sg_miplevel_dim(img->cmn.height, mip_level);
  18316. atts_ptrs.ds_image = img;
  18317. }
  18318. for (size_t i = 0; i < SG_MAX_STORAGE_ATTACHMENTS; i++) {
  18319. if (desc->storages[i].image.id) {
  18320. _sg_image_t* img = _sg_lookup_image(desc->storages[i].image.id);
  18321. if (!(img && img->slot.state == SG_RESOURCESTATE_VALID)) {
  18322. atts->slot.state = SG_RESOURCESTATE_FAILED;
  18323. return;
  18324. }
  18325. atts_ptrs.storage_images[i] = img;
  18326. }
  18327. }
  18328. _sg_attachments_common_init(&atts->cmn, desc, &atts_ptrs, width, height);
  18329. atts->slot.state = _sg_create_attachments(atts, desc);
  18330. } else {
  18331. atts->slot.state = SG_RESOURCESTATE_FAILED;
  18332. }
  18333. SOKOL_ASSERT((atts->slot.state == SG_RESOURCESTATE_VALID)||(atts->slot.state == SG_RESOURCESTATE_FAILED));
  18334. }
  18335. _SOKOL_PRIVATE void _sg_uninit_buffer(_sg_buffer_t* buf) {
  18336. SOKOL_ASSERT(buf && ((buf->slot.state == SG_RESOURCESTATE_VALID) || (buf->slot.state == SG_RESOURCESTATE_FAILED)));
  18337. _sg_discard_buffer(buf);
  18338. _sg_reset_buffer_to_alloc_state(buf);
  18339. }
  18340. _SOKOL_PRIVATE void _sg_uninit_image(_sg_image_t* img) {
  18341. SOKOL_ASSERT(img && ((img->slot.state == SG_RESOURCESTATE_VALID) || (img->slot.state == SG_RESOURCESTATE_FAILED)));
  18342. _sg_discard_image(img);
  18343. _sg_reset_image_to_alloc_state(img);
  18344. }
  18345. _SOKOL_PRIVATE void _sg_uninit_sampler(_sg_sampler_t* smp) {
  18346. SOKOL_ASSERT(smp && ((smp->slot.state == SG_RESOURCESTATE_VALID) || (smp->slot.state == SG_RESOURCESTATE_FAILED)));
  18347. _sg_discard_sampler(smp);
  18348. _sg_reset_sampler_to_alloc_state(smp);
  18349. }
  18350. _SOKOL_PRIVATE void _sg_uninit_shader(_sg_shader_t* shd) {
  18351. SOKOL_ASSERT(shd && ((shd->slot.state == SG_RESOURCESTATE_VALID) || (shd->slot.state == SG_RESOURCESTATE_FAILED)));
  18352. _sg_discard_shader(shd);
  18353. _sg_reset_shader_to_alloc_state(shd);
  18354. }
  18355. _SOKOL_PRIVATE void _sg_uninit_pipeline(_sg_pipeline_t* pip) {
  18356. SOKOL_ASSERT(pip && ((pip->slot.state == SG_RESOURCESTATE_VALID) || (pip->slot.state == SG_RESOURCESTATE_FAILED)));
  18357. _sg_discard_pipeline(pip);
  18358. _sg_reset_pipeline_to_alloc_state(pip);
  18359. }
  18360. _SOKOL_PRIVATE void _sg_uninit_attachments(_sg_attachments_t* atts) {
  18361. SOKOL_ASSERT(atts && ((atts->slot.state == SG_RESOURCESTATE_VALID) || (atts->slot.state == SG_RESOURCESTATE_FAILED)));
  18362. _sg_discard_attachments(atts);
  18363. _sg_reset_attachments_to_alloc_state(atts);
  18364. }
  18365. _SOKOL_PRIVATE void _sg_setup_commit_listeners(const sg_desc* desc) {
  18366. SOKOL_ASSERT(desc->max_commit_listeners > 0);
  18367. SOKOL_ASSERT(0 == _sg.commit_listeners.items);
  18368. SOKOL_ASSERT(0 == _sg.commit_listeners.num);
  18369. SOKOL_ASSERT(0 == _sg.commit_listeners.upper);
  18370. _sg.commit_listeners.num = desc->max_commit_listeners;
  18371. const size_t size = (size_t)_sg.commit_listeners.num * sizeof(sg_commit_listener);
  18372. _sg.commit_listeners.items = (sg_commit_listener*)_sg_malloc_clear(size);
  18373. }
  18374. _SOKOL_PRIVATE void _sg_discard_commit_listeners(void) {
  18375. SOKOL_ASSERT(0 != _sg.commit_listeners.items);
  18376. _sg_free(_sg.commit_listeners.items);
  18377. _sg.commit_listeners.items = 0;
  18378. }
  18379. _SOKOL_PRIVATE void _sg_notify_commit_listeners(void) {
  18380. SOKOL_ASSERT(_sg.commit_listeners.items);
  18381. for (int i = 0; i < _sg.commit_listeners.upper; i++) {
  18382. const sg_commit_listener* listener = &_sg.commit_listeners.items[i];
  18383. if (listener->func) {
  18384. listener->func(listener->user_data);
  18385. }
  18386. }
  18387. }
  18388. _SOKOL_PRIVATE bool _sg_add_commit_listener(const sg_commit_listener* new_listener) {
  18389. SOKOL_ASSERT(new_listener && new_listener->func);
  18390. SOKOL_ASSERT(_sg.commit_listeners.items);
  18391. // first check if the listener hadn't been added already
  18392. for (int i = 0; i < _sg.commit_listeners.upper; i++) {
  18393. const sg_commit_listener* slot = &_sg.commit_listeners.items[i];
  18394. if ((slot->func == new_listener->func) && (slot->user_data == new_listener->user_data)) {
  18395. _SG_ERROR(IDENTICAL_COMMIT_LISTENER);
  18396. return false;
  18397. }
  18398. }
  18399. // first try to plug a hole
  18400. sg_commit_listener* slot = 0;
  18401. for (int i = 0; i < _sg.commit_listeners.upper; i++) {
  18402. if (_sg.commit_listeners.items[i].func == 0) {
  18403. slot = &_sg.commit_listeners.items[i];
  18404. break;
  18405. }
  18406. }
  18407. if (!slot) {
  18408. // append to end
  18409. if (_sg.commit_listeners.upper < _sg.commit_listeners.num) {
  18410. slot = &_sg.commit_listeners.items[_sg.commit_listeners.upper++];
  18411. }
  18412. }
  18413. if (!slot) {
  18414. _SG_ERROR(COMMIT_LISTENER_ARRAY_FULL);
  18415. return false;
  18416. }
  18417. *slot = *new_listener;
  18418. return true;
  18419. }
  18420. _SOKOL_PRIVATE bool _sg_remove_commit_listener(const sg_commit_listener* listener) {
  18421. SOKOL_ASSERT(listener && listener->func);
  18422. SOKOL_ASSERT(_sg.commit_listeners.items);
  18423. for (int i = 0; i < _sg.commit_listeners.upper; i++) {
  18424. sg_commit_listener* slot = &_sg.commit_listeners.items[i];
  18425. // both the function pointer and user data must match!
  18426. if ((slot->func == listener->func) && (slot->user_data == listener->user_data)) {
  18427. slot->func = 0;
  18428. slot->user_data = 0;
  18429. // NOTE: since _sg_add_commit_listener() already catches duplicates,
  18430. // we don't need to worry about them here
  18431. return true;
  18432. }
  18433. }
  18434. return false;
  18435. }
  18436. _SOKOL_PRIVATE void _sg_setup_compute(const sg_desc* desc) {
  18437. SOKOL_ASSERT(desc && (desc->max_dispatch_calls_per_pass > 0));
  18438. const uint32_t max_tracked_sbufs = (uint32_t)desc->max_dispatch_calls_per_pass * SG_MAX_STORAGEBUFFER_BINDSLOTS;
  18439. _sg_tracker_init(&_sg.compute.readwrite_sbufs, max_tracked_sbufs);
  18440. }
  18441. _SOKOL_PRIVATE void _sg_discard_compute(void) {
  18442. _sg_tracker_discard(&_sg.compute.readwrite_sbufs);
  18443. }
  18444. _SOKOL_PRIVATE void _sg_compute_pass_track_storage_buffer(_sg_buffer_t* sbuf, bool readonly) {
  18445. SOKOL_ASSERT(sbuf);
  18446. if (!readonly) {
  18447. _sg_tracker_add(&_sg.compute.readwrite_sbufs, sbuf->slot.id);
  18448. }
  18449. }
  18450. _SOKOL_PRIVATE void _sg_compute_on_endpass(void) {
  18451. SOKOL_ASSERT(_sg.cur_pass.in_pass);
  18452. SOKOL_ASSERT(_sg.cur_pass.is_compute);
  18453. _sg_tracker_reset(&_sg.compute.readwrite_sbufs);
  18454. }
  18455. _SOKOL_PRIVATE sg_desc _sg_desc_defaults(const sg_desc* desc) {
  18456. /*
  18457. NOTE: on WebGPU, the default color pixel format MUST be provided,
  18458. cannot be a default compile-time constant.
  18459. */
  18460. sg_desc res = *desc;
  18461. #if defined(SOKOL_WGPU)
  18462. SOKOL_ASSERT(SG_PIXELFORMAT_NONE < res.environment.defaults.color_format);
  18463. #elif defined(SOKOL_METAL) || defined(SOKOL_D3D11)
  18464. res.environment.defaults.color_format = _sg_def(res.environment.defaults.color_format, SG_PIXELFORMAT_BGRA8);
  18465. #else
  18466. res.environment.defaults.color_format = _sg_def(res.environment.defaults.color_format, SG_PIXELFORMAT_RGBA8);
  18467. #endif
  18468. res.environment.defaults.depth_format = _sg_def(res.environment.defaults.depth_format, SG_PIXELFORMAT_DEPTH_STENCIL);
  18469. res.environment.defaults.sample_count = _sg_def(res.environment.defaults.sample_count, 1);
  18470. res.buffer_pool_size = _sg_def(res.buffer_pool_size, _SG_DEFAULT_BUFFER_POOL_SIZE);
  18471. res.image_pool_size = _sg_def(res.image_pool_size, _SG_DEFAULT_IMAGE_POOL_SIZE);
  18472. res.sampler_pool_size = _sg_def(res.sampler_pool_size, _SG_DEFAULT_SAMPLER_POOL_SIZE);
  18473. res.shader_pool_size = _sg_def(res.shader_pool_size, _SG_DEFAULT_SHADER_POOL_SIZE);
  18474. res.pipeline_pool_size = _sg_def(res.pipeline_pool_size, _SG_DEFAULT_PIPELINE_POOL_SIZE);
  18475. res.attachments_pool_size = _sg_def(res.attachments_pool_size, _SG_DEFAULT_ATTACHMENTS_POOL_SIZE);
  18476. res.uniform_buffer_size = _sg_def(res.uniform_buffer_size, _SG_DEFAULT_UB_SIZE);
  18477. res.max_dispatch_calls_per_pass = _sg_def(res.max_dispatch_calls_per_pass, _SG_DEFAULT_MAX_DISPATCH_CALLS_PER_PASS);
  18478. res.max_commit_listeners = _sg_def(res.max_commit_listeners, _SG_DEFAULT_MAX_COMMIT_LISTENERS);
  18479. res.wgpu_bindgroups_cache_size = _sg_def(res.wgpu_bindgroups_cache_size, _SG_DEFAULT_WGPU_BINDGROUP_CACHE_SIZE);
  18480. return res;
  18481. }
  18482. _SOKOL_PRIVATE sg_pass _sg_pass_defaults(const sg_pass* pass) {
  18483. sg_pass res = *pass;
  18484. if (!res.compute) {
  18485. if (res.attachments.id == SG_INVALID_ID) {
  18486. // this is a swapchain-pass
  18487. res.swapchain.sample_count = _sg_def(res.swapchain.sample_count, _sg.desc.environment.defaults.sample_count);
  18488. res.swapchain.color_format = _sg_def(res.swapchain.color_format, _sg.desc.environment.defaults.color_format);
  18489. res.swapchain.depth_format = _sg_def(res.swapchain.depth_format, _sg.desc.environment.defaults.depth_format);
  18490. }
  18491. res.action = _sg_pass_action_defaults(&res.action);
  18492. }
  18493. return res;
  18494. }
  18495. _SOKOL_PRIVATE void _sg_discard_all_resources(void) {
  18496. /* this is a bit dumb since it loops over all pool slots to
  18497. find the occupied slots, on the other hand it is only ever
  18498. executed at shutdown
  18499. NOTE: ONLY EXECUTE THIS AT SHUTDOWN
  18500. ...because the free queues will not be reset
  18501. and the resource slots not be cleared!
  18502. */
  18503. for (int i = 1; i < _sg.pools.buffer_pool.size; i++) {
  18504. sg_resource_state state = _sg.pools.buffers[i].slot.state;
  18505. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  18506. _sg_discard_buffer(&_sg.pools.buffers[i]);
  18507. }
  18508. }
  18509. for (int i = 1; i < _sg.pools.image_pool.size; i++) {
  18510. sg_resource_state state = _sg.pools.images[i].slot.state;
  18511. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  18512. _sg_discard_image(&_sg.pools.images[i]);
  18513. }
  18514. }
  18515. for (int i = 1; i < _sg.pools.sampler_pool.size; i++) {
  18516. sg_resource_state state = _sg.pools.samplers[i].slot.state;
  18517. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  18518. _sg_discard_sampler(&_sg.pools.samplers[i]);
  18519. }
  18520. }
  18521. for (int i = 1; i < _sg.pools.shader_pool.size; i++) {
  18522. sg_resource_state state = _sg.pools.shaders[i].slot.state;
  18523. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  18524. _sg_discard_shader(&_sg.pools.shaders[i]);
  18525. }
  18526. }
  18527. for (int i = 1; i < _sg.pools.pipeline_pool.size; i++) {
  18528. sg_resource_state state = _sg.pools.pipelines[i].slot.state;
  18529. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  18530. _sg_discard_pipeline(&_sg.pools.pipelines[i]);
  18531. }
  18532. }
  18533. for (int i = 1; i < _sg.pools.attachments_pool.size; i++) {
  18534. sg_resource_state state = _sg.pools.attachments[i].slot.state;
  18535. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  18536. _sg_discard_attachments(&_sg.pools.attachments[i]);
  18537. }
  18538. }
  18539. }
  18540. // ██████ ██ ██ ██████ ██ ██ ██████
  18541. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  18542. // ██████ ██ ██ ██████ ██ ██ ██
  18543. // ██ ██ ██ ██ ██ ██ ██ ██
  18544. // ██ ██████ ██████ ███████ ██ ██████
  18545. //
  18546. // >>public
  18547. SOKOL_API_IMPL void sg_setup(const sg_desc* desc) {
  18548. SOKOL_ASSERT(desc);
  18549. SOKOL_ASSERT((desc->_start_canary == 0) && (desc->_end_canary == 0));
  18550. SOKOL_ASSERT((desc->allocator.alloc_fn && desc->allocator.free_fn) || (!desc->allocator.alloc_fn && !desc->allocator.free_fn));
  18551. _SG_CLEAR_ARC_STRUCT(_sg_state_t, _sg);
  18552. _sg.desc = _sg_desc_defaults(desc);
  18553. _sg_setup_pools(&_sg.pools, &_sg.desc);
  18554. _sg_setup_compute(&_sg.desc);
  18555. _sg_setup_commit_listeners(&_sg.desc);
  18556. _sg.frame_index = 1;
  18557. _sg.stats_enabled = true;
  18558. _sg_setup_backend(&_sg.desc);
  18559. _sg.valid = true;
  18560. }
  18561. SOKOL_API_IMPL void sg_shutdown(void) {
  18562. _sg_discard_all_resources();
  18563. _sg_discard_backend();
  18564. _sg_discard_commit_listeners();
  18565. _sg_discard_compute();
  18566. _sg_discard_pools(&_sg.pools);
  18567. _SG_CLEAR_ARC_STRUCT(_sg_state_t, _sg);
  18568. }
  18569. SOKOL_API_IMPL bool sg_isvalid(void) {
  18570. return _sg.valid;
  18571. }
  18572. SOKOL_API_IMPL sg_desc sg_query_desc(void) {
  18573. SOKOL_ASSERT(_sg.valid);
  18574. return _sg.desc;
  18575. }
  18576. SOKOL_API_IMPL sg_backend sg_query_backend(void) {
  18577. SOKOL_ASSERT(_sg.valid);
  18578. return _sg.backend;
  18579. }
  18580. SOKOL_API_IMPL sg_features sg_query_features(void) {
  18581. SOKOL_ASSERT(_sg.valid);
  18582. return _sg.features;
  18583. }
  18584. SOKOL_API_IMPL sg_limits sg_query_limits(void) {
  18585. SOKOL_ASSERT(_sg.valid);
  18586. return _sg.limits;
  18587. }
  18588. SOKOL_API_IMPL sg_pixelformat_info sg_query_pixelformat(sg_pixel_format fmt) {
  18589. SOKOL_ASSERT(_sg.valid);
  18590. int fmt_index = (int) fmt;
  18591. SOKOL_ASSERT((fmt_index > SG_PIXELFORMAT_NONE) && (fmt_index < _SG_PIXELFORMAT_NUM));
  18592. const _sg_pixelformat_info_t* src = &_sg.formats[fmt_index];
  18593. sg_pixelformat_info res;
  18594. _sg_clear(&res, sizeof(res));
  18595. res.sample = src->sample;
  18596. res.filter = src->filter;
  18597. res.render = src->render;
  18598. res.blend = src->blend;
  18599. res.msaa = src->msaa;
  18600. res.depth = src->depth;
  18601. res.compressed = _sg_is_compressed_pixel_format(fmt);
  18602. res.read = src->read;
  18603. res.write = src->write;
  18604. if (!res.compressed) {
  18605. res.bytes_per_pixel = _sg_pixelformat_bytesize(fmt);
  18606. }
  18607. return res;
  18608. }
  18609. SOKOL_API_IMPL int sg_query_row_pitch(sg_pixel_format fmt, int width, int row_align_bytes) {
  18610. SOKOL_ASSERT(_sg.valid);
  18611. SOKOL_ASSERT(width > 0);
  18612. SOKOL_ASSERT((row_align_bytes > 0) && _sg_ispow2(row_align_bytes));
  18613. SOKOL_ASSERT(((int)fmt > SG_PIXELFORMAT_NONE) && ((int)fmt < _SG_PIXELFORMAT_NUM));
  18614. return _sg_row_pitch(fmt, width, row_align_bytes);
  18615. }
  18616. SOKOL_API_IMPL int sg_query_surface_pitch(sg_pixel_format fmt, int width, int height, int row_align_bytes) {
  18617. SOKOL_ASSERT(_sg.valid);
  18618. SOKOL_ASSERT((width > 0) && (height > 0));
  18619. SOKOL_ASSERT((row_align_bytes > 0) && _sg_ispow2(row_align_bytes));
  18620. SOKOL_ASSERT(((int)fmt > SG_PIXELFORMAT_NONE) && ((int)fmt < _SG_PIXELFORMAT_NUM));
  18621. return _sg_surface_pitch(fmt, width, height, row_align_bytes);
  18622. }
  18623. SOKOL_API_IMPL sg_frame_stats sg_query_frame_stats(void) {
  18624. SOKOL_ASSERT(_sg.valid);
  18625. return _sg.prev_stats;
  18626. }
  18627. SOKOL_API_IMPL sg_trace_hooks sg_install_trace_hooks(const sg_trace_hooks* trace_hooks) {
  18628. SOKOL_ASSERT(_sg.valid);
  18629. SOKOL_ASSERT(trace_hooks);
  18630. _SOKOL_UNUSED(trace_hooks);
  18631. #if defined(SOKOL_TRACE_HOOKS)
  18632. sg_trace_hooks old_hooks = _sg.hooks;
  18633. _sg.hooks = *trace_hooks;
  18634. #else
  18635. static sg_trace_hooks old_hooks;
  18636. _SG_WARN(TRACE_HOOKS_NOT_ENABLED);
  18637. #endif
  18638. return old_hooks;
  18639. }
  18640. SOKOL_API_IMPL sg_buffer sg_alloc_buffer(void) {
  18641. SOKOL_ASSERT(_sg.valid);
  18642. sg_buffer res = _sg_alloc_buffer();
  18643. _SG_TRACE_ARGS(alloc_buffer, res);
  18644. return res;
  18645. }
  18646. SOKOL_API_IMPL sg_image sg_alloc_image(void) {
  18647. SOKOL_ASSERT(_sg.valid);
  18648. sg_image res = _sg_alloc_image();
  18649. _SG_TRACE_ARGS(alloc_image, res);
  18650. return res;
  18651. }
  18652. SOKOL_API_IMPL sg_sampler sg_alloc_sampler(void) {
  18653. SOKOL_ASSERT(_sg.valid);
  18654. sg_sampler res = _sg_alloc_sampler();
  18655. _SG_TRACE_ARGS(alloc_sampler, res);
  18656. return res;
  18657. }
  18658. SOKOL_API_IMPL sg_shader sg_alloc_shader(void) {
  18659. SOKOL_ASSERT(_sg.valid);
  18660. sg_shader res = _sg_alloc_shader();
  18661. _SG_TRACE_ARGS(alloc_shader, res);
  18662. return res;
  18663. }
  18664. SOKOL_API_IMPL sg_pipeline sg_alloc_pipeline(void) {
  18665. SOKOL_ASSERT(_sg.valid);
  18666. sg_pipeline res = _sg_alloc_pipeline();
  18667. _SG_TRACE_ARGS(alloc_pipeline, res);
  18668. return res;
  18669. }
  18670. SOKOL_API_IMPL sg_attachments sg_alloc_attachments(void) {
  18671. SOKOL_ASSERT(_sg.valid);
  18672. sg_attachments res = _sg_alloc_attachments();
  18673. _SG_TRACE_ARGS(alloc_attachments, res);
  18674. return res;
  18675. }
  18676. SOKOL_API_IMPL void sg_dealloc_buffer(sg_buffer buf_id) {
  18677. SOKOL_ASSERT(_sg.valid);
  18678. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  18679. if (buf) {
  18680. if (buf->slot.state == SG_RESOURCESTATE_ALLOC) {
  18681. _sg_dealloc_buffer(buf);
  18682. } else {
  18683. _SG_ERROR(DEALLOC_BUFFER_INVALID_STATE);
  18684. }
  18685. }
  18686. _SG_TRACE_ARGS(dealloc_buffer, buf_id);
  18687. }
  18688. SOKOL_API_IMPL void sg_dealloc_image(sg_image img_id) {
  18689. SOKOL_ASSERT(_sg.valid);
  18690. _sg_image_t* img = _sg_lookup_image(img_id.id);
  18691. if (img) {
  18692. if (img->slot.state == SG_RESOURCESTATE_ALLOC) {
  18693. _sg_dealloc_image(img);
  18694. } else {
  18695. _SG_ERROR(DEALLOC_IMAGE_INVALID_STATE);
  18696. }
  18697. }
  18698. _SG_TRACE_ARGS(dealloc_image, img_id);
  18699. }
  18700. SOKOL_API_IMPL void sg_dealloc_sampler(sg_sampler smp_id) {
  18701. SOKOL_ASSERT(_sg.valid);
  18702. _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  18703. if (smp) {
  18704. if (smp->slot.state == SG_RESOURCESTATE_ALLOC) {
  18705. _sg_dealloc_sampler(smp);
  18706. } else {
  18707. _SG_ERROR(DEALLOC_SAMPLER_INVALID_STATE);
  18708. }
  18709. }
  18710. _SG_TRACE_ARGS(dealloc_sampler, smp_id);
  18711. }
  18712. SOKOL_API_IMPL void sg_dealloc_shader(sg_shader shd_id) {
  18713. SOKOL_ASSERT(_sg.valid);
  18714. _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  18715. if (shd) {
  18716. if (shd->slot.state == SG_RESOURCESTATE_ALLOC) {
  18717. _sg_dealloc_shader(shd);
  18718. } else {
  18719. _SG_ERROR(DEALLOC_SHADER_INVALID_STATE);
  18720. }
  18721. }
  18722. _SG_TRACE_ARGS(dealloc_shader, shd_id);
  18723. }
  18724. SOKOL_API_IMPL void sg_dealloc_pipeline(sg_pipeline pip_id) {
  18725. SOKOL_ASSERT(_sg.valid);
  18726. _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  18727. if (pip) {
  18728. if (pip->slot.state == SG_RESOURCESTATE_ALLOC) {
  18729. _sg_dealloc_pipeline(pip);
  18730. } else {
  18731. _SG_ERROR(DEALLOC_PIPELINE_INVALID_STATE);
  18732. }
  18733. }
  18734. _SG_TRACE_ARGS(dealloc_pipeline, pip_id);
  18735. }
  18736. SOKOL_API_IMPL void sg_dealloc_attachments(sg_attachments atts_id) {
  18737. SOKOL_ASSERT(_sg.valid);
  18738. _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  18739. if (atts) {
  18740. if (atts->slot.state == SG_RESOURCESTATE_ALLOC) {
  18741. _sg_dealloc_attachments(atts);
  18742. } else {
  18743. _SG_ERROR(DEALLOC_ATTACHMENTS_INVALID_STATE);
  18744. }
  18745. }
  18746. _SG_TRACE_ARGS(dealloc_attachments, atts_id);
  18747. }
  18748. SOKOL_API_IMPL void sg_init_buffer(sg_buffer buf_id, const sg_buffer_desc* desc) {
  18749. SOKOL_ASSERT(_sg.valid);
  18750. sg_buffer_desc desc_def = _sg_buffer_desc_defaults(desc);
  18751. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  18752. if (buf) {
  18753. if (buf->slot.state == SG_RESOURCESTATE_ALLOC) {
  18754. _sg_init_buffer(buf, &desc_def);
  18755. SOKOL_ASSERT((buf->slot.state == SG_RESOURCESTATE_VALID) || (buf->slot.state == SG_RESOURCESTATE_FAILED));
  18756. } else {
  18757. _SG_ERROR(INIT_BUFFER_INVALID_STATE);
  18758. }
  18759. }
  18760. _SG_TRACE_ARGS(init_buffer, buf_id, &desc_def);
  18761. }
  18762. SOKOL_API_IMPL void sg_init_image(sg_image img_id, const sg_image_desc* desc) {
  18763. SOKOL_ASSERT(_sg.valid);
  18764. sg_image_desc desc_def = _sg_image_desc_defaults(desc);
  18765. _sg_image_t* img = _sg_lookup_image(img_id.id);
  18766. if (img) {
  18767. if (img->slot.state == SG_RESOURCESTATE_ALLOC) {
  18768. _sg_init_image(img, &desc_def);
  18769. SOKOL_ASSERT((img->slot.state == SG_RESOURCESTATE_VALID) || (img->slot.state == SG_RESOURCESTATE_FAILED));
  18770. } else {
  18771. _SG_ERROR(INIT_IMAGE_INVALID_STATE);
  18772. }
  18773. }
  18774. _SG_TRACE_ARGS(init_image, img_id, &desc_def);
  18775. }
  18776. SOKOL_API_IMPL void sg_init_sampler(sg_sampler smp_id, const sg_sampler_desc* desc) {
  18777. SOKOL_ASSERT(_sg.valid);
  18778. sg_sampler_desc desc_def = _sg_sampler_desc_defaults(desc);
  18779. _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  18780. if (smp) {
  18781. if (smp->slot.state == SG_RESOURCESTATE_ALLOC) {
  18782. _sg_init_sampler(smp, &desc_def);
  18783. SOKOL_ASSERT((smp->slot.state == SG_RESOURCESTATE_VALID) || (smp->slot.state == SG_RESOURCESTATE_FAILED));
  18784. } else {
  18785. _SG_ERROR(INIT_SAMPLER_INVALID_STATE);
  18786. }
  18787. }
  18788. _SG_TRACE_ARGS(init_sampler, smp_id, &desc_def);
  18789. }
  18790. SOKOL_API_IMPL void sg_init_shader(sg_shader shd_id, const sg_shader_desc* desc) {
  18791. SOKOL_ASSERT(_sg.valid);
  18792. sg_shader_desc desc_def = _sg_shader_desc_defaults(desc);
  18793. _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  18794. if (shd) {
  18795. if (shd->slot.state == SG_RESOURCESTATE_ALLOC) {
  18796. _sg_init_shader(shd, &desc_def);
  18797. SOKOL_ASSERT((shd->slot.state == SG_RESOURCESTATE_VALID) || (shd->slot.state == SG_RESOURCESTATE_FAILED));
  18798. } else {
  18799. _SG_ERROR(INIT_SHADER_INVALID_STATE);
  18800. }
  18801. }
  18802. _SG_TRACE_ARGS(init_shader, shd_id, &desc_def);
  18803. }
  18804. SOKOL_API_IMPL void sg_init_pipeline(sg_pipeline pip_id, const sg_pipeline_desc* desc) {
  18805. SOKOL_ASSERT(_sg.valid);
  18806. sg_pipeline_desc desc_def = _sg_pipeline_desc_defaults(desc);
  18807. _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  18808. if (pip) {
  18809. if (pip->slot.state == SG_RESOURCESTATE_ALLOC) {
  18810. _sg_init_pipeline(pip, &desc_def);
  18811. SOKOL_ASSERT((pip->slot.state == SG_RESOURCESTATE_VALID) || (pip->slot.state == SG_RESOURCESTATE_FAILED));
  18812. } else {
  18813. _SG_ERROR(INIT_PIPELINE_INVALID_STATE);
  18814. }
  18815. }
  18816. _SG_TRACE_ARGS(init_pipeline, pip_id, &desc_def);
  18817. }
  18818. SOKOL_API_IMPL void sg_init_attachments(sg_attachments atts_id, const sg_attachments_desc* desc) {
  18819. SOKOL_ASSERT(_sg.valid);
  18820. sg_attachments_desc desc_def = _sg_attachments_desc_defaults(desc);
  18821. _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  18822. if (atts) {
  18823. if (atts->slot.state == SG_RESOURCESTATE_ALLOC) {
  18824. _sg_init_attachments(atts, &desc_def);
  18825. SOKOL_ASSERT((atts->slot.state == SG_RESOURCESTATE_VALID) || (atts->slot.state == SG_RESOURCESTATE_FAILED));
  18826. } else {
  18827. _SG_ERROR(INIT_ATTACHMENTS_INVALID_STATE);
  18828. }
  18829. }
  18830. _SG_TRACE_ARGS(init_attachments, atts_id, &desc_def);
  18831. }
  18832. SOKOL_API_IMPL void sg_uninit_buffer(sg_buffer buf_id) {
  18833. SOKOL_ASSERT(_sg.valid);
  18834. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  18835. if (buf) {
  18836. if ((buf->slot.state == SG_RESOURCESTATE_VALID) || (buf->slot.state == SG_RESOURCESTATE_FAILED)) {
  18837. _sg_uninit_buffer(buf);
  18838. SOKOL_ASSERT(buf->slot.state == SG_RESOURCESTATE_ALLOC);
  18839. } else {
  18840. _SG_ERROR(UNINIT_BUFFER_INVALID_STATE);
  18841. }
  18842. }
  18843. _SG_TRACE_ARGS(uninit_buffer, buf_id);
  18844. }
  18845. SOKOL_API_IMPL void sg_uninit_image(sg_image img_id) {
  18846. SOKOL_ASSERT(_sg.valid);
  18847. _sg_image_t* img = _sg_lookup_image(img_id.id);
  18848. if (img) {
  18849. if ((img->slot.state == SG_RESOURCESTATE_VALID) || (img->slot.state == SG_RESOURCESTATE_FAILED)) {
  18850. _sg_uninit_image(img);
  18851. SOKOL_ASSERT(img->slot.state == SG_RESOURCESTATE_ALLOC);
  18852. } else {
  18853. _SG_ERROR(UNINIT_IMAGE_INVALID_STATE);
  18854. }
  18855. }
  18856. _SG_TRACE_ARGS(uninit_image, img_id);
  18857. }
  18858. SOKOL_API_IMPL void sg_uninit_sampler(sg_sampler smp_id) {
  18859. SOKOL_ASSERT(_sg.valid);
  18860. _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  18861. if (smp) {
  18862. if ((smp->slot.state == SG_RESOURCESTATE_VALID) || (smp->slot.state == SG_RESOURCESTATE_FAILED)) {
  18863. _sg_uninit_sampler(smp);
  18864. SOKOL_ASSERT(smp->slot.state == SG_RESOURCESTATE_ALLOC);
  18865. } else {
  18866. _SG_ERROR(UNINIT_SAMPLER_INVALID_STATE);
  18867. }
  18868. }
  18869. _SG_TRACE_ARGS(uninit_sampler, smp_id);
  18870. }
  18871. SOKOL_API_IMPL void sg_uninit_shader(sg_shader shd_id) {
  18872. SOKOL_ASSERT(_sg.valid);
  18873. _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  18874. if (shd) {
  18875. if ((shd->slot.state == SG_RESOURCESTATE_VALID) || (shd->slot.state == SG_RESOURCESTATE_FAILED)) {
  18876. _sg_uninit_shader(shd);
  18877. SOKOL_ASSERT(shd->slot.state == SG_RESOURCESTATE_ALLOC);
  18878. } else {
  18879. _SG_ERROR(UNINIT_SHADER_INVALID_STATE);
  18880. }
  18881. }
  18882. _SG_TRACE_ARGS(uninit_shader, shd_id);
  18883. }
  18884. SOKOL_API_IMPL void sg_uninit_pipeline(sg_pipeline pip_id) {
  18885. SOKOL_ASSERT(_sg.valid);
  18886. _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  18887. if (pip) {
  18888. if ((pip->slot.state == SG_RESOURCESTATE_VALID) || (pip->slot.state == SG_RESOURCESTATE_FAILED)) {
  18889. _sg_uninit_pipeline(pip);
  18890. SOKOL_ASSERT(pip->slot.state == SG_RESOURCESTATE_ALLOC);
  18891. } else {
  18892. _SG_ERROR(UNINIT_PIPELINE_INVALID_STATE);
  18893. }
  18894. }
  18895. _SG_TRACE_ARGS(uninit_pipeline, pip_id);
  18896. }
  18897. SOKOL_API_IMPL void sg_uninit_attachments(sg_attachments atts_id) {
  18898. SOKOL_ASSERT(_sg.valid);
  18899. _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  18900. if (atts) {
  18901. if ((atts->slot.state == SG_RESOURCESTATE_VALID) || (atts->slot.state == SG_RESOURCESTATE_FAILED)) {
  18902. _sg_uninit_attachments(atts);
  18903. SOKOL_ASSERT(atts->slot.state == SG_RESOURCESTATE_ALLOC);
  18904. } else {
  18905. _SG_ERROR(UNINIT_ATTACHMENTS_INVALID_STATE);
  18906. }
  18907. }
  18908. _SG_TRACE_ARGS(uninit_attachments, atts_id);
  18909. }
  18910. SOKOL_API_IMPL void sg_fail_buffer(sg_buffer buf_id) {
  18911. SOKOL_ASSERT(_sg.valid);
  18912. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  18913. if (buf) {
  18914. if (buf->slot.state == SG_RESOURCESTATE_ALLOC) {
  18915. buf->slot.state = SG_RESOURCESTATE_FAILED;
  18916. } else {
  18917. _SG_ERROR(FAIL_BUFFER_INVALID_STATE);
  18918. }
  18919. }
  18920. _SG_TRACE_ARGS(fail_buffer, buf_id);
  18921. }
  18922. SOKOL_API_IMPL void sg_fail_image(sg_image img_id) {
  18923. SOKOL_ASSERT(_sg.valid);
  18924. _sg_image_t* img = _sg_lookup_image(img_id.id);
  18925. if (img) {
  18926. if (img->slot.state == SG_RESOURCESTATE_ALLOC) {
  18927. img->slot.state = SG_RESOURCESTATE_FAILED;
  18928. } else {
  18929. _SG_ERROR(FAIL_IMAGE_INVALID_STATE);
  18930. }
  18931. }
  18932. _SG_TRACE_ARGS(fail_image, img_id);
  18933. }
  18934. SOKOL_API_IMPL void sg_fail_sampler(sg_sampler smp_id) {
  18935. SOKOL_ASSERT(_sg.valid);
  18936. _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  18937. if (smp) {
  18938. if (smp->slot.state == SG_RESOURCESTATE_ALLOC) {
  18939. smp->slot.state = SG_RESOURCESTATE_FAILED;
  18940. } else {
  18941. _SG_ERROR(FAIL_SAMPLER_INVALID_STATE);
  18942. }
  18943. }
  18944. _SG_TRACE_ARGS(fail_sampler, smp_id);
  18945. }
  18946. SOKOL_API_IMPL void sg_fail_shader(sg_shader shd_id) {
  18947. SOKOL_ASSERT(_sg.valid);
  18948. _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  18949. if (shd) {
  18950. if (shd->slot.state == SG_RESOURCESTATE_ALLOC) {
  18951. shd->slot.state = SG_RESOURCESTATE_FAILED;
  18952. } else {
  18953. _SG_ERROR(FAIL_SHADER_INVALID_STATE);
  18954. }
  18955. }
  18956. _SG_TRACE_ARGS(fail_shader, shd_id);
  18957. }
  18958. SOKOL_API_IMPL void sg_fail_pipeline(sg_pipeline pip_id) {
  18959. SOKOL_ASSERT(_sg.valid);
  18960. _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  18961. if (pip) {
  18962. if (pip->slot.state == SG_RESOURCESTATE_ALLOC) {
  18963. pip->slot.state = SG_RESOURCESTATE_FAILED;
  18964. } else {
  18965. _SG_ERROR(FAIL_PIPELINE_INVALID_STATE);
  18966. }
  18967. }
  18968. _SG_TRACE_ARGS(fail_pipeline, pip_id);
  18969. }
  18970. SOKOL_API_IMPL void sg_fail_attachments(sg_attachments atts_id) {
  18971. SOKOL_ASSERT(_sg.valid);
  18972. _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  18973. if (atts) {
  18974. if (atts->slot.state == SG_RESOURCESTATE_ALLOC) {
  18975. atts->slot.state = SG_RESOURCESTATE_FAILED;
  18976. } else {
  18977. _SG_ERROR(FAIL_ATTACHMENTS_INVALID_STATE);
  18978. }
  18979. }
  18980. _SG_TRACE_ARGS(fail_attachments, atts_id);
  18981. }
  18982. SOKOL_API_IMPL sg_resource_state sg_query_buffer_state(sg_buffer buf_id) {
  18983. SOKOL_ASSERT(_sg.valid);
  18984. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  18985. sg_resource_state res = buf ? buf->slot.state : SG_RESOURCESTATE_INVALID;
  18986. return res;
  18987. }
  18988. SOKOL_API_IMPL sg_resource_state sg_query_image_state(sg_image img_id) {
  18989. SOKOL_ASSERT(_sg.valid);
  18990. _sg_image_t* img = _sg_lookup_image(img_id.id);
  18991. sg_resource_state res = img ? img->slot.state : SG_RESOURCESTATE_INVALID;
  18992. return res;
  18993. }
  18994. SOKOL_API_IMPL sg_resource_state sg_query_sampler_state(sg_sampler smp_id) {
  18995. SOKOL_ASSERT(_sg.valid);
  18996. _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  18997. sg_resource_state res = smp ? smp->slot.state : SG_RESOURCESTATE_INVALID;
  18998. return res;
  18999. }
  19000. SOKOL_API_IMPL sg_resource_state sg_query_shader_state(sg_shader shd_id) {
  19001. SOKOL_ASSERT(_sg.valid);
  19002. _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  19003. sg_resource_state res = shd ? shd->slot.state : SG_RESOURCESTATE_INVALID;
  19004. return res;
  19005. }
  19006. SOKOL_API_IMPL sg_resource_state sg_query_pipeline_state(sg_pipeline pip_id) {
  19007. SOKOL_ASSERT(_sg.valid);
  19008. _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  19009. sg_resource_state res = pip ? pip->slot.state : SG_RESOURCESTATE_INVALID;
  19010. return res;
  19011. }
  19012. SOKOL_API_IMPL sg_resource_state sg_query_attachments_state(sg_attachments atts_id) {
  19013. SOKOL_ASSERT(_sg.valid);
  19014. _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  19015. sg_resource_state res = atts ? atts->slot.state : SG_RESOURCESTATE_INVALID;
  19016. return res;
  19017. }
  19018. SOKOL_API_IMPL sg_buffer sg_make_buffer(const sg_buffer_desc* desc) {
  19019. SOKOL_ASSERT(_sg.valid);
  19020. SOKOL_ASSERT(desc);
  19021. sg_buffer_desc desc_def = _sg_buffer_desc_defaults(desc);
  19022. sg_buffer buf_id = _sg_alloc_buffer();
  19023. if (buf_id.id != SG_INVALID_ID) {
  19024. _sg_buffer_t* buf = _sg_buffer_at(buf_id.id);
  19025. SOKOL_ASSERT(buf && (buf->slot.state == SG_RESOURCESTATE_ALLOC));
  19026. _sg_init_buffer(buf, &desc_def);
  19027. SOKOL_ASSERT((buf->slot.state == SG_RESOURCESTATE_VALID) || (buf->slot.state == SG_RESOURCESTATE_FAILED));
  19028. }
  19029. _SG_TRACE_ARGS(make_buffer, &desc_def, buf_id);
  19030. return buf_id;
  19031. }
  19032. SOKOL_API_IMPL sg_image sg_make_image(const sg_image_desc* desc) {
  19033. SOKOL_ASSERT(_sg.valid);
  19034. SOKOL_ASSERT(desc);
  19035. sg_image_desc desc_def = _sg_image_desc_defaults(desc);
  19036. sg_image img_id = _sg_alloc_image();
  19037. if (img_id.id != SG_INVALID_ID) {
  19038. _sg_image_t* img = _sg_image_at(img_id.id);
  19039. SOKOL_ASSERT(img && (img->slot.state == SG_RESOURCESTATE_ALLOC));
  19040. _sg_init_image(img, &desc_def);
  19041. SOKOL_ASSERT((img->slot.state == SG_RESOURCESTATE_VALID) || (img->slot.state == SG_RESOURCESTATE_FAILED));
  19042. }
  19043. _SG_TRACE_ARGS(make_image, &desc_def, img_id);
  19044. return img_id;
  19045. }
  19046. SOKOL_API_IMPL sg_sampler sg_make_sampler(const sg_sampler_desc* desc) {
  19047. SOKOL_ASSERT(_sg.valid);
  19048. SOKOL_ASSERT(desc);
  19049. sg_sampler_desc desc_def = _sg_sampler_desc_defaults(desc);
  19050. sg_sampler smp_id = _sg_alloc_sampler();
  19051. if (smp_id.id != SG_INVALID_ID) {
  19052. _sg_sampler_t* smp = _sg_sampler_at(smp_id.id);
  19053. SOKOL_ASSERT(smp && (smp->slot.state == SG_RESOURCESTATE_ALLOC));
  19054. _sg_init_sampler(smp, &desc_def);
  19055. SOKOL_ASSERT((smp->slot.state == SG_RESOURCESTATE_VALID) || (smp->slot.state == SG_RESOURCESTATE_FAILED));
  19056. }
  19057. _SG_TRACE_ARGS(make_sampler, &desc_def, smp_id);
  19058. return smp_id;
  19059. }
  19060. SOKOL_API_IMPL sg_shader sg_make_shader(const sg_shader_desc* desc) {
  19061. SOKOL_ASSERT(_sg.valid);
  19062. SOKOL_ASSERT(desc);
  19063. sg_shader_desc desc_def = _sg_shader_desc_defaults(desc);
  19064. sg_shader shd_id = _sg_alloc_shader();
  19065. if (shd_id.id != SG_INVALID_ID) {
  19066. _sg_shader_t* shd = _sg_shader_at(shd_id.id);
  19067. SOKOL_ASSERT(shd && (shd->slot.state == SG_RESOURCESTATE_ALLOC));
  19068. _sg_init_shader(shd, &desc_def);
  19069. SOKOL_ASSERT((shd->slot.state == SG_RESOURCESTATE_VALID) || (shd->slot.state == SG_RESOURCESTATE_FAILED));
  19070. }
  19071. _SG_TRACE_ARGS(make_shader, &desc_def, shd_id);
  19072. return shd_id;
  19073. }
  19074. SOKOL_API_IMPL sg_pipeline sg_make_pipeline(const sg_pipeline_desc* desc) {
  19075. SOKOL_ASSERT(_sg.valid);
  19076. SOKOL_ASSERT(desc);
  19077. sg_pipeline_desc desc_def = _sg_pipeline_desc_defaults(desc);
  19078. sg_pipeline pip_id = _sg_alloc_pipeline();
  19079. if (pip_id.id != SG_INVALID_ID) {
  19080. _sg_pipeline_t* pip = _sg_pipeline_at(pip_id.id);
  19081. SOKOL_ASSERT(pip && (pip->slot.state == SG_RESOURCESTATE_ALLOC));
  19082. _sg_init_pipeline(pip, &desc_def);
  19083. SOKOL_ASSERT((pip->slot.state == SG_RESOURCESTATE_VALID) || (pip->slot.state == SG_RESOURCESTATE_FAILED));
  19084. }
  19085. _SG_TRACE_ARGS(make_pipeline, &desc_def, pip_id);
  19086. return pip_id;
  19087. }
  19088. SOKOL_API_IMPL sg_attachments sg_make_attachments(const sg_attachments_desc* desc) {
  19089. SOKOL_ASSERT(_sg.valid);
  19090. SOKOL_ASSERT(desc);
  19091. sg_attachments_desc desc_def = _sg_attachments_desc_defaults(desc);
  19092. sg_attachments atts_id = _sg_alloc_attachments();
  19093. if (atts_id.id != SG_INVALID_ID) {
  19094. _sg_attachments_t* atts = _sg_attachments_at(atts_id.id);
  19095. SOKOL_ASSERT(atts && (atts->slot.state == SG_RESOURCESTATE_ALLOC));
  19096. _sg_init_attachments(atts, &desc_def);
  19097. SOKOL_ASSERT((atts->slot.state == SG_RESOURCESTATE_VALID) || (atts->slot.state == SG_RESOURCESTATE_FAILED));
  19098. }
  19099. _SG_TRACE_ARGS(make_attachments, &desc_def, atts_id);
  19100. return atts_id;
  19101. }
  19102. SOKOL_API_IMPL void sg_destroy_buffer(sg_buffer buf_id) {
  19103. SOKOL_ASSERT(_sg.valid);
  19104. _SG_TRACE_ARGS(destroy_buffer, buf_id);
  19105. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19106. if (buf) {
  19107. if ((buf->slot.state == SG_RESOURCESTATE_VALID) || (buf->slot.state == SG_RESOURCESTATE_FAILED)) {
  19108. _sg_uninit_buffer(buf);
  19109. SOKOL_ASSERT(buf->slot.state == SG_RESOURCESTATE_ALLOC);
  19110. }
  19111. if (buf->slot.state == SG_RESOURCESTATE_ALLOC) {
  19112. _sg_dealloc_buffer(buf);
  19113. SOKOL_ASSERT(buf->slot.state == SG_RESOURCESTATE_INITIAL);
  19114. }
  19115. }
  19116. }
  19117. SOKOL_API_IMPL void sg_destroy_image(sg_image img_id) {
  19118. SOKOL_ASSERT(_sg.valid);
  19119. _SG_TRACE_ARGS(destroy_image, img_id);
  19120. _sg_image_t* img = _sg_lookup_image(img_id.id);
  19121. if (img) {
  19122. if ((img->slot.state == SG_RESOURCESTATE_VALID) || (img->slot.state == SG_RESOURCESTATE_FAILED)) {
  19123. _sg_uninit_image(img);
  19124. SOKOL_ASSERT(img->slot.state == SG_RESOURCESTATE_ALLOC);
  19125. }
  19126. if (img->slot.state == SG_RESOURCESTATE_ALLOC) {
  19127. _sg_dealloc_image(img);
  19128. SOKOL_ASSERT(img->slot.state == SG_RESOURCESTATE_INITIAL);
  19129. }
  19130. }
  19131. }
  19132. SOKOL_API_IMPL void sg_destroy_sampler(sg_sampler smp_id) {
  19133. SOKOL_ASSERT(_sg.valid);
  19134. _SG_TRACE_ARGS(destroy_sampler, smp_id);
  19135. _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  19136. if (smp) {
  19137. if ((smp->slot.state == SG_RESOURCESTATE_VALID) || (smp->slot.state == SG_RESOURCESTATE_FAILED)) {
  19138. _sg_uninit_sampler(smp);
  19139. SOKOL_ASSERT(smp->slot.state == SG_RESOURCESTATE_ALLOC);
  19140. }
  19141. if (smp->slot.state == SG_RESOURCESTATE_ALLOC) {
  19142. _sg_dealloc_sampler(smp);
  19143. SOKOL_ASSERT(smp->slot.state == SG_RESOURCESTATE_INITIAL);
  19144. }
  19145. }
  19146. }
  19147. SOKOL_API_IMPL void sg_destroy_shader(sg_shader shd_id) {
  19148. SOKOL_ASSERT(_sg.valid);
  19149. _SG_TRACE_ARGS(destroy_shader, shd_id);
  19150. _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  19151. if (shd) {
  19152. if ((shd->slot.state == SG_RESOURCESTATE_VALID) || (shd->slot.state == SG_RESOURCESTATE_FAILED)) {
  19153. _sg_uninit_shader(shd);
  19154. SOKOL_ASSERT(shd->slot.state == SG_RESOURCESTATE_ALLOC);
  19155. }
  19156. if (shd->slot.state == SG_RESOURCESTATE_ALLOC) {
  19157. _sg_dealloc_shader(shd);
  19158. SOKOL_ASSERT(shd->slot.state == SG_RESOURCESTATE_INITIAL);
  19159. }
  19160. }
  19161. }
  19162. SOKOL_API_IMPL void sg_destroy_pipeline(sg_pipeline pip_id) {
  19163. SOKOL_ASSERT(_sg.valid);
  19164. _SG_TRACE_ARGS(destroy_pipeline, pip_id);
  19165. _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  19166. if (pip) {
  19167. if ((pip->slot.state == SG_RESOURCESTATE_VALID) || (pip->slot.state == SG_RESOURCESTATE_FAILED)) {
  19168. _sg_uninit_pipeline(pip);
  19169. SOKOL_ASSERT(pip->slot.state == SG_RESOURCESTATE_ALLOC);
  19170. }
  19171. if (pip->slot.state == SG_RESOURCESTATE_ALLOC) {
  19172. _sg_dealloc_pipeline(pip);
  19173. SOKOL_ASSERT(pip->slot.state == SG_RESOURCESTATE_INITIAL);
  19174. }
  19175. }
  19176. }
  19177. SOKOL_API_IMPL void sg_destroy_attachments(sg_attachments atts_id) {
  19178. SOKOL_ASSERT(_sg.valid);
  19179. _SG_TRACE_ARGS(destroy_attachments, atts_id);
  19180. _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  19181. if (atts) {
  19182. if ((atts->slot.state == SG_RESOURCESTATE_VALID) || (atts->slot.state == SG_RESOURCESTATE_FAILED)) {
  19183. _sg_uninit_attachments(atts);
  19184. SOKOL_ASSERT(atts->slot.state == SG_RESOURCESTATE_ALLOC);
  19185. }
  19186. if (atts->slot.state == SG_RESOURCESTATE_ALLOC) {
  19187. _sg_dealloc_attachments(atts);
  19188. SOKOL_ASSERT(atts->slot.state == SG_RESOURCESTATE_INITIAL);
  19189. }
  19190. }
  19191. }
  19192. SOKOL_API_IMPL void sg_begin_pass(const sg_pass* pass) {
  19193. SOKOL_ASSERT(_sg.valid);
  19194. SOKOL_ASSERT(!_sg.cur_pass.valid);
  19195. SOKOL_ASSERT(!_sg.cur_pass.in_pass);
  19196. SOKOL_ASSERT(_sg_attachments_ref_null(&_sg.cur_pass.atts));
  19197. SOKOL_ASSERT(pass);
  19198. SOKOL_ASSERT((pass->_start_canary == 0) && (pass->_end_canary == 0));
  19199. const sg_pass pass_def = _sg_pass_defaults(pass);
  19200. if (!_sg_validate_begin_pass(&pass_def)) {
  19201. return;
  19202. }
  19203. _sg.cur_pass.atts = _sg_attachments_ref(0);
  19204. if (pass_def.attachments.id != SG_INVALID_ID) {
  19205. _sg_attachments_t* atts = _sg_lookup_attachments(pass_def.attachments.id);
  19206. if (0 == atts) {
  19207. _SG_ERROR(BEGINPASS_ATTACHMENT_INVALID);
  19208. return;
  19209. }
  19210. SOKOL_ASSERT(atts);
  19211. _sg.cur_pass.atts = _sg_attachments_ref(atts);
  19212. _sg.cur_pass.width = atts->cmn.width;
  19213. _sg.cur_pass.height = atts->cmn.height;
  19214. } else if (!pass_def.compute) {
  19215. // a swapchain pass
  19216. SOKOL_ASSERT(pass_def.swapchain.width > 0);
  19217. SOKOL_ASSERT(pass_def.swapchain.height > 0);
  19218. SOKOL_ASSERT(pass_def.swapchain.color_format > SG_PIXELFORMAT_NONE);
  19219. SOKOL_ASSERT(pass_def.swapchain.sample_count > 0);
  19220. _sg.cur_pass.width = pass_def.swapchain.width;
  19221. _sg.cur_pass.height = pass_def.swapchain.height;
  19222. _sg.cur_pass.swapchain.color_fmt = pass_def.swapchain.color_format;
  19223. _sg.cur_pass.swapchain.depth_fmt = pass_def.swapchain.depth_format;
  19224. _sg.cur_pass.swapchain.sample_count = pass_def.swapchain.sample_count;
  19225. }
  19226. _sg.cur_pass.valid = true; // may be overruled by backend begin-pass functions
  19227. _sg.cur_pass.in_pass = true;
  19228. _sg.cur_pass.is_compute = pass_def.compute;
  19229. _sg_begin_pass(&pass_def);
  19230. _SG_TRACE_ARGS(begin_pass, &pass_def);
  19231. }
  19232. SOKOL_API_IMPL void sg_apply_viewport(int x, int y, int width, int height, bool origin_top_left) {
  19233. SOKOL_ASSERT(_sg.valid);
  19234. #if defined(SOKOL_DEBUG)
  19235. if (!_sg_validate_apply_viewport(x, y, width, height, origin_top_left)) {
  19236. return;
  19237. }
  19238. #endif
  19239. _sg_stats_add(num_apply_viewport, 1);
  19240. if (!_sg.cur_pass.valid) {
  19241. return;
  19242. }
  19243. _sg_apply_viewport(x, y, width, height, origin_top_left);
  19244. _SG_TRACE_ARGS(apply_viewport, x, y, width, height, origin_top_left);
  19245. }
  19246. SOKOL_API_IMPL void sg_apply_viewportf(float x, float y, float width, float height, bool origin_top_left) {
  19247. sg_apply_viewport((int)x, (int)y, (int)width, (int)height, origin_top_left);
  19248. }
  19249. SOKOL_API_IMPL void sg_apply_scissor_rect(int x, int y, int width, int height, bool origin_top_left) {
  19250. SOKOL_ASSERT(_sg.valid);
  19251. #if defined(SOKOL_DEBUG)
  19252. if (!_sg_validate_apply_scissor_rect(x, y, width, height, origin_top_left)) {
  19253. return;
  19254. }
  19255. #endif
  19256. _sg_stats_add(num_apply_scissor_rect, 1);
  19257. if (!_sg.cur_pass.valid) {
  19258. return;
  19259. }
  19260. _sg_apply_scissor_rect(x, y, width, height, origin_top_left);
  19261. _SG_TRACE_ARGS(apply_scissor_rect, x, y, width, height, origin_top_left);
  19262. }
  19263. SOKOL_API_IMPL void sg_apply_scissor_rectf(float x, float y, float width, float height, bool origin_top_left) {
  19264. sg_apply_scissor_rect((int)x, (int)y, (int)width, (int)height, origin_top_left);
  19265. }
  19266. SOKOL_API_IMPL void sg_apply_pipeline(sg_pipeline pip_id) {
  19267. SOKOL_ASSERT(_sg.valid);
  19268. _sg_stats_add(num_apply_pipeline, 1);
  19269. if (!_sg_validate_apply_pipeline(pip_id)) {
  19270. _sg.next_draw_valid = false;
  19271. return;
  19272. }
  19273. if (!_sg.cur_pass.valid) {
  19274. return;
  19275. }
  19276. _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  19277. SOKOL_ASSERT(pip);
  19278. _sg.cur_pip = _sg_pipeline_ref(pip);
  19279. _sg.next_draw_valid = (SG_RESOURCESTATE_VALID == pip->slot.state);
  19280. if (!_sg.next_draw_valid) {
  19281. return;
  19282. }
  19283. _sg_apply_pipeline(pip);
  19284. // set the expected bindings and uniform block flags
  19285. const _sg_shader_t* shd = _sg_shader_ref_ptr(&pip->cmn.shader);
  19286. _sg.required_bindings_and_uniforms = pip->cmn.required_bindings_and_uniforms | shd->cmn.required_bindings_and_uniforms;
  19287. _sg.applied_bindings_and_uniforms = 0;
  19288. _SG_TRACE_ARGS(apply_pipeline, pip_id);
  19289. }
  19290. SOKOL_API_IMPL void sg_apply_bindings(const sg_bindings* bindings) {
  19291. SOKOL_ASSERT(_sg.valid);
  19292. SOKOL_ASSERT(bindings);
  19293. SOKOL_ASSERT((bindings->_start_canary == 0) && (bindings->_end_canary==0));
  19294. _sg_stats_add(num_apply_bindings, 1);
  19295. _sg.applied_bindings_and_uniforms |= (1 << SG_MAX_UNIFORMBLOCK_BINDSLOTS);
  19296. if (!_sg_validate_apply_bindings(bindings)) {
  19297. _sg.next_draw_valid = false;
  19298. }
  19299. if (!_sg_pipeline_ref_alive(&_sg.cur_pip)) {
  19300. _sg.next_draw_valid = false;
  19301. }
  19302. if (!_sg.cur_pass.valid) {
  19303. return;
  19304. }
  19305. if (!_sg.next_draw_valid) {
  19306. return;
  19307. }
  19308. _sg_bindings_ptrs_t bnd;
  19309. _sg_clear(&bnd, sizeof(bnd));
  19310. bnd.pip = _sg_pipeline_ref_ptr(&_sg.cur_pip);
  19311. const _sg_shader_t* shd = _sg_shader_ref_ptr(&bnd.pip->cmn.shader);
  19312. if (!_sg.cur_pass.is_compute) {
  19313. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  19314. if (bnd.pip->cmn.vertex_buffer_layout_active[i]) {
  19315. SOKOL_ASSERT(bindings->vertex_buffers[i].id != SG_INVALID_ID);
  19316. bnd.vbs[i] = _sg_lookup_buffer(bindings->vertex_buffers[i].id);
  19317. bnd.vb_offsets[i] = bindings->vertex_buffer_offsets[i];
  19318. if (bnd.vbs[i]) {
  19319. _sg.next_draw_valid &= (SG_RESOURCESTATE_VALID == bnd.vbs[i]->slot.state);
  19320. _sg.next_draw_valid &= !bnd.vbs[i]->cmn.append_overflow;
  19321. } else {
  19322. _sg.next_draw_valid = false;
  19323. }
  19324. }
  19325. }
  19326. if (bindings->index_buffer.id) {
  19327. bnd.ib = _sg_lookup_buffer(bindings->index_buffer.id);
  19328. bnd.ib_offset = bindings->index_buffer_offset;
  19329. if (bnd.ib) {
  19330. _sg.next_draw_valid &= (SG_RESOURCESTATE_VALID == bnd.ib->slot.state);
  19331. _sg.next_draw_valid &= !bnd.ib->cmn.append_overflow;
  19332. } else {
  19333. _sg.next_draw_valid = false;
  19334. }
  19335. }
  19336. }
  19337. for (int i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  19338. if (shd->cmn.images[i].stage != SG_SHADERSTAGE_NONE) {
  19339. SOKOL_ASSERT(bindings->images[i].id != SG_INVALID_ID);
  19340. bnd.imgs[i] = _sg_lookup_image(bindings->images[i].id);
  19341. if (bnd.imgs[i]) {
  19342. _sg.next_draw_valid &= (SG_RESOURCESTATE_VALID == bnd.imgs[i]->slot.state);
  19343. } else {
  19344. _sg.next_draw_valid = false;
  19345. }
  19346. }
  19347. }
  19348. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  19349. if (shd->cmn.samplers[i].stage != SG_SHADERSTAGE_NONE) {
  19350. SOKOL_ASSERT(bindings->samplers[i].id != SG_INVALID_ID);
  19351. bnd.smps[i] = _sg_lookup_sampler(bindings->samplers[i].id);
  19352. if (bnd.smps[i]) {
  19353. _sg.next_draw_valid &= (SG_RESOURCESTATE_VALID == bnd.smps[i]->slot.state);
  19354. } else {
  19355. _sg.next_draw_valid = false;
  19356. }
  19357. }
  19358. }
  19359. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  19360. if (shd->cmn.storage_buffers[i].stage != SG_SHADERSTAGE_NONE) {
  19361. SOKOL_ASSERT(bindings->storage_buffers[i].id != SG_INVALID_ID);
  19362. bnd.sbufs[i] = _sg_lookup_buffer(bindings->storage_buffers[i].id);
  19363. if (bnd.sbufs[i]) {
  19364. _sg.next_draw_valid &= (SG_RESOURCESTATE_VALID == bnd.sbufs[i]->slot.state);
  19365. if (_sg.cur_pass.is_compute) {
  19366. _sg_compute_pass_track_storage_buffer(bnd.sbufs[i], shd->cmn.storage_buffers[i].readonly);
  19367. }
  19368. } else {
  19369. _sg.next_draw_valid = false;
  19370. }
  19371. }
  19372. }
  19373. if (_sg.next_draw_valid) {
  19374. _sg.next_draw_valid &= _sg_apply_bindings(&bnd);
  19375. _SG_TRACE_ARGS(apply_bindings, bindings);
  19376. }
  19377. }
  19378. SOKOL_API_IMPL void sg_apply_uniforms(int ub_slot, const sg_range* data) {
  19379. SOKOL_ASSERT(_sg.valid);
  19380. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  19381. SOKOL_ASSERT(data && data->ptr && (data->size > 0));
  19382. _sg_stats_add(num_apply_uniforms, 1);
  19383. _sg_stats_add(size_apply_uniforms, (uint32_t)data->size);
  19384. _sg.applied_bindings_and_uniforms |= 1 << ub_slot;
  19385. if (!_sg_validate_apply_uniforms(ub_slot, data)) {
  19386. _sg.next_draw_valid = false;
  19387. return;
  19388. }
  19389. if (!_sg.cur_pass.valid) {
  19390. return;
  19391. }
  19392. if (!_sg.next_draw_valid) {
  19393. return;
  19394. }
  19395. _sg_apply_uniforms(ub_slot, data);
  19396. _SG_TRACE_ARGS(apply_uniforms, ub_slot, data);
  19397. }
  19398. SOKOL_API_IMPL void sg_draw(int base_element, int num_elements, int num_instances) {
  19399. SOKOL_ASSERT(_sg.valid);
  19400. #if defined(SOKOL_DEBUG)
  19401. if (!_sg_validate_draw(base_element, num_elements, num_instances)) {
  19402. return;
  19403. }
  19404. #endif
  19405. _sg_stats_add(num_draw, 1);
  19406. if (!_sg.cur_pass.valid) {
  19407. return;
  19408. }
  19409. if (!_sg.next_draw_valid) {
  19410. return;
  19411. }
  19412. // skip no-op draws
  19413. if ((0 == num_elements) || (0 == num_instances)) {
  19414. return;
  19415. }
  19416. _sg_draw(base_element, num_elements, num_instances);
  19417. _SG_TRACE_ARGS(draw, base_element, num_elements, num_instances);
  19418. }
  19419. SOKOL_API_IMPL void sg_dispatch(int num_groups_x, int num_groups_y, int num_groups_z) {
  19420. SOKOL_ASSERT(_sg.valid);
  19421. #if defined(SOKOL_DEBUG)
  19422. if (!_sg_validate_dispatch(num_groups_x, num_groups_y, num_groups_z)) {
  19423. return;
  19424. }
  19425. #endif
  19426. _sg_stats_add(num_dispatch, 1);
  19427. if (!_sg.cur_pass.valid) {
  19428. return;
  19429. }
  19430. if (!_sg.next_draw_valid) {
  19431. return;
  19432. }
  19433. // skip no-op dispatches
  19434. if ((0 == num_groups_x) || (0 == num_groups_y) || (0 == num_groups_z)) {
  19435. return;
  19436. }
  19437. _sg_dispatch(num_groups_x, num_groups_y, num_groups_z);
  19438. _SG_TRACE_ARGS(dispatch, num_groups_x, num_groups_y, num_groups_z);
  19439. }
  19440. SOKOL_API_IMPL void sg_end_pass(void) {
  19441. SOKOL_ASSERT(_sg.valid);
  19442. SOKOL_ASSERT(_sg.cur_pass.in_pass);
  19443. _sg_stats_add(num_passes, 1);
  19444. // NOTE: don't exit early if !_sg.cur_pass.valid
  19445. _sg_end_pass();
  19446. _sg.cur_pip = _sg_pipeline_ref(0);
  19447. if (_sg.cur_pass.is_compute) {
  19448. _sg_compute_on_endpass();
  19449. }
  19450. _sg_clear(&_sg.cur_pass, sizeof(_sg.cur_pass));
  19451. _SG_TRACE_NOARGS(end_pass);
  19452. }
  19453. SOKOL_API_IMPL void sg_commit(void) {
  19454. SOKOL_ASSERT(_sg.valid);
  19455. SOKOL_ASSERT(!_sg.cur_pass.valid);
  19456. SOKOL_ASSERT(!_sg.cur_pass.in_pass);
  19457. _sg_commit();
  19458. _sg.stats.frame_index = _sg.frame_index;
  19459. _sg.prev_stats = _sg.stats;
  19460. _sg_clear(&_sg.stats, sizeof(_sg.stats));
  19461. _sg_notify_commit_listeners();
  19462. _SG_TRACE_NOARGS(commit);
  19463. _sg.frame_index++;
  19464. }
  19465. SOKOL_API_IMPL void sg_reset_state_cache(void) {
  19466. SOKOL_ASSERT(_sg.valid);
  19467. _sg_reset_state_cache();
  19468. _SG_TRACE_NOARGS(reset_state_cache);
  19469. }
  19470. SOKOL_API_IMPL void sg_update_buffer(sg_buffer buf_id, const sg_range* data) {
  19471. SOKOL_ASSERT(_sg.valid);
  19472. SOKOL_ASSERT(data && data->ptr && (data->size > 0));
  19473. _sg_stats_add(num_update_buffer, 1);
  19474. _sg_stats_add(size_update_buffer, (uint32_t)data->size);
  19475. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19476. if ((data->size > 0) && buf && (buf->slot.state == SG_RESOURCESTATE_VALID)) {
  19477. if (_sg_validate_update_buffer(buf, data)) {
  19478. SOKOL_ASSERT(data->size <= (size_t)buf->cmn.size);
  19479. // only one update allowed per buffer and frame
  19480. SOKOL_ASSERT(buf->cmn.update_frame_index != _sg.frame_index);
  19481. // update and append on same buffer in same frame not allowed
  19482. SOKOL_ASSERT(buf->cmn.append_frame_index != _sg.frame_index);
  19483. _sg_update_buffer(buf, data);
  19484. buf->cmn.update_frame_index = _sg.frame_index;
  19485. }
  19486. }
  19487. _SG_TRACE_ARGS(update_buffer, buf_id, data);
  19488. }
  19489. SOKOL_API_IMPL int sg_append_buffer(sg_buffer buf_id, const sg_range* data) {
  19490. SOKOL_ASSERT(_sg.valid);
  19491. SOKOL_ASSERT(data && data->ptr);
  19492. _sg_stats_add(num_append_buffer, 1);
  19493. _sg_stats_add(size_append_buffer, (uint32_t)data->size);
  19494. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19495. int result;
  19496. if (buf) {
  19497. // rewind append cursor in a new frame
  19498. if (buf->cmn.append_frame_index != _sg.frame_index) {
  19499. buf->cmn.append_pos = 0;
  19500. buf->cmn.append_overflow = false;
  19501. }
  19502. if (((size_t)buf->cmn.append_pos + data->size) > (size_t)buf->cmn.size) {
  19503. buf->cmn.append_overflow = true;
  19504. }
  19505. const int start_pos = buf->cmn.append_pos;
  19506. // NOTE: the multiple-of-4 requirement for the buffer offset is coming
  19507. // from WebGPU, but we want identical behaviour between backends
  19508. SOKOL_ASSERT(_sg_multiple_u64((uint64_t)start_pos, 4));
  19509. if (buf->slot.state == SG_RESOURCESTATE_VALID) {
  19510. if (_sg_validate_append_buffer(buf, data)) {
  19511. if (!buf->cmn.append_overflow && (data->size > 0)) {
  19512. // update and append on same buffer in same frame not allowed
  19513. SOKOL_ASSERT(buf->cmn.update_frame_index != _sg.frame_index);
  19514. _sg_append_buffer(buf, data, buf->cmn.append_frame_index != _sg.frame_index);
  19515. buf->cmn.append_pos += (int) _sg_roundup_u64(data->size, 4);
  19516. buf->cmn.append_frame_index = _sg.frame_index;
  19517. }
  19518. }
  19519. }
  19520. result = start_pos;
  19521. } else {
  19522. // FIXME: should we return -1 here?
  19523. result = 0;
  19524. }
  19525. _SG_TRACE_ARGS(append_buffer, buf_id, data, result);
  19526. return result;
  19527. }
  19528. SOKOL_API_IMPL bool sg_query_buffer_overflow(sg_buffer buf_id) {
  19529. SOKOL_ASSERT(_sg.valid);
  19530. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19531. bool result = buf ? buf->cmn.append_overflow : false;
  19532. return result;
  19533. }
  19534. SOKOL_API_IMPL bool sg_query_buffer_will_overflow(sg_buffer buf_id, size_t size) {
  19535. SOKOL_ASSERT(_sg.valid);
  19536. _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19537. bool result = false;
  19538. if (buf) {
  19539. int append_pos = buf->cmn.append_pos;
  19540. // rewind append cursor in a new frame
  19541. if (buf->cmn.append_frame_index != _sg.frame_index) {
  19542. append_pos = 0;
  19543. }
  19544. if ((append_pos + _sg_roundup((int)size, 4)) > buf->cmn.size) {
  19545. result = true;
  19546. }
  19547. }
  19548. return result;
  19549. }
  19550. SOKOL_API_IMPL void sg_update_image(sg_image img_id, const sg_image_data* data) {
  19551. SOKOL_ASSERT(_sg.valid);
  19552. _sg_stats_add(num_update_image, 1);
  19553. for (int face_index = 0; face_index < SG_CUBEFACE_NUM; face_index++) {
  19554. for (int mip_index = 0; mip_index < SG_MAX_MIPMAPS; mip_index++) {
  19555. if (data->subimage[face_index][mip_index].size == 0) {
  19556. break;
  19557. }
  19558. _sg_stats_add(size_update_image, (uint32_t)data->subimage[face_index][mip_index].size);
  19559. }
  19560. }
  19561. _sg_image_t* img = _sg_lookup_image(img_id.id);
  19562. if (img && img->slot.state == SG_RESOURCESTATE_VALID) {
  19563. if (_sg_validate_update_image(img, data)) {
  19564. SOKOL_ASSERT(img->cmn.upd_frame_index != _sg.frame_index);
  19565. _sg_update_image(img, data);
  19566. img->cmn.upd_frame_index = _sg.frame_index;
  19567. }
  19568. }
  19569. _SG_TRACE_ARGS(update_image, img_id, data);
  19570. }
  19571. SOKOL_API_IMPL void sg_push_debug_group(const char* name) {
  19572. SOKOL_ASSERT(_sg.valid);
  19573. SOKOL_ASSERT(name);
  19574. _sg_push_debug_group(name);
  19575. _SG_TRACE_ARGS(push_debug_group, name);
  19576. }
  19577. SOKOL_API_IMPL void sg_pop_debug_group(void) {
  19578. SOKOL_ASSERT(_sg.valid);
  19579. _sg_pop_debug_group();
  19580. _SG_TRACE_NOARGS(pop_debug_group);
  19581. }
  19582. SOKOL_API_IMPL bool sg_add_commit_listener(sg_commit_listener listener) {
  19583. SOKOL_ASSERT(_sg.valid);
  19584. return _sg_add_commit_listener(&listener);
  19585. }
  19586. SOKOL_API_IMPL bool sg_remove_commit_listener(sg_commit_listener listener) {
  19587. SOKOL_ASSERT(_sg.valid);
  19588. return _sg_remove_commit_listener(&listener);
  19589. }
  19590. SOKOL_API_IMPL void sg_enable_frame_stats(void) {
  19591. SOKOL_ASSERT(_sg.valid);
  19592. _sg.stats_enabled = true;
  19593. }
  19594. SOKOL_API_IMPL void sg_disable_frame_stats(void) {
  19595. SOKOL_ASSERT(_sg.valid);
  19596. _sg.stats_enabled = false;
  19597. }
  19598. SOKOL_API_IMPL bool sg_frame_stats_enabled(void) {
  19599. return _sg.stats_enabled;
  19600. }
  19601. SOKOL_API_IMPL sg_buffer_info sg_query_buffer_info(sg_buffer buf_id) {
  19602. SOKOL_ASSERT(_sg.valid);
  19603. sg_buffer_info info;
  19604. _sg_clear(&info, sizeof(info));
  19605. const _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19606. if (buf) {
  19607. info.slot.state = buf->slot.state;
  19608. info.slot.res_id = buf->slot.id;
  19609. info.slot.uninit_count = buf->slot.uninit_count;
  19610. info.update_frame_index = buf->cmn.update_frame_index;
  19611. info.append_frame_index = buf->cmn.append_frame_index;
  19612. info.append_pos = buf->cmn.append_pos;
  19613. info.append_overflow = buf->cmn.append_overflow;
  19614. #if defined(SOKOL_D3D11)
  19615. info.num_slots = 1;
  19616. info.active_slot = 0;
  19617. #else
  19618. info.num_slots = buf->cmn.num_slots;
  19619. info.active_slot = buf->cmn.active_slot;
  19620. #endif
  19621. }
  19622. return info;
  19623. }
  19624. SOKOL_API_IMPL sg_image_info sg_query_image_info(sg_image img_id) {
  19625. SOKOL_ASSERT(_sg.valid);
  19626. sg_image_info info;
  19627. _sg_clear(&info, sizeof(info));
  19628. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19629. if (img) {
  19630. info.slot.state = img->slot.state;
  19631. info.slot.res_id = img->slot.id;
  19632. info.slot.uninit_count = img->slot.uninit_count;
  19633. info.upd_frame_index = img->cmn.upd_frame_index;
  19634. #if defined(SOKOL_D3D11)
  19635. info.num_slots = 1;
  19636. info.active_slot = 0;
  19637. #else
  19638. info.num_slots = img->cmn.num_slots;
  19639. info.active_slot = img->cmn.active_slot;
  19640. #endif
  19641. }
  19642. return info;
  19643. }
  19644. SOKOL_API_IMPL sg_sampler_info sg_query_sampler_info(sg_sampler smp_id) {
  19645. SOKOL_ASSERT(_sg.valid);
  19646. sg_sampler_info info;
  19647. _sg_clear(&info, sizeof(info));
  19648. const _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  19649. if (smp) {
  19650. info.slot.state = smp->slot.state;
  19651. info.slot.res_id = smp->slot.id;
  19652. info.slot.uninit_count = smp->slot.uninit_count;
  19653. }
  19654. return info;
  19655. }
  19656. SOKOL_API_IMPL sg_shader_info sg_query_shader_info(sg_shader shd_id) {
  19657. SOKOL_ASSERT(_sg.valid);
  19658. sg_shader_info info;
  19659. _sg_clear(&info, sizeof(info));
  19660. const _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  19661. if (shd) {
  19662. info.slot.state = shd->slot.state;
  19663. info.slot.res_id = shd->slot.id;
  19664. info.slot.uninit_count = shd->slot.uninit_count;
  19665. }
  19666. return info;
  19667. }
  19668. SOKOL_API_IMPL sg_pipeline_info sg_query_pipeline_info(sg_pipeline pip_id) {
  19669. SOKOL_ASSERT(_sg.valid);
  19670. sg_pipeline_info info;
  19671. _sg_clear(&info, sizeof(info));
  19672. const _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  19673. if (pip) {
  19674. info.slot.state = pip->slot.state;
  19675. info.slot.res_id = pip->slot.id;
  19676. info.slot.uninit_count = pip->slot.uninit_count;
  19677. }
  19678. return info;
  19679. }
  19680. SOKOL_API_IMPL sg_attachments_info sg_query_attachments_info(sg_attachments atts_id) {
  19681. SOKOL_ASSERT(_sg.valid);
  19682. sg_attachments_info info;
  19683. _sg_clear(&info, sizeof(info));
  19684. const _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  19685. if (atts) {
  19686. info.slot.state = atts->slot.state;
  19687. info.slot.res_id = atts->slot.id;
  19688. info.slot.uninit_count = atts->slot.uninit_count;
  19689. }
  19690. return info;
  19691. }
  19692. SOKOL_API_IMPL sg_buffer_desc sg_query_buffer_desc(sg_buffer buf_id) {
  19693. SOKOL_ASSERT(_sg.valid);
  19694. sg_buffer_desc desc;
  19695. _sg_clear(&desc, sizeof(desc));
  19696. const _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19697. if (buf) {
  19698. desc.size = (size_t)buf->cmn.size;
  19699. desc.usage = buf->cmn.usage;
  19700. }
  19701. return desc;
  19702. }
  19703. SOKOL_API_IMPL size_t sg_query_buffer_size(sg_buffer buf_id) {
  19704. SOKOL_ASSERT(_sg.valid);
  19705. const _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19706. if (buf) {
  19707. return (size_t)buf->cmn.size;
  19708. }
  19709. return 0;
  19710. }
  19711. SOKOL_API_IMPL sg_buffer_usage sg_query_buffer_usage(sg_buffer buf_id) {
  19712. SOKOL_ASSERT(_sg.valid);
  19713. sg_buffer_usage usg;
  19714. _sg_clear(&usg, sizeof(usg));
  19715. const _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19716. if (buf) {
  19717. usg = buf->cmn.usage;
  19718. }
  19719. return usg;
  19720. }
  19721. SOKOL_API_IMPL sg_image_desc sg_query_image_desc(sg_image img_id) {
  19722. SOKOL_ASSERT(_sg.valid);
  19723. sg_image_desc desc;
  19724. _sg_clear(&desc, sizeof(desc));
  19725. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19726. if (img) {
  19727. desc.type = img->cmn.type;
  19728. desc.width = img->cmn.width;
  19729. desc.height = img->cmn.height;
  19730. desc.num_slices = img->cmn.num_slices;
  19731. desc.num_mipmaps = img->cmn.num_mipmaps;
  19732. desc.usage = img->cmn.usage;
  19733. desc.pixel_format = img->cmn.pixel_format;
  19734. desc.sample_count = img->cmn.sample_count;
  19735. }
  19736. return desc;
  19737. }
  19738. SOKOL_API_IMPL sg_image_type sg_query_image_type(sg_image img_id) {
  19739. SOKOL_ASSERT(_sg.valid);
  19740. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19741. if (img) {
  19742. return img->cmn.type;
  19743. }
  19744. return _SG_IMAGETYPE_DEFAULT;
  19745. }
  19746. SOKOL_API_IMPL int sg_query_image_width(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.width;
  19751. }
  19752. return 0;
  19753. }
  19754. SOKOL_API_IMPL int sg_query_image_height(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.height;
  19759. }
  19760. return 0;
  19761. }
  19762. SOKOL_API_IMPL int sg_query_image_num_slices(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.num_slices;
  19767. }
  19768. return 0;
  19769. }
  19770. SOKOL_API_IMPL int sg_query_image_num_mipmaps(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_mipmaps;
  19775. }
  19776. return 0;
  19777. }
  19778. SOKOL_API_IMPL sg_pixel_format sg_query_image_pixelformat(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.pixel_format;
  19783. }
  19784. return _SG_PIXELFORMAT_DEFAULT;
  19785. }
  19786. SOKOL_API_IMPL sg_image_usage sg_query_image_usage(sg_image img_id) {
  19787. SOKOL_ASSERT(_sg.valid);
  19788. sg_image_usage usg;
  19789. _sg_clear(&usg, sizeof(usg));
  19790. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19791. if (img) {
  19792. usg = img->cmn.usage;
  19793. }
  19794. return usg;
  19795. }
  19796. SOKOL_API_IMPL int sg_query_image_sample_count(sg_image img_id) {
  19797. SOKOL_ASSERT(_sg.valid);
  19798. SOKOL_ASSERT(_sg.valid);
  19799. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19800. if (img) {
  19801. return img->cmn.sample_count;
  19802. }
  19803. return 0;
  19804. }
  19805. SOKOL_API_IMPL sg_sampler_desc sg_query_sampler_desc(sg_sampler smp_id) {
  19806. SOKOL_ASSERT(_sg.valid);
  19807. sg_sampler_desc desc;
  19808. _sg_clear(&desc, sizeof(desc));
  19809. const _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  19810. if (smp) {
  19811. desc.min_filter = smp->cmn.min_filter;
  19812. desc.mag_filter = smp->cmn.mag_filter;
  19813. desc.mipmap_filter = smp->cmn.mipmap_filter;
  19814. desc.wrap_u = smp->cmn.wrap_u;
  19815. desc.wrap_v = smp->cmn.wrap_v;
  19816. desc.wrap_w = smp->cmn.wrap_w;
  19817. desc.min_lod = smp->cmn.min_lod;
  19818. desc.max_lod = smp->cmn.max_lod;
  19819. desc.border_color = smp->cmn.border_color;
  19820. desc.compare = smp->cmn.compare;
  19821. desc.max_anisotropy = smp->cmn.max_anisotropy;
  19822. }
  19823. return desc;
  19824. }
  19825. SOKOL_API_IMPL sg_shader_desc sg_query_shader_desc(sg_shader shd_id) {
  19826. SOKOL_ASSERT(_sg.valid);
  19827. sg_shader_desc desc;
  19828. _sg_clear(&desc, sizeof(desc));
  19829. const _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  19830. if (shd) {
  19831. for (size_t ub_idx = 0; ub_idx < SG_MAX_UNIFORMBLOCK_BINDSLOTS; ub_idx++) {
  19832. sg_shader_uniform_block* ub_desc = &desc.uniform_blocks[ub_idx];
  19833. const _sg_shader_uniform_block_t* ub = &shd->cmn.uniform_blocks[ub_idx];
  19834. ub_desc->stage = ub->stage;
  19835. ub_desc->size = ub->size;
  19836. }
  19837. for (size_t sbuf_idx = 0; sbuf_idx < SG_MAX_STORAGEBUFFER_BINDSLOTS; sbuf_idx++) {
  19838. sg_shader_storage_buffer* sbuf_desc = &desc.storage_buffers[sbuf_idx];
  19839. const _sg_shader_storage_buffer_t* sbuf = &shd->cmn.storage_buffers[sbuf_idx];
  19840. sbuf_desc->stage = sbuf->stage;
  19841. sbuf_desc->readonly = sbuf->readonly;
  19842. }
  19843. for (size_t simg_idx = 0; simg_idx < SG_MAX_STORAGE_ATTACHMENTS; simg_idx++) {
  19844. sg_shader_storage_image* simg_desc = &desc.storage_images[simg_idx];
  19845. const _sg_shader_storage_image_t* simg = &shd->cmn.storage_images[simg_idx];
  19846. simg_desc->stage = simg->stage;
  19847. simg_desc->access_format = simg->access_format;
  19848. simg_desc->image_type = simg->image_type;
  19849. simg_desc->writeonly = simg->writeonly;
  19850. }
  19851. for (size_t img_idx = 0; img_idx < SG_MAX_IMAGE_BINDSLOTS; img_idx++) {
  19852. sg_shader_image* img_desc = &desc.images[img_idx];
  19853. const _sg_shader_image_t* img = &shd->cmn.images[img_idx];
  19854. img_desc->stage = img->stage;
  19855. img_desc->image_type = img->image_type;
  19856. img_desc->sample_type = img->sample_type;
  19857. img_desc->multisampled = img->multisampled;
  19858. }
  19859. for (size_t smp_idx = 0; smp_idx < SG_MAX_SAMPLER_BINDSLOTS; smp_idx++) {
  19860. sg_shader_sampler* smp_desc = &desc.samplers[smp_idx];
  19861. const _sg_shader_sampler_t* smp = &shd->cmn.samplers[smp_idx];
  19862. smp_desc->stage = smp->stage;
  19863. smp_desc->sampler_type = smp->sampler_type;
  19864. }
  19865. for (size_t img_smp_idx = 0; img_smp_idx < SG_MAX_IMAGE_SAMPLER_PAIRS; img_smp_idx++) {
  19866. sg_shader_image_sampler_pair* img_smp_desc = &desc.image_sampler_pairs[img_smp_idx];
  19867. const _sg_shader_image_sampler_t* img_smp = &shd->cmn.image_samplers[img_smp_idx];
  19868. img_smp_desc->stage = img_smp->stage;
  19869. img_smp_desc->image_slot = img_smp->image_slot;
  19870. img_smp_desc->sampler_slot = img_smp->sampler_slot;
  19871. }
  19872. }
  19873. return desc;
  19874. }
  19875. SOKOL_API_IMPL sg_pipeline_desc sg_query_pipeline_desc(sg_pipeline pip_id) {
  19876. SOKOL_ASSERT(_sg.valid);
  19877. sg_pipeline_desc desc;
  19878. _sg_clear(&desc, sizeof(desc));
  19879. const _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  19880. if (pip) {
  19881. desc.compute = pip->cmn.is_compute;
  19882. desc.shader.id = pip->cmn.shader.sref.id;
  19883. desc.layout = pip->cmn.layout;
  19884. desc.depth = pip->cmn.depth;
  19885. desc.stencil = pip->cmn.stencil;
  19886. desc.color_count = pip->cmn.color_count;
  19887. for (int i = 0; i < pip->cmn.color_count; i++) {
  19888. desc.colors[i] = pip->cmn.colors[i];
  19889. }
  19890. desc.primitive_type = pip->cmn.primitive_type;
  19891. desc.index_type = pip->cmn.index_type;
  19892. desc.cull_mode = pip->cmn.cull_mode;
  19893. desc.face_winding = pip->cmn.face_winding;
  19894. desc.sample_count = pip->cmn.sample_count;
  19895. desc.blend_color = pip->cmn.blend_color;
  19896. desc.alpha_to_coverage_enabled = pip->cmn.alpha_to_coverage_enabled;
  19897. }
  19898. return desc;
  19899. }
  19900. SOKOL_API_IMPL sg_attachments_desc sg_query_attachments_desc(sg_attachments atts_id) {
  19901. SOKOL_ASSERT(_sg.valid);
  19902. sg_attachments_desc desc;
  19903. _sg_clear(&desc, sizeof(desc));
  19904. const _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  19905. if (atts) {
  19906. for (int i = 0; i < atts->cmn.num_colors; i++) {
  19907. desc.colors[i].image.id = atts->cmn.colors[i].image.sref.id;
  19908. desc.colors[i].mip_level = atts->cmn.colors[i].mip_level;
  19909. desc.colors[i].slice = atts->cmn.colors[i].slice;
  19910. }
  19911. desc.depth_stencil.image.id = atts->cmn.depth_stencil.image.sref.id;
  19912. desc.depth_stencil.mip_level = atts->cmn.depth_stencil.mip_level;
  19913. desc.depth_stencil.slice = atts->cmn.depth_stencil.slice;
  19914. }
  19915. return desc;
  19916. }
  19917. SOKOL_API_IMPL sg_buffer_desc sg_query_buffer_defaults(const sg_buffer_desc* desc) {
  19918. SOKOL_ASSERT(_sg.valid && desc);
  19919. return _sg_buffer_desc_defaults(desc);
  19920. }
  19921. SOKOL_API_IMPL sg_image_desc sg_query_image_defaults(const sg_image_desc* desc) {
  19922. SOKOL_ASSERT(_sg.valid && desc);
  19923. return _sg_image_desc_defaults(desc);
  19924. }
  19925. SOKOL_API_IMPL sg_sampler_desc sg_query_sampler_defaults(const sg_sampler_desc* desc) {
  19926. SOKOL_ASSERT(_sg.valid && desc);
  19927. return _sg_sampler_desc_defaults(desc);
  19928. }
  19929. SOKOL_API_IMPL sg_shader_desc sg_query_shader_defaults(const sg_shader_desc* desc) {
  19930. SOKOL_ASSERT(_sg.valid && desc);
  19931. return _sg_shader_desc_defaults(desc);
  19932. }
  19933. SOKOL_API_IMPL sg_pipeline_desc sg_query_pipeline_defaults(const sg_pipeline_desc* desc) {
  19934. SOKOL_ASSERT(_sg.valid && desc);
  19935. return _sg_pipeline_desc_defaults(desc);
  19936. }
  19937. SOKOL_API_IMPL sg_attachments_desc sg_query_attachments_defaults(const sg_attachments_desc* desc) {
  19938. SOKOL_ASSERT(_sg.valid && desc);
  19939. return _sg_attachments_desc_defaults(desc);
  19940. }
  19941. SOKOL_API_IMPL const void* sg_d3d11_device(void) {
  19942. #if defined(SOKOL_D3D11)
  19943. return (const void*) _sg.d3d11.dev;
  19944. #else
  19945. return 0;
  19946. #endif
  19947. }
  19948. SOKOL_API_IMPL const void* sg_d3d11_device_context(void) {
  19949. #if defined(SOKOL_D3D11)
  19950. return (const void*) _sg.d3d11.ctx;
  19951. #else
  19952. return 0;
  19953. #endif
  19954. }
  19955. SOKOL_API_IMPL sg_d3d11_buffer_info sg_d3d11_query_buffer_info(sg_buffer buf_id) {
  19956. SOKOL_ASSERT(_sg.valid);
  19957. sg_d3d11_buffer_info res;
  19958. _sg_clear(&res, sizeof(res));
  19959. #if defined(SOKOL_D3D11)
  19960. const _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  19961. if (buf) {
  19962. res.buf = (const void*) buf->d3d11.buf;
  19963. }
  19964. #else
  19965. _SOKOL_UNUSED(buf_id);
  19966. #endif
  19967. return res;
  19968. }
  19969. SOKOL_API_IMPL sg_d3d11_image_info sg_d3d11_query_image_info(sg_image img_id) {
  19970. SOKOL_ASSERT(_sg.valid);
  19971. sg_d3d11_image_info res;
  19972. _sg_clear(&res, sizeof(res));
  19973. #if defined(SOKOL_D3D11)
  19974. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  19975. if (img) {
  19976. res.tex2d = (const void*) img->d3d11.tex2d;
  19977. res.tex3d = (const void*) img->d3d11.tex3d;
  19978. res.res = (const void*) img->d3d11.res;
  19979. res.srv = (const void*) img->d3d11.srv;
  19980. }
  19981. #else
  19982. _SOKOL_UNUSED(img_id);
  19983. #endif
  19984. return res;
  19985. }
  19986. SOKOL_API_IMPL sg_d3d11_sampler_info sg_d3d11_query_sampler_info(sg_sampler smp_id) {
  19987. SOKOL_ASSERT(_sg.valid);
  19988. sg_d3d11_sampler_info res;
  19989. _sg_clear(&res, sizeof(res));
  19990. #if defined(SOKOL_D3D11)
  19991. const _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  19992. if (smp) {
  19993. res.smp = (const void*) smp->d3d11.smp;
  19994. }
  19995. #else
  19996. _SOKOL_UNUSED(smp_id);
  19997. #endif
  19998. return res;
  19999. }
  20000. SOKOL_API_IMPL sg_d3d11_shader_info sg_d3d11_query_shader_info(sg_shader shd_id) {
  20001. SOKOL_ASSERT(_sg.valid);
  20002. sg_d3d11_shader_info res;
  20003. _sg_clear(&res, sizeof(res));
  20004. #if defined(SOKOL_D3D11)
  20005. const _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  20006. if (shd) {
  20007. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  20008. res.cbufs[i] = (const void*) shd->d3d11.all_cbufs[i];
  20009. }
  20010. res.vs = (const void*) shd->d3d11.vs;
  20011. res.fs = (const void*) shd->d3d11.fs;
  20012. }
  20013. #else
  20014. _SOKOL_UNUSED(shd_id);
  20015. #endif
  20016. return res;
  20017. }
  20018. SOKOL_API_IMPL sg_d3d11_pipeline_info sg_d3d11_query_pipeline_info(sg_pipeline pip_id) {
  20019. SOKOL_ASSERT(_sg.valid);
  20020. sg_d3d11_pipeline_info res;
  20021. _sg_clear(&res, sizeof(res));
  20022. #if defined(SOKOL_D3D11)
  20023. const _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  20024. if (pip) {
  20025. res.il = (const void*) pip->d3d11.il;
  20026. res.rs = (const void*) pip->d3d11.rs;
  20027. res.dss = (const void*) pip->d3d11.dss;
  20028. res.bs = (const void*) pip->d3d11.bs;
  20029. }
  20030. #else
  20031. _SOKOL_UNUSED(pip_id);
  20032. #endif
  20033. return res;
  20034. }
  20035. SOKOL_API_IMPL sg_d3d11_attachments_info sg_d3d11_query_attachments_info(sg_attachments atts_id) {
  20036. SOKOL_ASSERT(_sg.valid);
  20037. sg_d3d11_attachments_info res;
  20038. _sg_clear(&res, sizeof(res));
  20039. #if defined(SOKOL_D3D11)
  20040. const _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  20041. if (atts) {
  20042. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  20043. res.color_rtv[i] = (const void*) atts->d3d11.colors[i].view.rtv;
  20044. }
  20045. res.dsv = (const void*) atts->d3d11.depth_stencil.view.dsv;
  20046. }
  20047. #else
  20048. _SOKOL_UNUSED(atts_id);
  20049. #endif
  20050. return res;
  20051. }
  20052. SOKOL_API_IMPL const void* sg_mtl_device(void) {
  20053. #if defined(SOKOL_METAL)
  20054. if (nil != _sg.mtl.device) {
  20055. return (__bridge const void*) _sg.mtl.device;
  20056. } else {
  20057. return 0;
  20058. }
  20059. #else
  20060. return 0;
  20061. #endif
  20062. }
  20063. SOKOL_API_IMPL const void* sg_mtl_render_command_encoder(void) {
  20064. #if defined(SOKOL_METAL)
  20065. if (nil != _sg.mtl.render_cmd_encoder) {
  20066. return (__bridge const void*) _sg.mtl.render_cmd_encoder;
  20067. } else {
  20068. return 0;
  20069. }
  20070. #else
  20071. return 0;
  20072. #endif
  20073. }
  20074. SOKOL_API_IMPL const void* sg_mtl_compute_command_encoder(void) {
  20075. #if defined(SOKOL_METAL)
  20076. if (nil != _sg.mtl.compute_cmd_encoder) {
  20077. return (__bridge const void*) _sg.mtl.compute_cmd_encoder;
  20078. } else {
  20079. return 0;
  20080. }
  20081. #else
  20082. return 0;
  20083. #endif
  20084. }
  20085. SOKOL_API_IMPL sg_mtl_buffer_info sg_mtl_query_buffer_info(sg_buffer buf_id) {
  20086. SOKOL_ASSERT(_sg.valid);
  20087. sg_mtl_buffer_info res;
  20088. _sg_clear(&res, sizeof(res));
  20089. #if defined(SOKOL_METAL)
  20090. const _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  20091. if (buf) {
  20092. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  20093. if (buf->mtl.buf[i] != 0) {
  20094. res.buf[i] = (__bridge void*) _sg_mtl_id(buf->mtl.buf[i]);
  20095. }
  20096. }
  20097. res.active_slot = buf->cmn.active_slot;
  20098. }
  20099. #else
  20100. _SOKOL_UNUSED(buf_id);
  20101. #endif
  20102. return res;
  20103. }
  20104. SOKOL_API_IMPL sg_mtl_image_info sg_mtl_query_image_info(sg_image img_id) {
  20105. SOKOL_ASSERT(_sg.valid);
  20106. sg_mtl_image_info res;
  20107. _sg_clear(&res, sizeof(res));
  20108. #if defined(SOKOL_METAL)
  20109. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  20110. if (img) {
  20111. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  20112. if (img->mtl.tex[i] != 0) {
  20113. res.tex[i] = (__bridge void*) _sg_mtl_id(img->mtl.tex[i]);
  20114. }
  20115. }
  20116. res.active_slot = img->cmn.active_slot;
  20117. }
  20118. #else
  20119. _SOKOL_UNUSED(img_id);
  20120. #endif
  20121. return res;
  20122. }
  20123. SOKOL_API_IMPL sg_mtl_sampler_info sg_mtl_query_sampler_info(sg_sampler smp_id) {
  20124. SOKOL_ASSERT(_sg.valid);
  20125. sg_mtl_sampler_info res;
  20126. _sg_clear(&res, sizeof(res));
  20127. #if defined(SOKOL_METAL)
  20128. const _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  20129. if (smp) {
  20130. if (smp->mtl.sampler_state != 0) {
  20131. res.smp = (__bridge void*) _sg_mtl_id(smp->mtl.sampler_state);
  20132. }
  20133. }
  20134. #else
  20135. _SOKOL_UNUSED(smp_id);
  20136. #endif
  20137. return res;
  20138. }
  20139. SOKOL_API_IMPL sg_mtl_shader_info sg_mtl_query_shader_info(sg_shader shd_id) {
  20140. SOKOL_ASSERT(_sg.valid);
  20141. sg_mtl_shader_info res;
  20142. _sg_clear(&res, sizeof(res));
  20143. #if defined(SOKOL_METAL)
  20144. const _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  20145. if (shd) {
  20146. const int vertex_lib = shd->mtl.vertex_func.mtl_lib;
  20147. const int vertex_func = shd->mtl.vertex_func.mtl_func;
  20148. const int fragment_lib = shd->mtl.fragment_func.mtl_lib;
  20149. const int fragment_func = shd->mtl.fragment_func.mtl_func;
  20150. if (vertex_lib != 0) {
  20151. res.vertex_lib = (__bridge void*) _sg_mtl_id(vertex_lib);
  20152. }
  20153. if (fragment_lib != 0) {
  20154. res.fragment_lib = (__bridge void*) _sg_mtl_id(fragment_lib);
  20155. }
  20156. if (vertex_func != 0) {
  20157. res.vertex_func = (__bridge void*) _sg_mtl_id(vertex_func);
  20158. }
  20159. if (fragment_func != 0) {
  20160. res.fragment_func = (__bridge void*) _sg_mtl_id(fragment_func);
  20161. }
  20162. }
  20163. #else
  20164. _SOKOL_UNUSED(shd_id);
  20165. #endif
  20166. return res;
  20167. }
  20168. SOKOL_API_IMPL sg_mtl_pipeline_info sg_mtl_query_pipeline_info(sg_pipeline pip_id) {
  20169. SOKOL_ASSERT(_sg.valid);
  20170. sg_mtl_pipeline_info res;
  20171. _sg_clear(&res, sizeof(res));
  20172. #if defined(SOKOL_METAL)
  20173. const _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  20174. if (pip) {
  20175. if (pip->mtl.rps != 0) {
  20176. res.rps = (__bridge void*) _sg_mtl_id(pip->mtl.rps);
  20177. }
  20178. if (pip->mtl.dss != 0) {
  20179. res.dss = (__bridge void*) _sg_mtl_id(pip->mtl.dss);
  20180. }
  20181. }
  20182. #else
  20183. _SOKOL_UNUSED(pip_id);
  20184. #endif
  20185. return res;
  20186. }
  20187. SOKOL_API_IMPL const void* sg_wgpu_device(void) {
  20188. #if defined(SOKOL_WGPU)
  20189. return (const void*) _sg.wgpu.dev;
  20190. #else
  20191. return 0;
  20192. #endif
  20193. }
  20194. SOKOL_API_IMPL const void* sg_wgpu_queue(void) {
  20195. #if defined(SOKOL_WGPU)
  20196. return (const void*) _sg.wgpu.queue;
  20197. #else
  20198. return 0;
  20199. #endif
  20200. }
  20201. SOKOL_API_IMPL const void* sg_wgpu_command_encoder(void) {
  20202. #if defined(SOKOL_WGPU)
  20203. return (const void*) _sg.wgpu.cmd_enc;
  20204. #else
  20205. return 0;
  20206. #endif
  20207. }
  20208. SOKOL_API_IMPL const void* sg_wgpu_render_pass_encoder(void) {
  20209. #if defined(SOKOL_WGPU)
  20210. return (const void*) _sg.wgpu.rpass_enc;
  20211. #else
  20212. return 0;
  20213. #endif
  20214. }
  20215. SOKOL_API_IMPL const void* sg_wgpu_compute_pass_encoder(void) {
  20216. #if defined(SOKOL_WGPU)
  20217. return (const void*) _sg.wgpu.cpass_enc;
  20218. #else
  20219. return 0;
  20220. #endif
  20221. }
  20222. SOKOL_API_IMPL sg_wgpu_buffer_info sg_wgpu_query_buffer_info(sg_buffer buf_id) {
  20223. SOKOL_ASSERT(_sg.valid);
  20224. sg_wgpu_buffer_info res;
  20225. _sg_clear(&res, sizeof(res));
  20226. #if defined(SOKOL_WGPU)
  20227. const _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  20228. if (buf) {
  20229. res.buf = (const void*) buf->wgpu.buf;
  20230. }
  20231. #else
  20232. _SOKOL_UNUSED(buf_id);
  20233. #endif
  20234. return res;
  20235. }
  20236. SOKOL_API_IMPL sg_wgpu_image_info sg_wgpu_query_image_info(sg_image img_id) {
  20237. SOKOL_ASSERT(_sg.valid);
  20238. sg_wgpu_image_info res;
  20239. _sg_clear(&res, sizeof(res));
  20240. #if defined(SOKOL_WGPU)
  20241. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  20242. if (img) {
  20243. res.tex = (const void*) img->wgpu.tex;
  20244. res.view = (const void*) img->wgpu.view;
  20245. }
  20246. #else
  20247. _SOKOL_UNUSED(img_id);
  20248. #endif
  20249. return res;
  20250. }
  20251. SOKOL_API_IMPL sg_wgpu_sampler_info sg_wgpu_query_sampler_info(sg_sampler smp_id) {
  20252. SOKOL_ASSERT(_sg.valid);
  20253. sg_wgpu_sampler_info res;
  20254. _sg_clear(&res, sizeof(res));
  20255. #if defined(SOKOL_WGPU)
  20256. const _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  20257. if (smp) {
  20258. res.smp = (const void*) smp->wgpu.smp;
  20259. }
  20260. #else
  20261. _SOKOL_UNUSED(smp_id);
  20262. #endif
  20263. return res;
  20264. }
  20265. SOKOL_API_IMPL sg_wgpu_shader_info sg_wgpu_query_shader_info(sg_shader shd_id) {
  20266. SOKOL_ASSERT(_sg.valid);
  20267. sg_wgpu_shader_info res;
  20268. _sg_clear(&res, sizeof(res));
  20269. #if defined(SOKOL_WGPU)
  20270. const _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  20271. if (shd) {
  20272. res.vs_mod = (const void*) shd->wgpu.vertex_func.module;
  20273. res.fs_mod = (const void*) shd->wgpu.fragment_func.module;
  20274. res.bgl = (const void*) shd->wgpu.bgl_img_smp_sbuf;
  20275. }
  20276. #else
  20277. _SOKOL_UNUSED(shd_id);
  20278. #endif
  20279. return res;
  20280. }
  20281. SOKOL_API_IMPL sg_wgpu_pipeline_info sg_wgpu_query_pipeline_info(sg_pipeline pip_id) {
  20282. SOKOL_ASSERT(_sg.valid);
  20283. sg_wgpu_pipeline_info res;
  20284. _sg_clear(&res, sizeof(res));
  20285. #if defined(SOKOL_WGPU)
  20286. const _sg_pipeline_t* pip = _sg_lookup_pipeline(pip_id.id);
  20287. if (pip) {
  20288. res.render_pipeline = (const void*) pip->wgpu.rpip;
  20289. res.compute_pipeline = (const void*) pip->wgpu.cpip;
  20290. }
  20291. #else
  20292. _SOKOL_UNUSED(pip_id);
  20293. #endif
  20294. return res;
  20295. }
  20296. SOKOL_API_IMPL sg_wgpu_attachments_info sg_wgpu_query_attachments_info(sg_attachments atts_id) {
  20297. SOKOL_ASSERT(_sg.valid);
  20298. sg_wgpu_attachments_info res;
  20299. _sg_clear(&res, sizeof(res));
  20300. #if defined(SOKOL_WGPU)
  20301. const _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  20302. if (atts) {
  20303. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  20304. res.color_view[i] = (const void*) atts->wgpu.colors[i].view;
  20305. res.resolve_view[i] = (const void*) atts->wgpu.resolves[i].view;
  20306. }
  20307. res.ds_view = (const void*) atts->wgpu.depth_stencil.view;
  20308. }
  20309. #else
  20310. _SOKOL_UNUSED(atts_id);
  20311. #endif
  20312. return res;
  20313. }
  20314. SOKOL_API_IMPL sg_gl_buffer_info sg_gl_query_buffer_info(sg_buffer buf_id) {
  20315. SOKOL_ASSERT(_sg.valid);
  20316. sg_gl_buffer_info res;
  20317. _sg_clear(&res, sizeof(res));
  20318. #if defined(_SOKOL_ANY_GL)
  20319. const _sg_buffer_t* buf = _sg_lookup_buffer(buf_id.id);
  20320. if (buf) {
  20321. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  20322. res.buf[i] = buf->gl.buf[i];
  20323. }
  20324. res.active_slot = buf->cmn.active_slot;
  20325. }
  20326. #else
  20327. _SOKOL_UNUSED(buf_id);
  20328. #endif
  20329. return res;
  20330. }
  20331. SOKOL_API_IMPL sg_gl_image_info sg_gl_query_image_info(sg_image img_id) {
  20332. SOKOL_ASSERT(_sg.valid);
  20333. sg_gl_image_info res;
  20334. _sg_clear(&res, sizeof(res));
  20335. #if defined(_SOKOL_ANY_GL)
  20336. const _sg_image_t* img = _sg_lookup_image(img_id.id);
  20337. if (img) {
  20338. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  20339. res.tex[i] = img->gl.tex[i];
  20340. }
  20341. res.tex_target = img->gl.target;
  20342. res.msaa_render_buffer = img->gl.msaa_render_buffer;
  20343. res.active_slot = img->cmn.active_slot;
  20344. }
  20345. #else
  20346. _SOKOL_UNUSED(img_id);
  20347. #endif
  20348. return res;
  20349. }
  20350. SOKOL_API_IMPL sg_gl_sampler_info sg_gl_query_sampler_info(sg_sampler smp_id) {
  20351. SOKOL_ASSERT(_sg.valid);
  20352. sg_gl_sampler_info res;
  20353. _sg_clear(&res, sizeof(res));
  20354. #if defined(_SOKOL_ANY_GL)
  20355. const _sg_sampler_t* smp = _sg_lookup_sampler(smp_id.id);
  20356. if (smp) {
  20357. res.smp = smp->gl.smp;
  20358. }
  20359. #else
  20360. _SOKOL_UNUSED(smp_id);
  20361. #endif
  20362. return res;
  20363. }
  20364. SOKOL_API_IMPL sg_gl_shader_info sg_gl_query_shader_info(sg_shader shd_id) {
  20365. SOKOL_ASSERT(_sg.valid);
  20366. sg_gl_shader_info res;
  20367. _sg_clear(&res, sizeof(res));
  20368. #if defined(_SOKOL_ANY_GL)
  20369. const _sg_shader_t* shd = _sg_lookup_shader(shd_id.id);
  20370. if (shd) {
  20371. res.prog = shd->gl.prog;
  20372. }
  20373. #else
  20374. _SOKOL_UNUSED(shd_id);
  20375. #endif
  20376. return res;
  20377. }
  20378. SOKOL_API_IMPL sg_gl_attachments_info sg_gl_query_attachments_info(sg_attachments atts_id) {
  20379. SOKOL_ASSERT(_sg.valid);
  20380. sg_gl_attachments_info res;
  20381. _sg_clear(&res, sizeof(res));
  20382. #if defined(_SOKOL_ANY_GL)
  20383. const _sg_attachments_t* atts = _sg_lookup_attachments(atts_id.id);
  20384. if (atts) {
  20385. res.framebuffer = atts->gl.fb;
  20386. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  20387. res.msaa_resolve_framebuffer[i] = atts->gl.msaa_resolve_framebuffer[i];
  20388. }
  20389. }
  20390. #else
  20391. _SOKOL_UNUSED(atts_id);
  20392. #endif
  20393. return res;
  20394. }
  20395. #ifdef _MSC_VER
  20396. #pragma warning(pop)
  20397. #endif
  20398. #endif // SOKOL_GFX_IMPL