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 import java.nio.ByteBuffer;
21 import java.nio.file.Files;
22
23 /**
24 * Loads a custom binary file implemented for this library.
25 * The binary format has been created to keep 3D data in a more compact way than
26 * other formats.
27 */
28 public class LoaderBinary extends Loader {
29
30 /**
31 * Buffer size to load input file.
32 */
33 public static final int BUFFER_SIZE = 1024;
34
35 /**
36 * Version number of the binary format supported by this class.
37 */
38 private static final byte SUPPORTED_VERSION = 2;
39
40 /**
41 * Number of bytes required to determine the bounding box of a chunk or
42 * the whole 3D object (which are 2 3D points = 2x3 coordinates =
43 * 6 floats * 4 bytes per float).
44 */
45 private static final int BOUNDING_BYTES_SIZE = 6 * Float.SIZE / 8;
46
47 /**
48 * Iterator to load binary data in small chunks.
49 * Usually data is divided in chunks that can be directly loaded by
50 * graphic layers such as OpenGL.
51 */
52 private LoaderIteratorBinary loaderIterator;
53
54 /**
55 * Indicates if file has been checked to have a valid header. Notice that
56 * file might still be corrupt or incomplete at some point.
57 */
58 private final boolean validityChecked;
59
60 /**
61 * Indicates if after checking validity, the file header has been found to
62 * be valid or not.
63 */
64 private boolean validFile;
65
66 /**
67 * Constructor.
68 */
69 public LoaderBinary() {
70 loaderIterator = null;
71 validityChecked = false;
72 validFile = false;
73 }
74
75 /**
76 * Constructor.
77 *
78 * @param f file to be loaded.
79 * @throws IOException if an I/O error occurs.
80 */
81 public LoaderBinary(final File f) throws IOException {
82 super(f);
83 loaderIterator = null;
84 validityChecked = false;
85 validFile = false;
86 }
87
88 /**
89 * Constructor.
90 *
91 * @param listener listener to be notified of loading progress.
92 */
93 public LoaderBinary(final LoaderListener listener) {
94 super(listener);
95 loaderIterator = null;
96 validityChecked = false;
97 validFile = false;
98 }
99
100 /**
101 * Constructor.
102 *
103 * @param f file to be loaded.
104 * @param listener listener to be notified of loading progress.
105 * @throws IOException if an I/O error occurs.
106 */
107 public LoaderBinary(final File f, final LoaderListener listener) throws IOException {
108 super(f, listener);
109 loaderIterator = null;
110 validityChecked = false;
111 validFile = false;
112 }
113
114 /**
115 * If loader is ready to start loading a file.
116 * This is true once a file has been provided.
117 *
118 * @return true if ready to start loading a file, false otherwise.
119 */
120 @Override
121 public boolean isReady() {
122 return hasFile();
123 }
124
125 /**
126 * Returns mesh format supported by this class, which is MESH_FORMAT_BINARY2.
127 *
128 * @return mesh format supported by this class.
129 */
130 @Override
131 public MeshFormat getMeshFormat() {
132 return MeshFormat.MESH_FORMAT_BINARY2;
133 }
134
135 /**
136 * Determines if provided file is a valid file that can be read by this
137 * loader.
138 *
139 * @return true if file is valid, false otherwise.
140 * @throws LockedException raised if this instance is already locked.
141 * @throws IOException if an I/O error occurs.
142 */
143 @Override
144 public boolean isValidFile() throws LockedException, IOException {
145 if (!hasFile()) {
146 throw new IOException();
147 }
148 if (isLocked()) {
149 throw new LockedException();
150 }
151
152 if (!validityChecked) {
153 // check that file version is supported
154 final var version = reader.readByte();
155 validFile = (version == SUPPORTED_VERSION);
156 }
157
158 return validFile;
159 }
160
161 /**
162 * Starts the loading process of provided file.
163 * This method returns a LoaderIterator to start the iterative process to
164 * load a file in small chunks of data.
165 *
166 * @return a loader iterator to read the file in a step-by-step process.
167 * @throws LockedException raised if this instance is already locked.
168 * @throws NotReadyException raised if this instance is not yet ready.
169 * @throws IOException if an I/O error occurs.
170 * @throws LoaderException if file is corrupted or cannot be interpreted.
171 */
172 @Override
173 public LoaderIterator load() throws LockedException, NotReadyException, IOException, LoaderException {
174 if (isLocked()) {
175 throw new LockedException();
176 }
177 if (!isReady()) {
178 throw new NotReadyException();
179 }
180
181 // check file validity by reading its version
182 if (!isValidFile()) {
183 throw new LoaderException();
184 }
185
186 setLocked(true);
187 if (listener != null) {
188 listener.onLoadStart(this);
189 }
190
191 // do not leave this loader locked if file cannot be loaded
192 loadReleasingLockOnFailure(() -> {
193 readTextures();
194 return null;
195 });
196
197 loaderIterator = new LoaderIteratorBinary(this);
198 loaderIterator.setListener(new LoaderIteratorListenerImpl(this));
199 return loaderIterator;
200 }
201
202 /**
203 * Reads textures until no more textures are available.
204 *
205 * @throws IOException if an I/O error occurs.
206 * @throws LoaderException if file is corrupted or cannot be interpreted.
207 */
208 private void readTextures() throws IOException, LoaderException {
209 // read textures until no more textures are available
210 while (reader.readBoolean()) {
211 // texture data follows
212 final var texId = reader.readInt();
213 final var texWidth = reader.readInt();
214 final var texHeight = reader.readInt();
215 final var texLength = reader.readLong();
216 final var textureFileStartPos = reader.getPosition();
217
218 // check that at least texLength bytes remain otherwise file is
219 // incomplete or corrupted
220 if (texLength < 0
221 || texLength > file.length() - textureFileStartPos) {
222 throw new LoaderException();
223 }
224
225 // notify that texture data is available
226 if (listener instanceof LoaderListenerBinary loaderListener) {
227
228 // request file where texture will be stored
229 final var texFile = loaderListener.onTextureReceived(this, texId, texWidth, texHeight);
230
231 if (texFile != null) {
232 // write texture data at provided file
233 final var buffer = new byte[BUFFER_SIZE];
234
235 var counter = 0;
236 try (final var outStream = Files.newOutputStream(texFile.toPath())) {
237 int n;
238 var len = BUFFER_SIZE;
239 while (counter < texLength) {
240 if (counter + len > texLength) {
241 len = (int) texLength - counter;
242 }
243 n = reader.read(buffer, 0, len);
244 outStream.write(buffer, 0, n);
245 if (n > 0) {
246 counter += n;
247 } else {
248 break;
249 }
250 }
251
252 outStream.flush();
253 }
254
255 if (counter != texLength) {
256 throw new LoaderException();
257 }
258
259 // notify that texture data has been written to provided file
260 final var valid = loaderListener.onTextureDataAvailable(this, texFile, texId, texWidth,
261 texHeight);
262 // texture processing couldn't be correctly done
263 if (!valid) {
264 throw new LoaderException();
265 }
266 } else {
267 // skip to end of texture file in case that listener
268 // didn't provide a file to write texture data
269 reader.skip(texLength);
270 }
271 } else {
272 // skip to end of texture file in case that there is no listener
273 reader.skip(texLength);
274 }
275 }
276 }
277
278 /**
279 * Internal listener to be notified when loading process finishes.
280 * This listener is used to free resources when loading process finishes.
281 */
282 private class LoaderIteratorListenerImpl implements LoaderIteratorListener {
283
284 /**
285 * Reference to Loader loading binary file.
286 */
287 private final LoaderBinary loader;
288
289 /**
290 * Constructor.
291 *
292 * @param loader reference to Loader.
293 */
294 public LoaderIteratorListenerImpl(final LoaderBinary loader) {
295 this.loader = loader;
296 }
297
298 /**
299 * Method to be notified when the loading process finishes.
300 *
301 * @param iterator iterator loading the file in chunks.
302 */
303 @Override
304 public void onIteratorFinished(final LoaderIterator iterator) {
305 // because iterator is finished, we should allow subsequent calls to
306 // load method
307
308 // on subsequent calls
309 if (listener != null) {
310 listener.onLoadEnd(loader);
311 }
312 setLocked(false);
313 }
314 }
315
316 /**
317 * Loader iterator in charge of loading file data in small chunks.
318 * Usually data is divided in chunks small enough that can be directly
319 * loaded by graphical layers such as OpenGL (which has a limit of 65535
320 * indices when using Vertex Buffer Objects, which increase graphical
321 * performance).
322 */
323 private class LoaderIteratorBinary implements LoaderIterator {
324
325 /**
326 * Reference to loader loading binary file.
327 */
328 private final LoaderBinary loader;
329
330 /**
331 * Reference to the listener of this loader iterator. This listener will
332 * be notified when the loading process finishes so that resources can
333 * be freed.
334 */
335 private LoaderIteratorListener listener;
336
337 /**
338 * Constructor.
339 *
340 * @param loader reference to loader loading binary file.
341 */
342 public LoaderIteratorBinary(final LoaderBinary loader) {
343 this.loader = loader;
344 listener = null;
345 }
346
347 /**
348 * Method to set listener of this loader iterator.
349 * This listener will be notified when the loading process finishes.
350 *
351 * @param listener listener of this loader iterator.
352 */
353 public void setListener(final LoaderIteratorListener listener) {
354 this.listener = listener;
355 }
356
357 /**
358 * Indicates if there is another chunk of data to be loaded.
359 *
360 * @return true if there is another chunk of data, false otherwise.
361 */
362 @Override
363 public boolean hasNext() {
364 try {
365 return !reader.isEndOfStream();
366 } catch (final IOException e) {
367 return false;
368 }
369 }
370
371 /**
372 * Loads and returns next chunk of data, if available.
373 *
374 * @return next chunk of data.
375 * @throws NotAvailableException thrown if no more data is available.
376 * @throws LoaderException if file data is corrupt or cannot be
377 * understood.
378 * @throws IOException if an I/O error occurs.
379 */
380 @Override
381 public DataChunk next() throws NotAvailableException, LoaderException, IOException {
382 if (!hasNext()) {
383 throw new NotAvailableException();
384 }
385
386 // do not leave loader locked if file cannot be read
387 return readReleasingLockOnFailure(this::readNextChunk);
388 }
389
390 /**
391 * Reads next chunk of data.
392 *
393 * @return next chunk of data.
394 * @throws LoaderException if file data is corrupt or cannot be
395 * understood.
396 * @throws IOException if an I/O error occurs.
397 */
398 private DataChunk readNextChunk() throws LoaderException, IOException {
399 // read chunk size
400 final var chunkSize = reader.readInt();
401
402 // ensure that chunk size is positive, otherwise file is corrupted
403 if (chunkSize < 0) {
404 throw new LoaderException();
405 }
406
407 // get position of start of chunk
408 final var chunkStartPos = reader.getPosition();
409
410 // position of end of chunk
411 final var chunkEndPos = chunkStartPos + chunkSize;
412
413 // check that at least chunkSize bytes remain otherwise file is
414 // incomplete or corrupted
415 final var fileLength = file.length();
416 if (chunkEndPos > fileLength) {
417 throw new LoaderException();
418 }
419
420 final var chunk = new DataChunk();
421
422 // ----- MATERIAL ------
423 if (reader.readBoolean()) {
424 // material is available
425 final var materialId = reader.readInt();
426
427 final var material = new Material();
428 chunk.setMaterial(material);
429 material.setId(materialId);
430
431 if (reader.readBoolean()) {
432 // ambient color is available
433 byte b;
434 // red
435 b = reader.readByte();
436 material.setAmbientRedColor((short) (b & 0x000000ff));
437 // green
438 b = reader.readByte();
439 material.setAmbientGreenColor((short) (b & 0x000000ff));
440 // blue
441 b = reader.readByte();
442 material.setAmbientBlueColor((short) (b & 0x000000ff));
443 }
444
445 if (reader.readBoolean()) {
446 // diffuse color is available
447 // red
448 var b = reader.readByte();
449 material.setDiffuseRedColor((short) (b & 0x000000ff));
450 // green
451 b = reader.readByte();
452 material.setDiffuseGreenColor((short) (b & 0x000000ff));
453 // blue
454 b = reader.readByte();
455 material.setDiffuseBlueColor((short) (b & 0x000000ff));
456 }
457
458 if (reader.readBoolean()) {
459 // specular color is available
460 // red
461 var b = reader.readByte();
462 material.setSpecularRedColor((short) (b & 0x000000ff));
463 // green
464 b = reader.readByte();
465 material.setSpecularGreenColor((short) (b & 0x000000ff));
466 // blue
467 b = reader.readByte();
468 material.setSpecularBlueColor((short) (b & 0x000000ff));
469 }
470
471 if (reader.readBoolean()) {
472 // specular coefficient is available
473 material.setSpecularCoefficient(reader.readFloat());
474 }
475
476 if (reader.readBoolean()) {
477 // ambient texture map is available
478 final var textureId = reader.readInt();
479 final var tex = new Texture(textureId);
480 material.setAmbientTextureMap(tex);
481
482 tex.setWidth(reader.readInt());
483 tex.setHeight(reader.readInt());
484 }
485
486 if (reader.readBoolean()) {
487 // diffuse texture map is available
488 final var textureId = reader.readInt();
489 final var tex = new Texture(textureId);
490 material.setDiffuseTextureMap(tex);
491
492 tex.setWidth(reader.readInt());
493 tex.setHeight(reader.readInt());
494 }
495
496 if (reader.readBoolean()) {
497 // specular texture map is available
498 final var textureId = reader.readInt();
499 final var tex = new Texture(textureId);
500 material.setSpecularTextureMap(tex);
501
502 tex.setWidth(reader.readInt());
503 tex.setHeight(reader.readInt());
504 }
505
506 if (reader.readBoolean()) {
507 // alpha texture map is available
508 final var textureId = reader.readInt();
509 final var tex = new Texture(textureId);
510 material.setAlphaTextureMap(tex);
511
512 tex.setWidth(reader.readInt());
513 tex.setHeight(reader.readInt());
514 }
515
516 if (reader.readBoolean()) {
517 // bump texture map is available
518 final var textureId = reader.readInt();
519 final var tex = new Texture(textureId);
520 material.setBumpTextureMap(tex);
521
522 tex.setWidth(reader.readInt());
523 tex.setHeight(reader.readInt());
524 }
525
526 if (reader.readBoolean()) {
527 // transparency is available
528 final var b = reader.readByte();
529 material.setTransparency((short) (b & 0x000000ff));
530 }
531
532 if (reader.readBoolean()) {
533 // illumination is available
534 final var value = reader.readInt();
535 material.setIllumination(Illumination.forValue(value));
536 }
537 }
538
539 // ---- COORDS -------
540
541 // read coords size
542 final var coordsSizeInBytes = reader.readInt();
543
544 // ensure that coords size is positive, otherwise file is corrupted
545 if (coordsSizeInBytes < 0) {
546 throw new LoaderException();
547 }
548 // if size in bytes is not multiple of float size (4 bytes), then
549 // file is corrupted
550 if (coordsSizeInBytes % (Float.SIZE / 8) != 0) {
551 throw new LoaderException();
552 }
553
554 // if coords are available
555 if (coordsSizeInBytes > 0) {
556 // ensure that coords fit within chunk, otherwise file is
557 // corrupted
558 if (reader.getPosition() + coordsSizeInBytes > chunkEndPos) {
559 throw new LoaderException();
560 }
561
562 // get number of floats in coords
563 final var coordsLength = coordsSizeInBytes / (Float.SIZE / 8);
564
565 // read coordsSize bytes into array of floats
566 final var coords = new float[coordsLength];
567 final var bytes = new byte[coordsSizeInBytes];
568 reader.read(bytes);
569 final var bytesBuffer = ByteBuffer.wrap(bytes);
570 final var floatBuffer = bytesBuffer.asFloatBuffer();
571 floatBuffer.get(coords);
572
573 chunk.setVerticesCoordinatesData(coords);
574
575 // compute progress
576 if (loader.listener != null) {
577 loader.listener.onLoadProgressChange(loader,
578 (float) (reader.getPosition()) / (float) (file.length()));
579 }
580 }
581
582 // ----- COLORS ------
583
584 // read colors size
585 final var colorsSizeInBytes = reader.readInt();
586
587 // ensure that colors size is positive, otherwise file is corrupted
588 if (colorsSizeInBytes < 0) {
589 throw new LoaderException();
590 }
591
592 // each color data is stored in a byte, so there is no need to check size multiplicity
593
594 // if colors are available
595 if (colorsSizeInBytes > 0) {
596 // ensure that colors fit within chunk, otherwise file is corrupted
597 if (reader.getPosition() + colorsSizeInBytes > chunkEndPos) {
598 throw new LoaderException();
599 }
600
601 // read colorSizeInBytes into array of shorts (conversion
602 // must be done from unsigned bytes to shorts, as java does not
603 // support unsigned bytes values
604 final var colors = new short[colorsSizeInBytes];
605 final var bytes = new byte[colorsSizeInBytes];
606 reader.read(bytes);
607 for (var i = 0; i < colorsSizeInBytes; i++) {
608 // convert signed bytes into unsigned bytes stored in shorts
609 colors[i] = (short) (bytes[i] & 0x000000ff);
610 }
611 chunk.setColorData(colors);
612
613 // read color components
614 chunk.setColorComponents(reader.readInt());
615
616 // compute progress
617 if (loader.listener != null) {
618 loader.listener.onLoadProgressChange(loader,
619 (float) (reader.getPosition()) / (float) (file.length()));
620 }
621 }
622
623 // ------ INDICES ------
624
625 // read indices size
626 final var indicesSizeInBytes = reader.readInt();
627
628 // ensure that indices size is positive, otherwise file is corrupted
629 if (indicesSizeInBytes < 0) {
630 throw new LoaderException();
631 }
632 // if size in bytes is not multiple of float size (4 bytes), then file is corrupted
633 if (indicesSizeInBytes % (Short.SIZE / 8) != 0) {
634 throw new LoaderException();
635 }
636
637 // if indices are available
638 if (indicesSizeInBytes > 0) {
639 // ensure that indices fit within chunk, otherwise file is corrupted
640 if (reader.getPosition() + indicesSizeInBytes > chunkEndPos) {
641 throw new LoaderException();
642 }
643
644 // get number of shorts in indices
645 final var indicesLength = indicesSizeInBytes / (Short.SIZE / 8);
646
647 // read coordsSize bytes into array of floats
648 final var indices = new int[indicesLength];
649 final var bytes = new byte[indicesSizeInBytes];
650 reader.read(bytes);
651 int firstByte;
652 int secondByte;
653 var counter = 0;
654 for (var i = 0; i < indicesLength; i++) {
655 firstByte = bytes[counter] & 0x000000ff;
656 counter++;
657 secondByte = bytes[counter] & 0x000000ff;
658 counter++;
659 indices[i] = firstByte << 8 | secondByte;
660 }
661 chunk.setIndicesData(indices);
662
663 // compute progress
664 if (loader.listener != null) {
665 loader.listener.onLoadProgressChange(loader,
666 (float) (reader.getPosition()) / (float) (file.length()));
667 }
668 }
669
670 // -------- TEXTURE COORDS --------
671
672 // read texture coords size
673 final var texCoordsSizeInBytes = reader.readInt();
674
675 // ensure that texture coords size is positive, otherwise file is corrupted
676 if (texCoordsSizeInBytes < 0) {
677 throw new LoaderException();
678 }
679 // if size in bytes is not multiple of float size (4 bytes), then
680 // file is corrupted
681 if (texCoordsSizeInBytes % (Float.SIZE / 8) != 0) {
682 throw new LoaderException();
683 }
684
685 // if texture coords are available
686 if (texCoordsSizeInBytes > 0) {
687 // ensure that texture coords fit within chunk, otherwise file is
688 // corrupted
689 if (reader.getPosition() + texCoordsSizeInBytes > chunkEndPos) {
690 throw new LoaderException();
691 }
692
693 // get number of floats in coords
694 final var texCoordsLength = texCoordsSizeInBytes / (Float.SIZE / 8);
695
696 // read coordsSize bytes into array of floats
697 final var texCoords = new float[texCoordsLength];
698 final var bytes = new byte[texCoordsSizeInBytes];
699 reader.read(bytes);
700 final var bytesBuffer = ByteBuffer.wrap(bytes);
701 final var floatBuffer = bytesBuffer.asFloatBuffer();
702 floatBuffer.get(texCoords);
703 chunk.setTextureCoordinatesData(texCoords);
704
705 // compute progress
706 if (loader.listener != null) {
707 loader.listener.onLoadProgressChange(loader,
708 (float) (reader.getPosition()) / (float) (file.length()));
709 }
710 }
711
712 // -------- NORMALS --------
713
714 // read normals size
715 final var normalsSizeInBytes = reader.readInt();
716
717 // ensure that normals size is positive, otherwise file is
718 // corrupted
719 if (normalsSizeInBytes < 0) {
720 throw new LoaderException();
721 }
722 // if size in bytes is not multiple of float size (4 bytes), then
723 // file is corrupted
724 if (normalsSizeInBytes % (Float.SIZE / 8) != 0) {
725 throw new LoaderException();
726 }
727
728 // if texture coords are available
729 if (normalsSizeInBytes > 0) {
730 // ensure that normals fit within chunk, otherwise file is
731 // corrupted
732 if (reader.getPosition() + normalsSizeInBytes > chunkEndPos) {
733 throw new LoaderException();
734 }
735
736 // get number of floats in coords
737 final var normalsLength = normalsSizeInBytes / (Float.SIZE / 8);
738
739 // read coordsSize bytes into array of floats
740 final var normals = new float[normalsLength];
741 final var bytes = new byte[normalsSizeInBytes];
742 reader.read(bytes);
743 final var bytesBuffer = ByteBuffer.wrap(bytes);
744 final var floatBuffer = bytesBuffer.asFloatBuffer();
745 floatBuffer.get(normals);
746 chunk.setNormalsData(normals);
747
748 // compute progress
749 if (loader.listener != null) {
750 loader.listener.onLoadProgressChange(loader,
751 (float) (reader.getPosition()) / (float) (file.length()));
752 }
753 }
754
755 // read bounding box for chunk (min/max x, y, z)
756
757 // we need to load 6 floats, so position + 6 * Float.SIZE / 8 bytes must fit within chunk
758 if (reader.getPosition() + (BOUNDING_BYTES_SIZE) > chunkEndPos) {
759 throw new LoaderException();
760 }
761
762 final var bytes = new byte[BOUNDING_BYTES_SIZE];
763 reader.read(bytes);
764 final var bytesBuffer = ByteBuffer.wrap(bytes);
765 final var floatBuffer = bytesBuffer.asFloatBuffer();
766 chunk.setMinX(floatBuffer.get());
767 chunk.setMinY(floatBuffer.get());
768 chunk.setMinZ(floatBuffer.get());
769
770 chunk.setMaxX(floatBuffer.get());
771 chunk.setMaxY(floatBuffer.get());
772 chunk.setMaxZ(floatBuffer.get());
773
774 // compute progress
775 if (loader.listener != null) {
776 loader.listener.onLoadProgressChange(loader,
777 (float) (reader.getPosition()) / (float) (file.length()));
778 }
779
780 if (!hasNext() && listener != null) {
781 // notify iterator finished
782 listener.onIteratorFinished(this);
783 }
784
785 return chunk;
786 }
787 }
788 }