From 488fea63d06b7f485c759c11bb08d210acd90f49 Mon Sep 17 00:00:00 2001 From: Tobias Knerr Date: Fri, 19 May 2023 10:09:08 +0200 Subject: [PATCH] Avoid duplicate textures from texture atlas generation in glTF --- .../osm2world/core/target/gltf/GltfTarget.java | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/osm2world/core/target/gltf/GltfTarget.java b/src/main/java/org/osm2world/core/target/gltf/GltfTarget.java index 2b7d57ad..6070b8a6 100644 --- a/src/main/java/org/osm2world/core/target/gltf/GltfTarget.java +++ b/src/main/java/org/osm2world/core/target/gltf/GltfTarget.java @@ -57,6 +57,7 @@ public class GltfTarget extends MeshTarget { private final Gltf gltf = new Gltf(); private final Map materialIndexMap = new HashMap<>(); + private final Map textureIndexMap = new HashMap<>(); private final Map imageIndexMap = new HashMap<>(); public GltfTarget(File outputFile, @Nullable SimpleClosedShapeXZ bounds) { @@ -241,13 +242,9 @@ private int createMesh(Mesh mesh) throws IOException { int materialIndex; if (material.getNumTextureLayers() == 0) { - materialIndex = materialIndexMap.containsKey(material) - ? materialIndexMap.get(material) - : createMaterial(material, null); + materialIndex = createMaterial(material, null); } else { - materialIndex = materialIndexMap.containsKey(material) - ? materialIndexMap.get(material) - : createMaterial(material, material.getTextureLayers().get(0)); + materialIndex = createMaterial(material, material.getTextureLayers().get(0)); } primitive.material = materialIndex; @@ -333,6 +330,8 @@ private int createAccessor(int numComponents, List vs) { private int createMaterial(Material m, @Nullable TextureLayer textureLayer) throws IOException { + if (materialIndexMap.containsKey(m)) return materialIndexMap.get(m); + GltfMaterial material = new GltfMaterial(); material.pbrMetallicRoughness = new PbrMetallicRoughness(); @@ -399,6 +398,8 @@ private int createMaterial(Material m, @Nullable TextureLayer textureLayer) thro private int createTexture(TextureData textureData) throws IOException { + if (textureIndexMap.containsKey(textureData)) return textureIndexMap.get(textureData); + File outputDir = outputFile.getParentFile(); URI textureDir = new File(outputDir,FilenameUtils.removeExtension(outputFile.getName()) + "_textures").toURI(); ResourceOutputSettings resourceOutputSettings = ResourceOutputSettings.fromConfig(config, textureDir, true); @@ -431,7 +432,9 @@ private int createTexture(TextureData textureData) throws IOException { texture.sampler = samplerIndex; gltf.textures.add(texture); - return gltf.textures.size() - 1; + int index = gltf.textures.size() - 1; + textureIndexMap.put(textureData, index); + return index; }