tiny_gltf.h 249 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058
  1. //
  2. // Header-only tiny glTF 2.0 loader and serializer.
  3. //
  4. //
  5. // The MIT License (MIT)
  6. //
  7. // Copyright (c) 2015 - Present Syoyo Fujita, Aurélien Chatelain and many
  8. // contributors.
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining a copy
  11. // of this software and associated documentation files (the "Software"), to deal
  12. // in the Software without restriction, including without limitation the rights
  13. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. // copies of the Software, and to permit persons to whom the Software is
  15. // furnished to do so, subject to the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be included in
  18. // all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  26. // THE SOFTWARE.
  27. // Version:
  28. // - v2.8.1 Missed serialization texture sampler name fixed. PR#399.
  29. // - v2.8.0 Add URICallbacks for custom URI handling in Buffer and Image. PR#397.
  30. // - v2.7.0 Change WriteImageDataFunction user callback function signature. PR#393.
  31. // - v2.6.3 Fix GLB file with empty BIN chunk was not handled. PR#382 and PR#383.
  32. // - v2.6.2 Fix out-of-bounds access of accessors. PR#379.
  33. // - v2.6.1 Better GLB validation check when loading.
  34. // - v2.6.0 Support serializing sparse accessor(Thanks to @fynv).
  35. // Disable expanding file path for security(no use of awkward `wordexp` anymore).
  36. // - v2.5.0 Add SetPreserveImageChannels() option to load image data as is.
  37. // - v2.4.3 Fix null object output when material has all default
  38. // parameters.
  39. // - v2.4.2 Decode percent-encoded URI.
  40. // - v2.4.1 Fix some glTF object class does not have `extensions` and/or
  41. // `extras` property.
  42. // - v2.4.0 Experimental RapidJSON and C++14 support(Thanks to @jrkoone).
  43. // - v2.3.1 Set default value of minFilter and magFilter in Sampler to -1.
  44. // - v2.3.0 Modified Material representation according to glTF 2.0 schema
  45. // (and introduced TextureInfo class)
  46. // Change the behavior of `Value::IsNumber`. It return true either the
  47. // value is int or real.
  48. // - v2.2.0 Add loading 16bit PNG support. Add Sparse accessor support(Thanks
  49. // to @Ybalrid)
  50. // - v2.1.0 Add draco compression.
  51. // - v2.0.1 Add comparison feature(Thanks to @Selmar).
  52. // - v2.0.0 glTF 2.0!.
  53. //
  54. // Tiny glTF loader is using following third party libraries:
  55. //
  56. // - jsonhpp: C++ JSON library.
  57. // - base64: base64 decode/encode library.
  58. // - stb_image: Image loading library.
  59. //
  60. #ifndef TINY_GLTF_H_
  61. #define TINY_GLTF_H_
  62. #include <array>
  63. #include <cassert>
  64. #include <cmath> // std::fabs
  65. #include <cstdint>
  66. #include <cstdlib>
  67. #include <cstring>
  68. #include <limits>
  69. #include <map>
  70. #include <string>
  71. #include <vector>
  72. //Auto-detect C++14 standard version
  73. #if !defined(TINYGLTF_USE_CPP14) && defined(__cplusplus) && (__cplusplus >= 201402L)
  74. #define TINYGLTF_USE_CPP14
  75. #endif
  76. #ifndef TINYGLTF_USE_CPP14
  77. #include <functional>
  78. #endif
  79. #ifdef __ANDROID__
  80. #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS
  81. #include <android/asset_manager.h>
  82. #endif
  83. #endif
  84. #ifdef __GNUC__
  85. #if (__GNUC__ < 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ <= 8))
  86. #define TINYGLTF_NOEXCEPT
  87. #else
  88. #define TINYGLTF_NOEXCEPT noexcept
  89. #endif
  90. #else
  91. #define TINYGLTF_NOEXCEPT noexcept
  92. #endif
  93. #define DEFAULT_METHODS(x) \
  94. ~x() = default; \
  95. x(const x &) = default; \
  96. x(x &&) TINYGLTF_NOEXCEPT = default; \
  97. x &operator=(const x &) = default; \
  98. x &operator=(x &&) TINYGLTF_NOEXCEPT = default;
  99. namespace tinygltf {
  100. #define TINYGLTF_MODE_POINTS (0)
  101. #define TINYGLTF_MODE_LINE (1)
  102. #define TINYGLTF_MODE_LINE_LOOP (2)
  103. #define TINYGLTF_MODE_LINE_STRIP (3)
  104. #define TINYGLTF_MODE_TRIANGLES (4)
  105. #define TINYGLTF_MODE_TRIANGLE_STRIP (5)
  106. #define TINYGLTF_MODE_TRIANGLE_FAN (6)
  107. #define TINYGLTF_COMPONENT_TYPE_BYTE (5120)
  108. #define TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE (5121)
  109. #define TINYGLTF_COMPONENT_TYPE_SHORT (5122)
  110. #define TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT (5123)
  111. #define TINYGLTF_COMPONENT_TYPE_INT (5124)
  112. #define TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT (5125)
  113. #define TINYGLTF_COMPONENT_TYPE_FLOAT (5126)
  114. #define TINYGLTF_COMPONENT_TYPE_DOUBLE \
  115. (5130) // OpenGL double type. Note that some of glTF 2.0 validator does not
  116. // support double type even the schema seems allow any value of
  117. // integer:
  118. // https://github.com/KhronosGroup/glTF/blob/b9884a2fd45130b4d673dd6c8a706ee21ee5c5f7/specification/2.0/schema/accessor.schema.json#L22
  119. #define TINYGLTF_TEXTURE_FILTER_NEAREST (9728)
  120. #define TINYGLTF_TEXTURE_FILTER_LINEAR (9729)
  121. #define TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_NEAREST (9984)
  122. #define TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST (9985)
  123. #define TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_LINEAR (9986)
  124. #define TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_LINEAR (9987)
  125. #define TINYGLTF_TEXTURE_WRAP_REPEAT (10497)
  126. #define TINYGLTF_TEXTURE_WRAP_CLAMP_TO_EDGE (33071)
  127. #define TINYGLTF_TEXTURE_WRAP_MIRRORED_REPEAT (33648)
  128. // Redeclarations of the above for technique.parameters.
  129. #define TINYGLTF_PARAMETER_TYPE_BYTE (5120)
  130. #define TINYGLTF_PARAMETER_TYPE_UNSIGNED_BYTE (5121)
  131. #define TINYGLTF_PARAMETER_TYPE_SHORT (5122)
  132. #define TINYGLTF_PARAMETER_TYPE_UNSIGNED_SHORT (5123)
  133. #define TINYGLTF_PARAMETER_TYPE_INT (5124)
  134. #define TINYGLTF_PARAMETER_TYPE_UNSIGNED_INT (5125)
  135. #define TINYGLTF_PARAMETER_TYPE_FLOAT (5126)
  136. #define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC2 (35664)
  137. #define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC3 (35665)
  138. #define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC4 (35666)
  139. #define TINYGLTF_PARAMETER_TYPE_INT_VEC2 (35667)
  140. #define TINYGLTF_PARAMETER_TYPE_INT_VEC3 (35668)
  141. #define TINYGLTF_PARAMETER_TYPE_INT_VEC4 (35669)
  142. #define TINYGLTF_PARAMETER_TYPE_BOOL (35670)
  143. #define TINYGLTF_PARAMETER_TYPE_BOOL_VEC2 (35671)
  144. #define TINYGLTF_PARAMETER_TYPE_BOOL_VEC3 (35672)
  145. #define TINYGLTF_PARAMETER_TYPE_BOOL_VEC4 (35673)
  146. #define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT2 (35674)
  147. #define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT3 (35675)
  148. #define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT4 (35676)
  149. #define TINYGLTF_PARAMETER_TYPE_SAMPLER_2D (35678)
  150. // End parameter types
  151. #define TINYGLTF_TYPE_VEC2 (2)
  152. #define TINYGLTF_TYPE_VEC3 (3)
  153. #define TINYGLTF_TYPE_VEC4 (4)
  154. #define TINYGLTF_TYPE_MAT2 (32 + 2)
  155. #define TINYGLTF_TYPE_MAT3 (32 + 3)
  156. #define TINYGLTF_TYPE_MAT4 (32 + 4)
  157. #define TINYGLTF_TYPE_SCALAR (64 + 1)
  158. #define TINYGLTF_TYPE_VECTOR (64 + 4)
  159. #define TINYGLTF_TYPE_MATRIX (64 + 16)
  160. #define TINYGLTF_IMAGE_FORMAT_JPEG (0)
  161. #define TINYGLTF_IMAGE_FORMAT_PNG (1)
  162. #define TINYGLTF_IMAGE_FORMAT_BMP (2)
  163. #define TINYGLTF_IMAGE_FORMAT_GIF (3)
  164. #define TINYGLTF_TEXTURE_FORMAT_ALPHA (6406)
  165. #define TINYGLTF_TEXTURE_FORMAT_RGB (6407)
  166. #define TINYGLTF_TEXTURE_FORMAT_RGBA (6408)
  167. #define TINYGLTF_TEXTURE_FORMAT_LUMINANCE (6409)
  168. #define TINYGLTF_TEXTURE_FORMAT_LUMINANCE_ALPHA (6410)
  169. #define TINYGLTF_TEXTURE_TARGET_TEXTURE2D (3553)
  170. #define TINYGLTF_TEXTURE_TYPE_UNSIGNED_BYTE (5121)
  171. #define TINYGLTF_TARGET_ARRAY_BUFFER (34962)
  172. #define TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER (34963)
  173. #define TINYGLTF_SHADER_TYPE_VERTEX_SHADER (35633)
  174. #define TINYGLTF_SHADER_TYPE_FRAGMENT_SHADER (35632)
  175. #define TINYGLTF_DOUBLE_EPS (1.e-12)
  176. #define TINYGLTF_DOUBLE_EQUAL(a, b) (std::fabs((b) - (a)) < TINYGLTF_DOUBLE_EPS)
  177. #ifdef __ANDROID__
  178. #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS
  179. #ifdef TINYGLTF_IMPLEMENTATION
  180. AAssetManager *asset_manager = nullptr;
  181. #else
  182. extern AAssetManager *asset_manager;
  183. #endif
  184. #endif
  185. #endif
  186. typedef enum {
  187. NULL_TYPE,
  188. REAL_TYPE,
  189. INT_TYPE,
  190. BOOL_TYPE,
  191. STRING_TYPE,
  192. ARRAY_TYPE,
  193. BINARY_TYPE,
  194. OBJECT_TYPE
  195. } Type;
  196. static inline int32_t GetComponentSizeInBytes(uint32_t componentType) {
  197. if (componentType == TINYGLTF_COMPONENT_TYPE_BYTE) {
  198. return 1;
  199. } else if (componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE) {
  200. return 1;
  201. } else if (componentType == TINYGLTF_COMPONENT_TYPE_SHORT) {
  202. return 2;
  203. } else if (componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT) {
  204. return 2;
  205. } else if (componentType == TINYGLTF_COMPONENT_TYPE_INT) {
  206. return 4;
  207. } else if (componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT) {
  208. return 4;
  209. } else if (componentType == TINYGLTF_COMPONENT_TYPE_FLOAT) {
  210. return 4;
  211. } else if (componentType == TINYGLTF_COMPONENT_TYPE_DOUBLE) {
  212. return 8;
  213. } else {
  214. // Unknown component type
  215. return -1;
  216. }
  217. }
  218. static inline int32_t GetNumComponentsInType(uint32_t ty) {
  219. if (ty == TINYGLTF_TYPE_SCALAR) {
  220. return 1;
  221. } else if (ty == TINYGLTF_TYPE_VEC2) {
  222. return 2;
  223. } else if (ty == TINYGLTF_TYPE_VEC3) {
  224. return 3;
  225. } else if (ty == TINYGLTF_TYPE_VEC4) {
  226. return 4;
  227. } else if (ty == TINYGLTF_TYPE_MAT2) {
  228. return 4;
  229. } else if (ty == TINYGLTF_TYPE_MAT3) {
  230. return 9;
  231. } else if (ty == TINYGLTF_TYPE_MAT4) {
  232. return 16;
  233. } else {
  234. // Unknown component type
  235. return -1;
  236. }
  237. }
  238. // TODO(syoyo): Move these functions to TinyGLTF class
  239. bool IsDataURI(const std::string &in);
  240. bool DecodeDataURI(std::vector<unsigned char> *out, std::string &mime_type,
  241. const std::string &in, size_t reqBytes, bool checkSize);
  242. #ifdef __clang__
  243. #pragma clang diagnostic push
  244. // Suppress warning for : static Value null_value
  245. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  246. #pragma clang diagnostic ignored "-Wpadded"
  247. #endif
  248. // Simple class to represent JSON object
  249. class Value {
  250. public:
  251. typedef std::vector<Value> Array;
  252. typedef std::map<std::string, Value> Object;
  253. Value()
  254. : type_(NULL_TYPE),
  255. int_value_(0),
  256. real_value_(0.0),
  257. boolean_value_(false) {}
  258. explicit Value(bool b) : type_(BOOL_TYPE) { boolean_value_ = b; }
  259. explicit Value(int i) : type_(INT_TYPE) {
  260. int_value_ = i;
  261. real_value_ = i;
  262. }
  263. explicit Value(double n) : type_(REAL_TYPE) { real_value_ = n; }
  264. explicit Value(const std::string &s) : type_(STRING_TYPE) {
  265. string_value_ = s;
  266. }
  267. explicit Value(std::string &&s)
  268. : type_(STRING_TYPE), string_value_(std::move(s)) {}
  269. explicit Value(const unsigned char *p, size_t n) : type_(BINARY_TYPE) {
  270. binary_value_.resize(n);
  271. memcpy(binary_value_.data(), p, n);
  272. }
  273. explicit Value(std::vector<unsigned char> &&v) noexcept
  274. : type_(BINARY_TYPE),
  275. binary_value_(std::move(v)) {}
  276. explicit Value(const Array &a) : type_(ARRAY_TYPE) { array_value_ = a; }
  277. explicit Value(Array &&a) noexcept : type_(ARRAY_TYPE),
  278. array_value_(std::move(a)) {}
  279. explicit Value(const Object &o) : type_(OBJECT_TYPE) { object_value_ = o; }
  280. explicit Value(Object &&o) noexcept : type_(OBJECT_TYPE),
  281. object_value_(std::move(o)) {}
  282. DEFAULT_METHODS(Value)
  283. char Type() const { return static_cast<char>(type_); }
  284. bool IsBool() const { return (type_ == BOOL_TYPE); }
  285. bool IsInt() const { return (type_ == INT_TYPE); }
  286. bool IsNumber() const { return (type_ == REAL_TYPE) || (type_ == INT_TYPE); }
  287. bool IsReal() const { return (type_ == REAL_TYPE); }
  288. bool IsString() const { return (type_ == STRING_TYPE); }
  289. bool IsBinary() const { return (type_ == BINARY_TYPE); }
  290. bool IsArray() const { return (type_ == ARRAY_TYPE); }
  291. bool IsObject() const { return (type_ == OBJECT_TYPE); }
  292. // Use this function if you want to have number value as double.
  293. double GetNumberAsDouble() const {
  294. if (type_ == INT_TYPE) {
  295. return double(int_value_);
  296. } else {
  297. return real_value_;
  298. }
  299. }
  300. // Use this function if you want to have number value as int.
  301. // TODO(syoyo): Support int value larger than 32 bits
  302. int GetNumberAsInt() const {
  303. if (type_ == REAL_TYPE) {
  304. return int(real_value_);
  305. } else {
  306. return int_value_;
  307. }
  308. }
  309. // Accessor
  310. template <typename T>
  311. const T &Get() const;
  312. template <typename T>
  313. T &Get();
  314. // Lookup value from an array
  315. const Value &Get(int idx) const {
  316. static Value null_value;
  317. assert(IsArray());
  318. assert(idx >= 0);
  319. return (static_cast<size_t>(idx) < array_value_.size())
  320. ? array_value_[static_cast<size_t>(idx)]
  321. : null_value;
  322. }
  323. // Lookup value from a key-value pair
  324. const Value &Get(const std::string &key) const {
  325. static Value null_value;
  326. assert(IsObject());
  327. Object::const_iterator it = object_value_.find(key);
  328. return (it != object_value_.end()) ? it->second : null_value;
  329. }
  330. size_t ArrayLen() const {
  331. if (!IsArray()) return 0;
  332. return array_value_.size();
  333. }
  334. // Valid only for object type.
  335. bool Has(const std::string &key) const {
  336. if (!IsObject()) return false;
  337. Object::const_iterator it = object_value_.find(key);
  338. return (it != object_value_.end()) ? true : false;
  339. }
  340. // List keys
  341. std::vector<std::string> Keys() const {
  342. std::vector<std::string> keys;
  343. if (!IsObject()) return keys; // empty
  344. for (Object::const_iterator it = object_value_.begin();
  345. it != object_value_.end(); ++it) {
  346. keys.push_back(it->first);
  347. }
  348. return keys;
  349. }
  350. size_t Size() const { return (IsArray() ? ArrayLen() : Keys().size()); }
  351. bool operator==(const tinygltf::Value &other) const;
  352. protected:
  353. int type_ = NULL_TYPE;
  354. int int_value_ = 0;
  355. double real_value_ = 0.0;
  356. std::string string_value_;
  357. std::vector<unsigned char> binary_value_;
  358. Array array_value_;
  359. Object object_value_;
  360. bool boolean_value_ = false;
  361. };
  362. #ifdef __clang__
  363. #pragma clang diagnostic pop
  364. #endif
  365. #define TINYGLTF_VALUE_GET(ctype, var) \
  366. template <> \
  367. inline const ctype &Value::Get<ctype>() const { \
  368. return var; \
  369. } \
  370. template <> \
  371. inline ctype &Value::Get<ctype>() { \
  372. return var; \
  373. }
  374. TINYGLTF_VALUE_GET(bool, boolean_value_)
  375. TINYGLTF_VALUE_GET(double, real_value_)
  376. TINYGLTF_VALUE_GET(int, int_value_)
  377. TINYGLTF_VALUE_GET(std::string, string_value_)
  378. TINYGLTF_VALUE_GET(std::vector<unsigned char>, binary_value_)
  379. TINYGLTF_VALUE_GET(Value::Array, array_value_)
  380. TINYGLTF_VALUE_GET(Value::Object, object_value_)
  381. #undef TINYGLTF_VALUE_GET
  382. #ifdef __clang__
  383. #pragma clang diagnostic push
  384. #pragma clang diagnostic ignored "-Wc++98-compat"
  385. #pragma clang diagnostic ignored "-Wpadded"
  386. #endif
  387. /// Aggregate object for representing a color
  388. using ColorValue = std::array<double, 4>;
  389. // === legacy interface ====
  390. // TODO(syoyo): Deprecate `Parameter` class.
  391. struct Parameter {
  392. bool bool_value = false;
  393. bool has_number_value = false;
  394. std::string string_value;
  395. std::vector<double> number_array;
  396. std::map<std::string, double> json_double_value;
  397. double number_value = 0.0;
  398. // context sensitive methods. depending the type of the Parameter you are
  399. // accessing, these are either valid or not
  400. // If this parameter represent a texture map in a material, will return the
  401. // texture index
  402. /// Return the index of a texture if this Parameter is a texture map.
  403. /// Returned value is only valid if the parameter represent a texture from a
  404. /// material
  405. int TextureIndex() const {
  406. const auto it = json_double_value.find("index");
  407. if (it != std::end(json_double_value)) {
  408. return int(it->second);
  409. }
  410. return -1;
  411. }
  412. /// Return the index of a texture coordinate set if this Parameter is a
  413. /// texture map. Returned value is only valid if the parameter represent a
  414. /// texture from a material
  415. int TextureTexCoord() const {
  416. const auto it = json_double_value.find("texCoord");
  417. if (it != std::end(json_double_value)) {
  418. return int(it->second);
  419. }
  420. // As per the spec, if texCoord is omitted, this parameter is 0
  421. return 0;
  422. }
  423. /// Return the scale of a texture if this Parameter is a normal texture map.
  424. /// Returned value is only valid if the parameter represent a normal texture
  425. /// from a material
  426. double TextureScale() const {
  427. const auto it = json_double_value.find("scale");
  428. if (it != std::end(json_double_value)) {
  429. return it->second;
  430. }
  431. // As per the spec, if scale is omitted, this parameter is 1
  432. return 1;
  433. }
  434. /// Return the strength of a texture if this Parameter is a an occlusion map.
  435. /// Returned value is only valid if the parameter represent an occlusion map
  436. /// from a material
  437. double TextureStrength() const {
  438. const auto it = json_double_value.find("strength");
  439. if (it != std::end(json_double_value)) {
  440. return it->second;
  441. }
  442. // As per the spec, if strength is omitted, this parameter is 1
  443. return 1;
  444. }
  445. /// Material factor, like the roughness or metalness of a material
  446. /// Returned value is only valid if the parameter represent a texture from a
  447. /// material
  448. double Factor() const { return number_value; }
  449. /// Return the color of a material
  450. /// Returned value is only valid if the parameter represent a texture from a
  451. /// material
  452. ColorValue ColorFactor() const {
  453. return {
  454. {// this aggregate initialize the std::array object, and uses C++11 RVO.
  455. number_array[0], number_array[1], number_array[2],
  456. (number_array.size() > 3 ? number_array[3] : 1.0)}};
  457. }
  458. Parameter() = default;
  459. DEFAULT_METHODS(Parameter)
  460. bool operator==(const Parameter &) const;
  461. };
  462. #ifdef __clang__
  463. #pragma clang diagnostic pop
  464. #endif
  465. #ifdef __clang__
  466. #pragma clang diagnostic push
  467. #pragma clang diagnostic ignored "-Wpadded"
  468. #endif
  469. typedef std::map<std::string, Parameter> ParameterMap;
  470. typedef std::map<std::string, Value> ExtensionMap;
  471. struct AnimationChannel {
  472. int sampler; // required
  473. int target_node; // optional index of the node to target (alternative
  474. // target should be provided by extension)
  475. std::string target_path; // required with standard values of ["translation",
  476. // "rotation", "scale", "weights"]
  477. Value extras;
  478. ExtensionMap extensions;
  479. ExtensionMap target_extensions;
  480. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  481. std::string extras_json_string;
  482. std::string extensions_json_string;
  483. std::string target_extensions_json_string;
  484. AnimationChannel() : sampler(-1), target_node(-1) {}
  485. DEFAULT_METHODS(AnimationChannel)
  486. bool operator==(const AnimationChannel &) const;
  487. };
  488. struct AnimationSampler {
  489. int input; // required
  490. int output; // required
  491. std::string interpolation; // "LINEAR", "STEP","CUBICSPLINE" or user defined
  492. // string. default "LINEAR"
  493. Value extras;
  494. ExtensionMap extensions;
  495. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  496. std::string extras_json_string;
  497. std::string extensions_json_string;
  498. AnimationSampler() : input(-1), output(-1), interpolation("LINEAR") {}
  499. DEFAULT_METHODS(AnimationSampler)
  500. bool operator==(const AnimationSampler &) const;
  501. };
  502. struct Animation {
  503. std::string name;
  504. std::vector<AnimationChannel> channels;
  505. std::vector<AnimationSampler> samplers;
  506. Value extras;
  507. ExtensionMap extensions;
  508. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  509. std::string extras_json_string;
  510. std::string extensions_json_string;
  511. Animation() = default;
  512. DEFAULT_METHODS(Animation)
  513. bool operator==(const Animation &) const;
  514. };
  515. struct Skin {
  516. std::string name;
  517. int inverseBindMatrices; // required here but not in the spec
  518. int skeleton; // The index of the node used as a skeleton root
  519. std::vector<int> joints; // Indices of skeleton nodes
  520. Value extras;
  521. ExtensionMap extensions;
  522. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  523. std::string extras_json_string;
  524. std::string extensions_json_string;
  525. Skin() {
  526. inverseBindMatrices = -1;
  527. skeleton = -1;
  528. }
  529. DEFAULT_METHODS(Skin)
  530. bool operator==(const Skin &) const;
  531. };
  532. struct Sampler {
  533. std::string name;
  534. // glTF 2.0 spec does not define default value for `minFilter` and
  535. // `magFilter`. Set -1 in TinyGLTF(issue #186)
  536. int minFilter =
  537. -1; // optional. -1 = no filter defined. ["NEAREST", "LINEAR",
  538. // "NEAREST_MIPMAP_NEAREST", "LINEAR_MIPMAP_NEAREST",
  539. // "NEAREST_MIPMAP_LINEAR", "LINEAR_MIPMAP_LINEAR"]
  540. int magFilter =
  541. -1; // optional. -1 = no filter defined. ["NEAREST", "LINEAR"]
  542. int wrapS =
  543. TINYGLTF_TEXTURE_WRAP_REPEAT; // ["CLAMP_TO_EDGE", "MIRRORED_REPEAT",
  544. // "REPEAT"], default "REPEAT"
  545. int wrapT =
  546. TINYGLTF_TEXTURE_WRAP_REPEAT; // ["CLAMP_TO_EDGE", "MIRRORED_REPEAT",
  547. // "REPEAT"], default "REPEAT"
  548. // int wrapR = TINYGLTF_TEXTURE_WRAP_REPEAT; // TinyGLTF extension. currently
  549. // not used.
  550. Value extras;
  551. ExtensionMap extensions;
  552. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  553. std::string extras_json_string;
  554. std::string extensions_json_string;
  555. Sampler()
  556. : minFilter(-1),
  557. magFilter(-1),
  558. wrapS(TINYGLTF_TEXTURE_WRAP_REPEAT),
  559. wrapT(TINYGLTF_TEXTURE_WRAP_REPEAT) {}
  560. DEFAULT_METHODS(Sampler)
  561. bool operator==(const Sampler &) const;
  562. };
  563. struct Image {
  564. std::string name;
  565. int width;
  566. int height;
  567. int component;
  568. int bits; // bit depth per channel. 8(byte), 16 or 32.
  569. int pixel_type; // pixel type(TINYGLTF_COMPONENT_TYPE_***). usually
  570. // UBYTE(bits = 8) or USHORT(bits = 16)
  571. std::vector<unsigned char> image;
  572. int bufferView; // (required if no uri)
  573. std::string mimeType; // (required if no uri) ["image/jpeg", "image/png",
  574. // "image/bmp", "image/gif"]
  575. std::string uri; // (required if no mimeType) uri is not decoded(e.g.
  576. // whitespace may be represented as %20)
  577. Value extras;
  578. ExtensionMap extensions;
  579. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  580. std::string extras_json_string;
  581. std::string extensions_json_string;
  582. // When this flag is true, data is stored to `image` in as-is format(e.g. jpeg
  583. // compressed for "image/jpeg" mime) This feature is good if you use custom
  584. // image loader function. (e.g. delayed decoding of images for faster glTF
  585. // parsing) Default parser for Image does not provide as-is loading feature at
  586. // the moment. (You can manipulate this by providing your own LoadImageData
  587. // function)
  588. bool as_is;
  589. Image() : as_is(false) {
  590. bufferView = -1;
  591. width = -1;
  592. height = -1;
  593. component = -1;
  594. bits = -1;
  595. pixel_type = -1;
  596. }
  597. DEFAULT_METHODS(Image)
  598. bool operator==(const Image &) const;
  599. };
  600. struct Texture {
  601. std::string name;
  602. int sampler;
  603. int source;
  604. Value extras;
  605. ExtensionMap extensions;
  606. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  607. std::string extras_json_string;
  608. std::string extensions_json_string;
  609. Texture() : sampler(-1), source(-1) {}
  610. DEFAULT_METHODS(Texture)
  611. bool operator==(const Texture &) const;
  612. };
  613. struct TextureInfo {
  614. int index = -1; // required.
  615. int texCoord; // The set index of texture's TEXCOORD attribute used for
  616. // texture coordinate mapping.
  617. Value extras;
  618. ExtensionMap extensions;
  619. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  620. std::string extras_json_string;
  621. std::string extensions_json_string;
  622. TextureInfo() : index(-1), texCoord(0) {}
  623. DEFAULT_METHODS(TextureInfo)
  624. bool operator==(const TextureInfo &) const;
  625. };
  626. struct NormalTextureInfo {
  627. int index = -1; // required
  628. int texCoord; // The set index of texture's TEXCOORD attribute used for
  629. // texture coordinate mapping.
  630. double scale; // scaledNormal = normalize((<sampled normal texture value>
  631. // * 2.0 - 1.0) * vec3(<normal scale>, <normal scale>, 1.0))
  632. Value extras;
  633. ExtensionMap extensions;
  634. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  635. std::string extras_json_string;
  636. std::string extensions_json_string;
  637. NormalTextureInfo() : index(-1), texCoord(0), scale(1.0) {}
  638. DEFAULT_METHODS(NormalTextureInfo)
  639. bool operator==(const NormalTextureInfo &) const;
  640. };
  641. struct OcclusionTextureInfo {
  642. int index = -1; // required
  643. int texCoord; // The set index of texture's TEXCOORD attribute used for
  644. // texture coordinate mapping.
  645. double strength; // occludedColor = lerp(color, color * <sampled occlusion
  646. // texture value>, <occlusion strength>)
  647. Value extras;
  648. ExtensionMap extensions;
  649. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  650. std::string extras_json_string;
  651. std::string extensions_json_string;
  652. OcclusionTextureInfo() : index(-1), texCoord(0), strength(1.0) {}
  653. DEFAULT_METHODS(OcclusionTextureInfo)
  654. bool operator==(const OcclusionTextureInfo &) const;
  655. };
  656. // pbrMetallicRoughness class defined in glTF 2.0 spec.
  657. struct PbrMetallicRoughness {
  658. std::vector<double> baseColorFactor; // len = 4. default [1,1,1,1]
  659. TextureInfo baseColorTexture;
  660. double metallicFactor; // default 1
  661. double roughnessFactor; // default 1
  662. TextureInfo metallicRoughnessTexture;
  663. Value extras;
  664. ExtensionMap extensions;
  665. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  666. std::string extras_json_string;
  667. std::string extensions_json_string;
  668. PbrMetallicRoughness()
  669. : baseColorFactor(std::vector<double>{1.0, 1.0, 1.0, 1.0}),
  670. metallicFactor(1.0),
  671. roughnessFactor(1.0) {}
  672. DEFAULT_METHODS(PbrMetallicRoughness)
  673. bool operator==(const PbrMetallicRoughness &) const;
  674. };
  675. // Each extension should be stored in a ParameterMap.
  676. // members not in the values could be included in the ParameterMap
  677. // to keep a single material model
  678. struct Material {
  679. std::string name;
  680. std::vector<double> emissiveFactor; // length 3. default [0, 0, 0]
  681. std::string alphaMode; // default "OPAQUE"
  682. double alphaCutoff; // default 0.5
  683. bool doubleSided; // default false;
  684. PbrMetallicRoughness pbrMetallicRoughness;
  685. NormalTextureInfo normalTexture;
  686. OcclusionTextureInfo occlusionTexture;
  687. TextureInfo emissiveTexture;
  688. // For backward compatibility
  689. // TODO(syoyo): Remove `values` and `additionalValues` in the next release.
  690. ParameterMap values;
  691. ParameterMap additionalValues;
  692. ExtensionMap extensions;
  693. Value extras;
  694. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  695. std::string extras_json_string;
  696. std::string extensions_json_string;
  697. Material() : alphaMode("OPAQUE"), alphaCutoff(0.5), doubleSided(false) {}
  698. DEFAULT_METHODS(Material)
  699. bool operator==(const Material &) const;
  700. };
  701. struct BufferView {
  702. std::string name;
  703. int buffer{-1}; // Required
  704. size_t byteOffset{0}; // minimum 0, default 0
  705. size_t byteLength{0}; // required, minimum 1. 0 = invalid
  706. size_t byteStride{0}; // minimum 4, maximum 252 (multiple of 4), default 0 =
  707. // understood to be tightly packed
  708. int target{0}; // ["ARRAY_BUFFER", "ELEMENT_ARRAY_BUFFER"] for vertex indices
  709. // or attribs. Could be 0 for other data
  710. Value extras;
  711. ExtensionMap extensions;
  712. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  713. std::string extras_json_string;
  714. std::string extensions_json_string;
  715. bool dracoDecoded{false}; // Flag indicating this has been draco decoded
  716. BufferView()
  717. : buffer(-1),
  718. byteOffset(0),
  719. byteLength(0),
  720. byteStride(0),
  721. target(0),
  722. dracoDecoded(false) {}
  723. DEFAULT_METHODS(BufferView)
  724. bool operator==(const BufferView &) const;
  725. };
  726. struct Accessor {
  727. int bufferView; // optional in spec but required here since sparse accessor
  728. // are not supported
  729. std::string name;
  730. size_t byteOffset;
  731. bool normalized; // optional.
  732. int componentType; // (required) One of TINYGLTF_COMPONENT_TYPE_***
  733. size_t count; // required
  734. int type; // (required) One of TINYGLTF_TYPE_*** ..
  735. Value extras;
  736. ExtensionMap extensions;
  737. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  738. std::string extras_json_string;
  739. std::string extensions_json_string;
  740. std::vector<double>
  741. minValues; // optional. integer value is promoted to double
  742. std::vector<double>
  743. maxValues; // optional. integer value is promoted to double
  744. struct {
  745. int count;
  746. bool isSparse;
  747. struct {
  748. int byteOffset;
  749. int bufferView;
  750. int componentType; // a TINYGLTF_COMPONENT_TYPE_ value
  751. } indices;
  752. struct {
  753. int bufferView;
  754. int byteOffset;
  755. } values;
  756. } sparse;
  757. ///
  758. /// Utility function to compute byteStride for a given bufferView object.
  759. /// Returns -1 upon invalid glTF value or parameter configuration.
  760. ///
  761. int ByteStride(const BufferView &bufferViewObject) const {
  762. if (bufferViewObject.byteStride == 0) {
  763. // Assume data is tightly packed.
  764. int componentSizeInBytes =
  765. GetComponentSizeInBytes(static_cast<uint32_t>(componentType));
  766. if (componentSizeInBytes <= 0) {
  767. return -1;
  768. }
  769. int numComponents = GetNumComponentsInType(static_cast<uint32_t>(type));
  770. if (numComponents <= 0) {
  771. return -1;
  772. }
  773. return componentSizeInBytes * numComponents;
  774. } else {
  775. // Check if byteStride is a multiple of the size of the accessor's component
  776. // type.
  777. int componentSizeInBytes =
  778. GetComponentSizeInBytes(static_cast<uint32_t>(componentType));
  779. if (componentSizeInBytes <= 0) {
  780. return -1;
  781. }
  782. if ((bufferViewObject.byteStride % uint32_t(componentSizeInBytes)) != 0) {
  783. return -1;
  784. }
  785. return static_cast<int>(bufferViewObject.byteStride);
  786. }
  787. // unreachable return 0;
  788. }
  789. Accessor()
  790. : bufferView(-1),
  791. byteOffset(0),
  792. normalized(false),
  793. componentType(-1),
  794. count(0),
  795. type(-1) {
  796. sparse.isSparse = false;
  797. }
  798. DEFAULT_METHODS(Accessor)
  799. bool operator==(const tinygltf::Accessor &) const;
  800. };
  801. struct PerspectiveCamera {
  802. double aspectRatio; // min > 0
  803. double yfov; // required. min > 0
  804. double zfar; // min > 0
  805. double znear; // required. min > 0
  806. PerspectiveCamera()
  807. : aspectRatio(0.0),
  808. yfov(0.0),
  809. zfar(0.0) // 0 = use infinite projection matrix
  810. ,
  811. znear(0.0) {}
  812. DEFAULT_METHODS(PerspectiveCamera)
  813. bool operator==(const PerspectiveCamera &) const;
  814. ExtensionMap extensions;
  815. Value extras;
  816. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  817. std::string extras_json_string;
  818. std::string extensions_json_string;
  819. };
  820. struct OrthographicCamera {
  821. double xmag; // required. must not be zero.
  822. double ymag; // required. must not be zero.
  823. double zfar; // required. `zfar` must be greater than `znear`.
  824. double znear; // required
  825. OrthographicCamera() : xmag(0.0), ymag(0.0), zfar(0.0), znear(0.0) {}
  826. DEFAULT_METHODS(OrthographicCamera)
  827. bool operator==(const OrthographicCamera &) const;
  828. ExtensionMap extensions;
  829. Value extras;
  830. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  831. std::string extras_json_string;
  832. std::string extensions_json_string;
  833. };
  834. struct Camera {
  835. std::string type; // required. "perspective" or "orthographic"
  836. std::string name;
  837. PerspectiveCamera perspective;
  838. OrthographicCamera orthographic;
  839. Camera() {}
  840. DEFAULT_METHODS(Camera)
  841. bool operator==(const Camera &) const;
  842. ExtensionMap extensions;
  843. Value extras;
  844. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  845. std::string extras_json_string;
  846. std::string extensions_json_string;
  847. };
  848. struct Primitive {
  849. std::map<std::string, int> attributes; // (required) A dictionary object of
  850. // integer, where each integer
  851. // is the index of the accessor
  852. // containing an attribute.
  853. int material; // The index of the material to apply to this primitive
  854. // when rendering.
  855. int indices; // The index of the accessor that contains the indices.
  856. int mode; // one of TINYGLTF_MODE_***
  857. std::vector<std::map<std::string, int> > targets; // array of morph targets,
  858. // where each target is a dict with attributes in ["POSITION, "NORMAL",
  859. // "TANGENT"] pointing
  860. // to their corresponding accessors
  861. ExtensionMap extensions;
  862. Value extras;
  863. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  864. std::string extras_json_string;
  865. std::string extensions_json_string;
  866. Primitive() {
  867. material = -1;
  868. indices = -1;
  869. mode = -1;
  870. }
  871. DEFAULT_METHODS(Primitive)
  872. bool operator==(const Primitive &) const;
  873. };
  874. struct Mesh {
  875. std::string name;
  876. std::vector<Primitive> primitives;
  877. std::vector<double> weights; // weights to be applied to the Morph Targets
  878. ExtensionMap extensions;
  879. Value extras;
  880. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  881. std::string extras_json_string;
  882. std::string extensions_json_string;
  883. Mesh() = default;
  884. DEFAULT_METHODS(Mesh)
  885. bool operator==(const Mesh &) const;
  886. };
  887. class Node {
  888. public:
  889. Node() : camera(-1), skin(-1), mesh(-1) {}
  890. DEFAULT_METHODS(Node)
  891. bool operator==(const Node &) const;
  892. int camera; // the index of the camera referenced by this node
  893. std::string name;
  894. int skin;
  895. int mesh;
  896. std::vector<int> children;
  897. std::vector<double> rotation; // length must be 0 or 4
  898. std::vector<double> scale; // length must be 0 or 3
  899. std::vector<double> translation; // length must be 0 or 3
  900. std::vector<double> matrix; // length must be 0 or 16
  901. std::vector<double> weights; // The weights of the instantiated Morph Target
  902. ExtensionMap extensions;
  903. Value extras;
  904. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  905. std::string extras_json_string;
  906. std::string extensions_json_string;
  907. };
  908. struct Buffer {
  909. std::string name;
  910. std::vector<unsigned char> data;
  911. std::string
  912. uri; // considered as required here but not in the spec (need to clarify)
  913. // uri is not decoded(e.g. whitespace may be represented as %20)
  914. Value extras;
  915. ExtensionMap extensions;
  916. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  917. std::string extras_json_string;
  918. std::string extensions_json_string;
  919. Buffer() = default;
  920. DEFAULT_METHODS(Buffer)
  921. bool operator==(const Buffer &) const;
  922. };
  923. struct Asset {
  924. std::string version = "2.0"; // required
  925. std::string generator;
  926. std::string minVersion;
  927. std::string copyright;
  928. ExtensionMap extensions;
  929. Value extras;
  930. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  931. std::string extras_json_string;
  932. std::string extensions_json_string;
  933. Asset() = default;
  934. DEFAULT_METHODS(Asset)
  935. bool operator==(const Asset &) const;
  936. };
  937. struct Scene {
  938. std::string name;
  939. std::vector<int> nodes;
  940. ExtensionMap extensions;
  941. Value extras;
  942. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  943. std::string extras_json_string;
  944. std::string extensions_json_string;
  945. Scene() = default;
  946. DEFAULT_METHODS(Scene)
  947. bool operator==(const Scene &) const;
  948. };
  949. struct SpotLight {
  950. double innerConeAngle;
  951. double outerConeAngle;
  952. SpotLight() : innerConeAngle(0.0), outerConeAngle(0.7853981634) {}
  953. DEFAULT_METHODS(SpotLight)
  954. bool operator==(const SpotLight &) const;
  955. ExtensionMap extensions;
  956. Value extras;
  957. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  958. std::string extras_json_string;
  959. std::string extensions_json_string;
  960. };
  961. struct Light {
  962. std::string name;
  963. std::vector<double> color;
  964. double intensity{1.0};
  965. std::string type;
  966. double range{0.0}; // 0.0 = infinite
  967. SpotLight spot;
  968. Light() : intensity(1.0), range(0.0) {}
  969. DEFAULT_METHODS(Light)
  970. bool operator==(const Light &) const;
  971. ExtensionMap extensions;
  972. Value extras;
  973. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  974. std::string extras_json_string;
  975. std::string extensions_json_string;
  976. };
  977. class Model {
  978. public:
  979. Model() = default;
  980. DEFAULT_METHODS(Model)
  981. bool operator==(const Model &) const;
  982. std::vector<Accessor> accessors;
  983. std::vector<Animation> animations;
  984. std::vector<Buffer> buffers;
  985. std::vector<BufferView> bufferViews;
  986. std::vector<Material> materials;
  987. std::vector<Mesh> meshes;
  988. std::vector<Node> nodes;
  989. std::vector<Texture> textures;
  990. std::vector<Image> images;
  991. std::vector<Skin> skins;
  992. std::vector<Sampler> samplers;
  993. std::vector<Camera> cameras;
  994. std::vector<Scene> scenes;
  995. std::vector<Light> lights;
  996. int defaultScene = -1;
  997. std::vector<std::string> extensionsUsed;
  998. std::vector<std::string> extensionsRequired;
  999. Asset asset;
  1000. Value extras;
  1001. ExtensionMap extensions;
  1002. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  1003. std::string extras_json_string;
  1004. std::string extensions_json_string;
  1005. };
  1006. enum SectionCheck {
  1007. NO_REQUIRE = 0x00,
  1008. REQUIRE_VERSION = 0x01,
  1009. REQUIRE_SCENE = 0x02,
  1010. REQUIRE_SCENES = 0x04,
  1011. REQUIRE_NODES = 0x08,
  1012. REQUIRE_ACCESSORS = 0x10,
  1013. REQUIRE_BUFFERS = 0x20,
  1014. REQUIRE_BUFFER_VIEWS = 0x40,
  1015. REQUIRE_ALL = 0x7f
  1016. };
  1017. ///
  1018. /// URIEncodeFunction type. Signature for custom URI encoding of external
  1019. /// resources such as .bin and image files. Used by tinygltf to re-encode the
  1020. /// final location of saved files. object_type may be used to encode buffer and
  1021. /// image URIs differently, for example. See
  1022. /// https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#uris
  1023. ///
  1024. typedef bool (*URIEncodeFunction)(const std::string &in_uri,
  1025. const std::string &object_type,
  1026. std::string *out_uri, void *user_data);
  1027. ///
  1028. /// URIDecodeFunction type. Signature for custom URI decoding of external
  1029. /// resources such as .bin and image files. Used by tinygltf when computing
  1030. /// filenames to write resources.
  1031. ///
  1032. typedef bool (*URIDecodeFunction)(const std::string &in_uri,
  1033. std::string *out_uri, void *user_data);
  1034. // Declaration of default uri decode function
  1035. bool URIDecode(const std::string &in_uri, std::string *out_uri,
  1036. void *user_data);
  1037. ///
  1038. /// A structure containing URI callbacks and a pointer to their user data.
  1039. ///
  1040. struct URICallbacks {
  1041. URIEncodeFunction encode; // Optional encode method
  1042. URIDecodeFunction decode; // Required decode method
  1043. void *user_data; // An argument that is passed to all uri callbacks
  1044. };
  1045. ///
  1046. /// LoadImageDataFunction type. Signature for custom image loading callbacks.
  1047. ///
  1048. typedef bool (*LoadImageDataFunction)(Image *, const int, std::string *,
  1049. std::string *, int, int,
  1050. const unsigned char *, int,
  1051. void *user_pointer);
  1052. ///
  1053. /// WriteImageDataFunction type. Signature for custom image writing callbacks.
  1054. /// The out_uri parameter becomes the URI written to the gltf and may reference
  1055. /// a file or contain a data URI.
  1056. ///
  1057. typedef bool (*WriteImageDataFunction)(const std::string *basepath,
  1058. const std::string *filename,
  1059. const Image *image, bool embedImages,
  1060. const URICallbacks *uri_cb,
  1061. std::string *out_uri,
  1062. void *user_pointer);
  1063. #ifndef TINYGLTF_NO_STB_IMAGE
  1064. // Declaration of default image loader callback
  1065. bool LoadImageData(Image *image, const int image_idx, std::string *err,
  1066. std::string *warn, int req_width, int req_height,
  1067. const unsigned char *bytes, int size, void *);
  1068. #endif
  1069. #ifndef TINYGLTF_NO_STB_IMAGE_WRITE
  1070. // Declaration of default image writer callback
  1071. bool WriteImageData(const std::string *basepath, const std::string *filename,
  1072. const Image *image, bool embedImages,
  1073. const URICallbacks *uri_cb, std::string *out_uri, void *);
  1074. #endif
  1075. ///
  1076. /// FilExistsFunction type. Signature for custom filesystem callbacks.
  1077. ///
  1078. typedef bool (*FileExistsFunction)(const std::string &abs_filename, void *);
  1079. ///
  1080. /// ExpandFilePathFunction type. Signature for custom filesystem callbacks.
  1081. ///
  1082. typedef std::string (*ExpandFilePathFunction)(const std::string &, void *);
  1083. ///
  1084. /// ReadWholeFileFunction type. Signature for custom filesystem callbacks.
  1085. ///
  1086. typedef bool (*ReadWholeFileFunction)(std::vector<unsigned char> *,
  1087. std::string *, const std::string &,
  1088. void *);
  1089. ///
  1090. /// WriteWholeFileFunction type. Signature for custom filesystem callbacks.
  1091. ///
  1092. typedef bool (*WriteWholeFileFunction)(std::string *, const std::string &,
  1093. const std::vector<unsigned char> &,
  1094. void *);
  1095. ///
  1096. /// A structure containing all required filesystem callbacks and a pointer to
  1097. /// their user data.
  1098. ///
  1099. struct FsCallbacks {
  1100. FileExistsFunction FileExists;
  1101. ExpandFilePathFunction ExpandFilePath;
  1102. ReadWholeFileFunction ReadWholeFile;
  1103. WriteWholeFileFunction WriteWholeFile;
  1104. void *user_data; // An argument that is passed to all fs callbacks
  1105. };
  1106. #ifndef TINYGLTF_NO_FS
  1107. // Declaration of default filesystem callbacks
  1108. bool FileExists(const std::string &abs_filename, void *);
  1109. ///
  1110. /// Expand file path(e.g. `~` to home directory on posix, `%APPDATA%` to
  1111. /// `C:\\Users\\tinygltf\\AppData`)
  1112. ///
  1113. /// @param[in] filepath File path string. Assume UTF-8
  1114. /// @param[in] userdata User data. Set to `nullptr` if you don't need it.
  1115. ///
  1116. std::string ExpandFilePath(const std::string &filepath, void *userdata);
  1117. bool ReadWholeFile(std::vector<unsigned char> *out, std::string *err,
  1118. const std::string &filepath, void *);
  1119. bool WriteWholeFile(std::string *err, const std::string &filepath,
  1120. const std::vector<unsigned char> &contents, void *);
  1121. #endif
  1122. ///
  1123. /// glTF Parser/Serializer context.
  1124. ///
  1125. class TinyGLTF {
  1126. public:
  1127. #ifdef __clang__
  1128. #pragma clang diagnostic push
  1129. #pragma clang diagnostic ignored "-Wc++98-compat"
  1130. #endif
  1131. TinyGLTF() : bin_data_(nullptr), bin_size_(0), is_binary_(false) {}
  1132. #ifdef __clang__
  1133. #pragma clang diagnostic pop
  1134. #endif
  1135. ~TinyGLTF() {}
  1136. ///
  1137. /// Loads glTF ASCII asset from a file.
  1138. /// Set warning message to `warn` for example it fails to load asserts.
  1139. /// Returns false and set error string to `err` if there's an error.
  1140. ///
  1141. bool LoadASCIIFromFile(Model *model, std::string *err, std::string *warn,
  1142. const std::string &filename,
  1143. unsigned int check_sections = REQUIRE_VERSION);
  1144. ///
  1145. /// Loads glTF ASCII asset from string(memory).
  1146. /// `length` = strlen(str);
  1147. /// `base_dir` is a search path of glTF asset(e.g. images). Path Must be an
  1148. /// expanded path (e.g. no tilde(`~`), no environment variables). Set warning
  1149. /// message to `warn` for example it fails to load asserts. Returns false and
  1150. /// set error string to `err` if there's an error.
  1151. ///
  1152. bool LoadASCIIFromString(Model *model, std::string *err, std::string *warn,
  1153. const char *str, const unsigned int length,
  1154. const std::string &base_dir,
  1155. unsigned int check_sections = REQUIRE_VERSION);
  1156. ///
  1157. /// Loads glTF binary asset from a file.
  1158. /// Set warning message to `warn` for example it fails to load asserts.
  1159. /// Returns false and set error string to `err` if there's an error.
  1160. ///
  1161. bool LoadBinaryFromFile(Model *model, std::string *err, std::string *warn,
  1162. const std::string &filename,
  1163. unsigned int check_sections = REQUIRE_VERSION);
  1164. ///
  1165. /// Loads glTF binary asset from memory.
  1166. /// `length` = strlen(str);
  1167. /// `base_dir` is a search path of glTF asset(e.g. images). Path Must be an
  1168. /// expanded path (e.g. no tilde(`~`), no environment variables).
  1169. /// Set warning message to `warn` for example it fails to load asserts.
  1170. /// Returns false and set error string to `err` if there's an error.
  1171. ///
  1172. bool LoadBinaryFromMemory(Model *model, std::string *err, std::string *warn,
  1173. const unsigned char *bytes,
  1174. const unsigned int length,
  1175. const std::string &base_dir = "",
  1176. unsigned int check_sections = REQUIRE_VERSION);
  1177. ///
  1178. /// Write glTF to stream, buffers and images will be embedded
  1179. ///
  1180. bool WriteGltfSceneToStream(const Model *model, std::ostream &stream,
  1181. bool prettyPrint, bool writeBinary);
  1182. ///
  1183. /// Write glTF to file.
  1184. ///
  1185. bool WriteGltfSceneToFile(const Model *model, const std::string &filename,
  1186. bool embedImages, bool embedBuffers,
  1187. bool prettyPrint, bool writeBinary);
  1188. ///
  1189. /// Set callback to use for loading image data
  1190. ///
  1191. void SetImageLoader(LoadImageDataFunction LoadImageData, void *user_data);
  1192. ///
  1193. /// Unset(remove) callback of loading image data
  1194. ///
  1195. void RemoveImageLoader();
  1196. ///
  1197. /// Set callback to use for writing image data
  1198. ///
  1199. void SetImageWriter(WriteImageDataFunction WriteImageData, void *user_data);
  1200. ///
  1201. /// Set callbacks to use for URI encoding and decoding and their user data
  1202. ///
  1203. void SetURICallbacks(URICallbacks callbacks);
  1204. ///
  1205. /// Set callbacks to use for filesystem (fs) access and their user data
  1206. ///
  1207. void SetFsCallbacks(FsCallbacks callbacks);
  1208. ///
  1209. /// Set serializing default values(default = false).
  1210. /// When true, default values are force serialized to .glTF.
  1211. /// This may be helpful if you want to serialize a full description of glTF
  1212. /// data.
  1213. ///
  1214. /// TODO(LTE): Supply parsing option as function arguments to
  1215. /// `LoadASCIIFromFile()` and others, not by a class method
  1216. ///
  1217. void SetSerializeDefaultValues(const bool enabled) {
  1218. serialize_default_values_ = enabled;
  1219. }
  1220. bool GetSerializeDefaultValues() const { return serialize_default_values_; }
  1221. ///
  1222. /// Store original JSON string for `extras` and `extensions`.
  1223. /// This feature will be useful when the user want to reconstruct custom data
  1224. /// structure from JSON string.
  1225. ///
  1226. void SetStoreOriginalJSONForExtrasAndExtensions(const bool enabled) {
  1227. store_original_json_for_extras_and_extensions_ = enabled;
  1228. }
  1229. bool GetStoreOriginalJSONForExtrasAndExtensions() const {
  1230. return store_original_json_for_extras_and_extensions_;
  1231. }
  1232. ///
  1233. /// Specify whether preserve image channels when loading images or not.
  1234. /// (Not effective when the user supplies their own LoadImageData callbacks)
  1235. ///
  1236. void SetPreserveImageChannels(bool onoff) {
  1237. preserve_image_channels_ = onoff;
  1238. }
  1239. bool GetPreserveImageChannels() const { return preserve_image_channels_; }
  1240. private:
  1241. ///
  1242. /// Loads glTF asset from string(memory).
  1243. /// `length` = strlen(str);
  1244. /// Set warning message to `warn` for example it fails to load asserts
  1245. /// Returns false and set error string to `err` if there's an error.
  1246. ///
  1247. bool LoadFromString(Model *model, std::string *err, std::string *warn,
  1248. const char *str, const unsigned int length,
  1249. const std::string &base_dir, unsigned int check_sections);
  1250. const unsigned char *bin_data_ = nullptr;
  1251. size_t bin_size_ = 0;
  1252. bool is_binary_ = false;
  1253. bool serialize_default_values_ = false; ///< Serialize default values?
  1254. bool store_original_json_for_extras_and_extensions_ = false;
  1255. bool preserve_image_channels_ = false; /// Default false(expand channels to
  1256. /// RGBA) for backward compatibility.
  1257. // Warning & error messages
  1258. std::string warn_;
  1259. std::string err_;
  1260. FsCallbacks fs = {
  1261. #ifndef TINYGLTF_NO_FS
  1262. &tinygltf::FileExists, &tinygltf::ExpandFilePath,
  1263. &tinygltf::ReadWholeFile, &tinygltf::WriteWholeFile,
  1264. nullptr // Fs callback user data
  1265. #else
  1266. nullptr, nullptr, nullptr, nullptr,
  1267. nullptr // Fs callback user data
  1268. #endif
  1269. };
  1270. URICallbacks uri_cb = {
  1271. // Use paths as-is by default. This will use JSON string escaping.
  1272. nullptr,
  1273. // Decode all URIs before using them as paths as the application may have
  1274. // percent encoded them.
  1275. &tinygltf::URIDecode,
  1276. // URI callback user data
  1277. nullptr};
  1278. LoadImageDataFunction LoadImageData =
  1279. #ifndef TINYGLTF_NO_STB_IMAGE
  1280. &tinygltf::LoadImageData;
  1281. #else
  1282. nullptr;
  1283. #endif
  1284. void *load_image_user_data_{nullptr};
  1285. bool user_image_loader_{false};
  1286. WriteImageDataFunction WriteImageData =
  1287. #ifndef TINYGLTF_NO_STB_IMAGE_WRITE
  1288. &tinygltf::WriteImageData;
  1289. #else
  1290. nullptr;
  1291. #endif
  1292. void *write_image_user_data_{nullptr};
  1293. };
  1294. #ifdef __clang__
  1295. #pragma clang diagnostic pop // -Wpadded
  1296. #endif
  1297. } // namespace tinygltf
  1298. #endif // TINY_GLTF_H_
  1299. #if defined(TINYGLTF_IMPLEMENTATION) || defined(__INTELLISENSE__)
  1300. #include <algorithm>
  1301. //#include <cassert>
  1302. #ifndef TINYGLTF_NO_FS
  1303. #include <cstdio>
  1304. #include <fstream>
  1305. #endif
  1306. #include <sstream>
  1307. #ifdef __clang__
  1308. // Disable some warnings for external files.
  1309. #pragma clang diagnostic push
  1310. #pragma clang diagnostic ignored "-Wfloat-equal"
  1311. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  1312. #pragma clang diagnostic ignored "-Wconversion"
  1313. #pragma clang diagnostic ignored "-Wold-style-cast"
  1314. #pragma clang diagnostic ignored "-Wglobal-constructors"
  1315. #if __has_warning("-Wreserved-id-macro")
  1316. #pragma clang diagnostic ignored "-Wreserved-id-macro"
  1317. #endif
  1318. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  1319. #pragma clang diagnostic ignored "-Wpadded"
  1320. #pragma clang diagnostic ignored "-Wc++98-compat"
  1321. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  1322. #pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
  1323. #pragma clang diagnostic ignored "-Wswitch-enum"
  1324. #pragma clang diagnostic ignored "-Wimplicit-fallthrough"
  1325. #pragma clang diagnostic ignored "-Wweak-vtables"
  1326. #pragma clang diagnostic ignored "-Wcovered-switch-default"
  1327. #if __has_warning("-Wdouble-promotion")
  1328. #pragma clang diagnostic ignored "-Wdouble-promotion"
  1329. #endif
  1330. #if __has_warning("-Wcomma")
  1331. #pragma clang diagnostic ignored "-Wcomma"
  1332. #endif
  1333. #if __has_warning("-Wzero-as-null-pointer-constant")
  1334. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
  1335. #endif
  1336. #if __has_warning("-Wcast-qual")
  1337. #pragma clang diagnostic ignored "-Wcast-qual"
  1338. #endif
  1339. #if __has_warning("-Wmissing-variable-declarations")
  1340. #pragma clang diagnostic ignored "-Wmissing-variable-declarations"
  1341. #endif
  1342. #if __has_warning("-Wmissing-prototypes")
  1343. #pragma clang diagnostic ignored "-Wmissing-prototypes"
  1344. #endif
  1345. #if __has_warning("-Wcast-align")
  1346. #pragma clang diagnostic ignored "-Wcast-align"
  1347. #endif
  1348. #if __has_warning("-Wnewline-eof")
  1349. #pragma clang diagnostic ignored "-Wnewline-eof"
  1350. #endif
  1351. #if __has_warning("-Wunused-parameter")
  1352. #pragma clang diagnostic ignored "-Wunused-parameter"
  1353. #endif
  1354. #if __has_warning("-Wmismatched-tags")
  1355. #pragma clang diagnostic ignored "-Wmismatched-tags"
  1356. #endif
  1357. #if __has_warning("-Wextra-semi-stmt")
  1358. #pragma clang diagnostic ignored "-Wextra-semi-stmt"
  1359. #endif
  1360. #endif
  1361. // Disable GCC warnings
  1362. #ifdef __GNUC__
  1363. #pragma GCC diagnostic push
  1364. #pragma GCC diagnostic ignored "-Wtype-limits"
  1365. #endif // __GNUC__
  1366. #ifndef TINYGLTF_NO_INCLUDE_JSON
  1367. #ifndef TINYGLTF_USE_RAPIDJSON
  1368. #include "json.hpp"
  1369. #else
  1370. #ifndef TINYGLTF_NO_INCLUDE_RAPIDJSON
  1371. #include "document.h"
  1372. #include "prettywriter.h"
  1373. #include "rapidjson.h"
  1374. #include "stringbuffer.h"
  1375. #include "writer.h"
  1376. #endif
  1377. #endif
  1378. #endif
  1379. #ifdef TINYGLTF_ENABLE_DRACO
  1380. #include "draco/compression/decode.h"
  1381. #include "draco/core/decoder_buffer.h"
  1382. #endif
  1383. #ifndef TINYGLTF_NO_STB_IMAGE
  1384. #ifndef TINYGLTF_NO_INCLUDE_STB_IMAGE
  1385. #include "stb_image.h"
  1386. #endif
  1387. #endif
  1388. #ifndef TINYGLTF_NO_STB_IMAGE_WRITE
  1389. #ifndef TINYGLTF_NO_INCLUDE_STB_IMAGE_WRITE
  1390. #include "stb_image_write.h"
  1391. #endif
  1392. #endif
  1393. #ifdef __clang__
  1394. #pragma clang diagnostic pop
  1395. #endif
  1396. #ifdef __GNUC__
  1397. #pragma GCC diagnostic pop
  1398. #endif
  1399. #ifdef _WIN32
  1400. // issue 143.
  1401. // Define NOMINMAX to avoid min/max defines,
  1402. // but undef it after included Windows.h
  1403. #ifndef NOMINMAX
  1404. #define TINYGLTF_INTERNAL_NOMINMAX
  1405. #define NOMINMAX
  1406. #endif
  1407. #ifndef WIN32_LEAN_AND_MEAN
  1408. #define WIN32_LEAN_AND_MEAN
  1409. #define TINYGLTF_INTERNAL_WIN32_LEAN_AND_MEAN
  1410. #endif
  1411. #ifndef __MINGW32__
  1412. #include <Windows.h> // include API for expanding a file path
  1413. #else
  1414. #include <windows.h>
  1415. #endif
  1416. #ifdef TINYGLTF_INTERNAL_WIN32_LEAN_AND_MEAN
  1417. #undef WIN32_LEAN_AND_MEAN
  1418. #endif
  1419. #if defined(TINYGLTF_INTERNAL_NOMINMAX)
  1420. #undef NOMINMAX
  1421. #endif
  1422. #if defined(__GLIBCXX__) // mingw
  1423. #include <fcntl.h> // _O_RDONLY
  1424. #include <ext/stdio_filebuf.h> // fstream (all sorts of IO stuff) + stdio_filebuf (=streambuf)
  1425. #endif
  1426. #elif !defined(__ANDROID__) && !defined(__OpenBSD__)
  1427. //#include <wordexp.h>
  1428. #endif
  1429. #if defined(__sparcv9) || defined(__powerpc__)
  1430. // Big endian
  1431. #else
  1432. #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
  1433. #define TINYGLTF_LITTLE_ENDIAN 1
  1434. #endif
  1435. #endif
  1436. namespace tinygltf {
  1437. namespace detail {
  1438. #ifdef TINYGLTF_USE_RAPIDJSON
  1439. #ifdef TINYGLTF_USE_RAPIDJSON_CRTALLOCATOR
  1440. // This uses the RapidJSON CRTAllocator. It is thread safe and multiple
  1441. // documents may be active at once.
  1442. using json =
  1443. rapidjson::GenericValue<rapidjson::UTF8<>, rapidjson::CrtAllocator>;
  1444. using json_const_iterator = json::ConstMemberIterator;
  1445. using json_const_array_iterator = json const *;
  1446. using JsonDocument =
  1447. rapidjson::GenericDocument<rapidjson::UTF8<>, rapidjson::CrtAllocator>;
  1448. rapidjson::CrtAllocator s_CrtAllocator; // stateless and thread safe
  1449. rapidjson::CrtAllocator &GetAllocator() { return s_CrtAllocator; }
  1450. #else
  1451. // This uses the default RapidJSON MemoryPoolAllocator. It is very fast, but
  1452. // not thread safe. Only a single JsonDocument may be active at any one time,
  1453. // meaning only a single gltf load/save can be active any one time.
  1454. using json = rapidjson::Value;
  1455. using json_const_iterator = json::ConstMemberIterator;
  1456. using json_const_array_iterator = json const *;
  1457. rapidjson::Document *s_pActiveDocument = nullptr;
  1458. rapidjson::Document::AllocatorType &GetAllocator() {
  1459. assert(s_pActiveDocument); // Root json node must be JsonDocument type
  1460. return s_pActiveDocument->GetAllocator();
  1461. }
  1462. #ifdef __clang__
  1463. #pragma clang diagnostic push
  1464. // Suppress JsonDocument(JsonDocument &&rhs) noexcept
  1465. #pragma clang diagnostic ignored "-Wunused-member-function"
  1466. #endif
  1467. struct JsonDocument : public rapidjson::Document {
  1468. JsonDocument() {
  1469. assert(s_pActiveDocument ==
  1470. nullptr); // When using default allocator, only one document can be
  1471. // active at a time, if you need multiple active at once,
  1472. // define TINYGLTF_USE_RAPIDJSON_CRTALLOCATOR
  1473. s_pActiveDocument = this;
  1474. }
  1475. JsonDocument(const JsonDocument &) = delete;
  1476. JsonDocument(JsonDocument &&rhs) noexcept
  1477. : rapidjson::Document(std::move(rhs)) {
  1478. s_pActiveDocument = this;
  1479. rhs.isNil = true;
  1480. }
  1481. ~JsonDocument() {
  1482. if (!isNil) {
  1483. s_pActiveDocument = nullptr;
  1484. }
  1485. }
  1486. private:
  1487. bool isNil = false;
  1488. };
  1489. #ifdef __clang__
  1490. #pragma clang diagnostic pop
  1491. #endif
  1492. #endif // TINYGLTF_USE_RAPIDJSON_CRTALLOCATOR
  1493. #else
  1494. using nlohmann::json;
  1495. using json_const_iterator = json::const_iterator;
  1496. using json_const_array_iterator = json_const_iterator;
  1497. using JsonDocument = json;
  1498. #endif
  1499. void JsonParse(JsonDocument &doc, const char *str, size_t length,
  1500. bool throwExc = false) {
  1501. #ifdef TINYGLTF_USE_RAPIDJSON
  1502. (void)throwExc;
  1503. doc.Parse(str, length);
  1504. #else
  1505. doc = detail::json::parse(str, str + length, nullptr, throwExc);
  1506. #endif
  1507. }
  1508. } // namespace
  1509. }
  1510. #ifdef __APPLE__
  1511. #include "TargetConditionals.h"
  1512. #endif
  1513. #ifdef __clang__
  1514. #pragma clang diagnostic push
  1515. #pragma clang diagnostic ignored "-Wc++98-compat"
  1516. #endif
  1517. namespace tinygltf {
  1518. ///
  1519. /// Internal LoadImageDataOption struct.
  1520. /// This struct is passed through `user_pointer` in LoadImageData.
  1521. /// The struct is not passed when the user supply their own LoadImageData
  1522. /// callbacks.
  1523. ///
  1524. struct LoadImageDataOption {
  1525. // true: preserve image channels(e.g. load as RGB image if the image has RGB
  1526. // channels) default `false`(channels are expanded to RGBA for backward
  1527. // compatibility).
  1528. bool preserve_channels{false};
  1529. };
  1530. // Equals function for Value, for recursivity
  1531. static bool Equals(const tinygltf::Value &one, const tinygltf::Value &other) {
  1532. if (one.Type() != other.Type()) return false;
  1533. switch (one.Type()) {
  1534. case NULL_TYPE:
  1535. return true;
  1536. case BOOL_TYPE:
  1537. return one.Get<bool>() == other.Get<bool>();
  1538. case REAL_TYPE:
  1539. return TINYGLTF_DOUBLE_EQUAL(one.Get<double>(), other.Get<double>());
  1540. case INT_TYPE:
  1541. return one.Get<int>() == other.Get<int>();
  1542. case OBJECT_TYPE: {
  1543. auto oneObj = one.Get<tinygltf::Value::Object>();
  1544. auto otherObj = other.Get<tinygltf::Value::Object>();
  1545. if (oneObj.size() != otherObj.size()) return false;
  1546. for (auto &it : oneObj) {
  1547. auto otherIt = otherObj.find(it.first);
  1548. if (otherIt == otherObj.end()) return false;
  1549. if (!Equals(it.second, otherIt->second)) return false;
  1550. }
  1551. return true;
  1552. }
  1553. case ARRAY_TYPE: {
  1554. if (one.Size() != other.Size()) return false;
  1555. for (int i = 0; i < int(one.Size()); ++i)
  1556. if (!Equals(one.Get(i), other.Get(i))) return false;
  1557. return true;
  1558. }
  1559. case STRING_TYPE:
  1560. return one.Get<std::string>() == other.Get<std::string>();
  1561. case BINARY_TYPE:
  1562. return one.Get<std::vector<unsigned char> >() ==
  1563. other.Get<std::vector<unsigned char> >();
  1564. default: {
  1565. // unhandled type
  1566. return false;
  1567. }
  1568. }
  1569. }
  1570. // Equals function for std::vector<double> using TINYGLTF_DOUBLE_EPSILON
  1571. static bool Equals(const std::vector<double> &one,
  1572. const std::vector<double> &other) {
  1573. if (one.size() != other.size()) return false;
  1574. for (int i = 0; i < int(one.size()); ++i) {
  1575. if (!TINYGLTF_DOUBLE_EQUAL(one[size_t(i)], other[size_t(i)])) return false;
  1576. }
  1577. return true;
  1578. }
  1579. bool Accessor::operator==(const Accessor &other) const {
  1580. return this->bufferView == other.bufferView &&
  1581. this->byteOffset == other.byteOffset &&
  1582. this->componentType == other.componentType &&
  1583. this->count == other.count && this->extensions == other.extensions &&
  1584. this->extras == other.extras &&
  1585. Equals(this->maxValues, other.maxValues) &&
  1586. Equals(this->minValues, other.minValues) && this->name == other.name &&
  1587. this->normalized == other.normalized && this->type == other.type;
  1588. }
  1589. bool Animation::operator==(const Animation &other) const {
  1590. return this->channels == other.channels &&
  1591. this->extensions == other.extensions && this->extras == other.extras &&
  1592. this->name == other.name && this->samplers == other.samplers;
  1593. }
  1594. bool AnimationChannel::operator==(const AnimationChannel &other) const {
  1595. return this->extensions == other.extensions && this->extras == other.extras &&
  1596. this->target_node == other.target_node &&
  1597. this->target_path == other.target_path &&
  1598. this->sampler == other.sampler;
  1599. }
  1600. bool AnimationSampler::operator==(const AnimationSampler &other) const {
  1601. return this->extras == other.extras && this->extensions == other.extensions &&
  1602. this->input == other.input &&
  1603. this->interpolation == other.interpolation &&
  1604. this->output == other.output;
  1605. }
  1606. bool Asset::operator==(const Asset &other) const {
  1607. return this->copyright == other.copyright &&
  1608. this->extensions == other.extensions && this->extras == other.extras &&
  1609. this->generator == other.generator &&
  1610. this->minVersion == other.minVersion && this->version == other.version;
  1611. }
  1612. bool Buffer::operator==(const Buffer &other) const {
  1613. return this->data == other.data && this->extensions == other.extensions &&
  1614. this->extras == other.extras && this->name == other.name &&
  1615. this->uri == other.uri;
  1616. }
  1617. bool BufferView::operator==(const BufferView &other) const {
  1618. return this->buffer == other.buffer && this->byteLength == other.byteLength &&
  1619. this->byteOffset == other.byteOffset &&
  1620. this->byteStride == other.byteStride && this->name == other.name &&
  1621. this->target == other.target && this->extensions == other.extensions &&
  1622. this->extras == other.extras &&
  1623. this->dracoDecoded == other.dracoDecoded;
  1624. }
  1625. bool Camera::operator==(const Camera &other) const {
  1626. return this->name == other.name && this->extensions == other.extensions &&
  1627. this->extras == other.extras &&
  1628. this->orthographic == other.orthographic &&
  1629. this->perspective == other.perspective && this->type == other.type;
  1630. }
  1631. bool Image::operator==(const Image &other) const {
  1632. return this->bufferView == other.bufferView &&
  1633. this->component == other.component &&
  1634. this->extensions == other.extensions && this->extras == other.extras &&
  1635. this->height == other.height && this->image == other.image &&
  1636. this->mimeType == other.mimeType && this->name == other.name &&
  1637. this->uri == other.uri && this->width == other.width;
  1638. }
  1639. bool Light::operator==(const Light &other) const {
  1640. return Equals(this->color, other.color) && this->name == other.name &&
  1641. this->type == other.type;
  1642. }
  1643. bool Material::operator==(const Material &other) const {
  1644. return (this->pbrMetallicRoughness == other.pbrMetallicRoughness) &&
  1645. (this->normalTexture == other.normalTexture) &&
  1646. (this->occlusionTexture == other.occlusionTexture) &&
  1647. (this->emissiveTexture == other.emissiveTexture) &&
  1648. Equals(this->emissiveFactor, other.emissiveFactor) &&
  1649. (this->alphaMode == other.alphaMode) &&
  1650. TINYGLTF_DOUBLE_EQUAL(this->alphaCutoff, other.alphaCutoff) &&
  1651. (this->doubleSided == other.doubleSided) &&
  1652. (this->extensions == other.extensions) &&
  1653. (this->extras == other.extras) && (this->values == other.values) &&
  1654. (this->additionalValues == other.additionalValues) &&
  1655. (this->name == other.name);
  1656. }
  1657. bool Mesh::operator==(const Mesh &other) const {
  1658. return this->extensions == other.extensions && this->extras == other.extras &&
  1659. this->name == other.name && Equals(this->weights, other.weights) &&
  1660. this->primitives == other.primitives;
  1661. }
  1662. bool Model::operator==(const Model &other) const {
  1663. return this->accessors == other.accessors &&
  1664. this->animations == other.animations && this->asset == other.asset &&
  1665. this->buffers == other.buffers &&
  1666. this->bufferViews == other.bufferViews &&
  1667. this->cameras == other.cameras &&
  1668. this->defaultScene == other.defaultScene &&
  1669. this->extensions == other.extensions &&
  1670. this->extensionsRequired == other.extensionsRequired &&
  1671. this->extensionsUsed == other.extensionsUsed &&
  1672. this->extras == other.extras && this->images == other.images &&
  1673. this->lights == other.lights && this->materials == other.materials &&
  1674. this->meshes == other.meshes && this->nodes == other.nodes &&
  1675. this->samplers == other.samplers && this->scenes == other.scenes &&
  1676. this->skins == other.skins && this->textures == other.textures;
  1677. }
  1678. bool Node::operator==(const Node &other) const {
  1679. return this->camera == other.camera && this->children == other.children &&
  1680. this->extensions == other.extensions && this->extras == other.extras &&
  1681. Equals(this->matrix, other.matrix) && this->mesh == other.mesh &&
  1682. this->name == other.name && Equals(this->rotation, other.rotation) &&
  1683. Equals(this->scale, other.scale) && this->skin == other.skin &&
  1684. Equals(this->translation, other.translation) &&
  1685. Equals(this->weights, other.weights);
  1686. }
  1687. bool SpotLight::operator==(const SpotLight &other) const {
  1688. return this->extensions == other.extensions && this->extras == other.extras &&
  1689. TINYGLTF_DOUBLE_EQUAL(this->innerConeAngle, other.innerConeAngle) &&
  1690. TINYGLTF_DOUBLE_EQUAL(this->outerConeAngle, other.outerConeAngle);
  1691. }
  1692. bool OrthographicCamera::operator==(const OrthographicCamera &other) const {
  1693. return this->extensions == other.extensions && this->extras == other.extras &&
  1694. TINYGLTF_DOUBLE_EQUAL(this->xmag, other.xmag) &&
  1695. TINYGLTF_DOUBLE_EQUAL(this->ymag, other.ymag) &&
  1696. TINYGLTF_DOUBLE_EQUAL(this->zfar, other.zfar) &&
  1697. TINYGLTF_DOUBLE_EQUAL(this->znear, other.znear);
  1698. }
  1699. bool Parameter::operator==(const Parameter &other) const {
  1700. if (this->bool_value != other.bool_value ||
  1701. this->has_number_value != other.has_number_value)
  1702. return false;
  1703. if (!TINYGLTF_DOUBLE_EQUAL(this->number_value, other.number_value))
  1704. return false;
  1705. if (this->json_double_value.size() != other.json_double_value.size())
  1706. return false;
  1707. for (auto &it : this->json_double_value) {
  1708. auto otherIt = other.json_double_value.find(it.first);
  1709. if (otherIt == other.json_double_value.end()) return false;
  1710. if (!TINYGLTF_DOUBLE_EQUAL(it.second, otherIt->second)) return false;
  1711. }
  1712. if (!Equals(this->number_array, other.number_array)) return false;
  1713. if (this->string_value != other.string_value) return false;
  1714. return true;
  1715. }
  1716. bool PerspectiveCamera::operator==(const PerspectiveCamera &other) const {
  1717. return TINYGLTF_DOUBLE_EQUAL(this->aspectRatio, other.aspectRatio) &&
  1718. this->extensions == other.extensions && this->extras == other.extras &&
  1719. TINYGLTF_DOUBLE_EQUAL(this->yfov, other.yfov) &&
  1720. TINYGLTF_DOUBLE_EQUAL(this->zfar, other.zfar) &&
  1721. TINYGLTF_DOUBLE_EQUAL(this->znear, other.znear);
  1722. }
  1723. bool Primitive::operator==(const Primitive &other) const {
  1724. return this->attributes == other.attributes && this->extras == other.extras &&
  1725. this->indices == other.indices && this->material == other.material &&
  1726. this->mode == other.mode && this->targets == other.targets;
  1727. }
  1728. bool Sampler::operator==(const Sampler &other) const {
  1729. return this->extensions == other.extensions && this->extras == other.extras &&
  1730. this->magFilter == other.magFilter &&
  1731. this->minFilter == other.minFilter && this->name == other.name &&
  1732. this->wrapS == other.wrapS && this->wrapT == other.wrapT;
  1733. // this->wrapR == other.wrapR
  1734. }
  1735. bool Scene::operator==(const Scene &other) const {
  1736. return this->extensions == other.extensions && this->extras == other.extras &&
  1737. this->name == other.name && this->nodes == other.nodes;
  1738. }
  1739. bool Skin::operator==(const Skin &other) const {
  1740. return this->extensions == other.extensions && this->extras == other.extras &&
  1741. this->inverseBindMatrices == other.inverseBindMatrices &&
  1742. this->joints == other.joints && this->name == other.name &&
  1743. this->skeleton == other.skeleton;
  1744. }
  1745. bool Texture::operator==(const Texture &other) const {
  1746. return this->extensions == other.extensions && this->extras == other.extras &&
  1747. this->name == other.name && this->sampler == other.sampler &&
  1748. this->source == other.source;
  1749. }
  1750. bool TextureInfo::operator==(const TextureInfo &other) const {
  1751. return this->extensions == other.extensions && this->extras == other.extras &&
  1752. this->index == other.index && this->texCoord == other.texCoord;
  1753. }
  1754. bool NormalTextureInfo::operator==(const NormalTextureInfo &other) const {
  1755. return this->extensions == other.extensions && this->extras == other.extras &&
  1756. this->index == other.index && this->texCoord == other.texCoord &&
  1757. TINYGLTF_DOUBLE_EQUAL(this->scale, other.scale);
  1758. }
  1759. bool OcclusionTextureInfo::operator==(const OcclusionTextureInfo &other) const {
  1760. return this->extensions == other.extensions && this->extras == other.extras &&
  1761. this->index == other.index && this->texCoord == other.texCoord &&
  1762. TINYGLTF_DOUBLE_EQUAL(this->strength, other.strength);
  1763. }
  1764. bool PbrMetallicRoughness::operator==(const PbrMetallicRoughness &other) const {
  1765. return this->extensions == other.extensions && this->extras == other.extras &&
  1766. (this->baseColorTexture == other.baseColorTexture) &&
  1767. (this->metallicRoughnessTexture == other.metallicRoughnessTexture) &&
  1768. Equals(this->baseColorFactor, other.baseColorFactor) &&
  1769. TINYGLTF_DOUBLE_EQUAL(this->metallicFactor, other.metallicFactor) &&
  1770. TINYGLTF_DOUBLE_EQUAL(this->roughnessFactor, other.roughnessFactor);
  1771. }
  1772. bool Value::operator==(const Value &other) const {
  1773. return Equals(*this, other);
  1774. }
  1775. static void swap4(unsigned int *val) {
  1776. #ifdef TINYGLTF_LITTLE_ENDIAN
  1777. (void)val;
  1778. #else
  1779. unsigned int tmp = *val;
  1780. unsigned char *dst = reinterpret_cast<unsigned char *>(val);
  1781. unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
  1782. dst[0] = src[3];
  1783. dst[1] = src[2];
  1784. dst[2] = src[1];
  1785. dst[3] = src[0];
  1786. #endif
  1787. }
  1788. static std::string JoinPath(const std::string &path0,
  1789. const std::string &path1) {
  1790. if (path0.empty()) {
  1791. return path1;
  1792. } else {
  1793. // check '/'
  1794. char lastChar = *path0.rbegin();
  1795. if (lastChar != '/') {
  1796. return path0 + std::string("/") + path1;
  1797. } else {
  1798. return path0 + path1;
  1799. }
  1800. }
  1801. }
  1802. static std::string FindFile(const std::vector<std::string> &paths,
  1803. const std::string &filepath, FsCallbacks *fs) {
  1804. if (fs == nullptr || fs->ExpandFilePath == nullptr ||
  1805. fs->FileExists == nullptr) {
  1806. // Error, fs callback[s] missing
  1807. return std::string();
  1808. }
  1809. for (size_t i = 0; i < paths.size(); i++) {
  1810. std::string absPath =
  1811. fs->ExpandFilePath(JoinPath(paths[i], filepath), fs->user_data);
  1812. if (fs->FileExists(absPath, fs->user_data)) {
  1813. return absPath;
  1814. }
  1815. }
  1816. return std::string();
  1817. }
  1818. static std::string GetFilePathExtension(const std::string &FileName) {
  1819. if (FileName.find_last_of(".") != std::string::npos)
  1820. return FileName.substr(FileName.find_last_of(".") + 1);
  1821. return "";
  1822. }
  1823. static std::string GetBaseDir(const std::string &filepath) {
  1824. if (filepath.find_last_of("/\\") != std::string::npos)
  1825. return filepath.substr(0, filepath.find_last_of("/\\"));
  1826. return "";
  1827. }
  1828. static std::string GetBaseFilename(const std::string &filepath) {
  1829. auto idx = filepath.find_last_of("/\\");
  1830. if (idx != std::string::npos) return filepath.substr(idx + 1);
  1831. return filepath;
  1832. }
  1833. std::string base64_encode(unsigned char const *, unsigned int len);
  1834. std::string base64_decode(std::string const &s);
  1835. /*
  1836. base64.cpp and base64.h
  1837. Copyright (C) 2004-2008 René Nyffenegger
  1838. This source code is provided 'as-is', without any express or implied
  1839. warranty. In no event will the author be held liable for any damages
  1840. arising from the use of this software.
  1841. Permission is granted to anyone to use this software for any purpose,
  1842. including commercial applications, and to alter it and redistribute it
  1843. freely, subject to the following restrictions:
  1844. 1. The origin of this source code must not be misrepresented; you must not
  1845. claim that you wrote the original source code. If you use this source code
  1846. in a product, an acknowledgment in the product documentation would be
  1847. appreciated but is not required.
  1848. 2. Altered source versions must be plainly marked as such, and must not be
  1849. misrepresented as being the original source code.
  1850. 3. This notice may not be removed or altered from any source distribution.
  1851. René Nyffenegger rene.nyffenegger@adp-gmbh.ch
  1852. */
  1853. #ifdef __clang__
  1854. #pragma clang diagnostic push
  1855. #pragma clang diagnostic ignored "-Wsign-conversion"
  1856. #pragma clang diagnostic ignored "-Wconversion"
  1857. #endif
  1858. static inline bool is_base64(unsigned char c) {
  1859. return (isalnum(c) || (c == '+') || (c == '/'));
  1860. }
  1861. std::string base64_encode(unsigned char const *bytes_to_encode,
  1862. unsigned int in_len) {
  1863. std::string ret;
  1864. int i = 0;
  1865. int j = 0;
  1866. unsigned char char_array_3[3];
  1867. unsigned char char_array_4[4];
  1868. const char *base64_chars =
  1869. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1870. "abcdefghijklmnopqrstuvwxyz"
  1871. "0123456789+/";
  1872. while (in_len--) {
  1873. char_array_3[i++] = *(bytes_to_encode++);
  1874. if (i == 3) {
  1875. char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
  1876. char_array_4[1] =
  1877. ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
  1878. char_array_4[2] =
  1879. ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
  1880. char_array_4[3] = char_array_3[2] & 0x3f;
  1881. for (i = 0; (i < 4); i++) ret += base64_chars[char_array_4[i]];
  1882. i = 0;
  1883. }
  1884. }
  1885. if (i) {
  1886. for (j = i; j < 3; j++) char_array_3[j] = '\0';
  1887. char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
  1888. char_array_4[1] =
  1889. ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
  1890. char_array_4[2] =
  1891. ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
  1892. for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]];
  1893. while ((i++ < 3)) ret += '=';
  1894. }
  1895. return ret;
  1896. }
  1897. std::string base64_decode(std::string const &encoded_string) {
  1898. int in_len = static_cast<int>(encoded_string.size());
  1899. int i = 0;
  1900. int j = 0;
  1901. int in_ = 0;
  1902. unsigned char char_array_4[4], char_array_3[3];
  1903. std::string ret;
  1904. const std::string base64_chars =
  1905. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1906. "abcdefghijklmnopqrstuvwxyz"
  1907. "0123456789+/";
  1908. while (in_len-- && (encoded_string[in_] != '=') &&
  1909. is_base64(encoded_string[in_])) {
  1910. char_array_4[i++] = encoded_string[in_];
  1911. in_++;
  1912. if (i == 4) {
  1913. for (i = 0; i < 4; i++)
  1914. char_array_4[i] =
  1915. static_cast<unsigned char>(base64_chars.find(char_array_4[i]));
  1916. char_array_3[0] =
  1917. (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
  1918. char_array_3[1] =
  1919. ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  1920. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  1921. for (i = 0; (i < 3); i++) ret += char_array_3[i];
  1922. i = 0;
  1923. }
  1924. }
  1925. if (i) {
  1926. for (j = i; j < 4; j++) char_array_4[j] = 0;
  1927. for (j = 0; j < 4; j++)
  1928. char_array_4[j] =
  1929. static_cast<unsigned char>(base64_chars.find(char_array_4[j]));
  1930. char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
  1931. char_array_3[1] =
  1932. ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  1933. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  1934. for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
  1935. }
  1936. return ret;
  1937. }
  1938. #ifdef __clang__
  1939. #pragma clang diagnostic pop
  1940. #endif
  1941. // https://github.com/syoyo/tinygltf/issues/228
  1942. // TODO(syoyo): Use uriparser https://uriparser.github.io/ for stricter Uri
  1943. // decoding?
  1944. //
  1945. // Uri Decoding from DLIB
  1946. // http://dlib.net/dlib/server/server_http.cpp.html
  1947. // --- dlib begin ------------------------------------------------------------
  1948. // Copyright (C) 2003 Davis E. King (davis@dlib.net)
  1949. // License: Boost Software License
  1950. // Boost Software License - Version 1.0 - August 17th, 2003
  1951. // Permission is hereby granted, free of charge, to any person or organization
  1952. // obtaining a copy of the software and accompanying documentation covered by
  1953. // this license (the "Software") to use, reproduce, display, distribute,
  1954. // execute, and transmit the Software, and to prepare derivative works of the
  1955. // Software, and to permit third-parties to whom the Software is furnished to
  1956. // do so, all subject to the following:
  1957. // The copyright notices in the Software and this entire statement, including
  1958. // the above license grant, this restriction and the following disclaimer,
  1959. // must be included in all copies of the Software, in whole or in part, and
  1960. // all derivative works of the Software, unless such copies or derivative
  1961. // works are solely in the form of machine-executable object code generated by
  1962. // a source language processor.
  1963. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1964. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1965. // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
  1966. // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
  1967. // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
  1968. // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  1969. // DEALINGS IN THE SOFTWARE.
  1970. //
  1971. namespace dlib {
  1972. inline unsigned char from_hex(unsigned char ch) {
  1973. if (ch <= '9' && ch >= '0')
  1974. ch -= '0';
  1975. else if (ch <= 'f' && ch >= 'a')
  1976. ch -= 'a' - 10;
  1977. else if (ch <= 'F' && ch >= 'A')
  1978. ch -= 'A' - 10;
  1979. else
  1980. ch = 0;
  1981. return ch;
  1982. }
  1983. static const std::string urldecode(const std::string &str) {
  1984. using namespace std;
  1985. string result;
  1986. string::size_type i;
  1987. for (i = 0; i < str.size(); ++i) {
  1988. if (str[i] == '+') {
  1989. result += ' ';
  1990. } else if (str[i] == '%' && str.size() > i + 2) {
  1991. const unsigned char ch1 =
  1992. from_hex(static_cast<unsigned char>(str[i + 1]));
  1993. const unsigned char ch2 =
  1994. from_hex(static_cast<unsigned char>(str[i + 2]));
  1995. const unsigned char ch = static_cast<unsigned char>((ch1 << 4) | ch2);
  1996. result += static_cast<char>(ch);
  1997. i += 2;
  1998. } else {
  1999. result += str[i];
  2000. }
  2001. }
  2002. return result;
  2003. }
  2004. } // namespace dlib
  2005. // --- dlib end --------------------------------------------------------------
  2006. bool URIDecode(const std::string &in_uri, std::string *out_uri,
  2007. void *user_data) {
  2008. (void)user_data;
  2009. *out_uri = dlib::urldecode(in_uri);
  2010. return true;
  2011. }
  2012. static bool LoadExternalFile(std::vector<unsigned char> *out, std::string *err,
  2013. std::string *warn, const std::string &filename,
  2014. const std::string &basedir, bool required,
  2015. size_t reqBytes, bool checkSize, FsCallbacks *fs) {
  2016. if (fs == nullptr || fs->FileExists == nullptr ||
  2017. fs->ExpandFilePath == nullptr || fs->ReadWholeFile == nullptr) {
  2018. // This is a developer error, assert() ?
  2019. if (err) {
  2020. (*err) += "FS callback[s] not set\n";
  2021. }
  2022. return false;
  2023. }
  2024. std::string *failMsgOut = required ? err : warn;
  2025. out->clear();
  2026. std::vector<std::string> paths;
  2027. paths.push_back(basedir);
  2028. paths.push_back(".");
  2029. std::string filepath = FindFile(paths, filename, fs);
  2030. if (filepath.empty() || filename.empty()) {
  2031. if (failMsgOut) {
  2032. (*failMsgOut) += "File not found : " + filename + "\n";
  2033. }
  2034. return false;
  2035. }
  2036. std::vector<unsigned char> buf;
  2037. std::string fileReadErr;
  2038. bool fileRead =
  2039. fs->ReadWholeFile(&buf, &fileReadErr, filepath, fs->user_data);
  2040. if (!fileRead) {
  2041. if (failMsgOut) {
  2042. (*failMsgOut) +=
  2043. "File read error : " + filepath + " : " + fileReadErr + "\n";
  2044. }
  2045. return false;
  2046. }
  2047. size_t sz = buf.size();
  2048. if (sz == 0) {
  2049. if (failMsgOut) {
  2050. (*failMsgOut) += "File is empty : " + filepath + "\n";
  2051. }
  2052. return false;
  2053. }
  2054. if (checkSize) {
  2055. if (reqBytes == sz) {
  2056. out->swap(buf);
  2057. return true;
  2058. } else {
  2059. std::stringstream ss;
  2060. ss << "File size mismatch : " << filepath << ", requestedBytes "
  2061. << reqBytes << ", but got " << sz << std::endl;
  2062. if (failMsgOut) {
  2063. (*failMsgOut) += ss.str();
  2064. }
  2065. return false;
  2066. }
  2067. }
  2068. out->swap(buf);
  2069. return true;
  2070. }
  2071. void TinyGLTF::SetImageLoader(LoadImageDataFunction func, void *user_data) {
  2072. LoadImageData = func;
  2073. load_image_user_data_ = user_data;
  2074. user_image_loader_ = true;
  2075. }
  2076. void TinyGLTF::RemoveImageLoader() {
  2077. LoadImageData =
  2078. #ifndef TINYGLTF_NO_STB_IMAGE
  2079. &tinygltf::LoadImageData;
  2080. #else
  2081. nullptr;
  2082. #endif
  2083. load_image_user_data_ = nullptr;
  2084. user_image_loader_ = false;
  2085. }
  2086. #ifndef TINYGLTF_NO_STB_IMAGE
  2087. bool LoadImageData(Image *image, const int image_idx, std::string *err,
  2088. std::string *warn, int req_width, int req_height,
  2089. const unsigned char *bytes, int size, void *user_data) {
  2090. (void)warn;
  2091. LoadImageDataOption option;
  2092. if (user_data) {
  2093. option = *reinterpret_cast<LoadImageDataOption *>(user_data);
  2094. }
  2095. int w = 0, h = 0, comp = 0, req_comp = 0;
  2096. unsigned char *data = nullptr;
  2097. // preserve_channels true: Use channels stored in the image file.
  2098. // false: force 32-bit textures for common Vulkan compatibility. It appears
  2099. // that some GPU drivers do not support 24-bit images for Vulkan
  2100. req_comp = option.preserve_channels ? 0 : 4;
  2101. int bits = 8;
  2102. int pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE;
  2103. // It is possible that the image we want to load is a 16bit per channel image
  2104. // We are going to attempt to load it as 16bit per channel, and if it worked,
  2105. // set the image data accordingly. We are casting the returned pointer into
  2106. // unsigned char, because we are representing "bytes". But we are updating
  2107. // the Image metadata to signal that this image uses 2 bytes (16bits) per
  2108. // channel:
  2109. if (stbi_is_16_bit_from_memory(bytes, size)) {
  2110. data = reinterpret_cast<unsigned char *>(
  2111. stbi_load_16_from_memory(bytes, size, &w, &h, &comp, req_comp));
  2112. if (data) {
  2113. bits = 16;
  2114. pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT;
  2115. }
  2116. }
  2117. // at this point, if data is still NULL, it means that the image wasn't
  2118. // 16bit per channel, we are going to load it as a normal 8bit per channel
  2119. // image as we used to do:
  2120. // if image cannot be decoded, ignore parsing and keep it by its path
  2121. // don't break in this case
  2122. // FIXME we should only enter this function if the image is embedded. If
  2123. // image->uri references
  2124. // an image file, it should be left as it is. Image loading should not be
  2125. // mandatory (to support other formats)
  2126. if (!data) data = stbi_load_from_memory(bytes, size, &w, &h, &comp, req_comp);
  2127. if (!data) {
  2128. // NOTE: you can use `warn` instead of `err`
  2129. if (err) {
  2130. (*err) +=
  2131. "Unknown image format. STB cannot decode image data for image[" +
  2132. std::to_string(image_idx) + "] name = \"" + image->name + "\".\n";
  2133. }
  2134. return false;
  2135. }
  2136. if ((w < 1) || (h < 1)) {
  2137. stbi_image_free(data);
  2138. if (err) {
  2139. (*err) += "Invalid image data for image[" + std::to_string(image_idx) +
  2140. "] name = \"" + image->name + "\"\n";
  2141. }
  2142. return false;
  2143. }
  2144. if (req_width > 0) {
  2145. if (req_width != w) {
  2146. stbi_image_free(data);
  2147. if (err) {
  2148. (*err) += "Image width mismatch for image[" +
  2149. std::to_string(image_idx) + "] name = \"" + image->name +
  2150. "\"\n";
  2151. }
  2152. return false;
  2153. }
  2154. }
  2155. if (req_height > 0) {
  2156. if (req_height != h) {
  2157. stbi_image_free(data);
  2158. if (err) {
  2159. (*err) += "Image height mismatch. for image[" +
  2160. std::to_string(image_idx) + "] name = \"" + image->name +
  2161. "\"\n";
  2162. }
  2163. return false;
  2164. }
  2165. }
  2166. if (req_comp != 0) {
  2167. // loaded data has `req_comp` channels(components)
  2168. comp = req_comp;
  2169. }
  2170. image->width = w;
  2171. image->height = h;
  2172. image->component = comp;
  2173. image->bits = bits;
  2174. image->pixel_type = pixel_type;
  2175. image->image.resize(static_cast<size_t>(w * h * comp) * size_t(bits / 8));
  2176. std::copy(data, data + w * h * comp * (bits / 8), image->image.begin());
  2177. stbi_image_free(data);
  2178. return true;
  2179. }
  2180. #endif
  2181. void TinyGLTF::SetImageWriter(WriteImageDataFunction func, void *user_data) {
  2182. WriteImageData = func;
  2183. write_image_user_data_ = user_data;
  2184. }
  2185. #ifndef TINYGLTF_NO_STB_IMAGE_WRITE
  2186. static void WriteToMemory_stbi(void *context, void *data, int size) {
  2187. std::vector<unsigned char> *buffer =
  2188. reinterpret_cast<std::vector<unsigned char> *>(context);
  2189. unsigned char *pData = reinterpret_cast<unsigned char *>(data);
  2190. buffer->insert(buffer->end(), pData, pData + size);
  2191. }
  2192. bool WriteImageData(const std::string *basepath, const std::string *filename,
  2193. const Image *image, bool embedImages,
  2194. const URICallbacks *uri_cb, std::string *out_uri,
  2195. void *fsPtr) {
  2196. const std::string ext = GetFilePathExtension(*filename);
  2197. // Write image to temporary buffer
  2198. std::string header;
  2199. std::vector<unsigned char> data;
  2200. if (ext == "png") {
  2201. if ((image->bits != 8) ||
  2202. (image->pixel_type != TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE)) {
  2203. // Unsupported pixel format
  2204. return false;
  2205. }
  2206. if (!stbi_write_png_to_func(WriteToMemory_stbi, &data, image->width,
  2207. image->height, image->component,
  2208. &image->image[0], 0)) {
  2209. return false;
  2210. }
  2211. header = "data:image/png;base64,";
  2212. } else if (ext == "jpg") {
  2213. if (!stbi_write_jpg_to_func(WriteToMemory_stbi, &data, image->width,
  2214. image->height, image->component,
  2215. &image->image[0], 100)) {
  2216. return false;
  2217. }
  2218. header = "data:image/jpeg;base64,";
  2219. } else if (ext == "bmp") {
  2220. if (!stbi_write_bmp_to_func(WriteToMemory_stbi, &data, image->width,
  2221. image->height, image->component,
  2222. &image->image[0])) {
  2223. return false;
  2224. }
  2225. header = "data:image/bmp;base64,";
  2226. } else if (!embedImages) {
  2227. // Error: can't output requested format to file
  2228. return false;
  2229. }
  2230. if (embedImages) {
  2231. // Embed base64-encoded image into URI
  2232. if (data.size()) {
  2233. *out_uri = header +
  2234. base64_encode(&data[0], static_cast<unsigned int>(data.size()));
  2235. } else {
  2236. // Throw error?
  2237. }
  2238. } else {
  2239. // Write image to disc
  2240. FsCallbacks *fs = reinterpret_cast<FsCallbacks *>(fsPtr);
  2241. if ((fs != nullptr) && (fs->WriteWholeFile != nullptr)) {
  2242. const std::string imagefilepath = JoinPath(*basepath, *filename);
  2243. std::string writeError;
  2244. if (!fs->WriteWholeFile(&writeError, imagefilepath, data,
  2245. fs->user_data)) {
  2246. // Could not write image file to disc; Throw error ?
  2247. return false;
  2248. }
  2249. } else {
  2250. // Throw error?
  2251. }
  2252. if (uri_cb->encode) {
  2253. if (!uri_cb->encode(*filename, "image", out_uri, uri_cb->user_data)) {
  2254. return false;
  2255. }
  2256. } else {
  2257. *out_uri = *filename;
  2258. }
  2259. }
  2260. return true;
  2261. }
  2262. #endif
  2263. void TinyGLTF::SetURICallbacks(URICallbacks callbacks) {
  2264. assert(callbacks.decode);
  2265. if (callbacks.decode) {
  2266. uri_cb = callbacks;
  2267. }
  2268. }
  2269. void TinyGLTF::SetFsCallbacks(FsCallbacks callbacks) { fs = callbacks; }
  2270. #ifdef _WIN32
  2271. static inline std::wstring UTF8ToWchar(const std::string &str) {
  2272. int wstr_size =
  2273. MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), nullptr, 0);
  2274. std::wstring wstr((size_t)wstr_size, 0);
  2275. MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), &wstr[0],
  2276. (int)wstr.size());
  2277. return wstr;
  2278. }
  2279. static inline std::string WcharToUTF8(const std::wstring &wstr) {
  2280. int str_size = WideCharToMultiByte(CP_UTF8, 0, wstr.data(), (int)wstr.size(),
  2281. nullptr, 0, nullptr, nullptr);
  2282. std::string str((size_t)str_size, 0);
  2283. WideCharToMultiByte(CP_UTF8, 0, wstr.data(), (int)wstr.size(), &str[0],
  2284. (int)str.size(), nullptr, nullptr);
  2285. return str;
  2286. }
  2287. #endif
  2288. #ifndef TINYGLTF_NO_FS
  2289. // Default implementations of filesystem functions
  2290. bool FileExists(const std::string &abs_filename, void *) {
  2291. bool ret;
  2292. #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS
  2293. if (asset_manager) {
  2294. AAsset *asset = AAssetManager_open(asset_manager, abs_filename.c_str(),
  2295. AASSET_MODE_STREAMING);
  2296. if (!asset) {
  2297. return false;
  2298. }
  2299. AAsset_close(asset);
  2300. ret = true;
  2301. } else {
  2302. return false;
  2303. }
  2304. #else
  2305. #ifdef _WIN32
  2306. #if defined(_MSC_VER) || defined(__GLIBCXX__) || defined(_LIBCPP_VERSION)
  2307. FILE *fp = nullptr;
  2308. errno_t err = _wfopen_s(&fp, UTF8ToWchar(abs_filename).c_str(), L"rb");
  2309. if (err != 0) {
  2310. return false;
  2311. }
  2312. #else
  2313. FILE *fp = nullptr;
  2314. errno_t err = fopen_s(&fp, abs_filename.c_str(), "rb");
  2315. if (err != 0) {
  2316. return false;
  2317. }
  2318. #endif
  2319. #else
  2320. FILE *fp = fopen(abs_filename.c_str(), "rb");
  2321. #endif
  2322. if (fp) {
  2323. ret = true;
  2324. fclose(fp);
  2325. } else {
  2326. ret = false;
  2327. }
  2328. #endif
  2329. return ret;
  2330. }
  2331. std::string ExpandFilePath(const std::string &filepath, void *) {
  2332. // https://github.com/syoyo/tinygltf/issues/368
  2333. //
  2334. // No file path expansion in built-in FS function anymore, since glTF URI
  2335. // should not contain tilde('~') and environment variables, and for security
  2336. // reason(`wordexp`).
  2337. //
  2338. // Users need to supply `base_dir`(in `LoadASCIIFromString`,
  2339. // `LoadBinaryFromMemory`) in expanded absolute path.
  2340. return filepath;
  2341. #if 0
  2342. #ifdef _WIN32
  2343. // Assume input `filepath` is encoded in UTF-8
  2344. std::wstring wfilepath = UTF8ToWchar(filepath);
  2345. DWORD wlen = ExpandEnvironmentStringsW(wfilepath.c_str(), nullptr, 0);
  2346. wchar_t *wstr = new wchar_t[wlen];
  2347. ExpandEnvironmentStringsW(wfilepath.c_str(), wstr, wlen);
  2348. std::wstring ws(wstr);
  2349. delete[] wstr;
  2350. return WcharToUTF8(ws);
  2351. #else
  2352. #if defined(TARGET_OS_IPHONE) || defined(TARGET_IPHONE_SIMULATOR) || \
  2353. defined(__ANDROID__) || defined(__EMSCRIPTEN__) || defined(__OpenBSD__)
  2354. // no expansion
  2355. std::string s = filepath;
  2356. #else
  2357. std::string s;
  2358. wordexp_t p;
  2359. if (filepath.empty()) {
  2360. return "";
  2361. }
  2362. // Quote the string to keep any spaces in filepath intact.
  2363. std::string quoted_path = "\"" + filepath + "\"";
  2364. // char** w;
  2365. int ret = wordexp(quoted_path.c_str(), &p, 0);
  2366. if (ret) {
  2367. // err
  2368. s = filepath;
  2369. return s;
  2370. }
  2371. // Use first element only.
  2372. if (p.we_wordv) {
  2373. s = std::string(p.we_wordv[0]);
  2374. wordfree(&p);
  2375. } else {
  2376. s = filepath;
  2377. }
  2378. #endif
  2379. return s;
  2380. #endif
  2381. #endif
  2382. }
  2383. bool ReadWholeFile(std::vector<unsigned char> *out, std::string *err,
  2384. const std::string &filepath, void *) {
  2385. #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS
  2386. if (asset_manager) {
  2387. AAsset *asset = AAssetManager_open(asset_manager, filepath.c_str(),
  2388. AASSET_MODE_STREAMING);
  2389. if (!asset) {
  2390. if (err) {
  2391. (*err) += "File open error : " + filepath + "\n";
  2392. }
  2393. return false;
  2394. }
  2395. size_t size = AAsset_getLength(asset);
  2396. if (size == 0) {
  2397. if (err) {
  2398. (*err) += "Invalid file size : " + filepath +
  2399. " (does the path point to a directory?)";
  2400. }
  2401. return false;
  2402. }
  2403. out->resize(size);
  2404. AAsset_read(asset, reinterpret_cast<char *>(&out->at(0)), size);
  2405. AAsset_close(asset);
  2406. return true;
  2407. } else {
  2408. if (err) {
  2409. (*err) += "No asset manager specified : " + filepath + "\n";
  2410. }
  2411. return false;
  2412. }
  2413. #else
  2414. #ifdef _WIN32
  2415. #if defined(__GLIBCXX__) // mingw
  2416. int file_descriptor =
  2417. _wopen(UTF8ToWchar(filepath).c_str(), _O_RDONLY | _O_BINARY);
  2418. __gnu_cxx::stdio_filebuf<char> wfile_buf(file_descriptor, std::ios_base::in);
  2419. std::istream f(&wfile_buf);
  2420. #elif defined(_MSC_VER) || defined(_LIBCPP_VERSION)
  2421. // For libcxx, assume _LIBCPP_HAS_OPEN_WITH_WCHAR is defined to accept
  2422. // `wchar_t *`
  2423. std::ifstream f(UTF8ToWchar(filepath).c_str(), std::ifstream::binary);
  2424. #else
  2425. // Unknown compiler/runtime
  2426. std::ifstream f(filepath.c_str(), std::ifstream::binary);
  2427. #endif
  2428. #else
  2429. std::ifstream f(filepath.c_str(), std::ifstream::binary);
  2430. #endif
  2431. if (!f) {
  2432. if (err) {
  2433. (*err) += "File open error : " + filepath + "\n";
  2434. }
  2435. return false;
  2436. }
  2437. f.seekg(0, f.end);
  2438. size_t sz = static_cast<size_t>(f.tellg());
  2439. f.seekg(0, f.beg);
  2440. if (int64_t(sz) < 0) {
  2441. if (err) {
  2442. (*err) += "Invalid file size : " + filepath +
  2443. " (does the path point to a directory?)";
  2444. }
  2445. return false;
  2446. } else if (sz == 0) {
  2447. if (err) {
  2448. (*err) += "File is empty : " + filepath + "\n";
  2449. }
  2450. return false;
  2451. }
  2452. out->resize(sz);
  2453. f.read(reinterpret_cast<char *>(&out->at(0)),
  2454. static_cast<std::streamsize>(sz));
  2455. return true;
  2456. #endif
  2457. }
  2458. bool WriteWholeFile(std::string *err, const std::string &filepath,
  2459. const std::vector<unsigned char> &contents, void *) {
  2460. #ifdef _WIN32
  2461. #if defined(__GLIBCXX__) // mingw
  2462. int file_descriptor = _wopen(UTF8ToWchar(filepath).c_str(),
  2463. _O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY);
  2464. __gnu_cxx::stdio_filebuf<char> wfile_buf(
  2465. file_descriptor, std::ios_base::out | std::ios_base::binary);
  2466. std::ostream f(&wfile_buf);
  2467. #elif defined(_MSC_VER)
  2468. std::ofstream f(UTF8ToWchar(filepath).c_str(), std::ofstream::binary);
  2469. #else // clang?
  2470. std::ofstream f(filepath.c_str(), std::ofstream::binary);
  2471. #endif
  2472. #else
  2473. std::ofstream f(filepath.c_str(), std::ofstream::binary);
  2474. #endif
  2475. if (!f) {
  2476. if (err) {
  2477. (*err) += "File open error for writing : " + filepath + "\n";
  2478. }
  2479. return false;
  2480. }
  2481. f.write(reinterpret_cast<const char *>(&contents.at(0)),
  2482. static_cast<std::streamsize>(contents.size()));
  2483. if (!f) {
  2484. if (err) {
  2485. (*err) += "File write error: " + filepath + "\n";
  2486. }
  2487. return false;
  2488. }
  2489. return true;
  2490. }
  2491. #endif // TINYGLTF_NO_FS
  2492. static std::string MimeToExt(const std::string &mimeType) {
  2493. if (mimeType == "image/jpeg") {
  2494. return "jpg";
  2495. } else if (mimeType == "image/png") {
  2496. return "png";
  2497. } else if (mimeType == "image/bmp") {
  2498. return "bmp";
  2499. } else if (mimeType == "image/gif") {
  2500. return "gif";
  2501. }
  2502. return "";
  2503. }
  2504. static bool UpdateImageObject(const Image &image, std::string &baseDir,
  2505. int index, bool embedImages,
  2506. const URICallbacks *uri_cb,
  2507. WriteImageDataFunction *WriteImageData,
  2508. void *user_data, std::string *out_uri) {
  2509. std::string filename;
  2510. std::string ext;
  2511. // If image has uri, use it as a filename
  2512. if (image.uri.size()) {
  2513. std::string decoded_uri;
  2514. if (!uri_cb->decode(image.uri, &decoded_uri, uri_cb->user_data)) {
  2515. // A decode failure results in a failure to write the gltf.
  2516. return false;
  2517. }
  2518. filename = GetBaseFilename(decoded_uri);
  2519. ext = GetFilePathExtension(filename);
  2520. } else if (image.bufferView != -1) {
  2521. // If there's no URI and the data exists in a buffer,
  2522. // don't change properties or write images
  2523. } else if (image.name.size()) {
  2524. ext = MimeToExt(image.mimeType);
  2525. // Otherwise use name as filename
  2526. filename = image.name + "." + ext;
  2527. } else {
  2528. ext = MimeToExt(image.mimeType);
  2529. // Fallback to index of image as filename
  2530. filename = std::to_string(index) + "." + ext;
  2531. }
  2532. // If callback is set and image data exists, modify image data object. If
  2533. // image data does not exist, this is not considered a failure and the
  2534. // original uri should be maintained.
  2535. bool imageWritten = false;
  2536. if (*WriteImageData != nullptr && !filename.empty() && !image.image.empty()) {
  2537. imageWritten = (*WriteImageData)(&baseDir, &filename, &image, embedImages,
  2538. uri_cb, out_uri, user_data);
  2539. if (!imageWritten) {
  2540. return false;
  2541. }
  2542. }
  2543. // Use the original uri if the image was not written.
  2544. if (!imageWritten) {
  2545. *out_uri = image.uri;
  2546. }
  2547. return true;
  2548. }
  2549. bool IsDataURI(const std::string &in) {
  2550. std::string header = "data:application/octet-stream;base64,";
  2551. if (in.find(header) == 0) {
  2552. return true;
  2553. }
  2554. header = "data:image/jpeg;base64,";
  2555. if (in.find(header) == 0) {
  2556. return true;
  2557. }
  2558. header = "data:image/png;base64,";
  2559. if (in.find(header) == 0) {
  2560. return true;
  2561. }
  2562. header = "data:image/bmp;base64,";
  2563. if (in.find(header) == 0) {
  2564. return true;
  2565. }
  2566. header = "data:image/gif;base64,";
  2567. if (in.find(header) == 0) {
  2568. return true;
  2569. }
  2570. header = "data:text/plain;base64,";
  2571. if (in.find(header) == 0) {
  2572. return true;
  2573. }
  2574. header = "data:application/gltf-buffer;base64,";
  2575. if (in.find(header) == 0) {
  2576. return true;
  2577. }
  2578. return false;
  2579. }
  2580. bool DecodeDataURI(std::vector<unsigned char> *out, std::string &mime_type,
  2581. const std::string &in, size_t reqBytes, bool checkSize) {
  2582. std::string header = "data:application/octet-stream;base64,";
  2583. std::string data;
  2584. if (in.find(header) == 0) {
  2585. data = base64_decode(in.substr(header.size())); // cut mime string.
  2586. }
  2587. if (data.empty()) {
  2588. header = "data:image/jpeg;base64,";
  2589. if (in.find(header) == 0) {
  2590. mime_type = "image/jpeg";
  2591. data = base64_decode(in.substr(header.size())); // cut mime string.
  2592. }
  2593. }
  2594. if (data.empty()) {
  2595. header = "data:image/png;base64,";
  2596. if (in.find(header) == 0) {
  2597. mime_type = "image/png";
  2598. data = base64_decode(in.substr(header.size())); // cut mime string.
  2599. }
  2600. }
  2601. if (data.empty()) {
  2602. header = "data:image/bmp;base64,";
  2603. if (in.find(header) == 0) {
  2604. mime_type = "image/bmp";
  2605. data = base64_decode(in.substr(header.size())); // cut mime string.
  2606. }
  2607. }
  2608. if (data.empty()) {
  2609. header = "data:image/gif;base64,";
  2610. if (in.find(header) == 0) {
  2611. mime_type = "image/gif";
  2612. data = base64_decode(in.substr(header.size())); // cut mime string.
  2613. }
  2614. }
  2615. if (data.empty()) {
  2616. header = "data:text/plain;base64,";
  2617. if (in.find(header) == 0) {
  2618. mime_type = "text/plain";
  2619. data = base64_decode(in.substr(header.size()));
  2620. }
  2621. }
  2622. if (data.empty()) {
  2623. header = "data:application/gltf-buffer;base64,";
  2624. if (in.find(header) == 0) {
  2625. data = base64_decode(in.substr(header.size()));
  2626. }
  2627. }
  2628. // TODO(syoyo): Allow empty buffer? #229
  2629. if (data.empty()) {
  2630. return false;
  2631. }
  2632. if (checkSize) {
  2633. if (data.size() != reqBytes) {
  2634. return false;
  2635. }
  2636. out->resize(reqBytes);
  2637. } else {
  2638. out->resize(data.size());
  2639. }
  2640. std::copy(data.begin(), data.end(), out->begin());
  2641. return true;
  2642. }
  2643. namespace detail {
  2644. bool GetInt(const detail::json &o, int &val) {
  2645. #ifdef TINYGLTF_USE_RAPIDJSON
  2646. if (!o.IsDouble()) {
  2647. if (o.IsInt()) {
  2648. val = o.GetInt();
  2649. return true;
  2650. } else if (o.IsUint()) {
  2651. val = static_cast<int>(o.GetUint());
  2652. return true;
  2653. } else if (o.IsInt64()) {
  2654. val = static_cast<int>(o.GetInt64());
  2655. return true;
  2656. } else if (o.IsUint64()) {
  2657. val = static_cast<int>(o.GetUint64());
  2658. return true;
  2659. }
  2660. }
  2661. return false;
  2662. #else
  2663. auto type = o.type();
  2664. if ((type == detail::json::value_t::number_integer) ||
  2665. (type == detail::json::value_t::number_unsigned)) {
  2666. val = static_cast<int>(o.get<int64_t>());
  2667. return true;
  2668. }
  2669. return false;
  2670. #endif
  2671. }
  2672. #ifdef TINYGLTF_USE_RAPIDJSON
  2673. bool GetDouble(const detail::json &o, double &val) {
  2674. if (o.IsDouble()) {
  2675. val = o.GetDouble();
  2676. return true;
  2677. }
  2678. return false;
  2679. }
  2680. #endif
  2681. bool GetNumber(const detail::json &o, double &val) {
  2682. #ifdef TINYGLTF_USE_RAPIDJSON
  2683. if (o.IsNumber()) {
  2684. val = o.GetDouble();
  2685. return true;
  2686. }
  2687. return false;
  2688. #else
  2689. if (o.is_number()) {
  2690. val = o.get<double>();
  2691. return true;
  2692. }
  2693. return false;
  2694. #endif
  2695. }
  2696. bool GetString(const detail::json &o, std::string &val) {
  2697. #ifdef TINYGLTF_USE_RAPIDJSON
  2698. if (o.IsString()) {
  2699. val = o.GetString();
  2700. return true;
  2701. }
  2702. return false;
  2703. #else
  2704. if (o.type() == detail::json::value_t::string) {
  2705. val = o.get<std::string>();
  2706. return true;
  2707. }
  2708. return false;
  2709. #endif
  2710. }
  2711. bool IsArray(const detail::json &o) {
  2712. #ifdef TINYGLTF_USE_RAPIDJSON
  2713. return o.IsArray();
  2714. #else
  2715. return o.is_array();
  2716. #endif
  2717. }
  2718. detail::json_const_array_iterator ArrayBegin(const detail::json &o) {
  2719. #ifdef TINYGLTF_USE_RAPIDJSON
  2720. return o.Begin();
  2721. #else
  2722. return o.begin();
  2723. #endif
  2724. }
  2725. detail::json_const_array_iterator ArrayEnd(const detail::json &o) {
  2726. #ifdef TINYGLTF_USE_RAPIDJSON
  2727. return o.End();
  2728. #else
  2729. return o.end();
  2730. #endif
  2731. }
  2732. bool IsObject(const detail::json &o) {
  2733. #ifdef TINYGLTF_USE_RAPIDJSON
  2734. return o.IsObject();
  2735. #else
  2736. return o.is_object();
  2737. #endif
  2738. }
  2739. detail::json_const_iterator ObjectBegin(const detail::json &o) {
  2740. #ifdef TINYGLTF_USE_RAPIDJSON
  2741. return o.MemberBegin();
  2742. #else
  2743. return o.begin();
  2744. #endif
  2745. }
  2746. detail::json_const_iterator ObjectEnd(const detail::json &o) {
  2747. #ifdef TINYGLTF_USE_RAPIDJSON
  2748. return o.MemberEnd();
  2749. #else
  2750. return o.end();
  2751. #endif
  2752. }
  2753. // Making this a const char* results in a pointer to a temporary when
  2754. // TINYGLTF_USE_RAPIDJSON is off.
  2755. std::string GetKey(detail::json_const_iterator &it) {
  2756. #ifdef TINYGLTF_USE_RAPIDJSON
  2757. return it->name.GetString();
  2758. #else
  2759. return it.key().c_str();
  2760. #endif
  2761. }
  2762. bool FindMember(const detail::json &o, const char *member, detail::json_const_iterator &it) {
  2763. #ifdef TINYGLTF_USE_RAPIDJSON
  2764. if (!o.IsObject()) {
  2765. return false;
  2766. }
  2767. it = o.FindMember(member);
  2768. return it != o.MemberEnd();
  2769. #else
  2770. it = o.find(member);
  2771. return it != o.end();
  2772. #endif
  2773. }
  2774. const detail::json &GetValue(detail::json_const_iterator &it) {
  2775. #ifdef TINYGLTF_USE_RAPIDJSON
  2776. return it->value;
  2777. #else
  2778. return it.value();
  2779. #endif
  2780. }
  2781. std::string JsonToString(const detail::json &o, int spacing = -1) {
  2782. #ifdef TINYGLTF_USE_RAPIDJSON
  2783. using namespace rapidjson;
  2784. StringBuffer buffer;
  2785. if (spacing == -1) {
  2786. Writer<StringBuffer> writer(buffer);
  2787. // TODO: Better error handling.
  2788. // https://github.com/syoyo/tinygltf/issues/332
  2789. if (!o.Accept(writer)) {
  2790. return "tiny_gltf::JsonToString() failed rapidjson conversion";
  2791. }
  2792. } else {
  2793. PrettyWriter<StringBuffer> writer(buffer);
  2794. writer.SetIndent(' ', uint32_t(spacing));
  2795. if (!o.Accept(writer)) {
  2796. return "tiny_gltf::JsonToString() failed rapidjson conversion";
  2797. }
  2798. }
  2799. return buffer.GetString();
  2800. #else
  2801. return o.dump(spacing);
  2802. #endif
  2803. }
  2804. } // namespace
  2805. static bool ParseJsonAsValue(Value *ret, const detail::json &o) {
  2806. Value val{};
  2807. #ifdef TINYGLTF_USE_RAPIDJSON
  2808. using rapidjson::Type;
  2809. switch (o.GetType()) {
  2810. case Type::kObjectType: {
  2811. Value::Object value_object;
  2812. for (auto it = o.MemberBegin(); it != o.MemberEnd(); ++it) {
  2813. Value entry;
  2814. ParseJsonAsValue(&entry, it->value);
  2815. if (entry.Type() != NULL_TYPE)
  2816. value_object.emplace(detail::GetKey(it), std::move(entry));
  2817. }
  2818. if (value_object.size() > 0) val = Value(std::move(value_object));
  2819. } break;
  2820. case Type::kArrayType: {
  2821. Value::Array value_array;
  2822. value_array.reserve(o.Size());
  2823. for (auto it = o.Begin(); it != o.End(); ++it) {
  2824. Value entry;
  2825. ParseJsonAsValue(&entry, *it);
  2826. if (entry.Type() != NULL_TYPE)
  2827. value_array.emplace_back(std::move(entry));
  2828. }
  2829. if (value_array.size() > 0) val = Value(std::move(value_array));
  2830. } break;
  2831. case Type::kStringType:
  2832. val = Value(std::string(o.GetString()));
  2833. break;
  2834. case Type::kFalseType:
  2835. case Type::kTrueType:
  2836. val = Value(o.GetBool());
  2837. break;
  2838. case Type::kNumberType:
  2839. if (!o.IsDouble()) {
  2840. int i = 0;
  2841. detail::GetInt(o, i);
  2842. val = Value(i);
  2843. } else {
  2844. double d = 0.0;
  2845. detail::GetDouble(o, d);
  2846. val = Value(d);
  2847. }
  2848. break;
  2849. case Type::kNullType:
  2850. break;
  2851. // all types are covered, so no `case default`
  2852. }
  2853. #else
  2854. switch (o.type()) {
  2855. case detail::json::value_t::object: {
  2856. Value::Object value_object;
  2857. for (auto it = o.begin(); it != o.end(); it++) {
  2858. Value entry;
  2859. ParseJsonAsValue(&entry, it.value());
  2860. if (entry.Type() != NULL_TYPE)
  2861. value_object.emplace(it.key(), std::move(entry));
  2862. }
  2863. if (value_object.size() > 0) val = Value(std::move(value_object));
  2864. } break;
  2865. case detail::json::value_t::array: {
  2866. Value::Array value_array;
  2867. value_array.reserve(o.size());
  2868. for (auto it = o.begin(); it != o.end(); it++) {
  2869. Value entry;
  2870. ParseJsonAsValue(&entry, it.value());
  2871. if (entry.Type() != NULL_TYPE)
  2872. value_array.emplace_back(std::move(entry));
  2873. }
  2874. if (value_array.size() > 0) val = Value(std::move(value_array));
  2875. } break;
  2876. case detail::json::value_t::string:
  2877. val = Value(o.get<std::string>());
  2878. break;
  2879. case detail::json::value_t::boolean:
  2880. val = Value(o.get<bool>());
  2881. break;
  2882. case detail::json::value_t::number_integer:
  2883. case detail::json::value_t::number_unsigned:
  2884. val = Value(static_cast<int>(o.get<int64_t>()));
  2885. break;
  2886. case detail::json::value_t::number_float:
  2887. val = Value(o.get<double>());
  2888. break;
  2889. case detail::json::value_t::null:
  2890. case detail::json::value_t::discarded:
  2891. case detail::json::value_t::binary:
  2892. // default:
  2893. break;
  2894. }
  2895. #endif
  2896. const bool isNotNull = val.Type() != NULL_TYPE;
  2897. if (ret) *ret = std::move(val);
  2898. return isNotNull;
  2899. }
  2900. static bool ParseExtrasProperty(Value *ret, const detail::json &o) {
  2901. detail::json_const_iterator it;
  2902. if (!detail::FindMember(o, "extras", it)) {
  2903. return false;
  2904. }
  2905. return ParseJsonAsValue(ret, detail::GetValue(it));
  2906. }
  2907. static bool ParseBooleanProperty(bool *ret, std::string *err, const detail::json &o,
  2908. const std::string &property,
  2909. const bool required,
  2910. const std::string &parent_node = "") {
  2911. detail::json_const_iterator it;
  2912. if (!detail::FindMember(o, property.c_str(), it)) {
  2913. if (required) {
  2914. if (err) {
  2915. (*err) += "'" + property + "' property is missing";
  2916. if (!parent_node.empty()) {
  2917. (*err) += " in " + parent_node;
  2918. }
  2919. (*err) += ".\n";
  2920. }
  2921. }
  2922. return false;
  2923. }
  2924. auto &value = detail::GetValue(it);
  2925. bool isBoolean;
  2926. bool boolValue = false;
  2927. #ifdef TINYGLTF_USE_RAPIDJSON
  2928. isBoolean = value.IsBool();
  2929. if (isBoolean) {
  2930. boolValue = value.GetBool();
  2931. }
  2932. #else
  2933. isBoolean = value.is_boolean();
  2934. if (isBoolean) {
  2935. boolValue = value.get<bool>();
  2936. }
  2937. #endif
  2938. if (!isBoolean) {
  2939. if (required) {
  2940. if (err) {
  2941. (*err) += "'" + property + "' property is not a bool type.\n";
  2942. }
  2943. }
  2944. return false;
  2945. }
  2946. if (ret) {
  2947. (*ret) = boolValue;
  2948. }
  2949. return true;
  2950. }
  2951. static bool ParseIntegerProperty(int *ret, std::string *err, const detail::json &o,
  2952. const std::string &property,
  2953. const bool required,
  2954. const std::string &parent_node = "") {
  2955. detail::json_const_iterator it;
  2956. if (!detail::FindMember(o, property.c_str(), it)) {
  2957. if (required) {
  2958. if (err) {
  2959. (*err) += "'" + property + "' property is missing";
  2960. if (!parent_node.empty()) {
  2961. (*err) += " in " + parent_node;
  2962. }
  2963. (*err) += ".\n";
  2964. }
  2965. }
  2966. return false;
  2967. }
  2968. int intValue;
  2969. bool isInt = detail::GetInt(detail::GetValue(it), intValue);
  2970. if (!isInt) {
  2971. if (required) {
  2972. if (err) {
  2973. (*err) += "'" + property + "' property is not an integer type.\n";
  2974. }
  2975. }
  2976. return false;
  2977. }
  2978. if (ret) {
  2979. (*ret) = intValue;
  2980. }
  2981. return true;
  2982. }
  2983. static bool ParseUnsignedProperty(size_t *ret, std::string *err, const detail::json &o,
  2984. const std::string &property,
  2985. const bool required,
  2986. const std::string &parent_node = "") {
  2987. detail::json_const_iterator it;
  2988. if (!detail::FindMember(o, property.c_str(), it)) {
  2989. if (required) {
  2990. if (err) {
  2991. (*err) += "'" + property + "' property is missing";
  2992. if (!parent_node.empty()) {
  2993. (*err) += " in " + parent_node;
  2994. }
  2995. (*err) += ".\n";
  2996. }
  2997. }
  2998. return false;
  2999. }
  3000. auto &value = detail::GetValue(it);
  3001. size_t uValue = 0;
  3002. bool isUValue;
  3003. #ifdef TINYGLTF_USE_RAPIDJSON
  3004. isUValue = false;
  3005. if (value.IsUint()) {
  3006. uValue = value.GetUint();
  3007. isUValue = true;
  3008. } else if (value.IsUint64()) {
  3009. uValue = value.GetUint64();
  3010. isUValue = true;
  3011. }
  3012. #else
  3013. isUValue = value.is_number_unsigned();
  3014. if (isUValue) {
  3015. uValue = value.get<size_t>();
  3016. }
  3017. #endif
  3018. if (!isUValue) {
  3019. if (required) {
  3020. if (err) {
  3021. (*err) += "'" + property + "' property is not a positive integer.\n";
  3022. }
  3023. }
  3024. return false;
  3025. }
  3026. if (ret) {
  3027. (*ret) = uValue;
  3028. }
  3029. return true;
  3030. }
  3031. static bool ParseNumberProperty(double *ret, std::string *err, const detail::json &o,
  3032. const std::string &property,
  3033. const bool required,
  3034. const std::string &parent_node = "") {
  3035. detail::json_const_iterator it;
  3036. if (!detail::FindMember(o, property.c_str(), it)) {
  3037. if (required) {
  3038. if (err) {
  3039. (*err) += "'" + property + "' property is missing";
  3040. if (!parent_node.empty()) {
  3041. (*err) += " in " + parent_node;
  3042. }
  3043. (*err) += ".\n";
  3044. }
  3045. }
  3046. return false;
  3047. }
  3048. double numberValue;
  3049. bool isNumber = detail::GetNumber(detail::GetValue(it), numberValue);
  3050. if (!isNumber) {
  3051. if (required) {
  3052. if (err) {
  3053. (*err) += "'" + property + "' property is not a number type.\n";
  3054. }
  3055. }
  3056. return false;
  3057. }
  3058. if (ret) {
  3059. (*ret) = numberValue;
  3060. }
  3061. return true;
  3062. }
  3063. static bool ParseNumberArrayProperty(std::vector<double> *ret, std::string *err,
  3064. const detail::json &o, const std::string &property,
  3065. bool required,
  3066. const std::string &parent_node = "") {
  3067. detail::json_const_iterator it;
  3068. if (!detail::FindMember(o, property.c_str(), it)) {
  3069. if (required) {
  3070. if (err) {
  3071. (*err) += "'" + property + "' property is missing";
  3072. if (!parent_node.empty()) {
  3073. (*err) += " in " + parent_node;
  3074. }
  3075. (*err) += ".\n";
  3076. }
  3077. }
  3078. return false;
  3079. }
  3080. if (!detail::IsArray(detail::GetValue(it))) {
  3081. if (required) {
  3082. if (err) {
  3083. (*err) += "'" + property + "' property is not an array";
  3084. if (!parent_node.empty()) {
  3085. (*err) += " in " + parent_node;
  3086. }
  3087. (*err) += ".\n";
  3088. }
  3089. }
  3090. return false;
  3091. }
  3092. ret->clear();
  3093. auto end = detail::ArrayEnd(detail::GetValue(it));
  3094. for (auto i = detail::ArrayBegin(detail::GetValue(it)); i != end; ++i) {
  3095. double numberValue;
  3096. const bool isNumber = detail::GetNumber(*i, numberValue);
  3097. if (!isNumber) {
  3098. if (required) {
  3099. if (err) {
  3100. (*err) += "'" + property + "' property is not a number.\n";
  3101. if (!parent_node.empty()) {
  3102. (*err) += " in " + parent_node;
  3103. }
  3104. (*err) += ".\n";
  3105. }
  3106. }
  3107. return false;
  3108. }
  3109. ret->push_back(numberValue);
  3110. }
  3111. return true;
  3112. }
  3113. static bool ParseIntegerArrayProperty(std::vector<int> *ret, std::string *err,
  3114. const detail::json &o,
  3115. const std::string &property,
  3116. bool required,
  3117. const std::string &parent_node = "") {
  3118. detail::json_const_iterator it;
  3119. if (!detail::FindMember(o, property.c_str(), it)) {
  3120. if (required) {
  3121. if (err) {
  3122. (*err) += "'" + property + "' property is missing";
  3123. if (!parent_node.empty()) {
  3124. (*err) += " in " + parent_node;
  3125. }
  3126. (*err) += ".\n";
  3127. }
  3128. }
  3129. return false;
  3130. }
  3131. if (!detail::IsArray(detail::GetValue(it))) {
  3132. if (required) {
  3133. if (err) {
  3134. (*err) += "'" + property + "' property is not an array";
  3135. if (!parent_node.empty()) {
  3136. (*err) += " in " + parent_node;
  3137. }
  3138. (*err) += ".\n";
  3139. }
  3140. }
  3141. return false;
  3142. }
  3143. ret->clear();
  3144. auto end = detail::ArrayEnd(detail::GetValue(it));
  3145. for (auto i = detail::ArrayBegin(detail::GetValue(it)); i != end; ++i) {
  3146. int numberValue;
  3147. bool isNumber = detail::GetInt(*i, numberValue);
  3148. if (!isNumber) {
  3149. if (required) {
  3150. if (err) {
  3151. (*err) += "'" + property + "' property is not an integer type.\n";
  3152. if (!parent_node.empty()) {
  3153. (*err) += " in " + parent_node;
  3154. }
  3155. (*err) += ".\n";
  3156. }
  3157. }
  3158. return false;
  3159. }
  3160. ret->push_back(numberValue);
  3161. }
  3162. return true;
  3163. }
  3164. static bool ParseStringProperty(
  3165. std::string *ret, std::string *err, const detail::json &o,
  3166. const std::string &property, bool required,
  3167. const std::string &parent_node = std::string()) {
  3168. detail::json_const_iterator it;
  3169. if (!detail::FindMember(o, property.c_str(), it)) {
  3170. if (required) {
  3171. if (err) {
  3172. (*err) += "'" + property + "' property is missing";
  3173. if (parent_node.empty()) {
  3174. (*err) += ".\n";
  3175. } else {
  3176. (*err) += " in `" + parent_node + "'.\n";
  3177. }
  3178. }
  3179. }
  3180. return false;
  3181. }
  3182. std::string strValue;
  3183. if (!detail::GetString(detail::GetValue(it), strValue)) {
  3184. if (required) {
  3185. if (err) {
  3186. (*err) += "'" + property + "' property is not a string type.\n";
  3187. }
  3188. }
  3189. return false;
  3190. }
  3191. if (ret) {
  3192. (*ret) = std::move(strValue);
  3193. }
  3194. return true;
  3195. }
  3196. static bool ParseStringIntegerProperty(std::map<std::string, int> *ret,
  3197. std::string *err, const detail::json &o,
  3198. const std::string &property,
  3199. bool required,
  3200. const std::string &parent = "") {
  3201. detail::json_const_iterator it;
  3202. if (!detail::FindMember(o, property.c_str(), it)) {
  3203. if (required) {
  3204. if (err) {
  3205. if (!parent.empty()) {
  3206. (*err) +=
  3207. "'" + property + "' property is missing in " + parent + ".\n";
  3208. } else {
  3209. (*err) += "'" + property + "' property is missing.\n";
  3210. }
  3211. }
  3212. }
  3213. return false;
  3214. }
  3215. const detail::json &dict = detail::GetValue(it);
  3216. // Make sure we are dealing with an object / dictionary.
  3217. if (!detail::IsObject(dict)) {
  3218. if (required) {
  3219. if (err) {
  3220. (*err) += "'" + property + "' property is not an object.\n";
  3221. }
  3222. }
  3223. return false;
  3224. }
  3225. ret->clear();
  3226. detail::json_const_iterator dictIt(detail::ObjectBegin(dict));
  3227. detail::json_const_iterator dictItEnd(detail::ObjectEnd(dict));
  3228. for (; dictIt != dictItEnd; ++dictIt) {
  3229. int intVal;
  3230. if (!detail::GetInt(detail::GetValue(dictIt), intVal)) {
  3231. if (required) {
  3232. if (err) {
  3233. (*err) += "'" + property + "' value is not an integer type.\n";
  3234. }
  3235. }
  3236. return false;
  3237. }
  3238. // Insert into the list.
  3239. (*ret)[detail::GetKey(dictIt)] = intVal;
  3240. }
  3241. return true;
  3242. }
  3243. static bool ParseJSONProperty(std::map<std::string, double> *ret,
  3244. std::string *err, const detail::json &o,
  3245. const std::string &property, bool required) {
  3246. detail::json_const_iterator it;
  3247. if (!detail::FindMember(o, property.c_str(), it)) {
  3248. if (required) {
  3249. if (err) {
  3250. (*err) += "'" + property + "' property is missing. \n'";
  3251. }
  3252. }
  3253. return false;
  3254. }
  3255. const detail::json &obj = detail::GetValue(it);
  3256. if (!detail::IsObject(obj)) {
  3257. if (required) {
  3258. if (err) {
  3259. (*err) += "'" + property + "' property is not a JSON object.\n";
  3260. }
  3261. }
  3262. return false;
  3263. }
  3264. ret->clear();
  3265. detail::json_const_iterator it2(detail::ObjectBegin(obj));
  3266. detail::json_const_iterator itEnd(detail::ObjectEnd(obj));
  3267. for (; it2 != itEnd; ++it2) {
  3268. double numVal;
  3269. if (detail::GetNumber(detail::GetValue(it2), numVal))
  3270. ret->emplace(std::string(detail::GetKey(it2)), numVal);
  3271. }
  3272. return true;
  3273. }
  3274. static bool ParseParameterProperty(Parameter *param, std::string *err,
  3275. const detail::json &o, const std::string &prop,
  3276. bool required) {
  3277. // A parameter value can either be a string or an array of either a boolean or
  3278. // a number. Booleans of any kind aren't supported here. Granted, it
  3279. // complicates the Parameter structure and breaks it semantically in the sense
  3280. // that the client probably works off the assumption that if the string is
  3281. // empty the vector is used, etc. Would a tagged union work?
  3282. if (ParseStringProperty(&param->string_value, err, o, prop, false)) {
  3283. // Found string property.
  3284. return true;
  3285. } else if (ParseNumberArrayProperty(&param->number_array, err, o, prop,
  3286. false)) {
  3287. // Found a number array.
  3288. return true;
  3289. } else if (ParseNumberProperty(&param->number_value, err, o, prop, false)) {
  3290. param->has_number_value = true;
  3291. return true;
  3292. } else if (ParseJSONProperty(&param->json_double_value, err, o, prop,
  3293. false)) {
  3294. return true;
  3295. } else if (ParseBooleanProperty(&param->bool_value, err, o, prop, false)) {
  3296. return true;
  3297. } else {
  3298. if (required) {
  3299. if (err) {
  3300. (*err) += "parameter must be a string or number / number array.\n";
  3301. }
  3302. }
  3303. return false;
  3304. }
  3305. }
  3306. static bool ParseExtensionsProperty(ExtensionMap *ret, std::string *err,
  3307. const detail::json &o) {
  3308. (void)err;
  3309. detail::json_const_iterator it;
  3310. if (!detail::FindMember(o, "extensions", it)) {
  3311. return false;
  3312. }
  3313. auto &obj = detail::GetValue(it);
  3314. if (!detail::IsObject(obj)) {
  3315. return false;
  3316. }
  3317. ExtensionMap extensions;
  3318. detail::json_const_iterator extIt = detail::ObjectBegin(obj); // it.value().begin();
  3319. detail::json_const_iterator extEnd = detail::ObjectEnd(obj);
  3320. for (; extIt != extEnd; ++extIt) {
  3321. auto &itObj = detail::GetValue(extIt);
  3322. if (!detail::IsObject(itObj)) continue;
  3323. std::string key(detail::GetKey(extIt));
  3324. if (!ParseJsonAsValue(&extensions[key], itObj)) {
  3325. if (!key.empty()) {
  3326. // create empty object so that an extension object is still of type
  3327. // object
  3328. extensions[key] = Value{Value::Object{}};
  3329. }
  3330. }
  3331. }
  3332. if (ret) {
  3333. (*ret) = std::move(extensions);
  3334. }
  3335. return true;
  3336. }
  3337. static bool ParseAsset(Asset *asset, std::string *err, const detail::json &o,
  3338. bool store_original_json_for_extras_and_extensions) {
  3339. ParseStringProperty(&asset->version, err, o, "version", true, "Asset");
  3340. ParseStringProperty(&asset->generator, err, o, "generator", false, "Asset");
  3341. ParseStringProperty(&asset->minVersion, err, o, "minVersion", false, "Asset");
  3342. ParseStringProperty(&asset->copyright, err, o, "copyright", false, "Asset");
  3343. ParseExtensionsProperty(&asset->extensions, err, o);
  3344. // Unity exporter version is added as extra here
  3345. ParseExtrasProperty(&(asset->extras), o);
  3346. if (store_original_json_for_extras_and_extensions) {
  3347. {
  3348. detail::json_const_iterator it;
  3349. if (detail::FindMember(o, "extensions", it)) {
  3350. asset->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  3351. }
  3352. }
  3353. {
  3354. detail::json_const_iterator it;
  3355. if (detail::FindMember(o, "extras", it)) {
  3356. asset->extras_json_string = detail::JsonToString(detail::GetValue(it));
  3357. }
  3358. }
  3359. }
  3360. return true;
  3361. }
  3362. static bool ParseImage(Image *image, const int image_idx, std::string *err,
  3363. std::string *warn, const detail::json &o,
  3364. bool store_original_json_for_extras_and_extensions,
  3365. const std::string &basedir, FsCallbacks *fs,
  3366. const URICallbacks *uri_cb,
  3367. LoadImageDataFunction *LoadImageData = nullptr,
  3368. void *load_image_user_data = nullptr) {
  3369. // A glTF image must either reference a bufferView or an image uri
  3370. // schema says oneOf [`bufferView`, `uri`]
  3371. // TODO(syoyo): Check the type of each parameters.
  3372. detail::json_const_iterator it;
  3373. bool hasBufferView = detail::FindMember(o, "bufferView", it);
  3374. bool hasURI = detail::FindMember(o, "uri", it);
  3375. ParseStringProperty(&image->name, err, o, "name", false);
  3376. if (hasBufferView && hasURI) {
  3377. // Should not both defined.
  3378. if (err) {
  3379. (*err) +=
  3380. "Only one of `bufferView` or `uri` should be defined, but both are "
  3381. "defined for image[" +
  3382. std::to_string(image_idx) + "] name = \"" + image->name + "\"\n";
  3383. }
  3384. return false;
  3385. }
  3386. if (!hasBufferView && !hasURI) {
  3387. if (err) {
  3388. (*err) += "Neither required `bufferView` nor `uri` defined for image[" +
  3389. std::to_string(image_idx) + "] name = \"" + image->name +
  3390. "\"\n";
  3391. }
  3392. return false;
  3393. }
  3394. ParseExtensionsProperty(&image->extensions, err, o);
  3395. ParseExtrasProperty(&image->extras, o);
  3396. if (store_original_json_for_extras_and_extensions) {
  3397. {
  3398. detail::json_const_iterator eit;
  3399. if (detail::FindMember(o, "extensions", eit)) {
  3400. image->extensions_json_string = detail::JsonToString(detail::GetValue(eit));
  3401. }
  3402. }
  3403. {
  3404. detail::json_const_iterator eit;
  3405. if (detail::FindMember(o, "extras", eit)) {
  3406. image->extras_json_string = detail::JsonToString(detail::GetValue(eit));
  3407. }
  3408. }
  3409. }
  3410. if (hasBufferView) {
  3411. int bufferView = -1;
  3412. if (!ParseIntegerProperty(&bufferView, err, o, "bufferView", true)) {
  3413. if (err) {
  3414. (*err) += "Failed to parse `bufferView` for image[" +
  3415. std::to_string(image_idx) + "] name = \"" + image->name +
  3416. "\"\n";
  3417. }
  3418. return false;
  3419. }
  3420. std::string mime_type;
  3421. ParseStringProperty(&mime_type, err, o, "mimeType", false);
  3422. int width = 0;
  3423. ParseIntegerProperty(&width, err, o, "width", false);
  3424. int height = 0;
  3425. ParseIntegerProperty(&height, err, o, "height", false);
  3426. // Just only save some information here. Loading actual image data from
  3427. // bufferView is done after this `ParseImage` function.
  3428. image->bufferView = bufferView;
  3429. image->mimeType = mime_type;
  3430. image->width = width;
  3431. image->height = height;
  3432. return true;
  3433. }
  3434. // Parse URI & Load image data.
  3435. std::string uri;
  3436. std::string tmp_err;
  3437. if (!ParseStringProperty(&uri, &tmp_err, o, "uri", true)) {
  3438. if (err) {
  3439. (*err) += "Failed to parse `uri` for image[" + std::to_string(image_idx) +
  3440. "] name = \"" + image->name + "\".\n";
  3441. }
  3442. return false;
  3443. }
  3444. std::vector<unsigned char> img;
  3445. if (IsDataURI(uri)) {
  3446. if (!DecodeDataURI(&img, image->mimeType, uri, 0, false)) {
  3447. if (err) {
  3448. (*err) += "Failed to decode 'uri' for image[" +
  3449. std::to_string(image_idx) + "] name = [" + image->name +
  3450. "]\n";
  3451. }
  3452. return false;
  3453. }
  3454. } else {
  3455. // Assume external file
  3456. // Keep texture path (for textures that cannot be decoded)
  3457. image->uri = uri;
  3458. #ifdef TINYGLTF_NO_EXTERNAL_IMAGE
  3459. return true;
  3460. #else
  3461. std::string decoded_uri;
  3462. if (!uri_cb->decode(uri, &decoded_uri, uri_cb->user_data)) {
  3463. if (warn) {
  3464. (*warn) += "Failed to decode 'uri' for image[" +
  3465. std::to_string(image_idx) + "] name = [" + image->name +
  3466. "]\n";
  3467. }
  3468. // Image loading failure is not critical to overall gltf loading.
  3469. return true;
  3470. }
  3471. if (!LoadExternalFile(&img, err, warn, decoded_uri, basedir,
  3472. /* required */ false, /* required bytes */ 0,
  3473. /* checksize */ false, fs)) {
  3474. if (warn) {
  3475. (*warn) += "Failed to load external 'uri' for image[" +
  3476. std::to_string(image_idx) + "] name = [" + image->name +
  3477. "]\n";
  3478. }
  3479. // If the image cannot be loaded, keep uri as image->uri.
  3480. return true;
  3481. }
  3482. if (img.empty()) {
  3483. if (warn) {
  3484. (*warn) += "Image data is empty for image[" +
  3485. std::to_string(image_idx) + "] name = [" + image->name +
  3486. "] \n";
  3487. }
  3488. return false;
  3489. }
  3490. #endif
  3491. }
  3492. if (*LoadImageData == nullptr) {
  3493. if (err) {
  3494. (*err) += "No LoadImageData callback specified.\n";
  3495. }
  3496. return false;
  3497. }
  3498. return (*LoadImageData)(image, image_idx, err, warn, 0, 0, &img.at(0),
  3499. static_cast<int>(img.size()), load_image_user_data);
  3500. }
  3501. static bool ParseTexture(Texture *texture, std::string *err, const detail::json &o,
  3502. bool store_original_json_for_extras_and_extensions,
  3503. const std::string &basedir) {
  3504. (void)basedir;
  3505. int sampler = -1;
  3506. int source = -1;
  3507. ParseIntegerProperty(&sampler, err, o, "sampler", false);
  3508. ParseIntegerProperty(&source, err, o, "source", false);
  3509. texture->sampler = sampler;
  3510. texture->source = source;
  3511. ParseExtensionsProperty(&texture->extensions, err, o);
  3512. ParseExtrasProperty(&texture->extras, o);
  3513. if (store_original_json_for_extras_and_extensions) {
  3514. {
  3515. detail::json_const_iterator it;
  3516. if (detail::FindMember(o, "extensions", it)) {
  3517. texture->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  3518. }
  3519. }
  3520. {
  3521. detail::json_const_iterator it;
  3522. if (detail::FindMember(o, "extras", it)) {
  3523. texture->extras_json_string = detail::JsonToString(detail::GetValue(it));
  3524. }
  3525. }
  3526. }
  3527. ParseStringProperty(&texture->name, err, o, "name", false);
  3528. return true;
  3529. }
  3530. static bool ParseTextureInfo(
  3531. TextureInfo *texinfo, std::string *err, const detail::json &o,
  3532. bool store_original_json_for_extras_and_extensions) {
  3533. if (texinfo == nullptr) {
  3534. return false;
  3535. }
  3536. if (!ParseIntegerProperty(&texinfo->index, err, o, "index",
  3537. /* required */ true, "TextureInfo")) {
  3538. return false;
  3539. }
  3540. ParseIntegerProperty(&texinfo->texCoord, err, o, "texCoord", false);
  3541. ParseExtensionsProperty(&texinfo->extensions, err, o);
  3542. ParseExtrasProperty(&texinfo->extras, o);
  3543. if (store_original_json_for_extras_and_extensions) {
  3544. {
  3545. detail::json_const_iterator it;
  3546. if (detail::FindMember(o, "extensions", it)) {
  3547. texinfo->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  3548. }
  3549. }
  3550. {
  3551. detail::json_const_iterator it;
  3552. if (detail::FindMember(o, "extras", it)) {
  3553. texinfo->extras_json_string = detail::JsonToString(detail::GetValue(it));
  3554. }
  3555. }
  3556. }
  3557. return true;
  3558. }
  3559. static bool ParseNormalTextureInfo(
  3560. NormalTextureInfo *texinfo, std::string *err, const detail::json &o,
  3561. bool store_original_json_for_extras_and_extensions) {
  3562. if (texinfo == nullptr) {
  3563. return false;
  3564. }
  3565. if (!ParseIntegerProperty(&texinfo->index, err, o, "index",
  3566. /* required */ true, "NormalTextureInfo")) {
  3567. return false;
  3568. }
  3569. ParseIntegerProperty(&texinfo->texCoord, err, o, "texCoord", false);
  3570. ParseNumberProperty(&texinfo->scale, err, o, "scale", false);
  3571. ParseExtensionsProperty(&texinfo->extensions, err, o);
  3572. ParseExtrasProperty(&texinfo->extras, o);
  3573. if (store_original_json_for_extras_and_extensions) {
  3574. {
  3575. detail::json_const_iterator it;
  3576. if (detail::FindMember(o, "extensions", it)) {
  3577. texinfo->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  3578. }
  3579. }
  3580. {
  3581. detail::json_const_iterator it;
  3582. if (detail::FindMember(o, "extras", it)) {
  3583. texinfo->extras_json_string = detail::JsonToString(detail::GetValue(it));
  3584. }
  3585. }
  3586. }
  3587. return true;
  3588. }
  3589. static bool ParseOcclusionTextureInfo(
  3590. OcclusionTextureInfo *texinfo, std::string *err, const detail::json &o,
  3591. bool store_original_json_for_extras_and_extensions) {
  3592. if (texinfo == nullptr) {
  3593. return false;
  3594. }
  3595. if (!ParseIntegerProperty(&texinfo->index, err, o, "index",
  3596. /* required */ true, "NormalTextureInfo")) {
  3597. return false;
  3598. }
  3599. ParseIntegerProperty(&texinfo->texCoord, err, o, "texCoord", false);
  3600. ParseNumberProperty(&texinfo->strength, err, o, "strength", false);
  3601. ParseExtensionsProperty(&texinfo->extensions, err, o);
  3602. ParseExtrasProperty(&texinfo->extras, o);
  3603. if (store_original_json_for_extras_and_extensions) {
  3604. {
  3605. detail::json_const_iterator it;
  3606. if (detail::FindMember(o, "extensions", it)) {
  3607. texinfo->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  3608. }
  3609. }
  3610. {
  3611. detail::json_const_iterator it;
  3612. if (detail::FindMember(o, "extras", it)) {
  3613. texinfo->extras_json_string = detail::JsonToString(detail::GetValue(it));
  3614. }
  3615. }
  3616. }
  3617. return true;
  3618. }
  3619. static bool ParseBuffer(Buffer *buffer, std::string *err, const detail::json &o,
  3620. bool store_original_json_for_extras_and_extensions,
  3621. FsCallbacks *fs, const URICallbacks *uri_cb,
  3622. const std::string &basedir, bool is_binary = false,
  3623. const unsigned char *bin_data = nullptr,
  3624. size_t bin_size = 0) {
  3625. size_t byteLength;
  3626. if (!ParseUnsignedProperty(&byteLength, err, o, "byteLength", true,
  3627. "Buffer")) {
  3628. return false;
  3629. }
  3630. // In glTF 2.0, uri is not mandatory anymore
  3631. buffer->uri.clear();
  3632. ParseStringProperty(&buffer->uri, err, o, "uri", false, "Buffer");
  3633. // having an empty uri for a non embedded image should not be valid
  3634. if (!is_binary && buffer->uri.empty()) {
  3635. if (err) {
  3636. (*err) += "'uri' is missing from non binary glTF file buffer.\n";
  3637. }
  3638. }
  3639. detail::json_const_iterator type;
  3640. if (detail::FindMember(o, "type", type)) {
  3641. std::string typeStr;
  3642. if (detail::GetString(detail::GetValue(type), typeStr)) {
  3643. if (typeStr.compare("arraybuffer") == 0) {
  3644. // buffer.type = "arraybuffer";
  3645. }
  3646. }
  3647. }
  3648. if (is_binary) {
  3649. // Still binary glTF accepts external dataURI.
  3650. if (!buffer->uri.empty()) {
  3651. // First try embedded data URI.
  3652. if (IsDataURI(buffer->uri)) {
  3653. std::string mime_type;
  3654. if (!DecodeDataURI(&buffer->data, mime_type, buffer->uri, byteLength,
  3655. true)) {
  3656. if (err) {
  3657. (*err) +=
  3658. "Failed to decode 'uri' : " + buffer->uri + " in Buffer\n";
  3659. }
  3660. return false;
  3661. }
  3662. } else {
  3663. // External .bin file.
  3664. std::string decoded_uri;
  3665. if (!uri_cb->decode(buffer->uri, &decoded_uri, uri_cb->user_data)) {
  3666. return false;
  3667. }
  3668. if (!LoadExternalFile(&buffer->data, err, /* warn */ nullptr,
  3669. decoded_uri, basedir, /* required */ true,
  3670. byteLength, /* checkSize */ true, fs)) {
  3671. return false;
  3672. }
  3673. }
  3674. } else {
  3675. // load data from (embedded) binary data
  3676. if ((bin_size == 0) || (bin_data == nullptr)) {
  3677. if (err) {
  3678. (*err) += "Invalid binary data in `Buffer', or GLB with empty BIN chunk.\n";
  3679. }
  3680. return false;
  3681. }
  3682. if (byteLength > bin_size) {
  3683. if (err) {
  3684. std::stringstream ss;
  3685. ss << "Invalid `byteLength'. Must be equal or less than binary size: "
  3686. "`byteLength' = "
  3687. << byteLength << ", binary size = " << bin_size << std::endl;
  3688. (*err) += ss.str();
  3689. }
  3690. return false;
  3691. }
  3692. // Read buffer data
  3693. buffer->data.resize(static_cast<size_t>(byteLength));
  3694. memcpy(&(buffer->data.at(0)), bin_data, static_cast<size_t>(byteLength));
  3695. }
  3696. } else {
  3697. if (IsDataURI(buffer->uri)) {
  3698. std::string mime_type;
  3699. if (!DecodeDataURI(&buffer->data, mime_type, buffer->uri, byteLength,
  3700. true)) {
  3701. if (err) {
  3702. (*err) += "Failed to decode 'uri' : " + buffer->uri + " in Buffer\n";
  3703. }
  3704. return false;
  3705. }
  3706. } else {
  3707. // Assume external .bin file.
  3708. std::string decoded_uri;
  3709. if (!uri_cb->decode(buffer->uri, &decoded_uri, uri_cb->user_data)) {
  3710. return false;
  3711. }
  3712. if (!LoadExternalFile(&buffer->data, err, /* warn */ nullptr, decoded_uri,
  3713. basedir, /* required */ true, byteLength,
  3714. /* checkSize */ true, fs)) {
  3715. return false;
  3716. }
  3717. }
  3718. }
  3719. ParseStringProperty(&buffer->name, err, o, "name", false);
  3720. ParseExtensionsProperty(&buffer->extensions, err, o);
  3721. ParseExtrasProperty(&buffer->extras, o);
  3722. if (store_original_json_for_extras_and_extensions) {
  3723. {
  3724. detail::json_const_iterator it;
  3725. if (detail::FindMember(o, "extensions", it)) {
  3726. buffer->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  3727. }
  3728. }
  3729. {
  3730. detail::json_const_iterator it;
  3731. if (detail::FindMember(o, "extras", it)) {
  3732. buffer->extras_json_string = detail::JsonToString(detail::GetValue(it));
  3733. }
  3734. }
  3735. }
  3736. return true;
  3737. }
  3738. static bool ParseBufferView(
  3739. BufferView *bufferView, std::string *err, const detail::json &o,
  3740. bool store_original_json_for_extras_and_extensions) {
  3741. int buffer = -1;
  3742. if (!ParseIntegerProperty(&buffer, err, o, "buffer", true, "BufferView")) {
  3743. return false;
  3744. }
  3745. size_t byteOffset = 0;
  3746. ParseUnsignedProperty(&byteOffset, err, o, "byteOffset", false);
  3747. size_t byteLength = 1;
  3748. if (!ParseUnsignedProperty(&byteLength, err, o, "byteLength", true,
  3749. "BufferView")) {
  3750. return false;
  3751. }
  3752. size_t byteStride = 0;
  3753. if (!ParseUnsignedProperty(&byteStride, err, o, "byteStride", false)) {
  3754. // Spec says: When byteStride of referenced bufferView is not defined, it
  3755. // means that accessor elements are tightly packed, i.e., effective stride
  3756. // equals the size of the element.
  3757. // We cannot determine the actual byteStride until Accessor are parsed, thus
  3758. // set 0(= tightly packed) here(as done in OpenGL's VertexAttribPoiner)
  3759. byteStride = 0;
  3760. }
  3761. if ((byteStride > 252) || ((byteStride % 4) != 0)) {
  3762. if (err) {
  3763. std::stringstream ss;
  3764. ss << "Invalid `byteStride' value. `byteStride' must be the multiple of "
  3765. "4 : "
  3766. << byteStride << std::endl;
  3767. (*err) += ss.str();
  3768. }
  3769. return false;
  3770. }
  3771. int target = 0;
  3772. ParseIntegerProperty(&target, err, o, "target", false);
  3773. if ((target == TINYGLTF_TARGET_ARRAY_BUFFER) ||
  3774. (target == TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER)) {
  3775. // OK
  3776. } else {
  3777. target = 0;
  3778. }
  3779. bufferView->target = target;
  3780. ParseStringProperty(&bufferView->name, err, o, "name", false);
  3781. ParseExtensionsProperty(&bufferView->extensions, err, o);
  3782. ParseExtrasProperty(&bufferView->extras, o);
  3783. if (store_original_json_for_extras_and_extensions) {
  3784. {
  3785. detail::json_const_iterator it;
  3786. if (detail::FindMember(o, "extensions", it)) {
  3787. bufferView->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  3788. }
  3789. }
  3790. {
  3791. detail::json_const_iterator it;
  3792. if (detail::FindMember(o, "extras", it)) {
  3793. bufferView->extras_json_string = detail::JsonToString(detail::GetValue(it));
  3794. }
  3795. }
  3796. }
  3797. bufferView->buffer = buffer;
  3798. bufferView->byteOffset = byteOffset;
  3799. bufferView->byteLength = byteLength;
  3800. bufferView->byteStride = byteStride;
  3801. return true;
  3802. }
  3803. static bool ParseSparseAccessor(Accessor *accessor, std::string *err,
  3804. const detail::json &o) {
  3805. accessor->sparse.isSparse = true;
  3806. int count = 0;
  3807. if (!ParseIntegerProperty(&count, err, o, "count", true, "SparseAccessor")) {
  3808. return false;
  3809. }
  3810. detail::json_const_iterator indices_iterator;
  3811. detail::json_const_iterator values_iterator;
  3812. if (!detail::FindMember(o, "indices", indices_iterator)) {
  3813. (*err) = "the sparse object of this accessor doesn't have indices";
  3814. return false;
  3815. }
  3816. if (!detail::FindMember(o, "values", values_iterator)) {
  3817. (*err) = "the sparse object of this accessor doesn't have values";
  3818. return false;
  3819. }
  3820. const detail::json &indices_obj = detail::GetValue(indices_iterator);
  3821. const detail::json &values_obj = detail::GetValue(values_iterator);
  3822. int indices_buffer_view = 0, indices_byte_offset = 0, component_type = 0;
  3823. if (!ParseIntegerProperty(&indices_buffer_view, err, indices_obj,
  3824. "bufferView", true, "SparseAccessor")) {
  3825. return false;
  3826. }
  3827. ParseIntegerProperty(&indices_byte_offset, err, indices_obj, "byteOffset",
  3828. false);
  3829. if (!ParseIntegerProperty(&component_type, err, indices_obj, "componentType",
  3830. true, "SparseAccessor")) {
  3831. return false;
  3832. }
  3833. int values_buffer_view = 0, values_byte_offset = 0;
  3834. if (!ParseIntegerProperty(&values_buffer_view, err, values_obj, "bufferView",
  3835. true, "SparseAccessor")) {
  3836. return false;
  3837. }
  3838. ParseIntegerProperty(&values_byte_offset, err, values_obj, "byteOffset",
  3839. false);
  3840. accessor->sparse.count = count;
  3841. accessor->sparse.indices.bufferView = indices_buffer_view;
  3842. accessor->sparse.indices.byteOffset = indices_byte_offset;
  3843. accessor->sparse.indices.componentType = component_type;
  3844. accessor->sparse.values.bufferView = values_buffer_view;
  3845. accessor->sparse.values.byteOffset = values_byte_offset;
  3846. return true;
  3847. }
  3848. static bool ParseAccessor(Accessor *accessor, std::string *err, const detail::json &o,
  3849. bool store_original_json_for_extras_and_extensions) {
  3850. int bufferView = -1;
  3851. ParseIntegerProperty(&bufferView, err, o, "bufferView", false, "Accessor");
  3852. size_t byteOffset = 0;
  3853. ParseUnsignedProperty(&byteOffset, err, o, "byteOffset", false, "Accessor");
  3854. bool normalized = false;
  3855. ParseBooleanProperty(&normalized, err, o, "normalized", false, "Accessor");
  3856. size_t componentType = 0;
  3857. if (!ParseUnsignedProperty(&componentType, err, o, "componentType", true,
  3858. "Accessor")) {
  3859. return false;
  3860. }
  3861. size_t count = 0;
  3862. if (!ParseUnsignedProperty(&count, err, o, "count", true, "Accessor")) {
  3863. return false;
  3864. }
  3865. std::string type;
  3866. if (!ParseStringProperty(&type, err, o, "type", true, "Accessor")) {
  3867. return false;
  3868. }
  3869. if (type.compare("SCALAR") == 0) {
  3870. accessor->type = TINYGLTF_TYPE_SCALAR;
  3871. } else if (type.compare("VEC2") == 0) {
  3872. accessor->type = TINYGLTF_TYPE_VEC2;
  3873. } else if (type.compare("VEC3") == 0) {
  3874. accessor->type = TINYGLTF_TYPE_VEC3;
  3875. } else if (type.compare("VEC4") == 0) {
  3876. accessor->type = TINYGLTF_TYPE_VEC4;
  3877. } else if (type.compare("MAT2") == 0) {
  3878. accessor->type = TINYGLTF_TYPE_MAT2;
  3879. } else if (type.compare("MAT3") == 0) {
  3880. accessor->type = TINYGLTF_TYPE_MAT3;
  3881. } else if (type.compare("MAT4") == 0) {
  3882. accessor->type = TINYGLTF_TYPE_MAT4;
  3883. } else {
  3884. std::stringstream ss;
  3885. ss << "Unsupported `type` for accessor object. Got \"" << type << "\"\n";
  3886. if (err) {
  3887. (*err) += ss.str();
  3888. }
  3889. return false;
  3890. }
  3891. ParseStringProperty(&accessor->name, err, o, "name", false);
  3892. accessor->minValues.clear();
  3893. accessor->maxValues.clear();
  3894. ParseNumberArrayProperty(&accessor->minValues, err, o, "min", false,
  3895. "Accessor");
  3896. ParseNumberArrayProperty(&accessor->maxValues, err, o, "max", false,
  3897. "Accessor");
  3898. accessor->count = count;
  3899. accessor->bufferView = bufferView;
  3900. accessor->byteOffset = byteOffset;
  3901. accessor->normalized = normalized;
  3902. {
  3903. if (componentType >= TINYGLTF_COMPONENT_TYPE_BYTE &&
  3904. componentType <= TINYGLTF_COMPONENT_TYPE_DOUBLE) {
  3905. // OK
  3906. accessor->componentType = int(componentType);
  3907. } else {
  3908. std::stringstream ss;
  3909. ss << "Invalid `componentType` in accessor. Got " << componentType
  3910. << "\n";
  3911. if (err) {
  3912. (*err) += ss.str();
  3913. }
  3914. return false;
  3915. }
  3916. }
  3917. ParseExtensionsProperty(&(accessor->extensions), err, o);
  3918. ParseExtrasProperty(&(accessor->extras), o);
  3919. if (store_original_json_for_extras_and_extensions) {
  3920. {
  3921. detail::json_const_iterator it;
  3922. if (detail::FindMember(o, "extensions", it)) {
  3923. accessor->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  3924. }
  3925. }
  3926. {
  3927. detail::json_const_iterator it;
  3928. if (detail::FindMember(o, "extras", it)) {
  3929. accessor->extras_json_string = detail::JsonToString(detail::GetValue(it));
  3930. }
  3931. }
  3932. }
  3933. // check if accessor has a "sparse" object:
  3934. detail::json_const_iterator iterator;
  3935. if (detail::FindMember(o, "sparse", iterator)) {
  3936. // here this accessor has a "sparse" subobject
  3937. return ParseSparseAccessor(accessor, err, detail::GetValue(iterator));
  3938. }
  3939. return true;
  3940. }
  3941. #ifdef TINYGLTF_ENABLE_DRACO
  3942. static void DecodeIndexBuffer(draco::Mesh *mesh, size_t componentSize,
  3943. std::vector<uint8_t> &outBuffer) {
  3944. if (componentSize == 4) {
  3945. assert(sizeof(mesh->face(draco::FaceIndex(0))[0]) == componentSize);
  3946. memcpy(outBuffer.data(), &mesh->face(draco::FaceIndex(0))[0],
  3947. outBuffer.size());
  3948. } else {
  3949. size_t faceStride = componentSize * 3;
  3950. for (draco::FaceIndex f(0); f < mesh->num_faces(); ++f) {
  3951. const draco::Mesh::Face &face = mesh->face(f);
  3952. if (componentSize == 2) {
  3953. uint16_t indices[3] = {(uint16_t)face[0].value(),
  3954. (uint16_t)face[1].value(),
  3955. (uint16_t)face[2].value()};
  3956. memcpy(outBuffer.data() + f.value() * faceStride, &indices[0],
  3957. faceStride);
  3958. } else {
  3959. uint8_t indices[3] = {(uint8_t)face[0].value(),
  3960. (uint8_t)face[1].value(),
  3961. (uint8_t)face[2].value()};
  3962. memcpy(outBuffer.data() + f.value() * faceStride, &indices[0],
  3963. faceStride);
  3964. }
  3965. }
  3966. }
  3967. }
  3968. template <typename T>
  3969. static bool GetAttributeForAllPoints(draco::Mesh *mesh,
  3970. const draco::PointAttribute *pAttribute,
  3971. std::vector<uint8_t> &outBuffer) {
  3972. size_t byteOffset = 0;
  3973. T values[4] = {0, 0, 0, 0};
  3974. for (draco::PointIndex i(0); i < mesh->num_points(); ++i) {
  3975. const draco::AttributeValueIndex val_index = pAttribute->mapped_index(i);
  3976. if (!pAttribute->ConvertValue<T>(val_index, pAttribute->num_components(),
  3977. values))
  3978. return false;
  3979. memcpy(outBuffer.data() + byteOffset, &values[0],
  3980. sizeof(T) * pAttribute->num_components());
  3981. byteOffset += sizeof(T) * pAttribute->num_components();
  3982. }
  3983. return true;
  3984. }
  3985. static bool GetAttributeForAllPoints(uint32_t componentType, draco::Mesh *mesh,
  3986. const draco::PointAttribute *pAttribute,
  3987. std::vector<uint8_t> &outBuffer) {
  3988. bool decodeResult = false;
  3989. switch (componentType) {
  3990. case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE:
  3991. decodeResult =
  3992. GetAttributeForAllPoints<uint8_t>(mesh, pAttribute, outBuffer);
  3993. break;
  3994. case TINYGLTF_COMPONENT_TYPE_BYTE:
  3995. decodeResult =
  3996. GetAttributeForAllPoints<int8_t>(mesh, pAttribute, outBuffer);
  3997. break;
  3998. case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT:
  3999. decodeResult =
  4000. GetAttributeForAllPoints<uint16_t>(mesh, pAttribute, outBuffer);
  4001. break;
  4002. case TINYGLTF_COMPONENT_TYPE_SHORT:
  4003. decodeResult =
  4004. GetAttributeForAllPoints<int16_t>(mesh, pAttribute, outBuffer);
  4005. break;
  4006. case TINYGLTF_COMPONENT_TYPE_INT:
  4007. decodeResult =
  4008. GetAttributeForAllPoints<int32_t>(mesh, pAttribute, outBuffer);
  4009. break;
  4010. case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT:
  4011. decodeResult =
  4012. GetAttributeForAllPoints<uint32_t>(mesh, pAttribute, outBuffer);
  4013. break;
  4014. case TINYGLTF_COMPONENT_TYPE_FLOAT:
  4015. decodeResult =
  4016. GetAttributeForAllPoints<float>(mesh, pAttribute, outBuffer);
  4017. break;
  4018. case TINYGLTF_COMPONENT_TYPE_DOUBLE:
  4019. decodeResult =
  4020. GetAttributeForAllPoints<double>(mesh, pAttribute, outBuffer);
  4021. break;
  4022. default:
  4023. return false;
  4024. }
  4025. return decodeResult;
  4026. }
  4027. static bool ParseDracoExtension(Primitive *primitive, Model *model,
  4028. std::string *err,
  4029. const Value &dracoExtensionValue) {
  4030. (void)err;
  4031. auto bufferViewValue = dracoExtensionValue.Get("bufferView");
  4032. if (!bufferViewValue.IsInt()) return false;
  4033. auto attributesValue = dracoExtensionValue.Get("attributes");
  4034. if (!attributesValue.IsObject()) return false;
  4035. auto attributesObject = attributesValue.Get<Value::Object>();
  4036. int bufferView = bufferViewValue.Get<int>();
  4037. BufferView &view = model->bufferViews[bufferView];
  4038. Buffer &buffer = model->buffers[view.buffer];
  4039. // BufferView has already been decoded
  4040. if (view.dracoDecoded) return true;
  4041. view.dracoDecoded = true;
  4042. const char *bufferViewData =
  4043. reinterpret_cast<const char *>(buffer.data.data() + view.byteOffset);
  4044. size_t bufferViewSize = view.byteLength;
  4045. // decode draco
  4046. draco::DecoderBuffer decoderBuffer;
  4047. decoderBuffer.Init(bufferViewData, bufferViewSize);
  4048. draco::Decoder decoder;
  4049. auto decodeResult = decoder.DecodeMeshFromBuffer(&decoderBuffer);
  4050. if (!decodeResult.ok()) {
  4051. return false;
  4052. }
  4053. const std::unique_ptr<draco::Mesh> &mesh = decodeResult.value();
  4054. // create new bufferView for indices
  4055. if (primitive->indices >= 0) {
  4056. int32_t componentSize = GetComponentSizeInBytes(
  4057. model->accessors[primitive->indices].componentType);
  4058. Buffer decodedIndexBuffer;
  4059. decodedIndexBuffer.data.resize(mesh->num_faces() * 3 * componentSize);
  4060. DecodeIndexBuffer(mesh.get(), componentSize, decodedIndexBuffer.data);
  4061. model->buffers.emplace_back(std::move(decodedIndexBuffer));
  4062. BufferView decodedIndexBufferView;
  4063. decodedIndexBufferView.buffer = int(model->buffers.size() - 1);
  4064. decodedIndexBufferView.byteLength =
  4065. int(mesh->num_faces() * 3 * componentSize);
  4066. decodedIndexBufferView.byteOffset = 0;
  4067. decodedIndexBufferView.byteStride = 0;
  4068. decodedIndexBufferView.target = TINYGLTF_TARGET_ARRAY_BUFFER;
  4069. model->bufferViews.emplace_back(std::move(decodedIndexBufferView));
  4070. model->accessors[primitive->indices].bufferView =
  4071. int(model->bufferViews.size() - 1);
  4072. model->accessors[primitive->indices].count = int(mesh->num_faces() * 3);
  4073. }
  4074. for (const auto &attribute : attributesObject) {
  4075. if (!attribute.second.IsInt()) return false;
  4076. auto primitiveAttribute = primitive->attributes.find(attribute.first);
  4077. if (primitiveAttribute == primitive->attributes.end()) return false;
  4078. int dracoAttributeIndex = attribute.second.Get<int>();
  4079. const auto pAttribute = mesh->GetAttributeByUniqueId(dracoAttributeIndex);
  4080. const auto componentType =
  4081. model->accessors[primitiveAttribute->second].componentType;
  4082. // Create a new buffer for this decoded buffer
  4083. Buffer decodedBuffer;
  4084. size_t bufferSize = mesh->num_points() * pAttribute->num_components() *
  4085. GetComponentSizeInBytes(componentType);
  4086. decodedBuffer.data.resize(bufferSize);
  4087. if (!GetAttributeForAllPoints(componentType, mesh.get(), pAttribute,
  4088. decodedBuffer.data))
  4089. return false;
  4090. model->buffers.emplace_back(std::move(decodedBuffer));
  4091. BufferView decodedBufferView;
  4092. decodedBufferView.buffer = int(model->buffers.size() - 1);
  4093. decodedBufferView.byteLength = bufferSize;
  4094. decodedBufferView.byteOffset = pAttribute->byte_offset();
  4095. decodedBufferView.byteStride = pAttribute->byte_stride();
  4096. decodedBufferView.target = primitive->indices >= 0
  4097. ? TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER
  4098. : TINYGLTF_TARGET_ARRAY_BUFFER;
  4099. model->bufferViews.emplace_back(std::move(decodedBufferView));
  4100. model->accessors[primitiveAttribute->second].bufferView =
  4101. int(model->bufferViews.size() - 1);
  4102. model->accessors[primitiveAttribute->second].count =
  4103. int(mesh->num_points());
  4104. }
  4105. return true;
  4106. }
  4107. #endif
  4108. static bool ParsePrimitive(Primitive *primitive, Model *model, std::string *err,
  4109. const detail::json &o,
  4110. bool store_original_json_for_extras_and_extensions) {
  4111. int material = -1;
  4112. ParseIntegerProperty(&material, err, o, "material", false);
  4113. primitive->material = material;
  4114. int mode = TINYGLTF_MODE_TRIANGLES;
  4115. ParseIntegerProperty(&mode, err, o, "mode", false);
  4116. primitive->mode = mode; // Why only triangles were supported ?
  4117. int indices = -1;
  4118. ParseIntegerProperty(&indices, err, o, "indices", false);
  4119. primitive->indices = indices;
  4120. if (!ParseStringIntegerProperty(&primitive->attributes, err, o, "attributes",
  4121. true, "Primitive")) {
  4122. return false;
  4123. }
  4124. // Look for morph targets
  4125. detail::json_const_iterator targetsObject;
  4126. if (detail::FindMember(o, "targets", targetsObject) &&
  4127. detail::IsArray(detail::GetValue(targetsObject))) {
  4128. auto targetsObjectEnd = detail::ArrayEnd(detail::GetValue(targetsObject));
  4129. for (detail::json_const_array_iterator i = detail::ArrayBegin(detail::GetValue(targetsObject));
  4130. i != targetsObjectEnd; ++i) {
  4131. std::map<std::string, int> targetAttribues;
  4132. const detail::json &dict = *i;
  4133. if (detail::IsObject(dict)) {
  4134. detail::json_const_iterator dictIt(detail::ObjectBegin(dict));
  4135. detail::json_const_iterator dictItEnd(detail::ObjectEnd(dict));
  4136. for (; dictIt != dictItEnd; ++dictIt) {
  4137. int iVal;
  4138. if (detail::GetInt(detail::GetValue(dictIt), iVal))
  4139. targetAttribues[detail::GetKey(dictIt)] = iVal;
  4140. }
  4141. primitive->targets.emplace_back(std::move(targetAttribues));
  4142. }
  4143. }
  4144. }
  4145. ParseExtrasProperty(&(primitive->extras), o);
  4146. ParseExtensionsProperty(&primitive->extensions, err, o);
  4147. if (store_original_json_for_extras_and_extensions) {
  4148. {
  4149. detail::json_const_iterator it;
  4150. if (detail::FindMember(o, "extensions", it)) {
  4151. primitive->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  4152. }
  4153. }
  4154. {
  4155. detail::json_const_iterator it;
  4156. if (detail::FindMember(o, "extras", it)) {
  4157. primitive->extras_json_string = detail::JsonToString(detail::GetValue(it));
  4158. }
  4159. }
  4160. }
  4161. #ifdef TINYGLTF_ENABLE_DRACO
  4162. auto dracoExtension =
  4163. primitive->extensions.find("KHR_draco_mesh_compression");
  4164. if (dracoExtension != primitive->extensions.end()) {
  4165. ParseDracoExtension(primitive, model, err, dracoExtension->second);
  4166. }
  4167. #else
  4168. (void)model;
  4169. #endif
  4170. return true;
  4171. }
  4172. static bool ParseMesh(Mesh *mesh, Model *model, std::string *err, const detail::json &o,
  4173. bool store_original_json_for_extras_and_extensions) {
  4174. ParseStringProperty(&mesh->name, err, o, "name", false);
  4175. mesh->primitives.clear();
  4176. detail::json_const_iterator primObject;
  4177. if (detail::FindMember(o, "primitives", primObject) &&
  4178. detail::IsArray(detail::GetValue(primObject))) {
  4179. detail::json_const_array_iterator primEnd = detail::ArrayEnd(detail::GetValue(primObject));
  4180. for (detail::json_const_array_iterator i = detail::ArrayBegin(detail::GetValue(primObject));
  4181. i != primEnd; ++i) {
  4182. Primitive primitive;
  4183. if (ParsePrimitive(&primitive, model, err, *i,
  4184. store_original_json_for_extras_and_extensions)) {
  4185. // Only add the primitive if the parsing succeeds.
  4186. mesh->primitives.emplace_back(std::move(primitive));
  4187. }
  4188. }
  4189. }
  4190. // Should probably check if has targets and if dimensions fit
  4191. ParseNumberArrayProperty(&mesh->weights, err, o, "weights", false);
  4192. ParseExtensionsProperty(&mesh->extensions, err, o);
  4193. ParseExtrasProperty(&(mesh->extras), o);
  4194. if (store_original_json_for_extras_and_extensions) {
  4195. {
  4196. detail::json_const_iterator it;
  4197. if (detail::FindMember(o, "extensions", it)) {
  4198. mesh->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  4199. }
  4200. }
  4201. {
  4202. detail::json_const_iterator it;
  4203. if (detail::FindMember(o, "extras", it)) {
  4204. mesh->extras_json_string = detail::JsonToString(detail::GetValue(it));
  4205. }
  4206. }
  4207. }
  4208. return true;
  4209. }
  4210. static bool ParseNode(Node *node, std::string *err, const detail::json &o,
  4211. bool store_original_json_for_extras_and_extensions) {
  4212. ParseStringProperty(&node->name, err, o, "name", false);
  4213. int skin = -1;
  4214. ParseIntegerProperty(&skin, err, o, "skin", false);
  4215. node->skin = skin;
  4216. // Matrix and T/R/S are exclusive
  4217. if (!ParseNumberArrayProperty(&node->matrix, err, o, "matrix", false)) {
  4218. ParseNumberArrayProperty(&node->rotation, err, o, "rotation", false);
  4219. ParseNumberArrayProperty(&node->scale, err, o, "scale", false);
  4220. ParseNumberArrayProperty(&node->translation, err, o, "translation", false);
  4221. }
  4222. int camera = -1;
  4223. ParseIntegerProperty(&camera, err, o, "camera", false);
  4224. node->camera = camera;
  4225. int mesh = -1;
  4226. ParseIntegerProperty(&mesh, err, o, "mesh", false);
  4227. node->mesh = mesh;
  4228. node->children.clear();
  4229. ParseIntegerArrayProperty(&node->children, err, o, "children", false);
  4230. ParseNumberArrayProperty(&node->weights, err, o, "weights", false);
  4231. ParseExtensionsProperty(&node->extensions, err, o);
  4232. ParseExtrasProperty(&(node->extras), o);
  4233. if (store_original_json_for_extras_and_extensions) {
  4234. {
  4235. detail::json_const_iterator it;
  4236. if (detail::FindMember(o, "extensions", it)) {
  4237. node->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  4238. }
  4239. }
  4240. {
  4241. detail::json_const_iterator it;
  4242. if (detail::FindMember(o, "extras", it)) {
  4243. node->extras_json_string = detail::JsonToString(detail::GetValue(it));
  4244. }
  4245. }
  4246. }
  4247. return true;
  4248. }
  4249. static bool ParsePbrMetallicRoughness(
  4250. PbrMetallicRoughness *pbr, std::string *err, const detail::json &o,
  4251. bool store_original_json_for_extras_and_extensions) {
  4252. if (pbr == nullptr) {
  4253. return false;
  4254. }
  4255. std::vector<double> baseColorFactor;
  4256. if (ParseNumberArrayProperty(&baseColorFactor, err, o, "baseColorFactor",
  4257. /* required */ false)) {
  4258. if (baseColorFactor.size() != 4) {
  4259. if (err) {
  4260. (*err) +=
  4261. "Array length of `baseColorFactor` parameter in "
  4262. "pbrMetallicRoughness must be 4, but got " +
  4263. std::to_string(baseColorFactor.size()) + "\n";
  4264. }
  4265. return false;
  4266. }
  4267. pbr->baseColorFactor = baseColorFactor;
  4268. }
  4269. {
  4270. detail::json_const_iterator it;
  4271. if (detail::FindMember(o, "baseColorTexture", it)) {
  4272. ParseTextureInfo(&pbr->baseColorTexture, err, detail::GetValue(it),
  4273. store_original_json_for_extras_and_extensions);
  4274. }
  4275. }
  4276. {
  4277. detail::json_const_iterator it;
  4278. if (detail::FindMember(o, "metallicRoughnessTexture", it)) {
  4279. ParseTextureInfo(&pbr->metallicRoughnessTexture, err, detail::GetValue(it),
  4280. store_original_json_for_extras_and_extensions);
  4281. }
  4282. }
  4283. ParseNumberProperty(&pbr->metallicFactor, err, o, "metallicFactor", false);
  4284. ParseNumberProperty(&pbr->roughnessFactor, err, o, "roughnessFactor", false);
  4285. ParseExtensionsProperty(&pbr->extensions, err, o);
  4286. ParseExtrasProperty(&pbr->extras, o);
  4287. if (store_original_json_for_extras_and_extensions) {
  4288. {
  4289. detail::json_const_iterator it;
  4290. if (detail::FindMember(o, "extensions", it)) {
  4291. pbr->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  4292. }
  4293. }
  4294. {
  4295. detail::json_const_iterator it;
  4296. if (detail::FindMember(o, "extras", it)) {
  4297. pbr->extras_json_string = detail::JsonToString(detail::GetValue(it));
  4298. }
  4299. }
  4300. }
  4301. return true;
  4302. }
  4303. static bool ParseMaterial(Material *material, std::string *err, const detail::json &o,
  4304. bool store_original_json_for_extras_and_extensions) {
  4305. ParseStringProperty(&material->name, err, o, "name", /* required */ false);
  4306. if (ParseNumberArrayProperty(&material->emissiveFactor, err, o,
  4307. "emissiveFactor",
  4308. /* required */ false)) {
  4309. if (material->emissiveFactor.size() != 3) {
  4310. if (err) {
  4311. (*err) +=
  4312. "Array length of `emissiveFactor` parameter in "
  4313. "material must be 3, but got " +
  4314. std::to_string(material->emissiveFactor.size()) + "\n";
  4315. }
  4316. return false;
  4317. }
  4318. } else {
  4319. // fill with default values
  4320. material->emissiveFactor = {0.0, 0.0, 0.0};
  4321. }
  4322. ParseStringProperty(&material->alphaMode, err, o, "alphaMode",
  4323. /* required */ false);
  4324. ParseNumberProperty(&material->alphaCutoff, err, o, "alphaCutoff",
  4325. /* required */ false);
  4326. ParseBooleanProperty(&material->doubleSided, err, o, "doubleSided",
  4327. /* required */ false);
  4328. {
  4329. detail::json_const_iterator it;
  4330. if (detail::FindMember(o, "pbrMetallicRoughness", it)) {
  4331. ParsePbrMetallicRoughness(&material->pbrMetallicRoughness, err,
  4332. detail::GetValue(it),
  4333. store_original_json_for_extras_and_extensions);
  4334. }
  4335. }
  4336. {
  4337. detail::json_const_iterator it;
  4338. if (detail::FindMember(o, "normalTexture", it)) {
  4339. ParseNormalTextureInfo(&material->normalTexture, err, detail::GetValue(it),
  4340. store_original_json_for_extras_and_extensions);
  4341. }
  4342. }
  4343. {
  4344. detail::json_const_iterator it;
  4345. if (detail::FindMember(o, "occlusionTexture", it)) {
  4346. ParseOcclusionTextureInfo(&material->occlusionTexture, err, detail::GetValue(it),
  4347. store_original_json_for_extras_and_extensions);
  4348. }
  4349. }
  4350. {
  4351. detail::json_const_iterator it;
  4352. if (detail::FindMember(o, "emissiveTexture", it)) {
  4353. ParseTextureInfo(&material->emissiveTexture, err, detail::GetValue(it),
  4354. store_original_json_for_extras_and_extensions);
  4355. }
  4356. }
  4357. // Old code path. For backward compatibility, we still store material values
  4358. // as Parameter. This will create duplicated information for
  4359. // example(pbrMetallicRoughness), but should be negligible in terms of memory
  4360. // consumption.
  4361. // TODO(syoyo): Remove in the next major release.
  4362. material->values.clear();
  4363. material->additionalValues.clear();
  4364. detail::json_const_iterator it(detail::ObjectBegin(o));
  4365. detail::json_const_iterator itEnd(detail::ObjectEnd(o));
  4366. for (; it != itEnd; ++it) {
  4367. std::string key(detail::GetKey(it));
  4368. if (key == "pbrMetallicRoughness") {
  4369. if (detail::IsObject(detail::GetValue(it))) {
  4370. const detail::json &values_object = detail::GetValue(it);
  4371. detail::json_const_iterator itVal(detail::ObjectBegin(values_object));
  4372. detail::json_const_iterator itValEnd(detail::ObjectEnd(values_object));
  4373. for (; itVal != itValEnd; ++itVal) {
  4374. Parameter param;
  4375. if (ParseParameterProperty(&param, err, values_object, detail::GetKey(itVal),
  4376. false)) {
  4377. material->values.emplace(detail::GetKey(itVal), std::move(param));
  4378. }
  4379. }
  4380. }
  4381. } else if (key == "extensions" || key == "extras") {
  4382. // done later, skip, otherwise poorly parsed contents will be saved in the
  4383. // parametermap and serialized again later
  4384. } else {
  4385. Parameter param;
  4386. if (ParseParameterProperty(&param, err, o, key, false)) {
  4387. // names of materials have already been parsed. Putting it in this map
  4388. // doesn't correctly reflect the glTF specification
  4389. if (key != "name")
  4390. material->additionalValues.emplace(std::move(key), std::move(param));
  4391. }
  4392. }
  4393. }
  4394. material->extensions.clear();
  4395. ParseExtensionsProperty(&material->extensions, err, o);
  4396. ParseExtrasProperty(&(material->extras), o);
  4397. if (store_original_json_for_extras_and_extensions) {
  4398. {
  4399. detail::json_const_iterator eit;
  4400. if (detail::FindMember(o, "extensions", eit)) {
  4401. material->extensions_json_string = detail::JsonToString(detail::GetValue(eit));
  4402. }
  4403. }
  4404. {
  4405. detail::json_const_iterator eit;
  4406. if (detail::FindMember(o, "extras", eit)) {
  4407. material->extras_json_string = detail::JsonToString(detail::GetValue(eit));
  4408. }
  4409. }
  4410. }
  4411. return true;
  4412. }
  4413. static bool ParseAnimationChannel(
  4414. AnimationChannel *channel, std::string *err, const detail::json &o,
  4415. bool store_original_json_for_extras_and_extensions) {
  4416. int samplerIndex = -1;
  4417. int targetIndex = -1;
  4418. if (!ParseIntegerProperty(&samplerIndex, err, o, "sampler", true,
  4419. "AnimationChannel")) {
  4420. if (err) {
  4421. (*err) += "`sampler` field is missing in animation channels\n";
  4422. }
  4423. return false;
  4424. }
  4425. detail::json_const_iterator targetIt;
  4426. if (detail::FindMember(o, "target", targetIt) && detail::IsObject(detail::GetValue(targetIt))) {
  4427. const detail::json &target_object = detail::GetValue(targetIt);
  4428. ParseIntegerProperty(&targetIndex, err, target_object, "node", false);
  4429. if (!ParseStringProperty(&channel->target_path, err, target_object, "path",
  4430. true)) {
  4431. if (err) {
  4432. (*err) += "`path` field is missing in animation.channels.target\n";
  4433. }
  4434. return false;
  4435. }
  4436. ParseExtensionsProperty(&channel->target_extensions, err, target_object);
  4437. if (store_original_json_for_extras_and_extensions) {
  4438. detail::json_const_iterator it;
  4439. if (detail::FindMember(target_object, "extensions", it)) {
  4440. channel->target_extensions_json_string = detail::JsonToString(detail::GetValue(it));
  4441. }
  4442. }
  4443. }
  4444. channel->sampler = samplerIndex;
  4445. channel->target_node = targetIndex;
  4446. ParseExtensionsProperty(&channel->extensions, err, o);
  4447. ParseExtrasProperty(&(channel->extras), o);
  4448. if (store_original_json_for_extras_and_extensions) {
  4449. {
  4450. detail::json_const_iterator it;
  4451. if (detail::FindMember(o, "extensions", it)) {
  4452. channel->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  4453. }
  4454. }
  4455. {
  4456. detail::json_const_iterator it;
  4457. if (detail::FindMember(o, "extras", it)) {
  4458. channel->extras_json_string = detail::JsonToString(detail::GetValue(it));
  4459. }
  4460. }
  4461. }
  4462. return true;
  4463. }
  4464. static bool ParseAnimation(Animation *animation, std::string *err,
  4465. const detail::json &o,
  4466. bool store_original_json_for_extras_and_extensions) {
  4467. {
  4468. detail::json_const_iterator channelsIt;
  4469. if (detail::FindMember(o, "channels", channelsIt) &&
  4470. detail::IsArray(detail::GetValue(channelsIt))) {
  4471. detail::json_const_array_iterator channelEnd = detail::ArrayEnd(detail::GetValue(channelsIt));
  4472. for (detail::json_const_array_iterator i = detail::ArrayBegin(detail::GetValue(channelsIt));
  4473. i != channelEnd; ++i) {
  4474. AnimationChannel channel;
  4475. if (ParseAnimationChannel(
  4476. &channel, err, *i,
  4477. store_original_json_for_extras_and_extensions)) {
  4478. // Only add the channel if the parsing succeeds.
  4479. animation->channels.emplace_back(std::move(channel));
  4480. }
  4481. }
  4482. }
  4483. }
  4484. {
  4485. detail::json_const_iterator samplerIt;
  4486. if (detail::FindMember(o, "samplers", samplerIt) && detail::IsArray(detail::GetValue(samplerIt))) {
  4487. const detail::json &sampler_array = detail::GetValue(samplerIt);
  4488. detail::json_const_array_iterator it = detail::ArrayBegin(sampler_array);
  4489. detail::json_const_array_iterator itEnd = detail::ArrayEnd(sampler_array);
  4490. for (; it != itEnd; ++it) {
  4491. const detail::json &s = *it;
  4492. AnimationSampler sampler;
  4493. int inputIndex = -1;
  4494. int outputIndex = -1;
  4495. if (!ParseIntegerProperty(&inputIndex, err, s, "input", true)) {
  4496. if (err) {
  4497. (*err) += "`input` field is missing in animation.sampler\n";
  4498. }
  4499. return false;
  4500. }
  4501. ParseStringProperty(&sampler.interpolation, err, s, "interpolation",
  4502. false);
  4503. if (!ParseIntegerProperty(&outputIndex, err, s, "output", true)) {
  4504. if (err) {
  4505. (*err) += "`output` field is missing in animation.sampler\n";
  4506. }
  4507. return false;
  4508. }
  4509. sampler.input = inputIndex;
  4510. sampler.output = outputIndex;
  4511. ParseExtensionsProperty(&(sampler.extensions), err, o);
  4512. ParseExtrasProperty(&(sampler.extras), s);
  4513. if (store_original_json_for_extras_and_extensions) {
  4514. {
  4515. detail::json_const_iterator eit;
  4516. if (detail::FindMember(o, "extensions", eit)) {
  4517. sampler.extensions_json_string = detail::JsonToString(detail::GetValue(eit));
  4518. }
  4519. }
  4520. {
  4521. detail::json_const_iterator eit;
  4522. if (detail::FindMember(o, "extras", eit)) {
  4523. sampler.extras_json_string = detail::JsonToString(detail::GetValue(eit));
  4524. }
  4525. }
  4526. }
  4527. animation->samplers.emplace_back(std::move(sampler));
  4528. }
  4529. }
  4530. }
  4531. ParseStringProperty(&animation->name, err, o, "name", false);
  4532. ParseExtensionsProperty(&animation->extensions, err, o);
  4533. ParseExtrasProperty(&(animation->extras), o);
  4534. if (store_original_json_for_extras_and_extensions) {
  4535. {
  4536. detail::json_const_iterator it;
  4537. if (detail::FindMember(o, "extensions", it)) {
  4538. animation->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  4539. }
  4540. }
  4541. {
  4542. detail::json_const_iterator it;
  4543. if (detail::FindMember(o, "extras", it)) {
  4544. animation->extras_json_string = detail::JsonToString(detail::GetValue(it));
  4545. }
  4546. }
  4547. }
  4548. return true;
  4549. }
  4550. static bool ParseSampler(Sampler *sampler, std::string *err, const detail::json &o,
  4551. bool store_original_json_for_extras_and_extensions) {
  4552. ParseStringProperty(&sampler->name, err, o, "name", false);
  4553. int minFilter = -1;
  4554. int magFilter = -1;
  4555. int wrapS = TINYGLTF_TEXTURE_WRAP_REPEAT;
  4556. int wrapT = TINYGLTF_TEXTURE_WRAP_REPEAT;
  4557. // int wrapR = TINYGLTF_TEXTURE_WRAP_REPEAT;
  4558. ParseIntegerProperty(&minFilter, err, o, "minFilter", false);
  4559. ParseIntegerProperty(&magFilter, err, o, "magFilter", false);
  4560. ParseIntegerProperty(&wrapS, err, o, "wrapS", false);
  4561. ParseIntegerProperty(&wrapT, err, o, "wrapT", false);
  4562. // ParseIntegerProperty(&wrapR, err, o, "wrapR", false); // tinygltf
  4563. // extension
  4564. // TODO(syoyo): Check the value is allowed one.
  4565. // (e.g. we allow 9728(NEAREST), but don't allow 9727)
  4566. sampler->minFilter = minFilter;
  4567. sampler->magFilter = magFilter;
  4568. sampler->wrapS = wrapS;
  4569. sampler->wrapT = wrapT;
  4570. // sampler->wrapR = wrapR;
  4571. ParseExtensionsProperty(&(sampler->extensions), err, o);
  4572. ParseExtrasProperty(&(sampler->extras), o);
  4573. if (store_original_json_for_extras_and_extensions) {
  4574. {
  4575. detail::json_const_iterator it;
  4576. if (detail::FindMember(o, "extensions", it)) {
  4577. sampler->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  4578. }
  4579. }
  4580. {
  4581. detail::json_const_iterator it;
  4582. if (detail::FindMember(o, "extras", it)) {
  4583. sampler->extras_json_string = detail::JsonToString(detail::GetValue(it));
  4584. }
  4585. }
  4586. }
  4587. return true;
  4588. }
  4589. static bool ParseSkin(Skin *skin, std::string *err, const detail::json &o,
  4590. bool store_original_json_for_extras_and_extensions) {
  4591. ParseStringProperty(&skin->name, err, o, "name", false, "Skin");
  4592. std::vector<int> joints;
  4593. if (!ParseIntegerArrayProperty(&joints, err, o, "joints", false, "Skin")) {
  4594. return false;
  4595. }
  4596. skin->joints = std::move(joints);
  4597. int skeleton = -1;
  4598. ParseIntegerProperty(&skeleton, err, o, "skeleton", false, "Skin");
  4599. skin->skeleton = skeleton;
  4600. int invBind = -1;
  4601. ParseIntegerProperty(&invBind, err, o, "inverseBindMatrices", true, "Skin");
  4602. skin->inverseBindMatrices = invBind;
  4603. ParseExtensionsProperty(&(skin->extensions), err, o);
  4604. ParseExtrasProperty(&(skin->extras), o);
  4605. if (store_original_json_for_extras_and_extensions) {
  4606. {
  4607. detail::json_const_iterator it;
  4608. if (detail::FindMember(o, "extensions", it)) {
  4609. skin->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  4610. }
  4611. }
  4612. {
  4613. detail::json_const_iterator it;
  4614. if (detail::FindMember(o, "extras", it)) {
  4615. skin->extras_json_string = detail::JsonToString(detail::GetValue(it));
  4616. }
  4617. }
  4618. }
  4619. return true;
  4620. }
  4621. static bool ParsePerspectiveCamera(
  4622. PerspectiveCamera *camera, std::string *err, const detail::json &o,
  4623. bool store_original_json_for_extras_and_extensions) {
  4624. double yfov = 0.0;
  4625. if (!ParseNumberProperty(&yfov, err, o, "yfov", true, "OrthographicCamera")) {
  4626. return false;
  4627. }
  4628. double znear = 0.0;
  4629. if (!ParseNumberProperty(&znear, err, o, "znear", true,
  4630. "PerspectiveCamera")) {
  4631. return false;
  4632. }
  4633. double aspectRatio = 0.0; // = invalid
  4634. ParseNumberProperty(&aspectRatio, err, o, "aspectRatio", false,
  4635. "PerspectiveCamera");
  4636. double zfar = 0.0; // = invalid
  4637. ParseNumberProperty(&zfar, err, o, "zfar", false, "PerspectiveCamera");
  4638. camera->aspectRatio = aspectRatio;
  4639. camera->zfar = zfar;
  4640. camera->yfov = yfov;
  4641. camera->znear = znear;
  4642. ParseExtensionsProperty(&camera->extensions, err, o);
  4643. ParseExtrasProperty(&(camera->extras), o);
  4644. if (store_original_json_for_extras_and_extensions) {
  4645. {
  4646. detail::json_const_iterator it;
  4647. if (detail::FindMember(o, "extensions", it)) {
  4648. camera->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  4649. }
  4650. }
  4651. {
  4652. detail::json_const_iterator it;
  4653. if (detail::FindMember(o, "extras", it)) {
  4654. camera->extras_json_string = detail::JsonToString(detail::GetValue(it));
  4655. }
  4656. }
  4657. }
  4658. // TODO(syoyo): Validate parameter values.
  4659. return true;
  4660. }
  4661. static bool ParseSpotLight(SpotLight *light, std::string *err, const detail::json &o,
  4662. bool store_original_json_for_extras_and_extensions) {
  4663. ParseNumberProperty(&light->innerConeAngle, err, o, "innerConeAngle", false);
  4664. ParseNumberProperty(&light->outerConeAngle, err, o, "outerConeAngle", false);
  4665. ParseExtensionsProperty(&light->extensions, err, o);
  4666. ParseExtrasProperty(&light->extras, o);
  4667. if (store_original_json_for_extras_and_extensions) {
  4668. {
  4669. detail::json_const_iterator it;
  4670. if (detail::FindMember(o, "extensions", it)) {
  4671. light->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  4672. }
  4673. }
  4674. {
  4675. detail::json_const_iterator it;
  4676. if (detail::FindMember(o, "extras", it)) {
  4677. light->extras_json_string = detail::JsonToString(detail::GetValue(it));
  4678. }
  4679. }
  4680. }
  4681. // TODO(syoyo): Validate parameter values.
  4682. return true;
  4683. }
  4684. static bool ParseOrthographicCamera(
  4685. OrthographicCamera *camera, std::string *err, const detail::json &o,
  4686. bool store_original_json_for_extras_and_extensions) {
  4687. double xmag = 0.0;
  4688. if (!ParseNumberProperty(&xmag, err, o, "xmag", true, "OrthographicCamera")) {
  4689. return false;
  4690. }
  4691. double ymag = 0.0;
  4692. if (!ParseNumberProperty(&ymag, err, o, "ymag", true, "OrthographicCamera")) {
  4693. return false;
  4694. }
  4695. double zfar = 0.0;
  4696. if (!ParseNumberProperty(&zfar, err, o, "zfar", true, "OrthographicCamera")) {
  4697. return false;
  4698. }
  4699. double znear = 0.0;
  4700. if (!ParseNumberProperty(&znear, err, o, "znear", true,
  4701. "OrthographicCamera")) {
  4702. return false;
  4703. }
  4704. ParseExtensionsProperty(&camera->extensions, err, o);
  4705. ParseExtrasProperty(&(camera->extras), o);
  4706. if (store_original_json_for_extras_and_extensions) {
  4707. {
  4708. detail::json_const_iterator it;
  4709. if (detail::FindMember(o, "extensions", it)) {
  4710. camera->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  4711. }
  4712. }
  4713. {
  4714. detail::json_const_iterator it;
  4715. if (detail::FindMember(o, "extras", it)) {
  4716. camera->extras_json_string = detail::JsonToString(detail::GetValue(it));
  4717. }
  4718. }
  4719. }
  4720. camera->xmag = xmag;
  4721. camera->ymag = ymag;
  4722. camera->zfar = zfar;
  4723. camera->znear = znear;
  4724. // TODO(syoyo): Validate parameter values.
  4725. return true;
  4726. }
  4727. static bool ParseCamera(Camera *camera, std::string *err, const detail::json &o,
  4728. bool store_original_json_for_extras_and_extensions) {
  4729. if (!ParseStringProperty(&camera->type, err, o, "type", true, "Camera")) {
  4730. return false;
  4731. }
  4732. if (camera->type.compare("orthographic") == 0) {
  4733. detail::json_const_iterator orthoIt;
  4734. if (!detail::FindMember(o, "orthographic", orthoIt)) {
  4735. if (err) {
  4736. std::stringstream ss;
  4737. ss << "Orthographic camera description not found." << std::endl;
  4738. (*err) += ss.str();
  4739. }
  4740. return false;
  4741. }
  4742. const detail::json &v = detail::GetValue(orthoIt);
  4743. if (!detail::IsObject(v)) {
  4744. if (err) {
  4745. std::stringstream ss;
  4746. ss << "\"orthographic\" is not a JSON object." << std::endl;
  4747. (*err) += ss.str();
  4748. }
  4749. return false;
  4750. }
  4751. if (!ParseOrthographicCamera(
  4752. &camera->orthographic, err, v,
  4753. store_original_json_for_extras_and_extensions)) {
  4754. return false;
  4755. }
  4756. } else if (camera->type.compare("perspective") == 0) {
  4757. detail::json_const_iterator perspIt;
  4758. if (!detail::FindMember(o, "perspective", perspIt)) {
  4759. if (err) {
  4760. std::stringstream ss;
  4761. ss << "Perspective camera description not found." << std::endl;
  4762. (*err) += ss.str();
  4763. }
  4764. return false;
  4765. }
  4766. const detail::json &v = detail::GetValue(perspIt);
  4767. if (!detail::IsObject(v)) {
  4768. if (err) {
  4769. std::stringstream ss;
  4770. ss << "\"perspective\" is not a JSON object." << std::endl;
  4771. (*err) += ss.str();
  4772. }
  4773. return false;
  4774. }
  4775. if (!ParsePerspectiveCamera(
  4776. &camera->perspective, err, v,
  4777. store_original_json_for_extras_and_extensions)) {
  4778. return false;
  4779. }
  4780. } else {
  4781. if (err) {
  4782. std::stringstream ss;
  4783. ss << "Invalid camera type: \"" << camera->type
  4784. << "\". Must be \"perspective\" or \"orthographic\"" << std::endl;
  4785. (*err) += ss.str();
  4786. }
  4787. return false;
  4788. }
  4789. ParseStringProperty(&camera->name, err, o, "name", false);
  4790. ParseExtensionsProperty(&camera->extensions, err, o);
  4791. ParseExtrasProperty(&(camera->extras), o);
  4792. if (store_original_json_for_extras_and_extensions) {
  4793. {
  4794. detail::json_const_iterator it;
  4795. if (detail::FindMember(o, "extensions", it)) {
  4796. camera->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  4797. }
  4798. }
  4799. {
  4800. detail::json_const_iterator it;
  4801. if (detail::FindMember(o, "extras", it)) {
  4802. camera->extras_json_string = detail::JsonToString(detail::GetValue(it));
  4803. }
  4804. }
  4805. }
  4806. return true;
  4807. }
  4808. static bool ParseLight(Light *light, std::string *err, const detail::json &o,
  4809. bool store_original_json_for_extras_and_extensions) {
  4810. if (!ParseStringProperty(&light->type, err, o, "type", true)) {
  4811. return false;
  4812. }
  4813. if (light->type == "spot") {
  4814. detail::json_const_iterator spotIt;
  4815. if (!detail::FindMember(o, "spot", spotIt)) {
  4816. if (err) {
  4817. std::stringstream ss;
  4818. ss << "Spot light description not found." << std::endl;
  4819. (*err) += ss.str();
  4820. }
  4821. return false;
  4822. }
  4823. const detail::json &v = detail::GetValue(spotIt);
  4824. if (!detail::IsObject(v)) {
  4825. if (err) {
  4826. std::stringstream ss;
  4827. ss << "\"spot\" is not a JSON object." << std::endl;
  4828. (*err) += ss.str();
  4829. }
  4830. return false;
  4831. }
  4832. if (!ParseSpotLight(&light->spot, err, v,
  4833. store_original_json_for_extras_and_extensions)) {
  4834. return false;
  4835. }
  4836. }
  4837. ParseStringProperty(&light->name, err, o, "name", false);
  4838. ParseNumberArrayProperty(&light->color, err, o, "color", false);
  4839. ParseNumberProperty(&light->range, err, o, "range", false);
  4840. ParseNumberProperty(&light->intensity, err, o, "intensity", false);
  4841. ParseExtensionsProperty(&light->extensions, err, o);
  4842. ParseExtrasProperty(&(light->extras), o);
  4843. if (store_original_json_for_extras_and_extensions) {
  4844. {
  4845. detail::json_const_iterator it;
  4846. if (detail::FindMember(o, "extensions", it)) {
  4847. light->extensions_json_string = detail::JsonToString(detail::GetValue(it));
  4848. }
  4849. }
  4850. {
  4851. detail::json_const_iterator it;
  4852. if (detail::FindMember(o, "extras", it)) {
  4853. light->extras_json_string = detail::JsonToString(detail::GetValue(it));
  4854. }
  4855. }
  4856. }
  4857. return true;
  4858. }
  4859. bool TinyGLTF::LoadFromString(Model *model, std::string *err, std::string *warn,
  4860. const char *json_str,
  4861. unsigned int json_str_length,
  4862. const std::string &base_dir,
  4863. unsigned int check_sections) {
  4864. if (json_str_length < 4) {
  4865. if (err) {
  4866. (*err) = "JSON string too short.\n";
  4867. }
  4868. return false;
  4869. }
  4870. detail::JsonDocument v;
  4871. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || \
  4872. defined(_CPPUNWIND)) && \
  4873. !defined(TINYGLTF_NOEXCEPTION)
  4874. try {
  4875. detail::JsonParse(v, json_str, json_str_length, true);
  4876. } catch (const std::exception &e) {
  4877. if (err) {
  4878. (*err) = e.what();
  4879. }
  4880. return false;
  4881. }
  4882. #else
  4883. {
  4884. detail::JsonParse(v, json_str, json_str_length);
  4885. if (!detail::IsObject(v)) {
  4886. // Assume parsing was failed.
  4887. if (err) {
  4888. (*err) = "Failed to parse JSON object\n";
  4889. }
  4890. return false;
  4891. }
  4892. }
  4893. #endif
  4894. if (!detail::IsObject(v)) {
  4895. // root is not an object.
  4896. if (err) {
  4897. (*err) = "Root element is not a JSON object\n";
  4898. }
  4899. return false;
  4900. }
  4901. {
  4902. bool version_found = false;
  4903. detail::json_const_iterator it;
  4904. if (detail::FindMember(v, "asset", it) && detail::IsObject(detail::GetValue(it))) {
  4905. auto &itObj = detail::GetValue(it);
  4906. detail::json_const_iterator version_it;
  4907. std::string versionStr;
  4908. if (detail::FindMember(itObj, "version", version_it) &&
  4909. detail::GetString(detail::GetValue(version_it), versionStr)) {
  4910. version_found = true;
  4911. }
  4912. }
  4913. if (version_found) {
  4914. // OK
  4915. } else if (check_sections & REQUIRE_VERSION) {
  4916. if (err) {
  4917. (*err) += "\"asset\" object not found in .gltf or not an object type\n";
  4918. }
  4919. return false;
  4920. }
  4921. }
  4922. // scene is not mandatory.
  4923. // FIXME Maybe a better way to handle it than removing the code
  4924. auto IsArrayMemberPresent = [](const detail::json &_v, const char *name) -> bool {
  4925. detail::json_const_iterator it;
  4926. return detail::FindMember(_v, name, it) && detail::IsArray(detail::GetValue(it));
  4927. };
  4928. {
  4929. if ((check_sections & REQUIRE_SCENES) &&
  4930. !IsArrayMemberPresent(v, "scenes")) {
  4931. if (err) {
  4932. (*err) += "\"scenes\" object not found in .gltf or not an array type\n";
  4933. }
  4934. return false;
  4935. }
  4936. }
  4937. {
  4938. if ((check_sections & REQUIRE_NODES) && !IsArrayMemberPresent(v, "nodes")) {
  4939. if (err) {
  4940. (*err) += "\"nodes\" object not found in .gltf\n";
  4941. }
  4942. return false;
  4943. }
  4944. }
  4945. {
  4946. if ((check_sections & REQUIRE_ACCESSORS) &&
  4947. !IsArrayMemberPresent(v, "accessors")) {
  4948. if (err) {
  4949. (*err) += "\"accessors\" object not found in .gltf\n";
  4950. }
  4951. return false;
  4952. }
  4953. }
  4954. {
  4955. if ((check_sections & REQUIRE_BUFFERS) &&
  4956. !IsArrayMemberPresent(v, "buffers")) {
  4957. if (err) {
  4958. (*err) += "\"buffers\" object not found in .gltf\n";
  4959. }
  4960. return false;
  4961. }
  4962. }
  4963. {
  4964. if ((check_sections & REQUIRE_BUFFER_VIEWS) &&
  4965. !IsArrayMemberPresent(v, "bufferViews")) {
  4966. if (err) {
  4967. (*err) += "\"bufferViews\" object not found in .gltf\n";
  4968. }
  4969. return false;
  4970. }
  4971. }
  4972. model->buffers.clear();
  4973. model->bufferViews.clear();
  4974. model->accessors.clear();
  4975. model->meshes.clear();
  4976. model->cameras.clear();
  4977. model->nodes.clear();
  4978. model->extensionsUsed.clear();
  4979. model->extensionsRequired.clear();
  4980. model->extensions.clear();
  4981. model->defaultScene = -1;
  4982. // 1. Parse Asset
  4983. {
  4984. detail::json_const_iterator it;
  4985. if (detail::FindMember(v, "asset", it) && detail::IsObject(detail::GetValue(it))) {
  4986. const detail::json &root = detail::GetValue(it);
  4987. ParseAsset(&model->asset, err, root,
  4988. store_original_json_for_extras_and_extensions_);
  4989. }
  4990. }
  4991. #ifdef TINYGLTF_USE_CPP14
  4992. auto ForEachInArray = [](const detail::json &_v, const char *member,
  4993. const auto &cb) -> bool
  4994. #else
  4995. // The std::function<> implementation can be less efficient because it will
  4996. // allocate heap when the size of the captured lambda is above 16 bytes with
  4997. // clang and gcc, but it does not require C++14.
  4998. auto ForEachInArray = [](const detail::json &_v, const char *member,
  4999. const std::function<bool(const detail::json &)> &cb) -> bool
  5000. #endif
  5001. {
  5002. detail::json_const_iterator itm;
  5003. if (detail::FindMember(_v, member, itm) && detail::IsArray(detail::GetValue(itm))) {
  5004. const detail::json &root = detail::GetValue(itm);
  5005. auto it = detail::ArrayBegin(root);
  5006. auto end = detail::ArrayEnd(root);
  5007. for (; it != end; ++it) {
  5008. if (!cb(*it)) return false;
  5009. }
  5010. }
  5011. return true;
  5012. };
  5013. // 2. Parse extensionUsed
  5014. {
  5015. ForEachInArray(v, "extensionsUsed", [&](const detail::json &o) {
  5016. std::string str;
  5017. detail::GetString(o, str);
  5018. model->extensionsUsed.emplace_back(std::move(str));
  5019. return true;
  5020. });
  5021. }
  5022. {
  5023. ForEachInArray(v, "extensionsRequired", [&](const detail::json &o) {
  5024. std::string str;
  5025. detail::GetString(o, str);
  5026. model->extensionsRequired.emplace_back(std::move(str));
  5027. return true;
  5028. });
  5029. }
  5030. // 3. Parse Buffer
  5031. {
  5032. bool success = ForEachInArray(v, "buffers", [&](const detail::json &o) {
  5033. if (!detail::IsObject(o)) {
  5034. if (err) {
  5035. (*err) += "`buffers' does not contain an JSON object.";
  5036. }
  5037. return false;
  5038. }
  5039. Buffer buffer;
  5040. if (!ParseBuffer(&buffer, err, o,
  5041. store_original_json_for_extras_and_extensions_, &fs,
  5042. &uri_cb, base_dir, is_binary_, bin_data_, bin_size_)) {
  5043. return false;
  5044. }
  5045. model->buffers.emplace_back(std::move(buffer));
  5046. return true;
  5047. });
  5048. if (!success) {
  5049. return false;
  5050. }
  5051. }
  5052. // 4. Parse BufferView
  5053. {
  5054. bool success = ForEachInArray(v, "bufferViews", [&](const detail::json &o) {
  5055. if (!detail::IsObject(o)) {
  5056. if (err) {
  5057. (*err) += "`bufferViews' does not contain an JSON object.";
  5058. }
  5059. return false;
  5060. }
  5061. BufferView bufferView;
  5062. if (!ParseBufferView(&bufferView, err, o,
  5063. store_original_json_for_extras_and_extensions_)) {
  5064. return false;
  5065. }
  5066. model->bufferViews.emplace_back(std::move(bufferView));
  5067. return true;
  5068. });
  5069. if (!success) {
  5070. return false;
  5071. }
  5072. }
  5073. // 5. Parse Accessor
  5074. {
  5075. bool success = ForEachInArray(v, "accessors", [&](const detail::json &o) {
  5076. if (!detail::IsObject(o)) {
  5077. if (err) {
  5078. (*err) += "`accessors' does not contain an JSON object.";
  5079. }
  5080. return false;
  5081. }
  5082. Accessor accessor;
  5083. if (!ParseAccessor(&accessor, err, o,
  5084. store_original_json_for_extras_and_extensions_)) {
  5085. return false;
  5086. }
  5087. model->accessors.emplace_back(std::move(accessor));
  5088. return true;
  5089. });
  5090. if (!success) {
  5091. return false;
  5092. }
  5093. }
  5094. // 6. Parse Mesh
  5095. {
  5096. bool success = ForEachInArray(v, "meshes", [&](const detail::json &o) {
  5097. if (!detail::IsObject(o)) {
  5098. if (err) {
  5099. (*err) += "`meshes' does not contain an JSON object.";
  5100. }
  5101. return false;
  5102. }
  5103. Mesh mesh;
  5104. if (!ParseMesh(&mesh, model, err, o,
  5105. store_original_json_for_extras_and_extensions_)) {
  5106. return false;
  5107. }
  5108. model->meshes.emplace_back(std::move(mesh));
  5109. return true;
  5110. });
  5111. if (!success) {
  5112. return false;
  5113. }
  5114. }
  5115. // Assign missing bufferView target types
  5116. // - Look for missing Mesh indices
  5117. // - Look for missing Mesh attributes
  5118. for (auto &mesh : model->meshes) {
  5119. for (auto &primitive : mesh.primitives) {
  5120. if (primitive.indices >
  5121. -1) // has indices from parsing step, must be Element Array Buffer
  5122. {
  5123. if (size_t(primitive.indices) >= model->accessors.size()) {
  5124. if (err) {
  5125. (*err) += "primitive indices accessor out of bounds";
  5126. }
  5127. return false;
  5128. }
  5129. auto bufferView =
  5130. model->accessors[size_t(primitive.indices)].bufferView;
  5131. if (bufferView < 0 || size_t(bufferView) >= model->bufferViews.size()) {
  5132. if (err) {
  5133. (*err) += "accessor[" + std::to_string(primitive.indices) +
  5134. "] invalid bufferView";
  5135. }
  5136. return false;
  5137. }
  5138. model->bufferViews[size_t(bufferView)].target =
  5139. TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER;
  5140. // we could optionally check if accessors' bufferView type is Scalar, as
  5141. // it should be
  5142. }
  5143. for (auto &attribute : primitive.attributes) {
  5144. const auto accessorsIndex = size_t(attribute.second);
  5145. if (accessorsIndex < model->accessors.size()) {
  5146. const auto bufferView = model->accessors[accessorsIndex].bufferView;
  5147. // bufferView could be null(-1) for sparse morph target
  5148. if (bufferView >= 0 && bufferView < (int)model->bufferViews.size()) {
  5149. model->bufferViews[size_t(bufferView)].target =
  5150. TINYGLTF_TARGET_ARRAY_BUFFER;
  5151. }
  5152. }
  5153. }
  5154. for (auto &target : primitive.targets) {
  5155. for (auto &attribute : target) {
  5156. const auto accessorsIndex = size_t(attribute.second);
  5157. if (accessorsIndex < model->accessors.size()) {
  5158. const auto bufferView = model->accessors[accessorsIndex].bufferView;
  5159. // bufferView could be null(-1) for sparse morph target
  5160. if (bufferView >= 0 && bufferView < (int)model->bufferViews.size()) {
  5161. model->bufferViews[size_t(bufferView)].target =
  5162. TINYGLTF_TARGET_ARRAY_BUFFER;
  5163. }
  5164. }
  5165. }
  5166. }
  5167. }
  5168. }
  5169. // 7. Parse Node
  5170. {
  5171. bool success = ForEachInArray(v, "nodes", [&](const detail::json &o) {
  5172. if (!detail::IsObject(o)) {
  5173. if (err) {
  5174. (*err) += "`nodes' does not contain an JSON object.";
  5175. }
  5176. return false;
  5177. }
  5178. Node node;
  5179. if (!ParseNode(&node, err, o,
  5180. store_original_json_for_extras_and_extensions_)) {
  5181. return false;
  5182. }
  5183. model->nodes.emplace_back(std::move(node));
  5184. return true;
  5185. });
  5186. if (!success) {
  5187. return false;
  5188. }
  5189. }
  5190. // 8. Parse scenes.
  5191. {
  5192. bool success = ForEachInArray(v, "scenes", [&](const detail::json &o) {
  5193. if (!detail::IsObject(o)) {
  5194. if (err) {
  5195. (*err) += "`scenes' does not contain an JSON object.";
  5196. }
  5197. return false;
  5198. }
  5199. std::vector<int> nodes;
  5200. ParseIntegerArrayProperty(&nodes, err, o, "nodes", false);
  5201. Scene scene;
  5202. scene.nodes = std::move(nodes);
  5203. ParseStringProperty(&scene.name, err, o, "name", false);
  5204. ParseExtensionsProperty(&scene.extensions, err, o);
  5205. ParseExtrasProperty(&scene.extras, o);
  5206. if (store_original_json_for_extras_and_extensions_) {
  5207. {
  5208. detail::json_const_iterator it;
  5209. if (detail::FindMember(o, "extensions", it)) {
  5210. scene.extensions_json_string = detail::JsonToString(detail::GetValue(it));
  5211. }
  5212. }
  5213. {
  5214. detail::json_const_iterator it;
  5215. if (detail::FindMember(o, "extras", it)) {
  5216. scene.extras_json_string = detail::JsonToString(detail::GetValue(it));
  5217. }
  5218. }
  5219. }
  5220. model->scenes.emplace_back(std::move(scene));
  5221. return true;
  5222. });
  5223. if (!success) {
  5224. return false;
  5225. }
  5226. }
  5227. // 9. Parse default scenes.
  5228. {
  5229. detail::json_const_iterator rootIt;
  5230. int iVal;
  5231. if (detail::FindMember(v, "scene", rootIt) && detail::GetInt(detail::GetValue(rootIt), iVal)) {
  5232. model->defaultScene = iVal;
  5233. }
  5234. }
  5235. // 10. Parse Material
  5236. {
  5237. bool success = ForEachInArray(v, "materials", [&](const detail::json &o) {
  5238. if (!detail::IsObject(o)) {
  5239. if (err) {
  5240. (*err) += "`materials' does not contain an JSON object.";
  5241. }
  5242. return false;
  5243. }
  5244. Material material;
  5245. ParseStringProperty(&material.name, err, o, "name", false);
  5246. if (!ParseMaterial(&material, err, o,
  5247. store_original_json_for_extras_and_extensions_)) {
  5248. return false;
  5249. }
  5250. model->materials.emplace_back(std::move(material));
  5251. return true;
  5252. });
  5253. if (!success) {
  5254. return false;
  5255. }
  5256. }
  5257. // 11. Parse Image
  5258. void *load_image_user_data{nullptr};
  5259. LoadImageDataOption load_image_option;
  5260. if (user_image_loader_) {
  5261. // Use user supplied pointer
  5262. load_image_user_data = load_image_user_data_;
  5263. } else {
  5264. load_image_option.preserve_channels = preserve_image_channels_;
  5265. load_image_user_data = reinterpret_cast<void *>(&load_image_option);
  5266. }
  5267. {
  5268. int idx = 0;
  5269. bool success = ForEachInArray(v, "images", [&](const detail::json &o) {
  5270. if (!detail::IsObject(o)) {
  5271. if (err) {
  5272. (*err) += "image[" + std::to_string(idx) + "] is not a JSON object.";
  5273. }
  5274. return false;
  5275. }
  5276. Image image;
  5277. if (!ParseImage(&image, idx, err, warn, o,
  5278. store_original_json_for_extras_and_extensions_, base_dir,
  5279. &fs, &uri_cb, &this->LoadImageData,
  5280. load_image_user_data)) {
  5281. return false;
  5282. }
  5283. if (image.bufferView != -1) {
  5284. // Load image from the buffer view.
  5285. if (size_t(image.bufferView) >= model->bufferViews.size()) {
  5286. if (err) {
  5287. std::stringstream ss;
  5288. ss << "image[" << idx << "] bufferView \"" << image.bufferView
  5289. << "\" not found in the scene." << std::endl;
  5290. (*err) += ss.str();
  5291. }
  5292. return false;
  5293. }
  5294. const BufferView &bufferView =
  5295. model->bufferViews[size_t(image.bufferView)];
  5296. if (size_t(bufferView.buffer) >= model->buffers.size()) {
  5297. if (err) {
  5298. std::stringstream ss;
  5299. ss << "image[" << idx << "] buffer \"" << bufferView.buffer
  5300. << "\" not found in the scene." << std::endl;
  5301. (*err) += ss.str();
  5302. }
  5303. return false;
  5304. }
  5305. const Buffer &buffer = model->buffers[size_t(bufferView.buffer)];
  5306. if (*LoadImageData == nullptr) {
  5307. if (err) {
  5308. (*err) += "No LoadImageData callback specified.\n";
  5309. }
  5310. return false;
  5311. }
  5312. bool ret = LoadImageData(
  5313. &image, idx, err, warn, image.width, image.height,
  5314. &buffer.data[bufferView.byteOffset],
  5315. static_cast<int>(bufferView.byteLength), load_image_user_data);
  5316. if (!ret) {
  5317. return false;
  5318. }
  5319. }
  5320. model->images.emplace_back(std::move(image));
  5321. ++idx;
  5322. return true;
  5323. });
  5324. if (!success) {
  5325. return false;
  5326. }
  5327. }
  5328. // 12. Parse Texture
  5329. {
  5330. bool success = ForEachInArray(v, "textures", [&](const detail::json &o) {
  5331. if (!detail::IsObject(o)) {
  5332. if (err) {
  5333. (*err) += "`textures' does not contain an JSON object.";
  5334. }
  5335. return false;
  5336. }
  5337. Texture texture;
  5338. if (!ParseTexture(&texture, err, o,
  5339. store_original_json_for_extras_and_extensions_,
  5340. base_dir)) {
  5341. return false;
  5342. }
  5343. model->textures.emplace_back(std::move(texture));
  5344. return true;
  5345. });
  5346. if (!success) {
  5347. return false;
  5348. }
  5349. }
  5350. // 13. Parse Animation
  5351. {
  5352. bool success = ForEachInArray(v, "animations", [&](const detail::json &o) {
  5353. if (!detail::IsObject(o)) {
  5354. if (err) {
  5355. (*err) += "`animations' does not contain an JSON object.";
  5356. }
  5357. return false;
  5358. }
  5359. Animation animation;
  5360. if (!ParseAnimation(&animation, err, o,
  5361. store_original_json_for_extras_and_extensions_)) {
  5362. return false;
  5363. }
  5364. model->animations.emplace_back(std::move(animation));
  5365. return true;
  5366. });
  5367. if (!success) {
  5368. return false;
  5369. }
  5370. }
  5371. // 14. Parse Skin
  5372. {
  5373. bool success = ForEachInArray(v, "skins", [&](const detail::json &o) {
  5374. if (!detail::IsObject(o)) {
  5375. if (err) {
  5376. (*err) += "`skins' does not contain an JSON object.";
  5377. }
  5378. return false;
  5379. }
  5380. Skin skin;
  5381. if (!ParseSkin(&skin, err, o,
  5382. store_original_json_for_extras_and_extensions_)) {
  5383. return false;
  5384. }
  5385. model->skins.emplace_back(std::move(skin));
  5386. return true;
  5387. });
  5388. if (!success) {
  5389. return false;
  5390. }
  5391. }
  5392. // 15. Parse Sampler
  5393. {
  5394. bool success = ForEachInArray(v, "samplers", [&](const detail::json &o) {
  5395. if (!detail::IsObject(o)) {
  5396. if (err) {
  5397. (*err) += "`samplers' does not contain an JSON object.";
  5398. }
  5399. return false;
  5400. }
  5401. Sampler sampler;
  5402. if (!ParseSampler(&sampler, err, o,
  5403. store_original_json_for_extras_and_extensions_)) {
  5404. return false;
  5405. }
  5406. model->samplers.emplace_back(std::move(sampler));
  5407. return true;
  5408. });
  5409. if (!success) {
  5410. return false;
  5411. }
  5412. }
  5413. // 16. Parse Camera
  5414. {
  5415. bool success = ForEachInArray(v, "cameras", [&](const detail::json &o) {
  5416. if (!detail::IsObject(o)) {
  5417. if (err) {
  5418. (*err) += "`cameras' does not contain an JSON object.";
  5419. }
  5420. return false;
  5421. }
  5422. Camera camera;
  5423. if (!ParseCamera(&camera, err, o,
  5424. store_original_json_for_extras_and_extensions_)) {
  5425. return false;
  5426. }
  5427. model->cameras.emplace_back(std::move(camera));
  5428. return true;
  5429. });
  5430. if (!success) {
  5431. return false;
  5432. }
  5433. }
  5434. // 17. Parse Extensions
  5435. ParseExtensionsProperty(&model->extensions, err, v);
  5436. // 18. Specific extension implementations
  5437. {
  5438. detail::json_const_iterator rootIt;
  5439. if (detail::FindMember(v, "extensions", rootIt) && detail::IsObject(detail::GetValue(rootIt))) {
  5440. const detail::json &root = detail::GetValue(rootIt);
  5441. detail::json_const_iterator it(detail::ObjectBegin(root));
  5442. detail::json_const_iterator itEnd(detail::ObjectEnd(root));
  5443. for (; it != itEnd; ++it) {
  5444. // parse KHR_lights_punctual extension
  5445. std::string key(detail::GetKey(it));
  5446. if ((key == "KHR_lights_punctual") && detail::IsObject(detail::GetValue(it))) {
  5447. const detail::json &object = detail::GetValue(it);
  5448. detail::json_const_iterator itLight;
  5449. if (detail::FindMember(object, "lights", itLight)) {
  5450. const detail::json &lights = detail::GetValue(itLight);
  5451. if (!detail::IsArray(lights)) {
  5452. continue;
  5453. }
  5454. auto arrayIt(detail::ArrayBegin(lights));
  5455. auto arrayItEnd(detail::ArrayEnd(lights));
  5456. for (; arrayIt != arrayItEnd; ++arrayIt) {
  5457. Light light;
  5458. if (!ParseLight(&light, err, *arrayIt,
  5459. store_original_json_for_extras_and_extensions_)) {
  5460. return false;
  5461. }
  5462. model->lights.emplace_back(std::move(light));
  5463. }
  5464. }
  5465. }
  5466. }
  5467. }
  5468. }
  5469. // 19. Parse Extras
  5470. ParseExtrasProperty(&model->extras, v);
  5471. if (store_original_json_for_extras_and_extensions_) {
  5472. model->extras_json_string = detail::JsonToString(v["extras"]);
  5473. model->extensions_json_string = detail::JsonToString(v["extensions"]);
  5474. }
  5475. return true;
  5476. }
  5477. bool TinyGLTF::LoadASCIIFromString(Model *model, std::string *err,
  5478. std::string *warn, const char *str,
  5479. unsigned int length,
  5480. const std::string &base_dir,
  5481. unsigned int check_sections) {
  5482. is_binary_ = false;
  5483. bin_data_ = nullptr;
  5484. bin_size_ = 0;
  5485. return LoadFromString(model, err, warn, str, length, base_dir,
  5486. check_sections);
  5487. }
  5488. bool TinyGLTF::LoadASCIIFromFile(Model *model, std::string *err,
  5489. std::string *warn, const std::string &filename,
  5490. unsigned int check_sections) {
  5491. std::stringstream ss;
  5492. if (fs.ReadWholeFile == nullptr) {
  5493. // Programmer error, assert() ?
  5494. ss << "Failed to read file: " << filename
  5495. << ": one or more FS callback not set" << std::endl;
  5496. if (err) {
  5497. (*err) = ss.str();
  5498. }
  5499. return false;
  5500. }
  5501. std::vector<unsigned char> data;
  5502. std::string fileerr;
  5503. bool fileread = fs.ReadWholeFile(&data, &fileerr, filename, fs.user_data);
  5504. if (!fileread) {
  5505. ss << "Failed to read file: " << filename << ": " << fileerr << std::endl;
  5506. if (err) {
  5507. (*err) = ss.str();
  5508. }
  5509. return false;
  5510. }
  5511. size_t sz = data.size();
  5512. if (sz == 0) {
  5513. if (err) {
  5514. (*err) = "Empty file.";
  5515. }
  5516. return false;
  5517. }
  5518. std::string basedir = GetBaseDir(filename);
  5519. bool ret = LoadASCIIFromString(
  5520. model, err, warn, reinterpret_cast<const char *>(&data.at(0)),
  5521. static_cast<unsigned int>(data.size()), basedir, check_sections);
  5522. return ret;
  5523. }
  5524. bool TinyGLTF::LoadBinaryFromMemory(Model *model, std::string *err,
  5525. std::string *warn,
  5526. const unsigned char *bytes,
  5527. unsigned int size,
  5528. const std::string &base_dir,
  5529. unsigned int check_sections) {
  5530. if (size < 20) {
  5531. if (err) {
  5532. (*err) = "Too short data size for glTF Binary.";
  5533. }
  5534. return false;
  5535. }
  5536. if (bytes[0] == 'g' && bytes[1] == 'l' && bytes[2] == 'T' &&
  5537. bytes[3] == 'F') {
  5538. // ok
  5539. } else {
  5540. if (err) {
  5541. (*err) = "Invalid magic.";
  5542. }
  5543. return false;
  5544. }
  5545. unsigned int version; // 4 bytes
  5546. unsigned int length; // 4 bytes
  5547. unsigned int chunk0_length; // 4 bytes
  5548. unsigned int chunk0_format; // 4 bytes;
  5549. memcpy(&version, bytes + 4, 4);
  5550. swap4(&version);
  5551. memcpy(&length, bytes + 8, 4);
  5552. swap4(&length);
  5553. memcpy(&chunk0_length, bytes + 12, 4); // JSON data length
  5554. swap4(&chunk0_length);
  5555. memcpy(&chunk0_format, bytes + 16, 4);
  5556. swap4(&chunk0_format);
  5557. // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#binary-gltf-layout
  5558. //
  5559. // In case the Bin buffer is not present, the size is exactly 20 + size of
  5560. // JSON contents,
  5561. // so use "greater than" operator.
  5562. //
  5563. // https://github.com/syoyo/tinygltf/issues/372
  5564. // Use 64bit uint to avoid integer overflow.
  5565. uint64_t header_and_json_size = 20ull + uint64_t(chunk0_length);
  5566. if (header_and_json_size > std::numeric_limits<uint32_t>::max()) {
  5567. // Do not allow 4GB or more GLB data.
  5568. (*err) = "Invalid glTF binary. GLB data exceeds 4GB.";
  5569. }
  5570. if ((header_and_json_size > uint64_t(size)) || (chunk0_length < 1) || (length > size) ||
  5571. (header_and_json_size > uint64_t(length)) ||
  5572. (chunk0_format != 0x4E4F534A)) { // 0x4E4F534A = JSON format.
  5573. if (err) {
  5574. (*err) = "Invalid glTF binary.";
  5575. }
  5576. return false;
  5577. }
  5578. // Padding check
  5579. // The start and the end of each chunk must be aligned to a 4-byte boundary.
  5580. // No padding check for chunk0 start since its 4byte-boundary is ensured.
  5581. if ((header_and_json_size % 4) != 0) {
  5582. if (err) {
  5583. (*err) = "JSON Chunk end does not aligned to a 4-byte boundary.";
  5584. }
  5585. }
  5586. //std::cout << "header_and_json_size = " << header_and_json_size << "\n";
  5587. //std::cout << "length = " << length << "\n";
  5588. // Chunk1(BIN) data
  5589. // The spec says: When the binary buffer is empty or when it is stored by other means, this chunk SHOULD be omitted.
  5590. // So when header + JSON data == binary size, Chunk1 is omitted.
  5591. if (header_and_json_size == uint64_t(length)) {
  5592. bin_data_ = nullptr;
  5593. bin_size_ = 0;
  5594. } else {
  5595. // Read Chunk1 info(BIN data)
  5596. // At least Chunk1 should have 12 bytes(8 bytes(header) + 4 bytes(bin payload could be 1~3 bytes, but need to be aligned to 4 bytes)
  5597. if ((header_and_json_size + 12ull) > uint64_t(length)) {
  5598. if (err) {
  5599. (*err) = "Insufficient storage space for Chunk1(BIN data). At least Chunk1 Must have 4 bytes or more bytes, but got " + std::to_string((header_and_json_size + 12ull) - uint64_t(length)) + ".\n";
  5600. }
  5601. return false;
  5602. }
  5603. unsigned int chunk1_length; // 4 bytes
  5604. unsigned int chunk1_format; // 4 bytes;
  5605. memcpy(&chunk1_length, bytes + header_and_json_size, 4); // JSON data length
  5606. swap4(&chunk1_length);
  5607. memcpy(&chunk1_format, bytes + header_and_json_size + 4, 4);
  5608. swap4(&chunk1_format);
  5609. //std::cout << "chunk1_length = " << chunk1_length << "\n";
  5610. if (chunk1_length < 4) {
  5611. if (err) {
  5612. (*err) = "Insufficient Chunk1(BIN) data size.";
  5613. }
  5614. return false;
  5615. }
  5616. if ((chunk1_length % 4) != 0) {
  5617. if (err) {
  5618. (*err) = "BIN Chunk end does not aligned to a 4-byte boundary.";
  5619. }
  5620. return false;
  5621. }
  5622. if (uint64_t(chunk1_length) + header_and_json_size > uint64_t(length)) {
  5623. if (err) {
  5624. (*err) = "BIN Chunk data length exceeds the GLB size.";
  5625. }
  5626. return false;
  5627. }
  5628. if (chunk1_format != 0x004e4942) {
  5629. if (err) {
  5630. (*err) = "Invalid type for chunk1 data.";
  5631. }
  5632. return false;
  5633. }
  5634. //std::cout << "chunk1_length = " << chunk1_length << "\n";
  5635. bin_data_ = bytes + header_and_json_size +
  5636. 8; // 4 bytes (bin_buffer_length) + 4 bytes(bin_buffer_format)
  5637. bin_size_ = size_t(chunk1_length);
  5638. }
  5639. // Extract JSON string.
  5640. std::string jsonString(reinterpret_cast<const char *>(&bytes[20]),
  5641. chunk0_length);
  5642. is_binary_ = true;
  5643. bool ret = LoadFromString(model, err, warn,
  5644. reinterpret_cast<const char *>(&bytes[20]),
  5645. chunk0_length, base_dir, check_sections);
  5646. if (!ret) {
  5647. return ret;
  5648. }
  5649. return true;
  5650. }
  5651. bool TinyGLTF::LoadBinaryFromFile(Model *model, std::string *err,
  5652. std::string *warn,
  5653. const std::string &filename,
  5654. unsigned int check_sections) {
  5655. std::stringstream ss;
  5656. if (fs.ReadWholeFile == nullptr) {
  5657. // Programmer error, assert() ?
  5658. ss << "Failed to read file: " << filename
  5659. << ": one or more FS callback not set" << std::endl;
  5660. if (err) {
  5661. (*err) = ss.str();
  5662. }
  5663. return false;
  5664. }
  5665. std::vector<unsigned char> data;
  5666. std::string fileerr;
  5667. bool fileread = fs.ReadWholeFile(&data, &fileerr, filename, fs.user_data);
  5668. if (!fileread) {
  5669. ss << "Failed to read file: " << filename << ": " << fileerr << std::endl;
  5670. if (err) {
  5671. (*err) = ss.str();
  5672. }
  5673. return false;
  5674. }
  5675. std::string basedir = "";// GetBaseDir(filename);
  5676. bool ret = LoadBinaryFromMemory(model, err, warn, &data.at(0),
  5677. static_cast<unsigned int>(data.size()),
  5678. basedir, check_sections);
  5679. return ret;
  5680. }
  5681. ///////////////////////
  5682. // GLTF Serialization
  5683. ///////////////////////
  5684. namespace detail {
  5685. detail::json JsonFromString(const char *s) {
  5686. #ifdef TINYGLTF_USE_RAPIDJSON
  5687. return detail::json(s, detail::GetAllocator());
  5688. #else
  5689. return detail::json(s);
  5690. #endif
  5691. }
  5692. void JsonAssign(detail::json &dest, const detail::json &src) {
  5693. #ifdef TINYGLTF_USE_RAPIDJSON
  5694. dest.CopyFrom(src, detail::GetAllocator());
  5695. #else
  5696. dest = src;
  5697. #endif
  5698. }
  5699. void JsonAddMember(detail::json &o, const char *key, detail::json &&value) {
  5700. #ifdef TINYGLTF_USE_RAPIDJSON
  5701. if (!o.IsObject()) {
  5702. o.SetObject();
  5703. }
  5704. o.AddMember(detail::json(key, detail::GetAllocator()), std::move(value), detail::GetAllocator());
  5705. #else
  5706. o[key] = std::move(value);
  5707. #endif
  5708. }
  5709. void JsonPushBack(detail::json &o, detail::json &&value) {
  5710. #ifdef TINYGLTF_USE_RAPIDJSON
  5711. o.PushBack(std::move(value), detail::GetAllocator());
  5712. #else
  5713. o.push_back(std::move(value));
  5714. #endif
  5715. }
  5716. bool JsonIsNull(const detail::json &o) {
  5717. #ifdef TINYGLTF_USE_RAPIDJSON
  5718. return o.IsNull();
  5719. #else
  5720. return o.is_null();
  5721. #endif
  5722. }
  5723. void JsonSetObject(detail::json &o) {
  5724. #ifdef TINYGLTF_USE_RAPIDJSON
  5725. o.SetObject();
  5726. #else
  5727. o = o.object({});
  5728. #endif
  5729. }
  5730. void JsonReserveArray(detail::json &o, size_t s) {
  5731. #ifdef TINYGLTF_USE_RAPIDJSON
  5732. o.SetArray();
  5733. o.Reserve(static_cast<rapidjson::SizeType>(s), detail::GetAllocator());
  5734. #endif
  5735. (void)(o);
  5736. (void)(s);
  5737. }
  5738. } // namespace
  5739. // typedef std::pair<std::string, detail::json> json_object_pair;
  5740. template <typename T>
  5741. static void SerializeNumberProperty(const std::string &key, T number,
  5742. detail::json &obj) {
  5743. // obj.insert(
  5744. // json_object_pair(key, detail::json(static_cast<double>(number))));
  5745. // obj[key] = static_cast<double>(number);
  5746. detail::JsonAddMember(obj, key.c_str(), detail::json(number));
  5747. }
  5748. #ifdef TINYGLTF_USE_RAPIDJSON
  5749. template <>
  5750. void SerializeNumberProperty(const std::string &key, size_t number, detail::json &obj) {
  5751. detail::JsonAddMember(obj, key.c_str(), detail::json(static_cast<uint64_t>(number)));
  5752. }
  5753. #endif
  5754. template <typename T>
  5755. static void SerializeNumberArrayProperty(const std::string &key,
  5756. const std::vector<T> &value,
  5757. detail::json &obj) {
  5758. if (value.empty()) return;
  5759. detail::json ary;
  5760. detail::JsonReserveArray(ary, value.size());
  5761. for (const auto &s : value) {
  5762. detail::JsonPushBack(ary, detail::json(s));
  5763. }
  5764. detail::JsonAddMember(obj, key.c_str(), std::move(ary));
  5765. }
  5766. static void SerializeStringProperty(const std::string &key,
  5767. const std::string &value, detail::json &obj) {
  5768. detail::JsonAddMember(obj, key.c_str(), detail::JsonFromString(value.c_str()));
  5769. }
  5770. static void SerializeStringArrayProperty(const std::string &key,
  5771. const std::vector<std::string> &value,
  5772. detail::json &obj) {
  5773. detail::json ary;
  5774. detail::JsonReserveArray(ary, value.size());
  5775. for (auto &s : value) {
  5776. detail::JsonPushBack(ary, detail::JsonFromString(s.c_str()));
  5777. }
  5778. detail::JsonAddMember(obj, key.c_str(), std::move(ary));
  5779. }
  5780. static bool ValueToJson(const Value &value, detail::json *ret) {
  5781. detail::json obj;
  5782. #ifdef TINYGLTF_USE_RAPIDJSON
  5783. switch (value.Type()) {
  5784. case REAL_TYPE:
  5785. obj.SetDouble(value.Get<double>());
  5786. break;
  5787. case INT_TYPE:
  5788. obj.SetInt(value.Get<int>());
  5789. break;
  5790. case BOOL_TYPE:
  5791. obj.SetBool(value.Get<bool>());
  5792. break;
  5793. case STRING_TYPE:
  5794. obj.SetString(value.Get<std::string>().c_str(), detail::GetAllocator());
  5795. break;
  5796. case ARRAY_TYPE: {
  5797. obj.SetArray();
  5798. obj.Reserve(static_cast<rapidjson::SizeType>(value.ArrayLen()),
  5799. detail::GetAllocator());
  5800. for (unsigned int i = 0; i < value.ArrayLen(); ++i) {
  5801. Value elementValue = value.Get(int(i));
  5802. detail::json elementJson;
  5803. if (ValueToJson(value.Get(int(i)), &elementJson))
  5804. obj.PushBack(std::move(elementJson), detail::GetAllocator());
  5805. }
  5806. break;
  5807. }
  5808. case BINARY_TYPE:
  5809. // TODO
  5810. // obj = detail::json(value.Get<std::vector<unsigned char>>());
  5811. return false;
  5812. break;
  5813. case OBJECT_TYPE: {
  5814. obj.SetObject();
  5815. Value::Object objMap = value.Get<Value::Object>();
  5816. for (auto &it : objMap) {
  5817. detail::json elementJson;
  5818. if (ValueToJson(it.second, &elementJson)) {
  5819. obj.AddMember(detail::json(it.first.c_str(), detail::GetAllocator()),
  5820. std::move(elementJson), detail::GetAllocator());
  5821. }
  5822. }
  5823. break;
  5824. }
  5825. case NULL_TYPE:
  5826. default:
  5827. return false;
  5828. }
  5829. #else
  5830. switch (value.Type()) {
  5831. case REAL_TYPE:
  5832. obj = detail::json(value.Get<double>());
  5833. break;
  5834. case INT_TYPE:
  5835. obj = detail::json(value.Get<int>());
  5836. break;
  5837. case BOOL_TYPE:
  5838. obj = detail::json(value.Get<bool>());
  5839. break;
  5840. case STRING_TYPE:
  5841. obj = detail::json(value.Get<std::string>());
  5842. break;
  5843. case ARRAY_TYPE: {
  5844. for (unsigned int i = 0; i < value.ArrayLen(); ++i) {
  5845. Value elementValue = value.Get(int(i));
  5846. detail::json elementJson;
  5847. if (ValueToJson(value.Get(int(i)), &elementJson))
  5848. obj.push_back(elementJson);
  5849. }
  5850. break;
  5851. }
  5852. case BINARY_TYPE:
  5853. // TODO
  5854. // obj = json(value.Get<std::vector<unsigned char>>());
  5855. return false;
  5856. break;
  5857. case OBJECT_TYPE: {
  5858. Value::Object objMap = value.Get<Value::Object>();
  5859. for (auto &it : objMap) {
  5860. detail::json elementJson;
  5861. if (ValueToJson(it.second, &elementJson)) obj[it.first] = elementJson;
  5862. }
  5863. break;
  5864. }
  5865. case NULL_TYPE:
  5866. default:
  5867. return false;
  5868. }
  5869. #endif
  5870. if (ret) *ret = std::move(obj);
  5871. return true;
  5872. }
  5873. static void SerializeValue(const std::string &key, const Value &value,
  5874. detail::json &obj) {
  5875. detail::json ret;
  5876. if (ValueToJson(value, &ret)) {
  5877. detail::JsonAddMember(obj, key.c_str(), std::move(ret));
  5878. }
  5879. }
  5880. static void SerializeGltfBufferData(const std::vector<unsigned char> &data,
  5881. detail::json &o) {
  5882. std::string header = "data:application/octet-stream;base64,";
  5883. if (data.size() > 0) {
  5884. std::string encodedData =
  5885. base64_encode(&data[0], static_cast<unsigned int>(data.size()));
  5886. SerializeStringProperty("uri", header + encodedData, o);
  5887. } else {
  5888. // Issue #229
  5889. // size 0 is allowed. Just emit mime header.
  5890. SerializeStringProperty("uri", header, o);
  5891. }
  5892. }
  5893. static bool SerializeGltfBufferData(const std::vector<unsigned char> &data,
  5894. const std::string &binFilename) {
  5895. #ifdef _WIN32
  5896. #if defined(__GLIBCXX__) // mingw
  5897. int file_descriptor = _wopen(UTF8ToWchar(binFilename).c_str(),
  5898. _O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY);
  5899. __gnu_cxx::stdio_filebuf<char> wfile_buf(
  5900. file_descriptor, std::ios_base::out | std::ios_base::binary);
  5901. std::ostream output(&wfile_buf);
  5902. if (!wfile_buf.is_open()) return false;
  5903. #elif defined(_MSC_VER)
  5904. std::ofstream output(UTF8ToWchar(binFilename).c_str(), std::ofstream::binary);
  5905. if (!output.is_open()) return false;
  5906. #else
  5907. std::ofstream output(binFilename.c_str(), std::ofstream::binary);
  5908. if (!output.is_open()) return false;
  5909. #endif
  5910. #else
  5911. std::ofstream output(binFilename.c_str(), std::ofstream::binary);
  5912. if (!output.is_open()) return false;
  5913. #endif
  5914. if (data.size() > 0) {
  5915. output.write(reinterpret_cast<const char *>(&data[0]),
  5916. std::streamsize(data.size()));
  5917. } else {
  5918. // Issue #229
  5919. // size 0 will be still valid buffer data.
  5920. // write empty file.
  5921. }
  5922. return true;
  5923. }
  5924. #if 0 // FIXME(syoyo): not used. will be removed in the future release.
  5925. static void SerializeParameterMap(ParameterMap &param, detail::json &o) {
  5926. for (ParameterMap::iterator paramIt = param.begin(); paramIt != param.end();
  5927. ++paramIt) {
  5928. if (paramIt->second.number_array.size()) {
  5929. SerializeNumberArrayProperty<double>(paramIt->first,
  5930. paramIt->second.number_array, o);
  5931. } else if (paramIt->second.json_double_value.size()) {
  5932. detail::json json_double_value;
  5933. for (std::map<std::string, double>::iterator it =
  5934. paramIt->second.json_double_value.begin();
  5935. it != paramIt->second.json_double_value.end(); ++it) {
  5936. if (it->first == "index") {
  5937. json_double_value[it->first] = paramIt->second.TextureIndex();
  5938. } else {
  5939. json_double_value[it->first] = it->second;
  5940. }
  5941. }
  5942. o[paramIt->first] = json_double_value;
  5943. } else if (!paramIt->second.string_value.empty()) {
  5944. SerializeStringProperty(paramIt->first, paramIt->second.string_value, o);
  5945. } else if (paramIt->second.has_number_value) {
  5946. o[paramIt->first] = paramIt->second.number_value;
  5947. } else {
  5948. o[paramIt->first] = paramIt->second.bool_value;
  5949. }
  5950. }
  5951. }
  5952. #endif
  5953. static void SerializeExtensionMap(const ExtensionMap &extensions, detail::json &o) {
  5954. if (!extensions.size()) return;
  5955. detail::json extMap;
  5956. for (ExtensionMap::const_iterator extIt = extensions.begin();
  5957. extIt != extensions.end(); ++extIt) {
  5958. // Allow an empty object for extension(#97)
  5959. detail::json ret;
  5960. bool isNull = true;
  5961. if (ValueToJson(extIt->second, &ret)) {
  5962. isNull = detail::JsonIsNull(ret);
  5963. detail::JsonAddMember(extMap, extIt->first.c_str(), std::move(ret));
  5964. }
  5965. if (isNull) {
  5966. if (!(extIt->first.empty())) { // name should not be empty, but for sure
  5967. // create empty object so that an extension name is still included in
  5968. // json.
  5969. detail::json empty;
  5970. detail::JsonSetObject(empty);
  5971. detail::JsonAddMember(extMap, extIt->first.c_str(), std::move(empty));
  5972. }
  5973. }
  5974. }
  5975. detail::JsonAddMember(o, "extensions", std::move(extMap));
  5976. }
  5977. static void SerializeGltfAccessor(const Accessor &accessor, detail::json &o) {
  5978. if (accessor.bufferView >= 0)
  5979. SerializeNumberProperty<int>("bufferView", accessor.bufferView, o);
  5980. if (accessor.byteOffset != 0)
  5981. SerializeNumberProperty<int>("byteOffset", int(accessor.byteOffset), o);
  5982. SerializeNumberProperty<int>("componentType", accessor.componentType, o);
  5983. SerializeNumberProperty<size_t>("count", accessor.count, o);
  5984. if ((accessor.componentType == TINYGLTF_COMPONENT_TYPE_FLOAT) ||
  5985. (accessor.componentType == TINYGLTF_COMPONENT_TYPE_DOUBLE)) {
  5986. SerializeNumberArrayProperty<double>("min", accessor.minValues, o);
  5987. SerializeNumberArrayProperty<double>("max", accessor.maxValues, o);
  5988. } else {
  5989. // Issue #301. Serialize as integer.
  5990. // Assume int value is within [-2**31-1, 2**31-1]
  5991. {
  5992. std::vector<int> values;
  5993. std::transform(accessor.minValues.begin(), accessor.minValues.end(),
  5994. std::back_inserter(values),
  5995. [](double v) { return static_cast<int>(v); });
  5996. SerializeNumberArrayProperty<int>("min", values, o);
  5997. }
  5998. {
  5999. std::vector<int> values;
  6000. std::transform(accessor.maxValues.begin(), accessor.maxValues.end(),
  6001. std::back_inserter(values),
  6002. [](double v) { return static_cast<int>(v); });
  6003. SerializeNumberArrayProperty<int>("max", values, o);
  6004. }
  6005. }
  6006. if (accessor.normalized)
  6007. SerializeValue("normalized", Value(accessor.normalized), o);
  6008. std::string type;
  6009. switch (accessor.type) {
  6010. case TINYGLTF_TYPE_SCALAR:
  6011. type = "SCALAR";
  6012. break;
  6013. case TINYGLTF_TYPE_VEC2:
  6014. type = "VEC2";
  6015. break;
  6016. case TINYGLTF_TYPE_VEC3:
  6017. type = "VEC3";
  6018. break;
  6019. case TINYGLTF_TYPE_VEC4:
  6020. type = "VEC4";
  6021. break;
  6022. case TINYGLTF_TYPE_MAT2:
  6023. type = "MAT2";
  6024. break;
  6025. case TINYGLTF_TYPE_MAT3:
  6026. type = "MAT3";
  6027. break;
  6028. case TINYGLTF_TYPE_MAT4:
  6029. type = "MAT4";
  6030. break;
  6031. }
  6032. SerializeStringProperty("type", type, o);
  6033. if (!accessor.name.empty()) SerializeStringProperty("name", accessor.name, o);
  6034. if (accessor.extras.Type() != NULL_TYPE) {
  6035. SerializeValue("extras", accessor.extras, o);
  6036. }
  6037. // sparse
  6038. if (accessor.sparse.isSparse)
  6039. {
  6040. detail::json sparse;
  6041. SerializeNumberProperty<int>("count", accessor.sparse.count, sparse);
  6042. {
  6043. detail::json indices;
  6044. SerializeNumberProperty<int>("bufferView", accessor.sparse.indices.bufferView, indices);
  6045. SerializeNumberProperty<int>("byteOffset", accessor.sparse.indices.byteOffset, indices);
  6046. SerializeNumberProperty<int>("componentType", accessor.sparse.indices.componentType, indices);
  6047. detail::JsonAddMember(sparse, "indices", std::move(indices));
  6048. }
  6049. {
  6050. detail::json values;
  6051. SerializeNumberProperty<int>("bufferView", accessor.sparse.values.bufferView, values);
  6052. SerializeNumberProperty<int>("byteOffset", accessor.sparse.values.byteOffset, values);
  6053. detail::JsonAddMember(sparse, "values", std::move(values));
  6054. }
  6055. detail::JsonAddMember(o, "sparse", std::move(sparse));
  6056. }
  6057. }
  6058. static void SerializeGltfAnimationChannel(const AnimationChannel &channel,
  6059. detail::json &o) {
  6060. SerializeNumberProperty("sampler", channel.sampler, o);
  6061. {
  6062. detail::json target;
  6063. if (channel.target_node > 0) {
  6064. SerializeNumberProperty("node", channel.target_node, target);
  6065. }
  6066. SerializeStringProperty("path", channel.target_path, target);
  6067. SerializeExtensionMap(channel.target_extensions, target);
  6068. detail::JsonAddMember(o, "target", std::move(target));
  6069. }
  6070. if (channel.extras.Type() != NULL_TYPE) {
  6071. SerializeValue("extras", channel.extras, o);
  6072. }
  6073. SerializeExtensionMap(channel.extensions, o);
  6074. }
  6075. static void SerializeGltfAnimationSampler(const AnimationSampler &sampler,
  6076. detail::json &o) {
  6077. SerializeNumberProperty("input", sampler.input, o);
  6078. SerializeNumberProperty("output", sampler.output, o);
  6079. SerializeStringProperty("interpolation", sampler.interpolation, o);
  6080. if (sampler.extras.Type() != NULL_TYPE) {
  6081. SerializeValue("extras", sampler.extras, o);
  6082. }
  6083. }
  6084. static void SerializeGltfAnimation(const Animation &animation, detail::json &o) {
  6085. if (!animation.name.empty())
  6086. SerializeStringProperty("name", animation.name, o);
  6087. {
  6088. detail::json channels;
  6089. detail::JsonReserveArray(channels, animation.channels.size());
  6090. for (unsigned int i = 0; i < animation.channels.size(); ++i) {
  6091. detail::json channel;
  6092. AnimationChannel gltfChannel = animation.channels[i];
  6093. SerializeGltfAnimationChannel(gltfChannel, channel);
  6094. detail::JsonPushBack(channels, std::move(channel));
  6095. }
  6096. detail::JsonAddMember(o, "channels", std::move(channels));
  6097. }
  6098. {
  6099. detail::json samplers;
  6100. detail::JsonReserveArray(samplers, animation.samplers.size());
  6101. for (unsigned int i = 0; i < animation.samplers.size(); ++i) {
  6102. detail::json sampler;
  6103. AnimationSampler gltfSampler = animation.samplers[i];
  6104. SerializeGltfAnimationSampler(gltfSampler, sampler);
  6105. detail::JsonPushBack(samplers, std::move(sampler));
  6106. }
  6107. detail::JsonAddMember(o, "samplers", std::move(samplers));
  6108. }
  6109. if (animation.extras.Type() != NULL_TYPE) {
  6110. SerializeValue("extras", animation.extras, o);
  6111. }
  6112. SerializeExtensionMap(animation.extensions, o);
  6113. }
  6114. static void SerializeGltfAsset(const Asset &asset, detail::json &o) {
  6115. if (!asset.generator.empty()) {
  6116. SerializeStringProperty("generator", asset.generator, o);
  6117. }
  6118. if (!asset.copyright.empty()) {
  6119. SerializeStringProperty("copyright", asset.copyright, o);
  6120. }
  6121. auto version = asset.version;
  6122. if (version.empty()) {
  6123. // Just in case
  6124. // `version` must be defined
  6125. version = "2.0";
  6126. }
  6127. // TODO(syoyo): Do we need to check if `version` is greater or equal to 2.0?
  6128. SerializeStringProperty("version", version, o);
  6129. if (asset.extras.Keys().size()) {
  6130. SerializeValue("extras", asset.extras, o);
  6131. }
  6132. SerializeExtensionMap(asset.extensions, o);
  6133. }
  6134. static void SerializeGltfBufferBin(const Buffer &buffer, detail::json &o,
  6135. std::vector<unsigned char> &binBuffer) {
  6136. SerializeNumberProperty("byteLength", buffer.data.size(), o);
  6137. binBuffer = buffer.data;
  6138. if (buffer.name.size()) SerializeStringProperty("name", buffer.name, o);
  6139. if (buffer.extras.Type() != NULL_TYPE) {
  6140. SerializeValue("extras", buffer.extras, o);
  6141. }
  6142. }
  6143. static void SerializeGltfBuffer(const Buffer &buffer, detail::json &o) {
  6144. SerializeNumberProperty("byteLength", buffer.data.size(), o);
  6145. SerializeGltfBufferData(buffer.data, o);
  6146. if (buffer.name.size()) SerializeStringProperty("name", buffer.name, o);
  6147. if (buffer.extras.Type() != NULL_TYPE) {
  6148. SerializeValue("extras", buffer.extras, o);
  6149. }
  6150. }
  6151. static bool SerializeGltfBuffer(const Buffer &buffer, detail::json &o,
  6152. const std::string &binFilename,
  6153. const std::string &binUri) {
  6154. if (!SerializeGltfBufferData(buffer.data, binFilename)) return false;
  6155. SerializeNumberProperty("byteLength", buffer.data.size(), o);
  6156. SerializeStringProperty("uri", binUri, o);
  6157. if (buffer.name.size()) SerializeStringProperty("name", buffer.name, o);
  6158. if (buffer.extras.Type() != NULL_TYPE) {
  6159. SerializeValue("extras", buffer.extras, o);
  6160. }
  6161. return true;
  6162. }
  6163. static void SerializeGltfBufferView(const BufferView &bufferView, detail::json &o) {
  6164. SerializeNumberProperty("buffer", bufferView.buffer, o);
  6165. SerializeNumberProperty<size_t>("byteLength", bufferView.byteLength, o);
  6166. // byteStride is optional, minimum allowed is 4
  6167. if (bufferView.byteStride >= 4) {
  6168. SerializeNumberProperty<size_t>("byteStride", bufferView.byteStride, o);
  6169. }
  6170. // byteOffset is optional, default is 0
  6171. if (bufferView.byteOffset > 0) {
  6172. SerializeNumberProperty<size_t>("byteOffset", bufferView.byteOffset, o);
  6173. }
  6174. // Target is optional, check if it contains a valid value
  6175. if (bufferView.target == TINYGLTF_TARGET_ARRAY_BUFFER ||
  6176. bufferView.target == TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER) {
  6177. SerializeNumberProperty("target", bufferView.target, o);
  6178. }
  6179. if (bufferView.name.size()) {
  6180. SerializeStringProperty("name", bufferView.name, o);
  6181. }
  6182. if (bufferView.extras.Type() != NULL_TYPE) {
  6183. SerializeValue("extras", bufferView.extras, o);
  6184. }
  6185. }
  6186. static void SerializeGltfImage(const Image &image, const std::string &uri,
  6187. detail::json &o) {
  6188. // From 2.7.0, we look for `uri` parameter, not `Image.uri`
  6189. // if uri is empty, the mimeType and bufferview should be set
  6190. if (uri.empty()) {
  6191. SerializeStringProperty("mimeType", image.mimeType, o);
  6192. SerializeNumberProperty<int>("bufferView", image.bufferView, o);
  6193. } else {
  6194. SerializeStringProperty("uri", uri, o);
  6195. }
  6196. if (image.name.size()) {
  6197. SerializeStringProperty("name", image.name, o);
  6198. }
  6199. if (image.extras.Type() != NULL_TYPE) {
  6200. SerializeValue("extras", image.extras, o);
  6201. }
  6202. SerializeExtensionMap(image.extensions, o);
  6203. }
  6204. static void SerializeGltfTextureInfo(const TextureInfo &texinfo, detail::json &o) {
  6205. SerializeNumberProperty("index", texinfo.index, o);
  6206. if (texinfo.texCoord != 0) {
  6207. SerializeNumberProperty("texCoord", texinfo.texCoord, o);
  6208. }
  6209. if (texinfo.extras.Type() != NULL_TYPE) {
  6210. SerializeValue("extras", texinfo.extras, o);
  6211. }
  6212. SerializeExtensionMap(texinfo.extensions, o);
  6213. }
  6214. static void SerializeGltfNormalTextureInfo(const NormalTextureInfo &texinfo,
  6215. detail::json &o) {
  6216. SerializeNumberProperty("index", texinfo.index, o);
  6217. if (texinfo.texCoord != 0) {
  6218. SerializeNumberProperty("texCoord", texinfo.texCoord, o);
  6219. }
  6220. if (!TINYGLTF_DOUBLE_EQUAL(texinfo.scale, 1.0)) {
  6221. SerializeNumberProperty("scale", texinfo.scale, o);
  6222. }
  6223. if (texinfo.extras.Type() != NULL_TYPE) {
  6224. SerializeValue("extras", texinfo.extras, o);
  6225. }
  6226. SerializeExtensionMap(texinfo.extensions, o);
  6227. }
  6228. static void SerializeGltfOcclusionTextureInfo(
  6229. const OcclusionTextureInfo &texinfo, detail::json &o) {
  6230. SerializeNumberProperty("index", texinfo.index, o);
  6231. if (texinfo.texCoord != 0) {
  6232. SerializeNumberProperty("texCoord", texinfo.texCoord, o);
  6233. }
  6234. if (!TINYGLTF_DOUBLE_EQUAL(texinfo.strength, 1.0)) {
  6235. SerializeNumberProperty("strength", texinfo.strength, o);
  6236. }
  6237. if (texinfo.extras.Type() != NULL_TYPE) {
  6238. SerializeValue("extras", texinfo.extras, o);
  6239. }
  6240. SerializeExtensionMap(texinfo.extensions, o);
  6241. }
  6242. static void SerializeGltfPbrMetallicRoughness(const PbrMetallicRoughness &pbr,
  6243. detail::json &o) {
  6244. std::vector<double> default_baseColorFactor = {1.0, 1.0, 1.0, 1.0};
  6245. if (!Equals(pbr.baseColorFactor, default_baseColorFactor)) {
  6246. SerializeNumberArrayProperty<double>("baseColorFactor", pbr.baseColorFactor,
  6247. o);
  6248. }
  6249. if (!TINYGLTF_DOUBLE_EQUAL(pbr.metallicFactor, 1.0)) {
  6250. SerializeNumberProperty("metallicFactor", pbr.metallicFactor, o);
  6251. }
  6252. if (!TINYGLTF_DOUBLE_EQUAL(pbr.roughnessFactor, 1.0)) {
  6253. SerializeNumberProperty("roughnessFactor", pbr.roughnessFactor, o);
  6254. }
  6255. if (pbr.baseColorTexture.index > -1) {
  6256. detail::json texinfo;
  6257. SerializeGltfTextureInfo(pbr.baseColorTexture, texinfo);
  6258. detail::JsonAddMember(o, "baseColorTexture", std::move(texinfo));
  6259. }
  6260. if (pbr.metallicRoughnessTexture.index > -1) {
  6261. detail::json texinfo;
  6262. SerializeGltfTextureInfo(pbr.metallicRoughnessTexture, texinfo);
  6263. detail::JsonAddMember(o, "metallicRoughnessTexture", std::move(texinfo));
  6264. }
  6265. SerializeExtensionMap(pbr.extensions, o);
  6266. if (pbr.extras.Type() != NULL_TYPE) {
  6267. SerializeValue("extras", pbr.extras, o);
  6268. }
  6269. }
  6270. static void SerializeGltfMaterial(const Material &material, detail::json &o) {
  6271. if (material.name.size()) {
  6272. SerializeStringProperty("name", material.name, o);
  6273. }
  6274. // QUESTION(syoyo): Write material parameters regardless of its default value?
  6275. if (!TINYGLTF_DOUBLE_EQUAL(material.alphaCutoff, 0.5)) {
  6276. SerializeNumberProperty("alphaCutoff", material.alphaCutoff, o);
  6277. }
  6278. if (material.alphaMode.compare("OPAQUE") != 0) {
  6279. SerializeStringProperty("alphaMode", material.alphaMode, o);
  6280. }
  6281. if (material.doubleSided != false)
  6282. detail::JsonAddMember(o, "doubleSided", detail::json(material.doubleSided));
  6283. if (material.normalTexture.index > -1) {
  6284. detail::json texinfo;
  6285. SerializeGltfNormalTextureInfo(material.normalTexture, texinfo);
  6286. detail::JsonAddMember(o, "normalTexture", std::move(texinfo));
  6287. }
  6288. if (material.occlusionTexture.index > -1) {
  6289. detail::json texinfo;
  6290. SerializeGltfOcclusionTextureInfo(material.occlusionTexture, texinfo);
  6291. detail::JsonAddMember(o, "occlusionTexture", std::move(texinfo));
  6292. }
  6293. if (material.emissiveTexture.index > -1) {
  6294. detail::json texinfo;
  6295. SerializeGltfTextureInfo(material.emissiveTexture, texinfo);
  6296. detail::JsonAddMember(o, "emissiveTexture", std::move(texinfo));
  6297. }
  6298. std::vector<double> default_emissiveFactor = {0.0, 0.0, 0.0};
  6299. if (!Equals(material.emissiveFactor, default_emissiveFactor)) {
  6300. SerializeNumberArrayProperty<double>("emissiveFactor",
  6301. material.emissiveFactor, o);
  6302. }
  6303. {
  6304. detail::json pbrMetallicRoughness;
  6305. SerializeGltfPbrMetallicRoughness(material.pbrMetallicRoughness,
  6306. pbrMetallicRoughness);
  6307. // Issue 204
  6308. // Do not serialize `pbrMetallicRoughness` if pbrMetallicRoughness has all
  6309. // default values(json is null). Otherwise it will serialize to
  6310. // `pbrMetallicRoughness : null`, which cannot be read by other glTF
  6311. // importers (and validators).
  6312. //
  6313. if (!detail::JsonIsNull(pbrMetallicRoughness)) {
  6314. detail::JsonAddMember(o, "pbrMetallicRoughness", std::move(pbrMetallicRoughness));
  6315. }
  6316. }
  6317. #if 0 // legacy way. just for the record.
  6318. if (material.values.size()) {
  6319. detail::json pbrMetallicRoughness;
  6320. SerializeParameterMap(material.values, pbrMetallicRoughness);
  6321. detail::JsonAddMember(o, "pbrMetallicRoughness", std::move(pbrMetallicRoughness));
  6322. }
  6323. SerializeParameterMap(material.additionalValues, o);
  6324. #else
  6325. #endif
  6326. SerializeExtensionMap(material.extensions, o);
  6327. if (material.extras.Type() != NULL_TYPE) {
  6328. SerializeValue("extras", material.extras, o);
  6329. }
  6330. }
  6331. static void SerializeGltfMesh(const Mesh &mesh, detail::json &o) {
  6332. detail::json primitives;
  6333. detail::JsonReserveArray(primitives, mesh.primitives.size());
  6334. for (unsigned int i = 0; i < mesh.primitives.size(); ++i) {
  6335. detail::json primitive;
  6336. const Primitive &gltfPrimitive = mesh.primitives[i]; // don't make a copy
  6337. {
  6338. detail::json attributes;
  6339. for (auto attrIt = gltfPrimitive.attributes.begin();
  6340. attrIt != gltfPrimitive.attributes.end(); ++attrIt) {
  6341. SerializeNumberProperty<int>(attrIt->first, attrIt->second, attributes);
  6342. }
  6343. detail::JsonAddMember(primitive, "attributes", std::move(attributes));
  6344. }
  6345. // Indices is optional
  6346. if (gltfPrimitive.indices > -1) {
  6347. SerializeNumberProperty<int>("indices", gltfPrimitive.indices, primitive);
  6348. }
  6349. // Material is optional
  6350. if (gltfPrimitive.material > -1) {
  6351. SerializeNumberProperty<int>("material", gltfPrimitive.material,
  6352. primitive);
  6353. }
  6354. SerializeNumberProperty<int>("mode", gltfPrimitive.mode, primitive);
  6355. // Morph targets
  6356. if (gltfPrimitive.targets.size()) {
  6357. detail::json targets;
  6358. detail::JsonReserveArray(targets, gltfPrimitive.targets.size());
  6359. for (unsigned int k = 0; k < gltfPrimitive.targets.size(); ++k) {
  6360. detail::json targetAttributes;
  6361. std::map<std::string, int> targetData = gltfPrimitive.targets[k];
  6362. for (std::map<std::string, int>::iterator attrIt = targetData.begin();
  6363. attrIt != targetData.end(); ++attrIt) {
  6364. SerializeNumberProperty<int>(attrIt->first, attrIt->second,
  6365. targetAttributes);
  6366. }
  6367. detail::JsonPushBack(targets, std::move(targetAttributes));
  6368. }
  6369. detail::JsonAddMember(primitive, "targets", std::move(targets));
  6370. }
  6371. SerializeExtensionMap(gltfPrimitive.extensions, primitive);
  6372. if (gltfPrimitive.extras.Type() != NULL_TYPE) {
  6373. SerializeValue("extras", gltfPrimitive.extras, primitive);
  6374. }
  6375. detail::JsonPushBack(primitives, std::move(primitive));
  6376. }
  6377. detail::JsonAddMember(o, "primitives", std::move(primitives));
  6378. if (mesh.weights.size()) {
  6379. SerializeNumberArrayProperty<double>("weights", mesh.weights, o);
  6380. }
  6381. if (mesh.name.size()) {
  6382. SerializeStringProperty("name", mesh.name, o);
  6383. }
  6384. SerializeExtensionMap(mesh.extensions, o);
  6385. if (mesh.extras.Type() != NULL_TYPE) {
  6386. SerializeValue("extras", mesh.extras, o);
  6387. }
  6388. }
  6389. static void SerializeSpotLight(const SpotLight &spot, detail::json &o) {
  6390. SerializeNumberProperty("innerConeAngle", spot.innerConeAngle, o);
  6391. SerializeNumberProperty("outerConeAngle", spot.outerConeAngle, o);
  6392. SerializeExtensionMap(spot.extensions, o);
  6393. if (spot.extras.Type() != NULL_TYPE) {
  6394. SerializeValue("extras", spot.extras, o);
  6395. }
  6396. }
  6397. static void SerializeGltfLight(const Light &light, detail::json &o) {
  6398. if (!light.name.empty()) SerializeStringProperty("name", light.name, o);
  6399. SerializeNumberProperty("intensity", light.intensity, o);
  6400. if (light.range > 0.0) {
  6401. SerializeNumberProperty("range", light.range, o);
  6402. }
  6403. SerializeNumberArrayProperty("color", light.color, o);
  6404. SerializeStringProperty("type", light.type, o);
  6405. if (light.type == "spot") {
  6406. detail::json spot;
  6407. SerializeSpotLight(light.spot, spot);
  6408. detail::JsonAddMember(o, "spot", std::move(spot));
  6409. }
  6410. SerializeExtensionMap(light.extensions, o);
  6411. if (light.extras.Type() != NULL_TYPE) {
  6412. SerializeValue("extras", light.extras, o);
  6413. }
  6414. }
  6415. static void SerializeGltfNode(const Node &node, detail::json &o) {
  6416. if (node.translation.size() > 0) {
  6417. SerializeNumberArrayProperty<double>("translation", node.translation, o);
  6418. }
  6419. if (node.rotation.size() > 0) {
  6420. SerializeNumberArrayProperty<double>("rotation", node.rotation, o);
  6421. }
  6422. if (node.scale.size() > 0) {
  6423. SerializeNumberArrayProperty<double>("scale", node.scale, o);
  6424. }
  6425. if (node.matrix.size() > 0) {
  6426. SerializeNumberArrayProperty<double>("matrix", node.matrix, o);
  6427. }
  6428. if (node.mesh != -1) {
  6429. SerializeNumberProperty<int>("mesh", node.mesh, o);
  6430. }
  6431. if (node.skin != -1) {
  6432. SerializeNumberProperty<int>("skin", node.skin, o);
  6433. }
  6434. if (node.camera != -1) {
  6435. SerializeNumberProperty<int>("camera", node.camera, o);
  6436. }
  6437. if (node.weights.size() > 0) {
  6438. SerializeNumberArrayProperty<double>("weights", node.weights, o);
  6439. }
  6440. if (node.extras.Type() != NULL_TYPE) {
  6441. SerializeValue("extras", node.extras, o);
  6442. }
  6443. SerializeExtensionMap(node.extensions, o);
  6444. if (!node.name.empty()) SerializeStringProperty("name", node.name, o);
  6445. SerializeNumberArrayProperty<int>("children", node.children, o);
  6446. }
  6447. static void SerializeGltfSampler(const Sampler &sampler, detail::json &o) {
  6448. if (!sampler.name.empty()) {
  6449. SerializeStringProperty("name", sampler.name, o);
  6450. }
  6451. if (sampler.magFilter != -1) {
  6452. SerializeNumberProperty("magFilter", sampler.magFilter, o);
  6453. }
  6454. if (sampler.minFilter != -1) {
  6455. SerializeNumberProperty("minFilter", sampler.minFilter, o);
  6456. }
  6457. // SerializeNumberProperty("wrapR", sampler.wrapR, o);
  6458. SerializeNumberProperty("wrapS", sampler.wrapS, o);
  6459. SerializeNumberProperty("wrapT", sampler.wrapT, o);
  6460. if (sampler.extras.Type() != NULL_TYPE) {
  6461. SerializeValue("extras", sampler.extras, o);
  6462. }
  6463. }
  6464. static void SerializeGltfOrthographicCamera(const OrthographicCamera &camera,
  6465. detail::json &o) {
  6466. SerializeNumberProperty("zfar", camera.zfar, o);
  6467. SerializeNumberProperty("znear", camera.znear, o);
  6468. SerializeNumberProperty("xmag", camera.xmag, o);
  6469. SerializeNumberProperty("ymag", camera.ymag, o);
  6470. if (camera.extras.Type() != NULL_TYPE) {
  6471. SerializeValue("extras", camera.extras, o);
  6472. }
  6473. }
  6474. static void SerializeGltfPerspectiveCamera(const PerspectiveCamera &camera,
  6475. detail::json &o) {
  6476. SerializeNumberProperty("zfar", camera.zfar, o);
  6477. SerializeNumberProperty("znear", camera.znear, o);
  6478. if (camera.aspectRatio > 0) {
  6479. SerializeNumberProperty("aspectRatio", camera.aspectRatio, o);
  6480. }
  6481. if (camera.yfov > 0) {
  6482. SerializeNumberProperty("yfov", camera.yfov, o);
  6483. }
  6484. if (camera.extras.Type() != NULL_TYPE) {
  6485. SerializeValue("extras", camera.extras, o);
  6486. }
  6487. }
  6488. static void SerializeGltfCamera(const Camera &camera, detail::json &o) {
  6489. SerializeStringProperty("type", camera.type, o);
  6490. if (!camera.name.empty()) {
  6491. SerializeStringProperty("name", camera.name, o);
  6492. }
  6493. if (camera.type.compare("orthographic") == 0) {
  6494. detail::json orthographic;
  6495. SerializeGltfOrthographicCamera(camera.orthographic, orthographic);
  6496. detail::JsonAddMember(o, "orthographic", std::move(orthographic));
  6497. } else if (camera.type.compare("perspective") == 0) {
  6498. detail::json perspective;
  6499. SerializeGltfPerspectiveCamera(camera.perspective, perspective);
  6500. detail::JsonAddMember(o, "perspective", std::move(perspective));
  6501. } else {
  6502. // ???
  6503. }
  6504. if (camera.extras.Type() != NULL_TYPE) {
  6505. SerializeValue("extras", camera.extras, o);
  6506. }
  6507. SerializeExtensionMap(camera.extensions, o);
  6508. }
  6509. static void SerializeGltfScene(const Scene &scene, detail::json &o) {
  6510. SerializeNumberArrayProperty<int>("nodes", scene.nodes, o);
  6511. if (scene.name.size()) {
  6512. SerializeStringProperty("name", scene.name, o);
  6513. }
  6514. if (scene.extras.Type() != NULL_TYPE) {
  6515. SerializeValue("extras", scene.extras, o);
  6516. }
  6517. SerializeExtensionMap(scene.extensions, o);
  6518. }
  6519. static void SerializeGltfSkin(const Skin &skin, detail::json &o) {
  6520. // required
  6521. SerializeNumberArrayProperty<int>("joints", skin.joints, o);
  6522. if (skin.inverseBindMatrices >= 0) {
  6523. SerializeNumberProperty("inverseBindMatrices", skin.inverseBindMatrices, o);
  6524. }
  6525. if (skin.skeleton >= 0) {
  6526. SerializeNumberProperty("skeleton", skin.skeleton, o);
  6527. }
  6528. if (skin.name.size()) {
  6529. SerializeStringProperty("name", skin.name, o);
  6530. }
  6531. }
  6532. static void SerializeGltfTexture(const Texture &texture, detail::json &o) {
  6533. if (texture.sampler > -1) {
  6534. SerializeNumberProperty("sampler", texture.sampler, o);
  6535. }
  6536. if (texture.source > -1) {
  6537. SerializeNumberProperty("source", texture.source, o);
  6538. }
  6539. if (texture.name.size()) {
  6540. SerializeStringProperty("name", texture.name, o);
  6541. }
  6542. if (texture.extras.Type() != NULL_TYPE) {
  6543. SerializeValue("extras", texture.extras, o);
  6544. }
  6545. SerializeExtensionMap(texture.extensions, o);
  6546. }
  6547. ///
  6548. /// Serialize all properties except buffers and images.
  6549. ///
  6550. static void SerializeGltfModel(const Model *model, detail::json &o) {
  6551. // ACCESSORS
  6552. if (model->accessors.size()) {
  6553. detail::json accessors;
  6554. detail::JsonReserveArray(accessors, model->accessors.size());
  6555. for (unsigned int i = 0; i < model->accessors.size(); ++i) {
  6556. detail::json accessor;
  6557. SerializeGltfAccessor(model->accessors[i], accessor);
  6558. detail::JsonPushBack(accessors, std::move(accessor));
  6559. }
  6560. detail::JsonAddMember(o, "accessors", std::move(accessors));
  6561. }
  6562. // ANIMATIONS
  6563. if (model->animations.size()) {
  6564. detail::json animations;
  6565. detail::JsonReserveArray(animations, model->animations.size());
  6566. for (unsigned int i = 0; i < model->animations.size(); ++i) {
  6567. if (model->animations[i].channels.size()) {
  6568. detail::json animation;
  6569. SerializeGltfAnimation(model->animations[i], animation);
  6570. detail::JsonPushBack(animations, std::move(animation));
  6571. }
  6572. }
  6573. detail::JsonAddMember(o, "animations", std::move(animations));
  6574. }
  6575. // ASSET
  6576. detail::json asset;
  6577. SerializeGltfAsset(model->asset, asset);
  6578. detail::JsonAddMember(o, "asset", std::move(asset));
  6579. // BUFFERVIEWS
  6580. if (model->bufferViews.size()) {
  6581. detail::json bufferViews;
  6582. detail::JsonReserveArray(bufferViews, model->bufferViews.size());
  6583. for (unsigned int i = 0; i < model->bufferViews.size(); ++i) {
  6584. detail::json bufferView;
  6585. SerializeGltfBufferView(model->bufferViews[i], bufferView);
  6586. detail::JsonPushBack(bufferViews, std::move(bufferView));
  6587. }
  6588. detail::JsonAddMember(o, "bufferViews", std::move(bufferViews));
  6589. }
  6590. // Extensions required
  6591. if (model->extensionsRequired.size()) {
  6592. SerializeStringArrayProperty("extensionsRequired",
  6593. model->extensionsRequired, o);
  6594. }
  6595. // MATERIALS
  6596. if (model->materials.size()) {
  6597. detail::json materials;
  6598. detail::JsonReserveArray(materials, model->materials.size());
  6599. for (unsigned int i = 0; i < model->materials.size(); ++i) {
  6600. detail::json material;
  6601. SerializeGltfMaterial(model->materials[i], material);
  6602. if (detail::JsonIsNull(material)) {
  6603. // Issue 294.
  6604. // `material` does not have any required parameters
  6605. // so the result may be null(unmodified) when all material parameters
  6606. // have default value.
  6607. //
  6608. // null is not allowed thus we create an empty JSON object.
  6609. detail::JsonSetObject(material);
  6610. }
  6611. detail::JsonPushBack(materials, std::move(material));
  6612. }
  6613. detail::JsonAddMember(o, "materials", std::move(materials));
  6614. }
  6615. // MESHES
  6616. if (model->meshes.size()) {
  6617. detail::json meshes;
  6618. detail::JsonReserveArray(meshes, model->meshes.size());
  6619. for (unsigned int i = 0; i < model->meshes.size(); ++i) {
  6620. detail::json mesh;
  6621. SerializeGltfMesh(model->meshes[i], mesh);
  6622. detail::JsonPushBack(meshes, std::move(mesh));
  6623. }
  6624. detail::JsonAddMember(o, "meshes", std::move(meshes));
  6625. }
  6626. // NODES
  6627. if (model->nodes.size()) {
  6628. detail::json nodes;
  6629. detail::JsonReserveArray(nodes, model->nodes.size());
  6630. for (unsigned int i = 0; i < model->nodes.size(); ++i) {
  6631. detail::json node;
  6632. SerializeGltfNode(model->nodes[i], node);
  6633. detail::JsonPushBack(nodes, std::move(node));
  6634. }
  6635. detail::JsonAddMember(o, "nodes", std::move(nodes));
  6636. }
  6637. // SCENE
  6638. if (model->defaultScene > -1) {
  6639. SerializeNumberProperty<int>("scene", model->defaultScene, o);
  6640. }
  6641. // SCENES
  6642. if (model->scenes.size()) {
  6643. detail::json scenes;
  6644. detail::JsonReserveArray(scenes, model->scenes.size());
  6645. for (unsigned int i = 0; i < model->scenes.size(); ++i) {
  6646. detail::json currentScene;
  6647. SerializeGltfScene(model->scenes[i], currentScene);
  6648. detail::JsonPushBack(scenes, std::move(currentScene));
  6649. }
  6650. detail::JsonAddMember(o, "scenes", std::move(scenes));
  6651. }
  6652. // SKINS
  6653. if (model->skins.size()) {
  6654. detail::json skins;
  6655. detail::JsonReserveArray(skins, model->skins.size());
  6656. for (unsigned int i = 0; i < model->skins.size(); ++i) {
  6657. detail::json skin;
  6658. SerializeGltfSkin(model->skins[i], skin);
  6659. detail::JsonPushBack(skins, std::move(skin));
  6660. }
  6661. detail::JsonAddMember(o, "skins", std::move(skins));
  6662. }
  6663. // TEXTURES
  6664. if (model->textures.size()) {
  6665. detail::json textures;
  6666. detail::JsonReserveArray(textures, model->textures.size());
  6667. for (unsigned int i = 0; i < model->textures.size(); ++i) {
  6668. detail::json texture;
  6669. SerializeGltfTexture(model->textures[i], texture);
  6670. detail::JsonPushBack(textures, std::move(texture));
  6671. }
  6672. detail::JsonAddMember(o, "textures", std::move(textures));
  6673. }
  6674. // SAMPLERS
  6675. if (model->samplers.size()) {
  6676. detail::json samplers;
  6677. detail::JsonReserveArray(samplers, model->samplers.size());
  6678. for (unsigned int i = 0; i < model->samplers.size(); ++i) {
  6679. detail::json sampler;
  6680. SerializeGltfSampler(model->samplers[i], sampler);
  6681. detail::JsonPushBack(samplers, std::move(sampler));
  6682. }
  6683. detail::JsonAddMember(o, "samplers", std::move(samplers));
  6684. }
  6685. // CAMERAS
  6686. if (model->cameras.size()) {
  6687. detail::json cameras;
  6688. detail::JsonReserveArray(cameras, model->cameras.size());
  6689. for (unsigned int i = 0; i < model->cameras.size(); ++i) {
  6690. detail::json camera;
  6691. SerializeGltfCamera(model->cameras[i], camera);
  6692. detail::JsonPushBack(cameras, std::move(camera));
  6693. }
  6694. detail::JsonAddMember(o, "cameras", std::move(cameras));
  6695. }
  6696. // EXTENSIONS
  6697. SerializeExtensionMap(model->extensions, o);
  6698. auto extensionsUsed = model->extensionsUsed;
  6699. // LIGHTS as KHR_lights_punctual
  6700. if (model->lights.size()) {
  6701. detail::json lights;
  6702. detail::JsonReserveArray(lights, model->lights.size());
  6703. for (unsigned int i = 0; i < model->lights.size(); ++i) {
  6704. detail::json light;
  6705. SerializeGltfLight(model->lights[i], light);
  6706. detail::JsonPushBack(lights, std::move(light));
  6707. }
  6708. detail::json khr_lights_cmn;
  6709. detail::JsonAddMember(khr_lights_cmn, "lights", std::move(lights));
  6710. detail::json ext_j;
  6711. {
  6712. detail::json_const_iterator it;
  6713. if (detail::FindMember(o, "extensions", it)) {
  6714. detail::JsonAssign(ext_j, detail::GetValue(it));
  6715. }
  6716. }
  6717. detail::JsonAddMember(ext_j, "KHR_lights_punctual", std::move(khr_lights_cmn));
  6718. detail::JsonAddMember(o, "extensions", std::move(ext_j));
  6719. // Also add "KHR_lights_punctual" to `extensionsUsed`
  6720. {
  6721. auto has_khr_lights_punctual =
  6722. std::find_if(extensionsUsed.begin(), extensionsUsed.end(),
  6723. [](const std::string &s) {
  6724. return (s.compare("KHR_lights_punctual") == 0);
  6725. });
  6726. if (has_khr_lights_punctual == extensionsUsed.end()) {
  6727. extensionsUsed.push_back("KHR_lights_punctual");
  6728. }
  6729. }
  6730. }
  6731. // Extensions used
  6732. if (extensionsUsed.size()) {
  6733. SerializeStringArrayProperty("extensionsUsed", extensionsUsed, o);
  6734. }
  6735. // EXTRAS
  6736. if (model->extras.Type() != NULL_TYPE) {
  6737. SerializeValue("extras", model->extras, o);
  6738. }
  6739. }
  6740. static bool WriteGltfStream(std::ostream &stream, const std::string &content) {
  6741. stream << content << std::endl;
  6742. return true;
  6743. }
  6744. static bool WriteGltfFile(const std::string &output,
  6745. const std::string &content) {
  6746. #ifdef _WIN32
  6747. #if defined(_MSC_VER)
  6748. std::ofstream gltfFile(UTF8ToWchar(output).c_str());
  6749. #elif defined(__GLIBCXX__)
  6750. int file_descriptor = _wopen(UTF8ToWchar(output).c_str(),
  6751. _O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY);
  6752. __gnu_cxx::stdio_filebuf<char> wfile_buf(
  6753. file_descriptor, std::ios_base::out | std::ios_base::binary);
  6754. std::ostream gltfFile(&wfile_buf);
  6755. if (!wfile_buf.is_open()) return false;
  6756. #else
  6757. std::ofstream gltfFile(output.c_str());
  6758. if (!gltfFile.is_open()) return false;
  6759. #endif
  6760. #else
  6761. std::ofstream gltfFile(output.c_str());
  6762. if (!gltfFile.is_open()) return false;
  6763. #endif
  6764. return WriteGltfStream(gltfFile, content);
  6765. }
  6766. static bool WriteBinaryGltfStream(std::ostream &stream,
  6767. const std::string &content,
  6768. const std::vector<unsigned char> &binBuffer) {
  6769. const std::string header = "glTF";
  6770. const int version = 2;
  6771. const uint32_t content_size = uint32_t(content.size());
  6772. const uint32_t binBuffer_size = uint32_t(binBuffer.size());
  6773. // determine number of padding bytes required to ensure 4 byte alignment
  6774. const uint32_t content_padding_size =
  6775. content_size % 4 == 0 ? 0 : 4 - content_size % 4;
  6776. const uint32_t bin_padding_size =
  6777. binBuffer_size % 4 == 0 ? 0 : 4 - binBuffer_size % 4;
  6778. // 12 bytes for header, JSON content length, 8 bytes for JSON chunk info.
  6779. // Chunk data must be located at 4-byte boundary, which may require padding
  6780. const uint32_t length =
  6781. 12 + 8 + content_size + content_padding_size +
  6782. (binBuffer_size ? (8 + binBuffer_size + bin_padding_size) : 0);
  6783. stream.write(header.c_str(), std::streamsize(header.size()));
  6784. stream.write(reinterpret_cast<const char *>(&version), sizeof(version));
  6785. stream.write(reinterpret_cast<const char *>(&length), sizeof(length));
  6786. // JSON chunk info, then JSON data
  6787. const uint32_t model_length = uint32_t(content.size()) + content_padding_size;
  6788. const uint32_t model_format = 0x4E4F534A;
  6789. stream.write(reinterpret_cast<const char *>(&model_length),
  6790. sizeof(model_length));
  6791. stream.write(reinterpret_cast<const char *>(&model_format),
  6792. sizeof(model_format));
  6793. stream.write(content.c_str(), std::streamsize(content.size()));
  6794. // Chunk must be multiplies of 4, so pad with spaces
  6795. if (content_padding_size > 0) {
  6796. const std::string padding = std::string(size_t(content_padding_size), ' ');
  6797. stream.write(padding.c_str(), std::streamsize(padding.size()));
  6798. }
  6799. if (binBuffer.size() > 0) {
  6800. // BIN chunk info, then BIN data
  6801. const uint32_t bin_length = uint32_t(binBuffer.size()) + bin_padding_size;
  6802. const uint32_t bin_format = 0x004e4942;
  6803. stream.write(reinterpret_cast<const char *>(&bin_length),
  6804. sizeof(bin_length));
  6805. stream.write(reinterpret_cast<const char *>(&bin_format),
  6806. sizeof(bin_format));
  6807. stream.write(reinterpret_cast<const char *>(binBuffer.data()),
  6808. std::streamsize(binBuffer.size()));
  6809. // Chunksize must be multiplies of 4, so pad with zeroes
  6810. if (bin_padding_size > 0) {
  6811. const std::vector<unsigned char> padding =
  6812. std::vector<unsigned char>(size_t(bin_padding_size), 0);
  6813. stream.write(reinterpret_cast<const char *>(padding.data()),
  6814. std::streamsize(padding.size()));
  6815. }
  6816. }
  6817. // TODO: Check error on stream.write
  6818. return true;
  6819. }
  6820. static bool WriteBinaryGltfFile(const std::string &output,
  6821. const std::string &content,
  6822. const std::vector<unsigned char> &binBuffer) {
  6823. #ifdef _WIN32
  6824. #if defined(_MSC_VER)
  6825. std::ofstream gltfFile(UTF8ToWchar(output).c_str(), std::ios::binary);
  6826. #elif defined(__GLIBCXX__)
  6827. int file_descriptor = _wopen(UTF8ToWchar(output).c_str(),
  6828. _O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY);
  6829. __gnu_cxx::stdio_filebuf<char> wfile_buf(
  6830. file_descriptor, std::ios_base::out | std::ios_base::binary);
  6831. std::ostream gltfFile(&wfile_buf);
  6832. #else
  6833. std::ofstream gltfFile(output.c_str(), std::ios::binary);
  6834. #endif
  6835. #else
  6836. std::ofstream gltfFile(output.c_str(), std::ios::binary);
  6837. #endif
  6838. return WriteBinaryGltfStream(gltfFile, content, binBuffer);
  6839. }
  6840. bool TinyGLTF::WriteGltfSceneToStream(const Model *model, std::ostream &stream,
  6841. bool prettyPrint = true,
  6842. bool writeBinary = false) {
  6843. detail::JsonDocument output;
  6844. /// Serialize all properties except buffers and images.
  6845. SerializeGltfModel(model, output);
  6846. // BUFFERS
  6847. std::vector<unsigned char> binBuffer;
  6848. if (model->buffers.size()) {
  6849. detail::json buffers;
  6850. detail::JsonReserveArray(buffers, model->buffers.size());
  6851. for (unsigned int i = 0; i < model->buffers.size(); ++i) {
  6852. detail::json buffer;
  6853. if (writeBinary && i == 0 && model->buffers[i].uri.empty()) {
  6854. SerializeGltfBufferBin(model->buffers[i], buffer, binBuffer);
  6855. } else {
  6856. SerializeGltfBuffer(model->buffers[i], buffer);
  6857. }
  6858. detail::JsonPushBack(buffers, std::move(buffer));
  6859. }
  6860. detail::JsonAddMember(output, "buffers", std::move(buffers));
  6861. }
  6862. // IMAGES
  6863. if (model->images.size()) {
  6864. detail::json images;
  6865. detail::JsonReserveArray(images, model->images.size());
  6866. for (unsigned int i = 0; i < model->images.size(); ++i) {
  6867. detail::json image;
  6868. std::string dummystring = "";
  6869. // UpdateImageObject need baseDir but only uses it if embeddedImages is
  6870. // enabled, since we won't write separate images when writing to a stream
  6871. // we
  6872. std::string uri;
  6873. if (!UpdateImageObject(model->images[i], dummystring, int(i), true,
  6874. &uri_cb, &this->WriteImageData,
  6875. this->write_image_user_data_, &uri)) {
  6876. return false;
  6877. }
  6878. SerializeGltfImage(model->images[i], uri, image);
  6879. detail::JsonPushBack(images, std::move(image));
  6880. }
  6881. detail::JsonAddMember(output, "images", std::move(images));
  6882. }
  6883. if (writeBinary) {
  6884. return WriteBinaryGltfStream(stream, detail::JsonToString(output), binBuffer);
  6885. } else {
  6886. return WriteGltfStream(stream, detail::JsonToString(output, prettyPrint ? 2 : -1));
  6887. }
  6888. }
  6889. bool TinyGLTF::WriteGltfSceneToFile(const Model *model,
  6890. const std::string &filename,
  6891. bool embedImages = false,
  6892. bool embedBuffers = false,
  6893. bool prettyPrint = true,
  6894. bool writeBinary = false) {
  6895. detail::JsonDocument output;
  6896. std::string defaultBinFilename = GetBaseFilename(filename);
  6897. std::string defaultBinFileExt = ".bin";
  6898. std::string::size_type pos =
  6899. defaultBinFilename.rfind('.', defaultBinFilename.length());
  6900. if (pos != std::string::npos) {
  6901. defaultBinFilename = defaultBinFilename.substr(0, pos);
  6902. }
  6903. std::string baseDir = GetBaseDir(filename);
  6904. if (baseDir.empty()) {
  6905. baseDir = "./";
  6906. }
  6907. /// Serialize all properties except buffers and images.
  6908. SerializeGltfModel(model, output);
  6909. // BUFFERS
  6910. std::vector<std::string> usedFilenames;
  6911. std::vector<unsigned char> binBuffer;
  6912. if (model->buffers.size()) {
  6913. detail::json buffers;
  6914. detail::JsonReserveArray(buffers, model->buffers.size());
  6915. for (unsigned int i = 0; i < model->buffers.size(); ++i) {
  6916. detail::json buffer;
  6917. if (writeBinary && i == 0 && model->buffers[i].uri.empty()) {
  6918. SerializeGltfBufferBin(model->buffers[i], buffer, binBuffer);
  6919. } else if (embedBuffers) {
  6920. SerializeGltfBuffer(model->buffers[i], buffer);
  6921. } else {
  6922. std::string binSavePath;
  6923. std::string binFilename;
  6924. std::string binUri;
  6925. if (!model->buffers[i].uri.empty() &&
  6926. !IsDataURI(model->buffers[i].uri)) {
  6927. binUri = model->buffers[i].uri;
  6928. if (!uri_cb.decode(binUri, &binFilename, uri_cb.user_data)) {
  6929. return false;
  6930. }
  6931. } else {
  6932. binFilename = defaultBinFilename + defaultBinFileExt;
  6933. bool inUse = true;
  6934. int numUsed = 0;
  6935. while (inUse) {
  6936. inUse = false;
  6937. for (const std::string &usedName : usedFilenames) {
  6938. if (binFilename.compare(usedName) != 0) continue;
  6939. inUse = true;
  6940. binFilename = defaultBinFilename + std::to_string(numUsed++) +
  6941. defaultBinFileExt;
  6942. break;
  6943. }
  6944. }
  6945. if (uri_cb.encode) {
  6946. if (!uri_cb.encode(binFilename, "buffer", &binUri,
  6947. uri_cb.user_data)) {
  6948. return false;
  6949. }
  6950. } else {
  6951. binUri = binFilename;
  6952. }
  6953. }
  6954. usedFilenames.push_back(binFilename);
  6955. binSavePath = JoinPath(baseDir, binFilename);
  6956. if (!SerializeGltfBuffer(model->buffers[i], buffer, binSavePath,
  6957. binUri)) {
  6958. return false;
  6959. }
  6960. }
  6961. detail::JsonPushBack(buffers, std::move(buffer));
  6962. }
  6963. detail::JsonAddMember(output, "buffers", std::move(buffers));
  6964. }
  6965. // IMAGES
  6966. if (model->images.size()) {
  6967. detail::json images;
  6968. detail::JsonReserveArray(images, model->images.size());
  6969. for (unsigned int i = 0; i < model->images.size(); ++i) {
  6970. detail::json image;
  6971. std::string uri;
  6972. if (!UpdateImageObject(model->images[i], baseDir, int(i), embedImages,
  6973. &uri_cb, &this->WriteImageData,
  6974. this->write_image_user_data_, &uri)) {
  6975. return false;
  6976. }
  6977. SerializeGltfImage(model->images[i], uri, image);
  6978. detail::JsonPushBack(images, std::move(image));
  6979. }
  6980. detail::JsonAddMember(output, "images", std::move(images));
  6981. }
  6982. if (writeBinary) {
  6983. return WriteBinaryGltfFile(filename, detail::JsonToString(output), binBuffer);
  6984. } else {
  6985. return WriteGltfFile(filename, detail::JsonToString(output, (prettyPrint ? 2 : -1)));
  6986. }
  6987. }
  6988. } // namespace tinygltf
  6989. #ifdef __clang__
  6990. #pragma clang diagnostic pop
  6991. #endif
  6992. #endif // TINYGLTF_IMPLEMENTATION