1
0

tiniergltf.hpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  1. #pragma once
  2. #include <json/json.h>
  3. #include "util/base64.h"
  4. #include <cstdint>
  5. #include <functional>
  6. #include <stack>
  7. #include <string>
  8. #include <string_view>
  9. #include <variant>
  10. #include <vector>
  11. #include <array>
  12. #include <optional>
  13. #include <limits>
  14. #include <memory> // unique_ptr
  15. #include <stdexcept>
  16. #include <unordered_map>
  17. #include <unordered_set>
  18. #if JSONCPP_VERSION_HEXA < 0x01090000 /* 1.9.0 */
  19. namespace Json {
  20. using String = JSONCPP_STRING; // Polyfill
  21. }
  22. #endif
  23. namespace tiniergltf {
  24. static inline void check(bool cond) {
  25. if (!cond)
  26. throw std::runtime_error("invalid glTF");
  27. }
  28. template <typename T>
  29. static inline void checkIndex(const std::optional<std::vector<T>> &vec,
  30. const std::optional<std::size_t> &i) {
  31. if (!i.has_value()) return;
  32. check(vec.has_value());
  33. check(i < vec->size());
  34. }
  35. template <typename T>
  36. static inline void checkIndex(const std::vector<T> &vec,
  37. const std::optional<std::size_t> &i) {
  38. if (!i.has_value()) return;
  39. check(i < vec.size());
  40. }
  41. template <typename T, typename F>
  42. static inline void checkForall(const std::optional<std::vector<T>> &vec, const F &cond) {
  43. if (!vec.has_value())
  44. return;
  45. for (const T &v : vec.value())
  46. cond(v);
  47. }
  48. template <typename T>
  49. static inline void checkDuplicateFree(const std::vector<T> &vec) {
  50. check(std::unordered_set<T>(vec.begin(), vec.end()).size() == vec.size());
  51. }
  52. template <typename T>
  53. static inline T as(const Json::Value &o);
  54. template<>
  55. bool as(const Json::Value &o) {
  56. check(o.isBool());
  57. return o.asBool();
  58. }
  59. template<>
  60. double as (const Json::Value &o) {
  61. check(o.isDouble());
  62. return o.asDouble();
  63. }
  64. template<>
  65. std::size_t as(const Json::Value &o) {
  66. check(o.isUInt64());
  67. auto u = o.asUInt64();
  68. check(u <= std::numeric_limits<std::size_t>::max());
  69. return u;
  70. }
  71. template<>
  72. std::string as(const Json::Value &o) {
  73. check(o.isString());
  74. return o.asString();
  75. }
  76. template<typename U>
  77. std::vector<U> asVec(const Json::Value &o) {
  78. check(o.isArray());
  79. std::vector<U> res;
  80. res.reserve(o.size());
  81. for (Json::ArrayIndex i = 0; i < o.size(); ++i) {
  82. res.push_back(as<U>(o[i]));
  83. }
  84. return res;
  85. }
  86. template<typename U, std::size_t n>
  87. std::array<U, n> asArr(const Json::Value &o) {
  88. check(o.isArray());
  89. check(o.size() == n);
  90. std::array<U, n> res;
  91. for (Json::ArrayIndex i = 0; i < n; ++i) {
  92. res[i] = as<U>(o[i]);
  93. }
  94. return res;
  95. }
  96. struct AccessorSparseIndices {
  97. std::size_t bufferView;
  98. std::size_t byteOffset;
  99. // as defined in the glTF specification
  100. enum class ComponentType {
  101. UNSIGNED_BYTE,
  102. UNSIGNED_SHORT,
  103. UNSIGNED_INT,
  104. };
  105. ComponentType componentType;
  106. std::size_t componentSize() const {
  107. switch (componentType) {
  108. case ComponentType::UNSIGNED_BYTE:
  109. return 1;
  110. case ComponentType::UNSIGNED_SHORT:
  111. return 2;
  112. case ComponentType::UNSIGNED_INT:
  113. return 4;
  114. }
  115. throw std::logic_error("invalid component type");
  116. }
  117. std::size_t elementSize() const {
  118. return componentSize();
  119. }
  120. AccessorSparseIndices(const Json::Value &o)
  121. : bufferView(as<std::size_t>(o["bufferView"]))
  122. , byteOffset(0)
  123. {
  124. check(o.isObject());
  125. if (o.isMember("byteOffset")) {
  126. byteOffset = as<std::size_t>(o["byteOffset"]);
  127. check(byteOffset >= 0);
  128. }
  129. {
  130. static std::unordered_map<Json::UInt64, ComponentType> map = {
  131. {5121, ComponentType::UNSIGNED_BYTE},
  132. {5123, ComponentType::UNSIGNED_SHORT},
  133. {5125, ComponentType::UNSIGNED_INT},
  134. };
  135. const auto &v = o["componentType"]; check(v.isUInt64());
  136. componentType = map.at(v.asUInt64());
  137. }
  138. }
  139. };
  140. template<> AccessorSparseIndices as(const Json::Value &o) { return o; }
  141. struct AccessorSparseValues {
  142. std::size_t bufferView;
  143. std::size_t byteOffset;
  144. AccessorSparseValues(const Json::Value &o)
  145. : bufferView(as<std::size_t>(o["bufferView"]))
  146. , byteOffset(0)
  147. {
  148. check(o.isObject());
  149. if (o.isMember("byteOffset")) {
  150. byteOffset = as<std::size_t>(o["byteOffset"]);
  151. check(byteOffset >= 0);
  152. }
  153. }
  154. };
  155. template<> AccessorSparseValues as(const Json::Value &o) { return o; }
  156. struct AccessorSparse {
  157. std::size_t count;
  158. AccessorSparseIndices indices;
  159. AccessorSparseValues values;
  160. AccessorSparse(const Json::Value &o)
  161. : count(as<std::size_t>(o["count"]))
  162. , indices(as<AccessorSparseIndices>(o["indices"]))
  163. , values(as<AccessorSparseValues>(o["values"]))
  164. {
  165. check(o.isObject());
  166. check(count >= 1);
  167. }
  168. };
  169. template<> AccessorSparse as(const Json::Value &o) { return o; }
  170. struct Accessor {
  171. std::optional<std::size_t> bufferView;
  172. std::size_t byteOffset;
  173. // as defined in the glTF specification
  174. enum class ComponentType {
  175. BYTE,
  176. UNSIGNED_BYTE,
  177. SHORT,
  178. UNSIGNED_SHORT,
  179. UNSIGNED_INT,
  180. FLOAT,
  181. };
  182. ComponentType componentType;
  183. std::size_t componentSize() const {
  184. switch (componentType) {
  185. case ComponentType::BYTE:
  186. case ComponentType::UNSIGNED_BYTE:
  187. return 1;
  188. case ComponentType::SHORT:
  189. case ComponentType::UNSIGNED_SHORT:
  190. return 2;
  191. case ComponentType::UNSIGNED_INT:
  192. case ComponentType::FLOAT:
  193. return 4;
  194. }
  195. throw std::logic_error("invalid component type");
  196. }
  197. std::size_t count;
  198. std::optional<std::vector<double>> max;
  199. std::optional<std::vector<double>> min;
  200. std::optional<std::string> name;
  201. bool normalized;
  202. std::optional<AccessorSparse> sparse;
  203. enum class Type {
  204. MAT2,
  205. MAT3,
  206. MAT4,
  207. SCALAR,
  208. VEC2,
  209. VEC3,
  210. VEC4,
  211. };
  212. std::size_t typeCount() const {
  213. switch (type) {
  214. case Type::SCALAR:
  215. return 1;
  216. case Type::VEC2:
  217. return 2;
  218. case Type::VEC3:
  219. return 3;
  220. case Type::MAT2:
  221. case Type::VEC4:
  222. return 4;
  223. case Type::MAT3:
  224. return 9;
  225. case Type::MAT4:
  226. return 16;
  227. }
  228. throw std::logic_error("invalid type");
  229. }
  230. Type type;
  231. std::size_t elementSize() const {
  232. return componentSize() * typeCount();
  233. }
  234. Accessor(const Json::Value &o)
  235. : byteOffset(0)
  236. , count(as<std::size_t>(o["count"]))
  237. , normalized(false)
  238. {
  239. check(o.isObject());
  240. if (o.isMember("bufferView")) {
  241. bufferView = as<std::size_t>(o["bufferView"]);
  242. }
  243. {
  244. static std::unordered_map<Json::UInt64, ComponentType> map = {
  245. {5120, ComponentType::BYTE},
  246. {5121, ComponentType::UNSIGNED_BYTE},
  247. {5122, ComponentType::SHORT},
  248. {5123, ComponentType::UNSIGNED_SHORT},
  249. {5125, ComponentType::UNSIGNED_INT},
  250. {5126, ComponentType::FLOAT},
  251. };
  252. const auto &v = o["componentType"]; check(v.isUInt64());
  253. componentType = map.at(v.asUInt64());
  254. }
  255. if (o.isMember("byteOffset")) {
  256. byteOffset = as<std::size_t>(o["byteOffset"]);
  257. check(byteOffset >= 0);
  258. check(byteOffset % componentSize() == 0);
  259. }
  260. check(count >= 1);
  261. if (o.isMember("name")) {
  262. name = as<std::string>(o["name"]);
  263. }
  264. if (o.isMember("normalized")) {
  265. normalized = as<bool>(o["normalized"]);
  266. }
  267. if (o.isMember("sparse")) {
  268. sparse = as<AccessorSparse>(o["sparse"]);
  269. }
  270. {
  271. static std::unordered_map<Json::String, Type> map = {
  272. {"MAT2", Type::MAT2},
  273. {"MAT3", Type::MAT3},
  274. {"MAT4", Type::MAT4},
  275. {"SCALAR", Type::SCALAR},
  276. {"VEC2", Type::VEC2},
  277. {"VEC3", Type::VEC3},
  278. {"VEC4", Type::VEC4},
  279. };
  280. const auto &v = o["type"]; check(v.isString());
  281. type = map.at(v.asString());
  282. }
  283. if (o.isMember("max")) {
  284. max = asVec<double>(o["max"]);
  285. check(max->size() == typeCount());
  286. }
  287. if (o.isMember("min")) {
  288. min = asVec<double>(o["min"]);
  289. check(min->size() == typeCount());
  290. }
  291. }
  292. };
  293. template<> Accessor as(const Json::Value &o) { return o; }
  294. struct AnimationChannelTarget {
  295. std::optional<std::size_t> node;
  296. enum class Path {
  297. ROTATION,
  298. SCALE,
  299. TRANSLATION,
  300. WEIGHTS,
  301. };
  302. Path path;
  303. AnimationChannelTarget(const Json::Value &o)
  304. {
  305. check(o.isObject());
  306. if (o.isMember("node")) {
  307. node = as<std::size_t>(o["node"]);
  308. }
  309. {
  310. static std::unordered_map<Json::String, Path> map = {
  311. {"rotation", Path::ROTATION},
  312. {"scale", Path::SCALE},
  313. {"translation", Path::TRANSLATION},
  314. {"weights", Path::WEIGHTS},
  315. };
  316. const auto &v = o["path"]; check(v.isString());
  317. path = map.at(v.asString());
  318. }
  319. }
  320. };
  321. template<> AnimationChannelTarget as(const Json::Value &o) { return o; }
  322. struct AnimationChannel {
  323. std::size_t sampler;
  324. AnimationChannelTarget target;
  325. AnimationChannel(const Json::Value &o)
  326. : sampler(as<std::size_t>(o["sampler"]))
  327. , target(as<AnimationChannelTarget>(o["target"]))
  328. {
  329. check(o.isObject());
  330. }
  331. };
  332. template<> AnimationChannel as(const Json::Value &o) { return o; }
  333. struct AnimationSampler {
  334. std::size_t input;
  335. enum class Interpolation {
  336. CUBICSPLINE,
  337. LINEAR,
  338. STEP,
  339. };
  340. Interpolation interpolation;
  341. std::size_t output;
  342. AnimationSampler(const Json::Value &o)
  343. : input(as<std::size_t>(o["input"]))
  344. , interpolation(Interpolation::LINEAR)
  345. , output(as<std::size_t>(o["output"]))
  346. {
  347. check(o.isObject());
  348. if (o.isMember("interpolation")) {
  349. static std::unordered_map<Json::String, Interpolation> map = {
  350. {"CUBICSPLINE", Interpolation::CUBICSPLINE},
  351. {"LINEAR", Interpolation::LINEAR},
  352. {"STEP", Interpolation::STEP},
  353. };
  354. const auto &v = o["interpolation"]; check(v.isString());
  355. interpolation = map.at(v.asString());
  356. }
  357. }
  358. };
  359. template<> AnimationSampler as(const Json::Value &o) { return o; }
  360. struct Animation {
  361. std::vector<AnimationChannel> channels;
  362. std::optional<std::string> name;
  363. std::vector<AnimationSampler> samplers;
  364. Animation(const Json::Value &o)
  365. : channels(asVec<AnimationChannel>(o["channels"]))
  366. , samplers(asVec<AnimationSampler>(o["samplers"]))
  367. {
  368. check(o.isObject());
  369. check(channels.size() >= 1);
  370. if (o.isMember("name")) {
  371. name = as<std::string>(o["name"]);
  372. }
  373. check(samplers.size() >= 1);
  374. }
  375. };
  376. template<> Animation as(const Json::Value &o) { return o; }
  377. struct Asset {
  378. std::optional<std::string> copyright;
  379. std::optional<std::string> generator;
  380. std::optional<std::string> minVersion;
  381. std::string version;
  382. Asset(const Json::Value &o)
  383. : version(as<std::string>(o["version"]))
  384. {
  385. check(o.isObject());
  386. if (o.isMember("copyright")) {
  387. copyright = as<std::string>(o["copyright"]);
  388. }
  389. if (o.isMember("generator")) {
  390. generator = as<std::string>(o["generator"]);
  391. }
  392. if (o.isMember("minVersion")) {
  393. minVersion = as<std::string>(o["minVersion"]);
  394. }
  395. }
  396. };
  397. template<> Asset as(const Json::Value &o) { return o; }
  398. struct BufferView {
  399. std::size_t buffer;
  400. std::size_t byteLength;
  401. std::size_t byteOffset;
  402. std::optional<std::size_t> byteStride;
  403. std::optional<std::string> name;
  404. enum class Target {
  405. ARRAY_BUFFER,
  406. ELEMENT_ARRAY_BUFFER,
  407. };
  408. std::optional<Target> target;
  409. BufferView(const Json::Value &o)
  410. : buffer(as<std::size_t>(o["buffer"]))
  411. , byteLength(as<std::size_t>(o["byteLength"]))
  412. , byteOffset(0)
  413. {
  414. check(o.isObject());
  415. check(byteLength >= 1);
  416. if (o.isMember("byteOffset")) {
  417. byteOffset = as<std::size_t>(o["byteOffset"]);
  418. check(byteOffset >= 0);
  419. }
  420. if (o.isMember("byteStride")) {
  421. byteStride = as<std::size_t>(o["byteStride"]);
  422. check(byteStride.value() >= 4);
  423. check(byteStride.value() <= 252);
  424. check(byteStride.value() % 4 == 0);
  425. }
  426. if (o.isMember("name")) {
  427. name = as<std::string>(o["name"]);
  428. }
  429. if (o.isMember("target")) {
  430. static std::unordered_map<Json::UInt64, Target> map = {
  431. {34962, Target::ARRAY_BUFFER},
  432. {34963, Target::ELEMENT_ARRAY_BUFFER},
  433. };
  434. const auto &v = o["target"]; check(v.isUInt64());
  435. target = map.at(v.asUInt64());
  436. }
  437. }
  438. };
  439. template<> BufferView as(const Json::Value &o) { return o; }
  440. struct Buffer {
  441. std::size_t byteLength;
  442. std::optional<std::string> name;
  443. std::string data;
  444. Buffer(const Json::Value &o,
  445. const std::function<std::string(const std::string &uri)> &resolveURI,
  446. std::optional<std::string> &&glbData = std::nullopt)
  447. : byteLength(as<std::size_t>(o["byteLength"]))
  448. {
  449. check(o.isObject());
  450. check(byteLength >= 1);
  451. if (o.isMember("name")) {
  452. name = as<std::string>(o["name"]);
  453. }
  454. if (glbData.has_value()) {
  455. check(!o.isMember("uri"));
  456. data = *std::move(glbData);
  457. // GLB allows padding, which need not be reflected in the JSON
  458. check(byteLength + 3 >= data.size());
  459. check(data.size() >= byteLength);
  460. } else {
  461. check(o.isMember("uri"));
  462. bool dataURI = false;
  463. const std::string uri = as<std::string>(o["uri"]);
  464. for (auto &prefix : std::array<std::string, 2> {
  465. "data:application/octet-stream;base64,",
  466. "data:application/gltf-buffer;base64,"
  467. }) {
  468. if (std::string_view(uri).substr(0, prefix.length()) == prefix) {
  469. auto view = std::string_view(uri).substr(prefix.length());
  470. check(base64_is_valid(view));
  471. data = base64_decode(view);
  472. dataURI = true;
  473. break;
  474. }
  475. }
  476. if (!dataURI)
  477. data = resolveURI(uri);
  478. check(data.size() >= byteLength);
  479. }
  480. data.resize(byteLength);
  481. }
  482. };
  483. struct CameraOrthographic {
  484. double xmag;
  485. double ymag;
  486. double zfar;
  487. double znear;
  488. CameraOrthographic(const Json::Value &o)
  489. : xmag(as<double>(o["xmag"]))
  490. , ymag(as<double>(o["ymag"]))
  491. , zfar(as<double>(o["zfar"]))
  492. , znear(as<double>(o["znear"]))
  493. {
  494. check(o.isObject());
  495. check(zfar > 0);
  496. check(znear >= 0);
  497. }
  498. };
  499. template<> CameraOrthographic as(const Json::Value &o) { return o; }
  500. struct CameraPerspective {
  501. std::optional<double> aspectRatio;
  502. double yfov;
  503. std::optional<double> zfar;
  504. double znear;
  505. CameraPerspective(const Json::Value &o)
  506. : yfov(as<double>(o["yfov"]))
  507. , znear(as<double>(o["znear"]))
  508. {
  509. check(o.isObject());
  510. if (o.isMember("aspectRatio")) {
  511. aspectRatio = as<double>(o["aspectRatio"]);
  512. check(aspectRatio.value() > 0);
  513. }
  514. check(yfov > 0);
  515. if (o.isMember("zfar")) {
  516. zfar = as<double>(o["zfar"]);
  517. check(zfar.value() > 0);
  518. }
  519. check(znear > 0);
  520. }
  521. };
  522. template<> CameraPerspective as(const Json::Value &o) { return o; }
  523. struct Camera {
  524. std::optional<std::string> name;
  525. std::optional<CameraOrthographic> orthographic;
  526. std::optional<CameraPerspective> perspective;
  527. enum class Type {
  528. ORTHOGRAPHIC,
  529. PERSPECTIVE,
  530. };
  531. Type type;
  532. Camera(const Json::Value &o)
  533. {
  534. check(o.isObject());
  535. if (o.isMember("name")) {
  536. name = as<std::string>(o["name"]);
  537. }
  538. if (o.isMember("orthographic")) {
  539. orthographic = as<CameraOrthographic>(o["orthographic"]);
  540. }
  541. if (o.isMember("perspective")) {
  542. perspective = as<CameraPerspective>(o["perspective"]);
  543. }
  544. {
  545. static std::unordered_map<Json::String, Type> map = {
  546. {"orthographic", Type::ORTHOGRAPHIC},
  547. {"perspective", Type::PERSPECTIVE},
  548. };
  549. const auto &v = o["type"]; check(v.isString());
  550. type = map.at(v.asString());
  551. }
  552. }
  553. };
  554. template<> Camera as(const Json::Value &o) { return o; }
  555. struct Image {
  556. std::optional<std::size_t> bufferView;
  557. enum class MimeType {
  558. IMAGE_JPEG,
  559. IMAGE_PNG,
  560. };
  561. std::optional<MimeType> mimeType;
  562. std::optional<std::string> name;
  563. std::optional<std::string> uri;
  564. Image(const Json::Value &o)
  565. {
  566. check(o.isObject());
  567. if (o.isMember("bufferView")) {
  568. bufferView = as<std::size_t>(o["bufferView"]);
  569. }
  570. if (o.isMember("mimeType")) {
  571. static std::unordered_map<Json::String, MimeType> map = {
  572. {"image/jpeg", MimeType::IMAGE_JPEG},
  573. {"image/png", MimeType::IMAGE_PNG},
  574. };
  575. const auto &v = o["mimeType"]; check(v.isString());
  576. mimeType = map.at(v.asString());
  577. }
  578. if (o.isMember("name")) {
  579. name = as<std::string>(o["name"]);
  580. }
  581. if (o.isMember("uri")) {
  582. uri = as<std::string>(o["uri"]);
  583. }
  584. }
  585. };
  586. template<> Image as(const Json::Value &o) { return o; }
  587. struct TextureInfo {
  588. std::size_t index;
  589. std::size_t texCoord;
  590. TextureInfo(const Json::Value &o)
  591. : index(as<std::size_t>(o["index"]))
  592. , texCoord(0)
  593. {
  594. check(o.isObject());
  595. if (o.isMember("texCoord")) {
  596. texCoord = as<std::size_t>(o["texCoord"]);
  597. check(texCoord >= 0);
  598. }
  599. }
  600. };
  601. template<> TextureInfo as(const Json::Value &o) { return o; }
  602. struct MaterialNormalTextureInfo {
  603. std::size_t index;
  604. double scale;
  605. std::size_t texCoord;
  606. MaterialNormalTextureInfo(const Json::Value &o)
  607. : index(as<std::size_t>(o["index"]))
  608. , scale(1)
  609. , texCoord(0)
  610. {
  611. check(o.isObject());
  612. if (o.isMember("scale")) {
  613. scale = as<double>(o["scale"]);
  614. }
  615. if (o.isMember("texCoord")) {
  616. texCoord = as<std::size_t>(o["texCoord"]);
  617. }
  618. }
  619. };
  620. template<> MaterialNormalTextureInfo as(const Json::Value &o) { return o; }
  621. struct MaterialOcclusionTextureInfo {
  622. std::size_t index;
  623. double strength;
  624. std::size_t texCoord;
  625. MaterialOcclusionTextureInfo(const Json::Value &o)
  626. : index(as<std::size_t>(o["index"]))
  627. , strength(1)
  628. , texCoord(0)
  629. {
  630. check(o.isObject());
  631. if (o.isMember("strength")) {
  632. strength = as<double>(o["strength"]);
  633. check(strength >= 0);
  634. check(strength <= 1);
  635. }
  636. if (o.isMember("texCoord")) {
  637. texCoord = as<std::size_t>(o["texCoord"]);
  638. }
  639. }
  640. };
  641. template<> MaterialOcclusionTextureInfo as(const Json::Value &o) { return o; }
  642. struct MaterialPbrMetallicRoughness {
  643. std::array<double, 4> baseColorFactor;
  644. std::optional<TextureInfo> baseColorTexture;
  645. double metallicFactor;
  646. std::optional<TextureInfo> metallicRoughnessTexture;
  647. double roughnessFactor;
  648. MaterialPbrMetallicRoughness(const Json::Value &o)
  649. : baseColorFactor{1, 1, 1, 1}
  650. , metallicFactor(1)
  651. , roughnessFactor(1)
  652. {
  653. check(o.isObject());
  654. if (o.isMember("baseColorFactor")) {
  655. baseColorFactor = asArr<double, 4>(o["baseColorFactor"]);
  656. for (auto v: baseColorFactor) {
  657. check(v >= 0);
  658. check(v <= 1);
  659. }
  660. }
  661. if (o.isMember("baseColorTexture")) {
  662. baseColorTexture = as<TextureInfo>(o["baseColorTexture"]);
  663. }
  664. if (o.isMember("metallicFactor")) {
  665. metallicFactor = as<double>(o["metallicFactor"]);
  666. check(metallicFactor >= 0);
  667. check(metallicFactor <= 1);
  668. }
  669. if (o.isMember("metallicRoughnessTexture")) {
  670. metallicRoughnessTexture = as<TextureInfo>(o["metallicRoughnessTexture"]);
  671. }
  672. if (o.isMember("roughnessFactor")) {
  673. roughnessFactor = as<double>(o["roughnessFactor"]);
  674. check(roughnessFactor >= 0);
  675. check(roughnessFactor <= 1);
  676. }
  677. }
  678. };
  679. template<> MaterialPbrMetallicRoughness as(const Json::Value &o) { return o; }
  680. struct Material {
  681. double alphaCutoff;
  682. enum class AlphaMode {
  683. BLEND,
  684. MASK,
  685. OPAQUE,
  686. };
  687. AlphaMode alphaMode;
  688. bool doubleSided;
  689. std::array<double, 3> emissiveFactor;
  690. std::optional<TextureInfo> emissiveTexture;
  691. std::optional<std::string> name;
  692. std::optional<MaterialNormalTextureInfo> normalTexture;
  693. std::optional<MaterialOcclusionTextureInfo> occlusionTexture;
  694. std::optional<MaterialPbrMetallicRoughness> pbrMetallicRoughness;
  695. Material(const Json::Value &o)
  696. : alphaCutoff(0.5)
  697. , alphaMode(AlphaMode::OPAQUE)
  698. , doubleSided(false)
  699. , emissiveFactor{0, 0, 0}
  700. {
  701. check(o.isObject());
  702. if (o.isMember("alphaCutoff")) {
  703. alphaCutoff = as<double>(o["alphaCutoff"]);
  704. check(alphaCutoff >= 0);
  705. }
  706. if (o.isMember("alphaMode")){
  707. static std::unordered_map<Json::String, AlphaMode> map = {
  708. {"BLEND", AlphaMode::BLEND},
  709. {"MASK", AlphaMode::MASK},
  710. {"OPAQUE", AlphaMode::OPAQUE},
  711. };
  712. const auto &v = o["alphaMode"]; check(v.isString());
  713. alphaMode = map.at(v.asString());
  714. }
  715. if (o.isMember("doubleSided")) {
  716. doubleSided = as<bool>(o["doubleSided"]);
  717. }
  718. if (o.isMember("emissiveFactor")) {
  719. emissiveFactor = asArr<double, 3>(o["emissiveFactor"]);
  720. for (const auto &v: emissiveFactor) {
  721. check(v >= 0);
  722. check(v <= 1);
  723. }
  724. }
  725. if (o.isMember("emissiveTexture")) {
  726. emissiveTexture = as<TextureInfo>(o["emissiveTexture"]);
  727. }
  728. if (o.isMember("name")) {
  729. name = as<std::string>(o["name"]);
  730. }
  731. if (o.isMember("normalTexture")) {
  732. normalTexture = as<MaterialNormalTextureInfo>(o["normalTexture"]);
  733. }
  734. if (o.isMember("occlusionTexture")) {
  735. occlusionTexture = as<MaterialOcclusionTextureInfo>(o["occlusionTexture"]);
  736. }
  737. if (o.isMember("pbrMetallicRoughness")) {
  738. pbrMetallicRoughness = as<MaterialPbrMetallicRoughness>(o["pbrMetallicRoughness"]);
  739. }
  740. }
  741. };
  742. template<> Material as(const Json::Value &o) { return o; }
  743. struct MeshPrimitive {
  744. static void enumeratedProps(const Json::Value &o, const std::string &name, std::optional<std::vector<std::size_t>> &attr) {
  745. for (std::size_t i = 0;; ++i) {
  746. const std::string s = name + "_" + std::to_string(i);
  747. if (!o.isMember(s)) break;
  748. if (i == 0) {
  749. attr = std::vector<std::size_t>();
  750. }
  751. attr->push_back(as<std::size_t>(o[s]));
  752. }
  753. }
  754. struct Attributes {
  755. std::optional<std::size_t> position, normal, tangent;
  756. std::optional<std::vector<std::size_t>> texcoord, color, joints, weights;
  757. Attributes(const Json::Value &o) {
  758. if (o.isMember("POSITION"))
  759. position = as<std::size_t>(o["POSITION"]);
  760. if (o.isMember("NORMAL"))
  761. normal = as<std::size_t>(o["NORMAL"]);
  762. if (o.isMember("TANGENT"))
  763. tangent = as<std::size_t>(o["TANGENT"]);
  764. enumeratedProps(o, "TEXCOORD", texcoord);
  765. enumeratedProps(o, "COLOR", color);
  766. enumeratedProps(o, "JOINTS", joints);
  767. enumeratedProps(o, "WEIGHTS", weights);
  768. check(joints.has_value() == weights.has_value());
  769. if (joints.has_value()) {
  770. check(joints->size() == weights->size());
  771. }
  772. check(position.has_value()
  773. || normal.has_value()
  774. || tangent.has_value()
  775. || texcoord.has_value()
  776. || color.has_value()
  777. || joints.has_value()
  778. || weights.has_value());
  779. }
  780. };
  781. Attributes attributes;
  782. std::optional<std::size_t> indices;
  783. std::optional<std::size_t> material;
  784. enum class Mode {
  785. POINTS,
  786. LINES,
  787. LINE_LOOP,
  788. LINE_STRIP,
  789. TRIANGLES,
  790. TRIANGLE_STRIP,
  791. TRIANGLE_FAN,
  792. };
  793. Mode mode;
  794. struct MorphTargets {
  795. std::optional<std::size_t> position, normal, tangent;
  796. std::optional<std::vector<std::size_t>> texcoord, color;
  797. MorphTargets(const Json::Value &o) {
  798. if (o.isMember("POSITION"))
  799. position = as<std::size_t>(o["POSITION"]);
  800. if (o.isMember("NORMAL"))
  801. normal = as<std::size_t>(o["NORMAL"]);
  802. if (o.isMember("TANGENT"))
  803. tangent = as<std::size_t>(o["TANGENT"]);
  804. enumeratedProps(o, "TEXCOORD", texcoord);
  805. enumeratedProps(o, "COLOR", color);
  806. check(position.has_value()
  807. || normal.has_value()
  808. || tangent.has_value()
  809. || texcoord.has_value()
  810. || color.has_value());
  811. }
  812. };
  813. std::optional<std::vector<MorphTargets>> targets;
  814. MeshPrimitive(const Json::Value &o)
  815. : attributes(Attributes(o["attributes"]))
  816. , mode(Mode::TRIANGLES)
  817. {
  818. check(o.isObject());
  819. if (o.isMember("indices")) {
  820. indices = as<std::size_t>(o["indices"]);
  821. }
  822. if (o.isMember("material")) {
  823. material = as<std::size_t>(o["material"]);
  824. }
  825. if (o.isMember("mode")) {
  826. static std::unordered_map<Json::UInt64, Mode> map = {
  827. {0, Mode::POINTS},
  828. {1, Mode::LINES},
  829. {2, Mode::LINE_LOOP},
  830. {3, Mode::LINE_STRIP},
  831. {4, Mode::TRIANGLES},
  832. {5, Mode::TRIANGLE_STRIP},
  833. {6, Mode::TRIANGLE_FAN},
  834. };
  835. const auto &v = o["mode"]; check(v.isUInt64());
  836. mode = map.at(v.asUInt64());
  837. }
  838. if (o.isMember("targets")) {
  839. targets = asVec<MorphTargets>(o["targets"]);
  840. check(targets->size() >= 1);
  841. }
  842. }
  843. };
  844. template<> MeshPrimitive::MorphTargets as(const Json::Value &o) { return o; }
  845. template<> MeshPrimitive as(const Json::Value &o) { return o; }
  846. struct Mesh {
  847. std::optional<std::string> name;
  848. std::vector<MeshPrimitive> primitives;
  849. std::optional<std::vector<double>> weights;
  850. Mesh(const Json::Value &o)
  851. : primitives(asVec<MeshPrimitive>(o["primitives"]))
  852. {
  853. check(o.isObject());
  854. if (o.isMember("name")) {
  855. name = as<std::string>(o["name"]);
  856. }
  857. check(primitives.size() >= 1);
  858. if (o.isMember("weights")) {
  859. weights = asVec<double>(o["weights"]);
  860. check(weights->size() >= 1);
  861. }
  862. }
  863. };
  864. template<> Mesh as(const Json::Value &o) { return o; }
  865. struct Node {
  866. std::optional<std::size_t> camera;
  867. std::optional<std::vector<std::size_t>> children;
  868. typedef std::array<double, 16> Matrix;
  869. struct TRS {
  870. std::array<double, 3> translation = {0, 0, 0};
  871. std::array<double, 4> rotation = {0, 0, 0, 1};
  872. std::array<double, 3> scale = {1, 1, 1};
  873. };
  874. std::variant<Matrix, TRS> transform;
  875. std::optional<std::size_t> mesh;
  876. std::optional<std::string> name;
  877. std::optional<std::size_t> skin;
  878. std::optional<std::vector<double>> weights;
  879. Node(const Json::Value &o)
  880. : transform(Matrix {
  881. 1, 0, 0, 0,
  882. 0, 1, 0, 0,
  883. 0, 0, 1, 0,
  884. 0, 0, 0, 1
  885. })
  886. {
  887. check(o.isObject());
  888. if (o.isMember("camera")) {
  889. camera = as<std::size_t>(o["camera"]);
  890. }
  891. if (o.isMember("children")) {
  892. children = asVec<std::size_t>(o["children"]);
  893. check(children->size() >= 1);
  894. checkDuplicateFree(*children);
  895. }
  896. bool hasTRS = o.isMember("translation") || o.isMember("rotation") || o.isMember("scale");
  897. if (o.isMember("matrix")) {
  898. check(!hasTRS);
  899. transform = asArr<double, 16>(o["matrix"]);
  900. } else if (hasTRS) {
  901. TRS trs;
  902. if (o.isMember("translation")) {
  903. trs.translation = asArr<double, 3>(o["translation"]);
  904. }
  905. if (o.isMember("rotation")) {
  906. trs.rotation = asArr<double, 4>(o["rotation"]);
  907. for (auto v: trs.rotation) {
  908. check(v >= -1);
  909. check(v <= 1);
  910. }
  911. }
  912. if (o.isMember("scale")) {
  913. trs.scale = asArr<double, 3>(o["scale"]);
  914. }
  915. transform = trs;
  916. }
  917. if (o.isMember("mesh")) {
  918. mesh = as<std::size_t>(o["mesh"]);
  919. }
  920. if (o.isMember("name")) {
  921. name = as<std::string>(o["name"]);
  922. }
  923. if (o.isMember("skin")) {
  924. check(mesh.has_value());
  925. skin = as<std::size_t>(o["skin"]);
  926. }
  927. if (o.isMember("weights")) {
  928. weights = asVec<double>(o["weights"]);
  929. check(weights->size() >= 1);
  930. }
  931. }
  932. };
  933. template<> Node as(const Json::Value &o) { return o; }
  934. struct Sampler {
  935. enum class MagFilter {
  936. NEAREST,
  937. LINEAR,
  938. };
  939. std::optional<MagFilter> magFilter;
  940. enum class MinFilter {
  941. NEAREST,
  942. LINEAR,
  943. NEAREST_MIPMAP_NEAREST,
  944. LINEAR_MIPMAP_NEAREST,
  945. NEAREST_MIPMAP_LINEAR,
  946. LINEAR_MIPMAP_LINEAR,
  947. };
  948. std::optional<MinFilter> minFilter;
  949. std::optional<std::string> name;
  950. enum class Wrap {
  951. REPEAT,
  952. CLAMP_TO_EDGE,
  953. MIRRORED_REPEAT,
  954. };
  955. Wrap wrapS;
  956. Wrap wrapT;
  957. Sampler(const Json::Value &o)
  958. : wrapS(Wrap::REPEAT)
  959. , wrapT(Wrap::REPEAT)
  960. {
  961. check(o.isObject());
  962. if (o.isMember("magFilter")) {
  963. static std::unordered_map<Json::UInt64, MagFilter> map = {
  964. {9728, MagFilter::NEAREST},
  965. {9729, MagFilter::LINEAR},
  966. };
  967. const auto &v = o["magFilter"]; check(v.isUInt64());
  968. magFilter = map.at(v.asUInt64());
  969. }
  970. if (o.isMember("minFilter")) {
  971. static std::unordered_map<Json::UInt64, MinFilter> map = {
  972. {9728, MinFilter::NEAREST},
  973. {9729, MinFilter::LINEAR},
  974. {9984, MinFilter::NEAREST_MIPMAP_NEAREST},
  975. {9985, MinFilter::LINEAR_MIPMAP_NEAREST},
  976. {9986, MinFilter::NEAREST_MIPMAP_LINEAR},
  977. {9987, MinFilter::LINEAR_MIPMAP_LINEAR},
  978. };
  979. const auto &v = o["minFilter"]; check(v.isUInt64());
  980. minFilter = map.at(v.asUInt64());
  981. }
  982. if (o.isMember("name")) {
  983. name = as<std::string>(o["name"]);
  984. }
  985. static std::unordered_map<Json::UInt64, Wrap> map = {
  986. {10497, Wrap::REPEAT},
  987. {33071, Wrap::CLAMP_TO_EDGE},
  988. {33648, Wrap::MIRRORED_REPEAT},
  989. };
  990. if (o.isMember("wrapS")) {
  991. const auto &v = o["wrapS"]; check(v.isUInt64());
  992. wrapS = map.at(v.asUInt64());
  993. }
  994. if (o.isMember("wrapT")) {
  995. const auto &v = o["wrapT"]; check(v.isUInt64());
  996. wrapT = map.at(v.asUInt64());
  997. }
  998. }
  999. };
  1000. template<> Sampler as(const Json::Value &o) { return o; }
  1001. struct Scene {
  1002. std::optional<std::string> name;
  1003. std::optional<std::vector<std::size_t>> nodes;
  1004. Scene(const Json::Value &o)
  1005. {
  1006. check(o.isObject());
  1007. if (o.isMember("name")) {
  1008. name = as<std::string>(o["name"]);
  1009. }
  1010. if (o.isMember("nodes")) {
  1011. nodes = asVec<std::size_t>(o["nodes"]);
  1012. check(nodes->size() >= 1);
  1013. checkDuplicateFree(*nodes);
  1014. }
  1015. }
  1016. };
  1017. template<> Scene as(const Json::Value &o) { return o; }
  1018. struct Skin {
  1019. std::optional<std::size_t> inverseBindMatrices;
  1020. std::vector<std::size_t> joints;
  1021. std::optional<std::string> name;
  1022. std::optional<std::size_t> skeleton;
  1023. Skin(const Json::Value &o)
  1024. : joints(asVec<std::size_t>(o["joints"]))
  1025. {
  1026. check(o.isObject());
  1027. if (o.isMember("inverseBindMatrices")) {
  1028. inverseBindMatrices = as<std::size_t>(o["inverseBindMatrices"]);
  1029. }
  1030. check(joints.size() >= 1);
  1031. checkDuplicateFree(joints);
  1032. if (o.isMember("name")) {
  1033. name = as<std::string>(o["name"]);
  1034. }
  1035. if (o.isMember("skeleton")) {
  1036. skeleton = as<std::size_t>(o["skeleton"]);
  1037. }
  1038. }
  1039. };
  1040. template<> Skin as(const Json::Value &o) { return o; }
  1041. struct Texture {
  1042. std::optional<std::string> name;
  1043. std::optional<std::size_t> sampler;
  1044. std::optional<std::size_t> source;
  1045. Texture(const Json::Value &o)
  1046. {
  1047. check(o.isObject());
  1048. if (o.isMember("name")) {
  1049. name = as<std::string>(o["name"]);
  1050. }
  1051. if (o.isMember("sampler")) {
  1052. sampler = as<std::size_t>(o["sampler"]);
  1053. }
  1054. if (o.isMember("source")) {
  1055. source = as<std::size_t>(o["source"]);
  1056. }
  1057. }
  1058. };
  1059. template<> Texture as(const Json::Value &o) { return o; }
  1060. using UriResolver = std::function<std::string(const std::string &uri)>;
  1061. static inline std::string uriError(const std::string &uri) {
  1062. // only base64 data URI support by default
  1063. throw std::runtime_error("unsupported URI: " + uri);
  1064. }
  1065. struct GlTF {
  1066. std::optional<std::vector<Accessor>> accessors;
  1067. std::optional<std::vector<Animation>> animations;
  1068. Asset asset;
  1069. std::optional<std::vector<BufferView>> bufferViews;
  1070. std::optional<std::vector<Buffer>> buffers;
  1071. std::optional<std::vector<Camera>> cameras;
  1072. std::optional<std::vector<std::string>> extensionsRequired;
  1073. std::optional<std::vector<std::string>> extensionsUsed;
  1074. std::optional<std::vector<Image>> images;
  1075. std::optional<std::vector<Material>> materials;
  1076. std::optional<std::vector<Mesh>> meshes;
  1077. std::optional<std::vector<Node>> nodes;
  1078. std::optional<std::vector<Sampler>> samplers;
  1079. std::optional<std::size_t> scene;
  1080. std::optional<std::vector<Scene>> scenes;
  1081. std::optional<std::vector<Skin>> skins;
  1082. std::optional<std::vector<Texture>> textures;
  1083. GlTF(const Json::Value &o,
  1084. const UriResolver &resolveUri = uriError,
  1085. std::optional<std::string> &&glbData = std::nullopt)
  1086. : asset(as<Asset>(o["asset"]))
  1087. {
  1088. check(o.isObject());
  1089. if (o.isMember("accessors")) {
  1090. accessors = asVec<Accessor>(o["accessors"]);
  1091. check(accessors->size() >= 1);
  1092. }
  1093. if (o.isMember("animations")) {
  1094. animations = asVec<Animation>(o["animations"]);
  1095. check(animations->size() >= 1);
  1096. }
  1097. if (o.isMember("bufferViews")) {
  1098. bufferViews = asVec<BufferView>(o["bufferViews"]);
  1099. check(bufferViews->size() >= 1);
  1100. }
  1101. if (o.isMember("buffers")) {
  1102. auto b = o["buffers"];
  1103. check(b.isArray());
  1104. std::vector<Buffer> bufs;
  1105. bufs.reserve(b.size());
  1106. for (Json::ArrayIndex i = 0; i < b.size(); ++i) {
  1107. bufs.emplace_back(b[i], resolveUri,
  1108. i == 0 ? std::move(glbData) : std::nullopt);
  1109. }
  1110. check(bufs.size() >= 1);
  1111. buffers = std::move(bufs);
  1112. }
  1113. if (o.isMember("cameras")) {
  1114. cameras = asVec<Camera>(o["cameras"]);
  1115. check(cameras->size() >= 1);
  1116. }
  1117. if (o.isMember("extensionsRequired")) {
  1118. extensionsRequired = asVec<std::string>(o["extensionsRequired"]);
  1119. check(extensionsRequired->size() >= 1);
  1120. checkDuplicateFree(*extensionsRequired);
  1121. }
  1122. if (o.isMember("extensionsUsed")) {
  1123. extensionsUsed = asVec<std::string>(o["extensionsUsed"]);
  1124. check(extensionsUsed->size() >= 1);
  1125. checkDuplicateFree(*extensionsUsed);
  1126. }
  1127. if (o.isMember("images")) {
  1128. images = asVec<Image>(o["images"]);
  1129. check(images->size() >= 1);
  1130. }
  1131. if (o.isMember("materials")) {
  1132. materials = asVec<Material>(o["materials"]);
  1133. check(materials->size() >= 1);
  1134. }
  1135. if (o.isMember("meshes")) {
  1136. meshes = asVec<Mesh>(o["meshes"]);
  1137. check(meshes->size() >= 1);
  1138. }
  1139. if (o.isMember("nodes")) {
  1140. nodes = asVec<Node>(o["nodes"]);
  1141. check(nodes->size() >= 1);
  1142. // Nodes must be a forest:
  1143. // 1. Each node should have indegree 0 or 1:
  1144. std::vector<std::size_t> indeg(nodes->size());
  1145. for (std::size_t i = 0; i < nodes->size(); ++i) {
  1146. auto children = nodes->at(i).children;
  1147. if (!children.has_value()) continue;
  1148. for (auto child : children.value()) {
  1149. ++indeg.at(child);
  1150. }
  1151. }
  1152. for (const auto deg : indeg) {
  1153. check(deg <= 1);
  1154. }
  1155. // 2. There should be no cycles:
  1156. std::vector<bool> visited(nodes->size());
  1157. std::stack<std::size_t, std::vector<std::size_t>> toVisit;
  1158. for (std::size_t i = 0; i < nodes->size(); ++i) {
  1159. // Only start DFS in roots.
  1160. if (indeg[i] > 0)
  1161. continue;
  1162. toVisit.push(i);
  1163. do {
  1164. std::size_t j = toVisit.top();
  1165. check(!visited.at(j));
  1166. visited[j] = true;
  1167. toVisit.pop();
  1168. auto children = nodes->at(j).children;
  1169. if (!children.has_value())
  1170. continue;
  1171. for (auto child : *children) {
  1172. toVisit.push(child);
  1173. }
  1174. } while (!toVisit.empty());
  1175. }
  1176. }
  1177. if (o.isMember("samplers")) {
  1178. samplers = asVec<Sampler>(o["samplers"]);
  1179. check(samplers->size() >= 1);
  1180. }
  1181. if (o.isMember("scene")) {
  1182. scene = as<std::size_t>(o["scene"]);
  1183. }
  1184. if (o.isMember("scenes")) {
  1185. scenes = asVec<Scene>(o["scenes"]);
  1186. check(scenes->size() >= 1);
  1187. }
  1188. if (o.isMember("skins")) {
  1189. skins = asVec<Skin>(o["skins"]);
  1190. check(skins->size() >= 1);
  1191. }
  1192. if (o.isMember("textures")) {
  1193. textures = asVec<Texture>(o["textures"]);
  1194. check(textures->size() >= 1);
  1195. }
  1196. // Validation
  1197. checkForall(bufferViews, [&](const BufferView &view) {
  1198. check(buffers.has_value());
  1199. const Buffer &buf = buffers->at(view.buffer);
  1200. // Be careful because of possible integer overflows.
  1201. check(view.byteOffset < buf.byteLength);
  1202. check(view.byteLength <= buf.byteLength);
  1203. check(view.byteOffset <= buf.byteLength - view.byteLength);
  1204. });
  1205. const auto checkAccessor = [&](const auto &accessor,
  1206. std::size_t bufferView, std::size_t byteOffset, std::size_t count) {
  1207. const BufferView &view = bufferViews->at(bufferView);
  1208. if (view.byteStride.has_value())
  1209. check(*view.byteStride % accessor.componentSize() == 0);
  1210. check(byteOffset < view.byteLength);
  1211. // Use division to avoid overflows.
  1212. const auto effective_byte_stride = view.byteStride.value_or(accessor.elementSize());
  1213. check(count <= (view.byteLength - byteOffset) / effective_byte_stride);
  1214. };
  1215. checkForall(accessors, [&](const Accessor &accessor) {
  1216. if (accessor.bufferView.has_value())
  1217. checkAccessor(accessor, *accessor.bufferView, accessor.byteOffset, accessor.count);
  1218. if (accessor.sparse.has_value()) {
  1219. const auto &indices = accessor.sparse->indices;
  1220. checkAccessor(indices, indices.bufferView, indices.byteOffset, accessor.sparse->count);
  1221. const auto &values = accessor.sparse->values;
  1222. checkAccessor(accessor, values.bufferView, values.byteOffset, accessor.sparse->count);
  1223. }
  1224. });
  1225. checkForall(images, [&](const Image &image) {
  1226. checkIndex(bufferViews, image.bufferView);
  1227. });
  1228. checkForall(meshes, [&](const Mesh &mesh) {
  1229. for (const auto &primitive : mesh.primitives) {
  1230. checkIndex(accessors, primitive.indices);
  1231. checkIndex(materials, primitive.material);
  1232. checkIndex(accessors, primitive.attributes.normal);
  1233. checkIndex(accessors, primitive.attributes.position);
  1234. checkIndex(accessors, primitive.attributes.tangent);
  1235. checkForall(primitive.attributes.texcoord, [&](const std::size_t &i) {
  1236. checkIndex(accessors, i);
  1237. });
  1238. checkForall(primitive.attributes.color, [&](const std::size_t &i) {
  1239. checkIndex(accessors, i);
  1240. });
  1241. checkForall(primitive.attributes.joints, [&](const std::size_t &i) {
  1242. checkIndex(accessors, i);
  1243. });
  1244. checkForall(primitive.attributes.weights, [&](const std::size_t &i) {
  1245. checkIndex(accessors, i);
  1246. });
  1247. if (primitive.material.has_value()) {
  1248. const Material &material = materials->at(primitive.material.value());
  1249. if (material.emissiveTexture.has_value()) {
  1250. check(primitive.attributes.texcoord.has_value());
  1251. check(material.emissiveTexture->texCoord < primitive.attributes.texcoord->size());
  1252. }
  1253. if (material.normalTexture.has_value()) {
  1254. check(primitive.attributes.texcoord.has_value());
  1255. check(material.normalTexture->texCoord < primitive.attributes.texcoord->size());
  1256. }
  1257. if (material.occlusionTexture.has_value()) {
  1258. check(primitive.attributes.texcoord.has_value());
  1259. check(material.occlusionTexture->texCoord < primitive.attributes.texcoord->size());
  1260. }
  1261. }
  1262. checkForall(primitive.targets, [&](const MeshPrimitive::MorphTargets &target) {
  1263. checkIndex(accessors, target.normal);
  1264. checkIndex(accessors, target.position);
  1265. checkIndex(accessors, target.tangent);
  1266. checkForall(target.texcoord, [&](const std::size_t &i) {
  1267. checkIndex(accessors, i);
  1268. });
  1269. checkForall(target.color, [&](const std::size_t &i) {
  1270. checkIndex(accessors, i);
  1271. });
  1272. });
  1273. }
  1274. });
  1275. checkForall(nodes, [&](const Node &node) {
  1276. checkIndex(cameras, node.camera);
  1277. checkIndex(meshes, node.mesh);
  1278. checkIndex(skins, node.skin);
  1279. });
  1280. checkForall(scenes, [&](const Scene &scene) {
  1281. checkForall(scene.nodes, [&](const size_t &i) {
  1282. checkIndex(nodes, i);
  1283. });
  1284. });
  1285. checkForall(skins, [&](const Skin &skin) {
  1286. checkIndex(accessors, skin.inverseBindMatrices);
  1287. for (const std::size_t &i : skin.joints)
  1288. checkIndex(nodes, i);
  1289. checkIndex(nodes, skin.skeleton);
  1290. });
  1291. checkForall(textures, [&](const Texture &texture) {
  1292. checkIndex(samplers, texture.sampler);
  1293. checkIndex(images, texture.source);
  1294. });
  1295. checkForall(animations, [&](const Animation &animation) {
  1296. for (const auto &sampler : animation.samplers) {
  1297. checkIndex(accessors, sampler.input);
  1298. const auto &accessor = accessors->at(sampler.input);
  1299. check(accessor.type == Accessor::Type::SCALAR);
  1300. check(accessor.componentType == Accessor::ComponentType::FLOAT);
  1301. checkIndex(accessors, sampler.output);
  1302. }
  1303. for (const auto &channel : animation.channels) {
  1304. checkIndex(nodes, channel.target.node);
  1305. checkIndex(animation.samplers, channel.sampler);
  1306. }
  1307. });
  1308. checkIndex(scenes, scene);
  1309. }
  1310. };
  1311. // std::span is C++ 20, so we roll our own little struct here.
  1312. template <typename T>
  1313. struct Span {
  1314. T *ptr;
  1315. uint32_t len;
  1316. bool empty() const {
  1317. return len == 0;
  1318. }
  1319. T *end() const {
  1320. return ptr + len;
  1321. }
  1322. template <typename U>
  1323. Span<U> cast() const {
  1324. return {(U *) ptr, len};
  1325. }
  1326. };
  1327. static Json::Value readJson(Span<const char> span) {
  1328. Json::CharReaderBuilder builder;
  1329. const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
  1330. Json::Value json;
  1331. Json::String err;
  1332. if (!reader->parse(span.ptr, span.end(), &json, &err))
  1333. throw std::runtime_error(std::string("invalid JSON: ") + err);
  1334. return json;
  1335. }
  1336. inline GlTF readGlb(const char *data, std::size_t len, const UriResolver &resolveUri = uriError) {
  1337. struct Chunk {
  1338. uint32_t type;
  1339. Span<const uint8_t> span;
  1340. };
  1341. struct Stream {
  1342. Span<const uint8_t> span;
  1343. bool eof() const {
  1344. return span.empty();
  1345. }
  1346. void advance(uint32_t n) {
  1347. span.len -= n;
  1348. span.ptr += n;
  1349. }
  1350. uint32_t readUint32() {
  1351. if (span.len < 4)
  1352. throw std::runtime_error("premature EOF");
  1353. uint32_t res = 0;
  1354. for (int i = 0; i < 4; ++i)
  1355. res += span.ptr[i] << (i * 8);
  1356. advance(4);
  1357. return res;
  1358. }
  1359. Chunk readChunk() {
  1360. const auto chunkLen = readUint32();
  1361. if (chunkLen % 4 != 0)
  1362. throw std::runtime_error("chunk length must be multiple of 4");
  1363. const auto chunkType = readUint32();
  1364. auto chunkPtr = span.ptr;
  1365. if (span.len < chunkLen)
  1366. throw std::runtime_error("premature EOF");
  1367. advance(chunkLen);
  1368. return {chunkType, {chunkPtr, chunkLen}};
  1369. }
  1370. };
  1371. constexpr uint32_t MAGIC_GLTF = 0x46546C67;
  1372. constexpr uint32_t MAGIC_JSON = 0x4E4F534A;
  1373. constexpr uint32_t MAGIC_BIN = 0x004E4942;
  1374. if (len > std::numeric_limits<uint32_t>::max())
  1375. throw std::runtime_error("too large");
  1376. Stream is{{(const uint8_t *) data, static_cast<uint32_t>(len)}};
  1377. const auto magic = is.readUint32();
  1378. if (magic != MAGIC_GLTF)
  1379. throw std::runtime_error("wrong magic number");
  1380. const auto version = is.readUint32();
  1381. if (version != 2)
  1382. throw std::runtime_error("wrong version");
  1383. const auto length = is.readUint32();
  1384. if (length != len)
  1385. throw std::runtime_error("wrong length");
  1386. const auto json = is.readChunk();
  1387. if (json.type != MAGIC_JSON)
  1388. throw std::runtime_error("expected JSON chunk");
  1389. std::optional<std::string> buffer;
  1390. if (!is.eof()) {
  1391. const auto chunk = is.readChunk();
  1392. if (chunk.type == MAGIC_BIN)
  1393. buffer = std::string((const char *) chunk.span.ptr, chunk.span.len);
  1394. else if (chunk.type == MAGIC_JSON)
  1395. throw std::runtime_error("unexpected chunk");
  1396. // Ignore all other chunks. We still want to validate that
  1397. // 1. These chunks are valid;
  1398. // 2. These chunks are *not* JSON or BIN chunks
  1399. while (!is.eof()) {
  1400. const auto type = is.readChunk().type;
  1401. if (type == MAGIC_JSON || type == MAGIC_BIN)
  1402. throw std::runtime_error("unexpected chunk");
  1403. }
  1404. }
  1405. return GlTF(readJson(json.span.cast<const char>()), resolveUri, std::move(buffer));
  1406. }
  1407. inline GlTF readGlTF(const char *data, std::size_t len, const UriResolver &resolveUri = uriError) {
  1408. if (len > std::numeric_limits<uint32_t>::max())
  1409. throw std::runtime_error("too large");
  1410. return GlTF(readJson({data, static_cast<uint32_t>(len)}), resolveUri);
  1411. }
  1412. }