| 1 | package com.mojang.renderpearl.backend.vulkan;
|
| 2 |
|
| 3 | import com.mojang.renderpearl.util.UncheckedAutoCloseable;
|
| 4 | import it.unimi.dsi.fastutil.objects.ReferenceArrayList;
|
| 5 | import it.unimi.dsi.fastutil.objects.ReferenceList;
|
| 6 | import net.fabricmc.api.EnvType;
|
| 7 | import net.fabricmc.api.Environment;
|
| 8 |
|
| 9 | @Environment(EnvType.CLIENT)
|
| 10 | public class DestructionQueue<T> implements UncheckedAutoCloseable {
|
| 11 | private final DestructionQueue.Destroyer<T> destroyCallback;
|
| 12 | private final ReferenceList<ReferenceArrayList<T>> destructionQueues;
|
| 13 | private int currentDestructionQueueIndex = 0;
|
| 14 |
|
| 15 | public DestructionQueue(final int internalQueueCount, final DestructionQueue.Destroyer<T> destroyCallback) {
|
| 16 | this.destroyCallback = destroyCallback;
|
| 17 | this.destructionQueues = new ReferenceArrayList<>(internalQueueCount);
|
| 18 |
|
| 19 | for (int i = 0; i < internalQueueCount; i++) {
|
| 20 | this.destructionQueues.add(new ReferenceArrayList<>());
|
| 21 | }
|
| 22 | }
|
| 23 |
|
| 24 | @Override
|
| 25 | public void close() {
|
| 26 | for (int i = 0; i < this.destructionQueues.size(); i++) {
|
| 27 | if (this.rotate()) {
|
| 28 | i = 0;
|
| 29 | }
|
| 30 | }
|
| 31 | }
|
| 32 |
|
| 33 | public boolean rotate() {
|
| 34 | this.currentDestructionQueueIndex++;
|
| 35 | this.currentDestructionQueueIndex = this.currentDestructionQueueIndex % this.destructionQueues.size();
|
| 36 | ReferenceArrayList<T> currentQueue = this.destructionQueues.set(this.currentDestructionQueueIndex, new ReferenceArrayList<>());
|
| 37 | if (currentQueue.isEmpty()) {
|
| 38 | return false;
|
| 39 | }
|
| 40 |
|
| 41 | this.destroyCallback.begin(currentQueue.size());
|
| 42 | currentQueue.forEach(this.destroyCallback::destroy);
|
| 43 | this.destroyCallback.end();
|
| 44 | return true;
|
| 45 | }
|
| 46 |
|
| 47 | public void add(final T t) {
|
| 48 | ReferenceArrayList<T> currentQueue = this.destructionQueues.get(this.currentDestructionQueueIndex);
|
| 49 | currentQueue.add(t);
|
| 50 | }
|
| 51 |
|
| 52 | @Environment(EnvType.CLIENT)
|
| 53 | public interface Destroyer<T> {
|
| 54 | default void begin(final int count) {
|
| 55 | }
|
| 56 |
|
| 57 | void destroy(T t);
|
| 58 |
|
| 59 | default void end() {
|
| 60 | }
|
| 61 | }
|
| 62 | }
|
| 63 |
|