| 1 | package net.minecraft.client.renderer;
|
| 2 |
|
| 3 | import com.mojang.blaze3d.systems.RenderSystem;
|
| 4 | import com.mojang.renderpearl.api.buffers.GpuBuffer;
|
| 5 | import com.mojang.renderpearl.api.commands.GpuFence;
|
| 6 | import com.mojang.renderpearl.api.device.GpuDevice;
|
| 7 | import java.util.function.Supplier;
|
| 8 | import net.fabricmc.api.EnvType;
|
| 9 | import net.fabricmc.api.Environment;
|
| 10 | import org.jspecify.annotations.Nullable;
|
| 11 |
|
| 12 | @Environment(EnvType.CLIENT)
|
| 13 | public class MappableRingBuffer implements AutoCloseable {
|
| 14 | private static final int BUFFER_COUNT = 3;
|
| 15 | private final GpuBuffer[] buffers = new GpuBuffer[3];
|
| 16 | private final @Nullable GpuFence[] fences = new GpuFence[3];
|
| 17 | private final int size;
|
| 18 | private int current = 0;
|
| 19 |
|
| 20 | public MappableRingBuffer(final Supplier<String> label, final @GpuBuffer.Usage int usage, final int size) {
|
| 21 | GpuDevice device = RenderSystem.getDevice();
|
| 22 | if ((usage & 1) == 0 && (usage & 2) == 0) {
|
| 23 | throw new IllegalArgumentException("MappableRingBuffer requires at least one of USAGE_MAP_READ or USAGE_MAP_WRITE");
|
| 24 | }
|
| 25 |
|
| 26 | for (int i = 0; i < 3; i++) {
|
| 27 | int finalI = i;
|
| 28 | this.buffers[i] = device.createBuffer(() -> label.get() + " #" + finalI, usage, size);
|
| 29 | this.fences[i] = null;
|
| 30 | }
|
| 31 |
|
| 32 | this.size = size;
|
| 33 | }
|
| 34 |
|
| 35 | public int size() {
|
| 36 | return this.size;
|
| 37 | }
|
| 38 |
|
| 39 | public GpuBuffer currentBuffer() {
|
| 40 | GpuFence fence = this.fences[this.current];
|
| 41 | if (fence != null) {
|
| 42 | fence.awaitCompletion(-1L);
|
| 43 | fence.close();
|
| 44 | this.fences[this.current] = null;
|
| 45 | }
|
| 46 |
|
| 47 | return this.buffers[this.current];
|
| 48 | }
|
| 49 |
|
| 50 | public void rotate() {
|
| 51 | if (this.fences[this.current] != null) {
|
| 52 | this.fences[this.current].close();
|
| 53 | }
|
| 54 |
|
| 55 | this.fences[this.current] = RenderSystem.getDevice().createCommandEncoder().createFence();
|
| 56 | this.current = (this.current + 1) % 3;
|
| 57 | }
|
| 58 |
|
| 59 | @Override
|
| 60 | public void close() {
|
| 61 | for (int i = 0; i < 3; i++) {
|
| 62 | this.buffers[i].close();
|
| 63 | if (this.fences[i] != null) {
|
| 64 | this.fences[i].close();
|
| 65 | }
|
| 66 | }
|
| 67 | }
|
| 68 | }
|
| 69 |
|