gltf_document.cpp 292 KB

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