gltf_document.cpp 351 KB

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