-
Notifications
You must be signed in to change notification settings - Fork 0
/
objzero.c
1442 lines (1360 loc) · 46.5 KB
/
objzero.c
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
/*
https://github.com/jpcy/objzero
MIT License
Copyright (c) 2018-2019 Jonathan Young
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.
*/
/*
Ear clipping triangulation and tryParseDouble from tinyobjloader, also under MIT license.
https://github.com/syoyo/tinyobjloader
Copyright (c) 2012-2018 Syoyo Fujita and many contributors.
*/
#include <float.h>
#include <math.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include "objzero.h"
#ifdef _MSC_VER
#define OBJZ_FOPEN(_file, _filename, _mode) { if (fopen_s(&_file, _filename, _mode) != 0) _file = NULL; }
#define OBJZ_STRICMP _stricmp
#define OBJZ_STRTOK(_str, _delim, _context) strtok_s(_str, _delim, _context)
#else
#include <strings.h>
#define OBJZ_FOPEN(_file, _filename, _mode) _file = fopen(_filename, _mode)
#define OBJZ_STRICMP strcasecmp
#define OBJZ_STRTOK(_str, _delim, _context) strtok(_str, _delim)
#endif
#define OBJZ_MAX_ERROR_LENGTH 1024
#define OBJZ_MAX_TOKEN_LENGTH 256
#define OBJZ_RAW_ARRAY_LEN(_x) (sizeof(_x) / sizeof((_x)[0]))
#define OBJZ_SMALLEST(_a, _b) ((_a) < (_b) ? (_a) : (_b))
#define OBJZ_LARGEST(_a, _b) ((_a) > (_b) ? (_a) : (_b))
static char s_error[OBJZ_MAX_ERROR_LENGTH] = { 0 };
static objzReallocFunc s_realloc = NULL;
static objzProgressFunc s_progress = NULL;
static uint32_t s_indexFormat = OBJZ_INDEX_FORMAT_AUTO;
typedef struct {
size_t stride;
size_t positionOffset;
size_t texcoordOffset;
size_t normalOffset;
} VertexFormat;
static VertexFormat s_vertexDecl = {
.stride = sizeof(float) * (3 + 2 + 3),
.positionOffset = 0,
.texcoordOffset = sizeof(float) * 3,
.normalOffset = sizeof(float) * (3 + 2)
};
static void *objz_realloc(void *_ptr, size_t _size, char *_file, int _line) {
if (!_ptr && !_size)
return NULL;
void *result;
if (s_realloc)
result = s_realloc(_ptr, _size);
else
result = realloc(_ptr, _size);
if (_size > 0 && !result) {
fprintf(stderr, "Memory allocation failed %s %d\n", _file, _line);
abort();
}
return result;
}
#define OBJZ_MALLOC(_size) objz_realloc(NULL, (_size), __FILE__, __LINE__)
#define OBJZ_REALLOC(_ptr, _size) objz_realloc((_ptr), (_size), __FILE__, __LINE__)
#define OBJZ_FREE(_ptr) objz_realloc((_ptr), 0, __FILE__, __LINE__)
static size_t strLength(const char *_str, size_t _size)
{
const char *c = _str;
size_t len = 0;
while (*c != 0 && len < _size) {
c++;
len++;
}
return len;
}
static void strCopy(char *_dest, size_t _destSize, const char *_src, size_t _count)
{
const size_t n = OBJZ_SMALLEST(_destSize - 1, strLength(_src, _count));
memcpy(_dest, _src, n);
_dest[n] = 0;
}
static void strConcat(char *_dest, size_t _destSize, const char *_src, size_t _count)
{
const size_t start = strLength(_dest, _destSize);
strCopy(&_dest[start], _destSize - start, _src, _count);
}
// Tries to parse a floating point number located at s.
//
// s_end should be a location in the string where reading should absolutely
// stop. For example at the end of the string, to prevent buffer overflows.
//
// 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
//
// If the parsing is a success, result is set to the parsed value and true
// is returned.
//
// 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.
//
#define IS_DIGIT(x) ((unsigned int)((x) - '0') < (unsigned int)(10))
static bool tryParseDouble(const char *s, const char *s_end, double *result)
{
if (s >= s_end)
return false;
double mantissa = 0.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;
// Tells whether a loop terminated due to reaching s_end.
bool end_not_reached = false;
bool leading_decimal_dots = false;
// Find out what sign we've got.
if (*curr == '+' || *curr == '-') {
sign = *curr;
curr++;
if ((curr != s_end) && (*curr == '.')) {
// accept. Somethig like `.7e+2`, `-.5234`
leading_decimal_dots = true;
}
} else if (IS_DIGIT(*curr)) { /* Pass through. */
} else if (*curr == '.') {
// accept. Somethig like `.7e+2`, `-.5234`
leading_decimal_dots = true;
} else {
goto fail;
}
// Read the integer part.
end_not_reached = (curr != s_end);
if (!leading_decimal_dots) {
while (end_not_reached && IS_DIGIT(*curr)) {
mantissa *= 10;
mantissa += (int)(*curr - 0x30);
curr++;
read++;
end_not_reached = (curr != s_end);
}
// We must make sure we actually got something.
if (read == 0) goto fail;
}
// We allow numbers of form "#", "###" etc.
if (!end_not_reached) goto assemble;
// Read the decimal part.
if (*curr == '.') {
curr++;
read = 1;
end_not_reached = (curr != s_end);
while (end_not_reached && IS_DIGIT(*curr)) {
static const double pow_lut[] = { 1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001, };
const int lut_entries = sizeof pow_lut / sizeof pow_lut[0];
// NOTE: Don't use powf here, it will absolutely murder precision.
mantissa += (int)(*curr - 0x30) * (read < lut_entries ? pow_lut[read] : pow(10.0, -read));
read++;
curr++;
end_not_reached = (curr != s_end);
}
} else if (*curr == 'e' || *curr == 'E') {
} else {
goto assemble;
}
if (!end_not_reached) goto assemble;
// Read the exponent part.
if (*curr == 'e' || *curr == 'E') {
curr++;
// Figure out if a sign is present and if it is.
end_not_reached = (curr != s_end);
if (end_not_reached && (*curr == '+' || *curr == '-')) {
exp_sign = *curr;
curr++;
} else if (IS_DIGIT(*curr)) { /* Pass through. */
} else {
// Empty E is not allowed.
goto fail;
}
read = 0;
end_not_reached = (curr != s_end);
while (end_not_reached && IS_DIGIT(*curr)) {
exponent *= 10;
exponent += (int)(*curr - 0x30);
curr++;
read++;
end_not_reached = (curr != s_end);
}
exponent *= (exp_sign == '+' ? 1 : -1);
if (read == 0) goto fail;
}
assemble:
*result = (sign == '+' ? 1 : -1) * (exponent ? ldexp(mantissa * pow(5.0, exponent), exponent) : mantissa);
return true;
fail:
return false;
}
typedef struct {
float x, y, z;
} vec3;
#define OBJZ_VEC3_ABS(_out, _v) (_out).x = fabsf((_v).x); (_out).y = fabsf((_v).y); (_out).z = fabsf((_v).z);
#define OBJZ_VEC3_ADD(_out, _a, _b) (_out).x = (_a).x + (_b).x; (_out).y = (_a).y + (_b).y; (_out).z = (_a).z + (_b).z;
#define OBJZ_VEC3_CROSS(_out, _a, _b) \
(_out).x = (_a).y * (_b).z - (_a).z * (_b).y; \
(_out).y = (_a).z * (_b).x - (_a).x * (_b).z; \
(_out).z = (_a).x * (_b).y - (_a).y * (_b).x;
#define OBJZ_VEC3_COPY(_out, _in) (_out).x = (_in).x; (_out).y = (_in).y; (_out).z = (_in).z;
#define OBJZ_VEC3_DOT(_out, _a, _b) (_out) = (_a).x * (_b).x + (_a).y * (_b).y + (_a).z * (_b).z;
#define OBJZ_VEC3_MUL(_out, _v, _s) (_out).x = (_v).x * _s; (_out).y = (_v).y * _s; (_out).z = (_v).z * _s;
#define OBJZ_VEC3_SET(_out, _x, _y, _z) (_out).x = (_x); (_out).y = (_y); (_out).z = (_z);
#define OBJZ_VEC3_SUB(_out, _a, _b) (_out).x = (_a).x - (_b).x; (_out).y = (_a).y - (_b).y; (_out).z = (_a).z - (_b).z;
static bool vec3Equal(const vec3 *_a, const vec3 *_b, float epsilon) {
return fabsf(_a->x - _b->x) <= epsilon && fabsf(_a->y - _b->y) <= epsilon && fabsf(_a->z - _b->z) <= epsilon;
}
static void vec3Normalize(vec3 *_out, const vec3 *_in) {
float len;
OBJZ_VEC3_DOT(len, *_in, *_in);
if (len > 0) {
len = 1.0f / sqrtf(len);
OBJZ_VEC3_MUL(*_out, *_in, len);
} else {
OBJZ_VEC3_COPY(*_out, *_in);
}
}
static void appendError(const char *_format, ...) {
va_list args;
va_start(args, _format);
char buffer[OBJZ_MAX_ERROR_LENGTH];
vsnprintf(buffer, sizeof(buffer), _format, args);
va_end(args);
if (s_error[0]) {
const char *newline = "\n";
strConcat(s_error, sizeof(s_error), newline, 1);
}
strConcat(s_error, sizeof(s_error), buffer, strLength(buffer, sizeof(buffer)));
}
typedef struct {
uint8_t *data;
uint32_t length;
uint32_t capacity;
uint32_t elementSize;
uint32_t initialCapacity;
} Array;
static void arrayInit(Array *_array, size_t _elementSize, uint32_t _initialCapacity) {
_array->data = NULL;
_array->length = _array->capacity = 0;
_array->elementSize = (uint32_t)_elementSize;
_array->initialCapacity = _initialCapacity;
}
static void arrayDestroy(Array *_array) {
OBJZ_FREE(_array->data);
}
static void arrayAppend(Array *_array, const void *_element) {
if (!_array->data) {
_array->data = OBJZ_MALLOC(_array->elementSize * _array->initialCapacity);
_array->capacity = _array->initialCapacity;
} else if (_array->length == _array->capacity) {
_array->capacity *= 2;
_array->data = OBJZ_REALLOC(_array->data, _array->capacity * _array->elementSize);
}
memcpy(&_array->data[_array->length * _array->elementSize], _element, _array->elementSize);
_array->length++;
}
#define OBJZ_ARRAY_ELEMENT(_array, _index) (void *)&(_array).data[(_array).elementSize * (_index)]
// Array: reallocates the buffer when full. The buffer is a contiguous area of memory.
// ChunkedArray: allocates another chunk of memory when full. Buffer is a linked list of chunks, not contiguous.
typedef struct {
Array chunks;
uint32_t elementsPerChunk;
size_t elementSize;
uint32_t length;
} ChunkedArray;
static void chunkedArrayInit(ChunkedArray *_array, size_t _elementSize, uint32_t _chunkLength) {
arrayInit(&_array->chunks, sizeof(void *), 32);
_array->elementsPerChunk = _chunkLength;
_array->elementSize = _elementSize;
_array->length = 0;
}
static void chunkedArrayDestroy(ChunkedArray *_array) {
for (uint32_t i = 0; i < _array->chunks.length; i++) {
void **chunk = OBJZ_ARRAY_ELEMENT(_array->chunks, i);
OBJZ_FREE(*chunk);
}
arrayDestroy(&_array->chunks);
}
static void chunkedArrayAppend(ChunkedArray *_array, const void *_element) {
if (_array->length >= _array->chunks.length * _array->elementsPerChunk) {
void *newChunk = OBJZ_MALLOC(_array->elementsPerChunk * _array->elementSize);
arrayAppend(&_array->chunks, &newChunk);
}
uint8_t **chunk = OBJZ_ARRAY_ELEMENT(_array->chunks, _array->length / _array->elementsPerChunk);
memcpy(&(*chunk)[_array->elementSize * (_array->length % _array->elementsPerChunk)], _element, _array->elementSize);
_array->length++;
}
static void *chunkedArrayElement(const ChunkedArray *_array, uint32_t _index) {
uint8_t **chunk = OBJZ_ARRAY_ELEMENT(_array->chunks, _index / _array->elementsPerChunk);
return &(*chunk)[_array->elementSize * (_index % _array->elementsPerChunk)];
}
typedef struct {
char *buf;
uint32_t line, column;
} Lexer;
typedef struct {
char text[OBJZ_MAX_TOKEN_LENGTH];
uint32_t line, column;
} Token;
static void initLexer(Lexer *_lexer) {
_lexer->buf = NULL;
_lexer->column = 1;
_lexer->line = 0;
}
static bool isEol(const Lexer *_lexer) {
return (_lexer->buf[0] == 0);
}
static bool isWhitespace(const Lexer *_lexer) {
return (_lexer->buf[0] == ' ' || _lexer->buf[0] == '\t' || _lexer->buf[0] == '\r');
}
static void skipWhitespace(Lexer *_lexer) {
for (;;) {
if (isEol(_lexer))
break;
if (!isWhitespace(_lexer))
break;
_lexer->buf++;
_lexer->column++;
}
}
static void lexerSetLine(Lexer *_lexer, char *_buf) {
_lexer->column = 1;
_lexer->line++;
_lexer->buf = _buf;
}
static void tokenize(Lexer *_lexer, Token *_token, bool includeWhitespace) {
uint32_t i = 0;
skipWhitespace(_lexer);
_token->line = _lexer->line;
_token->column = _lexer->column;
for (;;) {
if (isEol(_lexer) || (!includeWhitespace && isWhitespace(_lexer)))
break;
_token->text[i++] = _lexer->buf[0];
_lexer->buf++;
_lexer->column++;
}
_token->text[i] = 0;
}
static bool parseFloats(Lexer *_lexer, float *_result, uint32_t n) {
Token token;
for (uint32_t i = 0; i < n; i++) {
tokenize(_lexer, &token, false);
const size_t len = strLength(token.text, sizeof(token.text));
if (len == 0) {
appendError("(%u:%u) Empty float string", token.line, token.column);
return false;
}
double value;
if (!tryParseDouble(token.text, token.text + len, &value)) {
appendError("(%u:%u) Error parsing float", token.line, token.column);
return false;
}
_result[i] = (float)value;
}
return true;
}
static bool skipTokens(Lexer *_lexer, int _n) {
Token token;
for (int i = 0; i < _n; i++) {
tokenize(_lexer, &token, false);
if (strLength(token.text, sizeof(token.text)) == 0) {
appendError("(%u:%u) Error skipping tokens", token.line, token.column);
return false;
}
}
return true;
}
typedef struct {
char *buffer;
size_t length;
size_t pos;
} File;
bool fileOpen(File *_file, const char *_filename) {
FILE *handle;
OBJZ_FOPEN(handle, _filename, "rb");
if (!handle)
return false;
fseek(handle, 0, SEEK_END);
_file->length = (size_t)ftell(handle);
fseek(handle, 0, SEEK_SET);
if (_file->length == 0) {
fclose(handle);
return false;
}
_file->pos = 0;
_file->buffer = OBJZ_MALLOC(_file->length + 1);
const size_t chunkSize = 8192;
size_t totalBytesRead = 0;
int progress = 0;
for (;;) {
const size_t bytesRemaining = _file->length - totalBytesRead;
const size_t bytesRequested = bytesRemaining > chunkSize ? chunkSize : bytesRemaining;
const size_t bytesRead = fread(&_file->buffer[totalBytesRead], 1, bytesRequested, handle);
totalBytesRead += bytesRead;
if (s_progress) {
const int newProgress = (int)(totalBytesRead / (float)_file->length * 50.0f);
if (newProgress > progress) {
progress = newProgress;
s_progress(_filename, progress);
}
}
if (totalBytesRead == _file->length) {
fclose(handle);
break;
} else if (bytesRead < bytesRequested) {
fclose(handle);
OBJZ_FREE(_file->buffer);
return false;
}
}
_file->buffer[_file->length] = 0;
return true;
}
void fileClose(File *_file) {
OBJZ_FREE(_file->buffer);
}
char *fileReadLine(File *_file) {
if (_file->buffer[_file->pos] == 0)
return NULL; // eof
char *start = &_file->buffer[_file->pos];
// Find eol. Newline is replaced with a null terminator. Position is set to the start of the next line.
for (;;) {
char *c = &_file->buffer[_file->pos];
if (*c == 0) {
break;
}
if (*c == '\r')
*c = 0; // Null terminate here, but keep reading until newline.
else if (*c == '\n') {
*c = 0;
_file->pos++;
break;
}
_file->pos++;
}
return start;
}
#define OBJZ_MAT_TOKEN_STRING 0
#define OBJZ_MAT_TOKEN_FLOAT 1
typedef struct {
const char *name;
uint32_t type;
size_t offset;
uint32_t n;
} MaterialProperty;
static MaterialProperty s_materialProperties[] = {
{ "d", OBJZ_MAT_TOKEN_FLOAT, offsetof(objzMaterial, opacity), 1 },
{ "Ka", OBJZ_MAT_TOKEN_FLOAT, offsetof(objzMaterial, ambient), 3 },
{ "Kd", OBJZ_MAT_TOKEN_FLOAT, offsetof(objzMaterial, diffuse), 3 },
{ "Ke", OBJZ_MAT_TOKEN_FLOAT, offsetof(objzMaterial, emission), 3 },
{ "Ks", OBJZ_MAT_TOKEN_FLOAT, offsetof(objzMaterial, specular), 3 },
{ "Ns", OBJZ_MAT_TOKEN_FLOAT, offsetof(objzMaterial, specularExponent), 1 },
{ "bump", OBJZ_MAT_TOKEN_STRING, offsetof(objzMaterial, bumpTexture), 1 },
{ "map_Bump", OBJZ_MAT_TOKEN_STRING, offsetof(objzMaterial, bumpTexture), 1 },
{ "map_Ka", OBJZ_MAT_TOKEN_STRING, offsetof(objzMaterial, ambientTexture), 1 },
{ "map_Kd", OBJZ_MAT_TOKEN_STRING, offsetof(objzMaterial, diffuseTexture), 1 },
{ "map_Ke", OBJZ_MAT_TOKEN_STRING, offsetof(objzMaterial, emissionTexture), 1 },
{ "map_Ks", OBJZ_MAT_TOKEN_STRING, offsetof(objzMaterial, specularTexture), 1 },
{ "map_Ns", OBJZ_MAT_TOKEN_STRING, offsetof(objzMaterial, specularExponentTexture), 1 },
{ "map_d", OBJZ_MAT_TOKEN_STRING, offsetof(objzMaterial, opacityTexture), 1 }
};
typedef struct {
const char *name;
uint32_t n;
} MaterialMapArg;
static MaterialMapArg s_materialMapArgs[] = {
{ "-blendu", 1 },
{ "-blendv", 1 },
{ "-bm", 1 },
{ "-boost", 1 },
{ "-clamp", 1 },
{ "-imfchan", 1 },
{ "-mm", 2 },
{ "-o", 3 },
{ "-s", 3 },
{ "-t", 3 },
{ "-texres", 1 },
{ "-type", 1 }
};
static void materialInit(objzMaterial *_mat) {
memset(_mat, 0, sizeof(*_mat));
_mat->diffuse[0] = _mat->diffuse[1] = _mat->diffuse[2] = 1;
_mat->opacity = 1;
}
static bool loadMaterialFile(const char *_objFilename, const char *_materialName, Array *_materials) {
char filename[256] = { 0 };
const char *lastSlash = strrchr(_objFilename, '/');
if (!lastSlash)
lastSlash = strrchr(_objFilename, '\\');
if (lastSlash) {
for (int i = 0;; i++) {
filename[i] = _objFilename[i];
if (&_objFilename[i] == lastSlash)
break;
}
strConcat(filename, sizeof(filename), _materialName, strLength(_materialName, OBJZ_MAX_TOKEN_LENGTH));
} else
strCopy(filename, sizeof(filename), _materialName, strLength(_materialName, OBJZ_MAX_TOKEN_LENGTH));
File file;
if (!fileOpen(&file, filename)) {
// Treat missing material file as a warning, not an error.
appendError("Failed to read material file '%s'", filename);
return true;
}
const uint32_t *bom32 = (const uint32_t *)file.buffer;
if (*bom32 == 0x0000feff || *bom32 == 0xfffe0000) {
appendError("UTF-32 encoding not supported in file '%s'", filename);
return false;
}
const uint16_t *bom16 = (const uint16_t *)file.buffer;
if (*bom16 == 0xfffe || *bom16 == 0xfeff) {
appendError("UTF-16 encoding not supported in file '%s'", filename);
return false;
}
Lexer lexer;
initLexer(&lexer);
Token token;
objzMaterial mat;
materialInit(&mat);
bool result = false;
for (;;) {
char *line = fileReadLine(&file);
if (!line)
break;
lexerSetLine(&lexer, line);
tokenize(&lexer, &token, false);
if (OBJZ_STRICMP(token.text, "newmtl") == 0) {
tokenize(&lexer, &token, false);
if (token.text[0] == 0) {
appendError("(%u:%u) Expected name after 'newmtl'", token.line, token.column);
goto cleanup;
}
if (mat.name[0] != 0)
arrayAppend(_materials, &mat);
materialInit(&mat);
strCopy(mat.name, sizeof(mat.name), token.text, strLength(token.text, sizeof(token.text)));
} else {
for (size_t i = 0; i < OBJZ_RAW_ARRAY_LEN(s_materialProperties); i++) {
const MaterialProperty *prop = &s_materialProperties[i];
uint8_t *dest = &((uint8_t *)&mat)[prop->offset];
if (OBJZ_STRICMP(token.text, prop->name) == 0) {
if (prop->type == OBJZ_MAT_TOKEN_STRING) {
Token argToken;
for (int j = 0;; j++) {
tokenize(&lexer, &argToken, false);
if (argToken.text[0] == 0) {
if (j == 0) {
appendError("(%u:%u) Expected token after '%s'", token.line, token.column, prop->name);
goto cleanup;
}
break;
}
bool match = false;
for (size_t k = 0; k < OBJZ_RAW_ARRAY_LEN(s_materialMapArgs); k++) {
const MaterialMapArg *arg = &s_materialMapArgs[k];
if (OBJZ_STRICMP(argToken.text, arg->name) == 0) {
match = true;
skipTokens(&lexer, arg->n);
break;
}
}
if (!match)
strCopy((char *)dest, OBJZ_NAME_MAX, argToken.text, strLength(argToken.text, sizeof(argToken.text)));
}
} else if (prop->type == OBJZ_MAT_TOKEN_FLOAT) {
if (!parseFloats(&lexer, (float *)dest, prop->n))
goto cleanup;
}
break;
}
}
}
}
if (mat.name[0] != 0)
arrayAppend(_materials, &mat);
result = true;
cleanup:
fileClose(&file);
return result;
}
static uint32_t sdbmHash(const uint8_t *_data, uint32_t _size)
{
uint32_t hash = 0;
for (uint32_t i = 0; i < _size; i++)
hash = (uint32_t)_data[i] + (hash << 6) + (hash << 16) - hash;
return hash;
}
typedef struct {
uint32_t object;
uint32_t pos;
uint32_t texcoord;
uint32_t normal;
uint32_t hashNext; // For hash collisions: next HashedVertex with the same hash.
} HashedVertex;
typedef struct {
uint32_t *slots;
uint32_t numSlots;
Array vertices;
} VertexHashMap;
static void vertexHashMapInit(VertexHashMap *_map, uint32_t _initialCapacity) {
_map->numSlots = (uint32_t)(_initialCapacity * 1.3f);
_map->slots = OBJZ_MALLOC(sizeof(uint32_t) * _map->numSlots);
for (uint32_t i = 0; i < _map->numSlots; i++)
_map->slots[i] = UINT32_MAX;
arrayInit(&_map->vertices, sizeof(HashedVertex), _initialCapacity);
}
static void vertexHashMapDestroy(VertexHashMap *_map) {
OBJZ_FREE(_map->slots);
arrayDestroy(&_map->vertices);
}
static uint32_t vertexHashMapInsert(VertexHashMap *_map, uint32_t _object, uint32_t _pos, uint32_t _texcoord, uint32_t _normal) {
uint32_t hashData[4] = { 0 };
hashData[0] = _object;
hashData[1] = _pos;
if (_texcoord != UINT32_MAX)
hashData[2] = _texcoord;
if (_normal != UINT32_MAX)
hashData[3] = _normal;
const uint32_t hash = sdbmHash((const uint8_t *)hashData, sizeof(hashData)) % _map->numSlots;
uint32_t i = _map->slots[hash];
while (i != UINT32_MAX) {
const HashedVertex *v = OBJZ_ARRAY_ELEMENT(_map->vertices, i);
if (v->object == _object && v->pos == _pos && v->texcoord == _texcoord && v->normal == _normal)
return i;
i = v->hashNext;
}
HashedVertex v;
v.object = _object;
v.pos = _pos;
v.texcoord = _texcoord;
v.normal = _normal;
v.hashNext = _map->slots[hash];
_map->slots[hash] = _map->vertices.length;
arrayAppend(&_map->vertices, &v);
return _map->slots[hash];
}
typedef struct {
uint32_t normalIndex;
uint32_t hashNext; // For hash collisions: next HashedNormal with the same hash.
} HashedNormal;
typedef struct {
uint32_t *slots;
uint32_t numSlots;
Array hashedNormals;
ChunkedArray *normals;
} NormalHashMap;
static void normalHashMapClear(NormalHashMap *_map) {
for (uint32_t i = 0; i < _map->numSlots; i++)
_map->slots[i] = UINT32_MAX;
_map->hashedNormals.length = 0;
}
static void normalHashMapInit(NormalHashMap *_map, uint32_t _initialCapacity, ChunkedArray *_normals) {
_map->numSlots = (uint32_t)(_initialCapacity * 1.3f);
_map->slots = OBJZ_MALLOC(sizeof(uint32_t) * _map->numSlots);
_map->normals = _normals;
arrayInit(&_map->hashedNormals, sizeof(HashedNormal), _initialCapacity);
normalHashMapClear(_map);
}
static void normalHashMapDestroy(NormalHashMap *_map) {
OBJZ_FREE(_map->slots);
arrayDestroy(&_map->hashedNormals);
}
static uint32_t normalHashMapInsert(NormalHashMap *_map, const vec3 *_normal) {
uint32_t hashData[3] = { 0 };
hashData[0] = (uint32_t)(_normal->x * 0.5f + 0.5f * 255);
hashData[1] = (uint32_t)(_normal->y * 0.5f + 0.5f * 255);
hashData[2] = (uint32_t)(_normal->z * 0.5f + 0.5f * 255);
const uint32_t hash = sdbmHash((const uint8_t *)hashData, sizeof(hashData)) % _map->numSlots;
uint32_t i = _map->slots[hash];
while (i != UINT32_MAX) {
const HashedNormal *n = OBJZ_ARRAY_ELEMENT(_map->hashedNormals, i);
if (vec3Equal(chunkedArrayElement(_map->normals, n->normalIndex), _normal, FLT_EPSILON))
return n->normalIndex;
i = n->hashNext;
}
HashedNormal n;
n.normalIndex = _map->normals->length;
n.hashNext = _map->slots[hash];
_map->slots[hash] = _map->hashedNormals.length;
arrayAppend(&_map->hashedNormals, &n);
chunkedArrayAppend(_map->normals, _normal);
return n.normalIndex;
}
typedef struct {
char name[OBJZ_NAME_MAX];
uint32_t firstFace;
uint32_t numFaces;
} TempObject;
typedef struct {
uint32_t v;
uint32_t vt;
uint32_t vn;
} IndexTriplet;
typedef struct {
int16_t materialIndex;
uint16_t smoothingGroup; // 0 is off
IndexTriplet indices[3];
} Face;
static bool parseVertexAttribIndices(Token *_token, int32_t *_out) {
int32_t *v = &_out[0];
int32_t *vt = &_out[1];
int32_t *vn = &_out[2];
*v = *vt = *vn = INT_MAX;
if (strLength(_token->text, sizeof(_token->text)) == 0)
return false; // Empty token.
const char *delim = "/";
char *start = _token->text;
bool eol = false;
// v
char *end = strstr(start, delim);
if (!end) {
end = &_token->text[strLength(_token->text, sizeof(_token->text))];
eol = true;
} else if (end == start)
return false; // Token is just a delimiter.
*end = 0;
*v = atoi(start);
// vt
if (eol)
return true; // No vt or vn.
start = end + 1;
if (*start == 0)
return true; // No vt or vn.
end = strstr(start, delim);
bool skipNormal = false;
if (!end) {
// No delimiter, must be no normal, i.e. "v/vt".
skipNormal = true;
end = &_token->text[strLength(_token->text, sizeof(_token->text)) - 1];
}
*end = 0;
if (start != end)
*vt = atoi(start);
// vn
if (skipNormal)
return true;
start = end + 1;
if (*start != 0)
*vn = atoi(start);
return true;
}
// Convert 1-indexed relative vertex attrib index to a 0-indexed absolute index.
static uint32_t fixVertexAttribIndex(int32_t _index, uint32_t _n) {
if (_index == INT_MAX)
return UINT32_MAX;
// Handle relative index.
if (_index < 0)
return (uint32_t)(_index + _n);
// Convert from 1-indexed to 0-indexed.
return (uint32_t)(_index - 1);
}
// code from https://wrf.ecse.rpi.edu//Research/Short_Notes/pnpoly.html
static int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy) {
bool c = false;
for (int i = 0, j = nvert - 1; i < nvert; j = i++) {
if (((verty[i] > testy) != (verty[j] > testy)) && (testx < (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + vertx[i]))
c = !c;
}
return c;
}
// Ear clipping triangulation from tinyobjloader
// https://github.com/syoyo/tinyobjloader
static void triangulate(const Array *_indices, const ChunkedArray *_positions, Array *_tempIndices, ChunkedArray *_faces, int32_t _materialIndex, uint16_t _smoothingGroup) {
// find the two axes to work in
uint32_t axes[2] = { 1, 2 };
for (uint32_t i = 0; i < _indices->length; i++) {
const IndexTriplet *indices = (const IndexTriplet *)_indices->data;
vec3 v[3];
for (int j = 0; j < 3; j++)
v[j] = *(const vec3 *)chunkedArrayElement(_positions, indices[(i + j) % _indices->length].v);
vec3 edges[2];
OBJZ_VEC3_SUB(edges[0], v[1], v[0]);
OBJZ_VEC3_SUB(edges[1], v[2], v[1]);
vec3 corner;
OBJZ_VEC3_CROSS(corner, edges[0], edges[1]);
OBJZ_VEC3_ABS(corner, corner);
if (corner.x > FLT_EPSILON || corner.y > FLT_EPSILON || corner.z > FLT_EPSILON) {
// found a corner
if (!(corner.x > corner.y && corner.x > corner.z)) {
axes[0] = 0;
if (corner.z > corner.x && corner.z > corner.y)
axes[1] = 1;
}
break;
}
}
float area = 0;
for (uint32_t i = 0; i < _indices->length; i++) {
const IndexTriplet *i0 = OBJZ_ARRAY_ELEMENT(*_indices, (i + 0) % _indices->length);
const IndexTriplet *i1 = OBJZ_ARRAY_ELEMENT(*_indices, (i + 1) % _indices->length);
const float *v0 = chunkedArrayElement(_positions, i0->v);
const float *v1 = chunkedArrayElement(_positions, i1->v);
area += (v0[axes[0]] * v1[axes[1]] - v0[axes[1]] * v1[axes[0]]) * 0.5f;
}
// Copy vertices.
Array *remainingIndices = _tempIndices;
remainingIndices->length = 0;
for (uint32_t i = 0; i < _indices->length; i++)
arrayAppend(remainingIndices, OBJZ_ARRAY_ELEMENT(*_indices, i));
// How many iterations can we do without decreasing the remaining vertices.
uint32_t remainingIterations = remainingIndices->length;
uint32_t previousRemainingIndices = remainingIndices->length;
uint32_t guess_vert = 0;
while (remainingIndices->length > 3 && remainingIterations > 0) {
if (guess_vert >= remainingIndices->length)
guess_vert -= remainingIndices->length;
if (previousRemainingIndices != remainingIndices->length) {
// The number of remaining vertices decreased. Reset counters.
previousRemainingIndices = remainingIndices->length;
remainingIterations = remainingIndices->length;
} else {
// We didn't consume a vertex on previous iteration, reduce the
// available iterations.
remainingIterations--;
}
IndexTriplet *ind[3];
float vx[3];
float vy[3];
for (uint32_t i = 0; i < 3; i++) {
ind[i] = OBJZ_ARRAY_ELEMENT(*remainingIndices, (guess_vert + i) % remainingIndices->length);
const float *pos = (float *)chunkedArrayElement(_positions, ind[i]->v);
vx[i] = pos[axes[0]];
vy[i] = pos[axes[1]];
}
float edge0[2], edge1[2];
edge0[0] = vx[1] - vx[0];
edge0[1] = vy[1] - vy[0];
edge1[0] = vx[2] - vx[1];
edge1[1] = vy[2] - vy[1];
const float cross = edge0[0] * edge1[1] - edge0[1] * edge1[0];
// if an internal angle
if (cross * area < 0.0f) {
guess_vert += 1;
continue;
}
// check all other verts in case they are inside this triangle
bool overlap = false;
for (uint32_t otherVert = 3; otherVert < remainingIndices->length; ++otherVert) {
uint32_t idx = (guess_vert + otherVert) % remainingIndices->length;
if (idx >= remainingIndices->length)
continue; // ???
uint32_t ovi = ((IndexTriplet *)OBJZ_ARRAY_ELEMENT(*remainingIndices, idx))->v;
float tx = ((float *)chunkedArrayElement(_positions, ovi))[axes[0]];
float ty = ((float *)chunkedArrayElement(_positions, ovi))[axes[1]];
if (pnpoly(3, vx, vy, tx, ty)) {
overlap = true;
break;
}
}
if (overlap) {
guess_vert += 1;
continue;
}
// this triangle is an ear
Face face;
for (int i = 0; i < 3; i++)
face.indices[i] = *ind[i];
face.materialIndex = (int16_t)_materialIndex;
face.smoothingGroup = _smoothingGroup;
chunkedArrayAppend(_faces, &face);
// remove v1 from the list
uint32_t removed_vert_index = (guess_vert + 1) % remainingIndices->length;
while (removed_vert_index + 1 < remainingIndices->length) {
IndexTriplet *remainingIndicesData = (IndexTriplet *)remainingIndices->data;
remainingIndicesData[removed_vert_index] = remainingIndicesData[removed_vert_index + 1];
removed_vert_index += 1;
}
remainingIndices->length--;
}
if (remainingIndices->length == 3) {
Face face;
for (int i = 0; i < 3; i++)
face.indices[i] = *(IndexTriplet *)OBJZ_ARRAY_ELEMENT(*remainingIndices, i);
face.materialIndex = (int16_t)_materialIndex;
face.smoothingGroup = _smoothingGroup;
chunkedArrayAppend(_faces, &face);
}
}
static vec3 calculateSmoothNormal(uint32_t _pos, ChunkedArray *_faces, Array *_faceNormals, uint16_t _smoothingGroup) {