| 1 | package com.mojang.blaze3d.pipeline;
|
| 2 |
|
| 3 | import com.mojang.renderpearl.api.device.GpuDevice;
|
| 4 | import com.mojang.renderpearl.api.pipeline.CompiledRenderPipeline;
|
| 5 | import com.mojang.renderpearl.api.pipeline.RenderPipeline;
|
| 6 | import com.mojang.renderpearl.api.pipeline.ShaderSource;
|
| 7 | import com.mojang.renderpearl.util.UncheckedAutoCloseable;
|
| 8 | import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap;
|
| 9 | import java.util.Map;
|
| 10 | import net.fabricmc.api.EnvType;
|
| 11 | import net.fabricmc.api.Environment;
|
| 12 | import net.minecraft.util.Util;
|
| 13 | import org.jspecify.annotations.Nullable;
|
| 14 |
|
| 15 | @Environment(EnvType.CLIENT)
|
| 16 | public class PipelineCache implements AutoCloseable {
|
| 17 | private final GpuDevice device;
|
| 18 | private final ShaderSource shaderSource;
|
| 19 | private final Map<RenderPipeline, CompiledRenderPipeline> cache = new Reference2ReferenceOpenHashMap<>();
|
| 20 |
|
| 21 | public PipelineCache(final GpuDevice device, final ShaderSource shaderSource) {
|
| 22 | this.device = device;
|
| 23 | this.shaderSource = shaderSource;
|
| 24 | }
|
| 25 |
|
| 26 | public void insert(final RenderPipeline pipeline, final CompiledRenderPipeline compiled) {
|
| 27 | this.cache.put(pipeline, compiled);
|
| 28 | }
|
| 29 |
|
| 30 | public @Nullable CompiledRenderPipeline get(final RenderPipeline pipeline) {
|
| 31 | CompiledRenderPipeline cachedPipeline = this.cache.get(pipeline);
|
| 32 | if (cachedPipeline != null) {
|
| 33 | return cachedPipeline;
|
| 34 | }
|
| 35 |
|
| 36 | CompiledRenderPipeline newPipeline = this.device.compilePipeline(pipeline, this.shaderSource, Util.backgroundExecutor()).join().finishCompile();
|
| 37 | if (newPipeline == null) {
|
| 38 | return null;
|
| 39 | }
|
| 40 |
|
| 41 | this.cache.put(pipeline, newPipeline);
|
| 42 | return newPipeline;
|
| 43 | }
|
| 44 |
|
| 45 | public void clear() {
|
| 46 | this.cache.values().forEach(UncheckedAutoCloseable::close);
|
| 47 | this.cache.clear();
|
| 48 | }
|
| 49 |
|
| 50 | @Override
|
| 51 | public void close() {
|
| 52 | this.clear();
|
| 53 | this.shaderSource.close();
|
| 54 | }
|
| 55 | }
|
| 56 |
|