SectionRenderDispatcher .java

net.minecraft.client.renderer.chunk.SectionRenderDispatcher (class): members: NEARBY_SECTION_DISTANCE_IN_BLOCKS, uploadTerrainBuffersToGpu, RenderSection.

net.minecraft.client.renderer.chunkclass415 linesclient14.5 KB

API Surface (26)

void setCompiler(final SectionCompiler sectionCompiler)
void setCameraPosition(final Vec3 cameraPosition)
void lock()
void unlock()
void uploadTerrainBuffersToGpu()
void clearCompileQueue()
boolean isQueueEmpty()
void dispose()
String getStats()
int getCompileQueueSize()
int getFreeBufferCount()
float getVisibility(final long now, final long fadeDuration)
AABB getBoundingBox()
void setSectionNode(final long sectionNode)
SectionMesh getSectionMesh()
void reset()
BlockPos getRenderOrigin()
long getSectionNode()
long getNeighborSectionNode(final Direction direction)
void resortTransparency()
boolean hasTranslucentGeometry()
boolean transparencyResortingScheduled()
void compileAsync(final RenderSectionRegion region)
void compileSync(final RenderSectionRegion region)
void updateUploadTime()
record RenderSectionBufferSlice(GpuBuffer vertexBuffer, long vertexBufferOffset, @Nullable GpuBuffer indexBuffer, long indexBufferOffset)

Fields & Constants (13)

NEARBY_SECTION_DISTANCE_IN_BLOCKS
queue
fixedBuffers
bufferPool
closed
executor
onSectionMeshUpdate
cameraPosition
sectionCompiler
stagingBuffer
chunkUberBuffers
copyLock
renderBuffers

String literals (2)

"Chunk"
"Batching sections"

Full Source

SectionRenderDispatcher.java415 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.client.renderer.chunk;
2
3
import com.mojang.blaze3d.systems.RenderSystem;
4
import com.mojang.blaze3d.vertex.StagingBuffer;
5
import com.mojang.blaze3d.vertex.TlsfAllocator;
6
import com.mojang.blaze3d.vertex.UberGpuBuffer;
7
import com.mojang.blaze3d.vertex.VertexSorting;
8
import com.mojang.renderpearl.api.buffers.GpuBuffer;
9
import com.mojang.renderpearl.api.device.GpuDevice;
10
import com.mojang.renderpearl.api.vertex.VertexFormat;
11
import java.nio.ByteBuffer;
12
import java.util.Locale;
13
import java.util.Map;
14
import java.util.Objects;
15
import java.util.concurrent.atomic.AtomicReference;
16
import java.util.concurrent.locks.ReentrantLock;
17
import java.util.function.Consumer;
18
import net.fabricmc.api.EnvType;
19
import net.fabricmc.api.Environment;
20
import net.minecraft.CrashReport;
21
import net.minecraft.TracingExecutor;
22
import net.minecraft.client.Minecraft;
23
import net.minecraft.client.RotatingSectionStorage;
24
import net.minecraft.client.renderer.RenderBuffers;
25
import net.minecraft.client.renderer.SectionBufferBuilderPack;
26
import net.minecraft.client.renderer.SectionBufferBuilderPool;
27
import net.minecraft.client.renderer.chunk.SectionRenderDispatcher.RenderSection.CompileTask;
28
import net.minecraft.client.renderer.chunk.SectionRenderDispatcher.RenderSection.ResortTransparencyTask;
29
import net.minecraft.client.renderer.chunk.SectionRenderDispatcher.RenderSection.SectionTask;
30
import net.minecraft.client.renderer.chunk.SectionRenderDispatcher.RenderSection.SectionTask.SectionTaskResult;
31
import net.minecraft.core.BlockPos;
32
import net.minecraft.core.Direction;
33
import net.minecraft.core.SectionPos;
34
import net.minecraft.core.BlockPos.MutableBlockPos;
35
import net.minecraft.util.Util;
36
import net.minecraft.util.VisibleForDebug;
37
import net.minecraft.world.phys.AABB;
38
import net.minecraft.world.phys.Vec3;
39
import org.jspecify.annotations.Nullable;
40
41
@Environment(EnvType.CLIENT)
42
public class SectionRenderDispatcher {
43
	public static final int NEARBY_SECTION_DISTANCE_IN_BLOCKS = 32;
44
	private final SectionTaskDynamicQueue queue = new SectionTaskDynamicQueue();
45
	private final SectionBufferBuilderPack fixedBuffers;
46
	private final SectionBufferBuilderPool bufferPool;
47
	private volatile boolean closed;
48
	private final TracingExecutor executor;
49
	private final Consumer<SectionRenderDispatcher.RenderSection> onSectionMeshUpdate;
50
	private final AtomicReference<Vec3> cameraPosition = new AtomicReference<>(Vec3.ZERO);
51
	private volatile SectionCompiler sectionCompiler;
52
	private final StagingBuffer stagingBuffer;
53
	private final Map<ChunkSectionLayer, SectionRenderDispatcher.SectionUberBuffers> chunkUberBuffers;
54
	private final ReentrantLock copyLock = new ReentrantLock();
55
56
	public SectionRenderDispatcher(
57
		final TracingExecutor executor,
58
		final RenderBuffers renderBuffers,
59
		final SectionCompiler sectionCompiler,
60
		final Consumer<SectionRenderDispatcher.RenderSection> onSectionMeshUpdate
61
	) {
62
		this.onSectionMeshUpdate = onSectionMeshUpdate;
63
		this.fixedBuffers = renderBuffers.fixedBufferPack();
64
		this.bufferPool = renderBuffers.sectionBufferPool();
65
		this.executor = executor;
66
		this.sectionCompiler = sectionCompiler;
67
		int vertexBufferHeapSize = 134217728;
68
		int indexBufferHeapSize = 33554432;
69
		int stagingBufferSize = 102760448;
70
		GpuDevice gpuDevice = RenderSystem.getDevice();
71
		this.stagingBuffer = StagingBuffer.create("Chunk", gpuDevice, 102760448);
72
		this.chunkUberBuffers = Util.makeEnumMap(ChunkSectionLayer.class, layer -> {
73
			VertexFormat vertexFormat = layer.pipeline(false).getVertexFormatBinding(0);
74
			UberGpuBuffer<SectionMesh> vertexUberBuffer = new UberGpuBuffer<>(layer.label(), 32, 134217728, vertexFormat.getVertexSize(), this.stagingBuffer);
75
			UberGpuBuffer<SectionMesh> indexUberBuffer = new UberGpuBuffer<>(layer.label(), 64, 33554432, 8, this.stagingBuffer);
76
			return new SectionRenderDispatcher.SectionUberBuffers(vertexUberBuffer, indexUberBuffer);
77
		});
78
	}
79
80
	public void setCompiler(final SectionCompiler sectionCompiler) {
81
		this.sectionCompiler = sectionCompiler;
82
	}
83
84
	private void runTask() {
85
		if (!this.closed) {
86
			SectionTask task = this.queue.poll(this.cameraPosition.get());
87
			if (task != null && !task.isCompleted.get() && !task.isCancelled.get()) {
88
				try {
89
					SectionBufferBuilderPack buffer = Objects.requireNonNull(this.bufferPool.acquire());
90
					SectionTaskResult result = task.doTask(buffer);
91
					task.isCompleted.set(true);
92
					if (result == SectionTaskResult.SUCCESSFUL) {
93
						buffer.clearAll();
94
					} else {
95
						buffer.discardAll();
96
					}
97
98
					this.bufferPool.release(buffer);
99
					this.executor.execute(this::runTask);
100
				} catch (NullPointerException e) {
101
					this.queue.add(task);
102
				} catch (Exception e) {
103
					Minecraft.getInstance().delayCrash(CrashReport.forThrowable(e, "Batching sections"));
104
				}
105
			}
106
		}
107
	}
108
109
	public void setCameraPosition(final Vec3 cameraPosition) {
110
		this.cameraPosition.set(cameraPosition);
111
	}
112
113
	public SectionRenderDispatcher.@Nullable RenderSectionBufferSlice getRenderSectionSlice(final SectionMesh sectionMesh, final ChunkSectionLayer layer) {
114
		SectionRenderDispatcher.SectionUberBuffers uberBuffers = this.chunkUberBuffers.get(layer);
115
		TlsfAllocator.Allocation vertexSlice = uberBuffers.vertexBuffer.getAllocation(sectionMesh);
116
		if (vertexSlice == null) {
117
			return null;
118
		}
119
120
		long vertexBufferOffset = vertexSlice.getOffsetFromHeap();
121
		TlsfAllocator.Allocation indexSlice = uberBuffers.indexBuffer.getAllocation(sectionMesh);
122
		long indexBufferOffset = 0L;
123
		GpuBuffer indexBuffer = null;
124
		if (indexSlice != null) {
125
			indexBufferOffset = indexSlice.getOffsetFromHeap();
126
			indexBuffer = uberBuffers.indexBuffer.getGpuBuffer(indexSlice);
127
		}
128
129
		return new SectionRenderDispatcher.RenderSectionBufferSlice(
130
			uberBuffers.vertexBuffer.getGpuBuffer(vertexSlice), vertexBufferOffset, indexBuffer, indexBufferOffset
131
		);
132
	}
133
134
	public void lock() {
135
		this.copyLock.lock();
136
	}
137
138
	public void unlock() {
139
		this.copyLock.unlock();
140
	}
141
142
	public void uploadTerrainBuffersToGpu() {
143
		GpuDevice device = RenderSystem.getDevice();
144
145
		try (StagingBuffer.Uploader uploader = this.stagingBuffer.startUploading(device.createCommandEncoder())) {
146
			for (SectionRenderDispatcher.SectionUberBuffers buffers : this.chunkUberBuffers.values()) {
147
				boolean performedBufferResize = buffers.vertexBuffer.uploadStagedAllocations(device, uploader);
148
				buffers.indexBuffer.uploadStagedAllocations(device, uploader);
149
				if (performedBufferResize) {
150
					break;
151
				}
152
			}
153
		}
154
	}
155
156
	private void schedule(final SectionTask task) {
157
		if (!this.closed) {
158
			this.queue.add(task);
159
			this.executor.execute(this::runTask);
160
		}
161
	}
162
163
	public void clearCompileQueue() {
164
		this.queue.clear();
165
	}
166
167
	public boolean isQueueEmpty() {
168
		return this.queue.size() == 0;
169
	}
170
171
	public void dispose() {
172
		this.closed = true;
173
		this.clearCompileQueue();
174
		this.copyLock.lock();
175
176
		try {
177
			for (SectionRenderDispatcher.SectionUberBuffers buffers : this.chunkUberBuffers.values()) {
178
				buffers.vertexBuffer.close();
179
				buffers.indexBuffer.close();
180
			}
181
182
			this.stagingBuffer.close();
183
		} finally {
184
			this.copyLock.unlock();
185
		}
186
	}
187
188
	@VisibleForDebug
189
	public String getStats() {
190
		return String.format(Locale.ROOT, "pC: %03d, aB: %02d", this.queue.size(), this.bufferPool.getFreeBufferCount());
191
	}
192
193
	@VisibleForDebug
194
	public int getCompileQueueSize() {
195
		return this.queue.size();
196
	}
197
198
	@VisibleForDebug
199
	public int getFreeBufferCount() {
200
		return this.bufferPool.getFreeBufferCount();
201
	}
202
203
	@Environment(EnvType.CLIENT)
204
	public class RenderSection implements RotatingSectionStorage.Value {
205
		public final int index;
206
		public final AtomicReference<SectionMesh> sectionMesh = new AtomicReference<>(CompiledSectionMesh.UNCOMPILED);
207
		private CompileTask/* @Nullable */ lastCompileTask;
208
		private ResortTransparencyTask/* @Nullable */ lastResortTransparencyTask;
209
		private AABB bb;
210
		private volatile long sectionNode = SectionPos.asLong(-1, -1, -1);
211
		private final MutableBlockPos renderOrigin = new MutableBlockPos(-1, -1, -1);
212
		private long uploadedTime;
213
214
		public RenderSection(final int index, final long sectionNode) {
215
			this.index = index;
216
			this.setSectionNode(sectionNode);
217
		}
218
219
		public float getVisibility(final long now, final long fadeDuration) {
220
			long elapsed = now - this.uploadedTime;
221
			return elapsed >= fadeDuration ? 1.0F : (float)elapsed / (float)fadeDuration;
222
		}
223
224
		public AABB getBoundingBox() {
225
			return this.bb;
226
		}
227
228
		@Override
229
		public void setSectionNode(final long sectionNode) {
230
			this.reset();
231
			this.sectionNode = sectionNode;
232
			int x = SectionPos.sectionToBlockCoord(SectionPos.x(sectionNode));
233
			int y = SectionPos.sectionToBlockCoord(SectionPos.y(sectionNode));
234
			int z = SectionPos.sectionToBlockCoord(SectionPos.z(sectionNode));
235
			this.renderOrigin.set(x, y, z);
236
			this.bb = new AABB(x, y, z, x + 16, y + 16, z + 16);
237
		}
238
239
		public SectionMesh getSectionMesh() {
240
			return this.sectionMesh.get();
241
		}
242
243
		public void reset() {
244
			this.cancelTasks();
245
			SectionMesh mesh = this.sectionMesh.getAndSet(CompiledSectionMesh.UNCOMPILED);
246
			SectionRenderDispatcher.this.copyLock.lock();
247
248
			try {
249
				this.releaseSectionMesh(mesh);
250
			} finally {
251
				SectionRenderDispatcher.this.copyLock.unlock();
252
			}
253
254
			this.uploadedTime = 0L;
255
		}
256
257
		public BlockPos getRenderOrigin() {
258
			return this.renderOrigin;
259
		}
260
261
		@Override
262
		public long getSectionNode() {
263
			return this.sectionNode;
264
		}
265
266
		public long getNeighborSectionNode(final Direction direction) {
267
			return SectionPos.offset(this.sectionNode, direction);
268
		}
269
270
		public void resortTransparency() {
271
			if (this.getSectionMesh() instanceof CompiledSectionMesh mesh) {
272
				this.lastResortTransparencyTask = new ResortTransparencyTask(this, mesh);
273
				SectionRenderDispatcher.this.schedule(this.lastResortTransparencyTask);
274
			}
275
		}
276
277
		public boolean hasTranslucentGeometry() {
278
			return this.getSectionMesh().hasTranslucentGeometry();
279
		}
280
281
		public boolean transparencyResortingScheduled() {
282
			return this.lastResortTransparencyTask != null && !this.lastResortTransparencyTask.isCompleted.get();
283
		}
284
285
		private void cancelTasks() {
286
			if (this.lastCompileTask != null) {
287
				this.lastCompileTask.cancel();
288
				this.lastCompileTask = null;
289
			}
290
291
			if (this.lastResortTransparencyTask != null) {
292
				this.lastResortTransparencyTask.cancel();
293
				this.lastResortTransparencyTask = null;
294
			}
295
		}
296
297
		private SectionTask createCompileTask(final RenderSectionRegion region) {
298
			this.cancelTasks();
299
			boolean isRecompile = this.sectionMesh.get() != CompiledSectionMesh.UNCOMPILED;
300
			this.lastCompileTask = new CompileTask(this, region, isRecompile);
301
			return this.lastCompileTask;
302
		}
303
304
		public void compileAsync(final RenderSectionRegion region) {
305
			SectionTask task = this.createCompileTask(region);
306
			SectionRenderDispatcher.this.schedule(task);
307
		}
308
309
		public void compileSync(final RenderSectionRegion region) {
310
			SectionTask task = this.createCompileTask(region);
311
			task.doTask(SectionRenderDispatcher.this.fixedBuffers);
312
		}
313
314
		private SectionMesh setSectionMesh(final SectionMesh sectionMesh) {
315
			SectionMesh oldMesh = this.sectionMesh.getAndSet(sectionMesh);
316
			SectionRenderDispatcher.this.onSectionMeshUpdate.accept(this);
317
			this.updateUploadTime();
318
			return oldMesh;
319
		}
320
321
		public void updateUploadTime() {
322
			if (this.uploadedTime == 0L) {
323
				this.uploadedTime = Util.getMillis();
324
			}
325
		}
326
327
		private void releaseSectionMesh(final SectionMesh oldMesh) {
328
			oldMesh.close();
329
330
			for (SectionRenderDispatcher.SectionUberBuffers buffers : SectionRenderDispatcher.this.chunkUberBuffers.values()) {
331
				buffers.vertexBuffer.removeAllocation(oldMesh);
332
				buffers.indexBuffer.removeAllocation(oldMesh);
333
			}
334
		}
335
336
		private VertexSorting createVertexSorting(final SectionPos sectionPos, final Vec3 cameraPos) {
337
			return VertexSorting.byDistance(
338
				(float)(cameraPos.x - sectionPos.minBlockX()), (float)(cameraPos.y - sectionPos.minBlockY()), (float)(cameraPos.z - sectionPos.minBlockZ())
339
			);
340
		}
341
342
		private void checkSectionMesh(final CompiledSectionMesh compiledSectionMesh) {
343
			boolean allBuffersUpdated = true;
344
345
			for (ChunkSectionLayer layer : ChunkSectionLayer.values()) {
346
				SectionMesh.SectionDraw draw = compiledSectionMesh.getSectionDraw(layer);
347
				if (draw != null) {
348
					allBuffersUpdated &= compiledSectionMesh.isIndexBufferUploaded(layer);
349
					allBuffersUpdated &= compiledSectionMesh.isVertexBufferUploaded(layer);
350
				}
351
			}
352
353
			if (allBuffersUpdated && this.sectionMesh.get() != compiledSectionMesh) {
354
				SectionMesh oldMesh = this.setSectionMesh(compiledSectionMesh);
355
				this.releaseSectionMesh(oldMesh);
356
			}
357
		}
358
359
		private void vertexBufferUploadCallback(final CompiledSectionMesh sectionMesh, final ChunkSectionLayer layer) {
360
			sectionMesh.setVertexBufferUploaded(layer);
361
			this.checkSectionMesh(sectionMesh);
362
		}
363
364
		private void indexBufferUploadCallback(final CompiledSectionMesh sectionMesh, final ChunkSectionLayer layer, final boolean sortedIndexBuffer) {
365
			sectionMesh.setIndexBufferUploaded(layer);
366
			if (!sortedIndexBuffer) {
367
				this.checkSectionMesh(sectionMesh);
368
			}
369
		}
370
371
		private boolean addSectionBuffersToUberBuffer(
372
			final ChunkSectionLayer layer, final CompiledSectionMesh key, final @Nullable ByteBuffer vertexBuffer, final @Nullable ByteBuffer indexBuffer
373
		) {
374
			boolean success = true;
375
			SectionRenderDispatcher.this.copyLock.lock();
376
377
			try {
378
				SectionMesh.SectionDraw draw = key.getSectionDraw(layer);
379
				if (draw != null) {
380
					SectionRenderDispatcher.SectionUberBuffers sectionBuffers = SectionRenderDispatcher.this.chunkUberBuffers.get(layer);
381
					assert sectionBuffers != null;
382
					if (vertexBuffer != null) {
383
						UberGpuBuffer.UploadCallback<CompiledSectionMesh> callback = mesh -> this.vertexBufferUploadCallback(mesh, layer);
384
						success &= sectionBuffers.vertexBuffer.addAllocation(key, callback, vertexBuffer);
385
					}
386
387
					if (indexBuffer != null) {
388
						boolean sortedIndexBuffer = vertexBuffer == null;
389
						UberGpuBuffer.UploadCallback<CompiledSectionMesh> callback = mesh -> this.indexBufferUploadCallback(mesh, layer, sortedIndexBuffer);
390
						success &= sectionBuffers.indexBuffer.addAllocation(key, callback, indexBuffer);
391
					} else {
392
						key.setIndexBufferUploaded(layer);
393
					}
394
				}
395
396
				if (!success && RenderSystem.isOnRenderThread()) {
397
					SectionRenderDispatcher.this.uploadTerrainBuffersToGpu();
398
				}
399
			} finally {
400
				SectionRenderDispatcher.this.copyLock.unlock();
401
			}
402
403
			return success;
404
		}
405
	}
406
407
	@Environment(EnvType.CLIENT)
408
	public record RenderSectionBufferSlice(GpuBuffer vertexBuffer, long vertexBufferOffset, @Nullable GpuBuffer indexBuffer, long indexBufferOffset) {
409
	}
410
411
	@Environment(EnvType.CLIENT)
412
	private record SectionUberBuffers(UberGpuBuffer<SectionMesh> vertexBuffer, UberGpuBuffer<SectionMesh> indexBuffer) {
413
	}
414
}
415

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