forked from noodlecollie/calliper
-
Notifications
You must be signed in to change notification settings - Fork 1
/
objfileparser.cpp
541 lines (445 loc) · 13.6 KB
/
objfileparser.cpp
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
#include "objfileparser.h"
#include <QFile>
#define IDSHORT_POSITION (('v' << 8) | 0)
#define IDSHORT_NORMAL (('v' << 8) | 'n')
#define IDSHORT_UV (('v' << 8) | 't')
#define IDSHORT_FACE (('f' << 8) | 0)
#define IDSHORT_COMMENT (('#' << 8) | 0)
#define MAX_IDENTIFIER_LENGTH 6
#define FACEATT_POSITION 0
#define FACEATT_UV 1
#define FACEATT_NORMAL 2
// No idea whether this is capable, but let's fuck with some bits.
uint qHash(const ObjFileParser::FaceVertex &key, uint seed = 0)
{
return (uint)(key.atts[0] + (key.atts[1] * key.atts[1]) + (key.atts[2] * key.atts[2] * key.atts[2])) ^ seed;
}
ObjFileParser::IdentifierToken ObjFileParser::longIdentifier(const char* id)
{
QString str(id);
if ( str == "mtllib" )
return MtlLib;
return Other;
}
// Potentially faster? Assumes an array of length at least 2,
// and where any chars after the last valid char are 0.
ObjFileParser::IdentifierToken ObjFileParser::shortIdentifier(const char* id)
{
unsigned short num = ((*id) << 8) | *(id+1);
switch (num)
{
case IDSHORT_POSITION:
return Position;
case IDSHORT_NORMAL:
return Normal;
case IDSHORT_UV:
return UV;
case IDSHORT_FACE:
return Face;
case IDSHORT_COMMENT:
return Comment;
default:
return longIdentifier(id);
}
}
static bool isWhiteSpace(const char* c)
{
switch (*c)
{
case ' ':
case '\t':
return true;
default:
return false;
}
}
// Assumes begin points to a non-whitespace character.
ObjFileParser::IdentifierToken ObjFileParser::getNextIdentifierToken(const char* begin, const char* final)
{
const int idLen = MAX_IDENTIFIER_LENGTH + 1;
char identifier[idLen];
memset(identifier, 0, idLen*sizeof(char));
for (int i = 0; i < idLen-1 && (begin+i) <= final; i++)
{
if ( isWhiteSpace(begin+i) )
break;
identifier[i] = *(begin+i);
}
return shortIdentifier(identifier);
}
// We are given the final character so that we don't go over it.
// This must be >= begin!
static int nextNewline(const char* begin, const char* final)
{
int advance = 0;
while ( true )
{
if ( *begin == '\n' )
{
return advance;
}
if ( begin == final )
{
return -1;
}
advance++;
begin++;
}
}
template<typename T>
static int parseFloats(const QByteArray &line, QList<T> &list, int floatCount, ObjFileParser::ParseError &error)
{
const char* begin = line.constData();
int count = line.count();
int startIndex = 0;
// Wind past the first token.
while ( startIndex < count && !isWhiteSpace(begin+startIndex) )
startIndex++;
// If we reached count, there was no whitespace.
if ( startIndex >= count )
{
error = ObjFileParser::InvalidLineFormat;
return 0;
}
int cur = startIndex;
T listItem;
for ( int i = 0; i < floatCount; i++ )
{
// Wind past any whitespace.
while ( cur < count && isWhiteSpace(begin+cur) )
cur++;
// If we reached count, there was no other value to read.
if ( cur >= count )
{
error = ObjFileParser::InvalidLineFormat;
return 0;
}
int tokenStart = cur;
// Wind past non-whitespace.
while ( cur < count && !isWhiteSpace(begin+cur) )
cur++;
if ( cur >= count )
{
// If we reached count and this was not the last iteration,
// there were not enough positional values on this line.
if ( i < floatCount-1 )
{
error = ObjFileParser::InvalidLineFormat;
return 0;
}
}
// Parse the value.
bool ok = false;
float value = QString(QByteArray(begin+tokenStart, cur-tokenStart)).toFloat(&ok);
if ( !ok )
{
error = ObjFileParser::InvalidNumber;
return tokenStart;
}
listItem[i] = value;
// Advance the current index.
cur++;
}
list.append(listItem);
error = ObjFileParser::NoError;
return -1;
}
void ObjFileParser::parseFaceVertex(const QByteArray &token, ObjFileParser::FaceVertex &fv)
{
QList<QByteArray> list = token.split('/');
switch (list.count())
{
// Position only.
case 1:
{
bool ok = false;
fv.atts[FACEATT_POSITION] = QString(list.at(0)).toInt(&ok);
if ( !ok )
{
memset(&fv, 0, sizeof(FaceVertex));
return;
}
return;
}
// Position, plus either UV or normal.
case 2:
{
// To find out whether the second item is UV or normal,
// look for the first occurrence of a slash.
int slash = token.indexOf('/');
// If the next character is also a slash, the second item is a normal.
// Otherwise it's a UV.
int index = token.at(slash+1) != '/' ? FACEATT_UV : FACEATT_NORMAL;
bool ok = false;
fv.atts[FACEATT_POSITION] = QString(list.at(0)).toInt(&ok);
if ( !ok )
{
memset(&fv, 0, sizeof(FaceVertex));
return;
}
ok = false;
fv.atts[index] = QString(list.at(1)).toInt(&ok);
if ( !ok )
{
memset(&fv, 0, sizeof(FaceVertex));
return;
}
return;
}
// All attributes.
case 3:
{
for ( int i = 0; i < 3; i++ )
{
bool ok = false;
fv.atts[i] = QString(list.at(i)).toInt(&ok);
if ( !ok )
{
memset(&fv, 0, sizeof(FaceVertex));
return;
}
}
return;
}
default:
memset(&fv, 0, sizeof(FaceVertex));
return;
}
}
int ObjFileParser::parseFace(const QByteArray &line, QList<ObjFileParser::FaceVertex> &fvList, ObjFileParser::ParseError &error)
{
const char* begin = line.constData();
int count = line.count();
int cur = 0;
// Wind past the first token.
while ( cur < count && !isWhiteSpace(begin+cur) )
cur++;
while (cur < count)
{
// Wind past any whitespace.
while ( cur < count && isWhiteSpace(begin+cur) )
cur++;
// If we reached count, break.
if ( cur >= count )
{
break;
}
int tokenStart = cur;
// Wind past non-whitespace.
while ( cur < count && !isWhiteSpace(begin+cur) )
cur++;
// Get information for this vertex.
FaceVertex fv;
parseFaceVertex(QByteArray(begin+tokenStart, cur-tokenStart), fv);
// If this vertex is not valid, exit out.
if ( !fv.isValid() )
{
error = ObjFileParser::InvalidVertexRef;
return tokenStart;
}
// Add this vertex to the list.
fvList.append(fv);
}
// If we didn't read enough vertices, return an invalid face error.
if ( fvList.count() < 3 )
{
error = ObjFileParser::InvalidFace;
return 0;
}
// We reached the end of the line.
error = ObjFileParser::NoError;
return -1;
}
ObjFileParser::ObjFileParser()
{
}
ObjFileParser::ParseResult ObjFileParser::fillAttributes(const QString &filename, QList<QVector3D> &positions,
QList<QVector3D> &normals, QList<QVector2D> &uvs,
QList<unsigned int> &indices, QString &texturePath)
{
m_Result.error = NoError;
m_Result.errorPosition = 0;
m_Result.filename = filename;
QFile file(filename);
if ( !file.open(QIODevice::ReadOnly) )
{
m_Result.error = FileAccessError;
return m_Result;
}
m_Array = file.readAll();
file.close();
m_IndexTable.clear();
const char* base = m_Array.constData();
m_pFinal = base + (m_Array.count()-1);
m_LocalPositions.clear();
m_LocalNormals.clear();
m_LocalUVs.clear();
for ( m_iPos = 0; m_iPos < m_Array.count(); m_iPos++ )
{
m_pCur = base + m_iPos;
// Find the first non-whitespace character.
if ( isWhiteSpace(m_pCur) || *m_pCur == '\n' )
continue;
// Get an identifier for the token.
IdentifierToken idt = getNextIdentifierToken(m_pCur, m_pFinal);
if ( idt == Position )
{
if ( !process<QVector3D>(m_LocalPositions, 3) )
return m_Result;
}
else if ( idt == Normal )
{
if ( !process<QVector3D>(m_LocalNormals, 3) )
return m_Result;
}
else if ( idt == UV )
{
if ( !process<QVector2D>(m_LocalUVs, 2) )
return m_Result;
}
else if ( idt == Face )
{
if ( !processFace() )
return m_Result;
}
else // Unrecognised
{
// Skip to the next line.
m_iPos += nextNewline(m_pCur, m_pFinal);
// If i is -1, we've reached the end of the data.
if ( m_iPos < 0 )
break;
// Otherwise, i will be incremented to point to the first character of the next line.
}
}
consolidate(positions, normals, uvs, indices);
// Reaching here means everything was OK.
return m_Result;
}
template<typename T>
bool ObjFileParser::process(QList<T> &list, int floatCount)
{
// This should never be 0 because a newline is not a position token!
int newlineOffset = nextNewline(m_pCur, m_pFinal);
if ( newlineOffset < 0 )
{
newlineOffset = m_Array.length()-1;
}
// We don't pass in the newline character itself.
int advance = parseFloats<T>(QByteArray(m_pCur, newlineOffset), list, floatCount, m_Result.error);
if ( m_Result.error != ObjFileParser::NoError )
{
m_Result.errorPosition = m_iPos + advance;
return false;
}
// If the return value was < 0, that means we can progress to the next line.
if ( advance < 0 )
{
m_iPos += newlineOffset;
}
else
{
m_iPos += advance;
}
return true;
}
bool ObjFileParser::processFace()
{
// This should never be 0 because a newline is not a position token!
int newlineOffset = nextNewline(m_pCur, m_pFinal);
if ( newlineOffset < 0 )
{
newlineOffset = m_Array.length()-1;
}
QList<FaceVertex> list;
int advance = parseFace(QByteArray(m_pCur, newlineOffset), list, m_Result.error);
if ( m_Result.error != ObjFileParser::NoError )
{
m_Result.errorPosition = m_iPos + advance;
return false;
}
// Create triangles.
for ( int i = 0; i < list.count(); i++ )
{
if ( i > 2 )
{
m_FaceVertices.append(list.at(0));
m_FaceVertices.append(list.at(i-1));
}
m_FaceVertices.append(list.at(i));
}
// If the return value was < 0, that means we can progress to the next line.
if ( advance < 0 )
{
m_iPos += newlineOffset;
}
else
{
m_iPos += advance;
}
return true;
}
void ObjFileParser::consolidate(QList<QVector3D> &positions, QList<QVector3D> &normals, QList<QVector2D> &uvs, QList<unsigned int> &indices)
{
m_IndexTable.clear();
for ( int i = 0; i < m_FaceVertices.count(); i++ )
{
const FaceVertex &fv = m_FaceVertices.at(i);
int index = -1;
// If we've encountered a vertex like this before:
if ( m_IndexTable.contains(fv) )
{
// It's at this index in the arrays.
index = m_IndexTable.value(fv);
}
// Otherwise, add the data to the arrays.
else
{
Q_ASSERT(positions.count() == normals.count() && normals.count() == uvs.count());
index = positions.count();
m_IndexTable.insert(fv, index);
int pos = fv.atts[FACEATT_POSITION]-1;
positions.append(pos >= 0 ? m_LocalPositions.at(pos) : QVector3D());
int nrm = fv.atts[FACEATT_NORMAL]-1;
normals.append(nrm >= 0 ? m_LocalNormals.at(nrm) : QVector3D());
int uv = fv.atts[FACEATT_UV]-1;
uvs.append(uv >= 0 ? m_LocalUVs.at(uv) : QVector2D());
}
Q_ASSERT(index >= 0);
indices.append(index);
}
}
QString ObjFileParser::errorString(const ParseResult &result)
{
switch (result.error)
{
case NoError:
{
return QString("No error.");
}
case FileAccessError:
{
return QString("Error opening file for reading.");
}
case InvalidNumber:
{
return QString("The number at position %0 could not be parsed").arg(result.errorPosition);
}
case InvalidLineFormat:
{
return QString("The line beginning at position %0 is not formatted correctly.").arg(result.errorPosition);
}
case InvalidFace:
{
return QString("The face at position %0 is invalid.").arg(result.errorPosition);
}
case InvalidVertexRef:
{
return QString("The vertex reference at position %0 is invalid.").arg(result.errorPosition);
}
default:
{
return QString("Unknown error at position %0.").arg(result.errorPosition);
}
}
}