repo_id
stringclasses
383 values
file_path
stringlengths
7
168
content
stringlengths
0
1.75M
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\data\ChunkMeshData.java
package me.jellysquid.mods.sodium.client.render.chunk.data; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import java.util.EnumMap; import java.util.Map; import me.jellysquid.mods.sodium.client.gl.buffer.VertexData; import me.jellysquid.mods.sodium.client.gl.util.BufferSlice; public class ChunkMeshData { public static final ChunkMeshData EMPTY = new ChunkMeshData(); private final EnumMap<ModelQuadFacing, BufferSlice> parts = new EnumMap<>(ModelQuadFacing.class); private VertexData vertexData; public void setVertexData(VertexData vertexData) { this.vertexData = vertexData; } public void clearSlices() { this.parts.clear(); } public void setModelSlice(ModelQuadFacing facing, BufferSlice slice) { this.parts.put(facing, slice); } public VertexData takeVertexData() { VertexData data = this.vertexData; if (data == null) { throw new NullPointerException("No pending data to upload"); } this.vertexData = null; return data; } public boolean hasVertexData() { return this.vertexData != null; } public int getVertexDataSize() { if (this.vertexData != null) { return this.vertexData.buffer.capacity(); } return 0; } public Iterable<? extends Map.Entry<ModelQuadFacing, BufferSlice>> getSlices() { return this.parts.entrySet(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\data\ChunkRenderBounds.java
package me.jellysquid.mods.sodium.client.render.chunk.data; import com.gtnewhorizons.angelica.compat.mojang.ChunkSectionPos; public class ChunkRenderBounds { public static final ChunkRenderBounds ALWAYS_FALSE = new ChunkRenderBounds(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY); public final float x1, y1, z1; public final float x2, y2, z2; public ChunkRenderBounds(float x1, float y1, float z1, float x2, float y2, float z2) { this.x1 = x1; this.y1 = y1; this.z1 = z1; this.x2 = x2; this.y2 = y2; this.z2 = z2; } public ChunkRenderBounds(ChunkSectionPos origin) { this.x1 = origin.getMinX(); this.y1 = origin.getMinY(); this.z1 = origin.getMinZ(); this.x2 = origin.getMaxX() + 1; this.y2 = origin.getMaxY() + 1; this.z2 = origin.getMaxZ() + 1; } public static class Builder { // Bit-mask of the blocks set on each axis private int x = 0, y = 0, z = 0; public void addBlock(int x, int y, int z) { // Accumulate bits on each axis for the given block position. This avoids needing to // branch multiple times trying to determine if the bounds need to grow. The min/max // value of each axis can later be extracted by counting the trailing/leading zeroes. this.x |= 1 << x; this.y |= 1 << y; this.z |= 1 << z; } public ChunkRenderBounds build(ChunkSectionPos origin) { // If no bits were set on any axis, return the default bounds if ((this.x | this.y | this.z) == 0) { return new ChunkRenderBounds(origin); } int x1 = origin.getMinX() + leftBound(this.x); int x2 = origin.getMinX() + rightBound(this.x); int y1 = origin.getMinY() + leftBound(this.y); int y2 = origin.getMinY() + rightBound(this.y); int z1 = origin.getMinZ() + leftBound(this.z); int z2 = origin.getMinZ() + rightBound(this.z); return new ChunkRenderBounds( Math.max(x1, origin.getMinX()) - 0.5f, Math.max(y1, origin.getMinY()) - 0.5f, Math.max(z1, origin.getMinZ()) - 0.5f, Math.min(x2, origin.getMaxX()) + 0.5f, Math.min(y2, origin.getMaxY()) + 0.5f, Math.min(z2, origin.getMaxZ()) + 0.5f ); } // Return the left-bound of the bit-masked axis private static int leftBound(int i) { return Integer.numberOfTrailingZeros(i); } // Return the right-bound of the bit-masked axis private static int rightBound(int i) { return 32 - Integer.numberOfLeadingZeros(i); } } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\data\ChunkRenderData.java
package me.jellysquid.mods.sodium.client.render.chunk.data; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import com.gtnewhorizons.angelica.compat.mojang.ChunkOcclusionData; import com.gtnewhorizons.angelica.mixins.interfaces.ISpriteExt; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import java.util.ArrayList; import java.util.Collection; import java.util.EnumMap; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Set; import lombok.Getter; import me.jellysquid.mods.sodium.client.gl.util.BufferSlice; import me.jellysquid.mods.sodium.client.render.chunk.passes.BlockRenderPass; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; /** * The render data for a chunk render container containing all the information about which meshes are attached, the * block entities contained by it, and any data used for occlusion testing. */ public class ChunkRenderData { public static final ChunkRenderData ABSENT = new Builder() .build(); public static final ChunkRenderData EMPTY = createEmptyData(); private Set<TileEntity> globalTileEntities; private List<TileEntity> tileEntities; private EnumMap<BlockRenderPass, ChunkMeshData> meshes; @Getter private ChunkOcclusionData occlusionData; @Getter private ChunkRenderBounds bounds; @Getter private List<TextureAtlasSprite> animatedSprites; private boolean isEmpty; private int meshByteSize; @Getter private int facesWithData; /** * @return True if the chunk has no renderables, otherwise false */ public boolean isEmpty() { return this.isEmpty; } /** * The collection of block entities contained by this rendered chunk. */ public Collection<TileEntity> getTileEntities() { return this.tileEntities; } /** * The collection of block entities contained by this rendered chunk section which are not part of its culling * volume. These entities should always be rendered regardless of the render being visible in the frustum. */ public Collection<TileEntity> getGlobalTileEntities() { return this.globalTileEntities; } /** * The collection of chunk meshes belonging to this render. */ public ChunkMeshData getMesh(BlockRenderPass pass) { return this.meshes.get(pass); } public void setMesh(BlockRenderPass pass, ChunkMeshData data) { if (this.meshes.get(pass) == null) throw new IllegalStateException("No mesh found"); this.meshes.put(pass, data); } public int getMeshSize() { return this.meshByteSize; } public ChunkRenderData copyAndReplaceMesh(Map<BlockRenderPass, ChunkMeshData> replacements) { ChunkRenderData data = new ChunkRenderData(); data.globalTileEntities = this.globalTileEntities; data.tileEntities = this.tileEntities; data.occlusionData = this.occlusionData; data.meshes = new EnumMap<>(this.meshes); data.bounds = this.bounds; data.animatedSprites = new ObjectArrayList<>(this.animatedSprites); data.meshes.putAll(replacements); int facesWithData = 0; int size = 0; for (ChunkMeshData meshData : this.meshes.values()) { size += meshData.getVertexDataSize(); for (Map.Entry<ModelQuadFacing, BufferSlice> entry : meshData.getSlices()) { facesWithData |= 1 << entry.getKey().ordinal(); } } data.isEmpty = this.globalTileEntities.isEmpty() && this.tileEntities.isEmpty() && facesWithData == 0; data.meshByteSize = size; data.facesWithData = facesWithData; return data; } public static class Builder { private final List<TileEntity> globalTileEntities = new ArrayList<>(); private final List<TileEntity> tileEntities = new ArrayList<>(); private final Set<TextureAtlasSprite> animatedSprites = new ObjectOpenHashSet<>(); private final EnumMap<BlockRenderPass, ChunkMeshData> meshes = new EnumMap<>(BlockRenderPass.class); private ChunkOcclusionData occlusionData; private ChunkRenderBounds bounds = ChunkRenderBounds.ALWAYS_FALSE; public Builder() { for (BlockRenderPass pass : BlockRenderPass.VALUES) { this.setMesh(pass, ChunkMeshData.EMPTY); } } public void setBounds(ChunkRenderBounds bounds) { this.bounds = bounds; } public void setOcclusionData(ChunkOcclusionData data) { this.occlusionData = data; } /** * Adds a sprite to this data container for tracking. If the sprite is tickable, it will be ticked every frame * before rendering as necessary. * @param sprite The sprite */ public void addSprite(TextureAtlasSprite sprite) { if (((ISpriteExt) sprite).isAnimation()) { this.animatedSprites.add(sprite); } } public void setMesh(BlockRenderPass pass, ChunkMeshData data) { this.meshes.put(pass, data); } /** * Adds a block entity to the data container. * @param entity The block entity itself * @param cull True if the block entity can be culled to this chunk render's volume, otherwise false */ public void addTileEntity(TileEntity entity, boolean cull) { (cull ? this.tileEntities : this.globalTileEntities).add(entity); } public ChunkRenderData build() { ChunkRenderData data = new ChunkRenderData(); data.globalTileEntities = new ObjectOpenHashSet<>(this.globalTileEntities); data.tileEntities = this.tileEntities; data.occlusionData = this.occlusionData; data.meshes = this.meshes; data.bounds = this.bounds; data.animatedSprites = new ObjectArrayList<>(this.animatedSprites); int facesWithData = 0; int size = 0; for (ChunkMeshData meshData : this.meshes.values()) { size += meshData.getVertexDataSize(); for (Map.Entry<ModelQuadFacing, BufferSlice> entry : meshData.getSlices()) { facesWithData |= 1 << entry.getKey().ordinal(); } } data.isEmpty = this.globalTileEntities.isEmpty() && this.tileEntities.isEmpty() && facesWithData == 0; data.meshByteSize = size; data.facesWithData = facesWithData; return data; } } private static ChunkRenderData createEmptyData() { ChunkOcclusionData occlusionData = new ChunkOcclusionData(); occlusionData.addOpenEdgeFaces(EnumSet.allOf(ForgeDirection.class)); Builder meshInfo = new Builder(); meshInfo.setOcclusionData(occlusionData); return meshInfo.build(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\format\ChunkMeshAttribute.java
package me.jellysquid.mods.sodium.client.render.chunk.format; public enum ChunkMeshAttribute { POSITION, COLOR, TEXTURE, LIGHT, // Iris NORMAL, TANGENT, MID_TEX_COORD, BLOCK_ID, MID_BLOCK }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\format\ChunkModelOffset.java
package me.jellysquid.mods.sodium.client.render.chunk.format; public class ChunkModelOffset { public float x, y, z; public void set(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\format\DefaultModelVertexFormats.java
package me.jellysquid.mods.sodium.client.render.chunk.format; import me.jellysquid.mods.sodium.client.render.chunk.format.hfp.HFPModelVertexType; import me.jellysquid.mods.sodium.client.render.chunk.format.sfp.SFPModelVertexType; public class DefaultModelVertexFormats { public static final HFPModelVertexType MODEL_VERTEX_HFP = new HFPModelVertexType(); public static final SFPModelVertexType MODEL_VERTEX_SFP = new SFPModelVertexType(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\format\ModelVertexSink.java
package me.jellysquid.mods.sodium.client.render.chunk.format; import me.jellysquid.mods.sodium.client.model.vertex.VertexSink; public interface ModelVertexSink extends VertexSink { /** * Writes a quad vertex to this sink. * @param x The x-position of the vertex * @param y The y-position of the vertex * @param z The z-position of the vertex * @param color The ABGR-packed color of the vertex * @param u The u-texture of the vertex * @param v The y-texture of the vertex * @param light The packed light-map coordinates of the vertex * @param shaderBlockId The blockId to be passed to the shader */ void writeQuad(float x, float y, float z, int color, float u, float v, int light, int shaderBlockId); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\format\ModelVertexUtil.java
package me.jellysquid.mods.sodium.client.render.chunk.format; public class ModelVertexUtil { /** * Converts a floating point vertex position in range 0..32 to a de-normalized unsigned short. * @param value The float in range 0..32 * @return The resulting de-normalized unsigned short */ public static short denormalizeVertexPositionFloatAsShort(float value) { // Since we're skipping the scaling formerly done in ChunkModelVertexTransformer to preserve precision, this // method actually takes input unnormalized within the range 0..32, and expands that to 0..65536. // TODO: Restructure things to be less arbitrary here return (short) (value * 2048.0f); } /** * Converts a normalized floating point texture coordinate to a de-normalized unsigned short. * @param value The normalized float * @return The resulting de-normalized unsigned short */ public static short denormalizeVertexTextureFloatAsShort(float value) { return (short) (Math.round(value * 32768.0F) & 0xFFFF); } /** * This moves some work out the shader code and simplifies things a bit. In vanilla, the game encodes light map * texture coordinates as two un-normalized unsigned shorts in the range 0..255. Using the fixed-function pipeline, * it then applies a matrix transformation which normalizes these coordinates and applies a centering offset. This * operation has non-zero overhead and complicates shader code a bit. * * To work around the problem, this function instead normalizes these light map texture coordinates and applies the * centering offset, allowing it to be baked into the vertex data itself. * * @param light The light map value * @return The light map texture coordinates as two unsigned shorts with a center offset applied */ public static int encodeLightMapTexCoord(int light) { int sl = (light >> 16) & 255; sl = (sl << 8) + 2048; int bl = light & 255; bl = (bl << 8) + 2048; return (sl << 16) | bl; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\lists\ChunkRenderList.java
package me.jellysquid.mods.sodium.client.render.chunk.lists; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.util.Arrays; /** * A simple extension over {@link ObjectArrayList} which provides iterator methods in either FIFO or LIFO ordering. */ public class ChunkRenderList<T> { private T[] stateArray; private int[] cullArray; private int size, capacity; public ChunkRenderList() { this(1024); } @SuppressWarnings("unchecked") public ChunkRenderList(int capacity) { this.size = 0; this.capacity = capacity; this.stateArray = (T[]) new Object[capacity]; this.cullArray = new int[capacity]; } private void resize() { this.capacity = this.capacity * 2; this.stateArray = Arrays.copyOf(this.stateArray, this.capacity); this.cullArray = Arrays.copyOf(this.cullArray, this.capacity); } public void add(T state, int cull) { int idx = this.size++; if (idx >= this.capacity) { this.resize(); } this.stateArray[idx] = state; this.cullArray[idx] = cull; } public void reset() { if (this.size == 0) { return; } for (int i = 0; i < this.size; i++) { this.stateArray[i] = null; } for (int i = 0; i < this.size; i++) { this.cullArray[i] = 0; } this.size = 0; } /** * @return An iterator which returns elements in FIFO order or LIFO order if {@param backwards} is set */ public ChunkRenderListIterator<T> iterator(boolean backwards) { if (backwards) { return new ChunkRenderListIterator<T>() { private int pos = ChunkRenderList.this.size - 1; @Override public T getGraphicsState() { return ChunkRenderList.this.stateArray[this.pos]; } @Override public int getVisibleFaces() { return ChunkRenderList.this.cullArray[this.pos]; } @Override public boolean hasNext() { return this.pos >= 0; } @Override public void advance() { this.pos--; } }; } else { return new ChunkRenderListIterator<T>() { private final int lim = ChunkRenderList.this.size; private int pos = 0; @Override public T getGraphicsState() { return ChunkRenderList.this.stateArray[this.pos]; } @Override public int getVisibleFaces() { return ChunkRenderList.this.cullArray[this.pos]; } @Override public boolean hasNext() { return this.pos < this.lim; } @Override public void advance() { this.pos++; } }; } } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\lists\ChunkRenderListIterator.java
package me.jellysquid.mods.sodium.client.render.chunk.lists; public interface ChunkRenderListIterator<T> { T getGraphicsState(); int getVisibleFaces(); boolean hasNext(); void advance(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\map\ChunkStatus.java
package me.jellysquid.mods.sodium.client.render.chunk.map; public class ChunkStatus { public static final int FLAG_HAS_BLOCK_DATA = 1; public static final int FLAG_HAS_LIGHT_DATA = 2; public static final int FLAG_ALL = FLAG_HAS_BLOCK_DATA | FLAG_HAS_LIGHT_DATA; }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\map\ChunkTracker.java
package me.jellysquid.mods.sodium.client.render.chunk.map; import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; import it.unimi.dsi.fastutil.longs.LongCollection; import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import it.unimi.dsi.fastutil.longs.LongSet; import it.unimi.dsi.fastutil.longs.LongSets; import net.minecraft.world.ChunkCoordIntPair; public class ChunkTracker implements ClientChunkEventListener { private final Long2IntOpenHashMap chunkStatus = new Long2IntOpenHashMap(); private final LongOpenHashSet chunkReady = new LongOpenHashSet(); private final LongSet unloadQueue = new LongOpenHashSet(); private final LongSet loadQueue = new LongOpenHashSet(); public ChunkTracker() { } @Override public void updateMapCenter(int chunkX, int chunkZ) { } @Override public void updateLoadDistance(int loadDistance) { } @Override public void onChunkStatusAdded(int x, int z, int flags) { var key = ChunkCoordIntPair.chunkXZ2Int(x, z); var prev = this.chunkStatus.get(key); var cur = prev | flags; if (prev == cur) { return; } this.chunkStatus.put(key, cur); this.updateNeighbors(x, z); } @Override public void onChunkStatusRemoved(int x, int z, int flags) { var key = ChunkCoordIntPair.chunkXZ2Int(x, z); var prev = this.chunkStatus.get(key); int cur = prev & ~flags; if (prev == cur) { return; } if (cur == this.chunkStatus.defaultReturnValue()) { this.chunkStatus.remove(key); } else { this.chunkStatus.put(key, cur); } this.updateNeighbors(x, z); } private void updateNeighbors(int x, int z) { for (int ox = -1; ox <= 1; ox++) { for (int oz = -1; oz <= 1; oz++) { this.updateMerged(ox + x, oz + z); } } } private void updateMerged(int x, int z) { long key = ChunkCoordIntPair.chunkXZ2Int(x, z); int flags = this.chunkStatus.get(key); for (int ox = -1; ox <= 1; ox++) { for (int oz = -1; oz <= 1; oz++) { flags &= this.chunkStatus.get(ChunkCoordIntPair.chunkXZ2Int(ox + x, oz + z)); } } if (flags == ChunkStatus.FLAG_ALL) { if (this.chunkReady.add(key) && !this.unloadQueue.remove(key)) { this.loadQueue.add(key); } } else { if (this.chunkReady.remove(key) && !this.loadQueue.remove(key)) { this.unloadQueue.add(key); } } } public LongCollection getReadyChunks() { return LongSets.unmodifiable(this.chunkReady); } public void forEachEvent(ChunkEventHandler loadEventHandler, ChunkEventHandler unloadEventHandler) { forEachChunk(this.unloadQueue, unloadEventHandler); this.unloadQueue.clear(); forEachChunk(this.loadQueue, loadEventHandler); this.loadQueue.clear(); } public static void forEachChunk(LongCollection queue, ChunkEventHandler handler) { var iterator = queue.iterator(); while (iterator.hasNext()) { var pos = iterator.nextLong(); var x = (int)(pos & 4294967295L); var z = (int)((pos >> 32L) & 4294967295L); handler.apply(x, z); } } public interface ChunkEventHandler { void apply(int x, int z); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\map\ChunkTrackerHolder.java
package me.jellysquid.mods.sodium.client.render.chunk.map; import net.minecraft.client.multiplayer.WorldClient; public interface ChunkTrackerHolder { static ChunkTracker get(WorldClient world) { return ((ChunkTrackerHolder) world).sodium$getTracker(); } ChunkTracker sodium$getTracker(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\map\ClientChunkEventListener.java
package me.jellysquid.mods.sodium.client.render.chunk.map; public interface ClientChunkEventListener { void updateMapCenter(int chunkX, int chunkZ); void updateLoadDistance(int loadDistance); void onChunkStatusAdded(int x, int z, int flags); void onChunkStatusRemoved(int x, int z, int flags); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\passes\BlockRenderPass.java
package me.jellysquid.mods.sodium.client.render.chunk.passes; /** * The order of these enums must match the passes used by vanilla. */ public enum BlockRenderPass { CUTOUT_MIPPED(false, 131072), TRANSLUCENT(true, 262144); public static final BlockRenderPass[] VALUES = BlockRenderPass.values(); public static final int COUNT = VALUES.length; private final boolean translucent; private final int bufferSize; BlockRenderPass(boolean translucent, int bufferSize) { this.translucent = translucent; this.bufferSize = bufferSize; } public boolean isTranslucent() { return this.translucent; } public int bufferSize() { return this.bufferSize; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\region\ChunkRegion.java
package me.jellysquid.mods.sodium.client.render.chunk.region; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import me.jellysquid.mods.sodium.client.gl.arena.GlBufferArena; import me.jellysquid.mods.sodium.client.gl.device.CommandList; import me.jellysquid.mods.sodium.client.gl.device.RenderDevice; import me.jellysquid.mods.sodium.client.gl.tessellation.GlTessellation; import me.jellysquid.mods.sodium.client.render.chunk.ChunkGraphicsState; import me.jellysquid.mods.sodium.client.render.chunk.backends.multidraw.ChunkDrawCallBatcher; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildResult; public class ChunkRegion<T extends ChunkGraphicsState> { private static final int EXPECTED_CHUNK_SIZE = 4 * 1024; private final GlBufferArena arena; private final ChunkDrawCallBatcher batch; private final RenderDevice device; private final ObjectArrayList<ChunkBuildResult<T>> uploadQueue; private GlTessellation tessellation; private final int x, y, z; public float camDistance; public ChunkRegion(RenderDevice device, int size, int x, int y, int z) { int arenaSize = EXPECTED_CHUNK_SIZE * size; this.device = device; this.arena = new GlBufferArena(device, arenaSize, arenaSize); this.uploadQueue = new ObjectArrayList<>(); this.batch = ChunkDrawCallBatcher.create(size * ModelQuadFacing.COUNT); this.x = x; this.y = y; this.z = z; } public int getCenterBlockX() { return (this.x * ChunkRegionManager.BUFFER_WIDTH * 16) + (ChunkRegionManager.BUFFER_WIDTH / 2 * 16); } public int getCenterBlockY() { return (this.y * ChunkRegionManager.BUFFER_HEIGHT * 16) + (ChunkRegionManager.BUFFER_HEIGHT / 2 * 16); } public int getCenterBlockZ() { return (this.z * ChunkRegionManager.BUFFER_LENGTH * 16) + (ChunkRegionManager.BUFFER_LENGTH / 2 * 16); } public GlBufferArena getBufferArena() { return this.arena; } public boolean isArenaEmpty() { return this.arena.isEmpty(); } public void deleteResources() { if (this.tessellation != null) { try (CommandList commands = this.device.createCommandList()) { commands.deleteTessellation(this.tessellation); } this.tessellation = null; } this.arena.delete(); this.batch.delete(); } public ObjectArrayList<ChunkBuildResult<T>> getUploadQueue() { return this.uploadQueue; } public ChunkDrawCallBatcher getDrawBatcher() { return this.batch; } public GlTessellation getTessellation() { return this.tessellation; } public void setTessellation(GlTessellation tessellation) { this.tessellation = tessellation; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\region\ChunkRegionManager.java
package me.jellysquid.mods.sodium.client.render.chunk.region; import com.gtnewhorizons.angelica.compat.mojang.ChunkSectionPos; import it.unimi.dsi.fastutil.longs.Long2ReferenceOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectIterator; import me.jellysquid.mods.sodium.client.gl.device.RenderDevice; import me.jellysquid.mods.sodium.client.render.chunk.ChunkGraphicsState; import me.jellysquid.mods.sodium.client.util.MathUtil; import org.apache.commons.lang3.Validate; public class ChunkRegionManager<T extends ChunkGraphicsState> { public static final int BUFFER_WIDTH = 8; public static final int BUFFER_HEIGHT = 4; public static final int BUFFER_LENGTH = 8; public static final int BUFFER_SIZE = BUFFER_WIDTH * BUFFER_HEIGHT * BUFFER_LENGTH; private static final int BUFFER_WIDTH_SH = Integer.bitCount(BUFFER_WIDTH - 1); private static final int BUFFER_HEIGHT_SH = Integer.bitCount(BUFFER_HEIGHT - 1); private static final int BUFFER_LENGTH_SH = Integer.bitCount(BUFFER_LENGTH - 1); static { Validate.isTrue(MathUtil.isPowerOfTwo(BUFFER_WIDTH)); Validate.isTrue(MathUtil.isPowerOfTwo(BUFFER_LENGTH)); Validate.isTrue(MathUtil.isPowerOfTwo(BUFFER_HEIGHT)); } private final Long2ReferenceOpenHashMap<ChunkRegion<T>> regions = new Long2ReferenceOpenHashMap<>(); private final RenderDevice device; public ChunkRegionManager(RenderDevice device) { this.device = device; } public ChunkRegion<T> getRegion(int x, int y, int z) { return this.regions.get(getRegionKey(x, y, z)); } public ChunkRegion<T> getOrCreateRegion(int x, int y, int z) { long key = getRegionKey(x, y, z); ChunkRegion<T> region = this.regions.get(key); if (region == null) { this.regions.put(key, region = new ChunkRegion<>(this.device, BUFFER_SIZE, x >> BUFFER_WIDTH_SH, y >> BUFFER_HEIGHT_SH, z >> BUFFER_LENGTH_SH)); } return region; } public static long getRegionKey(int x, int y, int z) { return ChunkSectionPos.asLong(x >> BUFFER_WIDTH_SH, y >> BUFFER_HEIGHT_SH, z >> BUFFER_LENGTH_SH); } public void delete() { for (ChunkRegion<T> region : this.regions.values()) { region.deleteResources(); } this.regions.clear(); } public void cleanup() { for (ObjectIterator<ChunkRegion<T>> iterator = this.regions.values().iterator(); iterator.hasNext(); ) { ChunkRegion<T> region = iterator.next(); if (region.isArenaEmpty()) { region.deleteResources(); iterator.remove(); } } } public int getAllocatedRegionCount() { return this.regions.size(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\shader\ChunkFogMode.java
package me.jellysquid.mods.sodium.client.render.chunk.shader; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.function.Function; public enum ChunkFogMode { NONE(ChunkShaderFogComponent.None::new, ImmutableList.of()), LINEAR(ChunkShaderFogComponent.Linear::new, ImmutableList.of("USE_FOG", "USE_FOG_LINEAR")), EXP2(ChunkShaderFogComponent.Exp2::new, ImmutableList.of("USE_FOG", "USE_FOG_EXP2")); private final Function<ChunkProgram, ChunkShaderFogComponent> factory; private final List<String> defines; ChunkFogMode(Function<ChunkProgram, ChunkShaderFogComponent> factory, List<String> defines) { this.factory = factory; this.defines = defines; } public Function<ChunkProgram, ChunkShaderFogComponent> getFactory() { return this.factory; } public List<String> getDefines() { return this.defines; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\shader\ChunkProgram.java
package me.jellysquid.mods.sodium.client.render.chunk.shader; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack.*; import com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack; import com.gtnewhorizons.angelica.compat.toremove.MatrixStack; import me.jellysquid.mods.sodium.client.gl.device.RenderDevice; import me.jellysquid.mods.sodium.client.gl.shader.GlProgram; import me.jellysquid.mods.sodium.client.render.GameRendererContext; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL20; import java.util.function.Function; /** * A forward-rendering shader program for chunks. */ public class ChunkProgram extends GlProgram { // Uniform variable binding indexes private final int uModelViewProjectionMatrix; private final int uModelScale; private final int uTextureScale; private final int uBlockTex; private final int uLightTex; // The fog shader component used by this program in order to setup the appropriate GL state private final ChunkShaderFogComponent fogShader; protected ChunkProgram(RenderDevice owner, ResourceLocation name, int handle, Function<ChunkProgram, ChunkShaderFogComponent> fogShaderFunction) { super(owner, name, handle); this.uModelViewProjectionMatrix = this.getUniformLocation("u_ModelViewProjectionMatrix"); this.uBlockTex = this.getUniformLocation("u_BlockTex"); this.uLightTex = this.getUniformLocation("u_LightTex"); this.uModelScale = this.getUniformLocation("u_ModelScale"); this.uTextureScale = this.getUniformLocation("u_TextureScale"); this.fogShader = fogShaderFunction.apply(this); } public void setup(MatrixStack matrixStack, float modelScale, float textureScale) { if(this.uBlockTex != -1) GL20.glUniform1i(this.uBlockTex, OpenGlHelper.defaultTexUnit - GL13.GL_TEXTURE0); if(this.uLightTex != -1) GL20.glUniform1i(this.uLightTex, OpenGlHelper.lightmapTexUnit - GL13.GL_TEXTURE0); if(this.uModelScale != -1) GL20.glUniform3f(this.uModelScale, modelScale, modelScale, modelScale); if(this.uTextureScale != -1) GL20.glUniform2f(this.uTextureScale, textureScale, textureScale); this.fogShader.setup(); if (this.uModelViewProjectionMatrix == -1) return; try (MemoryStack stack = stackPush()) { GL20.glUniformMatrix4( this.uModelViewProjectionMatrix, false, GameRendererContext.getModelViewProjectionMatrix(matrixStack.peek(), stack)); } } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\shader\ChunkRenderShaderBackend.java
package me.jellysquid.mods.sodium.client.render.chunk.shader; import com.gtnewhorizons.angelica.compat.toremove.MatrixStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexFormat; import me.jellysquid.mods.sodium.client.gl.compat.FogHelper; import me.jellysquid.mods.sodium.client.gl.device.RenderDevice; import me.jellysquid.mods.sodium.client.gl.shader.GlProgram; import me.jellysquid.mods.sodium.client.gl.shader.GlShader; import me.jellysquid.mods.sodium.client.gl.shader.ShaderConstants; import me.jellysquid.mods.sodium.client.gl.shader.ShaderLoader; import me.jellysquid.mods.sodium.client.gl.shader.ShaderType; import me.jellysquid.mods.sodium.client.model.vertex.type.ChunkVertexType; import me.jellysquid.mods.sodium.client.render.chunk.ChunkGraphicsState; import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderBackend; import me.jellysquid.mods.sodium.client.render.chunk.format.ChunkMeshAttribute; import me.jellysquid.mods.sodium.client.render.chunk.passes.BlockRenderPass; import net.coderbot.iris.Iris; import net.coderbot.iris.gl.program.ProgramSamplers; import net.coderbot.iris.gl.program.ProgramUniforms; import net.coderbot.iris.pipeline.SodiumTerrainPipeline; import net.coderbot.iris.pipeline.WorldRenderingPipeline; import net.coderbot.iris.shaderpack.transform.StringTransformations; import net.coderbot.iris.shaderpack.transform.Transformations; import net.coderbot.iris.shadows.ShadowRenderingState; import net.coderbot.iris.sodium.shader_overrides.IrisChunkProgramOverrides; import net.coderbot.iris.sodium.vertex_format.IrisModelVertexFormats; import net.minecraft.util.ResourceLocation; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.EnumMap; import java.util.List; public abstract class ChunkRenderShaderBackend<T extends ChunkGraphicsState> implements ChunkRenderBackend<T> { private final EnumMap<ChunkFogMode, ChunkProgram> programs = new EnumMap<>(ChunkFogMode.class); protected final ChunkVertexType vertexType; protected final GlVertexFormat<ChunkMeshAttribute> vertexFormat; protected ChunkProgram activeProgram; // Iris private IrisChunkProgramOverrides irisChunkProgramOverrides; private RenderDevice device; private ChunkProgram override; public ChunkRenderShaderBackend(ChunkVertexType vertexType) { if (Iris.enabled) { irisChunkProgramOverrides = new IrisChunkProgramOverrides(); } this.vertexType = vertexType; this.vertexFormat = vertexType.getCustomVertexFormat(); } public GlShader loadShaderRedirect(RenderDevice device, ShaderType type, ResourceLocation name, List<String> constants) { if (Iris.enabled && this.vertexType == IrisModelVertexFormats.MODEL_VERTEX_XHFP) { String shader = getShaderSource(ShaderLoader.getShaderPath(name, type)); shader = shader.replace("v_LightCoord = a_LightCoord", "v_LightCoord = (iris_LightmapTextureMatrix * vec4(a_LightCoord, 0, 1)).xy"); StringTransformations transformations = new StringTransformations(shader); transformations.injectLine( Transformations.InjectionPoint.BEFORE_CODE, "mat4 iris_LightmapTextureMatrix = mat4(vec4(0.00390625, 0.0, 0.0, 0.0), vec4(0.0, 0.00390625, 0.0, 0.0), vec4(0.0, 0.0, 0.00390625, 0.0), vec4(0.03125, 0.03125, 0.03125, 1.0));"); return new GlShader(device, type, name, transformations.toString(), ShaderConstants.fromStringList(constants)); } else { return ShaderLoader.loadShader(device, type, name, ShaderConstants.fromStringList(constants)); } } private ChunkProgram createShader(RenderDevice device, ChunkFogMode fogMode, GlVertexFormat<ChunkMeshAttribute> vertexFormat) { if(Iris.enabled) { this.device = device; WorldRenderingPipeline worldRenderingPipeline = Iris.getPipelineManager().getPipelineNullable(); SodiumTerrainPipeline sodiumTerrainPipeline = null; if (worldRenderingPipeline != null) { sodiumTerrainPipeline = worldRenderingPipeline.getSodiumTerrainPipeline(); } irisChunkProgramOverrides.createShaders(sodiumTerrainPipeline, device); } GlShader vertShader = loadShaderRedirect(device, ShaderType.VERTEX, new ResourceLocation("sodium", "chunk_gl20"), fogMode.getDefines()); GlShader fragShader = ShaderLoader.loadShader(device, ShaderType.FRAGMENT, new ResourceLocation("sodium", "chunk_gl20"), ShaderConstants.fromStringList(fogMode.getDefines())); try { return GlProgram.builder(new ResourceLocation("sodium", "chunk_shader")) .attachShader(vertShader) .attachShader(fragShader) .bindAttribute("a_Pos", ChunkShaderBindingPoints.POSITION) .bindAttribute("a_Color", ChunkShaderBindingPoints.COLOR) .bindAttribute("a_TexCoord", ChunkShaderBindingPoints.TEX_COORD) .bindAttribute("a_LightCoord", ChunkShaderBindingPoints.LIGHT_COORD) .bindAttribute("d_ModelOffset", ChunkShaderBindingPoints.MODEL_OFFSET) .build((program, name) -> new ChunkProgram(device, program, name, fogMode.getFactory())); } finally { vertShader.delete(); fragShader.delete(); } } private static String getShaderSource(String path) { try { InputStream in = ShaderLoader.class.getResourceAsStream(path); Exception throwable = null; String res; try { if (in == null) { throw new RuntimeException("Shader not found: " + path); } res = IOUtils.toString(in, StandardCharsets.UTF_8); } catch (Exception tr) { throwable = tr; throw tr; } finally { if (in != null) { if (throwable != null) { try { in.close(); } catch (Exception var12) { throwable.addSuppressed(var12); } } else { in.close(); } } } return res; } catch (IOException e) { throw new RuntimeException("Could not read shader sources", e); } } @Override public final void createShaders(RenderDevice device) { this.programs.put(ChunkFogMode.NONE, this.createShader(device, ChunkFogMode.NONE, this.vertexFormat)); this.programs.put(ChunkFogMode.LINEAR, this.createShader(device, ChunkFogMode.LINEAR, this.vertexFormat)); this.programs.put(ChunkFogMode.EXP2, this.createShader(device, ChunkFogMode.EXP2, this.vertexFormat)); } @Override public void begin(MatrixStack matrixStack) { this.activeProgram = this.programs.get(FogHelper.getFogMode()); if (Iris.enabled && override != null) { this.activeProgram = override; } this.activeProgram.bind(); this.activeProgram.setup(matrixStack, this.vertexType.getModelScale(), this.vertexType.getTextureScale()); } @Override public void end(MatrixStack matrixStack) { this.activeProgram.unbind(); this.activeProgram = null; if(Iris.enabled) { ProgramUniforms.clearActiveUniforms(); ProgramSamplers.clearActiveSamplers(); Iris.getPipelineManager().getPipeline().ifPresent(WorldRenderingPipeline::endSodiumTerrainRendering); } } @Override public void delete() { if(Iris.enabled) { irisChunkProgramOverrides.deleteShaders(); } for (ChunkProgram shader : this.programs.values()) { shader.delete(); } } @Override public ChunkVertexType getVertexType() { return this.vertexType; } // Iris public void iris$begin(MatrixStack matrixStack, BlockRenderPass pass) { if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { // No back face culling during the shadow pass // TODO: Hopefully this won't be necessary in the future... GLStateManager.disableCull(); } this.override = irisChunkProgramOverrides.getProgramOverride(device, pass); Iris.getPipelineManager().getPipeline().ifPresent(WorldRenderingPipeline::beginSodiumTerrainRendering); begin(matrixStack); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\shader\ChunkShaderBindingPoints.java
package me.jellysquid.mods.sodium.client.render.chunk.shader; import me.jellysquid.mods.sodium.client.gl.shader.ShaderBindingPoint; public class ChunkShaderBindingPoints { public static final ShaderBindingPoint POSITION = new ShaderBindingPoint(0); public static final ShaderBindingPoint COLOR = new ShaderBindingPoint(1); public static final ShaderBindingPoint TEX_COORD = new ShaderBindingPoint(2); public static final ShaderBindingPoint LIGHT_COORD = new ShaderBindingPoint(3); public static final ShaderBindingPoint MODEL_OFFSET = new ShaderBindingPoint(4); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\shader\ChunkShaderFogComponent.java
package me.jellysquid.mods.sodium.client.render.chunk.shader; import me.jellysquid.mods.sodium.client.gl.compat.FogHelper; import org.lwjgl.opengl.GL20; /** * These shader implementations try to remain compatible with the deprecated fixed function pipeline by manually * copying the state into each shader's uniforms. The shader code itself is a straight-forward implementation of the * fog functions themselves from the fixed-function pipeline, except that they use the distance from the camera * rather than the z-buffer to produce better looking fog that doesn't move with the player's view angle. * * Minecraft itself will actually try to enable distance-based fog by using the proprietary NV_fog_distance extension, * but as the name implies, this only works on graphics cards produced by NVIDIA. The shader implementation however does * not depend on any vendor-specific extensions and is written using very simple GLSL code. */ public abstract class ChunkShaderFogComponent { public abstract void setup(); public static class None extends ChunkShaderFogComponent { public None(ChunkProgram program) { } @Override public void setup() { } } public static class Exp2 extends ChunkShaderFogComponent { private final int uFogColor; private final int uFogDensity; public Exp2(ChunkProgram program) { this.uFogColor = program.getUniformLocation("u_FogColor"); this.uFogDensity = program.getUniformLocation("u_FogDensity"); } @Override public void setup() { final float[] fc = FogHelper.getFogColor(); GL20.glUniform4f(this.uFogColor, fc[0], fc[1], fc[2], fc[3]); GL20.glUniform1f(this.uFogDensity, FogHelper.getFogDensity()); } } public static class Linear extends ChunkShaderFogComponent { private final int uFogColor; private final int uFogLength; private final int uFogEnd; public Linear(ChunkProgram program) { this.uFogColor = program.getUniformLocation("u_FogColor"); this.uFogLength = program.getUniformLocation("u_FogLength"); this.uFogEnd = program.getUniformLocation("u_FogEnd"); } @Override public void setup() { float end = FogHelper.getFogEnd(); float start = FogHelper.getFogStart(); float[] color = FogHelper.getFogColor(); GL20.glUniform4f(this.uFogColor, color[0], color[1], color[2], color[3]); GL20.glUniform1f(this.uFogLength, end - start); GL20.glUniform1f(this.uFogEnd, end); } } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\tasks\ChunkRenderBuildTask.java
package me.jellysquid.mods.sodium.client.render.chunk.tasks; import me.jellysquid.mods.sodium.client.render.chunk.ChunkGraphicsState; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildBuffers; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildResult; import me.jellysquid.mods.sodium.client.render.pipeline.context.ChunkRenderCacheLocal; import me.jellysquid.mods.sodium.client.util.task.CancellationSource; /** * Build tasks are immutable jobs (with optional prioritization) which contain all the necessary state to perform * chunk mesh updates or quad sorting off the main thread. * * When a task is constructed on the main thread, it should copy all the state it requires in order to complete the task * without further synchronization. The task will then be scheduled for async execution on a thread pool. * * After the task completes, it returns a "build result" which contains any computed data that needs to be handled * on the main thread. * * @param <T> The graphics state of the chunk render */ public abstract class ChunkRenderBuildTask<T extends ChunkGraphicsState> { /** * Executes the given build task asynchronously from the calling thread. The implementation should be careful not * to access or modify global mutable state. * * @param cache The render cache to use for building this chunk * @param buffers The temporary scratch buffers for rendering block data * @param cancellationSource The cancellation source which can be used to query if the task is cancelled * @return The build result of this task, containing any data which needs to be uploaded on the main-thread, or null * if the task was cancelled. */ public abstract ChunkBuildResult<T> performBuild(ChunkRenderCacheLocal cache, ChunkBuildBuffers buffers, CancellationSource cancellationSource); public boolean willRenderInMainThread(ChunkRenderCacheLocal cache) { return false; }; /** * Called on the main render thread when the task's execution returns. The implementation should release any * resources it's still holding onto at this point. */ public abstract void releaseResources(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\tasks\ChunkRenderRebuildTask.java
package me.jellysquid.mods.sodium.client.render.chunk.tasks; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import com.gtnewhorizons.angelica.compat.ModStatus; import com.gtnewhorizons.angelica.compat.mojang.ChunkOcclusionDataBuilder; import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.mixins.interfaces.ITexturesCache; import net.coderbot.iris.Iris; import com.gtnewhorizons.angelica.rendering.AngelicaBlockSafetyRegistry; import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue; import com.gtnewhorizons.angelica.utils.AnimationsRenderUtils; import it.unimi.dsi.fastutil.longs.LongArrayFIFOQueue; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import me.jellysquid.mods.sodium.client.SodiumClientMod; import me.jellysquid.mods.sodium.client.render.chunk.ChunkGraphicsState; import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderContainer; import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderManager; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildBuffers; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildResult; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkMeshData; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderBounds; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderData; import me.jellysquid.mods.sodium.client.render.chunk.passes.BlockRenderPass; import me.jellysquid.mods.sodium.client.render.pipeline.WorldUtil; import me.jellysquid.mods.sodium.client.render.pipeline.context.ChunkRenderCacheLocal; import me.jellysquid.mods.sodium.client.util.MathUtil; import me.jellysquid.mods.sodium.client.util.task.CancellationSource; import me.jellysquid.mods.sodium.client.world.WorldSlice; import me.jellysquid.mods.sodium.client.world.cloned.ChunkRenderContext; import net.coderbot.iris.block_rendering.BlockRenderingSettings; import net.coderbot.iris.vertices.ExtendedDataHelper; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.IIcon; import net.minecraftforge.fluids.Fluid; import org.joml.Vector3d; /** * Rebuilds all the meshes of a chunk for each given render pass with non-occluded blocks. The result is then uploaded * to graphics memory on the main thread. * * This task takes a slice of the world from the thread it is created on. Since these slices require rather large * array allocations, they are pooled to ensure that the garbage collector doesn't become overloaded. */ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkRenderBuildTask<T> { private final ChunkRenderContainer<T> render; private final BlockPos offset; private final ChunkRenderContext context; private Vector3d camera; private final boolean translucencySorting; private boolean hasMainThreadBlocks = false; private boolean hasMainThreadBlocksComputed = false; public ChunkRenderRebuildTask(ChunkRenderContainer<T> render, ChunkRenderContext context, BlockPos offset) { this.render = render; this.offset = offset; this.context = context; this.camera = new Vector3d(); this.translucencySorting = SodiumClientMod.options().advanced.translucencySorting; } public ChunkRenderRebuildTask<T> withCameraPosition(Vector3d camera) { this.camera = camera; return this; } private boolean rendersOutsideBoundingBox(TileEntity entity, int baseX, int baseY, int baseZ) { AxisAlignedBB box = entity.getRenderBoundingBox(); // Check if it's explictly infinite if(box == TileEntity.INFINITE_EXTENT_AABB) return true; // Check if it extends outside our minimums if(box.minX < baseX || box.minY < baseY || box.minZ < baseZ) return true; // Check if it extends outside our maximums if(box.maxX > (baseX + 16) || box.maxY > (baseY + 16) || box.maxZ > (baseZ + 16)) return true; // So it's within the chunk return false; } private boolean rendersOffThread(Block block) { final int type = block.getRenderType(); return (type < 42 && type != 22 && AngelicaBlockSafetyRegistry.canBlockRenderOffThread(block, false, false)) || AngelicaBlockSafetyRegistry.canBlockRenderOffThread(block, true, false); } private void handleRenderBlocksTextures(RenderBlocks rb, ChunkRenderData.Builder builder) { if(!AngelicaConfig.speedupAnimations || !(rb instanceof ITexturesCache)) return; for(IIcon texture : ((ITexturesCache)rb).getRenderedTextures()) { if(texture instanceof TextureAtlasSprite textureAtlasSprite) { builder.addSprite(textureAtlasSprite); } } } private boolean canRenderInPass(Block block, BlockRenderPass pass) { boolean canRender = block.canRenderInPass(pass.ordinal()); Map<Block, RenderLayer> blockTypeIds = BlockRenderingSettings.INSTANCE.getBlockTypeIds(); RenderLayer renderLayer; if (blockTypeIds != null && (renderLayer = blockTypeIds.get(block)) != null) { canRender = switch (pass) { case CUTOUT_MIPPED -> renderLayer == RenderLayer.cutout(); case TRANSLUCENT -> renderLayer == RenderLayer.translucent(); }; } return canRender; } public boolean willRenderInMainThread(ChunkRenderCacheLocal cache) { if (hasMainThreadBlocksComputed) return hasMainThreadBlocks; final ChunkRenderData.Builder renderData = new ChunkRenderData.Builder(); final ChunkOcclusionDataBuilder occluder = new ChunkOcclusionDataBuilder(); final ChunkRenderBounds.Builder bounds = new ChunkRenderBounds.Builder(); cache.init(this.context); final WorldSlice slice = cache.getWorldSlice(); final int baseX = this.render.getOriginX(); final int baseY = this.render.getOriginY(); final int baseZ = this.render.getOriginZ(); final BlockPos pos = new BlockPos(); outer: for (int relY = 0; relY < 16; relY++) { for (int relZ = 0; relZ < 16; relZ++) { for (int relX = 0; relX < 16; relX++) { final Block block = slice.getBlockRelative(relX + 16, relY + 16, relZ + 16); // If the block is vanilla air, assume it renders nothing. Don't use isAir because mods // can abuse it for all sorts of things if (block.getMaterial() == Material.air) { continue; } if (!rendersOffThread(block)) { hasMainThreadBlocks = true; break outer; } } } } hasMainThreadBlocksComputed = true; return hasMainThreadBlocks; } @Override public ChunkBuildResult<T> performBuild(ChunkRenderCacheLocal cache, ChunkBuildBuffers buffers, CancellationSource cancellationSource) { final ChunkRenderData.Builder renderData = new ChunkRenderData.Builder(); final ChunkOcclusionDataBuilder occluder = new ChunkOcclusionDataBuilder(); final ChunkRenderBounds.Builder bounds = new ChunkRenderBounds.Builder(); buffers.init(renderData); cache.init(this.context); final WorldSlice slice = cache.getWorldSlice(); final RenderBlocks renderBlocks = new RenderBlocks(slice); if(renderBlocks instanceof ITexturesCache textureCache) { textureCache.enableTextureTracking(); AnimationsRenderUtils.pushCache(textureCache); } final int baseX = this.render.getOriginX(); final int baseY = this.render.getOriginY(); final int baseZ = this.render.getOriginZ(); final BlockPos pos = new BlockPos(); final BlockPos renderOffset = this.offset; final LongArrayFIFOQueue mainThreadBlocks = new LongArrayFIFOQueue(); for (int relY = 0; relY < 16; relY++) { if (cancellationSource.isCancelled()) { return null; } for (int relZ = 0; relZ < 16; relZ++) { for (int relX = 0; relX < 16; relX++) { Fluid fluid = null; if (ModStatus.isFluidLoggedLoaded) { fluid = slice.getFluidRelative(relX + 16, relY + 16, relZ + 16); } final Block block = slice.getBlockRelative(relX + 16, relY + 16, relZ + 16); // If the block is vanilla air, assume it renders nothing. Don't use isAir because mods // can abuse it for all sorts of things if (block.getMaterial() == Material.air) { continue; } final int meta = slice.getBlockMetadataRelative(relX + 16, relY + 16, relZ + 16); pos.set(baseX + relX, baseY + relY, baseZ + relZ); buffers.setRenderOffset(pos.x - renderOffset.getX(), pos.y - renderOffset.getY(), pos.z - renderOffset.getZ()); if(Iris.enabled) buffers.iris$setLocalPos(relX, relY, relZ); if (rendersOffThread(block)) { // Do regular block rendering final long seed = MathUtil.hashPos(pos.x, pos.y, pos.z); for (BlockRenderPass pass : BlockRenderPass.VALUES) { if (ModStatus.isFluidLoggedLoaded) { if (fluid != null && canRenderInPass(fluid.getBlock(), pass)) { ChunkRenderManager.setWorldRenderPass(pass); if(Iris.enabled) buffers.iris$setMaterialId(fluid.getBlock(), ExtendedDataHelper.FLUID_RENDER_TYPE); cache.getBlockRenderer().renderFluidLogged(cache.getWorldSlice(), fluid, renderBlocks, pos, buffers.get(pass), seed); } } if (canRenderInPass(block, pass) && !shouldUseSodiumFluidRendering(block)) { ChunkRenderManager.setWorldRenderPass(pass); if(Iris.enabled) buffers.iris$setMaterialId(block, ExtendedDataHelper.BLOCK_RENDER_TYPE); if (cache.getBlockRenderer().renderModel(cache.getWorldSlice(), renderBlocks, block, meta, pos, buffers.get(pass), true, seed)) { bounds.addBlock(relX, relY, relZ); } } } } else { mainThreadBlocks.enqueue(pos.asLong()); hasMainThreadBlocks = true; } // Do fluid rendering without RenderBlocks if (shouldUseSodiumFluidRendering(block)) { for (BlockRenderPass pass : BlockRenderPass.VALUES) { if (canRenderInPass(block, pass)) { ChunkRenderManager.setWorldRenderPass(pass); if(Iris.enabled) buffers.iris$setMaterialId(block, ExtendedDataHelper.FLUID_RENDER_TYPE); if (cache.getFluidRenderer().render(slice, cache.getWorldSlice(), block, pos, buffers.get(pass))) { bounds.addBlock(relX, relY, relZ); } } } } if(Iris.enabled) buffers.iris$resetBlockContext(); if (block.hasTileEntity(meta)) { final TileEntity entity = slice.getTileEntity(pos.x, pos.y, pos.z); final TileEntitySpecialRenderer renderer = TileEntityRendererDispatcher.instance.getSpecialRenderer(entity); if (entity != null && renderer != null) { renderData.addTileEntity(entity, !rendersOutsideBoundingBox(entity, baseX, baseY, baseZ)); bounds.addBlock(relX, relY, relZ); } } if (block.isOpaqueCube()) { occluder.markClosed(pos); } } } } if(renderBlocks instanceof ITexturesCache) { AnimationsRenderUtils.popCache(); } handleRenderBlocksTextures(renderBlocks, renderData); hasMainThreadBlocksComputed = true; if(hasMainThreadBlocks) { // Render the other blocks on the main thread var future = CompletableFuture.runAsync(() -> this.performMainBuild(cache, buffers, cancellationSource, bounds, renderData, mainThreadBlocks), AngelicaRenderQueue.executor()); while(!future.isDone() && !cancellationSource.isCancelled()) { try { future.get(); } catch(InterruptedException e) { // go around and check cancellation } catch(ExecutionException e) { throw new RuntimeException(e); } } // Check if cancellation happened during that, so we don't render an incomplete chunk if(cancellationSource.isCancelled()) return null; } render.setRebuildForTranslucents(false); for (BlockRenderPass pass : BlockRenderPass.VALUES) { final ChunkMeshData mesh = buffers.createMesh(pass, (float)camera.x - offset.getX(), (float)camera.y - offset.getY(), (float)camera.z - offset.getZ(), this.translucencySorting); if (mesh != null) { renderData.setMesh(pass, mesh); if(this.translucencySorting && pass.isTranslucent()) render.setRebuildForTranslucents(true); } } renderData.setOcclusionData(occluder.build()); renderData.setBounds(bounds.build(this.render.getChunkPos())); return new ChunkBuildResult<>(this.render, renderData.build()); } /** * Render the blocks that should be rendered on the main thread. */ private void performMainBuild(ChunkRenderCacheLocal cache, ChunkBuildBuffers buffers, CancellationSource cancellationSource, ChunkRenderBounds.Builder bounds, ChunkRenderData.Builder renderData, LongArrayFIFOQueue mainThreadBlocks) { final WorldSlice slice = cache.getWorldSlice(); final BlockPos pos = new BlockPos(); final int baseX = this.render.getOriginX(); final int baseY = this.render.getOriginY(); final int baseZ = this.render.getOriginZ(); final BlockPos renderOffset = this.offset; final RenderBlocks rb = new RenderBlocks(slice.getWorld()); if(rb instanceof ITexturesCache textureCache) { textureCache.enableTextureTracking(); AnimationsRenderUtils.pushCache(textureCache); } while(!mainThreadBlocks.isEmpty()) { final long longPos = mainThreadBlocks.dequeueLong(); if (cancellationSource.isCancelled()) { return; } pos.set(longPos); final int relX = pos.getX() - baseX; final int relY = pos.getY() - baseY; final int relZ = pos.getZ() - baseZ; final Block block = slice.getBlockRelative(relX + 16, relY + 16, relZ + 16); // Only render blocks that need main thread assistance if (block.getMaterial() == Material.air || rendersOffThread(block)) { continue; } // TODO: Collect data on which render types are hitting this code path most often so mods can be updated slowly final int meta = slice.getBlockMetadataRelative(relX + 16, relY + 16, relZ + 16); buffers.setRenderOffset(pos.x - renderOffset.getX(), pos.y - renderOffset.getY(), pos.z - renderOffset.getZ()); if(Iris.enabled) buffers.iris$setLocalPos(relX, relY, relZ); // Do regular block rendering for (BlockRenderPass pass : BlockRenderPass.VALUES) { if (canRenderInPass(block, pass) && !shouldUseSodiumFluidRendering(block)) { ChunkRenderManager.setWorldRenderPass(pass); final long seed = MathUtil.hashPos(pos.x, pos.y, pos.z); if(Iris.enabled) buffers.iris$setMaterialId(block, ExtendedDataHelper.BLOCK_RENDER_TYPE); if (cache.getBlockRenderer().renderModel(slice.getWorld(), rb, block, meta, pos, buffers.get(pass), true, seed)) { bounds.addBlock(relX, relY, relZ); } } } if(Iris.enabled) buffers.iris$resetBlockContext(); } if(rb instanceof ITexturesCache) { AnimationsRenderUtils.popCache(); } handleRenderBlocksTextures(rb, renderData); } @Override public void releaseResources() { this.context.releaseResources(); } @Override public String toString() { return "ChunkRenderRebuildTask{" + "offset=" + offset + ", camera=" + camera + ", translucencySorting=" + translucencySorting + ", hasMainThreadBlocks=" + hasMainThreadBlocks + '}'; } private static boolean shouldUseSodiumFluidRendering(Block block) { return AngelicaConfig.enableSodiumFluidRendering && WorldUtil.isFluidBlock(block) && !ModStatus.isFluidLoggedLoaded; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\tasks\ChunkRenderTranslucencySortTask.java
package me.jellysquid.mods.sodium.client.render.chunk.tasks; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import me.jellysquid.mods.sodium.client.gl.buffer.VertexData; import me.jellysquid.mods.sodium.client.gl.util.BufferSlice; import me.jellysquid.mods.sodium.client.render.chunk.ChunkGraphicsState; import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderContainer; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBufferSorter; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildBuffers; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildResult; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkMeshData; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderData; import me.jellysquid.mods.sodium.client.render.chunk.passes.BlockRenderPass; import me.jellysquid.mods.sodium.client.render.pipeline.context.ChunkRenderCacheLocal; import me.jellysquid.mods.sodium.client.util.task.CancellationSource; import org.joml.Vector3d; import org.lwjgl.BufferUtils; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Handles sorting translucency data in built chunks. */ public class ChunkRenderTranslucencySortTask<T extends ChunkGraphicsState> extends ChunkRenderBuildTask<T> { private static final BlockRenderPass[] TRANSLUCENT_PASSES = Arrays.stream(BlockRenderPass.VALUES).filter(BlockRenderPass::isTranslucent).toArray(BlockRenderPass[]::new); private static final BlockRenderPass[] NO_PASSES = new BlockRenderPass[0]; private final ChunkRenderContainer<T> render; private final BlockPos offset; private final Vector3d camera; public ChunkRenderTranslucencySortTask(ChunkRenderContainer<T> render, BlockPos offset, Vector3d camera) { this.render = render; this.offset = offset; this.camera = camera; } @Override public ChunkBuildResult<T> performBuild(ChunkRenderCacheLocal cache, ChunkBuildBuffers buffers, CancellationSource cancellationSource) { final ChunkRenderData data = this.render.getData(); final Map<BlockRenderPass, ChunkMeshData> replacementMeshes; if(!data.isEmpty()) { replacementMeshes = new HashMap<>(); for(BlockRenderPass pass : TRANSLUCENT_PASSES) { final ChunkGraphicsState state = this.render.getGraphicsState(pass); if(state == null) continue; final ByteBuffer translucencyData = state.getTranslucencyData(); if(translucencyData == null) continue; final ChunkMeshData translucentMesh = data.getMesh(pass); if(translucentMesh == null) continue; // Make a snapshot of the translucency data to sort final ByteBuffer sortedData = BufferUtils.createByteBuffer(translucencyData.capacity()); synchronized (translucencyData) { sortedData.put(translucencyData); translucencyData.position(0); translucencyData.limit(translucencyData.capacity()); } sortedData.flip(); // Sort it and create the new mesh ChunkBufferSorter.sortStandardFormat(buffers.getVertexType(), sortedData, sortedData.capacity(), (float) camera.x - offset.getX(), (float)camera.y - offset.getY(), (float)camera.z - offset.getZ()); final ChunkMeshData newMesh = new ChunkMeshData(); newMesh.setVertexData(new VertexData(sortedData, buffers.getVertexType().getCustomVertexFormat())); for(Map.Entry<ModelQuadFacing, BufferSlice> entry : translucentMesh.getSlices()) { newMesh.setModelSlice(entry.getKey(), entry.getValue()); } replacementMeshes.put(pass, newMesh); } } else { replacementMeshes = Collections.emptyMap(); } final ChunkBuildResult<T> result = new ChunkBuildResult<>(this.render, data.copyAndReplaceMesh(replacementMeshes)); result.passesToUpload = replacementMeshes.keySet().toArray(NO_PASSES); return result; } @Override public void releaseResources() { } @Override public String toString() { return "ChunkRenderTranslucencySortTask{" + "offset=" + offset + ", camera=" + camera + '}'; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\backends\multidraw\ChunkDrawCallBatcher.java
package me.jellysquid.mods.sodium.client.render.chunk.backends.multidraw; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; import com.gtnewhorizons.angelica.compat.mojang.CompatMathHelper; import me.jellysquid.mods.sodium.client.SodiumClientMod; import org.lwjgl.MemoryUtil; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; /** * Provides a fixed-size buffer which can be used to batch chunk section draw calls. */ public abstract class ChunkDrawCallBatcher extends StructBuffer { protected final int capacity; protected boolean isBuilding; protected int count; protected int arrayLength; protected ChunkDrawCallBatcher(int capacity) { super(CompatMathHelper.smallestEncompassingPowerOfTwo(capacity), 16); this.capacity = capacity; } public static ChunkDrawCallBatcher create(int capacity) { return SodiumClientMod.isDirectMemoryAccessEnabled() ? new UnsafeChunkDrawCallBatcher(capacity) : new NioChunkDrawCallBatcher(capacity); } public void begin() { this.isBuilding = true; this.count = 0; this.arrayLength = 0; this.buffer.limit(this.buffer.capacity()); } public void end() { this.isBuilding = false; this.arrayLength = this.count * this.stride; this.buffer.limit(this.arrayLength); this.buffer.position(0); } public boolean isBuilding() { return this.isBuilding; } public abstract void addIndirectDrawCall(int first, int count, int baseInstance, int instanceCount); public int getCount() { return this.count; } public boolean isEmpty() { return this.count <= 0; } public static class UnsafeChunkDrawCallBatcher extends ChunkDrawCallBatcher { private final long basePointer; private long writePointer; public UnsafeChunkDrawCallBatcher(int capacity) { super(capacity); this.basePointer = MemoryUtil.getAddress(this.buffer); } @Override public void begin() { super.begin(); this.writePointer = this.basePointer; } @Override public void addIndirectDrawCall(int first, int count, int baseInstance, int instanceCount) { if (this.count++ >= this.capacity) { throw new BufferUnderflowException(); } memPutInt(this.writePointer , count); // Vertex Count memPutInt(this.writePointer + 4, instanceCount); // Instance Count memPutInt(this.writePointer + 8, first); // Vertex Start memPutInt(this.writePointer + 12, baseInstance); // Base Instance this.writePointer += this.stride; } } public static class NioChunkDrawCallBatcher extends ChunkDrawCallBatcher { private int writeOffset; public NioChunkDrawCallBatcher(int capacity) { super(capacity); } @Override public void begin() { super.begin(); this.writeOffset = 0; } @Override public void addIndirectDrawCall(int first, int count, int baseInstance, int instanceCount) { ByteBuffer buf = this.buffer; buf.putInt(this.writeOffset , count); // Vertex Count buf.putInt(this.writeOffset + 4, instanceCount); // Instance Count buf.putInt(this.writeOffset + 8, first); // Vertex Start buf.putInt(this.writeOffset + 12, baseInstance); // Base Instance this.writeOffset += this.stride; this.count++; } } public int getArrayLength() { return this.arrayLength; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\backends\multidraw\ChunkDrawParamsVector.java
package me.jellysquid.mods.sodium.client.render.chunk.backends.multidraw; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; import me.jellysquid.mods.sodium.client.SodiumClientMod; import org.lwjgl.MemoryUtil; import java.nio.ByteBuffer; /** * Provides a resizeable vector backed by native memory that can be used to build an array of chunk draw call * parameters. */ public abstract class ChunkDrawParamsVector extends StructBuffer { protected int capacity; protected int count; protected ChunkDrawParamsVector(int capacity) { super(capacity, 16); this.capacity = capacity; } public static ChunkDrawParamsVector create(int capacity) { return SodiumClientMod.isDirectMemoryAccessEnabled() ? new UnsafeChunkDrawCallVector(capacity) : new NioChunkDrawCallVector(capacity); } public abstract void pushChunkDrawParams(float x, float y, float z); public void reset() { this.count = 0; } protected void growBuffer() { this.capacity = this.capacity * 2; this.buffer = memRealloc(this.buffer, this.capacity * this.stride); } public static class UnsafeChunkDrawCallVector extends ChunkDrawParamsVector { private long basePointer; private long writePointer; public UnsafeChunkDrawCallVector(int capacity) { super(capacity); this.basePointer = MemoryUtil.getAddress(this.buffer); } @Override public void pushChunkDrawParams(float x, float y, float z) { if (this.count++ >= this.capacity) { this.growBuffer(); } memPutFloat(this.writePointer , x); memPutFloat(this.writePointer + 4, y); memPutFloat(this.writePointer + 8, z); this.writePointer += this.stride; } @Override protected void growBuffer() { super.growBuffer(); long offset = this.writePointer - this.basePointer; this.basePointer = memAddress(this.buffer); this.writePointer = this.basePointer + offset; } @Override public void reset() { super.reset(); this.writePointer = this.basePointer; } } public static class NioChunkDrawCallVector extends ChunkDrawParamsVector { private int writeOffset; public NioChunkDrawCallVector(int capacity) { super(capacity); } @Override public void pushChunkDrawParams(float x, float y, float z) { if (this.count++ >= this.capacity) { this.growBuffer(); } ByteBuffer buf = this.buffer; buf.putFloat(this.writeOffset , x); buf.putFloat(this.writeOffset + 4, y); buf.putFloat(this.writeOffset + 8, z); this.writeOffset += this.stride; } @Override public void reset() { super.reset(); this.writeOffset = 0; } } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\backends\multidraw\IndirectCommandBufferVector.java
package me.jellysquid.mods.sodium.client.render.chunk.backends.multidraw; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; public class IndirectCommandBufferVector extends StructBuffer { protected IndirectCommandBufferVector(int capacity) { super(capacity, 16); } public static IndirectCommandBufferVector create(int capacity) { return new IndirectCommandBufferVector(capacity); } public void begin() { this.buffer.clear(); } public void end() { if(this.buffer.position() > 0) { this.buffer.flip(); } } public void pushCommandBuffer(ChunkDrawCallBatcher batcher) { int len = batcher.getArrayLength(); if (this.buffer.remaining() < len) { this.growBuffer(len); } this.buffer.put(batcher.getBuffer()); } protected void growBuffer(int n) { this.buffer = memRealloc(this.buffer, Math.max(this.buffer.capacity() * 2, this.buffer.capacity() + n)); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\backends\multidraw\MultidrawChunkRenderBackend.java
package me.jellysquid.mods.sodium.client.render.chunk.backends.multidraw; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import it.unimi.dsi.fastutil.objects.ObjectArrayFIFOQueue; import net.coderbot.iris.Iris; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import lombok.Setter; import me.jellysquid.mods.sodium.client.gl.arena.GlBufferArena; import me.jellysquid.mods.sodium.client.gl.arena.GlBufferSegment; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexAttribute; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexAttributeBinding; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexAttributeFormat; import me.jellysquid.mods.sodium.client.gl.buffer.GlBuffer; import me.jellysquid.mods.sodium.client.gl.buffer.GlBufferTarget; import me.jellysquid.mods.sodium.client.gl.buffer.GlBufferUsage; import me.jellysquid.mods.sodium.client.gl.buffer.GlMutableBuffer; import me.jellysquid.mods.sodium.client.gl.buffer.VertexData; import me.jellysquid.mods.sodium.client.gl.device.CommandList; import me.jellysquid.mods.sodium.client.gl.device.DrawCommandList; import me.jellysquid.mods.sodium.client.gl.device.RenderDevice; import me.jellysquid.mods.sodium.client.gl.func.GlFunctions; import me.jellysquid.mods.sodium.client.gl.tessellation.GlPrimitiveType; import me.jellysquid.mods.sodium.client.gl.tessellation.GlTessellation; import me.jellysquid.mods.sodium.client.gl.tessellation.TessellationBinding; import me.jellysquid.mods.sodium.client.gl.util.BufferSlice; import me.jellysquid.mods.sodium.client.model.vertex.type.ChunkVertexType; import me.jellysquid.mods.sodium.client.render.chunk.ChunkCameraContext; import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderContainer; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildResult; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkMeshData; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderData; import me.jellysquid.mods.sodium.client.render.chunk.format.ChunkMeshAttribute; import me.jellysquid.mods.sodium.client.render.chunk.lists.ChunkRenderListIterator; import me.jellysquid.mods.sodium.client.render.chunk.passes.BlockRenderPass; import me.jellysquid.mods.sodium.client.render.chunk.region.ChunkRegion; import me.jellysquid.mods.sodium.client.render.chunk.region.ChunkRegionManager; import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkRenderShaderBackend; import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkShaderBindingPoints; import net.coderbot.iris.block_rendering.BlockRenderingSettings; import net.coderbot.iris.sodium.IrisChunkShaderBindingPoints; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.Util; import org.lwjgl.opengl.GL11; /** * Shader-based chunk renderer which makes use of a custom memory allocator on top of large buffer objects to allow * for draw call batching without buffer switching. * * The biggest bottleneck after setting up vertex attribute state is the sheer number of buffer switches and draw calls * being performed. In vanilla, the game uses one buffer for every chunk section, which means we need to bind, setup, * and draw every chunk individually. * * In order to reduce the number of these calls, we need to firstly reduce the number of buffer switches. We do this * through sub-dividing the world into larger "chunk regions" which then have one large buffer object in OpenGL. From * here, we can allocate slices of this buffer to each individual chunk and then only bind it once before drawing. Then, * our draw calls can simply point to individual sections within the buffer by manipulating the offset and count * parameters. * * However, an unfortunate consequence is that if we run out of space in a buffer, we need to re-allocate the entire * storage, which can take a ton of time! With old OpenGL 2.1 code, the only way to do this would be to copy the buffer's * memory from the graphics card over the host bus into CPU memory, allocate a new buffer, and then copy it back over * the bus and into graphics card. For reasons that should be obvious, this is extremely inefficient and requires the * CPU and GPU to be synchronized. * * If we make use of more modern OpenGL 3.0 features, we can avoid this transfer over the memory bus and instead just * perform the copy between buffers in GPU memory with the aptly named "copy buffer" function. It's still not blazing * fast, but it's much better than what we're stuck with in older versions. We can help prevent these re-allocations by * sizing our buffers to be a bit larger than what we expect all the chunk data to be, but this wastes memory. * * In the initial implementation, this solution worked fine enough, but the amount of time being spent on uploading * chunks to the large buffers was now a magnitude more than what it was before all of this and it made chunk updates * *very* slow. It took some tinkering to figure out what was going wrong here, but at least on the NVIDIA drivers, it * seems that updating sub-regions of buffer memory hits some kind of slow path. A workaround for this problem is to * create a scratch buffer object and upload the chunk data there *first*, re-allocating the storage each time. Then, * you can copy the contents of the scratch buffer into the chunk region buffer, rise and repeat. I'm not happy with * this solution, but it performs surprisingly well across all hardware I tried. * * With both of these changes, the amount of CPU time taken by rendering chunks linearly decreases with the reduction * in buffer bind/setup/draw calls. Using the default settings of 4x2x4 chunk region buffers, the number of calls can be * reduced up to a factor of ~32x. */ public class MultidrawChunkRenderBackend extends ChunkRenderShaderBackend<MultidrawGraphicsState> { private final ChunkRegionManager<MultidrawGraphicsState> bufferManager; private final ObjectArrayList<ChunkRegion<MultidrawGraphicsState>> pendingBatches = new ObjectArrayList<>(); private final ObjectArrayFIFOQueue<ChunkRegion<MultidrawGraphicsState>> pendingUploads = new ObjectArrayFIFOQueue<>(); private final GlMutableBuffer uploadBuffer; private final GlMutableBuffer uniformBuffer; private final GlMutableBuffer commandBuffer; private final ChunkDrawParamsVector uniformBufferBuilder; private final IndirectCommandBufferVector commandClientBufferBuilder; public MultidrawChunkRenderBackend(RenderDevice device, ChunkVertexType vertexType) { super(vertexType); this.bufferManager = new ChunkRegionManager<>(device); try (CommandList commands = device.createCommandList()) { this.uploadBuffer = commands.createMutableBuffer(GlBufferUsage.GL_STREAM_DRAW); this.uniformBuffer = commands.createMutableBuffer(GlBufferUsage.GL_STATIC_DRAW); this.commandBuffer = isWindowsIntelDriver() ? null : commands.createMutableBuffer(GlBufferUsage.GL_STREAM_DRAW); } this.uniformBufferBuilder = ChunkDrawParamsVector.create(2048); this.commandClientBufferBuilder = IndirectCommandBufferVector.create(2048); } @Override public void upload(CommandList commandList, Iterator<ChunkBuildResult<MultidrawGraphicsState>> queue) { if(queue != null) { this.setupUploadBatches(queue); } commandList.bindBuffer(GlBufferTarget.ARRAY_BUFFER, this.uploadBuffer); while (!this.pendingUploads.isEmpty()) { final ChunkRegion<MultidrawGraphicsState> region = this.pendingUploads.dequeue(); final GlBufferArena arena = region.getBufferArena(); final GlBuffer buffer = arena.getBuffer(); final ObjectArrayList<ChunkBuildResult<MultidrawGraphicsState>> uploadQueue = region.getUploadQueue(); arena.prepareBuffer(commandList, getUploadQueuePayloadSize(uploadQueue)); for (ChunkBuildResult<MultidrawGraphicsState> result : uploadQueue) { final ChunkRenderContainer<MultidrawGraphicsState> render = result.render; final ChunkRenderData data = result.data; for (BlockRenderPass pass : result.passesToUpload) { final MultidrawGraphicsState graphics = render.getGraphicsState(pass); // De-allocate the existing buffer arena for this render // This will allow it to be cheaply re-allocated just below if (graphics != null) { graphics.delete(commandList); } final ChunkMeshData meshData = data.getMesh(pass); if (meshData.hasVertexData()) { final VertexData upload = meshData.takeVertexData(); commandList.uploadData(this.uploadBuffer, upload.buffer); final GlBufferSegment segment = arena.uploadBuffer(commandList, this.uploadBuffer, 0, upload.buffer.capacity()); final MultidrawGraphicsState graphicsState = new MultidrawGraphicsState(render, region, segment, meshData, this.vertexFormat); if(pass.isTranslucent()) { upload.buffer.limit(upload.buffer.capacity()); upload.buffer.position(0); graphicsState.setTranslucencyData(upload.buffer); } render.setGraphicsState(pass, graphicsState); } else { render.setGraphicsState(pass, null); } } render.setData(data); } // Check if the tessellation needs to be updated // This happens whenever the backing buffer object for the arena changes, or if it hasn't already been created if (region.getTessellation() == null || buffer != arena.getBuffer()) { if (region.getTessellation() != null) { commandList.deleteTessellation(region.getTessellation()); } region.setTessellation(this.createRegionTessellation(commandList, arena.getBuffer())); } uploadQueue.clear(); } commandList.invalidateBuffer(this.uploadBuffer); } private GlTessellation createRegionTessellation(CommandList commandList, GlBuffer buffer) { return commandList.createTessellation(GlPrimitiveType.QUADS, new TessellationBinding[] { new TessellationBinding(buffer,getBindings(), false), new TessellationBinding(this.uniformBuffer, new GlVertexAttributeBinding[] { new GlVertexAttributeBinding(ChunkShaderBindingPoints.MODEL_OFFSET, new GlVertexAttribute(GlVertexAttributeFormat.FLOAT, 4, false, 0, 0)) }, true) }); } private GlVertexAttributeBinding[] getBindings() { if(Iris.enabled && BlockRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat()) { return new GlVertexAttributeBinding[] { new GlVertexAttributeBinding(ChunkShaderBindingPoints.POSITION, this.vertexFormat.getAttribute(ChunkMeshAttribute.POSITION)), new GlVertexAttributeBinding(ChunkShaderBindingPoints.COLOR, this.vertexFormat.getAttribute(ChunkMeshAttribute.COLOR)), new GlVertexAttributeBinding(ChunkShaderBindingPoints.TEX_COORD, this.vertexFormat.getAttribute(ChunkMeshAttribute.TEXTURE)), new GlVertexAttributeBinding(ChunkShaderBindingPoints.LIGHT_COORD, this.vertexFormat.getAttribute(ChunkMeshAttribute.LIGHT)), new GlVertexAttributeBinding(IrisChunkShaderBindingPoints.NORMAL, vertexFormat.getAttribute(ChunkMeshAttribute.NORMAL)), new GlVertexAttributeBinding(IrisChunkShaderBindingPoints.TANGENT, vertexFormat.getAttribute(ChunkMeshAttribute.TANGENT)), new GlVertexAttributeBinding(IrisChunkShaderBindingPoints.MID_TEX_COORD, vertexFormat.getAttribute(ChunkMeshAttribute.MID_TEX_COORD)), new GlVertexAttributeBinding(IrisChunkShaderBindingPoints.BLOCK_ID, vertexFormat.getAttribute(ChunkMeshAttribute.BLOCK_ID)), new GlVertexAttributeBinding(IrisChunkShaderBindingPoints.MID_BLOCK, vertexFormat.getAttribute(ChunkMeshAttribute.MID_BLOCK)) }; } else { return new GlVertexAttributeBinding[] { new GlVertexAttributeBinding(ChunkShaderBindingPoints.POSITION, this.vertexFormat.getAttribute(ChunkMeshAttribute.POSITION)), new GlVertexAttributeBinding(ChunkShaderBindingPoints.COLOR, this.vertexFormat.getAttribute(ChunkMeshAttribute.COLOR)), new GlVertexAttributeBinding(ChunkShaderBindingPoints.TEX_COORD, this.vertexFormat.getAttribute(ChunkMeshAttribute.TEXTURE)), new GlVertexAttributeBinding(ChunkShaderBindingPoints.LIGHT_COORD, this.vertexFormat.getAttribute(ChunkMeshAttribute.LIGHT)) }; } } /** * -- SETTER -- * Sets whether to reverse the order in which regions are drawn */ @Setter private boolean reverseRegions = false; private ChunkCameraContext regionCamera; @Override public void render(CommandList commandList, ChunkRenderListIterator<MultidrawGraphicsState> renders, ChunkCameraContext camera) { this.bufferManager.cleanup(); this.setupDrawBatches(commandList, renders, camera); this.buildCommandBuffer(); if (this.commandBuffer != null) { commandList.bindBuffer(GlBufferTarget.DRAW_INDIRECT_BUFFER, this.commandBuffer); commandList.uploadData(this.commandBuffer, this.commandClientBufferBuilder.getBuffer()); } long pointer = 0L; ByteBuffer pointerBuffer; int originalPointerBufferPos = 0; if (this.commandBuffer != null) { pointerBuffer = null; } else { pointerBuffer = this.commandClientBufferBuilder.getBuffer(); originalPointerBufferPos = pointerBuffer.position(); } for (ChunkRegion<?> region : this.pendingBatches) { final ChunkDrawCallBatcher batch = region.getDrawBatcher(); if (!batch.isEmpty()) { try (DrawCommandList drawCommandList = commandList.beginTessellating(region.getTessellation())) { if(pointerBuffer == null) { drawCommandList.multiDrawArraysIndirect(pointer, batch.getCount(), 0 /* tightly packed */); } else { drawCommandList.multiDrawArraysIndirect(pointerBuffer, batch.getCount(), 0 /* tightly packed */); } } } if(pointerBuffer == null) { pointer += batch.getArrayLength(); } else { pointerBuffer.position(pointerBuffer.position() + batch.getArrayLength()); } } if (pointerBuffer != null) pointerBuffer.position(originalPointerBufferPos); this.pendingBatches.clear(); } private static final Comparator<ChunkRegion<?>> REGION_REVERSER = Comparator.<ChunkRegion<?>>comparingDouble(r -> r.camDistance).reversed(); private void buildCommandBuffer() { this.commandClientBufferBuilder.begin(); if(this.reverseRegions) { final ChunkCameraContext camera = this.regionCamera; for (ChunkRegion<?> region : this.pendingBatches) { final float x = camera.getChunkModelOffset(region.getCenterBlockX(), camera.blockOriginX, camera.originX); final float y = camera.getChunkModelOffset(region.getCenterBlockY(), camera.blockOriginY, camera.originY); final float z = camera.getChunkModelOffset(region.getCenterBlockZ(), camera.blockOriginZ, camera.originZ); region.camDistance = x * x + y * y + z * z; } this.pendingBatches.sort(REGION_REVERSER); } for (ChunkRegion<?> region : this.pendingBatches) { final ChunkDrawCallBatcher batcher = region.getDrawBatcher(); batcher.end(); this.commandClientBufferBuilder.pushCommandBuffer(batcher); } this.commandClientBufferBuilder.end(); } private void setupUploadBatches(Iterator<ChunkBuildResult<MultidrawGraphicsState>> renders) { while (renders.hasNext()) { final ChunkBuildResult<MultidrawGraphicsState> result = renders.next(); if(result == null) { continue; } final ChunkRenderContainer<MultidrawGraphicsState> render = result.render; ChunkRegion<MultidrawGraphicsState> region = this.bufferManager.getRegion(render.getChunkX(), render.getChunkY(), render.getChunkZ()); if (region == null) { if (result.data.getMeshSize() <= 0) { render.setData(result.data); continue; } region = this.bufferManager.getOrCreateRegion(render.getChunkX(), render.getChunkY(), render.getChunkZ()); } final ObjectArrayList<ChunkBuildResult<MultidrawGraphicsState>> uploadQueue = region.getUploadQueue(); if (uploadQueue.isEmpty()) { this.pendingUploads.enqueue(region); } uploadQueue.add(result); } } private void setupDrawBatches(CommandList commandList, ChunkRenderListIterator<MultidrawGraphicsState> it, ChunkCameraContext camera) { this.uniformBufferBuilder.reset(); this.regionCamera = camera; int drawCount = 0; while (it.hasNext()) { final MultidrawGraphicsState state = it.getGraphicsState(); final int visible = it.getVisibleFaces(); final int index = drawCount++; final float x = camera.getChunkModelOffset(state.getX(), camera.blockOriginX, camera.originX); final float y = camera.getChunkModelOffset(state.getY(), camera.blockOriginY, camera.originY); final float z = camera.getChunkModelOffset(state.getZ(), camera.blockOriginZ, camera.originZ); this.uniformBufferBuilder.pushChunkDrawParams(x, y, z); final ChunkRegion<MultidrawGraphicsState> region = state.getRegion(); final ChunkDrawCallBatcher batch = region.getDrawBatcher(); if (!batch.isBuilding()) { batch.begin(); this.pendingBatches.add(region); } int mask = 0b1; for (int i = 0; i < ModelQuadFacing.COUNT; i++) { if ((visible & mask) != 0) { final long part = state.getModelPart(i); batch.addIndirectDrawCall(BufferSlice.unpackStart(part), BufferSlice.unpackLength(part), index, 1); } mask <<= 1; } it.advance(); } commandList.uploadData(this.uniformBuffer, this.uniformBufferBuilder.getBuffer()); } private static int getUploadQueuePayloadSize(List<ChunkBuildResult<MultidrawGraphicsState>> queue) { int size = 0; for (ChunkBuildResult<MultidrawGraphicsState> result : queue) { size += result.data.getMeshSize(); } return size; } @Override public void delete() { super.delete(); try (CommandList commands = RenderDevice.INSTANCE.createCommandList()) { commands.deleteBuffer(this.uploadBuffer); commands.deleteBuffer(this.uniformBuffer); if (this.commandBuffer != null) { commands.deleteBuffer(this.commandBuffer); } } this.bufferManager.delete(); this.commandClientBufferBuilder.delete(); this.uniformBufferBuilder.delete(); } @Override public Class<MultidrawGraphicsState> getGraphicsStateType() { return MultidrawGraphicsState.class; } public static boolean isSupported(boolean disableDriverBlacklist) { if (!disableDriverBlacklist && isKnownBrokenIntelDriver()) { return false; } return GlFunctions.isVertexArraySupported() && GlFunctions.isBufferCopySupported() && GlFunctions.isIndirectMultiDrawSupported() && GlFunctions.isInstancedArraySupported(); } // https://www.intel.com/content/www/us/en/support/articles/000005654/graphics.html private static final Pattern INTEL_BUILD_MATCHER = Pattern.compile("(\\d.\\d.\\d) - Build (\\d+).(\\d+).(\\d+).(\\d+)"); private static final String INTEL_VENDOR_NAME = "Intel"; /** * Determines whether or not the current OpenGL renderer is an integrated Intel GPU on Windows. * These drivers on Windows are known to fail when using command buffers. */ private static boolean isWindowsIntelDriver() { // We only care about Windows // The open-source drivers on Linux are not known to have driver bugs with indirect command buffers if (Util.getOSType() != Util.EnumOS.WINDOWS) { return false; } // Check to see if the GPU vendor is Intel return Objects.equals(GL11.glGetString(GL11.GL_VENDOR), INTEL_VENDOR_NAME); } /** * Determines whether or not the current OpenGL renderer is an old integrated Intel GPU (prior to Skylake/Gen8) on * Windows. These drivers on Windows are unsupported and known to create significant trouble with the multi-draw * renderer. */ private static boolean isKnownBrokenIntelDriver() { if (!isWindowsIntelDriver()) { return false; } final String version = GL11.glGetString(GL11.GL_VERSION); // The returned version string may be null in the case of an error if (version == null) { return false; } final Matcher matcher = INTEL_BUILD_MATCHER.matcher(version); // If the version pattern doesn't match, assume we're dealing with something special if (!matcher.matches()) { return false; } // Anything with a major build of >=100 is GPU Gen8 or newer // The fourth group is the major build number return Integer.parseInt(matcher.group(4)) < 100; } @Override public String getRendererName() { return "Multidraw"; } @Override public List<String> getDebugStrings() { final List<String> list = new ArrayList<>(); list.add(String.format("Active Buffers: %s", this.bufferManager.getAllocatedRegionCount())); list.add(String.format("Submission Mode: %s", this.commandBuffer != null ? EnumChatFormatting.AQUA + "Buffer" : EnumChatFormatting.LIGHT_PURPLE + "Client Memory")); return list; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\backends\multidraw\MultidrawGraphicsState.java
package me.jellysquid.mods.sodium.client.render.chunk.backends.multidraw; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import me.jellysquid.mods.sodium.client.gl.arena.GlBufferSegment; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexFormat; import me.jellysquid.mods.sodium.client.gl.device.CommandList; import me.jellysquid.mods.sodium.client.gl.util.BufferSlice; import me.jellysquid.mods.sodium.client.render.chunk.ChunkGraphicsState; import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderContainer; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkMeshData; import me.jellysquid.mods.sodium.client.render.chunk.region.ChunkRegion; import java.util.Map; public class MultidrawGraphicsState extends ChunkGraphicsState { private final ChunkRegion<MultidrawGraphicsState> region; private final GlBufferSegment segment; private final long[] parts; public MultidrawGraphicsState(ChunkRenderContainer<?> container, ChunkRegion<MultidrawGraphicsState> region, GlBufferSegment segment, ChunkMeshData meshData, GlVertexFormat<?> vertexFormat) { super(container); this.region = region; this.segment = segment; this.parts = new long[ModelQuadFacing.COUNT]; for (Map.Entry<ModelQuadFacing, BufferSlice> entry : meshData.getSlices()) { ModelQuadFacing facing = entry.getKey(); BufferSlice slice = entry.getValue(); int start = (segment.getStart() + slice.start) / vertexFormat.getStride(); int count = slice.len / vertexFormat.getStride(); this.parts[facing.ordinal()] = BufferSlice.pack(start, count); } } @Override public void delete(CommandList commandList) { this.segment.delete(); } public ChunkRegion<MultidrawGraphicsState> getRegion() { return this.region; } public long getModelPart(int facing) { return this.parts[facing]; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\backends\multidraw\StructBuffer.java
package me.jellysquid.mods.sodium.client.render.chunk.backends.multidraw; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; import java.nio.ByteBuffer; public abstract class StructBuffer { protected ByteBuffer buffer; protected final int stride; protected StructBuffer(int bytes, int stride) { this.buffer = memAlloc(bytes * stride); this.stride = stride; } public ByteBuffer getBuffer() { return this.buffer; } public long getBufferAddress() { return memAddress(this.buffer); } public void delete() { // no-op, because Java direct buffers free themselves } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\backends\oneshot\ChunkOneshotGraphicsState.java
package me.jellysquid.mods.sodium.client.render.chunk.backends.oneshot; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexAttributeBinding; import net.coderbot.iris.Iris; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexFormat; import me.jellysquid.mods.sodium.client.gl.buffer.GlBufferUsage; import me.jellysquid.mods.sodium.client.gl.buffer.GlMutableBuffer; import me.jellysquid.mods.sodium.client.gl.buffer.VertexData; import me.jellysquid.mods.sodium.client.gl.device.CommandList; import me.jellysquid.mods.sodium.client.gl.device.RenderDevice; import me.jellysquid.mods.sodium.client.gl.tessellation.GlPrimitiveType; import me.jellysquid.mods.sodium.client.gl.tessellation.GlTessellation; import me.jellysquid.mods.sodium.client.gl.tessellation.TessellationBinding; import me.jellysquid.mods.sodium.client.gl.util.BufferSlice; import me.jellysquid.mods.sodium.client.render.chunk.ChunkGraphicsState; import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderContainer; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkMeshData; import me.jellysquid.mods.sodium.client.render.chunk.format.ChunkMeshAttribute; import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkShaderBindingPoints; import net.coderbot.iris.block_rendering.BlockRenderingSettings; import net.coderbot.iris.sodium.IrisChunkShaderBindingPoints; import java.util.Arrays; import java.util.Map; public class ChunkOneshotGraphicsState extends ChunkGraphicsState { private final GlMutableBuffer vertexBuffer; protected GlTessellation tessellation; private final long[] parts; protected ChunkOneshotGraphicsState(RenderDevice device, ChunkRenderContainer<?> container) { super(container); this.parts = new long[ModelQuadFacing.COUNT]; try (CommandList commands = device.createCommandList()) { this.vertexBuffer = commands.createMutableBuffer(GlBufferUsage.GL_STATIC_DRAW); } } public long getModelPart(int facing) { return this.parts[facing]; } protected void setModelPart(ModelQuadFacing facing, long slice) { this.parts[facing.ordinal()] = slice; } protected void setupModelParts(ChunkMeshData meshData, GlVertexFormat<?> vertexFormat) { int stride = vertexFormat.getStride(); Arrays.fill(this.parts, 0L); for (Map.Entry<ModelQuadFacing, BufferSlice> entry : meshData.getSlices()) { ModelQuadFacing facing = entry.getKey(); BufferSlice slice = entry.getValue(); this.setModelPart(facing, BufferSlice.pack(slice.start / stride, slice.len / stride)); } } @Override public void delete(CommandList commandList) { commandList.deleteBuffer(this.vertexBuffer); } public void upload(CommandList commandList, ChunkMeshData meshData) { VertexData vertexData = meshData.takeVertexData(); commandList.uploadData(this.vertexBuffer, vertexData); @SuppressWarnings("unchecked") GlVertexFormat<ChunkMeshAttribute> vertexFormat = (GlVertexFormat<ChunkMeshAttribute>) vertexData.format; this.tessellation = commandList.createTessellation(GlPrimitiveType.QUADS, new TessellationBinding[] { new TessellationBinding(this.vertexBuffer, getBindings(vertexFormat), false) }); this.setupModelParts(meshData, vertexData.format); vertexData.buffer.limit(vertexData.buffer.capacity()); vertexData.buffer.position(0); this.setTranslucencyData(vertexData.buffer); } private GlVertexAttributeBinding[] getBindings(GlVertexFormat<ChunkMeshAttribute> vertexFormat) { if(Iris.enabled && BlockRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat()) { return new GlVertexAttributeBinding[] { new GlVertexAttributeBinding(ChunkShaderBindingPoints.POSITION, vertexFormat.getAttribute(ChunkMeshAttribute.POSITION)), new GlVertexAttributeBinding(ChunkShaderBindingPoints.COLOR, vertexFormat.getAttribute(ChunkMeshAttribute.COLOR)), new GlVertexAttributeBinding(ChunkShaderBindingPoints.TEX_COORD, vertexFormat.getAttribute(ChunkMeshAttribute.TEXTURE)), new GlVertexAttributeBinding(ChunkShaderBindingPoints.LIGHT_COORD, vertexFormat.getAttribute(ChunkMeshAttribute.LIGHT)), new GlVertexAttributeBinding(IrisChunkShaderBindingPoints.BLOCK_ID, vertexFormat.getAttribute(ChunkMeshAttribute.BLOCK_ID)), new GlVertexAttributeBinding(IrisChunkShaderBindingPoints.MID_TEX_COORD, vertexFormat.getAttribute(ChunkMeshAttribute.MID_TEX_COORD)), new GlVertexAttributeBinding(IrisChunkShaderBindingPoints.TANGENT, vertexFormat.getAttribute(ChunkMeshAttribute.TANGENT)), new GlVertexAttributeBinding(IrisChunkShaderBindingPoints.NORMAL, vertexFormat.getAttribute(ChunkMeshAttribute.NORMAL)) }; } else { return new GlVertexAttributeBinding[] { new GlVertexAttributeBinding(ChunkShaderBindingPoints.POSITION, vertexFormat.getAttribute(ChunkMeshAttribute.POSITION)), new GlVertexAttributeBinding(ChunkShaderBindingPoints.COLOR, vertexFormat.getAttribute(ChunkMeshAttribute.COLOR)), new GlVertexAttributeBinding(ChunkShaderBindingPoints.TEX_COORD, vertexFormat.getAttribute(ChunkMeshAttribute.TEXTURE)), new GlVertexAttributeBinding(ChunkShaderBindingPoints.LIGHT_COORD, vertexFormat.getAttribute(ChunkMeshAttribute.LIGHT)) }; } } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\backends\oneshot\ChunkRenderBackendOneshot.java
package me.jellysquid.mods.sodium.client.render.chunk.backends.oneshot; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import me.jellysquid.mods.sodium.client.gl.device.CommandList; import me.jellysquid.mods.sodium.client.gl.device.DrawCommandList; import me.jellysquid.mods.sodium.client.gl.device.RenderDevice; import me.jellysquid.mods.sodium.client.gl.util.BufferSlice; import me.jellysquid.mods.sodium.client.gl.util.GlMultiDrawBatch; import me.jellysquid.mods.sodium.client.model.vertex.type.ChunkVertexType; import me.jellysquid.mods.sodium.client.render.chunk.ChunkCameraContext; import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderContainer; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildResult; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkMeshData; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderData; import me.jellysquid.mods.sodium.client.render.chunk.lists.ChunkRenderListIterator; import me.jellysquid.mods.sodium.client.render.chunk.passes.BlockRenderPass; import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkRenderShaderBackend; import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkShaderBindingPoints; import org.lwjgl.opengl.GL20; import java.util.Iterator; public class ChunkRenderBackendOneshot extends ChunkRenderShaderBackend<ChunkOneshotGraphicsState> { private final GlMultiDrawBatch batch = new GlMultiDrawBatch(ModelQuadFacing.COUNT); public ChunkRenderBackendOneshot(ChunkVertexType vertexType) { super(vertexType); } @Override public void upload(CommandList commandList, Iterator<ChunkBuildResult<ChunkOneshotGraphicsState>> queue) { while (queue.hasNext()) { ChunkBuildResult<ChunkOneshotGraphicsState> result = queue.next(); ChunkRenderContainer<ChunkOneshotGraphicsState> render = result.render; ChunkRenderData data = result.data; for (BlockRenderPass pass : result.passesToUpload) { ChunkOneshotGraphicsState state = render.getGraphicsState(pass); ChunkMeshData mesh = data.getMesh(pass); if (mesh.hasVertexData()) { if (state == null) { state = new ChunkOneshotGraphicsState(RenderDevice.INSTANCE, render); } state.upload(commandList, mesh); // For code simplicity, ChunkOneshotGraphicsState stores the buffer unconditionally // Reset it here if the pass isn't translucent, as we don't want to store useless // buffers if(!pass.isTranslucent()) state.setTranslucencyData(null); } else { if (state != null) { state.delete(commandList); } state = null; } render.setGraphicsState(pass, state); } render.setData(data); } } @Override public void render(CommandList commandList, ChunkRenderListIterator<ChunkOneshotGraphicsState> it, ChunkCameraContext camera) { while (it.hasNext()) { ChunkOneshotGraphicsState state = it.getGraphicsState(); int visibleFaces = it.getVisibleFaces(); this.buildBatch(state, visibleFaces); if (this.batch.isBuilding()) { this.prepareDrawBatch(camera, state); this.drawBatch(commandList, state); } it.advance(); } } protected void prepareDrawBatch(ChunkCameraContext camera, ChunkOneshotGraphicsState state) { final float modelX = camera.getChunkModelOffset(state.getX(), camera.blockOriginX, camera.originX); final float modelY = camera.getChunkModelOffset(state.getY(), camera.blockOriginY, camera.originY); final float modelZ = camera.getChunkModelOffset(state.getZ(), camera.blockOriginZ, camera.originZ); GL20.glVertexAttrib4f(ChunkShaderBindingPoints.MODEL_OFFSET.getGenericAttributeIndex(), modelX, modelY, modelZ, 0.0F); } protected void buildBatch(ChunkOneshotGraphicsState state, int visibleFaces) { GlMultiDrawBatch batch = this.batch; batch.begin(); for (int i = 0; i < ModelQuadFacing.COUNT; i++) { if ((visibleFaces & (1 << i)) == 0) { continue; } long part = state.getModelPart(i); batch.addChunkRender(BufferSlice.unpackStart(part), BufferSlice.unpackLength(part)); } } protected void drawBatch(CommandList commandList, ChunkOneshotGraphicsState state) { this.batch.end(); if (!batch.isEmpty()) { try (DrawCommandList drawCommandList = commandList.beginTessellating(state.tessellation)) { drawCommandList.multiDrawArrays(this.batch.getIndicesBuffer(), this.batch.getLengthBuffer()); } } } @Override public void delete() { super.delete(); this.batch.delete(); } @Override public Class<ChunkOneshotGraphicsState> getGraphicsStateType() { return ChunkOneshotGraphicsState.class; } @Override public String getRendererName() { return "Oneshot"; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\compile\buffers\BakedChunkModelBuffers.java
package me.jellysquid.mods.sodium.client.render.chunk.compile.buffers; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderData; import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink; public class BakedChunkModelBuffers implements ChunkModelBuffers { private final ModelVertexSink[] builders; private final ChunkRenderData.Builder renderData; public BakedChunkModelBuffers(ModelVertexSink[] builders, ChunkRenderData.Builder renderData) { this.builders = builders; this.renderData = renderData; } @Override public ModelVertexSink getSink(ModelQuadFacing facing) { return this.builders[facing.ordinal()]; } @Override public ChunkRenderData.Builder getRenderData() { return this.renderData; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\compile\buffers\ChunkModelBuffers.java
package me.jellysquid.mods.sodium.client.render.chunk.compile.buffers; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderData; import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink; public interface ChunkModelBuffers { ModelVertexSink getSink(ModelQuadFacing facing); @Deprecated ChunkRenderData.Builder getRenderData(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\compile\buffers\ChunkModelVertexTransformer.java
package me.jellysquid.mods.sodium.client.render.chunk.compile.buffers; import me.jellysquid.mods.sodium.client.model.vertex.transformers.AbstractVertexTransformer; import me.jellysquid.mods.sodium.client.render.chunk.format.ChunkModelOffset; import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink; public class ChunkModelVertexTransformer extends AbstractVertexTransformer<ModelVertexSink> implements ModelVertexSink { /** * The translation to be applied to all quads written into this mesh builder. */ private final ChunkModelOffset offset; public ChunkModelVertexTransformer(ModelVertexSink delegate, ChunkModelOffset offset) { super(delegate); this.offset = offset; } @Override public void writeQuad(float x, float y, float z, int color, float u, float v, int light, int shaderBlockId) { this.delegate.writeQuad(x + this.offset.x, y + this.offset.y, z + this.offset.z, color, u, v, light, shaderBlockId); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\compile\buffers\FallbackChunkModelBuffers.java
package me.jellysquid.mods.sodium.client.render.chunk.compile.buffers; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.properties.ModelQuadFacing; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderData; import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink; public class FallbackChunkModelBuffers implements ChunkModelBuffers { public FallbackChunkModelBuffers() { } @Override public ModelVertexSink getSink(ModelQuadFacing facing) { return null; } @Override public ChunkRenderData.Builder getRenderData() { return null; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\cull\graph\ChunkGraphCuller.java
package me.jellysquid.mods.sodium.client.render.chunk.cull.graph; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import com.gtnewhorizons.angelica.compat.mojang.Camera; import com.gtnewhorizons.angelica.compat.mojang.ChunkOcclusionData; import com.gtnewhorizons.angelica.compat.mojang.ChunkSectionPos; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import me.jellysquid.mods.sodium.client.render.chunk.cull.ChunkCuller; import me.jellysquid.mods.sodium.client.util.math.FrustumExtended; import net.minecraft.block.Block; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class ChunkGraphCuller implements ChunkCuller { private final Long2ObjectMap<ChunkGraphNode> nodes = new Long2ObjectOpenHashMap<>(); private final ChunkGraphIterationQueue visible = new ChunkGraphIterationQueue(); private final World world; private final int renderDistance; private FrustumExtended frustum; private boolean useOcclusionCulling; private int activeFrame = 0; private int centerChunkX, centerChunkZ; public ChunkGraphCuller(World world, int renderDistance) { this.world = world; this.renderDistance = renderDistance; } @Override public IntArrayList computeVisible(Camera camera, FrustumExtended frustum, int frame, boolean spectator) { this.initSearch(camera, frustum, frame, spectator); ChunkGraphIterationQueue queue = this.visible; for (int i = 0; i < queue.size(); i++) { ChunkGraphNode node = queue.getNode(i); short cullData = node.computeQueuePop(); for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { if (useOcclusionCulling && (cullData & (1 << dir.ordinal())) == 0) { continue; } ChunkGraphNode adj = node.getConnectedNode(dir); if (adj != null && this.isWithinRenderDistance(adj)) { this.bfsEnqueue(node, adj, dir.getOpposite(), cullData); } } } return this.visible.getOrderedIdList(); } private boolean isWithinRenderDistance(ChunkGraphNode adj) { int x = Math.abs(adj.getChunkX() - this.centerChunkX); int z = Math.abs(adj.getChunkZ() - this.centerChunkZ); return x <= this.renderDistance && z <= this.renderDistance; } private void initSearch(Camera camera, FrustumExtended frustum, int frame, boolean spectator) { this.activeFrame = frame; this.frustum = frustum; this.useOcclusionCulling = true; this.visible.clear(); final BlockPos origin = camera.getBlockPos(); final int chunkX = origin.getX() >> 4; int chunkY = origin.getY() >> 4; final int chunkZ = origin.getZ() >> 4; this.centerChunkX = chunkX; this.centerChunkZ = chunkZ; final ChunkGraphNode rootNode = this.getNode(chunkX, chunkY, chunkZ); if (rootNode != null) { rootNode.resetCullingState(); rootNode.setLastVisibleFrame(frame); if (spectator) { final Block block = this.world.getBlock(origin.getX(), origin.getY(), origin.getZ()); if(block.isOpaqueCube()) { this.useOcclusionCulling = false; } } this.visible.add(rootNode); } else { chunkY = MathHelper.clamp_int(origin.getY() >> 4, 0, 15); final List<ChunkGraphNode> bestNodes = new ArrayList<>(); for (int x2 = -this.renderDistance; x2 <= this.renderDistance; ++x2) { for (int z2 = -this.renderDistance; z2 <= this.renderDistance; ++z2) { final ChunkGraphNode node = this.getNode(chunkX + x2, chunkY, chunkZ + z2); if (node == null || node.isCulledByFrustum(frustum)) { continue; } node.resetCullingState(); node.setLastVisibleFrame(frame); bestNodes.add(node); } } bestNodes.sort(Comparator.comparingDouble(node -> node.getSquaredDistance(origin))); for (ChunkGraphNode node : bestNodes) { this.visible.add(node); } } } private void bfsEnqueue(ChunkGraphNode parent, ChunkGraphNode node, ForgeDirection flow, short parentalData) { if (node.getLastVisibleFrame() == this.activeFrame) { node.updateCullingState(flow, parentalData); return; } node.setLastVisibleFrame(this.activeFrame); if (node.isCulledByFrustum(this.frustum)) { return; } node.setCullingState(parentalData); node.updateCullingState(flow, parentalData); this.visible.add(node); } private void connectNeighborNodes(ChunkGraphNode node) { for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { final ChunkGraphNode adj = this.findAdjacentNode(node, dir); if (adj != null) { adj.setAdjacentNode(dir.getOpposite(), node); } node.setAdjacentNode(dir, adj); } } private void disconnectNeighborNodes(ChunkGraphNode node) { for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { final ChunkGraphNode adj = node.getConnectedNode(dir); if (adj != null) { adj.setAdjacentNode(dir.getOpposite(), null); } node.setAdjacentNode(dir, null); } } private ChunkGraphNode findAdjacentNode(ChunkGraphNode node, ForgeDirection dir) { return this.getNode(node.getChunkX() + dir.offsetX, node.getChunkY() + dir.offsetY, node.getChunkZ() + dir.offsetZ); } private ChunkGraphNode getNode(int x, int y, int z) { return this.nodes.get(ChunkSectionPos.asLong(x, y, z)); } @Override public void onSectionStateChanged(int x, int y, int z, ChunkOcclusionData occlusionData) { ChunkGraphNode node = this.getNode(x, y, z); if (node != null) { node.setOcclusionData(occlusionData); } } @Override public void onSectionLoaded(int x, int y, int z, int id) { final ChunkGraphNode node = new ChunkGraphNode(x, y, z, id); final ChunkGraphNode prev; if ((prev = this.nodes.put(ChunkSectionPos.asLong(x, y, z), node)) != null) { this.disconnectNeighborNodes(prev); } this.connectNeighborNodes(node); } @Override public void onSectionUnloaded(int x, int y, int z) { final ChunkGraphNode node = this.nodes.remove(ChunkSectionPos.asLong(x, y, z)); if (node != null) { this.disconnectNeighborNodes(node); } } @Override public boolean isSectionVisible(int x, int y, int z) { final ChunkGraphNode render = this.getNode(x, y, z); if (render == null) { return false; } return render.getLastVisibleFrame() == this.activeFrame; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\cull\graph\ChunkGraphIterationQueue.java
package me.jellysquid.mods.sodium.client.render.chunk.cull.graph; import it.unimi.dsi.fastutil.ints.IntArrayList; import java.util.Arrays; public class ChunkGraphIterationQueue { private int[] positions; private ChunkGraphNode[] nodes; private int pos; private int capacity; public ChunkGraphIterationQueue() { this(4096); } public ChunkGraphIterationQueue(int capacity) { this.positions = new int[capacity]; this.nodes = new ChunkGraphNode[capacity]; this.capacity = capacity; } public void add(ChunkGraphNode node) { int i = this.pos++; if (i == this.capacity) { this.resize(); } this.positions[i] = node.getId(); this.nodes[i] = node; } private void resize() { this.capacity *= 2; this.positions = Arrays.copyOf(this.positions, this.capacity); this.nodes = Arrays.copyOf(this.nodes, this.capacity); } public ChunkGraphNode getNode(int i) { return this.nodes[i]; } public void clear() { this.pos = 0; } public int size() { return this.pos; } public IntArrayList getOrderedIdList() { return IntArrayList.wrap(this.positions, this.pos); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\cull\graph\ChunkGraphNode.java
package me.jellysquid.mods.sodium.client.render.chunk.cull.graph; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import com.gtnewhorizons.angelica.compat.mojang.ChunkOcclusionData; import me.jellysquid.mods.sodium.client.render.chunk.data.ChunkRenderData; import me.jellysquid.mods.sodium.client.util.math.FrustumExtended; import net.minecraftforge.common.util.ForgeDirection; public class ChunkGraphNode { private static final long DEFAULT_VISIBILITY_DATA = calculateVisibilityData(ChunkRenderData.EMPTY.getOcclusionData()); private static final float FRUSTUM_EPSILON = 1.0f /* block model margin */ + 0.125f /* epsilon */; private final ChunkGraphNode[] nodes = new ChunkGraphNode[ForgeDirection.VALID_DIRECTIONS.length]; private final int id; private final int chunkX, chunkY, chunkZ; private int lastVisibleFrame = -1; private long visibilityData; private short cullingState; public ChunkGraphNode(int chunkX, int chunkY, int chunkZ, int id) { this.chunkX = chunkX; this.chunkY = chunkY; this.chunkZ = chunkZ; this.id = id; this.visibilityData = DEFAULT_VISIBILITY_DATA; } public ChunkGraphNode getConnectedNode(ForgeDirection dir) { return this.nodes[dir.ordinal()]; } public void setLastVisibleFrame(int frame) { this.lastVisibleFrame = frame; } public int getLastVisibleFrame() { return this.lastVisibleFrame; } public int getChunkX() { return this.chunkX; } public int getChunkY() { return this.chunkY; } public int getChunkZ() { return this.chunkZ; } public void setAdjacentNode(ForgeDirection dir, ChunkGraphNode node) { this.nodes[dir.ordinal()] = node; } public void setOcclusionData(ChunkOcclusionData occlusionData) { this.visibilityData = calculateVisibilityData(occlusionData); } private static long calculateVisibilityData(ChunkOcclusionData occlusionData) { long visibilityData = 0; for (ForgeDirection from : ForgeDirection.VALID_DIRECTIONS) { for (ForgeDirection to : ForgeDirection.VALID_DIRECTIONS) { if (occlusionData == null || occlusionData.isVisibleThrough(from, to)) { visibilityData |= (1L << ((from.ordinal() << 3) + to.ordinal())); } } } return visibilityData; } //The way this works now is that the culling state contains 2 inner states // visited directions mask, and visitable direction mask //On graph start, the root node(s) have the visit and visitable masks set to all visible // when a chunk section is popped off the queue, the visited direction mask is anded with the // visitable direction mask to return a bitfield containing what directions the graph can flow too //When a chunk is visited in the graph the inbound direction is masked off from the visited direction mask // and the visitable direction mask is updated (ored) with the visibilityData of the inbound direction //When a chunk hasnt been visited before, it uses the parents data as the initial visited direction mask public short computeQueuePop() { short retVal = (short) (cullingState & (((cullingState >> 8) & 0xFF) | 0xFF00)); cullingState = 0; return retVal; } public void updateCullingState(ForgeDirection flow, short parent) { int inbound = flow.ordinal(); this.cullingState |= (visibilityData >> (inbound<<3)) & 0xFF; this.cullingState &= ~(1 << (inbound + 8)); //NOTE: this isnt strictly needed, due to the properties provided from the bfs search (never backtracking), // but just incase/better readability/understandability this.cullingState &= parent|0x00FF; } public void setCullingState(short parent) { this.cullingState = (short) (parent & 0xFF00); } public void resetCullingState() { this.cullingState = -1; } public int getId() { return this.id; } public boolean isCulledByFrustum(FrustumExtended frustum) { float x = this.getOriginX(); float y = this.getOriginY(); float z = this.getOriginZ(); return !frustum.fastAabbTest(x - FRUSTUM_EPSILON, y - FRUSTUM_EPSILON, z - FRUSTUM_EPSILON, x + 16.0f + FRUSTUM_EPSILON, y + 16.0f + FRUSTUM_EPSILON, z + 16.0f + FRUSTUM_EPSILON); } /** * @return The x-coordinate of the origin position of this chunk render */ public int getOriginX() { return this.chunkX << 4; } /** * @return The y-coordinate of the origin position of this chunk render */ public int getOriginY() { return this.chunkY << 4; } /** * @return The z-coordinate of the origin position of this chunk render */ public int getOriginZ() { return this.chunkZ << 4; } /** * @return The squared distance from the center of this chunk in the world to the center of the block position * given by {@param pos} */ public double getSquaredDistance(BlockPos pos) { return this.getSquaredDistance(pos.x + 0.5D, pos.y + 0.5D, pos.z + 0.5D); } /** * @return The x-coordinate of the center position of this chunk render */ private double getCenterX() { return this.getOriginX() + 8.0D; } /** * @return The y-coordinate of the center position of this chunk render */ private double getCenterY() { return this.getOriginY() + 8.0D; } /** * @return The z-coordinate of the center position of this chunk render */ private double getCenterZ() { return this.getOriginZ() + 8.0D; } /** * @return The squared distance from the center of this chunk in the world to the given position */ public double getSquaredDistance(double x, double y, double z) { double xDist = x - this.getCenterX(); double yDist = y - this.getCenterY(); double zDist = z - this.getCenterZ(); return (xDist * xDist) + (yDist * yDist) + (zDist * zDist); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\format\hfp\HFPModelVertexBufferWriterNio.java
package me.jellysquid.mods.sodium.client.render.chunk.format.hfp; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferWriterNio; import me.jellysquid.mods.sodium.client.render.chunk.format.DefaultModelVertexFormats; import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink; import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexUtil; import java.nio.ByteBuffer; public class HFPModelVertexBufferWriterNio extends VertexBufferWriterNio implements ModelVertexSink { public HFPModelVertexBufferWriterNio(VertexBufferView backingBuffer) { super(backingBuffer, DefaultModelVertexFormats.MODEL_VERTEX_HFP); } @Override public void writeQuad(float x, float y, float z, int color, float u, float v, int light, int shaderBlockId) { this.writeQuadInternal( ModelVertexUtil.denormalizeVertexPositionFloatAsShort(x), ModelVertexUtil.denormalizeVertexPositionFloatAsShort(y), ModelVertexUtil.denormalizeVertexPositionFloatAsShort(z), color, ModelVertexUtil.denormalizeVertexTextureFloatAsShort(u), ModelVertexUtil.denormalizeVertexTextureFloatAsShort(v), ModelVertexUtil.encodeLightMapTexCoord(light) ); } private void writeQuadInternal(short x, short y, short z, int color, short u, short v, int light) { final int i = this.writeOffset; final ByteBuffer buffer = this.byteBuffer; buffer.putShort(i, x); buffer.putShort(i + 2, y); buffer.putShort(i + 4, z); buffer.putInt(i + 8, color); buffer.putShort(i + 12, u); buffer.putShort(i + 14, v); buffer.putInt(i + 16, light); this.advance(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\format\hfp\HFPModelVertexBufferWriterUnsafe.java
package me.jellysquid.mods.sodium.client.render.chunk.format.hfp; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferWriterUnsafe; import me.jellysquid.mods.sodium.client.render.chunk.format.DefaultModelVertexFormats; import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink; import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexUtil; public class HFPModelVertexBufferWriterUnsafe extends VertexBufferWriterUnsafe implements ModelVertexSink { public HFPModelVertexBufferWriterUnsafe(VertexBufferView backingBuffer) { super(backingBuffer, DefaultModelVertexFormats.MODEL_VERTEX_HFP); } @Override public void writeQuad(float x, float y, float z, int color, float u, float v, int light, int shaderBlockId) { this.writeQuadInternal( ModelVertexUtil.denormalizeVertexPositionFloatAsShort(x), ModelVertexUtil.denormalizeVertexPositionFloatAsShort(y), ModelVertexUtil.denormalizeVertexPositionFloatAsShort(z), color, ModelVertexUtil.denormalizeVertexTextureFloatAsShort(u), ModelVertexUtil.denormalizeVertexTextureFloatAsShort(v), ModelVertexUtil.encodeLightMapTexCoord(light) ); } private void writeQuadInternal(short x, short y, short z, int color, short u, short v, int light) { long i = this.writePointer; memPutShort(i, x); memPutShort(i + 2, y); memPutShort(i + 4, z); memPutInt(i + 8, color); memPutShort(i + 12, u); memPutShort(i + 14, v); memPutInt(i + 16, light); this.advance(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\format\hfp\HFPModelVertexType.java
package me.jellysquid.mods.sodium.client.render.chunk.format.hfp; import com.gtnewhorizons.angelica.compat.toremove.VertexConsumer; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexAttributeFormat; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexFormat; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.type.BlittableVertexType; import me.jellysquid.mods.sodium.client.model.vertex.type.ChunkVertexType; import me.jellysquid.mods.sodium.client.render.chunk.format.ChunkMeshAttribute; import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink; /** * Uses half-precision floating point numbers to represent position coordinates and normalized unsigned shorts for * texture coordinates. All texel positions in the block diffuse texture atlas can be exactly mapped (including * their centering offset). */ public class HFPModelVertexType implements ChunkVertexType { public static final int STRIDE = 20; public static final GlVertexFormat<ChunkMeshAttribute> VERTEX_FORMAT = GlVertexFormat.builder(ChunkMeshAttribute.class, STRIDE) .addElement(ChunkMeshAttribute.POSITION, 0, GlVertexAttributeFormat.UNSIGNED_SHORT, 3, false) .addElement(ChunkMeshAttribute.COLOR, 8, GlVertexAttributeFormat.UNSIGNED_BYTE, 4, true) .addElement(ChunkMeshAttribute.TEXTURE, 12, GlVertexAttributeFormat.UNSIGNED_SHORT, 2, false) .addElement(ChunkMeshAttribute.LIGHT, 16, GlVertexAttributeFormat.UNSIGNED_SHORT, 2, true) .build(); public static final float MODEL_SCALE = (32.0f / 65536.0f); public static final float TEXTURE_SCALE = (1.0f / 32768.0f); @Override public ModelVertexSink createFallbackWriter(VertexConsumer consumer) { throw new UnsupportedOperationException(); } @Override public ModelVertexSink createBufferWriter(VertexBufferView buffer, boolean direct) { return direct ? new HFPModelVertexBufferWriterUnsafe(buffer) : new HFPModelVertexBufferWriterNio(buffer); } @Override public BlittableVertexType<ModelVertexSink> asBlittable() { return this; } @Override public GlVertexFormat<ChunkMeshAttribute> getCustomVertexFormat() { return VERTEX_FORMAT; } @Override public float getModelScale() { return MODEL_SCALE; } @Override public float getTextureScale() { return TEXTURE_SCALE; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\format\sfp\SFPModelVertexBufferWriterNio.java
package me.jellysquid.mods.sodium.client.render.chunk.format.sfp; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferWriterNio; import me.jellysquid.mods.sodium.client.render.chunk.format.DefaultModelVertexFormats; import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink; import java.nio.ByteBuffer; public class SFPModelVertexBufferWriterNio extends VertexBufferWriterNio implements ModelVertexSink { public SFPModelVertexBufferWriterNio(VertexBufferView backingBuffer) { super(backingBuffer, DefaultModelVertexFormats.MODEL_VERTEX_SFP); } @Override public void writeQuad(float x, float y, float z, int color, float u, float v, int light, int shaderBlockId) { int i = this.writeOffset; ByteBuffer buffer = this.byteBuffer; buffer.putFloat(i, x); buffer.putFloat(i + 4, y); buffer.putFloat(i + 8, z); buffer.putInt(i + 12, color); buffer.putFloat(i + 16, u); buffer.putFloat(i + 20, v); buffer.putInt(i + 24, encodeLightMapTexCoord(light)); this.advance(); } /** * This moves some work out the shader code and simplifies things a bit. In vanilla, the game encodes light map * texture coordinates as two un-normalized unsigned shorts in the range 0..255. Using the fixed-function pipeline, * it then applies a matrix transformation which normalizes these coordinates and applies a centering offset. This * operation has non-zero overhead and complicates shader code a bit. * * To work around the problem, this function instead normalizes these light map texture coordinates and applies the * centering offset, allowing it to be baked into the vertex data itself. * * @param light The light map value * @return The light map texture coordinates as two unsigned shorts with a center offset applied */ private static int encodeLightMapTexCoord(int light) { int sl = (light >> 16) & 255; sl = (sl << 8) + 2048; int bl = light & 255; bl = (bl << 8) + 2048; return (sl << 16) | bl; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\format\sfp\SFPModelVertexBufferWriterUnsafe.java
package me.jellysquid.mods.sodium.client.render.chunk.format.sfp; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferWriterUnsafe; import me.jellysquid.mods.sodium.client.render.chunk.format.DefaultModelVertexFormats; import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink; public class SFPModelVertexBufferWriterUnsafe extends VertexBufferWriterUnsafe implements ModelVertexSink { public SFPModelVertexBufferWriterUnsafe(VertexBufferView backingBuffer) { super(backingBuffer, DefaultModelVertexFormats.MODEL_VERTEX_SFP); } @Override public void writeQuad(float x, float y, float z, int color, float u, float v, int light, int shaderBlockId) { long i = this.writePointer; memPutFloat(i, x); memPutFloat(i + 4, y); memPutFloat(i + 8, z); memPutInt(i + 12, color); memPutFloat(i + 16, u); memPutFloat(i + 20, v); memPutInt(i + 24, encodeLightMapTexCoord(light)); this.advance(); } /** * This moves some work out the shader code and simplifies things a bit. In vanilla, the game encodes light map * texture coordinates as two un-normalized unsigned shorts in the range 0..255. Using the fixed-function pipeline, * it then applies a matrix transformation which normalizes these coordinates and applies a centering offset. This * operation has non-zero overhead and complicates shader code a bit. * * To work around the problem, this function instead normalizes these light map texture coordinates and applies the * centering offset, allowing it to be baked into the vertex data itself. * * @param light The light map value * @return The light map texture coordinates as two unsigned shorts with a center offset applied */ private static int encodeLightMapTexCoord(int light) { int sl = (light >> 16) & 255; sl = (sl << 8) + 2048; int bl = light & 255; bl = (bl << 8) + 2048; return (sl << 16) | bl; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\chunk\format\sfp\SFPModelVertexType.java
package me.jellysquid.mods.sodium.client.render.chunk.format.sfp; import com.gtnewhorizons.angelica.compat.toremove.VertexConsumer; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexAttributeFormat; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexFormat; import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView; import me.jellysquid.mods.sodium.client.model.vertex.type.BlittableVertexType; import me.jellysquid.mods.sodium.client.model.vertex.type.ChunkVertexType; import me.jellysquid.mods.sodium.client.render.chunk.format.ChunkMeshAttribute; import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink; /** * Simple vertex format which uses single-precision floating point numbers to represent position and texture * coordinates. */ public class SFPModelVertexType implements ChunkVertexType { public static final GlVertexFormat<ChunkMeshAttribute> VERTEX_FORMAT = GlVertexFormat.builder(ChunkMeshAttribute.class, 32) .addElement(ChunkMeshAttribute.POSITION, 0, GlVertexAttributeFormat.FLOAT, 3, false) .addElement(ChunkMeshAttribute.COLOR, 12, GlVertexAttributeFormat.UNSIGNED_BYTE, 4, true) .addElement(ChunkMeshAttribute.TEXTURE, 16, GlVertexAttributeFormat.FLOAT, 2, false) .addElement(ChunkMeshAttribute.LIGHT, 24, GlVertexAttributeFormat.UNSIGNED_SHORT, 2, true) .build(); public static final float MODEL_SCALE = 1.0f; public static final float TEXTURE_SCALE = 1.0f; @Override public ModelVertexSink createFallbackWriter(VertexConsumer consumer) { throw new UnsupportedOperationException(); } @Override public ModelVertexSink createBufferWriter(VertexBufferView buffer, boolean direct) { return direct ? new SFPModelVertexBufferWriterUnsafe(buffer) : new SFPModelVertexBufferWriterNio(buffer); } @Override public BlittableVertexType<ModelVertexSink> asBlittable() { return this; } @Override public GlVertexFormat<ChunkMeshAttribute> getCustomVertexFormat() { return VERTEX_FORMAT; } @Override public float getModelScale() { return MODEL_SCALE; } @Override public float getTextureScale() { return TEXTURE_SCALE; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\pipeline\context\ChunkRenderCacheLocal.java
package me.jellysquid.mods.sodium.client.render.pipeline.context; import lombok.Getter; import me.jellysquid.mods.sodium.client.model.light.LightPipelineProvider; import me.jellysquid.mods.sodium.client.model.light.cache.ArrayLightDataCache; import me.jellysquid.mods.sodium.client.render.pipeline.BlockRenderer; import me.jellysquid.mods.sodium.client.render.pipeline.ChunkRenderCache; import me.jellysquid.mods.sodium.client.render.pipeline.FluidRenderer; import me.jellysquid.mods.sodium.client.world.WorldSlice; import me.jellysquid.mods.sodium.client.world.cloned.ChunkRenderContext; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; public class ChunkRenderCacheLocal extends ChunkRenderCache { private final ArrayLightDataCache lightDataCache; @Getter private final BlockRenderer blockRenderer; @Getter private final FluidRenderer fluidRenderer; @Getter private final WorldSlice worldSlice; public ChunkRenderCacheLocal(Minecraft client, WorldClient world) { this.worldSlice = new WorldSlice(world); this.lightDataCache = new ArrayLightDataCache(this.worldSlice); final LightPipelineProvider lightPipelineProvider = new LightPipelineProvider(lightDataCache); this.blockRenderer = new BlockRenderer(lightPipelineProvider); this.fluidRenderer = new FluidRenderer(lightPipelineProvider); } public void init(ChunkRenderContext context) { this.lightDataCache.reset(context.getOrigin()); this.worldSlice.copyData(context); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\render\pipeline\context\ChunkRenderCacheShared.java
package me.jellysquid.mods.sodium.client.render.pipeline.context; import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; import me.jellysquid.mods.sodium.client.model.light.LightPipelineProvider; import me.jellysquid.mods.sodium.client.model.light.cache.HashLightDataCache; import me.jellysquid.mods.sodium.client.render.pipeline.BlockRenderer; import me.jellysquid.mods.sodium.client.render.pipeline.ChunkRenderCache; import me.jellysquid.mods.sodium.client.world.WorldSlice; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.world.World; import java.util.Map; public class ChunkRenderCacheShared extends ChunkRenderCache { private static final Map<World, ChunkRenderCacheShared> INSTANCES = new Reference2ObjectOpenHashMap<>(); private final BlockRenderer blockRenderer; private final HashLightDataCache lightCache; private ChunkRenderCacheShared(WorldSlice world) { this.lightCache = new HashLightDataCache(world); LightPipelineProvider lightPipelineProvider = new LightPipelineProvider(this.lightCache); this.blockRenderer = new BlockRenderer(lightPipelineProvider); } public BlockRenderer getBlockRenderer() { return this.blockRenderer; } private void resetCache() { this.lightCache.clearCache(); } public static ChunkRenderCacheShared getInstance(WorldClient world) { ChunkRenderCacheShared instance = INSTANCES.get(world); if (instance == null) { throw new IllegalStateException("No global renderer exists"); } return instance; } public static void destroyRenderContext(WorldClient world) { if (INSTANCES.remove(world) == null) { throw new IllegalStateException("No render context exists for world: " + world); } } public static void createRenderContext(WorldClient world) { if (INSTANCES.containsKey(world)) { throw new IllegalStateException("Render context already exists for world: " + world); } INSTANCES.put(world, new ChunkRenderCacheShared(new WorldSlice(world))); } public static void resetCaches() { for (ChunkRenderCacheShared context : INSTANCES.values()) { context.resetCache(); } } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\util\math\FrustumExtended.java
package me.jellysquid.mods.sodium.client.util.math; public interface FrustumExtended { boolean fastAabbTest(float minX, float minY, float minZ, float maxX, float maxY, float maxZ); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\util\math\Matrix3fExtended.java
package me.jellysquid.mods.sodium.client.util.math; import net.minecraftforge.common.util.ForgeDirection; import org.joml.Vector3f; public interface Matrix3fExtended { /** * Applies the specified rotation to this matrix in-place. * * @param quaternion The quaternion to rotate this matrix by */ // void rotate(Quaternion quaternion); int computeNormal(ForgeDirection dir); float transformVecX(float x, float y, float z); float transformVecY(float x, float y, float z); float transformVecZ(float x, float y, float z); default float transformVecX(Vector3f dir) { return this.transformVecX(dir.x, dir.y, dir.z); } default float transformVecY(Vector3f dir) { return this.transformVecY(dir.x, dir.y, dir.z); } default float transformVecZ(Vector3f dir) { return this.transformVecZ(dir.x, dir.y, dir.z); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\util\math\Matrix4fExtended.java
package me.jellysquid.mods.sodium.client.util.math; public interface Matrix4fExtended { /** * Applies the specified rotation to this matrix in-place. * * @param quaternion The quaternion to rotate this matrix by */ // void rotate(Quaternion quaternion); /** * Applies the specified translation to this matrix in-place. * * @param x The x-component of the translation * @param y The y-component of the translation * @param z The z-component of the translation */ void translate(float x, float y, float z); /** * Applies this matrix transformation to the given input vector, returning the x-component. Avoids the lack of * struct types in Java and allows for allocation-free return. * @param x The x-component of the vector * @param y The y-component of the vector * @param z The z-component of the vector * @return The x-component of the transformed input vector */ float transformVecX(float x, float y, float z); /** * Applies this matrix transformation to the given input vector, returning the y-component. Avoids the lack of * struct types in Java and allows for allocation-free return. * @param x The x-component of the vector * @param y The y-component of the vector * @param z The z-component of the vector * @return The y-component of the transformed input vector */ float transformVecY(float x, float y, float z); /** * Applies this matrix transformation to the given input vector, returning the z-component. Avoids the lack of * struct types in Java and allows for allocation-free return. * @param x The x-component of the vector * @param y The y-component of the vector * @param z The z-component of the vector * @return The z-component of the transformed input vector */ float transformVecZ(float x, float y, float z); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\util\math\MatrixUtil.java
package me.jellysquid.mods.sodium.client.util.math; import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.NormI8; import net.minecraftforge.common.util.ForgeDirection; import org.joml.Matrix3f; import org.joml.Matrix4f; public class MatrixUtil { public static int computeNormal(Matrix3f normalMatrix, ForgeDirection facing) { return ((Matrix3fExtended) (Object) normalMatrix).computeNormal(facing); } public static Matrix4fExtended getExtendedMatrix(Matrix4f matrix) { return (Matrix4fExtended) (Object) matrix; } public static Matrix3fExtended getExtendedMatrix(Matrix3f matrix) { return (Matrix3fExtended) (Object) matrix; } public static int transformPackedNormal(int norm, Matrix3f matrix) { Matrix3fExtended mat = MatrixUtil.getExtendedMatrix(matrix); float normX1 = NormI8.unpackX(norm); float normY1 = NormI8.unpackY(norm); float normZ1 = NormI8.unpackZ(norm); float normX2 = mat.transformVecX(normX1, normY1, normZ1); float normY2 = mat.transformVecY(normX1, normY1, normZ1); float normZ2 = mat.transformVecZ(normX1, normY1, normZ1); return NormI8.pack(normX2, normY2, normZ2); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\util\rand\SplitMixRandom.java
package me.jellysquid.mods.sodium.client.util.rand; import it.unimi.dsi.fastutil.HashCommon; // SplitMixRandom implementation from DSI Utilities, adopted in a minimal implementation to not // import Apache Commons. // // http://xoshiro.di.unimi.it/ public class SplitMixRandom { private static final long PHI = 0x9E3779B97F4A7C15L; private long x; public SplitMixRandom() { this(XoRoShiRoRandom.randomSeed()); } public SplitMixRandom(final long seed) { this.setSeed(seed); } private static long staffordMix13(long z) { z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9L; z = (z ^ (z >>> 27)) * 0x94D049BB133111EBL; return z ^ (z >>> 31); } private static int staffordMix4Upper32(long z) { z = (z ^ (z >>> 33)) * 0x62A9D9ED799705F5L; return (int) (((z ^ (z >>> 28)) * 0xCB24D0A5C88C35B3L) >>> 32); } public long nextLong() { return staffordMix13(this.x += PHI); } public int nextInt() { return staffordMix4Upper32(this.x += PHI); } public int nextInt(final int n) { return (int) this.nextLong(n); } public long nextLong(final long n) { if (n <= 0) { throw new IllegalArgumentException("illegal bound " + n + " (must be positive)"); } long t = staffordMix13(this.x += PHI); final long nMinus1 = n - 1; if ((n & nMinus1) == 0) { return t & nMinus1; } long u = t >>> 1; while (u + nMinus1 - (t = u % n) < 0) { u = staffordMix13(this.x += PHI) >>> 1; } return t; } public double nextDouble() { return (staffordMix13(this.x += PHI) >>> 11) * 0x1.0p-53; } public float nextFloat() { return (staffordMix4Upper32(this.x += PHI) >>> 8) * 0x1.0p-24f; } public boolean nextBoolean() { return staffordMix4Upper32(this.x += PHI) < 0; } public void nextBytes(final byte[] bytes) { int i = bytes.length, n; while (i != 0) { n = Math.min(i, 8); for (long bits = staffordMix13(this.x += PHI); n-- != 0; bits >>= 8) { bytes[--i] = (byte) bits; } } } public void setSeed(final long seed) { this.x = HashCommon.murmurHash3(seed); } public void setState(final long state) { this.x = state; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\util\rand\XoRoShiRoRandom.java
package me.jellysquid.mods.sodium.client.util.rand; import java.util.Random; // XoRoShiRo128** implementation from DSI Utilities, adopted in a minimal implementation to not // import Apache Commons. // // http://xoshiro.di.unimi.it/ public class XoRoShiRoRandom extends Random { private static final long serialVersionUID = 1L; private SplitMixRandom mixer; private long seed = Long.MIN_VALUE; private long p0, p1; // The initialization words for the current seed private long s0, s1; // The current random words private boolean hasSavedState; // True if we can be quickly reseed by using resetting the words private static final SplitMixRandom seedUniquifier = new SplitMixRandom(System.nanoTime()); public static long randomSeed() { final long x; synchronized (XoRoShiRoRandom.seedUniquifier) { x = XoRoShiRoRandom.seedUniquifier.nextLong(); } return x ^ System.nanoTime(); } public XoRoShiRoRandom() { this(XoRoShiRoRandom.randomSeed()); } public XoRoShiRoRandom(final long seed) { this.setSeed(seed); } @Override public long nextLong() { final long s0 = this.s0; long s1 = this.s1; final long result = s0 + s1; s1 ^= s0; this.s0 = Long.rotateLeft(s0, 24) ^ s1 ^ s1 << 16; this.s1 = Long.rotateLeft(s1, 37); return result; } @Override public int nextInt() { return (int) this.nextLong(); } @Override public int nextInt(final int n) { return (int) this.nextLong(n); } public long nextLong(final long n) { if (n <= 0) { throw new IllegalArgumentException("illegal bound " + n + " (must be positive)"); } long t = this.nextLong(); final long nMinus1 = n - 1; // Shortcut for powers of two--high bits if ((n & nMinus1) == 0) { return (t >>> Long.numberOfLeadingZeros(nMinus1)) & nMinus1; } // Rejection-based algorithm to get uniform integers in the general case long u = t >>> 1; while (u + nMinus1 - (t = u % n) < 0) { u = this.nextLong() >>> 1; } return t; } @Override public double nextDouble() { return Double.longBitsToDouble(0x3FFL << 52 | this.nextLong() >>> 12) - 1.0; } @Override public float nextFloat() { return (this.nextLong() >>> 40) * 0x1.0p-24f; } @Override public boolean nextBoolean() { return this.nextLong() < 0; } @Override public void nextBytes(final byte[] bytes) { int i = bytes.length, n; while (i != 0) { n = Math.min(i, 8); for (long bits = this.nextLong(); n-- != 0; bits >>= 8) { bytes[--i] = (byte) bits; } } } @Override public void setSeed(final long seed) { // Restore the previous initial state if the seed hasn't changed // Setting and mixing the seed is expensive, so this saves some CPU cycles if (this.hasSavedState && this.seed == seed) { this.s0 = this.p0; this.s1 = this.p1; } else { SplitMixRandom mixer = this.mixer; // Avoid allocations of SplitMixRandom if (mixer == null) { mixer = this.mixer = new SplitMixRandom(seed); } else { mixer.setSeed(seed); } this.s0 = mixer.nextLong(); this.s1 = mixer.nextLong(); this.p0 = this.s0; this.p1 = this.s1; this.seed = seed; this.hasSavedState = true; } } public XoRoShiRoRandom setSeedAndReturn(final long seed) { this.setSeed(seed); return this; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\util\task\CancellationSource.java
package me.jellysquid.mods.sodium.client.util.task; public interface CancellationSource { boolean isCancelled(); }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\world\cloned\ChunkRenderContext.java
package me.jellysquid.mods.sodium.client.world.cloned; import com.gtnewhorizons.angelica.compat.mojang.ChunkSectionPos; import net.minecraft.world.gen.structure.StructureBoundingBox; public class ChunkRenderContext { private final ChunkSectionPos origin; private final ClonedChunkSection[] sections; private final StructureBoundingBox volume; public ChunkRenderContext(ChunkSectionPos origin, ClonedChunkSection[] sections, StructureBoundingBox volume) { this.origin = origin; this.sections = sections; this.volume = volume; } public ClonedChunkSection[] getSections() { return this.sections; } public ChunkSectionPos getOrigin() { return this.origin; } public StructureBoundingBox getVolume() { return this.volume; } public void releaseResources() { for (ClonedChunkSection section : sections) { if (section != null) { section.getBackingCache().release(section); } } } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\world\cloned\ClonedChunkSection.java
package me.jellysquid.mods.sodium.client.world.cloned; import com.falsepattern.endlessids.mixin.helpers.ChunkBiomeHook; import com.gtnewhorizons.angelica.compat.ExtendedBlockStorageExt; import com.gtnewhorizons.angelica.compat.ModStatus; import com.gtnewhorizons.angelica.compat.mojang.ChunkSectionPos; import it.unimi.dsi.fastutil.shorts.Short2ObjectMap; import it.unimi.dsi.fastutil.shorts.Short2ObjectOpenHashMap; import lombok.Getter; import mega.fluidlogged.internal.mixin.hook.FLSubChunk; import net.minecraft.block.Block; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.NibbleArray; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import net.minecraftforge.fluids.Fluid; import java.util.concurrent.atomic.AtomicInteger; public class ClonedChunkSection { private static final ExtendedBlockStorage EMPTY_SECTION = new ExtendedBlockStorage(0, false); private final AtomicInteger referenceCount = new AtomicInteger(0); private final ClonedChunkSectionCache backingCache; private final Short2ObjectMap<TileEntity> tileEntities; private ExtendedBlockStorageExt data; private final World world; private ChunkSectionPos pos; @Getter private BiomeGenBase[] biomeData; private long lastUsedTimestamp = Long.MAX_VALUE; ClonedChunkSection(ClonedChunkSectionCache backingCache, World world) { this.backingCache = backingCache; this.world = world; this.tileEntities = new Short2ObjectOpenHashMap<>(); } public void init(ChunkSectionPos pos) { final Chunk chunk = world.getChunkFromChunkCoords(pos.x, pos.z); if (chunk == null) { throw new RuntimeException("Couldn't retrieve chunk at " + pos.toChunkPos()); } ExtendedBlockStorage section = getChunkSection(chunk, pos); if (section == null /*WorldChunk.EMPTY_SECTION*/ /*ChunkSection.isEmpty(section)*/) { section = EMPTY_SECTION; } this.pos = pos; this.data = new ExtendedBlockStorageExt(chunk, section); int bArrLength; if (ModStatus.isEIDBiomeLoaded) { bArrLength = ((ChunkBiomeHook)chunk).getBiomeShortArray().length; } else { bArrLength = chunk.getBiomeArray().length; } this.biomeData = new BiomeGenBase[bArrLength]; this.tileEntities.clear(); // Check for tile entities for(int y = pos.getMinY(); y <= pos.getMaxY(); y++) { for(int z = pos.getMinZ(); z <= pos.getMaxZ(); z++) { for(int x = pos.getMinX(); x <= pos.getMaxX(); x++) { int lX = x & 15, lY = y & 15, lZ = z & 15; // We have to use this insanity because in 1.7 the tile entity isn't guaranteed to be created // when the chunk gets scheduled for rendering. So we might have to create it. // Cloning is done on the main thread so this will not introduce threading issues Block block = data.getBlockByExtId(lX, lY, lZ); if(block.hasTileEntity(data.getExtBlockMetadata(lX, lY, lZ))) { TileEntity tileentity = chunk.func_150806_e(x & 15, y, z & 15); if (tileentity != null) { this.tileEntities.put(ChunkSectionPos.packLocal(tileentity.xCoord & 15, tileentity.yCoord & 15, tileentity.zCoord & 15), tileentity); } } } } } // Fill biome data for(int z = pos.getMinZ(); z <= pos.getMaxZ(); z++) { for(int x = pos.getMinX(); x <= pos.getMaxX(); x++) { this.biomeData[((z & 15) << 4) | (x & 15)] = world.getBiomeGenForCoords(x, z); } } } public Block getBlock(int x, int y, int z) { return data.getBlockByExtId(x, y, z); } public Fluid getFluid(int x, int y, int z) { if (ModStatus.isFluidLoggedLoaded) { return ((FLSubChunk) data).fl$getFluid(x, y, z); } return null; } public int getBlockMetadata(int x, int y, int z) { return data.getExtBlockMetadata(x, y, z); } public NibbleArray getLightArray(EnumSkyBlock type) { if(type == EnumSkyBlock.Sky) { return (!world.provider.hasNoSky && data.hasSky) ? data.getSkylightArray() : null; } return data.getBlocklightArray(); } public BiomeGenBase getBiomeForNoiseGen(int x, int y, int z) { return this.biomeData[x | z << 4]; } public TileEntity getBlockEntity(int x, int y, int z) { return this.tileEntities.get(packLocal(x, y, z)); } public ChunkSectionPos getPosition() { return this.pos; } public static boolean isOutOfBuildLimitVertically(int y) { return y < 0 || y >= 256; } private static ExtendedBlockStorage getChunkSection(Chunk chunk, ChunkSectionPos pos) { if (!isOutOfBuildLimitVertically(ChunkSectionPos.getBlockCoord(pos.y()))) { return chunk.getBlockStorageArray()[pos.y]; } return null; } public void acquireReference() { this.referenceCount.incrementAndGet(); } public boolean releaseReference() { return this.referenceCount.decrementAndGet() <= 0; } public long getLastUsedTimestamp() { return this.lastUsedTimestamp; } public void setLastUsedTimestamp(long timestamp) { this.lastUsedTimestamp = timestamp; } public ClonedChunkSectionCache getBackingCache() { return this.backingCache; } /** * @param x The local x-coordinate * @param y The local y-coordinate * @param z The local z-coordinate * @return An index which can be used to key entities or blocks within a chunk */ private static short packLocal(int x, int y, int z) { return (short) (x << 8 | z << 4 | y); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\client\world\cloned\ClonedChunkSectionCache.java
package me.jellysquid.mods.sodium.client.world.cloned; import com.gtnewhorizons.angelica.compat.mojang.ChunkSectionPos; import it.unimi.dsi.fastutil.longs.Long2ReferenceLinkedOpenHashMap; import net.minecraft.world.World; import java.util.concurrent.TimeUnit; public class ClonedChunkSectionCache { private static final int MAX_CACHE_SIZE = 512; /* number of entries */ private static final long MAX_CACHE_DURATION = TimeUnit.SECONDS.toNanos(5); /* number of nanoseconds */ private final World world; private final Long2ReferenceLinkedOpenHashMap<ClonedChunkSection> byPosition = new Long2ReferenceLinkedOpenHashMap<>(); private long time; // updated once per frame to be the elapsed time since application start public ClonedChunkSectionCache(World world) { this.world = world; this.time = getMonotonicTimeSource(); } public synchronized void cleanup() { this.time = getMonotonicTimeSource(); this.byPosition.values().removeIf(entry -> this.time > (entry.getLastUsedTimestamp() + MAX_CACHE_DURATION)); } public synchronized ClonedChunkSection acquire(int x, int y, int z) { long key = ChunkSectionPos.asLong(x, y, z); ClonedChunkSection section = this.byPosition.get(key); if (section == null) { while (this.byPosition.size() >= MAX_CACHE_SIZE) { this.byPosition.removeFirst(); } section = this.createSection(x, y, z); } section.setLastUsedTimestamp(this.time); return section; } private ClonedChunkSection createSection(int x, int y, int z) { ClonedChunkSection section = this.allocate(); ChunkSectionPos pos = ChunkSectionPos.from(x, y, z); section.init(pos); this.byPosition.putAndMoveToLast(pos.asLong(), section); return section; } public synchronized void invalidate(int x, int y, int z) { this.byPosition.remove(ChunkSectionPos.asLong(x, y, z)); } public void release(ClonedChunkSection section) { } private ClonedChunkSection allocate() { return new ClonedChunkSection(this, this.world); } private static long getMonotonicTimeSource() { // Should be monotonic in JDK 17 on sane platforms... return System.nanoTime(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\common\config\Option.java
package me.jellysquid.mods.sodium.common.config; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; public class Option { private final String name; private Set<String> modDefined = null; private boolean enabled; private boolean userDefined; public Option(String name, boolean enabled, boolean userDefined) { this.name = name; this.enabled = enabled; this.userDefined = userDefined; } public void setEnabled(boolean enabled, boolean userDefined) { this.enabled = enabled; this.userDefined = userDefined; } public void addModOverride(boolean enabled, String modId) { this.enabled = enabled; if (this.modDefined == null) { this.modDefined = new LinkedHashSet<>(); } this.modDefined.add(modId); } public boolean isEnabled() { return this.enabled; } public boolean isOverridden() { return this.isUserDefined() || this.isModDefined(); } public boolean isUserDefined() { return this.userDefined; } public boolean isModDefined() { return this.modDefined != null; } public String getName() { return this.name; } public void clearModsDefiningValue() { this.modDefined = null; } public Collection<String> getDefiningMods() { return this.modDefined != null ? Collections.unmodifiableCollection(this.modDefined) : Collections.emptyList(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\common\config\SodiumConfig.java
package me.jellysquid.mods.sodium.common.config; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * Documentation of these options: https://github.com/jellysquid3/sodium-fabric/wiki/Configuration-File */ public class SodiumConfig { private static final Logger LOGGER = LogManager.getLogger("EmbeddiumConfig"); private final Map<String, Option> options = new HashMap<>(); private SodiumConfig() { } private void readProperties(Properties props) { for (Map.Entry<Object, Object> entry : props.entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); Option option = this.options.get(key); if (option == null) { LOGGER.warn("No configuration key exists with name '{}', ignoring", key); continue; } boolean enabled; if (value.equalsIgnoreCase("true")) { enabled = true; } else if (value.equalsIgnoreCase("false")) { enabled = false; } else { LOGGER.warn("Invalid value '{}' encountered for configuration key '{}', ignoring", value, key); continue; } // TODO: Sodium Config // if(!enabled && FMLEnvironment.production && SYSTEM_OPTIONS.contains(key)) { // LOGGER.warn("Configuration key '{}' is a required option and cannot be disabled", key); // continue; // } option.setEnabled(enabled, true); } } /** * Loads the configuration file from the specified location. If it does not exist, a new configuration file will be * created. The file on disk will then be updated to include any new options. */ public static SodiumConfig load(File file) { if (!file.exists()) { try { writeDefaultConfig(file); } catch (IOException e) { LOGGER.warn("Could not write default configuration file", e); } return new SodiumConfig(); } final Properties props = new Properties(); try (FileInputStream fin = new FileInputStream(file)){ props.load(fin); } catch (IOException e) { throw new RuntimeException("Could not load config file", e); } final SodiumConfig config = new SodiumConfig(); config.readProperties(props); return config; } private static void writeDefaultConfig(File file) throws IOException { final File dir = file.getParentFile(); if (!dir.exists()) { if (!dir.mkdirs()) { throw new IOException("Could not create parent directories"); } } else if (!dir.isDirectory()) { throw new IOException("The parent file is not a directory"); } try (Writer writer = new FileWriter(file)) { writer.write("# This is the configuration file for Sodium.\n"); writer.write("#\n"); writer.write("# You can find information on editing this file and all the available options here:\n"); writer.write("# https://github.com/jellysquid3/sodium-fabric/wiki/Configuration-File\n"); writer.write("#\n"); writer.write("# By default, this file will be empty except for this notice.\n"); } } }
Angelica
src\main\java\me\jellysquid\mods\sodium\common\util\IdTable.java
package me.jellysquid.mods.sodium.common.util; import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue; import java.util.Arrays; public class IdTable<T> { private final IntArrayFIFOQueue freeIds = new IntArrayFIFOQueue(); private T[] elements; private int nextId; private int capacity; @SuppressWarnings("unchecked") public IdTable(int capacity) { this.elements = (T[]) new Object[capacity]; this.capacity = capacity; } public int add(T element) { int id = this.allocateId(); if (id >= this.capacity) { this.grow(); } this.elements[id] = element; return id; } private void grow() { this.elements = Arrays.copyOf(this.elements, this.capacity *= 2); } public void remove(int id) { this.elements[id] = null; this.freeIds.enqueue(id); } private int allocateId() { if (!this.freeIds.isEmpty()) { return this.freeIds.dequeueInt(); } return this.nextId++; } public T get(int id) { return this.elements[id]; } public void set(int id, T value) { this.elements[id] = value; } public Object[] getElements() { return this.elements; } }
Angelica
src\main\java\me\jellysquid\mods\sodium\common\util\ListUtil.java
package me.jellysquid.mods.sodium.common.util; import java.util.Collection; public class ListUtil { public static <T> void updateList(Collection<T> collection, Collection<T> before, Collection<T> after) { if (!before.isEmpty()) { collection.removeAll(before); } if (!after.isEmpty()) { collection.addAll(after); } } }
Angelica
src\main\java\me\jellysquid\mods\sodium\common\util\collections\DequeDrain.java
package me.jellysquid.mods.sodium.common.util.collections; import java.util.Deque; import java.util.Iterator; public class DequeDrain<T> implements Iterator<T> { private final Deque<T> deque; public DequeDrain(Deque<T> deque) { this.deque = deque; } @Override public boolean hasNext() { return !this.deque.isEmpty(); } @Override public T next() { return this.deque.remove(); } }
Angelica
src\main\java\me\jellysquid\mods\sodium\common\util\collections\FutureDequeDrain.java
package me.jellysquid.mods.sodium.common.util.collections; import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue; import java.util.Deque; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; public class FutureDequeDrain<T> implements Iterator<T> { private final Deque<CompletableFuture<T>> deque; private T next = null; public FutureDequeDrain(Deque<CompletableFuture<T>> deque) { this.deque = deque; } @Override public boolean hasNext() { if (next != null) { return true; } findNext(); return next != null; } private void findNext() { while (!deque.isEmpty()) { CompletableFuture<T> future = deque.remove(); try { AngelicaRenderQueue.managedBlock(future::isDone); next = future.join(); return; } catch (CancellationException e) { // no-op } } } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } T result = next; next = null; return result; } }
Angelica
src\main\java\net\coderbot\iris\Iris.java
package net.coderbot.iris; import com.google.common.base.Throwables; import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; import com.gtnewhorizons.angelica.AngelicaMod; import com.gtnewhorizons.angelica.Tags; import com.gtnewhorizons.angelica.config.AngelicaConfig; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.InputEvent; import it.unimi.dsi.fastutil.objects.Object2IntMap; import lombok.Getter; import net.coderbot.iris.block_rendering.BlockRenderingSettings; import net.coderbot.iris.config.IrisConfig; import net.coderbot.iris.gl.shader.StandardMacros; import net.coderbot.iris.gui.screen.ShaderPackScreen; import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; import net.coderbot.iris.pipeline.transform.ShaderTransformer; import net.coderbot.iris.pipeline.transform.TransformPatcher; import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; import net.coderbot.iris.pipeline.FixedFunctionWorldRenderingPipeline; import net.coderbot.iris.pipeline.PipelineManager; import net.coderbot.iris.pipeline.WorldRenderingPipeline; import net.coderbot.iris.shaderpack.DimensionId; import net.coderbot.iris.shaderpack.OptionalBoolean; import net.coderbot.iris.shaderpack.ProgramSet; import net.coderbot.iris.shaderpack.ShaderPack; import net.coderbot.iris.shaderpack.discovery.ShaderpackDirectoryManager; import net.coderbot.iris.shaderpack.option.OptionSet; import net.coderbot.iris.shaderpack.option.Profile; import net.coderbot.iris.shaderpack.option.values.MutableOptionValues; import net.coderbot.iris.shaderpack.option.values.OptionValues; import net.coderbot.iris.sodium.block_context.BlockContextHolder; import net.coderbot.iris.texture.pbr.PBRTextureManager; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.resources.I18n; import net.minecraft.client.settings.KeyBinding; import net.minecraft.launchwrapper.Launch; import net.minecraft.util.ChatComponentText; import net.minecraft.util.EnumChatFormatting; import org.jetbrains.annotations.NotNull; import org.lwjgl.input.Keyboard; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.FileSystem; import java.nio.file.FileSystemNotFoundException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinWorkerThread; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import java.util.stream.Stream; import java.util.zip.ZipError; import java.util.zip.ZipException; public class Iris { public final boolean isDevelopmentEnvironment; /** * The user-facing name of the mod. Moved into a constant to facilitate easy branding changes (for forks). You'll still need to change this separately in * mixin plugin classes & the language files. */ public static final String MODNAME = "AngelicaShaders"; public static final IrisLogging logger = new IrisLogging(MODNAME); // Cached at class load - config must be loaded before Iris. Do not change at runtime. public static final boolean enabled = AngelicaConfig.enableIris; private static Path shaderpacksDirectory; private static ShaderpackDirectoryManager shaderpacksDirectoryManager; private static ShaderPack currentPack; @Getter private static String currentPackName; @Getter private static boolean initialized; @Getter private static int shaderPackLoadId = 0; private static PipelineManager pipelineManager; @Getter private static IrisConfig irisConfig; private static FileSystem zipFileSystem; @Getter private static final Map<String, String> shaderPackOptionQueue = new HashMap<>(); // Flag variable used when reloading // Used in favor of queueDefaultShaderPackOptionValues() for resetting as the // behavior is more concrete and therefore is more likely to repair a user's issues private static boolean resetShaderPackOptions = false; private static String IRIS_VERSION; @Getter private static boolean fallback; /** * Lazy executor for parallelizing shader transformations during shader pack loading. * Creates threads on demand and shuts down after a period of inactivity. */ public static final class ShaderTransformExecutor { private static final long IDLE_TIMEOUT_SECONDS = 120; private static final int THREAD_COUNT = Math.max(2, Math.min(12, Runtime.getRuntime().availableProcessors() / 2)); private static final Object lock = new Object(); private static ExecutorService executor; private static ScheduledExecutorService scheduler; private static volatile long lastActivityTime; private static final AtomicInteger inFlight = new AtomicInteger(0); private static boolean idleCheckScheduled; private ShaderTransformExecutor() {} private static void noteActivity() { lastActivityTime = System.nanoTime(); } public static ExecutorService get() { synchronized (lock) { noteActivity(); if (executor != null && !executor.isShutdown()) { return executor; } executor = new ForkJoinPool( THREAD_COUNT, pool -> { ForkJoinWorkerThread t = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); t.setName("Shader-Transform-" + t.getPoolIndex()); t.setDaemon(true); return t; }, null, // UncaughtExceptionHandler true // asyncMode - FIFO, better for independent tasks ); logger.debug("Created shader transform executor with " + THREAD_COUNT + " threads"); if (scheduler == null || scheduler.isShutdown()) { scheduler = Executors.newSingleThreadScheduledExecutor(r -> { Thread t = new Thread(r, "Shader-Transform-Scheduler"); t.setDaemon(true); return t; }); } if (!idleCheckScheduled) { idleCheckScheduled = true; scheduleIdleCheck(IDLE_TIMEOUT_SECONDS); } return executor; } } private static void scheduleIdleCheck(long delaySeconds) { try { scheduler.schedule(ShaderTransformExecutor::checkIdleShutdown, delaySeconds, TimeUnit.SECONDS); } catch (Exception e) { // If scheduling fails, reset the flag so a future get() can try again idleCheckScheduled = false; logger.warn("Failed to schedule idle check", e); } } /** * Ensures the executor exists and begins spinning up worker threads. * Intended for UI entrypoints (eg. shader settings screen open). */ public static void prepare() { // Submit empty tasks to warm up all worker threads without blocking the UI thread. for (int i = 0; i < THREAD_COUNT; i++) { submitTracked(() -> { }); } } /** * Warm up the threadpool by running a representative shader transformation. */ public static void warmup() { final String vertexShader = "#version 120\nvoid main() { gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; }"; final String fragmentShader = "#version 120\nvoid main() { gl_FragColor = vec4(1.0); }"; try { submitTracked(() -> { TransformPatcher.patchComposite(vertexShader, null, fragmentShader); TransformPatcher.patchAttributes(vertexShader, null, fragmentShader, new InputAvailability(true, true)); }).get(); } catch (Exception e) { logger.warn("Warmup failed", e); } } public static <T> CompletableFuture<T> submitTracked(Supplier<T> supplier) { Objects.requireNonNull(supplier); noteActivity(); inFlight.incrementAndGet(); try { return CompletableFuture.supplyAsync(() -> { try { return supplier.get(); } finally { noteActivity(); inFlight.decrementAndGet(); } }, get()); } catch (Exception e) { inFlight.decrementAndGet(); throw e; } } public static CompletableFuture<Void> submitTracked(Runnable runnable) { Objects.requireNonNull(runnable); noteActivity(); inFlight.incrementAndGet(); try { return CompletableFuture.runAsync(() -> { try { runnable.run(); } finally { noteActivity(); inFlight.decrementAndGet(); } }, get()); } catch (Exception e) { inFlight.decrementAndGet(); throw e; } } private static void checkIdleShutdown() { synchronized (lock) { final ExecutorService current = executor; if (current == null || current.isShutdown()) { // Executor already gone, shut down scheduler if (scheduler != null && !scheduler.isShutdown()) { scheduler.shutdown(); scheduler = null; } idleCheckScheduled = false; return; } final long idleNanos = System.nanoTime() - lastActivityTime; final long idleSeconds = TimeUnit.NANOSECONDS.toSeconds(idleNanos); if (idleSeconds >= IDLE_TIMEOUT_SECONDS && inFlight.get() == 0) { logger.debug("Shutting down idle shader transform executor after " + idleSeconds + " seconds"); current.shutdown(); executor = null; scheduler.shutdown(); scheduler = null; idleCheckScheduled = false; // Clear transformation caches - no longer needed after loading TransformPatcher.clearCache(); ShaderTransformer.clearCache(); } else { // Still active (or in-flight), schedule another check. final long remainingSeconds = Math.max(1, IDLE_TIMEOUT_SECONDS - idleSeconds + 1); scheduleIdleCheck(remainingSeconds); } } } } private static KeyBinding reloadKeybind; private static KeyBinding toggleShadersKeybind; private static KeyBinding shaderpackScreenKeybind; public static Iris INSTANCE = new Iris(); private Iris() { // Guard against null blackboard in test environments final Object deobfEnv = Launch.blackboard != null ? Launch.blackboard.get("fml.deobfuscatedEnvironment") : null; isDevelopmentEnvironment = deobfEnv != null && (boolean) deobfEnv; } @SubscribeEvent public void onKeypress(InputEvent.KeyInputEvent event) { if (reloadKeybind.isPressed()) { final Minecraft mc = Minecraft.getMinecraft(); try { reload(); if (mc.thePlayer != null) mc.thePlayer.addChatMessage(new ChatComponentText("Shaders Reloaded!")); } catch (Exception e) { logger.error("Error while reloading Shaders for Iris!", e); if (mc.thePlayer != null) mc.thePlayer.addChatMessage(new ChatComponentText( "Failed tgo reload shaders! Reason: " + Throwables.getRootCause(e).getMessage())); } } else if (toggleShadersKeybind.isPressed()) { final Minecraft mc = Minecraft.getMinecraft(); try { toggleShaders(mc, !irisConfig.areShadersEnabled()); } catch (Exception e) { logger.error("Error while toggling shaders!", e); if (mc.thePlayer != null) mc.thePlayer.addChatMessage(new ChatComponentText( "Failed tgo toggle shaders! Reason: " + Throwables.getRootCause(e).getMessage())); setShadersDisabled(); fallback = true; } } else if (shaderpackScreenKeybind.isPressed()) { final Minecraft mc = Minecraft.getMinecraft(); mc.displayGuiScreen(new ShaderPackScreen(null)); } } @SubscribeEvent public void keyUp(InputEvent.KeyInputEvent event) { final int key = Keyboard.getEventKey(); final boolean released = !Keyboard.getEventKeyState(); if (Minecraft.getMinecraft().gameSettings.showDebugInfo && GuiScreen.isShiftKeyDown() && GuiScreen.isCtrlKeyDown() && released) { if (key == Keyboard.KEY_N) { AngelicaMod.animationsMode.next(); } } } /** * Called very early on in Minecraft initialization. At this point we *cannot* safely access OpenGL, but we can do some very basic setup, config loading, * and environment checks. * * <p>This is roughly equivalent to Fabric Loader's ClientModInitializer#onInitializeClient entrypoint, except * it's entirely cross platform & we get to decide its exact semantics.</p> * * <p>This is called right before options are loaded, so we can add key bindings here.</p> */ public void onEarlyInitialize() { try { if (!Files.exists(getShaderpacksDirectory())) { Files.createDirectories(getShaderpacksDirectory()); } } catch (IOException e) { logger.warn("Failed to create the shaderpacks directory!"); logger.warn("", e); } irisConfig = new IrisConfig(Minecraft.getMinecraft().mcDataDir.toPath().resolve("config").resolve("shaders.properties")); try { irisConfig.initialize(); } catch (IOException e) { logger.error("Failed to initialize Angelica configuration, default values will be used instead"); logger.error("", e); } initialized = true; } /** * Called once RenderSystem#initRenderer has completed. This means that we can safely access OpenGL. */ public static void onRenderSystemInit() { if (!initialized) { Iris.logger.warn("Iris::onRenderSystemInit was called, but Iris::onEarlyInitialize was not called." + " Trying to avoid a crash but this is an odd state."); return; } // Warm up the threadpool so shader transformations are faster when we need them ShaderTransformExecutor.warmup(); PBRTextureManager.INSTANCE.init(); // Only load the shader pack when we can access OpenGL loadShaderpack(); } /** * Called when the title screen is initialized for the first time. */ public static void onLoadingComplete() { if (!initialized) { Iris.logger.warn("Iris::onLoadingComplete was called, but Iris::onEarlyInitialize was not called." + " Trying to avoid a crash but this is an odd state."); return; } // Initialize the pipeline now so that we don't increase world loading time. Just going to guess that // the player is in the overworld. // See: https://github.com/IrisShaders/Iris/issues/323 lastDimension = DimensionId.OVERWORLD; Iris.getPipelineManager().preparePipeline(DimensionId.OVERWORLD); } public static void toggleShaders(Minecraft minecraft, boolean enabled) throws IOException { irisConfig.setShadersEnabled(enabled); irisConfig.save(); reload(); if (minecraft.thePlayer != null) { minecraft.thePlayer.addChatMessage(new ChatComponentText(enabled ? I18n.format("iris.shaders.toggled", currentPackName) : I18n.format("iris.shaders.disabled"))); } } public static void loadShaderpack() { if (irisConfig == null) { if (!initialized) { throw new IllegalStateException("Iris::loadShaderpack was called, but Iris::onInitializeClient wasn't" + " called yet. How did this happen?"); } else { throw new NullPointerException("Iris.irisConfig was null unexpectedly"); } } if (!irisConfig.areShadersEnabled()) { logger.info("Shaders are disabled because enableShaders is set to false in shaders.properties"); setShadersDisabled(); return; } // Attempt to load an external shaderpack if it is available final Optional<String> externalName = irisConfig.getShaderPackName(); if (!externalName.isPresent()) { logger.info("Shaders are disabled because no valid shaderpack is selected"); setShadersDisabled(); return; } if (!loadExternalShaderpack(externalName.get())) { logger.warn("Falling back to normal rendering without shaders because the shaderpack could not be loaded"); setShadersDisabled(); fallback = true; } } private static boolean loadExternalShaderpack(String name) { final Path shaderPackRoot; final Path shaderPackConfigTxt; try { shaderPackRoot = getShaderpacksDirectory().resolve(name); shaderPackConfigTxt = getShaderpacksDirectory().resolve(name + ".txt"); } catch (InvalidPathException e) { logger.error("Failed to load the shaderpack \"{}\" because it contains invalid characters in its path", name); return false; } final Path shaderPackPath; if (shaderPackRoot.toString().endsWith(".zip")) { final Optional<Path> optionalPath; try { optionalPath = loadExternalZipShaderpack(shaderPackRoot); } catch (FileSystemNotFoundException | NoSuchFileException e) { logger.error("Failed to load the shaderpack \"{}\" because it does not exist in your shaderpacks folder!", name); return false; } catch (ZipException e) { logger.error("The shaderpack \"{}\" appears to be corrupted, please try downloading it again!", name); return false; } catch (IOException e) { logger.error("Failed to load the shaderpack \"{}\"!", name); logger.error("", e); return false; } if (optionalPath.isPresent()) { shaderPackPath = optionalPath.get(); } else { logger.error("Could not load the shaderpack \"{}\" because it appears to lack a \"shaders\" directory", name); return false; } } else { if (!Files.exists(shaderPackRoot)) { logger.error("Failed to load the shaderpack \"{}\" because it does not exist!", name); return false; } // If it's a folder-based shaderpack, just use the shaders subdirectory shaderPackPath = shaderPackRoot.resolve("shaders"); } if (!Files.exists(shaderPackPath)) { logger.error("Could not load the shaderpack \"{}\" because it appears to lack a \"shaders\" directory", name); return false; } @SuppressWarnings("unchecked") final Map<String, String> changedConfigs = tryReadConfigProperties(shaderPackConfigTxt).map(properties -> (Map<String, String>) (Map<?, ?>) properties) .orElse(new HashMap<>()); changedConfigs.putAll(shaderPackOptionQueue); clearShaderPackOptionQueue(); if (resetShaderPackOptions) { changedConfigs.clear(); } resetShaderPackOptions = false; try { currentPack = new ShaderPack(shaderPackPath, changedConfigs, StandardMacros.createStandardEnvironmentDefines()); final MutableOptionValues changedConfigsValues = currentPack.getShaderPackOptions().getOptionValues().mutableCopy(); // Store changed values from those currently in use by the shader pack final Properties configsToSave = new Properties(); changedConfigsValues.getBooleanValues().forEach((k, v) -> configsToSave.setProperty(k, Boolean.toString(v))); changedConfigsValues.getStringValues().forEach(configsToSave::setProperty); tryUpdateConfigPropertiesFile(shaderPackConfigTxt, configsToSave); } catch (Exception e) { logger.error("Failed to load the shaderpack \"{}\"!", name); logger.error("", e); return false; } fallback = false; currentPackName = name; logger.info("Using shaderpack: " + name); return true; } private static Optional<Path> loadExternalZipShaderpack(Path shaderpackPath) throws IOException { final FileSystem zipSystem = FileSystems.newFileSystem(shaderpackPath, Iris.class.getClassLoader()); zipFileSystem = zipSystem; // Should only be one root directory for a zip shaderpack final Path root = zipSystem.getRootDirectories().iterator().next(); final Path potentialShaderDir = zipSystem.getPath("shaders"); // If the shaders dir was immediately found return it // Otherwise, manually search through each directory path until it ends with "shaders" if (Files.exists(potentialShaderDir)) { return Optional.of(potentialShaderDir); } // Sometimes shaderpacks have their shaders directory within another folder in the shaderpack // For example Sildurs-Vibrant-Shaders.zip/shaders // While other packs have Trippy-Shaderpack-master.zip/Trippy-Shaderpack-master/shaders // This makes it hard to determine what is the actual shaders dir try (Stream<Path> stream = Files.walk(root)) { return stream.filter(Files::isDirectory).filter(path -> path.endsWith("shaders")).findFirst(); } } private static void setShadersDisabled() { currentPack = null; fallback = false; currentPackName = "(off)"; logger.info("Shaders are disabled"); } private static Optional<Properties> tryReadConfigProperties(Path path) { final Properties properties = new Properties(); if (Files.exists(path)) { try (InputStream is = Files.newInputStream(path)) { // NB: config properties are specified to be encoded with ISO-8859-1 by OptiFine, // so we don't need to do the UTF-8 workaround here. properties.load(is); } catch (IOException e) { // TODO: Better error handling return Optional.empty(); } } return Optional.of(properties); } private static void tryUpdateConfigPropertiesFile(Path path, Properties properties) { try { if (properties.isEmpty()) { // Delete the file or don't create it if there are no changed configs if (Files.exists(path)) { Files.delete(path); } return; } try (OutputStream out = Files.newOutputStream(path)) { properties.store(out, null); } } catch (IOException e) { // TODO: Better error handling } } public static boolean isValidShaderpack(Path pack) { if (Files.isDirectory(pack)) { // Sometimes the shaderpack directory itself can be // identified as a shader pack due to it containing // folders which contain "shaders" folders, this is // necessary to check against that if (pack.equals(getShaderpacksDirectory())) { return false; } try (Stream<Path> stream = Files.walk(pack)) { return stream.filter(Files::isDirectory) // Prevent a pack simply named "shaders" from being // identified as a valid pack .filter(path -> !path.equals(pack)).anyMatch(path -> path.endsWith("shaders")); } catch (IOException ignored) { // ignored, not a valid shader pack. } } if (pack.toString().endsWith(".zip")) { try (FileSystem zipSystem = FileSystems.newFileSystem(pack, Iris.class.getClassLoader())) { final Path root = zipSystem.getRootDirectories().iterator().next(); try (Stream<Path> stream = Files.walk(root)) { return stream.filter(Files::isDirectory).anyMatch(path -> path.endsWith("shaders")); } } catch (ZipError zipError) { // Java 8 seems to throw a ZipError instead of a subclass of IOException Iris.logger.warn("The ZIP at " + pack + " is corrupt"); } catch (IOException ignored) { // ignored, not a valid shader pack. } } return false; } public static void queueShaderPackOptionsFromProfile(Profile profile) { getShaderPackOptionQueue().putAll(profile.optionValues); } public static void queueShaderPackOptionsFromProperties(Properties properties) { queueDefaultShaderPackOptionValues(); properties.stringPropertyNames().forEach(key -> getShaderPackOptionQueue().put(key, properties.getProperty(key))); } // Used in favor of resetShaderPackOptions as the aforementioned requires the pack to be reloaded public static void queueDefaultShaderPackOptionValues() { clearShaderPackOptionQueue(); getCurrentPack().ifPresent(pack -> { final OptionSet options = pack.getShaderPackOptions().getOptionSet(); final OptionValues values = pack.getShaderPackOptions().getOptionValues(); options.getStringOptions().forEach((key, mOpt) -> { if (values.getStringValue(key).isPresent()) { getShaderPackOptionQueue().put(key, mOpt.getOption().getDefaultValue()); } }); options.getBooleanOptions().forEach((key, mOpt) -> { if (values.getBooleanValue(key) != OptionalBoolean.DEFAULT) { getShaderPackOptionQueue().put(key, Boolean.toString(mOpt.getOption().getDefaultValue())); } }); }); } public static void clearShaderPackOptionQueue() { getShaderPackOptionQueue().clear(); } public static void resetShaderPackOptionsOnNextReload() { resetShaderPackOptions = true; } public static boolean shouldResetShaderPackOptionsOnNextReload() { return resetShaderPackOptions; } public static void reload() throws IOException { // allows shaderpacks to be changed at runtime irisConfig.initialize(); // Destroy all allocated resources destroyEverything(); // Load the new shaderpack loadShaderpack(); // Very important - we need to re-create the pipeline straight away. // https://github.com/IrisShaders/Iris/issues/1330 if (Minecraft.getMinecraft().theWorld != null) { Iris.getPipelineManager().preparePipeline(Iris.getCurrentDimension()); } } /** * Destroys and deallocates all created OpenGL resources. Useful as part of a reload. */ private static void destroyEverything() { currentPack = null; getPipelineManager().destroyPipeline(); // Close the zip filesystem that the shaderpack was loaded from // // This prevents a FileSystemAlreadyExistsException when reloading shaderpacks. if (zipFileSystem != null) { try { zipFileSystem.close(); } catch (NoSuchFileException e) { logger.warn("Failed to close the shaderpack zip when reloading because it was deleted, proceeding anyways."); } catch (IOException e) { logger.error("Failed to close zip file system?", e); } } } public static DimensionId lastDimension = null; public static DimensionId getCurrentDimension() { final WorldClient level = Minecraft.getMinecraft().theWorld; if (level != null) { if (level.provider == null) return DimensionId.OVERWORLD; if (level.provider.isHellWorld || level.provider.dimensionId == -1) { return DimensionId.NETHER; } else if (level.provider.dimensionId == 1) { return DimensionId.END; } else { return DimensionId.OVERWORLD; } } else { // This prevents us from reloading the shaderpack unless we need to. Otherwise, if the player is in the // nether and quits the game, we might end up reloading the shaders on exit and on entry to the level // because the code thinks that the dimension changed. return lastDimension; } } private static WorldRenderingPipeline createPipeline(DimensionId dimensionId) { if (currentPack == null) { // Completely disables shader-based rendering return new FixedFunctionWorldRenderingPipeline(); } final ProgramSet programs = currentPack.getProgramSet(dimensionId); try { shaderPackLoadId++; long startTime = System.nanoTime(); WorldRenderingPipeline pipeline = new DeferredWorldRenderingPipeline(programs); long endTime = System.nanoTime(); logger.info("[Load #{}] Total shaderpack load time for '{}': {} ms", shaderPackLoadId, currentPackName, String.format("%.1f", (endTime - startTime) / 1_000_000.0)); return pipeline; } catch (Exception e) { logger.error("Failed to create shader rendering pipeline, disabling shaders!", e); // TODO: This should be reverted if a dimension change causes shaders to compile again fallback = true; return new FixedFunctionWorldRenderingPipeline(); } } @NotNull public static PipelineManager getPipelineManager() { if (pipelineManager == null) { pipelineManager = new PipelineManager(Iris::createPipeline); } return pipelineManager; } @NotNull public static Optional<ShaderPack> getCurrentPack() { return Optional.ofNullable(currentPack); } public static String getVersion() { if (IRIS_VERSION == null) { return "Version info unknown!"; } return IRIS_VERSION; } public static String getFormattedVersion() { final EnumChatFormatting color; String version = getVersion(); if (version.endsWith("-development-environment")) { color = EnumChatFormatting.GOLD; version = version.replace("-development-environment", " (Development Environment)"); } else if (version.endsWith("-dirty") || version.contains("unknown") || version.endsWith("-nogit")) { color = EnumChatFormatting.RED; } else if (version.contains("+rev.")) { color = EnumChatFormatting.LIGHT_PURPLE; } else { color = EnumChatFormatting.GREEN; } return color + version; } public static Path getShaderpacksDirectory() { if (shaderpacksDirectory == null) { shaderpacksDirectory = Minecraft.getMinecraft().mcDataDir.toPath().resolve("shaderpacks"); } return shaderpacksDirectory; } public static ShaderpackDirectoryManager getShaderpacksDirectoryManager() { if (shaderpacksDirectoryManager == null) { shaderpacksDirectoryManager = new ShaderpackDirectoryManager(getShaderpacksDirectory()); } return shaderpacksDirectoryManager; } public void fmlInitEvent() { IRIS_VERSION = Tags.VERSION; reloadKeybind = new KeyBinding("Reload Shaders", 0, "Iris Keybinds"); toggleShadersKeybind = new KeyBinding("Toggle Shaders", 0, "Iris Keybinds"); shaderpackScreenKeybind = new KeyBinding("Shaderpack Selection Screen", 0, "Iris Keybinds"); ClientRegistry.registerKeyBinding(reloadKeybind); ClientRegistry.registerKeyBinding(toggleShadersKeybind); ClientRegistry.registerKeyBinding(shaderpackScreenKeybind); } static BlockContextHolder contextHolder; private static int getShaderMaterialOverrideId(Block block, int meta) { if (contextHolder == null) { final Object2IntMap<Block> blockMatches = BlockRenderingSettings.INSTANCE.getBlockMatches(); if (blockMatches == null) { return -1; } contextHolder = new BlockContextHolder(blockMatches); } contextHolder.set(block, (short) block.getRenderType()); return contextHolder.blockId; } public static void setShaderMaterialOverride(Block block, int meta) { if (!enabled) return; int blockId = getShaderMaterialOverrideId(block, meta); if (TessellatorManager.get() instanceof CapturingTessellator tess) tess.setShaderBlockId(blockId); } public static void resetShaderMaterialOverride() { if (!enabled) return; if (TessellatorManager.get() instanceof CapturingTessellator tess) tess.setShaderBlockId(-1); } }
Angelica
src\main\java\net\coderbot\iris\IrisLogging.java
package net.coderbot.iris; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class IrisLogging { public static boolean ENABLE_SPAM = false; // FabricLoader.getInstance().isDevelopmentEnvironment(); private final Logger logger; public IrisLogging(String loggerName) { this.logger = LogManager.getLogger(loggerName); } public void fatal(String fatal) { this.logger.fatal(fatal); } public void error(String error) { this.logger.error(error); } public void error(String error, Object... o) { this.logger.error(error, o); } public void error(String error, Throwable t) { this.logger.error(error, t); } public void warn(String warning) { this.logger.warn(warning); } public void warn(String warning, Throwable t) { this.logger.warn(warning, t); } public void warn(Object... o) { this.logger.warn(o); } public void info(String info) { this.logger.info(info); } public void info(String info, Object... o) { this.logger.info(info, o); } public void debug(String debug) { this.logger.debug(debug); } public void debug(String debug, Throwable t) { this.logger.debug(debug, t); } }
Angelica
src\main\java\net\coderbot\iris\JomlConversions.java
package net.coderbot.iris; import net.minecraft.util.Vec3; import org.joml.Vector3d; import org.joml.Vector4f; public class JomlConversions { public static Vector3d fromVec3(Vec3 vec) { return new Vector3d(vec.xCoord, vec.yCoord, vec.zCoord); } public static Vector4f toJoml(Vector4f v) { return new Vector4f(v.x(), v.y(), v.z(), v.w()); } }
Angelica
src\main\java\net\coderbot\iris\LaunchWarn.java
package net.coderbot.iris; import javax.swing.JOptionPane; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import java.awt.Desktop; import java.awt.GraphicsEnvironment; import java.io.IOException; import java.net.URI; public class LaunchWarn { public static void main(String[] args) { // TODO: make this translatable String message = "This file is the Fabric version of Iris, meant to be installed as a mod. Would you like to get the Iris Installer instead?"; String fallback = "This file is the Fabric version of Iris, meant to be installed as a mod. Please download the Iris Installer from https://irisshaders.net."; if (GraphicsEnvironment.isHeadless()) { System.err.println(fallback); } else { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ReflectiveOperationException | UnsupportedLookAndFeelException ignored) { // Ignored } if (Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { int option = JOptionPane.showOptionDialog(null, message, "Iris Installer", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null); if (option == JOptionPane.YES_OPTION) { try { Desktop.getDesktop().browse(URI.create("https://irisshaders.net")); } catch (IOException e) { e.printStackTrace(); } } } else { // Fallback for Linux, etc users with no "default" browser JOptionPane.showMessageDialog(null, fallback); } } System.exit(0); } }
Angelica
src\main\java\net\coderbot\batchedentityrendering\impl\BatchingDebugMessageHelper.java
package net.coderbot.batchedentityrendering.impl; public class BatchingDebugMessageHelper { public static String getDebugMessage(DrawCallTrackingRenderBuffers drawTracker) { int drawCalls = drawTracker.getDrawCalls(); int renderTypes = drawTracker.getRenderTypes(); if (drawCalls > 0) { int effectivenessTimes10 = renderTypes * 1000 / drawCalls; float effectiveness = effectivenessTimes10 / 10.0F; return drawCalls + " draw calls / " + renderTypes + " render types = " + effectiveness + "% effective"; } else { return "(no draw calls)"; } } }
Angelica
src\main\java\net\coderbot\batchedentityrendering\impl\BlendingStateHolder.java
package net.coderbot.batchedentityrendering.impl; public interface BlendingStateHolder { TransparencyType getTransparencyType(); }
Angelica
src\main\java\net\coderbot\batchedentityrendering\impl\BufferSegment.java
package net.coderbot.batchedentityrendering.impl; import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; import lombok.Getter; import java.nio.ByteBuffer; public class BufferSegment { private final ByteBuffer slice; @Getter private final RenderLayer type; public BufferSegment(ByteBuffer slice, RenderLayer type) { this.slice = slice; this.type = type; } public ByteBuffer getSlice() { return slice; } public RenderLayer getRenderType() { return type; } }
Angelica
src\main\java\net\coderbot\batchedentityrendering\impl\DrawCallTrackingRenderBuffers.java
package net.coderbot.batchedentityrendering.impl; public interface DrawCallTrackingRenderBuffers { int getDrawCalls(); int getRenderTypes(); void resetDrawCounts(); }
Angelica
src\main\java\net\coderbot\batchedentityrendering\impl\FlushableMultiBufferSource.java
package net.coderbot.batchedentityrendering.impl; public interface FlushableMultiBufferSource { void flushNonTranslucentContent(); void flushTranslucentContent(); }
Angelica
src\main\java\net\coderbot\batchedentityrendering\impl\Groupable.java
package net.coderbot.batchedentityrendering.impl; public interface Groupable { void startGroup(); boolean maybeStartGroup(); void endGroup(); }
Angelica
src\main\java\net\coderbot\batchedentityrendering\impl\MemoryTrackingBuffer.java
package net.coderbot.batchedentityrendering.impl; public interface MemoryTrackingBuffer { int getAllocatedSize(); int getUsedSize(); }
Angelica
src\main\java\net\coderbot\batchedentityrendering\impl\MemoryTrackingRenderBuffers.java
package net.coderbot.batchedentityrendering.impl; public interface MemoryTrackingRenderBuffers { int getEntityBufferAllocatedSize(); int getMiscBufferAllocatedSize(); int getMaxBegins(); }
Angelica
src\main\java\net\coderbot\batchedentityrendering\impl\RenderBuffersExt.java
package net.coderbot.batchedentityrendering.impl; public interface RenderBuffersExt { void beginLevelRendering(); void endLevelRendering(); }
Angelica
src\main\java\net\coderbot\batchedentityrendering\impl\TransparencyType.java
package net.coderbot.batchedentityrendering.impl; public enum TransparencyType { /** * Opaque, non transparent content. */ OPAQUE, /** * Generally transparent / translucent content. */ GENERAL_TRANSPARENT, /** * Enchantment glint and crumbling blocks * These *must* be rendered after their corresponding opaque / transparent parts. */ DECAL, /** * Water mask, should be drawn after pretty much everything except for translucent terrain and lines. * Prevents water from appearing inside of boats. */ WATER_MASK, /** * Block outlines and other debug things that are overlaid on to the world. * Should be drawn last to avoid weirdness with entity shadows / banners. */ LINES }
Angelica
src\main\java\net\coderbot\batchedentityrendering\impl\WrappableRenderType.java
package net.coderbot.batchedentityrendering.impl; import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; public interface WrappableRenderType { /** * Returns the underlying wrapped RenderType. Might return itself if this RenderType doesn't wrap anything. */ RenderLayer unwrap(); }
Angelica
src\main\java\net\coderbot\batchedentityrendering\impl\ordering\GraphTranslucencyRenderOrderManager.java
package net.coderbot.batchedentityrendering.impl.ordering; import de.odysseus.ithaka.digraph.Digraph; import de.odysseus.ithaka.digraph.Digraphs; import de.odysseus.ithaka.digraph.MapDigraph; import de.odysseus.ithaka.digraph.util.fas.FeedbackArcSet; import de.odysseus.ithaka.digraph.util.fas.FeedbackArcSetPolicy; import de.odysseus.ithaka.digraph.util.fas.FeedbackArcSetProvider; import de.odysseus.ithaka.digraph.util.fas.SimpleFeedbackArcSetProvider; import net.coderbot.batchedentityrendering.impl.BlendingStateHolder; import net.coderbot.batchedentityrendering.impl.TransparencyType; import net.coderbot.batchedentityrendering.impl.WrappableRenderType; import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; public class GraphTranslucencyRenderOrderManager implements RenderOrderManager { private final FeedbackArcSetProvider feedbackArcSetProvider; private final EnumMap<TransparencyType, Digraph<RenderLayer>> types; private boolean inGroup = false; private final EnumMap<TransparencyType, RenderLayer> currentTypes; public GraphTranslucencyRenderOrderManager() { feedbackArcSetProvider = new SimpleFeedbackArcSetProvider(); types = new EnumMap<>(TransparencyType.class); currentTypes = new EnumMap<>(TransparencyType.class); for (TransparencyType type : TransparencyType.values()) { types.put(type, new MapDigraph<>()); } } private static TransparencyType getTransparencyType(RenderLayer type) { while (type instanceof WrappableRenderType) { type = ((WrappableRenderType) type).unwrap(); } if (type instanceof BlendingStateHolder blendingState) { return blendingState.getTransparencyType(); } // Default to "generally transparent" if we can't figure it out. return TransparencyType.GENERAL_TRANSPARENT; } public void begin(RenderLayer renderType) { TransparencyType transparencyType = getTransparencyType(renderType); Digraph<RenderLayer> graph = types.get(transparencyType); graph.add(renderType); if (inGroup) { RenderLayer previous = currentTypes.put(transparencyType, renderType); if (previous == null) { return; } int weight = graph.get(previous, renderType).orElse(0); weight += 1; graph.put(previous, renderType, weight); } } public void startGroup() { if (inGroup) { throw new IllegalStateException("Already in a group"); } currentTypes.clear(); inGroup = true; } public boolean maybeStartGroup() { if (inGroup) { return false; } currentTypes.clear(); inGroup = true; return true; } public void endGroup() { if (!inGroup) { throw new IllegalStateException("Not in a group"); } currentTypes.clear(); inGroup = false; } @Override public void reset() { // TODO: Is reallocation efficient? types.clear(); for (TransparencyType type : TransparencyType.values()) { types.put(type, new MapDigraph<>()); } } public Iterable<RenderLayer> getRenderOrder() { int layerCount = 0; for (Digraph<RenderLayer> graph : types.values()) { layerCount += graph.getVertexCount(); } List<RenderLayer> allLayers = new ArrayList<>(layerCount); for (Digraph<RenderLayer> graph : types.values()) { // TODO: Make sure that FAS can't become a bottleneck! // Running NP-hard algorithms in a real time rendering loop might not be an amazing idea. // This shouldn't be necessary in sane scenes, though, and if there aren't cycles, // then this *should* be relatively inexpensive, since it'll bail out and return an empty set. FeedbackArcSet<RenderLayer> arcSet = feedbackArcSetProvider.getFeedbackArcSet(graph, graph, FeedbackArcSetPolicy.MIN_WEIGHT); if (arcSet.getEdgeCount() > 0) { // This means that our dependency graph had cycles!!! // This is very weird and isn't expected - but we try to handle it gracefully anyways. // Our feedback arc set algorithm finds some dependency links that can be removed hopefully // without disrupting the overall order too much. Hopefully it isn't too slow! for (RenderLayer source : arcSet.vertices()) { for (RenderLayer target : arcSet.targets(source)) { graph.remove(source, target); } } } allLayers.addAll(Digraphs.toposort(graph, false)); } return allLayers; } }
Angelica
src\main\java\net\coderbot\batchedentityrendering\impl\ordering\RenderOrderManager.java
package net.coderbot.batchedentityrendering.impl.ordering; import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; public interface RenderOrderManager { void begin(RenderLayer type); void startGroup(); boolean maybeStartGroup(); void endGroup(); void reset(); Iterable<RenderLayer> getRenderOrder(); }
Angelica
src\main\java\net\coderbot\batchedentityrendering\impl\ordering\SimpleRenderOrderManager.java
package net.coderbot.batchedentityrendering.impl.ordering; import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; import java.util.LinkedHashSet; public class SimpleRenderOrderManager implements RenderOrderManager { private final LinkedHashSet<RenderLayer> renderTypes; public SimpleRenderOrderManager() { renderTypes = new LinkedHashSet<>(); } public void begin(RenderLayer type) { renderTypes.add(type); } public void startGroup() { // no-op } public boolean maybeStartGroup() { // no-op return false; } public void endGroup() { // no-op } @Override public void reset() { renderTypes.clear(); } public Iterable<RenderLayer> getRenderOrder() { return renderTypes; } }
Angelica
src\main\java\net\coderbot\batchedentityrendering\impl\ordering\TranslucencyRenderOrderManager.java
package net.coderbot.batchedentityrendering.impl.ordering; import net.coderbot.batchedentityrendering.impl.BlendingStateHolder; import net.coderbot.batchedentityrendering.impl.TransparencyType; import net.coderbot.batchedentityrendering.impl.WrappableRenderType; import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; import java.util.ArrayList; import java.util.EnumMap; import java.util.LinkedHashSet; import java.util.List; public class TranslucencyRenderOrderManager implements RenderOrderManager { private final EnumMap<TransparencyType, LinkedHashSet<RenderLayer>> renderTypes; public TranslucencyRenderOrderManager() { renderTypes = new EnumMap<>(TransparencyType.class); for (TransparencyType type : TransparencyType.values()) { renderTypes.put(type, new LinkedHashSet<>()); } } private static TransparencyType getTransparencyType(RenderLayer type) { while (type instanceof WrappableRenderType) { type = ((WrappableRenderType) type).unwrap(); } if (type instanceof BlendingStateHolder) { return ((BlendingStateHolder) type).getTransparencyType(); } // Default to "generally transparent" if we can't figure it out. return TransparencyType.GENERAL_TRANSPARENT; } public void begin(RenderLayer type) { renderTypes.get(getTransparencyType(type)).add(type); } public void startGroup() { // no-op } public boolean maybeStartGroup() { // no-op return false; } public void endGroup() { // no-op } @Override public void reset() { renderTypes.forEach((type, set) -> { set.clear(); }); } public Iterable<RenderLayer> getRenderOrder() { int layerCount = 0; for (LinkedHashSet<RenderLayer> set : renderTypes.values()) { layerCount += set.size(); } List<RenderLayer> allRenderTypes = new ArrayList<>(layerCount); for (LinkedHashSet<RenderLayer> set : renderTypes.values()) { allRenderTypes.addAll(set); } return allRenderTypes; } }
Angelica
src\main\java\net\coderbot\iris\apiimpl\IrisApiV0ConfigImpl.java
package net.coderbot.iris.apiimpl; import net.coderbot.iris.Iris; import net.coderbot.iris.config.IrisConfig; import net.irisshaders.iris.api.v0.IrisApiConfig; import java.io.IOException; public class IrisApiV0ConfigImpl implements IrisApiConfig { @Override public boolean areShadersEnabled() { return Iris.getIrisConfig().areShadersEnabled(); } @Override public void setShadersEnabledAndApply(boolean enabled) { IrisConfig config = Iris.getIrisConfig(); config.setShadersEnabled(enabled); try { config.save(); } catch (IOException e) { Iris.logger.error("Error saving configuration file!", e); } try { Iris.reload(); } catch (IOException e) { Iris.logger.error("Error reloading shader pack while applying changes!", e); } } }
Angelica
src\main\java\net\coderbot\iris\apiimpl\IrisApiV0Impl.java
package net.coderbot.iris.apiimpl; import net.coderbot.iris.Iris; import net.coderbot.iris.pipeline.FixedFunctionWorldRenderingPipeline; import net.coderbot.iris.pipeline.WorldRenderingPipeline; import net.coderbot.iris.shadows.ShadowRenderingState; import net.irisshaders.iris.api.v0.IrisApi; import net.irisshaders.iris.api.v0.IrisApiConfig; public class IrisApiV0Impl implements IrisApi { public static final IrisApiV0Impl INSTANCE = new IrisApiV0Impl(); private static final IrisApiV0ConfigImpl CONFIG = new IrisApiV0ConfigImpl(); @Override public int getMinorApiRevision() { return 1; } @Override public boolean isShaderPackInUse() { WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); if (pipeline == null) { return false; } return !(pipeline instanceof FixedFunctionWorldRenderingPipeline); } @Override public boolean isRenderingShadowPass() { return ShadowRenderingState.areShadowsCurrentlyBeingRendered(); } @Override public Object openMainIrisScreenObj(Object parent) { return new Object(); // TODO: GUI // return new ShaderPackScreen((GuiScreen) parent); } @Override public String getMainScreenLanguageKey() { return "options.iris.shaderPackSelection"; } @Override public IrisApiConfig getConfig() { return CONFIG; } }
Angelica
src\main\java\net\coderbot\iris\block_rendering\BlockMaterialMapping.java
package net.coderbot.iris.block_rendering; import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; import net.coderbot.iris.shaderpack.materialmap.BlockEntry; import net.coderbot.iris.shaderpack.materialmap.BlockRenderType; import net.coderbot.iris.shaderpack.materialmap.NamespacedId; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.util.ResourceLocation; import java.util.List; import java.util.Map; public class BlockMaterialMapping { public static Object2IntMap<Block> createBlockStateIdMap(Int2ObjectMap<List<BlockEntry>> blockPropertiesMap) { Object2IntMap<Block> blockMatches = new Object2IntOpenHashMap<>(); blockPropertiesMap.forEach((intId, entries) -> { for (BlockEntry entry : entries) { addBlock(entry, blockMatches, intId); } }); return blockMatches; } public static Map<Block, RenderLayer> createBlockTypeMap(Map<NamespacedId, BlockRenderType> blockPropertiesMap) { Map<Block, RenderLayer> blockTypeIds = new Reference2ReferenceOpenHashMap<>(); blockPropertiesMap.forEach((id, blockType) -> { ResourceLocation resourceLocation = new ResourceLocation(id.getNamespace(), id.getName()); Block block = Block.getBlockFromName(resourceLocation.toString()); blockTypeIds.put(block, convertBlockToRenderType(blockType)); }); return blockTypeIds; } private static RenderLayer convertBlockToRenderType(BlockRenderType type) { if (type == null) { return null; } return switch (type) { // Everything renders in cutout or translucent in 1.7.10 case SOLID, CUTOUT, CUTOUT_MIPPED -> RenderLayer.cutout(); // case SOLID -> RenderLayer.solid(); // case CUTOUT_MIPPED -> RenderLayer.cutoutMipped(); case TRANSLUCENT -> RenderLayer.translucent(); default -> null; }; } private static void addBlock(BlockEntry entry, Object2IntMap<Block> idMap, int intId) { final NamespacedId id = entry.getId(); final ResourceLocation resourceLocation = new ResourceLocation(id.getNamespace(), id.getName()); final Block block = (Block) Block.blockRegistry.getObject(resourceLocation.toString()); // If the block doesn't exist, by default the registry will return AIR. That probably isn't what we want. // TODO: Assuming that Registry.BLOCK.getDefaultId() == "minecraft:air" here if (block == null || block == Blocks.air) { return; } idMap.put(block, intId); // Set<Integer> metas = entry.getMetas(); // // All metas match // if (metas.isEmpty()) { // idMap.putIfAbsent(new BlockMatch(block, null), intId); // return; // } // // // A subset of metas match // for(int meta : metas) { // idMap.putIfAbsent(new BlockMatch(block, meta), intId); // } } // We ignore generics here, the actual types don't matter because we just convert // them to strings anyways, and the compiler checks just get in the way. // // If you're able to rewrite this function without SuppressWarnings, feel free. // But otherwise it works fine. // TODO: BlockStateIdMap // @SuppressWarnings({"rawtypes", "unchecked"}) // private static boolean checkState(BlockState state, Map<Property<?>, String> expectedValues) { // for (Map.Entry<Property<?>, String> condition : expectedValues.entrySet()) { // Property property = condition.getKey(); // String expectedValue = condition.getValue(); // // String actualValue = property.getName(state.getValue(property)); // // if (!expectedValue.equals(actualValue)) { // return false; // } // } // // return true; // } }
Angelica
src\main\java\net\coderbot\iris\block_rendering\BlockRenderingSettings.java
package net.coderbot.iris.block_rendering; import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; import it.unimi.dsi.fastutil.objects.Object2IntFunction; import it.unimi.dsi.fastutil.objects.Object2IntMap; import lombok.Getter; import net.coderbot.iris.shaderpack.materialmap.NamespacedId; import net.minecraft.block.Block; import org.jetbrains.annotations.Nullable; import java.util.Map; public class BlockRenderingSettings { public static final BlockRenderingSettings INSTANCE = new BlockRenderingSettings(); @Getter private boolean reloadRequired; private Object2IntMap<Block> blockMatches; private Map<Block, RenderLayer> blockTypeIds; private Object2IntFunction<NamespacedId> entityIds; private float ambientOcclusionLevel; private boolean disableDirectionalShading; private boolean useSeparateAo; private boolean useExtendedVertexFormat; public BlockRenderingSettings() { reloadRequired = false; blockMatches = null; blockTypeIds = null; ambientOcclusionLevel = 1.0F; disableDirectionalShading = false; useSeparateAo = false; useExtendedVertexFormat = false; } public void clearReloadRequired() { reloadRequired = false; } @Nullable public Object2IntMap<Block> getBlockMatches() { return blockMatches; } @Nullable public Map<Block, RenderLayer> getBlockTypeIds() { return blockTypeIds; } @Nullable public Object2IntFunction<NamespacedId> getEntityIds() { return entityIds; } public void setBlockMatches(Object2IntMap<Block> blockIds) { if (this.blockMatches != null && this.blockMatches.equals(blockIds)) { return; } this.reloadRequired = true; this.blockMatches = blockIds; } public void setBlockTypeIds(Map<Block, RenderLayer> blockTypeIds) { if (this.blockTypeIds != null && this.blockTypeIds.equals(blockTypeIds)) { return; } this.reloadRequired = true; this.blockTypeIds = blockTypeIds; } public void setEntityIds(Object2IntFunction<NamespacedId> entityIds) { // note: no reload needed, entities are rebuilt every frame. this.entityIds = entityIds; } public float getAmbientOcclusionLevel() { return ambientOcclusionLevel; } public void setAmbientOcclusionLevel(float ambientOcclusionLevel) { if (ambientOcclusionLevel == this.ambientOcclusionLevel) { return; } this.reloadRequired = true; this.ambientOcclusionLevel = ambientOcclusionLevel; } public boolean shouldDisableDirectionalShading() { return disableDirectionalShading; } public void setDisableDirectionalShading(boolean disableDirectionalShading) { if (disableDirectionalShading == this.disableDirectionalShading) { return; } this.reloadRequired = true; this.disableDirectionalShading = disableDirectionalShading; } public boolean shouldUseSeparateAo() { return useSeparateAo; } public void setUseSeparateAo(boolean useSeparateAo) { if (useSeparateAo == this.useSeparateAo) { return; } this.reloadRequired = true; this.useSeparateAo = useSeparateAo; } public boolean shouldUseExtendedVertexFormat() { return useExtendedVertexFormat; } public void setUseExtendedVertexFormat(boolean useExtendedVertexFormat) { if (useExtendedVertexFormat == this.useExtendedVertexFormat) { return; } this.reloadRequired = true; this.useExtendedVertexFormat = useExtendedVertexFormat; } }
Angelica
src\main\java\net\coderbot\iris\client\IrisDebugScreenHandler.java
package net.coderbot.iris.client; import com.gtnewhorizons.angelica.AngelicaMod; import com.gtnewhorizons.angelica.config.AngelicaConfig; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.coderbot.iris.Iris; import net.minecraft.client.Minecraft; import net.minecraftforge.client.event.RenderGameOverlayEvent; import java.lang.management.BufferPoolMXBean; import java.lang.management.ManagementFactory; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.List; import java.util.Objects; public class IrisDebugScreenHandler { public static final IrisDebugScreenHandler INSTANCE = new IrisDebugScreenHandler(); private static final List<BufferPoolMXBean> iris$pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class); private static final BufferPoolMXBean iris$directPool; static { BufferPoolMXBean found = null; for (BufferPoolMXBean pool : iris$pools) { if (pool.getName().equals("direct")) { found = pool; break; } } iris$directPool = Objects.requireNonNull(found); } @SubscribeEvent(priority = EventPriority.LOW) public void onRenderGameOverlayTextEvent(RenderGameOverlayEvent.Text event) { final Minecraft mc = Minecraft.getMinecraft(); if (mc.gameSettings.showDebugInfo) { event.right.add(Math.min(event.right.size(), 2), "Direct Buffers: +" + iris$humanReadableByteCountBin(iris$directPool.getMemoryUsed())); event.right.add(""); if (Iris.getIrisConfig().areShadersEnabled()) { event.right.add("[" + Iris.MODNAME + "] Shaderpack: " + Iris.getCurrentPackName() + (Iris.isFallback() ? " (fallback)" : "")); Iris.getCurrentPack().ifPresent(pack -> event.right.add("[" + Iris.MODNAME + "] " + pack.getProfileInfo())); } else { event.right.add("[" + Iris.MODNAME + "] Shaders are disabled"); } if (AngelicaConfig.speedupAnimations) { event.right.add(Math.min(event.right.size(), 9), "animationsMode: " + AngelicaMod.animationsMode); } Iris.getPipelineManager().getPipeline().ifPresent(pipeline -> pipeline.addDebugText(event.left)); } } private static String iris$humanReadableByteCountBin(long bytes) { long absB = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes); if (absB < 1024) { return bytes + " B"; } long value = absB; CharacterIterator ci = new StringCharacterIterator("KMGTPE"); for (int i = 40; i >= 0 && absB > 0xfffccccccccccccL >> i; i -= 10) { value >>= 10; ci.next(); } value *= Long.signum(bytes); return String.format("%.3f %ciB", value / 1024.0, ci.current()); } }
Angelica
src\main\java\net\coderbot\iris\config\IrisConfig.java
package net.coderbot.iris.config; import net.coderbot.iris.Iris; import net.coderbot.iris.gui.option.IrisVideoSettings; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Optional; import java.util.Properties; /** * A class dedicated to storing the config values of shaderpacks. Right now it only stores the path to the current shaderpack */ public class IrisConfig { private static final String COMMENT = "This file stores configuration options for " + Iris.MODNAME + ", such as the currently active shaderpack"; /** * The path to the current shaderpack. Null if the internal shaderpack is being used. */ private String shaderPackName; /** * Whether or not shaders are used for rendering. False to disable all shader-based rendering, true to enable it. */ private boolean enableShaders; /** * If the update notification should be disabled or not. */ private boolean disableUpdateMessage; private final Path propertiesPath; public IrisConfig(Path propertiesPath) { shaderPackName = null; enableShaders = true; disableUpdateMessage = false; this.propertiesPath = propertiesPath; } /** * Initializes the configuration, loading it if it is present and creating a default config otherwise. * * @throws IOException file exceptions */ public void initialize() throws IOException { load(); if (!Files.exists(propertiesPath)) { save(); } } /** * returns whether or not the current shaderpack is internal * * @return if the shaderpack is internal */ public boolean isInternal() { return false; } /** * Returns the name of the current shaderpack * * @return Returns the current shaderpack name - if internal shaders are being used it returns "(internal)" */ public Optional<String> getShaderPackName() { return Optional.ofNullable(shaderPackName); } /** * Sets the name of the current shaderpack */ public void setShaderPackName(String name) { if (name == null || name.equals("(internal)") || name.isEmpty()) { this.shaderPackName = null; } else { this.shaderPackName = name; } } /** * Determines whether or not shaders are used for rendering. * * @return False to disable all shader-based rendering, true to enable shader-based rendering. */ public boolean areShadersEnabled() { return enableShaders; } public boolean shouldDisableUpdateMessage() { return disableUpdateMessage; } /** * Sets whether shaders should be used for rendering. */ public void setShadersEnabled(boolean enabled) { this.enableShaders = enabled; } /** * loads the config file and then populates the string, int, and boolean entries with the parsed entries * * @throws IOException if the file cannot be loaded */ public void load() throws IOException { if (!Files.exists(propertiesPath)) { return; } Properties properties = new Properties(); // NB: This uses ISO-8859-1 with unicode escapes as the encoding try (InputStream is = Files.newInputStream(propertiesPath)) { properties.load(is); } shaderPackName = properties.getProperty("shaderPack"); enableShaders = !"false".equals(properties.getProperty("enableShaders")); disableUpdateMessage = "true".equals(properties.getProperty("disableUpdateMessage")); // TODO: GUI try { IrisVideoSettings.shadowDistance = Integer.parseInt(properties.getProperty("maxShadowRenderDistance", "32")); } catch (NumberFormatException e) { Iris.logger.error("Shadow distance setting reset; value is invalid."); IrisVideoSettings.shadowDistance = 32; save(); } if (shaderPackName != null) { if (shaderPackName.equals("(internal)") || shaderPackName.isEmpty()) { shaderPackName = null; } } } /** * Serializes the config into a file. Should be called whenever any config values are modified. * * @throws IOException file exceptions */ public void save() throws IOException { final Properties properties = new Properties(); properties.setProperty("shaderPack", getShaderPackName().orElse("")); properties.setProperty("enableShaders", enableShaders ? "true" : "false"); properties.setProperty("disableUpdateMessage", disableUpdateMessage ? "true" : "false"); properties.setProperty("maxShadowRenderDistance", String.valueOf(IrisVideoSettings.shadowDistance)); // NB: This uses ISO-8859-1 with unicode escapes as the encoding try (OutputStream os = Files.newOutputStream(propertiesPath)) { properties.store(os, COMMENT); } } }
Angelica
src\main\java\net\coderbot\iris\fantastic\IrisParticleRenderTypes.java
package net.coderbot.iris.fantastic; // TODO: RenderType //public class IrisParticleRenderTypes { // public static final ParticleRenderType OPAQUE_TERRAIN = new ParticleRenderType() { // public void begin(BufferBuilder bufferBuilder, TextureManager textureManager) { // GL11.glDisable(GL11.GL_BLEND); // GL11.glDepthMask(true); // GL11.glAlphaFunc(GL11.GL_GREATER, 0.1F); // textureManager.bind(TextureAtlas.LOCATION_BLOCKS); // bufferBuilder.begin(7, DefaultVertexFormat.PARTICLE); // } // // public void end(Tesselator tesselator) { // tesselator.end(); // } // // public String toString() { // return "OPAQUE_TERRAIN_SHEET"; // } // }; //}
Angelica
src\main\java\net\coderbot\iris\fantastic\ParticleRenderingPhase.java
package net.coderbot.iris.fantastic; public enum ParticleRenderingPhase { EVERYTHING, OPAQUE, TRANSLUCENT }
Angelica
src\main\java\net\coderbot\iris\fantastic\PhasedParticleEngine.java
package net.coderbot.iris.fantastic; public interface PhasedParticleEngine { void setParticleRenderingPhase(ParticleRenderingPhase phase); }
Angelica
src\main\java\net\coderbot\iris\fantastic\WrappingMultiBufferSource.java
package net.coderbot.iris.fantastic; import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; import java.util.function.Function; public interface WrappingMultiBufferSource { void pushWrappingFunction(Function<RenderLayer, RenderLayer> wrappingFunction); void popWrappingFunction(); void assertWrapStackEmpty(); }
Angelica
src\main\java\net\coderbot\iris\features\FeatureFlags.java
package net.coderbot.iris.features; import com.gtnewhorizons.angelica.glsm.RenderSystem; import net.minecraft.client.resources.I18n; import org.apache.commons.lang3.text.WordUtils; import java.util.List; import java.util.function.BooleanSupplier; public enum FeatureFlags { SEPARATE_HARDWARE_SAMPLERS(() -> true, () -> true), PER_BUFFER_BLENDING(() -> true, RenderSystem::supportsBufferBlending), COMPUTE_SHADERS(() -> true, RenderSystem::supportsCompute), ENTITY_TRANSLUCENT(() -> true, () -> true), UNKNOWN(() -> false, () -> false); private final BooleanSupplier irisRequirement; private final BooleanSupplier hardwareRequirement; FeatureFlags(BooleanSupplier irisRequirement, BooleanSupplier hardwareRequirement) { this.irisRequirement = irisRequirement; this.hardwareRequirement = hardwareRequirement; } public static String getInvalidStatus(List<FeatureFlags> invalidFeatureFlags) { boolean unsupportedHardware = false, unsupportedIris = false; FeatureFlags[] flags = invalidFeatureFlags.toArray(new FeatureFlags[0]); for (FeatureFlags flag : flags) { unsupportedIris |= !flag.irisRequirement.getAsBoolean(); unsupportedHardware |= !flag.hardwareRequirement.getAsBoolean(); } if (unsupportedIris) { if (unsupportedHardware) { return I18n.format("iris.unsupported.irisorpc"); } return I18n.format("iris.unsupported.iris"); } else if (unsupportedHardware) { return I18n.format("iris.unsupported.pc"); } else { return null; } } public String getHumanReadableName() { return WordUtils.capitalize(name().replace("_", " ").toLowerCase()); } public boolean isUsable() { return irisRequirement.getAsBoolean() && hardwareRequirement.getAsBoolean(); } public static boolean isInvalid(String name) { try { return !FeatureFlags.valueOf(name).isUsable(); } catch (IllegalArgumentException e) { return true; } } public static FeatureFlags getValue(String value) { try { return FeatureFlags.valueOf(value); } catch (IllegalArgumentException e) { return FeatureFlags.UNKNOWN; } } }
Angelica
src\main\java\net\coderbot\iris\gl\GlResource.java
package net.coderbot.iris.gl; public abstract class GlResource { private final int id; private boolean isValid; protected GlResource(int id) { this.id = id; isValid = true; } public final void destroy() { destroyInternal(); isValid = false; } protected abstract void destroyInternal(); protected void assertValid() { if (!isValid) { throw new IllegalStateException("Tried to use a destroyed GlResource"); } } protected int getGlId() { assertValid(); return id; } }
Angelica
src\main\java\net\coderbot\iris\gl\GlVersion.java
package net.coderbot.iris.gl; public enum GlVersion { GL_11, GL_12, GL_30, GL_31 }
Angelica
src\main\java\net\coderbot\iris\gui\FileDialogUtil.java
package net.coderbot.iris.gui; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Class used to make interfacing with {@link TinyFileDialogs} easier and asynchronous. */ public final class FileDialogUtil { private static final ExecutorService FILE_DIALOG_EXECUTOR = Executors.newSingleThreadExecutor(); private FileDialogUtil() {} /** * Opens an asynchronous file select dialog window. * * @param dialog Whether to open a "save" dialog or an "open" dialog * @param title The title of the dialog window * @param origin The path that the window should start at * @param filterLabel A label used to describe what file extensions are allowed and their purpose * @param filters The file extension filters used by the dialog, each formatted as {@code "*.extension"} * @return a {@link CompletableFuture} which is completed once a file is selected or the dialog is cancelled. */ // public static CompletableFuture<Optional<Path>> fileSelectDialog(DialogType dialog, String title, @Nullable Path origin, @Nullable String filterLabel, String ... filters) { // CompletableFuture<Optional<Path>> future = new CompletableFuture<>(); // // FILE_DIALOG_EXECUTOR.submit(() -> { // String result = null; // // try (MemoryStack stack = MemoryStack.stackPush()) { // PointerBuffer filterBuffer = stack.mallocPointer(filters.length); // // for (String filter : filters) { // filterBuffer.put(stack.UTF8(filter)); // } // filterBuffer.flip(); // // String path = origin != null ? origin.toAbsolutePath().toString() : null; // // if (dialog == DialogType.SAVE) { // result = TinyFileDialogs.tinyfd_saveFileDialog(title, path, filterBuffer, filterLabel); // } else if (dialog == DialogType.OPEN) { // result = TinyFileDialogs.tinyfd_openFileDialog(title, path, filterBuffer, filterLabel, false); // } // } // // future.complete(Optional.ofNullable(result).map(Paths::get)); // }); // // return future; // } public enum DialogType { SAVE, OPEN } }
Angelica
src\main\java\net\coderbot\iris\gui\GuiUtil.java
package net.coderbot.iris.gui; import com.gtnewhorizons.angelica.glsm.GLStateManager; import cpw.mods.fml.client.config.GuiUtils; import lombok.Getter; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import net.minecraft.client.resources.I18n; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL14; /** * Class serving as abstraction and * centralization for common GUI * rendering/other code calls. * * Helps allow for easier portability * to Minecraft 1.17 by abstracting * some code that will be changed. */ public final class GuiUtil { public static final ResourceLocation IRIS_WIDGETS_TEX = new ResourceLocation("iris", "textures/gui/widgets.png"); private static final String ELLIPSIS = "..."; private GuiUtil() {} private static Minecraft client() { return Minecraft.getMinecraft(); } /** * Binds Iris's widgets texture to be * used for succeeding draw calls. */ public static void bindIrisWidgetsTexture() { client().getTextureManager().bindTexture(IRIS_WIDGETS_TEX); } /** * Draws a button. Button textures must be mapped with the * same coordinates as those on the vanilla widgets texture. * * @param x X position of the left of the button * @param y Y position of the top of the button * @param width Width of the button, maximum 398 * @param height Height of the button, maximum 20 * @param hovered Whether the button is being hovered over with the mouse * @param disabled Whether the button should use the "disabled" texture */ public static void drawButton(int x, int y, int width, int height, boolean hovered, boolean disabled) { // Create variables for half of the width and height. // Will not be exact when width and height are odd, but // that case is handled within the draw calls. final int halfWidth = width / 2; final int halfHeight = height / 2; // V offset for which button texture to use final int vOffset = disabled ? 46 : hovered ? 86 : 66; // Sets RenderSystem to use solid white as the tint color for blend mode, and enables blend mode GL14.glBlendColor(1.0f, 1.0f, 1.0f, 1.0f); GLStateManager.enableBlend(); // Sets RenderSystem to be able to use textures when drawing GLStateManager.enableTexture(); // Top left section GuiUtils.drawTexturedModalRect(x, y, 0, vOffset, halfWidth, halfHeight, 0); // Top right section GuiUtils.drawTexturedModalRect(x + halfWidth, y, 200 - (width - halfWidth), vOffset, width - halfWidth, halfHeight, 0); // Bottom left section GuiUtils.drawTexturedModalRect(x, y + halfHeight, 0, vOffset + (20 - (height - halfHeight)), halfWidth, height - halfHeight, 0); // Bottom right section GuiUtils.drawTexturedModalRect(x + halfWidth, y + halfHeight, 200 - (width - halfWidth), vOffset + (20 - (height - halfHeight)), width - halfWidth, height - halfHeight, 0); } /** * Draws a translucent black panel * with a light border. * * @param x The x position of the panel * @param y The y position of the panel * @param width The width of the panel * @param height The height of the panel */ public static void drawPanel(int x, int y, int width, int height) { final int borderColor = 0xDEDEDEDE; final int innerColor = 0xDE000000; // Top border section Gui.drawRect(x, y, x + width, y + 1, borderColor); // Bottom border section Gui.drawRect(x, (y + height) - 1, x + width, y + height, borderColor); // Left border section Gui.drawRect(x, y + 1, x + 1, (y + height) - 1, borderColor); // Right border section Gui.drawRect((x + width) - 1, y + 1, x + width, (y + height) - 1, borderColor); // Inner section Gui.drawRect(x + 1, y + 1, (x + width) - 1, (y + height) - 1, innerColor); } /** * Draws a text with a panel behind it. * * @param text The text String to draw * @param x The x position of the panel * @param y The y position of the panel */ public static void drawTextPanel(FontRenderer font, String text, int x, int y) { drawPanel(x, y, font.getStringWidth(text) + 8, 16); font.drawStringWithShadow(text, x + 4, y + 4, 0xFFFFFF); } /** * Shorten a text to a specific length, adding an ellipsis (...) * to the end if shortened. * * Text may lose formatting. * * @param font Font to use for determining the width of text * @param text Text to shorten * @param width Width to shorten text to * @return a shortened text */ public static String shortenText(FontRenderer font, String text, int width) { if (font.getStringWidth(text) > width) { return font.trimStringToWidth(text, width - font.getStringWidth(ELLIPSIS)) + ELLIPSIS; } return text; } /** * Creates a new translated text, if a translation * is present. If not, will return the default text * String passed. * * @param defaultText Default text to use if no translation is found * @param translationDesc Translation key to try and use * @param format Formatting arguments for the translated text, if created * @return the translated text if found, otherwise the default provided */ public static String translateOrDefault(String defaultText, String translationDesc, Object ... format) { final String translated = I18n.format(translationDesc, format); if(!translated.equals(translationDesc)) { return translated; } return defaultText; } /** * Plays the {@code UI_BUTTON_CLICK} sound event as a * master sound effect. * * Used in non-{@code ButtonWidget} UI elements upon click * or other action. */ public static void playButtonClickSound() { // client().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1)); } /** * A class representing a section of a * texture, to be easily drawn in GUIs. */ public static class Icon { public static final Icon SEARCH = new Icon(0, 0, 7, 8); public static final Icon CLOSE = new Icon(7, 0, 5, 6); public static final Icon REFRESH = new Icon(12, 0, 10, 10); public static final Icon EXPORT = new Icon(22, 0, 7, 8); public static final Icon EXPORT_COLORED = new Icon(29, 0, 7, 8); public static final Icon IMPORT = new Icon(22, 8, 7, 8); public static final Icon IMPORT_COLORED = new Icon(29, 8, 7, 8); private final int u; private final int v; @Getter private final int width; @Getter private final int height; public Icon(int u, int v, int width, int height) { this.u = u; this.v = v; this.width = width; this.height = height; } /** * Draws this icon to the screen at the specified coordinates. * * @param x The x position to draw the icon at (left) * @param y The y position to draw the icon at (top) */ public void draw(int x, int y) { // Sets RenderSystem to use solid white as the tint color for blend mode, and enables blend mode GL14.glBlendColor(1.0f, 1.0f, 1.0f, 1.0f); GLStateManager.enableBlend(); // Sets RenderSystem to be able to use textures when drawing GLStateManager.enableTexture(); // Draw the texture to the screen GuiUtils.drawTexturedModalRect(x, y, u, v, width, height, 256); } } }
Angelica
src\main\java\net\coderbot\iris\gui\NavigationController.java
package net.coderbot.iris.gui; import lombok.Getter; import net.coderbot.iris.gui.element.ShaderPackOptionList; import java.util.ArrayDeque; import java.util.Deque; public class NavigationController { private ShaderPackOptionList optionList; @Getter private String currentScreen = null; private final Deque<String> history = new ArrayDeque<>(); public void back() { if (history.size() > 0) { history.removeLast(); if (history.size() > 0) { currentScreen = history.getLast(); } else { currentScreen = null; } } else { currentScreen = null; } this.rebuild(); } public void open(String screen) { currentScreen = screen; history.addLast(screen); this.rebuild(); } public void rebuild() { if (optionList != null) { optionList.rebuild(); } } public void refresh() { if (optionList != null) { optionList.refresh(); } } public boolean hasHistory() { return this.history.size() > 0; } public void setActiveOptionList(ShaderPackOptionList optionList) { this.optionList = optionList; } }
Angelica
src\main\java\net\coderbot\iris\layer\GbufferPrograms.java
package net.coderbot.iris.layer; import net.coderbot.iris.Iris; import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; import net.coderbot.iris.gl.state.StateUpdateNotifiers; import net.coderbot.iris.pipeline.WorldRenderingPhase; import net.coderbot.iris.pipeline.WorldRenderingPipeline; public class GbufferPrograms { private static boolean entities; private static boolean blockEntities; private static boolean outline; private static Runnable phaseChangeListener; private static void checkReentrancy() { if (entities || blockEntities || outline) { throw new IllegalStateException("GbufferPrograms in weird state, tried to call begin function when entities = " + entities + ", blockEntities = " + blockEntities + ", outline = " + outline); } } public static void beginEntities() { checkReentrancy(); setPhase(WorldRenderingPhase.ENTITIES); entities = true; } public static void endEntities() { if (!entities) { throw new IllegalStateException("GbufferPrograms in weird state, tried to call endEntities when entities = false"); } setPhase(WorldRenderingPhase.NONE); entities = false; } public static void beginOutline() { checkReentrancy(); setPhase(WorldRenderingPhase.OUTLINE); outline = true; } public static void endOutline() { if (!outline) { throw new IllegalStateException("GbufferPrograms in weird state, tried to call endOutline when outline = false"); } setPhase(WorldRenderingPhase.NONE); outline = false; } public static void beginBlockEntities() { checkReentrancy(); setPhase(WorldRenderingPhase.BLOCK_ENTITIES); blockEntities = true; } public static void endBlockEntities() { if (!blockEntities) { throw new IllegalStateException("GbufferPrograms in weird state, tried to call endBlockEntities when blockEntities = false"); } setPhase(WorldRenderingPhase.NONE); blockEntities = false; } public static WorldRenderingPhase getCurrentPhase() { final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); if (pipeline != null) { return pipeline.getPhase(); } else { return WorldRenderingPhase.NONE; } } private static void setPhase(WorldRenderingPhase phase) { final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); if (pipeline != null) { pipeline.setPhase(phase); } } public static void setOverridePhase(WorldRenderingPhase phase) { final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); if (pipeline != null) { pipeline.setOverridePhase(phase); } } public static void runPhaseChangeNotifier() { if (phaseChangeListener != null) { phaseChangeListener.run(); } } public static void setupSpecialRenderCondition(SpecialCondition override) { Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setSpecialCondition(override)); } public static void teardownSpecialRenderCondition() { Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setSpecialCondition(null)); } static { StateUpdateNotifiers.phaseChangeNotifier = listener -> phaseChangeListener = listener; } public static void init() { // Empty initializer to run static } }