gltf_document.cpp 331 KB

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