gltfpack.cpp 97 KB

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