1 /*
2 * Copyright (C) 2012 Alberto Irurueta Carro (alberto@irurueta.com)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package com.irurueta.geometry.io;
17
18 import com.irurueta.geometry.Point3D;
19 import com.irurueta.geometry.Triangle3D;
20 import com.irurueta.geometry.Triangulator3D;
21 import com.irurueta.geometry.TriangulatorException;
22
23 import java.io.File;
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.Collections;
27 import java.util.HashSet;
28 import java.util.LinkedList;
29 import java.util.List;
30 import java.util.Set;
31 import java.util.TreeMap;
32
33 /**
34 * Loads an OBJ file.
35 * If a LoaderListenerOBJ is provided, this class might also attempt to load the
36 * associated material file if available.
37 */
38 public class LoaderOBJ extends Loader {
39
40 /**
41 * Number of vertices of a triangle.
42 */
43 private static final long VERTICES_PER_TRIANGLE = 3L;
44
45 /**
46 * Constant defining the default value of maximum number of vertices to keep
47 * in a chunk. This is 65535, which corresponds to the maximum value allowed
48 * by graphical layer such as OpenGL when working with Vertex Buffer Objects.
49 */
50 public static final int DEFAULT_MAX_VERTICES_IN_CHUNK = 0xffff;
51
52 /**
53 * Minimum allowed value for maximum number of vertices in chunk, which is
54 * one.
55 */
56 public static final int MIN_MAX_VERTICES_IN_CHUNK = 1;
57
58 /**
59 * Constant indicating that duplicated vertices are allowed by default,
60 * which allows faster loading.
61 */
62 public static final boolean DEFAULT_ALLOW_DUPLICATE_VERTICES_IN_CHUNK = true;
63
64 /**
65 * Maximum number of stream positions to be cached by default.
66 */
67 public static final int DEFAULT_MAX_STREAM_POSITIONS = 1000000;
68
69 /**
70 * Minimum allowed number of stream positions.
71 */
72 public static final int MIN_STREAM_POSITIONS = 1;
73
74 /**
75 * Amount of progress variation (1%) used to notify progress.
76 */
77 public static final float PROGRESS_DELTA = 0.01f;
78
79 /**
80 * Indicates that loading should continue even if triangulation of some
81 * polygons fails.
82 */
83 public static final boolean DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR = true;
84
85 /**
86 * Identifies materials.
87 */
88 private static final String USEMTL = "usemtl ";
89
90 /**
91 * Iterator to load OBJ file data in small chunks.
92 * Usually data is divided in chunks that can be directly loaded by
93 * graphic layers such as OpenGL.
94 */
95 private LoaderIteratorOBJ loaderIterator;
96
97 /**
98 * Maximum number of vertices allowed in a chunk. Once this value is
99 * exceeded when loading a file, a new chunk of data is created.
100 */
101 private int maxVerticesInChunk;
102
103 /**
104 * To allow faster file loading, it might be allowed to repeat points in a
105 * chunk. When representing data graphically, this has no visual.
106 * consequences but chunks will take up more memory. This value represents
107 * a trade-off between loading speed and memory usage.
108 */
109 private boolean allowDuplicateVerticesInChunk;
110
111 /**
112 * Maximum number of file stream positions to be cached.
113 * This class keeps a cache of positions in the file to allow faster file
114 * loading at the expense of larger memory usage.
115 * If the geometry of a file reuses a large number of points, keeping a
116 * large cache will increase the speed of loading a file, otherwise the
117 * impact of this parameter will be low.
118 * The default value will work fine for most cases.
119 */
120 private long maxStreamPositions;
121
122 /**
123 * List containing comments contained in the file.
124 */
125 private final List<String> comments;
126
127 /**
128 * Collection of materials contained in the material's file associated to an
129 * OBJ file.
130 */
131 private Set<Material> materials;
132
133 /**
134 * Determines if file loading should continue even if the triangulation of
135 * a polygon fails. The triangulation of a polygon might fail if the polygon
136 * is degenerate or has invalid numerical values such as NaN of infinity.
137 * If true, loading will continue but the result will lack the polygons that
138 * failed.
139 */
140 private boolean continueIfTriangulationError;
141
142 /**
143 * Constructor.
144 */
145 public LoaderOBJ() {
146 loaderIterator = null;
147 maxVerticesInChunk = DEFAULT_MAX_VERTICES_IN_CHUNK;
148 allowDuplicateVerticesInChunk = DEFAULT_ALLOW_DUPLICATE_VERTICES_IN_CHUNK;
149 maxStreamPositions = DEFAULT_MAX_STREAM_POSITIONS;
150 comments = new LinkedList<>();
151 continueIfTriangulationError = DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR;
152 }
153
154 /**
155 * Constructor.
156 *
157 * @param maxVerticesInChunk Maximum number of vertices allowed in a chunk.
158 * Once this value is exceeded when loading a file, a new chunk of data is
159 * created.
160 * @throws IllegalArgumentException if maximum number of vertices allowed in
161 * a chunk is lower than 1.
162 */
163 public LoaderOBJ(final int maxVerticesInChunk) {
164 loaderIterator = null;
165 internalSetMaxVerticesInChunk(maxVerticesInChunk);
166 allowDuplicateVerticesInChunk = DEFAULT_ALLOW_DUPLICATE_VERTICES_IN_CHUNK;
167 maxStreamPositions = DEFAULT_MAX_STREAM_POSITIONS;
168 comments = new LinkedList<>();
169 continueIfTriangulationError = DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR;
170 }
171
172 /**
173 * Constructor.
174 *
175 * @param maxVerticesInChunk Maximum number of vertices allowed in a chunk.
176 * Once this value is exceeded when loading a file, a new chunk of data is
177 * created.
178 * @param allowDuplicateVerticesInChunk indicates if repeated vertices in a
179 * chunk are allowed to provide faster file loading. When representing data
180 * graphically, this has no visual consequences but chunks will take up more
181 * memory.
182 * @throws IllegalArgumentException if maximum number of vertices allowed in
183 * a chunk is lower than 1.
184 */
185 public LoaderOBJ(final int maxVerticesInChunk, final boolean allowDuplicateVerticesInChunk) {
186 loaderIterator = null;
187 internalSetMaxVerticesInChunk(maxVerticesInChunk);
188 this.allowDuplicateVerticesInChunk = allowDuplicateVerticesInChunk;
189 maxStreamPositions = DEFAULT_MAX_STREAM_POSITIONS;
190 comments = new LinkedList<>();
191 continueIfTriangulationError = DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR;
192 }
193
194 /**
195 * Constructor.
196 *
197 * @param maxVerticesInChunk Maximum number of vertices allowed in a chunk.
198 * Once this value is exceeded when loading a file, a new chunk of data is
199 * created.
200 * @param allowDuplicateVerticesInChunk indicates if repeated vertices in a
201 * chunk are allowed to provide faster file loading. When representing data
202 * graphically, this has no visual consequences but chunks will take up more
203 * memory.
204 * @param maxStreamPositions Maximum number of file stream positions to be
205 * cached.
206 * @throws IllegalArgumentException if maximum number of vertices allowed in
207 * a chunk is lower than 1.
208 */
209 public LoaderOBJ(final int maxVerticesInChunk, final boolean allowDuplicateVerticesInChunk,
210 final long maxStreamPositions) {
211 loaderIterator = null;
212 internalSetMaxVerticesInChunk(maxVerticesInChunk);
213 this.allowDuplicateVerticesInChunk = allowDuplicateVerticesInChunk;
214 internalSetMaxStreamPositions(maxStreamPositions);
215 comments = new LinkedList<>();
216 continueIfTriangulationError = DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR;
217 }
218
219 /**
220 * Constructor.
221 *
222 * @param f file to be loaded.
223 * @throws IOException if an I/O error occurs.
224 */
225 public LoaderOBJ(final File f) throws IOException {
226 super(f);
227 loaderIterator = null;
228 maxVerticesInChunk = DEFAULT_MAX_VERTICES_IN_CHUNK;
229 allowDuplicateVerticesInChunk = DEFAULT_ALLOW_DUPLICATE_VERTICES_IN_CHUNK;
230 maxStreamPositions = DEFAULT_MAX_STREAM_POSITIONS;
231 comments = new LinkedList<>();
232 continueIfTriangulationError = DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR;
233 }
234
235 /**
236 * Constructor.
237 *
238 * @param f file to be loaded.
239 * @param maxVerticesInChunk Maximum number of vertices allowed in a chunk.
240 * Once this value is exceeded when loading a file, a new chunk of data is
241 * created.
242 * @throws IllegalArgumentException if maximum number of vertices allowed in
243 * a chunk is lower than 1.
244 * @throws IOException if an I/O error occurs.
245 */
246 public LoaderOBJ(final File f, final int maxVerticesInChunk) throws IOException {
247 super(f);
248 loaderIterator = null;
249 internalSetMaxVerticesInChunk(maxVerticesInChunk);
250 allowDuplicateVerticesInChunk = DEFAULT_ALLOW_DUPLICATE_VERTICES_IN_CHUNK;
251 maxStreamPositions = DEFAULT_MAX_STREAM_POSITIONS;
252 comments = new LinkedList<>();
253 continueIfTriangulationError = DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR;
254 }
255
256 /**
257 * Constructor.
258 *
259 * @param f file to be loaded.
260 * @param maxVerticesInChunk Maximum number of vertices allowed in a chunk.
261 * Once this value is exceeded when loading a file, a new chunk of data is
262 * created.
263 * @param allowDuplicateVerticesInChunk indicates if repeated vertices in a
264 * chunk are allowed to provide faster file loading. When representing data
265 * graphically, this has no visual consequences but chunks will take up more
266 * memory.
267 * @throws IllegalArgumentException if maximum number of vertices allowed in
268 * a chunk is lower than 1.
269 * @throws IOException if an I/O error occurs.
270 */
271 public LoaderOBJ(final File f, final int maxVerticesInChunk, final boolean allowDuplicateVerticesInChunk)
272 throws IOException {
273 super(f);
274 loaderIterator = null;
275 internalSetMaxVerticesInChunk(maxVerticesInChunk);
276 this.allowDuplicateVerticesInChunk = allowDuplicateVerticesInChunk;
277 maxStreamPositions = DEFAULT_MAX_STREAM_POSITIONS;
278 comments = new LinkedList<>();
279 continueIfTriangulationError = DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR;
280 }
281
282 /**
283 * Constructor.
284 *
285 * @param f file to be loaded.
286 * @param maxVerticesInChunk Maximum number of vertices allowed in a chunk.
287 * Once this value is exceeded when loading a file, a new chunk of data is
288 * created.
289 * @param allowDuplicateVerticesInChunk indicates if repeated vertices in a
290 * chunk are allowed to provide faster file loading. When representing data
291 * graphically, this has no visual consequences but chunks will take up more
292 * memory.
293 * @param maxStreamPositions Maximum number of file stream positions to be
294 * cached.
295 * @throws IllegalArgumentException if maximum number of vertices allowed in
296 * a chunk is lower than 1.
297 * @throws IOException if an I/O error occurs.
298 */
299 public LoaderOBJ(final File f, final int maxVerticesInChunk, final boolean allowDuplicateVerticesInChunk,
300 final long maxStreamPositions) throws IOException {
301 super(f);
302 loaderIterator = null;
303 internalSetMaxVerticesInChunk(maxVerticesInChunk);
304 this.allowDuplicateVerticesInChunk = allowDuplicateVerticesInChunk;
305 internalSetMaxStreamPositions(maxStreamPositions);
306 comments = new LinkedList<>();
307 continueIfTriangulationError = DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR;
308 }
309
310 /**
311 * Constructor.
312 *
313 * @param listener listener to be notified of loading progress and when
314 * loading process starts or finishes.
315 */
316 public LoaderOBJ(final LoaderListener listener) {
317 super(listener);
318 maxVerticesInChunk = DEFAULT_MAX_VERTICES_IN_CHUNK;
319 allowDuplicateVerticesInChunk = DEFAULT_ALLOW_DUPLICATE_VERTICES_IN_CHUNK;
320 maxStreamPositions = DEFAULT_MAX_STREAM_POSITIONS;
321 comments = new LinkedList<>();
322 continueIfTriangulationError = DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR;
323 }
324
325 /**
326 * Constructor.
327 *
328 * @param listener listener to be notified of loading progress and when
329 * loading process starts or finishes.
330 * @param maxVerticesInChunk Maximum number of vertices allowed in a chunk.
331 * Once this value is exceeded when loading a file, a new chunk of data is
332 * created.
333 * @throws IllegalArgumentException if maximum number of vertices allowed in
334 * a chunk is lower than 1.
335 */
336 public LoaderOBJ(final LoaderListener listener, final int maxVerticesInChunk) {
337 super(listener);
338 loaderIterator = null;
339 internalSetMaxVerticesInChunk(maxVerticesInChunk);
340 allowDuplicateVerticesInChunk = DEFAULT_ALLOW_DUPLICATE_VERTICES_IN_CHUNK;
341 maxStreamPositions = DEFAULT_MAX_STREAM_POSITIONS;
342 comments = new LinkedList<>();
343 continueIfTriangulationError = DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR;
344 }
345
346 /**
347 * Constructor.
348 *
349 * @param listener listener to be notified of loading progress and when
350 * loading process starts or finishes.
351 * @param maxVerticesInChunk Maximum number of vertices allowed in a chunk.
352 * Once this value is exceeded when loading a file, a new chunk of data is
353 * created.
354 * @param allowDuplicateVerticesInChunk indicates if repeated vertices in a
355 * chunk are allowed to provide faster file loading. When representing data
356 * graphically, this has no visual consequences but chunks will take up more
357 * memory.
358 * @throws IllegalArgumentException if maximum number of vertices allowed in
359 * a chunk is lower than 1.
360 */
361 public LoaderOBJ(final LoaderListener listener, final int maxVerticesInChunk,
362 final boolean allowDuplicateVerticesInChunk) {
363 super(listener);
364 loaderIterator = null;
365 internalSetMaxVerticesInChunk(maxVerticesInChunk);
366 this.allowDuplicateVerticesInChunk = allowDuplicateVerticesInChunk;
367 maxStreamPositions = DEFAULT_MAX_STREAM_POSITIONS;
368 comments = new LinkedList<>();
369 continueIfTriangulationError = DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR;
370 }
371
372 /**
373 * Constructor.
374 *
375 * @param listener listener to be notified of loading progress and when
376 * loading process starts or finishes.
377 * @param maxVerticesInChunk Maximum number of vertices allowed in a chunk.
378 * Once this value is exceeded when loading a file, a new chunk of data is
379 * created.
380 * @param allowDuplicateVerticesInChunk indicates if repeated vertices in a
381 * chunk are allowed to provide faster file loading. When representing data
382 * graphically, this has no visual consequences but chunks will take up more
383 * memory.
384 * @param maxStreamPositions Maximum number of file stream positions to be
385 * cached.
386 * @throws IllegalArgumentException if maximum number of vertices allowed in
387 * a chunk is lower than 1.
388 */
389 public LoaderOBJ(final LoaderListener listener, final int maxVerticesInChunk,
390 final boolean allowDuplicateVerticesInChunk, final long maxStreamPositions) {
391 super(listener);
392 loaderIterator = null;
393 internalSetMaxVerticesInChunk(maxVerticesInChunk);
394 this.allowDuplicateVerticesInChunk = allowDuplicateVerticesInChunk;
395 internalSetMaxStreamPositions(maxStreamPositions);
396 comments = new LinkedList<>();
397 continueIfTriangulationError = DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR;
398 }
399
400 /**
401 * Constructor.
402 *
403 * @param f file to be loaded.
404 * @param listener listener to be notified of loading progress and when
405 * loading process starts or finishes.
406 * @throws IOException if an I/O error occurs.
407 */
408 public LoaderOBJ(final File f, final LoaderListener listener) throws IOException {
409 super(f, listener);
410 loaderIterator = null;
411 maxVerticesInChunk = DEFAULT_MAX_VERTICES_IN_CHUNK;
412 allowDuplicateVerticesInChunk = DEFAULT_ALLOW_DUPLICATE_VERTICES_IN_CHUNK;
413 maxStreamPositions = DEFAULT_MAX_STREAM_POSITIONS;
414 comments = new LinkedList<>();
415 continueIfTriangulationError = DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR;
416 }
417
418 /**
419 * Constructor.
420 *
421 * @param f file to be loaded.
422 * @param listener listener to be notified of loading progress and when
423 * loading process starts or finishes.
424 * @param maxVerticesInChunk Maximum number of vertices allowed in a chunk.
425 * Once this value is exceeded when loading a file, a new chunk of data is
426 * created.
427 * @throws IllegalArgumentException if maximum number of vertices allowed in
428 * a chunk is lower than 1.
429 * @throws IOException if an I/O error occurs.
430 */
431 public LoaderOBJ(final File f, final LoaderListener listener, final int maxVerticesInChunk) throws IOException {
432 super(f, listener);
433 loaderIterator = null;
434 internalSetMaxVerticesInChunk(maxVerticesInChunk);
435 allowDuplicateVerticesInChunk = DEFAULT_ALLOW_DUPLICATE_VERTICES_IN_CHUNK;
436 maxStreamPositions = DEFAULT_MAX_STREAM_POSITIONS;
437 comments = new LinkedList<>();
438 continueIfTriangulationError = DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR;
439 }
440
441 /**
442 * Constructor.
443 *
444 * @param f file to be loaded.
445 * @param listener listener to be notified of loading progress and when
446 * loading process starts or finishes.
447 * @param maxVerticesInChunk Maximum number of vertices allowed in a chunk.
448 * Once this value is exceeded when loading a file, a new chunk of data is
449 * created.
450 * @param allowDuplicateVerticesInChunk indicates if repeated vertices in a
451 * chunk are allowed to provide faster file loading. When representing data
452 * graphically, this has no visual consequences but chunks will take up more
453 * memory.
454 * @throws IllegalArgumentException if maximum number of vertices allowed in
455 * a chunk is lower than 1.
456 * @throws IOException if an I/O error occurs.
457 */
458 public LoaderOBJ(final File f, final LoaderListener listener, final int maxVerticesInChunk,
459 final boolean allowDuplicateVerticesInChunk) throws IOException {
460 super(f, listener);
461 loaderIterator = null;
462 internalSetMaxVerticesInChunk(maxVerticesInChunk);
463 this.allowDuplicateVerticesInChunk = allowDuplicateVerticesInChunk;
464 maxStreamPositions = DEFAULT_MAX_STREAM_POSITIONS;
465 comments = new LinkedList<>();
466 continueIfTriangulationError = DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR;
467 }
468
469 /**
470 * Constructor.
471 *
472 * @param f file to be loaded.
473 * @param listener listener to be notified of loading progress and when
474 * loading process starts or finishes.
475 * @param maxVerticesInChunk Maximum number of vertices allowed in a chunk.
476 * Once this value is exceeded when loading a file, a new chunk of data is
477 * created.
478 * @param allowDuplicateVerticesInChunk indicates if repeated vertices in a
479 * chunk are allowed to provide faster file loading. When representing data
480 * graphically, this has no visual consequences but chunks will take up more
481 * memory.
482 * @param maxStreamPositions Maximum number of file stream positions to be
483 * cached.
484 * @throws IllegalArgumentException if maximum number of vertices allowed in
485 * a chunk is lower than 1.
486 * @throws IOException if an I/O error occurs.
487 */
488 public LoaderOBJ(final File f, final LoaderListener listener, final int maxVerticesInChunk,
489 final boolean allowDuplicateVerticesInChunk, final long maxStreamPositions) throws IOException {
490 super(f, listener);
491 loaderIterator = null;
492 internalSetMaxVerticesInChunk(maxVerticesInChunk);
493 this.allowDuplicateVerticesInChunk = allowDuplicateVerticesInChunk;
494 internalSetMaxStreamPositions(maxStreamPositions);
495 comments = new LinkedList<>();
496 continueIfTriangulationError = DEFAULT_CONTINUE_IF_TRIANGULATION_ERROR;
497 }
498
499 /**
500 * Returns maximum number of vertices allowed in a chunk.
501 * Once this value is exceeded when loading a file, a new chunk of data is
502 * created.
503 *
504 * @return maximum number of vertices allowed in a chunk.
505 */
506 public int getMaxVerticesInChunk() {
507 return maxVerticesInChunk;
508 }
509
510 /**
511 * Sets maximum number of vertices allowed in a chunk.
512 * Once this value is exceeded when loading a file, a new chunk of data is
513 * created.
514 *
515 * @param maxVerticesInChunk maximum allowed number of vertices to be set.
516 * @throws IllegalArgumentException if provided value is lower than 1.
517 * @throws LockedException if this loader is currently loading a file.
518 */
519 public void setMaxVerticesInChunk(final int maxVerticesInChunk) throws LockedException {
520 if (isLocked()) {
521 throw new LockedException();
522 }
523 internalSetMaxVerticesInChunk(maxVerticesInChunk);
524 }
525
526 /**
527 * Returns boolean indicating if repeated vertices in a chunk are allowed to
528 * provide faster file loading. When representing data graphically, this has
529 * no visual consequences but chunks will take up more memory.
530 *
531 * @return true if duplicate vertices are allowed, false otherwise.
532 */
533 public boolean areDuplicateVerticesInChunkAllowed() {
534 return allowDuplicateVerticesInChunk;
535 }
536
537 /**
538 * Sets boolean indicating if repeated vertices in a chunk are allowed to
539 * provide faster file loading. When representing data graphically, this has
540 * no visual consequences but chunks will take up more memory.
541 *
542 * @param allow true if duplicate vertices are allowed, false otherwise.
543 * @throws LockedException if this loader is currently loading a file.
544 */
545 public void setAllowDuplicateVerticesInChunk(final boolean allow) throws LockedException {
546 if (isLocked()) {
547 throw new LockedException();
548 }
549 allowDuplicateVerticesInChunk = allow;
550 }
551
552 /**
553 * Returns maximum number of file stream positions to be cached.
554 * This class keeps a cache of positions in the file to allow faster file
555 * loading at the expense of larger memory usage.
556 * If the geometry of a file reuses a large number of points, keeping a
557 * large cache will increase the speed of loading a file, otherwise the
558 * impact of this parameter will be low.
559 * The default value will work fine for most cases.
560 *
561 * @return maximum number of file stream positions to be cached.
562 */
563 public long getMaxStreamPositions() {
564 return maxStreamPositions;
565 }
566
567 /**
568 * Sets maximum number of file stream positions to be cached.
569 * This class keeps a cache of positions in the file to allow faster file
570 * loading at the expense of larger memory usage.
571 * If the geometry of a file reuses a large number of points, keeping a
572 * large cache will increase the speed of loading a file, otherwise the
573 * impact of this parameter will be low.
574 * The default value will work fine for most cases.
575 *
576 * @param maxStreamPositions maximum number of file stream positions to be
577 * set.
578 * @throws IllegalArgumentException if provided value is lower than 1.
579 * @throws LockedException if this loader is currently loading a file.
580 */
581 public void setMaxStreamPositions(final long maxStreamPositions) throws LockedException {
582 if (isLocked()) {
583 throw new LockedException();
584 }
585 internalSetMaxStreamPositions(maxStreamPositions);
586 }
587
588 /**
589 * Returns boolean indicating if file loading should continue even if the
590 * triangulation of a polygon fails. The triangulation of a polygon might
591 * fail if the polygon is degenerate or has invalid numerical values such as
592 * NaN of infinity.
593 *
594 * @return If true, loading will continue but the result will lack the
595 * polygons that failed.
596 */
597 public boolean isContinueIfTriangulationError() {
598 return continueIfTriangulationError;
599 }
600
601 /**
602 * Sets boolean indicating if file loading should continue even if the
603 * triangulation of a polygon fails. The triangulation of a polygon might
604 * fail if the polygon is degenerate or has invalid numerical values such as
605 * NaN or infinity.
606 *
607 * @param continueIfTriangulationError if ture, loading will continue but
608 * the result will lack the polygons that failed.
609 */
610 public void setContinueIfTriangulationError(final boolean continueIfTriangulationError) {
611 this.continueIfTriangulationError = continueIfTriangulationError;
612 }
613
614 /**
615 * Returns a list of the comments contained in the file.
616 *
617 * @return list of the comments contained in the file.
618 */
619 public List<String> getComments() {
620 return Collections.unmodifiableList(comments);
621 }
622
623 /**
624 * Gets collection of materials contained in the materials file associated to an
625 * OBJ file.
626 *
627 * @return collection of material.
628 */
629 public Set<Material> getMaterials() {
630 return materials;
631 }
632
633 /**
634 * If loader is ready to start loading a file.
635 * This is true once a file has been provided.
636 *
637 * @return true if ready to start loading a file, false otherwise.
638 */
639 @Override
640 public boolean isReady() {
641 return hasFile();
642 }
643
644 /**
645 * Returns mesh format supported by this class, which is MESH_FORMAT_OBJ.
646 *
647 * @return mesh format supported by this class.
648 */
649 @Override
650 public MeshFormat getMeshFormat() {
651 return MeshFormat.MESH_FORMAT_OBJ;
652 }
653
654 /**
655 * Determines if provided file is a valid file that can be read by this
656 * loader.
657 *
658 * @return true if file is valid, false otherwise.
659 * @throws LockedException raised if this instance is already locked.
660 * @throws IOException if an I/O error occurs..
661 */
662 @Override
663 public boolean isValidFile() throws LockedException, IOException {
664 if (!hasFile()) {
665 throw new IOException();
666 }
667 if (isLocked()) {
668 throw new LockedException();
669 }
670 return true;
671 }
672
673 /**
674 * Starts the loading process of provided file.
675 * This method returns a LoaderIterator to start the iterative process to
676 * load a file in small chunks of data.
677 *
678 * @return a loader iterator to read the file in a step-by-step process.
679 * @throws LockedException raised if this instance is already locked.
680 * @throws NotReadyException raised if this instance is not yet ready.
681 * @throws IOException if an I/O error occurs.
682 * @throws LoaderException if file is corrupted or cannot be interpreted.
683 */
684 @Override
685 public LoaderIterator load() throws LockedException, NotReadyException, IOException, LoaderException {
686 if (isLocked()) {
687 throw new LockedException();
688 }
689 if (!isReady()) {
690 throw new NotReadyException();
691 }
692
693 setLocked(true);
694 if (listener != null) {
695 listener.onLoadStart(this);
696 }
697
698 // do not leave this loader locked if file cannot be loaded
699 loaderIterator = loadReleasingLockOnFailure(
700 () -> new LoaderIteratorOBJ(this));
701 loaderIterator.setListener(new LoaderIteratorListenerImpl(this));
702 return loaderIterator;
703 }
704
705 /**
706 * Internal method to set maximum number of vertices allowed in a chunk.
707 * This method is reused both in the constructor and in the setter of
708 * maximum number of vertices allowed in a chunk.
709 *
710 * @param maxVerticesInChunk maximum allowed number of vertices to be set.
711 * @throws IllegalArgumentException if provided value is lower than 1.
712 */
713 private void internalSetMaxVerticesInChunk(final int maxVerticesInChunk) {
714 if (maxVerticesInChunk < MIN_MAX_VERTICES_IN_CHUNK) {
715 throw new IllegalArgumentException();
716 }
717
718 this.maxVerticesInChunk = maxVerticesInChunk;
719 }
720
721 /**
722 * Internal method to set maximum number of file stream positions to be
723 * cached.
724 * This method is reused both in the constructor and in the setter of
725 * maximum number stream positions.
726 *
727 * @param maxStreamPositions maximum number of file stream positions to be
728 * cached.
729 * @throws IllegalArgumentException if provided value is lower than 1.
730 */
731 private void internalSetMaxStreamPositions(final long maxStreamPositions) {
732 if (maxStreamPositions < MIN_STREAM_POSITIONS) {
733 throw new IllegalArgumentException();
734 }
735
736 this.maxStreamPositions = maxStreamPositions;
737 }
738
739 /**
740 * Internal listener to be notified when loading process finishes.
741 * This listener is used to free resources when loading process finishes.
742 */
743 private class LoaderIteratorListenerImpl implements LoaderIteratorListener {
744
745 /**
746 * Reference to Loader loading an OBJ file.
747 */
748 private final LoaderOBJ loader;
749
750 /**
751 * Constructor.
752 *
753 * @param loader reference to Loader.
754 */
755 public LoaderIteratorListenerImpl(final LoaderOBJ loader) {
756 this.loader = loader;
757 }
758
759 /**
760 * Method to be notified when the loading process finishes.
761 *
762 * @param iterator iterator loading the file in chunks.
763 */
764 @Override
765 public void onIteratorFinished(final LoaderIterator iterator) {
766 // because iterator is finished, we should allow subsequent calls to
767 // load method
768 try {
769 // attempt restart stream to initial position
770 reader.seek(0);
771 } catch (final Exception ignore) {
772 // this is the best effort operation, if it fails it is ignored
773 }
774
775 // on subsequent calls
776 if (listener != null) {
777 listener.onLoadEnd(loader);
778 }
779 setLocked(false);
780 }
781 }
782
783 /**
784 * Loader iterator in charge of loading file data in small chunks.
785 * Usually data is divided in chunks small enough that can be directly
786 * loaded by graphical layers such as OpenGL (which has a limit of 65535
787 * indices when using Vertex Buffer Objects, which increase graphical
788 * performance).
789 */
790 private class LoaderIteratorOBJ implements LoaderIterator {
791
792 /**
793 * Reference to loader loading OBJ file.
794 */
795 private final LoaderOBJ loader;
796
797 /**
798 * X coordinate of the latest point that has been read.
799 */
800 private float coordX;
801
802 /**
803 * Y coordinate of the latest point that has been read.
804 */
805 private float coordY;
806
807 /**
808 * Z coordinate of the latest point that has been read.
809 */
810 private float coordZ;
811
812 /**
813 * U texture coordinate of the latest point that has been read.
814 * U coordinate refers to the horizontal axis in the texture image and
815 * usually is a normalized value between 0.0 and 1.0. Larger values can
816 * be used to repeat textures, negative values can be used to reverse
817 * textures.
818 */
819 private float textureU;
820
821 /**
822 * V texture coordinate of the latest point that has been read.
823 * V coordinate refers to the vertical axis in the texture image and
824 * usually is a normalized value between 0.0 and 1.0. Larger values can
825 * be used to repeat textures, negative values can be used to reverse
826 * textures.
827 */
828 private float textureV;
829
830 /**
831 * X coordinate of the latest point normal that has been read.
832 */
833 private float nX;
834
835 /**
836 * Y coordinate of the latest point normal that has been read.
837 */
838 private float nY;
839
840 /**
841 * Z coordinate of the latest point normal that has been read.
842 */
843 private float nZ;
844
845 /**
846 * Vertex index in the file of the latest point that has been read.
847 */
848 private int vertexIndex;
849
850 /**
851 * Texture index in the file of the latest point that has been read.
852 */
853 private int textureIndex;
854
855 /**
856 * Normal index in the file of the latest point that has been read.
857 */
858 private int normalIndex;
859
860 // coordinates for bounding box in a chunk
861
862 /**
863 * X coordinate of the minimum point forming the bounding box in a chunk
864 * of data. This value will be updated while the chunk is being filled.
865 */
866 private float minX;
867
868 /**
869 * Y coordinate of the minimum point forming the bounding box in a chunk
870 * of data. This value will be updated while the chunk is being filled.
871 */
872 private float minY;
873
874 /**
875 * Z coordinate of the minimum point forming the bounding box in a chunk
876 * of data. This value will be updated while the chunk is being filled.
877 */
878 private float minZ;
879
880 /**
881 * X coordinate of the maximum point forming the bounding box in a chunk
882 * of data. This value will be updated while the chunk is being filled.
883 */
884 private float maxX;
885
886 /**
887 * Y coordinate of the maximum point forming the bounding box in a chunk
888 * of data. This value will be updated while the chunk is being filled.
889 */
890 private float maxY;
891
892 /**
893 * Z coordinate of the maximum point forming the bounding box in a chunk
894 * of data. This value will be updated while the chunk is being filled.
895 */
896 private float maxZ;
897
898 /**
899 * Indicates if vertices have been loaded and must be added to current
900 * chunk being loaded.
901 */
902 private boolean verticesAvailable;
903
904 /**
905 * Indicates if texture coordinates have been loaded and must be added
906 * to current chunk being loaded.
907 */
908 private boolean textureAvailable;
909
910 /**
911 * Indicates if normals have been loaded and must be added to current
912 * chunk being loaded.
913 */
914 private boolean normalsAvailable;
915
916 /**
917 * Indicates if indices have been loaded and must be added to current
918 * chunk being loaded.
919 */
920 private boolean indicesAvailable;
921
922 /**
923 * Indicates if materials have been loaded and must be added to current
924 * chunk being loaded.
925 */
926 private boolean materialsAvailable;
927
928 /**
929 * Number of vertices that have been loaded in current chunk.
930 */
931 private long numberOfVertices;
932
933 /**
934 * Number of texture coordinates that have been loaded in current chunk.
935 */
936 private long numberOfTextureCoords;
937
938 /**
939 * Number of normals that have been loaded in current chunk.
940 */
941 private long numberOfNormals;
942
943 /**
944 * Number of faces (i.e. polygons) that have been loaded in current
945 * chunk.
946 */
947 private long numberOfFaces;
948
949 /**
950 * Index of current face (i.e. polygon) that has been loaded.
951 */
952 private long currentFace;
953
954 /**
955 * Position of first vertex in the file. This is stored to reduce
956 * fetching time when parsing the OBJ file.
957 */
958 private long firstVertexStreamPosition;
959
960 /**
961 * Indicates if first vertex position has been found.
962 */
963 private boolean firstVertexStreamPositionAvailable;
964
965 /**
966 * Position of first texture coordinate in the file. This is stored to
967 * reduce fetching time when parsing the OBJ file.
968 */
969 private long firstTextureCoordStreamPosition;
970
971 /**
972 * Indicates if first texture coordinate has been found.
973 */
974 private boolean firstTextureCoordStreamPositionAvailable;
975
976 /**
977 * Position of first normal coordinate in the file. This is stored to
978 * reduce fetching time when parsing the OBJ file.
979 */
980 private long firstNormalStreamPosition;
981
982 /**
983 * Indicates if first normal coordinate has been found.
984 */
985 private boolean firstNormalStreamPositionAvailable;
986
987 /**
988 * Position of first face (i.e. polygon) in the file. This is stored to
989 * reduce fetching time when parsing the OBJ file.
990 */
991 private long firstFaceStreamPosition;
992
993 /**
994 * Indicates if first face has been found.
995 */
996 private boolean firstFaceStreamPositionAvailable;
997
998 /**
999 * Indicates location of first material in the file. This is stored to
1000 * reduce fetching time when parsing the OBJ file.
1001 */
1002 private long firstMaterialStreamPosition;
1003
1004 /**
1005 * Indicates if first material has been found.
1006 */
1007 private boolean firstMaterialStreamPositionAvailable;
1008
1009 /**
1010 * Contains position where file is currently being loaded.
1011 */
1012 private long currentStreamPosition;
1013
1014 /**
1015 * Reference to the listener of this loader iterator. This listener will
1016 * be notified when the loading process finishes so that resources can
1017 * be freed.
1018 */
1019 private LoaderIteratorListener listener;
1020
1021 /**
1022 * Array containing vertices coordinates to be added to current chunk
1023 * of data.
1024 */
1025 private float[] coordsInChunkArray;
1026
1027 /**
1028 * Array containing texture coordinates to be added to current chunk of
1029 * data.
1030 */
1031 private float[] textureCoordsInChunkArray;
1032
1033 /**
1034 * Array containing normal coordinates to be added to current chunk of
1035 * data.
1036 */
1037 private float[] normalsInChunkArray;
1038
1039 /**
1040 * Array containing indices to be added to current chunk of data. Notice
1041 * that these indices are not the original indices appearing in the file.
1042 * Instead, they are indices referring to data in current chunk,
1043 * accounting for duplicate points, etc. This way, indices in a chunk
1044 * can be directly used to draw the chunk of data by the graphical layer.
1045 */
1046 private int[] indicesInChunkArray;
1047
1048 /**
1049 * Array containing vertex indices as they appear in the OBJ file.
1050 * These indices are only used to fetch data, they will never appear in
1051 * resulting chunk of data.
1052 */
1053 private long[] originalVertexIndicesInChunkArray;
1054
1055 /**
1056 * Array containing texture indices as they appear in the OBJ file.
1057 * These indices are only used to fetch data, they will never appear in
1058 * resulting chunk of data.
1059 */
1060 private long[] originalTextureIndicesInChunkArray;
1061
1062 /**
1063 * Array containing normal indices as they appear in the OBJ file.
1064 * These indices are only used to fetch data, they will never appear in
1065 * resulting chunk of data.
1066 */
1067 private long[] originalNormalIndicesInChunkArray;
1068
1069 /**
1070 * Map to relate vertex indices in a file respect to chunk indices.
1071 */
1072 private final TreeMap<Long, Integer> vertexIndicesMap;
1073
1074 /**
1075 * Map to relate texture coordinates indices in a file respect to chunk
1076 * indices.
1077 */
1078 private final TreeMap<Long, Integer> textureCoordsIndicesMap;
1079
1080 /**
1081 * Map to relate normals coordinates indices in a file respect to chunk
1082 * indices.
1083 */
1084 private final TreeMap<Long, Integer> normalsIndicesMap;
1085
1086 /**
1087 * Map to cache vertex positions in a file.
1088 */
1089 private final TreeMap<Long, Long> verticesStreamPositionMap;
1090
1091 /**
1092 * Map to cache texture coordinates positions in a file.
1093 */
1094 private final TreeMap<Long, Long> textureCoordsStreamPositionMap;
1095
1096 /**
1097 * Map to cache normals coordinates positions in a file.
1098 */
1099 private final TreeMap<Long, Long> normalsStreamPositionMap;
1100
1101 /**
1102 * Number of vertices stored in chunk.
1103 */
1104 private int verticesInChunk;
1105
1106 /**
1107 * Number of indices stored in chunk.
1108 */
1109 private int indicesInChunk;
1110
1111 /**
1112 * Size of indices stored in chunk.
1113 */
1114 private int indicesInChunkSize;
1115
1116 /**
1117 * Vertex position in file.
1118 */
1119 private long vertexStreamPosition;
1120
1121 /**
1122 * Texture coordinate position in file.
1123 */
1124 private long textureCoordStreamPosition;
1125
1126 /**
1127 * Normal coordinate position in file.
1128 */
1129 private long normalStreamPosition;
1130
1131 /**
1132 * Name of current material of data being loaded.
1133 */
1134 private String currentChunkMaterialName;
1135
1136 /**
1137 * Reference to current material of data being loaded.
1138 */
1139 private MaterialOBJ currentMaterial;
1140
1141 /**
1142 * Reference to material loader in charge of loading the associated MTL
1143 * of file to this OBJ file.
1144 */
1145 private MaterialLoaderOBJ materialLoader;
1146
1147 /**
1148 * Constructor.
1149 *
1150 * @param loader reference to loader loading binary file.
1151 * @throws IOException if an I/O error occurs.
1152 * @throws LoaderException if file data is corrupt or cannot be
1153 * understood.
1154 */
1155 public LoaderIteratorOBJ(final LoaderOBJ loader) throws IOException, LoaderException {
1156 this.loader = loader;
1157 nX = nY = nZ = 1.0f;
1158 vertexIndex = textureIndex = normalIndex = 0;
1159 verticesAvailable = textureAvailable = normalsAvailable = indicesAvailable = materialsAvailable = false;
1160 numberOfVertices = numberOfTextureCoords = numberOfNormals = numberOfFaces = 0;
1161 currentFace = 0;
1162 firstVertexStreamPosition = 0;
1163 firstVertexStreamPositionAvailable = false;
1164 firstTextureCoordStreamPosition = 0;
1165 firstTextureCoordStreamPositionAvailable = false;
1166 firstNormalStreamPosition = 0;
1167 firstNormalStreamPositionAvailable = false;
1168 firstFaceStreamPosition = 0;
1169 firstFaceStreamPositionAvailable = false;
1170 firstMaterialStreamPosition = 0;
1171 firstMaterialStreamPositionAvailable = false;
1172 currentStreamPosition = 0;
1173 listener = null;
1174 coordsInChunkArray = null;
1175 textureCoordsInChunkArray = null;
1176 normalsInChunkArray = null;
1177 indicesInChunkArray = null;
1178
1179 originalVertexIndicesInChunkArray = null;
1180 originalTextureIndicesInChunkArray = null;
1181 originalNormalIndicesInChunkArray = null;
1182
1183 vertexIndicesMap = new TreeMap<>();
1184 textureCoordsIndicesMap = new TreeMap<>();
1185 normalsIndicesMap = new TreeMap<>();
1186
1187 verticesStreamPositionMap = new TreeMap<>();
1188 textureCoordsStreamPositionMap = new TreeMap<>();
1189 normalsStreamPositionMap = new TreeMap<>();
1190
1191 verticesInChunk = indicesInChunk = 0;
1192 indicesInChunkSize = 0;
1193
1194 vertexStreamPosition = 0;
1195 textureCoordStreamPosition = 0;
1196 normalStreamPosition = 0;
1197
1198 minX = minY = minZ = Float.MAX_VALUE;
1199 maxX = maxY = maxZ = -Float.MAX_VALUE;
1200
1201 currentChunkMaterialName = "";
1202
1203 materialLoader = null;
1204
1205 setUp();
1206 }
1207
1208 /**
1209 * Method to set listener of this loader iterator.
1210 * This listener will be notified when the loading process finishes.
1211 *
1212 * @param listener listener of this loader iterator.
1213 */
1214 public void setListener(final LoaderIteratorListener listener) {
1215 this.listener = listener;
1216 }
1217
1218 /**
1219 * Indicates if there is another chunk of data to be loaded.
1220 *
1221 * @return true if there is another chunk of data, false otherwise.
1222 */
1223 @Override
1224 public boolean hasNext() {
1225 return currentFace < numberOfFaces;
1226 }
1227
1228 /**
1229 * Loads and returns next chunk of data, if available.
1230 *
1231 * @return next chunk of data.
1232 * @throws NotAvailableException thrown if no more data is available.
1233 * @throws LoaderException if file data is corrupt or cannot be
1234 * understood.
1235 * @throws IOException if an I/O error occurs.
1236 */
1237 @Override
1238 public DataChunk next() throws NotAvailableException, LoaderException, IOException {
1239 if (reader == null) {
1240 throw new IOException();
1241 }
1242
1243 if (!hasNext()) {
1244 throw new NotAvailableException();
1245 }
1246
1247 // do not leave loader locked if file cannot be read
1248 return readReleasingLockOnFailure(this::readNextChunk);
1249 }
1250
1251 /**
1252 * Reads next chunk of data.
1253 *
1254 * @return next chunk of data.
1255 * @throws NotAvailableException if no more data is available.
1256 * @throws LoaderException if file data is corrupt or cannot be
1257 * understood.
1258 * @throws IOException if an I/O error occurs.
1259 */
1260 private DataChunk readNextChunk()
1261 throws NotAvailableException, LoaderException, IOException {
1262 initChunkArrays();
1263
1264 // reset chunk bounding box values
1265 minX = minY = minZ = Float.MAX_VALUE;
1266 maxX = maxY = maxZ = -Float.MAX_VALUE;
1267
1268 final var progressStep = Math.max((long) (LoaderOBJ.PROGRESS_DELTA * numberOfFaces), 1);
1269
1270 boolean materialChange = false;
1271
1272 try {
1273 while (currentFace < numberOfFaces) { // && !materialChange
1274
1275 final var faceStreamPos = reader.getPosition();
1276 var str = reader.readLine();
1277 if ((str == null) && (currentFace < (numberOfFaces - 1))) {
1278 // unexpected end of file
1279 throw new LoaderException();
1280 } else if (str == null) {
1281 break;
1282 }
1283
1284 // check if line corresponds to face or material, otherwise,
1285 // ignore
1286 if (str.startsWith(USEMTL)) {
1287
1288 if (currentChunkMaterialName.isEmpty()) {
1289 currentChunkMaterialName = str.substring(USEMTL.length()).trim();
1290 // search current material on material library
1291 currentMaterial = null;
1292 if (materialLoader != null) {
1293 currentMaterial = materialLoader.getMaterialByName(currentChunkMaterialName);
1294 }
1295 } else {
1296 // stop reading this chunk and reset position to
1297 // beginning of line so that usemtl is read again
1298 materialChange = true;
1299 reader.seek(faceStreamPos);
1300 break;
1301 }
1302
1303 } else if (str.startsWith("f ")) {
1304
1305 // line is a face, so we keep data after "f"
1306 str = str.substring("f ".length()).trim();
1307 // retrieve words in data
1308 final var valuesTemp = str.split(" ");
1309 final var valuesSet = new HashSet<String[]>();
1310
1311 // check that each face contains three elements to define a
1312 // triangle only
1313 if (valuesTemp.length == 3) {
1314 valuesSet.add(valuesTemp);
1315
1316 } else if (valuesTemp.length > 3) {
1317 // if instead of a triangle we have a polygon then we
1318 // to divide valuesTemp into a set of values forming
1319 // triangles. A polygon whose triangulation will
1320 // never fit in a chunk is rejected before
1321 // triangulating it
1322 if (VERTICES_PER_TRIANGLE * (valuesTemp.length - 2L)
1323 > loader.maxVerticesInChunk) {
1324 throw new LoaderException();
1325 }
1326 final var verticesList = getFaceValues(valuesTemp);
1327 try {
1328 valuesSet.addAll(buildTriangulatedIndices(verticesList));
1329 } catch (final TriangulatorException e) {
1330 // triangulation failed for some reason, but
1331 // file reading continues if configured like that
1332 // (by default it is)
1333 if (!continueIfTriangulationError) {
1334 throw new LoaderException(e);
1335 }
1336 }
1337 } else {
1338 throw new LoaderException();
1339 }
1340
1341
1342 // a face that never fits in a chunk cannot be loaded
1343 if (valuesSet.size() * VERTICES_PER_TRIANGLE
1344 > loader.maxVerticesInChunk) {
1345 throw new LoaderException();
1346 }
1347
1348 // each word corresponds to a vertex/texture/normal index,
1349 // so we check if such number of indices can be added into
1350 // this chunk
1351 if ((verticesInChunk + valuesSet.size() * 3) > loader.maxVerticesInChunk) { // values.length
1352 // no more vertices can be added to chunk, so we reset
1353 // stream to start on current face
1354 reader.seek(faceStreamPos);
1355 break;
1356 }
1357
1358 // keep current stream position for next face
1359 currentStreamPosition = reader.getPosition();
1360
1361 for (final var values : valuesSet) {
1362
1363 // otherwise values can be added into chunk, so we read
1364 // vertex index, texture index and normal index
1365 for (final var value : values) {
1366 // value can be of the form v/vt/vn, where v stands
1367 // for vertex index, vt for texture index and vn for
1368 // normal index, and where vt and vn are optional
1369 final var indices = value.split("/");
1370 var addExistingVertexCoords = false;
1371 var addExistingTextureCoords = false;
1372 var addExistingNormal = false;
1373 var vertexCoordsChunkIndex = -1;
1374 var textureCoordsChunkIndex = -1;
1375 var normalChunkIndex = -1;
1376
1377 boolean addExisting;
1378 var chunkIndex = 0;
1379
1380 // first check if vertex has to be added as new or
1381 // not
1382 if (indices.length >= 1 && (!indices[0].isEmpty())) {
1383 indicesAvailable = true;
1384 // indices start at 1 in OBJ
1385 vertexIndex = Integer.parseInt(indices[0]) - 1;
1386
1387 if (vertexIndex < 0) {
1388 // invalid index (<= 0 or overflow)
1389 throw new LoaderException();
1390 }
1391
1392 // determine if vertex coordinates have to be
1393 // added as new, or they can be reused from an
1394 // existing vertex
1395 addExistingVertexCoords = !loader.allowDuplicateVerticesInChunk
1396 && (vertexCoordsChunkIndex = searchVertexIndexInChunk(vertexIndex)) >= 0;
1397 }
1398 if (indices.length >= 2 && (!indices[1].isEmpty())) {
1399 textureAvailable = true;
1400 // indices start at 1 in OBJ
1401 textureIndex = Integer.parseInt(indices[1]) - 1;
1402
1403 if (textureIndex < 0) {
1404 // invalid index (<= 0 or overflow)
1405 throw new LoaderException();
1406 }
1407
1408 // determine if texture coordinates have to be
1409 // added as new, or they can be reused from an
1410 // existing vertex
1411 addExistingTextureCoords = !loader.allowDuplicateVerticesInChunk
1412 && (textureCoordsChunkIndex = searchTextureCoordIndexInChunk(textureIndex)) >= 0;
1413 }
1414 if (indices.length >= 3 && (!indices[2].isEmpty())) {
1415 normalsAvailable = true;
1416 // indices start at 1 in OBJ
1417 normalIndex = Integer.parseInt(indices[2]) - 1;
1418
1419 if (normalIndex < 0) {
1420 // invalid index (<= 0 or overflow)
1421 throw new LoaderException();
1422 }
1423
1424 // determine if normal coordinates have to be
1425 // added as new, or they can be reused from an
1426 // existing vertex
1427 addExistingNormal = !loader.allowDuplicateVerticesInChunk
1428 && (normalChunkIndex = searchNormalIndexInChunk(normalIndex)) >= 0;
1429 }
1430
1431 // if either vertex coordinates, texture coordinates
1432 // or normal indicate that a new vertex needs to be
1433 // added, then do so, only if all three use an
1434 // existing vertex into chunk use that existing
1435 // vertex. Also, in case that existing vertex is
1436 // added, if chunk indices of existing vertex,
1437 // texture and normal are not the same add as a new
1438 // vertex into chunk
1439
1440 // if some chunk index is found, set add existing to
1441 // true
1442 addExisting = (vertexCoordsChunkIndex >= 0) || (textureCoordsChunkIndex >= 0)
1443 || (normalChunkIndex >= 0);
1444 // ensure that if index is present an existing vertex
1445 // in chunk exists
1446 if (indices.length >= 1 && (!indices[0].isEmpty())) {
1447 addExisting &= addExistingVertexCoords;
1448 }
1449 if (indices.length >= 2 && (!indices[1].isEmpty())) {
1450 addExisting &= addExistingTextureCoords;
1451 }
1452 if (indices.length >= 3 && (!indices[2].isEmpty())) {
1453 addExisting &= addExistingNormal;
1454 }
1455
1456 if (addExisting) {
1457 // if finally an existing vertex is added, set
1458 // chunk index
1459 if (vertexCoordsChunkIndex >= 0) {
1460 chunkIndex = vertexCoordsChunkIndex;
1461 }
1462 if (textureCoordsChunkIndex >= 0) {
1463 chunkIndex = textureCoordsChunkIndex;
1464 }
1465 if (normalChunkIndex >= 0) {
1466 chunkIndex = normalChunkIndex;
1467 }
1468 }
1469
1470 if (indices.length >= 1 && (!indices[0].isEmpty()) && !addExistingVertexCoords) {
1471 // new vertex needs to be added into chunk,
1472 // so we need to read vertex data
1473
1474 // fetch vertex data position
1475 fetchVertex(vertexIndex);
1476 vertexStreamPosition = reader.getPosition();
1477
1478 // read all vertex data
1479 String vertexLine = reader.readLine();
1480 if (!vertexLine.startsWith("v ")) {
1481 throw new LoaderException();
1482 }
1483 vertexLine = vertexLine.substring("v ".length()).trim();
1484 // retrieve words in vertexLine, which contain
1485 // vertex coordinates either as x, y, z or x,
1486 // y, z, w
1487 final var vertexCoordinates = vertexLine.split(" ");
1488 if (vertexCoordinates.length == 4) {
1489 // homogeneous coordinates x, y, z, w
1490
1491 // check that values are valid
1492 if (vertexCoordinates[0].isEmpty()) {
1493 throw new LoaderException();
1494 }
1495 if (vertexCoordinates[1].isEmpty()) {
1496 throw new LoaderException();
1497 }
1498 if (vertexCoordinates[2].isEmpty()) {
1499 throw new LoaderException();
1500 }
1501 if (vertexCoordinates[3].isEmpty()) {
1502 throw new LoaderException();
1503 }
1504
1505 final var w = Float.parseFloat(vertexCoordinates[3]);
1506 coordX = Float.parseFloat(vertexCoordinates[0]) / w;
1507 coordY = Float.parseFloat(vertexCoordinates[1]) / w;
1508 coordZ = Float.parseFloat(vertexCoordinates[2]) / w;
1509
1510 } else if (vertexCoordinates.length >= 3) {
1511 // inhomogeneous coordinates x, y, z
1512
1513 // check that values are valid
1514 if (vertexCoordinates[0].isEmpty()) {
1515 throw new LoaderException();
1516 }
1517 if (vertexCoordinates[1].isEmpty()) {
1518 throw new LoaderException();
1519 }
1520 if (vertexCoordinates[2].isEmpty()) {
1521 throw new LoaderException();
1522 }
1523
1524 coordX = Float.parseFloat(vertexCoordinates[0]);
1525 coordY = Float.parseFloat(vertexCoordinates[1]);
1526 coordZ = Float.parseFloat(vertexCoordinates[2]);
1527
1528 } else {
1529 // unsupported length
1530 throw new LoaderException();
1531 }
1532 }
1533 if (indices.length >= 2 && (!indices[1].isEmpty()) && !addExistingTextureCoords) {
1534 // new texture values need to be added into
1535 // chunk, so we need to read texture
1536 // coordinates data
1537
1538 // fetch texture data position
1539 fetchTexture(textureIndex);
1540 textureCoordStreamPosition = reader.getPosition();
1541
1542 // read all texture data
1543 var textureLine = reader.readLine();
1544 if (!textureLine.startsWith("vt ")) {
1545 throw new LoaderException();
1546 }
1547 textureLine = textureLine.substring("vt ".length()).trim();
1548 // retrieve words in textureLine, which contain
1549 // texture coordinates either as u, w or u, v, w
1550 final var textureCoordinates = textureLine.split(" ");
1551 if (textureCoordinates.length == 3) {
1552 // homogeneous coordinates u, v, w
1553
1554 // check that values are valid
1555 if (textureCoordinates[0].isEmpty()) {
1556 throw new LoaderException();
1557 }
1558 if (textureCoordinates[1].isEmpty()) {
1559 throw new LoaderException();
1560 }
1561 if (textureCoordinates[2].isEmpty()) {
1562 throw new LoaderException();
1563 }
1564
1565 final var w = Float.parseFloat(textureCoordinates[2]);
1566
1567 textureU = Float.parseFloat(textureCoordinates[0]) / w;
1568 textureV = Float.parseFloat(textureCoordinates[1]) / w;
1569 if (Math.abs(w) < Float.MIN_VALUE || Float.isInfinite(textureU)
1570 || Float.isNaN(textureU) || Float.isInfinite(textureV)
1571 || Float.isNaN(textureV)) {
1572 textureU = Float.parseFloat(textureCoordinates[0]);
1573 textureV = Float.parseFloat(textureCoordinates[1]);
1574 }
1575
1576 } else if (textureCoordinates.length >= 2) {
1577 // inhomogeneous coordinates u, v
1578
1579 // check that values are valid
1580 if (textureCoordinates[0].isEmpty()) {
1581 throw new LoaderException();
1582 }
1583 if (textureCoordinates[1].isEmpty()) {
1584 throw new LoaderException();
1585 }
1586
1587 textureU = Float.parseFloat(textureCoordinates[0]);
1588 textureV = Float.parseFloat(textureCoordinates[1]);
1589 } else {
1590 // unsupported length
1591 throw new LoaderException();
1592 }
1593 }
1594 if (indices.length >= 3 && (!indices[2].isEmpty()) && !addExistingNormal) {
1595 // new normal needs to be added into chunk,
1596 // so we need to read vertex data
1597
1598 // fetch normal data position
1599 fetchNormal(normalIndex);
1600 normalStreamPosition = reader.getPosition();
1601
1602 // read all normal data
1603 var normalLine = reader.readLine();
1604 if (!normalLine.startsWith("vn ")) {
1605 throw new LoaderException();
1606 }
1607 normalLine = normalLine.substring("vn ".length()).trim();
1608 // retrieve words in normalLine, which must
1609 // contain normal coordinates as x, y, z
1610 final var normalCoordinates = normalLine.split(" ");
1611 if (normalCoordinates.length == 3) {
1612 // normal coordinates x, y, z
1613
1614 // check that values are valid
1615 if (normalCoordinates[0].isEmpty()) {
1616 throw new LoaderException();
1617 }
1618 if (normalCoordinates[1].isEmpty()) {
1619 throw new LoaderException();
1620 }
1621 if (normalCoordinates[2].isEmpty()) {
1622 throw new LoaderException();
1623 }
1624
1625 nX = Float.parseFloat(normalCoordinates[0]);
1626 nY = Float.parseFloat(normalCoordinates[1]);
1627 nZ = Float.parseFloat(normalCoordinates[2]);
1628 } else {
1629 // unsupported length
1630 throw new LoaderException();
1631 }
1632 }
1633
1634 if (addExisting) {
1635 addExistingVertexToChunk(chunkIndex);
1636 } else {
1637 addNewVertexDataToChunk();
1638 }
1639 }
1640 }
1641 // reset face stream position
1642 reader.seek(currentStreamPosition);
1643 currentFace++;
1644 }
1645
1646 // compute progress
1647 if (loader.listener != null && (currentFace % progressStep) == 0) {
1648 loader.listener.onLoadProgressChange(loader,
1649 (float) (currentFace) / (float) (numberOfFaces));
1650 }
1651 }
1652 } catch (final NumberFormatException e) {
1653 throw new LoaderException(e);
1654 }
1655
1656 // trim arrays to store only needed data
1657 trimArrays();
1658
1659 // Instantiate DataChunk with chunk arrays
1660 final var dataChunk = new DataChunk();
1661
1662 if (verticesAvailable) {
1663 dataChunk.setVerticesCoordinatesData(coordsInChunkArray);
1664 dataChunk.setMinX(minX);
1665 dataChunk.setMinY(minY);
1666 dataChunk.setMinZ(minZ);
1667 dataChunk.setMaxX(maxX);
1668 dataChunk.setMaxY(maxY);
1669 dataChunk.setMaxZ(maxZ);
1670 } else {
1671 // so it can be garbage collected
1672 coordsInChunkArray = null;
1673 }
1674
1675 if (textureAvailable) {
1676 dataChunk.setTextureCoordinatesData(textureCoordsInChunkArray);
1677 } else {
1678 // so it can be garbage collected
1679 textureCoordsInChunkArray = null;
1680 }
1681
1682 if (currentMaterial != null) {
1683 dataChunk.setMaterial(currentMaterial);
1684 }
1685
1686 if (materialChange) {
1687 currentChunkMaterialName = "";
1688 currentMaterial = null;
1689 }
1690
1691 if (indicesAvailable) {
1692 dataChunk.setIndicesData(indicesInChunkArray);
1693 } else {
1694 // so it can be garbage collected
1695 indicesInChunkArray = null;
1696 }
1697
1698 if (normalsAvailable) {
1699 dataChunk.setNormalsData(normalsInChunkArray);
1700 } else {
1701 // so it can be garbage collected
1702 normalsInChunkArray = null;
1703 }
1704
1705 if (!hasNext() && listener != null) {
1706 // notify iterator finished
1707 listener.onIteratorFinished(this);
1708 }
1709
1710 // if no more chunks are available, then close input reader
1711 if (!hasNext()) {
1712 reader.close();
1713 }
1714
1715 return dataChunk;
1716 }
1717
1718 /**
1719 * Fetches vertex data in the file using provided index. Index refers
1720 * to indices contained in OBJ file.
1721 *
1722 * @param index index corresponding to vertex being fetched.
1723 * @throws LoaderException if data is corrupted or cannot be understood.
1724 * @throws IOException if an I/O error occurs.
1725 */
1726 public void fetchVertex(long index) throws LoaderException, IOException {
1727 if (index >= numberOfVertices) {
1728 throw new LoaderException();
1729 }
1730
1731 var startStreamPos = firstVertexStreamPosition;
1732 var startIndex = 0L;
1733
1734 if (!verticesStreamPositionMap.isEmpty()) {
1735 // with floorEntry, we will pick element immediately
1736 // before or equal to index if any exists
1737 final var entry = verticesStreamPositionMap.floorEntry(index);
1738 if (entry != null) {
1739 final var origIndex = entry.getKey();
1740 final var pos = entry.getValue();
1741 if ((origIndex <= index) && (pos >= 0)) {
1742 startIndex = origIndex;
1743 startStreamPos = pos;
1744 }
1745 }
1746 }
1747
1748 // if we need to read next vertex, don't do anything, otherwise
1749 // move to next vertex location if reading some vertex located
1750 // further on the stream. For previous vertex indices, start
1751 // from beginning
1752 if (reader.getPosition() != startStreamPos) {
1753 reader.seek(startStreamPos);
1754 }
1755
1756 // read from stream until start of data of desired vertex
1757 var streamPosition = 0L;
1758 for (var i = startIndex; i <= index; i++) {
1759
1760 // when traversing stream of data until reaching desired
1761 // index, we add all vertex, texture and normal positions
1762 // into maps
1763 String str;
1764 var end = false;
1765 do {
1766 streamPosition = reader.getPosition();
1767 str = reader.readLine();
1768 if (str == null) {
1769 end = true;
1770 break;
1771 }
1772
1773 if (str.startsWith("v ")) {
1774 // line contains vertex coordinates, so we store
1775 // stream position into corresponding map and exit
1776 // while loop
1777 addVertexPositionToMap(i, streamPosition);
1778 break;
1779 }
1780 } while (true); // read until end of file when str == null
1781
1782 // unexpected end
1783 if (end) {
1784 throw new LoaderException();
1785 }
1786 }
1787
1788 // seek to last streamPosition which contains the desired data
1789 reader.seek(streamPosition);
1790 }
1791
1792 /**
1793 * Fetches texture data in the file using provided index. Index refers
1794 * to indices contained in OBJ file.
1795 *
1796 * @param index index corresponding to texture being fetched.
1797 * @throws LoaderException if data is corrupted or cannot be understood.
1798 * @throws IOException if an I/O error occurs.
1799 */
1800 public void fetchTexture(final long index) throws LoaderException, IOException {
1801 if (index >= numberOfTextureCoords) {
1802 throw new LoaderException();
1803 }
1804
1805 var startStreamPos = firstTextureCoordStreamPosition;
1806 var startIndex = 0L;
1807
1808 if (!textureCoordsStreamPositionMap.isEmpty()) {
1809 // with floorEntry, we will pick element immediately
1810 // before or equal to index if any exists
1811 final var entry = textureCoordsStreamPositionMap.floorEntry(index);
1812 if (entry != null) {
1813 final var origIndex = entry.getKey();
1814 final var pos = entry.getValue();
1815 if ((origIndex <= index) && (pos >= 0)) {
1816 startIndex = origIndex;
1817 startStreamPos = pos;
1818 }
1819 }
1820 }
1821
1822 // if we need to read next texture vertex, don't do anything,
1823 // otherwise move to next texture vertex located further on the
1824 // stream. For previous texture vertex indices, start from
1825 // beginning
1826 if (reader.getPosition() != startStreamPos) {
1827 reader.seek(startStreamPos);
1828 }
1829
1830 // read from stream until start of data of desired texture vertex
1831 var streamPosition = 0L;
1832 for (var i = startIndex; i <= index; i++) {
1833
1834 // when traversing stream of data until reaching desired
1835 // index, we add all vertex, texture and normal positions
1836 // into maps
1837 String str;
1838 var end = false;
1839 do {
1840 streamPosition = reader.getPosition();
1841 str = reader.readLine();
1842 if (str == null) {
1843 end = true;
1844 break;
1845 }
1846
1847 if (str.startsWith("vt ")) {
1848 // line contains texture coordinates, so we store
1849 // stream position into corresponding map and exit
1850 // while loop
1851 addTextureCoordPositionToMap(i, streamPosition);
1852 break;
1853 }
1854 } while (true); // read until end of file when str == null
1855
1856 // unexpected end
1857 if (end) {
1858 throw new LoaderException();
1859 }
1860 }
1861
1862 // seek to last streamPosition which contains the desired data
1863 reader.seek(streamPosition);
1864 }
1865
1866 /**
1867 * Fetches normal data in the file using provided index. Index refers
1868 * to indices contained in OBJ file.
1869 *
1870 * @param index index corresponding to normal being fetched.
1871 * @throws LoaderException if data is corrupted or cannot be understood.
1872 * @throws IOException if an I/O error occurs.
1873 */
1874 public void fetchNormal(final long index) throws LoaderException, IOException {
1875 if (index >= numberOfNormals) {
1876 throw new LoaderException();
1877 }
1878
1879 var startStreamPos = firstNormalStreamPosition;
1880 var startIndex = 0L;
1881
1882 if (!normalsStreamPositionMap.isEmpty()) {
1883 // with floorEntry, we will pick element immediately before or
1884 // equal to index if any exists
1885 final var entry = normalsStreamPositionMap.floorEntry(index);
1886 if (entry != null) {
1887 final var origIndex = entry.getKey();
1888 final var pos = entry.getValue();
1889 if ((origIndex <= index) && (pos >= 0)) {
1890 startIndex = origIndex;
1891 startStreamPos = pos;
1892 }
1893 }
1894 }
1895
1896 // if we need to read next normal, don't do anything, otherwise
1897 // move to next normal located further on the stream.
1898 // For previous normals indices, start from beginning
1899 if (reader.getPosition() != startStreamPos) {
1900 reader.seek(startStreamPos);
1901 }
1902
1903 // read from stream until start of data of desired normal
1904 var streamPosition = 0L;
1905 for (var i = startIndex; i <= index; i++) {
1906
1907 // when traversing stream of data until reaching desired
1908 // index, we add all vertex, texture and normal positions
1909 // into maps
1910 String str;
1911 var end = false;
1912 do {
1913 streamPosition = reader.getPosition();
1914 str = reader.readLine();
1915 if (str == null) {
1916 end = true;
1917 break;
1918 }
1919
1920 if (str.startsWith("vn ")) {
1921 // line contains normal, so we store stream position
1922 // into corresponding map and exit while loop
1923 addNormalPositionToMap(i, streamPosition);
1924 break;
1925 }
1926 } while (true); // read until end of file when str == null
1927
1928 // unexpected end
1929 if (end) {
1930 throw new LoaderException();
1931 }
1932 }
1933
1934 // seek to last streamPosition which contains the desired data
1935 reader.seek(streamPosition);
1936 }
1937
1938 /**
1939 * Internal method to decompose an array of vertices forming a polygon
1940 * in a set of arrays of vertices corresponding to triangles after
1941 * triangulation of the polygon. This method is used to triangulate
1942 * polygons with more than 3 vertices contained in the file.
1943 *
1944 * @param vertices list of vertices forming a polygon to be triangulated.
1945 * @return a set containing arrays of indices of vertices (in string
1946 * format) corresponding to the triangles forming the polygon after the
1947 * triangulation.
1948 * @throws TriangulatorException if triangulation fails (because polygon
1949 * is degenerate or contains invalid values such as NaN or infinity).
1950 */
1951 private Set<String[]> buildTriangulatedIndices(final List<VertexOBJ> vertices) throws TriangulatorException {
1952 final var polygonVertices = new ArrayList<Point3D>(vertices.size());
1953 for (final var v : vertices) {
1954 if (v.getVertex() == null) {
1955 throw new TriangulatorException();
1956 }
1957 polygonVertices.add(v.getVertex());
1958 }
1959 final var indices = new ArrayList<int[]>();
1960 final var triangulator = Triangulator3D.create();
1961 final var triangles = triangulator.triangulate(polygonVertices, indices);
1962
1963 final var result = new HashSet<String[]>();
1964 String[] face;
1965 var counter = 0;
1966 int[] triangleIndices;
1967 int index;
1968 VertexOBJ vertex;
1969 StringBuilder builder;
1970 for (final var ignored : triangles) {
1971 triangleIndices = indices.get(counter);
1972 face = new String[Triangle3D.NUM_VERTICES];
1973 for (var i = 0; i < Triangle3D.NUM_VERTICES; i++) {
1974 index = triangleIndices[i];
1975 vertex = vertices.get(index);
1976 builder = new StringBuilder();
1977 if (vertex.isVertexIndexAvailable()) {
1978 builder.append(vertex.getVertexIndex());
1979 }
1980 if (vertex.isTextureIndexAvailable() || vertex.isNormalIndexAvailable()) {
1981 builder.append("/");
1982 if (vertex.isTextureIndexAvailable()) {
1983 builder.append(vertex.getTextureIndex());
1984 }
1985 if (vertex.isNormalIndexAvailable()) {
1986 builder.append("/");
1987 builder.append(vertex.getNormalIndex());
1988 }
1989 }
1990
1991 face[i] = builder.toString();
1992 }
1993 counter++;
1994 result.add(face);
1995 }
1996
1997 return result;
1998 }
1999
2000 /**
2001 * This method reads a line containing face (i.e. polygon) indices of
2002 * vertices and fetches those vertices coordinates and associated data
2003 * such as texture coordinates or normal coordinates.
2004 *
2005 * @param values a string containing vertex indices forming a polygon.
2006 * Note that indices refer to the values contained in OBJ file, not the
2007 * indices in the chunk of data.
2008 * @return a list of vertices forming a face (i.e, polygon).
2009 * @throws IOException if an I/O error occurs.
2010 * @throws LoaderException if loading fails because data is corrupted or
2011 * cannot be interpreted.
2012 */
2013 private List<VertexOBJ> getFaceValues(final String[] values) throws IOException, LoaderException {
2014
2015 VertexOBJ tmpVertex;
2016 Point3D point;
2017 final var vertices = new ArrayList<VertexOBJ>(values.length);
2018
2019 // keep current stream position for next face
2020 final var tempPosition = reader.getPosition();
2021
2022 for (final var value : values) {
2023 tmpVertex = new VertexOBJ();
2024 point = Point3D.create();
2025 tmpVertex.setVertex(point);
2026
2027 final var indices = value.split("/");
2028
2029 if (indices.length >= 1 && (!indices[0].isEmpty())) {
2030 vertexIndex = Integer.parseInt(indices[0]) - 1;
2031
2032 if (vertexIndex < 0) {
2033 // invalid index (<= 0 or overflow)
2034 throw new LoaderException();
2035 }
2036 tmpVertex.setVertexIndex(vertexIndex + 1);
2037 fetchVertex(vertexIndex);
2038 vertexStreamPosition = reader.getPosition();
2039
2040 var vertexLine = reader.readLine();
2041 if (!vertexLine.startsWith("v ")) {
2042 throw new LoaderException();
2043 }
2044 vertexLine = vertexLine.substring("v ".length()).trim();
2045 final var vertexCoordinates = vertexLine.split(" ");
2046
2047 if (vertexCoordinates.length == 4) {
2048 // homogeneous coordinates x, y, z, w
2049 // ensure that vertex coordinates are not empty
2050 if (vertexCoordinates[0].isEmpty()) {
2051 throw new LoaderException();
2052 }
2053 if (vertexCoordinates[1].isEmpty()) {
2054 throw new LoaderException();
2055 }
2056 if (vertexCoordinates[2].isEmpty()) {
2057 throw new LoaderException();
2058 }
2059 if (vertexCoordinates[3].isEmpty()) {
2060 throw new LoaderException();
2061 }
2062
2063 try {
2064 point.setHomogeneousCoordinates(
2065 Double.parseDouble(vertexCoordinates[0]),
2066 Double.parseDouble(vertexCoordinates[1]),
2067 Double.parseDouble(vertexCoordinates[2]),
2068 Double.parseDouble(vertexCoordinates[3]));
2069 } catch (final NumberFormatException e) {
2070 // some vertex coordinate value could not be parsed
2071 throw new LoaderException(e);
2072 }
2073 } else if (vertexCoordinates.length >= 3) {
2074 // inhomogeneous coordinates x, y, z
2075 // ensure that vertex coordinate are not empty
2076 if (vertexCoordinates[0].isEmpty()) {
2077 throw new LoaderException();
2078 }
2079 if (vertexCoordinates[1].isEmpty()) {
2080 throw new LoaderException();
2081 }
2082 if (vertexCoordinates[2].isEmpty()) {
2083 throw new LoaderException();
2084 }
2085
2086 try {
2087 point.setInhomogeneousCoordinates(
2088 Double.parseDouble(vertexCoordinates[0]),
2089 Double.parseDouble(vertexCoordinates[1]),
2090 Double.parseDouble(vertexCoordinates[2]));
2091 } catch (final NumberFormatException e) {
2092 // some vertex coordinate value could not be parsed
2093 throw new LoaderException(e);
2094 }
2095 } else {
2096 // unsupported length
2097 throw new LoaderException();
2098 }
2099 }
2100 if (indices.length >= 2 && (!indices[1].isEmpty())) {
2101 tmpVertex.setTextureIndex(Integer.parseInt(indices[1]));
2102 }
2103 if (indices.length >= 3 && (!indices[2].isEmpty())) {
2104 tmpVertex.setNormalIndex(Integer.parseInt(indices[2]));
2105 }
2106
2107 vertices.add(tmpVertex);
2108 }
2109
2110 reader.seek(tempPosition);
2111 return vertices;
2112 }
2113
2114 /**
2115 * Initializes arrays forming current chunk of data.
2116 */
2117 private void initChunkArrays() {
2118 coordsInChunkArray = new float[loader.maxVerticesInChunk * 3];
2119 textureCoordsInChunkArray = new float[loader.maxVerticesInChunk * 2];
2120 normalsInChunkArray = new float[loader.maxVerticesInChunk * 3];
2121 indicesInChunkArray = new int[loader.maxVerticesInChunk];
2122
2123 originalVertexIndicesInChunkArray = new long[loader.maxVerticesInChunk];
2124 originalTextureIndicesInChunkArray = new long[loader.maxVerticesInChunk];
2125 originalNormalIndicesInChunkArray = new long[loader.maxVerticesInChunk];
2126 verticesInChunk = 0;
2127 indicesInChunk = 0;
2128 indicesInChunkSize = loader.maxVerticesInChunk;
2129
2130 vertexIndicesMap.clear();
2131 textureCoordsIndicesMap.clear();
2132 normalsIndicesMap.clear();
2133 }
2134
2135 /**
2136 * Searches vertex index in current chunk of data by using the index
2137 * used in the OBJ file.
2138 * This method searches within the cached indices which relate indices
2139 * in the chunk of data respect to indices in the OBJ file.
2140 *
2141 * @param originalIndex vertex index used in the OBJ file.
2142 * @return vertex index used in current chunk of data or -1 if not found.
2143 */
2144 private int searchVertexIndexInChunk(final long originalIndex) {
2145 // returns chunk index array position where index is found
2146 final var chunkIndex = vertexIndicesMap.get(originalIndex);
2147
2148 if (chunkIndex == null) {
2149 return -1;
2150 }
2151
2152 // returns index of vertex in chunk
2153 return indicesInChunkArray[chunkIndex];
2154 }
2155
2156 /**
2157 * Searches texture index in current chunk of data by using the index
2158 * used in the OBJ file.
2159 * This method searches within the cached indices which relate indices
2160 * in the chunk of data respect to indices in the OBJ file.
2161 *
2162 * @param originalIndex texture index used in the OBJ file.
2163 * @return texture index used in current chunk of data or -1 if not
2164 * found.
2165 */
2166 private int searchTextureCoordIndexInChunk(final long originalIndex) {
2167 return searchVertexIndexInChunk(originalIndex);
2168 }
2169
2170 /**
2171 * Searches normal index in current chunk of data by using the index
2172 * used in the OBJ file.
2173 * This method searches within the cached indices which relate indices
2174 * in the chunk of data respect to indices in the OBJ file.
2175 *
2176 * @param originalIndex normal index used in the OBJ file.
2177 * @return normal index used in current chunk of data or -1 if not found.
2178 */
2179 private int searchNormalIndexInChunk(final long originalIndex) {
2180 return searchVertexIndexInChunk(originalIndex);
2181 }
2182
2183 /**
2184 * Add vertex position to cache of file positions.
2185 *
2186 * @param originalIndex vertex index used in OBJ file.
2187 * @param streamPosition stream position where vertex is located.
2188 */
2189 private void addVertexPositionToMap(final long originalIndex, final long streamPosition) {
2190 if (verticesStreamPositionMap.size() > loader.maxStreamPositions) {
2191 // Map is full. Remove 1st item before adding a new one
2192 final var origIndex = verticesStreamPositionMap.firstKey();
2193 verticesStreamPositionMap.remove(origIndex);
2194 }
2195 // add new item
2196 verticesStreamPositionMap.put(originalIndex, streamPosition);
2197 }
2198
2199 /**
2200 * Add texture coordinate position to cache of file positions.
2201 *
2202 * @param originalIndex texture coordinate index used in OBJ file.
2203 * @param streamPosition stream position where texture coordinate is
2204 * located.
2205 */
2206 private void addTextureCoordPositionToMap(final long originalIndex, final long streamPosition) {
2207 if (textureCoordsStreamPositionMap.size() > loader.maxStreamPositions) {
2208 // Map is full. Remove 1st item before adding a new one
2209 final var origIndex = textureCoordsStreamPositionMap.firstKey();
2210 textureCoordsStreamPositionMap.remove(origIndex);
2211 }
2212 // add new item
2213 textureCoordsStreamPositionMap.put(originalIndex, streamPosition);
2214 }
2215
2216 /**
2217 * Add normal coordinate to cache of file positions.
2218 *
2219 * @param originalIndex normal coordinate index used in OBJ file.
2220 * @param streamPosition stream position where normal coordinate is
2221 * located.
2222 */
2223 private void addNormalPositionToMap(final long originalIndex, final long streamPosition) {
2224 if (normalsStreamPositionMap.size() > loader.maxStreamPositions) {
2225 // Map is full. Remove 1st item before adding a new one
2226 final var origIndex = normalsStreamPositionMap.firstKey();
2227 normalsStreamPositionMap.remove(origIndex);
2228 }
2229 // add new item
2230 normalsStreamPositionMap.put(originalIndex, streamPosition);
2231 }
2232
2233 /**
2234 * Adds data of last vertex being loaded to current chunk of data as a
2235 * new vertex.
2236 */
2237 private void addNewVertexDataToChunk() {
2238 var pos = 3 * verticesInChunk;
2239 var textPos = 2 * verticesInChunk;
2240
2241 coordsInChunkArray[pos] = coordX;
2242 normalsInChunkArray[pos] = nX;
2243 textureCoordsInChunkArray[textPos] = textureU;
2244
2245 pos++;
2246 textPos++;
2247
2248 coordsInChunkArray[pos] = coordY;
2249 normalsInChunkArray[pos] = nY;
2250 textureCoordsInChunkArray[textPos] = textureV;
2251
2252 pos++;
2253
2254 coordsInChunkArray[pos] = coordZ;
2255 normalsInChunkArray[pos] = nZ;
2256
2257 // update bounding box values
2258 if (coordX < minX) {
2259 minX = coordX;
2260 }
2261 if (coordY < minY) {
2262 minY = coordY;
2263 }
2264 if (coordZ < minZ) {
2265 minZ = coordZ;
2266 }
2267
2268 if (coordX > maxX) {
2269 maxX = coordX;
2270 }
2271 if (coordY > maxY) {
2272 maxY = coordY;
2273 }
2274 if (coordZ > maxZ) {
2275 maxZ = coordZ;
2276 }
2277
2278 // if arrays of indices become full, we need to resize them
2279 if (indicesInChunk >= indicesInChunkSize) {
2280 increaseIndicesArraySize();
2281 }
2282 indicesInChunkArray[indicesInChunk] = verticesInChunk;
2283 originalVertexIndicesInChunkArray[indicesInChunk] = vertexIndex;
2284 originalTextureIndicesInChunkArray[indicesInChunk] = textureIndex;
2285 originalNormalIndicesInChunkArray[indicesInChunk] = normalIndex;
2286 // store original indices in maps, so we can search chunk index by
2287 // original indices of vertices, texture or normal
2288 vertexIndicesMap.put((long) vertexIndex, indicesInChunk);
2289 textureCoordsIndicesMap.put((long) textureIndex, indicesInChunk);
2290 normalsIndicesMap.put((long) normalIndex, indicesInChunk);
2291
2292 // store vertex, texture and normal stream positions
2293 addVertexPositionToMap(vertexIndex, vertexStreamPosition);
2294 addTextureCoordPositionToMap(textureIndex, textureCoordStreamPosition);
2295 addNormalPositionToMap(normalIndex, normalStreamPosition);
2296
2297 verticesInChunk++;
2298 indicesInChunk++;
2299 }
2300
2301 /**
2302 * Adds index to current chunk of data referring to a previously
2303 * existing vertex in the chunk.
2304 *
2305 * @param existingIndex index of vertex that already exists in the chunk.
2306 */
2307 private void addExistingVertexToChunk(final int existingIndex) {
2308 // if arrays of indices become full, we need to resize them
2309 if (indicesInChunk >= indicesInChunkSize) {
2310 increaseIndicesArraySize();
2311 }
2312 indicesInChunkArray[indicesInChunk] = existingIndex;
2313 originalVertexIndicesInChunkArray[indicesInChunk] = vertexIndex;
2314 originalTextureIndicesInChunkArray[indicesInChunk] = textureIndex;
2315 originalNormalIndicesInChunkArray[indicesInChunk] = normalIndex;
2316
2317 indicesInChunk++;
2318 }
2319
2320 /**
2321 * Increases size of arrays of data. This method is called when needed.
2322 */
2323 private void increaseIndicesArraySize() {
2324 final var newIndicesInChunkSize = indicesInChunkSize + loader.maxVerticesInChunk;
2325 final var newIndicesInChunkArray = new int[newIndicesInChunkSize];
2326 final var newOriginalVertexIndicesInChunkArray = new long[newIndicesInChunkSize];
2327 final var newOriginalTextureIndicesInChunkArray = new long[newIndicesInChunkSize];
2328 final var newOriginalNormalIndicesInChunkArray = new long[newIndicesInChunkSize];
2329
2330 // copy contents of old array
2331 System.arraycopy(indicesInChunkArray, 0, newIndicesInChunkArray, 0, indicesInChunkSize);
2332 System.arraycopy(originalVertexIndicesInChunkArray, 0, newOriginalVertexIndicesInChunkArray,
2333 0, indicesInChunkSize);
2334 System.arraycopy(originalTextureIndicesInChunkArray, 0, newOriginalTextureIndicesInChunkArray,
2335 0, indicesInChunkSize);
2336 System.arraycopy(originalNormalIndicesInChunkArray, 0, newOriginalNormalIndicesInChunkArray,
2337 0, indicesInChunkSize);
2338
2339 // set new arrays and new size
2340 indicesInChunkArray = newIndicesInChunkArray;
2341 originalVertexIndicesInChunkArray = newOriginalVertexIndicesInChunkArray;
2342 originalTextureIndicesInChunkArray = newOriginalTextureIndicesInChunkArray;
2343 originalNormalIndicesInChunkArray = newOriginalNormalIndicesInChunkArray;
2344 indicesInChunkSize = newIndicesInChunkSize;
2345 }
2346
2347 /**
2348 * Trims arrays of data to reduce size of arrays to fit chunk data. This
2349 * method is loaded just before copying data to chunk being returned.
2350 */
2351 private void trimArrays() {
2352 if (verticesInChunk > 0) {
2353 final var elems = verticesInChunk * 3;
2354 final var textElems = verticesInChunk * 2;
2355
2356 final var newCoordsInChunkArray = new float[elems];
2357 final var newTextureCoordsInChunkArray = new float[elems];
2358 final var newNormalsInChunkArray = new float[elems];
2359
2360 // copy contents of old arrays
2361 System.arraycopy(coordsInChunkArray, 0, newCoordsInChunkArray, 0, elems);
2362 System.arraycopy(textureCoordsInChunkArray, 0, newTextureCoordsInChunkArray, 0,
2363 textElems);
2364 System.arraycopy(normalsInChunkArray, 0, newNormalsInChunkArray, 0, elems);
2365
2366 // set new arrays
2367 coordsInChunkArray = newCoordsInChunkArray;
2368 textureCoordsInChunkArray = newTextureCoordsInChunkArray;
2369 normalsInChunkArray = newNormalsInChunkArray;
2370 } else {
2371 // allow garbage collection
2372 coordsInChunkArray = null;
2373 textureCoordsInChunkArray = null;
2374 normalsInChunkArray = null;
2375 }
2376
2377 if (indicesInChunk > 0) {
2378 final var newIndicesInChunkArray = new int[indicesInChunk];
2379 System.arraycopy(indicesInChunkArray, 0, newIndicesInChunkArray, 0, indicesInChunk);
2380
2381 // set new array
2382 indicesInChunkArray = newIndicesInChunkArray;
2383 } else {
2384 // allow garbage collection
2385 indicesInChunkArray = null;
2386 originalVertexIndicesInChunkArray = null;
2387 originalTextureIndicesInChunkArray = null;
2388 originalNormalIndicesInChunkArray = null;
2389 }
2390 }
2391
2392 /**
2393 * Setups loader iterator. This method is called when constructing
2394 * this iterator.
2395 *
2396 * @throws IOException if an I/O error occurs.
2397 * @throws LoaderException if data is corrupted or cannot be understood.
2398 */
2399 private void setUp() throws IOException, LoaderException {
2400 numberOfVertices = numberOfTextureCoords = numberOfNormals = numberOfFaces = 0;
2401
2402 do {
2403 final var streamPosition = reader.getPosition();
2404 final var str = reader.readLine();
2405 if (str == null) {
2406 break;
2407 }
2408
2409 if (str.startsWith("#")) {
2410 // line is a comment, so we should add it to the list of
2411 // comments
2412 loader.comments.add(str.substring("#".length()).trim());
2413 } else if (str.startsWith("vt ")) {
2414 // line contains texture coordinates, so we keep its stream
2415 // position and indicate that chunks will contain texture
2416 // coordinates
2417 if (!firstTextureCoordStreamPositionAvailable) {
2418 firstTextureCoordStreamPosition = streamPosition;
2419 firstTextureCoordStreamPositionAvailable = true;
2420 textureAvailable = true;
2421 }
2422 numberOfTextureCoords++;
2423 } else if (str.startsWith("vn ")) {
2424 // line contains normal, so we keep its stream position and
2425 // indicate that chunks will contain normals
2426 if (!firstNormalStreamPositionAvailable) {
2427 firstNormalStreamPosition = streamPosition;
2428 firstNormalStreamPositionAvailable = true;
2429 normalsAvailable = true;
2430 }
2431 numberOfNormals++;
2432 } else if (str.startsWith("v ")) {
2433 // line contains vertex coordinates, so we keep its stream
2434 // position and indicate that chunks will contain vertex
2435 // coordinates
2436 if (!firstVertexStreamPositionAvailable) {
2437 firstVertexStreamPosition = streamPosition;
2438 firstVertexStreamPositionAvailable = true;
2439 verticesAvailable = true;
2440 }
2441 numberOfVertices++;
2442 } else if (str.startsWith("f ")) {
2443 // line contains face definition, so we keep its stream
2444 // position and indicate that chunks will contain indices
2445 if (!firstFaceStreamPositionAvailable) {
2446 firstFaceStreamPosition = streamPosition;
2447 firstFaceStreamPositionAvailable = true;
2448 indicesAvailable = true;
2449 }
2450
2451 numberOfFaces++;
2452
2453 } else if (str.startsWith("mtllib ")) {
2454 // a material library is found
2455 final var path = str.substring("mtllib ".length()).trim();
2456 if (loader.listener instanceof LoaderListenerOBJ loaderListener) {
2457 materialLoader = loaderListener.onMaterialLoaderRequested(loader, path);
2458 } else {
2459 materialLoader = new MaterialLoaderOBJ(new File(path));
2460 }
2461
2462 // now load library of materials
2463 try {
2464 if (materialLoader != null) {
2465 loader.materials = materialLoader.load();
2466 // to release file resources
2467 materialLoader.close();
2468 }
2469 } catch (final LoaderException e) {
2470 throw e;
2471 } catch (final Exception e) {
2472 throw new LoaderException(e);
2473 }
2474
2475 } else if (str.startsWith(USEMTL) && !firstMaterialStreamPositionAvailable) {
2476 firstMaterialStreamPositionAvailable = true;
2477 firstMaterialStreamPosition = streamPosition;
2478 materialsAvailable = true;
2479 }
2480
2481 // ignore any other line
2482 } while (true); // read until end of file when str == null
2483
2484 // move to first face tream position
2485 if (!firstFaceStreamPositionAvailable) {
2486 throw new LoaderException();
2487 }
2488
2489 if (materialsAvailable && firstMaterialStreamPosition < firstFaceStreamPosition) {
2490 reader.seek(firstMaterialStreamPosition);
2491 } else {
2492 reader.seek(firstFaceStreamPosition);
2493 }
2494 }
2495 }
2496 }