@loaders.gl/obj 4.0.0-alpha.9 → 4.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,440 +0,0 @@
1
- "use strict";
2
- // OBJ Loader, adapted from THREE.js (MIT license)
3
- //
4
- // Attributions per original THREE.js source file:
5
- //
6
- // @author mrdoob / http://mrdoob.com/
7
- Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.parseOBJMeshes = void 0;
9
- // @ts-nocheck
10
- // o object_name | g group_name
11
- const OBJECT_RE = /^[og]\s*(.+)?/;
12
- // mtllib file_reference
13
- const MATERIAL_RE = /^mtllib /;
14
- // usemtl material_name
15
- const MATERIAL_USE_RE = /^usemtl /;
16
- class MeshMaterial {
17
- constructor({ index, name = '', mtllib, smooth, groupStart }) {
18
- this.index = index;
19
- this.name = name;
20
- this.mtllib = mtllib;
21
- this.smooth = smooth;
22
- this.groupStart = groupStart;
23
- this.groupEnd = -1;
24
- this.groupCount = -1;
25
- this.inherited = false;
26
- }
27
- clone(index = this.index) {
28
- return new MeshMaterial({
29
- index,
30
- name: this.name,
31
- mtllib: this.mtllib,
32
- smooth: this.smooth,
33
- groupStart: 0
34
- });
35
- }
36
- }
37
- class MeshObject {
38
- constructor(name = '') {
39
- this.name = name;
40
- this.geometry = {
41
- vertices: [],
42
- normals: [],
43
- colors: [],
44
- uvs: []
45
- };
46
- this.materials = [];
47
- this.smooth = true;
48
- this.fromDeclaration = null;
49
- }
50
- startMaterial(name, libraries) {
51
- const previous = this._finalize(false);
52
- // New usemtl declaration overwrites an inherited material, except if faces were declared
53
- // after the material, then it must be preserved for proper MultiMaterial continuation.
54
- if (previous && (previous.inherited || previous.groupCount <= 0)) {
55
- this.materials.splice(previous.index, 1);
56
- }
57
- const material = new MeshMaterial({
58
- index: this.materials.length,
59
- name,
60
- mtllib: Array.isArray(libraries) && libraries.length > 0 ? libraries[libraries.length - 1] : '',
61
- smooth: previous !== undefined ? previous.smooth : this.smooth,
62
- groupStart: previous !== undefined ? previous.groupEnd : 0
63
- });
64
- this.materials.push(material);
65
- return material;
66
- }
67
- currentMaterial() {
68
- if (this.materials.length > 0) {
69
- return this.materials[this.materials.length - 1];
70
- }
71
- return undefined;
72
- }
73
- _finalize(end) {
74
- const lastMultiMaterial = this.currentMaterial();
75
- if (lastMultiMaterial && lastMultiMaterial.groupEnd === -1) {
76
- lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
77
- lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
78
- lastMultiMaterial.inherited = false;
79
- }
80
- // Ignore objects tail materials if no face declarations followed them before a new o/g started.
81
- if (end && this.materials.length > 1) {
82
- for (let mi = this.materials.length - 1; mi >= 0; mi--) {
83
- if (this.materials[mi].groupCount <= 0) {
84
- this.materials.splice(mi, 1);
85
- }
86
- }
87
- }
88
- // Guarantee at least one empty material, this makes the creation later more straight forward.
89
- if (end && this.materials.length === 0) {
90
- this.materials.push({
91
- name: '',
92
- smooth: this.smooth
93
- });
94
- }
95
- return lastMultiMaterial;
96
- }
97
- }
98
- class ParserState {
99
- constructor() {
100
- this.objects = [];
101
- this.object = null;
102
- this.vertices = [];
103
- this.normals = [];
104
- this.colors = [];
105
- this.uvs = [];
106
- this.materialLibraries = [];
107
- this.startObject('', false);
108
- }
109
- startObject(name, fromDeclaration = true) {
110
- // If the current object (initial from reset) is not from a g/o declaration in the parsed
111
- // file. We need to use it for the first parsed g/o to keep things in sync.
112
- if (this.object && !this.object.fromDeclaration) {
113
- this.object.name = name;
114
- this.object.fromDeclaration = fromDeclaration;
115
- return;
116
- }
117
- const previousMaterial = this.object && typeof this.object.currentMaterial === 'function'
118
- ? this.object.currentMaterial()
119
- : undefined;
120
- if (this.object && typeof this.object._finalize === 'function') {
121
- this.object._finalize(true);
122
- }
123
- this.object = new MeshObject(name);
124
- this.object.fromDeclaration = fromDeclaration;
125
- // Inherit previous objects material.
126
- // Spec tells us that a declared material must be set to all objects until a new material is declared.
127
- // If a usemtl declaration is encountered while this new object is being parsed, it will
128
- // overwrite the inherited material. Exception being that there was already face declarations
129
- // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
130
- if (previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function') {
131
- const declared = previousMaterial.clone(0);
132
- declared.inherited = true;
133
- this.object.materials.push(declared);
134
- }
135
- this.objects.push(this.object);
136
- }
137
- finalize() {
138
- if (this.object && typeof this.object._finalize === 'function') {
139
- this.object._finalize(true);
140
- }
141
- }
142
- parseVertexIndex(value, len) {
143
- const index = parseInt(value);
144
- return (index >= 0 ? index - 1 : index + len / 3) * 3;
145
- }
146
- parseNormalIndex(value, len) {
147
- const index = parseInt(value);
148
- return (index >= 0 ? index - 1 : index + len / 3) * 3;
149
- }
150
- parseUVIndex(value, len) {
151
- const index = parseInt(value);
152
- return (index >= 0 ? index - 1 : index + len / 2) * 2;
153
- }
154
- addVertex(a, b, c) {
155
- const src = this.vertices;
156
- const dst = this.object.geometry.vertices;
157
- dst.push(src[a + 0], src[a + 1], src[a + 2]);
158
- dst.push(src[b + 0], src[b + 1], src[b + 2]);
159
- dst.push(src[c + 0], src[c + 1], src[c + 2]);
160
- }
161
- addVertexPoint(a) {
162
- const src = this.vertices;
163
- const dst = this.object.geometry.vertices;
164
- dst.push(src[a + 0], src[a + 1], src[a + 2]);
165
- }
166
- addVertexLine(a) {
167
- const src = this.vertices;
168
- const dst = this.object.geometry.vertices;
169
- dst.push(src[a + 0], src[a + 1], src[a + 2]);
170
- }
171
- addNormal(a, b, c) {
172
- const src = this.normals;
173
- const dst = this.object.geometry.normals;
174
- dst.push(src[a + 0], src[a + 1], src[a + 2]);
175
- dst.push(src[b + 0], src[b + 1], src[b + 2]);
176
- dst.push(src[c + 0], src[c + 1], src[c + 2]);
177
- }
178
- addColor(a, b, c) {
179
- const src = this.colors;
180
- const dst = this.object.geometry.colors;
181
- dst.push(src[a + 0], src[a + 1], src[a + 2]);
182
- dst.push(src[b + 0], src[b + 1], src[b + 2]);
183
- dst.push(src[c + 0], src[c + 1], src[c + 2]);
184
- }
185
- addUV(a, b, c) {
186
- const src = this.uvs;
187
- const dst = this.object.geometry.uvs;
188
- dst.push(src[a + 0], src[a + 1]);
189
- dst.push(src[b + 0], src[b + 1]);
190
- dst.push(src[c + 0], src[c + 1]);
191
- }
192
- addUVLine(a) {
193
- const src = this.uvs;
194
- const dst = this.object.geometry.uvs;
195
- dst.push(src[a + 0], src[a + 1]);
196
- }
197
- // eslint-disable-next-line max-params
198
- addFace(a, b, c, ua, ub, uc, na, nb, nc) {
199
- const vLen = this.vertices.length;
200
- let ia = this.parseVertexIndex(a, vLen);
201
- let ib = this.parseVertexIndex(b, vLen);
202
- let ic = this.parseVertexIndex(c, vLen);
203
- this.addVertex(ia, ib, ic);
204
- if (ua !== undefined && ua !== '') {
205
- const uvLen = this.uvs.length;
206
- ia = this.parseUVIndex(ua, uvLen);
207
- ib = this.parseUVIndex(ub, uvLen);
208
- ic = this.parseUVIndex(uc, uvLen);
209
- this.addUV(ia, ib, ic);
210
- }
211
- if (na !== undefined && na !== '') {
212
- // Normals are many times the same. If so, skip function call and parseInt.
213
- const nLen = this.normals.length;
214
- ia = this.parseNormalIndex(na, nLen);
215
- ib = na === nb ? ia : this.parseNormalIndex(nb, nLen);
216
- ic = na === nc ? ia : this.parseNormalIndex(nc, nLen);
217
- this.addNormal(ia, ib, ic);
218
- }
219
- if (this.colors.length > 0) {
220
- this.addColor(ia, ib, ic);
221
- }
222
- }
223
- addPointGeometry(vertices) {
224
- this.object.geometry.type = 'Points';
225
- const vLen = this.vertices.length;
226
- for (const vertex of vertices) {
227
- this.addVertexPoint(this.parseVertexIndex(vertex, vLen));
228
- }
229
- }
230
- addLineGeometry(vertices, uvs) {
231
- this.object.geometry.type = 'Line';
232
- const vLen = this.vertices.length;
233
- const uvLen = this.uvs.length;
234
- for (const vertex of vertices) {
235
- this.addVertexLine(this.parseVertexIndex(vertex, vLen));
236
- }
237
- for (const uv of uvs) {
238
- this.addUVLine(this.parseUVIndex(uv, uvLen));
239
- }
240
- }
241
- }
242
- // eslint-disable-next-line max-statements, complexity
243
- function parseOBJMeshes(text) {
244
- const state = new ParserState();
245
- if (text.indexOf('\r\n') !== -1) {
246
- // This is faster than String.split with regex that splits on both
247
- text = text.replace(/\r\n/g, '\n');
248
- }
249
- if (text.indexOf('\\\n') !== -1) {
250
- // join lines separated by a line continuation character (\)
251
- text = text.replace(/\\\n/g, '');
252
- }
253
- const lines = text.split('\n');
254
- let line = '';
255
- let lineFirstChar = '';
256
- let lineLength = 0;
257
- let result = [];
258
- // Faster to just trim left side of the line. Use if available.
259
- const trimLeft = typeof ''.trimLeft === 'function';
260
- /* eslint-disable no-continue, max-depth */
261
- for (let i = 0, l = lines.length; i < l; i++) {
262
- line = lines[i];
263
- line = trimLeft ? line.trimLeft() : line.trim();
264
- lineLength = line.length;
265
- if (lineLength === 0)
266
- continue;
267
- lineFirstChar = line.charAt(0);
268
- // @todo invoke passed in handler if any
269
- if (lineFirstChar === '#')
270
- continue;
271
- if (lineFirstChar === 'v') {
272
- const data = line.split(/\s+/);
273
- switch (data[0]) {
274
- case 'v':
275
- state.vertices.push(parseFloat(data[1]), parseFloat(data[2]), parseFloat(data[3]));
276
- if (data.length === 8) {
277
- state.colors.push(parseFloat(data[4]), parseFloat(data[5]), parseFloat(data[6]));
278
- }
279
- break;
280
- case 'vn':
281
- state.normals.push(parseFloat(data[1]), parseFloat(data[2]), parseFloat(data[3]));
282
- break;
283
- case 'vt':
284
- state.uvs.push(parseFloat(data[1]), parseFloat(data[2]));
285
- break;
286
- default:
287
- }
288
- }
289
- else if (lineFirstChar === 'f') {
290
- const lineData = line.substr(1).trim();
291
- const vertexData = lineData.split(/\s+/);
292
- const faceVertices = [];
293
- // Parse the face vertex data into an easy to work with format
294
- for (let j = 0, jl = vertexData.length; j < jl; j++) {
295
- const vertex = vertexData[j];
296
- if (vertex.length > 0) {
297
- const vertexParts = vertex.split('/');
298
- faceVertices.push(vertexParts);
299
- }
300
- }
301
- // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
302
- const v1 = faceVertices[0];
303
- for (let j = 1, jl = faceVertices.length - 1; j < jl; j++) {
304
- const v2 = faceVertices[j];
305
- const v3 = faceVertices[j + 1];
306
- state.addFace(v1[0], v2[0], v3[0], v1[1], v2[1], v3[1], v1[2], v2[2], v3[2]);
307
- }
308
- }
309
- else if (lineFirstChar === 'l') {
310
- const lineParts = line.substring(1).trim().split(' ');
311
- let lineVertices;
312
- const lineUVs = [];
313
- if (line.indexOf('/') === -1) {
314
- lineVertices = lineParts;
315
- }
316
- else {
317
- lineVertices = [];
318
- for (let li = 0, llen = lineParts.length; li < llen; li++) {
319
- const parts = lineParts[li].split('/');
320
- if (parts[0] !== '')
321
- lineVertices.push(parts[0]);
322
- if (parts[1] !== '')
323
- lineUVs.push(parts[1]);
324
- }
325
- }
326
- state.addLineGeometry(lineVertices, lineUVs);
327
- }
328
- else if (lineFirstChar === 'p') {
329
- const lineData = line.substr(1).trim();
330
- const pointData = lineData.split(' ');
331
- state.addPointGeometry(pointData);
332
- }
333
- else if ((result = OBJECT_RE.exec(line)) !== null) {
334
- // o object_name
335
- // or
336
- // g group_name
337
- // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
338
- // var name = result[ 0 ].substr( 1 ).trim();
339
- const name = (' ' + result[0].substr(1).trim()).substr(1); // eslint-disable-line
340
- state.startObject(name);
341
- }
342
- else if (MATERIAL_USE_RE.test(line)) {
343
- // material
344
- state.object.startMaterial(line.substring(7).trim(), state.materialLibraries);
345
- }
346
- else if (MATERIAL_RE.test(line)) {
347
- // mtl file
348
- state.materialLibraries.push(line.substring(7).trim());
349
- }
350
- else if (lineFirstChar === 's') {
351
- result = line.split(' ');
352
- // smooth shading
353
- // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
354
- // but does not define a usemtl for each face set.
355
- // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
356
- // This requires some care to not create extra material on each smooth value for "normal" obj files.
357
- // where explicit usemtl defines geometry groups.
358
- // Example asset: examples/models/obj/cerberus/Cerberus.obj
359
- /*
360
- * http://paulbourke.net/dataformats/obj/
361
- * or
362
- * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
363
- *
364
- * From chapter "Grouping" Syntax explanation "s group_number":
365
- * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
366
- * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
367
- * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
368
- * than 0."
369
- */
370
- if (result.length > 1) {
371
- const value = result[1].trim().toLowerCase();
372
- state.object.smooth = value !== '0' && value !== 'off';
373
- }
374
- else {
375
- // ZBrush can produce "s" lines #11707
376
- state.object.smooth = true;
377
- }
378
- const material = state.object.currentMaterial();
379
- if (material)
380
- material.smooth = state.object.smooth;
381
- }
382
- else {
383
- // Handle null terminated files without exception
384
- if (line === '\0')
385
- continue;
386
- throw new Error(`Unexpected line: "${line}"`);
387
- }
388
- }
389
- state.finalize();
390
- const meshes = [];
391
- const materials = [];
392
- for (const object of state.objects) {
393
- const { geometry } = object;
394
- // Skip o/g line declarations that did not follow with any faces
395
- if (geometry.vertices.length === 0)
396
- continue;
397
- const mesh = {
398
- header: {
399
- vertexCount: geometry.vertices.length / 3
400
- },
401
- attributes: {}
402
- };
403
- switch (geometry.type) {
404
- case 'Points':
405
- mesh.mode = 0; // GL.POINTS
406
- break;
407
- case 'Line':
408
- mesh.mode = 1; // GL.LINES
409
- break;
410
- default:
411
- mesh.mode = 4; // GL.TRIANGLES
412
- break;
413
- }
414
- mesh.attributes.POSITION = { value: new Float32Array(geometry.vertices), size: 3 };
415
- if (geometry.normals.length > 0) {
416
- mesh.attributes.NORMAL = { value: new Float32Array(geometry.normals), size: 3 };
417
- }
418
- if (geometry.colors.length > 0) {
419
- mesh.attributes.COLOR_0 = { value: new Float32Array(geometry.colors), size: 3 };
420
- }
421
- if (geometry.uvs.length > 0) {
422
- mesh.attributes.TEXCOORD_0 = { value: new Float32Array(geometry.uvs), size: 2 };
423
- }
424
- // Create materials
425
- mesh.materials = [];
426
- for (const sourceMaterial of object.materials) {
427
- // TODO - support full spec
428
- const _material = {
429
- name: sourceMaterial.name,
430
- flatShading: !sourceMaterial.smooth
431
- };
432
- mesh.materials.push(_material);
433
- materials.push(_material);
434
- }
435
- mesh.name = object.name;
436
- meshes.push(mesh);
437
- }
438
- return { meshes, materials };
439
- }
440
- exports.parseOBJMeshes = parseOBJMeshes;
@@ -1,72 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseOBJ = void 0;
4
- const schema_1 = require("@loaders.gl/schema");
5
- const parse_obj_meshes_1 = require("./parse-obj-meshes");
6
- const get_obj_schema_1 = require("./get-obj-schema");
7
- function parseOBJ(text, options) {
8
- const { meshes } = (0, parse_obj_meshes_1.parseOBJMeshes)(text);
9
- // @ts-expect-error
10
- const vertexCount = meshes.reduce((s, mesh) => s + mesh.header.vertexCount, 0);
11
- // TODO - render objects separately
12
- const attributes = mergeAttributes(meshes, vertexCount);
13
- const header = {
14
- vertexCount,
15
- // @ts-ignore Need to export Attributes type
16
- boundingBox: (0, schema_1.getMeshBoundingBox)(attributes)
17
- };
18
- const schema = (0, get_obj_schema_1.getOBJSchema)(attributes, {
19
- mode: 4,
20
- boundingBox: header.boundingBox
21
- });
22
- return {
23
- // Data return by this loader implementation
24
- loaderData: {
25
- header: {}
26
- },
27
- // Normalised data
28
- schema,
29
- header,
30
- mode: 4,
31
- topology: 'point-list',
32
- attributes
33
- };
34
- }
35
- exports.parseOBJ = parseOBJ;
36
- // eslint-disable-next-line max-statements
37
- function mergeAttributes(meshes, vertexCount) {
38
- const positions = new Float32Array(vertexCount * 3);
39
- let normals;
40
- let colors;
41
- let uvs;
42
- let i = 0;
43
- for (const mesh of meshes) {
44
- const { POSITION, NORMAL, COLOR_0, TEXCOORD_0 } = mesh.attributes;
45
- positions.set(POSITION.value, i * 3);
46
- if (NORMAL) {
47
- normals = normals || new Float32Array(vertexCount * 3);
48
- normals.set(NORMAL.value, i * 3);
49
- }
50
- if (COLOR_0) {
51
- colors = colors || new Float32Array(vertexCount * 3);
52
- colors.set(COLOR_0.value, i * 3);
53
- }
54
- if (TEXCOORD_0) {
55
- uvs = uvs || new Float32Array(vertexCount * 2);
56
- uvs.set(TEXCOORD_0.value, i * 2);
57
- }
58
- i += POSITION.value.length / 3;
59
- }
60
- const attributes = {};
61
- attributes.POSITION = { value: positions, size: 3 };
62
- if (normals) {
63
- attributes.NORMAL = { value: normals, size: 3 };
64
- }
65
- if (colors) {
66
- attributes.COLOR_0 = { value: colors, size: 3 };
67
- }
68
- if (uvs) {
69
- attributes.TEXCOORD_0 = { value: uvs, size: 2 };
70
- }
71
- return attributes;
72
- }
@@ -1,24 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports._typecheckMTLLoader = exports.MTLLoader = void 0;
4
- // __VERSION__ is injected by babel-plugin-version-inline
5
- // @ts-ignore TS2304: Cannot find name '__VERSION__'.
6
- const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';
7
- /**
8
- * Loader for the MTL material format
9
- * Parses a Wavefront .mtl file specifying materials
10
- */
11
- exports.MTLLoader = {
12
- name: 'MTL',
13
- id: 'mtl',
14
- module: 'mtl',
15
- version: VERSION,
16
- worker: true,
17
- extensions: ['mtl'],
18
- mimeTypes: ['text/plain'],
19
- testText: (text) => text.includes('newmtl'),
20
- options: {
21
- mtl: {}
22
- }
23
- };
24
- exports._typecheckMTLLoader = exports.MTLLoader;
@@ -1,27 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports._typecheckOBJLoader = exports.OBJLoader = void 0;
4
- // __VERSION__ is injected by babel-plugin-version-inline
5
- // @ts-ignore TS2304: Cannot find name '__VERSION__'.
6
- const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';
7
- /**
8
- * Worker loader for the OBJ geometry format
9
- */
10
- exports.OBJLoader = {
11
- name: 'OBJ',
12
- id: 'obj',
13
- module: 'obj',
14
- version: VERSION,
15
- worker: true,
16
- extensions: ['obj'],
17
- mimeTypes: ['text/plain'],
18
- testText: testOBJFile,
19
- options: {
20
- obj: {}
21
- }
22
- };
23
- function testOBJFile(text) {
24
- // TODO - There could be comment line first
25
- return text[0] === 'v';
26
- }
27
- exports._typecheckOBJLoader = exports.OBJLoader;
@@ -1,5 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const loader_utils_1 = require("@loaders.gl/loader-utils");
4
- const index_1 = require("../index");
5
- (0, loader_utils_1.createLoaderWorker)(index_1.OBJLoader);