gltf_document.cpp 331 KB

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