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 java.io.File;
19 import java.io.IOException;
20
21 public class LoaderSTL extends Loader {
22 /**
23 * Constant defining the default value of maximum number of vertices to keep
24 * in a chunk. This is 65535, which corresponds to the maximum value allowed
25 * by graphical layer such as OpenGL when working with Vertex Buffer Objects.
26 */
27 public static final int DEFAULT_MAX_VERTICES_IN_CHUNK = 0xffff;
28
29 /**
30 * Minimum allowed value for maximum number of vertices in chunk, which is
31 * one.
32 */
33 public static final int MIN_MAX_VERTICES_IN_CHUNK = 1;
34
35 /**
36 * Amount of progress variation (1%) used to notify progress.
37 */
38 public static final float PROGRESS_DELTA = 0.01f;
39
40 private LoaderIteratorSTL loaderIterator;
41
42 private int maxVerticesInChunk;
43
44 /**
45 * Constructor.
46 */
47 public LoaderSTL() {
48 loaderIterator = null;
49 maxVerticesInChunk = DEFAULT_MAX_VERTICES_IN_CHUNK;
50 }
51
52 /**
53 * Constructor.
54 *
55 * @param maxVerticesInChunk Maximum number of vertices allowed in a chunk.
56 * Once this value is exceeded when loading a file, a new chunk of data is
57 * created.
58 * @throws IllegalArgumentException if maximum number of vertices allowed in
59 * a chunk is lower than 1.
60 */
61 public LoaderSTL(final int maxVerticesInChunk) {
62 loaderIterator = null;
63 internalSetMaxVerticesInChunk(maxVerticesInChunk);
64 }
65
66 /**
67 * Constructor.
68 *
69 * @param f file to be loaded.
70 * @throws IOException if an I/O error occurs.
71 */
72 public LoaderSTL(final File f) throws IOException {
73 super(f);
74 loaderIterator = null;
75 maxVerticesInChunk = DEFAULT_MAX_VERTICES_IN_CHUNK;
76 }
77
78 /**
79 * Constructor.
80 *
81 * @param f file to be loaded.
82 * @param maxVerticesInChunk Maximum number of vertices allowed in a chunk.
83 * Once this value is exceeded when loading a file, a new chunk of data is
84 * created.
85 * @throws IllegalArgumentException if maximum number of vertices allowed in
86 * a chunk is lower than 1.
87 * @throws IOException if an I/O error occurs.
88 */
89 public LoaderSTL(final File f, final int maxVerticesInChunk) throws IOException {
90 super(f);
91 loaderIterator = null;
92 internalSetMaxVerticesInChunk(maxVerticesInChunk);
93 }
94
95 /**
96 * Constructor.
97 *
98 * @param listener listener to be notified of loading progress and when
99 * loading process starts or finishes.
100 */
101 public LoaderSTL(final LoaderListener listener) {
102 super(listener);
103 maxVerticesInChunk = DEFAULT_MAX_VERTICES_IN_CHUNK;
104 }
105
106 /**
107 * Constructor.
108 *
109 * @param listener listener to be notified of loading progress and when
110 * loading process starts or finishes.
111 * @param maxVerticesInChunk Maximum number of vertices allowed in a chunk.
112 * Once this value is exceeded when loading a file, a new chunk of data is
113 * created.
114 * @throws IllegalArgumentException if maximum number of vertices allowed in
115 * a chunk is lower than 1.
116 */
117 public LoaderSTL(final LoaderListener listener, final int maxVerticesInChunk) {
118 super(listener);
119 loaderIterator = null;
120 internalSetMaxVerticesInChunk(maxVerticesInChunk);
121 }
122
123 /**
124 * Constructor.
125 *
126 * @param f file to be loaded.
127 * @param listener listener to be notified of loading progress and when
128 * loading process starts or finishes.
129 * @throws IOException if an I/O error occurs.
130 */
131 public LoaderSTL(final File f, final LoaderListener listener) throws IOException {
132 super(f, listener);
133 loaderIterator = null;
134 maxVerticesInChunk = DEFAULT_MAX_VERTICES_IN_CHUNK;
135 }
136
137 /**
138 * Constructor.
139 *
140 * @param f file to be loaded.
141 * @param listener listener to be notified of loading progress and when
142 * loading process starts or finishes.
143 * @param maxVerticesInChunk Maximum number of vertices allowed in a chunk.
144 * Once this value is exceeded when loading a file, a new chunk of data is
145 * created.
146 * @throws IllegalArgumentException if maximum number of vertices allowed in
147 * a chunk is lower than 1.
148 * @throws IOException if an I/O error occurs.
149 */
150 public LoaderSTL(final File f, final LoaderListener listener, final int maxVerticesInChunk) throws IOException {
151 super(f, listener);
152 loaderIterator = null;
153 internalSetMaxVerticesInChunk(maxVerticesInChunk);
154 }
155
156 /**
157 * Sets 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 *
161 * @param maxVerticesInChunk maximum allowed number of vertices to be set.
162 * @throws IllegalArgumentException if provided value is lower than 1.
163 * @throws LockedException if this loader is currently loading a file.
164 */
165 public void setMaxVerticesInChunk(final int maxVerticesInChunk) throws LockedException {
166 if (isLocked()) {
167 throw new LockedException();
168 }
169 internalSetMaxVerticesInChunk(maxVerticesInChunk);
170 }
171
172 /**
173 * Returns maximum number of vertices allowed in a chunk.
174 * Once this value is exceeded when loading a file, a new chunk of data is
175 * created.
176 *
177 * @return maximum number of vertices allowed in a chunk.
178 */
179 public int getMaxVerticesInChunk() {
180 return maxVerticesInChunk;
181 }
182
183 /**
184 * If loader is ready to start loading a file.
185 * This is true once a file has been provided.
186 *
187 * @return true if ready to start loading a file, false otherwise.
188 */
189 @Override
190 public boolean isReady() {
191 return hasFile();
192 }
193
194 /**
195 * Returns mesh format supported by this class, which is MESH_FORMAT_STL.
196 *
197 * @return mesh format supported by this class.
198 */
199 @Override
200 public MeshFormat getMeshFormat() {
201 return MeshFormat.MESH_FORMAT_STL;
202 }
203
204 /**
205 * Determines if provided file is a valid file that can be read by this
206 * loader.
207 *
208 * @return true if file is valid, false otherwise.
209 * @throws LockedException raised if this instance is already locked.
210 * @throws IOException if an I/O error occurs.
211 */
212 @Override
213 public boolean isValidFile() throws LockedException, IOException {
214 if (!hasFile()) {
215 throw new IOException();
216 }
217 if (isLocked()) {
218 throw new LockedException();
219 }
220 return true;
221 }
222
223 /**
224 * Starts the loading process of provided file.
225 * This method returns a LoaderIterator to start the iterative process to
226 * load a file in small chunks of data.
227 *
228 * @return a loader iterator to read the file in a step-by-step process.
229 * @throws LockedException raised if this instance is already locked.
230 * @throws NotReadyException raised if this instance is not yet ready.
231 * @throws IOException if an I/O error occurs.
232 * @throws LoaderException if file is corrupted or cannot be interpreted.
233 */
234 @Override
235 public LoaderIterator load() throws LockedException, NotReadyException, IOException, LoaderException {
236 if (isLocked()) {
237 throw new LockedException();
238 }
239 if (!isReady()) {
240 throw new NotReadyException();
241 }
242
243 setLocked(true);
244 if (listener != null) {
245 listener.onLoadStart(this);
246 }
247
248 // do not leave this loader locked if file cannot be loaded
249 loaderIterator = loadReleasingLockOnFailure(
250 () -> new LoaderIteratorSTL(this));
251 loaderIterator.setListener(new LoaderIteratorListenerImpl(this));
252 return loaderIterator;
253 }
254
255 /**
256 * Returns name for the 3D object.
257 *
258 * @return name for the 3D object.
259 */
260 protected String getSolidName() {
261 return loaderIterator != null ? loaderIterator.getSolidName() : null;
262 }
263
264 /**
265 * Gets number of vertices contained in the file.
266 *
267 * @return number of vertices contained in the file.
268 */
269 protected Long getNumberOfVertices() {
270 return loaderIterator != null ? loaderIterator.getNumberOfVertices() : null;
271 }
272
273
274 /**
275 * Internal method to set maximum number of vertices allowed in a chunk.
276 * This method is reused both in the constructor and in the setter of
277 * maximum number of vertices allowed in a chunk.
278 *
279 * @param maxVerticesInChunk maximum allowed number of vertices to be set.
280 * @throws IllegalArgumentException if provided value is lower than 1.
281 */
282 private void internalSetMaxVerticesInChunk(final int maxVerticesInChunk) {
283 if (maxVerticesInChunk < MIN_MAX_VERTICES_IN_CHUNK) {
284 throw new IllegalArgumentException();
285 }
286
287 this.maxVerticesInChunk = maxVerticesInChunk;
288 }
289
290 /**
291 * Internal listener to be notified when loading process finishes.
292 * This listener is used to free resources when loading process finishes.
293 */
294 private class LoaderIteratorListenerImpl implements LoaderIteratorListener {
295 /**
296 * Reference to Loader loading an STL file.
297 */
298 private final LoaderSTL loader;
299
300 public LoaderIteratorListenerImpl(final LoaderSTL loader) {
301 this.loader = loader;
302 }
303
304 /**
305 * Method to be notified when the loading process finishes.
306 *
307 * @param iterator iterator loading the file in chunks.
308 */
309 @Override
310 public void onIteratorFinished(final LoaderIterator iterator) {
311 // because iterator is finished, we should allow subsequent calls to
312 // load method
313 try {
314 // attempt restart stream to initial position
315 reader.seek(0);
316 } catch (final Exception ignore) {
317 // this is the best effort operation, if it fails it is ignored
318 }
319
320 // on subsequent calls
321 if (listener != null) {
322 listener.onLoadEnd(loader);
323 }
324 setLocked(false);
325 }
326 }
327
328 /**
329 * Loader iterator in charge of loading file data in small chunks.
330 * Usually data is divided in chunks small enough that can be directly
331 * loaded by graphical layers such as OpenGL (which has a limit of 65535
332 * indices when using Vertex Buffer Objects, which increase graphical
333 * performance).
334 */
335 private class LoaderIteratorSTL implements LoaderIterator {
336
337 /**
338 * Reference to loader loading STL file.
339 */
340 private final LoaderSTL loader;
341
342 /**
343 * X coordinate of the latest point that has been read.
344 */
345 private float coordX;
346
347 /**
348 * Y coordinate of the latest point that has been read.
349 */
350 private float coordY;
351
352 /**
353 * Z coordinate of the latest point that has been read.
354 */
355 private float coordZ;
356
357 /**
358 * X coordinate of the latest point normal that has been read.
359 */
360 private float nX;
361
362 /**
363 * Y coordinate of the latest point normal that has been read.
364 */
365 private float nY;
366
367 /**
368 * Z coordinate of the latest point normal that has been read.
369 */
370 private float nZ;
371
372 // coordinates for bounding box in a chunk
373
374 /**
375 * X coordinate of the minimum point forming the bounding box in a chunk
376 * of data. This value will be updated while the chunk is being filled.
377 */
378 private float minX;
379
380 /**
381 * Y coordinate of the minimum point forming the bounding box in a chunk
382 * of data. This value will be updated while the chunk is being filled.
383 */
384 private float minY;
385
386 /**
387 * Z coordinate of the minimum point forming the bounding box in a chunk
388 * of data. This value will be updated while the chunk is being filled.
389 */
390 private float minZ;
391
392 /**
393 * X coordinate of the maximum point forming the bounding box in a chunk
394 * of data. This value will be updated while the chunk is being filled.
395 */
396 private float maxX;
397
398 /**
399 * Y coordinate of the maximum point forming the bounding box in a chunk
400 * of data. This value will be updated while the chunk is being filled.
401 */
402 private float maxY;
403
404 /**
405 * Z coordinate of the maximum point forming the bounding box in a chunk
406 * of data. This value will be updated while the chunk is being filled.
407 */
408 private float maxZ;
409
410 /**
411 * Reference to the listener of this loader iterator. This listener will
412 * be notified when the loading process finishes so that resources can
413 * be freed.
414 */
415 private LoaderIteratorListener listener;
416
417 /**
418 * Array containing vertices coordinates to be added to current chunk
419 * of data.
420 */
421 private float[] coordsInChunkArray;
422
423 /**
424 * Array containing normal coordinates to be added to current chunk of
425 * data.
426 */
427 private float[] normalsInChunkArray;
428
429 /**
430 * Array containing indices to be added to current chunk of data. Notice
431 * that these indices are not the original indices appearing in the file.
432 * Instead, they are indices referring to data in current chunk,
433 * accounting for duplicate points, etc. This way, indices in a chunk
434 * can be directly used to draw the chunk of data by the graphical layer.
435 */
436 private int[] indicesInChunkArray;
437
438 /**
439 * Number of vertices stored in chunk.
440 */
441 private int verticesInChunk;
442
443 /**
444 * Number of indices stored in chunk.
445 */
446 private int indicesInChunk;
447
448 /**
449 * Size of indices stored in chunk.
450 */
451 private int indicesInChunkSize;
452
453 /**
454 * Indicates if file is in ASCII format or in binary format.
455 */
456 private boolean isAscii;
457
458 /**
459 * Indicates number of triangles that are contained in the file (when
460 * available).
461 */
462 private long numberOfTriangles;
463
464 /**
465 * Indicates current triangle being read (when available).
466 */
467 private long currentTriangle;
468
469 /**
470 * Contains number of vertices contained in the file.
471 */
472 private long numberOfVertices;
473
474 /**
475 * Indicates when end of file has been reached.
476 */
477 private boolean endOfFileReached;
478
479 /**
480 * Contains name for the 3D object.
481 */
482 private String solidName;
483
484 /**
485 * Constant defining beginning of 3D file.
486 */
487 public static final String ASCII_START = "solid";
488
489 /**
490 * Constant defining end of 3D file.
491 */
492 public static final String ASCII_END = "endsolid";
493
494 /**
495 * Constant defining a face (i.e. triangle or polygon).
496 */
497 public static final String ASCII_FACET = "facet";
498
499 /**
500 * Constant defining a normal.
501 */
502 public static final String ASCII_NORMAL = "normal";
503
504 /**
505 * Constant defining grouping levels.
506 */
507 public static final String ASCII_OUTER = "outer";
508
509 /**
510 * Constant defining a loop that will contain vertices.
511 */
512 public static final String ASCII_LOOP = "loop";
513
514 /**
515 * Constant defining a vertex.
516 */
517 public static final String ASCII_VERTEX = "vertex";
518
519 /**
520 * Constant defining end of loop containing vertices.
521 */
522 public static final String ASCII_END_LOOP = "endloop";
523
524 /**
525 * Constant defining end of 3D face (i.e. triangle or polygon).
526 */
527 public static final String ASCII_END_FACET = "endfacet";
528
529 /**
530 * Header size for binary format.
531 */
532 public static final int BINARY_HEADER_SIZE = 80;
533
534 /**
535 * Constant defining number of vertices in a triangle.
536 */
537 public static final int VERTICES_PER_TRIANGLE = 3;
538
539 /**
540 * Size in bytes of the number of triangles field in binary files.
541 */
542 private static final int BINARY_COUNT_SIZE = 4;
543
544 /**
545 * Size in bytes of each triangle (normal, 3 vertices and attribute).
546 */
547 private static final int BINARY_TRIANGLE_SIZE = 50;
548
549 /**
550 * Constructor.
551 *
552 * @param loader reference to loader loading binary file.
553 * @throws IOException if an I/O error occurs.
554 * @throws LoaderException if file data is corrupt or cannot be
555 * understood.
556 */
557 public LoaderIteratorSTL(final LoaderSTL loader) throws IOException, LoaderException {
558 this.loader = loader;
559 nX = nY = nZ = 1.0f;
560 listener = null;
561 coordsInChunkArray = null;
562 normalsInChunkArray = null;
563 indicesInChunkArray = null;
564
565 verticesInChunk = indicesInChunk = indicesInChunkSize = 0;
566
567 minX = minY = minZ = Float.MAX_VALUE;
568 maxX = maxY = maxZ = -Float.MAX_VALUE;
569
570 isAscii = false;
571 numberOfTriangles = currentTriangle = 0;
572 endOfFileReached = false;
573
574 numberOfVertices = 0;
575
576 setUp();
577 }
578
579 /**
580 * Method to set listener of this loader iterator.
581 * This listener will be notified when the loading process finishes.
582 *
583 * @param listener listener of this loader iterator.
584 */
585 public void setListener(final LoaderIteratorListener listener) {
586 this.listener = listener;
587 }
588
589 /**
590 * Indicates if there is another chunk of data to be loaded.
591 *
592 * @return true if there is another chunk of data, false otherwise.
593 */
594 @Override
595 public boolean hasNext() {
596 if (isAscii) {
597 return !endOfFileReached;
598 } else {
599 return currentTriangle < numberOfTriangles;
600 }
601 }
602
603 /**
604 * Loads and returns next chunk of data, if available.
605 *
606 * @return next chunk of data.
607 * @throws NotAvailableException thrown if no more data is available.
608 * @throws LoaderException if file data is corrupt or cannot be
609 * understood.
610 * @throws IOException if an I/O error occurs.
611 */
612 @Override
613 public DataChunk next() throws NotAvailableException, LoaderException, IOException {
614
615 if (reader == null) {
616 throw new IOException();
617 }
618
619 if (!hasNext()) {
620 throw new NotAvailableException();
621 }
622
623 // do not leave loader locked if file cannot be read
624 return readReleasingLockOnFailure(this::readNextChunk);
625 }
626
627 /**
628 * Reads next chunk of data.
629 *
630 * @return next chunk of data.
631 * @throws NotAvailableException if no more data is available.
632 * @throws LoaderException if file data is corrupt or cannot be
633 * understood.
634 * @throws IOException if an I/O error occurs.
635 */
636 private DataChunk readNextChunk()
637 throws NotAvailableException, LoaderException, IOException {
638 initChunkArrays();
639
640 // reset chunk bounding box values
641 minX = minY = minZ = Float.MAX_VALUE;
642 maxX = maxY = maxZ = -Float.MAX_VALUE;
643
644 // read data until chunk is full
645 var endOfChunk = false;
646 final var fileLength = file.length();
647
648 final var progressStep = Math.max((long) (LoaderSTL.PROGRESS_DELTA * fileLength), 1);
649 var previousPos = 0L;
650
651 try {
652 if (isAscii) {
653
654 // ascii format
655 String word;
656 do {
657 // read facet
658 word = readNonEmptyWord();
659 if (word == null) {
660 // undefined word
661 throw new LoaderException();
662 }
663
664 if (word.equalsIgnoreCase(ASCII_FACET)) {
665 // read normal
666 word = readNonEmptyWord();
667 if (word == null) {
668 // undefined word
669 throw new LoaderException();
670 }
671
672 if (word.equalsIgnoreCase(ASCII_NORMAL)) {
673 // read 3 normal values
674 word = readNonEmptyWord();
675 nX = Float.parseFloat(word);
676 word = readNonEmptyWord();
677 nY = Float.parseFloat(word);
678 word = readNonEmptyWord();
679 nZ = Float.parseFloat(word);
680 } else {
681 // unexpected word
682 throw new LoaderException();
683 }
684
685 } else if (word.equalsIgnoreCase(ASCII_OUTER)) {
686 // next word has to be "loop"
687 word = readNonEmptyWord();
688 if (word == null) {
689 // undefined word
690 throw new LoaderException();
691 }
692
693 if (!word.equalsIgnoreCase(ASCII_LOOP)) {
694 // unexpected word
695 throw new LoaderException();
696 }
697
698 } else if (word.equalsIgnoreCase(ASCII_VERTEX)) {
699 // read vertex data
700 word = readNonEmptyWord();
701 coordX = Float.parseFloat(word);
702 word = readNonEmptyWord();
703 coordY = Float.parseFloat(word);
704 word = readNonEmptyWord();
705 coordZ = Float.parseFloat(word);
706
707 // add coordinates into chunk arrays
708 addNewVertexDataToChunk();
709
710 // check if chunk is full
711 if (verticesInChunk == loader.maxVerticesInChunk) {
712 // no more vertices can be added to this chunk
713 break;
714 }
715
716 } else if (word.equalsIgnoreCase(ASCII_END_LOOP)) {
717 // check if chunk is full
718 if (verticesInChunk + VERTICES_PER_TRIANGLE >= loader.maxVerticesInChunk) {
719 // no more triangles vertices can be added to
720 // this chunk
721 break;
722 }
723
724 } else if (word.equalsIgnoreCase(ASCII_END_FACET)) {
725 // check if chunk is full
726 if (verticesInChunk + VERTICES_PER_TRIANGLE >= loader.maxVerticesInChunk) {
727 // no more triangles vertices can be added to
728 // this chunk
729 break;
730 }
731 } else if (word.equalsIgnoreCase(ASCII_END)) {
732 endOfFileReached = true;
733 break;
734 } else {
735 // unexpected word
736 throw new LoaderException();
737 }
738
739 // compute progress
740 if ((loader.listener != null) && (reader.getPosition() - previousPos) >= progressStep) {
741 previousPos = reader.getPosition();
742 loader.listener.onLoadProgressChange(loader,
743 (float) (reader.getPosition()) / fileLength);
744 }
745
746 } while (!endOfFileReached);
747
748 } else {
749 do {
750 // read vertex data (triangle normal, triangle vertices
751 // and two bytes attribute byte count
752
753 // read vertex normals
754 nX = reader.readFloat(EndianType.LITTLE_ENDIAN_TYPE);
755 nY = reader.readFloat(EndianType.LITTLE_ENDIAN_TYPE);
756 nZ = reader.readFloat(EndianType.LITTLE_ENDIAN_TYPE);
757
758 // read 1st vertex coordinates of triangle
759 coordX = reader.readFloat(EndianType.LITTLE_ENDIAN_TYPE);
760 coordY = reader.readFloat(EndianType.LITTLE_ENDIAN_TYPE);
761 coordZ = reader.readFloat(EndianType.LITTLE_ENDIAN_TYPE);
762
763 // add coordinates into chunk arrays
764 addNewVertexDataToChunk();
765
766 // read 2nd vertex coordinates of triangle
767 coordX = reader.readFloat(EndianType.LITTLE_ENDIAN_TYPE);
768 coordY = reader.readFloat(EndianType.LITTLE_ENDIAN_TYPE);
769 coordZ = reader.readFloat(EndianType.LITTLE_ENDIAN_TYPE);
770
771 // add coordinates into chunk arrays
772 addNewVertexDataToChunk();
773
774 // read 3rd vertex coordinates of triangle
775 coordX = reader.readFloat(EndianType.LITTLE_ENDIAN_TYPE);
776 coordY = reader.readFloat(EndianType.LITTLE_ENDIAN_TYPE);
777 coordZ = reader.readFloat(EndianType.LITTLE_ENDIAN_TYPE);
778
779 // add coordinates into chunk arrays
780 addNewVertexDataToChunk();
781
782 // read two bytes attribute byte count
783 reader.readUnsignedShort(EndianType.LITTLE_ENDIAN_TYPE);
784
785 currentTriangle++;
786
787 // compute progress
788 if ((loader.listener != null) && (reader.getPosition() - previousPos) >= progressStep) {
789 previousPos = reader.getPosition();
790 loader.listener.onLoadProgressChange(loader,
791 (float) (reader.getPosition()) / fileLength);
792 }
793
794 if (verticesInChunk + VERTICES_PER_TRIANGLE >= loader.maxVerticesInChunk) {
795 // no more triangles vertices can be added to this
796 // chunk
797 endOfChunk = true;
798 break;
799 }
800
801 } while (!reader.isEndOfStream() && currentTriangle < numberOfTriangles);
802
803 // file ended before all triangles were read
804 if (currentTriangle < numberOfTriangles && !endOfChunk) {
805 throw new LoaderException();
806 }
807 }
808 } catch (final IOException | LoaderException e) {
809 throw e;
810 } catch (final Exception e) {
811 throw new LoaderException(e);
812 }
813
814 // trim arrays to store only needed data
815 trimArrays();
816
817 // Instantiate DataChunk with chunk arrays
818 final var dataChunk = new DataChunk();
819
820 dataChunk.setVerticesCoordinatesData(coordsInChunkArray);
821 dataChunk.setMinX(minX);
822 dataChunk.setMinY(minY);
823 dataChunk.setMinZ(minZ);
824 dataChunk.setMaxX(maxX);
825 dataChunk.setMaxY(maxY);
826 dataChunk.setMaxZ(maxZ);
827
828 dataChunk.setIndicesData(indicesInChunkArray);
829
830 dataChunk.setNormalsData(normalsInChunkArray);
831
832 if (!hasNext() && listener != null) {
833 // notify iterator finished
834 listener.onIteratorFinished(this);
835 }
836
837 // if no more chunks are available, then close input reader
838 if (!hasNext()) {
839 reader.close();
840 }
841
842 return dataChunk;
843 }
844
845 /**
846 * Returns name for the 3D object.
847 *
848 * @return name for the 3D object.
849 */
850 public String getSolidName() {
851 return solidName;
852 }
853
854 /**
855 * Gets number of vertices contained in the file.
856 *
857 * @return number of vertices contained in the file.
858 */
859 public long getNumberOfVertices() {
860 return numberOfVertices;
861 }
862
863 /**
864 * Internal method to read a word from ASCII file.
865 *
866 * @return next word that has been read.
867 * @throws IOException if an I/O error occurs.
868 */
869 private String readNonEmptyWord() throws IOException {
870 // read normal
871 String word;
872 do {
873 // ignore empty words
874 // (line feeds, etc.)
875 word = reader.readWord();
876 } while (word != null && word.isEmpty());
877 return word;
878 }
879
880 /**
881 * Initializes arrays forming current chunk of data.
882 */
883 private void initChunkArrays() {
884 coordsInChunkArray = new float[loader.maxVerticesInChunk * VERTICES_PER_TRIANGLE];
885 normalsInChunkArray = new float[loader.maxVerticesInChunk * VERTICES_PER_TRIANGLE];
886 indicesInChunkArray = new int[loader.maxVerticesInChunk];
887
888 verticesInChunk = indicesInChunk = 0;
889 indicesInChunkSize = loader.maxVerticesInChunk;
890 }
891
892 /**
893 * Adds data of last vertex being loaded to current chunk of data as a
894 * new vertex.
895 */
896 private void addNewVertexDataToChunk() {
897 var pos = 3 * verticesInChunk;
898
899 coordsInChunkArray[pos] = coordX;
900 normalsInChunkArray[pos] = nX;
901
902 pos++;
903
904 coordsInChunkArray[pos] = coordY;
905 normalsInChunkArray[pos] = nY;
906
907 pos++;
908
909 coordsInChunkArray[pos] = coordZ;
910 normalsInChunkArray[pos] = nZ;
911
912 // update bounding box values
913 if (coordX < minX) {
914 minX = coordX;
915 }
916 if (coordY < minY) {
917 minY = coordY;
918 }
919 if (coordZ < minZ) {
920 minZ = coordZ;
921 }
922
923 if (coordX > maxX) {
924 maxX = coordX;
925 }
926 if (coordY > maxY) {
927 maxY = coordY;
928 }
929 if (coordZ > maxZ) {
930 maxZ = coordZ;
931 }
932
933 // if arrays of indices become full, we need to resize them
934 if (indicesInChunk >= indicesInChunkSize) {
935 increaseIndicesArraySize();
936 }
937 indicesInChunkArray[indicesInChunk] = verticesInChunk;
938
939 verticesInChunk++;
940 indicesInChunk++;
941 }
942
943 /**
944 * Increases size of arrays of data. This method is called when needed.
945 */
946 private void increaseIndicesArraySize() {
947 final var newIndicesInChunkSize = indicesInChunkSize + loader.maxVerticesInChunk;
948 final var newIndicesInChunkArray = new int[newIndicesInChunkSize];
949
950 // copy contents of old array
951 System.arraycopy(indicesInChunkArray, 0, newIndicesInChunkArray, 0, indicesInChunkSize);
952
953 // set new arrays and new size
954 indicesInChunkArray = newIndicesInChunkArray;
955 indicesInChunkSize = newIndicesInChunkSize;
956 }
957
958 /**
959 * Trims arrays of data to reduce size of arrays to fit chunk data. This
960 * method is loaded just before copying data to chunk being returned.
961 */
962 private void trimArrays() {
963 if (verticesInChunk > 0) {
964 final var elems = verticesInChunk * VERTICES_PER_TRIANGLE;
965
966 final var newCoordsInChunkArray = new float[elems];
967 final var newNormalsInChunkArray = new float[elems];
968
969 // copy contents of old arrays
970 System.arraycopy(coordsInChunkArray, 0, newCoordsInChunkArray, 0, elems);
971 System.arraycopy(normalsInChunkArray, 0, newNormalsInChunkArray, 0, elems);
972
973 // set new arrays
974 coordsInChunkArray = newCoordsInChunkArray;
975 normalsInChunkArray = newNormalsInChunkArray;
976 } else {
977 // allow garbage collection
978 coordsInChunkArray = null;
979 normalsInChunkArray = null;
980 }
981
982 if (indicesInChunk > 0) {
983 final var newIndicesInChunkArray = new int[indicesInChunk];
984 System.arraycopy(indicesInChunkArray, 0, newIndicesInChunkArray, 0, indicesInChunk);
985
986 // set new array
987 indicesInChunkArray = newIndicesInChunkArray;
988 } else {
989 // allow garbage collection
990 indicesInChunkArray = null;
991 }
992 }
993
994 /**
995 * Setups loader iterator. This method is called when constructing
996 * this iterator.
997 *
998 * @throws IOException if an I/O error occurs.
999 * @throws LoaderException if data is corrupted or cannot be understood.
1000 */
1001 private void setUp() throws IOException, LoaderException {
1002 // read start of file to determine whether it is in ascii or binary
1003 // format
1004
1005 // move to start of file
1006 reader.seek(0);
1007 final var magicStartLength = ASCII_START.length();
1008 final var buffer = new byte[magicStartLength];
1009 final var n = reader.read(buffer);
1010 if (n != magicStartLength) {
1011 throw new LoaderException();
1012 }
1013 final var str = new String(buffer);
1014
1015 isAscii = str.equalsIgnoreCase(ASCII_START);
1016 if (isAscii) {
1017 // check
1018 if (reader.isEndOfStream()) {
1019 throw new LoaderException();
1020 }
1021 // load solid name
1022 solidName = reader.readLine();
1023 } else {
1024 // Binary format (always is in little endian form)
1025
1026 // set position after 80 byte header
1027 reader.seek(BINARY_HEADER_SIZE);
1028
1029 // header + number of triangles must fit in file
1030 final var fileLength = file.length();
1031 if (fileLength < BINARY_HEADER_SIZE + BINARY_COUNT_SIZE) {
1032 throw new LoaderException();
1033 }
1034
1035 // read number of triangles
1036 numberOfTriangles = reader.readUnsignedInt(EndianType.LITTLE_ENDIAN_TYPE);
1037
1038 // validate declared triangles against actual file length
1039 // (long math to avoid overflow)
1040 final var expectedLength = BINARY_HEADER_SIZE
1041 + BINARY_COUNT_SIZE
1042 + numberOfTriangles * BINARY_TRIANGLE_SIZE;
1043 if (expectedLength > fileLength) {
1044 throw new LoaderException();
1045 }
1046 numberOfVertices = VERTICES_PER_TRIANGLE * numberOfTriangles;
1047 }
1048 }
1049
1050 }
1051 }