-
Notifications
You must be signed in to change notification settings - Fork 34
/
tiny_gltf_loader.h
2667 lines (2231 loc) · 74.8 KB
/
tiny_gltf_loader.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Tiny glTF loader.
//
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2016 Syoyo Fujita and many contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Version:
// - v0.9.5 Support parsing `extras` parameter.
// - v0.9.4 Support parsing `shader`, `program` and `tecnique` thanks to
// @lukesanantonio
// - v0.9.3 Support binary glTF
// - v0.9.2 Support parsing `texture`
// - v0.9.1 Support loading glTF asset from memory
// - v0.9.0 Initial
//
// Tiny glTF loader is using following third party libraries:
//
// - picojson: C++ JSON library.
// - base64: base64 decode/encode library.
// - stb_image: Image loading library.
//
#ifndef TINY_GLTF_LOADER_H_
#define TINY_GLTF_LOADER_H_
#include <cassert>
#include <cstring>
#include <map>
#include <string>
#include <vector>
namespace tinygltf {
#define TINYGLTF_MODE_POINTS (0)
#define TINYGLTF_MODE_LINE (1)
#define TINYGLTF_MODE_LINE_LOOP (2)
#define TINYGLTF_MODE_TRIANGLES (4)
#define TINYGLTF_MODE_TRIANGLE_STRIP (5)
#define TINYGLTF_MODE_TRIANGLE_FAN (6)
#define TINYGLTF_COMPONENT_TYPE_BYTE (5120)
#define TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE (5121)
#define TINYGLTF_COMPONENT_TYPE_SHORT (5122)
#define TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT (5123)
#define TINYGLTF_COMPONENT_TYPE_INT (5124)
#define TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT (5125)
#define TINYGLTF_COMPONENT_TYPE_FLOAT (5126)
#define TINYGLTF_COMPONENT_TYPE_DOUBLE (5127)
#define TINYGLTF_TEXTURE_FILTER_NEAREST (9728)
#define TINYGLTF_TEXTURE_FILTER_LINEAR (9729)
#define TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_NEAREST (9984)
#define TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST (9985)
#define TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_LINEAR (9986)
#define TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_LINEAR (9987)
#define TINYGLTF_TEXTURE_WRAP_RPEAT (10497)
#define TINYGLTF_TEXTURE_WRAP_CLAMP_TO_EDGE (33071)
#define TINYGLTF_TEXTURE_WRAP_MIRRORED_REPEAT (33648)
// Redeclarations of the above for technique.parameters.
#define TINYGLTF_PARAMETER_TYPE_BYTE (5120)
#define TINYGLTF_PARAMETER_TYPE_UNSIGNED_BYTE (5121)
#define TINYGLTF_PARAMETER_TYPE_SHORT (5122)
#define TINYGLTF_PARAMETER_TYPE_UNSIGNED_SHORT (5123)
#define TINYGLTF_PARAMETER_TYPE_INT (5124)
#define TINYGLTF_PARAMETER_TYPE_UNSIGNED_INT (5125)
#define TINYGLTF_PARAMETER_TYPE_FLOAT (5126)
#define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC2 (35664)
#define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC3 (35665)
#define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC4 (35666)
#define TINYGLTF_PARAMETER_TYPE_INT_VEC2 (35667)
#define TINYGLTF_PARAMETER_TYPE_INT_VEC3 (35668)
#define TINYGLTF_PARAMETER_TYPE_INT_VEC4 (35669)
#define TINYGLTF_PARAMETER_TYPE_BOOL (35670)
#define TINYGLTF_PARAMETER_TYPE_BOOL_VEC2 (35671)
#define TINYGLTF_PARAMETER_TYPE_BOOL_VEC3 (35672)
#define TINYGLTF_PARAMETER_TYPE_BOOL_VEC4 (35673)
#define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT2 (35674)
#define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT3 (35675)
#define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT4 (35676)
#define TINYGLTF_PARAMETER_TYPE_SAMPLER_2D (35678)
// End parameter types
#define TINYGLTF_TYPE_VEC2 (2)
#define TINYGLTF_TYPE_VEC3 (3)
#define TINYGLTF_TYPE_VEC4 (4)
#define TINYGLTF_TYPE_MAT2 (32 + 2)
#define TINYGLTF_TYPE_MAT3 (32 + 3)
#define TINYGLTF_TYPE_MAT4 (32 + 4)
#define TINYGLTF_TYPE_SCALAR (64 + 1)
#define TINYGLTF_TYPE_VECTOR (64 + 4)
#define TINYGLTF_TYPE_MATRIX (64 + 16)
#define TINYGLTF_IMAGE_FORMAT_JPEG (0)
#define TINYGLTF_IMAGE_FORMAT_PNG (1)
#define TINYGLTF_IMAGE_FORMAT_BMP (2)
#define TINYGLTF_IMAGE_FORMAT_GIF (3)
#define TINYGLTF_TEXTURE_FORMAT_ALPHA (6406)
#define TINYGLTF_TEXTURE_FORMAT_RGB (6407)
#define TINYGLTF_TEXTURE_FORMAT_RGBA (6408)
#define TINYGLTF_TEXTURE_FORMAT_LUMINANCE (6409)
#define TINYGLTF_TEXTURE_FORMAT_LUMINANCE_ALPHA (6410)
#define TINYGLTF_TEXTURE_TARGET_TEXTURE2D (3553)
#define TINYGLTF_TEXTURE_TYPE_UNSIGNED_BYTE (5121)
#define TINYGLTF_TARGET_ARRAY_BUFFER (34962)
#define TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER (34963)
#define TINYGLTF_SHADER_TYPE_VERTEX_SHADER (35633)
#define TINYGLTF_SHADER_TYPE_FRAGMENT_SHADER (35632)
typedef enum {
NULL_TYPE = 0,
NUMBER_TYPE = 1,
INT_TYPE = 2,
BOOL_TYPE = 3,
STRING_TYPE = 4,
ARRAY_TYPE = 5,
BINARY_TYPE = 6,
OBJECT_TYPE = 7
} Type;
// Simple class to represent JSON object
class Value {
public:
typedef std::vector<Value> Array;
typedef std::map<std::string, Value> Object;
Value() : type_(NULL_TYPE) {}
explicit Value(bool b) : type_(BOOL_TYPE) { boolean_value_ = b; }
explicit Value(int i) : type_(INT_TYPE) { int_value_ = i; }
explicit Value(double n) : type_(NUMBER_TYPE) { number_value_ = n; }
explicit Value(const std::string &s) : type_(STRING_TYPE) {
string_value_ = s;
}
explicit Value(const unsigned char *p, size_t n) : type_(BINARY_TYPE) {
binary_value_.resize(n);
memcpy(binary_value_.data(), p, n);
}
explicit Value(const Array &a) : type_(ARRAY_TYPE) {
array_value_ = Array(a);
}
explicit Value(const Object &o) : type_(OBJECT_TYPE) {
object_value_ = Object(o);
}
char Type() const { return static_cast<const char>(type_); }
bool IsBool() const { return (type_ == BOOL_TYPE); }
bool IsInt() const { return (type_ == INT_TYPE); }
bool IsNumber() const { return (type_ == NUMBER_TYPE); }
bool IsString() const { return (type_ == STRING_TYPE); }
bool IsBinary() const { return (type_ == BINARY_TYPE); }
bool IsArray() const { return (type_ == ARRAY_TYPE); }
bool IsObject() const { return (type_ == OBJECT_TYPE); }
// Accessor
template <typename T>
const T &Get() const;
template <typename T>
T &Get();
// Lookup value from an array
inline const Value &Get(int idx) const {
assert(IsArray());
assert(idx >= 0);
return (static_cast<size_t>(idx) < array_value_.size())
? array_value_[static_cast<size_t>(idx)]
: null_value_;
}
// Lookup value from a key-value pair
inline const Value &Get(const std::string &key) const {
assert(IsObject());
Object::const_iterator it = object_value_.find(key);
return (it != object_value_.end()) ? it->second : null_value_;
}
size_t ArrayLen() const {
if (!IsArray()) return 0;
return array_value_.size();
}
// Valid only for object type.
bool Has(const std::string &key) const {
if (!IsObject()) return false;
Object::const_iterator it = object_value_.find(key);
return (it != object_value_.end()) ? true : false;
}
// List keys
std::vector<std::string> Keys() const {
std::vector<std::string> keys;
if (!IsObject()) return keys; // empty
for (Object::const_iterator it = object_value_.begin();
it != object_value_.end(); ++it) {
keys.push_back(it->first);
}
return keys;
}
protected:
int type_;
int int_value_;
double number_value_;
std::string string_value_;
std::vector<unsigned char> binary_value_;
Array array_value_;
Object object_value_;
bool boolean_value_;
char pad[3];
int pad0;
private:
static Value null_value_;
};
#define TINYGLTF_VALUE_GET(ctype, var) \
template <> \
inline const ctype &Value::Get<ctype>() const { \
return var; \
} \
template <> \
inline ctype &Value::Get<ctype>() { \
return var; \
}
TINYGLTF_VALUE_GET(bool, boolean_value_)
TINYGLTF_VALUE_GET(double, number_value_)
TINYGLTF_VALUE_GET(int, int_value_)
TINYGLTF_VALUE_GET(std::string, string_value_)
TINYGLTF_VALUE_GET(std::vector<unsigned char>, binary_value_)
TINYGLTF_VALUE_GET(Value::Array, array_value_)
TINYGLTF_VALUE_GET(Value::Object, object_value_)
#undef TINYGLTF_VALUE_GET
typedef struct {
std::string string_value;
std::vector<double> number_array;
} Parameter;
typedef std::map<std::string, Parameter> ParameterMap;
typedef struct {
std::string sampler;
std::string target_id;
std::string target_path;
Value extras;
} AnimationChannel;
typedef struct {
std::string input;
std::string interpolation;
std::string output;
Value extras;
} AnimationSampler;
typedef struct {
std::string name;
std::vector<AnimationChannel> channels;
std::map<std::string, AnimationSampler> samplers;
ParameterMap parameters;
Value extras;
} Animation;
typedef struct {
std::string name;
int minFilter;
int magFilter;
int wrapS;
int wrapT;
int wrapR; // TinyGLTF extension
int pad0;
Value extras;
} Sampler;
typedef struct {
std::string name;
int width;
int height;
int component;
int pad0;
std::vector<unsigned char> image;
std::string bufferView; // KHR_binary_glTF extenstion.
std::string mimeType; // KHR_binary_glTF extenstion.
Value extras;
} Image;
typedef struct {
int format;
int internalFormat;
std::string sampler; // Required
std::string source; // Required
int target;
int type;
std::string name;
Value extras;
} Texture;
typedef struct {
std::string name;
std::string technique;
ParameterMap values;
Value extras;
} Material;
typedef struct {
std::string name;
std::string buffer; // Required
size_t byteOffset; // Required
size_t byteLength; // default: 0
int target;
int pad0;
Value extras;
} BufferView;
typedef struct {
std::string bufferView;
std::string name;
size_t byteOffset;
size_t byteStride;
int componentType; // One of TINYGLTF_COMPONENT_TYPE_***
int pad0;
size_t count;
int type; // One of TINYGLTF_TYPE_***
int pad1;
std::vector<double> minValues; // Optional
std::vector<double> maxValues; // Optional
Value extras;
} Accessor;
class Camera {
public:
Camera() {}
~Camera() {}
std::string name;
bool isOrthographic; // false = perspective.
// Some common properties.
float aspectRatio;
float yFov;
float zFar;
float zNear;
};
typedef struct {
std::map<std::string, std::string> attributes; // A dictionary object of
// strings, where each string
// is the ID of the accessor
// containing an attribute.
std::string material; // The ID of the material to apply to this primitive
// when rendering.
std::string indices; // The ID of the accessor that contains the indices.
int mode; // one of TINYGLTF_MODE_***
int pad0;
Value extras; // "extra" property
} Primitive;
typedef struct {
std::string name;
std::vector<Primitive> primitives;
Value extras;
} Mesh;
class Node {
public:
Node() {}
~Node() {}
std::string camera; // camera object referenced by this node.
std::string name;
std::vector<std::string> children;
std::vector<double> rotation; // length must be 0 or 4
std::vector<double> scale; // length must be 0 or 3
std::vector<double> translation; // length must be 0 or 3
std::vector<double> matrix; // length must be 0 or 16
std::vector<std::string> meshes;
Value extras;
};
typedef struct {
std::string name;
std::vector<unsigned char> data;
Value extras;
} Buffer;
typedef struct {
std::string name;
int type;
int pad0;
std::vector<unsigned char> source;
Value extras;
} Shader;
typedef struct {
std::string name;
std::string vertexShader;
std::string fragmentShader;
std::vector<std::string> attributes;
Value extras;
} Program;
typedef struct {
int count;
int pad0;
std::string node;
std::string semantic;
int type;
int pad1;
Parameter value;
} TechniqueParameter;
typedef struct {
std::string name;
std::string program;
std::map<std::string, TechniqueParameter> parameters;
std::map<std::string, std::string> attributes;
std::map<std::string, std::string> uniforms;
Value extras;
} Technique;
typedef struct {
std::string generator;
std::string version;
std::string profile_api;
std::string profile_version;
bool premultipliedAlpha;
char pad[7];
Value extras;
} Asset;
class Scene {
public:
Scene() {}
~Scene() {}
std::map<std::string, Accessor> accessors;
std::map<std::string, Animation> animations;
std::map<std::string, Buffer> buffers;
std::map<std::string, BufferView> bufferViews;
std::map<std::string, Material> materials;
std::map<std::string, Mesh> meshes;
std::map<std::string, Node> nodes;
std::map<std::string, Texture> textures;
std::map<std::string, Image> images;
std::map<std::string, Shader> shaders;
std::map<std::string, Program> programs;
std::map<std::string, Technique> techniques;
std::map<std::string, Sampler> samplers;
std::map<std::string, std::vector<std::string> > scenes; // list of nodes
std::string defaultScene;
Asset asset;
Value extras;
};
enum SectionCheck {
NO_REQUIRE = 0x00,
REQUIRE_SCENE = 0x01,
REQUIRE_SCENES = 0x02,
REQUIRE_NODES = 0x04,
REQUIRE_ACCESSORS = 0x08,
REQUIRE_BUFFERS = 0x10,
REQUIRE_BUFFER_VIEWS = 0x20,
REQUIRE_ALL = 0x3f
};
class TinyGLTFLoader {
public:
TinyGLTFLoader() : bin_data_(NULL), bin_size_(0), is_binary_(false) {
pad[0] = pad[1] = pad[2] = pad[3] = pad[4] = pad[5] = pad[6] = 0;
}
~TinyGLTFLoader() {}
/// Loads glTF ASCII asset from a file.
/// Returns false and set error string to `err` if there's an error.
bool LoadASCIIFromFile(Scene *scene, std::string *err,
const std::string &filename,
unsigned int check_sections = REQUIRE_ALL);
/// Loads glTF ASCII asset from string(memory).
/// `length` = strlen(str);
/// Returns false and set error string to `err` if there's an error.
bool LoadASCIIFromString(Scene *scene, std::string *err, const char *str,
const unsigned int length,
const std::string &base_dir,
unsigned int check_sections = REQUIRE_ALL);
/// Loads glTF binary asset from a file.
/// Returns false and set error string to `err` if there's an error.
bool LoadBinaryFromFile(Scene *scene, std::string *err,
const std::string &filename,
unsigned int check_sections = REQUIRE_ALL);
/// Loads glTF binary asset from memory.
/// `length` = strlen(str);
/// Returns false and set error string to `err` if there's an error.
bool LoadBinaryFromMemory(Scene *scene, std::string *err,
const unsigned char *bytes,
const unsigned int length,
const std::string &base_dir = "",
unsigned int check_sections = REQUIRE_ALL);
private:
/// Loads glTF asset from string(memory).
/// `length` = strlen(str);
/// Returns false and set error string to `err` if there's an error.
bool LoadFromString(Scene *scene, std::string *err, const char *str,
const unsigned int length, const std::string &base_dir,
unsigned int check_sections);
const unsigned char *bin_data_;
size_t bin_size_;
bool is_binary_;
char pad[7];
};
} // namespace tinygltf
#endif // TINY_GLTF_LOADER_H_
#ifdef TINYGLTF_LOADER_IMPLEMENTATION
#include <algorithm>
//#include <cassert>
#include <fstream>
#include <sstream>
#ifdef __clang__
// Disable some warnings for external files.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wfloat-equal"
#pragma clang diagnostic ignored "-Wexit-time-destructors"
#pragma clang diagnostic ignored "-Wconversion"
#pragma clang diagnostic ignored "-Wold-style-cast"
#pragma clang diagnostic ignored "-Wdouble-promotion"
#pragma clang diagnostic ignored "-Wglobal-constructors"
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
#pragma clang diagnostic ignored "-Wpadded"
#ifdef __APPLE__
#if __clang_major__ >= 8 && __clang_minor__ >= 1
#pragma clang diagnostic ignored "-Wcomma"
#endif
#else // __APPLE__
#if (__clang_major__ >= 4) || (__clang_major__ >= 3 && __clang_minor__ > 8)
#pragma clang diagnostic ignored "-Wcomma"
#endif
#endif // __APPLE__
#endif
#define PICOJSON_USE_INT64
#include "./picojson.h"
#include "./stb_image.h"
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef _WIN32
#include <Windows.h>
#else
#include <wordexp.h>
#endif
#if defined(__sparcv9)
// Big endian
#else
#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
#define TINYGLTF_LITTLE_ENDIAN 1
#endif
#endif
namespace tinygltf {
static void swap4(unsigned int *val) {
#ifdef TINYGLTF_LITTLE_ENDIAN
(void)val;
#else
unsigned int tmp = *val;
unsigned char *dst = reinterpret_cast<unsigned char *>(val);
unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
dst[0] = src[3];
dst[1] = src[2];
dst[2] = src[1];
dst[3] = src[0];
#endif
}
static bool FileExists(const std::string &abs_filename) {
bool ret;
#ifdef _WIN32
FILE *fp;
errno_t err = fopen_s(&fp, abs_filename.c_str(), "rb");
if (err != 0) {
return false;
}
#else
FILE *fp = fopen(abs_filename.c_str(), "rb");
#endif
if (fp) {
ret = true;
fclose(fp);
} else {
ret = false;
}
return ret;
}
static std::string ExpandFilePath(const std::string &filepath) {
#ifdef _WIN32
DWORD len = ExpandEnvironmentStringsA(filepath.c_str(), NULL, 0);
char *str = new char[len];
ExpandEnvironmentStringsA(filepath.c_str(), str, len);
std::string s(str);
delete[] str;
return s;
#else
#if defined(TARGET_OS_IPHONE) || defined(TARGET_IPHONE_SIMULATOR)
// no expansion
std::string s = filepath;
#else
std::string s;
wordexp_t p;
if (filepath.empty()) {
return "";
}
// char** w;
int ret = wordexp(filepath.c_str(), &p, 0);
if (ret) {
// err
s = filepath;
return s;
}
// Use first element only.
if (p.we_wordv) {
s = std::string(p.we_wordv[0]);
wordfree(&p);
} else {
s = filepath;
}
#endif
return s;
#endif
}
static std::string JoinPath(const std::string &path0,
const std::string &path1) {
if (path0.empty()) {
return path1;
} else {
// check '/'
char lastChar = *path0.rbegin();
if (lastChar != '/') {
return path0 + std::string("/") + path1;
} else {
return path0 + path1;
}
}
}
static std::string FindFile(const std::vector<std::string> &paths,
const std::string &filepath) {
for (size_t i = 0; i < paths.size(); i++) {
std::string absPath = ExpandFilePath(JoinPath(paths[i], filepath));
if (FileExists(absPath)) {
return absPath;
}
}
return std::string();
}
// std::string GetFilePathExtension(const std::string& FileName)
//{
// if(FileName.find_last_of(".") != std::string::npos)
// return FileName.substr(FileName.find_last_of(".")+1);
// return "";
//}
static std::string GetBaseDir(const std::string &filepath) {
if (filepath.find_last_of("/\\") != std::string::npos)
return filepath.substr(0, filepath.find_last_of("/\\"));
return "";
}
// std::string base64_encode(unsigned char const* , unsigned int len);
std::string base64_decode(std::string const &s);
/*
base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger rene.nyffenegger@adp-gmbh.ch
*/
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wexit-time-destructors"
#pragma clang diagnostic ignored "-Wglobal-constructors"
#pragma clang diagnostic ignored "-Wsign-conversion"
#pragma clang diagnostic ignored "-Wconversion"
#endif
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_decode(std::string const &encoded_string) {
int in_len = static_cast<int>(encoded_string.size());
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && (encoded_string[in_] != '=') &&
is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_];
in_++;
if (i == 4) {
for (i = 0; i < 4; i++)
char_array_4[i] =
static_cast<unsigned char>(base64_chars.find(char_array_4[i]));
char_array_3[0] =
(char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] =
((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++) ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j < 4; j++) char_array_4[j] = 0;
for (j = 0; j < 4; j++)
char_array_4[j] =
static_cast<unsigned char>(base64_chars.find(char_array_4[j]));
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] =
((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
static bool LoadExternalFile(std::vector<unsigned char> *out, std::string *err,
const std::string &filename,
const std::string &basedir, size_t reqBytes,
bool checkSize) {
out->clear();
std::vector<std::string> paths;
paths.push_back(basedir);
paths.push_back(".");
std::string filepath = FindFile(paths, filename);
if (filepath.empty()) {
if (err) {
(*err) += "File not found : " + filename + "\n";
}
return false;
}
std::ifstream f(filepath.c_str(), std::ifstream::binary);
if (!f) {
if (err) {
(*err) += "File open error : " + filepath + "\n";
}
return false;
}
f.seekg(0, f.end);
size_t sz = static_cast<size_t>(f.tellg());
std::vector<unsigned char> buf(sz);
f.seekg(0, f.beg);
f.read(reinterpret_cast<char *>(&buf.at(0)),
static_cast<std::streamsize>(sz));
f.close();
if (checkSize) {
if (reqBytes == sz) {
out->swap(buf);
return true;
} else {
std::stringstream ss;
ss << "File size mismatch : " << filepath << ", requestedBytes "
<< reqBytes << ", but got " << sz << std::endl;
if (err) {
(*err) += ss.str();
}
return false;
}
}
out->swap(buf);
return true;
}
static bool LoadImageData(Image *image, std::string *err, int req_width,
int req_height, const unsigned char *bytes,
int size) {
int w, h, comp;
unsigned char *data = stbi_load_from_memory(bytes, size, &w, &h, &comp, 0);
if (!data) {
if (err) {
(*err) += "Unknown image format.\n";
}
return false;
}
if (w < 1 || h < 1) {
free(data);
if (err) {
(*err) += "Unknown image format.\n";
}
return false;
}
if (req_width > 0) {
if (req_width != w) {
free(data);
if (err) {
(*err) += "Image width mismatch.\n";
}
return false;
}
}
if (req_height > 0) {
if (req_height != h) {
free(data);
if (err) {
(*err) += "Image height mismatch.\n";
}
return false;
}
}
image->width = w;
image->height = h;
image->component = comp;
image->image.resize(static_cast<size_t>(w * h * comp));
std::copy(data, data + w * h * comp, image->image.begin());
free(data);
return true;
}
static bool IsDataURI(const std::string &in) {
std::string header = "data:application/octet-stream;base64,";
if (in.find(header) == 0) {
return true;
}
header = "data:image/png;base64,";
if (in.find(header) == 0) {
return true;
}
header = "data:image/jpeg;base64,";
if (in.find(header) == 0) {
return true;
}
header = "data:text/plain;base64,";
if (in.find(header) == 0) {
return true;
}
return false;
}
static bool DecodeDataURI(std::vector<unsigned char> *out,
const std::string &in, size_t reqBytes,
bool checkSize) {
std::string header = "data:application/octet-stream;base64,";
std::string data;
if (in.find(header) == 0) {
data = base64_decode(in.substr(header.size())); // cut mime string.
}
if (data.empty()) {
header = "data:image/jpeg;base64,";
if (in.find(header) == 0) {
data = base64_decode(in.substr(header.size())); // cut mime string.
}
}
if (data.empty()) {
header = "data:image/png;base64,";
if (in.find(header) == 0) {
data = base64_decode(in.substr(header.size())); // cut mime string.
}
}
if (data.empty()) {
header = "data:text/plain;base64,";
if (in.find(header) == 0) {
data = base64_decode(in.substr(header.size()));
}
}
if (data.empty()) {