forked from syoyo/tinyobjloader-c
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tinyobj_loader_c.h
3282 lines (3020 loc) · 96.6 KB
/
tinyobj_loader_c.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
/* About: License
* The MIT License (MIT)
*
* Copyright (c) 2016-2019 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.
*/
#ifndef TINOBJ_LOADER_C_H_
#define TINOBJ_LOADER_C_H_
/* @todo { Remove stddef dependency. size_t? } */
#include <stddef.h>
/* Constant: TINYOBJ_LOADER_C_IMPLEMENTATION
* Constant used to mark the .c file that holds the implementation of tinyobj
*
* Only *one* file should have this definition!
*/
/* Constant: TINYOBJ_USE_UTHASH
* Use <UThash: http://troydhanson.github.io/uthash/> hashtable implementation
* instead of tinyobj's implementation
*/
//#define TINYOBJ_USE_UTHASH
/* Constant: TINYOBJ_ENABLE_OLDER_ATTRIBUTE
*
* Enable use of older attribute type for objects (deprecated)
*
* See:
* - <COMPATtinyobj_attrib_t>
* - <tinyobj_new2old>
* - <tinyobj_attrib_freeCOMPAT>
*/
#define TINYOBJ_ENABLE_OLDER_ATTRIBUTE
/* Constant: TINYOBJ_FLAG_TRIANGULATE
*
* Should the faces be triangulated upon loading
* When triangulating we parse the vertices as if they were part of
* a triangle fan, so every three indices the next is always the first
* triplet of this face
*
* See:
* <tinyobj_obj_parse_face>
*/
#define TINYOBJ_FLAG_TRIANGULATE (1 << 0)
/* Constant: TINYOBJ_INVALID_INDEX
*
* Invalid vertex index used when referencing vertices in couples/tuples
*
* See:
* - <fixIndex>
* - <parseRawTriple>
* - <tinyobj_vertex_index_t>
*/
#define TINYOBJ_INVALID_INDEX (0x80000000)
/* Constants: Return codes
*
* TINYOBJ_NO_COMMAND - No command
* TINYOBJ_SUCCESS - Success
* TINYOBJ_ERROR_NOT_SET - Default error
* TINYOBJ_ERROR_MEMORY - Memory failure
* TINYOBJ_ERROR_EMPTY - Empty file
* TINYOBJ_ERROR_FILE_OPERATION - Failed file operation
* TINYOBJ_ERROR_INVALID_PARAMETER - Invalid parameter (function)
* TINYOBJ_ERROR_UNKNOWN_PARAMETER - Unknown parameter for object/material
* TINYOBJ_ERROR_MALFORMED_PARAMETER - Malformed parameter for object/material
*/
#define TINYOBJ_NO_COMMAND (1)
#define TINYOBJ_SUCCESS (0)
#define TINYOBJ_ERROR_NOT_SET (-1)
#define TINYOBJ_ERROR_MEMORY (-2)
#define TINYOBJ_ERROR_EMPTY (-3)
#define TINYOBJ_ERROR_FILE_OPERATION (-4)
#define TINYOBJ_ERROR_INVALID_PARAMETER (-5)
#define TINYOBJ_ERROR_UNKNOWN_PARAMETER (-6)
#define TINYOBJ_ERROR_MALFORMED_PARAMETER (-7)
/* Constants: Dynamic array basic parameters
*
* Initial array lengths and growth factors
*
* TINYOBJ_POINT_INITIAL_COUNT - Point array initial length
* TINYOBJ_POINT_GROWTH_FACTOR - Point array growth factor
* TINYOBJ_COUPLE_INITIAL_COUNT - Couple (line) array initial length
* TINYOBJ_COUPLE_GROWTH_FACTOR - Couple (line) array growth factor
* TINYOBJ_TRIPLET_INITIAL_COUNT - Triplet (face) array initial length
* TINYOBJ_TRIPLET_GROWTH_FACTOR - Triplet (face) array growth factor
* TINYOBJ_MATERIAL_INITIAL_COUNT - Material array initial length
* TINYOBJ_MATERIAL_GROWTH_FACTOR - Material array growth factor
*/
#define TINYOBJ_POINT_INITIAL_COUNT (16)
#define TINYOBJ_POINT_GROWTH_FACTOR (2)
#define TINYOBJ_COUPLE_INITIAL_COUNT (16)
#define TINYOBJ_COUPLE_GROWTH_FACTOR (2)
#define TINYOBJ_TRIPLET_INITIAL_COUNT (16)
#define TINYOBJ_TRIPLET_GROWTH_FACTOR (2)
#define TINYOBJ_MATERIAL_INITIAL_COUNT (2)
#define TINYOBJ_MATERIAL_GROWTH_FACTOR (2)
/***********************************************************************************************
* Group: Vertex data
***********************************************************************************************/
/* Structure: tinyobj_vertex_t
*
* Geometric vertex (v)
* Specifies a geometric vertex and its x y z coordinates. Rational
* curves and surfaces require a fourth homogeneous coordinate, also
* called the weight.
* > v x y z w
*
* Fields:
*
* x - x coordinate
* y - y coordinate
* z - z coordinate
* weight - (Rational curves/surfaces) Weight (default: 1.0f)
*/
typedef struct s_tinyobj_vertex {
float x, y, z; //< Coordinates
float weight; //< (Rational curves/surfaces) Weight (default: 1.0f)
} tinyobj_vertex_t;
/* Structure: tinyobj_vertex_normal_t
*
* Vertex normal (vn)
* Specifies a normal vector with components i, j, and k
* > vn i j k
*
* Fields:
*
* i - i coordinate
* j - j coordinate
* k - k coordinate
*/
typedef struct s_tinyobj_vertex_normal {
float i, j, k; //< Coordinates
} tinyobj_vertex_normal_t;
/* Structure: tinyobj_vertex_texture_t
*
* Texture vertex (vt)
* Specifies a texture vertex and its coordinates
* > vt u v w
*
* Fields:
*
* u - Horizontal direction
* v - (2D and 3D) Vertical direction (Default: 0)
* w - (3D) Depth (Default: 0)
*/
typedef struct s_tinyobj_vertex_texture {
float u; //< Horizontal direction
float v; //< (2D and 3D) Vertical direction (Default: 0)
float w; //< (3D) Depth (Default: 0)
} tinyobj_vertex_texture_t;
/* Structure: tinyobj_vertex_param_t
*
* Parameter space vertex (vp)
* Specifies a point in the parameter space of a curve or surface.
* > vp u v w
*
* Fields:
*
* u - (1D) Space control point
* v - (2D) Space control point
* weight - (Rational trimming curves) Weight (default: 0)
*/
typedef struct s_tinyobj_vertex_param {
float u, v;
float weight;
} tinyobj_vertex_param_t;
/***********************************************************************************************
* Group: Element data
* Polygonal and free-form geometry
***********************************************************************************************/
/* Structure: tinyobj_vertex_index_t
* Indices for each vertex type, used for triplets in faces
* See:
* <tinyobj_face_t>
*
* Fields:
*
* v_idx - Geometric vertex index
* vt_idx - Texture vertex index
* vn_idx - Normal vertex index
*/
typedef struct {
int v_idx, vt_idx, vn_idx;
} tinyobj_vertex_index_t;
/* Structure: tinyobj_point_t
* Point (p)
* Specifies a point element and its vertex
* > p v1 v2 v3
*
* Fields:
*
* v_idx - List of vertices
* count - Point count
* length - List length
*/
typedef struct s_tinyobj_point {
int *v_idx; //< List of vertices
size_t count; //< Point count
size_t length; //< List length
} tinyobj_point_t;
/* Structure: tinyobj_line_t
* Line (l)
* Specifies a line and its vertex reference numbers
* > l v1/vt1 v2/vt2 v3/vt3
*
* Fields:
*
* couple_list - List of couples contained in this line
* count - Count of couples
* length - Total length of couple list
*/
typedef struct s_tinyobj_line {
/* Structure: tinyobj_line_t.s_line_vertex_index
* List of couples
*
* Fields:
*
* v_idx - Geometric vertex
* vt_idx - Texture vertex (optional)
*/
struct s_line_vertex_index {
int v_idx, //< Geometric Vertex
vt_idx; //< Texture Vertex (optional)
} * couple_list;
size_t count; //< Count of couples
size_t length; //< Length of couple list
} tinyobj_line_t;
/* Structure: tinyobj_face_t
* Face (f)
* Specifies a face element and its vertex reference number
* > f v1/vt1/vn1 v2/vt2/vn2
* > fo (deprecated)
*
* Fields:
*
* triplet list - A list of triplets contained in this face
*
* *v* Geometric vertex (minimum of 3)
*
* *vt* Texture vertex (optional)
*
* *vn* Vertex normal (optional)
*
* When an index is empty it is equal to <TINYOBJ_INVALID_INDEX>
* count - Count of triplets
* length - Length of triplet list
* triangle_count - Number of triangles in this face
* material_id - Material to be applied to this face (defaults to -1)
* smoothing_id - Smoothing group to be applied to this face (defaults to 0)
*/
typedef struct s_tinyobj_face {
tinyobj_vertex_index_t *triplet_list;
unsigned int count; //< Count of triplets
unsigned int length; //< Length of triplet list
unsigned int triangle_count; //< Number of triangles in this face
int material_id; //< Material to be applied to this face (defaults to -1)
int smoothing_id; //< Smoothing group to be applied to this face (defaults to 0)
} tinyobj_face_t;
/* Structure: tinyobj_coefficient_t
* RGB Color coefficient information used in materials
* <tinyobj_material_t>
*/
typedef struct s_coefficient_information {
float r, g, b;
} tinyobj_coefficient_t;
/* Structure: tinyobj_material_t
* Material attribute
* <.mtl format: http://paulbourke.net/dataformats/mtl/>
*
* Fields:
*
* name - Material name
* ambient - Ambient color coefficient (reflectivity)
* diffuse - Diffuse color coefficient (reflectivity)
* specular - Specular color coefficient (reflectivity)
* transmittance - Transmittance color coefficient (reflectivity)
* emission - Emission color coefficient (reflectivity)
* shininess - Specular exponent
* ior - Index Of Refraction (ior) 'optical density'
* dissolve - Non-transparency to be alpha 'dissolve' (0.0f transparent-1.0f opaque)
* illum - Illumination model (0-10)
* ambient_texname - map_Ka
* diffuse_texname - map_Kd
* specular_texname - map_Ks
* specular_highlight_texname - map_Ns
* bump_texname - map_bump, bump
* displacement_texname - disp
* alpha_texname - map_d
*/
typedef struct s_tinyobj_material {
char *name; //< Name
/**
* Color coefficients (reflectivity)
**/
tinyobj_coefficient_t ambient;
tinyobj_coefficient_t diffuse;
tinyobj_coefficient_t specular;
tinyobj_coefficient_t transmittance;
tinyobj_coefficient_t emission;
float shininess; //< Specular exponent
float ior; //< Index Of Refraction (ior) 'optical density'
float dissolve; //< Non-transparency to be alpha 'dissolve' (0.0f transparent -> 1.0f opaque)
int illum; //< Illumination model (0 - 10)
char *ambient_texname; /* map_Ka */
char *diffuse_texname; /* map_Kd */
char *specular_texname; /* map_Ks */
char *specular_highlight_texname; /* map_Ns */
char *bump_texname; /* map_bump, bump */
char *displacement_texname; /* disp */
char *alpha_texname; /* map_d */
} tinyobj_material_t;
/* Structure: tinyobj_shape_t
* Shapes contained in a given attribute
*
* Fields:
*
* name - Group name or object name
* face_offset - Face offset of this shape (starting point)
* length - Length of this shape (ending point)
*/
typedef struct s_tinyobj_shape {
char *name;
size_t face_offset;
size_t length;
} tinyobj_shape_t;
/* Structure: tinyobj_attrib_t
* Object attributes
* <.obj format: http://paulbourke.net/dataformats/obj/>
*
* Fields:
*
* v - Geometric vertices
* v_count - Geometric vertex count
* vn - Vertex normals
* vn_count - Vertex normal count
* vt - Texture vertices
* vt_count - Texture vertex count
* vp - Parameter space vertices
* vp_count - Parameter space vertex count
* f - Object faces
* f_count - Face count
* triangle_count_total - Total count of triangles
* l - Lines
* l_count - Line count
* p - Points
*/
typedef struct s_tinyobj_attrib {
tinyobj_vertex_t *v; //< Geometric vertices
size_t v_count; //< Geometric vertex count
tinyobj_vertex_normal_t *vn; //< Vertex normals
size_t vn_count; //< Vertex normal count
tinyobj_vertex_texture_t *vt; //< Texture vertices
size_t vt_count; //< Texture vertex count
tinyobj_vertex_param_t *vp; //< Parameter space vertices
size_t vp_count; //< Parameter space vertex count
tinyobj_face_t *f; //< Object faces
size_t f_count; //< Face count
size_t triangle_count_total; //< Total count of triangles
tinyobj_line_t *l; //< Lines
size_t l_count; //< Line count
tinyobj_point_t p; //< Points
} tinyobj_attrib_t;
#ifdef TINYOBJ_ENABLE_OLDER_ATTRIBUTE
#ifdef _MSC_VER
#pragma message( \
"warning: Using deprecated attribute type in TINYOBJ (TINYOBJ_ENABLE_OLDER_ATTRIBUTE)")
#else
#warning \
"Using deprecated attribute type in TINYOBJ (TINYOBJ_ENABLE_OLDER_ATTRIBUTE)"
#endif
/* Structure: COMPATtinyobj_attrib_t
* Object attributes *(deprecated)*
*
* Fields:
*
* vertices - Array of geometric vertices (x0, y0, z0, x1, y1, z1, ...)
* num_vertices - Number of vertices in 'vertices' (the actual array length is num_vertices*3)
* normals - Array of vertex normals (i0, j0, k0, i1, j1, k1, ...)
* num_normals - Number of vertices in 'normals' (the actual array length is num_normals*3)
* texcoords - Array of texture vertices (u0, w0, u1, w1, ...)
* num_texcoords - Number of vertices in 'texcoords' (the actual array length is num_normals*2)
* faces - Array of faces (containing <tinyobj_vertex_index_t> information)
* num_faces - Length of 'faces'
* face_num_verts - Array of number of vertices in each face (3 for triangulated faces)
* num_face_num_verts - Total number of triangles in this object (length of face_num_verts)
* material_ids - Array with the id of the material for each face (length is num_faces)
**/
typedef struct {
unsigned int num_vertices;
unsigned int num_normals;
unsigned int num_texcoords;
unsigned int num_faces;
unsigned int num_face_num_verts;
int pad0;
float *vertices;
float *normals;
float *texcoords;
tinyobj_vertex_index_t *faces;
int *face_num_verts;
int *material_ids;
} COMPATtinyobj_attrib_t;
int tinyobj_new2old(tinyobj_attrib_t *attrib,
COMPATtinyobj_attrib_t *out_attrib);
void tinyobj_attrib_free_compat(COMPATtinyobj_attrib_t *attrib);
#endif // TINYOBJ_ENABLE_OLDER_ATTRIBUTE
int tinyobj_parse_mtl_file(tinyobj_material_t **materials_out,
unsigned int *num_materials_out,
const char *filename);
void tinyobj_material_free(tinyobj_material_t *materials,
unsigned int num_materials);
void tinyobj_shape_free(tinyobj_shape_t *shapes, unsigned int num_shapes);
void tinyobj_attrib_free(tinyobj_attrib_t *attrib);
int tinyobj_parse_obj(tinyobj_attrib_t *attrib, tinyobj_shape_t **shapes,
unsigned int *num_shapes,
tinyobj_material_t **materials_out,
unsigned int *num_materials_out, const char *buf,
size_t len, unsigned int flags);
#ifdef TINYOBJ_LOADER_C_IMPLEMENTATION
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h> // atoi
#include <string.h>
#if defined(TINYOBJ_MALLOC) && defined(TINYOBJ_REALLOC) && \
defined(TINYOBJ_CALLOC) && defined(TINYOBJ_FREE)
/* ok */
#elif !defined(TINYOBJ_MALLOC) && !defined(TINYOBJ_REALLOC) && \
!defined(TINYOBJ_CALLOC) && !defined(TINYOBJ_FREE)
/* ok */
#else
#error \
"Must define all or none of TINYOBJ_MALLOC, TINYOBJ_REALLOC, TINYOBJ_CALLOC and TINYOBJ_FREE."
#endif
#ifndef TINYOBJ_MALLOC
#define TINYOBJ_MALLOC malloc
#define TINYOBJ_REALLOC realloc
#define TINYOBJ_CALLOC calloc
#define TINYOBJ_FREE free
#endif
#ifdef TINYOBJ_USE_UTHASH
#include <uthash.h>
#endif
#ifdef _MSC_VER
#define __func__ __FUNCTION__
#endif
/***********************************************************************************************
* Group: String handling
***********************************************************************************************/
/* Functions: String handling macros
*
* IS_SPACE - Is this character a spacing character ' ' or '\t'
* IS_DIGIT - Is this character a digit
* IS_NEW_LINE - Is this character a new line character '\r','\n','\0'
*/
#define IS_SPACE(x) (((x) == ' ') || ((x) == '\t'))
#define IS_DIGIT(x) ((unsigned int)((x) - '0') < (unsigned int)(10))
#define IS_NEW_LINE(x) (((x) == '\r') || ((x) == '\n') || ((x) == '\0'))
/* Function: is_line_ending
* Is given line ending in this character?
*
* Returns:
* True if line is ending
**/
static int is_line_ending(const char *p, size_t i, size_t end_i) {
if (p[i] == '\0') return 1;
if (p[i] == '\n') return 1; // this includes \r\n
if (p[i] == '\r') {
if (((i + 1) < end_i) && (p[i + 1] != '\n')) { // detect only \r case
return 1;
}
}
return 0;
}
/* Function: skip_space
* Skips the next spacing characters in given token
*/
static void skip_space(const char **token) {
while ((*token)[0] == ' ' || (*token)[0] == '\t') {
if ((*token)[0] == '\0') return;
(*token)++;
}
}
/* Function: skip_space_and_cr
* Skips the next spacing characters and also carriage return in given token
*/
static void skip_space_and_cr(const char **token) {
while ((*token)[0] == ' ' || (*token)[0] == '\t' || (*token)[0] == '\r') {
if ((*token)[0] == '\0') return;
(*token)++;
}
}
/* Function: length_until_space
* Calculates and returns the length until next space character in this token
*
* Parameters:
*
* token - Token to be used
* n - Maximum number of characters to count
*
* Returns:
*
* Length until next space character
*/
static size_t length_until_space(const char *token, size_t n) {
size_t len = 0;
for (len = 0; len < n - 1; len++) {
if (token[len] == '\n' || token[len] == ' ' || token[len] == '\t' ||
token[len] == '\r')
break;
}
return len;
}
/* Function: until_space
* Skips the next spacing characters
* > '\0',' ', '\t', '\r'
*/
static int until_space(const char *token) {
const char *p = token;
while (p[0] != '\0' && p[0] != ' ' && p[0] != '\t' && p[0] != '\r') {
p++;
}
return (int)(p - token);
}
/* Function: until_space_cr_slash
* Skips the next characters in given token
* > '\0','/', ' ', '\t', '\r'
*/
static void until_space_cr_slash(const char **token) {
while ((*token)[0] != '\0' && (*token)[0] != '/' && (*token)[0] != ' ' &&
(*token)[0] != '\t' && (*token)[0] != '\r')
(*token)++;
}
/* Function: length_until_newline_comment_space
*
* Returns the length until the next characters:
* > \n \r\n \0 ' ' \t #
*
* Parameters:
* token - Buffer
* n - Maximum number of characters to count
*
* Returns:
*
* Length until next character
*/
static size_t length_until_newline_comment_space(const char *token, size_t n) {
size_t len = 0;
for(len = 0; len < n-1; len++) {
if(token[len] == '\n')
break;
if((token[len] == '\r') && ((len < (n - 2)) && (token[len + 1] != '\n')))
break;
if(token[len] == '\0' || token[len] == ' ' || token[len] == '\t' || token[len] == '#')
break;
}
return len;
}
/* Function: length_until_line_feed
*
* Returns the length until the next line feed
*
* *Assumes token[n-1] = '\0'*
*
* Parameters:
* token - Buffer
* n - Maximum number of characters to count
*/
static size_t length_until_line_feed(const char *token, size_t n) {
size_t len = 0;
for (len = 0; len < n; len++) {
if ((token[len] == '\n') || (token[len] == '\r')) break;
}
return len;
}
/* Function: strdup_ml
* Duplicates 'max_length' characters of given string
* (strdup with max length specified)
*
* Parameters:
*
* s - String to be duplicated
* max_length - Maximum length to be duplicated
*
* Returns:
*
* Duplicated string (*should be freed by the caller*)
*/
static char *strdup_ml(const char *s, size_t max_length) {
char *d;
size_t len;
if (s == NULL) return NULL;
/* Do not consider CRLF line ending(#19) */
len = length_until_line_feed(s, max_length);
/* len = strlen(s); */
/* trim line ending and append '\0' */
d = TINYOBJ_MALLOC(len + 1); /* + '\0' */
memcpy(d, s, len);
d[len] = '\0';
return d;
}
#ifndef strndup
/* Function: strndup
* strndup implementation for non-GNU compliant compilers
*/
char *strndup(const char *s, size_t len) {
char *d;
size_t slen;
if (s == NULL || len == 0) return NULL;
d = TINYOBJ_MALLOC(len + 1); /* + '\0' */
if (d == NULL) return NULL;
slen = strlen(s);
if (slen < len) {
memcpy(d, s, slen);
d[slen] = '\0';
} else {
memcpy(d, s, len);
d[len] = '\0';
}
return d;
}
#endif
/* Function: dynamic_fgets
* fgets with a dynamic buffer
*/
static char *dynamic_fgets(char **buf, int *size, FILE *file) {
char *offset;
char *ret;
int old_size;
if (!(ret = fgets(*buf, (int)*size, file))) {
return ret;
}
if (NULL != strchr(*buf, '\n')) {
return ret;
}
do {
old_size = *size;
*size *= 2;
*buf = TINYOBJ_REALLOC(*buf, *size);
offset = &((*buf)[old_size - 1]);
ret = fgets(offset, (int)(old_size + 1), file);
} while (ret && (NULL == strchr(*buf, '\n')));
return ret;
}
/***********************************************************************************************
* Group: Triplet handling
***********************************************************************************************/
/* Function: fixIndex
*
* Converts given absolute index, from triplet to zero-base, supports relative
* indices
*
* See:
*
* - <tinyobj_vertex_index_t>
* - <parseRawTriple>
* - <tinyobj_attrib_construct>
*
*
* Parameters:
*
* idx - Index to be converted
* n - Position of this couple/tuple regarding to the vertex type of this index
*
* Returns:
*
* - Fixed index value that's able to be used when accessing vertex arrays
* - <TINYOBJ_INVALID_INDEX> when there's no equivalent index
*/
static int fixIndex(int idx, size_t n) {
if (idx > 0) return idx - 1;
if (idx == 0) return 0;
if (idx == TINYOBJ_INVALID_INDEX) return TINYOBJ_INVALID_INDEX;
return (int)n + idx; // Negative value = relative
}
/* Function: parseRawTriple
*
* Parses raw triplets of given tokens
* > v, v/vt/vn, v//vn, v/vt
*
* > Valid triplets:
* > <x> 1//1
* > <x> 1//1 2//2 3//3 4//4
* > <x> 1/1/1 2/2/2 3/3/3 4/4/4
* > The following are examples of illegal statements
* > <x> 1/1/1 2/2/2 3//3 4//4
* > <x> 1/ 1/1 2/2/2 3/3/3 4/4/4
*
* Parameters:
* token - Token to parse
*
* Returns:
* Indices parsed from given token, if one of the indices is not present it's
* equal to <TINYOBJ_INVALID_INDEX>
*/
static tinyobj_vertex_index_t parseRawTriple(const char **token) {
tinyobj_vertex_index_t vi;
vi.v_idx = (int)(TINYOBJ_INVALID_INDEX);
vi.vn_idx = (int)(TINYOBJ_INVALID_INDEX);
vi.vt_idx = (int)(TINYOBJ_INVALID_INDEX);
// v
vi.v_idx = atoi((*token));
until_space_cr_slash(token);
if ((*token)[0] != '/') return vi;
(*token)++;
// v//vn
if ((*token)[0] == '/') {
(*token)++;
vi.vn_idx = atoi((*token));
until_space_cr_slash(token);
return vi;
}
// v/vt/vn or v/vt
vi.vt_idx = atoi((*token));
until_space_cr_slash(token);
if ((*token)[0] != '/') return vi;
// v/vt/vn
(*token)++; // skip '/'
vi.vn_idx = atoi((*token));
until_space_cr_slash(token);
return vi;
}
/***********************************************************************************************
* Group: Integer/Double/Float handling
***********************************************************************************************/
/* Function: parseInt
* Returns equivalent integer of next non-space character, the token is advanced
* until next space
*/
static int parseInt(const char **token) {
int i = 0;
skip_space(token);
i = atoi((*token));
(*token) += until_space((*token));
return i;
}
/* Function: tryParseDouble_assemble
*
* Last step of <tryParseDouble>
*
* Assembles given information into double
*
* Parameters:
* sign - Sign of this double
* mantissa - Mantissa
* exp_sign - Exponent sign
* exponent - Exponent
*
* Returns:
*
* Assembled double
*/
static double tryParseDouble_assemble(char sign, double mantissa, char exp_sign,
int exponent) {
double a = 1.0; /* = pow(5.0, exponent); */
double b = 1.0; /* = 2.0^exponent */
int i;
for (i = 0; i < exponent; i++) a = a * 5.0;
for (i = 0; i < exponent; i++) b = b * 2.0;
if (exp_sign == '-') {
a = 1.0 / a;
b = 1.0 / b;
}
/* (sign == '+' ? 1 : -1) * ldexp(mantissa * pow(5.0, exponent),
exponent); */
return (sign == '+' ? 1 : -1) * (mantissa * a * b);
}
/* Function: tryParseDouble_integer
*
* Part of <tryParseDouble>
*
* Parses integer part of a double (advances curr)
*
* Parameters:
*
* curr - Current position in a buffer
* s_end - End of the buffer
* sign - [out] Sign to be filled
* integer - [out] Integer to be filled
*
* Returns:
* True integer was successfuly parsed, false if nothing was read
*/
static unsigned char tryParseDouble_integer(const char **curr,
const char *s_end, char *sign,
int *integer) {
unsigned int read = 0;
*sign = '+'; // Default sign
// Read sign
if ((*curr)[0] == '+' || (*curr)[0] == '-') {
(*sign) = (*curr)[0];
if ((*curr)++ == s_end) return 0; // No more data to read (invalid number)
} else if (!IS_DIGIT((*curr)[0])) {
return 0; // A digit is expected
}
// Read integer
for (; (*curr) != s_end && IS_DIGIT(((*curr)[0])); (*curr)++, read++) {
(*integer) *= 10;
(*integer) += (int)((*curr)[0] - 0x30);
}
return (read > 0);
}
/* Function: tryParseDouble
*
* Tries to parse a floating point number located at s.
* > Parses the following EBNF grammar:
* > sign = "+" | "-" ;
* > END = ? anything not in digit ?
* > digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
* > integer = [sign] , digit , {digit} ;
* > decimal = integer , ["." , integer] ;
* > float = ( decimal , END ) | ( decimal , ("E" | "e") , integer , END ) ;
*
* > Valid strings are for example:
* > -0 +3.1417e+2 -0.0E-3 1.0324 -1.41 11e2
*
* The function is greedy and will parse until any of the following happens:
*
* - a non-conforming character is encountered.
* - s_end is reached.
*
* The following situations triggers a failure:
*
* - s >= s_end.
* - parse failure.
*
* Parameters:
*
* s - String to be parsed
* s_end - Location in the string where reading should halt, e.g. the end of
* the string result - [out] Parsed double
*
* Returns
* If the parsing is a success, result is set to the parsed value and true
* is returned.
*/
static unsigned char tryParseDouble(const char *s, const char *s_end,
double *result) {
double mantissa = 0.0;
int integer = 0;
/* This exponent is base 2 rather than 10.
* However the exponent we parse is supposed to be one of ten,
* thus we must take care to convert the exponent/and or the
* mantissa to a * 2^E, where a is the mantissa and E is the
* exponent.
* To get the final double we will use ldexp, it requires the
* exponent to be in base 2.
*/
int exponent = 0;
/* NOTE: THESE MUST BE DECLARED HERE SINCE WE ARE NOT ALLOWED
* TO JUMP OVER DEFINITIONS.
*/
char sign = '+';
char exp_sign = '+';
char const *curr = s;
/* How many characters were read in a loop. */
int read = 0;
/* BEGIN PARSING. */
if (s >= s_end) // Passed stopping point
return 0;
// Read integer and sign
if (!tryParseDouble_integer(&curr, s_end, &sign, &integer))
return 0; // Nothing was read
mantissa = integer;
while (curr != s_end) {
switch (*curr) {
// Read decimal
case '.': {
if (curr++ == s_end) return 0;
read = 1;
while (curr != s_end && IS_DIGIT(*curr)) {
/* pow(10.0, -read) */
double frac_value = 1.0;
int f;
for (f = 0; f < read; f++) frac_value *= 0.1;
mantissa += (int)(*curr - 0x30) * frac_value;
read++;
curr++;
}
break;
}
// Read Exponent
case 'E':
case 'e': {
if (curr++ == s_end) return 0;
if (!tryParseDouble_integer(&curr, s_end, &exp_sign, &exponent))
return 0; // Empty E is not allowed
break;
}
default:
curr++;
break;
}