-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Improve memory efficiency and speed of gltf importer #2553
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
riccardobl
wants to merge
6
commits into
jMonkeyEngine:master
Choose a base branch
from
riccardobl:gltfimp
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
024bd34
improve memory efficiency of gltf importer
riccardobl 4cb2bf4
cleanup
riccardobl 8f66338
cleanup
riccardobl 3929561
fix license
riccardobl 8d10d72
further optimize streams by reading straight into the destination whe…
riccardobl 68e1fd0
ensure it does not skip outside of the buffer
riccardobl File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Submodule angle
added at
231960
72 changes: 72 additions & 0 deletions
72
jme3-core/src/main/java/com/jme3/util/BufferInputStream.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| /** | ||
| * Copyright (c) 2025, Nostr Game Engine | ||
| * | ||
| * Redistribution and use in source and binary forms, with or without | ||
| * modification, are permitted provided that the following conditions are met: | ||
| * | ||
| * 1. Redistributions of source code must retain the above copyright notice, this | ||
| * list of conditions and the following disclaimer. | ||
| * | ||
| * 2. Redistributions in binary form must reproduce the above copyright notice, | ||
| * this list of conditions and the following disclaimer in the documentation | ||
| * and/or other materials provided with the distribution. | ||
| * | ||
| * 3. Neither the name of the copyright holder nor the names of its | ||
| * contributors may be used to endorse or promote products derived from | ||
| * this software without specific prior written permission. | ||
| * | ||
| * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | ||
| * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | ||
| * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
| * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | ||
| * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | ||
| * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | ||
| * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | ||
| * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | ||
| * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
| * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
| * | ||
| * Nostr Game Engine is a fork of the jMonkeyEngine, which is licensed under | ||
| * the BSD 3-Clause License. The original jMonkeyEngine license is as follows: | ||
| */ | ||
| package com.jme3.util; | ||
|
|
||
| import java.io.IOException; | ||
| import java.io.InputStream; | ||
| import java.nio.ByteBuffer; | ||
|
|
||
| public class BufferInputStream extends InputStream { | ||
|
|
||
| ByteBuffer input; | ||
|
|
||
| public BufferInputStream(ByteBuffer input) { | ||
| this.input = input; | ||
| } | ||
|
|
||
| @Override | ||
| public int read() throws IOException { | ||
| if (input.remaining() == 0) return -1; else return input.get() & 0xff; | ||
| } | ||
|
|
||
| @Override | ||
| public int read(byte[] b) { | ||
| return read(b, 0, b.length); | ||
| } | ||
|
|
||
| @Override | ||
| public int read(byte[] b, int off, int len) { | ||
| if (b == null) throw new NullPointerException("b == null"); | ||
| if (off < 0 || len < 0 || len > b.length - off) throw new IndexOutOfBoundsException(); | ||
| if (len == 0) return 0; | ||
| if (!input.hasRemaining()) return -1; | ||
|
|
||
| int toRead = Math.min(len, input.remaining()); | ||
| input.get(b, off, toRead); | ||
| return toRead; | ||
| } | ||
|
|
||
| @Override | ||
| public int available() { | ||
| return input.remaining(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -48,11 +48,14 @@ | |
| import static com.jme3.scene.plugins.gltf.GltfUtils.*; | ||
| import com.jme3.texture.Texture; | ||
| import com.jme3.texture.Texture2D; | ||
| import com.jme3.util.BufferInputStream; | ||
| import com.jme3.util.BufferUtils; | ||
| import com.jme3.util.IntMap; | ||
| import com.jme3.util.mikktspace.MikktspaceTangentGenerator; | ||
| import java.io.*; | ||
| import java.net.URLDecoder; | ||
| import java.nio.Buffer; | ||
| import java.nio.ByteBuffer; | ||
| import java.nio.FloatBuffer; | ||
| import java.util.*; | ||
| import java.util.logging.Level; | ||
|
|
@@ -109,7 +112,6 @@ public Object load(AssetInfo assetInfo) throws IOException { | |
|
|
||
| protected Object loadFromStream(AssetInfo assetInfo, InputStream stream) throws IOException { | ||
| try { | ||
| dataCache.clear(); | ||
| info = assetInfo; | ||
| skinnedSpatials.clear(); | ||
| rootNode = new Node(); | ||
|
|
@@ -181,6 +183,27 @@ protected Object loadFromStream(AssetInfo assetInfo, InputStream stream) throws | |
| throw new AssetLoadException("An error occurred loading " + assetInfo.getKey().getName(), e); | ||
| } finally { | ||
| stream.close(); | ||
| dataCache.clear(); | ||
| skinBuffers.clear(); | ||
| skinnedSpatials.clear(); | ||
| info = null; | ||
| docRoot = null; | ||
| rootNode = null; | ||
| defaultMat = null; | ||
| accessors = null; | ||
| bufferViews = null; | ||
| buffers = null; | ||
| scenes = null; | ||
| nodes = null; | ||
| meshes = null; | ||
| materials = null; | ||
| textures = null; | ||
| images = null; | ||
| samplers = null; | ||
| animations = null; | ||
| skins = null; | ||
| cameras = null; | ||
| useNormalsFlag = false; | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This stuff can be pretty huge on big scenes, so leaving it there is pretty bad for devices with limited memory |
||
| } | ||
| } | ||
|
|
||
|
|
@@ -553,11 +576,15 @@ public Object readBuffer(Integer bufferViewIndex, int byteOffset, int count, Obj | |
| // Not sure it's useful for us, but I guess it's useful when you map data directly to the GPU. | ||
| // int target = getAsInteger(bufferView, "target", 0); | ||
|
|
||
| byte[] data = readData(bufferIndex); | ||
| ByteBuffer data = readData(bufferIndex); | ||
| data = customContentManager.readExtensionAndExtras("bufferView", bufferView, data); | ||
|
|
||
| if(!(data instanceof ByteBuffer)){ | ||
| throw new IOException("Buffer data is not a NIO Buffer"); | ||
| } | ||
|
|
||
| if (store == null) { | ||
| store = new byte[byteLength]; | ||
| store = BufferUtils.createByteBuffer(byteLength); | ||
| } | ||
|
|
||
| if (count == -1) { | ||
|
|
@@ -569,14 +596,40 @@ public Object readBuffer(Integer bufferViewIndex, int byteOffset, int count, Obj | |
| return store; | ||
| } | ||
|
|
||
| public byte[] readData(int bufferIndex) throws IOException { | ||
| public Buffer viewBuffer(Integer bufferViewIndex, int byteOffset, int count, | ||
| int numComponents, VertexBuffer.Format originalFormat, VertexBuffer.Format targetFormat) throws IOException { | ||
| JsonObject bufferView = bufferViews.get(bufferViewIndex).getAsJsonObject(); | ||
| Integer bufferIndex = getAsInteger(bufferView, "buffer"); | ||
| assertNotNull(bufferIndex, "No buffer defined for bufferView " + bufferViewIndex); | ||
| int bvByteOffset = getAsInteger(bufferView, "byteOffset", 0); | ||
| Integer byteLength = getAsInteger(bufferView, "byteLength"); | ||
| assertNotNull(byteLength, "No byte length defined for bufferView " + bufferViewIndex); | ||
| int byteStride = getAsInteger(bufferView, "byteStride", 0); | ||
|
|
||
| ByteBuffer data = readData(bufferIndex); | ||
| data = customContentManager.readExtensionAndExtras("bufferView", bufferView, data); | ||
|
|
||
| if(!(data instanceof ByteBuffer)){ | ||
| throw new IOException("Buffer data is not a NIO Buffer"); | ||
| } | ||
|
|
||
|
|
||
| if (count == -1) { | ||
| count = byteLength; | ||
| } | ||
|
|
||
| return GltfUtils.getBufferView(data, byteOffset + bvByteOffset, count, byteStride, numComponents, originalFormat, targetFormat ); | ||
|
|
||
| } | ||
|
|
||
| public ByteBuffer readData(int bufferIndex) throws IOException { | ||
| assertNotNull(buffers, "No buffer defined"); | ||
|
|
||
| JsonObject buffer = buffers.get(bufferIndex).getAsJsonObject(); | ||
| String uri = getAsString(buffer, "uri"); | ||
| Integer bufferLength = getAsInteger(buffer, "byteLength"); | ||
| assertNotNull(bufferLength, "No byteLength defined for buffer " + bufferIndex); | ||
| byte[] data = (byte[]) fetchFromCache("buffers", bufferIndex, Object.class); | ||
| ByteBuffer data = (ByteBuffer) fetchFromCache("buffers", bufferIndex, Object.class); | ||
| if (data != null) { | ||
| return data; | ||
| } | ||
|
|
@@ -588,12 +641,12 @@ public byte[] readData(int bufferIndex) throws IOException { | |
| return data; | ||
| } | ||
|
|
||
| protected byte[] getBytes(int bufferIndex, String uri, Integer bufferLength) throws IOException { | ||
| byte[] data; | ||
| protected ByteBuffer getBytes(int bufferIndex, String uri, Integer bufferLength) throws IOException { | ||
| ByteBuffer data; | ||
| if (uri != null) { | ||
| if (uri.startsWith("data:")) { | ||
| // base 64 embed data | ||
| data = Base64.getDecoder().decode(uri.substring(uri.indexOf(",") + 1)); | ||
| data = BufferUtils.createByteBuffer(Base64.getDecoder().decode(uri.substring(uri.indexOf(",") + 1))); | ||
| } else { | ||
| // external file let's load it | ||
| String decoded = decodeUri(uri); | ||
|
|
@@ -603,11 +656,11 @@ protected byte[] getBytes(int bufferIndex, String uri, Integer bufferLength) thr | |
| } | ||
|
|
||
| BinDataKey key = new BinDataKey(info.getKey().getFolder() + decoded); | ||
| InputStream input = (InputStream) info.getManager().loadAsset(key); | ||
| data = new byte[bufferLength]; | ||
| try (DataInputStream dataStream = new DataInputStream(input)) { | ||
| dataStream.readFully(data); | ||
| try(InputStream input = (InputStream) info.getManager().loadAsset(key)){ | ||
| data = BufferUtils.createByteBuffer(bufferLength); | ||
| GltfUtils.readToByteBuffer(input, data, bufferLength, -1); | ||
| } | ||
|
|
||
| } | ||
| } else { | ||
| // no URI, this should not happen in a gltf file, only in glb files. | ||
|
|
@@ -784,19 +837,23 @@ public Texture2D readImage(int sourceIndex, boolean flip) throws IOException { | |
| if (uri == null) { | ||
| assertNotNull(bufferView, "Image " + sourceIndex + " should either have an uri or a bufferView"); | ||
| assertNotNull(mimeType, "Image " + sourceIndex + " should have a mimeType"); | ||
| byte[] data = (byte[]) readBuffer(bufferView, 0, -1, null, 1, VertexBuffer.Format.Byte); | ||
| ByteBuffer data = (ByteBuffer) viewBuffer(bufferView, 0, -1, 1, VertexBuffer.Format.Byte, VertexBuffer.Format.Byte); | ||
|
|
||
| String extension = mimeType.split("/")[1]; | ||
| TextureKey key = new TextureKey("image" + sourceIndex + "." + extension, flip); | ||
| result = (Texture2D) info.getManager().loadAssetFromStream(key, new ByteArrayInputStream(data)); | ||
|
|
||
| try(BufferedInputStream bis = new BufferedInputStream(new BufferInputStream(data))){ | ||
| result = (Texture2D) info.getManager().loadAssetFromStream(key, bis); | ||
| } | ||
| } else if (uri.startsWith("data:")) { | ||
| // base64 encoded image | ||
| String[] uriInfo = uri.split(","); | ||
| byte[] data = Base64.getDecoder().decode(uriInfo[1]); | ||
| ByteBuffer data = BufferUtils.createByteBuffer(Base64.getDecoder().decode(uriInfo[1])); | ||
| String headerInfo = uriInfo[0].split(";")[0]; | ||
| String extension = headerInfo.split("/")[1]; | ||
| TextureKey key = new TextureKey("image" + sourceIndex + "." + extension, flip); | ||
| result = (Texture2D) info.getManager().loadAssetFromStream(key, new ByteArrayInputStream(data)); | ||
| try(BufferedInputStream bis = new BufferedInputStream(new BufferInputStream(data))){ | ||
| result = (Texture2D) info.getManager().loadAssetFromStream(key, bis); | ||
| } | ||
| } else { | ||
| // external file image | ||
| String decoded = decodeUri(uri); | ||
|
|
@@ -1338,13 +1395,14 @@ public VertexBuffer populate(Integer bufferViewIndex, int componentType, String | |
| } | ||
| int numComponents = getNumberOfComponents(type); | ||
|
|
||
| Buffer buff = VertexBuffer.createBuffer(format, numComponents, count); | ||
| int bufferSize = numComponents * count; | ||
| Buffer buff; | ||
| if (bufferViewIndex == null) { | ||
| buff = VertexBuffer.createBuffer(format, numComponents, count); | ||
| // no referenced buffer, specs says to pad the buffer with zeros. | ||
| padBuffer(buff, bufferSize); | ||
| } else { | ||
| readBuffer(bufferViewIndex, byteOffset, count, buff, numComponents, originalFormat); | ||
| buff = (Buffer) viewBuffer(bufferViewIndex, byteOffset, count, numComponents, originalFormat, format); | ||
| } | ||
|
|
||
| if (bufferType == VertexBuffer.Type.Index) { | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This fixes the way the stream is read, since
stream.read, as it was used before, can return before the stream is read fully, if it hangs (eg. when loading from a slow disk or network)