| 1 | package net.minecraft.client.renderer;
|
| 2 |
|
| 3 | import com.google.common.collect.Queues;
|
| 4 | import com.mojang.logging.LogUtils;
|
| 5 | import java.util.ArrayList;
|
| 6 | import java.util.List;
|
| 7 | import java.util.concurrent.ArrayBlockingQueue;
|
| 8 | import net.fabricmc.api.EnvType;
|
| 9 | import net.fabricmc.api.Environment;
|
| 10 | import org.jspecify.annotations.Nullable;
|
| 11 | import org.slf4j.Logger;
|
| 12 |
|
| 13 | @Environment(EnvType.CLIENT)
|
| 14 | public class SectionBufferBuilderPool implements AutoCloseable {
|
| 15 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 16 | private final ArrayBlockingQueue<SectionBufferBuilderPack> freeBuffers;
|
| 17 |
|
| 18 | private SectionBufferBuilderPool(final List<SectionBufferBuilderPack> buffers) {
|
| 19 | this.freeBuffers = Queues.newArrayBlockingQueue(buffers.size());
|
| 20 | this.freeBuffers.addAll(buffers);
|
| 21 | }
|
| 22 |
|
| 23 | public static SectionBufferBuilderPool allocate(final int maxWorkers) {
|
| 24 | int maxBuffers = Math.max(1, (int)(Runtime.getRuntime().maxMemory() * 0.3) / SectionBufferBuilderPack.TOTAL_BUFFERS_SIZE);
|
| 25 | int targetBufferCount = Math.max(1, Math.min(maxWorkers, maxBuffers));
|
| 26 | List<SectionBufferBuilderPack> buffers = new ArrayList<>(targetBufferCount);
|
| 27 |
|
| 28 | try {
|
| 29 | for (int i = 0; i < targetBufferCount; i++) {
|
| 30 | buffers.add(new SectionBufferBuilderPack());
|
| 31 | }
|
| 32 | } catch (OutOfMemoryError e) {
|
| 33 | LOGGER.warn("Allocated only {}/{} buffers", buffers.size(), targetBufferCount);
|
| 34 | int buffersToDrop = Math.min(buffers.size() * 2 / 3, buffers.size() - 1);
|
| 35 |
|
| 36 | for (int i = 0; i < buffersToDrop; i++) {
|
| 37 | buffers.remove(buffers.size() - 1).close();
|
| 38 | }
|
| 39 | }
|
| 40 |
|
| 41 | return new SectionBufferBuilderPool(buffers);
|
| 42 | }
|
| 43 |
|
| 44 | public @Nullable SectionBufferBuilderPack acquire() {
|
| 45 | return this.freeBuffers.poll();
|
| 46 | }
|
| 47 |
|
| 48 | public void release(final SectionBufferBuilderPack buffer) {
|
| 49 | this.freeBuffers.offer(buffer);
|
| 50 | }
|
| 51 |
|
| 52 | public boolean isEmpty() {
|
| 53 | return this.freeBuffers.isEmpty();
|
| 54 | }
|
| 55 |
|
| 56 | public int getFreeBufferCount() {
|
| 57 | return this.freeBuffers.size();
|
| 58 | }
|
| 59 |
|
| 60 | @Override
|
| 61 | public void close() {
|
| 62 | this.freeBuffers.forEach(SectionBufferBuilderPack::close);
|
| 63 | this.freeBuffers.clear();
|
| 64 | }
|
| 65 | }
|
| 66 |
|