gltfpack.cpp 90 KB

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