gltf_document.cpp 262 KB

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