gltf_document.cpp 235 KB

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