TextureAtlas .java

net.minecraft.client.renderer.texture.TextureAtlas (class, 314 lines): members: animatedTexturesStates, cycleAnimationFrames, LOCATION_PARTICLES, mipViews.

net.minecraft.client.renderer.textureclass314 linesclientextends AbstractTexture11.5 KB

Implements

API Surface (11)

void upload(final SpriteLoader.Preparations preparations)
void dumpContents(final Identifier selfId, final Path dir)
void cycleAnimationFrames()
void tick()
TextureAtlasSprite getSprite(final Identifier location)
TextureAtlasSprite missingSprite()
void clearTextureData()
void releaseTextures()
void close()
Identifier location()
int maxSupportedTextureSize()

Fields & Constants (16)

LOGGER
LOCATION_BLOCKS
LOCATION_ITEMS
LOCATION_PARTICLES
sprites
animatedTexturesStates
texturesByName
missingSprite
location
maxSupportedTextureSize
width
height
maxMipLevel
mipLevelCount
mipViews
spriteUbos

String literals (11)

"textures/atlas/blocks.png"
"textures/atlas/items.png"
"textures/atlas/particles.png"
"Atlas '"
" sprites) has no missing texture sprite"
" sprite UBOs"
"SpriteAnimationInfo"
"Animate "
"Sprite"
".txt"
"Atlas not initialized"

Full Source

TextureAtlas.java314 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.client.renderer.texture;
2
3
import com.google.common.collect.ImmutableList;
4
import com.google.common.collect.ImmutableList.Builder;
5
import com.mojang.blaze3d.platform.TextureUtil;
6
import com.mojang.blaze3d.systems.RenderSystem;
7
import com.mojang.logging.LogUtils;
8
import com.mojang.renderpearl.api.GpuFormat;
9
import com.mojang.renderpearl.api.buffers.GpuBuffer;
10
import com.mojang.renderpearl.api.commands.RenderPass;
11
import com.mojang.renderpearl.api.device.GpuDevice;
12
import com.mojang.renderpearl.api.textures.FilterMode;
13
import com.mojang.renderpearl.api.textures.GpuSampler;
14
import com.mojang.renderpearl.api.textures.GpuTexture;
15
import com.mojang.renderpearl.api.textures.GpuTextureView;
16
import java.io.IOException;
17
import java.io.Writer;
18
import java.nio.ByteBuffer;
19
import java.nio.file.Files;
20
import java.nio.file.Path;
21
import java.util.ArrayList;
22
import java.util.List;
23
import java.util.Locale;
24
import java.util.Map;
25
import java.util.Objects;
26
import java.util.Optional;
27
import java.util.Map.Entry;
28
import net.fabricmc.api.EnvType;
29
import net.fabricmc.api.Environment;
30
import net.fabricmc.fabric.api.client.renderer.v1.sprite.FabricTextureAtlas;
31
import net.minecraft.SharedConstants;
32
import net.minecraft.client.renderer.RenderPipelines;
33
import net.minecraft.resources.Identifier;
34
import net.minecraft.util.Mth;
35
import org.jspecify.annotations.Nullable;
36
import org.lwjgl.system.MemoryUtil;
37
import org.slf4j.Logger;
38
39
@Environment(EnvType.CLIENT)
40
public class TextureAtlas extends AbstractTexture implements TickableTexture, Dumpable, FabricTextureAtlas {
41
	private static final Logger LOGGER = LogUtils.getLogger();
42
	@Deprecated
43
	public static final Identifier LOCATION_BLOCKS = Identifier.withDefaultNamespace("textures/atlas/blocks.png");
44
	@Deprecated
45
	public static final Identifier LOCATION_ITEMS = Identifier.withDefaultNamespace("textures/atlas/items.png");
46
	@Deprecated
47
	public static final Identifier LOCATION_PARTICLES = Identifier.withDefaultNamespace("textures/atlas/particles.png");
48
	private List<TextureAtlasSprite> sprites = List.of();
49
	private List<SpriteContents.AnimationState> animatedTexturesStates = List.of();
50
	private Map<Identifier, TextureAtlasSprite> texturesByName = Map.of();
51
	private @Nullable TextureAtlasSprite missingSprite;
52
	private final Identifier location;
53
	private final int maxSupportedTextureSize;
54
	private int width;
55
	private int height;
56
	private int maxMipLevel;
57
	private int mipLevelCount;
58
	private GpuTextureView[] mipViews = new GpuTextureView[0];
59
	private @Nullable GpuBuffer spriteUbos;
60
61
	public TextureAtlas(final Identifier location) {
62
		this.location = location;
63
		this.maxSupportedTextureSize = RenderSystem.getDevice().getDeviceInfo().limits().maxTextureSizeForFormat(GpuFormat.RGBA8_UNORM);
64
	}
65
66
	private void createTexture(final int newWidth, final int newHeight, final int newMipLevel) {
67
		LOGGER.info("Created: {}x{}x{} {}-atlas", newWidth, newHeight, newMipLevel, this.location);
68
		GpuDevice device = RenderSystem.getDevice();
69
		this.releaseTextures();
70
		this.texture = device.createTexture(this.location::toString, 15, GpuFormat.RGBA8_UNORM, newWidth, newHeight, 1, newMipLevel + 1);
71
		this.textureView = device.createTextureView(this.texture);
72
		this.width = newWidth;
73
		this.height = newHeight;
74
		this.maxMipLevel = newMipLevel;
75
		this.mipLevelCount = newMipLevel + 1;
76
		this.mipViews = new GpuTextureView[this.mipLevelCount];
77
78
		for (int level = 0; level <= this.maxMipLevel; level++) {
79
			this.mipViews[level] = device.createTextureView(this.texture, level, 1);
80
		}
81
	}
82
83
	public void upload(final SpriteLoader.Preparations preparations) {
84
		this.createTexture(preparations.width(), preparations.height(), preparations.mipLevel());
85
		this.clearTextureData();
86
		this.sampler = RenderSystem.getSamplerCache().getClampToEdge(FilterMode.NEAREST);
87
		this.texturesByName = Map.copyOf(preparations.regions());
88
		this.missingSprite = this.texturesByName.get(MissingTextureAtlasSprite.getLocation());
89
		if (this.missingSprite == null) {
90
			throw new IllegalStateException("Atlas '" + this.location + "' (" + this.texturesByName.size() + " sprites) has no missing texture sprite");
91
		}
92
93
		Builder<TextureAtlasSprite> spritesBuilder = ImmutableList.builder();
94
		int animatedSpriteCount = 0;
95
96
		for (TextureAtlasSprite sprite : preparations.regions().values()) {
97
			spritesBuilder.add(sprite);
98
			if (sprite.isAnimated()) {
99
				animatedSpriteCount++;
100
			}
101
		}
102
103
		this.sprites = spritesBuilder.build();
104
		if (animatedSpriteCount > 0) {
105
			Builder<SpriteContents.AnimationState> animationStates = ImmutableList.builder();
106
			int spriteUboSize = Mth.roundToward(SpriteContents.UBO_SIZE, RenderSystem.getDevice().getDeviceInfo().limits().minUniformOffsetAlignment());
107
			int uboBlockSize = spriteUboSize * this.mipLevelCount;
108
			ByteBuffer spriteUboBuffer = MemoryUtil.memAlloc(animatedSpriteCount * uboBlockSize);
109
			int animationIndex = 0;
110
111
			for (TextureAtlasSprite sprite : this.sprites) {
112
				if (sprite.isAnimated()) {
113
					sprite.uploadSpriteUbo(spriteUboBuffer, animationIndex * uboBlockSize, this.maxMipLevel, this.width, this.height, spriteUboSize);
114
					animationIndex++;
115
				}
116
			}
117
118
			GpuBuffer spriteUbos = RenderSystem.getDevice().createBuffer(() -> this.location + " sprite UBOs", 128, spriteUboBuffer);
119
			animationIndex = 0;
120
121
			for (TextureAtlasSprite sprite : this.sprites) {
122
				if (sprite.isAnimated()) {
123
					SpriteContents.AnimationState animationState = sprite.createAnimationState(spriteUbos.slice(animationIndex * uboBlockSize, uboBlockSize), spriteUboSize);
124
					animationIndex++;
125
					if (animationState != null) {
126
						animationStates.add(animationState);
127
					}
128
				}
129
			}
130
131
			this.spriteUbos = spriteUbos;
132
			this.animatedTexturesStates = animationStates.build();
133
			MemoryUtil.memFree(spriteUboBuffer);
134
		}
135
136
		this.uploadInitialContents();
137
		if (SharedConstants.DEBUG_DUMP_TEXTURE_ATLAS) {
138
			Path dumpDir = TextureUtil.getDebugTexturePath();
139
140
			try {
141
				Files.createDirectories(dumpDir);
142
				this.dumpContents(this.location, dumpDir);
143
			} catch (Exception e) {
144
				LOGGER.warn("Failed to dump atlas contents to {}", dumpDir);
145
			}
146
		}
147
	}
148
149
	private void uploadInitialContents() {
150
		GpuDevice device = RenderSystem.getDevice();
151
		int spriteUboSize = Mth.roundToward(SpriteContents.UBO_SIZE, device.getDeviceInfo().limits().minUniformOffsetAlignment());
152
		int uboBlockSize = spriteUboSize * this.mipLevelCount;
153
		GpuSampler sampler = RenderSystem.getSamplerCache().getClampToEdge(FilterMode.NEAREST, true);
154
		List<TextureAtlasSprite> staticSprites = this.sprites.stream().filter(s -> !s.isAnimated()).toList();
155
		List<GpuTextureView[]> scratchTextures = new ArrayList<>();
156
		ByteBuffer buffer = MemoryUtil.memAlloc(staticSprites.size() * uboBlockSize);
157
158
		for (int i = 0; i < staticSprites.size(); i++) {
159
			TextureAtlasSprite sprite = staticSprites.get(i);
160
			sprite.uploadSpriteUbo(buffer, i * uboBlockSize, this.maxMipLevel, this.width, this.height, spriteUboSize);
161
			GpuTexture scratchTexture = device.createTexture(
162
				() -> sprite.contents().name().toString(), 5, GpuFormat.RGBA8_UNORM, sprite.contents().width(), sprite.contents().height(), 1, this.mipLevelCount
163
			);
164
			GpuTextureView[] views = new GpuTextureView[this.mipLevelCount];
165
166
			for (int level = 0; level <= this.maxMipLevel; level++) {
167
				sprite.uploadFirstFrame(scratchTexture, level);
168
				views[level] = device.createTextureView(scratchTexture);
169
			}
170
171
			scratchTextures.add(views);
172
		}
173
174
		try (GpuBuffer ubo = device.createBuffer(() -> "SpriteAnimationInfo", 128, buffer)) {
175
			for (int level = 0; level < this.mipLevelCount; level++) {
176
				try (RenderPass renderPass = RenderSystem.getDevice()
177
						.createCommandEncoder()
178
						.createRenderPass(() -> "Animate " + this.location, this.mipViews[level], Optional.empty())) {
179
					RenderSystem.bindDefaultUniforms(renderPass);
180
					renderPass.setPipeline(RenderSystem.getCompiledPipeline(RenderPipelines.ANIMATE_SPRITE_BLIT));
181
182
					for (int i = 0; i < staticSprites.size(); i++) {
183
						renderPass.setUniform("Sprite", scratchTextures.get(i)[level], sampler);
184
						renderPass.setUniform("SpriteAnimationInfo", ubo.slice(i * uboBlockSize + level * spriteUboSize, SpriteContents.UBO_SIZE));
185
						renderPass.draw(6, 1, 0, 0);
186
					}
187
				}
188
			}
189
		}
190
191
		for (GpuTextureView[] views : scratchTextures) {
192
			for (GpuTextureView view : views) {
193
				view.close();
194
				view.texture().close();
195
			}
196
		}
197
198
		MemoryUtil.memFree(buffer);
199
		this.uploadAnimationFrames();
200
	}
201
202
	@Override
203
	public void dumpContents(final Identifier selfId, final Path dir) throws IOException {
204
		String outputId = selfId.toDebugFileName();
205
		TextureUtil.writeAsPNG(dir, outputId, this.getTexture(), this.maxMipLevel, argb -> argb);
206
		dumpSpriteNames(dir, outputId, this.texturesByName);
207
	}
208
209
	private static void dumpSpriteNames(final Path dir, final String outputId, final Map<Identifier, TextureAtlasSprite> regions) {
210
		Path outputPath = dir.resolve(outputId + ".txt");
211
212
		try (Writer output = Files.newBufferedWriter(outputPath)) {
213
			for (Entry<Identifier, TextureAtlasSprite> e : regions.entrySet().stream().sorted(Entry.comparingByKey()).toList()) {
214
				TextureAtlasSprite value = e.getValue();
215
				output.write(
216
					String.format(Locale.ROOT, "%s\tx=%d\ty=%d\tw=%d\th=%d%n", e.getKey(), value.getX(), value.getY(), value.contents().width(), value.contents().height())
217
				);
218
			}
219
		} catch (IOException e) {
220
			LOGGER.warn("Failed to write file {}", outputPath, e);
221
		}
222
	}
223
224
	public void cycleAnimationFrames() {
225
		if (this.texture != null) {
226
			for (SpriteContents.AnimationState animationState : this.animatedTexturesStates) {
227
				animationState.tick();
228
			}
229
230
			this.uploadAnimationFrames();
231
		}
232
	}
233
234
	private void uploadAnimationFrames() {
235
		if (this.animatedTexturesStates.stream().anyMatch(SpriteContents.AnimationState::needsToDraw)) {
236
			for (int level = 0; level <= this.maxMipLevel; level++) {
237
				try (RenderPass renderPass = RenderSystem.getDevice()
238
						.createCommandEncoder()
239
						.createRenderPass(() -> "Animate " + this.location, this.mipViews[level], Optional.empty())) {
240
					RenderSystem.bindDefaultUniforms(renderPass);
241
242
					for (SpriteContents.AnimationState animationState : this.animatedTexturesStates) {
243
						if (animationState.needsToDraw()) {
244
							animationState.drawToAtlas(renderPass, animationState.getDrawUbo(level));
245
						}
246
					}
247
				}
248
			}
249
		}
250
	}
251
252
	@Override
253
	public void tick() {
254
		this.cycleAnimationFrames();
255
	}
256
257
	public TextureAtlasSprite getSprite(final Identifier location) {
258
		TextureAtlasSprite result = this.texturesByName.getOrDefault(location, this.missingSprite);
259
		if (result == null) {
260
			throw new IllegalStateException("Tried to lookup sprite, but atlas is not initialized");
261
		} else {
262
			return result;
263
		}
264
	}
265
266
	public TextureAtlasSprite missingSprite() {
267
		return Objects.requireNonNull(this.missingSprite, "Atlas not initialized");
268
	}
269
270
	public void clearTextureData() {
271
		this.sprites.forEach(TextureAtlasSprite::close);
272
		this.sprites = List.of();
273
		this.animatedTexturesStates.forEach(SpriteContents.AnimationState::close);
274
		this.animatedTexturesStates = List.of();
275
		this.texturesByName = Map.of();
276
		this.missingSprite = null;
277
		if (this.spriteUbos != null) {
278
			this.spriteUbos.close();
279
			this.spriteUbos = null;
280
		}
281
	}
282
283
	@Override
284
	protected void releaseTextures() {
285
		super.releaseTextures();
286
287
		for (GpuTextureView view : this.mipViews) {
288
			view.close();
289
		}
290
	}
291
292
	@Override
293
	public void close() {
294
		this.clearTextureData();
295
		super.close();
296
	}
297
298
	public Identifier location() {
299
		return this.location;
300
	}
301
302
	public int maxSupportedTextureSize() {
303
		return this.maxSupportedTextureSize;
304
	}
305
306
	int getWidth() {
307
		return this.width;
308
	}
309
310
	int getHeight() {
311
		return this.height;
312
	}
313
}
314

Decompiled Minecraft 26.3 source of TextureAtlas (net/minecraft/client/renderer/texture/TextureAtlas.java) with Mojang official mappings, stored verbatim on the site.