gltfpack.cpp 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514
  1. // gltfpack is part of meshoptimizer library; see meshoptimizer.h for version/license details
  2. //
  3. // gltfpack is a command-line tool that takes a glTF file as an input and can produce two types of files:
  4. // - regular glb/gltf files that use data that has been optimized for GPU consumption using various cache optimizers
  5. // and quantization
  6. // - packed glb/gltf files that additionally use meshoptimizer codecs to reduce the size of vertex/index data; these
  7. // files can be further compressed with deflate/etc.
  8. //
  9. // To load regular glb files, it should be sufficient to use a standard glTF loader (although note that these files
  10. // use quantized position/texture coordinates that are technically invalid per spec; THREE.js and BabylonJS support
  11. // these files out of the box).
  12. // To load packed glb files, meshoptimizer vertex decoder needs to be integrated into the loader; demo/GLTFLoader.js
  13. // contains a work-in-progress loader - please note that the extension specification isn't ready yet so the format
  14. // will change!
  15. #ifndef _CRT_SECURE_NO_WARNINGS
  16. #define _CRT_SECURE_NO_WARNINGS
  17. #endif
  18. #ifndef _CRT_NONSTDC_NO_WARNINGS
  19. #define _CRT_NONSTDC_NO_WARNINGS
  20. #endif
  21. #include "../src/meshoptimizer.h"
  22. #include <algorithm>
  23. #include <string>
  24. #include <vector>
  25. #include <float.h>
  26. #include <limits.h>
  27. #include <math.h>
  28. #include <stdint.h>
  29. #include <stdio.h>
  30. #include <string.h>
  31. #include "cgltf.h"
  32. #include "fast_obj.h"
  33. struct Attr
  34. {
  35. float f[4];
  36. };
  37. struct Stream
  38. {
  39. cgltf_attribute_type type;
  40. int index;
  41. int target; // 0 = base mesh, 1+ = morph target
  42. std::vector<Attr> data;
  43. };
  44. struct Mesh
  45. {
  46. cgltf_node* node;
  47. cgltf_material* material;
  48. cgltf_skin* skin;
  49. std::vector<Stream> streams;
  50. std::vector<unsigned int> indices;
  51. size_t targets;
  52. std::vector<float> weights;
  53. };
  54. struct Settings
  55. {
  56. int pos_bits;
  57. int tex_bits;
  58. int nrm_bits;
  59. bool nrm_unit;
  60. int anim_freq;
  61. bool anim_const;
  62. bool keep_named;
  63. bool compress;
  64. int verbose;
  65. };
  66. struct QuantizationParams
  67. {
  68. float pos_offset[3];
  69. float pos_scale;
  70. int pos_bits;
  71. float uv_offset[2];
  72. float uv_scale[2];
  73. int uv_bits;
  74. };
  75. struct StreamFormat
  76. {
  77. cgltf_type type;
  78. cgltf_component_type component_type;
  79. bool normalized;
  80. size_t stride;
  81. };
  82. struct NodeInfo
  83. {
  84. bool keep;
  85. bool animated;
  86. unsigned int animated_paths;
  87. int remap;
  88. std::vector<size_t> meshes;
  89. };
  90. struct MaterialInfo
  91. {
  92. bool keep;
  93. int remap;
  94. };
  95. struct BufferView
  96. {
  97. enum Kind
  98. {
  99. Kind_Vertex,
  100. Kind_Index,
  101. Kind_Skin,
  102. Kind_Time,
  103. Kind_Keyframe,
  104. Kind_Image,
  105. Kind_Count
  106. };
  107. Kind kind;
  108. int variant;
  109. size_t stride;
  110. bool compressed;
  111. std::string data;
  112. size_t bytes;
  113. };
  114. const char* getError(cgltf_result result)
  115. {
  116. switch (result)
  117. {
  118. case cgltf_result_file_not_found:
  119. return "file not found";
  120. case cgltf_result_io_error:
  121. return "I/O error";
  122. case cgltf_result_invalid_json:
  123. return "invalid JSON";
  124. case cgltf_result_invalid_gltf:
  125. return "invalid GLTF";
  126. case cgltf_result_out_of_memory:
  127. return "out of memory";
  128. default:
  129. return "unknown error";
  130. }
  131. }
  132. cgltf_accessor* getAccessor(const cgltf_attribute* attributes, size_t attribute_count, cgltf_attribute_type type, int index = 0)
  133. {
  134. for (size_t i = 0; i < attribute_count; ++i)
  135. if (attributes[i].type == type && attributes[i].index == index)
  136. return attributes[i].data;
  137. return 0;
  138. }
  139. void transformPosition(float* ptr, const float* transform)
  140. {
  141. float x = ptr[0] * transform[0] + ptr[1] * transform[4] + ptr[2] * transform[8] + transform[12];
  142. float y = ptr[0] * transform[1] + ptr[1] * transform[5] + ptr[2] * transform[9] + transform[13];
  143. float z = ptr[0] * transform[2] + ptr[1] * transform[6] + ptr[2] * transform[10] + transform[14];
  144. ptr[0] = x;
  145. ptr[1] = y;
  146. ptr[2] = z;
  147. }
  148. void transformNormal(float* ptr, const float* transform)
  149. {
  150. float x = ptr[0] * transform[0] + ptr[1] * transform[4] + ptr[2] * transform[8];
  151. float y = ptr[0] * transform[1] + ptr[1] * transform[5] + ptr[2] * transform[9];
  152. float z = ptr[0] * transform[2] + ptr[1] * transform[6] + ptr[2] * transform[10];
  153. float l = sqrtf(x * x + y * y + z * z);
  154. float s = (l == 0.f) ? 0.f : 1 / l;
  155. ptr[0] = x * s;
  156. ptr[1] = y * s;
  157. ptr[2] = z * s;
  158. }
  159. void transformMesh(Mesh& mesh, const cgltf_node* node)
  160. {
  161. float transform[16];
  162. cgltf_node_transform_world(node, transform);
  163. for (size_t si = 0; si < mesh.streams.size(); ++si)
  164. {
  165. Stream& stream = mesh.streams[si];
  166. if (stream.type == cgltf_attribute_type_position)
  167. {
  168. for (size_t i = 0; i < stream.data.size(); ++i)
  169. transformPosition(stream.data[i].f, transform);
  170. }
  171. else if (stream.type == cgltf_attribute_type_normal || stream.type == cgltf_attribute_type_tangent)
  172. {
  173. for (size_t i = 0; i < stream.data.size(); ++i)
  174. transformNormal(stream.data[i].f, transform);
  175. }
  176. }
  177. }
  178. void parseMeshesGltf(cgltf_data* data, std::vector<Mesh>& meshes)
  179. {
  180. for (size_t ni = 0; ni < data->nodes_count; ++ni)
  181. {
  182. cgltf_node& node = data->nodes[ni];
  183. if (!node.mesh)
  184. continue;
  185. const cgltf_mesh& mesh = *node.mesh;
  186. int mesh_id = int(&mesh - data->meshes);
  187. for (size_t pi = 0; pi < mesh.primitives_count; ++pi)
  188. {
  189. const cgltf_primitive& primitive = mesh.primitives[pi];
  190. if (primitive.type != cgltf_primitive_type_triangles)
  191. {
  192. fprintf(stderr, "Warning: ignoring primitive %d of mesh %d because type %d is not supported\n", int(pi), mesh_id, primitive.type);
  193. continue;
  194. }
  195. Mesh result;
  196. result.node = &node;
  197. result.material = primitive.material;
  198. result.skin = node.skin;
  199. if (primitive.indices)
  200. {
  201. result.indices.resize(primitive.indices->count);
  202. for (size_t i = 0; i < primitive.indices->count; ++i)
  203. result.indices[i] = unsigned(cgltf_accessor_read_index(primitive.indices, i));
  204. }
  205. else
  206. {
  207. size_t count = primitive.attributes ? primitive.attributes[0].data->count : 0;
  208. // note, while we could generate a good index buffer, reindexMesh will take care of this
  209. result.indices.resize(count);
  210. for (size_t i = 0; i < count; ++i)
  211. result.indices[i] = unsigned(i);
  212. }
  213. for (size_t ai = 0; ai < primitive.attributes_count; ++ai)
  214. {
  215. const cgltf_attribute& attr = primitive.attributes[ai];
  216. if (attr.type == cgltf_attribute_type_invalid)
  217. {
  218. fprintf(stderr, "Warning: ignoring unknown attribute %s in primitive %d of mesh %d\n", attr.name, int(pi), mesh_id);
  219. continue;
  220. }
  221. Stream s = {attr.type, attr.index};
  222. s.data.resize(attr.data->count);
  223. for (size_t i = 0; i < attr.data->count; ++i)
  224. cgltf_accessor_read_float(attr.data, i, s.data[i].f, 4);
  225. result.streams.push_back(s);
  226. }
  227. for (size_t ti = 0; ti < primitive.targets_count; ++ti)
  228. {
  229. const cgltf_morph_target& target = primitive.targets[ti];
  230. for (size_t ai = 0; ai < target.attributes_count; ++ai)
  231. {
  232. const cgltf_attribute& attr = target.attributes[ai];
  233. if (attr.type == cgltf_attribute_type_invalid)
  234. {
  235. fprintf(stderr, "Warning: ignoring unknown attribute %s in morph target %d of primitive %d of mesh %d\n", attr.name, int(ti), int(pi), mesh_id);
  236. continue;
  237. }
  238. Stream s = {attr.type, attr.index, int(ti + 1)};
  239. s.data.resize(attr.data->count);
  240. for (size_t i = 0; i < attr.data->count; ++i)
  241. cgltf_accessor_read_float(attr.data, i, s.data[i].f, 4);
  242. result.streams.push_back(s);
  243. }
  244. }
  245. result.targets = primitive.targets_count;
  246. result.weights.assign(mesh.weights, mesh.weights + mesh.weights_count);
  247. meshes.push_back(result);
  248. }
  249. }
  250. }
  251. void defaultFree(void*, void* p)
  252. {
  253. free(p);
  254. }
  255. int textureIndex(const std::vector<std::string>& textures, const char* name)
  256. {
  257. for (size_t i = 0; i < textures.size(); ++i)
  258. if (textures[i] == name)
  259. return int(i);
  260. return -1;
  261. }
  262. cgltf_data* parseSceneObj(fastObjMesh* obj)
  263. {
  264. cgltf_data* data = (cgltf_data*)calloc(1, sizeof(cgltf_data));
  265. data->memory_free = defaultFree;
  266. std::vector<std::string> textures;
  267. for (unsigned int mi = 0; mi < obj->material_count; ++mi)
  268. {
  269. fastObjMaterial& om = obj->materials[mi];
  270. if (om.map_Kd.name && textureIndex(textures, om.map_Kd.name) < 0)
  271. textures.push_back(om.map_Kd.name);
  272. }
  273. data->images = (cgltf_image*)calloc(textures.size(), sizeof(cgltf_image));
  274. data->images_count = textures.size();
  275. for (size_t i = 0; i < textures.size(); ++i)
  276. {
  277. data->images[i].uri = strdup(textures[i].c_str());
  278. }
  279. data->textures = (cgltf_texture*)calloc(textures.size(), sizeof(cgltf_texture));
  280. data->textures_count = textures.size();
  281. for (size_t i = 0; i < textures.size(); ++i)
  282. {
  283. data->textures[i].image = &data->images[i];
  284. }
  285. data->materials = (cgltf_material*)calloc(obj->material_count, sizeof(cgltf_material));
  286. data->materials_count = obj->material_count;
  287. for (unsigned int mi = 0; mi < obj->material_count; ++mi)
  288. {
  289. cgltf_material& gm = data->materials[mi];
  290. fastObjMaterial& om = obj->materials[mi];
  291. gm.has_pbr_metallic_roughness = true;
  292. gm.pbr_metallic_roughness.base_color_factor[0] = 1.0f;
  293. gm.pbr_metallic_roughness.base_color_factor[1] = 1.0f;
  294. gm.pbr_metallic_roughness.base_color_factor[2] = 1.0f;
  295. gm.pbr_metallic_roughness.base_color_factor[3] = 1.0f;
  296. gm.pbr_metallic_roughness.metallic_factor = 0.0f;
  297. gm.pbr_metallic_roughness.roughness_factor = 1.0f;
  298. gm.alpha_cutoff = 0.5f;
  299. if (om.map_Kd.name)
  300. {
  301. gm.pbr_metallic_roughness.base_color_texture.texture = &data->textures[textureIndex(textures, om.map_Kd.name)];
  302. gm.pbr_metallic_roughness.base_color_texture.scale = 1.0f;
  303. gm.alpha_mode = (om.illum == 4 || om.illum == 6 || om.illum == 7 || om.illum == 9) ? cgltf_alpha_mode_mask : cgltf_alpha_mode_opaque;
  304. }
  305. if (om.map_d.name)
  306. {
  307. gm.alpha_mode = cgltf_alpha_mode_blend;
  308. }
  309. }
  310. return data;
  311. }
  312. void parseMeshesObj(fastObjMesh* obj, cgltf_data* data, std::vector<Mesh>& meshes)
  313. {
  314. unsigned int material_count = std::max(obj->material_count, 1u);
  315. std::vector<size_t> vertex_count(material_count);
  316. std::vector<size_t> index_count(material_count);
  317. for (unsigned int fi = 0; fi < obj->face_count; ++fi)
  318. {
  319. unsigned int mi = obj->face_materials[fi];
  320. vertex_count[mi] += obj->face_vertices[fi];
  321. index_count[mi] += (obj->face_vertices[fi] - 2) * 3;
  322. }
  323. std::vector<size_t> mesh_index(material_count);
  324. for (unsigned int mi = 0; mi < material_count; ++mi)
  325. {
  326. if (index_count[mi] == 0)
  327. continue;
  328. mesh_index[mi] = meshes.size();
  329. meshes.push_back(Mesh());
  330. Mesh& mesh = meshes.back();
  331. if (data->materials_count)
  332. {
  333. assert(mi < data->materials_count);
  334. mesh.material = &data->materials[mi];
  335. }
  336. mesh.streams.resize(3);
  337. mesh.streams[0].type = cgltf_attribute_type_position;
  338. mesh.streams[0].data.resize(vertex_count[mi]);
  339. mesh.streams[1].type = cgltf_attribute_type_normal;
  340. mesh.streams[1].data.resize(vertex_count[mi]);
  341. mesh.streams[2].type = cgltf_attribute_type_texcoord;
  342. mesh.streams[2].data.resize(vertex_count[mi]);
  343. mesh.indices.resize(index_count[mi]);
  344. mesh.targets = 0;
  345. }
  346. std::vector<size_t> vertex_offset(material_count);
  347. std::vector<size_t> index_offset(material_count);
  348. size_t group_offset = 0;
  349. for (unsigned int fi = 0; fi < obj->face_count; ++fi)
  350. {
  351. unsigned int mi = obj->face_materials[fi];
  352. Mesh& mesh = meshes[mesh_index[mi]];
  353. size_t vo = vertex_offset[mi];
  354. size_t io = index_offset[mi];
  355. for (unsigned int vi = 0; vi < obj->face_vertices[fi]; ++vi)
  356. {
  357. fastObjIndex ii = obj->indices[group_offset + vi];
  358. Attr p = {{obj->positions[ii.p * 3 + 0], obj->positions[ii.p * 3 + 1], obj->positions[ii.p * 3 + 2]}};
  359. Attr n = {{obj->normals[ii.n * 3 + 0], obj->normals[ii.n * 3 + 1], obj->normals[ii.n * 3 + 2]}};
  360. Attr t = {{obj->texcoords[ii.t * 2 + 0], 1.f - obj->texcoords[ii.t * 2 + 1]}};
  361. mesh.streams[0].data[vo + vi] = p;
  362. mesh.streams[1].data[vo + vi] = n;
  363. mesh.streams[2].data[vo + vi] = t;
  364. }
  365. for (unsigned int vi = 2; vi < obj->face_vertices[fi]; ++vi)
  366. {
  367. size_t to = io + (vi - 2) * 3;
  368. mesh.indices[to + 0] = unsigned(vo);
  369. mesh.indices[to + 1] = unsigned(vo + vi - 1);
  370. mesh.indices[to + 2] = unsigned(vo + vi);
  371. }
  372. vertex_offset[mi] += obj->face_vertices[fi];
  373. index_offset[mi] += (obj->face_vertices[fi] - 2) * 3;
  374. group_offset += obj->face_vertices[fi];
  375. }
  376. }
  377. bool areTextureViewsEqual(const cgltf_texture_view& lhs, const cgltf_texture_view& rhs)
  378. {
  379. if (lhs.has_transform != rhs.has_transform)
  380. return false;
  381. if (lhs.has_transform)
  382. {
  383. const cgltf_texture_transform& lt = lhs.transform;
  384. const cgltf_texture_transform& rt = rhs.transform;
  385. if (memcmp(lt.offset, rt.offset, sizeof(cgltf_float) * 2) != 0)
  386. return false;
  387. if (lt.rotation != rt.rotation)
  388. return false;
  389. if (memcmp(lt.scale, rt.scale, sizeof(cgltf_float) * 2) != 0)
  390. return false;
  391. if (lt.texcoord != rt.texcoord)
  392. return false;
  393. }
  394. if (lhs.texture != rhs.texture)
  395. return false;
  396. if (lhs.texcoord != rhs.texcoord)
  397. return false;
  398. if (lhs.scale != rhs.scale)
  399. return false;
  400. return true;
  401. }
  402. bool areMaterialsEqual(const cgltf_material& lhs, const cgltf_material& rhs)
  403. {
  404. if (lhs.has_pbr_metallic_roughness != rhs.has_pbr_metallic_roughness)
  405. return false;
  406. if (lhs.has_pbr_metallic_roughness)
  407. {
  408. const cgltf_pbr_metallic_roughness& lpbr = lhs.pbr_metallic_roughness;
  409. const cgltf_pbr_metallic_roughness& rpbr = rhs.pbr_metallic_roughness;
  410. if (!areTextureViewsEqual(lpbr.base_color_texture, rpbr.base_color_texture))
  411. return false;
  412. if (!areTextureViewsEqual(lpbr.metallic_roughness_texture, rpbr.metallic_roughness_texture))
  413. return false;
  414. if (memcmp(lpbr.base_color_factor, rpbr.base_color_factor, sizeof(cgltf_float) * 4) != 0)
  415. return false;
  416. if (lpbr.metallic_factor != rpbr.metallic_factor)
  417. return false;
  418. if (lpbr.roughness_factor != rpbr.roughness_factor)
  419. return false;
  420. }
  421. if (lhs.has_pbr_specular_glossiness != rhs.has_pbr_specular_glossiness)
  422. return false;
  423. if (lhs.has_pbr_specular_glossiness)
  424. {
  425. const cgltf_pbr_specular_glossiness& lpbr = lhs.pbr_specular_glossiness;
  426. const cgltf_pbr_specular_glossiness& rpbr = rhs.pbr_specular_glossiness;
  427. if (!areTextureViewsEqual(lpbr.diffuse_texture, rpbr.diffuse_texture))
  428. return false;
  429. if (!areTextureViewsEqual(lpbr.specular_glossiness_texture, rpbr.specular_glossiness_texture))
  430. return false;
  431. if (memcmp(lpbr.diffuse_factor, rpbr.diffuse_factor, sizeof(cgltf_float) * 4) != 0)
  432. return false;
  433. if (memcmp(lpbr.specular_factor, rpbr.specular_factor, sizeof(cgltf_float) * 3) != 0)
  434. return false;
  435. if (lpbr.glossiness_factor != rpbr.glossiness_factor)
  436. return false;
  437. }
  438. if (!areTextureViewsEqual(lhs.normal_texture, rhs.normal_texture))
  439. return false;
  440. if (!areTextureViewsEqual(lhs.occlusion_texture, rhs.occlusion_texture))
  441. return false;
  442. if (!areTextureViewsEqual(lhs.emissive_texture, rhs.emissive_texture))
  443. return false;
  444. if (memcmp(lhs.emissive_factor, rhs.emissive_factor, sizeof(cgltf_float) * 3) != 0)
  445. return false;
  446. if (lhs.alpha_mode != rhs.alpha_mode)
  447. return false;
  448. if (lhs.alpha_cutoff != rhs.alpha_cutoff)
  449. return false;
  450. if (lhs.double_sided != rhs.double_sided)
  451. return false;
  452. if (lhs.unlit != rhs.unlit)
  453. return false;
  454. return true;
  455. }
  456. void mergeMeshMaterials(cgltf_data* data, std::vector<Mesh>& meshes)
  457. {
  458. for (size_t i = 0; i < meshes.size(); ++i)
  459. {
  460. Mesh& mesh = meshes[i];
  461. if (mesh.indices.empty())
  462. continue;
  463. if (!mesh.material)
  464. continue;
  465. for (int j = 0; j < mesh.material - data->materials; ++j)
  466. {
  467. if (areMaterialsEqual(*mesh.material, data->materials[j]))
  468. {
  469. mesh.material = &data->materials[j];
  470. break;
  471. }
  472. }
  473. }
  474. }
  475. bool canMergeMeshes(const Mesh& lhs, const Mesh& rhs, const Settings& settings)
  476. {
  477. if (lhs.node != rhs.node)
  478. {
  479. if (!lhs.node || !rhs.node)
  480. return false;
  481. if (lhs.node->parent != rhs.node->parent)
  482. return false;
  483. bool lhs_transform = lhs.node->has_translation | lhs.node->has_rotation | lhs.node->has_scale | lhs.node->has_matrix | (!!lhs.node->weights);
  484. bool rhs_transform = rhs.node->has_translation | rhs.node->has_rotation | rhs.node->has_scale | rhs.node->has_matrix | (!!rhs.node->weights);
  485. if (lhs_transform || rhs_transform)
  486. return false;
  487. if (settings.keep_named)
  488. {
  489. if (lhs.node->name && *lhs.node->name)
  490. return false;
  491. if (rhs.node->name && *rhs.node->name)
  492. return false;
  493. }
  494. // we can merge nodes that don't have transforms of their own and have the same parent
  495. // this is helpful when instead of splitting mesh into primitives, DCCs split mesh into mesh nodes
  496. }
  497. if (lhs.material != rhs.material)
  498. return false;
  499. if (lhs.skin != rhs.skin)
  500. return false;
  501. if (lhs.targets != rhs.targets)
  502. return false;
  503. if (lhs.weights.size() != rhs.weights.size())
  504. return false;
  505. for (size_t i = 0; i < lhs.weights.size(); ++i)
  506. if (lhs.weights[i] != rhs.weights[i])
  507. return false;
  508. if (lhs.streams.size() != rhs.streams.size())
  509. return false;
  510. for (size_t i = 0; i < lhs.streams.size(); ++i)
  511. if (lhs.streams[i].type != rhs.streams[i].type || lhs.streams[i].index != rhs.streams[i].index || lhs.streams[i].target != rhs.streams[i].target)
  512. return false;
  513. return true;
  514. }
  515. void mergeMeshes(Mesh& target, const Mesh& mesh)
  516. {
  517. assert(target.streams.size() == mesh.streams.size());
  518. size_t vertex_offset = target.streams[0].data.size();
  519. size_t index_offset = target.indices.size();
  520. for (size_t i = 0; i < target.streams.size(); ++i)
  521. target.streams[i].data.insert(target.streams[i].data.end(), mesh.streams[i].data.begin(), mesh.streams[i].data.end());
  522. target.indices.resize(target.indices.size() + mesh.indices.size());
  523. size_t index_count = mesh.indices.size();
  524. for (size_t i = 0; i < index_count; ++i)
  525. target.indices[index_offset + i] = unsigned(vertex_offset + mesh.indices[i]);
  526. }
  527. void mergeMeshes(std::vector<Mesh>& meshes, const Settings& settings)
  528. {
  529. for (size_t i = 0; i < meshes.size(); ++i)
  530. {
  531. Mesh& mesh = meshes[i];
  532. for (size_t j = 0; j < i; ++j)
  533. {
  534. Mesh& target = meshes[j];
  535. if (target.indices.size() && canMergeMeshes(mesh, target, settings))
  536. {
  537. mergeMeshes(target, mesh);
  538. mesh.streams.clear();
  539. mesh.indices.clear();
  540. break;
  541. }
  542. }
  543. }
  544. }
  545. void reindexMesh(Mesh& mesh)
  546. {
  547. size_t total_vertices = mesh.streams[0].data.size();
  548. size_t total_indices = mesh.indices.size();
  549. std::vector<meshopt_Stream> streams;
  550. for (size_t i = 0; i < mesh.streams.size(); ++i)
  551. {
  552. if (mesh.streams[i].target)
  553. continue;
  554. assert(mesh.streams[i].data.size() == total_vertices);
  555. meshopt_Stream stream = {&mesh.streams[i].data[0], sizeof(Attr), sizeof(Attr)};
  556. streams.push_back(stream);
  557. }
  558. std::vector<unsigned int> remap(total_vertices);
  559. size_t unique_vertices = meshopt_generateVertexRemapMulti(&remap[0], &mesh.indices[0], total_indices, total_vertices, &streams[0], streams.size());
  560. assert(unique_vertices <= total_vertices);
  561. meshopt_remapIndexBuffer(&mesh.indices[0], &mesh.indices[0], total_indices, &remap[0]);
  562. for (size_t i = 0; i < mesh.streams.size(); ++i)
  563. {
  564. assert(mesh.streams[i].data.size() == total_vertices);
  565. meshopt_remapVertexBuffer(&mesh.streams[i].data[0], &mesh.streams[i].data[0], total_vertices, sizeof(Attr), &remap[0]);
  566. mesh.streams[i].data.resize(unique_vertices);
  567. }
  568. }
  569. void optimizeMesh(Mesh& mesh)
  570. {
  571. size_t vertex_count = mesh.streams[0].data.size();
  572. meshopt_optimizeVertexCache(&mesh.indices[0], &mesh.indices[0], mesh.indices.size(), vertex_count);
  573. std::vector<unsigned int> remap(vertex_count);
  574. size_t unique_vertices = meshopt_optimizeVertexFetchRemap(&remap[0], &mesh.indices[0], mesh.indices.size(), vertex_count);
  575. assert(unique_vertices == vertex_count);
  576. (void)unique_vertices;
  577. meshopt_remapIndexBuffer(&mesh.indices[0], &mesh.indices[0], mesh.indices.size(), &remap[0]);
  578. for (size_t i = 0; i < mesh.streams.size(); ++i)
  579. meshopt_remapVertexBuffer(&mesh.streams[i].data[0], &mesh.streams[i].data[0], vertex_count, sizeof(Attr), &remap[0]);
  580. }
  581. bool getAttributeBounds(const std::vector<Mesh>& meshes, cgltf_attribute_type type, Attr& min, Attr& max)
  582. {
  583. min.f[0] = min.f[1] = min.f[2] = min.f[3] = +FLT_MAX;
  584. max.f[0] = max.f[1] = max.f[2] = max.f[3] = -FLT_MAX;
  585. Attr pad = {};
  586. bool valid = false;
  587. for (size_t i = 0; i < meshes.size(); ++i)
  588. {
  589. const Mesh& mesh = meshes[i];
  590. for (size_t j = 0; j < mesh.streams.size(); ++j)
  591. {
  592. const Stream& s = mesh.streams[j];
  593. if (s.type == type)
  594. {
  595. if (s.target == 0)
  596. {
  597. for (size_t k = 0; k < s.data.size(); ++k)
  598. {
  599. const Attr& a = s.data[k];
  600. min.f[0] = std::min(min.f[0], a.f[0]);
  601. min.f[1] = std::min(min.f[1], a.f[1]);
  602. min.f[2] = std::min(min.f[2], a.f[2]);
  603. min.f[3] = std::min(min.f[3], a.f[3]);
  604. max.f[0] = std::max(max.f[0], a.f[0]);
  605. max.f[1] = std::max(max.f[1], a.f[1]);
  606. max.f[2] = std::max(max.f[2], a.f[2]);
  607. max.f[3] = std::max(max.f[3], a.f[3]);
  608. valid = true;
  609. }
  610. }
  611. else
  612. {
  613. for (size_t k = 0; k < s.data.size(); ++k)
  614. {
  615. const Attr& a = s.data[k];
  616. pad.f[0] = std::max(pad.f[0], fabsf(a.f[0]));
  617. pad.f[1] = std::max(pad.f[1], fabsf(a.f[1]));
  618. pad.f[2] = std::max(pad.f[2], fabsf(a.f[2]));
  619. pad.f[3] = std::max(pad.f[3], fabsf(a.f[3]));
  620. }
  621. }
  622. }
  623. }
  624. }
  625. if (valid)
  626. {
  627. for (int k = 0; k < 4; ++k)
  628. {
  629. min.f[k] -= pad.f[k];
  630. max.f[k] += pad.f[k];
  631. }
  632. }
  633. return valid;
  634. }
  635. QuantizationParams prepareQuantization(const std::vector<Mesh>& meshes, const Settings& settings)
  636. {
  637. QuantizationParams result = {};
  638. result.pos_bits = settings.pos_bits;
  639. Attr pos_min, pos_max;
  640. if (getAttributeBounds(meshes, cgltf_attribute_type_position, pos_min, pos_max))
  641. {
  642. result.pos_offset[0] = pos_min.f[0];
  643. result.pos_offset[1] = pos_min.f[1];
  644. result.pos_offset[2] = pos_min.f[2];
  645. result.pos_scale = std::max(pos_max.f[0] - pos_min.f[0], std::max(pos_max.f[1] - pos_min.f[1], pos_max.f[2] - pos_min.f[2]));
  646. }
  647. result.uv_bits = settings.tex_bits;
  648. Attr uv_min, uv_max;
  649. if (getAttributeBounds(meshes, cgltf_attribute_type_texcoord, uv_min, uv_max))
  650. {
  651. result.uv_offset[0] = uv_min.f[0];
  652. result.uv_offset[1] = uv_min.f[1];
  653. result.uv_scale[0] = uv_max.f[0] - uv_min.f[0];
  654. result.uv_scale[1] = uv_max.f[1] - uv_min.f[1];
  655. }
  656. return result;
  657. }
  658. void rescaleNormal(float& nx, float& ny, float& nz)
  659. {
  660. // scale the normal to make sure the largest component is +-1.0
  661. // this reduces the entropy of the normal by ~1.5 bits without losing precision
  662. // it's better to use octahedral encoding but that requires special shader support
  663. float nm = std::max(fabsf(nx), std::max(fabsf(ny), fabsf(nz)));
  664. float ns = nm == 0.f ? 0.f : 1 / nm;
  665. nx *= ns;
  666. ny *= ns;
  667. nz *= ns;
  668. }
  669. void renormalizeWeights(uint8_t (&w)[4])
  670. {
  671. int sum = w[0] + w[1] + w[2] + w[3];
  672. if (sum == 255)
  673. return;
  674. // we assume that the total error is limited to 0.5/component = 2
  675. // this means that it's acceptable to adjust the max. component to compensate for the error
  676. int max = 0;
  677. for (int k = 1; k < 4; ++k)
  678. if (w[k] > w[max])
  679. max = k;
  680. w[max] += uint8_t(255 - sum);
  681. }
  682. StreamFormat writeVertexStream(std::string& bin, const Stream& stream, const QuantizationParams& params, const Settings& settings, bool has_targets)
  683. {
  684. if (stream.type == cgltf_attribute_type_position)
  685. {
  686. if (stream.target == 0)
  687. {
  688. float pos_rscale = params.pos_scale == 0.f ? 0.f : 1.f / params.pos_scale;
  689. for (size_t i = 0; i < stream.data.size(); ++i)
  690. {
  691. const Attr& a = stream.data[i];
  692. uint16_t v[4] = {
  693. uint16_t(meshopt_quantizeUnorm((a.f[0] - params.pos_offset[0]) * pos_rscale, params.pos_bits)),
  694. uint16_t(meshopt_quantizeUnorm((a.f[1] - params.pos_offset[1]) * pos_rscale, params.pos_bits)),
  695. uint16_t(meshopt_quantizeUnorm((a.f[2] - params.pos_offset[2]) * pos_rscale, params.pos_bits)),
  696. 0};
  697. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  698. }
  699. StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_16u, false, 8};
  700. return format;
  701. }
  702. else
  703. {
  704. float pos_rscale = params.pos_scale == 0.f ? 0.f : 1.f / params.pos_scale;
  705. for (size_t i = 0; i < stream.data.size(); ++i)
  706. {
  707. const Attr& a = stream.data[i];
  708. int16_t v[4] = {
  709. int16_t((a.f[0] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[0]) * pos_rscale, params.pos_bits)),
  710. int16_t((a.f[1] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[1]) * pos_rscale, params.pos_bits)),
  711. int16_t((a.f[2] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[2]) * pos_rscale, params.pos_bits)),
  712. 0};
  713. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  714. }
  715. StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_16, false, 8};
  716. return format;
  717. }
  718. }
  719. else if (stream.type == cgltf_attribute_type_texcoord)
  720. {
  721. float uv_rscale[2] = {
  722. params.uv_scale[0] == 0.f ? 0.f : 1.f / params.uv_scale[0],
  723. params.uv_scale[1] == 0.f ? 0.f : 1.f / params.uv_scale[1],
  724. };
  725. for (size_t i = 0; i < stream.data.size(); ++i)
  726. {
  727. const Attr& a = stream.data[i];
  728. uint16_t v[2] = {
  729. uint16_t(meshopt_quantizeUnorm((a.f[0] - params.uv_offset[0]) * uv_rscale[0], params.uv_bits)),
  730. uint16_t(meshopt_quantizeUnorm((a.f[1] - params.uv_offset[1]) * uv_rscale[1], params.uv_bits)),
  731. };
  732. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  733. }
  734. StreamFormat format = {cgltf_type_vec2, cgltf_component_type_r_16u, false, 4};
  735. return format;
  736. }
  737. else if (stream.type == cgltf_attribute_type_normal)
  738. {
  739. bool nrm_unit = has_targets || settings.nrm_unit;
  740. int bits = nrm_unit ? 8 : settings.nrm_bits;
  741. for (size_t i = 0; i < stream.data.size(); ++i)
  742. {
  743. const Attr& a = stream.data[i];
  744. float nx = a.f[0], ny = a.f[1], nz = a.f[2];
  745. if (!nrm_unit)
  746. rescaleNormal(nx, ny, nz);
  747. int8_t v[4] = {
  748. int8_t(meshopt_quantizeSnorm(nx, bits)),
  749. int8_t(meshopt_quantizeSnorm(ny, bits)),
  750. int8_t(meshopt_quantizeSnorm(nz, bits)),
  751. 0};
  752. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  753. }
  754. StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_8, true, 4};
  755. return format;
  756. }
  757. else if (stream.type == cgltf_attribute_type_tangent)
  758. {
  759. bool nrm_unit = has_targets || settings.nrm_unit;
  760. int bits = nrm_unit ? 8 : settings.nrm_bits;
  761. for (size_t i = 0; i < stream.data.size(); ++i)
  762. {
  763. const Attr& a = stream.data[i];
  764. float nx = a.f[0], ny = a.f[1], nz = a.f[2], nw = a.f[3];
  765. if (!nrm_unit)
  766. rescaleNormal(nx, ny, nz);
  767. int8_t v[4] = {
  768. int8_t(meshopt_quantizeSnorm(nx, bits)),
  769. int8_t(meshopt_quantizeSnorm(ny, bits)),
  770. int8_t(meshopt_quantizeSnorm(nz, bits)),
  771. int8_t(meshopt_quantizeSnorm(nw, 8))};
  772. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  773. }
  774. if (stream.target == 0)
  775. {
  776. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_8, true, 4};
  777. return format;
  778. }
  779. else
  780. {
  781. StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_8, true, 4};
  782. return format;
  783. }
  784. }
  785. else if (stream.type == cgltf_attribute_type_color)
  786. {
  787. for (size_t i = 0; i < stream.data.size(); ++i)
  788. {
  789. const Attr& a = stream.data[i];
  790. uint8_t v[4] = {
  791. uint8_t(meshopt_quantizeUnorm(a.f[0], 8)),
  792. uint8_t(meshopt_quantizeUnorm(a.f[1], 8)),
  793. uint8_t(meshopt_quantizeUnorm(a.f[2], 8)),
  794. uint8_t(meshopt_quantizeUnorm(a.f[3], 8))};
  795. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  796. }
  797. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_8u, true, 4};
  798. return format;
  799. }
  800. else if (stream.type == cgltf_attribute_type_weights)
  801. {
  802. for (size_t i = 0; i < stream.data.size(); ++i)
  803. {
  804. const Attr& a = stream.data[i];
  805. uint8_t v[4] = {
  806. uint8_t(meshopt_quantizeUnorm(a.f[0], 8)),
  807. uint8_t(meshopt_quantizeUnorm(a.f[1], 8)),
  808. uint8_t(meshopt_quantizeUnorm(a.f[2], 8)),
  809. uint8_t(meshopt_quantizeUnorm(a.f[3], 8))};
  810. renormalizeWeights(v);
  811. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  812. }
  813. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_8u, true, 4};
  814. return format;
  815. }
  816. else if (stream.type == cgltf_attribute_type_joints)
  817. {
  818. unsigned int maxj = 0;
  819. for (size_t i = 0; i < stream.data.size(); ++i)
  820. maxj = std::max(maxj, unsigned(stream.data[i].f[0]));
  821. assert(maxj <= 65535);
  822. if (maxj <= 255)
  823. {
  824. for (size_t i = 0; i < stream.data.size(); ++i)
  825. {
  826. const Attr& a = stream.data[i];
  827. uint8_t v[4] = {
  828. uint8_t(a.f[0]),
  829. uint8_t(a.f[1]),
  830. uint8_t(a.f[2]),
  831. uint8_t(a.f[3])};
  832. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  833. }
  834. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_8u, false, 4};
  835. return format;
  836. }
  837. else
  838. {
  839. for (size_t i = 0; i < stream.data.size(); ++i)
  840. {
  841. const Attr& a = stream.data[i];
  842. uint16_t v[4] = {
  843. uint16_t(a.f[0]),
  844. uint16_t(a.f[1]),
  845. uint16_t(a.f[2]),
  846. uint16_t(a.f[3])};
  847. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  848. }
  849. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_16u, false, 8};
  850. return format;
  851. }
  852. }
  853. else
  854. {
  855. for (size_t i = 0; i < stream.data.size(); ++i)
  856. {
  857. const Attr& a = stream.data[i];
  858. float v[4] = {
  859. a.f[0],
  860. a.f[1],
  861. a.f[2],
  862. a.f[3]};
  863. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  864. }
  865. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_32f, false, 16};
  866. return format;
  867. }
  868. }
  869. void getPositionBounds(int min[3], int max[3], const Stream& stream, const QuantizationParams& params)
  870. {
  871. assert(stream.type == cgltf_attribute_type_position);
  872. assert(stream.data.size() > 0);
  873. min[0] = min[1] = min[2] = INT_MAX;
  874. max[0] = max[1] = max[2] = INT_MIN;
  875. float pos_rscale = params.pos_scale == 0.f ? 0.f : 1.f / params.pos_scale;
  876. if (stream.target == 0)
  877. {
  878. for (size_t i = 0; i < stream.data.size(); ++i)
  879. {
  880. const Attr& a = stream.data[i];
  881. for (int k = 0; k < 3; ++k)
  882. {
  883. int v = meshopt_quantizeUnorm((a.f[k] - params.pos_offset[k]) * pos_rscale, params.pos_bits);
  884. min[k] = std::min(min[k], v);
  885. max[k] = std::max(max[k], v);
  886. }
  887. }
  888. }
  889. else
  890. {
  891. for (size_t i = 0; i < stream.data.size(); ++i)
  892. {
  893. const Attr& a = stream.data[i];
  894. for (int k = 0; k < 3; ++k)
  895. {
  896. int v = (a.f[k] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[k]) * pos_rscale, params.pos_bits);
  897. min[k] = std::min(min[k], v);
  898. max[k] = std::max(max[k], v);
  899. }
  900. }
  901. }
  902. }
  903. StreamFormat writeIndexStream(std::string& bin, const std::vector<unsigned int>& stream)
  904. {
  905. unsigned int maxi = 0;
  906. for (size_t i = 0; i < stream.size(); ++i)
  907. maxi = std::max(maxi, stream[i]);
  908. // save 16-bit indices if we can; note that we can't use restart index (65535)
  909. if (maxi < 65535)
  910. {
  911. for (size_t i = 0; i < stream.size(); ++i)
  912. {
  913. uint16_t v[1] = {uint16_t(stream[i])};
  914. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  915. }
  916. StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_16u, false, 2};
  917. return format;
  918. }
  919. else
  920. {
  921. for (size_t i = 0; i < stream.size(); ++i)
  922. {
  923. uint32_t v[1] = {stream[i]};
  924. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  925. }
  926. StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_32u, false, 4};
  927. return format;
  928. }
  929. }
  930. StreamFormat writeTimeStream(std::string& bin, const std::vector<float>& data)
  931. {
  932. for (size_t i = 0; i < data.size(); ++i)
  933. {
  934. float v[1] = {data[i]};
  935. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  936. }
  937. StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_32f, false, 4};
  938. return format;
  939. }
  940. StreamFormat writeKeyframeStream(std::string& bin, cgltf_animation_path_type type, const std::vector<Attr>& data)
  941. {
  942. if (type == cgltf_animation_path_type_rotation)
  943. {
  944. for (size_t i = 0; i < data.size(); ++i)
  945. {
  946. const Attr& a = data[i];
  947. int16_t v[4] = {
  948. int16_t(meshopt_quantizeSnorm(a.f[0], 16)),
  949. int16_t(meshopt_quantizeSnorm(a.f[1], 16)),
  950. int16_t(meshopt_quantizeSnorm(a.f[2], 16)),
  951. int16_t(meshopt_quantizeSnorm(a.f[3], 16)),
  952. };
  953. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  954. }
  955. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_16, true, 8};
  956. return format;
  957. }
  958. else if (type == cgltf_animation_path_type_weights)
  959. {
  960. for (size_t i = 0; i < data.size(); ++i)
  961. {
  962. const Attr& a = data[i];
  963. uint8_t v[1] = {uint8_t(meshopt_quantizeUnorm(a.f[0], 8))};
  964. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  965. }
  966. StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_8u, true, 1};
  967. return format;
  968. }
  969. else
  970. {
  971. for (size_t i = 0; i < data.size(); ++i)
  972. {
  973. const Attr& a = data[i];
  974. float v[3] = {a.f[0], a.f[1], a.f[2]};
  975. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  976. }
  977. StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_32f, false, 12};
  978. return format;
  979. }
  980. }
  981. void compressVertexStream(std::string& bin, const std::string& data, size_t count, size_t stride)
  982. {
  983. assert(data.size() == count * stride);
  984. std::vector<unsigned char> compressed(meshopt_encodeVertexBufferBound(count, stride));
  985. size_t size = meshopt_encodeVertexBuffer(&compressed[0], compressed.size(), data.c_str(), count, stride);
  986. bin.append(reinterpret_cast<const char*>(&compressed[0]), size);
  987. }
  988. void compressIndexStream(std::string& bin, const std::string& data, size_t count, size_t stride)
  989. {
  990. assert(stride == 2 || stride == 4);
  991. assert(data.size() == count * stride);
  992. std::vector<unsigned char> compressed(meshopt_encodeIndexBufferBound(count, count * 3));
  993. size_t size = 0;
  994. if (stride == 2)
  995. size = meshopt_encodeIndexBuffer(&compressed[0], compressed.size(), reinterpret_cast<const uint16_t*>(data.c_str()), count);
  996. else
  997. size = meshopt_encodeIndexBuffer(&compressed[0], compressed.size(), reinterpret_cast<const uint32_t*>(data.c_str()), count);
  998. bin.append(reinterpret_cast<const char*>(&compressed[0]), size);
  999. }
  1000. void comma(std::string& s)
  1001. {
  1002. char ch = s.empty() ? 0 : s[s.size() - 1];
  1003. if (ch != 0 && ch != '[' && ch != '{')
  1004. s += ",";
  1005. }
  1006. void append(std::string& s, size_t v)
  1007. {
  1008. char buf[32];
  1009. sprintf(buf, "%zu", v);
  1010. s += buf;
  1011. }
  1012. void append(std::string& s, float v)
  1013. {
  1014. char buf[512];
  1015. sprintf(buf, "%.9g", v);
  1016. s += buf;
  1017. }
  1018. void append(std::string& s, const char* v)
  1019. {
  1020. s += v;
  1021. }
  1022. void append(std::string& s, const std::string& v)
  1023. {
  1024. s += v;
  1025. }
  1026. const char* componentType(cgltf_component_type type)
  1027. {
  1028. switch (type)
  1029. {
  1030. case cgltf_component_type_r_8:
  1031. return "5120";
  1032. case cgltf_component_type_r_8u:
  1033. return "5121";
  1034. case cgltf_component_type_r_16:
  1035. return "5122";
  1036. case cgltf_component_type_r_16u:
  1037. return "5123";
  1038. case cgltf_component_type_r_32u:
  1039. return "5125";
  1040. case cgltf_component_type_r_32f:
  1041. return "5126";
  1042. default:
  1043. return "0";
  1044. }
  1045. }
  1046. const char* shapeType(cgltf_type type)
  1047. {
  1048. switch (type)
  1049. {
  1050. case cgltf_type_scalar:
  1051. return "SCALAR";
  1052. case cgltf_type_vec2:
  1053. return "VEC2";
  1054. case cgltf_type_vec3:
  1055. return "VEC3";
  1056. case cgltf_type_vec4:
  1057. return "VEC4";
  1058. case cgltf_type_mat2:
  1059. return "MAT2";
  1060. case cgltf_type_mat3:
  1061. return "MAT3";
  1062. case cgltf_type_mat4:
  1063. return "MAT4";
  1064. default:
  1065. return "";
  1066. }
  1067. }
  1068. const char* attributeType(cgltf_attribute_type type)
  1069. {
  1070. switch (type)
  1071. {
  1072. case cgltf_attribute_type_position:
  1073. return "POSITION";
  1074. case cgltf_attribute_type_normal:
  1075. return "NORMAL";
  1076. case cgltf_attribute_type_tangent:
  1077. return "TANGENT";
  1078. case cgltf_attribute_type_texcoord:
  1079. return "TEXCOORD";
  1080. case cgltf_attribute_type_color:
  1081. return "COLOR";
  1082. case cgltf_attribute_type_joints:
  1083. return "JOINTS";
  1084. case cgltf_attribute_type_weights:
  1085. return "WEIGHTS";
  1086. default:
  1087. return "ATTRIBUTE";
  1088. }
  1089. }
  1090. const char* animationPath(cgltf_animation_path_type type)
  1091. {
  1092. switch (type)
  1093. {
  1094. case cgltf_animation_path_type_translation:
  1095. return "translation";
  1096. case cgltf_animation_path_type_rotation:
  1097. return "rotation";
  1098. case cgltf_animation_path_type_scale:
  1099. return "scale";
  1100. case cgltf_animation_path_type_weights:
  1101. return "weights";
  1102. default:
  1103. return "";
  1104. }
  1105. }
  1106. const char* lightType(cgltf_light_type type)
  1107. {
  1108. switch (type)
  1109. {
  1110. case cgltf_light_type_directional:
  1111. return "directional";
  1112. case cgltf_light_type_point:
  1113. return "point";
  1114. case cgltf_light_type_spot:
  1115. return "spot";
  1116. default:
  1117. return "";
  1118. }
  1119. }
  1120. void writeTextureInfo(std::string& json, const cgltf_data* data, const cgltf_texture_view& view, const QuantizationParams& qp)
  1121. {
  1122. assert(view.texture);
  1123. cgltf_texture_transform transform = {};
  1124. if (view.has_transform)
  1125. {
  1126. transform = view.transform;
  1127. }
  1128. else
  1129. {
  1130. transform.scale[0] = transform.scale[1] = 1.f;
  1131. }
  1132. transform.offset[0] += qp.uv_offset[0];
  1133. transform.offset[1] += qp.uv_offset[1];
  1134. transform.scale[0] *= qp.uv_scale[0] / float((1 << qp.uv_bits) - 1);
  1135. transform.scale[1] *= qp.uv_scale[1] / float((1 << qp.uv_bits) - 1);
  1136. append(json, "{\"index\":");
  1137. append(json, size_t(view.texture - data->textures));
  1138. append(json, ",\"texCoord\":");
  1139. append(json, size_t(view.texcoord));
  1140. append(json, ",\"extensions\":{\"KHR_texture_transform\":{");
  1141. append(json, "\"offset\":[");
  1142. append(json, transform.offset[0]);
  1143. append(json, ",");
  1144. append(json, transform.offset[1]);
  1145. append(json, "],\"scale\":[");
  1146. append(json, transform.scale[0]);
  1147. append(json, ",");
  1148. append(json, transform.scale[1]);
  1149. append(json, "]");
  1150. if (transform.rotation != 0.f)
  1151. {
  1152. append(json, ",\"rotation\":");
  1153. append(json, transform.rotation);
  1154. }
  1155. append(json, "}}}");
  1156. }
  1157. void writeMaterialInfo(std::string& json, const cgltf_data* data, const cgltf_material& material, const QuantizationParams& qp)
  1158. {
  1159. static const float white[4] = {1, 1, 1, 1};
  1160. static const float black[4] = {0, 0, 0, 0};
  1161. if (material.has_pbr_metallic_roughness)
  1162. {
  1163. const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness;
  1164. comma(json);
  1165. append(json, "\"pbrMetallicRoughness\":{");
  1166. if (memcmp(pbr.base_color_factor, white, 16) != 0)
  1167. {
  1168. comma(json);
  1169. append(json, "\"baseColorFactor\":[");
  1170. append(json, pbr.base_color_factor[0]);
  1171. append(json, ",");
  1172. append(json, pbr.base_color_factor[1]);
  1173. append(json, ",");
  1174. append(json, pbr.base_color_factor[2]);
  1175. append(json, ",");
  1176. append(json, pbr.base_color_factor[3]);
  1177. append(json, "]");
  1178. }
  1179. if (pbr.base_color_texture.texture)
  1180. {
  1181. comma(json);
  1182. append(json, "\"baseColorTexture\":");
  1183. writeTextureInfo(json, data, pbr.base_color_texture, qp);
  1184. }
  1185. if (pbr.metallic_factor != 1)
  1186. {
  1187. comma(json);
  1188. append(json, "\"metallicFactor\":");
  1189. append(json, pbr.metallic_factor);
  1190. }
  1191. if (pbr.roughness_factor != 1)
  1192. {
  1193. comma(json);
  1194. append(json, "\"roughnessFactor\":");
  1195. append(json, pbr.roughness_factor);
  1196. }
  1197. if (pbr.metallic_roughness_texture.texture)
  1198. {
  1199. comma(json);
  1200. append(json, "\"metallicRoughnessTexture\":");
  1201. writeTextureInfo(json, data, pbr.metallic_roughness_texture, qp);
  1202. }
  1203. append(json, "}");
  1204. }
  1205. if (material.normal_texture.texture)
  1206. {
  1207. comma(json);
  1208. append(json, "\"normalTexture\":");
  1209. writeTextureInfo(json, data, material.normal_texture, qp);
  1210. }
  1211. if (material.occlusion_texture.texture)
  1212. {
  1213. comma(json);
  1214. append(json, "\"occlusionTexture\":");
  1215. writeTextureInfo(json, data, material.occlusion_texture, qp);
  1216. }
  1217. if (material.emissive_texture.texture)
  1218. {
  1219. comma(json);
  1220. append(json, "\"emissiveTexture\":");
  1221. writeTextureInfo(json, data, material.emissive_texture, qp);
  1222. }
  1223. if (memcmp(material.emissive_factor, black, 12) != 0)
  1224. {
  1225. comma(json);
  1226. append(json, "\"emissiveFactor\":[");
  1227. append(json, material.emissive_factor[0]);
  1228. append(json, ",");
  1229. append(json, material.emissive_factor[1]);
  1230. append(json, ",");
  1231. append(json, material.emissive_factor[2]);
  1232. append(json, "]");
  1233. }
  1234. if (material.alpha_mode != cgltf_alpha_mode_opaque)
  1235. {
  1236. comma(json);
  1237. append(json, "\"alphaMode\":");
  1238. append(json, (material.alpha_mode == cgltf_alpha_mode_blend) ? "\"BLEND\"" : "\"MASK\"");
  1239. }
  1240. if (material.alpha_cutoff != 0.5f)
  1241. {
  1242. comma(json);
  1243. append(json, "\"alphaCutoff\":");
  1244. append(json, material.alpha_cutoff);
  1245. }
  1246. if (material.double_sided)
  1247. {
  1248. comma(json);
  1249. append(json, "\"doubleSided\":true");
  1250. }
  1251. if (material.has_pbr_specular_glossiness || material.unlit)
  1252. {
  1253. comma(json);
  1254. append(json, "\"extensions\":{");
  1255. if (material.has_pbr_specular_glossiness)
  1256. {
  1257. const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness;
  1258. comma(json);
  1259. append(json, "\"KHR_materials_pbrSpecularGlossiness\":{");
  1260. if (pbr.diffuse_texture.texture)
  1261. {
  1262. comma(json);
  1263. append(json, "\"diffuseTexture\":");
  1264. writeTextureInfo(json, data, pbr.diffuse_texture, qp);
  1265. }
  1266. if (pbr.specular_glossiness_texture.texture)
  1267. {
  1268. comma(json);
  1269. append(json, "\"specularGlossinessTexture\":");
  1270. writeTextureInfo(json, data, pbr.specular_glossiness_texture, qp);
  1271. }
  1272. if (memcmp(pbr.diffuse_factor, white, 16) != 0)
  1273. {
  1274. comma(json);
  1275. append(json, "\"diffuseFactor\":[");
  1276. append(json, pbr.diffuse_factor[0]);
  1277. append(json, ",");
  1278. append(json, pbr.diffuse_factor[1]);
  1279. append(json, ",");
  1280. append(json, pbr.diffuse_factor[2]);
  1281. append(json, ",");
  1282. append(json, pbr.diffuse_factor[3]);
  1283. append(json, "]");
  1284. }
  1285. if (memcmp(pbr.specular_factor, white, 12) != 0)
  1286. {
  1287. comma(json);
  1288. append(json, "\"specularFactor\":[");
  1289. append(json, pbr.specular_factor[0]);
  1290. append(json, ",");
  1291. append(json, pbr.specular_factor[1]);
  1292. append(json, ",");
  1293. append(json, pbr.specular_factor[2]);
  1294. append(json, "]");
  1295. }
  1296. if (pbr.glossiness_factor != 1)
  1297. {
  1298. comma(json);
  1299. append(json, "\"glossinessFactor\":");
  1300. append(json, pbr.glossiness_factor);
  1301. }
  1302. append(json, "}");
  1303. }
  1304. if (material.unlit)
  1305. {
  1306. comma(json);
  1307. append(json, "\"KHR_materials_unlit\":{}");
  1308. }
  1309. append(json, "}");
  1310. }
  1311. }
  1312. bool usesTextureSet(const cgltf_material& material, int set)
  1313. {
  1314. if (material.has_pbr_metallic_roughness)
  1315. {
  1316. const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness;
  1317. if (pbr.base_color_texture.texture && pbr.base_color_texture.texcoord == set)
  1318. return true;
  1319. if (pbr.metallic_roughness_texture.texture && pbr.metallic_roughness_texture.texcoord == set)
  1320. return true;
  1321. }
  1322. if (material.has_pbr_specular_glossiness)
  1323. {
  1324. const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness;
  1325. if (pbr.diffuse_texture.texture && pbr.diffuse_texture.texcoord == set)
  1326. return true;
  1327. if (pbr.specular_glossiness_texture.texture && pbr.specular_glossiness_texture.texcoord == set)
  1328. return true;
  1329. }
  1330. if (material.normal_texture.texture && material.normal_texture.texcoord == set)
  1331. return true;
  1332. if (material.occlusion_texture.texture && material.occlusion_texture.texcoord == set)
  1333. return true;
  1334. if (material.emissive_texture.texture && material.emissive_texture.texcoord == set)
  1335. return true;
  1336. return false;
  1337. }
  1338. size_t getBufferView(std::vector<BufferView>& views, BufferView::Kind kind, int variant, size_t stride, bool compressed)
  1339. {
  1340. if (variant >= 0)
  1341. {
  1342. for (size_t i = 0; i < views.size(); ++i)
  1343. if (views[i].kind == kind && views[i].variant == variant && views[i].stride == stride && views[i].compressed == compressed)
  1344. return i;
  1345. }
  1346. BufferView view = {kind, variant, stride, compressed};
  1347. views.push_back(view);
  1348. return views.size() - 1;
  1349. }
  1350. void writeBufferView(std::string& json, BufferView::Kind kind, size_t count, size_t stride, size_t bin_offset, size_t bin_size, int compression)
  1351. {
  1352. append(json, "{\"buffer\":0");
  1353. append(json, ",\"byteLength\":");
  1354. append(json, bin_size);
  1355. append(json, ",\"byteOffset\":");
  1356. append(json, bin_offset);
  1357. if (kind == BufferView::Kind_Vertex)
  1358. {
  1359. append(json, ",\"byteStride\":");
  1360. append(json, stride);
  1361. }
  1362. if (kind == BufferView::Kind_Vertex || kind == BufferView::Kind_Index)
  1363. {
  1364. append(json, ",\"target\":");
  1365. append(json, (kind == BufferView::Kind_Vertex) ? "34962" : "34963");
  1366. }
  1367. if (compression >= 0)
  1368. {
  1369. append(json, ",\"extensions\":{");
  1370. append(json, "\"MESHOPT_compression\":{");
  1371. append(json, "\"mode\":");
  1372. append(json, size_t(compression));
  1373. append(json, ",\"count\":");
  1374. append(json, count);
  1375. append(json, ",\"byteStride\":");
  1376. append(json, stride);
  1377. append(json, "}}");
  1378. }
  1379. append(json, "}");
  1380. }
  1381. void writeAccessor(std::string& json, size_t view, size_t offset, cgltf_type type, cgltf_component_type component_type, bool normalized, size_t count, const float* min = 0, const float* max = 0, size_t numminmax = 0)
  1382. {
  1383. append(json, "{\"bufferView\":");
  1384. append(json, view);
  1385. append(json, ",\"byteOffset\":");
  1386. append(json, offset);
  1387. append(json, ",\"componentType\":");
  1388. append(json, componentType(component_type));
  1389. append(json, ",\"count\":");
  1390. append(json, count);
  1391. append(json, ",\"type\":\"");
  1392. append(json, shapeType(type));
  1393. append(json, "\"");
  1394. if (normalized)
  1395. {
  1396. append(json, ",\"normalized\":true");
  1397. }
  1398. if (min && max)
  1399. {
  1400. assert(numminmax);
  1401. append(json, ",\"min\":[");
  1402. for (size_t k = 0; k < numminmax; ++k)
  1403. {
  1404. comma(json);
  1405. append(json, min[k]);
  1406. }
  1407. append(json, "],\"max\":[");
  1408. for (size_t k = 0; k < numminmax; ++k)
  1409. {
  1410. comma(json);
  1411. append(json, max[k]);
  1412. }
  1413. append(json, "]");
  1414. }
  1415. append(json, "}");
  1416. }
  1417. float getDelta(const Attr& l, const Attr& r, cgltf_animation_path_type type)
  1418. {
  1419. if (type == cgltf_animation_path_type_rotation)
  1420. {
  1421. float error = 1.f - fabsf(l.f[0] * r.f[0] + l.f[1] * r.f[1] + l.f[2] * r.f[2] + l.f[3] * r.f[3]);
  1422. return error;
  1423. }
  1424. else
  1425. {
  1426. float error = 0;
  1427. for (int k = 0; k < 4; ++k)
  1428. error += fabsf(r.f[k] - l.f[k]);
  1429. return error;
  1430. }
  1431. }
  1432. bool isTrackConstant(const cgltf_animation_sampler& sampler, cgltf_animation_path_type type, cgltf_node* target_node)
  1433. {
  1434. const float tolerance = 1e-3f;
  1435. size_t value_stride = (sampler.interpolation == cgltf_interpolation_type_cubic_spline) ? 3 : 1;
  1436. size_t value_offset = (sampler.interpolation == cgltf_interpolation_type_cubic_spline) ? 1 : 0;
  1437. size_t components = (type == cgltf_animation_path_type_weights) ? target_node->mesh->primitives[0].targets_count : 1;
  1438. assert(sampler.input->count * value_stride * components == sampler.output->count);
  1439. for (size_t j = 0; j < components; ++j)
  1440. {
  1441. Attr first = {};
  1442. cgltf_accessor_read_float(sampler.output, j * value_stride + value_offset, first.f, 4);
  1443. for (size_t i = 1; i < sampler.input->count; ++i)
  1444. {
  1445. Attr attr = {};
  1446. cgltf_accessor_read_float(sampler.output, (i * components + j) * value_stride + value_offset, attr.f, 4);
  1447. if (getDelta(first, attr, type) > tolerance)
  1448. return false;
  1449. }
  1450. if (sampler.interpolation == cgltf_interpolation_type_cubic_spline)
  1451. {
  1452. for (size_t i = 0; i < sampler.input->count; ++i)
  1453. {
  1454. for (int k = 0; k < 2; ++k)
  1455. {
  1456. Attr t = {};
  1457. cgltf_accessor_read_float(sampler.output, (i * components + j) * 3 + k * 2, t.f, 4);
  1458. float error = fabsf(t.f[0]) + fabsf(t.f[1]) + fabsf(t.f[2]) + fabsf(t.f[3]);
  1459. if (error > tolerance)
  1460. return false;
  1461. }
  1462. }
  1463. }
  1464. }
  1465. return true;
  1466. }
  1467. Attr interpolateLinear(const Attr& l, const Attr& r, float t, cgltf_animation_path_type type)
  1468. {
  1469. if (type == cgltf_animation_path_type_rotation)
  1470. {
  1471. // Approximating slerp, https://zeux.io/2015/07/23/approximating-slerp/
  1472. // We also handle quaternion double-cover
  1473. float ca = l.f[0] * r.f[0] + l.f[1] * r.f[1] + l.f[2] * r.f[2] + l.f[3] * r.f[3];
  1474. float d = fabsf(ca);
  1475. float A = 1.0904f + d * (-3.2452f + d * (3.55645f - d * 1.43519f));
  1476. float B = 0.848013f + d * (-1.06021f + d * 0.215638f);
  1477. float k = A * (t - 0.5f) * (t - 0.5f) + B;
  1478. float ot = t + t * (t - 0.5f) * (t - 1) * k;
  1479. float t0 = 1 - ot;
  1480. float t1 = ca > 0 ? ot : -ot;
  1481. Attr lerp = {{
  1482. l.f[0] * t0 + r.f[0] * t1,
  1483. l.f[1] * t0 + r.f[1] * t1,
  1484. l.f[2] * t0 + r.f[2] * t1,
  1485. l.f[3] * t0 + r.f[3] * t1,
  1486. }};
  1487. float len = sqrtf(lerp.f[0] * lerp.f[0] + lerp.f[1] * lerp.f[1] + lerp.f[2] * lerp.f[2] + lerp.f[3] * lerp.f[3]);
  1488. if (len > 0.f)
  1489. {
  1490. lerp.f[0] /= len;
  1491. lerp.f[1] /= len;
  1492. lerp.f[2] /= len;
  1493. lerp.f[3] /= len;
  1494. }
  1495. return lerp;
  1496. }
  1497. else
  1498. {
  1499. Attr lerp = {{
  1500. l.f[0] * (1 - t) + r.f[0] * t,
  1501. l.f[1] * (1 - t) + r.f[1] * t,
  1502. l.f[2] * (1 - t) + r.f[2] * t,
  1503. l.f[3] * (1 - t) + r.f[3] * t,
  1504. }};
  1505. return lerp;
  1506. }
  1507. }
  1508. Attr interpolateHermite(const Attr& v0, const Attr& t0, const Attr& v1, const Attr& t1, float t, float dt, cgltf_animation_path_type type)
  1509. {
  1510. float s0 = 1 + t * t * (2 * t - 3);
  1511. float s1 = t + t * t * (t - 2);
  1512. float s2 = 1 - s0;
  1513. float s3 = t * t * (t - 1);
  1514. float ts1 = dt * s1;
  1515. float ts3 = dt * s3;
  1516. Attr lerp = {{
  1517. s0 * v0.f[0] + ts1 * t0.f[0] + s2 * v1.f[0] + ts3 * t1.f[0],
  1518. s0 * v0.f[1] + ts1 * t0.f[1] + s2 * v1.f[1] + ts3 * t1.f[1],
  1519. s0 * v0.f[2] + ts1 * t0.f[2] + s2 * v1.f[2] + ts3 * t1.f[2],
  1520. s0 * v0.f[3] + ts1 * t0.f[3] + s2 * v1.f[3] + ts3 * t1.f[3],
  1521. }};
  1522. if (type == cgltf_animation_path_type_rotation)
  1523. {
  1524. float len = sqrtf(lerp.f[0] * lerp.f[0] + lerp.f[1] * lerp.f[1] + lerp.f[2] * lerp.f[2] + lerp.f[3] * lerp.f[3]);
  1525. if (len > 0.f)
  1526. {
  1527. lerp.f[0] /= len;
  1528. lerp.f[1] /= len;
  1529. lerp.f[2] /= len;
  1530. lerp.f[3] /= len;
  1531. }
  1532. }
  1533. return lerp;
  1534. }
  1535. void resampleKeyframes(std::vector<Attr>& data, const cgltf_animation_sampler& sampler, cgltf_animation_path_type type, cgltf_node* target_node, int frames, float mint, int freq)
  1536. {
  1537. size_t components = (type == cgltf_animation_path_type_weights) ? target_node->mesh->primitives[0].targets_count : 1;
  1538. size_t cursor = 0;
  1539. for (int i = 0; i < frames; ++i)
  1540. {
  1541. float time = mint + float(i) / freq;
  1542. while (cursor + 1 < sampler.input->count)
  1543. {
  1544. float next_time = 0;
  1545. cgltf_accessor_read_float(sampler.input, cursor + 1, &next_time, 1);
  1546. if (next_time > time)
  1547. break;
  1548. cursor++;
  1549. }
  1550. if (cursor + 1 < sampler.input->count)
  1551. {
  1552. float cursor_time = 0;
  1553. float next_time = 0;
  1554. cgltf_accessor_read_float(sampler.input, cursor + 0, &cursor_time, 1);
  1555. cgltf_accessor_read_float(sampler.input, cursor + 1, &next_time, 1);
  1556. float range = next_time - cursor_time;
  1557. float inv_range = (range == 0.f) ? 0.f : 1.f / (next_time - cursor_time);
  1558. float t = std::max(0.f, std::min(1.f, (time - cursor_time) * inv_range));
  1559. for (size_t j = 0; j < components; ++j)
  1560. {
  1561. switch (sampler.interpolation)
  1562. {
  1563. case cgltf_interpolation_type_linear:
  1564. {
  1565. Attr v0 = {};
  1566. Attr v1 = {};
  1567. cgltf_accessor_read_float(sampler.output, (cursor + 0) * components + j, v0.f, 4);
  1568. cgltf_accessor_read_float(sampler.output, (cursor + 1) * components + j, v1.f, 4);
  1569. data.push_back(interpolateLinear(v0, v1, t, type));
  1570. }
  1571. break;
  1572. case cgltf_interpolation_type_step:
  1573. {
  1574. Attr v = {};
  1575. cgltf_accessor_read_float(sampler.output, cursor * components + j, v.f, 4);
  1576. data.push_back(v);
  1577. }
  1578. break;
  1579. case cgltf_interpolation_type_cubic_spline:
  1580. {
  1581. Attr v0 = {};
  1582. Attr b0 = {};
  1583. Attr a1 = {};
  1584. Attr v1 = {};
  1585. cgltf_accessor_read_float(sampler.output, (cursor * 3 + 1) * components + j, v0.f, 4);
  1586. cgltf_accessor_read_float(sampler.output, (cursor * 3 + 2) * components + j, b0.f, 4);
  1587. cgltf_accessor_read_float(sampler.output, (cursor * 3 + 3) * components + j, a1.f, 4);
  1588. cgltf_accessor_read_float(sampler.output, (cursor * 3 + 4) * components + j, v1.f, 4);
  1589. data.push_back(interpolateHermite(v0, b0, v1, a1, t, range, type));
  1590. }
  1591. break;
  1592. default:
  1593. assert(!"Unknown interpolation type");
  1594. }
  1595. }
  1596. }
  1597. else
  1598. {
  1599. size_t offset = (sampler.interpolation == cgltf_interpolation_type_cubic_spline) ? cursor * 3 + 1 : cursor;
  1600. for (size_t j = 0; j < components; ++j)
  1601. {
  1602. Attr v = {};
  1603. cgltf_accessor_read_float(sampler.output, offset * components + j, v.f, 4);
  1604. data.push_back(v);
  1605. }
  1606. }
  1607. }
  1608. }
  1609. void markAnimated(cgltf_data* data, std::vector<NodeInfo>& nodes)
  1610. {
  1611. for (size_t i = 0; i < data->animations_count; ++i)
  1612. {
  1613. const cgltf_animation& animation = data->animations[i];
  1614. for (size_t j = 0; j < animation.channels_count; ++j)
  1615. {
  1616. const cgltf_animation_channel& channel = animation.channels[j];
  1617. const cgltf_animation_sampler& sampler = *channel.sampler;
  1618. if (!channel.target_node)
  1619. continue;
  1620. NodeInfo& ni = nodes[channel.target_node - data->nodes];
  1621. // mark nodes that have animation tracks that change their base transform as animated
  1622. if (!isTrackConstant(sampler, channel.target_path, channel.target_node))
  1623. {
  1624. ni.animated_paths |= (1 << channel.target_path);
  1625. }
  1626. else
  1627. {
  1628. Attr base = {};
  1629. switch (channel.target_path)
  1630. {
  1631. case cgltf_animation_path_type_translation:
  1632. memcpy(base.f, channel.target_node->translation, 3 * sizeof(float));
  1633. break;
  1634. case cgltf_animation_path_type_rotation:
  1635. memcpy(base.f, channel.target_node->rotation, 4 * sizeof(float));
  1636. break;
  1637. case cgltf_animation_path_type_scale:
  1638. memcpy(base.f, channel.target_node->scale, 3 * sizeof(float));
  1639. break;
  1640. default:;
  1641. }
  1642. Attr first = {};
  1643. cgltf_accessor_read_float(sampler.output, 0, first.f, 4);
  1644. const float tolerance = 1e-3f;
  1645. if (getDelta(base, first, channel.target_path) > tolerance)
  1646. {
  1647. ni.animated_paths |= (1 << channel.target_path);
  1648. }
  1649. }
  1650. }
  1651. }
  1652. for (size_t i = 0; i < data->nodes_count; ++i)
  1653. {
  1654. NodeInfo& ni = nodes[i];
  1655. for (cgltf_node* node = &data->nodes[i]; node; node = node->parent)
  1656. ni.animated |= nodes[node - data->nodes].animated_paths != 0;
  1657. }
  1658. }
  1659. void markNeededNodes(cgltf_data* data, std::vector<NodeInfo>& nodes, const std::vector<Mesh>& meshes, const Settings& settings)
  1660. {
  1661. // mark all joints as kept
  1662. for (size_t i = 0; i < data->skins_count; ++i)
  1663. {
  1664. const cgltf_skin& skin = data->skins[i];
  1665. // for now we keep all joints directly referenced by the skin and the entire ancestry tree; we keep names for joints as well
  1666. for (size_t j = 0; j < skin.joints_count; ++j)
  1667. {
  1668. NodeInfo& ni = nodes[skin.joints[j] - data->nodes];
  1669. ni.keep = true;
  1670. }
  1671. }
  1672. // mark all animated nodes as kept
  1673. for (size_t i = 0; i < data->animations_count; ++i)
  1674. {
  1675. const cgltf_animation& animation = data->animations[i];
  1676. for (size_t j = 0; j < animation.channels_count; ++j)
  1677. {
  1678. const cgltf_animation_channel& channel = animation.channels[j];
  1679. if (channel.target_node)
  1680. {
  1681. NodeInfo& ni = nodes[channel.target_node - data->nodes];
  1682. ni.keep = true;
  1683. }
  1684. }
  1685. }
  1686. // mark all mesh nodes as kept
  1687. for (size_t i = 0; i < meshes.size(); ++i)
  1688. {
  1689. const Mesh& mesh = meshes[i];
  1690. if (mesh.indices.empty())
  1691. continue;
  1692. if (mesh.node)
  1693. {
  1694. NodeInfo& ni = nodes[mesh.node - data->nodes];
  1695. ni.keep = true;
  1696. }
  1697. }
  1698. // mark all light/camera nodes as kept
  1699. for (size_t i = 0; i < data->nodes_count; ++i)
  1700. {
  1701. const cgltf_node& node = data->nodes[i];
  1702. if (node.light || node.camera)
  1703. {
  1704. nodes[i].keep = true;
  1705. }
  1706. }
  1707. // mark all named nodes as needed (if -kn is specified)
  1708. if (settings.keep_named)
  1709. {
  1710. for (size_t i = 0; i < data->nodes_count; ++i)
  1711. {
  1712. const cgltf_node& node = data->nodes[i];
  1713. if (node.name && *node.name)
  1714. {
  1715. nodes[i].keep = true;
  1716. }
  1717. }
  1718. }
  1719. }
  1720. void markNeededMaterials(cgltf_data* data, std::vector<MaterialInfo>& materials, const std::vector<Mesh>& meshes)
  1721. {
  1722. // mark all used materials as kept
  1723. for (size_t i = 0; i < meshes.size(); ++i)
  1724. {
  1725. const Mesh& mesh = meshes[i];
  1726. if (mesh.indices.empty())
  1727. continue;
  1728. if (mesh.material)
  1729. {
  1730. MaterialInfo& mi = materials[mesh.material - data->materials];
  1731. mi.keep = true;
  1732. }
  1733. }
  1734. }
  1735. void remapNodes(cgltf_data* data, std::vector<NodeInfo>& nodes, size_t& node_offset)
  1736. {
  1737. // to keep a node, we currently need to keep the entire ancestry chain
  1738. for (size_t i = 0; i < data->nodes_count; ++i)
  1739. {
  1740. if (!nodes[i].keep)
  1741. continue;
  1742. for (cgltf_node* node = &data->nodes[i]; node; node = node->parent)
  1743. nodes[node - data->nodes].keep = true;
  1744. }
  1745. // generate sequential indices for all nodes; they aren't sorted topologically
  1746. for (size_t i = 0; i < data->nodes_count; ++i)
  1747. {
  1748. NodeInfo& ni = nodes[i];
  1749. if (ni.keep)
  1750. {
  1751. ni.remap = int(node_offset);
  1752. node_offset++;
  1753. }
  1754. }
  1755. }
  1756. bool parseDataUri(const char* uri, std::string& mime_type, std::string& result)
  1757. {
  1758. if (strncmp(uri, "data:", 5) == 0)
  1759. {
  1760. const char* comma = strchr(uri, ',');
  1761. if (comma && comma - uri >= 7 && strncmp(comma - 7, ";base64", 7) == 0)
  1762. {
  1763. const char* base64 = comma + 1;
  1764. size_t base64_size = strlen(base64);
  1765. size_t size = base64_size - base64_size / 4;
  1766. if (base64_size >= 2)
  1767. {
  1768. size -= base64[base64_size - 2] == '=';
  1769. size -= base64[base64_size - 1] == '=';
  1770. }
  1771. void* data = 0;
  1772. cgltf_options options = {};
  1773. cgltf_result res = cgltf_load_buffer_base64(&options, size, base64, &data);
  1774. if (res != cgltf_result_success)
  1775. return false;
  1776. mime_type = std::string(uri + 5, comma - 7);
  1777. result = std::string(static_cast<const char*>(data), size);
  1778. free(data);
  1779. return true;
  1780. }
  1781. }
  1782. return false;
  1783. }
  1784. void writeEmbeddedImage(std::string& json, std::vector<BufferView>& views, const char* data, size_t size, const char* mime_type)
  1785. {
  1786. size_t view = getBufferView(views, BufferView::Kind_Image, -1, 1, false);
  1787. assert(views[view].data.empty());
  1788. views[view].data.assign(data, size);
  1789. append(json, "\"bufferView\":");
  1790. append(json, view);
  1791. append(json, ",\"mimeType\":\"");
  1792. append(json, mime_type);
  1793. append(json, "\"");
  1794. }
  1795. void writeMeshAttributes(std::string& json, std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const Mesh& mesh, int target, const QuantizationParams& qp, const Settings& settings)
  1796. {
  1797. std::string scratch;
  1798. for (size_t j = 0; j < mesh.streams.size(); ++j)
  1799. {
  1800. const Stream& stream = mesh.streams[j];
  1801. if (stream.target != target)
  1802. continue;
  1803. if (stream.type == cgltf_attribute_type_texcoord && (!mesh.material || !usesTextureSet(*mesh.material, stream.index)))
  1804. continue;
  1805. if ((stream.type == cgltf_attribute_type_joints || stream.type == cgltf_attribute_type_weights) && !mesh.skin)
  1806. continue;
  1807. scratch.clear();
  1808. StreamFormat format = writeVertexStream(scratch, stream, qp, settings, mesh.targets > 0);
  1809. size_t view = getBufferView(views, BufferView::Kind_Vertex, stream.type, format.stride, settings.compress);
  1810. size_t offset = views[view].data.size();
  1811. views[view].data += scratch;
  1812. comma(json_accessors);
  1813. if (stream.type == cgltf_attribute_type_position)
  1814. {
  1815. int min[3] = {};
  1816. int max[3] = {};
  1817. getPositionBounds(min, max, stream, qp);
  1818. float minf[3] = {float(min[0]), float(min[1]), float(min[2])};
  1819. float maxf[3] = {float(max[0]), float(max[1]), float(max[2])};
  1820. writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, stream.data.size(), minf, maxf, 3);
  1821. }
  1822. else
  1823. {
  1824. writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, stream.data.size());
  1825. }
  1826. size_t vertex_accr = accr_offset++;
  1827. comma(json);
  1828. append(json, "\"");
  1829. append(json, attributeType(stream.type));
  1830. if (stream.type != cgltf_attribute_type_position && stream.type != cgltf_attribute_type_normal && stream.type != cgltf_attribute_type_tangent)
  1831. {
  1832. append(json, "_");
  1833. append(json, size_t(stream.index));
  1834. }
  1835. append(json, "\":");
  1836. append(json, vertex_accr);
  1837. }
  1838. }
  1839. size_t writeMeshIndices(std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const Mesh& mesh, const Settings& settings)
  1840. {
  1841. std::string scratch;
  1842. StreamFormat format = writeIndexStream(scratch, mesh.indices);
  1843. // note: we prefer to merge all index streams together; however, index codec currently doesn't handle concatenated index streams well and loses compression ratio
  1844. int variant = settings.compress ? -1 : 0;
  1845. size_t view = getBufferView(views, BufferView::Kind_Index, variant, format.stride, settings.compress);
  1846. size_t offset = views[view].data.size();
  1847. views[view].data += scratch;
  1848. comma(json_accessors);
  1849. writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, mesh.indices.size());
  1850. size_t index_accr = accr_offset++;
  1851. return index_accr;
  1852. }
  1853. size_t writeAnimationTime(std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, float mint, int frames, const Settings& settings)
  1854. {
  1855. std::vector<float> time(frames);
  1856. for (int j = 0; j < frames; ++j)
  1857. time[j] = mint + float(j) / settings.anim_freq;
  1858. std::string scratch;
  1859. StreamFormat format = writeTimeStream(scratch, time);
  1860. size_t view = getBufferView(views, BufferView::Kind_Time, 0, format.stride, settings.compress);
  1861. size_t offset = views[view].data.size();
  1862. views[view].data += scratch;
  1863. comma(json_accessors);
  1864. writeAccessor(json_accessors, view, offset, cgltf_type_scalar, format.component_type, format.normalized, frames, &time.front(), &time.back(), 1);
  1865. size_t time_accr = accr_offset++;
  1866. return time_accr;
  1867. }
  1868. size_t writeJointBindMatrices(std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const cgltf_skin& skin, const QuantizationParams& qp, const Settings& settings)
  1869. {
  1870. std::string scratch;
  1871. for (size_t j = 0; j < skin.joints_count; ++j)
  1872. {
  1873. float transform[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
  1874. if (skin.inverse_bind_matrices)
  1875. {
  1876. cgltf_accessor_read_float(skin.inverse_bind_matrices, j, transform, 16);
  1877. }
  1878. float node_scale = qp.pos_scale / float((1 << qp.pos_bits) - 1);
  1879. // pos_offset has to be applied first, thus it results in an offset rotated by the bind matrix
  1880. transform[12] += qp.pos_offset[0] * transform[0] + qp.pos_offset[1] * transform[4] + qp.pos_offset[2] * transform[8];
  1881. transform[13] += qp.pos_offset[0] * transform[1] + qp.pos_offset[1] * transform[5] + qp.pos_offset[2] * transform[9];
  1882. transform[14] += qp.pos_offset[0] * transform[2] + qp.pos_offset[1] * transform[6] + qp.pos_offset[2] * transform[10];
  1883. // node_scale will be applied before the rotation/scale from transform
  1884. for (int k = 0; k < 12; ++k)
  1885. transform[k] *= node_scale;
  1886. scratch.append(reinterpret_cast<const char*>(transform), sizeof(transform));
  1887. }
  1888. size_t view = getBufferView(views, BufferView::Kind_Skin, 0, 64, settings.compress);
  1889. size_t offset = views[view].data.size();
  1890. views[view].data += scratch;
  1891. comma(json_accessors);
  1892. writeAccessor(json_accessors, view, offset, cgltf_type_mat4, cgltf_component_type_r_32f, false, skin.joints_count);
  1893. size_t matrix_accr = accr_offset++;
  1894. return matrix_accr;
  1895. }
  1896. void writeMeshNode(std::string& json, size_t mesh_offset, const Mesh& mesh, cgltf_data* data, const QuantizationParams& qp)
  1897. {
  1898. float node_scale = qp.pos_scale / float((1 << qp.pos_bits) - 1);
  1899. comma(json);
  1900. append(json, "{\"mesh\":");
  1901. append(json, mesh_offset);
  1902. if (mesh.skin)
  1903. {
  1904. comma(json);
  1905. append(json, "\"skin\":");
  1906. append(json, size_t(mesh.skin - data->skins));
  1907. }
  1908. append(json, ",\"translation\":[");
  1909. append(json, qp.pos_offset[0]);
  1910. append(json, ",");
  1911. append(json, qp.pos_offset[1]);
  1912. append(json, ",");
  1913. append(json, qp.pos_offset[2]);
  1914. append(json, "],\"scale\":[");
  1915. append(json, node_scale);
  1916. append(json, ",");
  1917. append(json, node_scale);
  1918. append(json, ",");
  1919. append(json, node_scale);
  1920. append(json, "]");
  1921. if (mesh.node && mesh.node->weights_count)
  1922. {
  1923. append(json, ",\"weights\":[");
  1924. for (size_t j = 0; j < mesh.node->weights_count; ++j)
  1925. {
  1926. comma(json);
  1927. append(json, mesh.node->weights[j]);
  1928. }
  1929. append(json, "]");
  1930. }
  1931. append(json, "}");
  1932. }
  1933. void writeNode(std::string& json, const cgltf_node& node, const std::vector<NodeInfo>& nodes, cgltf_data* data)
  1934. {
  1935. const NodeInfo& ni = nodes[&node - data->nodes];
  1936. comma(json);
  1937. append(json, "{");
  1938. if (node.name && *node.name)
  1939. {
  1940. comma(json);
  1941. append(json, "\"name\":\"");
  1942. append(json, node.name);
  1943. append(json, "\"");
  1944. }
  1945. if (node.has_translation)
  1946. {
  1947. comma(json);
  1948. append(json, "\"translation\":[");
  1949. append(json, node.translation[0]);
  1950. append(json, ",");
  1951. append(json, node.translation[1]);
  1952. append(json, ",");
  1953. append(json, node.translation[2]);
  1954. append(json, "]");
  1955. }
  1956. if (node.has_rotation)
  1957. {
  1958. comma(json);
  1959. append(json, "\"rotation\":[");
  1960. append(json, node.rotation[0]);
  1961. append(json, ",");
  1962. append(json, node.rotation[1]);
  1963. append(json, ",");
  1964. append(json, node.rotation[2]);
  1965. append(json, ",");
  1966. append(json, node.rotation[3]);
  1967. append(json, "]");
  1968. }
  1969. if (node.has_scale)
  1970. {
  1971. comma(json);
  1972. append(json, "\"scale\":[");
  1973. append(json, node.scale[0]);
  1974. append(json, ",");
  1975. append(json, node.scale[1]);
  1976. append(json, ",");
  1977. append(json, node.scale[2]);
  1978. append(json, "]");
  1979. }
  1980. if (node.has_matrix)
  1981. {
  1982. comma(json);
  1983. append(json, "\"matrix\":[");
  1984. for (int k = 0; k < 16; ++k)
  1985. {
  1986. comma(json);
  1987. append(json, node.matrix[k]);
  1988. }
  1989. append(json, "]");
  1990. }
  1991. if (node.children_count || !ni.meshes.empty())
  1992. {
  1993. comma(json);
  1994. append(json, "\"children\":[");
  1995. for (size_t j = 0; j < node.children_count; ++j)
  1996. {
  1997. const NodeInfo& ci = nodes[node.children[j] - data->nodes];
  1998. if (ci.keep)
  1999. {
  2000. comma(json);
  2001. append(json, size_t(ci.remap));
  2002. }
  2003. }
  2004. for (size_t j = 0; j < ni.meshes.size(); ++j)
  2005. {
  2006. comma(json);
  2007. append(json, ni.meshes[j]);
  2008. }
  2009. append(json, "]");
  2010. }
  2011. if (node.camera)
  2012. {
  2013. comma(json);
  2014. append(json, "\"camera\":");
  2015. append(json, size_t(node.camera - data->cameras));
  2016. }
  2017. if (node.light)
  2018. {
  2019. comma(json);
  2020. append(json, "\"extensions\":{\"KHR_lights_punctual\":{\"light\":");
  2021. append(json, size_t(node.light - data->lights));
  2022. append(json, "}}");
  2023. }
  2024. append(json, "}");
  2025. }
  2026. void writeAnimation(std::string& json, std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const cgltf_animation& animation, cgltf_data* data, const std::vector<NodeInfo>& nodes, const Settings& settings)
  2027. {
  2028. std::vector<const cgltf_animation_channel*> tracks;
  2029. for (size_t j = 0; j < animation.channels_count; ++j)
  2030. {
  2031. const cgltf_animation_channel& channel = animation.channels[j];
  2032. if (!channel.target_node)
  2033. {
  2034. fprintf(stderr, "Warning: ignoring channel %d of animation %d because it has no target node\n", int(j), int(&animation - data->animations));
  2035. continue;
  2036. }
  2037. const NodeInfo& ni = nodes[channel.target_node - data->nodes];
  2038. if (!ni.keep)
  2039. continue;
  2040. if (!settings.anim_const && (ni.animated_paths & (1 << channel.target_path)) == 0)
  2041. continue;
  2042. tracks.push_back(&channel);
  2043. }
  2044. if (tracks.empty())
  2045. {
  2046. fprintf(stderr, "Warning: ignoring animation %d because it has no valid tracks\n", int(&animation - data->animations));
  2047. return;
  2048. }
  2049. float mint = 0, maxt = 0;
  2050. bool needs_time = false;
  2051. bool needs_pose = false;
  2052. for (size_t j = 0; j < tracks.size(); ++j)
  2053. {
  2054. const cgltf_animation_channel& channel = *tracks[j];
  2055. const cgltf_animation_sampler& sampler = *channel.sampler;
  2056. mint = std::min(mint, sampler.input->min[0]);
  2057. maxt = std::max(maxt, sampler.input->max[0]);
  2058. bool tc = isTrackConstant(sampler, channel.target_path, channel.target_node);
  2059. needs_time = needs_time || !tc;
  2060. needs_pose = needs_pose || tc;
  2061. }
  2062. // round the number of frames to nearest but favor the "up" direction
  2063. // this means that at 10 Hz resampling, we will try to preserve the last frame <10ms
  2064. // but if the last frame is <2ms we favor just removing this data
  2065. int frames = 1 + int((maxt - mint) * settings.anim_freq + 0.8f);
  2066. size_t time_accr = needs_time ? writeAnimationTime(views, json_accessors, accr_offset, mint, frames, settings) : 0;
  2067. size_t pose_accr = needs_pose ? writeAnimationTime(views, json_accessors, accr_offset, mint, 1, settings) : 0;
  2068. std::string json_samplers;
  2069. std::string json_channels;
  2070. size_t track_offset = 0;
  2071. for (size_t j = 0; j < tracks.size(); ++j)
  2072. {
  2073. const cgltf_animation_channel& channel = *tracks[j];
  2074. const cgltf_animation_sampler& sampler = *channel.sampler;
  2075. bool tc = isTrackConstant(sampler, channel.target_path, channel.target_node);
  2076. std::vector<Attr> track;
  2077. resampleKeyframes(track, sampler, channel.target_path, channel.target_node, tc ? 1 : frames, mint, settings.anim_freq);
  2078. std::string scratch;
  2079. StreamFormat format = writeKeyframeStream(scratch, channel.target_path, track);
  2080. size_t view = getBufferView(views, BufferView::Kind_Keyframe, channel.target_path, format.stride, settings.compress && channel.target_path != cgltf_animation_path_type_weights);
  2081. size_t offset = views[view].data.size();
  2082. views[view].data += scratch;
  2083. comma(json_accessors);
  2084. writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, track.size());
  2085. size_t data_accr = accr_offset++;
  2086. comma(json_samplers);
  2087. append(json_samplers, "{\"input\":");
  2088. append(json_samplers, tc ? pose_accr : time_accr);
  2089. append(json_samplers, ",\"output\":");
  2090. append(json_samplers, data_accr);
  2091. append(json_samplers, "}");
  2092. const NodeInfo& tni = nodes[channel.target_node - data->nodes];
  2093. size_t target_node = size_t(tni.remap);
  2094. if (channel.target_path == cgltf_animation_path_type_weights)
  2095. {
  2096. assert(tni.meshes.size() == 1);
  2097. target_node = tni.meshes[0];
  2098. }
  2099. comma(json_channels);
  2100. append(json_channels, "{\"sampler\":");
  2101. append(json_channels, track_offset);
  2102. append(json_channels, ",\"target\":{\"node\":");
  2103. append(json_channels, target_node);
  2104. append(json_channels, ",\"path\":\"");
  2105. append(json_channels, animationPath(channel.target_path));
  2106. append(json_channels, "\"}}");
  2107. track_offset++;
  2108. }
  2109. comma(json);
  2110. append(json, "{");
  2111. if (animation.name && *animation.name)
  2112. {
  2113. append(json, "\"name\":\"");
  2114. append(json, animation.name);
  2115. append(json, "\",");
  2116. }
  2117. append(json, "\"samplers\":[");
  2118. append(json, json_samplers);
  2119. append(json, "],\"channels\":[");
  2120. append(json, json_channels);
  2121. append(json, "]}");
  2122. }
  2123. void writeCamera(std::string& json, const cgltf_camera& camera)
  2124. {
  2125. comma(json);
  2126. append(json, "{");
  2127. switch (camera.type)
  2128. {
  2129. case cgltf_camera_type_perspective:
  2130. append(json, "\"type\":\"perspective\",\"perspective\":{");
  2131. append(json, "\"yfov\":");
  2132. append(json, camera.perspective.yfov);
  2133. append(json, ",\"znear\":");
  2134. append(json, camera.perspective.znear);
  2135. if (camera.perspective.aspect_ratio != 0.f)
  2136. {
  2137. append(json, ",\"aspectRatio\":");
  2138. append(json, camera.perspective.aspect_ratio);
  2139. }
  2140. if (camera.perspective.zfar != 0.f)
  2141. {
  2142. append(json, ",\"zfar\":");
  2143. append(json, camera.perspective.zfar);
  2144. }
  2145. append(json, "}");
  2146. break;
  2147. case cgltf_camera_type_orthographic:
  2148. append(json, "\"type\":\"orthographic\",\"orthographic\":{");
  2149. append(json, "\"xmag\":");
  2150. append(json, camera.orthographic.xmag);
  2151. append(json, ",\"ymag\":");
  2152. append(json, camera.orthographic.ymag);
  2153. append(json, ",\"znear\":");
  2154. append(json, camera.orthographic.znear);
  2155. append(json, ",\"zfar\":");
  2156. append(json, camera.orthographic.zfar);
  2157. append(json, "}");
  2158. break;
  2159. default:
  2160. fprintf(stderr, "Warning: skipping camera of unknown type\n");
  2161. }
  2162. append(json, "}");
  2163. }
  2164. void writeLight(std::string& json, const cgltf_light& light)
  2165. {
  2166. static const float white[3] = {1, 1, 1};
  2167. comma(json);
  2168. append(json, "{\"type\":\"");
  2169. append(json, lightType(light.type));
  2170. append(json, "\"");
  2171. if (memcmp(light.color, white, sizeof(white)) != 0)
  2172. {
  2173. comma(json);
  2174. append(json, "\"color\":[");
  2175. append(json, light.color[0]);
  2176. append(json, ",");
  2177. append(json, light.color[1]);
  2178. append(json, ",");
  2179. append(json, light.color[2]);
  2180. append(json, "]");
  2181. }
  2182. if (light.intensity != 1.f)
  2183. {
  2184. comma(json);
  2185. append(json, "\"intensity\":");
  2186. append(json, light.intensity);
  2187. }
  2188. if (light.range != 0.f)
  2189. {
  2190. comma(json);
  2191. append(json, "\"range\":");
  2192. append(json, light.range);
  2193. }
  2194. if (light.type == cgltf_light_type_spot)
  2195. {
  2196. comma(json);
  2197. append(json, "\"spot\":{");
  2198. append(json, "\"innerConeAngle\":");
  2199. append(json, light.spot_inner_cone_angle);
  2200. append(json, ",\"outerConeAngle\":");
  2201. append(json, light.spot_outer_cone_angle == 0.f ? 0.78539816339f : light.spot_outer_cone_angle);
  2202. append(json, "}");
  2203. }
  2204. append(json, "}");
  2205. }
  2206. void printStats(const std::vector<BufferView>& views, BufferView::Kind kind, const char* name)
  2207. {
  2208. for (size_t i = 0; i < views.size(); ++i)
  2209. {
  2210. const BufferView& view = views[i];
  2211. if (view.kind != kind)
  2212. continue;
  2213. const char* variant = "unknown";
  2214. switch (kind)
  2215. {
  2216. case BufferView::Kind_Vertex:
  2217. variant = attributeType(cgltf_attribute_type(view.variant));
  2218. break;
  2219. case BufferView::Kind_Index:
  2220. variant = "index";
  2221. break;
  2222. case BufferView::Kind_Keyframe:
  2223. variant = animationPath(cgltf_animation_path_type(view.variant));
  2224. break;
  2225. default:;
  2226. }
  2227. size_t count = view.data.size() / view.stride;
  2228. printf("stats: %s %s: compressed %d bytes (%.1f bits), raw %d bytes (%d bits)\n",
  2229. name,
  2230. variant,
  2231. int(view.bytes),
  2232. double(view.bytes) / double(count) * 8,
  2233. int(view.data.size()),
  2234. int(view.stride * 8));
  2235. }
  2236. }
  2237. void process(cgltf_data* data, std::vector<Mesh>& meshes, const Settings& settings, std::string& json, std::string& bin)
  2238. {
  2239. if (settings.verbose)
  2240. {
  2241. printf("input: %d nodes, %d meshes (%d primitives), %d materials, %d skins, %d animations\n",
  2242. int(data->nodes_count), int(data->meshes_count), int(meshes.size()), int(data->materials_count), int(data->skins_count), int(data->animations_count));
  2243. }
  2244. std::vector<NodeInfo> nodes(data->nodes_count);
  2245. markAnimated(data, nodes);
  2246. for (size_t i = 0; i < meshes.size(); ++i)
  2247. {
  2248. Mesh& mesh = meshes[i];
  2249. // note: when -kn is specified, we keep mesh-node attachment so that named nodes can be transformed
  2250. if (mesh.node && !settings.keep_named)
  2251. {
  2252. NodeInfo& ni = nodes[mesh.node - data->nodes];
  2253. // we transform all non-skinned non-animated meshes to world space
  2254. // this makes sure that quantization doesn't introduce gaps if the original scene was watertight
  2255. if (!ni.animated && !mesh.skin && mesh.targets == 0)
  2256. {
  2257. transformMesh(mesh, mesh.node);
  2258. mesh.node = 0;
  2259. }
  2260. // skinned and animated meshes will be anchored to the same node that they used to be in
  2261. // for animated meshes, this is important since they need to be transformed by the same animation
  2262. // for skinned meshes, in theory this isn't important since the transform of the skinned node doesn't matter; in practice this affects generated bounding box in three.js
  2263. }
  2264. }
  2265. mergeMeshMaterials(data, meshes);
  2266. mergeMeshes(meshes, settings);
  2267. markNeededNodes(data, nodes, meshes, settings);
  2268. std::vector<MaterialInfo> materials(data->materials_count);
  2269. markNeededMaterials(data, materials, meshes);
  2270. for (size_t i = 0; i < meshes.size(); ++i)
  2271. {
  2272. Mesh& mesh = meshes[i];
  2273. if (mesh.indices.empty())
  2274. continue;
  2275. reindexMesh(mesh);
  2276. optimizeMesh(mesh);
  2277. }
  2278. if (settings.verbose)
  2279. {
  2280. size_t triangles = 0;
  2281. size_t vertices = 0;
  2282. for (size_t i = 0; i < meshes.size(); ++i)
  2283. {
  2284. const Mesh& mesh = meshes[i];
  2285. triangles += mesh.indices.size() / 3;
  2286. vertices += mesh.streams.empty() ? 0 : mesh.streams[0].data.size();
  2287. }
  2288. printf("meshes: %d triangles, %d vertices\n", int(triangles), int(vertices));
  2289. }
  2290. QuantizationParams qp = prepareQuantization(meshes, settings);
  2291. std::string json_images;
  2292. std::string json_textures;
  2293. std::string json_materials;
  2294. std::string json_accessors;
  2295. std::string json_meshes;
  2296. std::string json_nodes;
  2297. std::string json_skins;
  2298. std::string json_roots;
  2299. std::string json_animations;
  2300. std::string json_cameras;
  2301. std::string json_lights;
  2302. std::vector<BufferView> views;
  2303. bool ext_pbr_specular_glossiness = false;
  2304. bool ext_unlit = false;
  2305. size_t accr_offset = 0;
  2306. size_t node_offset = 0;
  2307. size_t mesh_offset = 0;
  2308. size_t material_offset = 0;
  2309. for (size_t i = 0; i < data->images_count; ++i)
  2310. {
  2311. const cgltf_image& image = data->images[i];
  2312. comma(json_images);
  2313. append(json_images, "{");
  2314. if (image.uri)
  2315. {
  2316. std::string mime_type;
  2317. std::string img;
  2318. if (parseDataUri(image.uri, mime_type, img))
  2319. {
  2320. writeEmbeddedImage(json_images, views, img.c_str(), img.size(), mime_type.c_str());
  2321. }
  2322. else
  2323. {
  2324. append(json_images, "\"uri\":\"");
  2325. append(json_images, image.uri);
  2326. append(json_images, "\"");
  2327. }
  2328. }
  2329. else if (image.buffer_view && image.buffer_view->buffer->data && image.mime_type)
  2330. {
  2331. const char* img = static_cast<const char*>(image.buffer_view->buffer->data) + image.buffer_view->offset;
  2332. size_t size = image.buffer_view->size;
  2333. writeEmbeddedImage(json_images, views, img, size, image.mime_type);
  2334. }
  2335. else
  2336. {
  2337. fprintf(stderr, "Warning: ignoring image %d since it has no URI and no valid buffer data\n", int(i));
  2338. }
  2339. append(json_images, "}");
  2340. }
  2341. for (size_t i = 0; i < data->textures_count; ++i)
  2342. {
  2343. const cgltf_texture& texture = data->textures[i];
  2344. comma(json_textures);
  2345. append(json_textures, "{");
  2346. if (texture.image)
  2347. {
  2348. append(json_textures, "\"source\":");
  2349. append(json_textures, size_t(texture.image - data->images));
  2350. }
  2351. append(json_textures, "}");
  2352. }
  2353. for (size_t i = 0; i < data->materials_count; ++i)
  2354. {
  2355. MaterialInfo& mi = materials[i];
  2356. if (!mi.keep)
  2357. continue;
  2358. const cgltf_material& material = data->materials[i];
  2359. comma(json_materials);
  2360. append(json_materials, "{");
  2361. writeMaterialInfo(json_materials, data, material, qp);
  2362. append(json_materials, "}");
  2363. mi.remap = int(material_offset);
  2364. material_offset++;
  2365. ext_pbr_specular_glossiness = ext_pbr_specular_glossiness || material.has_pbr_specular_glossiness;
  2366. ext_unlit = ext_unlit || material.unlit;
  2367. }
  2368. for (size_t i = 0; i < meshes.size(); ++i)
  2369. {
  2370. const Mesh& mesh = meshes[i];
  2371. if (mesh.indices.empty())
  2372. continue;
  2373. comma(json_meshes);
  2374. append(json_meshes, "{\"primitives\":[");
  2375. size_t pi = i;
  2376. for (; pi < meshes.size(); ++pi)
  2377. {
  2378. const Mesh& prim = meshes[pi];
  2379. if (prim.indices.empty())
  2380. continue;
  2381. if (prim.node != mesh.node || prim.skin != mesh.skin || prim.targets != mesh.targets)
  2382. break;
  2383. if (mesh.weights.size() && (prim.weights.size() != mesh.weights.size() || memcmp(&mesh.weights[0], &prim.weights[0], mesh.weights.size() * sizeof(float)) != 0))
  2384. break;
  2385. comma(json_meshes);
  2386. append(json_meshes, "{\"attributes\":{");
  2387. writeMeshAttributes(json_meshes, views, json_accessors, accr_offset, prim, 0, qp, settings);
  2388. append(json_meshes, "}");
  2389. if (mesh.targets)
  2390. {
  2391. append(json_meshes, ",\"targets\":[");
  2392. for (size_t j = 0; j < mesh.targets; ++j)
  2393. {
  2394. comma(json_meshes);
  2395. append(json_meshes, "{");
  2396. writeMeshAttributes(json_meshes, views, json_accessors, accr_offset, prim, int(1 + j), qp, settings);
  2397. append(json_meshes, "}");
  2398. }
  2399. append(json_meshes, "]");
  2400. }
  2401. size_t index_accr = writeMeshIndices(views, json_accessors, accr_offset, prim, settings);
  2402. append(json_meshes, ",\"indices\":");
  2403. append(json_meshes, index_accr);
  2404. if (prim.material)
  2405. {
  2406. MaterialInfo& mi = materials[prim.material - data->materials];
  2407. assert(mi.keep);
  2408. append(json_meshes, ",\"material\":");
  2409. append(json_meshes, size_t(mi.remap));
  2410. }
  2411. append(json_meshes, "}");
  2412. }
  2413. append(json_meshes, "]");
  2414. if (mesh.weights.size())
  2415. {
  2416. append(json_meshes, ",\"weights\":[");
  2417. for (size_t j = 0; j < mesh.weights.size(); ++j)
  2418. {
  2419. comma(json_meshes);
  2420. append(json_meshes, mesh.weights[j]);
  2421. }
  2422. append(json_meshes, "]");
  2423. }
  2424. append(json_meshes, "}");
  2425. writeMeshNode(json_nodes, mesh_offset, mesh, data, qp);
  2426. if (mesh.node)
  2427. {
  2428. NodeInfo& ni = nodes[mesh.node - data->nodes];
  2429. assert(ni.keep);
  2430. ni.meshes.push_back(node_offset);
  2431. }
  2432. else
  2433. {
  2434. comma(json_roots);
  2435. append(json_roots, node_offset);
  2436. }
  2437. node_offset++;
  2438. mesh_offset++;
  2439. // skip all meshes that we've written in this iteration
  2440. assert(pi > i);
  2441. i = pi - 1;
  2442. }
  2443. remapNodes(data, nodes, node_offset);
  2444. for (size_t i = 0; i < data->nodes_count; ++i)
  2445. {
  2446. NodeInfo& ni = nodes[i];
  2447. if (!ni.keep)
  2448. continue;
  2449. const cgltf_node& node = data->nodes[i];
  2450. if (!node.parent)
  2451. {
  2452. comma(json_roots);
  2453. append(json_roots, size_t(ni.remap));
  2454. }
  2455. writeNode(json_nodes, node, nodes, data);
  2456. }
  2457. for (size_t i = 0; i < data->skins_count; ++i)
  2458. {
  2459. const cgltf_skin& skin = data->skins[i];
  2460. size_t matrix_accr = writeJointBindMatrices(views, json_accessors, accr_offset, skin, qp, settings);
  2461. comma(json_skins);
  2462. append(json_skins, "{");
  2463. append(json_skins, "\"joints\":[");
  2464. for (size_t j = 0; j < skin.joints_count; ++j)
  2465. {
  2466. comma(json_skins);
  2467. append(json_skins, size_t(nodes[skin.joints[j] - data->nodes].remap));
  2468. }
  2469. append(json_skins, "]");
  2470. append(json_skins, ",\"inverseBindMatrices\":");
  2471. append(json_skins, matrix_accr);
  2472. if (skin.skeleton)
  2473. {
  2474. comma(json_skins);
  2475. append(json_skins, "\"skeleton\":");
  2476. append(json_skins, size_t(nodes[skin.skeleton - data->nodes].remap));
  2477. }
  2478. append(json_skins, "}");
  2479. }
  2480. for (size_t i = 0; i < data->animations_count; ++i)
  2481. {
  2482. const cgltf_animation& animation = data->animations[i];
  2483. writeAnimation(json_animations, views, json_accessors, accr_offset, animation, data, nodes, settings);
  2484. }
  2485. for (size_t i = 0; i < data->cameras_count; ++i)
  2486. {
  2487. const cgltf_camera& camera = data->cameras[i];
  2488. writeCamera(json_cameras, camera);
  2489. }
  2490. for (size_t i = 0; i < data->lights_count; ++i)
  2491. {
  2492. const cgltf_light& light = data->lights[i];
  2493. writeLight(json_lights, light);
  2494. }
  2495. char version[32];
  2496. sprintf(version, "%d.%d", MESHOPTIMIZER_VERSION / 1000, (MESHOPTIMIZER_VERSION % 1000) / 10);
  2497. append(json, "\"asset\":{");
  2498. append(json, "\"version\":\"2.0\",\"generator\":\"gltfpack ");
  2499. append(json, version);
  2500. append(json, "\"");
  2501. if (data->asset.extras.start_offset)
  2502. {
  2503. append(json, ",\"extras\":");
  2504. json.append(data->json + data->asset.extras.start_offset, data->json + data->asset.extras.end_offset);
  2505. }
  2506. append(json, "}");
  2507. append(json, ",\"extensionsUsed\":[");
  2508. append(json, "\"MESHOPT_quantized_geometry\"");
  2509. if (settings.compress)
  2510. {
  2511. comma(json);
  2512. append(json, "\"MESHOPT_compression\"");
  2513. }
  2514. if (!json_textures.empty())
  2515. {
  2516. comma(json);
  2517. append(json, "\"KHR_texture_transform\"");
  2518. }
  2519. if (ext_pbr_specular_glossiness)
  2520. {
  2521. comma(json);
  2522. append(json, "\"KHR_materials_pbrSpecularGlossiness\"");
  2523. }
  2524. if (ext_unlit)
  2525. {
  2526. comma(json);
  2527. append(json, "\"KHR_materials_unlit\"");
  2528. }
  2529. if (data->lights_count)
  2530. {
  2531. comma(json);
  2532. append(json, "\"KHR_lights_punctual\"");
  2533. }
  2534. append(json, "]");
  2535. if (settings.compress)
  2536. {
  2537. append(json, ",\"extensionsRequired\":[");
  2538. // Note: ideally we should include MESHOPT_quantized_geometry in the required extension list (regardless of compression)
  2539. // This extension *only* allows the use of quantized attributes for positions/normals/etc. This happens to be supported
  2540. // by popular JS frameworks, however, Babylon.JS refuses to load files with unsupported required extensions.
  2541. // For now we don't include it in the list, which will be fixed at some point once this extension becomes official.
  2542. append(json, "\"MESHOPT_compression\"");
  2543. append(json, "]");
  2544. }
  2545. size_t bytes[BufferView::Kind_Count] = {};
  2546. if (!views.empty())
  2547. {
  2548. append(json, ",\"bufferViews\":[");
  2549. for (size_t i = 0; i < views.size(); ++i)
  2550. {
  2551. BufferView& view = views[i];
  2552. size_t offset = bin.size();
  2553. size_t count = view.data.size() / view.stride;
  2554. int compression = -1;
  2555. if (view.compressed)
  2556. {
  2557. if (view.kind == BufferView::Kind_Index)
  2558. {
  2559. compressIndexStream(bin, view.data, count, view.stride);
  2560. compression = 1;
  2561. }
  2562. else
  2563. {
  2564. compressVertexStream(bin, view.data, count, view.stride);
  2565. compression = 0;
  2566. }
  2567. }
  2568. else
  2569. {
  2570. bin += view.data;
  2571. }
  2572. comma(json);
  2573. writeBufferView(json, view.kind, count, view.stride, offset, bin.size() - offset, compression);
  2574. view.bytes = bin.size() - offset;
  2575. bytes[view.kind] += view.bytes;
  2576. // align each bufferView by 4 bytes
  2577. bin.resize((bin.size() + 3) & ~3);
  2578. }
  2579. append(json, "]");
  2580. }
  2581. if (!json_accessors.empty())
  2582. {
  2583. append(json, ",\"accessors\":[");
  2584. append(json, json_accessors);
  2585. append(json, "]");
  2586. }
  2587. if (!json_images.empty())
  2588. {
  2589. append(json, ",\"images\":[");
  2590. append(json, json_images);
  2591. append(json, "]");
  2592. }
  2593. if (!json_textures.empty())
  2594. {
  2595. append(json, ",\"textures\":[");
  2596. append(json, json_textures);
  2597. append(json, "]");
  2598. }
  2599. if (!json_materials.empty())
  2600. {
  2601. append(json, ",\"materials\":[");
  2602. append(json, json_materials);
  2603. append(json, "]");
  2604. }
  2605. if (!json_meshes.empty())
  2606. {
  2607. append(json, ",\"meshes\":[");
  2608. append(json, json_meshes);
  2609. append(json, "]");
  2610. }
  2611. if (!json_skins.empty())
  2612. {
  2613. append(json, ",\"skins\":[");
  2614. append(json, json_skins);
  2615. append(json, "]");
  2616. }
  2617. if (!json_animations.empty())
  2618. {
  2619. append(json, ",\"animations\":[");
  2620. append(json, json_animations);
  2621. append(json, "]");
  2622. }
  2623. if (!json_roots.empty())
  2624. {
  2625. append(json, ",\"nodes\":[");
  2626. append(json, json_nodes);
  2627. append(json, "],\"scenes\":[");
  2628. append(json, "{\"nodes\":[");
  2629. append(json, json_roots);
  2630. append(json, "]}]");
  2631. }
  2632. if (!json_cameras.empty())
  2633. {
  2634. append(json, ",\"cameras\":[");
  2635. append(json, json_cameras);
  2636. append(json, "]");
  2637. }
  2638. if (!json_lights.empty())
  2639. {
  2640. append(json, ",\"extensions\":{\"KHR_lights_punctual\":{\"lights\":[");
  2641. append(json, json_lights);
  2642. append(json, "]}}");
  2643. }
  2644. if (!json_roots.empty())
  2645. {
  2646. append(json, ",\"scene\":0");
  2647. }
  2648. if (settings.verbose)
  2649. {
  2650. size_t primitives = 0;
  2651. for (size_t i = 0; i < meshes.size(); ++i)
  2652. primitives += !meshes[i].indices.empty();
  2653. printf("output: %d nodes, %d meshes (%d primitives), %d materials\n", int(node_offset), int(mesh_offset), int(primitives), int(material_offset));
  2654. printf("output: JSON %d bytes, buffers %d bytes\n", int(json.size()), int(bin.size()));
  2655. printf("output: buffers: vertex %d bytes, index %d bytes, skin %d bytes, time %d bytes, keyframe %d bytes, image %d bytes\n",
  2656. int(bytes[BufferView::Kind_Vertex]), int(bytes[BufferView::Kind_Index]), int(bytes[BufferView::Kind_Skin]),
  2657. int(bytes[BufferView::Kind_Time]), int(bytes[BufferView::Kind_Keyframe]), int(bytes[BufferView::Kind_Image]));
  2658. }
  2659. if (settings.verbose > 1)
  2660. {
  2661. printStats(views, BufferView::Kind_Vertex, "vertex");
  2662. printStats(views, BufferView::Kind_Index, "index");
  2663. printStats(views, BufferView::Kind_Keyframe, "keyframe");
  2664. }
  2665. }
  2666. void writeU32(FILE* out, uint32_t data)
  2667. {
  2668. fwrite(&data, 4, 1, out);
  2669. }
  2670. bool requiresExtension(cgltf_data* data, const char* name)
  2671. {
  2672. for (size_t i = 0; i < data->extensions_required_count; ++i)
  2673. if (strcmp(data->extensions_required[i], name) == 0)
  2674. return true;
  2675. return false;
  2676. }
  2677. int gltfpack(const char* input, const char* output, const Settings& settings)
  2678. {
  2679. cgltf_data* data = 0;
  2680. std::vector<Mesh> meshes;
  2681. const char* iext = strrchr(input, '.');
  2682. if (iext && (strcmp(iext, ".gltf") == 0 || strcmp(iext, ".GLTF") == 0 || strcmp(iext, ".glb") == 0 || strcmp(iext, ".GLB") == 0))
  2683. {
  2684. cgltf_options options = {};
  2685. cgltf_result result = cgltf_parse_file(&options, input, &data);
  2686. result = (result == cgltf_result_success) ? cgltf_validate(data) : result;
  2687. result = (result == cgltf_result_success) ? cgltf_load_buffers(&options, data, input) : result;
  2688. const char* error = NULL;
  2689. if (result != cgltf_result_success)
  2690. error = getError(result);
  2691. else if (requiresExtension(data, "KHR_draco_mesh_compression"))
  2692. error = "file requires Draco mesh compression support";
  2693. else if (requiresExtension(data, "MESHOPT_compression"))
  2694. error = "file has already been compressed using gltfpack";
  2695. if (error)
  2696. {
  2697. fprintf(stderr, "Error loading %s: %s\n", input, error);
  2698. cgltf_free(data);
  2699. return 2;
  2700. }
  2701. parseMeshesGltf(data, meshes);
  2702. }
  2703. else if (iext && (strcmp(iext, ".obj") == 0 || strcmp(iext, ".OBJ") == 0))
  2704. {
  2705. fastObjMesh* obj = fast_obj_read(input);
  2706. if (!obj)
  2707. {
  2708. fprintf(stderr, "Error loading %s: file not found\n", input);
  2709. cgltf_free(data);
  2710. return 2;
  2711. }
  2712. data = parseSceneObj(obj);
  2713. parseMeshesObj(obj, data, meshes);
  2714. fast_obj_destroy(obj);
  2715. }
  2716. else
  2717. {
  2718. fprintf(stderr, "Error loading %s: unknown extension (expected .gltf or .glb or .obj)\n", input);
  2719. return 2;
  2720. }
  2721. std::string json, bin;
  2722. process(data, meshes, settings, json, bin);
  2723. cgltf_free(data);
  2724. if (!output)
  2725. {
  2726. return 0;
  2727. }
  2728. const char* oext = strrchr(output, '.');
  2729. if (oext && (strcmp(oext, ".gltf") == 0 || strcmp(oext, ".GLTF") == 0))
  2730. {
  2731. std::string binpath = output;
  2732. binpath.replace(binpath.size() - 5, 5, ".bin");
  2733. std::string binname = binpath;
  2734. std::string::size_type slash = binname.find_last_of("/\\");
  2735. if (slash != std::string::npos)
  2736. binname.erase(0, slash + 1);
  2737. FILE* outjson = fopen(output, "wb");
  2738. FILE* outbin = fopen(binpath.c_str(), "wb");
  2739. if (!outjson || !outbin)
  2740. {
  2741. fprintf(stderr, "Error saving %s\n", output);
  2742. return 4;
  2743. }
  2744. fprintf(outjson, "{\"buffers\":[{\"uri\":\"%s\",\"byteLength\":%zu}],", binname.c_str(), bin.size());
  2745. fwrite(json.c_str(), json.size(), 1, outjson);
  2746. fprintf(outjson, "}");
  2747. fwrite(bin.c_str(), bin.size(), 1, outbin);
  2748. fclose(outjson);
  2749. fclose(outbin);
  2750. }
  2751. else if (oext && (strcmp(oext, ".glb") == 0 || strcmp(oext, ".GLB") == 0))
  2752. {
  2753. FILE* out = fopen(output, "wb");
  2754. if (!out)
  2755. {
  2756. fprintf(stderr, "Error saving %s\n", output);
  2757. return 4;
  2758. }
  2759. char bufferspec[64];
  2760. sprintf(bufferspec, "{\"buffers\":[{\"byteLength\":%zu}],", bin.size());
  2761. json.insert(0, bufferspec);
  2762. json.push_back('}');
  2763. while (json.size() % 4)
  2764. json.push_back(' ');
  2765. while (bin.size() % 4)
  2766. bin.push_back('\0');
  2767. writeU32(out, 0x46546C67);
  2768. writeU32(out, 2);
  2769. writeU32(out, uint32_t(12 + 8 + json.size() + 8 + bin.size()));
  2770. writeU32(out, uint32_t(json.size()));
  2771. writeU32(out, 0x4E4F534A);
  2772. fwrite(json.c_str(), json.size(), 1, out);
  2773. writeU32(out, uint32_t(bin.size()));
  2774. writeU32(out, 0x004E4942);
  2775. fwrite(bin.c_str(), bin.size(), 1, out);
  2776. fclose(out);
  2777. }
  2778. else
  2779. {
  2780. fprintf(stderr, "Error saving %s: unknown extension (expected .gltf or .glb)\n", output);
  2781. return 4;
  2782. }
  2783. return 0;
  2784. }
  2785. int main(int argc, char** argv)
  2786. {
  2787. Settings settings = {};
  2788. settings.pos_bits = 14;
  2789. settings.tex_bits = 12;
  2790. settings.nrm_bits = 8;
  2791. settings.anim_freq = 30;
  2792. const char* input = 0;
  2793. const char* output = 0;
  2794. bool help = false;
  2795. int test = 0;
  2796. for (int i = 1; i < argc; ++i)
  2797. {
  2798. const char* arg = argv[i];
  2799. if (strcmp(arg, "-vp") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
  2800. {
  2801. settings.pos_bits = atoi(argv[++i]);
  2802. }
  2803. else if (strcmp(arg, "-vt") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
  2804. {
  2805. settings.tex_bits = atoi(argv[++i]);
  2806. }
  2807. else if (strcmp(arg, "-vn") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
  2808. {
  2809. settings.nrm_bits = atoi(argv[++i]);
  2810. }
  2811. else if (strcmp(arg, "-vu") == 0)
  2812. {
  2813. settings.nrm_unit = true;
  2814. }
  2815. else if (strcmp(arg, "-af") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
  2816. {
  2817. settings.anim_freq = atoi(argv[++i]);
  2818. }
  2819. else if (strcmp(arg, "-ac") == 0)
  2820. {
  2821. settings.anim_const = true;
  2822. }
  2823. else if (strcmp(arg, "-kn") == 0)
  2824. {
  2825. settings.keep_named = true;
  2826. }
  2827. else if (strcmp(arg, "-i") == 0 && i + 1 < argc && !input)
  2828. {
  2829. input = argv[++i];
  2830. }
  2831. else if (strcmp(arg, "-o") == 0 && i + 1 < argc && !output)
  2832. {
  2833. output = argv[++i];
  2834. }
  2835. else if (strcmp(arg, "-c") == 0)
  2836. {
  2837. settings.compress = true;
  2838. }
  2839. else if (strcmp(arg, "-v") == 0)
  2840. {
  2841. settings.verbose = 1;
  2842. }
  2843. else if (strcmp(arg, "-vv") == 0)
  2844. {
  2845. settings.verbose = 2;
  2846. }
  2847. else if (strcmp(arg, "-h") == 0)
  2848. {
  2849. help = true;
  2850. }
  2851. else if (strcmp(arg, "-test") == 0)
  2852. {
  2853. test = i + 1;
  2854. break;
  2855. }
  2856. else
  2857. {
  2858. fprintf(stderr, "Unrecognized option %s\n", arg);
  2859. return 1;
  2860. }
  2861. }
  2862. if (test)
  2863. {
  2864. for (int i = test; i < argc; ++i)
  2865. {
  2866. printf("%s\n", argv[i]);
  2867. gltfpack(argv[i], NULL, settings);
  2868. }
  2869. return 0;
  2870. }
  2871. if (!input || !output || help)
  2872. {
  2873. fprintf(stderr, "Usage: gltfpack [options] -i input -o output\n");
  2874. fprintf(stderr, "\n");
  2875. fprintf(stderr, "Options:\n");
  2876. fprintf(stderr, "-i file: input file to process, .obj/.gltf/.glb\n");
  2877. fprintf(stderr, "-o file: output file path, .gltf/.glb\n");
  2878. fprintf(stderr, "-vp N: use N-bit quantization for positions (default: 14; N should be between 1 and 16)\n");
  2879. fprintf(stderr, "-vt N: use N-bit quantization for texture corodinates (default: 12; N should be between 1 and 16)\n");
  2880. fprintf(stderr, "-vn N: use N-bit quantization for normals and tangents (default: 8; N should be between 1 and 8)\n");
  2881. fprintf(stderr, "-vu: use unit-length normal/tangent vectors (default: off)\n");
  2882. fprintf(stderr, "-af N: resample animations at N Hz (default: 30)\n");
  2883. fprintf(stderr, "-ac: keep constant animation tracks even if they don't modify the node transform\n");
  2884. fprintf(stderr, "-kn: keep named nodes and meshes attached to named nodes so that named nodes can be transformed externally\n");
  2885. fprintf(stderr, "-c: produce compressed glb files\n");
  2886. fprintf(stderr, "-v: verbose output\n");
  2887. fprintf(stderr, "-h: display this help and exit\n");
  2888. return 1;
  2889. }
  2890. return gltfpack(input, output, settings);
  2891. }