gltf_document.cpp 221 KB

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