gltf_document.cpp 257 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175
  1. /**************************************************************************/
  2. /* gltf_document.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "gltf_document.h"
  31. #include "extensions/gltf_spec_gloss.h"
  32. #include "gltf_state.h"
  33. #include "skin_tool.h"
  34. #include "core/config/project_settings.h"
  35. #include "core/crypto/crypto_core.h"
  36. #include "core/io/config_file.h"
  37. #include "core/io/dir_access.h"
  38. #include "core/io/file_access.h"
  39. #include "core/io/file_access_memory.h"
  40. #include "core/io/json.h"
  41. #include "core/io/stream_peer.h"
  42. #include "core/object/object_id.h"
  43. #include "core/version.h"
  44. #include "scene/3d/bone_attachment_3d.h"
  45. #include "scene/3d/camera_3d.h"
  46. #include "scene/3d/importer_mesh_instance_3d.h"
  47. #include "scene/3d/light_3d.h"
  48. #include "scene/3d/mesh_instance_3d.h"
  49. #include "scene/3d/multimesh_instance_3d.h"
  50. #include "scene/resources/3d/skin.h"
  51. #include "scene/resources/image_texture.h"
  52. #include "scene/resources/portable_compressed_texture.h"
  53. #include "scene/resources/surface_tool.h"
  54. #ifdef TOOLS_ENABLED
  55. #include "editor/editor_file_system.h"
  56. #endif
  57. // FIXME: Hardcoded to avoid editor dependency.
  58. #define GLTF_IMPORT_GENERATE_TANGENT_ARRAYS 8
  59. #define GLTF_IMPORT_USE_NAMED_SKIN_BINDS 16
  60. #define GLTF_IMPORT_DISCARD_MESHES_AND_MATERIALS 32
  61. #define GLTF_IMPORT_FORCE_DISABLE_MESH_COMPRESSION 64
  62. #include <stdio.h>
  63. #include <stdlib.h>
  64. #include <cstdint>
  65. static Ref<ImporterMesh> _mesh_to_importer_mesh(Ref<Mesh> p_mesh) {
  66. Ref<ImporterMesh> importer_mesh;
  67. importer_mesh.instantiate();
  68. if (p_mesh.is_null()) {
  69. return importer_mesh;
  70. }
  71. Ref<ArrayMesh> array_mesh = p_mesh;
  72. if (p_mesh->get_blend_shape_count()) {
  73. ArrayMesh::BlendShapeMode shape_mode = ArrayMesh::BLEND_SHAPE_MODE_NORMALIZED;
  74. if (array_mesh.is_valid()) {
  75. shape_mode = array_mesh->get_blend_shape_mode();
  76. }
  77. importer_mesh->set_blend_shape_mode(shape_mode);
  78. for (int morph_i = 0; morph_i < p_mesh->get_blend_shape_count(); morph_i++) {
  79. importer_mesh->add_blend_shape(p_mesh->get_blend_shape_name(morph_i));
  80. }
  81. }
  82. for (int32_t surface_i = 0; surface_i < p_mesh->get_surface_count(); surface_i++) {
  83. Array array = p_mesh->surface_get_arrays(surface_i);
  84. Ref<Material> mat = p_mesh->surface_get_material(surface_i);
  85. String mat_name;
  86. if (mat.is_valid()) {
  87. mat_name = mat->get_name();
  88. } else {
  89. // Assign default material when no material is assigned.
  90. mat = Ref<StandardMaterial3D>(memnew(StandardMaterial3D));
  91. }
  92. importer_mesh->add_surface(p_mesh->surface_get_primitive_type(surface_i),
  93. array, p_mesh->surface_get_blend_shape_arrays(surface_i), p_mesh->surface_get_lods(surface_i), mat,
  94. mat_name, p_mesh->surface_get_format(surface_i));
  95. }
  96. return importer_mesh;
  97. }
  98. Error GLTFDocument::_serialize(Ref<GLTFState> p_state) {
  99. if (!p_state->buffers.size()) {
  100. p_state->buffers.push_back(Vector<uint8_t>());
  101. }
  102. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  103. ERR_CONTINUE(ext.is_null());
  104. Error err = ext->export_preserialize(p_state);
  105. ERR_CONTINUE(err != OK);
  106. }
  107. /* STEP CONVERT MESH INSTANCES */
  108. _convert_mesh_instances(p_state);
  109. /* STEP SERIALIZE CAMERAS */
  110. Error err = _serialize_cameras(p_state);
  111. if (err != OK) {
  112. return Error::FAILED;
  113. }
  114. /* STEP 3 CREATE SKINS */
  115. err = _serialize_skins(p_state);
  116. if (err != OK) {
  117. return Error::FAILED;
  118. }
  119. /* STEP SERIALIZE MESHES (we have enough info now) */
  120. err = _serialize_meshes(p_state);
  121. if (err != OK) {
  122. return Error::FAILED;
  123. }
  124. /* STEP SERIALIZE TEXTURES */
  125. err = _serialize_materials(p_state);
  126. if (err != OK) {
  127. return Error::FAILED;
  128. }
  129. /* STEP SERIALIZE TEXTURE SAMPLERS */
  130. err = _serialize_texture_samplers(p_state);
  131. if (err != OK) {
  132. return Error::FAILED;
  133. }
  134. /* STEP SERIALIZE ANIMATIONS */
  135. err = _serialize_animations(p_state);
  136. if (err != OK) {
  137. return Error::FAILED;
  138. }
  139. /* STEP SERIALIZE ACCESSORS */
  140. err = _encode_accessors(p_state);
  141. if (err != OK) {
  142. return Error::FAILED;
  143. }
  144. /* STEP SERIALIZE IMAGES */
  145. err = _serialize_images(p_state);
  146. if (err != OK) {
  147. return Error::FAILED;
  148. }
  149. /* STEP SERIALIZE TEXTURES */
  150. err = _serialize_textures(p_state);
  151. if (err != OK) {
  152. return Error::FAILED;
  153. }
  154. for (GLTFBufferViewIndex i = 0; i < p_state->buffer_views.size(); i++) {
  155. p_state->buffer_views.write[i]->buffer = 0;
  156. }
  157. /* STEP SERIALIZE BUFFER VIEWS */
  158. err = _encode_buffer_views(p_state);
  159. if (err != OK) {
  160. return Error::FAILED;
  161. }
  162. /* STEP SERIALIZE NODES */
  163. err = _serialize_nodes(p_state);
  164. if (err != OK) {
  165. return Error::FAILED;
  166. }
  167. /* STEP SERIALIZE SCENE */
  168. err = _serialize_scenes(p_state);
  169. if (err != OK) {
  170. return Error::FAILED;
  171. }
  172. /* STEP SERIALIZE LIGHTS */
  173. err = _serialize_lights(p_state);
  174. if (err != OK) {
  175. return Error::FAILED;
  176. }
  177. /* STEP SERIALIZE EXTENSIONS */
  178. err = _serialize_gltf_extensions(p_state);
  179. if (err != OK) {
  180. return Error::FAILED;
  181. }
  182. /* STEP SERIALIZE VERSION */
  183. err = _serialize_asset_header(p_state);
  184. if (err != OK) {
  185. return Error::FAILED;
  186. }
  187. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  188. ERR_CONTINUE(ext.is_null());
  189. err = ext->export_post(p_state);
  190. ERR_FAIL_COND_V(err != OK, err);
  191. }
  192. return OK;
  193. }
  194. Error GLTFDocument::_serialize_gltf_extensions(Ref<GLTFState> p_state) const {
  195. Vector<String> extensions_used = p_state->extensions_used;
  196. Vector<String> extensions_required = p_state->extensions_required;
  197. if (!p_state->lights.is_empty()) {
  198. extensions_used.push_back("KHR_lights_punctual");
  199. }
  200. if (p_state->use_khr_texture_transform) {
  201. extensions_used.push_back("KHR_texture_transform");
  202. extensions_required.push_back("KHR_texture_transform");
  203. }
  204. if (!extensions_used.is_empty()) {
  205. extensions_used.sort();
  206. p_state->json["extensionsUsed"] = extensions_used;
  207. }
  208. if (!extensions_required.is_empty()) {
  209. extensions_required.sort();
  210. p_state->json["extensionsRequired"] = extensions_required;
  211. }
  212. return OK;
  213. }
  214. Error GLTFDocument::_serialize_scenes(Ref<GLTFState> p_state) {
  215. ERR_FAIL_COND_V_MSG(p_state->root_nodes.is_empty(), ERR_INVALID_DATA, "GLTF export: The scene must have at least one root node.");
  216. // Godot only supports one scene per glTF file.
  217. Array scenes;
  218. Dictionary scene_dict;
  219. scenes.append(scene_dict);
  220. p_state->json["scenes"] = scenes;
  221. p_state->json["scene"] = 0;
  222. // Add nodes to the scene dict.
  223. scene_dict["nodes"] = p_state->root_nodes;
  224. if (!p_state->scene_name.is_empty()) {
  225. scene_dict["name"] = p_state->scene_name;
  226. }
  227. return OK;
  228. }
  229. Error GLTFDocument::_parse_json(const String &p_path, Ref<GLTFState> p_state) {
  230. Error err;
  231. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::READ, &err);
  232. if (file.is_null()) {
  233. return err;
  234. }
  235. Vector<uint8_t> array;
  236. array.resize(file->get_length());
  237. file->get_buffer(array.ptrw(), array.size());
  238. String text;
  239. text.parse_utf8((const char *)array.ptr(), array.size());
  240. JSON json;
  241. err = json.parse(text);
  242. if (err != OK) {
  243. _err_print_error("", p_path.utf8().get_data(), json.get_error_line(), json.get_error_message().utf8().get_data(), false, ERR_HANDLER_SCRIPT);
  244. return err;
  245. }
  246. p_state->json = json.get_data();
  247. return OK;
  248. }
  249. Error GLTFDocument::_parse_glb(Ref<FileAccess> p_file, Ref<GLTFState> p_state) {
  250. ERR_FAIL_NULL_V(p_file, ERR_INVALID_PARAMETER);
  251. ERR_FAIL_NULL_V(p_state, ERR_INVALID_PARAMETER);
  252. ERR_FAIL_COND_V(p_file->get_position() != 0, ERR_FILE_CANT_READ);
  253. uint32_t magic = p_file->get_32();
  254. ERR_FAIL_COND_V(magic != 0x46546C67, ERR_FILE_UNRECOGNIZED); //glTF
  255. p_file->get_32(); // version
  256. p_file->get_32(); // length
  257. uint32_t chunk_length = p_file->get_32();
  258. uint32_t chunk_type = p_file->get_32();
  259. ERR_FAIL_COND_V(chunk_type != 0x4E4F534A, ERR_PARSE_ERROR); //JSON
  260. Vector<uint8_t> json_data;
  261. json_data.resize(chunk_length);
  262. uint32_t len = p_file->get_buffer(json_data.ptrw(), chunk_length);
  263. ERR_FAIL_COND_V(len != chunk_length, ERR_FILE_CORRUPT);
  264. String text;
  265. text.parse_utf8((const char *)json_data.ptr(), json_data.size());
  266. JSON json;
  267. Error err = json.parse(text);
  268. if (err != OK) {
  269. _err_print_error("", "", json.get_error_line(), json.get_error_message().utf8().get_data(), false, ERR_HANDLER_SCRIPT);
  270. return err;
  271. }
  272. p_state->json = json.get_data();
  273. //data?
  274. chunk_length = p_file->get_32();
  275. chunk_type = p_file->get_32();
  276. if (p_file->eof_reached()) {
  277. return OK; //all good
  278. }
  279. ERR_FAIL_COND_V(chunk_type != 0x004E4942, ERR_PARSE_ERROR); //BIN
  280. p_state->glb_data.resize(chunk_length);
  281. len = p_file->get_buffer(p_state->glb_data.ptrw(), chunk_length);
  282. ERR_FAIL_COND_V(len != chunk_length, ERR_FILE_CORRUPT);
  283. return OK;
  284. }
  285. static Array _vec3_to_arr(const Vector3 &p_vec3) {
  286. Array array;
  287. array.resize(3);
  288. array[0] = p_vec3.x;
  289. array[1] = p_vec3.y;
  290. array[2] = p_vec3.z;
  291. return array;
  292. }
  293. static Vector3 _arr_to_vec3(const Array &p_array) {
  294. ERR_FAIL_COND_V(p_array.size() != 3, Vector3());
  295. return Vector3(p_array[0], p_array[1], p_array[2]);
  296. }
  297. static Array _quaternion_to_array(const Quaternion &p_quaternion) {
  298. Array array;
  299. array.resize(4);
  300. array[0] = p_quaternion.x;
  301. array[1] = p_quaternion.y;
  302. array[2] = p_quaternion.z;
  303. array[3] = p_quaternion.w;
  304. return array;
  305. }
  306. static Quaternion _arr_to_quaternion(const Array &p_array) {
  307. ERR_FAIL_COND_V(p_array.size() != 4, Quaternion());
  308. return Quaternion(p_array[0], p_array[1], p_array[2], p_array[3]);
  309. }
  310. static Transform3D _arr_to_xform(const Array &p_array) {
  311. ERR_FAIL_COND_V(p_array.size() != 16, Transform3D());
  312. Transform3D xform;
  313. xform.basis.set_column(Vector3::AXIS_X, Vector3(p_array[0], p_array[1], p_array[2]));
  314. xform.basis.set_column(Vector3::AXIS_Y, Vector3(p_array[4], p_array[5], p_array[6]));
  315. xform.basis.set_column(Vector3::AXIS_Z, Vector3(p_array[8], p_array[9], p_array[10]));
  316. xform.set_origin(Vector3(p_array[12], p_array[13], p_array[14]));
  317. return xform;
  318. }
  319. static Vector<real_t> _xform_to_array(const Transform3D p_transform) {
  320. Vector<real_t> array;
  321. array.resize(16);
  322. Vector3 axis_x = p_transform.get_basis().get_column(Vector3::AXIS_X);
  323. array.write[0] = axis_x.x;
  324. array.write[1] = axis_x.y;
  325. array.write[2] = axis_x.z;
  326. array.write[3] = 0.0f;
  327. Vector3 axis_y = p_transform.get_basis().get_column(Vector3::AXIS_Y);
  328. array.write[4] = axis_y.x;
  329. array.write[5] = axis_y.y;
  330. array.write[6] = axis_y.z;
  331. array.write[7] = 0.0f;
  332. Vector3 axis_z = p_transform.get_basis().get_column(Vector3::AXIS_Z);
  333. array.write[8] = axis_z.x;
  334. array.write[9] = axis_z.y;
  335. array.write[10] = axis_z.z;
  336. array.write[11] = 0.0f;
  337. Vector3 origin = p_transform.get_origin();
  338. array.write[12] = origin.x;
  339. array.write[13] = origin.y;
  340. array.write[14] = origin.z;
  341. array.write[15] = 1.0f;
  342. return array;
  343. }
  344. Error GLTFDocument::_serialize_nodes(Ref<GLTFState> p_state) {
  345. Array nodes;
  346. const int scene_node_count = p_state->scene_nodes.size();
  347. for (int i = 0; i < p_state->nodes.size(); i++) {
  348. Dictionary node;
  349. Ref<GLTFNode> gltf_node = p_state->nodes[i];
  350. Dictionary extensions;
  351. node["extensions"] = extensions;
  352. if (!gltf_node->get_name().is_empty()) {
  353. node["name"] = gltf_node->get_name();
  354. }
  355. if (gltf_node->camera != -1) {
  356. node["camera"] = gltf_node->camera;
  357. }
  358. if (gltf_node->light != -1) {
  359. Dictionary lights_punctual;
  360. extensions["KHR_lights_punctual"] = lights_punctual;
  361. lights_punctual["light"] = gltf_node->light;
  362. }
  363. if (gltf_node->mesh != -1) {
  364. node["mesh"] = gltf_node->mesh;
  365. }
  366. if (gltf_node->skin != -1) {
  367. node["skin"] = gltf_node->skin;
  368. }
  369. if (gltf_node->skeleton != -1 && gltf_node->skin < 0) {
  370. }
  371. if (gltf_node->transform.basis.is_orthogonal()) {
  372. // An orthogonal transform is decomposable into TRS, so prefer that.
  373. const Vector3 position = gltf_node->get_position();
  374. if (!position.is_zero_approx()) {
  375. node["translation"] = _vec3_to_arr(position);
  376. }
  377. const Quaternion rotation = gltf_node->get_rotation();
  378. if (!rotation.is_equal_approx(Quaternion())) {
  379. node["rotation"] = _quaternion_to_array(rotation);
  380. }
  381. const Vector3 scale = gltf_node->get_scale();
  382. if (!scale.is_equal_approx(Vector3(1.0f, 1.0f, 1.0f))) {
  383. node["scale"] = _vec3_to_arr(scale);
  384. }
  385. } else {
  386. node["matrix"] = _xform_to_array(gltf_node->transform);
  387. }
  388. if (gltf_node->children.size()) {
  389. Array children;
  390. for (int j = 0; j < gltf_node->children.size(); j++) {
  391. children.push_back(gltf_node->children[j]);
  392. }
  393. node["children"] = children;
  394. }
  395. Node *scene_node = nullptr;
  396. if (i < scene_node_count) {
  397. scene_node = p_state->scene_nodes[i];
  398. }
  399. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  400. ERR_CONTINUE(ext.is_null());
  401. Error err = ext->export_node(p_state, gltf_node, node, scene_node);
  402. ERR_CONTINUE(err != OK);
  403. }
  404. nodes.push_back(node);
  405. }
  406. p_state->json["nodes"] = nodes;
  407. return OK;
  408. }
  409. String GLTFDocument::_gen_unique_name(Ref<GLTFState> p_state, const String &p_name) {
  410. return _gen_unique_name_static(p_state->unique_names, p_name);
  411. }
  412. String GLTFDocument::_sanitize_animation_name(const String &p_name) {
  413. // Animations disallow the normal node invalid characters as well as "," and "["
  414. // (See animation/animation_player.cpp::add_animation)
  415. // TODO: Consider adding invalid_characters or a validate_animation_name to animation_player to mirror Node.
  416. String anim_name = p_name.validate_node_name();
  417. anim_name = anim_name.replace(",", "");
  418. anim_name = anim_name.replace("[", "");
  419. return anim_name;
  420. }
  421. String GLTFDocument::_gen_unique_animation_name(Ref<GLTFState> p_state, const String &p_name) {
  422. const String s_name = _sanitize_animation_name(p_name);
  423. String u_name;
  424. int index = 1;
  425. while (true) {
  426. u_name = s_name;
  427. if (index > 1) {
  428. u_name += itos(index);
  429. }
  430. if (!p_state->unique_animation_names.has(u_name)) {
  431. break;
  432. }
  433. index++;
  434. }
  435. p_state->unique_animation_names.insert(u_name);
  436. return u_name;
  437. }
  438. String GLTFDocument::_sanitize_bone_name(const String &p_name) {
  439. String bone_name = p_name;
  440. bone_name = bone_name.replace(":", "_");
  441. bone_name = bone_name.replace("/", "_");
  442. return bone_name;
  443. }
  444. String GLTFDocument::_gen_unique_bone_name(Ref<GLTFState> p_state, const GLTFSkeletonIndex p_skel_i, const String &p_name) {
  445. String s_name = _sanitize_bone_name(p_name);
  446. if (s_name.is_empty()) {
  447. s_name = "bone";
  448. }
  449. String u_name;
  450. int index = 1;
  451. while (true) {
  452. u_name = s_name;
  453. if (index > 1) {
  454. u_name += "_" + itos(index);
  455. }
  456. if (!p_state->skeletons[p_skel_i]->unique_names.has(u_name)) {
  457. break;
  458. }
  459. index++;
  460. }
  461. p_state->skeletons.write[p_skel_i]->unique_names.insert(u_name);
  462. return u_name;
  463. }
  464. Error GLTFDocument::_parse_scenes(Ref<GLTFState> p_state) {
  465. p_state->unique_names.insert("Skeleton3D"); // Reserve skeleton name.
  466. ERR_FAIL_COND_V(!p_state->json.has("scenes"), ERR_FILE_CORRUPT);
  467. const Array &scenes = p_state->json["scenes"];
  468. int loaded_scene = 0;
  469. if (p_state->json.has("scene")) {
  470. loaded_scene = p_state->json["scene"];
  471. } else {
  472. WARN_PRINT("The load-time scene is not defined in the glTF2 file. Picking the first scene.");
  473. }
  474. if (scenes.size()) {
  475. ERR_FAIL_COND_V(loaded_scene >= scenes.size(), ERR_FILE_CORRUPT);
  476. const Dictionary &scene_dict = scenes[loaded_scene];
  477. ERR_FAIL_COND_V(!scene_dict.has("nodes"), ERR_UNAVAILABLE);
  478. const Array &nodes = scene_dict["nodes"];
  479. for (int j = 0; j < nodes.size(); j++) {
  480. p_state->root_nodes.push_back(nodes[j]);
  481. }
  482. // Determine what to use for the scene name.
  483. if (scene_dict.has("name") && !String(scene_dict["name"]).is_empty() && !((String)scene_dict["name"]).begins_with("Scene")) {
  484. p_state->scene_name = scene_dict["name"];
  485. } else if (p_state->scene_name.is_empty()) {
  486. p_state->scene_name = p_state->filename;
  487. }
  488. if (_naming_version == 0) {
  489. p_state->scene_name = _gen_unique_name(p_state, p_state->scene_name);
  490. }
  491. }
  492. return OK;
  493. }
  494. Error GLTFDocument::_parse_nodes(Ref<GLTFState> p_state) {
  495. ERR_FAIL_COND_V(!p_state->json.has("nodes"), ERR_FILE_CORRUPT);
  496. const Array &nodes = p_state->json["nodes"];
  497. for (int i = 0; i < nodes.size(); i++) {
  498. Ref<GLTFNode> node;
  499. node.instantiate();
  500. const Dictionary &n = nodes[i];
  501. if (n.has("name")) {
  502. node->set_original_name(n["name"]);
  503. node->set_name(n["name"]);
  504. }
  505. if (n.has("camera")) {
  506. node->camera = n["camera"];
  507. }
  508. if (n.has("mesh")) {
  509. node->mesh = n["mesh"];
  510. }
  511. if (n.has("skin")) {
  512. node->skin = n["skin"];
  513. }
  514. if (n.has("matrix")) {
  515. node->transform = _arr_to_xform(n["matrix"]);
  516. } else {
  517. if (n.has("translation")) {
  518. node->set_position(_arr_to_vec3(n["translation"]));
  519. }
  520. if (n.has("rotation")) {
  521. node->set_rotation(_arr_to_quaternion(n["rotation"]));
  522. }
  523. if (n.has("scale")) {
  524. node->set_scale(_arr_to_vec3(n["scale"]));
  525. }
  526. Transform3D godot_rest_transform;
  527. godot_rest_transform.basis.set_quaternion_scale(node->transform.basis.get_rotation_quaternion(), node->transform.basis.get_scale());
  528. godot_rest_transform.origin = node->transform.origin;
  529. node->set_additional_data("GODOT_rest_transform", godot_rest_transform);
  530. }
  531. if (n.has("extensions")) {
  532. Dictionary extensions = n["extensions"];
  533. if (extensions.has("KHR_lights_punctual")) {
  534. Dictionary lights_punctual = extensions["KHR_lights_punctual"];
  535. if (lights_punctual.has("light")) {
  536. GLTFLightIndex light = lights_punctual["light"];
  537. node->light = light;
  538. }
  539. }
  540. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  541. ERR_CONTINUE(ext.is_null());
  542. Error err = ext->parse_node_extensions(p_state, node, extensions);
  543. ERR_CONTINUE_MSG(err != OK, "GLTF: Encountered error " + itos(err) + " when parsing node extensions for node " + node->get_name() + " in file " + p_state->filename + ". Continuing.");
  544. }
  545. }
  546. if (n.has("children")) {
  547. const Array &children = n["children"];
  548. for (int j = 0; j < children.size(); j++) {
  549. node->children.push_back(children[j]);
  550. }
  551. }
  552. p_state->nodes.push_back(node);
  553. }
  554. // build the hierarchy
  555. for (GLTFNodeIndex node_i = 0; node_i < p_state->nodes.size(); node_i++) {
  556. for (int j = 0; j < p_state->nodes[node_i]->children.size(); j++) {
  557. GLTFNodeIndex child_i = p_state->nodes[node_i]->children[j];
  558. ERR_FAIL_INDEX_V(child_i, p_state->nodes.size(), ERR_FILE_CORRUPT);
  559. ERR_CONTINUE(p_state->nodes[child_i]->parent != -1); //node already has a parent, wtf.
  560. p_state->nodes.write[child_i]->parent = node_i;
  561. }
  562. }
  563. _compute_node_heights(p_state);
  564. return OK;
  565. }
  566. void GLTFDocument::_compute_node_heights(Ref<GLTFState> p_state) {
  567. p_state->root_nodes.clear();
  568. for (GLTFNodeIndex node_i = 0; node_i < p_state->nodes.size(); ++node_i) {
  569. Ref<GLTFNode> node = p_state->nodes[node_i];
  570. node->height = 0;
  571. GLTFNodeIndex current_i = node_i;
  572. while (current_i >= 0) {
  573. const GLTFNodeIndex parent_i = p_state->nodes[current_i]->parent;
  574. if (parent_i >= 0) {
  575. ++node->height;
  576. }
  577. current_i = parent_i;
  578. }
  579. if (node->height == 0) {
  580. p_state->root_nodes.push_back(node_i);
  581. }
  582. }
  583. }
  584. static Vector<uint8_t> _parse_base64_uri(const String &p_uri) {
  585. int start = p_uri.find(",");
  586. ERR_FAIL_COND_V(start == -1, Vector<uint8_t>());
  587. CharString substr = p_uri.substr(start + 1).ascii();
  588. int strlen = substr.length();
  589. Vector<uint8_t> buf;
  590. buf.resize(strlen / 4 * 3 + 1 + 1);
  591. size_t len = 0;
  592. ERR_FAIL_COND_V(CryptoCore::b64_decode(buf.ptrw(), buf.size(), &len, (unsigned char *)substr.get_data(), strlen) != OK, Vector<uint8_t>());
  593. buf.resize(len);
  594. return buf;
  595. }
  596. Error GLTFDocument::_encode_buffer_glb(Ref<GLTFState> p_state, const String &p_path) {
  597. print_verbose("glTF: Total buffers: " + itos(p_state->buffers.size()));
  598. if (!p_state->buffers.size()) {
  599. return OK;
  600. }
  601. Array buffers;
  602. if (p_state->buffers.size()) {
  603. Vector<uint8_t> buffer_data = p_state->buffers[0];
  604. Dictionary gltf_buffer;
  605. gltf_buffer["byteLength"] = buffer_data.size();
  606. buffers.push_back(gltf_buffer);
  607. }
  608. for (GLTFBufferIndex i = 1; i < p_state->buffers.size() - 1; i++) {
  609. Vector<uint8_t> buffer_data = p_state->buffers[i];
  610. Dictionary gltf_buffer;
  611. String filename = p_path.get_basename().get_file() + itos(i) + ".bin";
  612. String path = p_path.get_base_dir() + "/" + filename;
  613. Error err;
  614. Ref<FileAccess> file = FileAccess::open(path, FileAccess::WRITE, &err);
  615. if (file.is_null()) {
  616. return err;
  617. }
  618. if (buffer_data.size() == 0) {
  619. return OK;
  620. }
  621. file->create(FileAccess::ACCESS_RESOURCES);
  622. file->store_buffer(buffer_data.ptr(), buffer_data.size());
  623. gltf_buffer["uri"] = filename;
  624. gltf_buffer["byteLength"] = buffer_data.size();
  625. buffers.push_back(gltf_buffer);
  626. }
  627. p_state->json["buffers"] = buffers;
  628. return OK;
  629. }
  630. Error GLTFDocument::_encode_buffer_bins(Ref<GLTFState> p_state, const String &p_path) {
  631. print_verbose("glTF: Total buffers: " + itos(p_state->buffers.size()));
  632. if (!p_state->buffers.size()) {
  633. return OK;
  634. }
  635. Array buffers;
  636. for (GLTFBufferIndex i = 0; i < p_state->buffers.size(); i++) {
  637. Vector<uint8_t> buffer_data = p_state->buffers[i];
  638. Dictionary gltf_buffer;
  639. String filename = p_path.get_basename().get_file() + itos(i) + ".bin";
  640. String path = p_path.get_base_dir() + "/" + filename;
  641. Error err;
  642. Ref<FileAccess> file = FileAccess::open(path, FileAccess::WRITE, &err);
  643. if (file.is_null()) {
  644. return err;
  645. }
  646. if (buffer_data.size() == 0) {
  647. return OK;
  648. }
  649. file->create(FileAccess::ACCESS_RESOURCES);
  650. file->store_buffer(buffer_data.ptr(), buffer_data.size());
  651. gltf_buffer["uri"] = filename;
  652. gltf_buffer["byteLength"] = buffer_data.size();
  653. buffers.push_back(gltf_buffer);
  654. }
  655. p_state->json["buffers"] = buffers;
  656. return OK;
  657. }
  658. Error GLTFDocument::_parse_buffers(Ref<GLTFState> p_state, const String &p_base_path) {
  659. if (!p_state->json.has("buffers")) {
  660. return OK;
  661. }
  662. const Array &buffers = p_state->json["buffers"];
  663. for (GLTFBufferIndex i = 0; i < buffers.size(); i++) {
  664. if (i == 0 && p_state->glb_data.size()) {
  665. p_state->buffers.push_back(p_state->glb_data);
  666. } else {
  667. const Dictionary &buffer = buffers[i];
  668. if (buffer.has("uri")) {
  669. Vector<uint8_t> buffer_data;
  670. String uri = buffer["uri"];
  671. if (uri.begins_with("data:")) { // Embedded data using base64.
  672. // Validate data MIME types and throw an error if it's one we don't know/support.
  673. if (!uri.begins_with("data:application/octet-stream;base64") &&
  674. !uri.begins_with("data:application/gltf-buffer;base64")) {
  675. ERR_PRINT("glTF: Got buffer with an unknown URI data type: " + uri);
  676. }
  677. buffer_data = _parse_base64_uri(uri);
  678. } else { // Relative path to an external image file.
  679. ERR_FAIL_COND_V(p_base_path.is_empty(), ERR_INVALID_PARAMETER);
  680. uri = uri.uri_decode();
  681. uri = p_base_path.path_join(uri).replace("\\", "/"); // Fix for Windows.
  682. buffer_data = FileAccess::get_file_as_bytes(uri);
  683. ERR_FAIL_COND_V_MSG(buffer.is_empty(), ERR_PARSE_ERROR, "glTF: Couldn't load binary file as an array: " + uri);
  684. }
  685. ERR_FAIL_COND_V(!buffer.has("byteLength"), ERR_PARSE_ERROR);
  686. int byteLength = buffer["byteLength"];
  687. ERR_FAIL_COND_V(byteLength < buffer_data.size(), ERR_PARSE_ERROR);
  688. p_state->buffers.push_back(buffer_data);
  689. }
  690. }
  691. }
  692. print_verbose("glTF: Total buffers: " + itos(p_state->buffers.size()));
  693. return OK;
  694. }
  695. Error GLTFDocument::_encode_buffer_views(Ref<GLTFState> p_state) {
  696. Array buffers;
  697. for (GLTFBufferViewIndex i = 0; i < p_state->buffer_views.size(); i++) {
  698. Dictionary d;
  699. Ref<GLTFBufferView> buffer_view = p_state->buffer_views[i];
  700. d["buffer"] = buffer_view->buffer;
  701. d["byteLength"] = buffer_view->byte_length;
  702. d["byteOffset"] = buffer_view->byte_offset;
  703. if (buffer_view->byte_stride != -1) {
  704. d["byteStride"] = buffer_view->byte_stride;
  705. }
  706. // TODO Sparse
  707. // d["target"] = buffer_view->indices;
  708. ERR_FAIL_COND_V(!d.has("buffer"), ERR_INVALID_DATA);
  709. ERR_FAIL_COND_V(!d.has("byteLength"), ERR_INVALID_DATA);
  710. buffers.push_back(d);
  711. }
  712. print_verbose("glTF: Total buffer views: " + itos(p_state->buffer_views.size()));
  713. if (!buffers.size()) {
  714. return OK;
  715. }
  716. p_state->json["bufferViews"] = buffers;
  717. return OK;
  718. }
  719. Error GLTFDocument::_parse_buffer_views(Ref<GLTFState> p_state) {
  720. if (!p_state->json.has("bufferViews")) {
  721. return OK;
  722. }
  723. const Array &buffers = p_state->json["bufferViews"];
  724. for (GLTFBufferViewIndex i = 0; i < buffers.size(); i++) {
  725. const Dictionary &d = buffers[i];
  726. Ref<GLTFBufferView> buffer_view;
  727. buffer_view.instantiate();
  728. ERR_FAIL_COND_V(!d.has("buffer"), ERR_PARSE_ERROR);
  729. buffer_view->buffer = d["buffer"];
  730. ERR_FAIL_COND_V(!d.has("byteLength"), ERR_PARSE_ERROR);
  731. buffer_view->byte_length = d["byteLength"];
  732. if (d.has("byteOffset")) {
  733. buffer_view->byte_offset = d["byteOffset"];
  734. }
  735. if (d.has("byteStride")) {
  736. buffer_view->byte_stride = d["byteStride"];
  737. }
  738. if (d.has("target")) {
  739. const int target = d["target"];
  740. buffer_view->indices = target == GLTFDocument::ELEMENT_ARRAY_BUFFER;
  741. }
  742. p_state->buffer_views.push_back(buffer_view);
  743. }
  744. print_verbose("glTF: Total buffer views: " + itos(p_state->buffer_views.size()));
  745. return OK;
  746. }
  747. Error GLTFDocument::_encode_accessors(Ref<GLTFState> p_state) {
  748. Array accessors;
  749. for (GLTFAccessorIndex i = 0; i < p_state->accessors.size(); i++) {
  750. Dictionary d;
  751. Ref<GLTFAccessor> accessor = p_state->accessors[i];
  752. d["componentType"] = accessor->component_type;
  753. d["count"] = accessor->count;
  754. d["type"] = _get_accessor_type_name(accessor->type);
  755. d["byteOffset"] = accessor->byte_offset;
  756. d["normalized"] = accessor->normalized;
  757. d["max"] = accessor->max;
  758. d["min"] = accessor->min;
  759. d["bufferView"] = accessor->buffer_view; //optional because it may be sparse...
  760. // Dictionary s;
  761. // s["count"] = accessor->sparse_count;
  762. // ERR_FAIL_COND_V(!s.has("count"), ERR_PARSE_ERROR);
  763. // s["indices"] = accessor->sparse_accessors;
  764. // ERR_FAIL_COND_V(!s.has("indices"), ERR_PARSE_ERROR);
  765. // Dictionary si;
  766. // si["bufferView"] = accessor->sparse_indices_buffer_view;
  767. // ERR_FAIL_COND_V(!si.has("bufferView"), ERR_PARSE_ERROR);
  768. // si["componentType"] = accessor->sparse_indices_component_type;
  769. // if (si.has("byteOffset")) {
  770. // si["byteOffset"] = accessor->sparse_indices_byte_offset;
  771. // }
  772. // ERR_FAIL_COND_V(!si.has("componentType"), ERR_PARSE_ERROR);
  773. // s["indices"] = si;
  774. // Dictionary sv;
  775. // sv["bufferView"] = accessor->sparse_values_buffer_view;
  776. // if (sv.has("byteOffset")) {
  777. // sv["byteOffset"] = accessor->sparse_values_byte_offset;
  778. // }
  779. // ERR_FAIL_COND_V(!sv.has("bufferView"), ERR_PARSE_ERROR);
  780. // s["values"] = sv;
  781. // ERR_FAIL_COND_V(!s.has("values"), ERR_PARSE_ERROR);
  782. // d["sparse"] = s;
  783. accessors.push_back(d);
  784. }
  785. if (!accessors.size()) {
  786. return OK;
  787. }
  788. p_state->json["accessors"] = accessors;
  789. ERR_FAIL_COND_V(!p_state->json.has("accessors"), ERR_FILE_CORRUPT);
  790. print_verbose("glTF: Total accessors: " + itos(p_state->accessors.size()));
  791. return OK;
  792. }
  793. String GLTFDocument::_get_accessor_type_name(const GLTFType p_type) {
  794. if (p_type == GLTFType::TYPE_SCALAR) {
  795. return "SCALAR";
  796. }
  797. if (p_type == GLTFType::TYPE_VEC2) {
  798. return "VEC2";
  799. }
  800. if (p_type == GLTFType::TYPE_VEC3) {
  801. return "VEC3";
  802. }
  803. if (p_type == GLTFType::TYPE_VEC4) {
  804. return "VEC4";
  805. }
  806. if (p_type == GLTFType::TYPE_MAT2) {
  807. return "MAT2";
  808. }
  809. if (p_type == GLTFType::TYPE_MAT3) {
  810. return "MAT3";
  811. }
  812. if (p_type == GLTFType::TYPE_MAT4) {
  813. return "MAT4";
  814. }
  815. ERR_FAIL_V("SCALAR");
  816. }
  817. GLTFType GLTFDocument::_get_type_from_str(const String &p_string) {
  818. if (p_string == "SCALAR") {
  819. return GLTFType::TYPE_SCALAR;
  820. }
  821. if (p_string == "VEC2") {
  822. return GLTFType::TYPE_VEC2;
  823. }
  824. if (p_string == "VEC3") {
  825. return GLTFType::TYPE_VEC3;
  826. }
  827. if (p_string == "VEC4") {
  828. return GLTFType::TYPE_VEC4;
  829. }
  830. if (p_string == "MAT2") {
  831. return GLTFType::TYPE_MAT2;
  832. }
  833. if (p_string == "MAT3") {
  834. return GLTFType::TYPE_MAT3;
  835. }
  836. if (p_string == "MAT4") {
  837. return GLTFType::TYPE_MAT4;
  838. }
  839. ERR_FAIL_V(GLTFType::TYPE_SCALAR);
  840. }
  841. Error GLTFDocument::_parse_accessors(Ref<GLTFState> p_state) {
  842. if (!p_state->json.has("accessors")) {
  843. return OK;
  844. }
  845. const Array &accessors = p_state->json["accessors"];
  846. for (GLTFAccessorIndex i = 0; i < accessors.size(); i++) {
  847. const Dictionary &d = accessors[i];
  848. Ref<GLTFAccessor> accessor;
  849. accessor.instantiate();
  850. ERR_FAIL_COND_V(!d.has("componentType"), ERR_PARSE_ERROR);
  851. accessor->component_type = d["componentType"];
  852. ERR_FAIL_COND_V(!d.has("count"), ERR_PARSE_ERROR);
  853. accessor->count = d["count"];
  854. ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR);
  855. accessor->type = _get_type_from_str(d["type"]);
  856. if (d.has("bufferView")) {
  857. accessor->buffer_view = d["bufferView"]; //optional because it may be sparse...
  858. }
  859. if (d.has("byteOffset")) {
  860. accessor->byte_offset = d["byteOffset"];
  861. }
  862. if (d.has("normalized")) {
  863. accessor->normalized = d["normalized"];
  864. }
  865. if (d.has("max")) {
  866. accessor->max = d["max"];
  867. }
  868. if (d.has("min")) {
  869. accessor->min = d["min"];
  870. }
  871. if (d.has("sparse")) {
  872. //eeh..
  873. const Dictionary &s = d["sparse"];
  874. ERR_FAIL_COND_V(!s.has("count"), ERR_PARSE_ERROR);
  875. accessor->sparse_count = s["count"];
  876. ERR_FAIL_COND_V(!s.has("indices"), ERR_PARSE_ERROR);
  877. const Dictionary &si = s["indices"];
  878. ERR_FAIL_COND_V(!si.has("bufferView"), ERR_PARSE_ERROR);
  879. accessor->sparse_indices_buffer_view = si["bufferView"];
  880. ERR_FAIL_COND_V(!si.has("componentType"), ERR_PARSE_ERROR);
  881. accessor->sparse_indices_component_type = si["componentType"];
  882. if (si.has("byteOffset")) {
  883. accessor->sparse_indices_byte_offset = si["byteOffset"];
  884. }
  885. ERR_FAIL_COND_V(!s.has("values"), ERR_PARSE_ERROR);
  886. const Dictionary &sv = s["values"];
  887. ERR_FAIL_COND_V(!sv.has("bufferView"), ERR_PARSE_ERROR);
  888. accessor->sparse_values_buffer_view = sv["bufferView"];
  889. if (sv.has("byteOffset")) {
  890. accessor->sparse_values_byte_offset = sv["byteOffset"];
  891. }
  892. }
  893. p_state->accessors.push_back(accessor);
  894. }
  895. print_verbose("glTF: Total accessors: " + itos(p_state->accessors.size()));
  896. return OK;
  897. }
  898. double GLTFDocument::_filter_number(double p_float) {
  899. if (Math::is_nan(p_float)) {
  900. return 0.0f;
  901. }
  902. return p_float;
  903. }
  904. String GLTFDocument::_get_component_type_name(const uint32_t p_component) {
  905. switch (p_component) {
  906. case GLTFDocument::COMPONENT_TYPE_BYTE:
  907. return "Byte";
  908. case GLTFDocument::COMPONENT_TYPE_UNSIGNED_BYTE:
  909. return "UByte";
  910. case GLTFDocument::COMPONENT_TYPE_SHORT:
  911. return "Short";
  912. case GLTFDocument::COMPONENT_TYPE_UNSIGNED_SHORT:
  913. return "UShort";
  914. case GLTFDocument::COMPONENT_TYPE_INT:
  915. return "Int";
  916. case GLTFDocument::COMPONENT_TYPE_FLOAT:
  917. return "Float";
  918. }
  919. return "<Error>";
  920. }
  921. String GLTFDocument::_get_type_name(const GLTFType p_component) {
  922. static const char *names[] = {
  923. "float",
  924. "vec2",
  925. "vec3",
  926. "vec4",
  927. "mat2",
  928. "mat3",
  929. "mat4"
  930. };
  931. return names[p_component];
  932. }
  933. Error GLTFDocument::_encode_buffer_view(Ref<GLTFState> p_state, const double *p_src, const int p_count, const GLTFType p_type, const int p_component_type, const bool p_normalized, const int p_byte_offset, const bool p_for_vertex, GLTFBufferViewIndex &r_accessor) {
  934. const int component_count_for_type[7] = {
  935. 1, 2, 3, 4, 4, 9, 16
  936. };
  937. const int component_count = component_count_for_type[p_type];
  938. const int component_size = _get_component_type_size(p_component_type);
  939. ERR_FAIL_COND_V(component_size == 0, FAILED);
  940. int skip_every = 0;
  941. int skip_bytes = 0;
  942. //special case of alignments, as described in spec
  943. switch (p_component_type) {
  944. case COMPONENT_TYPE_BYTE:
  945. case COMPONENT_TYPE_UNSIGNED_BYTE: {
  946. if (p_type == TYPE_MAT2) {
  947. skip_every = 2;
  948. skip_bytes = 2;
  949. }
  950. if (p_type == TYPE_MAT3) {
  951. skip_every = 3;
  952. skip_bytes = 1;
  953. }
  954. } break;
  955. case COMPONENT_TYPE_SHORT:
  956. case COMPONENT_TYPE_UNSIGNED_SHORT: {
  957. if (p_type == TYPE_MAT3) {
  958. skip_every = 6;
  959. skip_bytes = 4;
  960. }
  961. } break;
  962. default: {
  963. }
  964. }
  965. Ref<GLTFBufferView> bv;
  966. bv.instantiate();
  967. const uint32_t offset = bv->byte_offset = p_byte_offset;
  968. Vector<uint8_t> &gltf_buffer = p_state->buffers.write[0];
  969. int stride = _get_component_type_size(p_component_type);
  970. if (p_for_vertex && stride % 4) {
  971. stride += 4 - (stride % 4); //according to spec must be multiple of 4
  972. }
  973. //use to debug
  974. print_verbose("glTF: encoding type " + _get_type_name(p_type) + " component type: " + _get_component_type_name(p_component_type) + " stride: " + itos(stride) + " amount " + itos(p_count));
  975. print_verbose("glTF: encoding accessor offset " + itos(p_byte_offset) + " view offset: " + itos(bv->byte_offset) + " total buffer len: " + itos(gltf_buffer.size()) + " view len " + itos(bv->byte_length));
  976. const int buffer_end = (stride * (p_count - 1)) + _get_component_type_size(p_component_type);
  977. // TODO define bv->byte_stride
  978. bv->byte_offset = gltf_buffer.size();
  979. switch (p_component_type) {
  980. case COMPONENT_TYPE_BYTE: {
  981. Vector<int8_t> buffer;
  982. buffer.resize(p_count * component_count);
  983. int32_t dst_i = 0;
  984. for (int i = 0; i < p_count; i++) {
  985. for (int j = 0; j < component_count; j++) {
  986. if (skip_every && j > 0 && (j % skip_every) == 0) {
  987. dst_i += skip_bytes;
  988. }
  989. double d = *p_src;
  990. if (p_normalized) {
  991. buffer.write[dst_i] = d * 128.0;
  992. } else {
  993. buffer.write[dst_i] = d;
  994. }
  995. p_src++;
  996. dst_i++;
  997. }
  998. }
  999. int64_t old_size = gltf_buffer.size();
  1000. gltf_buffer.resize(old_size + (buffer.size() * sizeof(int8_t)));
  1001. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int8_t));
  1002. bv->byte_length = buffer.size() * sizeof(int8_t);
  1003. } break;
  1004. case COMPONENT_TYPE_UNSIGNED_BYTE: {
  1005. Vector<uint8_t> buffer;
  1006. buffer.resize(p_count * component_count);
  1007. int32_t dst_i = 0;
  1008. for (int i = 0; i < p_count; i++) {
  1009. for (int j = 0; j < component_count; j++) {
  1010. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1011. dst_i += skip_bytes;
  1012. }
  1013. double d = *p_src;
  1014. if (p_normalized) {
  1015. buffer.write[dst_i] = d * 255.0;
  1016. } else {
  1017. buffer.write[dst_i] = d;
  1018. }
  1019. p_src++;
  1020. dst_i++;
  1021. }
  1022. }
  1023. gltf_buffer.append_array(buffer);
  1024. bv->byte_length = buffer.size() * sizeof(uint8_t);
  1025. } break;
  1026. case COMPONENT_TYPE_SHORT: {
  1027. Vector<int16_t> buffer;
  1028. buffer.resize(p_count * component_count);
  1029. int32_t dst_i = 0;
  1030. for (int i = 0; i < p_count; i++) {
  1031. for (int j = 0; j < component_count; j++) {
  1032. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1033. dst_i += skip_bytes;
  1034. }
  1035. double d = *p_src;
  1036. if (p_normalized) {
  1037. buffer.write[dst_i] = d * 32768.0;
  1038. } else {
  1039. buffer.write[dst_i] = d;
  1040. }
  1041. p_src++;
  1042. dst_i++;
  1043. }
  1044. }
  1045. int64_t old_size = gltf_buffer.size();
  1046. gltf_buffer.resize(old_size + (buffer.size() * sizeof(int16_t)));
  1047. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int16_t));
  1048. bv->byte_length = buffer.size() * sizeof(int16_t);
  1049. } break;
  1050. case COMPONENT_TYPE_UNSIGNED_SHORT: {
  1051. Vector<uint16_t> buffer;
  1052. buffer.resize(p_count * component_count);
  1053. int32_t dst_i = 0;
  1054. for (int i = 0; i < p_count; i++) {
  1055. for (int j = 0; j < component_count; j++) {
  1056. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1057. dst_i += skip_bytes;
  1058. }
  1059. double d = *p_src;
  1060. if (p_normalized) {
  1061. buffer.write[dst_i] = d * 65535.0;
  1062. } else {
  1063. buffer.write[dst_i] = d;
  1064. }
  1065. p_src++;
  1066. dst_i++;
  1067. }
  1068. }
  1069. int64_t old_size = gltf_buffer.size();
  1070. gltf_buffer.resize(old_size + (buffer.size() * sizeof(uint16_t)));
  1071. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(uint16_t));
  1072. bv->byte_length = buffer.size() * sizeof(uint16_t);
  1073. } break;
  1074. case COMPONENT_TYPE_INT: {
  1075. Vector<int> buffer;
  1076. buffer.resize(p_count * component_count);
  1077. int32_t dst_i = 0;
  1078. for (int i = 0; i < p_count; i++) {
  1079. for (int j = 0; j < component_count; j++) {
  1080. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1081. dst_i += skip_bytes;
  1082. }
  1083. double d = *p_src;
  1084. buffer.write[dst_i] = d;
  1085. p_src++;
  1086. dst_i++;
  1087. }
  1088. }
  1089. int64_t old_size = gltf_buffer.size();
  1090. gltf_buffer.resize(old_size + (buffer.size() * sizeof(int32_t)));
  1091. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int32_t));
  1092. bv->byte_length = buffer.size() * sizeof(int32_t);
  1093. } break;
  1094. case COMPONENT_TYPE_FLOAT: {
  1095. Vector<float> buffer;
  1096. buffer.resize(p_count * component_count);
  1097. int32_t dst_i = 0;
  1098. for (int i = 0; i < p_count; i++) {
  1099. for (int j = 0; j < component_count; j++) {
  1100. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1101. dst_i += skip_bytes;
  1102. }
  1103. double d = *p_src;
  1104. buffer.write[dst_i] = d;
  1105. p_src++;
  1106. dst_i++;
  1107. }
  1108. }
  1109. int64_t old_size = gltf_buffer.size();
  1110. gltf_buffer.resize(old_size + (buffer.size() * sizeof(float)));
  1111. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(float));
  1112. bv->byte_length = buffer.size() * sizeof(float);
  1113. } break;
  1114. }
  1115. ERR_FAIL_COND_V(buffer_end > bv->byte_length, ERR_INVALID_DATA);
  1116. ERR_FAIL_COND_V((int)(offset + buffer_end) > gltf_buffer.size(), ERR_INVALID_DATA);
  1117. r_accessor = bv->buffer = p_state->buffer_views.size();
  1118. p_state->buffer_views.push_back(bv);
  1119. return OK;
  1120. }
  1121. Error GLTFDocument::_decode_buffer_view(Ref<GLTFState> p_state, double *p_dst, const GLTFBufferViewIndex p_buffer_view, const int p_skip_every, const int p_skip_bytes, const int p_element_size, const int p_count, const GLTFType p_type, const int p_component_count, const int p_component_type, const int p_component_size, const bool p_normalized, const int p_byte_offset, const bool p_for_vertex) {
  1122. const Ref<GLTFBufferView> bv = p_state->buffer_views[p_buffer_view];
  1123. int stride = p_element_size;
  1124. if (bv->byte_stride != -1) {
  1125. stride = bv->byte_stride;
  1126. }
  1127. if (p_for_vertex && stride % 4) {
  1128. stride += 4 - (stride % 4); //according to spec must be multiple of 4
  1129. }
  1130. ERR_FAIL_INDEX_V(bv->buffer, p_state->buffers.size(), ERR_PARSE_ERROR);
  1131. const uint32_t offset = bv->byte_offset + p_byte_offset;
  1132. Vector<uint8_t> buffer = p_state->buffers[bv->buffer]; //copy on write, so no performance hit
  1133. const uint8_t *bufptr = buffer.ptr();
  1134. //use to debug
  1135. print_verbose("glTF: type " + _get_type_name(p_type) + " component type: " + _get_component_type_name(p_component_type) + " stride: " + itos(stride) + " amount " + itos(p_count));
  1136. print_verbose("glTF: accessor offset " + itos(p_byte_offset) + " view offset: " + itos(bv->byte_offset) + " total buffer len: " + itos(buffer.size()) + " view len " + itos(bv->byte_length));
  1137. const int buffer_end = (stride * (p_count - 1)) + p_element_size;
  1138. ERR_FAIL_COND_V(buffer_end > bv->byte_length, ERR_PARSE_ERROR);
  1139. ERR_FAIL_COND_V((int)(offset + buffer_end) > buffer.size(), ERR_PARSE_ERROR);
  1140. //fill everything as doubles
  1141. for (int i = 0; i < p_count; i++) {
  1142. const uint8_t *src = &bufptr[offset + i * stride];
  1143. for (int j = 0; j < p_component_count; j++) {
  1144. if (p_skip_every && j > 0 && (j % p_skip_every) == 0) {
  1145. src += p_skip_bytes;
  1146. }
  1147. double d = 0;
  1148. switch (p_component_type) {
  1149. case COMPONENT_TYPE_BYTE: {
  1150. int8_t b = int8_t(*src);
  1151. if (p_normalized) {
  1152. d = (double(b) / 128.0);
  1153. } else {
  1154. d = double(b);
  1155. }
  1156. } break;
  1157. case COMPONENT_TYPE_UNSIGNED_BYTE: {
  1158. uint8_t b = *src;
  1159. if (p_normalized) {
  1160. d = (double(b) / 255.0);
  1161. } else {
  1162. d = double(b);
  1163. }
  1164. } break;
  1165. case COMPONENT_TYPE_SHORT: {
  1166. int16_t s = *(int16_t *)src;
  1167. if (p_normalized) {
  1168. d = (double(s) / 32768.0);
  1169. } else {
  1170. d = double(s);
  1171. }
  1172. } break;
  1173. case COMPONENT_TYPE_UNSIGNED_SHORT: {
  1174. uint16_t s = *(uint16_t *)src;
  1175. if (p_normalized) {
  1176. d = (double(s) / 65535.0);
  1177. } else {
  1178. d = double(s);
  1179. }
  1180. } break;
  1181. case COMPONENT_TYPE_INT: {
  1182. d = *(int *)src;
  1183. } break;
  1184. case COMPONENT_TYPE_FLOAT: {
  1185. d = *(float *)src;
  1186. } break;
  1187. }
  1188. *p_dst++ = d;
  1189. src += p_component_size;
  1190. }
  1191. }
  1192. return OK;
  1193. }
  1194. int GLTFDocument::_get_component_type_size(const int p_component_type) {
  1195. switch (p_component_type) {
  1196. case COMPONENT_TYPE_BYTE:
  1197. case COMPONENT_TYPE_UNSIGNED_BYTE:
  1198. return 1;
  1199. break;
  1200. case COMPONENT_TYPE_SHORT:
  1201. case COMPONENT_TYPE_UNSIGNED_SHORT:
  1202. return 2;
  1203. break;
  1204. case COMPONENT_TYPE_INT:
  1205. case COMPONENT_TYPE_FLOAT:
  1206. return 4;
  1207. break;
  1208. default: {
  1209. ERR_FAIL_V(0);
  1210. }
  1211. }
  1212. return 0;
  1213. }
  1214. Vector<double> GLTFDocument::_decode_accessor(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1215. //spec, for reference:
  1216. //https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
  1217. ERR_FAIL_INDEX_V(p_accessor, p_state->accessors.size(), Vector<double>());
  1218. const Ref<GLTFAccessor> a = p_state->accessors[p_accessor];
  1219. const int component_count_for_type[7] = {
  1220. 1, 2, 3, 4, 4, 9, 16
  1221. };
  1222. const int component_count = component_count_for_type[a->type];
  1223. const int component_size = _get_component_type_size(a->component_type);
  1224. ERR_FAIL_COND_V(component_size == 0, Vector<double>());
  1225. int element_size = component_count * component_size;
  1226. int skip_every = 0;
  1227. int skip_bytes = 0;
  1228. //special case of alignments, as described in spec
  1229. switch (a->component_type) {
  1230. case COMPONENT_TYPE_BYTE:
  1231. case COMPONENT_TYPE_UNSIGNED_BYTE: {
  1232. if (a->type == TYPE_MAT2) {
  1233. skip_every = 2;
  1234. skip_bytes = 2;
  1235. element_size = 8; //override for this case
  1236. }
  1237. if (a->type == TYPE_MAT3) {
  1238. skip_every = 3;
  1239. skip_bytes = 1;
  1240. element_size = 12; //override for this case
  1241. }
  1242. } break;
  1243. case COMPONENT_TYPE_SHORT:
  1244. case COMPONENT_TYPE_UNSIGNED_SHORT: {
  1245. if (a->type == TYPE_MAT3) {
  1246. skip_every = 6;
  1247. skip_bytes = 4;
  1248. element_size = 16; //override for this case
  1249. }
  1250. } break;
  1251. default: {
  1252. }
  1253. }
  1254. Vector<double> dst_buffer;
  1255. dst_buffer.resize(component_count * a->count);
  1256. double *dst = dst_buffer.ptrw();
  1257. if (a->buffer_view >= 0) {
  1258. ERR_FAIL_INDEX_V(a->buffer_view, p_state->buffer_views.size(), Vector<double>());
  1259. const Error err = _decode_buffer_view(p_state, dst, a->buffer_view, skip_every, skip_bytes, element_size, a->count, a->type, component_count, a->component_type, component_size, a->normalized, a->byte_offset, p_for_vertex);
  1260. if (err != OK) {
  1261. return Vector<double>();
  1262. }
  1263. } else {
  1264. //fill with zeros, as bufferview is not defined.
  1265. for (int i = 0; i < (a->count * component_count); i++) {
  1266. dst_buffer.write[i] = 0;
  1267. }
  1268. }
  1269. if (a->sparse_count > 0) {
  1270. // I could not find any file using this, so this code is so far untested
  1271. Vector<double> indices;
  1272. indices.resize(a->sparse_count);
  1273. const int indices_component_size = _get_component_type_size(a->sparse_indices_component_type);
  1274. Error err = _decode_buffer_view(p_state, indices.ptrw(), a->sparse_indices_buffer_view, 0, 0, indices_component_size, a->sparse_count, TYPE_SCALAR, 1, a->sparse_indices_component_type, indices_component_size, false, a->sparse_indices_byte_offset, false);
  1275. if (err != OK) {
  1276. return Vector<double>();
  1277. }
  1278. Vector<double> data;
  1279. data.resize(component_count * a->sparse_count);
  1280. err = _decode_buffer_view(p_state, data.ptrw(), a->sparse_values_buffer_view, skip_every, skip_bytes, element_size, a->sparse_count, a->type, component_count, a->component_type, component_size, a->normalized, a->sparse_values_byte_offset, p_for_vertex);
  1281. if (err != OK) {
  1282. return Vector<double>();
  1283. }
  1284. for (int i = 0; i < indices.size(); i++) {
  1285. const int write_offset = int(indices[i]) * component_count;
  1286. for (int j = 0; j < component_count; j++) {
  1287. dst[write_offset + j] = data[i * component_count + j];
  1288. }
  1289. }
  1290. }
  1291. return dst_buffer;
  1292. }
  1293. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_ints(Ref<GLTFState> p_state, const Vector<int32_t> p_attribs, const bool p_for_vertex) {
  1294. if (p_attribs.size() == 0) {
  1295. return -1;
  1296. }
  1297. const int element_count = 1;
  1298. const int ret_size = p_attribs.size();
  1299. Vector<double> attribs;
  1300. attribs.resize(ret_size);
  1301. Vector<double> type_max;
  1302. type_max.resize(element_count);
  1303. Vector<double> type_min;
  1304. type_min.resize(element_count);
  1305. for (int i = 0; i < p_attribs.size(); i++) {
  1306. attribs.write[i] = Math::snapped(p_attribs[i], 1.0);
  1307. if (i == 0) {
  1308. for (int32_t type_i = 0; type_i < element_count; type_i++) {
  1309. type_max.write[type_i] = attribs[(i * element_count) + type_i];
  1310. type_min.write[type_i] = attribs[(i * element_count) + type_i];
  1311. }
  1312. }
  1313. for (int32_t type_i = 0; type_i < element_count; type_i++) {
  1314. type_max.write[type_i] = MAX(attribs[(i * element_count) + type_i], type_max[type_i]);
  1315. type_min.write[type_i] = MIN(attribs[(i * element_count) + type_i], type_min[type_i]);
  1316. type_max.write[type_i] = _filter_number(type_max.write[type_i]);
  1317. type_min.write[type_i] = _filter_number(type_min.write[type_i]);
  1318. }
  1319. }
  1320. ERR_FAIL_COND_V(attribs.is_empty(), -1);
  1321. Ref<GLTFAccessor> accessor;
  1322. accessor.instantiate();
  1323. GLTFBufferIndex buffer_view_i;
  1324. int64_t size = p_state->buffers[0].size();
  1325. const GLTFType type = GLTFType::TYPE_SCALAR;
  1326. const int component_type = GLTFDocument::COMPONENT_TYPE_INT;
  1327. accessor->max = type_max;
  1328. accessor->min = type_min;
  1329. accessor->normalized = false;
  1330. accessor->count = ret_size;
  1331. accessor->type = type;
  1332. accessor->component_type = component_type;
  1333. accessor->byte_offset = 0;
  1334. Error err = _encode_buffer_view(p_state, attribs.ptr(), attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1335. if (err != OK) {
  1336. return -1;
  1337. }
  1338. accessor->buffer_view = buffer_view_i;
  1339. p_state->accessors.push_back(accessor);
  1340. return p_state->accessors.size() - 1;
  1341. }
  1342. Vector<int> GLTFDocument::_decode_accessor_as_ints(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1343. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1344. Vector<int> ret;
  1345. if (attribs.size() == 0) {
  1346. return ret;
  1347. }
  1348. const double *attribs_ptr = attribs.ptr();
  1349. const int ret_size = attribs.size();
  1350. ret.resize(ret_size);
  1351. {
  1352. for (int i = 0; i < ret_size; i++) {
  1353. ret.write[i] = int(attribs_ptr[i]);
  1354. }
  1355. }
  1356. return ret;
  1357. }
  1358. Vector<float> GLTFDocument::_decode_accessor_as_floats(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1359. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1360. Vector<float> ret;
  1361. if (attribs.size() == 0) {
  1362. return ret;
  1363. }
  1364. const double *attribs_ptr = attribs.ptr();
  1365. const int ret_size = attribs.size();
  1366. ret.resize(ret_size);
  1367. {
  1368. for (int i = 0; i < ret_size; i++) {
  1369. ret.write[i] = float(attribs_ptr[i]);
  1370. }
  1371. }
  1372. return ret;
  1373. }
  1374. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_vec2(Ref<GLTFState> p_state, const Vector<Vector2> p_attribs, const bool p_for_vertex) {
  1375. if (p_attribs.size() == 0) {
  1376. return -1;
  1377. }
  1378. const int element_count = 2;
  1379. const int ret_size = p_attribs.size() * element_count;
  1380. Vector<double> attribs;
  1381. attribs.resize(ret_size);
  1382. Vector<double> type_max;
  1383. type_max.resize(element_count);
  1384. Vector<double> type_min;
  1385. type_min.resize(element_count);
  1386. for (int i = 0; i < p_attribs.size(); i++) {
  1387. Vector2 attrib = p_attribs[i];
  1388. attribs.write[(i * element_count) + 0] = Math::snapped(attrib.x, CMP_NORMALIZE_TOLERANCE);
  1389. attribs.write[(i * element_count) + 1] = Math::snapped(attrib.y, CMP_NORMALIZE_TOLERANCE);
  1390. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1391. }
  1392. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1393. Ref<GLTFAccessor> accessor;
  1394. accessor.instantiate();
  1395. GLTFBufferIndex buffer_view_i;
  1396. int64_t size = p_state->buffers[0].size();
  1397. const GLTFType type = GLTFType::TYPE_VEC2;
  1398. const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
  1399. accessor->max = type_max;
  1400. accessor->min = type_min;
  1401. accessor->normalized = false;
  1402. accessor->count = p_attribs.size();
  1403. accessor->type = type;
  1404. accessor->component_type = component_type;
  1405. accessor->byte_offset = 0;
  1406. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1407. if (err != OK) {
  1408. return -1;
  1409. }
  1410. accessor->buffer_view = buffer_view_i;
  1411. p_state->accessors.push_back(accessor);
  1412. return p_state->accessors.size() - 1;
  1413. }
  1414. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_color(Ref<GLTFState> p_state, const Vector<Color> p_attribs, const bool p_for_vertex) {
  1415. if (p_attribs.size() == 0) {
  1416. return -1;
  1417. }
  1418. const int ret_size = p_attribs.size() * 4;
  1419. Vector<double> attribs;
  1420. attribs.resize(ret_size);
  1421. const int element_count = 4;
  1422. Vector<double> type_max;
  1423. type_max.resize(element_count);
  1424. Vector<double> type_min;
  1425. type_min.resize(element_count);
  1426. for (int i = 0; i < p_attribs.size(); i++) {
  1427. Color attrib = p_attribs[i];
  1428. attribs.write[(i * element_count) + 0] = Math::snapped(attrib.r, CMP_NORMALIZE_TOLERANCE);
  1429. attribs.write[(i * element_count) + 1] = Math::snapped(attrib.g, CMP_NORMALIZE_TOLERANCE);
  1430. attribs.write[(i * element_count) + 2] = Math::snapped(attrib.b, CMP_NORMALIZE_TOLERANCE);
  1431. attribs.write[(i * element_count) + 3] = Math::snapped(attrib.a, CMP_NORMALIZE_TOLERANCE);
  1432. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1433. }
  1434. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1435. Ref<GLTFAccessor> accessor;
  1436. accessor.instantiate();
  1437. GLTFBufferIndex buffer_view_i;
  1438. int64_t size = p_state->buffers[0].size();
  1439. const GLTFType type = GLTFType::TYPE_VEC4;
  1440. const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
  1441. accessor->max = type_max;
  1442. accessor->min = type_min;
  1443. accessor->normalized = false;
  1444. accessor->count = p_attribs.size();
  1445. accessor->type = type;
  1446. accessor->component_type = component_type;
  1447. accessor->byte_offset = 0;
  1448. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1449. if (err != OK) {
  1450. return -1;
  1451. }
  1452. accessor->buffer_view = buffer_view_i;
  1453. p_state->accessors.push_back(accessor);
  1454. return p_state->accessors.size() - 1;
  1455. }
  1456. void GLTFDocument::_calc_accessor_min_max(int p_i, const int p_element_count, Vector<double> &p_type_max, Vector<double> p_attribs, Vector<double> &p_type_min) {
  1457. if (p_i == 0) {
  1458. for (int32_t type_i = 0; type_i < p_element_count; type_i++) {
  1459. p_type_max.write[type_i] = p_attribs[(p_i * p_element_count) + type_i];
  1460. p_type_min.write[type_i] = p_attribs[(p_i * p_element_count) + type_i];
  1461. }
  1462. }
  1463. for (int32_t type_i = 0; type_i < p_element_count; type_i++) {
  1464. p_type_max.write[type_i] = MAX(p_attribs[(p_i * p_element_count) + type_i], p_type_max[type_i]);
  1465. p_type_min.write[type_i] = MIN(p_attribs[(p_i * p_element_count) + type_i], p_type_min[type_i]);
  1466. p_type_max.write[type_i] = _filter_number(p_type_max.write[type_i]);
  1467. p_type_min.write[type_i] = _filter_number(p_type_min.write[type_i]);
  1468. }
  1469. }
  1470. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_weights(Ref<GLTFState> p_state, const Vector<Color> p_attribs, const bool p_for_vertex) {
  1471. if (p_attribs.size() == 0) {
  1472. return -1;
  1473. }
  1474. const int ret_size = p_attribs.size() * 4;
  1475. Vector<double> attribs;
  1476. attribs.resize(ret_size);
  1477. const int element_count = 4;
  1478. Vector<double> type_max;
  1479. type_max.resize(element_count);
  1480. Vector<double> type_min;
  1481. type_min.resize(element_count);
  1482. for (int i = 0; i < p_attribs.size(); i++) {
  1483. Color attrib = p_attribs[i];
  1484. attribs.write[(i * element_count) + 0] = Math::snapped(attrib.r, CMP_NORMALIZE_TOLERANCE);
  1485. attribs.write[(i * element_count) + 1] = Math::snapped(attrib.g, CMP_NORMALIZE_TOLERANCE);
  1486. attribs.write[(i * element_count) + 2] = Math::snapped(attrib.b, CMP_NORMALIZE_TOLERANCE);
  1487. attribs.write[(i * element_count) + 3] = Math::snapped(attrib.a, CMP_NORMALIZE_TOLERANCE);
  1488. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1489. }
  1490. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1491. Ref<GLTFAccessor> accessor;
  1492. accessor.instantiate();
  1493. GLTFBufferIndex buffer_view_i;
  1494. int64_t size = p_state->buffers[0].size();
  1495. const GLTFType type = GLTFType::TYPE_VEC4;
  1496. const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
  1497. accessor->max = type_max;
  1498. accessor->min = type_min;
  1499. accessor->normalized = false;
  1500. accessor->count = p_attribs.size();
  1501. accessor->type = type;
  1502. accessor->component_type = component_type;
  1503. accessor->byte_offset = 0;
  1504. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1505. if (err != OK) {
  1506. return -1;
  1507. }
  1508. accessor->buffer_view = buffer_view_i;
  1509. p_state->accessors.push_back(accessor);
  1510. return p_state->accessors.size() - 1;
  1511. }
  1512. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_joints(Ref<GLTFState> p_state, const Vector<Color> p_attribs, const bool p_for_vertex) {
  1513. if (p_attribs.size() == 0) {
  1514. return -1;
  1515. }
  1516. const int element_count = 4;
  1517. const int ret_size = p_attribs.size() * element_count;
  1518. Vector<double> attribs;
  1519. attribs.resize(ret_size);
  1520. Vector<double> type_max;
  1521. type_max.resize(element_count);
  1522. Vector<double> type_min;
  1523. type_min.resize(element_count);
  1524. for (int i = 0; i < p_attribs.size(); i++) {
  1525. Color attrib = p_attribs[i];
  1526. attribs.write[(i * element_count) + 0] = Math::snapped(attrib.r, CMP_NORMALIZE_TOLERANCE);
  1527. attribs.write[(i * element_count) + 1] = Math::snapped(attrib.g, CMP_NORMALIZE_TOLERANCE);
  1528. attribs.write[(i * element_count) + 2] = Math::snapped(attrib.b, CMP_NORMALIZE_TOLERANCE);
  1529. attribs.write[(i * element_count) + 3] = Math::snapped(attrib.a, CMP_NORMALIZE_TOLERANCE);
  1530. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1531. }
  1532. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1533. Ref<GLTFAccessor> accessor;
  1534. accessor.instantiate();
  1535. GLTFBufferIndex buffer_view_i;
  1536. int64_t size = p_state->buffers[0].size();
  1537. const GLTFType type = GLTFType::TYPE_VEC4;
  1538. const int component_type = GLTFDocument::COMPONENT_TYPE_UNSIGNED_SHORT;
  1539. accessor->max = type_max;
  1540. accessor->min = type_min;
  1541. accessor->normalized = false;
  1542. accessor->count = p_attribs.size();
  1543. accessor->type = type;
  1544. accessor->component_type = component_type;
  1545. accessor->byte_offset = 0;
  1546. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1547. if (err != OK) {
  1548. return -1;
  1549. }
  1550. accessor->buffer_view = buffer_view_i;
  1551. p_state->accessors.push_back(accessor);
  1552. return p_state->accessors.size() - 1;
  1553. }
  1554. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_quaternions(Ref<GLTFState> p_state, const Vector<Quaternion> p_attribs, const bool p_for_vertex) {
  1555. if (p_attribs.size() == 0) {
  1556. return -1;
  1557. }
  1558. const int element_count = 4;
  1559. const int ret_size = p_attribs.size() * element_count;
  1560. Vector<double> attribs;
  1561. attribs.resize(ret_size);
  1562. Vector<double> type_max;
  1563. type_max.resize(element_count);
  1564. Vector<double> type_min;
  1565. type_min.resize(element_count);
  1566. for (int i = 0; i < p_attribs.size(); i++) {
  1567. Quaternion quaternion = p_attribs[i];
  1568. attribs.write[(i * element_count) + 0] = Math::snapped(quaternion.x, CMP_NORMALIZE_TOLERANCE);
  1569. attribs.write[(i * element_count) + 1] = Math::snapped(quaternion.y, CMP_NORMALIZE_TOLERANCE);
  1570. attribs.write[(i * element_count) + 2] = Math::snapped(quaternion.z, CMP_NORMALIZE_TOLERANCE);
  1571. attribs.write[(i * element_count) + 3] = Math::snapped(quaternion.w, CMP_NORMALIZE_TOLERANCE);
  1572. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1573. }
  1574. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1575. Ref<GLTFAccessor> accessor;
  1576. accessor.instantiate();
  1577. GLTFBufferIndex buffer_view_i;
  1578. int64_t size = p_state->buffers[0].size();
  1579. const GLTFType type = GLTFType::TYPE_VEC4;
  1580. const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
  1581. accessor->max = type_max;
  1582. accessor->min = type_min;
  1583. accessor->normalized = false;
  1584. accessor->count = p_attribs.size();
  1585. accessor->type = type;
  1586. accessor->component_type = component_type;
  1587. accessor->byte_offset = 0;
  1588. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1589. if (err != OK) {
  1590. return -1;
  1591. }
  1592. accessor->buffer_view = buffer_view_i;
  1593. p_state->accessors.push_back(accessor);
  1594. return p_state->accessors.size() - 1;
  1595. }
  1596. Vector<Vector2> GLTFDocument::_decode_accessor_as_vec2(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1597. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1598. Vector<Vector2> ret;
  1599. if (attribs.size() == 0) {
  1600. return ret;
  1601. }
  1602. ERR_FAIL_COND_V(attribs.size() % 2 != 0, ret);
  1603. const double *attribs_ptr = attribs.ptr();
  1604. const int ret_size = attribs.size() / 2;
  1605. ret.resize(ret_size);
  1606. {
  1607. for (int i = 0; i < ret_size; i++) {
  1608. ret.write[i] = Vector2(attribs_ptr[i * 2 + 0], attribs_ptr[i * 2 + 1]);
  1609. }
  1610. }
  1611. return ret;
  1612. }
  1613. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_floats(Ref<GLTFState> p_state, const Vector<real_t> p_attribs, const bool p_for_vertex) {
  1614. if (p_attribs.size() == 0) {
  1615. return -1;
  1616. }
  1617. const int element_count = 1;
  1618. const int ret_size = p_attribs.size();
  1619. Vector<double> attribs;
  1620. attribs.resize(ret_size);
  1621. Vector<double> type_max;
  1622. type_max.resize(element_count);
  1623. Vector<double> type_min;
  1624. type_min.resize(element_count);
  1625. for (int i = 0; i < p_attribs.size(); i++) {
  1626. attribs.write[i] = Math::snapped(p_attribs[i], CMP_NORMALIZE_TOLERANCE);
  1627. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1628. }
  1629. ERR_FAIL_COND_V(attribs.is_empty(), -1);
  1630. Ref<GLTFAccessor> accessor;
  1631. accessor.instantiate();
  1632. GLTFBufferIndex buffer_view_i;
  1633. int64_t size = p_state->buffers[0].size();
  1634. const GLTFType type = GLTFType::TYPE_SCALAR;
  1635. const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
  1636. accessor->max = type_max;
  1637. accessor->min = type_min;
  1638. accessor->normalized = false;
  1639. accessor->count = ret_size;
  1640. accessor->type = type;
  1641. accessor->component_type = component_type;
  1642. accessor->byte_offset = 0;
  1643. Error err = _encode_buffer_view(p_state, attribs.ptr(), attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1644. if (err != OK) {
  1645. return -1;
  1646. }
  1647. accessor->buffer_view = buffer_view_i;
  1648. p_state->accessors.push_back(accessor);
  1649. return p_state->accessors.size() - 1;
  1650. }
  1651. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_vec3(Ref<GLTFState> p_state, const Vector<Vector3> p_attribs, const bool p_for_vertex) {
  1652. if (p_attribs.size() == 0) {
  1653. return -1;
  1654. }
  1655. const int element_count = 3;
  1656. const int ret_size = p_attribs.size() * element_count;
  1657. Vector<double> attribs;
  1658. attribs.resize(ret_size);
  1659. Vector<double> type_max;
  1660. type_max.resize(element_count);
  1661. Vector<double> type_min;
  1662. type_min.resize(element_count);
  1663. for (int i = 0; i < p_attribs.size(); i++) {
  1664. Vector3 attrib = p_attribs[i];
  1665. attribs.write[(i * element_count) + 0] = Math::snapped(attrib.x, CMP_NORMALIZE_TOLERANCE);
  1666. attribs.write[(i * element_count) + 1] = Math::snapped(attrib.y, CMP_NORMALIZE_TOLERANCE);
  1667. attribs.write[(i * element_count) + 2] = Math::snapped(attrib.z, CMP_NORMALIZE_TOLERANCE);
  1668. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1669. }
  1670. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1671. Ref<GLTFAccessor> accessor;
  1672. accessor.instantiate();
  1673. GLTFBufferIndex buffer_view_i;
  1674. int64_t size = p_state->buffers[0].size();
  1675. const GLTFType type = GLTFType::TYPE_VEC3;
  1676. const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
  1677. accessor->max = type_max;
  1678. accessor->min = type_min;
  1679. accessor->normalized = false;
  1680. accessor->count = p_attribs.size();
  1681. accessor->type = type;
  1682. accessor->component_type = component_type;
  1683. accessor->byte_offset = 0;
  1684. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1685. if (err != OK) {
  1686. return -1;
  1687. }
  1688. accessor->buffer_view = buffer_view_i;
  1689. p_state->accessors.push_back(accessor);
  1690. return p_state->accessors.size() - 1;
  1691. }
  1692. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_xform(Ref<GLTFState> p_state, const Vector<Transform3D> p_attribs, const bool p_for_vertex) {
  1693. if (p_attribs.size() == 0) {
  1694. return -1;
  1695. }
  1696. const int element_count = 16;
  1697. const int ret_size = p_attribs.size() * element_count;
  1698. Vector<double> attribs;
  1699. attribs.resize(ret_size);
  1700. Vector<double> type_max;
  1701. type_max.resize(element_count);
  1702. Vector<double> type_min;
  1703. type_min.resize(element_count);
  1704. for (int i = 0; i < p_attribs.size(); i++) {
  1705. Transform3D attrib = p_attribs[i];
  1706. Basis basis = attrib.get_basis();
  1707. Vector3 axis_0 = basis.get_column(Vector3::AXIS_X);
  1708. attribs.write[i * element_count + 0] = Math::snapped(axis_0.x, CMP_NORMALIZE_TOLERANCE);
  1709. attribs.write[i * element_count + 1] = Math::snapped(axis_0.y, CMP_NORMALIZE_TOLERANCE);
  1710. attribs.write[i * element_count + 2] = Math::snapped(axis_0.z, CMP_NORMALIZE_TOLERANCE);
  1711. attribs.write[i * element_count + 3] = 0.0;
  1712. Vector3 axis_1 = basis.get_column(Vector3::AXIS_Y);
  1713. attribs.write[i * element_count + 4] = Math::snapped(axis_1.x, CMP_NORMALIZE_TOLERANCE);
  1714. attribs.write[i * element_count + 5] = Math::snapped(axis_1.y, CMP_NORMALIZE_TOLERANCE);
  1715. attribs.write[i * element_count + 6] = Math::snapped(axis_1.z, CMP_NORMALIZE_TOLERANCE);
  1716. attribs.write[i * element_count + 7] = 0.0;
  1717. Vector3 axis_2 = basis.get_column(Vector3::AXIS_Z);
  1718. attribs.write[i * element_count + 8] = Math::snapped(axis_2.x, CMP_NORMALIZE_TOLERANCE);
  1719. attribs.write[i * element_count + 9] = Math::snapped(axis_2.y, CMP_NORMALIZE_TOLERANCE);
  1720. attribs.write[i * element_count + 10] = Math::snapped(axis_2.z, CMP_NORMALIZE_TOLERANCE);
  1721. attribs.write[i * element_count + 11] = 0.0;
  1722. Vector3 origin = attrib.get_origin();
  1723. attribs.write[i * element_count + 12] = Math::snapped(origin.x, CMP_NORMALIZE_TOLERANCE);
  1724. attribs.write[i * element_count + 13] = Math::snapped(origin.y, CMP_NORMALIZE_TOLERANCE);
  1725. attribs.write[i * element_count + 14] = Math::snapped(origin.z, CMP_NORMALIZE_TOLERANCE);
  1726. attribs.write[i * element_count + 15] = 1.0;
  1727. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1728. }
  1729. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1730. Ref<GLTFAccessor> accessor;
  1731. accessor.instantiate();
  1732. GLTFBufferIndex buffer_view_i;
  1733. int64_t size = p_state->buffers[0].size();
  1734. const GLTFType type = GLTFType::TYPE_MAT4;
  1735. const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
  1736. accessor->max = type_max;
  1737. accessor->min = type_min;
  1738. accessor->normalized = false;
  1739. accessor->count = p_attribs.size();
  1740. accessor->type = type;
  1741. accessor->component_type = component_type;
  1742. accessor->byte_offset = 0;
  1743. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1744. if (err != OK) {
  1745. return -1;
  1746. }
  1747. accessor->buffer_view = buffer_view_i;
  1748. p_state->accessors.push_back(accessor);
  1749. return p_state->accessors.size() - 1;
  1750. }
  1751. Vector<Vector3> GLTFDocument::_decode_accessor_as_vec3(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1752. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1753. Vector<Vector3> ret;
  1754. if (attribs.size() == 0) {
  1755. return ret;
  1756. }
  1757. ERR_FAIL_COND_V(attribs.size() % 3 != 0, ret);
  1758. const double *attribs_ptr = attribs.ptr();
  1759. const int ret_size = attribs.size() / 3;
  1760. ret.resize(ret_size);
  1761. {
  1762. for (int i = 0; i < ret_size; i++) {
  1763. ret.write[i] = Vector3(attribs_ptr[i * 3 + 0], attribs_ptr[i * 3 + 1], attribs_ptr[i * 3 + 2]);
  1764. }
  1765. }
  1766. return ret;
  1767. }
  1768. Vector<Color> GLTFDocument::_decode_accessor_as_color(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1769. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1770. Vector<Color> ret;
  1771. if (attribs.size() == 0) {
  1772. return ret;
  1773. }
  1774. const int type = p_state->accessors[p_accessor]->type;
  1775. ERR_FAIL_COND_V(!(type == TYPE_VEC3 || type == TYPE_VEC4), ret);
  1776. int vec_len = 3;
  1777. if (type == TYPE_VEC4) {
  1778. vec_len = 4;
  1779. }
  1780. ERR_FAIL_COND_V(attribs.size() % vec_len != 0, ret);
  1781. const double *attribs_ptr = attribs.ptr();
  1782. const int ret_size = attribs.size() / vec_len;
  1783. ret.resize(ret_size);
  1784. {
  1785. for (int i = 0; i < ret_size; i++) {
  1786. ret.write[i] = Color(attribs_ptr[i * vec_len + 0], attribs_ptr[i * vec_len + 1], attribs_ptr[i * vec_len + 2], vec_len == 4 ? attribs_ptr[i * 4 + 3] : 1.0);
  1787. }
  1788. }
  1789. return ret;
  1790. }
  1791. Vector<Quaternion> GLTFDocument::_decode_accessor_as_quaternion(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1792. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1793. Vector<Quaternion> ret;
  1794. if (attribs.size() == 0) {
  1795. return ret;
  1796. }
  1797. ERR_FAIL_COND_V(attribs.size() % 4 != 0, ret);
  1798. const double *attribs_ptr = attribs.ptr();
  1799. const int ret_size = attribs.size() / 4;
  1800. ret.resize(ret_size);
  1801. {
  1802. for (int i = 0; i < ret_size; i++) {
  1803. ret.write[i] = Quaternion(attribs_ptr[i * 4 + 0], attribs_ptr[i * 4 + 1], attribs_ptr[i * 4 + 2], attribs_ptr[i * 4 + 3]).normalized();
  1804. }
  1805. }
  1806. return ret;
  1807. }
  1808. Vector<Transform2D> GLTFDocument::_decode_accessor_as_xform2d(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1809. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1810. Vector<Transform2D> ret;
  1811. if (attribs.size() == 0) {
  1812. return ret;
  1813. }
  1814. ERR_FAIL_COND_V(attribs.size() % 4 != 0, ret);
  1815. ret.resize(attribs.size() / 4);
  1816. for (int i = 0; i < ret.size(); i++) {
  1817. ret.write[i][0] = Vector2(attribs[i * 4 + 0], attribs[i * 4 + 1]);
  1818. ret.write[i][1] = Vector2(attribs[i * 4 + 2], attribs[i * 4 + 3]);
  1819. }
  1820. return ret;
  1821. }
  1822. Vector<Basis> GLTFDocument::_decode_accessor_as_basis(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1823. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1824. Vector<Basis> ret;
  1825. if (attribs.size() == 0) {
  1826. return ret;
  1827. }
  1828. ERR_FAIL_COND_V(attribs.size() % 9 != 0, ret);
  1829. ret.resize(attribs.size() / 9);
  1830. for (int i = 0; i < ret.size(); i++) {
  1831. ret.write[i].set_column(0, Vector3(attribs[i * 9 + 0], attribs[i * 9 + 1], attribs[i * 9 + 2]));
  1832. ret.write[i].set_column(1, Vector3(attribs[i * 9 + 3], attribs[i * 9 + 4], attribs[i * 9 + 5]));
  1833. ret.write[i].set_column(2, Vector3(attribs[i * 9 + 6], attribs[i * 9 + 7], attribs[i * 9 + 8]));
  1834. }
  1835. return ret;
  1836. }
  1837. Vector<Transform3D> GLTFDocument::_decode_accessor_as_xform(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1838. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1839. Vector<Transform3D> ret;
  1840. if (attribs.size() == 0) {
  1841. return ret;
  1842. }
  1843. ERR_FAIL_COND_V(attribs.size() % 16 != 0, ret);
  1844. ret.resize(attribs.size() / 16);
  1845. for (int i = 0; i < ret.size(); i++) {
  1846. ret.write[i].basis.set_column(0, Vector3(attribs[i * 16 + 0], attribs[i * 16 + 1], attribs[i * 16 + 2]));
  1847. ret.write[i].basis.set_column(1, Vector3(attribs[i * 16 + 4], attribs[i * 16 + 5], attribs[i * 16 + 6]));
  1848. ret.write[i].basis.set_column(2, Vector3(attribs[i * 16 + 8], attribs[i * 16 + 9], attribs[i * 16 + 10]));
  1849. ret.write[i].set_origin(Vector3(attribs[i * 16 + 12], attribs[i * 16 + 13], attribs[i * 16 + 14]));
  1850. }
  1851. return ret;
  1852. }
  1853. Error GLTFDocument::_serialize_meshes(Ref<GLTFState> p_state) {
  1854. Array meshes;
  1855. for (GLTFMeshIndex gltf_mesh_i = 0; gltf_mesh_i < p_state->meshes.size(); gltf_mesh_i++) {
  1856. print_verbose("glTF: Serializing mesh: " + itos(gltf_mesh_i));
  1857. Ref<ImporterMesh> import_mesh = p_state->meshes.write[gltf_mesh_i]->get_mesh();
  1858. if (import_mesh.is_null()) {
  1859. continue;
  1860. }
  1861. Array instance_materials = p_state->meshes.write[gltf_mesh_i]->get_instance_materials();
  1862. Array primitives;
  1863. Dictionary gltf_mesh;
  1864. Array target_names;
  1865. Array weights;
  1866. for (int morph_i = 0; morph_i < import_mesh->get_blend_shape_count(); morph_i++) {
  1867. target_names.push_back(import_mesh->get_blend_shape_name(morph_i));
  1868. }
  1869. for (int surface_i = 0; surface_i < import_mesh->get_surface_count(); surface_i++) {
  1870. Array targets;
  1871. Dictionary primitive;
  1872. Mesh::PrimitiveType primitive_type = import_mesh->get_surface_primitive_type(surface_i);
  1873. switch (primitive_type) {
  1874. case Mesh::PRIMITIVE_POINTS: {
  1875. primitive["mode"] = 0;
  1876. break;
  1877. }
  1878. case Mesh::PRIMITIVE_LINES: {
  1879. primitive["mode"] = 1;
  1880. break;
  1881. }
  1882. // case Mesh::PRIMITIVE_LINE_LOOP: {
  1883. // primitive["mode"] = 2;
  1884. // break;
  1885. // }
  1886. case Mesh::PRIMITIVE_LINE_STRIP: {
  1887. primitive["mode"] = 3;
  1888. break;
  1889. }
  1890. case Mesh::PRIMITIVE_TRIANGLES: {
  1891. primitive["mode"] = 4;
  1892. break;
  1893. }
  1894. case Mesh::PRIMITIVE_TRIANGLE_STRIP: {
  1895. primitive["mode"] = 5;
  1896. break;
  1897. }
  1898. // case Mesh::PRIMITIVE_TRIANGLE_FAN: {
  1899. // primitive["mode"] = 6;
  1900. // break;
  1901. // }
  1902. default: {
  1903. ERR_FAIL_V(FAILED);
  1904. }
  1905. }
  1906. Array array = import_mesh->get_surface_arrays(surface_i);
  1907. uint64_t format = import_mesh->get_surface_format(surface_i);
  1908. int32_t vertex_num = 0;
  1909. Dictionary attributes;
  1910. {
  1911. Vector<Vector3> a = array[Mesh::ARRAY_VERTEX];
  1912. ERR_FAIL_COND_V(a.is_empty(), ERR_INVALID_DATA);
  1913. attributes["POSITION"] = _encode_accessor_as_vec3(p_state, a, true);
  1914. vertex_num = a.size();
  1915. }
  1916. {
  1917. Vector<real_t> a = array[Mesh::ARRAY_TANGENT];
  1918. if (a.size()) {
  1919. const int ret_size = a.size() / 4;
  1920. Vector<Color> attribs;
  1921. attribs.resize(ret_size);
  1922. for (int i = 0; i < ret_size; i++) {
  1923. Color out;
  1924. out.r = a[(i * 4) + 0];
  1925. out.g = a[(i * 4) + 1];
  1926. out.b = a[(i * 4) + 2];
  1927. out.a = a[(i * 4) + 3];
  1928. attribs.write[i] = out;
  1929. }
  1930. attributes["TANGENT"] = _encode_accessor_as_color(p_state, attribs, true);
  1931. }
  1932. }
  1933. {
  1934. Vector<Vector3> a = array[Mesh::ARRAY_NORMAL];
  1935. if (a.size()) {
  1936. const int ret_size = a.size();
  1937. Vector<Vector3> attribs;
  1938. attribs.resize(ret_size);
  1939. for (int i = 0; i < ret_size; i++) {
  1940. attribs.write[i] = Vector3(a[i]).normalized();
  1941. }
  1942. attributes["NORMAL"] = _encode_accessor_as_vec3(p_state, attribs, true);
  1943. }
  1944. }
  1945. {
  1946. Vector<Vector2> a = array[Mesh::ARRAY_TEX_UV];
  1947. if (a.size()) {
  1948. attributes["TEXCOORD_0"] = _encode_accessor_as_vec2(p_state, a, true);
  1949. }
  1950. }
  1951. {
  1952. Vector<Vector2> a = array[Mesh::ARRAY_TEX_UV2];
  1953. if (a.size()) {
  1954. attributes["TEXCOORD_1"] = _encode_accessor_as_vec2(p_state, a, true);
  1955. }
  1956. }
  1957. for (int custom_i = 0; custom_i < 3; custom_i++) {
  1958. Vector<float> a = array[Mesh::ARRAY_CUSTOM0 + custom_i];
  1959. if (a.size()) {
  1960. int num_channels = 4;
  1961. int custom_shift = Mesh::ARRAY_FORMAT_CUSTOM0_SHIFT + custom_i * Mesh::ARRAY_FORMAT_CUSTOM_BITS;
  1962. switch ((format >> custom_shift) & Mesh::ARRAY_FORMAT_CUSTOM_MASK) {
  1963. case Mesh::ARRAY_CUSTOM_R_FLOAT:
  1964. num_channels = 1;
  1965. break;
  1966. case Mesh::ARRAY_CUSTOM_RG_FLOAT:
  1967. num_channels = 2;
  1968. break;
  1969. case Mesh::ARRAY_CUSTOM_RGB_FLOAT:
  1970. num_channels = 3;
  1971. break;
  1972. case Mesh::ARRAY_CUSTOM_RGBA_FLOAT:
  1973. num_channels = 4;
  1974. break;
  1975. }
  1976. int texcoord_i = 2 + 2 * custom_i;
  1977. String gltf_texcoord_key;
  1978. for (int prev_texcoord_i = 0; prev_texcoord_i < texcoord_i; prev_texcoord_i++) {
  1979. gltf_texcoord_key = vformat("TEXCOORD_%d", prev_texcoord_i);
  1980. if (!attributes.has(gltf_texcoord_key)) {
  1981. Vector<Vector2> empty;
  1982. empty.resize(vertex_num);
  1983. attributes[gltf_texcoord_key] = _encode_accessor_as_vec2(p_state, empty, true);
  1984. }
  1985. }
  1986. LocalVector<Vector2> first_channel;
  1987. first_channel.resize(vertex_num);
  1988. LocalVector<Vector2> second_channel;
  1989. second_channel.resize(vertex_num);
  1990. for (int32_t vert_i = 0; vert_i < vertex_num; vert_i++) {
  1991. float u = a[vert_i * num_channels + 0];
  1992. float v = (num_channels == 1 ? 0.0f : a[vert_i * num_channels + 1]);
  1993. first_channel[vert_i] = Vector2(u, v);
  1994. u = 0;
  1995. v = 0;
  1996. if (num_channels >= 3) {
  1997. u = a[vert_i * num_channels + 2];
  1998. v = (num_channels == 3 ? 0.0f : a[vert_i * num_channels + 3]);
  1999. second_channel[vert_i] = Vector2(u, v);
  2000. }
  2001. }
  2002. gltf_texcoord_key = vformat("TEXCOORD_%d", texcoord_i);
  2003. attributes[gltf_texcoord_key] = _encode_accessor_as_vec2(p_state, first_channel, true);
  2004. gltf_texcoord_key = vformat("TEXCOORD_%d", texcoord_i + 1);
  2005. attributes[gltf_texcoord_key] = _encode_accessor_as_vec2(p_state, second_channel, true);
  2006. }
  2007. }
  2008. {
  2009. Vector<Color> a = array[Mesh::ARRAY_COLOR];
  2010. if (a.size()) {
  2011. attributes["COLOR_0"] = _encode_accessor_as_color(p_state, a, true);
  2012. }
  2013. }
  2014. HashMap<int, int> joint_i_to_bone_i;
  2015. for (GLTFNodeIndex node_i = 0; node_i < p_state->nodes.size(); node_i++) {
  2016. GLTFSkinIndex skin_i = -1;
  2017. if (p_state->nodes[node_i]->mesh == gltf_mesh_i) {
  2018. skin_i = p_state->nodes[node_i]->skin;
  2019. }
  2020. if (skin_i != -1) {
  2021. joint_i_to_bone_i = p_state->skins[skin_i]->joint_i_to_bone_i;
  2022. break;
  2023. }
  2024. }
  2025. {
  2026. const Array &a = array[Mesh::ARRAY_BONES];
  2027. const Vector<Vector3> &vertex_array = array[Mesh::ARRAY_VERTEX];
  2028. if ((a.size() / JOINT_GROUP_SIZE) == vertex_array.size()) {
  2029. const int ret_size = a.size() / JOINT_GROUP_SIZE;
  2030. Vector<Color> attribs;
  2031. attribs.resize(ret_size);
  2032. {
  2033. for (int array_i = 0; array_i < attribs.size(); array_i++) {
  2034. int32_t joint_0 = a[(array_i * JOINT_GROUP_SIZE) + 0];
  2035. int32_t joint_1 = a[(array_i * JOINT_GROUP_SIZE) + 1];
  2036. int32_t joint_2 = a[(array_i * JOINT_GROUP_SIZE) + 2];
  2037. int32_t joint_3 = a[(array_i * JOINT_GROUP_SIZE) + 3];
  2038. attribs.write[array_i] = Color(joint_0, joint_1, joint_2, joint_3);
  2039. }
  2040. }
  2041. attributes["JOINTS_0"] = _encode_accessor_as_joints(p_state, attribs, true);
  2042. } else if ((a.size() / (JOINT_GROUP_SIZE * 2)) >= vertex_array.size()) {
  2043. Vector<Color> joints_0;
  2044. joints_0.resize(vertex_num);
  2045. Vector<Color> joints_1;
  2046. joints_1.resize(vertex_num);
  2047. int32_t weights_8_count = JOINT_GROUP_SIZE * 2;
  2048. for (int32_t vertex_i = 0; vertex_i < vertex_num; vertex_i++) {
  2049. Color joint_0;
  2050. joint_0.r = a[vertex_i * weights_8_count + 0];
  2051. joint_0.g = a[vertex_i * weights_8_count + 1];
  2052. joint_0.b = a[vertex_i * weights_8_count + 2];
  2053. joint_0.a = a[vertex_i * weights_8_count + 3];
  2054. joints_0.write[vertex_i] = joint_0;
  2055. Color joint_1;
  2056. joint_1.r = a[vertex_i * weights_8_count + 4];
  2057. joint_1.g = a[vertex_i * weights_8_count + 5];
  2058. joint_1.b = a[vertex_i * weights_8_count + 6];
  2059. joint_1.a = a[vertex_i * weights_8_count + 7];
  2060. joints_1.write[vertex_i] = joint_1;
  2061. }
  2062. attributes["JOINTS_0"] = _encode_accessor_as_joints(p_state, joints_0, true);
  2063. attributes["JOINTS_1"] = _encode_accessor_as_joints(p_state, joints_1, true);
  2064. }
  2065. }
  2066. {
  2067. const Array &a = array[Mesh::ARRAY_WEIGHTS];
  2068. const Vector<Vector3> &vertex_array = array[Mesh::ARRAY_VERTEX];
  2069. if ((a.size() / JOINT_GROUP_SIZE) == vertex_array.size()) {
  2070. int32_t vertex_count = vertex_array.size();
  2071. Vector<Color> attribs;
  2072. attribs.resize(vertex_count);
  2073. for (int i = 0; i < vertex_count; i++) {
  2074. attribs.write[i] = Color(a[(i * JOINT_GROUP_SIZE) + 0], a[(i * JOINT_GROUP_SIZE) + 1], a[(i * JOINT_GROUP_SIZE) + 2], a[(i * JOINT_GROUP_SIZE) + 3]);
  2075. }
  2076. attributes["WEIGHTS_0"] = _encode_accessor_as_weights(p_state, attribs, true);
  2077. } else if ((a.size() / (JOINT_GROUP_SIZE * 2)) >= vertex_array.size()) {
  2078. Vector<Color> weights_0;
  2079. weights_0.resize(vertex_num);
  2080. Vector<Color> weights_1;
  2081. weights_1.resize(vertex_num);
  2082. int32_t weights_8_count = JOINT_GROUP_SIZE * 2;
  2083. for (int32_t vertex_i = 0; vertex_i < vertex_num; vertex_i++) {
  2084. Color weight_0;
  2085. weight_0.r = a[vertex_i * weights_8_count + 0];
  2086. weight_0.g = a[vertex_i * weights_8_count + 1];
  2087. weight_0.b = a[vertex_i * weights_8_count + 2];
  2088. weight_0.a = a[vertex_i * weights_8_count + 3];
  2089. weights_0.write[vertex_i] = weight_0;
  2090. Color weight_1;
  2091. weight_1.r = a[vertex_i * weights_8_count + 4];
  2092. weight_1.g = a[vertex_i * weights_8_count + 5];
  2093. weight_1.b = a[vertex_i * weights_8_count + 6];
  2094. weight_1.a = a[vertex_i * weights_8_count + 7];
  2095. weights_1.write[vertex_i] = weight_1;
  2096. }
  2097. attributes["WEIGHTS_0"] = _encode_accessor_as_weights(p_state, weights_0, true);
  2098. attributes["WEIGHTS_1"] = _encode_accessor_as_weights(p_state, weights_1, true);
  2099. }
  2100. }
  2101. {
  2102. Vector<int32_t> mesh_indices = array[Mesh::ARRAY_INDEX];
  2103. if (mesh_indices.size()) {
  2104. if (primitive_type == Mesh::PRIMITIVE_TRIANGLES) {
  2105. //swap around indices, convert ccw to cw for front face
  2106. const int is = mesh_indices.size();
  2107. for (int k = 0; k < is; k += 3) {
  2108. SWAP(mesh_indices.write[k + 0], mesh_indices.write[k + 2]);
  2109. }
  2110. }
  2111. primitive["indices"] = _encode_accessor_as_ints(p_state, mesh_indices, true);
  2112. } else {
  2113. if (primitive_type == Mesh::PRIMITIVE_TRIANGLES) {
  2114. //generate indices because they need to be swapped for CW/CCW
  2115. const Vector<Vector3> &vertices = array[Mesh::ARRAY_VERTEX];
  2116. Ref<SurfaceTool> st;
  2117. st.instantiate();
  2118. st->create_from_triangle_arrays(array);
  2119. st->index();
  2120. Vector<int32_t> generated_indices = st->commit_to_arrays()[Mesh::ARRAY_INDEX];
  2121. const int vs = vertices.size();
  2122. generated_indices.resize(vs);
  2123. {
  2124. for (int k = 0; k < vs; k += 3) {
  2125. generated_indices.write[k] = k;
  2126. generated_indices.write[k + 1] = k + 2;
  2127. generated_indices.write[k + 2] = k + 1;
  2128. }
  2129. }
  2130. primitive["indices"] = _encode_accessor_as_ints(p_state, generated_indices, true);
  2131. }
  2132. }
  2133. }
  2134. primitive["attributes"] = attributes;
  2135. //blend shapes
  2136. print_verbose("glTF: Mesh has targets");
  2137. if (import_mesh->get_blend_shape_count()) {
  2138. ArrayMesh::BlendShapeMode shape_mode = import_mesh->get_blend_shape_mode();
  2139. for (int morph_i = 0; morph_i < import_mesh->get_blend_shape_count(); morph_i++) {
  2140. Array array_morph = import_mesh->get_surface_blend_shape_arrays(surface_i, morph_i);
  2141. Dictionary t;
  2142. Vector<Vector3> varr = array_morph[Mesh::ARRAY_VERTEX];
  2143. Array mesh_arrays = import_mesh->get_surface_arrays(surface_i);
  2144. if (varr.size()) {
  2145. Vector<Vector3> src_varr = array[Mesh::ARRAY_VERTEX];
  2146. if (shape_mode == ArrayMesh::BlendShapeMode::BLEND_SHAPE_MODE_NORMALIZED) {
  2147. const int max_idx = src_varr.size();
  2148. for (int blend_i = 0; blend_i < max_idx; blend_i++) {
  2149. varr.write[blend_i] = Vector3(varr[blend_i]) - src_varr[blend_i];
  2150. }
  2151. }
  2152. t["POSITION"] = _encode_accessor_as_vec3(p_state, varr, true);
  2153. }
  2154. Vector<Vector3> narr = array_morph[Mesh::ARRAY_NORMAL];
  2155. if (narr.size()) {
  2156. t["NORMAL"] = _encode_accessor_as_vec3(p_state, narr, true);
  2157. }
  2158. Vector<real_t> tarr = array_morph[Mesh::ARRAY_TANGENT];
  2159. if (tarr.size()) {
  2160. const int ret_size = tarr.size() / 4;
  2161. Vector<Vector3> attribs;
  2162. attribs.resize(ret_size);
  2163. for (int i = 0; i < ret_size; i++) {
  2164. Vector3 vec3;
  2165. vec3.x = tarr[(i * 4) + 0];
  2166. vec3.y = tarr[(i * 4) + 1];
  2167. vec3.z = tarr[(i * 4) + 2];
  2168. }
  2169. t["TANGENT"] = _encode_accessor_as_vec3(p_state, attribs, true);
  2170. }
  2171. targets.push_back(t);
  2172. }
  2173. }
  2174. Variant v;
  2175. if (surface_i < instance_materials.size()) {
  2176. v = instance_materials.get(surface_i);
  2177. }
  2178. Ref<Material> mat = v;
  2179. if (!mat.is_valid()) {
  2180. mat = import_mesh->get_surface_material(surface_i);
  2181. }
  2182. if (mat.is_valid()) {
  2183. HashMap<Ref<Material>, GLTFMaterialIndex>::Iterator material_cache_i = p_state->material_cache.find(mat);
  2184. if (material_cache_i && material_cache_i->value != -1) {
  2185. primitive["material"] = material_cache_i->value;
  2186. } else {
  2187. GLTFMaterialIndex mat_i = p_state->materials.size();
  2188. p_state->materials.push_back(mat);
  2189. primitive["material"] = mat_i;
  2190. p_state->material_cache.insert(mat, mat_i);
  2191. }
  2192. }
  2193. if (targets.size()) {
  2194. primitive["targets"] = targets;
  2195. }
  2196. primitives.push_back(primitive);
  2197. }
  2198. Dictionary e;
  2199. e["targetNames"] = target_names;
  2200. weights.resize(target_names.size());
  2201. for (int name_i = 0; name_i < target_names.size(); name_i++) {
  2202. real_t weight = 0.0;
  2203. if (name_i < p_state->meshes.write[gltf_mesh_i]->get_blend_weights().size()) {
  2204. weight = p_state->meshes.write[gltf_mesh_i]->get_blend_weights()[name_i];
  2205. }
  2206. weights[name_i] = weight;
  2207. }
  2208. if (weights.size()) {
  2209. gltf_mesh["weights"] = weights;
  2210. }
  2211. ERR_FAIL_COND_V(target_names.size() != weights.size(), FAILED);
  2212. gltf_mesh["extras"] = e;
  2213. gltf_mesh["primitives"] = primitives;
  2214. meshes.push_back(gltf_mesh);
  2215. }
  2216. if (!meshes.size()) {
  2217. return OK;
  2218. }
  2219. p_state->json["meshes"] = meshes;
  2220. print_verbose("glTF: Total meshes: " + itos(meshes.size()));
  2221. return OK;
  2222. }
  2223. Error GLTFDocument::_parse_meshes(Ref<GLTFState> p_state) {
  2224. if (!p_state->json.has("meshes")) {
  2225. return OK;
  2226. }
  2227. Array meshes = p_state->json["meshes"];
  2228. for (GLTFMeshIndex i = 0; i < meshes.size(); i++) {
  2229. print_verbose("glTF: Parsing mesh: " + itos(i));
  2230. Dictionary d = meshes[i];
  2231. Ref<GLTFMesh> mesh;
  2232. mesh.instantiate();
  2233. bool has_vertex_color = false;
  2234. ERR_FAIL_COND_V(!d.has("primitives"), ERR_PARSE_ERROR);
  2235. Array primitives = d["primitives"];
  2236. const Dictionary &extras = d.has("extras") ? (Dictionary)d["extras"] : Dictionary();
  2237. Ref<ImporterMesh> import_mesh;
  2238. import_mesh.instantiate();
  2239. String mesh_name = "mesh";
  2240. if (d.has("name") && !String(d["name"]).is_empty()) {
  2241. mesh_name = d["name"];
  2242. mesh->set_original_name(mesh_name);
  2243. }
  2244. import_mesh->set_name(_gen_unique_name(p_state, vformat("%s_%s", p_state->scene_name, mesh_name)));
  2245. mesh->set_name(import_mesh->get_name());
  2246. for (int j = 0; j < primitives.size(); j++) {
  2247. uint64_t flags = RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES;
  2248. Dictionary p = primitives[j];
  2249. Array array;
  2250. array.resize(Mesh::ARRAY_MAX);
  2251. ERR_FAIL_COND_V(!p.has("attributes"), ERR_PARSE_ERROR);
  2252. Dictionary a = p["attributes"];
  2253. Mesh::PrimitiveType primitive = Mesh::PRIMITIVE_TRIANGLES;
  2254. if (p.has("mode")) {
  2255. const int mode = p["mode"];
  2256. ERR_FAIL_INDEX_V(mode, 7, ERR_FILE_CORRUPT);
  2257. // Convert mesh.primitive.mode to Godot Mesh enum. See:
  2258. // https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html#_mesh_primitive_mode
  2259. static const Mesh::PrimitiveType primitives2[7] = {
  2260. Mesh::PRIMITIVE_POINTS, // 0 POINTS
  2261. Mesh::PRIMITIVE_LINES, // 1 LINES
  2262. Mesh::PRIMITIVE_LINES, // 2 LINE_LOOP; loop not supported, should be converted
  2263. Mesh::PRIMITIVE_LINE_STRIP, // 3 LINE_STRIP
  2264. Mesh::PRIMITIVE_TRIANGLES, // 4 TRIANGLES
  2265. Mesh::PRIMITIVE_TRIANGLE_STRIP, // 5 TRIANGLE_STRIP
  2266. Mesh::PRIMITIVE_TRIANGLES, // 6 TRIANGLE_FAN fan not supported, should be converted
  2267. // TODO: Line loop and triangle fan are not supported and need to be converted to lines and triangles.
  2268. };
  2269. primitive = primitives2[mode];
  2270. }
  2271. ERR_FAIL_COND_V(!a.has("POSITION"), ERR_PARSE_ERROR);
  2272. int32_t vertex_num = 0;
  2273. if (a.has("POSITION")) {
  2274. PackedVector3Array vertices = _decode_accessor_as_vec3(p_state, a["POSITION"], true);
  2275. array[Mesh::ARRAY_VERTEX] = vertices;
  2276. vertex_num = vertices.size();
  2277. }
  2278. if (a.has("NORMAL")) {
  2279. array[Mesh::ARRAY_NORMAL] = _decode_accessor_as_vec3(p_state, a["NORMAL"], true);
  2280. }
  2281. if (a.has("TANGENT")) {
  2282. array[Mesh::ARRAY_TANGENT] = _decode_accessor_as_floats(p_state, a["TANGENT"], true);
  2283. }
  2284. if (a.has("TEXCOORD_0")) {
  2285. array[Mesh::ARRAY_TEX_UV] = _decode_accessor_as_vec2(p_state, a["TEXCOORD_0"], true);
  2286. }
  2287. if (a.has("TEXCOORD_1")) {
  2288. array[Mesh::ARRAY_TEX_UV2] = _decode_accessor_as_vec2(p_state, a["TEXCOORD_1"], true);
  2289. }
  2290. for (int custom_i = 0; custom_i < 3; custom_i++) {
  2291. Vector<float> cur_custom;
  2292. Vector<Vector2> texcoord_first;
  2293. Vector<Vector2> texcoord_second;
  2294. int texcoord_i = 2 + 2 * custom_i;
  2295. String gltf_texcoord_key = vformat("TEXCOORD_%d", texcoord_i);
  2296. int num_channels = 0;
  2297. if (a.has(gltf_texcoord_key)) {
  2298. texcoord_first = _decode_accessor_as_vec2(p_state, a[gltf_texcoord_key], true);
  2299. num_channels = 2;
  2300. }
  2301. gltf_texcoord_key = vformat("TEXCOORD_%d", texcoord_i + 1);
  2302. if (a.has(gltf_texcoord_key)) {
  2303. texcoord_second = _decode_accessor_as_vec2(p_state, a[gltf_texcoord_key], true);
  2304. num_channels = 4;
  2305. }
  2306. if (!num_channels) {
  2307. break;
  2308. }
  2309. if (num_channels == 2 || num_channels == 4) {
  2310. cur_custom.resize(vertex_num * num_channels);
  2311. for (int32_t uv_i = 0; uv_i < texcoord_first.size() && uv_i < vertex_num; uv_i++) {
  2312. cur_custom.write[uv_i * num_channels + 0] = texcoord_first[uv_i].x;
  2313. cur_custom.write[uv_i * num_channels + 1] = texcoord_first[uv_i].y;
  2314. }
  2315. // Vector.resize seems to not zero-initialize. Ensure all unused elements are 0:
  2316. for (int32_t uv_i = texcoord_first.size(); uv_i < vertex_num; uv_i++) {
  2317. cur_custom.write[uv_i * num_channels + 0] = 0;
  2318. cur_custom.write[uv_i * num_channels + 1] = 0;
  2319. }
  2320. }
  2321. if (num_channels == 4) {
  2322. for (int32_t uv_i = 0; uv_i < texcoord_second.size() && uv_i < vertex_num; uv_i++) {
  2323. // num_channels must be 4
  2324. cur_custom.write[uv_i * num_channels + 2] = texcoord_second[uv_i].x;
  2325. cur_custom.write[uv_i * num_channels + 3] = texcoord_second[uv_i].y;
  2326. }
  2327. // Vector.resize seems to not zero-initialize. Ensure all unused elements are 0:
  2328. for (int32_t uv_i = texcoord_second.size(); uv_i < vertex_num; uv_i++) {
  2329. cur_custom.write[uv_i * num_channels + 2] = 0;
  2330. cur_custom.write[uv_i * num_channels + 3] = 0;
  2331. }
  2332. }
  2333. if (cur_custom.size() > 0) {
  2334. array[Mesh::ARRAY_CUSTOM0 + custom_i] = cur_custom;
  2335. int custom_shift = Mesh::ARRAY_FORMAT_CUSTOM0_SHIFT + custom_i * Mesh::ARRAY_FORMAT_CUSTOM_BITS;
  2336. if (num_channels == 2) {
  2337. flags |= Mesh::ARRAY_CUSTOM_RG_FLOAT << custom_shift;
  2338. } else {
  2339. flags |= Mesh::ARRAY_CUSTOM_RGBA_FLOAT << custom_shift;
  2340. }
  2341. }
  2342. }
  2343. if (a.has("COLOR_0")) {
  2344. array[Mesh::ARRAY_COLOR] = _decode_accessor_as_color(p_state, a["COLOR_0"], true);
  2345. has_vertex_color = true;
  2346. }
  2347. if (a.has("JOINTS_0") && !a.has("JOINTS_1")) {
  2348. array[Mesh::ARRAY_BONES] = _decode_accessor_as_ints(p_state, a["JOINTS_0"], true);
  2349. } else if (a.has("JOINTS_0") && a.has("JOINTS_1")) {
  2350. PackedInt32Array joints_0 = _decode_accessor_as_ints(p_state, a["JOINTS_0"], true);
  2351. PackedInt32Array joints_1 = _decode_accessor_as_ints(p_state, a["JOINTS_1"], true);
  2352. ERR_FAIL_COND_V(joints_0.size() != joints_1.size(), ERR_INVALID_DATA);
  2353. int32_t weight_8_count = JOINT_GROUP_SIZE * 2;
  2354. Vector<int> joints;
  2355. joints.resize(vertex_num * weight_8_count);
  2356. for (int32_t vertex_i = 0; vertex_i < vertex_num; vertex_i++) {
  2357. joints.write[vertex_i * weight_8_count + 0] = joints_0[vertex_i * JOINT_GROUP_SIZE + 0];
  2358. joints.write[vertex_i * weight_8_count + 1] = joints_0[vertex_i * JOINT_GROUP_SIZE + 1];
  2359. joints.write[vertex_i * weight_8_count + 2] = joints_0[vertex_i * JOINT_GROUP_SIZE + 2];
  2360. joints.write[vertex_i * weight_8_count + 3] = joints_0[vertex_i * JOINT_GROUP_SIZE + 3];
  2361. joints.write[vertex_i * weight_8_count + 4] = joints_1[vertex_i * JOINT_GROUP_SIZE + 0];
  2362. joints.write[vertex_i * weight_8_count + 5] = joints_1[vertex_i * JOINT_GROUP_SIZE + 1];
  2363. joints.write[vertex_i * weight_8_count + 6] = joints_1[vertex_i * JOINT_GROUP_SIZE + 2];
  2364. joints.write[vertex_i * weight_8_count + 7] = joints_1[vertex_i * JOINT_GROUP_SIZE + 3];
  2365. }
  2366. array[Mesh::ARRAY_BONES] = joints;
  2367. }
  2368. if (a.has("WEIGHTS_0") && !a.has("WEIGHTS_1")) {
  2369. Vector<float> weights = _decode_accessor_as_floats(p_state, a["WEIGHTS_0"], true);
  2370. { //gltf does not seem to normalize the weights for some reason..
  2371. int wc = weights.size();
  2372. float *w = weights.ptrw();
  2373. for (int k = 0; k < wc; k += 4) {
  2374. float total = 0.0;
  2375. total += w[k + 0];
  2376. total += w[k + 1];
  2377. total += w[k + 2];
  2378. total += w[k + 3];
  2379. if (total > 0.0) {
  2380. w[k + 0] /= total;
  2381. w[k + 1] /= total;
  2382. w[k + 2] /= total;
  2383. w[k + 3] /= total;
  2384. }
  2385. }
  2386. }
  2387. array[Mesh::ARRAY_WEIGHTS] = weights;
  2388. } else if (a.has("WEIGHTS_0") && a.has("WEIGHTS_1")) {
  2389. Vector<float> weights_0 = _decode_accessor_as_floats(p_state, a["WEIGHTS_0"], true);
  2390. Vector<float> weights_1 = _decode_accessor_as_floats(p_state, a["WEIGHTS_1"], true);
  2391. Vector<float> weights;
  2392. ERR_FAIL_COND_V(weights_0.size() != weights_1.size(), ERR_INVALID_DATA);
  2393. int32_t weight_8_count = JOINT_GROUP_SIZE * 2;
  2394. weights.resize(vertex_num * weight_8_count);
  2395. for (int32_t vertex_i = 0; vertex_i < vertex_num; vertex_i++) {
  2396. weights.write[vertex_i * weight_8_count + 0] = weights_0[vertex_i * JOINT_GROUP_SIZE + 0];
  2397. weights.write[vertex_i * weight_8_count + 1] = weights_0[vertex_i * JOINT_GROUP_SIZE + 1];
  2398. weights.write[vertex_i * weight_8_count + 2] = weights_0[vertex_i * JOINT_GROUP_SIZE + 2];
  2399. weights.write[vertex_i * weight_8_count + 3] = weights_0[vertex_i * JOINT_GROUP_SIZE + 3];
  2400. weights.write[vertex_i * weight_8_count + 4] = weights_1[vertex_i * JOINT_GROUP_SIZE + 0];
  2401. weights.write[vertex_i * weight_8_count + 5] = weights_1[vertex_i * JOINT_GROUP_SIZE + 1];
  2402. weights.write[vertex_i * weight_8_count + 6] = weights_1[vertex_i * JOINT_GROUP_SIZE + 2];
  2403. weights.write[vertex_i * weight_8_count + 7] = weights_1[vertex_i * JOINT_GROUP_SIZE + 3];
  2404. }
  2405. { //gltf does not seem to normalize the weights for some reason..
  2406. int wc = weights.size();
  2407. float *w = weights.ptrw();
  2408. for (int k = 0; k < wc; k += weight_8_count) {
  2409. float total = 0.0;
  2410. total += w[k + 0];
  2411. total += w[k + 1];
  2412. total += w[k + 2];
  2413. total += w[k + 3];
  2414. total += w[k + 4];
  2415. total += w[k + 5];
  2416. total += w[k + 6];
  2417. total += w[k + 7];
  2418. if (total > 0.0) {
  2419. w[k + 0] /= total;
  2420. w[k + 1] /= total;
  2421. w[k + 2] /= total;
  2422. w[k + 3] /= total;
  2423. w[k + 4] /= total;
  2424. w[k + 5] /= total;
  2425. w[k + 6] /= total;
  2426. w[k + 7] /= total;
  2427. }
  2428. }
  2429. }
  2430. array[Mesh::ARRAY_WEIGHTS] = weights;
  2431. }
  2432. if (p.has("indices")) {
  2433. Vector<int> indices = _decode_accessor_as_ints(p_state, p["indices"], false);
  2434. if (primitive == Mesh::PRIMITIVE_TRIANGLES) {
  2435. //swap around indices, convert ccw to cw for front face
  2436. const int is = indices.size();
  2437. int *w = indices.ptrw();
  2438. for (int k = 0; k < is; k += 3) {
  2439. SWAP(w[k + 1], w[k + 2]);
  2440. }
  2441. }
  2442. array[Mesh::ARRAY_INDEX] = indices;
  2443. } else if (primitive == Mesh::PRIMITIVE_TRIANGLES) {
  2444. //generate indices because they need to be swapped for CW/CCW
  2445. const Vector<Vector3> &vertices = array[Mesh::ARRAY_VERTEX];
  2446. ERR_FAIL_COND_V(vertices.is_empty(), ERR_PARSE_ERROR);
  2447. Vector<int> indices;
  2448. const int vs = vertices.size();
  2449. indices.resize(vs);
  2450. {
  2451. int *w = indices.ptrw();
  2452. for (int k = 0; k < vs; k += 3) {
  2453. w[k] = k;
  2454. w[k + 1] = k + 2;
  2455. w[k + 2] = k + 1;
  2456. }
  2457. }
  2458. array[Mesh::ARRAY_INDEX] = indices;
  2459. }
  2460. bool generate_tangents = p_state->force_generate_tangents && (primitive == Mesh::PRIMITIVE_TRIANGLES && !a.has("TANGENT") && a.has("NORMAL"));
  2461. if (generate_tangents && !a.has("TEXCOORD_0")) {
  2462. // If we don't have UVs we provide a dummy tangent array.
  2463. Vector<float> tangents;
  2464. tangents.resize(vertex_num * 4);
  2465. float *tangentsw = tangents.ptrw();
  2466. Vector<Vector3> normals = array[Mesh::ARRAY_NORMAL];
  2467. for (int k = 0; k < vertex_num; k++) {
  2468. Vector3 tan = Vector3(0.0, 1.0, 0.0).cross(normals[k]);
  2469. tangentsw[k * 4 + 0] = tan.x;
  2470. tangentsw[k * 4 + 1] = tan.y;
  2471. tangentsw[k * 4 + 2] = tan.z;
  2472. tangentsw[k * 4 + 3] = 1.0;
  2473. }
  2474. array[Mesh::ARRAY_TANGENT] = tangents;
  2475. }
  2476. if (p_state->force_disable_compression || !a.has("POSITION") || !a.has("NORMAL") || p.has("targets") || (a.has("JOINTS_0") || a.has("JOINTS_1"))) {
  2477. flags &= ~RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES;
  2478. }
  2479. Ref<SurfaceTool> mesh_surface_tool;
  2480. mesh_surface_tool.instantiate();
  2481. mesh_surface_tool->create_from_triangle_arrays(array);
  2482. if (a.has("JOINTS_0") && a.has("JOINTS_1")) {
  2483. mesh_surface_tool->set_skin_weight_count(SurfaceTool::SKIN_8_WEIGHTS);
  2484. }
  2485. mesh_surface_tool->index();
  2486. if (generate_tangents && a.has("TEXCOORD_0")) {
  2487. //must generate mikktspace tangents.. ergh..
  2488. mesh_surface_tool->generate_tangents();
  2489. }
  2490. array = mesh_surface_tool->commit_to_arrays();
  2491. Array morphs;
  2492. //blend shapes
  2493. if (p.has("targets")) {
  2494. print_verbose("glTF: Mesh has targets");
  2495. const Array &targets = p["targets"];
  2496. //ideally BLEND_SHAPE_MODE_RELATIVE since gltf2 stores in displacement
  2497. //but it could require a larger refactor?
  2498. import_mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
  2499. if (j == 0) {
  2500. const Array &target_names = extras.has("targetNames") ? (Array)extras["targetNames"] : Array();
  2501. for (int k = 0; k < targets.size(); k++) {
  2502. String bs_name;
  2503. if (k < target_names.size() && ((String)target_names[k]).size() != 0) {
  2504. bs_name = (String)target_names[k];
  2505. } else {
  2506. bs_name = String("morph_") + itos(k);
  2507. }
  2508. import_mesh->add_blend_shape(bs_name);
  2509. }
  2510. }
  2511. for (int k = 0; k < targets.size(); k++) {
  2512. const Dictionary &t = targets[k];
  2513. Array array_copy;
  2514. array_copy.resize(Mesh::ARRAY_MAX);
  2515. for (int l = 0; l < Mesh::ARRAY_MAX; l++) {
  2516. array_copy[l] = array[l];
  2517. }
  2518. if (t.has("POSITION")) {
  2519. Vector<Vector3> varr = _decode_accessor_as_vec3(p_state, t["POSITION"], true);
  2520. const Vector<Vector3> src_varr = array[Mesh::ARRAY_VERTEX];
  2521. const int size = src_varr.size();
  2522. ERR_FAIL_COND_V(size == 0, ERR_PARSE_ERROR);
  2523. {
  2524. const int max_idx = varr.size();
  2525. varr.resize(size);
  2526. Vector3 *w_varr = varr.ptrw();
  2527. const Vector3 *r_varr = varr.ptr();
  2528. const Vector3 *r_src_varr = src_varr.ptr();
  2529. for (int l = 0; l < size; l++) {
  2530. if (l < max_idx) {
  2531. w_varr[l] = r_varr[l] + r_src_varr[l];
  2532. } else {
  2533. w_varr[l] = r_src_varr[l];
  2534. }
  2535. }
  2536. }
  2537. array_copy[Mesh::ARRAY_VERTEX] = varr;
  2538. }
  2539. if (t.has("NORMAL")) {
  2540. Vector<Vector3> narr = _decode_accessor_as_vec3(p_state, t["NORMAL"], true);
  2541. const Vector<Vector3> src_narr = array[Mesh::ARRAY_NORMAL];
  2542. int size = src_narr.size();
  2543. ERR_FAIL_COND_V(size == 0, ERR_PARSE_ERROR);
  2544. {
  2545. int max_idx = narr.size();
  2546. narr.resize(size);
  2547. Vector3 *w_narr = narr.ptrw();
  2548. const Vector3 *r_narr = narr.ptr();
  2549. const Vector3 *r_src_narr = src_narr.ptr();
  2550. for (int l = 0; l < size; l++) {
  2551. if (l < max_idx) {
  2552. w_narr[l] = r_narr[l] + r_src_narr[l];
  2553. } else {
  2554. w_narr[l] = r_src_narr[l];
  2555. }
  2556. }
  2557. }
  2558. array_copy[Mesh::ARRAY_NORMAL] = narr;
  2559. }
  2560. if (t.has("TANGENT")) {
  2561. const Vector<Vector3> tangents_v3 = _decode_accessor_as_vec3(p_state, t["TANGENT"], true);
  2562. const Vector<float> src_tangents = array[Mesh::ARRAY_TANGENT];
  2563. ERR_FAIL_COND_V(src_tangents.is_empty(), ERR_PARSE_ERROR);
  2564. Vector<float> tangents_v4;
  2565. {
  2566. int max_idx = tangents_v3.size();
  2567. int size4 = src_tangents.size();
  2568. tangents_v4.resize(size4);
  2569. float *w4 = tangents_v4.ptrw();
  2570. const Vector3 *r3 = tangents_v3.ptr();
  2571. const float *r4 = src_tangents.ptr();
  2572. for (int l = 0; l < size4 / 4; l++) {
  2573. if (l < max_idx) {
  2574. w4[l * 4 + 0] = r3[l].x + r4[l * 4 + 0];
  2575. w4[l * 4 + 1] = r3[l].y + r4[l * 4 + 1];
  2576. w4[l * 4 + 2] = r3[l].z + r4[l * 4 + 2];
  2577. } else {
  2578. w4[l * 4 + 0] = r4[l * 4 + 0];
  2579. w4[l * 4 + 1] = r4[l * 4 + 1];
  2580. w4[l * 4 + 2] = r4[l * 4 + 2];
  2581. }
  2582. w4[l * 4 + 3] = r4[l * 4 + 3]; //copy flip value
  2583. }
  2584. }
  2585. array_copy[Mesh::ARRAY_TANGENT] = tangents_v4;
  2586. }
  2587. Ref<SurfaceTool> blend_surface_tool;
  2588. blend_surface_tool.instantiate();
  2589. blend_surface_tool->create_from_triangle_arrays(array_copy);
  2590. if (a.has("JOINTS_0") && a.has("JOINTS_1")) {
  2591. blend_surface_tool->set_skin_weight_count(SurfaceTool::SKIN_8_WEIGHTS);
  2592. }
  2593. blend_surface_tool->index();
  2594. if (generate_tangents) {
  2595. blend_surface_tool->generate_tangents();
  2596. }
  2597. array_copy = blend_surface_tool->commit_to_arrays();
  2598. // Enforce blend shape mask array format
  2599. for (int l = 0; l < Mesh::ARRAY_MAX; l++) {
  2600. if (!(Mesh::ARRAY_FORMAT_BLEND_SHAPE_MASK & (1ULL << l))) {
  2601. array_copy[l] = Variant();
  2602. }
  2603. }
  2604. morphs.push_back(array_copy);
  2605. }
  2606. }
  2607. Ref<Material> mat;
  2608. String mat_name;
  2609. if (!p_state->discard_meshes_and_materials) {
  2610. if (p.has("material")) {
  2611. const int material = p["material"];
  2612. ERR_FAIL_INDEX_V(material, p_state->materials.size(), ERR_FILE_CORRUPT);
  2613. Ref<Material> mat3d = p_state->materials[material];
  2614. ERR_FAIL_NULL_V(mat3d, ERR_FILE_CORRUPT);
  2615. Ref<BaseMaterial3D> base_material = mat3d;
  2616. if (has_vertex_color && base_material.is_valid()) {
  2617. base_material->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  2618. }
  2619. mat = mat3d;
  2620. } else {
  2621. Ref<StandardMaterial3D> mat3d;
  2622. mat3d.instantiate();
  2623. if (has_vertex_color) {
  2624. mat3d->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  2625. }
  2626. mat = mat3d;
  2627. }
  2628. ERR_FAIL_NULL_V(mat, ERR_FILE_CORRUPT);
  2629. mat_name = mat->get_name();
  2630. }
  2631. import_mesh->add_surface(primitive, array, morphs,
  2632. Dictionary(), mat, mat_name, flags);
  2633. }
  2634. Vector<float> blend_weights;
  2635. blend_weights.resize(import_mesh->get_blend_shape_count());
  2636. for (int32_t weight_i = 0; weight_i < blend_weights.size(); weight_i++) {
  2637. blend_weights.write[weight_i] = 0.0f;
  2638. }
  2639. if (d.has("weights")) {
  2640. const Array &weights = d["weights"];
  2641. for (int j = 0; j < weights.size(); j++) {
  2642. if (j >= blend_weights.size()) {
  2643. break;
  2644. }
  2645. blend_weights.write[j] = weights[j];
  2646. }
  2647. }
  2648. mesh->set_blend_weights(blend_weights);
  2649. mesh->set_mesh(import_mesh);
  2650. p_state->meshes.push_back(mesh);
  2651. }
  2652. print_verbose("glTF: Total meshes: " + itos(p_state->meshes.size()));
  2653. return OK;
  2654. }
  2655. void GLTFDocument::set_naming_version(int p_version) {
  2656. _naming_version = p_version;
  2657. }
  2658. int GLTFDocument::get_naming_version() const {
  2659. return _naming_version;
  2660. }
  2661. void GLTFDocument::set_image_format(const String &p_image_format) {
  2662. _image_format = p_image_format;
  2663. }
  2664. String GLTFDocument::get_image_format() const {
  2665. return _image_format;
  2666. }
  2667. void GLTFDocument::set_lossy_quality(float p_lossy_quality) {
  2668. _lossy_quality = p_lossy_quality;
  2669. }
  2670. float GLTFDocument::get_lossy_quality() const {
  2671. return _lossy_quality;
  2672. }
  2673. Error GLTFDocument::_serialize_images(Ref<GLTFState> p_state) {
  2674. Array images;
  2675. // Check if any extension wants to be the image saver.
  2676. _image_save_extension = Ref<GLTFDocumentExtension>();
  2677. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  2678. ERR_CONTINUE(ext.is_null());
  2679. Vector<String> image_formats = ext->get_saveable_image_formats();
  2680. if (image_formats.has(_image_format)) {
  2681. _image_save_extension = ext;
  2682. break;
  2683. }
  2684. }
  2685. // Serialize every image in the state's images array.
  2686. for (int i = 0; i < p_state->images.size(); i++) {
  2687. Dictionary image_dict;
  2688. ERR_CONTINUE(p_state->images[i].is_null());
  2689. Ref<Image> image = p_state->images[i]->get_image();
  2690. ERR_CONTINUE(image.is_null());
  2691. if (image->is_compressed()) {
  2692. image->decompress();
  2693. ERR_FAIL_COND_V_MSG(image->is_compressed(), ERR_INVALID_DATA, "GLTF: Image was compressed, but could not be decompressed.");
  2694. }
  2695. if (p_state->filename.to_lower().ends_with("gltf")) {
  2696. String img_name = p_state->images[i]->get_name();
  2697. if (img_name.is_empty()) {
  2698. img_name = itos(i);
  2699. }
  2700. img_name = _gen_unique_name(p_state, img_name);
  2701. img_name = img_name.pad_zeros(3);
  2702. String relative_texture_dir = "textures";
  2703. String full_texture_dir = p_state->base_path.path_join(relative_texture_dir);
  2704. Ref<DirAccess> da = DirAccess::open(p_state->base_path);
  2705. ERR_FAIL_COND_V(da.is_null(), FAILED);
  2706. if (!da->dir_exists(full_texture_dir)) {
  2707. da->make_dir(full_texture_dir);
  2708. }
  2709. if (_image_save_extension.is_valid()) {
  2710. img_name = img_name + _image_save_extension->get_image_file_extension();
  2711. Error err = _image_save_extension->save_image_at_path(p_state, image, full_texture_dir.path_join(img_name), _image_format, _lossy_quality);
  2712. ERR_FAIL_COND_V_MSG(err != OK, err, "GLTF: Failed to save image in '" + _image_format + "' format as a separate file.");
  2713. } else if (_image_format == "PNG") {
  2714. img_name = img_name + ".png";
  2715. image->save_png(full_texture_dir.path_join(img_name));
  2716. } else if (_image_format == "JPEG") {
  2717. img_name = img_name + ".jpg";
  2718. image->save_jpg(full_texture_dir.path_join(img_name), _lossy_quality);
  2719. } else {
  2720. ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "GLTF: Unknown image format '" + _image_format + "'.");
  2721. }
  2722. image_dict["uri"] = relative_texture_dir.path_join(img_name).uri_encode();
  2723. } else {
  2724. GLTFBufferViewIndex bvi;
  2725. Ref<GLTFBufferView> bv;
  2726. bv.instantiate();
  2727. const GLTFBufferIndex bi = 0;
  2728. bv->buffer = bi;
  2729. bv->byte_offset = p_state->buffers[bi].size();
  2730. ERR_FAIL_INDEX_V(bi, p_state->buffers.size(), ERR_PARAMETER_RANGE_ERROR);
  2731. Vector<uint8_t> buffer;
  2732. Ref<ImageTexture> img_tex = image;
  2733. if (img_tex.is_valid()) {
  2734. image = img_tex->get_image();
  2735. }
  2736. // Save in various image formats. Note that if the format is "None",
  2737. // the state's images will be empty, so this code will not be reached.
  2738. if (_image_save_extension.is_valid()) {
  2739. buffer = _image_save_extension->serialize_image_to_bytes(p_state, image, image_dict, _image_format, _lossy_quality);
  2740. } else if (_image_format == "PNG") {
  2741. buffer = image->save_png_to_buffer();
  2742. image_dict["mimeType"] = "image/png";
  2743. } else if (_image_format == "JPEG") {
  2744. buffer = image->save_jpg_to_buffer(_lossy_quality);
  2745. image_dict["mimeType"] = "image/jpeg";
  2746. } else {
  2747. ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "GLTF: Unknown image format '" + _image_format + "'.");
  2748. }
  2749. ERR_FAIL_COND_V_MSG(buffer.is_empty(), ERR_INVALID_DATA, "GLTF: Failed to save image in '" + _image_format + "' format.");
  2750. bv->byte_length = buffer.size();
  2751. p_state->buffers.write[bi].resize(p_state->buffers[bi].size() + bv->byte_length);
  2752. memcpy(&p_state->buffers.write[bi].write[bv->byte_offset], buffer.ptr(), buffer.size());
  2753. ERR_FAIL_COND_V(bv->byte_offset + bv->byte_length > p_state->buffers[bi].size(), ERR_FILE_CORRUPT);
  2754. p_state->buffer_views.push_back(bv);
  2755. bvi = p_state->buffer_views.size() - 1;
  2756. image_dict["bufferView"] = bvi;
  2757. }
  2758. images.push_back(image_dict);
  2759. }
  2760. print_verbose("Total images: " + itos(p_state->images.size()));
  2761. if (!images.size()) {
  2762. return OK;
  2763. }
  2764. p_state->json["images"] = images;
  2765. return OK;
  2766. }
  2767. Ref<Image> GLTFDocument::_parse_image_bytes_into_image(Ref<GLTFState> p_state, const Vector<uint8_t> &p_bytes, const String &p_mime_type, int p_index, String &r_file_extension) {
  2768. Ref<Image> r_image;
  2769. r_image.instantiate();
  2770. // Check if any GLTFDocumentExtensions want to import this data as an image.
  2771. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  2772. ERR_CONTINUE(ext.is_null());
  2773. Error err = ext->parse_image_data(p_state, p_bytes, p_mime_type, r_image);
  2774. ERR_CONTINUE_MSG(err != OK, "GLTF: Encountered error " + itos(err) + " when parsing image " + itos(p_index) + " in file " + p_state->filename + ". Continuing.");
  2775. if (!r_image->is_empty()) {
  2776. r_file_extension = ext->get_image_file_extension();
  2777. return r_image;
  2778. }
  2779. }
  2780. // If no extension wanted to import this data as an image, try to load a PNG or JPEG.
  2781. // First we honor the mime types if they were defined.
  2782. if (p_mime_type == "image/png") { // Load buffer as PNG.
  2783. r_image->load_png_from_buffer(p_bytes);
  2784. r_file_extension = ".png";
  2785. } else if (p_mime_type == "image/jpeg") { // Loader buffer as JPEG.
  2786. r_image->load_jpg_from_buffer(p_bytes);
  2787. r_file_extension = ".jpg";
  2788. }
  2789. // If we didn't pass the above tests, we attempt loading as PNG and then JPEG directly.
  2790. // This covers URIs with base64-encoded data with application/* type but
  2791. // no optional mimeType property, or bufferViews with a bogus mimeType
  2792. // (e.g. `image/jpeg` but the data is actually PNG).
  2793. // That's not *exactly* what the spec mandates but this lets us be
  2794. // lenient with bogus glb files which do exist in production.
  2795. if (r_image->is_empty()) { // Try PNG first.
  2796. r_image->load_png_from_buffer(p_bytes);
  2797. }
  2798. if (r_image->is_empty()) { // And then JPEG.
  2799. r_image->load_jpg_from_buffer(p_bytes);
  2800. }
  2801. // If it still can't be loaded, give up and insert an empty image as placeholder.
  2802. if (r_image->is_empty()) {
  2803. ERR_PRINT(vformat("glTF: Couldn't load image index '%d' with its given mimetype: %s.", p_index, p_mime_type));
  2804. }
  2805. return r_image;
  2806. }
  2807. void GLTFDocument::_parse_image_save_image(Ref<GLTFState> p_state, const Vector<uint8_t> &p_bytes, const String &p_file_extension, int p_index, Ref<Image> p_image) {
  2808. GLTFState::GLTFHandleBinary handling = GLTFState::GLTFHandleBinary(p_state->handle_binary_image);
  2809. if (p_image->is_empty() || handling == GLTFState::GLTFHandleBinary::HANDLE_BINARY_DISCARD_TEXTURES) {
  2810. p_state->images.push_back(Ref<Texture2D>());
  2811. p_state->source_images.push_back(Ref<Image>());
  2812. return;
  2813. }
  2814. #ifdef TOOLS_ENABLED
  2815. if (Engine::get_singleton()->is_editor_hint() && handling == GLTFState::GLTFHandleBinary::HANDLE_BINARY_EXTRACT_TEXTURES) {
  2816. if (p_state->base_path.is_empty()) {
  2817. p_state->images.push_back(Ref<Texture2D>());
  2818. p_state->source_images.push_back(Ref<Image>());
  2819. } else if (p_image->get_name().is_empty()) {
  2820. WARN_PRINT(vformat("glTF: Image index '%d' couldn't be named. Skipping it.", p_index));
  2821. p_state->images.push_back(Ref<Texture2D>());
  2822. p_state->source_images.push_back(Ref<Image>());
  2823. } else {
  2824. bool must_import = true;
  2825. Vector<uint8_t> img_data = p_image->get_data();
  2826. Dictionary generator_parameters;
  2827. String file_path = p_state->get_base_path().path_join(p_state->filename.get_basename() + "_" + p_image->get_name());
  2828. file_path += p_file_extension.is_empty() ? ".png" : p_file_extension;
  2829. if (FileAccess::exists(file_path + ".import")) {
  2830. Ref<ConfigFile> config;
  2831. config.instantiate();
  2832. config->load(file_path + ".import");
  2833. if (config->has_section_key("remap", "generator_parameters")) {
  2834. generator_parameters = (Dictionary)config->get_value("remap", "generator_parameters");
  2835. }
  2836. if (!generator_parameters.has("md5")) {
  2837. must_import = false; // Didn't come from a gltf document; don't overwrite.
  2838. }
  2839. }
  2840. if (must_import) {
  2841. String existing_md5 = generator_parameters["md5"];
  2842. unsigned char md5_hash[16];
  2843. CryptoCore::md5(img_data.ptr(), img_data.size(), md5_hash);
  2844. String new_md5 = String::hex_encode_buffer(md5_hash, 16);
  2845. generator_parameters["md5"] = new_md5;
  2846. if (new_md5 == existing_md5) {
  2847. must_import = false;
  2848. }
  2849. }
  2850. if (must_import) {
  2851. Error err = OK;
  2852. if (p_file_extension.is_empty()) {
  2853. // If a file extension was not specified, save the image data to a PNG file.
  2854. err = p_image->save_png(file_path);
  2855. ERR_FAIL_COND(err != OK);
  2856. } else {
  2857. // If a file extension was specified, save the original bytes to a file with that extension.
  2858. Ref<FileAccess> file = FileAccess::open(file_path, FileAccess::WRITE, &err);
  2859. ERR_FAIL_COND(err != OK);
  2860. file->store_buffer(p_bytes);
  2861. file->close();
  2862. }
  2863. // ResourceLoader::import will crash if not is_editor_hint(), so this case is protected above and will fall through to uncompressed.
  2864. HashMap<StringName, Variant> custom_options;
  2865. custom_options[SNAME("mipmaps/generate")] = true;
  2866. // Will only use project settings defaults if custom_importer is empty.
  2867. EditorFileSystem::get_singleton()->update_file(file_path);
  2868. EditorFileSystem::get_singleton()->reimport_append(file_path, custom_options, String(), generator_parameters);
  2869. }
  2870. Ref<Texture2D> saved_image = ResourceLoader::load(file_path, "Texture2D");
  2871. if (saved_image.is_valid()) {
  2872. p_state->images.push_back(saved_image);
  2873. p_state->source_images.push_back(saved_image->get_image());
  2874. } else {
  2875. WARN_PRINT(vformat("glTF: Image index '%d' couldn't be loaded with the name: %s. Skipping it.", p_index, p_image->get_name()));
  2876. // Placeholder to keep count.
  2877. p_state->images.push_back(Ref<Texture2D>());
  2878. p_state->source_images.push_back(Ref<Image>());
  2879. }
  2880. }
  2881. return;
  2882. }
  2883. #endif // TOOLS_ENABLED
  2884. if (handling == GLTFState::GLTFHandleBinary::HANDLE_BINARY_EMBED_AS_BASISU) {
  2885. Ref<PortableCompressedTexture2D> tex;
  2886. tex.instantiate();
  2887. tex->set_name(p_image->get_name());
  2888. tex->set_keep_compressed_buffer(true);
  2889. tex->create_from_image(p_image, PortableCompressedTexture2D::COMPRESSION_MODE_BASIS_UNIVERSAL);
  2890. p_state->images.push_back(tex);
  2891. p_state->source_images.push_back(p_image);
  2892. return;
  2893. }
  2894. // This handles the case of HANDLE_BINARY_EMBED_AS_UNCOMPRESSED, and it also serves
  2895. // as a fallback for HANDLE_BINARY_EXTRACT_TEXTURES when this is not the editor.
  2896. Ref<ImageTexture> tex;
  2897. tex.instantiate();
  2898. tex->set_name(p_image->get_name());
  2899. tex->set_image(p_image);
  2900. p_state->images.push_back(tex);
  2901. p_state->source_images.push_back(p_image);
  2902. }
  2903. Error GLTFDocument::_parse_images(Ref<GLTFState> p_state, const String &p_base_path) {
  2904. ERR_FAIL_NULL_V(p_state, ERR_INVALID_PARAMETER);
  2905. if (!p_state->json.has("images")) {
  2906. return OK;
  2907. }
  2908. // Ref: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#images
  2909. const Array &images = p_state->json["images"];
  2910. HashSet<String> used_names;
  2911. for (int i = 0; i < images.size(); i++) {
  2912. const Dictionary &dict = images[i];
  2913. // glTF 2.0 supports PNG and JPEG types, which can be specified as (from spec):
  2914. // "- a URI to an external file in one of the supported images formats, or
  2915. // - a URI with embedded base64-encoded data, or
  2916. // - a reference to a bufferView; in that case mimeType must be defined."
  2917. // Since mimeType is optional for external files and base64 data, we'll have to
  2918. // fall back on letting Godot parse the data to figure out if it's PNG or JPEG.
  2919. // We'll assume that we use either URI or bufferView, so let's warn the user
  2920. // if their image somehow uses both. And fail if it has neither.
  2921. ERR_CONTINUE_MSG(!dict.has("uri") && !dict.has("bufferView"), "Invalid image definition in glTF file, it should specify an 'uri' or 'bufferView'.");
  2922. if (dict.has("uri") && dict.has("bufferView")) {
  2923. WARN_PRINT("Invalid image definition in glTF file using both 'uri' and 'bufferView'. 'uri' will take precedence.");
  2924. }
  2925. String mime_type;
  2926. if (dict.has("mimeType")) { // Should be "image/png", "image/jpeg", or something handled by an extension.
  2927. mime_type = dict["mimeType"];
  2928. }
  2929. String image_name;
  2930. if (dict.has("name")) {
  2931. image_name = dict["name"];
  2932. image_name = image_name.get_file().get_basename().validate_filename();
  2933. }
  2934. if (image_name.is_empty()) {
  2935. image_name = itos(i);
  2936. }
  2937. while (used_names.has(image_name)) {
  2938. image_name += "_" + itos(i);
  2939. }
  2940. used_names.insert(image_name);
  2941. // Load the image data. If we get a byte array, store here for later.
  2942. Vector<uint8_t> data;
  2943. if (dict.has("uri")) {
  2944. // Handles the first two bullet points from the spec (embedded data, or external file).
  2945. String uri = dict["uri"];
  2946. if (uri.begins_with("data:")) { // Embedded data using base64.
  2947. data = _parse_base64_uri(uri);
  2948. // mimeType is optional, but if we have it defined in the URI, let's use it.
  2949. if (mime_type.is_empty() && uri.contains(";")) {
  2950. // Trim "data:" prefix which is 5 characters long, and end at ";base64".
  2951. mime_type = uri.substr(5, uri.find(";base64") - 5);
  2952. }
  2953. } else { // Relative path to an external image file.
  2954. ERR_FAIL_COND_V(p_base_path.is_empty(), ERR_INVALID_PARAMETER);
  2955. uri = uri.uri_decode();
  2956. uri = p_base_path.path_join(uri).replace("\\", "/"); // Fix for Windows.
  2957. // ResourceLoader will rely on the file extension to use the relevant loader.
  2958. // The spec says that if mimeType is defined, it should take precedence (e.g.
  2959. // there could be a `.png` image which is actually JPEG), but there's no easy
  2960. // API for that in Godot, so we'd have to load as a buffer (i.e. embedded in
  2961. // the material), so we only do that only as fallback.
  2962. Ref<Texture2D> texture = ResourceLoader::load(uri);
  2963. if (texture.is_valid()) {
  2964. p_state->images.push_back(texture);
  2965. p_state->source_images.push_back(texture->get_image());
  2966. continue;
  2967. }
  2968. // mimeType is optional, but if we have it in the file extension, let's use it.
  2969. // If the mimeType does not match with the file extension, either it should be
  2970. // specified in the file, or the GLTFDocumentExtension should handle it.
  2971. if (mime_type.is_empty()) {
  2972. mime_type = "image/" + uri.get_extension();
  2973. }
  2974. // Fallback to loading as byte array. This enables us to support the
  2975. // spec's requirement that we honor mimetype regardless of file URI.
  2976. data = FileAccess::get_file_as_bytes(uri);
  2977. if (data.size() == 0) {
  2978. WARN_PRINT(vformat("glTF: Image index '%d' couldn't be loaded as a buffer of MIME type '%s' from URI: %s because there was no data to load. Skipping it.", i, mime_type, uri));
  2979. p_state->images.push_back(Ref<Texture2D>()); // Placeholder to keep count.
  2980. p_state->source_images.push_back(Ref<Image>());
  2981. continue;
  2982. }
  2983. }
  2984. } else if (dict.has("bufferView")) {
  2985. // Handles the third bullet point from the spec (bufferView).
  2986. ERR_FAIL_COND_V_MSG(mime_type.is_empty(), ERR_FILE_CORRUPT, vformat("glTF: Image index '%d' specifies 'bufferView' but no 'mimeType', which is invalid.", i));
  2987. const GLTFBufferViewIndex bvi = dict["bufferView"];
  2988. ERR_FAIL_INDEX_V(bvi, p_state->buffer_views.size(), ERR_PARAMETER_RANGE_ERROR);
  2989. Ref<GLTFBufferView> bv = p_state->buffer_views[bvi];
  2990. const GLTFBufferIndex bi = bv->buffer;
  2991. ERR_FAIL_INDEX_V(bi, p_state->buffers.size(), ERR_PARAMETER_RANGE_ERROR);
  2992. ERR_FAIL_COND_V(bv->byte_offset + bv->byte_length > p_state->buffers[bi].size(), ERR_FILE_CORRUPT);
  2993. const PackedByteArray &buffer = p_state->buffers[bi];
  2994. data = buffer.slice(bv->byte_offset, bv->byte_offset + bv->byte_length);
  2995. }
  2996. // Done loading the image data bytes. Check that we actually got data to parse.
  2997. // Note: There are paths above that return early, so this point might not be reached.
  2998. if (data.is_empty()) {
  2999. WARN_PRINT(vformat("glTF: Image index '%d' couldn't be loaded, no data found. Skipping it.", i));
  3000. p_state->images.push_back(Ref<Texture2D>()); // Placeholder to keep count.
  3001. p_state->source_images.push_back(Ref<Image>());
  3002. continue;
  3003. }
  3004. // Parse the image data from bytes into an Image resource and save if needed.
  3005. String file_extension;
  3006. Ref<Image> img = _parse_image_bytes_into_image(p_state, data, mime_type, i, file_extension);
  3007. img->set_name(image_name);
  3008. _parse_image_save_image(p_state, data, file_extension, i, img);
  3009. }
  3010. print_verbose("glTF: Total images: " + itos(p_state->images.size()));
  3011. return OK;
  3012. }
  3013. Error GLTFDocument::_serialize_textures(Ref<GLTFState> p_state) {
  3014. if (!p_state->textures.size()) {
  3015. return OK;
  3016. }
  3017. Array textures;
  3018. for (int32_t i = 0; i < p_state->textures.size(); i++) {
  3019. Dictionary texture_dict;
  3020. Ref<GLTFTexture> gltf_texture = p_state->textures[i];
  3021. if (_image_save_extension.is_valid()) {
  3022. Error err = _image_save_extension->serialize_texture_json(p_state, texture_dict, gltf_texture, _image_format);
  3023. ERR_FAIL_COND_V(err != OK, err);
  3024. } else {
  3025. ERR_CONTINUE(gltf_texture->get_src_image() == -1);
  3026. texture_dict["source"] = gltf_texture->get_src_image();
  3027. }
  3028. GLTFTextureSamplerIndex sampler_index = gltf_texture->get_sampler();
  3029. if (sampler_index != -1) {
  3030. texture_dict["sampler"] = sampler_index;
  3031. }
  3032. textures.push_back(texture_dict);
  3033. }
  3034. p_state->json["textures"] = textures;
  3035. return OK;
  3036. }
  3037. Error GLTFDocument::_parse_textures(Ref<GLTFState> p_state) {
  3038. if (!p_state->json.has("textures")) {
  3039. return OK;
  3040. }
  3041. const Array &textures = p_state->json["textures"];
  3042. for (GLTFTextureIndex i = 0; i < textures.size(); i++) {
  3043. const Dictionary &texture_dict = textures[i];
  3044. Ref<GLTFTexture> gltf_texture;
  3045. gltf_texture.instantiate();
  3046. // Check if any GLTFDocumentExtensions want to handle this texture JSON.
  3047. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  3048. ERR_CONTINUE(ext.is_null());
  3049. Error err = ext->parse_texture_json(p_state, texture_dict, gltf_texture);
  3050. ERR_CONTINUE_MSG(err != OK, "GLTF: Encountered error " + itos(err) + " when parsing texture JSON " + String(Variant(texture_dict)) + " in file " + p_state->filename + ". Continuing.");
  3051. if (gltf_texture->get_src_image() != -1) {
  3052. break;
  3053. }
  3054. }
  3055. if (gltf_texture->get_src_image() == -1) {
  3056. // No extensions handled it, so use the base GLTF source.
  3057. // This may be the fallback, or the only option anyway.
  3058. ERR_FAIL_COND_V(!texture_dict.has("source"), ERR_PARSE_ERROR);
  3059. gltf_texture->set_src_image(texture_dict["source"]);
  3060. }
  3061. if (gltf_texture->get_sampler() == -1 && texture_dict.has("sampler")) {
  3062. gltf_texture->set_sampler(texture_dict["sampler"]);
  3063. }
  3064. p_state->textures.push_back(gltf_texture);
  3065. }
  3066. return OK;
  3067. }
  3068. GLTFTextureIndex GLTFDocument::_set_texture(Ref<GLTFState> p_state, Ref<Texture2D> p_texture, StandardMaterial3D::TextureFilter p_filter_mode, bool p_repeats) {
  3069. ERR_FAIL_COND_V(p_texture.is_null(), -1);
  3070. Ref<GLTFTexture> gltf_texture;
  3071. gltf_texture.instantiate();
  3072. ERR_FAIL_COND_V(p_texture->get_image().is_null(), -1);
  3073. GLTFImageIndex gltf_src_image_i = p_state->images.size();
  3074. p_state->images.push_back(p_texture);
  3075. p_state->source_images.push_back(p_texture->get_image());
  3076. gltf_texture->set_src_image(gltf_src_image_i);
  3077. gltf_texture->set_sampler(_set_sampler_for_mode(p_state, p_filter_mode, p_repeats));
  3078. GLTFTextureIndex gltf_texture_i = p_state->textures.size();
  3079. p_state->textures.push_back(gltf_texture);
  3080. return gltf_texture_i;
  3081. }
  3082. Ref<Texture2D> GLTFDocument::_get_texture(Ref<GLTFState> p_state, const GLTFTextureIndex p_texture, int p_texture_types) {
  3083. ERR_FAIL_INDEX_V(p_texture, p_state->textures.size(), Ref<Texture2D>());
  3084. const GLTFImageIndex image = p_state->textures[p_texture]->get_src_image();
  3085. ERR_FAIL_INDEX_V(image, p_state->images.size(), Ref<Texture2D>());
  3086. if (GLTFState::GLTFHandleBinary(p_state->handle_binary_image) == GLTFState::GLTFHandleBinary::HANDLE_BINARY_EMBED_AS_BASISU) {
  3087. ERR_FAIL_INDEX_V(image, p_state->source_images.size(), Ref<Texture2D>());
  3088. Ref<PortableCompressedTexture2D> portable_texture;
  3089. portable_texture.instantiate();
  3090. portable_texture->set_keep_compressed_buffer(true);
  3091. Ref<Image> new_img = p_state->source_images[image]->duplicate();
  3092. ERR_FAIL_COND_V(new_img.is_null(), Ref<Texture2D>());
  3093. new_img->generate_mipmaps();
  3094. if (p_texture_types) {
  3095. portable_texture->create_from_image(new_img, PortableCompressedTexture2D::COMPRESSION_MODE_BASIS_UNIVERSAL, true);
  3096. } else {
  3097. portable_texture->create_from_image(new_img, PortableCompressedTexture2D::COMPRESSION_MODE_BASIS_UNIVERSAL, false);
  3098. }
  3099. p_state->images.write[image] = portable_texture;
  3100. p_state->source_images.write[image] = new_img;
  3101. }
  3102. return p_state->images[image];
  3103. }
  3104. GLTFTextureSamplerIndex GLTFDocument::_set_sampler_for_mode(Ref<GLTFState> p_state, StandardMaterial3D::TextureFilter p_filter_mode, bool p_repeats) {
  3105. for (int i = 0; i < p_state->texture_samplers.size(); ++i) {
  3106. if (p_state->texture_samplers[i]->get_filter_mode() == p_filter_mode) {
  3107. return i;
  3108. }
  3109. }
  3110. GLTFTextureSamplerIndex gltf_sampler_i = p_state->texture_samplers.size();
  3111. Ref<GLTFTextureSampler> gltf_sampler;
  3112. gltf_sampler.instantiate();
  3113. gltf_sampler->set_filter_mode(p_filter_mode);
  3114. gltf_sampler->set_wrap_mode(p_repeats);
  3115. p_state->texture_samplers.push_back(gltf_sampler);
  3116. return gltf_sampler_i;
  3117. }
  3118. Ref<GLTFTextureSampler> GLTFDocument::_get_sampler_for_texture(Ref<GLTFState> p_state, const GLTFTextureIndex p_texture) {
  3119. ERR_FAIL_INDEX_V(p_texture, p_state->textures.size(), Ref<Texture2D>());
  3120. const GLTFTextureSamplerIndex sampler = p_state->textures[p_texture]->get_sampler();
  3121. if (sampler == -1) {
  3122. return p_state->default_texture_sampler;
  3123. } else {
  3124. ERR_FAIL_INDEX_V(sampler, p_state->texture_samplers.size(), Ref<GLTFTextureSampler>());
  3125. return p_state->texture_samplers[sampler];
  3126. }
  3127. }
  3128. Error GLTFDocument::_serialize_texture_samplers(Ref<GLTFState> p_state) {
  3129. if (!p_state->texture_samplers.size()) {
  3130. return OK;
  3131. }
  3132. Array samplers;
  3133. for (int32_t i = 0; i < p_state->texture_samplers.size(); ++i) {
  3134. Dictionary d;
  3135. Ref<GLTFTextureSampler> s = p_state->texture_samplers[i];
  3136. d["magFilter"] = s->get_mag_filter();
  3137. d["minFilter"] = s->get_min_filter();
  3138. d["wrapS"] = s->get_wrap_s();
  3139. d["wrapT"] = s->get_wrap_t();
  3140. samplers.push_back(d);
  3141. }
  3142. p_state->json["samplers"] = samplers;
  3143. return OK;
  3144. }
  3145. Error GLTFDocument::_parse_texture_samplers(Ref<GLTFState> p_state) {
  3146. p_state->default_texture_sampler.instantiate();
  3147. p_state->default_texture_sampler->set_min_filter(GLTFTextureSampler::FilterMode::LINEAR_MIPMAP_LINEAR);
  3148. p_state->default_texture_sampler->set_mag_filter(GLTFTextureSampler::FilterMode::LINEAR);
  3149. p_state->default_texture_sampler->set_wrap_s(GLTFTextureSampler::WrapMode::REPEAT);
  3150. p_state->default_texture_sampler->set_wrap_t(GLTFTextureSampler::WrapMode::REPEAT);
  3151. if (!p_state->json.has("samplers")) {
  3152. return OK;
  3153. }
  3154. const Array &samplers = p_state->json["samplers"];
  3155. for (int i = 0; i < samplers.size(); ++i) {
  3156. const Dictionary &d = samplers[i];
  3157. Ref<GLTFTextureSampler> sampler;
  3158. sampler.instantiate();
  3159. if (d.has("minFilter")) {
  3160. sampler->set_min_filter(d["minFilter"]);
  3161. } else {
  3162. sampler->set_min_filter(GLTFTextureSampler::FilterMode::LINEAR_MIPMAP_LINEAR);
  3163. }
  3164. if (d.has("magFilter")) {
  3165. sampler->set_mag_filter(d["magFilter"]);
  3166. } else {
  3167. sampler->set_mag_filter(GLTFTextureSampler::FilterMode::LINEAR);
  3168. }
  3169. if (d.has("wrapS")) {
  3170. sampler->set_wrap_s(d["wrapS"]);
  3171. } else {
  3172. sampler->set_wrap_s(GLTFTextureSampler::WrapMode::DEFAULT);
  3173. }
  3174. if (d.has("wrapT")) {
  3175. sampler->set_wrap_t(d["wrapT"]);
  3176. } else {
  3177. sampler->set_wrap_t(GLTFTextureSampler::WrapMode::DEFAULT);
  3178. }
  3179. p_state->texture_samplers.push_back(sampler);
  3180. }
  3181. return OK;
  3182. }
  3183. Error GLTFDocument::_serialize_materials(Ref<GLTFState> p_state) {
  3184. Array materials;
  3185. for (int32_t i = 0; i < p_state->materials.size(); i++) {
  3186. Dictionary d;
  3187. Ref<Material> material = p_state->materials[i];
  3188. if (material.is_null()) {
  3189. materials.push_back(d);
  3190. continue;
  3191. }
  3192. if (!material->get_name().is_empty()) {
  3193. d["name"] = _gen_unique_name(p_state, material->get_name());
  3194. }
  3195. Ref<BaseMaterial3D> base_material = material;
  3196. if (base_material.is_null()) {
  3197. materials.push_back(d);
  3198. continue;
  3199. }
  3200. Dictionary mr;
  3201. {
  3202. Array arr;
  3203. const Color c = base_material->get_albedo().srgb_to_linear();
  3204. arr.push_back(c.r);
  3205. arr.push_back(c.g);
  3206. arr.push_back(c.b);
  3207. arr.push_back(c.a);
  3208. mr["baseColorFactor"] = arr;
  3209. }
  3210. if (_image_format != "None") {
  3211. Dictionary bct;
  3212. Ref<Texture2D> albedo_texture = base_material->get_texture(BaseMaterial3D::TEXTURE_ALBEDO);
  3213. GLTFTextureIndex gltf_texture_index = -1;
  3214. if (albedo_texture.is_valid() && albedo_texture->get_image().is_valid()) {
  3215. albedo_texture->set_name(material->get_name() + "_albedo");
  3216. gltf_texture_index = _set_texture(p_state, albedo_texture, base_material->get_texture_filter(), base_material->get_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT));
  3217. }
  3218. if (gltf_texture_index != -1) {
  3219. bct["index"] = gltf_texture_index;
  3220. Dictionary extensions = _serialize_texture_transform_uv1(material);
  3221. if (!extensions.is_empty()) {
  3222. bct["extensions"] = extensions;
  3223. p_state->use_khr_texture_transform = true;
  3224. }
  3225. mr["baseColorTexture"] = bct;
  3226. }
  3227. }
  3228. mr["metallicFactor"] = base_material->get_metallic();
  3229. mr["roughnessFactor"] = base_material->get_roughness();
  3230. if (_image_format != "None") {
  3231. bool has_roughness = base_material->get_texture(BaseMaterial3D::TEXTURE_ROUGHNESS).is_valid() && base_material->get_texture(BaseMaterial3D::TEXTURE_ROUGHNESS)->get_image().is_valid();
  3232. bool has_ao = base_material->get_feature(BaseMaterial3D::FEATURE_AMBIENT_OCCLUSION) && base_material->get_texture(BaseMaterial3D::TEXTURE_AMBIENT_OCCLUSION).is_valid();
  3233. bool has_metalness = base_material->get_texture(BaseMaterial3D::TEXTURE_METALLIC).is_valid() && base_material->get_texture(BaseMaterial3D::TEXTURE_METALLIC)->get_image().is_valid();
  3234. if (has_ao || has_roughness || has_metalness) {
  3235. Dictionary mrt;
  3236. Ref<Texture2D> roughness_texture = base_material->get_texture(BaseMaterial3D::TEXTURE_ROUGHNESS);
  3237. BaseMaterial3D::TextureChannel roughness_channel = base_material->get_roughness_texture_channel();
  3238. Ref<Texture2D> metallic_texture = base_material->get_texture(BaseMaterial3D::TEXTURE_METALLIC);
  3239. BaseMaterial3D::TextureChannel metalness_channel = base_material->get_metallic_texture_channel();
  3240. Ref<Texture2D> ao_texture = base_material->get_texture(BaseMaterial3D::TEXTURE_AMBIENT_OCCLUSION);
  3241. BaseMaterial3D::TextureChannel ao_channel = base_material->get_ao_texture_channel();
  3242. Ref<ImageTexture> orm_texture;
  3243. orm_texture.instantiate();
  3244. Ref<Image> orm_image;
  3245. orm_image.instantiate();
  3246. int32_t height = 0;
  3247. int32_t width = 0;
  3248. Ref<Image> ao_image;
  3249. if (has_ao) {
  3250. height = ao_texture->get_height();
  3251. width = ao_texture->get_width();
  3252. ao_image = ao_texture->get_image();
  3253. Ref<ImageTexture> img_tex = ao_image;
  3254. if (img_tex.is_valid()) {
  3255. ao_image = img_tex->get_image();
  3256. }
  3257. if (ao_image->is_compressed()) {
  3258. ao_image->decompress();
  3259. }
  3260. }
  3261. Ref<Image> roughness_image;
  3262. if (has_roughness) {
  3263. height = roughness_texture->get_height();
  3264. width = roughness_texture->get_width();
  3265. roughness_image = roughness_texture->get_image();
  3266. Ref<ImageTexture> img_tex = roughness_image;
  3267. if (img_tex.is_valid()) {
  3268. roughness_image = img_tex->get_image();
  3269. }
  3270. if (roughness_image->is_compressed()) {
  3271. roughness_image->decompress();
  3272. }
  3273. }
  3274. Ref<Image> metallness_image;
  3275. if (has_metalness) {
  3276. height = metallic_texture->get_height();
  3277. width = metallic_texture->get_width();
  3278. metallness_image = metallic_texture->get_image();
  3279. Ref<ImageTexture> img_tex = metallness_image;
  3280. if (img_tex.is_valid()) {
  3281. metallness_image = img_tex->get_image();
  3282. }
  3283. if (metallness_image->is_compressed()) {
  3284. metallness_image->decompress();
  3285. }
  3286. }
  3287. Ref<Texture2D> albedo_texture = base_material->get_texture(BaseMaterial3D::TEXTURE_ALBEDO);
  3288. if (albedo_texture.is_valid() && albedo_texture->get_image().is_valid()) {
  3289. height = albedo_texture->get_height();
  3290. width = albedo_texture->get_width();
  3291. }
  3292. orm_image->initialize_data(width, height, false, Image::FORMAT_RGBA8);
  3293. if (ao_image.is_valid() && ao_image->get_size() != Vector2(width, height)) {
  3294. ao_image->resize(width, height, Image::INTERPOLATE_LANCZOS);
  3295. }
  3296. if (roughness_image.is_valid() && roughness_image->get_size() != Vector2(width, height)) {
  3297. roughness_image->resize(width, height, Image::INTERPOLATE_LANCZOS);
  3298. }
  3299. if (metallness_image.is_valid() && metallness_image->get_size() != Vector2(width, height)) {
  3300. metallness_image->resize(width, height, Image::INTERPOLATE_LANCZOS);
  3301. }
  3302. for (int32_t h = 0; h < height; h++) {
  3303. for (int32_t w = 0; w < width; w++) {
  3304. Color c = Color(1.0f, 1.0f, 1.0f);
  3305. if (has_ao) {
  3306. if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_RED == ao_channel) {
  3307. c.r = ao_image->get_pixel(w, h).r;
  3308. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_GREEN == ao_channel) {
  3309. c.r = ao_image->get_pixel(w, h).g;
  3310. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_BLUE == ao_channel) {
  3311. c.r = ao_image->get_pixel(w, h).b;
  3312. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_ALPHA == ao_channel) {
  3313. c.r = ao_image->get_pixel(w, h).a;
  3314. }
  3315. }
  3316. if (has_roughness) {
  3317. if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_RED == roughness_channel) {
  3318. c.g = roughness_image->get_pixel(w, h).r;
  3319. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_GREEN == roughness_channel) {
  3320. c.g = roughness_image->get_pixel(w, h).g;
  3321. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_BLUE == roughness_channel) {
  3322. c.g = roughness_image->get_pixel(w, h).b;
  3323. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_ALPHA == roughness_channel) {
  3324. c.g = roughness_image->get_pixel(w, h).a;
  3325. }
  3326. }
  3327. if (has_metalness) {
  3328. if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_RED == metalness_channel) {
  3329. c.b = metallness_image->get_pixel(w, h).r;
  3330. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_GREEN == metalness_channel) {
  3331. c.b = metallness_image->get_pixel(w, h).g;
  3332. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_BLUE == metalness_channel) {
  3333. c.b = metallness_image->get_pixel(w, h).b;
  3334. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_ALPHA == metalness_channel) {
  3335. c.b = metallness_image->get_pixel(w, h).a;
  3336. }
  3337. }
  3338. orm_image->set_pixel(w, h, c);
  3339. }
  3340. }
  3341. orm_image->generate_mipmaps();
  3342. orm_texture->set_image(orm_image);
  3343. GLTFTextureIndex orm_texture_index = -1;
  3344. if (has_ao || has_roughness || has_metalness) {
  3345. orm_texture->set_name(material->get_name() + "_orm");
  3346. orm_texture_index = _set_texture(p_state, orm_texture, base_material->get_texture_filter(), base_material->get_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT));
  3347. }
  3348. if (has_ao) {
  3349. Dictionary occt;
  3350. occt["index"] = orm_texture_index;
  3351. d["occlusionTexture"] = occt;
  3352. }
  3353. if (has_roughness || has_metalness) {
  3354. mrt["index"] = orm_texture_index;
  3355. Dictionary extensions = _serialize_texture_transform_uv1(material);
  3356. if (!extensions.is_empty()) {
  3357. mrt["extensions"] = extensions;
  3358. p_state->use_khr_texture_transform = true;
  3359. }
  3360. mr["metallicRoughnessTexture"] = mrt;
  3361. }
  3362. }
  3363. }
  3364. d["pbrMetallicRoughness"] = mr;
  3365. if (base_material->get_feature(BaseMaterial3D::FEATURE_NORMAL_MAPPING) && _image_format != "None") {
  3366. Dictionary nt;
  3367. Ref<ImageTexture> tex;
  3368. tex.instantiate();
  3369. {
  3370. Ref<Texture2D> normal_texture = base_material->get_texture(BaseMaterial3D::TEXTURE_NORMAL);
  3371. if (normal_texture.is_valid()) {
  3372. // Code for uncompressing RG normal maps
  3373. Ref<Image> img = normal_texture->get_image();
  3374. if (img.is_valid()) {
  3375. Ref<ImageTexture> img_tex = img;
  3376. if (img_tex.is_valid()) {
  3377. img = img_tex->get_image();
  3378. }
  3379. img->decompress();
  3380. img->convert(Image::FORMAT_RGBA8);
  3381. for (int32_t y = 0; y < img->get_height(); y++) {
  3382. for (int32_t x = 0; x < img->get_width(); x++) {
  3383. Color c = img->get_pixel(x, y);
  3384. Vector2 red_green = Vector2(c.r, c.g);
  3385. red_green = red_green * Vector2(2.0f, 2.0f) - Vector2(1.0f, 1.0f);
  3386. float blue = 1.0f - red_green.dot(red_green);
  3387. blue = MAX(0.0f, blue);
  3388. c.b = Math::sqrt(blue);
  3389. img->set_pixel(x, y, c);
  3390. }
  3391. }
  3392. tex->set_image(img);
  3393. }
  3394. }
  3395. }
  3396. GLTFTextureIndex gltf_texture_index = -1;
  3397. if (tex.is_valid() && tex->get_image().is_valid()) {
  3398. tex->set_name(material->get_name() + "_normal");
  3399. gltf_texture_index = _set_texture(p_state, tex, base_material->get_texture_filter(), base_material->get_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT));
  3400. }
  3401. nt["scale"] = base_material->get_normal_scale();
  3402. if (gltf_texture_index != -1) {
  3403. nt["index"] = gltf_texture_index;
  3404. d["normalTexture"] = nt;
  3405. }
  3406. }
  3407. if (base_material->get_feature(BaseMaterial3D::FEATURE_EMISSION)) {
  3408. const Color c = base_material->get_emission().linear_to_srgb();
  3409. Array arr;
  3410. arr.push_back(c.r);
  3411. arr.push_back(c.g);
  3412. arr.push_back(c.b);
  3413. d["emissiveFactor"] = arr;
  3414. }
  3415. if (base_material->get_feature(BaseMaterial3D::FEATURE_EMISSION) && _image_format != "None") {
  3416. Dictionary et;
  3417. Ref<Texture2D> emission_texture = base_material->get_texture(BaseMaterial3D::TEXTURE_EMISSION);
  3418. GLTFTextureIndex gltf_texture_index = -1;
  3419. if (emission_texture.is_valid() && emission_texture->get_image().is_valid()) {
  3420. emission_texture->set_name(material->get_name() + "_emission");
  3421. gltf_texture_index = _set_texture(p_state, emission_texture, base_material->get_texture_filter(), base_material->get_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT));
  3422. }
  3423. if (gltf_texture_index != -1) {
  3424. et["index"] = gltf_texture_index;
  3425. d["emissiveTexture"] = et;
  3426. }
  3427. }
  3428. const bool ds = base_material->get_cull_mode() == BaseMaterial3D::CULL_DISABLED;
  3429. if (ds) {
  3430. d["doubleSided"] = ds;
  3431. }
  3432. if (base_material->get_transparency() == BaseMaterial3D::TRANSPARENCY_ALPHA_SCISSOR) {
  3433. d["alphaMode"] = "MASK";
  3434. d["alphaCutoff"] = base_material->get_alpha_scissor_threshold();
  3435. } else if (base_material->get_transparency() != BaseMaterial3D::TRANSPARENCY_DISABLED) {
  3436. d["alphaMode"] = "BLEND";
  3437. }
  3438. Dictionary extensions;
  3439. if (base_material->get_shading_mode() == BaseMaterial3D::SHADING_MODE_UNSHADED) {
  3440. Dictionary mat_unlit;
  3441. extensions["KHR_materials_unlit"] = mat_unlit;
  3442. p_state->add_used_extension("KHR_materials_unlit");
  3443. }
  3444. if (base_material->get_feature(BaseMaterial3D::FEATURE_EMISSION) && !Math::is_equal_approx(base_material->get_emission_energy_multiplier(), 1.0f)) {
  3445. Dictionary mat_emissive_strength;
  3446. mat_emissive_strength["emissiveStrength"] = base_material->get_emission_energy_multiplier();
  3447. extensions["KHR_materials_emissive_strength"] = mat_emissive_strength;
  3448. p_state->add_used_extension("KHR_materials_emissive_strength");
  3449. }
  3450. d["extensions"] = extensions;
  3451. materials.push_back(d);
  3452. }
  3453. if (!materials.size()) {
  3454. return OK;
  3455. }
  3456. p_state->json["materials"] = materials;
  3457. print_verbose("Total materials: " + itos(p_state->materials.size()));
  3458. return OK;
  3459. }
  3460. Error GLTFDocument::_parse_materials(Ref<GLTFState> p_state) {
  3461. if (!p_state->json.has("materials")) {
  3462. return OK;
  3463. }
  3464. const Array &materials = p_state->json["materials"];
  3465. for (GLTFMaterialIndex i = 0; i < materials.size(); i++) {
  3466. const Dictionary &material_dict = materials[i];
  3467. Ref<StandardMaterial3D> material;
  3468. material.instantiate();
  3469. if (material_dict.has("name") && !String(material_dict["name"]).is_empty()) {
  3470. material->set_name(material_dict["name"]);
  3471. } else {
  3472. material->set_name(vformat("material_%s", itos(i)));
  3473. }
  3474. Dictionary material_extensions;
  3475. if (material_dict.has("extensions")) {
  3476. material_extensions = material_dict["extensions"];
  3477. }
  3478. if (material_extensions.has("KHR_materials_unlit")) {
  3479. material->set_shading_mode(BaseMaterial3D::SHADING_MODE_UNSHADED);
  3480. }
  3481. if (material_extensions.has("KHR_materials_emissive_strength")) {
  3482. Dictionary emissive_strength = material_extensions["KHR_materials_emissive_strength"];
  3483. if (emissive_strength.has("emissiveStrength")) {
  3484. material->set_emission_energy_multiplier(emissive_strength["emissiveStrength"]);
  3485. }
  3486. }
  3487. if (material_extensions.has("KHR_materials_pbrSpecularGlossiness")) {
  3488. WARN_PRINT("Material uses a specular and glossiness workflow. Textures will be converted to roughness and metallic workflow, which may not be 100% accurate.");
  3489. Dictionary sgm = material_extensions["KHR_materials_pbrSpecularGlossiness"];
  3490. Ref<GLTFSpecGloss> spec_gloss;
  3491. spec_gloss.instantiate();
  3492. if (sgm.has("diffuseTexture")) {
  3493. const Dictionary &diffuse_texture_dict = sgm["diffuseTexture"];
  3494. if (diffuse_texture_dict.has("index")) {
  3495. Ref<GLTFTextureSampler> diffuse_sampler = _get_sampler_for_texture(p_state, diffuse_texture_dict["index"]);
  3496. if (diffuse_sampler.is_valid()) {
  3497. material->set_texture_filter(diffuse_sampler->get_filter_mode());
  3498. material->set_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT, diffuse_sampler->get_wrap_mode());
  3499. }
  3500. Ref<Texture2D> diffuse_texture = _get_texture(p_state, diffuse_texture_dict["index"], TEXTURE_TYPE_GENERIC);
  3501. if (diffuse_texture.is_valid()) {
  3502. spec_gloss->diffuse_img = diffuse_texture->get_image();
  3503. material->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, diffuse_texture);
  3504. }
  3505. }
  3506. }
  3507. if (sgm.has("diffuseFactor")) {
  3508. const Array &arr = sgm["diffuseFactor"];
  3509. ERR_FAIL_COND_V(arr.size() != 4, ERR_PARSE_ERROR);
  3510. const Color c = Color(arr[0], arr[1], arr[2], arr[3]).linear_to_srgb();
  3511. spec_gloss->diffuse_factor = c;
  3512. material->set_albedo(spec_gloss->diffuse_factor);
  3513. }
  3514. if (sgm.has("specularFactor")) {
  3515. const Array &arr = sgm["specularFactor"];
  3516. ERR_FAIL_COND_V(arr.size() != 3, ERR_PARSE_ERROR);
  3517. spec_gloss->specular_factor = Color(arr[0], arr[1], arr[2]);
  3518. }
  3519. if (sgm.has("glossinessFactor")) {
  3520. spec_gloss->gloss_factor = sgm["glossinessFactor"];
  3521. material->set_roughness(1.0f - CLAMP(spec_gloss->gloss_factor, 0.0f, 1.0f));
  3522. }
  3523. if (sgm.has("specularGlossinessTexture")) {
  3524. const Dictionary &spec_gloss_texture = sgm["specularGlossinessTexture"];
  3525. if (spec_gloss_texture.has("index")) {
  3526. const Ref<Texture2D> orig_texture = _get_texture(p_state, spec_gloss_texture["index"], TEXTURE_TYPE_GENERIC);
  3527. if (orig_texture.is_valid()) {
  3528. spec_gloss->spec_gloss_img = orig_texture->get_image();
  3529. }
  3530. }
  3531. }
  3532. spec_gloss_to_rough_metal(spec_gloss, material);
  3533. } else if (material_dict.has("pbrMetallicRoughness")) {
  3534. const Dictionary &mr = material_dict["pbrMetallicRoughness"];
  3535. if (mr.has("baseColorFactor")) {
  3536. const Array &arr = mr["baseColorFactor"];
  3537. ERR_FAIL_COND_V(arr.size() != 4, ERR_PARSE_ERROR);
  3538. const Color c = Color(arr[0], arr[1], arr[2], arr[3]).linear_to_srgb();
  3539. material->set_albedo(c);
  3540. }
  3541. if (mr.has("baseColorTexture")) {
  3542. const Dictionary &bct = mr["baseColorTexture"];
  3543. if (bct.has("index")) {
  3544. Ref<GLTFTextureSampler> bct_sampler = _get_sampler_for_texture(p_state, bct["index"]);
  3545. material->set_texture_filter(bct_sampler->get_filter_mode());
  3546. material->set_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT, bct_sampler->get_wrap_mode());
  3547. material->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, _get_texture(p_state, bct["index"], TEXTURE_TYPE_GENERIC));
  3548. }
  3549. if (!mr.has("baseColorFactor")) {
  3550. material->set_albedo(Color(1, 1, 1));
  3551. }
  3552. _set_texture_transform_uv1(bct, material);
  3553. }
  3554. if (mr.has("metallicFactor")) {
  3555. material->set_metallic(mr["metallicFactor"]);
  3556. } else {
  3557. material->set_metallic(1.0);
  3558. }
  3559. if (mr.has("roughnessFactor")) {
  3560. material->set_roughness(mr["roughnessFactor"]);
  3561. } else {
  3562. material->set_roughness(1.0);
  3563. }
  3564. if (mr.has("metallicRoughnessTexture")) {
  3565. const Dictionary &bct = mr["metallicRoughnessTexture"];
  3566. if (bct.has("index")) {
  3567. const Ref<Texture2D> t = _get_texture(p_state, bct["index"], TEXTURE_TYPE_GENERIC);
  3568. material->set_texture(BaseMaterial3D::TEXTURE_METALLIC, t);
  3569. material->set_metallic_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_BLUE);
  3570. material->set_texture(BaseMaterial3D::TEXTURE_ROUGHNESS, t);
  3571. material->set_roughness_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_GREEN);
  3572. if (!mr.has("metallicFactor")) {
  3573. material->set_metallic(1);
  3574. }
  3575. if (!mr.has("roughnessFactor")) {
  3576. material->set_roughness(1);
  3577. }
  3578. }
  3579. }
  3580. }
  3581. if (material_dict.has("normalTexture")) {
  3582. const Dictionary &bct = material_dict["normalTexture"];
  3583. if (bct.has("index")) {
  3584. material->set_texture(BaseMaterial3D::TEXTURE_NORMAL, _get_texture(p_state, bct["index"], TEXTURE_TYPE_NORMAL));
  3585. material->set_feature(BaseMaterial3D::FEATURE_NORMAL_MAPPING, true);
  3586. }
  3587. if (bct.has("scale")) {
  3588. material->set_normal_scale(bct["scale"]);
  3589. }
  3590. }
  3591. if (material_dict.has("occlusionTexture")) {
  3592. const Dictionary &bct = material_dict["occlusionTexture"];
  3593. if (bct.has("index")) {
  3594. material->set_texture(BaseMaterial3D::TEXTURE_AMBIENT_OCCLUSION, _get_texture(p_state, bct["index"], TEXTURE_TYPE_GENERIC));
  3595. material->set_ao_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_RED);
  3596. material->set_feature(BaseMaterial3D::FEATURE_AMBIENT_OCCLUSION, true);
  3597. }
  3598. }
  3599. if (material_dict.has("emissiveFactor")) {
  3600. const Array &arr = material_dict["emissiveFactor"];
  3601. ERR_FAIL_COND_V(arr.size() != 3, ERR_PARSE_ERROR);
  3602. const Color c = Color(arr[0], arr[1], arr[2]).linear_to_srgb();
  3603. material->set_feature(BaseMaterial3D::FEATURE_EMISSION, true);
  3604. material->set_emission(c);
  3605. }
  3606. if (material_dict.has("emissiveTexture")) {
  3607. const Dictionary &bct = material_dict["emissiveTexture"];
  3608. if (bct.has("index")) {
  3609. material->set_texture(BaseMaterial3D::TEXTURE_EMISSION, _get_texture(p_state, bct["index"], TEXTURE_TYPE_GENERIC));
  3610. material->set_feature(BaseMaterial3D::FEATURE_EMISSION, true);
  3611. material->set_emission(Color(0, 0, 0));
  3612. }
  3613. }
  3614. if (material_dict.has("doubleSided")) {
  3615. const bool ds = material_dict["doubleSided"];
  3616. if (ds) {
  3617. material->set_cull_mode(BaseMaterial3D::CULL_DISABLED);
  3618. }
  3619. }
  3620. if (material_dict.has("alphaMode")) {
  3621. const String &am = material_dict["alphaMode"];
  3622. if (am == "BLEND") {
  3623. material->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS);
  3624. } else if (am == "MASK") {
  3625. material->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA_SCISSOR);
  3626. if (material_dict.has("alphaCutoff")) {
  3627. material->set_alpha_scissor_threshold(material_dict["alphaCutoff"]);
  3628. } else {
  3629. material->set_alpha_scissor_threshold(0.5f);
  3630. }
  3631. }
  3632. }
  3633. p_state->materials.push_back(material);
  3634. }
  3635. print_verbose("Total materials: " + itos(p_state->materials.size()));
  3636. return OK;
  3637. }
  3638. void GLTFDocument::_set_texture_transform_uv1(const Dictionary &p_dict, Ref<BaseMaterial3D> p_material) {
  3639. if (p_dict.has("extensions")) {
  3640. const Dictionary &extensions = p_dict["extensions"];
  3641. if (extensions.has("KHR_texture_transform")) {
  3642. if (p_material.is_valid()) {
  3643. const Dictionary &texture_transform = extensions["KHR_texture_transform"];
  3644. const Array &offset_arr = texture_transform["offset"];
  3645. if (offset_arr.size() == 2) {
  3646. const Vector3 offset_vector3 = Vector3(offset_arr[0], offset_arr[1], 0.0f);
  3647. p_material->set_uv1_offset(offset_vector3);
  3648. }
  3649. const Array &scale_arr = texture_transform["scale"];
  3650. if (scale_arr.size() == 2) {
  3651. const Vector3 scale_vector3 = Vector3(scale_arr[0], scale_arr[1], 1.0f);
  3652. p_material->set_uv1_scale(scale_vector3);
  3653. }
  3654. }
  3655. }
  3656. }
  3657. }
  3658. void GLTFDocument::spec_gloss_to_rough_metal(Ref<GLTFSpecGloss> r_spec_gloss, Ref<BaseMaterial3D> p_material) {
  3659. if (r_spec_gloss.is_null()) {
  3660. return;
  3661. }
  3662. if (r_spec_gloss->spec_gloss_img.is_null()) {
  3663. return;
  3664. }
  3665. if (r_spec_gloss->diffuse_img.is_null()) {
  3666. return;
  3667. }
  3668. if (p_material.is_null()) {
  3669. return;
  3670. }
  3671. bool has_roughness = false;
  3672. bool has_metal = false;
  3673. p_material->set_roughness(1.0f);
  3674. p_material->set_metallic(1.0f);
  3675. Ref<Image> rm_img = Image::create_empty(r_spec_gloss->spec_gloss_img->get_width(), r_spec_gloss->spec_gloss_img->get_height(), false, Image::FORMAT_RGBA8);
  3676. r_spec_gloss->spec_gloss_img->decompress();
  3677. if (r_spec_gloss->diffuse_img.is_valid()) {
  3678. r_spec_gloss->diffuse_img->decompress();
  3679. r_spec_gloss->diffuse_img->resize(r_spec_gloss->spec_gloss_img->get_width(), r_spec_gloss->spec_gloss_img->get_height(), Image::INTERPOLATE_LANCZOS);
  3680. r_spec_gloss->spec_gloss_img->resize(r_spec_gloss->diffuse_img->get_width(), r_spec_gloss->diffuse_img->get_height(), Image::INTERPOLATE_LANCZOS);
  3681. }
  3682. for (int32_t y = 0; y < r_spec_gloss->spec_gloss_img->get_height(); y++) {
  3683. for (int32_t x = 0; x < r_spec_gloss->spec_gloss_img->get_width(); x++) {
  3684. const Color specular_pixel = r_spec_gloss->spec_gloss_img->get_pixel(x, y).srgb_to_linear();
  3685. Color specular = Color(specular_pixel.r, specular_pixel.g, specular_pixel.b);
  3686. specular *= r_spec_gloss->specular_factor;
  3687. Color diffuse = Color(1.0f, 1.0f, 1.0f);
  3688. diffuse *= r_spec_gloss->diffuse_img->get_pixel(x, y).srgb_to_linear();
  3689. float metallic = 0.0f;
  3690. Color base_color;
  3691. spec_gloss_to_metal_base_color(specular, diffuse, base_color, metallic);
  3692. Color mr = Color(1.0f, 1.0f, 1.0f);
  3693. mr.g = specular_pixel.a;
  3694. mr.b = metallic;
  3695. if (!Math::is_equal_approx(mr.g, 1.0f)) {
  3696. has_roughness = true;
  3697. }
  3698. if (!Math::is_zero_approx(mr.b)) {
  3699. has_metal = true;
  3700. }
  3701. mr.g *= r_spec_gloss->gloss_factor;
  3702. mr.g = 1.0f - mr.g;
  3703. rm_img->set_pixel(x, y, mr);
  3704. if (r_spec_gloss->diffuse_img.is_valid()) {
  3705. r_spec_gloss->diffuse_img->set_pixel(x, y, base_color.linear_to_srgb());
  3706. }
  3707. }
  3708. }
  3709. rm_img->generate_mipmaps();
  3710. r_spec_gloss->diffuse_img->generate_mipmaps();
  3711. p_material->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, ImageTexture::create_from_image(r_spec_gloss->diffuse_img));
  3712. Ref<ImageTexture> rm_image_texture = ImageTexture::create_from_image(rm_img);
  3713. if (has_roughness) {
  3714. p_material->set_texture(BaseMaterial3D::TEXTURE_ROUGHNESS, rm_image_texture);
  3715. p_material->set_roughness_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_GREEN);
  3716. }
  3717. if (has_metal) {
  3718. p_material->set_texture(BaseMaterial3D::TEXTURE_METALLIC, rm_image_texture);
  3719. p_material->set_metallic_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_BLUE);
  3720. }
  3721. }
  3722. void GLTFDocument::spec_gloss_to_metal_base_color(const Color &p_specular_factor, const Color &p_diffuse, Color &r_base_color, float &r_metallic) {
  3723. const Color DIELECTRIC_SPECULAR = Color(0.04f, 0.04f, 0.04f);
  3724. Color specular = Color(p_specular_factor.r, p_specular_factor.g, p_specular_factor.b);
  3725. const float one_minus_specular_strength = 1.0f - get_max_component(specular);
  3726. const float dielectric_specular_red = DIELECTRIC_SPECULAR.r;
  3727. float brightness_diffuse = get_perceived_brightness(p_diffuse);
  3728. const float brightness_specular = get_perceived_brightness(specular);
  3729. r_metallic = solve_metallic(dielectric_specular_red, brightness_diffuse, brightness_specular, one_minus_specular_strength);
  3730. const float one_minus_metallic = 1.0f - r_metallic;
  3731. const Color base_color_from_diffuse = p_diffuse * (one_minus_specular_strength / (1.0f - dielectric_specular_red) / MAX(one_minus_metallic, CMP_EPSILON));
  3732. const Color base_color_from_specular = (specular - (DIELECTRIC_SPECULAR * (one_minus_metallic))) * (1.0f / MAX(r_metallic, CMP_EPSILON));
  3733. r_base_color.r = Math::lerp(base_color_from_diffuse.r, base_color_from_specular.r, r_metallic * r_metallic);
  3734. r_base_color.g = Math::lerp(base_color_from_diffuse.g, base_color_from_specular.g, r_metallic * r_metallic);
  3735. r_base_color.b = Math::lerp(base_color_from_diffuse.b, base_color_from_specular.b, r_metallic * r_metallic);
  3736. r_base_color.a = p_diffuse.a;
  3737. r_base_color = r_base_color.clamp();
  3738. }
  3739. Error GLTFDocument::_parse_skins(Ref<GLTFState> p_state) {
  3740. if (!p_state->json.has("skins")) {
  3741. return OK;
  3742. }
  3743. const Array &skins = p_state->json["skins"];
  3744. // Create the base skins, and mark nodes that are joints
  3745. for (int i = 0; i < skins.size(); i++) {
  3746. const Dictionary &d = skins[i];
  3747. Ref<GLTFSkin> skin;
  3748. skin.instantiate();
  3749. ERR_FAIL_COND_V(!d.has("joints"), ERR_PARSE_ERROR);
  3750. const Array &joints = d["joints"];
  3751. if (d.has("inverseBindMatrices")) {
  3752. skin->inverse_binds = _decode_accessor_as_xform(p_state, d["inverseBindMatrices"], false);
  3753. ERR_FAIL_COND_V(skin->inverse_binds.size() != joints.size(), ERR_PARSE_ERROR);
  3754. }
  3755. for (int j = 0; j < joints.size(); j++) {
  3756. const GLTFNodeIndex node = joints[j];
  3757. ERR_FAIL_INDEX_V(node, p_state->nodes.size(), ERR_PARSE_ERROR);
  3758. skin->joints.push_back(node);
  3759. skin->joints_original.push_back(node);
  3760. p_state->nodes.write[node]->joint = true;
  3761. }
  3762. if (d.has("name") && !String(d["name"]).is_empty()) {
  3763. skin->set_name(d["name"]);
  3764. } else {
  3765. skin->set_name(vformat("skin_%s", itos(i)));
  3766. }
  3767. if (d.has("skeleton")) {
  3768. skin->skin_root = d["skeleton"];
  3769. }
  3770. p_state->skins.push_back(skin);
  3771. }
  3772. for (GLTFSkinIndex i = 0; i < p_state->skins.size(); ++i) {
  3773. Ref<GLTFSkin> skin = p_state->skins.write[i];
  3774. // Expand the skin to capture all the extra non-joints that lie in between the actual joints,
  3775. // and expand the hierarchy to ensure multi-rooted trees lie on the same height level
  3776. ERR_FAIL_COND_V(SkinTool::_expand_skin(p_state->nodes, skin), ERR_PARSE_ERROR);
  3777. ERR_FAIL_COND_V(SkinTool::_verify_skin(p_state->nodes, skin), ERR_PARSE_ERROR);
  3778. }
  3779. print_verbose("glTF: Total skins: " + itos(p_state->skins.size()));
  3780. return OK;
  3781. }
  3782. Error GLTFDocument::_serialize_skins(Ref<GLTFState> p_state) {
  3783. _remove_duplicate_skins(p_state);
  3784. Array json_skins;
  3785. for (int skin_i = 0; skin_i < p_state->skins.size(); skin_i++) {
  3786. Ref<GLTFSkin> gltf_skin = p_state->skins[skin_i];
  3787. Dictionary json_skin;
  3788. json_skin["inverseBindMatrices"] = _encode_accessor_as_xform(p_state, gltf_skin->inverse_binds, false);
  3789. json_skin["joints"] = gltf_skin->get_joints();
  3790. json_skin["name"] = gltf_skin->get_name();
  3791. json_skins.push_back(json_skin);
  3792. }
  3793. if (!p_state->skins.size()) {
  3794. return OK;
  3795. }
  3796. p_state->json["skins"] = json_skins;
  3797. return OK;
  3798. }
  3799. Error GLTFDocument::_create_skins(Ref<GLTFState> p_state) {
  3800. for (GLTFSkinIndex skin_i = 0; skin_i < p_state->skins.size(); ++skin_i) {
  3801. Ref<GLTFSkin> gltf_skin = p_state->skins.write[skin_i];
  3802. Ref<Skin> skin;
  3803. skin.instantiate();
  3804. // Some skins don't have IBM's! What absolute monsters!
  3805. const bool has_ibms = !gltf_skin->inverse_binds.is_empty();
  3806. for (int joint_i = 0; joint_i < gltf_skin->joints_original.size(); ++joint_i) {
  3807. GLTFNodeIndex node = gltf_skin->joints_original[joint_i];
  3808. String bone_name = p_state->nodes[node]->get_name();
  3809. Transform3D xform;
  3810. if (has_ibms) {
  3811. xform = gltf_skin->inverse_binds[joint_i];
  3812. }
  3813. if (p_state->use_named_skin_binds) {
  3814. skin->add_named_bind(bone_name, xform);
  3815. } else {
  3816. int32_t bone_i = gltf_skin->joint_i_to_bone_i[joint_i];
  3817. skin->add_bind(bone_i, xform);
  3818. }
  3819. }
  3820. gltf_skin->godot_skin = skin;
  3821. }
  3822. // Purge the duplicates!
  3823. _remove_duplicate_skins(p_state);
  3824. // Create unique names now, after removing duplicates
  3825. for (GLTFSkinIndex skin_i = 0; skin_i < p_state->skins.size(); ++skin_i) {
  3826. Ref<Skin> skin = p_state->skins.write[skin_i]->godot_skin;
  3827. if (skin->get_name().is_empty()) {
  3828. // Make a unique name, no gltf node represents this skin
  3829. skin->set_name(_gen_unique_name(p_state, "Skin"));
  3830. }
  3831. }
  3832. return OK;
  3833. }
  3834. bool GLTFDocument::_skins_are_same(const Ref<Skin> p_skin_a, const Ref<Skin> p_skin_b) {
  3835. if (p_skin_a->get_bind_count() != p_skin_b->get_bind_count()) {
  3836. return false;
  3837. }
  3838. for (int i = 0; i < p_skin_a->get_bind_count(); ++i) {
  3839. if (p_skin_a->get_bind_bone(i) != p_skin_b->get_bind_bone(i)) {
  3840. return false;
  3841. }
  3842. if (p_skin_a->get_bind_name(i) != p_skin_b->get_bind_name(i)) {
  3843. return false;
  3844. }
  3845. Transform3D a_xform = p_skin_a->get_bind_pose(i);
  3846. Transform3D b_xform = p_skin_b->get_bind_pose(i);
  3847. if (a_xform != b_xform) {
  3848. return false;
  3849. }
  3850. }
  3851. return true;
  3852. }
  3853. void GLTFDocument::_remove_duplicate_skins(Ref<GLTFState> p_state) {
  3854. for (int i = 0; i < p_state->skins.size(); ++i) {
  3855. for (int j = i + 1; j < p_state->skins.size(); ++j) {
  3856. const Ref<Skin> skin_i = p_state->skins[i]->godot_skin;
  3857. const Ref<Skin> skin_j = p_state->skins[j]->godot_skin;
  3858. if (_skins_are_same(skin_i, skin_j)) {
  3859. // replace it and delete the old
  3860. p_state->skins.write[j]->godot_skin = skin_i;
  3861. }
  3862. }
  3863. }
  3864. }
  3865. Error GLTFDocument::_serialize_lights(Ref<GLTFState> p_state) {
  3866. if (p_state->lights.is_empty()) {
  3867. return OK;
  3868. }
  3869. Array lights;
  3870. for (GLTFLightIndex i = 0; i < p_state->lights.size(); i++) {
  3871. lights.push_back(p_state->lights[i]->to_dictionary());
  3872. }
  3873. Dictionary extensions;
  3874. if (p_state->json.has("extensions")) {
  3875. extensions = p_state->json["extensions"];
  3876. } else {
  3877. p_state->json["extensions"] = extensions;
  3878. }
  3879. Dictionary lights_punctual;
  3880. extensions["KHR_lights_punctual"] = lights_punctual;
  3881. lights_punctual["lights"] = lights;
  3882. print_verbose("glTF: Total lights: " + itos(p_state->lights.size()));
  3883. return OK;
  3884. }
  3885. Error GLTFDocument::_serialize_cameras(Ref<GLTFState> p_state) {
  3886. Array cameras;
  3887. cameras.resize(p_state->cameras.size());
  3888. for (GLTFCameraIndex i = 0; i < p_state->cameras.size(); i++) {
  3889. cameras[i] = p_state->cameras[i]->to_dictionary();
  3890. }
  3891. if (!p_state->cameras.size()) {
  3892. return OK;
  3893. }
  3894. p_state->json["cameras"] = cameras;
  3895. print_verbose("glTF: Total cameras: " + itos(p_state->cameras.size()));
  3896. return OK;
  3897. }
  3898. Error GLTFDocument::_parse_lights(Ref<GLTFState> p_state) {
  3899. if (!p_state->json.has("extensions")) {
  3900. return OK;
  3901. }
  3902. Dictionary extensions = p_state->json["extensions"];
  3903. if (!extensions.has("KHR_lights_punctual")) {
  3904. return OK;
  3905. }
  3906. Dictionary lights_punctual = extensions["KHR_lights_punctual"];
  3907. if (!lights_punctual.has("lights")) {
  3908. return OK;
  3909. }
  3910. const Array &lights = lights_punctual["lights"];
  3911. for (GLTFLightIndex light_i = 0; light_i < lights.size(); light_i++) {
  3912. Ref<GLTFLight> light = GLTFLight::from_dictionary(lights[light_i]);
  3913. if (light.is_null()) {
  3914. return Error::ERR_PARSE_ERROR;
  3915. }
  3916. p_state->lights.push_back(light);
  3917. }
  3918. print_verbose("glTF: Total lights: " + itos(p_state->lights.size()));
  3919. return OK;
  3920. }
  3921. Error GLTFDocument::_parse_cameras(Ref<GLTFState> p_state) {
  3922. if (!p_state->json.has("cameras")) {
  3923. return OK;
  3924. }
  3925. const Array cameras = p_state->json["cameras"];
  3926. for (GLTFCameraIndex i = 0; i < cameras.size(); i++) {
  3927. p_state->cameras.push_back(GLTFCamera::from_dictionary(cameras[i]));
  3928. }
  3929. print_verbose("glTF: Total cameras: " + itos(p_state->cameras.size()));
  3930. return OK;
  3931. }
  3932. String GLTFDocument::interpolation_to_string(const GLTFAnimation::Interpolation p_interp) {
  3933. String interp = "LINEAR";
  3934. if (p_interp == GLTFAnimation::INTERP_STEP) {
  3935. interp = "STEP";
  3936. } else if (p_interp == GLTFAnimation::INTERP_LINEAR) {
  3937. interp = "LINEAR";
  3938. } else if (p_interp == GLTFAnimation::INTERP_CATMULLROMSPLINE) {
  3939. interp = "CATMULLROMSPLINE";
  3940. } else if (p_interp == GLTFAnimation::INTERP_CUBIC_SPLINE) {
  3941. interp = "CUBICSPLINE";
  3942. }
  3943. return interp;
  3944. }
  3945. Error GLTFDocument::_serialize_animations(Ref<GLTFState> p_state) {
  3946. if (!p_state->animation_players.size()) {
  3947. return OK;
  3948. }
  3949. for (int32_t player_i = 0; player_i < p_state->animation_players.size(); player_i++) {
  3950. AnimationPlayer *animation_player = p_state->animation_players[player_i];
  3951. List<StringName> animations;
  3952. animation_player->get_animation_list(&animations);
  3953. for (const StringName &animation_name : animations) {
  3954. _convert_animation(p_state, animation_player, animation_name);
  3955. }
  3956. }
  3957. Array animations;
  3958. for (GLTFAnimationIndex animation_i = 0; animation_i < p_state->animations.size(); animation_i++) {
  3959. Dictionary d;
  3960. Ref<GLTFAnimation> gltf_animation = p_state->animations[animation_i];
  3961. if (!gltf_animation->get_tracks().size()) {
  3962. continue;
  3963. }
  3964. if (!gltf_animation->get_name().is_empty()) {
  3965. d["name"] = gltf_animation->get_name();
  3966. }
  3967. Array channels;
  3968. Array samplers;
  3969. for (KeyValue<int, GLTFAnimation::Track> &track_i : gltf_animation->get_tracks()) {
  3970. GLTFAnimation::Track track = track_i.value;
  3971. if (track.position_track.times.size()) {
  3972. Dictionary t;
  3973. t["sampler"] = samplers.size();
  3974. Dictionary s;
  3975. s["interpolation"] = interpolation_to_string(track.position_track.interpolation);
  3976. Vector<real_t> times = Variant(track.position_track.times);
  3977. s["input"] = _encode_accessor_as_floats(p_state, times, false);
  3978. Vector<Vector3> values = Variant(track.position_track.values);
  3979. s["output"] = _encode_accessor_as_vec3(p_state, values, false);
  3980. samplers.push_back(s);
  3981. Dictionary target;
  3982. target["path"] = "translation";
  3983. target["node"] = track_i.key;
  3984. t["target"] = target;
  3985. channels.push_back(t);
  3986. }
  3987. if (track.rotation_track.times.size()) {
  3988. Dictionary t;
  3989. t["sampler"] = samplers.size();
  3990. Dictionary s;
  3991. s["interpolation"] = interpolation_to_string(track.rotation_track.interpolation);
  3992. Vector<real_t> times = Variant(track.rotation_track.times);
  3993. s["input"] = _encode_accessor_as_floats(p_state, times, false);
  3994. Vector<Quaternion> values = track.rotation_track.values;
  3995. s["output"] = _encode_accessor_as_quaternions(p_state, values, false);
  3996. samplers.push_back(s);
  3997. Dictionary target;
  3998. target["path"] = "rotation";
  3999. target["node"] = track_i.key;
  4000. t["target"] = target;
  4001. channels.push_back(t);
  4002. }
  4003. if (track.scale_track.times.size()) {
  4004. Dictionary t;
  4005. t["sampler"] = samplers.size();
  4006. Dictionary s;
  4007. s["interpolation"] = interpolation_to_string(track.scale_track.interpolation);
  4008. Vector<real_t> times = Variant(track.scale_track.times);
  4009. s["input"] = _encode_accessor_as_floats(p_state, times, false);
  4010. Vector<Vector3> values = Variant(track.scale_track.values);
  4011. s["output"] = _encode_accessor_as_vec3(p_state, values, false);
  4012. samplers.push_back(s);
  4013. Dictionary target;
  4014. target["path"] = "scale";
  4015. target["node"] = track_i.key;
  4016. t["target"] = target;
  4017. channels.push_back(t);
  4018. }
  4019. if (track.weight_tracks.size()) {
  4020. double length = 0.0f;
  4021. for (int32_t track_idx = 0; track_idx < track.weight_tracks.size(); track_idx++) {
  4022. int32_t last_time_index = track.weight_tracks[track_idx].times.size() - 1;
  4023. length = MAX(length, track.weight_tracks[track_idx].times[last_time_index]);
  4024. }
  4025. Dictionary t;
  4026. t["sampler"] = samplers.size();
  4027. Dictionary s;
  4028. Vector<real_t> times;
  4029. const double increment = 1.0 / BAKE_FPS;
  4030. {
  4031. double time = 0.0;
  4032. bool last = false;
  4033. while (true) {
  4034. times.push_back(time);
  4035. if (last) {
  4036. break;
  4037. }
  4038. time += increment;
  4039. if (time >= length) {
  4040. last = true;
  4041. time = length;
  4042. }
  4043. }
  4044. }
  4045. for (int32_t track_idx = 0; track_idx < track.weight_tracks.size(); track_idx++) {
  4046. double time = 0.0;
  4047. bool last = false;
  4048. Vector<real_t> weight_track;
  4049. while (true) {
  4050. float weight = _interpolate_track<real_t>(track.weight_tracks[track_idx].times,
  4051. track.weight_tracks[track_idx].values,
  4052. time,
  4053. track.weight_tracks[track_idx].interpolation);
  4054. weight_track.push_back(weight);
  4055. if (last) {
  4056. break;
  4057. }
  4058. time += increment;
  4059. if (time >= length) {
  4060. last = true;
  4061. time = length;
  4062. }
  4063. }
  4064. track.weight_tracks.write[track_idx].times = times;
  4065. track.weight_tracks.write[track_idx].values = weight_track;
  4066. }
  4067. Vector<real_t> all_track_times = times;
  4068. Vector<real_t> all_track_values;
  4069. int32_t values_size = track.weight_tracks[0].values.size();
  4070. int32_t weight_tracks_size = track.weight_tracks.size();
  4071. all_track_values.resize(weight_tracks_size * values_size);
  4072. for (int k = 0; k < track.weight_tracks.size(); k++) {
  4073. Vector<real_t> wdata = track.weight_tracks[k].values;
  4074. for (int l = 0; l < wdata.size(); l++) {
  4075. int32_t index = l * weight_tracks_size + k;
  4076. ERR_BREAK(index >= all_track_values.size());
  4077. all_track_values.write[index] = wdata.write[l];
  4078. }
  4079. }
  4080. s["interpolation"] = interpolation_to_string(track.weight_tracks[track.weight_tracks.size() - 1].interpolation);
  4081. s["input"] = _encode_accessor_as_floats(p_state, all_track_times, false);
  4082. s["output"] = _encode_accessor_as_floats(p_state, all_track_values, false);
  4083. samplers.push_back(s);
  4084. Dictionary target;
  4085. target["path"] = "weights";
  4086. target["node"] = track_i.key;
  4087. t["target"] = target;
  4088. channels.push_back(t);
  4089. }
  4090. }
  4091. if (channels.size() && samplers.size()) {
  4092. d["channels"] = channels;
  4093. d["samplers"] = samplers;
  4094. animations.push_back(d);
  4095. }
  4096. }
  4097. if (!animations.size()) {
  4098. return OK;
  4099. }
  4100. p_state->json["animations"] = animations;
  4101. print_verbose("glTF: Total animations '" + itos(p_state->animations.size()) + "'.");
  4102. return OK;
  4103. }
  4104. Error GLTFDocument::_parse_animations(Ref<GLTFState> p_state) {
  4105. if (!p_state->json.has("animations")) {
  4106. return OK;
  4107. }
  4108. const Array &animations = p_state->json["animations"];
  4109. for (GLTFAnimationIndex i = 0; i < animations.size(); i++) {
  4110. const Dictionary &d = animations[i];
  4111. Ref<GLTFAnimation> animation;
  4112. animation.instantiate();
  4113. if (!d.has("channels") || !d.has("samplers")) {
  4114. continue;
  4115. }
  4116. Array channels = d["channels"];
  4117. Array samplers = d["samplers"];
  4118. if (d.has("name")) {
  4119. const String anim_name = d["name"];
  4120. const String anim_name_lower = anim_name.to_lower();
  4121. if (anim_name_lower.begins_with("loop") || anim_name_lower.ends_with("loop") || anim_name_lower.begins_with("cycle") || anim_name_lower.ends_with("cycle")) {
  4122. animation->set_loop(true);
  4123. }
  4124. animation->set_original_name(anim_name);
  4125. animation->set_name(_gen_unique_animation_name(p_state, anim_name));
  4126. }
  4127. for (int j = 0; j < channels.size(); j++) {
  4128. const Dictionary &c = channels[j];
  4129. if (!c.has("target")) {
  4130. continue;
  4131. }
  4132. const Dictionary &t = c["target"];
  4133. if (!t.has("node") || !t.has("path")) {
  4134. continue;
  4135. }
  4136. ERR_FAIL_COND_V(!c.has("sampler"), ERR_PARSE_ERROR);
  4137. const int sampler = c["sampler"];
  4138. ERR_FAIL_INDEX_V(sampler, samplers.size(), ERR_PARSE_ERROR);
  4139. GLTFNodeIndex node = t["node"];
  4140. String path = t["path"];
  4141. ERR_FAIL_INDEX_V(node, p_state->nodes.size(), ERR_PARSE_ERROR);
  4142. GLTFAnimation::Track *track = nullptr;
  4143. if (!animation->get_tracks().has(node)) {
  4144. animation->get_tracks()[node] = GLTFAnimation::Track();
  4145. }
  4146. track = &animation->get_tracks()[node];
  4147. const Dictionary &s = samplers[sampler];
  4148. ERR_FAIL_COND_V(!s.has("input"), ERR_PARSE_ERROR);
  4149. ERR_FAIL_COND_V(!s.has("output"), ERR_PARSE_ERROR);
  4150. const int input = s["input"];
  4151. const int output = s["output"];
  4152. GLTFAnimation::Interpolation interp = GLTFAnimation::INTERP_LINEAR;
  4153. int output_count = 1;
  4154. if (s.has("interpolation")) {
  4155. const String &in = s["interpolation"];
  4156. if (in == "STEP") {
  4157. interp = GLTFAnimation::INTERP_STEP;
  4158. } else if (in == "LINEAR") {
  4159. interp = GLTFAnimation::INTERP_LINEAR;
  4160. } else if (in == "CATMULLROMSPLINE") {
  4161. interp = GLTFAnimation::INTERP_CATMULLROMSPLINE;
  4162. output_count = 3;
  4163. } else if (in == "CUBICSPLINE") {
  4164. interp = GLTFAnimation::INTERP_CUBIC_SPLINE;
  4165. output_count = 3;
  4166. }
  4167. }
  4168. const Vector<float> times = _decode_accessor_as_floats(p_state, input, false);
  4169. if (path == "translation") {
  4170. const Vector<Vector3> positions = _decode_accessor_as_vec3(p_state, output, false);
  4171. track->position_track.interpolation = interp;
  4172. track->position_track.times = Variant(times); //convert via variant
  4173. track->position_track.values = Variant(positions); //convert via variant
  4174. } else if (path == "rotation") {
  4175. const Vector<Quaternion> rotations = _decode_accessor_as_quaternion(p_state, output, false);
  4176. track->rotation_track.interpolation = interp;
  4177. track->rotation_track.times = Variant(times); //convert via variant
  4178. track->rotation_track.values = rotations;
  4179. } else if (path == "scale") {
  4180. const Vector<Vector3> scales = _decode_accessor_as_vec3(p_state, output, false);
  4181. track->scale_track.interpolation = interp;
  4182. track->scale_track.times = Variant(times); //convert via variant
  4183. track->scale_track.values = Variant(scales); //convert via variant
  4184. } else if (path == "weights") {
  4185. const Vector<float> weights = _decode_accessor_as_floats(p_state, output, false);
  4186. ERR_FAIL_INDEX_V(p_state->nodes[node]->mesh, p_state->meshes.size(), ERR_PARSE_ERROR);
  4187. Ref<GLTFMesh> mesh = p_state->meshes[p_state->nodes[node]->mesh];
  4188. ERR_CONTINUE(!mesh->get_blend_weights().size());
  4189. const int wc = mesh->get_blend_weights().size();
  4190. track->weight_tracks.resize(wc);
  4191. const int expected_value_count = times.size() * output_count * wc;
  4192. ERR_CONTINUE_MSG(weights.size() != expected_value_count, "Invalid weight data, expected " + itos(expected_value_count) + " weight values, got " + itos(weights.size()) + " instead.");
  4193. const int wlen = weights.size() / wc;
  4194. for (int k = 0; k < wc; k++) { //separate tracks, having them together is not such a good idea
  4195. GLTFAnimation::Channel<real_t> cf;
  4196. cf.interpolation = interp;
  4197. cf.times = Variant(times);
  4198. Vector<real_t> wdata;
  4199. wdata.resize(wlen);
  4200. for (int l = 0; l < wlen; l++) {
  4201. wdata.write[l] = weights[l * wc + k];
  4202. }
  4203. cf.values = wdata;
  4204. track->weight_tracks.write[k] = cf;
  4205. }
  4206. } else {
  4207. WARN_PRINT("Invalid path '" + path + "'.");
  4208. }
  4209. }
  4210. p_state->animations.push_back(animation);
  4211. }
  4212. print_verbose("glTF: Total animations '" + itos(p_state->animations.size()) + "'.");
  4213. return OK;
  4214. }
  4215. void GLTFDocument::_assign_node_names(Ref<GLTFState> p_state) {
  4216. for (int i = 0; i < p_state->nodes.size(); i++) {
  4217. Ref<GLTFNode> gltf_node = p_state->nodes[i];
  4218. // Any joints get unique names generated when the skeleton is made, unique to the skeleton
  4219. if (gltf_node->skeleton >= 0) {
  4220. continue;
  4221. }
  4222. String gltf_node_name = gltf_node->get_name();
  4223. if (gltf_node_name.is_empty()) {
  4224. if (_naming_version == 0) {
  4225. if (gltf_node->mesh >= 0) {
  4226. gltf_node_name = _gen_unique_name(p_state, "Mesh");
  4227. } else if (gltf_node->camera >= 0) {
  4228. gltf_node_name = _gen_unique_name(p_state, "Camera3D");
  4229. } else {
  4230. gltf_node_name = _gen_unique_name(p_state, "Node");
  4231. }
  4232. } else {
  4233. if (gltf_node->mesh >= 0) {
  4234. gltf_node_name = "Mesh";
  4235. } else if (gltf_node->camera >= 0) {
  4236. gltf_node_name = "Camera";
  4237. } else {
  4238. gltf_node_name = "Node";
  4239. }
  4240. }
  4241. }
  4242. gltf_node->set_name(_gen_unique_name(p_state, gltf_node_name));
  4243. }
  4244. }
  4245. BoneAttachment3D *GLTFDocument::_generate_bone_attachment(Ref<GLTFState> p_state, Skeleton3D *p_skeleton, const GLTFNodeIndex p_node_index, const GLTFNodeIndex p_bone_index) {
  4246. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  4247. Ref<GLTFNode> bone_node = p_state->nodes[p_bone_index];
  4248. BoneAttachment3D *bone_attachment = memnew(BoneAttachment3D);
  4249. print_verbose("glTF: Creating bone attachment for: " + gltf_node->get_name());
  4250. ERR_FAIL_COND_V(!bone_node->joint, nullptr);
  4251. bone_attachment->set_bone_name(bone_node->get_name());
  4252. return bone_attachment;
  4253. }
  4254. GLTFMeshIndex GLTFDocument::_convert_mesh_to_gltf(Ref<GLTFState> p_state, MeshInstance3D *p_mesh_instance) {
  4255. ERR_FAIL_NULL_V(p_mesh_instance, -1);
  4256. ERR_FAIL_COND_V_MSG(p_mesh_instance->get_mesh().is_null(), -1, "glTF: Tried to export a MeshInstance3D node named " + p_mesh_instance->get_name() + ", but it has no mesh. This node will be exported without a mesh.");
  4257. Ref<Mesh> mesh_resource = p_mesh_instance->get_mesh();
  4258. ERR_FAIL_COND_V_MSG(mesh_resource->get_surface_count() == 0, -1, "glTF: Tried to export a MeshInstance3D node named " + p_mesh_instance->get_name() + ", but its mesh has no surfaces. This node will be exported without a mesh.");
  4259. Ref<ImporterMesh> current_mesh = _mesh_to_importer_mesh(mesh_resource);
  4260. Vector<float> blend_weights;
  4261. int32_t blend_count = mesh_resource->get_blend_shape_count();
  4262. blend_weights.resize(blend_count);
  4263. for (int32_t blend_i = 0; blend_i < blend_count; blend_i++) {
  4264. blend_weights.write[blend_i] = 0.0f;
  4265. }
  4266. Ref<GLTFMesh> gltf_mesh;
  4267. gltf_mesh.instantiate();
  4268. TypedArray<Material> instance_materials;
  4269. for (int32_t surface_i = 0; surface_i < current_mesh->get_surface_count(); surface_i++) {
  4270. Ref<Material> mat = current_mesh->get_surface_material(surface_i);
  4271. if (p_mesh_instance->get_surface_override_material(surface_i).is_valid()) {
  4272. mat = p_mesh_instance->get_surface_override_material(surface_i);
  4273. }
  4274. if (p_mesh_instance->get_material_override().is_valid()) {
  4275. mat = p_mesh_instance->get_material_override();
  4276. }
  4277. instance_materials.append(mat);
  4278. }
  4279. gltf_mesh->set_instance_materials(instance_materials);
  4280. gltf_mesh->set_mesh(current_mesh);
  4281. gltf_mesh->set_blend_weights(blend_weights);
  4282. GLTFMeshIndex mesh_i = p_state->meshes.size();
  4283. p_state->meshes.push_back(gltf_mesh);
  4284. return mesh_i;
  4285. }
  4286. ImporterMeshInstance3D *GLTFDocument::_generate_mesh_instance(Ref<GLTFState> p_state, const GLTFNodeIndex p_node_index) {
  4287. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  4288. ERR_FAIL_INDEX_V(gltf_node->mesh, p_state->meshes.size(), nullptr);
  4289. ImporterMeshInstance3D *mi = memnew(ImporterMeshInstance3D);
  4290. print_verbose("glTF: Creating mesh for: " + gltf_node->get_name());
  4291. p_state->scene_mesh_instances.insert(p_node_index, mi);
  4292. Ref<GLTFMesh> mesh = p_state->meshes.write[gltf_node->mesh];
  4293. if (mesh.is_null()) {
  4294. return mi;
  4295. }
  4296. Ref<ImporterMesh> import_mesh = mesh->get_mesh();
  4297. if (import_mesh.is_null()) {
  4298. return mi;
  4299. }
  4300. mi->set_mesh(import_mesh);
  4301. return mi;
  4302. }
  4303. Light3D *GLTFDocument::_generate_light(Ref<GLTFState> p_state, const GLTFNodeIndex p_node_index) {
  4304. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  4305. ERR_FAIL_INDEX_V(gltf_node->light, p_state->lights.size(), nullptr);
  4306. print_verbose("glTF: Creating light for: " + gltf_node->get_name());
  4307. Ref<GLTFLight> l = p_state->lights[gltf_node->light];
  4308. return l->to_node();
  4309. }
  4310. Camera3D *GLTFDocument::_generate_camera(Ref<GLTFState> p_state, const GLTFNodeIndex p_node_index) {
  4311. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  4312. ERR_FAIL_INDEX_V(gltf_node->camera, p_state->cameras.size(), nullptr);
  4313. print_verbose("glTF: Creating camera for: " + gltf_node->get_name());
  4314. Ref<GLTFCamera> c = p_state->cameras[gltf_node->camera];
  4315. return c->to_node();
  4316. }
  4317. GLTFCameraIndex GLTFDocument::_convert_camera(Ref<GLTFState> p_state, Camera3D *p_camera) {
  4318. print_verbose("glTF: Converting camera: " + p_camera->get_name());
  4319. Ref<GLTFCamera> c = GLTFCamera::from_node(p_camera);
  4320. GLTFCameraIndex camera_index = p_state->cameras.size();
  4321. p_state->cameras.push_back(c);
  4322. return camera_index;
  4323. }
  4324. GLTFLightIndex GLTFDocument::_convert_light(Ref<GLTFState> p_state, Light3D *p_light) {
  4325. print_verbose("glTF: Converting light: " + p_light->get_name());
  4326. Ref<GLTFLight> l = GLTFLight::from_node(p_light);
  4327. GLTFLightIndex light_index = p_state->lights.size();
  4328. p_state->lights.push_back(l);
  4329. return light_index;
  4330. }
  4331. void GLTFDocument::_convert_spatial(Ref<GLTFState> p_state, Node3D *p_spatial, Ref<GLTFNode> p_node) {
  4332. p_node->transform = p_spatial->get_transform();
  4333. }
  4334. Node3D *GLTFDocument::_generate_spatial(Ref<GLTFState> p_state, const GLTFNodeIndex p_node_index) {
  4335. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  4336. Node3D *spatial = memnew(Node3D);
  4337. print_verbose("glTF: Converting spatial: " + gltf_node->get_name());
  4338. return spatial;
  4339. }
  4340. void GLTFDocument::_convert_scene_node(Ref<GLTFState> p_state, Node *p_current, const GLTFNodeIndex p_gltf_parent, const GLTFNodeIndex p_gltf_root) {
  4341. bool retflag = true;
  4342. _check_visibility(p_current, retflag);
  4343. if (retflag) {
  4344. return;
  4345. }
  4346. #ifdef TOOLS_ENABLED
  4347. if (Engine::get_singleton()->is_editor_hint() && p_gltf_root != -1 && p_current->get_owner() == nullptr) {
  4348. WARN_VERBOSE("glTF export warning: Node '" + p_current->get_name() + "' has no owner. This is likely a temporary node generated by a @tool script. This would not be saved when saving the Godot scene, therefore it will not be exported to glTF.");
  4349. return;
  4350. }
  4351. #endif // TOOLS_ENABLED
  4352. Ref<GLTFNode> gltf_node;
  4353. gltf_node.instantiate();
  4354. gltf_node->set_original_name(p_current->get_name());
  4355. gltf_node->set_name(_gen_unique_name(p_state, p_current->get_name()));
  4356. if (cast_to<Node3D>(p_current)) {
  4357. Node3D *spatial = cast_to<Node3D>(p_current);
  4358. _convert_spatial(p_state, spatial, gltf_node);
  4359. }
  4360. if (cast_to<MeshInstance3D>(p_current)) {
  4361. MeshInstance3D *mi = cast_to<MeshInstance3D>(p_current);
  4362. _convert_mesh_instance_to_gltf(mi, p_state, gltf_node);
  4363. } else if (cast_to<BoneAttachment3D>(p_current)) {
  4364. BoneAttachment3D *bone = cast_to<BoneAttachment3D>(p_current);
  4365. _convert_bone_attachment_to_gltf(bone, p_state, p_gltf_parent, p_gltf_root, gltf_node);
  4366. return;
  4367. } else if (cast_to<Skeleton3D>(p_current)) {
  4368. Skeleton3D *skel = cast_to<Skeleton3D>(p_current);
  4369. _convert_skeleton_to_gltf(skel, p_state, p_gltf_parent, p_gltf_root, gltf_node);
  4370. // We ignore the Godot Engine node that is the skeleton.
  4371. return;
  4372. } else if (cast_to<MultiMeshInstance3D>(p_current)) {
  4373. MultiMeshInstance3D *multi = cast_to<MultiMeshInstance3D>(p_current);
  4374. _convert_multi_mesh_instance_to_gltf(multi, p_gltf_parent, p_gltf_root, gltf_node, p_state);
  4375. #ifdef MODULE_CSG_ENABLED
  4376. } else if (cast_to<CSGShape3D>(p_current)) {
  4377. CSGShape3D *shape = cast_to<CSGShape3D>(p_current);
  4378. if (shape->get_parent() && shape->is_root_shape()) {
  4379. _convert_csg_shape_to_gltf(shape, p_gltf_parent, gltf_node, p_state);
  4380. }
  4381. #endif // MODULE_CSG_ENABLED
  4382. #ifdef MODULE_GRIDMAP_ENABLED
  4383. } else if (cast_to<GridMap>(p_current)) {
  4384. GridMap *gridmap = Object::cast_to<GridMap>(p_current);
  4385. _convert_grid_map_to_gltf(gridmap, p_gltf_parent, p_gltf_root, gltf_node, p_state);
  4386. #endif // MODULE_GRIDMAP_ENABLED
  4387. } else if (cast_to<Camera3D>(p_current)) {
  4388. Camera3D *camera = Object::cast_to<Camera3D>(p_current);
  4389. _convert_camera_to_gltf(camera, p_state, gltf_node);
  4390. } else if (cast_to<Light3D>(p_current)) {
  4391. Light3D *light = Object::cast_to<Light3D>(p_current);
  4392. _convert_light_to_gltf(light, p_state, gltf_node);
  4393. } else if (cast_to<AnimationPlayer>(p_current)) {
  4394. AnimationPlayer *animation_player = Object::cast_to<AnimationPlayer>(p_current);
  4395. _convert_animation_player_to_gltf(animation_player, p_state, p_gltf_parent, p_gltf_root, gltf_node, p_current);
  4396. }
  4397. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  4398. ERR_CONTINUE(ext.is_null());
  4399. ext->convert_scene_node(p_state, gltf_node, p_current);
  4400. }
  4401. GLTFNodeIndex current_node_i = p_state->nodes.size();
  4402. GLTFNodeIndex gltf_root = p_gltf_root;
  4403. if (gltf_root == -1) {
  4404. gltf_root = current_node_i;
  4405. p_state->root_nodes.push_back(gltf_root);
  4406. }
  4407. _create_gltf_node(p_state, p_current, current_node_i, p_gltf_parent, gltf_root, gltf_node);
  4408. for (int node_i = 0; node_i < p_current->get_child_count(); node_i++) {
  4409. _convert_scene_node(p_state, p_current->get_child(node_i), current_node_i, gltf_root);
  4410. }
  4411. }
  4412. #ifdef MODULE_CSG_ENABLED
  4413. void GLTFDocument::_convert_csg_shape_to_gltf(CSGShape3D *p_current, GLTFNodeIndex p_gltf_parent, Ref<GLTFNode> p_gltf_node, Ref<GLTFState> p_state) {
  4414. CSGShape3D *csg = p_current;
  4415. csg->call("_update_shape");
  4416. Array meshes = csg->get_meshes();
  4417. if (meshes.size() != 2) {
  4418. return;
  4419. }
  4420. Ref<ImporterMesh> mesh;
  4421. mesh.instantiate();
  4422. {
  4423. Ref<Mesh> csg_mesh = csg->get_meshes()[1];
  4424. for (int32_t surface_i = 0; surface_i < csg_mesh->get_surface_count(); surface_i++) {
  4425. Array array = csg_mesh->surface_get_arrays(surface_i);
  4426. Ref<Material> mat = csg_mesh->surface_get_material(surface_i);
  4427. String mat_name;
  4428. if (mat.is_valid()) {
  4429. mat_name = mat->get_name();
  4430. } else {
  4431. // Assign default material when no material is assigned.
  4432. mat = Ref<StandardMaterial3D>(memnew(StandardMaterial3D));
  4433. }
  4434. mesh->add_surface(csg_mesh->surface_get_primitive_type(surface_i),
  4435. array, csg_mesh->surface_get_blend_shape_arrays(surface_i), csg_mesh->surface_get_lods(surface_i), mat,
  4436. mat_name, csg_mesh->surface_get_format(surface_i));
  4437. }
  4438. }
  4439. Ref<GLTFMesh> gltf_mesh;
  4440. gltf_mesh.instantiate();
  4441. gltf_mesh->set_mesh(mesh);
  4442. gltf_mesh->set_original_name(csg->get_name());
  4443. GLTFMeshIndex mesh_i = p_state->meshes.size();
  4444. p_state->meshes.push_back(gltf_mesh);
  4445. p_gltf_node->mesh = mesh_i;
  4446. p_gltf_node->transform = csg->get_meshes()[0];
  4447. p_gltf_node->set_original_name(csg->get_name());
  4448. p_gltf_node->set_name(_gen_unique_name(p_state, csg->get_name()));
  4449. }
  4450. #endif // MODULE_CSG_ENABLED
  4451. void GLTFDocument::_create_gltf_node(Ref<GLTFState> p_state, Node *p_scene_parent, GLTFNodeIndex p_current_node_i,
  4452. GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_gltf_node, Ref<GLTFNode> p_gltf_node) {
  4453. p_state->scene_nodes.insert(p_current_node_i, p_scene_parent);
  4454. p_state->nodes.push_back(p_gltf_node);
  4455. ERR_FAIL_COND(p_current_node_i == p_parent_node_index);
  4456. p_state->nodes.write[p_current_node_i]->parent = p_parent_node_index;
  4457. if (p_parent_node_index == -1) {
  4458. return;
  4459. }
  4460. p_state->nodes.write[p_parent_node_index]->children.push_back(p_current_node_i);
  4461. }
  4462. void GLTFDocument::_convert_animation_player_to_gltf(AnimationPlayer *p_animation_player, Ref<GLTFState> p_state, GLTFNodeIndex p_gltf_current, GLTFNodeIndex p_gltf_root_index, Ref<GLTFNode> p_gltf_node, Node *p_scene_parent) {
  4463. ERR_FAIL_NULL(p_animation_player);
  4464. p_state->animation_players.push_back(p_animation_player);
  4465. print_verbose(String("glTF: Converting animation player: ") + p_animation_player->get_name());
  4466. }
  4467. void GLTFDocument::_check_visibility(Node *p_node, bool &r_retflag) {
  4468. r_retflag = true;
  4469. Node3D *spatial = Object::cast_to<Node3D>(p_node);
  4470. Node2D *node_2d = Object::cast_to<Node2D>(p_node);
  4471. if (node_2d && !node_2d->is_visible()) {
  4472. return;
  4473. }
  4474. if (spatial && !spatial->is_visible()) {
  4475. return;
  4476. }
  4477. r_retflag = false;
  4478. }
  4479. void GLTFDocument::_convert_camera_to_gltf(Camera3D *camera, Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node) {
  4480. ERR_FAIL_NULL(camera);
  4481. GLTFCameraIndex camera_index = _convert_camera(p_state, camera);
  4482. if (camera_index != -1) {
  4483. p_gltf_node->camera = camera_index;
  4484. }
  4485. }
  4486. void GLTFDocument::_convert_light_to_gltf(Light3D *light, Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node) {
  4487. ERR_FAIL_NULL(light);
  4488. GLTFLightIndex light_index = _convert_light(p_state, light);
  4489. if (light_index != -1) {
  4490. p_gltf_node->light = light_index;
  4491. }
  4492. }
  4493. #ifdef MODULE_GRIDMAP_ENABLED
  4494. void GLTFDocument::_convert_grid_map_to_gltf(GridMap *p_grid_map, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_node_index, Ref<GLTFNode> p_gltf_node, Ref<GLTFState> p_state) {
  4495. Array cells = p_grid_map->get_used_cells();
  4496. for (int32_t k = 0; k < cells.size(); k++) {
  4497. GLTFNode *new_gltf_node = memnew(GLTFNode);
  4498. p_gltf_node->children.push_back(p_state->nodes.size());
  4499. p_state->nodes.push_back(new_gltf_node);
  4500. Vector3 cell_location = cells[k];
  4501. int32_t cell = p_grid_map->get_cell_item(
  4502. Vector3(cell_location.x, cell_location.y, cell_location.z));
  4503. Transform3D cell_xform;
  4504. cell_xform.basis = p_grid_map->get_basis_with_orthogonal_index(
  4505. p_grid_map->get_cell_item_orientation(
  4506. Vector3(cell_location.x, cell_location.y, cell_location.z)));
  4507. cell_xform.basis.scale(Vector3(p_grid_map->get_cell_scale(),
  4508. p_grid_map->get_cell_scale(),
  4509. p_grid_map->get_cell_scale()));
  4510. cell_xform.set_origin(p_grid_map->map_to_local(
  4511. Vector3(cell_location.x, cell_location.y, cell_location.z)));
  4512. Ref<GLTFMesh> gltf_mesh;
  4513. gltf_mesh.instantiate();
  4514. gltf_mesh->set_mesh(_mesh_to_importer_mesh(p_grid_map->get_mesh_library()->get_item_mesh(cell)));
  4515. gltf_mesh->set_original_name(p_grid_map->get_mesh_library()->get_item_name(cell));
  4516. new_gltf_node->mesh = p_state->meshes.size();
  4517. p_state->meshes.push_back(gltf_mesh);
  4518. new_gltf_node->transform = cell_xform * p_grid_map->get_transform();
  4519. new_gltf_node->set_original_name(p_grid_map->get_mesh_library()->get_item_name(cell));
  4520. new_gltf_node->set_name(_gen_unique_name(p_state, p_grid_map->get_mesh_library()->get_item_name(cell)));
  4521. }
  4522. }
  4523. #endif // MODULE_GRIDMAP_ENABLED
  4524. void GLTFDocument::_convert_multi_mesh_instance_to_gltf(
  4525. MultiMeshInstance3D *p_multi_mesh_instance,
  4526. GLTFNodeIndex p_parent_node_index,
  4527. GLTFNodeIndex p_root_node_index,
  4528. Ref<GLTFNode> p_gltf_node, Ref<GLTFState> p_state) {
  4529. ERR_FAIL_NULL(p_multi_mesh_instance);
  4530. Ref<MultiMesh> multi_mesh = p_multi_mesh_instance->get_multimesh();
  4531. if (multi_mesh.is_null()) {
  4532. return;
  4533. }
  4534. Ref<GLTFMesh> gltf_mesh;
  4535. gltf_mesh.instantiate();
  4536. Ref<Mesh> mesh = multi_mesh->get_mesh();
  4537. if (mesh.is_null()) {
  4538. return;
  4539. }
  4540. gltf_mesh->set_original_name(multi_mesh->get_name());
  4541. gltf_mesh->set_name(multi_mesh->get_name());
  4542. Ref<ImporterMesh> importer_mesh;
  4543. importer_mesh.instantiate();
  4544. Ref<ArrayMesh> array_mesh = multi_mesh->get_mesh();
  4545. if (array_mesh.is_valid()) {
  4546. importer_mesh->set_blend_shape_mode(array_mesh->get_blend_shape_mode());
  4547. for (int32_t blend_i = 0; blend_i < array_mesh->get_blend_shape_count(); blend_i++) {
  4548. importer_mesh->add_blend_shape(array_mesh->get_blend_shape_name(blend_i));
  4549. }
  4550. }
  4551. for (int32_t surface_i = 0; surface_i < mesh->get_surface_count(); surface_i++) {
  4552. Ref<Material> mat = mesh->surface_get_material(surface_i);
  4553. String material_name;
  4554. if (mat.is_valid()) {
  4555. material_name = mat->get_name();
  4556. }
  4557. Array blend_arrays;
  4558. if (array_mesh.is_valid()) {
  4559. blend_arrays = array_mesh->surface_get_blend_shape_arrays(surface_i);
  4560. }
  4561. importer_mesh->add_surface(mesh->surface_get_primitive_type(surface_i), mesh->surface_get_arrays(surface_i),
  4562. blend_arrays, mesh->surface_get_lods(surface_i), mat, material_name, mesh->surface_get_format(surface_i));
  4563. }
  4564. gltf_mesh->set_mesh(importer_mesh);
  4565. GLTFMeshIndex mesh_index = p_state->meshes.size();
  4566. p_state->meshes.push_back(gltf_mesh);
  4567. for (int32_t instance_i = 0; instance_i < multi_mesh->get_instance_count();
  4568. instance_i++) {
  4569. Transform3D transform;
  4570. if (multi_mesh->get_transform_format() == MultiMesh::TRANSFORM_2D) {
  4571. Transform2D xform_2d = multi_mesh->get_instance_transform_2d(instance_i);
  4572. transform.origin =
  4573. Vector3(xform_2d.get_origin().x, 0, xform_2d.get_origin().y);
  4574. real_t rotation = xform_2d.get_rotation();
  4575. Quaternion quaternion(Vector3(0, 1, 0), rotation);
  4576. Size2 scale = xform_2d.get_scale();
  4577. transform.basis.set_quaternion_scale(quaternion,
  4578. Vector3(scale.x, 0, scale.y));
  4579. transform = p_multi_mesh_instance->get_transform() * transform;
  4580. } else if (multi_mesh->get_transform_format() == MultiMesh::TRANSFORM_3D) {
  4581. transform = p_multi_mesh_instance->get_transform() *
  4582. multi_mesh->get_instance_transform(instance_i);
  4583. }
  4584. Ref<GLTFNode> new_gltf_node;
  4585. new_gltf_node.instantiate();
  4586. new_gltf_node->mesh = mesh_index;
  4587. new_gltf_node->transform = transform;
  4588. new_gltf_node->set_original_name(p_multi_mesh_instance->get_name());
  4589. new_gltf_node->set_name(_gen_unique_name(p_state, p_multi_mesh_instance->get_name()));
  4590. p_gltf_node->children.push_back(p_state->nodes.size());
  4591. p_state->nodes.push_back(new_gltf_node);
  4592. }
  4593. }
  4594. void GLTFDocument::_convert_skeleton_to_gltf(Skeleton3D *p_skeleton3d, Ref<GLTFState> p_state, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_node_index, Ref<GLTFNode> p_gltf_node) {
  4595. Skeleton3D *skeleton = p_skeleton3d;
  4596. Ref<GLTFSkeleton> gltf_skeleton;
  4597. gltf_skeleton.instantiate();
  4598. // GLTFSkeleton is only used to hold internal p_state data. It will not be written to the document.
  4599. //
  4600. gltf_skeleton->godot_skeleton = skeleton;
  4601. GLTFSkeletonIndex skeleton_i = p_state->skeletons.size();
  4602. p_state->skeleton3d_to_gltf_skeleton[skeleton->get_instance_id()] = skeleton_i;
  4603. p_state->skeletons.push_back(gltf_skeleton);
  4604. BoneId bone_count = skeleton->get_bone_count();
  4605. for (BoneId bone_i = 0; bone_i < bone_count; bone_i++) {
  4606. Ref<GLTFNode> joint_node;
  4607. joint_node.instantiate();
  4608. // Note that we cannot use _gen_unique_bone_name here, because glTF spec requires all node
  4609. // names to be unique regardless of whether or not they are used as joints.
  4610. joint_node->set_original_name(skeleton->get_bone_name(bone_i));
  4611. joint_node->set_name(_gen_unique_name(p_state, skeleton->get_bone_name(bone_i)));
  4612. joint_node->transform = skeleton->get_bone_pose(bone_i);
  4613. joint_node->joint = true;
  4614. GLTFNodeIndex current_node_i = p_state->nodes.size();
  4615. p_state->scene_nodes.insert(current_node_i, skeleton);
  4616. p_state->nodes.push_back(joint_node);
  4617. gltf_skeleton->joints.push_back(current_node_i);
  4618. if (skeleton->get_bone_parent(bone_i) == -1) {
  4619. gltf_skeleton->roots.push_back(current_node_i);
  4620. }
  4621. gltf_skeleton->godot_bone_node.insert(bone_i, current_node_i);
  4622. }
  4623. for (BoneId bone_i = 0; bone_i < bone_count; bone_i++) {
  4624. GLTFNodeIndex current_node_i = gltf_skeleton->godot_bone_node[bone_i];
  4625. BoneId parent_bone_id = skeleton->get_bone_parent(bone_i);
  4626. if (parent_bone_id == -1) {
  4627. if (p_parent_node_index != -1) {
  4628. p_state->nodes.write[current_node_i]->parent = p_parent_node_index;
  4629. p_state->nodes.write[p_parent_node_index]->children.push_back(current_node_i);
  4630. }
  4631. } else {
  4632. GLTFNodeIndex parent_node_i = gltf_skeleton->godot_bone_node[parent_bone_id];
  4633. p_state->nodes.write[current_node_i]->parent = parent_node_i;
  4634. p_state->nodes.write[parent_node_i]->children.push_back(current_node_i);
  4635. }
  4636. }
  4637. // Remove placeholder skeleton3d node by not creating the gltf node
  4638. // Skins are per mesh
  4639. for (int node_i = 0; node_i < skeleton->get_child_count(); node_i++) {
  4640. _convert_scene_node(p_state, skeleton->get_child(node_i), p_parent_node_index, p_root_node_index);
  4641. }
  4642. }
  4643. void GLTFDocument::_convert_bone_attachment_to_gltf(BoneAttachment3D *p_bone_attachment, Ref<GLTFState> p_state, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_node_index, Ref<GLTFNode> p_gltf_node) {
  4644. Skeleton3D *skeleton;
  4645. // Note that relative transforms to external skeletons and pose overrides are not supported.
  4646. if (p_bone_attachment->get_use_external_skeleton()) {
  4647. skeleton = cast_to<Skeleton3D>(p_bone_attachment->get_node_or_null(p_bone_attachment->get_external_skeleton()));
  4648. } else {
  4649. skeleton = cast_to<Skeleton3D>(p_bone_attachment->get_parent());
  4650. }
  4651. GLTFSkeletonIndex skel_gltf_i = -1;
  4652. if (skeleton != nullptr && p_state->skeleton3d_to_gltf_skeleton.has(skeleton->get_instance_id())) {
  4653. skel_gltf_i = p_state->skeleton3d_to_gltf_skeleton[skeleton->get_instance_id()];
  4654. }
  4655. int bone_idx = -1;
  4656. if (skeleton != nullptr) {
  4657. bone_idx = p_bone_attachment->get_bone_idx();
  4658. if (bone_idx == -1) {
  4659. bone_idx = skeleton->find_bone(p_bone_attachment->get_bone_name());
  4660. }
  4661. }
  4662. GLTFNodeIndex par_node_index = p_parent_node_index;
  4663. if (skeleton != nullptr && bone_idx != -1 && skel_gltf_i != -1) {
  4664. Ref<GLTFSkeleton> gltf_skeleton = p_state->skeletons.write[skel_gltf_i];
  4665. gltf_skeleton->bone_attachments.push_back(p_bone_attachment);
  4666. par_node_index = gltf_skeleton->joints[bone_idx];
  4667. }
  4668. for (int node_i = 0; node_i < p_bone_attachment->get_child_count(); node_i++) {
  4669. _convert_scene_node(p_state, p_bone_attachment->get_child(node_i), par_node_index, p_root_node_index);
  4670. }
  4671. }
  4672. void GLTFDocument::_convert_mesh_instance_to_gltf(MeshInstance3D *p_scene_parent, Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node) {
  4673. GLTFMeshIndex gltf_mesh_index = _convert_mesh_to_gltf(p_state, p_scene_parent);
  4674. if (gltf_mesh_index != -1) {
  4675. p_gltf_node->mesh = gltf_mesh_index;
  4676. }
  4677. }
  4678. void GLTFDocument::_generate_scene_node(Ref<GLTFState> p_state, const GLTFNodeIndex p_node_index, Node *p_scene_parent, Node *p_scene_root) {
  4679. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  4680. if (gltf_node->skeleton >= 0) {
  4681. _generate_skeleton_bone_node(p_state, p_node_index, p_scene_parent, p_scene_root);
  4682. return;
  4683. }
  4684. Node3D *current_node = nullptr;
  4685. // Is our parent a skeleton
  4686. Skeleton3D *active_skeleton = Object::cast_to<Skeleton3D>(p_scene_parent);
  4687. const bool non_bone_parented_to_skeleton = active_skeleton;
  4688. // skinned meshes must not be placed in a bone attachment.
  4689. if (non_bone_parented_to_skeleton && gltf_node->skin < 0) {
  4690. // Bone Attachment - Parent Case
  4691. BoneAttachment3D *bone_attachment = _generate_bone_attachment(p_state, active_skeleton, p_node_index, gltf_node->parent);
  4692. p_scene_parent->add_child(bone_attachment, true);
  4693. // Find the correct bone_idx so we can properly serialize it.
  4694. bone_attachment->set_bone_idx(active_skeleton->find_bone(gltf_node->get_name()));
  4695. bone_attachment->set_owner(p_scene_root);
  4696. // There is no gltf_node that represent this, so just directly create a unique name
  4697. bone_attachment->set_name(gltf_node->get_name());
  4698. // We change the scene_parent to our bone attachment now. We do not set current_node because we want to make the node
  4699. // and attach it to the bone_attachment
  4700. p_scene_parent = bone_attachment;
  4701. }
  4702. // Check if any GLTFDocumentExtension classes want to generate a node for us.
  4703. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  4704. ERR_CONTINUE(ext.is_null());
  4705. current_node = ext->generate_scene_node(p_state, gltf_node, p_scene_parent);
  4706. if (current_node) {
  4707. break;
  4708. }
  4709. }
  4710. // If none of our GLTFDocumentExtension classes generated us a node, we generate one.
  4711. if (!current_node) {
  4712. if (gltf_node->skin >= 0 && gltf_node->mesh >= 0 && !gltf_node->children.is_empty()) {
  4713. // GLTF specifies that skinned meshes should ignore their node transforms,
  4714. // only being controlled by the skeleton, so Godot will reparent a skinned
  4715. // mesh to its skeleton. However, we still need to ensure any child nodes
  4716. // keep their place in the tree, so if there are any child nodes, the skinned
  4717. // mesh must not be the base node, so generate an empty spatial base.
  4718. current_node = _generate_spatial(p_state, p_node_index);
  4719. Node3D *mesh_inst = _generate_mesh_instance(p_state, p_node_index);
  4720. mesh_inst->set_name(gltf_node->get_name());
  4721. current_node->add_child(mesh_inst, true);
  4722. } else if (gltf_node->mesh >= 0) {
  4723. current_node = _generate_mesh_instance(p_state, p_node_index);
  4724. } else if (gltf_node->camera >= 0) {
  4725. current_node = _generate_camera(p_state, p_node_index);
  4726. } else if (gltf_node->light >= 0) {
  4727. current_node = _generate_light(p_state, p_node_index);
  4728. } else {
  4729. current_node = _generate_spatial(p_state, p_node_index);
  4730. }
  4731. }
  4732. String gltf_node_name = gltf_node->get_name();
  4733. if (!gltf_node_name.is_empty()) {
  4734. current_node->set_name(gltf_node_name);
  4735. }
  4736. // Note: p_scene_parent and p_scene_root must either both be null or both be valid.
  4737. if (p_scene_root == nullptr) {
  4738. // If the root node argument is null, this is the root node.
  4739. p_scene_root = current_node;
  4740. } else {
  4741. // Add the node we generated and set the owner to the scene root.
  4742. p_scene_parent->add_child(current_node, true);
  4743. Array args;
  4744. args.append(p_scene_root);
  4745. current_node->propagate_call(StringName("set_owner"), args);
  4746. current_node->set_transform(gltf_node->transform);
  4747. }
  4748. p_state->scene_nodes.insert(p_node_index, current_node);
  4749. for (int i = 0; i < gltf_node->children.size(); ++i) {
  4750. _generate_scene_node(p_state, gltf_node->children[i], current_node, p_scene_root);
  4751. }
  4752. }
  4753. void GLTFDocument::_generate_skeleton_bone_node(Ref<GLTFState> p_state, const GLTFNodeIndex p_node_index, Node *p_scene_parent, Node *p_scene_root) {
  4754. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  4755. Node3D *current_node = nullptr;
  4756. Skeleton3D *skeleton = p_state->skeletons[gltf_node->skeleton]->godot_skeleton;
  4757. // In this case, this node is already a bone in skeleton.
  4758. const bool is_skinned_mesh = (gltf_node->skin >= 0 && gltf_node->mesh >= 0);
  4759. const bool requires_extra_node = (gltf_node->mesh >= 0 || gltf_node->camera >= 0 || gltf_node->light >= 0);
  4760. Skeleton3D *active_skeleton = Object::cast_to<Skeleton3D>(p_scene_parent);
  4761. if (active_skeleton != skeleton) {
  4762. if (active_skeleton) {
  4763. // Should no longer be possible.
  4764. ERR_PRINT(vformat("glTF: Generating scene detected direct parented Skeletons at node %d", p_node_index));
  4765. BoneAttachment3D *bone_attachment = _generate_bone_attachment(p_state, active_skeleton, p_node_index, gltf_node->parent);
  4766. p_scene_parent->add_child(bone_attachment, true);
  4767. bone_attachment->set_owner(p_scene_root);
  4768. // There is no gltf_node that represent this, so just directly create a unique name
  4769. bone_attachment->set_name(_gen_unique_name(p_state, "BoneAttachment3D"));
  4770. // We change the scene_parent to our bone attachment now. We do not set current_node because we want to make the node
  4771. // and attach it to the bone_attachment
  4772. p_scene_parent = bone_attachment;
  4773. }
  4774. if (skeleton->get_parent() == nullptr) {
  4775. if (p_scene_root) {
  4776. p_scene_parent->add_child(skeleton, true);
  4777. skeleton->set_owner(p_scene_root);
  4778. } else {
  4779. p_scene_parent = skeleton;
  4780. p_scene_root = skeleton;
  4781. }
  4782. }
  4783. }
  4784. active_skeleton = skeleton;
  4785. current_node = active_skeleton;
  4786. if (requires_extra_node) {
  4787. current_node = nullptr;
  4788. // skinned meshes must not be placed in a bone attachment.
  4789. if (!is_skinned_mesh) {
  4790. // Bone Attachment - Same Node Case
  4791. BoneAttachment3D *bone_attachment = _generate_bone_attachment(p_state, active_skeleton, p_node_index, p_node_index);
  4792. p_scene_parent->add_child(bone_attachment, true);
  4793. // Find the correct bone_idx so we can properly serialize it.
  4794. bone_attachment->set_bone_idx(active_skeleton->find_bone(gltf_node->get_name()));
  4795. bone_attachment->set_owner(p_scene_root);
  4796. // There is no gltf_node that represent this, so just directly create a unique name
  4797. bone_attachment->set_name(gltf_node->get_name());
  4798. // We change the scene_parent to our bone attachment now. We do not set current_node because we want to make the node
  4799. // and attach it to the bone_attachment
  4800. p_scene_parent = bone_attachment;
  4801. }
  4802. // Check if any GLTFDocumentExtension classes want to generate a node for us.
  4803. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  4804. ERR_CONTINUE(ext.is_null());
  4805. current_node = ext->generate_scene_node(p_state, gltf_node, p_scene_parent);
  4806. if (current_node) {
  4807. break;
  4808. }
  4809. }
  4810. // If none of our GLTFDocumentExtension classes generated us a node, we generate one.
  4811. if (!current_node) {
  4812. if (gltf_node->mesh >= 0) {
  4813. current_node = _generate_mesh_instance(p_state, p_node_index);
  4814. } else if (gltf_node->camera >= 0) {
  4815. current_node = _generate_camera(p_state, p_node_index);
  4816. } else if (gltf_node->light >= 0) {
  4817. current_node = _generate_light(p_state, p_node_index);
  4818. } else {
  4819. current_node = _generate_spatial(p_state, p_node_index);
  4820. }
  4821. }
  4822. // Add the node we generated and set the owner to the scene root.
  4823. p_scene_parent->add_child(current_node, true);
  4824. if (current_node != p_scene_root) {
  4825. Array args;
  4826. args.append(p_scene_root);
  4827. current_node->propagate_call(StringName("set_owner"), args);
  4828. }
  4829. // Do not set transform here. Transform is already applied to our bone.
  4830. current_node->set_name(gltf_node->get_name());
  4831. }
  4832. p_state->scene_nodes.insert(p_node_index, current_node);
  4833. for (int i = 0; i < gltf_node->children.size(); ++i) {
  4834. _generate_scene_node(p_state, gltf_node->children[i], active_skeleton, p_scene_root);
  4835. }
  4836. }
  4837. template <class T>
  4838. struct SceneFormatImporterGLTFInterpolate {
  4839. T lerp(const T &a, const T &b, float c) const {
  4840. return a + (b - a) * c;
  4841. }
  4842. T catmull_rom(const T &p0, const T &p1, const T &p2, const T &p3, float t) {
  4843. const float t2 = t * t;
  4844. const float t3 = t2 * t;
  4845. return 0.5f * ((2.0f * p1) + (-p0 + p2) * t + (2.0f * p0 - 5.0f * p1 + 4.0f * p2 - p3) * t2 + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3);
  4846. }
  4847. T bezier(T start, T control_1, T control_2, T end, float t) {
  4848. /* Formula from Wikipedia article on Bezier curves. */
  4849. const real_t omt = (1.0 - t);
  4850. const real_t omt2 = omt * omt;
  4851. const real_t omt3 = omt2 * omt;
  4852. const real_t t2 = t * t;
  4853. const real_t t3 = t2 * t;
  4854. return start * omt3 + control_1 * omt2 * t * 3.0 + control_2 * omt * t2 * 3.0 + end * t3;
  4855. }
  4856. };
  4857. // thank you for existing, partial specialization
  4858. template <>
  4859. struct SceneFormatImporterGLTFInterpolate<Quaternion> {
  4860. Quaternion lerp(const Quaternion &a, const Quaternion &b, const float c) const {
  4861. ERR_FAIL_COND_V_MSG(!a.is_normalized(), Quaternion(), vformat("The quaternion \"a\" %s must be normalized.", a));
  4862. ERR_FAIL_COND_V_MSG(!b.is_normalized(), Quaternion(), vformat("The quaternion \"b\" %s must be normalized.", b));
  4863. return a.slerp(b, c).normalized();
  4864. }
  4865. Quaternion catmull_rom(const Quaternion &p0, const Quaternion &p1, const Quaternion &p2, const Quaternion &p3, const float c) {
  4866. ERR_FAIL_COND_V_MSG(!p1.is_normalized(), Quaternion(), vformat("The quaternion \"p1\" (%s) must be normalized.", p1));
  4867. ERR_FAIL_COND_V_MSG(!p2.is_normalized(), Quaternion(), vformat("The quaternion \"p2\" (%s) must be normalized.", p2));
  4868. return p1.slerp(p2, c).normalized();
  4869. }
  4870. Quaternion bezier(const Quaternion start, const Quaternion control_1, const Quaternion control_2, const Quaternion end, const float t) {
  4871. ERR_FAIL_COND_V_MSG(!start.is_normalized(), Quaternion(), vformat("The start quaternion %s must be normalized.", start));
  4872. ERR_FAIL_COND_V_MSG(!end.is_normalized(), Quaternion(), vformat("The end quaternion %s must be normalized.", end));
  4873. return start.slerp(end, t).normalized();
  4874. }
  4875. };
  4876. template <class T>
  4877. T GLTFDocument::_interpolate_track(const Vector<real_t> &p_times, const Vector<T> &p_values, const float p_time, const GLTFAnimation::Interpolation p_interp) {
  4878. ERR_FAIL_COND_V(p_values.is_empty(), T());
  4879. if (p_times.size() != (p_values.size() / (p_interp == GLTFAnimation::INTERP_CUBIC_SPLINE ? 3 : 1))) {
  4880. ERR_PRINT_ONCE("The interpolated values are not corresponding to its times.");
  4881. return p_values[0];
  4882. }
  4883. //could use binary search, worth it?
  4884. int idx = -1;
  4885. for (int i = 0; i < p_times.size(); i++) {
  4886. if (p_times[i] > p_time) {
  4887. break;
  4888. }
  4889. idx++;
  4890. }
  4891. SceneFormatImporterGLTFInterpolate<T> interp;
  4892. switch (p_interp) {
  4893. case GLTFAnimation::INTERP_LINEAR: {
  4894. if (idx == -1) {
  4895. return p_values[0];
  4896. } else if (idx >= p_times.size() - 1) {
  4897. return p_values[p_times.size() - 1];
  4898. }
  4899. const float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  4900. return interp.lerp(p_values[idx], p_values[idx + 1], c);
  4901. } break;
  4902. case GLTFAnimation::INTERP_STEP: {
  4903. if (idx == -1) {
  4904. return p_values[0];
  4905. } else if (idx >= p_times.size() - 1) {
  4906. return p_values[p_times.size() - 1];
  4907. }
  4908. return p_values[idx];
  4909. } break;
  4910. case GLTFAnimation::INTERP_CATMULLROMSPLINE: {
  4911. if (idx == -1) {
  4912. return p_values[1];
  4913. } else if (idx >= p_times.size() - 1) {
  4914. return p_values[1 + p_times.size() - 1];
  4915. }
  4916. const float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  4917. return interp.catmull_rom(p_values[idx - 1], p_values[idx], p_values[idx + 1], p_values[idx + 3], c);
  4918. } break;
  4919. case GLTFAnimation::INTERP_CUBIC_SPLINE: {
  4920. if (idx == -1) {
  4921. return p_values[1];
  4922. } else if (idx >= p_times.size() - 1) {
  4923. return p_values[(p_times.size() - 1) * 3 + 1];
  4924. }
  4925. const float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  4926. const T &from = p_values[idx * 3 + 1];
  4927. const T c1 = from + p_values[idx * 3 + 2];
  4928. const T &to = p_values[idx * 3 + 4];
  4929. const T c2 = to + p_values[idx * 3 + 3];
  4930. return interp.bezier(from, c1, c2, to, c);
  4931. } break;
  4932. }
  4933. ERR_FAIL_V(p_values[0]);
  4934. }
  4935. void GLTFDocument::_import_animation(Ref<GLTFState> p_state, AnimationPlayer *p_animation_player, const GLTFAnimationIndex p_index, const float p_bake_fps, const bool p_trimming, const bool p_remove_immutable_tracks) {
  4936. Ref<GLTFAnimation> anim = p_state->animations[p_index];
  4937. String anim_name = anim->get_name();
  4938. if (anim_name.is_empty()) {
  4939. // No node represent these, and they are not in the hierarchy, so just make a unique name
  4940. anim_name = _gen_unique_name(p_state, "Animation");
  4941. }
  4942. Ref<Animation> animation;
  4943. animation.instantiate();
  4944. animation->set_name(anim_name);
  4945. if (anim->get_loop()) {
  4946. animation->set_loop_mode(Animation::LOOP_LINEAR);
  4947. }
  4948. double anim_start = p_trimming ? INFINITY : 0.0;
  4949. double anim_end = 0.0;
  4950. for (const KeyValue<int, GLTFAnimation::Track> &track_i : anim->get_tracks()) {
  4951. const GLTFAnimation::Track &track = track_i.value;
  4952. //need to find the path: for skeletons, weight tracks will affect the mesh
  4953. NodePath node_path;
  4954. //for skeletons, transform tracks always affect bones
  4955. NodePath transform_node_path;
  4956. //for meshes, especially skinned meshes, there are cases where it will be added as a child
  4957. NodePath mesh_instance_node_path;
  4958. GLTFNodeIndex node_index = track_i.key;
  4959. const Ref<GLTFNode> gltf_node = p_state->nodes[track_i.key];
  4960. Node *root = p_animation_player->get_parent();
  4961. ERR_FAIL_NULL(root);
  4962. HashMap<GLTFNodeIndex, Node *>::Iterator node_element = p_state->scene_nodes.find(node_index);
  4963. ERR_CONTINUE_MSG(!node_element, vformat("Unable to find node %d for animation.", node_index));
  4964. node_path = root->get_path_to(node_element->value);
  4965. HashMap<GLTFNodeIndex, ImporterMeshInstance3D *>::Iterator mesh_instance_element = p_state->scene_mesh_instances.find(node_index);
  4966. if (mesh_instance_element) {
  4967. mesh_instance_node_path = root->get_path_to(mesh_instance_element->value);
  4968. } else {
  4969. mesh_instance_node_path = node_path;
  4970. }
  4971. if (gltf_node->skeleton >= 0) {
  4972. const Skeleton3D *sk = p_state->skeletons[gltf_node->skeleton]->godot_skeleton;
  4973. ERR_FAIL_NULL(sk);
  4974. const String path = p_animation_player->get_parent()->get_path_to(sk);
  4975. const String bone = gltf_node->get_name();
  4976. transform_node_path = path + ":" + bone;
  4977. } else {
  4978. transform_node_path = node_path;
  4979. }
  4980. if (p_trimming) {
  4981. for (int i = 0; i < track.rotation_track.times.size(); i++) {
  4982. anim_start = MIN(anim_start, track.rotation_track.times[i]);
  4983. anim_end = MAX(anim_end, track.rotation_track.times[i]);
  4984. }
  4985. for (int i = 0; i < track.position_track.times.size(); i++) {
  4986. anim_start = MIN(anim_start, track.position_track.times[i]);
  4987. anim_end = MAX(anim_end, track.position_track.times[i]);
  4988. }
  4989. for (int i = 0; i < track.scale_track.times.size(); i++) {
  4990. anim_start = MIN(anim_start, track.scale_track.times[i]);
  4991. anim_end = MAX(anim_end, track.scale_track.times[i]);
  4992. }
  4993. for (int i = 0; i < track.weight_tracks.size(); i++) {
  4994. for (int j = 0; j < track.weight_tracks[i].times.size(); j++) {
  4995. anim_start = MIN(anim_start, track.weight_tracks[i].times[j]);
  4996. anim_end = MAX(anim_end, track.weight_tracks[i].times[j]);
  4997. }
  4998. }
  4999. } else {
  5000. // If you don't use trimming and the first key time is not at 0.0, fake keys will be inserted.
  5001. for (int i = 0; i < track.rotation_track.times.size(); i++) {
  5002. anim_end = MAX(anim_end, track.rotation_track.times[i]);
  5003. }
  5004. for (int i = 0; i < track.position_track.times.size(); i++) {
  5005. anim_end = MAX(anim_end, track.position_track.times[i]);
  5006. }
  5007. for (int i = 0; i < track.scale_track.times.size(); i++) {
  5008. anim_end = MAX(anim_end, track.scale_track.times[i]);
  5009. }
  5010. for (int i = 0; i < track.weight_tracks.size(); i++) {
  5011. for (int j = 0; j < track.weight_tracks[i].times.size(); j++) {
  5012. anim_end = MAX(anim_end, track.weight_tracks[i].times[j]);
  5013. }
  5014. }
  5015. }
  5016. // Animated TRS properties will not affect a skinned mesh.
  5017. const bool transform_affects_skinned_mesh_instance = gltf_node->skeleton < 0 && gltf_node->skin >= 0;
  5018. if ((track.rotation_track.values.size() || track.position_track.values.size() || track.scale_track.values.size()) && !transform_affects_skinned_mesh_instance) {
  5019. //make transform track
  5020. int base_idx = animation->get_track_count();
  5021. int position_idx = -1;
  5022. int rotation_idx = -1;
  5023. int scale_idx = -1;
  5024. if (track.position_track.values.size()) {
  5025. bool is_default = true; //discard the track if all it contains is default values
  5026. if (p_remove_immutable_tracks) {
  5027. Vector3 base_pos = gltf_node->get_position();
  5028. for (int i = 0; i < track.position_track.times.size(); i++) {
  5029. int value_index = track.position_track.interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE ? (1 + i * 3) : i;
  5030. ERR_FAIL_COND_MSG(value_index >= track.position_track.values.size(), "Animation sampler output accessor with 'CUBICSPLINE' interpolation doesn't have enough elements.");
  5031. Vector3 value = track.position_track.values[value_index];
  5032. if (!value.is_equal_approx(base_pos)) {
  5033. is_default = false;
  5034. break;
  5035. }
  5036. }
  5037. }
  5038. if (!p_remove_immutable_tracks || !is_default) {
  5039. position_idx = base_idx;
  5040. animation->add_track(Animation::TYPE_POSITION_3D);
  5041. animation->track_set_path(position_idx, transform_node_path);
  5042. animation->track_set_imported(position_idx, true); //helps merging later
  5043. if (track.position_track.interpolation == GLTFAnimation::INTERP_STEP) {
  5044. animation->track_set_interpolation_type(position_idx, Animation::InterpolationType::INTERPOLATION_NEAREST);
  5045. }
  5046. base_idx++;
  5047. }
  5048. }
  5049. if (track.rotation_track.values.size()) {
  5050. bool is_default = true; //discard the track if all it contains is default values
  5051. if (p_remove_immutable_tracks) {
  5052. Quaternion base_rot = gltf_node->get_rotation();
  5053. for (int i = 0; i < track.rotation_track.times.size(); i++) {
  5054. int value_index = track.rotation_track.interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE ? (1 + i * 3) : i;
  5055. ERR_FAIL_COND_MSG(value_index >= track.rotation_track.values.size(), "Animation sampler output accessor with 'CUBICSPLINE' interpolation doesn't have enough elements.");
  5056. Quaternion value = track.rotation_track.values[value_index].normalized();
  5057. if (!value.is_equal_approx(base_rot)) {
  5058. is_default = false;
  5059. break;
  5060. }
  5061. }
  5062. }
  5063. if (!p_remove_immutable_tracks || !is_default) {
  5064. rotation_idx = base_idx;
  5065. animation->add_track(Animation::TYPE_ROTATION_3D);
  5066. animation->track_set_path(rotation_idx, transform_node_path);
  5067. animation->track_set_imported(rotation_idx, true); //helps merging later
  5068. if (track.rotation_track.interpolation == GLTFAnimation::INTERP_STEP) {
  5069. animation->track_set_interpolation_type(rotation_idx, Animation::InterpolationType::INTERPOLATION_NEAREST);
  5070. }
  5071. base_idx++;
  5072. }
  5073. }
  5074. if (track.scale_track.values.size()) {
  5075. bool is_default = true; //discard the track if all it contains is default values
  5076. if (p_remove_immutable_tracks) {
  5077. Vector3 base_scale = gltf_node->get_scale();
  5078. for (int i = 0; i < track.scale_track.times.size(); i++) {
  5079. int value_index = track.scale_track.interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE ? (1 + i * 3) : i;
  5080. ERR_FAIL_COND_MSG(value_index >= track.scale_track.values.size(), "Animation sampler output accessor with 'CUBICSPLINE' interpolation doesn't have enough elements.");
  5081. Vector3 value = track.scale_track.values[value_index];
  5082. if (!value.is_equal_approx(base_scale)) {
  5083. is_default = false;
  5084. break;
  5085. }
  5086. }
  5087. }
  5088. if (!p_remove_immutable_tracks || !is_default) {
  5089. scale_idx = base_idx;
  5090. animation->add_track(Animation::TYPE_SCALE_3D);
  5091. animation->track_set_path(scale_idx, transform_node_path);
  5092. animation->track_set_imported(scale_idx, true); //helps merging later
  5093. if (track.scale_track.interpolation == GLTFAnimation::INTERP_STEP) {
  5094. animation->track_set_interpolation_type(scale_idx, Animation::InterpolationType::INTERPOLATION_NEAREST);
  5095. }
  5096. base_idx++;
  5097. }
  5098. }
  5099. const double increment = 1.0 / p_bake_fps;
  5100. double time = anim_start;
  5101. Vector3 base_pos;
  5102. Quaternion base_rot;
  5103. Vector3 base_scale = Vector3(1, 1, 1);
  5104. if (rotation_idx == -1) {
  5105. base_rot = gltf_node->get_rotation();
  5106. }
  5107. if (position_idx == -1) {
  5108. base_pos = gltf_node->get_position();
  5109. }
  5110. if (scale_idx == -1) {
  5111. base_scale = gltf_node->get_scale();
  5112. }
  5113. bool last = false;
  5114. while (true) {
  5115. Vector3 pos = base_pos;
  5116. Quaternion rot = base_rot;
  5117. Vector3 scale = base_scale;
  5118. if (position_idx >= 0) {
  5119. pos = _interpolate_track<Vector3>(track.position_track.times, track.position_track.values, time, track.position_track.interpolation);
  5120. animation->position_track_insert_key(position_idx, time - anim_start, pos);
  5121. }
  5122. if (rotation_idx >= 0) {
  5123. rot = _interpolate_track<Quaternion>(track.rotation_track.times, track.rotation_track.values, time, track.rotation_track.interpolation);
  5124. animation->rotation_track_insert_key(rotation_idx, time - anim_start, rot);
  5125. }
  5126. if (scale_idx >= 0) {
  5127. scale = _interpolate_track<Vector3>(track.scale_track.times, track.scale_track.values, time, track.scale_track.interpolation);
  5128. animation->scale_track_insert_key(scale_idx, time - anim_start, scale);
  5129. }
  5130. if (last) {
  5131. break;
  5132. }
  5133. time += increment;
  5134. if (time >= anim_end) {
  5135. last = true;
  5136. time = anim_end;
  5137. }
  5138. }
  5139. }
  5140. for (int i = 0; i < track.weight_tracks.size(); i++) {
  5141. ERR_CONTINUE(gltf_node->mesh < 0 || gltf_node->mesh >= p_state->meshes.size());
  5142. Ref<GLTFMesh> mesh = p_state->meshes[gltf_node->mesh];
  5143. ERR_CONTINUE(mesh.is_null());
  5144. ERR_CONTINUE(mesh->get_mesh().is_null());
  5145. ERR_CONTINUE(mesh->get_mesh()->get_mesh().is_null());
  5146. const String blend_path = String(mesh_instance_node_path) + ":" + String(mesh->get_mesh()->get_blend_shape_name(i));
  5147. const int track_idx = animation->get_track_count();
  5148. animation->add_track(Animation::TYPE_BLEND_SHAPE);
  5149. animation->track_set_path(track_idx, blend_path);
  5150. animation->track_set_imported(track_idx, true); //helps merging later
  5151. // Only LINEAR and STEP (NEAREST) can be supported out of the box by Godot's Animation,
  5152. // the other modes have to be baked.
  5153. GLTFAnimation::Interpolation gltf_interp = track.weight_tracks[i].interpolation;
  5154. if (gltf_interp == GLTFAnimation::INTERP_LINEAR || gltf_interp == GLTFAnimation::INTERP_STEP) {
  5155. animation->track_set_interpolation_type(track_idx, gltf_interp == GLTFAnimation::INTERP_STEP ? Animation::INTERPOLATION_NEAREST : Animation::INTERPOLATION_LINEAR);
  5156. for (int j = 0; j < track.weight_tracks[i].times.size(); j++) {
  5157. const float t = track.weight_tracks[i].times[j];
  5158. const float attribs = track.weight_tracks[i].values[j];
  5159. animation->blend_shape_track_insert_key(track_idx, t, attribs);
  5160. }
  5161. } else {
  5162. // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
  5163. const double increment = 1.0 / p_bake_fps;
  5164. double time = 0.0;
  5165. bool last = false;
  5166. while (true) {
  5167. real_t blend = _interpolate_track<real_t>(track.weight_tracks[i].times, track.weight_tracks[i].values, time, gltf_interp);
  5168. animation->blend_shape_track_insert_key(track_idx, time - anim_start, blend);
  5169. if (last) {
  5170. break;
  5171. }
  5172. time += increment;
  5173. if (time >= anim_end) {
  5174. last = true;
  5175. time = anim_end;
  5176. }
  5177. }
  5178. }
  5179. }
  5180. }
  5181. animation->set_length(anim_end - anim_start);
  5182. Ref<AnimationLibrary> library;
  5183. if (!p_animation_player->has_animation_library("")) {
  5184. library.instantiate();
  5185. p_animation_player->add_animation_library("", library);
  5186. } else {
  5187. library = p_animation_player->get_animation_library("");
  5188. }
  5189. library->add_animation(anim_name, animation);
  5190. }
  5191. void GLTFDocument::_convert_mesh_instances(Ref<GLTFState> p_state) {
  5192. for (GLTFNodeIndex mi_node_i = 0; mi_node_i < p_state->nodes.size(); ++mi_node_i) {
  5193. Ref<GLTFNode> node = p_state->nodes[mi_node_i];
  5194. if (node->mesh < 0) {
  5195. continue;
  5196. }
  5197. HashMap<GLTFNodeIndex, Node *>::Iterator mi_element = p_state->scene_nodes.find(mi_node_i);
  5198. if (!mi_element) {
  5199. continue;
  5200. }
  5201. MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(mi_element->value);
  5202. if (!mi) {
  5203. continue;
  5204. }
  5205. node->transform = mi->get_transform();
  5206. Node *skel_node = mi->get_node_or_null(mi->get_skeleton_path());
  5207. Skeleton3D *godot_skeleton = Object::cast_to<Skeleton3D>(skel_node);
  5208. if (!godot_skeleton || godot_skeleton->get_bone_count() == 0) {
  5209. continue;
  5210. }
  5211. // At this point in the code, we know we have a Skeleton3D with at least one bone.
  5212. Ref<Skin> skin = mi->get_skin();
  5213. Ref<GLTFSkin> gltf_skin;
  5214. gltf_skin.instantiate();
  5215. Array json_joints;
  5216. if (p_state->skeleton3d_to_gltf_skeleton.has(godot_skeleton->get_instance_id())) {
  5217. // This is a skinned mesh. If the mesh has no ARRAY_WEIGHTS or ARRAY_BONES, it will be invisible.
  5218. const GLTFSkeletonIndex skeleton_gltf_i = p_state->skeleton3d_to_gltf_skeleton[godot_skeleton->get_instance_id()];
  5219. Ref<GLTFSkeleton> gltf_skeleton = p_state->skeletons[skeleton_gltf_i];
  5220. int bone_cnt = godot_skeleton->get_bone_count();
  5221. ERR_FAIL_COND(bone_cnt != gltf_skeleton->joints.size());
  5222. ObjectID gltf_skin_key;
  5223. if (skin.is_valid()) {
  5224. gltf_skin_key = skin->get_instance_id();
  5225. }
  5226. ObjectID gltf_skel_key = godot_skeleton->get_instance_id();
  5227. GLTFSkinIndex skin_gltf_i = -1;
  5228. GLTFNodeIndex root_gltf_i = -1;
  5229. if (!gltf_skeleton->roots.is_empty()) {
  5230. root_gltf_i = gltf_skeleton->roots[0];
  5231. }
  5232. if (p_state->skin_and_skeleton3d_to_gltf_skin.has(gltf_skin_key) && p_state->skin_and_skeleton3d_to_gltf_skin[gltf_skin_key].has(gltf_skel_key)) {
  5233. skin_gltf_i = p_state->skin_and_skeleton3d_to_gltf_skin[gltf_skin_key][gltf_skel_key];
  5234. } else {
  5235. if (skin.is_null()) {
  5236. // Note that gltf_skin_key should remain null, so these can share a reference.
  5237. skin = godot_skeleton->create_skin_from_rest_transforms();
  5238. }
  5239. gltf_skin.instantiate();
  5240. gltf_skin->godot_skin = skin;
  5241. gltf_skin->set_name(skin->get_name());
  5242. gltf_skin->skeleton = skeleton_gltf_i;
  5243. gltf_skin->skin_root = root_gltf_i;
  5244. //gltf_state->godot_to_gltf_node[skel_node]
  5245. HashMap<StringName, int> bone_name_to_idx;
  5246. for (int bone_i = 0; bone_i < bone_cnt; bone_i++) {
  5247. bone_name_to_idx[godot_skeleton->get_bone_name(bone_i)] = bone_i;
  5248. }
  5249. for (int bind_i = 0, cnt = skin->get_bind_count(); bind_i < cnt; bind_i++) {
  5250. int bone_i = skin->get_bind_bone(bind_i);
  5251. Transform3D bind_pose = skin->get_bind_pose(bind_i);
  5252. StringName bind_name = skin->get_bind_name(bind_i);
  5253. if (bind_name != StringName()) {
  5254. bone_i = bone_name_to_idx[bind_name];
  5255. }
  5256. ERR_CONTINUE(bone_i < 0 || bone_i >= bone_cnt);
  5257. if (bind_name == StringName()) {
  5258. bind_name = godot_skeleton->get_bone_name(bone_i);
  5259. }
  5260. GLTFNodeIndex skeleton_bone_i = gltf_skeleton->joints[bone_i];
  5261. gltf_skin->joints_original.push_back(skeleton_bone_i);
  5262. gltf_skin->joints.push_back(skeleton_bone_i);
  5263. gltf_skin->inverse_binds.push_back(bind_pose);
  5264. if (godot_skeleton->get_bone_parent(bone_i) == -1) {
  5265. gltf_skin->roots.push_back(skeleton_bone_i);
  5266. }
  5267. gltf_skin->joint_i_to_bone_i[bind_i] = bone_i;
  5268. gltf_skin->joint_i_to_name[bind_i] = bind_name;
  5269. }
  5270. skin_gltf_i = p_state->skins.size();
  5271. p_state->skins.push_back(gltf_skin);
  5272. p_state->skin_and_skeleton3d_to_gltf_skin[gltf_skin_key][gltf_skel_key] = skin_gltf_i;
  5273. }
  5274. node->skin = skin_gltf_i;
  5275. node->skeleton = skeleton_gltf_i;
  5276. }
  5277. }
  5278. }
  5279. float GLTFDocument::solve_metallic(float p_dielectric_specular, float p_diffuse, float p_specular, float p_one_minus_specular_strength) {
  5280. if (p_specular <= p_dielectric_specular) {
  5281. return 0.0f;
  5282. }
  5283. const float a = p_dielectric_specular;
  5284. const float b = p_diffuse * p_one_minus_specular_strength / (1.0f - p_dielectric_specular) + p_specular - 2.0f * p_dielectric_specular;
  5285. const float c = p_dielectric_specular - p_specular;
  5286. const float D = b * b - 4.0f * a * c;
  5287. return CLAMP((-b + Math::sqrt(D)) / (2.0f * a), 0.0f, 1.0f);
  5288. }
  5289. float GLTFDocument::get_perceived_brightness(const Color p_color) {
  5290. const Color coeff = Color(R_BRIGHTNESS_COEFF, G_BRIGHTNESS_COEFF, B_BRIGHTNESS_COEFF);
  5291. const Color value = coeff * (p_color * p_color);
  5292. const float r = value.r;
  5293. const float g = value.g;
  5294. const float b = value.b;
  5295. return Math::sqrt(r + g + b);
  5296. }
  5297. float GLTFDocument::get_max_component(const Color &p_color) {
  5298. const float r = p_color.r;
  5299. const float g = p_color.g;
  5300. const float b = p_color.b;
  5301. return MAX(MAX(r, g), b);
  5302. }
  5303. void GLTFDocument::_process_mesh_instances(Ref<GLTFState> p_state, Node *p_scene_root) {
  5304. for (GLTFNodeIndex node_i = 0; node_i < p_state->nodes.size(); ++node_i) {
  5305. Ref<GLTFNode> node = p_state->nodes[node_i];
  5306. if (node->skin >= 0 && node->mesh >= 0) {
  5307. const GLTFSkinIndex skin_i = node->skin;
  5308. ImporterMeshInstance3D *mi = nullptr;
  5309. HashMap<GLTFNodeIndex, ImporterMeshInstance3D *>::Iterator mi_element = p_state->scene_mesh_instances.find(node_i);
  5310. if (mi_element) {
  5311. mi = mi_element->value;
  5312. } else {
  5313. HashMap<GLTFNodeIndex, Node *>::Iterator si_element = p_state->scene_nodes.find(node_i);
  5314. ERR_CONTINUE_MSG(!si_element, vformat("Unable to find node %d", node_i));
  5315. mi = Object::cast_to<ImporterMeshInstance3D>(si_element->value);
  5316. ERR_CONTINUE_MSG(mi == nullptr, vformat("Unable to cast node %d of type %s to ImporterMeshInstance3D", node_i, si_element->value->get_class_name()));
  5317. }
  5318. const GLTFSkeletonIndex skel_i = p_state->skins.write[node->skin]->skeleton;
  5319. Ref<GLTFSkeleton> gltf_skeleton = p_state->skeletons.write[skel_i];
  5320. Skeleton3D *skeleton = gltf_skeleton->godot_skeleton;
  5321. ERR_CONTINUE_MSG(skeleton == nullptr, vformat("Unable to find Skeleton for node %d skin %d", node_i, skin_i));
  5322. mi->get_parent()->remove_child(mi);
  5323. skeleton->add_child(mi, true);
  5324. mi->set_owner(p_scene_root);
  5325. mi->set_skin(p_state->skins.write[skin_i]->godot_skin);
  5326. mi->set_skeleton_path(mi->get_path_to(skeleton));
  5327. mi->set_transform(Transform3D());
  5328. }
  5329. }
  5330. }
  5331. GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> p_state, GLTFAnimation::Track p_track, Ref<Animation> p_animation, int32_t p_track_i, GLTFNodeIndex p_node_i) {
  5332. Animation::InterpolationType interpolation = p_animation->track_get_interpolation_type(p_track_i);
  5333. GLTFAnimation::Interpolation gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  5334. if (interpolation == Animation::InterpolationType::INTERPOLATION_LINEAR) {
  5335. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  5336. } else if (interpolation == Animation::InterpolationType::INTERPOLATION_NEAREST) {
  5337. gltf_interpolation = GLTFAnimation::INTERP_STEP;
  5338. } else if (interpolation == Animation::InterpolationType::INTERPOLATION_CUBIC) {
  5339. gltf_interpolation = GLTFAnimation::INTERP_CUBIC_SPLINE;
  5340. }
  5341. Animation::TrackType track_type = p_animation->track_get_type(p_track_i);
  5342. int32_t key_count = p_animation->track_get_key_count(p_track_i);
  5343. Vector<real_t> times;
  5344. times.resize(key_count);
  5345. String path = p_animation->track_get_path(p_track_i);
  5346. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  5347. times.write[key_i] = p_animation->track_get_key_time(p_track_i, key_i);
  5348. }
  5349. double anim_end = p_animation->get_length();
  5350. if (track_type == Animation::TYPE_SCALE_3D) {
  5351. if (gltf_interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE) {
  5352. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  5353. p_track.scale_track.times.clear();
  5354. p_track.scale_track.values.clear();
  5355. // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
  5356. const double increment = 1.0 / BAKE_FPS;
  5357. double time = 0.0;
  5358. bool last = false;
  5359. while (true) {
  5360. Vector3 scale;
  5361. Error err = p_animation->try_scale_track_interpolate(p_track_i, time, &scale);
  5362. ERR_CONTINUE(err != OK);
  5363. p_track.scale_track.values.push_back(scale);
  5364. p_track.scale_track.times.push_back(time);
  5365. if (last) {
  5366. break;
  5367. }
  5368. time += increment;
  5369. if (time >= anim_end) {
  5370. last = true;
  5371. time = anim_end;
  5372. }
  5373. }
  5374. } else {
  5375. p_track.scale_track.times = times;
  5376. p_track.scale_track.interpolation = gltf_interpolation;
  5377. p_track.scale_track.values.resize(key_count);
  5378. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  5379. Vector3 scale;
  5380. Error err = p_animation->scale_track_get_key(p_track_i, key_i, &scale);
  5381. ERR_CONTINUE(err != OK);
  5382. p_track.scale_track.values.write[key_i] = scale;
  5383. }
  5384. }
  5385. } else if (track_type == Animation::TYPE_POSITION_3D) {
  5386. if (gltf_interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE) {
  5387. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  5388. p_track.position_track.times.clear();
  5389. p_track.position_track.values.clear();
  5390. // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
  5391. const double increment = 1.0 / BAKE_FPS;
  5392. double time = 0.0;
  5393. bool last = false;
  5394. while (true) {
  5395. Vector3 scale;
  5396. Error err = p_animation->try_position_track_interpolate(p_track_i, time, &scale);
  5397. ERR_CONTINUE(err != OK);
  5398. p_track.position_track.values.push_back(scale);
  5399. p_track.position_track.times.push_back(time);
  5400. if (last) {
  5401. break;
  5402. }
  5403. time += increment;
  5404. if (time >= anim_end) {
  5405. last = true;
  5406. time = anim_end;
  5407. }
  5408. }
  5409. } else {
  5410. p_track.position_track.times = times;
  5411. p_track.position_track.values.resize(key_count);
  5412. p_track.position_track.interpolation = gltf_interpolation;
  5413. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  5414. Vector3 position;
  5415. Error err = p_animation->position_track_get_key(p_track_i, key_i, &position);
  5416. ERR_CONTINUE(err != OK);
  5417. p_track.position_track.values.write[key_i] = position;
  5418. }
  5419. }
  5420. } else if (track_type == Animation::TYPE_ROTATION_3D) {
  5421. if (gltf_interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE) {
  5422. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  5423. p_track.rotation_track.times.clear();
  5424. p_track.rotation_track.values.clear();
  5425. // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
  5426. const double increment = 1.0 / BAKE_FPS;
  5427. double time = 0.0;
  5428. bool last = false;
  5429. while (true) {
  5430. Quaternion rotation;
  5431. Error err = p_animation->try_rotation_track_interpolate(p_track_i, time, &rotation);
  5432. ERR_CONTINUE(err != OK);
  5433. p_track.rotation_track.values.push_back(rotation);
  5434. p_track.rotation_track.times.push_back(time);
  5435. if (last) {
  5436. break;
  5437. }
  5438. time += increment;
  5439. if (time >= anim_end) {
  5440. last = true;
  5441. time = anim_end;
  5442. }
  5443. }
  5444. } else {
  5445. p_track.rotation_track.times = times;
  5446. p_track.rotation_track.values.resize(key_count);
  5447. p_track.rotation_track.interpolation = gltf_interpolation;
  5448. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  5449. Quaternion rotation;
  5450. Error err = p_animation->rotation_track_get_key(p_track_i, key_i, &rotation);
  5451. ERR_CONTINUE(err != OK);
  5452. p_track.rotation_track.values.write[key_i] = rotation;
  5453. }
  5454. }
  5455. } else if (track_type == Animation::TYPE_VALUE) {
  5456. if (path.contains(":position")) {
  5457. p_track.position_track.interpolation = gltf_interpolation;
  5458. p_track.position_track.times = times;
  5459. p_track.position_track.values.resize(key_count);
  5460. if (gltf_interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE) {
  5461. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  5462. p_track.position_track.times.clear();
  5463. p_track.position_track.values.clear();
  5464. // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
  5465. const double increment = 1.0 / BAKE_FPS;
  5466. double time = 0.0;
  5467. bool last = false;
  5468. while (true) {
  5469. Vector3 position;
  5470. Error err = p_animation->try_position_track_interpolate(p_track_i, time, &position);
  5471. ERR_CONTINUE(err != OK);
  5472. p_track.position_track.values.push_back(position);
  5473. p_track.position_track.times.push_back(time);
  5474. if (last) {
  5475. break;
  5476. }
  5477. time += increment;
  5478. if (time >= anim_end) {
  5479. last = true;
  5480. time = anim_end;
  5481. }
  5482. }
  5483. } else {
  5484. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  5485. Vector3 position = p_animation->track_get_key_value(p_track_i, key_i);
  5486. p_track.position_track.values.write[key_i] = position;
  5487. }
  5488. }
  5489. } else if (path.contains(":rotation")) {
  5490. p_track.rotation_track.interpolation = gltf_interpolation;
  5491. p_track.rotation_track.times = times;
  5492. p_track.rotation_track.values.resize(key_count);
  5493. if (gltf_interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE) {
  5494. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  5495. p_track.rotation_track.times.clear();
  5496. p_track.rotation_track.values.clear();
  5497. // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
  5498. const double increment = 1.0 / BAKE_FPS;
  5499. double time = 0.0;
  5500. bool last = false;
  5501. while (true) {
  5502. Quaternion rotation;
  5503. Error err = p_animation->try_rotation_track_interpolate(p_track_i, time, &rotation);
  5504. ERR_CONTINUE(err != OK);
  5505. p_track.rotation_track.values.push_back(rotation);
  5506. p_track.rotation_track.times.push_back(time);
  5507. if (last) {
  5508. break;
  5509. }
  5510. time += increment;
  5511. if (time >= anim_end) {
  5512. last = true;
  5513. time = anim_end;
  5514. }
  5515. }
  5516. } else {
  5517. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  5518. Vector3 rotation_radian = p_animation->track_get_key_value(p_track_i, key_i);
  5519. p_track.rotation_track.values.write[key_i] = Quaternion::from_euler(rotation_radian);
  5520. }
  5521. }
  5522. } else if (path.contains(":scale")) {
  5523. p_track.scale_track.times = times;
  5524. p_track.scale_track.interpolation = gltf_interpolation;
  5525. p_track.scale_track.values.resize(key_count);
  5526. p_track.scale_track.interpolation = gltf_interpolation;
  5527. if (gltf_interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE) {
  5528. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  5529. p_track.scale_track.times.clear();
  5530. p_track.scale_track.values.clear();
  5531. // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
  5532. const double increment = 1.0 / BAKE_FPS;
  5533. double time = 0.0;
  5534. bool last = false;
  5535. while (true) {
  5536. Vector3 scale;
  5537. Error err = p_animation->try_scale_track_interpolate(p_track_i, time, &scale);
  5538. ERR_CONTINUE(err != OK);
  5539. p_track.scale_track.values.push_back(scale);
  5540. p_track.scale_track.times.push_back(time);
  5541. if (last) {
  5542. break;
  5543. }
  5544. time += increment;
  5545. if (time >= anim_end) {
  5546. last = true;
  5547. time = anim_end;
  5548. }
  5549. }
  5550. } else {
  5551. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  5552. Vector3 scale_track = p_animation->track_get_key_value(p_track_i, key_i);
  5553. p_track.scale_track.values.write[key_i] = scale_track;
  5554. }
  5555. }
  5556. }
  5557. } else if (track_type == Animation::TYPE_BEZIER) {
  5558. const int32_t keys = anim_end * BAKE_FPS;
  5559. if (path.contains(":scale")) {
  5560. if (!p_track.scale_track.times.size()) {
  5561. p_track.scale_track.interpolation = gltf_interpolation;
  5562. Vector<real_t> new_times;
  5563. new_times.resize(keys);
  5564. for (int32_t key_i = 0; key_i < keys; key_i++) {
  5565. new_times.write[key_i] = key_i / BAKE_FPS;
  5566. }
  5567. p_track.scale_track.times = new_times;
  5568. p_track.scale_track.values.resize(keys);
  5569. for (int32_t key_i = 0; key_i < keys; key_i++) {
  5570. p_track.scale_track.values.write[key_i] = Vector3(1.0f, 1.0f, 1.0f);
  5571. }
  5572. for (int32_t key_i = 0; key_i < keys; key_i++) {
  5573. Vector3 bezier_track = p_track.scale_track.values[key_i];
  5574. if (path.contains(":scale:x")) {
  5575. bezier_track.x = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
  5576. } else if (path.contains(":scale:y")) {
  5577. bezier_track.y = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
  5578. } else if (path.contains(":scale:z")) {
  5579. bezier_track.z = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
  5580. }
  5581. p_track.scale_track.values.write[key_i] = bezier_track;
  5582. }
  5583. }
  5584. } else if (path.contains(":position")) {
  5585. if (!p_track.position_track.times.size()) {
  5586. p_track.position_track.interpolation = gltf_interpolation;
  5587. Vector<real_t> new_times;
  5588. new_times.resize(keys);
  5589. for (int32_t key_i = 0; key_i < keys; key_i++) {
  5590. new_times.write[key_i] = key_i / BAKE_FPS;
  5591. }
  5592. p_track.position_track.times = new_times;
  5593. p_track.position_track.values.resize(keys);
  5594. }
  5595. for (int32_t key_i = 0; key_i < keys; key_i++) {
  5596. Vector3 bezier_track = p_track.position_track.values[key_i];
  5597. if (path.contains(":position:x")) {
  5598. bezier_track.x = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
  5599. } else if (path.contains(":position:y")) {
  5600. bezier_track.y = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
  5601. } else if (path.contains(":position:z")) {
  5602. bezier_track.z = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
  5603. }
  5604. p_track.position_track.values.write[key_i] = bezier_track;
  5605. }
  5606. } else if (path.contains(":rotation")) {
  5607. if (!p_track.rotation_track.times.size()) {
  5608. p_track.rotation_track.interpolation = gltf_interpolation;
  5609. Vector<real_t> new_times;
  5610. new_times.resize(keys);
  5611. for (int32_t key_i = 0; key_i < keys; key_i++) {
  5612. new_times.write[key_i] = key_i / BAKE_FPS;
  5613. }
  5614. p_track.rotation_track.times = new_times;
  5615. p_track.rotation_track.values.resize(keys);
  5616. }
  5617. for (int32_t key_i = 0; key_i < keys; key_i++) {
  5618. Quaternion bezier_track = p_track.rotation_track.values[key_i];
  5619. if (path.contains(":rotation:x")) {
  5620. bezier_track.x = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
  5621. } else if (path.contains(":rotation:y")) {
  5622. bezier_track.y = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
  5623. } else if (path.contains(":rotation:z")) {
  5624. bezier_track.z = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
  5625. } else if (path.contains(":rotation:w")) {
  5626. bezier_track.w = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
  5627. }
  5628. p_track.rotation_track.values.write[key_i] = bezier_track;
  5629. }
  5630. }
  5631. }
  5632. return p_track;
  5633. }
  5634. void GLTFDocument::_convert_animation(Ref<GLTFState> p_state, AnimationPlayer *p_animation_player, String p_animation_track_name) {
  5635. Ref<Animation> animation = p_animation_player->get_animation(p_animation_track_name);
  5636. Ref<GLTFAnimation> gltf_animation;
  5637. gltf_animation.instantiate();
  5638. gltf_animation->set_original_name(p_animation_track_name);
  5639. gltf_animation->set_name(_gen_unique_name(p_state, p_animation_track_name));
  5640. for (int32_t track_i = 0; track_i < animation->get_track_count(); track_i++) {
  5641. if (!animation->track_is_enabled(track_i)) {
  5642. continue;
  5643. }
  5644. String final_track_path = animation->track_get_path(track_i);
  5645. Node *animation_base_node = p_animation_player->get_parent();
  5646. ERR_CONTINUE_MSG(!animation_base_node, "Cannot get the parent of the animation player.");
  5647. if (String(final_track_path).contains(":position")) {
  5648. const Vector<String> node_suffix = String(final_track_path).split(":position");
  5649. const NodePath path = node_suffix[0];
  5650. const Node *node = animation_base_node->get_node_or_null(path);
  5651. ERR_CONTINUE_MSG(!node, "Cannot get the node from a position path.");
  5652. for (const KeyValue<GLTFNodeIndex, Node *> &position_scene_node_i : p_state->scene_nodes) {
  5653. if (position_scene_node_i.value == node) {
  5654. GLTFNodeIndex node_index = position_scene_node_i.key;
  5655. HashMap<int, GLTFAnimation::Track>::Iterator position_track_i = gltf_animation->get_tracks().find(node_index);
  5656. GLTFAnimation::Track track;
  5657. if (position_track_i) {
  5658. track = position_track_i->value;
  5659. }
  5660. track = _convert_animation_track(p_state, track, animation, track_i, node_index);
  5661. gltf_animation->get_tracks().insert(node_index, track);
  5662. }
  5663. }
  5664. } else if (String(final_track_path).contains(":rotation_degrees")) {
  5665. const Vector<String> node_suffix = String(final_track_path).split(":rotation_degrees");
  5666. const NodePath path = node_suffix[0];
  5667. const Node *node = animation_base_node->get_node_or_null(path);
  5668. ERR_CONTINUE_MSG(!node, "Cannot get the node from a rotation degrees path.");
  5669. for (const KeyValue<GLTFNodeIndex, Node *> &rotation_degree_scene_node_i : p_state->scene_nodes) {
  5670. if (rotation_degree_scene_node_i.value == node) {
  5671. GLTFNodeIndex node_index = rotation_degree_scene_node_i.key;
  5672. HashMap<int, GLTFAnimation::Track>::Iterator rotation_degree_track_i = gltf_animation->get_tracks().find(node_index);
  5673. GLTFAnimation::Track track;
  5674. if (rotation_degree_track_i) {
  5675. track = rotation_degree_track_i->value;
  5676. }
  5677. track = _convert_animation_track(p_state, track, animation, track_i, node_index);
  5678. gltf_animation->get_tracks().insert(node_index, track);
  5679. }
  5680. }
  5681. } else if (String(final_track_path).contains(":scale")) {
  5682. const Vector<String> node_suffix = String(final_track_path).split(":scale");
  5683. const NodePath path = node_suffix[0];
  5684. const Node *node = animation_base_node->get_node_or_null(path);
  5685. ERR_CONTINUE_MSG(!node, "Cannot get the node from a scale path.");
  5686. for (const KeyValue<GLTFNodeIndex, Node *> &scale_scene_node_i : p_state->scene_nodes) {
  5687. if (scale_scene_node_i.value == node) {
  5688. GLTFNodeIndex node_index = scale_scene_node_i.key;
  5689. HashMap<int, GLTFAnimation::Track>::Iterator scale_track_i = gltf_animation->get_tracks().find(node_index);
  5690. GLTFAnimation::Track track;
  5691. if (scale_track_i) {
  5692. track = scale_track_i->value;
  5693. }
  5694. track = _convert_animation_track(p_state, track, animation, track_i, node_index);
  5695. gltf_animation->get_tracks().insert(node_index, track);
  5696. }
  5697. }
  5698. } else if (String(final_track_path).contains(":transform")) {
  5699. const Vector<String> node_suffix = String(final_track_path).split(":transform");
  5700. const NodePath path = node_suffix[0];
  5701. const Node *node = animation_base_node->get_node_or_null(path);
  5702. ERR_CONTINUE_MSG(!node, "Cannot get the node from a transform path.");
  5703. for (const KeyValue<GLTFNodeIndex, Node *> &transform_track_i : p_state->scene_nodes) {
  5704. if (transform_track_i.value == node) {
  5705. GLTFAnimation::Track track;
  5706. track = _convert_animation_track(p_state, track, animation, track_i, transform_track_i.key);
  5707. gltf_animation->get_tracks().insert(transform_track_i.key, track);
  5708. }
  5709. }
  5710. } else if (String(final_track_path).contains(":") && animation->track_get_type(track_i) == Animation::TYPE_BLEND_SHAPE) {
  5711. const Vector<String> node_suffix = String(final_track_path).split(":");
  5712. const NodePath path = node_suffix[0];
  5713. const String suffix = node_suffix[1];
  5714. Node *node = animation_base_node->get_node_or_null(path);
  5715. ERR_CONTINUE_MSG(!node, "Cannot get the node from a blend shape path.");
  5716. MeshInstance3D *mi = cast_to<MeshInstance3D>(node);
  5717. if (!mi) {
  5718. continue;
  5719. }
  5720. Ref<Mesh> mesh = mi->get_mesh();
  5721. ERR_CONTINUE(mesh.is_null());
  5722. int32_t mesh_index = -1;
  5723. for (const KeyValue<GLTFNodeIndex, Node *> &mesh_track_i : p_state->scene_nodes) {
  5724. if (mesh_track_i.value == node) {
  5725. mesh_index = mesh_track_i.key;
  5726. }
  5727. }
  5728. ERR_CONTINUE(mesh_index == -1);
  5729. HashMap<int, GLTFAnimation::Track> &tracks = gltf_animation->get_tracks();
  5730. GLTFAnimation::Track track = gltf_animation->get_tracks().has(mesh_index) ? gltf_animation->get_tracks()[mesh_index] : GLTFAnimation::Track();
  5731. if (!tracks.has(mesh_index)) {
  5732. for (int32_t shape_i = 0; shape_i < mesh->get_blend_shape_count(); shape_i++) {
  5733. String shape_name = mesh->get_blend_shape_name(shape_i);
  5734. NodePath shape_path = String(path) + ":" + shape_name;
  5735. int32_t shape_track_i = animation->find_track(shape_path, Animation::TYPE_BLEND_SHAPE);
  5736. if (shape_track_i == -1) {
  5737. GLTFAnimation::Channel<real_t> weight;
  5738. weight.interpolation = GLTFAnimation::INTERP_LINEAR;
  5739. weight.times.push_back(0.0f);
  5740. weight.times.push_back(0.0f);
  5741. weight.values.push_back(0.0f);
  5742. weight.values.push_back(0.0f);
  5743. track.weight_tracks.push_back(weight);
  5744. continue;
  5745. }
  5746. Animation::InterpolationType interpolation = animation->track_get_interpolation_type(track_i);
  5747. GLTFAnimation::Interpolation gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  5748. if (interpolation == Animation::InterpolationType::INTERPOLATION_LINEAR) {
  5749. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  5750. } else if (interpolation == Animation::InterpolationType::INTERPOLATION_NEAREST) {
  5751. gltf_interpolation = GLTFAnimation::INTERP_STEP;
  5752. } else if (interpolation == Animation::InterpolationType::INTERPOLATION_CUBIC) {
  5753. gltf_interpolation = GLTFAnimation::INTERP_CUBIC_SPLINE;
  5754. }
  5755. int32_t key_count = animation->track_get_key_count(shape_track_i);
  5756. GLTFAnimation::Channel<real_t> weight;
  5757. weight.interpolation = gltf_interpolation;
  5758. weight.times.resize(key_count);
  5759. for (int32_t time_i = 0; time_i < key_count; time_i++) {
  5760. weight.times.write[time_i] = animation->track_get_key_time(shape_track_i, time_i);
  5761. }
  5762. weight.values.resize(key_count);
  5763. for (int32_t value_i = 0; value_i < key_count; value_i++) {
  5764. weight.values.write[value_i] = animation->track_get_key_value(shape_track_i, value_i);
  5765. }
  5766. track.weight_tracks.push_back(weight);
  5767. }
  5768. tracks[mesh_index] = track;
  5769. }
  5770. } else if (String(final_track_path).contains(":")) {
  5771. //Process skeleton
  5772. const Vector<String> node_suffix = String(final_track_path).split(":");
  5773. const String &node = node_suffix[0];
  5774. const NodePath node_path = node;
  5775. const String &suffix = node_suffix[1];
  5776. Node *godot_node = animation_base_node->get_node_or_null(node_path);
  5777. if (!godot_node) {
  5778. continue;
  5779. }
  5780. Skeleton3D *skeleton = cast_to<Skeleton3D>(animation_base_node->get_node_or_null(node));
  5781. if (!skeleton) {
  5782. continue;
  5783. }
  5784. GLTFSkeletonIndex skeleton_gltf_i = -1;
  5785. for (GLTFSkeletonIndex skeleton_i = 0; skeleton_i < p_state->skeletons.size(); skeleton_i++) {
  5786. if (p_state->skeletons[skeleton_i]->godot_skeleton == cast_to<Skeleton3D>(godot_node)) {
  5787. skeleton = p_state->skeletons[skeleton_i]->godot_skeleton;
  5788. skeleton_gltf_i = skeleton_i;
  5789. ERR_CONTINUE(!skeleton);
  5790. Ref<GLTFSkeleton> skeleton_gltf = p_state->skeletons[skeleton_gltf_i];
  5791. int32_t bone = skeleton->find_bone(suffix);
  5792. ERR_CONTINUE_MSG(bone == -1, vformat("Cannot find the bone %s.", suffix));
  5793. if (!skeleton_gltf->godot_bone_node.has(bone)) {
  5794. continue;
  5795. }
  5796. GLTFNodeIndex node_i = skeleton_gltf->godot_bone_node[bone];
  5797. HashMap<int, GLTFAnimation::Track>::Iterator property_track_i = gltf_animation->get_tracks().find(node_i);
  5798. GLTFAnimation::Track track;
  5799. if (property_track_i) {
  5800. track = property_track_i->value;
  5801. }
  5802. track = _convert_animation_track(p_state, track, animation, track_i, node_i);
  5803. gltf_animation->get_tracks()[node_i] = track;
  5804. }
  5805. }
  5806. } else if (!String(final_track_path).contains(":")) {
  5807. ERR_CONTINUE(!animation_base_node);
  5808. Node *godot_node = animation_base_node->get_node_or_null(final_track_path);
  5809. ERR_CONTINUE_MSG(!godot_node, vformat("Cannot get the node from a skeleton path %s.", final_track_path));
  5810. for (const KeyValue<GLTFNodeIndex, Node *> &scene_node_i : p_state->scene_nodes) {
  5811. if (scene_node_i.value == godot_node) {
  5812. GLTFNodeIndex node_i = scene_node_i.key;
  5813. HashMap<int, GLTFAnimation::Track>::Iterator node_track_i = gltf_animation->get_tracks().find(node_i);
  5814. GLTFAnimation::Track track;
  5815. if (node_track_i) {
  5816. track = node_track_i->value;
  5817. }
  5818. track = _convert_animation_track(p_state, track, animation, track_i, node_i);
  5819. gltf_animation->get_tracks()[node_i] = track;
  5820. break;
  5821. }
  5822. }
  5823. }
  5824. }
  5825. if (gltf_animation->get_tracks().size()) {
  5826. p_state->animations.push_back(gltf_animation);
  5827. }
  5828. }
  5829. Error GLTFDocument::_parse(Ref<GLTFState> p_state, String p_path, Ref<FileAccess> p_file) {
  5830. Error err;
  5831. if (p_file.is_null()) {
  5832. return FAILED;
  5833. }
  5834. p_file->seek(0);
  5835. uint32_t magic = p_file->get_32();
  5836. if (magic == 0x46546C67) {
  5837. //binary file
  5838. //text file
  5839. p_file->seek(0);
  5840. err = _parse_glb(p_file, p_state);
  5841. if (err != OK) {
  5842. return err;
  5843. }
  5844. } else {
  5845. p_file->seek(0);
  5846. String text = p_file->get_as_utf8_string();
  5847. JSON json;
  5848. err = json.parse(text);
  5849. if (err != OK) {
  5850. _err_print_error("", "", json.get_error_line(), json.get_error_message().utf8().get_data(), false, ERR_HANDLER_SCRIPT);
  5851. }
  5852. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  5853. p_state->json = json.get_data();
  5854. }
  5855. err = _parse_asset_header(p_state);
  5856. ERR_FAIL_COND_V(err != OK, err);
  5857. document_extensions.clear();
  5858. for (Ref<GLTFDocumentExtension> ext : all_document_extensions) {
  5859. ERR_CONTINUE(ext.is_null());
  5860. err = ext->import_preflight(p_state, p_state->json["extensionsUsed"]);
  5861. if (err == OK) {
  5862. document_extensions.push_back(ext);
  5863. }
  5864. }
  5865. err = _parse_gltf_state(p_state, p_path);
  5866. ERR_FAIL_COND_V(err != OK, err);
  5867. return OK;
  5868. }
  5869. Dictionary _serialize_texture_transform_uv(Vector2 p_offset, Vector2 p_scale) {
  5870. Dictionary texture_transform;
  5871. bool is_offset = p_offset != Vector2(0.0, 0.0);
  5872. if (is_offset) {
  5873. Array offset;
  5874. offset.resize(2);
  5875. offset[0] = p_offset.x;
  5876. offset[1] = p_offset.y;
  5877. texture_transform["offset"] = offset;
  5878. }
  5879. bool is_scaled = p_scale != Vector2(1.0, 1.0);
  5880. if (is_scaled) {
  5881. Array scale;
  5882. scale.resize(2);
  5883. scale[0] = p_scale.x;
  5884. scale[1] = p_scale.y;
  5885. texture_transform["scale"] = scale;
  5886. }
  5887. Dictionary extension;
  5888. // Note: Godot doesn't support texture rotation.
  5889. if (is_offset || is_scaled) {
  5890. extension["KHR_texture_transform"] = texture_transform;
  5891. }
  5892. return extension;
  5893. }
  5894. Dictionary GLTFDocument::_serialize_texture_transform_uv1(Ref<BaseMaterial3D> p_material) {
  5895. ERR_FAIL_NULL_V(p_material, Dictionary());
  5896. Vector3 offset = p_material->get_uv1_offset();
  5897. Vector3 scale = p_material->get_uv1_scale();
  5898. return _serialize_texture_transform_uv(Vector2(offset.x, offset.y), Vector2(scale.x, scale.y));
  5899. }
  5900. Dictionary GLTFDocument::_serialize_texture_transform_uv2(Ref<BaseMaterial3D> p_material) {
  5901. ERR_FAIL_NULL_V(p_material, Dictionary());
  5902. Vector3 offset = p_material->get_uv2_offset();
  5903. Vector3 scale = p_material->get_uv2_scale();
  5904. return _serialize_texture_transform_uv(Vector2(offset.x, offset.y), Vector2(scale.x, scale.y));
  5905. }
  5906. Error GLTFDocument::_serialize_asset_header(Ref<GLTFState> p_state) {
  5907. const String version = "2.0";
  5908. p_state->major_version = version.get_slice(".", 0).to_int();
  5909. p_state->minor_version = version.get_slice(".", 1).to_int();
  5910. Dictionary asset;
  5911. asset["version"] = version;
  5912. if (!p_state->copyright.is_empty()) {
  5913. asset["copyright"] = p_state->copyright;
  5914. }
  5915. String hash = String(VERSION_HASH);
  5916. asset["generator"] = String(VERSION_FULL_NAME) + String("@") + (hash.is_empty() ? String("unknown") : hash);
  5917. p_state->json["asset"] = asset;
  5918. ERR_FAIL_COND_V(!asset.has("version"), Error::FAILED);
  5919. ERR_FAIL_COND_V(!p_state->json.has("asset"), Error::FAILED);
  5920. return OK;
  5921. }
  5922. Error GLTFDocument::_serialize_file(Ref<GLTFState> p_state, const String p_path) {
  5923. Error err = FAILED;
  5924. if (p_path.to_lower().ends_with("glb")) {
  5925. err = _encode_buffer_glb(p_state, p_path);
  5926. ERR_FAIL_COND_V(err != OK, err);
  5927. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  5928. ERR_FAIL_COND_V(file.is_null(), FAILED);
  5929. String json = Variant(p_state->json).to_json_string();
  5930. const uint32_t magic = 0x46546C67; // GLTF
  5931. const int32_t header_size = 12;
  5932. const int32_t chunk_header_size = 8;
  5933. CharString cs = json.utf8();
  5934. const uint32_t text_data_length = cs.length();
  5935. const uint32_t text_chunk_length = ((text_data_length + 3) & (~3));
  5936. const uint32_t text_chunk_type = 0x4E4F534A; //JSON
  5937. uint32_t binary_data_length = 0;
  5938. if (p_state->buffers.size()) {
  5939. binary_data_length = p_state->buffers[0].size();
  5940. }
  5941. const uint32_t binary_chunk_length = ((binary_data_length + 3) & (~3));
  5942. const uint32_t binary_chunk_type = 0x004E4942; //BIN
  5943. file->create(FileAccess::ACCESS_RESOURCES);
  5944. file->store_32(magic);
  5945. file->store_32(p_state->major_version); // version
  5946. file->store_32(header_size + chunk_header_size + text_chunk_length + chunk_header_size + binary_chunk_length); // length
  5947. file->store_32(text_chunk_length);
  5948. file->store_32(text_chunk_type);
  5949. file->store_buffer((uint8_t *)&cs[0], cs.length());
  5950. for (uint32_t pad_i = text_data_length; pad_i < text_chunk_length; pad_i++) {
  5951. file->store_8(' ');
  5952. }
  5953. if (binary_chunk_length) {
  5954. file->store_32(binary_chunk_length);
  5955. file->store_32(binary_chunk_type);
  5956. file->store_buffer(p_state->buffers[0].ptr(), binary_data_length);
  5957. }
  5958. for (uint32_t pad_i = binary_data_length; pad_i < binary_chunk_length; pad_i++) {
  5959. file->store_8(0);
  5960. }
  5961. } else {
  5962. err = _encode_buffer_bins(p_state, p_path);
  5963. ERR_FAIL_COND_V(err != OK, err);
  5964. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  5965. ERR_FAIL_COND_V(file.is_null(), FAILED);
  5966. file->create(FileAccess::ACCESS_RESOURCES);
  5967. String json = Variant(p_state->json).to_json_string();
  5968. file->store_string(json);
  5969. }
  5970. return err;
  5971. }
  5972. void GLTFDocument::_bind_methods() {
  5973. BIND_ENUM_CONSTANT(ROOT_NODE_MODE_SINGLE_ROOT);
  5974. BIND_ENUM_CONSTANT(ROOT_NODE_MODE_KEEP_ROOT);
  5975. BIND_ENUM_CONSTANT(ROOT_NODE_MODE_MULTI_ROOT);
  5976. ClassDB::bind_method(D_METHOD("set_image_format", "image_format"), &GLTFDocument::set_image_format);
  5977. ClassDB::bind_method(D_METHOD("get_image_format"), &GLTFDocument::get_image_format);
  5978. ClassDB::bind_method(D_METHOD("set_lossy_quality", "lossy_quality"), &GLTFDocument::set_lossy_quality);
  5979. ClassDB::bind_method(D_METHOD("get_lossy_quality"), &GLTFDocument::get_lossy_quality);
  5980. ClassDB::bind_method(D_METHOD("set_root_node_mode", "root_node_mode"), &GLTFDocument::set_root_node_mode);
  5981. ClassDB::bind_method(D_METHOD("get_root_node_mode"), &GLTFDocument::get_root_node_mode);
  5982. ClassDB::bind_method(D_METHOD("append_from_file", "path", "state", "flags", "base_path"),
  5983. &GLTFDocument::append_from_file, DEFVAL(0), DEFVAL(String()));
  5984. ClassDB::bind_method(D_METHOD("append_from_buffer", "bytes", "base_path", "state", "flags"),
  5985. &GLTFDocument::append_from_buffer, DEFVAL(0));
  5986. ClassDB::bind_method(D_METHOD("append_from_scene", "node", "state", "flags"),
  5987. &GLTFDocument::append_from_scene, DEFVAL(0));
  5988. ClassDB::bind_method(D_METHOD("generate_scene", "state", "bake_fps", "trimming", "remove_immutable_tracks"),
  5989. &GLTFDocument::generate_scene, DEFVAL(30), DEFVAL(false), DEFVAL(true));
  5990. ClassDB::bind_method(D_METHOD("generate_buffer", "state"),
  5991. &GLTFDocument::generate_buffer);
  5992. ClassDB::bind_method(D_METHOD("write_to_filesystem", "state", "path"),
  5993. &GLTFDocument::write_to_filesystem);
  5994. ADD_PROPERTY(PropertyInfo(Variant::STRING, "image_format"), "set_image_format", "get_image_format");
  5995. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "lossy_quality"), "set_lossy_quality", "get_lossy_quality");
  5996. ADD_PROPERTY(PropertyInfo(Variant::INT, "root_node_mode"), "set_root_node_mode", "get_root_node_mode");
  5997. ClassDB::bind_static_method("GLTFDocument", D_METHOD("register_gltf_document_extension", "extension", "first_priority"),
  5998. &GLTFDocument::register_gltf_document_extension, DEFVAL(false));
  5999. ClassDB::bind_static_method("GLTFDocument", D_METHOD("unregister_gltf_document_extension", "extension"),
  6000. &GLTFDocument::unregister_gltf_document_extension);
  6001. }
  6002. void GLTFDocument::_build_parent_hierachy(Ref<GLTFState> p_state) {
  6003. // build the hierarchy
  6004. for (GLTFNodeIndex node_i = 0; node_i < p_state->nodes.size(); node_i++) {
  6005. for (int j = 0; j < p_state->nodes[node_i]->children.size(); j++) {
  6006. GLTFNodeIndex child_i = p_state->nodes[node_i]->children[j];
  6007. ERR_FAIL_INDEX(child_i, p_state->nodes.size());
  6008. if (p_state->nodes.write[child_i]->parent != -1) {
  6009. continue;
  6010. }
  6011. p_state->nodes.write[child_i]->parent = node_i;
  6012. }
  6013. }
  6014. }
  6015. Vector<Ref<GLTFDocumentExtension>> GLTFDocument::all_document_extensions;
  6016. void GLTFDocument::register_gltf_document_extension(Ref<GLTFDocumentExtension> p_extension, bool p_first_priority) {
  6017. if (all_document_extensions.find(p_extension) == -1) {
  6018. if (p_first_priority) {
  6019. all_document_extensions.insert(0, p_extension);
  6020. } else {
  6021. all_document_extensions.push_back(p_extension);
  6022. }
  6023. }
  6024. }
  6025. void GLTFDocument::unregister_gltf_document_extension(Ref<GLTFDocumentExtension> p_extension) {
  6026. all_document_extensions.erase(p_extension);
  6027. }
  6028. void GLTFDocument::unregister_all_gltf_document_extensions() {
  6029. all_document_extensions.clear();
  6030. }
  6031. Vector<Ref<GLTFDocumentExtension>> GLTFDocument::get_all_gltf_document_extensions() {
  6032. return all_document_extensions;
  6033. }
  6034. PackedByteArray GLTFDocument::_serialize_glb_buffer(Ref<GLTFState> p_state, Error *r_err) {
  6035. Error err = _encode_buffer_glb(p_state, "");
  6036. if (r_err) {
  6037. *r_err = err;
  6038. }
  6039. ERR_FAIL_COND_V(err != OK, PackedByteArray());
  6040. String json = Variant(p_state->json).to_json_string();
  6041. const uint32_t magic = 0x46546C67; // GLTF
  6042. const int32_t header_size = 12;
  6043. const int32_t chunk_header_size = 8;
  6044. int32_t padding = (chunk_header_size + json.utf8().length()) % 4;
  6045. json += String(" ").repeat(padding);
  6046. CharString cs = json.utf8();
  6047. const uint32_t text_chunk_length = cs.length();
  6048. const uint32_t text_chunk_type = 0x4E4F534A; //JSON
  6049. int32_t binary_data_length = 0;
  6050. if (p_state->buffers.size()) {
  6051. binary_data_length = p_state->buffers[0].size();
  6052. }
  6053. const int32_t binary_chunk_length = binary_data_length;
  6054. const int32_t binary_chunk_type = 0x004E4942; //BIN
  6055. Ref<StreamPeerBuffer> buffer;
  6056. buffer.instantiate();
  6057. buffer->put_32(magic);
  6058. buffer->put_32(p_state->major_version); // version
  6059. buffer->put_32(header_size + chunk_header_size + text_chunk_length + chunk_header_size + binary_data_length); // length
  6060. buffer->put_32(text_chunk_length);
  6061. buffer->put_32(text_chunk_type);
  6062. buffer->put_data((uint8_t *)&cs[0], cs.length());
  6063. if (binary_chunk_length) {
  6064. buffer->put_32(binary_chunk_length);
  6065. buffer->put_32(binary_chunk_type);
  6066. buffer->put_data(p_state->buffers[0].ptr(), binary_data_length);
  6067. }
  6068. return buffer->get_data_array();
  6069. }
  6070. Node *GLTFDocument::_generate_scene_node_tree(Ref<GLTFState> p_state) {
  6071. // Generate the skeletons and skins (if any).
  6072. HashMap<ObjectID, SkinSkeletonIndex> skeleton_map;
  6073. Error err = SkinTool::_create_skeletons(p_state->unique_names, p_state->skins, p_state->nodes,
  6074. skeleton_map, p_state->skeletons, p_state->scene_nodes);
  6075. ERR_FAIL_COND_V_MSG(err != OK, nullptr, "GLTF: Failed to create skeletons.");
  6076. err = _create_skins(p_state);
  6077. ERR_FAIL_COND_V_MSG(err != OK, nullptr, "GLTF: Failed to create skins.");
  6078. // Generate the node tree.
  6079. Node *single_root;
  6080. if (p_state->extensions_used.has("GODOT_single_root")) {
  6081. _generate_scene_node(p_state, 0, nullptr, nullptr);
  6082. single_root = p_state->scene_nodes[0];
  6083. } else {
  6084. single_root = memnew(Node3D);
  6085. for (int32_t root_i = 0; root_i < p_state->root_nodes.size(); root_i++) {
  6086. _generate_scene_node(p_state, p_state->root_nodes[root_i], single_root, single_root);
  6087. }
  6088. }
  6089. // Assign the scene name and single root name to each other
  6090. // if one is missing, or do nothing if both are already set.
  6091. if (unlikely(p_state->scene_name.is_empty())) {
  6092. p_state->scene_name = single_root->get_name();
  6093. } else if (single_root->get_name() == StringName()) {
  6094. if (_naming_version == 0) {
  6095. single_root->set_name(p_state->scene_name);
  6096. } else {
  6097. single_root->set_name(_gen_unique_name(p_state, p_state->scene_name));
  6098. }
  6099. }
  6100. return single_root;
  6101. }
  6102. Error GLTFDocument::_parse_asset_header(Ref<GLTFState> p_state) {
  6103. if (!p_state->json.has("asset")) {
  6104. return ERR_PARSE_ERROR;
  6105. }
  6106. Dictionary asset = p_state->json["asset"];
  6107. if (!asset.has("version")) {
  6108. return ERR_PARSE_ERROR;
  6109. }
  6110. String version = asset["version"];
  6111. p_state->major_version = version.get_slice(".", 0).to_int();
  6112. p_state->minor_version = version.get_slice(".", 1).to_int();
  6113. if (asset.has("copyright")) {
  6114. p_state->copyright = asset["copyright"];
  6115. }
  6116. return OK;
  6117. }
  6118. Error GLTFDocument::_parse_gltf_state(Ref<GLTFState> p_state, const String &p_search_path) {
  6119. Error err;
  6120. /* PARSE EXTENSIONS */
  6121. err = _parse_gltf_extensions(p_state);
  6122. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  6123. /* PARSE SCENE */
  6124. err = _parse_scenes(p_state);
  6125. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  6126. /* PARSE NODES */
  6127. err = _parse_nodes(p_state);
  6128. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  6129. /* PARSE BUFFERS */
  6130. err = _parse_buffers(p_state, p_search_path);
  6131. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  6132. /* PARSE BUFFER VIEWS */
  6133. err = _parse_buffer_views(p_state);
  6134. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  6135. /* PARSE ACCESSORS */
  6136. err = _parse_accessors(p_state);
  6137. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  6138. if (!p_state->discard_meshes_and_materials) {
  6139. /* PARSE IMAGES */
  6140. err = _parse_images(p_state, p_search_path);
  6141. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  6142. /* PARSE TEXTURE SAMPLERS */
  6143. err = _parse_texture_samplers(p_state);
  6144. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  6145. /* PARSE TEXTURES */
  6146. err = _parse_textures(p_state);
  6147. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  6148. /* PARSE TEXTURES */
  6149. err = _parse_materials(p_state);
  6150. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  6151. }
  6152. /* PARSE SKINS */
  6153. err = _parse_skins(p_state);
  6154. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  6155. /* DETERMINE SKELETONS */
  6156. err = SkinTool::_determine_skeletons(p_state->skins, p_state->nodes, p_state->skeletons);
  6157. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  6158. /* PARSE MESHES (we have enough info now) */
  6159. err = _parse_meshes(p_state);
  6160. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  6161. /* PARSE LIGHTS */
  6162. err = _parse_lights(p_state);
  6163. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  6164. /* PARSE CAMERAS */
  6165. err = _parse_cameras(p_state);
  6166. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  6167. /* PARSE ANIMATIONS */
  6168. err = _parse_animations(p_state);
  6169. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  6170. /* ASSIGN SCENE NAMES */
  6171. _assign_node_names(p_state);
  6172. return OK;
  6173. }
  6174. PackedByteArray GLTFDocument::generate_buffer(Ref<GLTFState> p_state) {
  6175. Ref<GLTFState> state = p_state;
  6176. ERR_FAIL_NULL_V(state, PackedByteArray());
  6177. // For buffers, set the state filename to an empty string, but
  6178. // don't touch the base path, in case the user set it manually.
  6179. state->filename = "";
  6180. Error err = _serialize(state);
  6181. ERR_FAIL_COND_V(err != OK, PackedByteArray());
  6182. PackedByteArray bytes = _serialize_glb_buffer(state, &err);
  6183. return bytes;
  6184. }
  6185. Error GLTFDocument::write_to_filesystem(Ref<GLTFState> p_state, const String &p_path) {
  6186. Ref<GLTFState> state = p_state;
  6187. ERR_FAIL_NULL_V(state, ERR_INVALID_PARAMETER);
  6188. state->base_path = p_path.get_base_dir();
  6189. state->filename = p_path.get_file();
  6190. Error err = _serialize(state);
  6191. if (err != OK) {
  6192. return err;
  6193. }
  6194. err = _serialize_file(state, p_path);
  6195. if (err != OK) {
  6196. return Error::FAILED;
  6197. }
  6198. return OK;
  6199. }
  6200. Node *GLTFDocument::generate_scene(Ref<GLTFState> p_state, float p_bake_fps, bool p_trimming, bool p_remove_immutable_tracks) {
  6201. Ref<GLTFState> state = p_state;
  6202. ERR_FAIL_NULL_V(state, nullptr);
  6203. ERR_FAIL_INDEX_V(0, state->root_nodes.size(), nullptr);
  6204. Error err = OK;
  6205. Node *root = _generate_scene_node_tree(state);
  6206. ERR_FAIL_NULL_V(root, nullptr);
  6207. _process_mesh_instances(state, root);
  6208. if (state->get_create_animations() && state->animations.size()) {
  6209. AnimationPlayer *ap = memnew(AnimationPlayer);
  6210. root->add_child(ap, true);
  6211. ap->set_owner(root);
  6212. for (int i = 0; i < state->animations.size(); i++) {
  6213. _import_animation(state, ap, i, p_bake_fps, p_trimming, p_remove_immutable_tracks);
  6214. }
  6215. }
  6216. for (KeyValue<GLTFNodeIndex, Node *> E : state->scene_nodes) {
  6217. ERR_CONTINUE(!E.value);
  6218. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  6219. ERR_CONTINUE(ext.is_null());
  6220. Dictionary node_json;
  6221. if (state->json.has("nodes")) {
  6222. Array nodes = state->json["nodes"];
  6223. if (0 <= E.key && E.key < nodes.size()) {
  6224. node_json = nodes[E.key];
  6225. }
  6226. }
  6227. Ref<GLTFNode> gltf_node = state->nodes[E.key];
  6228. err = ext->import_node(p_state, gltf_node, node_json, E.value);
  6229. ERR_CONTINUE(err != OK);
  6230. }
  6231. }
  6232. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  6233. ERR_CONTINUE(ext.is_null());
  6234. err = ext->import_post(p_state, root);
  6235. ERR_CONTINUE(err != OK);
  6236. }
  6237. ERR_FAIL_NULL_V(root, nullptr);
  6238. return root;
  6239. }
  6240. Error GLTFDocument::append_from_scene(Node *p_node, Ref<GLTFState> p_state, uint32_t p_flags) {
  6241. Ref<GLTFState> state = p_state;
  6242. ERR_FAIL_COND_V(state.is_null(), FAILED);
  6243. state->use_named_skin_binds = p_flags & GLTF_IMPORT_USE_NAMED_SKIN_BINDS;
  6244. state->discard_meshes_and_materials = p_flags & GLTF_IMPORT_DISCARD_MESHES_AND_MATERIALS;
  6245. state->force_generate_tangents = p_flags & GLTF_IMPORT_GENERATE_TANGENT_ARRAYS;
  6246. state->force_disable_compression = p_flags & GLTF_IMPORT_FORCE_DISABLE_MESH_COMPRESSION;
  6247. if (!state->buffers.size()) {
  6248. state->buffers.push_back(Vector<uint8_t>());
  6249. }
  6250. // Perform export preflight for document extensions. Only extensions that
  6251. // return OK will be used for the rest of the export steps.
  6252. document_extensions.clear();
  6253. for (Ref<GLTFDocumentExtension> ext : all_document_extensions) {
  6254. ERR_CONTINUE(ext.is_null());
  6255. Error err = ext->export_preflight(state, p_node);
  6256. if (err == OK) {
  6257. document_extensions.push_back(ext);
  6258. }
  6259. }
  6260. // Add the root node(s) and their descendants to the state.
  6261. if (_root_node_mode == RootNodeMode::ROOT_NODE_MODE_MULTI_ROOT) {
  6262. const int child_count = p_node->get_child_count();
  6263. if (child_count > 0) {
  6264. for (int i = 0; i < child_count; i++) {
  6265. _convert_scene_node(state, p_node->get_child(i), -1, -1);
  6266. }
  6267. state->scene_name = p_node->get_name();
  6268. return OK;
  6269. }
  6270. }
  6271. if (_root_node_mode == RootNodeMode::ROOT_NODE_MODE_SINGLE_ROOT) {
  6272. state->extensions_used.append("GODOT_single_root");
  6273. }
  6274. _convert_scene_node(state, p_node, -1, -1);
  6275. return OK;
  6276. }
  6277. Error GLTFDocument::append_from_buffer(PackedByteArray p_bytes, String p_base_path, Ref<GLTFState> p_state, uint32_t p_flags) {
  6278. Ref<GLTFState> state = p_state;
  6279. ERR_FAIL_COND_V(state.is_null(), FAILED);
  6280. // TODO Add missing texture and missing .bin file paths to r_missing_deps 2021-09-10 fire
  6281. Error err = FAILED;
  6282. state->use_named_skin_binds = p_flags & GLTF_IMPORT_USE_NAMED_SKIN_BINDS;
  6283. state->discard_meshes_and_materials = p_flags & GLTF_IMPORT_DISCARD_MESHES_AND_MATERIALS;
  6284. state->force_generate_tangents = p_flags & GLTF_IMPORT_GENERATE_TANGENT_ARRAYS;
  6285. state->force_disable_compression = p_flags & GLTF_IMPORT_FORCE_DISABLE_MESH_COMPRESSION;
  6286. Ref<FileAccessMemory> file_access;
  6287. file_access.instantiate();
  6288. file_access->open_custom(p_bytes.ptr(), p_bytes.size());
  6289. state->base_path = p_base_path.get_base_dir();
  6290. err = _parse(p_state, state->base_path, file_access);
  6291. ERR_FAIL_COND_V(err != OK, err);
  6292. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  6293. ERR_CONTINUE(ext.is_null());
  6294. err = ext->import_post_parse(state);
  6295. ERR_FAIL_COND_V(err != OK, err);
  6296. }
  6297. return OK;
  6298. }
  6299. Error GLTFDocument::append_from_file(String p_path, Ref<GLTFState> p_state, uint32_t p_flags, String p_base_path) {
  6300. Ref<GLTFState> state = p_state;
  6301. // TODO Add missing texture and missing .bin file paths to r_missing_deps 2021-09-10 fire
  6302. if (state == Ref<GLTFState>()) {
  6303. state.instantiate();
  6304. }
  6305. state->filename = p_path.get_file().get_basename();
  6306. state->use_named_skin_binds = p_flags & GLTF_IMPORT_USE_NAMED_SKIN_BINDS;
  6307. state->discard_meshes_and_materials = p_flags & GLTF_IMPORT_DISCARD_MESHES_AND_MATERIALS;
  6308. state->force_generate_tangents = p_flags & GLTF_IMPORT_GENERATE_TANGENT_ARRAYS;
  6309. state->force_disable_compression = p_flags & GLTF_IMPORT_FORCE_DISABLE_MESH_COMPRESSION;
  6310. Error err;
  6311. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::READ, &err);
  6312. ERR_FAIL_COND_V(err != OK, ERR_FILE_CANT_OPEN);
  6313. ERR_FAIL_NULL_V(file, ERR_FILE_CANT_OPEN);
  6314. String base_path = p_base_path;
  6315. if (base_path.is_empty()) {
  6316. base_path = p_path.get_base_dir();
  6317. }
  6318. state->base_path = base_path;
  6319. err = _parse(p_state, base_path, file);
  6320. ERR_FAIL_COND_V(err != OK, err);
  6321. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  6322. ERR_CONTINUE(ext.is_null());
  6323. err = ext->import_post_parse(p_state);
  6324. ERR_FAIL_COND_V(err != OK, err);
  6325. }
  6326. return OK;
  6327. }
  6328. Error GLTFDocument::_parse_gltf_extensions(Ref<GLTFState> p_state) {
  6329. ERR_FAIL_NULL_V(p_state, ERR_PARSE_ERROR);
  6330. if (p_state->json.has("extensionsUsed")) {
  6331. Vector<String> ext_array = p_state->json["extensionsUsed"];
  6332. p_state->extensions_used = ext_array;
  6333. }
  6334. if (p_state->json.has("extensionsRequired")) {
  6335. Vector<String> ext_array = p_state->json["extensionsRequired"];
  6336. p_state->extensions_required = ext_array;
  6337. }
  6338. HashSet<String> supported_extensions;
  6339. supported_extensions.insert("KHR_lights_punctual");
  6340. supported_extensions.insert("KHR_materials_pbrSpecularGlossiness");
  6341. supported_extensions.insert("KHR_texture_transform");
  6342. supported_extensions.insert("KHR_materials_unlit");
  6343. supported_extensions.insert("KHR_materials_emissive_strength");
  6344. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  6345. ERR_CONTINUE(ext.is_null());
  6346. Vector<String> ext_supported_extensions = ext->get_supported_extensions();
  6347. for (int i = 0; i < ext_supported_extensions.size(); ++i) {
  6348. supported_extensions.insert(ext_supported_extensions[i]);
  6349. }
  6350. }
  6351. Error ret = OK;
  6352. for (int i = 0; i < p_state->extensions_required.size(); i++) {
  6353. if (!supported_extensions.has(p_state->extensions_required[i])) {
  6354. ERR_PRINT("GLTF: Can't import file '" + p_state->filename + "', required extension '" + String(p_state->extensions_required[i]) + "' is not supported. Are you missing a GLTFDocumentExtension plugin?");
  6355. ret = ERR_UNAVAILABLE;
  6356. }
  6357. }
  6358. return ret;
  6359. }
  6360. void GLTFDocument::set_root_node_mode(GLTFDocument::RootNodeMode p_root_node_mode) {
  6361. _root_node_mode = p_root_node_mode;
  6362. }
  6363. GLTFDocument::RootNodeMode GLTFDocument::get_root_node_mode() const {
  6364. return _root_node_mode;
  6365. }
  6366. String GLTFDocument::_gen_unique_name_static(HashSet<String> &r_unique_names, const String &p_name) {
  6367. const String s_name = p_name.validate_node_name();
  6368. String u_name;
  6369. int index = 1;
  6370. while (true) {
  6371. u_name = s_name;
  6372. if (index > 1) {
  6373. u_name += itos(index);
  6374. }
  6375. if (!r_unique_names.has(u_name)) {
  6376. break;
  6377. }
  6378. index++;
  6379. }
  6380. r_unique_names.insert(u_name);
  6381. return u_name;
  6382. }