gltf_document.cpp 222 KB

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