repo_id
stringclasses 383
values | file_path
stringlengths 7
168
| content
stringlengths 0
1.75M
|
|---|---|---|
acedium
|
build.gradle
|
plugins {
id 'dev.architectury.loom' version '1.4-SNAPSHOT'
id 'maven-publish'
}
version = project.mod_version
group = project.maven_group
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
loom {
runs {
it.configureEach {
vmArgs("-Xmx8G", "-XX:+UseZGC")
}
}
silentMojangMappingsLicense()
}
processResources {
inputs.property "version", project.version
archivesBaseName = "acedium"
filesMatching("META-INF/mods.toml") {
expand "version": project.version
}
}
repositories {
maven {
name = "Modrinth"
url = "https://api.modrinth.com/maven"
content {
includeGroup "maven.modrinth"
}
}
maven { url "https://maven.neoforged.net" }
}
dependencies {
mappings loom.layered() {
it.mappings("net.fabricmc:yarn:${project.yarn_mappings}:v2")
it.mappings file("mappings/yarnpatch.tiny")
}
// To change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:${project.minecraft_version}"
//mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
neoForge "net.neoforged:neoforge:${project.neoforge_version}"
modImplementation "maven.modrinth:embeddium:0.3.14+mc1.20.4"
modCompileOnly "maven.modrinth:oculus:1.20.1-1.7.0"
// Fabric API
//modImplementation(fabricApi.module("fabric-api-base", project.fabric_version))
//modImplementation(fabricApi.module("fabric-block-view-api-v2", project.fabric_version))
//modImplementation(fabricApi.module("fabric-rendering-fluids-v1", project.fabric_version))
//modImplementation("net.fabricmc.fabric-api:fabric-rendering-data-attachment-v1:0.3.40+73761d2e3b")
//modImplementation(fabricApi.module("fabric-resource-loader-v0", project.fabric_version))
//modImplementation "maven.modrinth:c2me-fabric:0.2.0+alpha.10.49+1.19.4"
//modImplementation "maven.modrinth:chunks-fade-in:v1.0.3-1.19.4"
//modImplementation "maven.modrinth:immersiveportals:v2.7.3-mc1.19.4"
//modCompileOnly "maven.modrinth:iris:1.7.0+1.20.6"
}
|
acedium
|
settings.gradle
|
pluginManagement {
repositories {
maven {
name = 'Fabric'
url = 'https://maven.fabricmc.net/'
}
maven { url "https://maven.neoforged.net" }
maven { url "https://maven.architectury.dev/" }
mavenCentral()
gradlePluginPortal()
}
}
|
acedium
|
src\main\resources\fabric.mod.json
|
{
"schemaVersion": 1,
"id": "nvidium",
"version": "${version}",
"name": "Nvidium",
"description": "Replacement rendering engine for sodium",
"authors": [
"Cortex"
],
"contact": {},
"license": "LGPL-3.0",
"icon": "assets/nvidium/nvidium.png",
"environment": "client",
"entrypoints": {},
"mixins": [
"nvidium.mixins.json"
],
"depends": {
"fabricloader": ">=0.15",
"minecraft": ">=1.20.6",
"sodium": ["=0.5.8"]
}
}
|
acedium
|
src\main\resources\nvidium.mixins.json
|
{
"required": true,
"package": "me.cortex.nvidium.mixin",
"compatibilityLevel": "JAVA_17",
"client": [
"minecraft.LightMapAccessor",
"minecraft.MixinBackgroundRenderer",
"minecraft.MixinGameRenderer",
"minecraft.MixinMinecraftClient",
"minecraft.MixinWindow",
"minecraft.MixinWorldRenderer",
"sodium.MixinChunkBuilder",
"sodium.MixinChunkBuilderMeshingTask",
"sodium.MixinChunkBuildOutput",
"sodium.MixinChunkJobQueue",
"sodium.MixinOptionFlag",
"sodium.MixinRenderRegionManager",
"sodium.MixinRenderSection",
"sodium.MixinRenderSectionManager",
"sodium.MixinSodiumOptionsGUI",
"sodium.MixinSodiumWorldRenderer",
"sodium.SodiumWorldRendererAccessor"
],
"injectors": {
"defaultRequire": 1
},
"minVersion": "0.8.4",
"refmap": "nvidium.refmap.json"
}
|
acedium
|
src\main\java\me\cortex\nvidium\Nvidium.java
|
package me.cortex.nvidium;
import me.cortex.nvidium.config.NvidiumConfig;
import net.minecraft.util.Util;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.IExtensionPoint;
import net.neoforged.fml.ModLoadingContext;
import net.neoforged.fml.common.Mod;
import net.neoforged.fml.event.lifecycle.FMLConstructModEvent;
import net.neoforged.fml.loading.FMLLoader;
import org.lwjgl.opengl.GL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//NOTE: with sodium async bfs, just reimplement the bfs dont try to convert sodiums bfs into async
@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT, modid = Nvidium.MOD_ID)
@Mod(Nvidium.MOD_ID)
public class Nvidium {
public static final String MOD_ID = "acedium";
public static String MOD_VERSION;
public static final Logger LOGGER = LoggerFactory.getLogger("Acedium");
public static boolean IS_COMPATIBLE = false;
public static boolean IS_ENABLED = false;
public static boolean IS_DEBUG = System.getProperty("nvidium.isDebug", "false").equals("TRUE");
public static boolean SUPPORTS_PERSISTENT_SPARSE_ADDRESSABLE_BUFFER = true;
public static boolean FORCE_DISABLE = false;
public static NvidiumConfig config;
public Nvidium() {
}
@SubscribeEvent
public static void modLoading(FMLConstructModEvent event) {
config = NvidiumConfig.loadOrCreate();
config.save();
MOD_VERSION = FMLLoader.getLoadingModList().getModFileById(MOD_ID).versionString();
}
//TODO: basicly have the terrain be a virtual geometry buffer
// once it gets too full, start culling via a callback task system
// which executes a task on the gpu and calls back once its done
// use this to then do a rasterizing check on the terrain and remove
// the oldest regions and sections
//TODO: ADD LODS
public static void checkSystemIsCapable() {
var cap = GL.getCapabilities();
boolean supported = cap.GL_NV_mesh_shader &&
cap.GL_NV_uniform_buffer_unified_memory &&
cap.GL_NV_vertex_buffer_unified_memory &&
cap.GL_NV_representative_fragment_test &&
cap.GL_ARB_sparse_buffer &&
cap.GL_NV_bindless_multi_draw_indirect;
IS_COMPATIBLE = supported;
if (IS_COMPATIBLE) {
LOGGER.info("All capabilities met");
} else {
LOGGER.warn("Not all requirements met, disabling nvidium (acedium)");
}
if (IS_COMPATIBLE && Util.getOperatingSystem() == Util.OperatingSystem.LINUX) {
LOGGER.warn("Linux currently uses fallback terrain buffer due to driver inconsistencies, expect increase vram usage");
SUPPORTS_PERSISTENT_SPARSE_ADDRESSABLE_BUFFER = false;
}
if (IS_COMPATIBLE) {
LOGGER.info("Enabling Nvidium (Acedium)");
}
IS_ENABLED = IS_COMPATIBLE;
}
public static void setupGLDebugCallback() {
}
public static void preWindowInit() {
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\NvidiumStub.java
|
package me.cortex.nvidium;
import net.neoforged.fml.common.Mod;
@Mod("nvidium")
public class NvidiumStub {
public NvidiumStub() {
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\NvidiumWorldRenderer.java
|
package me.cortex.nvidium;
import me.cortex.nvidium.gl.RenderDevice;
import me.cortex.nvidium.managers.AsyncOcclusionTracker;
import me.cortex.nvidium.managers.SectionManager;
import me.cortex.nvidium.sodiumCompat.NvidiumCompactChunkVertex;
import me.cortex.nvidium.util.DownloadTaskStream;
import me.cortex.nvidium.util.UploadingBufferStream;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderMatrices;
import me.jellysquid.mods.sodium.client.render.chunk.RenderSection;
import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildOutput;
import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.impl.CompactChunkVertex;
import me.jellysquid.mods.sodium.client.render.viewport.Viewport;
import net.minecraft.client.render.Camera;
import net.minecraft.client.texture.Sprite;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4fc;
import org.joml.Matrix4x3fc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.lwjgl.opengl.GL11.glGetInteger;
import static org.lwjgl.opengl.GL11.glNewList;
import static org.lwjgl.opengl.NVXGPUMemoryInfo.GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX;
public class NvidiumWorldRenderer {
private static final RenderDevice device = new RenderDevice();
private final UploadingBufferStream uploadStream;
private final DownloadTaskStream downloadStream;
private final SectionManager sectionManager;
private final RenderPipeline renderPipeline;
private final AsyncOcclusionTracker asyncChunkTracker;
//Max memory that the gpu can use to store geometry in mb
private long max_geometry_memory;
private long last_sample_time;
//Note: the reason that asyncChunkTracker is passed in as an already constructed object is cause of the amount of argmuents it takes to construct it
public NvidiumWorldRenderer(AsyncOcclusionTracker asyncChunkTracker) {
int frames = SodiumClientMod.options().advanced.cpuRenderAheadLimit+1;
//32 mb upload buffer
this.uploadStream = new UploadingBufferStream(device, 32000000);
//8 mb download buffer
this.downloadStream = new DownloadTaskStream(device, frames, 8000000);
update_allowed_memory();
//this.sectionManager = new SectionManager(device, max_geometry_memory*1024*1024, uploadStream, 150, 24, CompactChunkVertex.STRIDE);
this.sectionManager = new SectionManager(device, max_geometry_memory*1024*1024, uploadStream, NvidiumCompactChunkVertex.STRIDE, this);
this.renderPipeline = new RenderPipeline(device, uploadStream, downloadStream, sectionManager);
this.asyncChunkTracker = asyncChunkTracker;
}
//TODO: cleanup this spagetti
public void enqueueRegionSort(int regionId) {
this.renderPipeline.enqueueRegionSort(regionId);
}
public void delete() {
uploadStream.delete();
downloadStream.delete();
renderPipeline.delete();
if (asyncChunkTracker != null) {
asyncChunkTracker.delete();
}
sectionManager.destroy();
}
public void reloadShaders() {
renderPipeline.reloadShaders();
}
public void renderFrame(Viewport viewport, ChunkRenderMatrices matrices, double x, double y, double z) {
renderPipeline.renderFrame(viewport, matrices, x, y, z);
if (sectionManager.terrainAreana.getUsedMB()>(max_geometry_memory-50)) {
renderPipeline.removeARegion();
}
if (Nvidium.SUPPORTS_PERSISTENT_SPARSE_ADDRESSABLE_BUFFER && (System.currentTimeMillis() - last_sample_time) > 60000) {
last_sample_time = System.currentTimeMillis();
update_allowed_memory();
}
}
public void renderTranslucent() {
this.renderPipeline.renderTranslucent();
}
public void deleteSection(RenderSection section) {
this.sectionManager.deleteSection(section);
}
public void uploadBuildResult(ChunkBuildOutput buildOutput) {
this.sectionManager.uploadChunkBuildResult(buildOutput);
}
public void addDebugInfo(ArrayList<String> debugInfo) {
debugInfo.add("Using nvidium renderer: "+ Nvidium.MOD_VERSION);
debugInfo.add("Memory limit: " + max_geometry_memory + " mb");
debugInfo.add("Terrain Memory MB: " + sectionManager.terrainAreana.getAllocatedMB()+(Nvidium.SUPPORTS_PERSISTENT_SPARSE_ADDRESSABLE_BUFFER?"":" (fallback mode)"));
debugInfo.add(String.format("Fragmentation: %.2f", sectionManager.terrainAreana.getFragmentation()*100));
debugInfo.add("Regions: " + sectionManager.getRegionManager().regionCount() + "/" + sectionManager.getRegionManager().maxRegions());
if (asyncChunkTracker != null) {
debugInfo.add("Async BFS iteration time: " + asyncChunkTracker.getIterationTime());
debugInfo.add("Build queue sizes: " + Arrays.toString(this.asyncChunkTracker.getBuildQueueSizes()));
}
renderPipeline.addDebugInfo(debugInfo);
}
private void update_allowed_memory() {
if (Nvidium.config.automatic_memory) {
max_geometry_memory = (glGetInteger(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX) / 1024) + (sectionManager==null?0:sectionManager.terrainAreana.getMemoryUsed()/(1024*1024));
max_geometry_memory -= 1024;//Minus 1gb of vram
max_geometry_memory = Math.max(2048, max_geometry_memory);//Minimum 2 gb of vram
} else {
max_geometry_memory = Nvidium.config.max_geometry_memory;
}
}
public void update(Camera camera, Viewport viewport, int frame, boolean spectator) {
if (asyncChunkTracker != null) {
asyncChunkTracker.update(viewport, camera, spectator);
}
}
public int getAsyncFrameId() {
if (asyncChunkTracker != null) {
return asyncChunkTracker.getFrame();
} else {
return -1;
}
}
public List<RenderSection> getSectionsWithEntities() {
if (asyncChunkTracker != null) {
return asyncChunkTracker.getLatestSectionsWithEntities();
} else {
return List.of();
}
}
public SectionManager getSectionManager() {
return sectionManager;
}
@Nullable
public Sprite[] getAnimatedSpriteSet() {
if (asyncChunkTracker != null) {
return asyncChunkTracker.getVisibleAnimatedSprites();
} else {
return new Sprite[0];
}
}
public void setTransformation(int id, Matrix4fc transform) {
this.renderPipeline.setTransformation(id, transform);
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\RenderPipeline.java
|
package me.cortex.nvidium;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import it.unimi.dsi.fastutil.ints.*;
import me.cortex.nvidium.api0.NvidiumAPI;
import me.cortex.nvidium.config.StatisticsLoggingLevel;
import me.cortex.nvidium.config.TranslucencySortingLevel;
import me.cortex.nvidium.gl.RenderDevice;
import me.cortex.nvidium.gl.buffers.IDeviceMappedBuffer;
import me.cortex.nvidium.managers.RegionManager;
import me.cortex.nvidium.managers.RegionVisibilityTracker;
import me.cortex.nvidium.managers.SectionManager;
import me.cortex.nvidium.renderers.*;
import me.cortex.nvidium.util.DownloadTaskStream;
import me.cortex.nvidium.util.TickableManager;
import me.cortex.nvidium.util.UploadingBufferStream;
import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderMatrices;
import me.jellysquid.mods.sodium.client.render.viewport.Viewport;
import org.joml.*;
import org.lwjgl.opengl.GL11C;
import org.lwjgl.system.MemoryUtil;
import java.lang.Math;
import java.util.BitSet;
import java.util.List;
import static me.cortex.nvidium.gl.buffers.PersistentSparseAddressableBuffer.alignUp;
import static org.lwjgl.opengl.ARBDirectStateAccess.glClearNamedBufferSubData;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL30C.GL_R8UI;
import static org.lwjgl.opengl.GL30C.GL_RED_INTEGER;
import static org.lwjgl.opengl.GL42.*;
import static org.lwjgl.opengl.GL43C.GL_SHADER_STORAGE_BARRIER_BIT;
import static org.lwjgl.opengl.NVRepresentativeFragmentTest.GL_REPRESENTATIVE_FRAGMENT_TEST_NV;
import static org.lwjgl.opengl.NVShaderBufferStore.GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV;
import static org.lwjgl.opengl.NVUniformBufferUnifiedMemory.GL_UNIFORM_BUFFER_ADDRESS_NV;
import static org.lwjgl.opengl.NVUniformBufferUnifiedMemory.GL_UNIFORM_BUFFER_UNIFIED_NV;
import static org.lwjgl.opengl.NVVertexBufferUnifiedMemory.*;
//TODO: extract out sectionManager, uploadStream, downloadStream and other funky things to an auxiliary parent NvidiumWorldRenderer class
public class RenderPipeline {
public static final int GL_DRAW_INDIRECT_UNIFIED_NV = 0x8F40;
public static final int GL_DRAW_INDIRECT_ADDRESS_NV = 0x8F41;
private final RenderDevice device;
private final UploadingBufferStream uploadStream;
private final DownloadTaskStream downloadStream;
private final SectionManager sectionManager;
public final RegionVisibilityTracker regionVisibilityTracking;
private PrimaryTerrainRasterizer terrainRasterizer;
private RegionRasterizer regionRasterizer;
private SectionRasterizer sectionRasterizer;
private TemporalTerrainRasterizer temporalRasterizer;
private TranslucentTerrainRasterizer translucencyTerrainRasterizer;
private SortRegionSectionPhase regionSectionSorter;
private final IDeviceMappedBuffer sceneUniform;
private static final int SCENE_SIZE = (int) alignUp(4*4*4+4*4+4*4+4+4*4+4*4+8*8+3*4+3+4, 2);
private final IDeviceMappedBuffer regionVisibility;
private final IDeviceMappedBuffer sectionVisibility;
private final IDeviceMappedBuffer terrainCommandBuffer;
private final IDeviceMappedBuffer translucencyCommandBuffer;
private final IDeviceMappedBuffer regionSortingList;
private final IDeviceMappedBuffer statisticsBuffer;
private final IDeviceMappedBuffer transformationArray;
private final BitSet regionVisibilityTracker;
//Set of regions that need to be sorted
private final IntSet regionsToSort = new IntOpenHashSet();
private static final class Statistics {
public int frustumCount;
public int regionCount;
public int sectionCount;
public int quadCount;
}
private final Statistics stats;
public RenderPipeline(RenderDevice device, UploadingBufferStream uploadStream, DownloadTaskStream downloadStream, SectionManager sectionManager) {
this.device = device;
this.uploadStream = uploadStream;
this.downloadStream = downloadStream;
this.sectionManager = sectionManager;
terrainRasterizer = new PrimaryTerrainRasterizer();
regionRasterizer = new RegionRasterizer();
sectionRasterizer = new SectionRasterizer();
temporalRasterizer = new TemporalTerrainRasterizer();
translucencyTerrainRasterizer = new TranslucentTerrainRasterizer();
regionSectionSorter = new SortRegionSectionPhase();
int maxRegions = sectionManager.getRegionManager().maxRegions();
sceneUniform = device.createDeviceOnlyMappedBuffer(SCENE_SIZE + maxRegions*2L);
regionVisibility = device.createDeviceOnlyMappedBuffer(maxRegions);
sectionVisibility = device.createDeviceOnlyMappedBuffer(maxRegions * 256L);
terrainCommandBuffer = device.createDeviceOnlyMappedBuffer(maxRegions*8L);
translucencyCommandBuffer = device.createDeviceOnlyMappedBuffer(maxRegions*8L);
regionSortingList = device.createDeviceOnlyMappedBuffer(maxRegions*2L);
this.transformationArray = device.createDeviceOnlyMappedBuffer(RegionManager.MAX_TRANSFORMATION_COUNT * (4*4*4));
regionVisibilityTracker = new BitSet(maxRegions);
regionVisibilityTracking = new RegionVisibilityTracker(downloadStream, maxRegions);
statisticsBuffer = device.createDeviceOnlyMappedBuffer(4*4);
stats = new Statistics();
//Initialize the transformationArray buffer to the identity affine transform
{
long ptr = this.uploadStream.upload(this.transformationArray, 0, RegionManager.MAX_TRANSFORMATION_COUNT * (4*4*4));
var transform = new Matrix4f().identity();
for (int i = 0; i < RegionManager.MAX_TRANSFORMATION_COUNT; i++) {
transform.getToAddress(ptr);
ptr += 4*4*4;
}
}
}
//TODO: FIXME: optimize this so that multiple uploads just upload a single time per frame!!!
// THIS IS CRITICAL
public void setTransformation(int id, Matrix4fc transform) {
if (id < 0 || id >= RegionManager.MAX_TRANSFORMATION_COUNT) {
throw new IllegalArgumentException("Id out of bounds: " + id);
}
long ptr = this.uploadStream.upload(this.transformationArray, id * (4*4*4), 4*4*4);
transform.getToAddress(ptr);
}
private int prevRegionCount;
private int frameId;
//ISSUE TODO: regions that where in frustum but are now out of frustum must have the visibility data cleared
// this is due to funny issue of pain where the section was "visible" last frame cause it didnt get ticked
public void renderFrame(Viewport frustum, ChunkRenderMatrices crm, double px, double py, double pz) {//NOTE: can use any of the command list rendering commands to basicly draw X indirects using the same shader, thus allowing for terrain to be rendered very efficently
if (sectionManager.getRegionManager().regionCount() == 0) return;//Dont render anything if there is nothing to render
final int DEBUG_RENDER_LEVEL = 0;//0: no debug, 1: region debug, 2: section debug
final boolean WRITE_DEPTH = false;
//new NvidiumAPI("nvidium").setRegionTransformId(0, 0, 2, 0);
//new NvidiumAPI("nvidium").setTransformation(0, new Matrix4f().identity().scale(1f,1,1));
Vector3i blockPos = new Vector3i(((int)Math.floor(px)), ((int)Math.floor(py)), ((int)Math.floor(pz)));
Vector3i chunkPos = new Vector3i(blockPos.x>>4,blockPos.y>>4,blockPos.z>>4);
// /tp @p 0.0 -1.62 0.0 0 0
//Clear the first gl error, not our fault
//glGetError();
int visibleRegions = 0;
long queryAddr = 0;
var rm = sectionManager.getRegionManager();
short[] regionMap;
//Enqueue all the visible regions
{
//The region data indicies is located at the end of the sceneUniform
IntSortedSet regions = new IntAVLTreeSet();
for (int i = 0; i < rm.maxRegionIndex(); i++) {
if (!rm.regionExists(i)) continue;
if ((Nvidium.config.region_keep_distance != 256 && Nvidium.config.region_keep_distance != 32) && !rm.withinSquare(Nvidium.config.region_keep_distance+4, i, chunkPos.x, chunkPos.y, chunkPos.z)) {
removeRegion(i);
continue;
}
//TODO: fog culling/region removal cause with bobby the removal distance is huge and people run out of vram very fast
if (rm.isRegionVisible(frustum, i)) {
//Note, its sorted like this because of overdraw, also the translucency command buffer is written to
// in a reverse order to this in the section_raster/task.glsl shader
regions.add(((rm.distance(i, chunkPos.x, chunkPos.y, chunkPos.z))<<16)|i);
visibleRegions++;
regionVisibilityTracker.set(i);
if (rm.isRegionInACameraAxis(i, px, py, pz)) {
regionsToSort.add(i);
}
} else {
if (regionVisibilityTracker.get(i)) {//Going from visible to non visible
//Clear the visibility bits
if (Nvidium.config.enable_temporal_coherence) {
glClearNamedBufferSubData(sectionVisibility.getId(), GL_R8UI, (long) i << 8, 255, GL_RED_INTEGER, GL_UNSIGNED_BYTE, new int[]{0});
}
}
regionVisibilityTracker.clear(i);
}
}
regionMap = new short[regions.size()];
if (visibleRegions == 0) return;
long addr = uploadStream.upload(sceneUniform, SCENE_SIZE, visibleRegions*2);
queryAddr = addr;//This is ungodly hacky
int j = 0;
for (int i : regions) {
regionMap[j] = (short) i;
MemoryUtil.memPutShort(addr+((long) j <<1), (short) i);
j++;
}
if (Nvidium.config.statistics_level != StatisticsLoggingLevel.NONE) {
stats.frustumCount = regions.size();
}
}
{
//TODO: maybe segment the uniform buffer into 2 parts, always updating and static where static holds pointers
Vector3f delta = new Vector3f((float) (px-(chunkPos.x<<4)), (float) (py-(chunkPos.y<<4)), (float) (pz-(chunkPos.z<<4)));
delta.negate();
long addr = uploadStream.upload(sceneUniform, 0, SCENE_SIZE);
var mvp =new Matrix4f(crm.projection())
.mul(crm.modelView())
.translate(delta)//Translate the subchunk position
.getToAddress(addr);
addr += 4*4*4;
new Vector4i(chunkPos.x, chunkPos.y, chunkPos.z, 0).getToAddress(addr);//Chunk the camera is in//TODO: THIS
addr += 16;
new Vector4f(delta,0).getToAddress(addr);//Subchunk offset (note, delta is already negated)
addr += 16;
new Vector4f(RenderSystem.getShaderFogColor()).getToAddress(addr);
addr += 16;
MemoryUtil.memPutLong(addr, sceneUniform.getDeviceAddress() + SCENE_SIZE);//Put in the location of the region indexs
addr += 8;
MemoryUtil.memPutLong(addr, sectionManager.getRegionManager().getRegionBufferAddress());
addr += 8;
MemoryUtil.memPutLong(addr, sectionManager.getRegionManager().getSectionBufferAddress());
addr += 8;
MemoryUtil.memPutLong(addr, regionVisibility.getDeviceAddress());
addr += 8;
MemoryUtil.memPutLong(addr, sectionVisibility.getDeviceAddress());
addr += 8;
MemoryUtil.memPutLong(addr, terrainCommandBuffer.getDeviceAddress());
addr += 8;
MemoryUtil.memPutLong(addr, translucencyCommandBuffer.getDeviceAddress());
addr += 8;
MemoryUtil.memPutLong(addr, regionSortingList.getDeviceAddress());
addr += 8;
MemoryUtil.memPutLong(addr, sectionManager.terrainAreana.buffer.getDeviceAddress());
addr += 8;
MemoryUtil.memPutLong(addr, this.transformationArray.getDeviceAddress());
addr += 8;
MemoryUtil.memPutLong(addr, statisticsBuffer == null?0:statisticsBuffer.getDeviceAddress());//Logging buffer
addr += 8;
MemoryUtil.memPutFloat(addr, RenderSystem.getShaderFogStart());//FogStart
addr += 4;
MemoryUtil.memPutFloat(addr, RenderSystem.getShaderFogEnd());//FogEnd
addr += 4;
MemoryUtil.memPutInt(addr, RenderSystem.getShaderFogShape().getId());//IsSphericalFog
addr += 4;
MemoryUtil.memPutShort(addr, (short) visibleRegions);
addr += 2;
MemoryUtil.memPutByte(addr, (byte) (frameId++));
}
if (Nvidium.config.translucency_sorting_level == TranslucencySortingLevel.NONE) {
regionsToSort.clear();
}
int regionSortSize = this.regionsToSort.size();
if (regionSortSize != 0){
long regionSortUpload = uploadStream.upload(regionSortingList, 0, regionSortSize * 2);
for (int region : regionsToSort) {
MemoryUtil.memPutShort(regionSortUpload, (short) region);
regionSortUpload += 2;
}
regionsToSort.clear();
}
sectionManager.commitChanges();//Commit all uploads done to the terrain and meta data
uploadStream.commit();
TickableManager.TickAll();
//if ((err = glGetError()) != 0) {
// throw new IllegalStateException("GLERROR: "+err);
//}
glEnableClientState(GL_UNIFORM_BUFFER_UNIFIED_NV);
glEnableClientState(GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV);
glEnableClientState(GL_ELEMENT_ARRAY_UNIFIED_NV);
glEnableClientState(GL_DRAW_INDIRECT_UNIFIED_NV);
//Bind the uniform, it doesnt get wiped between shader changes
glBufferAddressRangeNV(GL_UNIFORM_BUFFER_ADDRESS_NV, 0, sceneUniform.getDeviceAddress(), SCENE_SIZE);
if (prevRegionCount != 0) {
glEnable(GL_DEPTH_TEST);
terrainRasterizer.raster(prevRegionCount, terrainCommandBuffer.getDeviceAddress());
glMemoryBarrier(GL_FRAMEBUFFER_BARRIER_BIT);
}
//NOTE: For GL_REPRESENTATIVE_FRAGMENT_TEST_NV to work, depth testing must be disabled, or depthMask = false
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glDepthMask(false);
if (DEBUG_RENDER_LEVEL == 1 && WRITE_DEPTH) {
glDepthMask(true);
}
if (DEBUG_RENDER_LEVEL != 1) {
glColorMask(false, false, false, false);
}
if (DEBUG_RENDER_LEVEL == 0)
{
glEnable(GL_REPRESENTATIVE_FRAGMENT_TEST_NV);
}
regionRasterizer.raster(visibleRegions);
if (DEBUG_RENDER_LEVEL == 1) {
glColorMask(false, false, false, false);
}
//glMemoryBarrier(GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
//glColorMask(true, true, true, true);
if (DEBUG_RENDER_LEVEL == 2) {
glColorMask(true, true, true, true);
}
if (DEBUG_RENDER_LEVEL == 2 && WRITE_DEPTH) {
glDepthMask(true);
}
sectionRasterizer.raster(visibleRegions);
glDisable(GL_REPRESENTATIVE_FRAGMENT_TEST_NV);
glDepthMask(true);
glColorMask(true, true, true, true);
//glMemoryBarrier(GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
prevRegionCount = visibleRegions;
//Do temporal rasterization
if (Nvidium.config.enable_temporal_coherence) {
glMemoryBarrier(GL_COMMAND_BARRIER_BIT);
temporalRasterizer.raster(visibleRegions, terrainCommandBuffer.getDeviceAddress());
}
{//Do proper visibility tracking
glDepthMask(false);
glColorMask(false, false, false, false);
glEnable(GL_REPRESENTATIVE_FRAGMENT_TEST_NV);
regionVisibilityTracking.computeVisibility(visibleRegions, regionVisibility, regionMap);
glDisable(GL_REPRESENTATIVE_FRAGMENT_TEST_NV);
glDepthMask(true);
glColorMask(true, true, true, true);
}
if (regionSortSize != 0) {
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
regionSectionSorter.dispatch(regionSortSize);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
}
glDisableClientState(GL_UNIFORM_BUFFER_UNIFIED_NV);
glDisableClientState(GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV);
glDisableClientState(GL_ELEMENT_ARRAY_UNIFIED_NV);
glDisableClientState(GL_DRAW_INDIRECT_UNIFIED_NV);
glDepthFunc(GL11C.GL_LEQUAL);
glDisable(GL_DEPTH_TEST);
//if ((err = glGetError()) != 0) {
// throw new IllegalStateException("GLERROR: "+err);
//}
}
void enqueueRegionSort(int regionId) {
this.regionsToSort.add(regionId);
}
//TODO: refactor to different location
private void removeRegion(int id) {
sectionManager.removeRegionById(id);
regionVisibilityTracking.resetRegion(id);
}
//TODO: refactor out of the render pipeline along with regionVisibilityTracking and removeRegion and statistics
public void removeARegion() {
removeRegion(regionVisibilityTracking.findMostLikelyLeastSeenRegion(sectionManager.getRegionManager().maxRegionIndex()));
}
/*
private void setRegionVisible(long rid) {
glClearNamedBufferSubData(regionVisibility.getId(), GL_R8UI, rid, 1, GL_RED_INTEGER, GL_UNSIGNED_BYTE, new int[]{(byte)(1)});
}*/
//Translucency is rendered in a very cursed and incorrect way
// it hijacks the unassigned indirect command dispatch and uses that to dispatch the translucent chunks as well
public void renderTranslucent() {
glEnableClientState(GL_UNIFORM_BUFFER_UNIFIED_NV);
glEnableClientState(GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV);
glEnableClientState(GL_ELEMENT_ARRAY_UNIFIED_NV);
glEnableClientState(GL_DRAW_INDIRECT_UNIFIED_NV);
//Need to rebind the uniform since it might have been wiped
glBufferAddressRangeNV(GL_UNIFORM_BUFFER_ADDRESS_NV, 0, sceneUniform.getDeviceAddress(), SCENE_SIZE);
//Translucency sorting
{
glEnable(GL_DEPTH_TEST);
RenderSystem.enableBlend();
RenderSystem.blendFuncSeparate(GlStateManager.SrcFactor.SRC_ALPHA, GlStateManager.DstFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SrcFactor.ONE, GlStateManager.DstFactor.ONE_MINUS_SRC_ALPHA);
translucencyTerrainRasterizer.raster(prevRegionCount, translucencyCommandBuffer.getDeviceAddress());
RenderSystem.disableBlend();
RenderSystem.defaultBlendFunc();
glDisable(GL_DEPTH_TEST);
}
glDisableClientState(GL_UNIFORM_BUFFER_UNIFIED_NV);
glDisableClientState(GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV);
glDisableClientState(GL_ELEMENT_ARRAY_UNIFIED_NV);
glDisableClientState(GL_DRAW_INDIRECT_UNIFIED_NV);
//Download statistics
if (Nvidium.config.statistics_level.ordinal() > StatisticsLoggingLevel.FRUSTUM.ordinal()){
downloadStream.download(statisticsBuffer, 0, 4*4, (addr)-> {
stats.regionCount = MemoryUtil.memGetInt(addr);
stats.sectionCount = MemoryUtil.memGetInt(addr+4);
stats.quadCount = MemoryUtil.memGetInt(addr+8);
});
}
if (Nvidium.config.statistics_level.ordinal() > StatisticsLoggingLevel.FRUSTUM.ordinal()) {
//glMemoryBarrier(GL_ALL_BARRIER_BITS);
//Stupid bloody nvidia not following spec forcing me to use a upload stream
long upload = this.uploadStream.upload(statisticsBuffer, 0, 4*4);
MemoryUtil.memSet(upload, 0, 4*4);
//glClearNamedBufferSubData(statisticsBuffer.getId(), GL_R32UI, 0, 4 * 4, GL_RED_INTEGER, GL_UNSIGNED_INT, new int[]{0});
}
}
public void delete() {
regionVisibilityTracking.delete();
sceneUniform.delete();
regionVisibility.delete();
sectionVisibility.delete();
terrainCommandBuffer.delete();
translucencyCommandBuffer.delete();
regionSortingList.delete();
terrainRasterizer.delete();
regionRasterizer.delete();
sectionRasterizer.delete();
temporalRasterizer.delete();
translucencyTerrainRasterizer.delete();
regionSectionSorter.delete();
this.transformationArray.delete();
if (statisticsBuffer != null) {
statisticsBuffer.delete();
}
}
public void addDebugInfo(List<String> info) {
if (Nvidium.config.statistics_level != StatisticsLoggingLevel.NONE) {
StringBuilder builder = new StringBuilder();
builder.append("Statistics: \n");
if (Nvidium.config.statistics_level.ordinal() >= StatisticsLoggingLevel.FRUSTUM.ordinal()) {
builder.append("Frustum: ").append(stats.frustumCount).append("\n");
}
if (Nvidium.config.statistics_level.ordinal() >= StatisticsLoggingLevel.REGIONS.ordinal()) {
builder.append("Regions: ").append(stats.regionCount).append("\n");
}
if (Nvidium.config.statistics_level.ordinal() >= StatisticsLoggingLevel.SECTIONS.ordinal()) {
builder.append("Sections: ").append(stats.sectionCount).append("\n");
}
if (Nvidium.config.statistics_level.ordinal() >= StatisticsLoggingLevel.QUADS.ordinal()) {
builder.append("Quads: ").append(stats.quadCount).append("\n");
}
info.addAll(List.of(builder.toString().split("\n")));
}
}
public void reloadShaders() {
terrainRasterizer.delete();
regionRasterizer.delete();
sectionRasterizer.delete();
temporalRasterizer.delete();
translucencyTerrainRasterizer.delete();
regionSectionSorter.delete();
terrainRasterizer = new PrimaryTerrainRasterizer();
regionRasterizer = new RegionRasterizer();
sectionRasterizer = new SectionRasterizer();
temporalRasterizer = new TemporalTerrainRasterizer();
translucencyTerrainRasterizer = new TranslucentTerrainRasterizer();
regionSectionSorter = new SortRegionSectionPhase();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\api0\NvidiumAPI.java
|
package me.cortex.nvidium.api0;
import me.cortex.nvidium.Nvidium;
import me.cortex.nvidium.sodiumCompat.INvidiumWorldRendererGetter;
import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer;
import org.joml.Matrix4fc;
import org.joml.Matrix4x3fc;
public class NvidiumAPI {
private final String modName;
public NvidiumAPI(String modName) {
this.modName = modName;
}
/***
* Forces a render section to not render, guarantees the section will stay hidden until it is marked as visible
* @param x sectionX pos
* @param y sectionY pos
* @param z sectionZ pos
*/
public void hideSection(int x, int y, int z) {
if (Nvidium.IS_ENABLED) {
var renderer = ((INvidiumWorldRendererGetter) SodiumWorldRenderer.instance()).getRenderer();
renderer.getSectionManager().setHideBit(x, y, z, true);
}
}
/***
* Unhides a render section if it was previously hidden
* @param x sectionX pos
* @param y sectionY pos
* @param z sectionZ pos
*/
public void showSection(int x, int y, int z) {
if (Nvidium.IS_ENABLED) {
var renderer = ((INvidiumWorldRendererGetter) SodiumWorldRenderer.instance()).getRenderer();
renderer.getSectionManager().setHideBit(x, y, z, false);
}
}
/***
* Assigns a specified region to the supplied transformation id
* @param id id to set the region too (all regions have the default id of 0)
* @param x region X pos
* @param y region Y pos
* @param z region Z pos
*/
public void setRegionTransformId(int id, int x, int y, int z) {
if (Nvidium.IS_ENABLED) {
var renderer = ((INvidiumWorldRendererGetter) SodiumWorldRenderer.instance()).getRenderer();
renderer.getSectionManager().getRegionManager().setRegionTransformId(x, y, z, id);
}
}
/***
* Sets the affine transform for the supplied id
* @param id The id to set the transform of
* @param transform The transform to set it too
*/
public void setTransformation(int id, Matrix4fc transform) {
if (Nvidium.IS_ENABLED) {
var renderer = ((INvidiumWorldRendererGetter) SodiumWorldRenderer.instance()).getRenderer();
renderer.setTransformation(id, transform);
}
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\config\ConfigGuiBuilder.java
|
package me.cortex.nvidium.config;
import com.google.common.collect.ImmutableList;
import me.cortex.nvidium.Nvidium;
import me.cortex.nvidium.sodiumCompat.NvidiumOptionFlags;
import me.jellysquid.mods.sodium.client.gui.options.*;
import me.jellysquid.mods.sodium.client.gui.options.control.ControlValueFormatter;
import me.jellysquid.mods.sodium.client.gui.options.control.CyclingControl;
import me.jellysquid.mods.sodium.client.gui.options.control.SliderControl;
import me.jellysquid.mods.sodium.client.gui.options.control.TickBoxControl;
import net.minecraft.text.Text;
import java.util.ArrayList;
import java.util.List;
public class ConfigGuiBuilder {
private static final NvidiumConfigStore store = new NvidiumConfigStore();
public static void addNvidiumGui(List<OptionPage> pages) {
List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, store)
.setName(Text.literal("Disable nvidium"))
.setTooltip(Text.literal("Used to disable nvidium (DOES NOT SAVE, WILL RE-ENABLE AFTER A RE-LAUNCH)"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.HIGH)
.setBinding((opts, value) -> Nvidium.FORCE_DISABLE = value, opts -> Nvidium.FORCE_DISABLE)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
).build());
if (Nvidium.IS_COMPATIBLE && !Nvidium.IS_ENABLED && !Nvidium.FORCE_DISABLE) {
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, store)
.setName(Text.literal("Nvidium disabled due to shaders being loaded"))
.setTooltip(Text.literal("Nvidium disabled due to shaders being loaded"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.VARIES)
.setBinding((opts, value) -> {}, opts -> false)
.setFlags()
.build()
).build());
}
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(int.class, store)
.setName(Text.translatable("nvidium.options.region_keep_distance.name"))
.setTooltip(Text.translatable("nvidium.options.region_keep_distance.tooltip"))
.setControl(option -> new SliderControl(option, 32, 256, 1, x->Text.literal(x==32?"Vanilla":(x==256?"Keep All":x+" chunks"))))
.setImpact(OptionImpact.VARIES)
.setEnabled(Nvidium.IS_ENABLED)
.setBinding((opts, value) -> opts.region_keep_distance = value, opts -> opts.region_keep_distance)
.setFlags()
.build()
).add(OptionImpl.createBuilder(boolean.class, store)
.setName(Text.translatable("nvidium.options.enable_temporal_coherence.name"))
.setTooltip(Text.translatable("nvidium.options.enable_temporal_coherence.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setEnabled(Nvidium.IS_ENABLED)
.setBinding((opts, value) -> opts.enable_temporal_coherence = value, opts -> opts.enable_temporal_coherence)
.setFlags()
.build()
).add(OptionImpl.createBuilder(boolean.class, store)
.setName(Text.translatable("nvidium.options.async_bfs.name"))
.setTooltip(Text.translatable("nvidium.options.async_bfs.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.HIGH)
.setEnabled(Nvidium.IS_ENABLED)
.setBinding((opts, value) -> opts.async_bfs = value, opts -> opts.async_bfs)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
).add(OptionImpl.createBuilder(boolean.class, store)
.setName(Text.translatable("nvidium.options.automatic_memory_limit.name"))
.setTooltip(Text.translatable("nvidium.options.automatic_memory_limit.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.VARIES)
.setEnabled(Nvidium.IS_ENABLED)
.setBinding((opts, value) -> opts.automatic_memory = value, opts -> opts.automatic_memory)
.setFlags()
.build())
.add(OptionImpl.createBuilder(int.class, store)
.setName(Text.translatable("nvidium.options.max_gpu_memory.name"))
.setTooltip(Text.translatable("nvidium.options.max_gpu_memory.tooltip"))
.setControl(option -> new SliderControl(option, 2048, 32768, 512, ControlValueFormatter.translateVariable("nvidium.options.mb")))
.setImpact(OptionImpact.VARIES)
.setEnabled(Nvidium.IS_ENABLED && !Nvidium.config.automatic_memory)
.setBinding((opts, value) -> opts.max_geometry_memory = value, opts -> opts.max_geometry_memory)
.setFlags(Nvidium.SUPPORTS_PERSISTENT_SPARSE_ADDRESSABLE_BUFFER?new OptionFlag[0]:new OptionFlag[]{OptionFlag.REQUIRES_RENDERER_RELOAD})
.build()
).add(OptionImpl.createBuilder(TranslucencySortingLevel.class, store)
.setName(Text.translatable("nvidium.options.translucency_sorting.name"))
.setTooltip(Text.translatable("nvidium.options.translucency_sorting.tooltip"))
.setControl(
opts -> new CyclingControl<>(
opts,
TranslucencySortingLevel.class,
new Text[]{
Text.translatable("nvidium.options.translucency_sorting.none"),
Text.translatable("nvidium.options.translucency_sorting.sections"),
Text.translatable("nvidium.options.translucency_sorting.quads")
}
)
)
.setBinding((opts, value) -> opts.translucency_sorting_level = value, opts -> opts.translucency_sorting_level)
.setEnabled(Nvidium.IS_ENABLED)
.setImpact(OptionImpact.MEDIUM)
//Technically, only need to reload when going from NONE->SECTIONS
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
).add(OptionImpl.createBuilder(StatisticsLoggingLevel.class, store)
.setName(Text.translatable("nvidium.options.statistics_level.name"))
.setTooltip(Text.translatable("nvidium.options.statistics_level.tooltip"))
.setControl(
opts -> new CyclingControl<>(
opts,
StatisticsLoggingLevel.class,
new Text[]{
Text.translatable("nvidium.options.statistics_level.none"),
Text.translatable("nvidium.options.statistics_level.frustum"),
Text.translatable("nvidium.options.statistics_level.regions"),
Text.translatable("nvidium.options.statistics_level.sections"),
Text.translatable("nvidium.options.statistics_level.quads")
}
)
)
.setBinding((opts, value) -> opts.statistics_level = value, opts -> opts.statistics_level)
.setEnabled(Nvidium.IS_ENABLED)
.setImpact(OptionImpact.LOW)
.setFlags(NvidiumOptionFlags.REQUIRES_SHADER_RELOAD)
.build()
)
.build());
if (Nvidium.IS_COMPATIBLE) {
pages.add(new OptionPage(Text.translatable("nvidium.options.pages.nvidium"), ImmutableList.copyOf(groups)));
}
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\config\NvidiumConfig.java
|
package me.cortex.nvidium.config;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import me.cortex.nvidium.Nvidium;
import net.neoforged.fml.loading.FMLConfig;
import net.neoforged.fml.loading.FMLPaths;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.nio.file.Files;
import java.nio.file.Path;
public class NvidiumConfig {
//The options
public int extra_rd = 100;
public boolean enable_temporal_coherence = true;
public int max_geometry_memory = 2048;
public boolean automatic_memory = true;
public boolean async_bfs = true;
public int region_keep_distance = 32;
public TranslucencySortingLevel translucency_sorting_level = TranslucencySortingLevel.QUADS;
public StatisticsLoggingLevel statistics_level = StatisticsLoggingLevel.NONE;
private static final Gson GSON = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setPrettyPrinting()
.excludeFieldsWithModifiers(Modifier.PRIVATE)
.create();
private NvidiumConfig() {}
public static NvidiumConfig loadOrCreate() {
var path = getConfigPath();
if (Files.exists(path)) {
try (FileReader reader = new FileReader(path.toFile())) {
return GSON.fromJson(reader, NvidiumConfig.class);
} catch (IOException e) {
Nvidium.LOGGER.error("Could not parse config", e);
}
}
return new NvidiumConfig();
}
public void save() {
//Unsafe, todo: fixme! needs to be atomic!
try {
Files.writeString(getConfigPath(), GSON.toJson(this));
} catch (IOException e) {
Nvidium.LOGGER.error("Failed to write config file", e);
}
}
private static Path getConfigPath() {
return FMLPaths.CONFIGDIR.get().resolve("nvidium-config.json");
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\config\NvidiumConfigStore.java
|
package me.cortex.nvidium.config;
import me.cortex.nvidium.Nvidium;
import me.cortex.nvidium.config.NvidiumConfig;
import me.jellysquid.mods.sodium.client.gui.options.storage.OptionStorage;
public class NvidiumConfigStore implements OptionStorage<NvidiumConfig> {
private final NvidiumConfig config;
public NvidiumConfigStore() {
config = Nvidium.config;
}
@Override
public NvidiumConfig getData() {
return config;
}
@Override
public void save() {
config.save();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\config\StatisticsLoggingLevel.java
|
package me.cortex.nvidium.config;
public enum StatisticsLoggingLevel {
NONE,
FRUSTUM,
REGIONS,
SECTIONS,
QUADS
}
|
acedium
|
src\main\java\me\cortex\nvidium\config\TranslucencySortingLevel.java
|
package me.cortex.nvidium.config;
public enum TranslucencySortingLevel {
NONE,
SECTIONS,
QUADS
}
|
acedium
|
src\main\java\me\cortex\nvidium\gl\GlFence.java
|
package me.cortex.nvidium.gl;
import static org.lwjgl.opengl.GL32.*;
public class GlFence extends TrackedObject {
private final long fence;
private boolean signaled;
public GlFence() {
this.fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
}
public boolean signaled() {
this.assertNotFreed();
if (!this.signaled) {
int ret = glClientWaitSync(this.fence, 0, 0);
if (ret == GL_ALREADY_SIGNALED || ret == GL_CONDITION_SATISFIED) {
this.signaled = true;
} else if (ret != GL_TIMEOUT_EXPIRED) {
throw new IllegalStateException("Poll for fence failed, ret: " + ret + " glError: " + glGetError());
}
}
return this.signaled;
}
@Override
public void free() {
super.free0();
glDeleteSync(this.fence);
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\gl\GlObject.java
|
package me.cortex.nvidium.gl;
public abstract class GlObject extends TrackedObject implements IResource {
protected final int id;
protected GlObject(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\gl\IResource.java
|
package me.cortex.nvidium.gl;
public interface IResource {
void delete();
}
|
acedium
|
src\main\java\me\cortex\nvidium\gl\RenderDevice.java
|
package me.cortex.nvidium.gl;
import me.cortex.nvidium.gl.buffers.*;
import static org.lwjgl.opengl.ARBDirectStateAccess.glCopyNamedBufferSubData;
import static org.lwjgl.opengl.ARBDirectStateAccess.glFlushMappedNamedBufferRange;
import static org.lwjgl.opengl.GL15C.glIsBuffer;
import static org.lwjgl.opengl.GL42C.glMemoryBarrier;
public class RenderDevice {
public PersistentClientMappedBuffer createClientMappedBuffer(long size) {
return new PersistentClientMappedBuffer(size);
}
public void flush(IClientMappedBuffer buffer, long offset, int size) {
int id = ((GlObject)buffer).getId();
glFlushMappedNamedBufferRange(id, offset, size);
}
public void barrier(int flags) {
glMemoryBarrier(flags);
}
public void copyBuffer(Buffer src, Buffer dst, long srcOffset, long dstOffset, long size) {
glCopyNamedBufferSubData(((GlObject)src).getId(), ((GlObject)dst).getId(), srcOffset, dstOffset, size);
}
public PersistentSparseAddressableBuffer createSparseBuffer(long totalSize) {
return new PersistentSparseAddressableBuffer(totalSize);
}
public IDeviceMappedBuffer createDeviceOnlyMappedBuffer(long size) {
return new DeviceOnlyMappedBuffer(size);
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\gl\TrackedObject.java
|
package me.cortex.nvidium.gl;
import me.cortex.nvidium.Nvidium;
import java.lang.ref.Cleaner;
public abstract class TrackedObject {
private final Ref ref;
public TrackedObject() {
this.ref = register(this);
}
protected void free0() {
if (this.isFreed()) {
throw new IllegalStateException("Object " + this + " was double freed.");
}
this.ref.freedRef[0] = true;
this.ref.cleanable.clean();
}
public abstract void free();
public void assertNotFreed() {
if (isFreed()) {
throw new IllegalStateException("Object " + this + " should not be free, but is");
}
}
public boolean isFreed() {
return this.ref.freedRef[0];
}
public record Ref(Cleaner.Cleanable cleanable, boolean[] freedRef) {}
private static final Cleaner cleaner = Cleaner.create();
public static Ref register(Object obj) {
String clazz = obj.getClass().getName();
Throwable trace;
if (Nvidium.IS_DEBUG) {
trace = new Throwable();
} else {
trace = null;
}
boolean[] freed = new boolean[1];
var clean = cleaner.register(obj, ()->{
if (!freed[0]) {
System.err.println("Object named: "+ clazz+" was not freed, location at:\n");
if (trace != null) {
trace.printStackTrace();
} else {
System.err.println("Unknown location, turn on debug mode");
}
System.err.flush();
}
});
return new Ref(clean, freed);
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\managers\AsyncOcclusionTracker.java
|
package me.cortex.nvidium.managers;
import com.mojang.blaze3d.systems.RenderSystem;
import it.unimi.dsi.fastutil.longs.Long2ReferenceMap;
import me.cortex.nvidium.sodiumCompat.IRenderSectionExtension;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import me.jellysquid.mods.sodium.client.render.chunk.ChunkUpdateType;
import me.jellysquid.mods.sodium.client.render.chunk.RenderSection;
import me.jellysquid.mods.sodium.client.render.chunk.RenderSectionFlags;
import me.jellysquid.mods.sodium.client.render.chunk.occlusion.OcclusionCuller;
import me.jellysquid.mods.sodium.client.render.viewport.Viewport;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.render.Camera;
import net.minecraft.client.texture.Sprite;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import static java.lang.Thread.MAX_PRIORITY;
public class AsyncOcclusionTracker {
private final OcclusionCuller occlusionCuller;
private final Thread cullThread;
private final World world;
private volatile boolean running = true;
private volatile int frame = 0;
private volatile Viewport viewport = null;
private final Semaphore framesAhead = new Semaphore(0);
private final AtomicReference<List<RenderSection>> atomicBfsResult = new AtomicReference<>();
private final AtomicReference<List<RenderSection>> blockEntitySectionsRef = new AtomicReference<>(new ArrayList<>());
private final AtomicReference<Sprite[]> visibleAnimatedSpritesRef = new AtomicReference<>();
private final Map<ChunkUpdateType, ArrayDeque<RenderSection>> outputRebuildQueue;
private final float renderDistance;
private volatile long iterationTimeMillis;
private volatile boolean shouldUseOcclusionCulling = true;
public AsyncOcclusionTracker(int renderDistance, Long2ReferenceMap<RenderSection> sections, World world, Map<ChunkUpdateType, ArrayDeque<RenderSection>> outputRebuildQueue) {
this.occlusionCuller = new OcclusionCuller(sections, world);
this.cullThread = new Thread(this::run);
this.cullThread.setName("Cull thread");
this.cullThread.setPriority(MAX_PRIORITY);
this.cullThread.start();
this.renderDistance = renderDistance * 16f;
this.outputRebuildQueue = outputRebuildQueue;
this.world = world;
}
private void run() {
while (running) {
framesAhead.acquireUninterruptibly();
if (!running) break;
long startTime = System.currentTimeMillis();
final boolean animateVisibleSpritesOnly = SodiumClientMod.options().performance.animateOnlyVisibleTextures;
//The reason for batching is so that ordering is strongly defined
List<RenderSection> chunkUpdates = new ArrayList<>();
List<RenderSection> blockEntitySections = new ArrayList<>();
Set<Sprite> animatedSpriteSet = animateVisibleSpritesOnly?new HashSet<>():null;
final OcclusionCuller.Visitor visitor = (section, visible) -> {
if (section.getPendingUpdate() != null && section.getBuildCancellationToken() == null) {
if ((!((IRenderSectionExtension)section).isSubmittedRebuild()) && !((IRenderSectionExtension)section).isSeen()) {//If it is in submission queue or seen dont enqueue
//Set that the section has been seen
((IRenderSectionExtension)section).isSeen(true);
chunkUpdates.add(section);
}
}
if (!visible) {
return;
}
if ((section.getFlags()&(1<<RenderSectionFlags.HAS_BLOCK_ENTITIES))!=0 &&
section.getPosition().isWithinDistance(viewport.getChunkCoord(),33)) {//32 rd max chunk distance
blockEntitySections.add(section);
}
if (animateVisibleSpritesOnly && (section.getFlags()&(1<<RenderSectionFlags.HAS_ANIMATED_SPRITES)) != 0 &&
section.getPosition().isWithinDistance(viewport.getChunkCoord(),33)) {//32 rd max chunk distance (i.e. only animate sprites up to 32 chunks away)
var animatedSprites = section.getAnimatedSprites();
if (animatedSprites != null) {
animatedSpriteSet.addAll(List.of(animatedSprites));
}
}
};
frame++;
float searchDistance = this.getSearchDistance();
boolean useOcclusionCulling = this.shouldUseOcclusionCulling;
try {
this.occlusionCuller.findVisible(visitor, viewport, searchDistance, useOcclusionCulling, frame);
} catch (Throwable e) {
System.err.println("Error doing traversal");
e.printStackTrace();
}
if (!chunkUpdates.isEmpty()) {
var previous = atomicBfsResult.getAndSet(chunkUpdates);
if (previous != null) {
//We need to cleanup our state from a previous iteration
for (var section : previous) {
if (section.isDisposed())
continue;
//Reset that it hasnt been seen
((IRenderSectionExtension) section).isSeen(false);
}
}
}
blockEntitySectionsRef.set(blockEntitySections);
visibleAnimatedSpritesRef.set(animatedSpriteSet==null?null:animatedSpriteSet.toArray(new Sprite[0]));
iterationTimeMillis = System.currentTimeMillis() - startTime;
}
}
public final void update(Viewport viewport, Camera camera, boolean spectator) {
this.shouldUseOcclusionCulling = this.shouldUseOcclusionCulling(camera, spectator);
this.viewport = viewport;
if (framesAhead.availablePermits() < 5) {//This stops a runaway when the traversal time is greater than frametime
framesAhead.release();
}
var bfsResult = atomicBfsResult.getAndSet(null);
if (bfsResult != null) {
for (var section : bfsResult) {
if (section.isDisposed())
continue;
var type = section.getPendingUpdate();
if (type != null && section.getBuildCancellationToken() == null) {
var queue = outputRebuildQueue.get(type);
if (queue.size() < type.getMaximumQueueSize()) {
((IRenderSectionExtension) section).isSubmittedRebuild(true);
queue.add(section);
}
}
//Reset that the section has not been seen (whether its been submitted to the queue or not)
((IRenderSectionExtension) section).isSeen(false);
}
}
}
public void delete() {
running = false;
framesAhead.release(1000);
try {
cullThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private float getSearchDistance() {
return renderDistance;
}
private float getSearchDistance2() {
float distance;
if (SodiumClientMod.options().performance.useFogOcclusion) {
distance = this.getEffectiveRenderDistance();
} else {
distance = this.getRenderDistance();
}
return distance;
}
private boolean shouldUseOcclusionCulling(Camera camera, boolean spectator) {
BlockPos origin = camera.getBlockPos();
boolean useOcclusionCulling;
if (spectator && this.world.getBlockState(origin).isOpaqueFullCube(this.world, origin)) {
useOcclusionCulling = false;
} else {
useOcclusionCulling = MinecraftClient.getInstance().chunkCullingEnabled;
}
return useOcclusionCulling;
}
private float getEffectiveRenderDistance() {
float[] color = RenderSystem.getShaderFogColor();
float distance = RenderSystem.getShaderFogEnd();
float renderDistance = this.getRenderDistance();
return !MathHelper.approximatelyEquals(color[3], 1.0F) ? renderDistance : Math.min(renderDistance, distance + 0.5F);
}
private float getRenderDistance() {
return (float)this.renderDistance;
}
public int getFrame() {
return frame;
}
public List<RenderSection> getLatestSectionsWithEntities() {
return blockEntitySectionsRef.get();
}
@Nullable
public Sprite[] getVisibleAnimatedSprites() {
return visibleAnimatedSpritesRef.get();
}
public long getIterationTime() {
return this.iterationTimeMillis;
}
public int[] getBuildQueueSizes() {
var ret = new int[this.outputRebuildQueue.size()];
for (var type : ChunkUpdateType.values()) {
ret[type.ordinal()] = this.outputRebuildQueue.get(type).size();
}
return ret;
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\managers\RegionManager.java
|
package me.cortex.nvidium.managers;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
import me.cortex.nvidium.Nvidium;
import me.cortex.nvidium.gl.RenderDevice;
import me.cortex.nvidium.gl.buffers.IDeviceMappedBuffer;
import me.cortex.nvidium.util.IdProvider;
import me.cortex.nvidium.util.UploadingBufferStream;
import me.jellysquid.mods.sodium.client.render.viewport.Viewport;
import net.minecraft.util.math.ChunkSectionPos;
import org.lwjgl.system.MemoryUtil;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.function.Consumer;
//8x4x8
public class RegionManager {
public static final int MAX_TRANSFORMATION_SIZE_BITS = 10;
public static final int MAX_TRANSFORMATION_COUNT = (1<<MAX_TRANSFORMATION_SIZE_BITS);
private static final boolean SAFETY_CHECKS = Nvidium.IS_DEBUG;
public static final int META_SIZE = 16;
private static final int TOTAL_SECTION_META_SIZE = SectionManager.SECTION_SIZE * 256;
private final IDeviceMappedBuffer regionBuffer;
private final IDeviceMappedBuffer sectionBuffer;
private final RenderDevice device;
private final UploadingBufferStream uploadStream;
private final Long2IntOpenHashMap regionTransformationIdMapping = new Long2IntOpenHashMap();
private final Long2IntOpenHashMap regionMap = new Long2IntOpenHashMap();
private final IdProvider idProvider = new IdProvider();
private final Region[] regions;
private final ArrayDeque<Region> dirtyRegions = new ArrayDeque<>();
private final Consumer<Integer> regionUploadCallback;
public RegionManager(RenderDevice device, int maxRegions, int maxSections, UploadingBufferStream uploadStream, Consumer<Integer> regionUploaded) {
this.regionMap.defaultReturnValue(-1);
this.device = device;
this.regionBuffer = device.createDeviceOnlyMappedBuffer((long) maxRegions * META_SIZE);
this.sectionBuffer = device.createDeviceOnlyMappedBuffer((long) maxSections * SectionManager.SECTION_SIZE);
this.uploadStream = uploadStream;
this.regions = new Region[maxRegions];
this.regionUploadCallback = regionUploaded;
}
public void delete() {
this.regionBuffer.delete();
this.sectionBuffer.delete();
}
//Commits all the pending region changes to the gpu
public void commitChanges() {
if (this.dirtyRegions.isEmpty())
return;
while (!this.dirtyRegions.isEmpty()) {
var region = this.dirtyRegions.pop();
region.isDirty = false;
//If the region was removed, check if a new region took its place, if it has, no furthure action is needed
// as the new region will override the old regions data
if (region.isRemoved) {
if (this.regions[region.id] == null) {
//There is no region that has replaced the old one at the id so we need to clear the region metadata
// to prevent the gpu from rendering arbitary data
long regionUpload = this.uploadStream.upload(this.regionBuffer, (long) region.id * META_SIZE, META_SIZE);
MemoryUtil.memSet(regionUpload, -1, META_SIZE);
long sectionUpload = this.uploadStream.upload(this.sectionBuffer,
(long) region.id * TOTAL_SECTION_META_SIZE,
TOTAL_SECTION_META_SIZE);
MemoryUtil.memSet(sectionUpload, 0, TOTAL_SECTION_META_SIZE);
}
} else {
//It is just a normal region update
long regionUpload = this.uploadStream.upload(this.regionBuffer, (long) region.id * META_SIZE, META_SIZE);
this.setRegionMetadata(regionUpload, region);
long sectionUpload = this.uploadStream.upload(this.sectionBuffer,
(long) region.id * TOTAL_SECTION_META_SIZE,
TOTAL_SECTION_META_SIZE);
MemoryUtil.memCopy(region.sectionData, sectionUpload, TOTAL_SECTION_META_SIZE);
this.regionUploadCallback.accept(region.id);
}
}
}
private void setRegionMetadata(long upload, Region region) {
int minX = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int minY = Integer.MAX_VALUE;
int maxY = Integer.MIN_VALUE;
int minZ = Integer.MAX_VALUE;
int maxZ = Integer.MIN_VALUE;
int lastIdx = 0;
for (int i = 0; i < 256; i++) {
if (region.pos2id[i] == -1) continue;//Skip over empty sections
int x = i&7;
int y = i>>>6;
int z = (i>>>3)&7;
minX = Math.min(minX, x);
minY = Math.min(minY, y);
minZ = Math.min(minZ, z);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
maxZ = Math.max(maxZ, z);
lastIdx = i;
}
long size = (long)(maxY-minY)<<62 | (long)(maxX-minX)<<59 | (long)(maxZ-minZ)<<56;
long count = (long)(lastIdx)<<48;
long x = ((((long) region.rx <<3)+minX)&((1<<24)-1))<<24;
long y = ((((long) region.ry <<2)+minY)&((1<<24)-1))<<0;//TODO:FIXME! y height does _not_ need to be 24 bits big
long z = ((((long) region.rz <<3)+minZ)&((1<<24)-1))<<(64-24);
long transformationId = (((long)region.transformationId)<<(64-24-MAX_TRANSFORMATION_SIZE_BITS));
MemoryUtil.memPutLong(upload, size|count|x|y);
MemoryUtil.memPutLong(upload+8, z | transformationId);
}
public int getSectionRefId(int section) {
var region = this.regions[section >>> 8];
int id = region.pos2id[section&0xFF];
if (id<0 || id>=256) {
throw new IllegalStateException();
}
return id;
}
//Returns a pointer to where the section data can be read or updated
// it has a lifetime of until any other function call to this class instance
// will mark the region as dirty and needing an update
public long setSectionData(int sectionId) {
var region = this.regions[sectionId >>> 8];
sectionId &= 0xFF;
sectionId = region.pos2id[sectionId];
if (sectionId<0 || sectionId>=256) {
throw new IllegalStateException();
}
this.markDirty(region);
return region.sectionData + (sectionId * SectionManager.SECTION_SIZE);
}
public void removeSection(int sectionId) {
var region = this.regions[sectionId >>> 8];
sectionId &= 0xFF;
if (region == null) {
throw new IllegalStateException("Region is null");
}
int sectionPos = sectionId;
sectionId = region.pos2id[sectionId];
//Set the metadata of the section to empty
MemoryUtil.memSet(region.sectionData + (long) sectionId * SectionManager.SECTION_SIZE, 0, SectionManager.SECTION_SIZE);
region.pos2id[sectionPos] = -1;
region.id2pos[sectionId] = -1;
region.verifyIntegrity();
//TODO: need to act like a heap and move the last index to the removed index slot so that
// we have a contiguous allocation
int endId = --region.count;
//If the endId is not the sectionId we need to move whatever was at the end to the new position
if (endId != sectionId) {
int oldPos = region.id2pos[endId];
if (oldPos == -1) {
throw new IllegalStateException();
}
//Copy the data from the last element to the now vacant slot
MemoryUtil.memCopy(region.sectionData + (long) endId * SectionManager.SECTION_SIZE, region.sectionData + (long) sectionId * SectionManager.SECTION_SIZE, SectionManager.SECTION_SIZE);
MemoryUtil.memSet(region.sectionData + (long) endId * SectionManager.SECTION_SIZE, 0, SectionManager.SECTION_SIZE);
if (region.id2pos[endId] == -1 || region.pos2id[oldPos] == -1) {
throw new IllegalStateException();
}
region.id2pos[endId] = -1;
region.pos2id[oldPos] = -1;
region.id2pos[sectionId] = oldPos;
region.pos2id[oldPos] = sectionId;
//TODO:FIXME! the issue is that the internal tracking id needs to be updated, that is the id to the section
// needs to change
// to the region needs to change
long ptr = region.sectionData + (long) sectionId * SectionManager.SECTION_SIZE + 4;
int data = MemoryUtil.memGetInt(ptr);
data &= ~(0xFF<<18);
data |= sectionId<<18;
MemoryUtil.memPutInt(ptr, data);
region.verifyIntegrity();
}
if (region.count == 0) {
//Remove the region and mark it as removed
region.isRemoved = true;
region.delete();
this.regions[region.id] = null;
this.idProvider.release(region.id);
this.regionMap.remove(region.key);
}
this.markDirty(region);
region.verifyIntegrity();
}
public int allocateSection(int sectionX, int sectionY, int sectionZ) {
long regionKey = ChunkSectionPos.asLong(sectionX>>3, sectionY>>2, sectionZ>>3);
int regionId = this.regionMap.computeIfAbsent(regionKey, k -> this.idProvider.provide());
//The region doesnt exist so we must create a new one
if (this.regions[regionId] == null) {
this.regions[regionId] = new Region(regionId, sectionX>>3, sectionY>>2, sectionZ>>3);
this.regions[regionId].transformationId = this.regionTransformationIdMapping.get(regionKey);
}
var region = this.regions[regionId];
int sectionKey = ((sectionY & 3) << 6 | sectionX & 7 | (sectionZ & 7) << 3);
int sectionId = region.count++;
if (region.pos2id[sectionKey] != -1 || region.id2pos[sectionId] != -1) {
throw new IllegalStateException("Section id not free!");
}
region.pos2id[sectionKey] = sectionId;
region.id2pos[sectionId] = sectionKey;
this.markDirty(region);
region.verifyIntegrity();
return sectionKey | (regionId << 8);
}
//Adds the region to the dirty list if it wasnt already in it
private void markDirty(Region region) {
if (region.isDirty)
return;
region.isDirty = true;
this.dirtyRegions.add(region);
}
public int regionCount() {
return this.regionMap.size();
}
public int maxRegions() {
return this.regions.length;
}
public int maxRegionIndex() {
return this.idProvider.maxIndex();
}
public boolean regionExists(int regionId) {
return this.regions[regionId] != null;
}
public boolean isRegionVisible(Viewport frustum, int regionId) {
var region = this.regions[regionId];
if (region == null) {
return false;
} else {
//FIXME: should make it use the region data so that the frustum bounds check is more accurate
return frustum.isBoxVisible((region.rx<<7)+(1<<6),(region.ry<<6)+(1<<5), (region.rz<<7)+(1<<6), 1<<6, 1<<5, 1<<6);
}
}
public int distance(int regionId, int camChunkX, int camChunkY, int camChunkZ) {
var region = this.regions[regionId];
return (Math.abs((region.rx<<3)+4-camChunkX)+
Math.abs((region.ry<<2)+2-camChunkY)+
Math.abs((region.rz<<3)+4-camChunkZ)+
Math.abs((region.rx<<3)+3-camChunkX)+
Math.abs((region.ry<<2)+1-camChunkY)+
Math.abs((region.rz<<3)+3-camChunkZ))>>1;
}
public boolean withinSquare(int dist, int regionId, int camChunkX, int camChunkY, int camChunkZ) {
var region = this.regions[regionId];
return Math.abs((region.rx<<3)+4-camChunkX)<=dist &&
Math.abs((region.ry<<2)+2-camChunkY)<=dist &&
Math.abs((region.rz<<3)+4-camChunkZ)<=dist;
}
public boolean isRegionInACameraAxis(int regionId, double camX, double camY, double camZ) {
var region = this.regions[regionId];
//TODO: also account for region area instead of entire region
return (region.rx<<7 <= camX && camX <= ((region.rx+1)<<7))||
(region.ry<<6 <= camY && camY <= ((region.ry+1)<<6))||
(region.rz<<7 <= camZ && camZ <= ((region.rz+1)<<7))
;
}
public long getRegionBufferAddress() {
return this.regionBuffer.getDeviceAddress();
}
public long getSectionBufferAddress() {
return this.sectionBuffer.getDeviceAddress();
}
public long regionIdToKey(int regionId) {
if (this.regions[regionId] == null) {
throw new IllegalStateException();
}
return this.regions[regionId].key;
}
public void setRegionTransformId(int x, int y, int z, int id) {
if (id < 0 || id >= MAX_TRANSFORMATION_COUNT) {
throw new IllegalArgumentException("Transformation id out of bounds");
}
long regionKey = ChunkSectionPos.asLong(x, y, z);
int oldId = this.regionTransformationIdMapping.put(regionKey, id);
if (oldId != id) {
//The region has a new id so need to set and propagate the data
int regionId = this.regionMap.get(regionKey);
if (regionId == -1) {
//Region doesnt exist in memory so ignore it
return;
}
var region = this.regions[regionId];
region.transformationId = id;
this.markDirty(region);
}
}
private static class Region {
private final int rx;
private final int ry;
private final int rz;
private final long key;
private final int id;
public int transformationId = 0;
private int count;
private final int[] pos2id = new int[256];//Can be a short in all honesty
private final int[] id2pos = new int[256];//Can be a short in all honesty
private boolean isDirty;
private boolean isRemoved;
//Contains also all the metadata about the sections within, then on commit, upload the entire regions metadata
// this should :tm: _drastically_ improve performance when mass edits are done to the world and the section metadata
private final long sectionData = MemoryUtil.nmemAlloc(8*4*8*SectionManager.SECTION_SIZE);
private Region(int id, int rx, int ry, int rz) {
Arrays.fill(this.pos2id, -1);
Arrays.fill(this.id2pos, -1);
MemoryUtil.memSet(sectionData, 0, 256 * SectionManager.SECTION_SIZE);
this.key = ChunkSectionPos.asLong(rx, ry, rz);
this.id = id;
this.rx = rx;
this.ry = ry;
this.rz = rz;
}
public void delete() {
MemoryUtil.nmemFree(this.sectionData);
}
public void verifyIntegrity() {
if (!SAFETY_CHECKS) return;
for (int i = 0; i < 256; i++) {
if (this.id2pos[i] != -1 && this.pos2id[this.id2pos[i]] != i) {
throw new IllegalStateException();
}
if (this.pos2id[i] != -1 && this.id2pos[this.pos2id[i]] != i) {
throw new IllegalStateException();
}
}
}
}
public void destroy() {
this.sectionBuffer.delete();
this.regionBuffer.delete();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\managers\RegionVisibilityTracker.java
|
package me.cortex.nvidium.managers;
import me.cortex.nvidium.gl.RenderDevice;
import me.cortex.nvidium.gl.buffers.Buffer;
import me.cortex.nvidium.gl.shader.Shader;
import me.cortex.nvidium.sodiumCompat.ShaderLoader;
import me.cortex.nvidium.util.DownloadTaskStream;
import net.minecraft.util.Identifier;
import org.lwjgl.system.MemoryUtil;
import static me.cortex.nvidium.gl.shader.ShaderType.FRAGMENT;
import static me.cortex.nvidium.gl.shader.ShaderType.MESH;
import static org.lwjgl.opengl.GL42.GL_COMMAND_BARRIER_BIT;
import static org.lwjgl.opengl.GL42.glMemoryBarrier;
import static org.lwjgl.opengl.GL43C.GL_SHADER_STORAGE_BARRIER_BIT;
import static org.lwjgl.opengl.NVMeshShader.glDrawMeshTasksNV;
public class RegionVisibilityTracker {
private final Shader shader = Shader.make()
.addSource(MESH, ShaderLoader.parse(new Identifier("nvidium", "occlusion/queries/region/mesh.glsl")))
.addSource(FRAGMENT, ShaderLoader.parse(new Identifier("nvidium", "occlusion/queries/region/fragment.frag")))
.compile();
private final DownloadTaskStream downStream;
private final int[] frustum;
private final int[] visible;
public RegionVisibilityTracker(DownloadTaskStream downStream, int maxRegions) {
this.downStream = downStream;
visible = new int[maxRegions];
frustum = new int[maxRegions];
for (int i = 0; i < maxRegions; i++) {
frustum[i] = 0;
visible[i] = 0;
}
}
private int fram = 0;
//This is kind of evil in the fact that it just reuses the visibility buffer
public void computeVisibility(int regionCount, Buffer regionVisibilityBuffer, short[] regionMapping) {
shader.bind();
fram++;
glDrawMeshTasksNV(0,regionCount);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
downStream.download(regionVisibilityBuffer, 0, regionCount, ptr -> {
for (int i = 0; i < regionMapping.length; i++) {
if (MemoryUtil.memGetByte(ptr + i) == 1) {
//System.out.println(regionMapping[i] + " was visible");
frustum[regionMapping[i]]++;
visible[regionMapping[i]] = fram;
} else {
//System.out.println(regionMapping[i] + " was not visible");
frustum[regionMapping[i]]++;
}
}
});
}
public void delete() {
shader.delete();
}
public void resetRegion(int id) {
frustum[id] = 0;
visible[id] = 0;
}
public int findMostLikelyLeastSeenRegion(int maxIndex) {
int maxRank = Integer.MIN_VALUE;
int id = -1;
for (int i = 0; i < maxIndex; i++) {
if (frustum[i] <= 200) continue;
int rank = - visible[i];
//int rank = -visible[i];
if (maxRank < rank) {
maxRank = rank;
id = i;
}
}
return id;
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\managers\SectionManager.java
|
package me.cortex.nvidium.managers;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import it.unimi.dsi.fastutil.longs.LongSet;
import me.cortex.nvidium.NvidiumWorldRenderer;
import me.cortex.nvidium.gl.RenderDevice;
import me.cortex.nvidium.sodiumCompat.IRepackagedResult;
import me.cortex.nvidium.util.BufferArena;
import me.cortex.nvidium.util.UploadingBufferStream;
import me.jellysquid.mods.sodium.client.render.chunk.RenderSection;
import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildOutput;
import net.minecraft.util.math.ChunkSectionPos;
import org.joml.Vector3i;
import org.joml.Vector4i;
import org.lwjgl.system.MemoryUtil;
public class SectionManager {
public static final int SECTION_SIZE = 32;
//Sections should be grouped and batched into sizes of the count of sections in a region
private final RegionManager regionManager;
private final Long2IntOpenHashMap section2id = new Long2IntOpenHashMap();
private final Long2IntOpenHashMap section2terrain = new Long2IntOpenHashMap();
public final UploadingBufferStream uploadStream;
public final BufferArena terrainAreana;
private final RenderDevice device;
private final LongSet hiddenSectionKeys = new LongOpenHashSet();
public SectionManager(RenderDevice device, long fallbackMemorySize, UploadingBufferStream uploadStream, int quadVertexSize, NvidiumWorldRenderer worldRenderer) {
int maxRegions = 50_000;
this.device = device;
this.uploadStream = uploadStream;
this.terrainAreana = new BufferArena(device, fallbackMemorySize, quadVertexSize);
this.regionManager = new RegionManager(device, maxRegions, maxRegions * 200, uploadStream, worldRenderer::enqueueRegionSort);
this.section2id.defaultReturnValue(-1);
this.section2terrain.defaultReturnValue(-1);
}
public void uploadChunkBuildResult(ChunkBuildOutput result) {
var output = ((IRepackagedResult)result).getOutput();
RenderSection section = result.render;
long sectionKey = ChunkSectionPos.asLong(section.getChunkX(), section.getChunkY(), section.getChunkZ());
if (output == null || output.quads() == 0) {
deleteSection(sectionKey);
return;
}
//Get the section id or allocate a new instance for it
int sectionIdx = this.section2id.computeIfAbsent(
sectionKey,
key -> this.regionManager.allocateSection(ChunkSectionPos.unpackX(key), ChunkSectionPos.unpackY(key), ChunkSectionPos.unpackZ(key))
);
int terrainAddress;
{
//Attempt to reuse the same memory
terrainAddress = this.section2terrain.get(sectionKey);
if (terrainAddress != -1 && !this.terrainAreana.canReuse(terrainAddress, output.quads())) {
this.section2terrain.remove(sectionKey);
this.terrainAreana.free(terrainAddress);
terrainAddress = -1;
}
if (terrainAddress == -1) {
terrainAddress = this.terrainAreana.allocQuads(output.quads());
}
this.section2terrain.put(sectionKey, terrainAddress);
long geometryUpload = terrainAreana.upload(uploadStream, terrainAddress);
MemoryUtil.memCopy(MemoryUtil.memAddress(output.geometry().getDirectBuffer()), geometryUpload, output.geometry().getLength());
}
long metadata = regionManager.setSectionData(sectionIdx);
boolean hideSectionBitSet = this.hiddenSectionKeys.contains(sectionKey);
Vector3i min = output.min();
Vector3i size = output.size();
//NOTE:TODO: The y encoded height position only has a range of like 6 bits max, that gives 18 bits free/spare for something
// realistically it would only be 16 free bits cause ee but still thats 2 bytes free
//bits 18->26 taken by section id (used for translucency sorting/rendering)
int px = section.getChunkX()<<8 | size.x<<4 | min.x;
int py = (section.getChunkY()&0x1FF)<<8 | size.y<<4 | min.y | (hideSectionBitSet?1<<17:0) | ((regionManager.getSectionRefId(sectionIdx))<<18);
int pz = section.getChunkZ()<<8 | size.z<<4 | min.z;
int pw = terrainAddress;
new Vector4i(px, py, pz, pw).getToAddress(metadata);
metadata += 4*4;
//Write the geometry offsets, packed into ints
for (int i = 0; i < 4; i++) {
int geo = Short.toUnsignedInt(output.offsets()[i*2])|(Short.toUnsignedInt(output.offsets()[i*2+1])<<16);
MemoryUtil.memPutInt(metadata, geo);
metadata += 4;
}
}
public void setHideBit(int x, int y, int z, boolean hide) {
long sectionKey = ChunkSectionPos.asLong(x, y, z);
if (hide) {
//Do a fast return if it was already hidden
if (!this.hiddenSectionKeys.add(sectionKey)) {
return;
}
} else {
//Do a fast return if the section was not hidden
if (!this.hiddenSectionKeys.remove(sectionKey)) {
return;
}
}
int sectionId = this.section2id.get(sectionKey);
//Only update the section if it is loaded
if (sectionId != -1) {
long metadata = this.regionManager.setSectionData(sectionId);
MemoryUtil.memPutInt(metadata + 4, (MemoryUtil.memGetInt(metadata + 4)&~(1<<17))| (hide?1:0)<<17);
}
}
public void deleteSection(RenderSection section) {
deleteSection(ChunkSectionPos.asLong(section.getChunkX(), section.getChunkY(), section.getChunkZ()));
}
private void deleteSection(long sectionKey) {
int sectionIdx = this.section2id.remove(sectionKey);
if (sectionIdx != -1) {
this.terrainAreana.free(this.section2terrain.remove(sectionKey));
//Clear the segment
this.regionManager.removeSection(sectionIdx);
}
}
public void destroy() {
this.regionManager.destroy();
this.terrainAreana.delete();
}
public void commitChanges() {
this.regionManager.commitChanges();
}
public RegionManager getRegionManager() {
return regionManager;
}
public void removeRegionById(int regionId) {
if (!this.regionManager.regionExists(regionId)) return;
long rk = this.regionManager.regionIdToKey(regionId);
int X = ChunkSectionPos.unpackX(rk)<<3;
int Y = ChunkSectionPos.unpackY(rk)<<2;
int Z = ChunkSectionPos.unpackZ(rk)<<3;
for (int x = X; x < X+8; x++) {
for (int y = Y; y < Y+4; y++) {
for (int z = Z; z < Z+8; z++) {
this.deleteSection(ChunkSectionPos.asLong(x, y, z));
}
}
}
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\renderers\Phase.java
|
package me.cortex.nvidium.renderers;
public abstract class Phase {
}
|
acedium
|
src\main\java\me\cortex\nvidium\renderers\PrimaryTerrainRasterizer.java
|
package me.cortex.nvidium.renderers;
import com.mojang.blaze3d.platform.GlStateManager;
import me.cortex.nvidium.gl.shader.Shader;
import me.cortex.nvidium.sodiumCompat.ShaderLoader;
import me.cortex.nvidium.mixin.minecraft.LightMapAccessor;
import net.minecraft.client.MinecraftClient;
import net.minecraft.util.Identifier;
import org.lwjgl.opengl.GL45;
import org.lwjgl.opengl.GL45C;
import static me.cortex.nvidium.RenderPipeline.GL_DRAW_INDIRECT_ADDRESS_NV;
import static me.cortex.nvidium.gl.shader.ShaderType.*;
import static org.lwjgl.opengl.GL11C.*;
import static org.lwjgl.opengl.GL33.glGenSamplers;
import static org.lwjgl.opengl.NVMeshShader.glMultiDrawMeshTasksIndirectNV;
import static org.lwjgl.opengl.NVVertexBufferUnifiedMemory.glBufferAddressRangeNV;
public class PrimaryTerrainRasterizer extends Phase {
private final int blockSampler = glGenSamplers();
private final int lightSampler = glGenSamplers();
private final Shader shader = Shader.make()
.addSource(TASK, ShaderLoader.parse(new Identifier("nvidium", "terrain/task.glsl")))
.addSource(MESH, ShaderLoader.parse(new Identifier("nvidium", "terrain/mesh.glsl")))
.addSource(FRAGMENT, ShaderLoader.parse(new Identifier("nvidium", "terrain/frag.frag"))).compile();
public PrimaryTerrainRasterizer() {
GL45C.glSamplerParameteri(blockSampler, GL45C.GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
GL45C.glSamplerParameteri(blockSampler, GL45C.GL_TEXTURE_MAG_FILTER, GL_NEAREST);
GL45C.glSamplerParameteri(blockSampler, GL45C.GL_TEXTURE_MIN_LOD, 0);
GL45C.glSamplerParameteri(blockSampler, GL45C.GL_TEXTURE_MAX_LOD, 4);
}
private static void setTexture(int textureId, int bindingPoint) {
GlStateManager._activeTexture(33984 + bindingPoint);
GlStateManager._bindTexture(textureId);
}
public void raster(int regionCount, long commandAddr) {
shader.bind();
int blockId = MinecraftClient.getInstance().getTextureManager().getTexture(new Identifier("minecraft", "textures/atlas/blocks.png")).getGlId();
int lightId = ((LightMapAccessor)MinecraftClient.getInstance().gameRenderer.getLightmapTextureManager()).getTexture().getGlId();
//GL45C.glBindTextureUnit(0, blockId);
GL45C.glBindSampler(0, blockSampler);
//GL45C.glBindTextureUnit(1, lightId);
GL45C.glBindSampler(1, lightSampler);
setTexture(blockId, 0);
setTexture(lightId, 1);
glBufferAddressRangeNV(GL_DRAW_INDIRECT_ADDRESS_NV, 0, commandAddr, regionCount*8L);//Bind the command buffer
glMultiDrawMeshTasksIndirectNV( 0, regionCount, 0);
GL45C.glBindSampler(0, 0);
GL45C.glBindSampler(1, 0);
}
public void delete() {
GL45.glDeleteSamplers(blockSampler);
GL45.glDeleteSamplers(lightSampler);
shader.delete();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\renderers\RegionRasterizer.java
|
package me.cortex.nvidium.renderers;
import me.cortex.nvidium.gl.shader.Shader;
import me.cortex.nvidium.sodiumCompat.ShaderLoader;
import me.jellysquid.mods.sodium.client.gl.shader.ShaderParser;
import net.minecraft.util.Identifier;
import static me.cortex.nvidium.gl.shader.ShaderType.FRAGMENT;
import static me.cortex.nvidium.gl.shader.ShaderType.MESH;
import static org.lwjgl.opengl.NVMeshShader.glDrawMeshTasksNV;
public class RegionRasterizer extends Phase {
private final Shader shader = Shader.make()
.addSource(MESH, ShaderLoader.parse(new Identifier("nvidium", "occlusion/region_raster/mesh.glsl")))
.addSource(FRAGMENT, ShaderLoader.parse(new Identifier("nvidium", "occlusion/region_raster/fragment.frag")))
.compile();
public void raster(int regionCount) {
shader.bind();
glDrawMeshTasksNV(0,regionCount);
}
public void delete() {
shader.delete();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\renderers\SectionRasterizer.java
|
package me.cortex.nvidium.renderers;
import me.cortex.nvidium.gl.shader.Shader;
import me.cortex.nvidium.sodiumCompat.ShaderLoader;
import me.jellysquid.mods.sodium.client.gl.shader.ShaderParser;
import net.minecraft.util.Identifier;
import static me.cortex.nvidium.gl.shader.ShaderType.*;
import static org.lwjgl.opengl.NVMeshShader.glDrawMeshTasksNV;
//TODO:FIXME: CLEANUP
public class SectionRasterizer extends Phase {
private final Shader shader = Shader.make()
.addSource(TASK, ShaderLoader.parse(new Identifier("nvidium", "occlusion/section_raster/task.glsl")))
.addSource(MESH, ShaderLoader.parse(new Identifier("nvidium", "occlusion/section_raster/mesh.glsl")))
.addSource(FRAGMENT, ShaderLoader.parse(new Identifier("nvidium", "occlusion/section_raster/fragment.glsl"))).compile();
public void raster(int regionCount) {
shader.bind();
glDrawMeshTasksNV(0,regionCount);
}
public void delete() {
shader.delete();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\renderers\SortRegionSectionPhase.java
|
package me.cortex.nvidium.renderers;
import com.mojang.blaze3d.platform.GlStateManager;
import me.cortex.nvidium.gl.shader.Shader;
import me.cortex.nvidium.mixin.minecraft.LightMapAccessor;
import me.cortex.nvidium.sodiumCompat.ShaderLoader;
import net.minecraft.client.MinecraftClient;
import net.minecraft.util.Identifier;
import org.lwjgl.opengl.GL45;
import org.lwjgl.opengl.GL45C;
import static me.cortex.nvidium.RenderPipeline.GL_DRAW_INDIRECT_ADDRESS_NV;
import static me.cortex.nvidium.gl.shader.ShaderType.*;
import static org.lwjgl.opengl.GL11C.GL_NEAREST;
import static org.lwjgl.opengl.GL11C.GL_NEAREST_MIPMAP_LINEAR;
import static org.lwjgl.opengl.GL33.glGenSamplers;
import static org.lwjgl.opengl.GL43C.glDispatchCompute;
import static org.lwjgl.opengl.NVMeshShader.glMultiDrawMeshTasksIndirectNV;
import static org.lwjgl.opengl.NVVertexBufferUnifiedMemory.glBufferAddressRangeNV;
public class SortRegionSectionPhase extends Phase {
private final Shader shader = Shader.make()
.addSource(COMPUTE, ShaderLoader.parse(new Identifier("nvidium", "sorting/region_section_sorter.comp")))
.compile();
public SortRegionSectionPhase() {
}
public void dispatch(int sortingRegionCount) {
shader.bind();
glDispatchCompute(sortingRegionCount, 1, 1);
}
public void delete() {
shader.delete();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\renderers\TemporalTerrainRasterizer.java
|
package me.cortex.nvidium.renderers;
import me.cortex.nvidium.gl.shader.Shader;
import me.cortex.nvidium.sodiumCompat.ShaderLoader;
import me.cortex.nvidium.mixin.minecraft.LightMapAccessor;
import net.minecraft.client.MinecraftClient;
import net.minecraft.util.Identifier;
import org.lwjgl.opengl.GL45;
import org.lwjgl.opengl.GL45C;
import static me.cortex.nvidium.RenderPipeline.GL_DRAW_INDIRECT_ADDRESS_NV;
import static me.cortex.nvidium.gl.shader.ShaderType.*;
import static org.lwjgl.opengl.GL11C.GL_NEAREST;
import static org.lwjgl.opengl.GL11C.GL_NEAREST_MIPMAP_LINEAR;
import static org.lwjgl.opengl.GL33.glGenSamplers;
import static org.lwjgl.opengl.NVMeshShader.glMultiDrawMeshTasksIndirectNV;
import static org.lwjgl.opengl.NVVertexBufferUnifiedMemory.glBufferAddressRangeNV;
public class TemporalTerrainRasterizer extends Phase {
private final int blockSampler = glGenSamplers();
private final int lightSampler = glGenSamplers();
private final Shader shader = Shader.make()
.addSource(TASK, ShaderLoader.parse(new Identifier("nvidium", "terrain/temporal_task.glsl")))
.addSource(MESH, ShaderLoader.parse(new Identifier("nvidium", "terrain/mesh.glsl")))
.addSource(FRAGMENT, ShaderLoader.parse(new Identifier("nvidium", "terrain/frag.frag"))).compile();
public TemporalTerrainRasterizer() {
GL45C.glSamplerParameteri(blockSampler, GL45C.GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
GL45C.glSamplerParameteri(blockSampler, GL45C.GL_TEXTURE_MAG_FILTER, GL_NEAREST);
GL45C.glSamplerParameteri(blockSampler, GL45C.GL_TEXTURE_MIN_LOD, 0);
GL45C.glSamplerParameteri(blockSampler, GL45C.GL_TEXTURE_MAX_LOD, 4);
}
public void raster(int regionCount, long commandAddr) {
shader.bind();
int blockId = MinecraftClient.getInstance().getTextureManager().getTexture(new Identifier("minecraft", "textures/atlas/blocks.png")).getGlId();
int lightId = ((LightMapAccessor)MinecraftClient.getInstance().gameRenderer.getLightmapTextureManager()).getTexture().getGlId();
GL45C.glBindTextureUnit(0, blockId);
GL45C.glBindSampler(0, blockSampler);
GL45C.glBindTextureUnit(1, lightId);
GL45C.glBindSampler(1, lightSampler);
glBufferAddressRangeNV(GL_DRAW_INDIRECT_ADDRESS_NV, 0, commandAddr, regionCount*8L);//Bind the command buffer
glMultiDrawMeshTasksIndirectNV( 0, regionCount, 0);
GL45C.glBindSampler(0, 0);
GL45C.glBindSampler(1, 0);
}
public void delete() {
GL45.glDeleteSamplers(blockSampler);
GL45.glDeleteSamplers(lightSampler);
shader.delete();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\renderers\TranslucentTerrainRasterizer.java
|
package me.cortex.nvidium.renderers;
import com.mojang.blaze3d.platform.GlStateManager;
import me.cortex.nvidium.gl.shader.Shader;
import me.cortex.nvidium.sodiumCompat.ShaderLoader;
import me.cortex.nvidium.mixin.minecraft.LightMapAccessor;
import net.minecraft.client.MinecraftClient;
import net.minecraft.util.Identifier;
import org.lwjgl.opengl.GL30C;
import org.lwjgl.opengl.GL45;
import org.lwjgl.opengl.GL45C;
import static me.cortex.nvidium.RenderPipeline.GL_DRAW_INDIRECT_ADDRESS_NV;
import static me.cortex.nvidium.gl.shader.ShaderType.*;
import static org.lwjgl.opengl.GL11C.GL_NEAREST;
import static org.lwjgl.opengl.GL11C.GL_NEAREST_MIPMAP_LINEAR;
import static org.lwjgl.opengl.GL33.glGenSamplers;
import static org.lwjgl.opengl.NVMeshShader.glMultiDrawMeshTasksIndirectNV;
import static org.lwjgl.opengl.NVVertexBufferUnifiedMemory.glBufferAddressRangeNV;
public class TranslucentTerrainRasterizer extends Phase {
private final int blockSampler = glGenSamplers();
private final int lightSampler = glGenSamplers();
private final Shader shader = Shader.make()
.addSource(TASK, ShaderLoader.parse(new Identifier("nvidium", "terrain/translucent/task.glsl")))
.addSource(MESH, ShaderLoader.parse(new Identifier("nvidium", "terrain/translucent/mesh.glsl")))
.addSource(FRAGMENT, ShaderLoader.parse(new Identifier("nvidium", "terrain/translucent/frag.frag")))
.compile();
public TranslucentTerrainRasterizer() {
GL45C.glSamplerParameteri(blockSampler, GL45C.GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
GL45C.glSamplerParameteri(blockSampler, GL45C.GL_TEXTURE_MAG_FILTER, GL_NEAREST);
GL45C.glSamplerParameteri(blockSampler, GL45C.GL_TEXTURE_MIN_LOD, 0);
GL45C.glSamplerParameteri(blockSampler, GL45C.GL_TEXTURE_MAX_LOD, 4);
}
private static void setTexture(int textureId, int bindingPoint) {
GlStateManager._activeTexture(33984 + bindingPoint);
GlStateManager._bindTexture(textureId);
}
//Translucency is rendered in a very cursed and incorrect way
// it hijacks the unassigned indirect command dispatch and uses that to dispatch the translucent chunks as well
public void raster(int regionCount, long commandAddr) {
shader.bind();
int blockId = MinecraftClient.getInstance().getTextureManager().getTexture(new Identifier("minecraft", "textures/atlas/blocks.png")).getGlId();
int lightId = ((LightMapAccessor)MinecraftClient.getInstance().gameRenderer.getLightmapTextureManager()).getTexture().getGlId();
//GL45C.glBindTextureUnit(0, blockId);
//GL45C.glBindSampler(0, blockSampler);
//GL45C.glBindTextureUnit(1, lightId);
//GL45C.glBindSampler(1, lightSampler);
setTexture(blockId, 0);
setTexture(lightId, 1);
//the +8*6 is to offset to the unassigned dispatch
glBufferAddressRangeNV(GL_DRAW_INDIRECT_ADDRESS_NV, 0, commandAddr, regionCount*8L);//Bind the command buffer
glMultiDrawMeshTasksIndirectNV( 0, regionCount, 0);
GL45C.glBindSampler(0, 0);
GL45C.glBindSampler(1, 0);
}
public void delete() {
GL45.glDeleteSamplers(blockSampler);
GL45.glDeleteSamplers(lightSampler);
shader.delete();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\sodiumCompat\INvidiumWorldRendererGetter.java
|
package me.cortex.nvidium.sodiumCompat;
import me.cortex.nvidium.NvidiumWorldRenderer;
public interface INvidiumWorldRendererGetter {
NvidiumWorldRenderer getRenderer();
}
|
acedium
|
src\main\java\me\cortex\nvidium\sodiumCompat\INvidiumWorldRendererSetter.java
|
package me.cortex.nvidium.sodiumCompat;
import me.cortex.nvidium.NvidiumWorldRenderer;
public interface INvidiumWorldRendererSetter {
void setWorldRenderer(NvidiumWorldRenderer renderer);
}
|
acedium
|
src\main\java\me\cortex\nvidium\sodiumCompat\IRenderSectionExtension.java
|
package me.cortex.nvidium.sodiumCompat;
public interface IRenderSectionExtension {
boolean isSubmittedRebuild();
void isSubmittedRebuild(boolean state);
boolean isSeen();
void isSeen(boolean state);
}
|
acedium
|
src\main\java\me\cortex\nvidium\sodiumCompat\IRepackagedResult.java
|
package me.cortex.nvidium.sodiumCompat;
public interface IRepackagedResult {
RepackagedSectionOutput getOutput();
void set(RepackagedSectionOutput output);
}
|
acedium
|
src\main\java\me\cortex\nvidium\sodiumCompat\IrisCheck.java
|
package me.cortex.nvidium.sodiumCompat;
import net.irisshaders.iris.api.v0.IrisApi;
import net.neoforged.fml.loading.FMLLoader;
public class IrisCheck {
public static final boolean IRIS_LOADED = FMLLoader.getLoadingModList().getModFileById("oculus") != null;
private static boolean checkIrisShaders() {
return IrisApi.getInstance().isShaderPackInUse();
}
public static boolean checkIrisShouldDisable() {
return !(IRIS_LOADED && checkIrisShaders());
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\sodiumCompat\NvidiumCompactChunkVertex.java
|
package me.cortex.nvidium.sodiumCompat;
import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexAttributeFormat;
import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexFormat;
import me.jellysquid.mods.sodium.client.render.chunk.terrain.material.Material;
import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkMeshAttribute;
import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexEncoder;
import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexType;
import net.caffeinemc.mods.sodium.api.util.ColorABGR;
import net.caffeinemc.mods.sodium.api.util.ColorU8;
import org.lwjgl.system.MemoryUtil;
public class NvidiumCompactChunkVertex implements ChunkVertexType {
public static final GlVertexFormat<ChunkMeshAttribute> VERTEX_FORMAT = new GlVertexFormat<>(ChunkMeshAttribute.class, null, 16);
public static final int STRIDE = 16;
public static final NvidiumCompactChunkVertex INSTANCE = new NvidiumCompactChunkVertex();
private static final int POSITION_MAX_VALUE = 65536;
public static final int TEXTURE_MAX_VALUE = 32768;
private static final float MODEL_ORIGIN = 8.0f;
private static final float MODEL_RANGE = 32.0f;
private static final float MODEL_SCALE = MODEL_RANGE / POSITION_MAX_VALUE;
private static final float MODEL_SCALE_INV = POSITION_MAX_VALUE / MODEL_RANGE;
private static final float TEXTURE_SCALE = (1.0f / TEXTURE_MAX_VALUE);
@Override
public float getTextureScale() {
return TEXTURE_SCALE;
}
@Override
public float getPositionScale() {
return MODEL_SCALE;
}
@Override
public float getPositionOffset() {
return -MODEL_ORIGIN;
}
@Override
public GlVertexFormat<ChunkMeshAttribute> getVertexFormat() {
return VERTEX_FORMAT;
}
@Override
public ChunkVertexEncoder getEncoder() {
return (ptr, material, vertex, sectionIndex) -> {
MemoryUtil.memPutInt(ptr + 0, (encodePosition(vertex.x) << 0) | (encodePosition(vertex.y) << 16));
MemoryUtil.memPutInt(ptr + 4, (encodePosition(vertex.z) << 0) | (encodeDrawParameters(material, sectionIndex) << 16));
MemoryUtil.memPutInt(ptr + 8, (encodeColor(vertex.color) << 0) | (encodeLight(vertex.light) << 24));
MemoryUtil.memPutInt(ptr + 12, encodeTexture(vertex.u, vertex.v));
return ptr + STRIDE;
};
}
private static int encodePosition(float v) {
return (int) ((MODEL_ORIGIN + v) * MODEL_SCALE_INV);
}
private static int encodeDrawParameters(Material material, int sectionIndex) {
return (((sectionIndex & 0xFF) << 8) | ((material.bits() & 0xFF) << 0));
}
private static int encodeColor(int color) {
var brightness = ColorU8.byteToNormalizedFloat(ColorABGR.unpackAlpha(color));
int r = ColorU8.normalizedFloatToByte(ColorU8.byteToNormalizedFloat(ColorABGR.unpackRed(color)) * brightness);
int g = ColorU8.normalizedFloatToByte(ColorU8.byteToNormalizedFloat(ColorABGR.unpackGreen(color)) * brightness);
int b = ColorU8.normalizedFloatToByte(ColorU8.byteToNormalizedFloat(ColorABGR.unpackBlue(color)) * brightness);
return ColorABGR.pack(r, g, b, 0x00);
}
private static int encodeLight(int light) {
int block = (light >> 4) & 0xF;
int sky = (light >> 20) & 0xF;
return ((block << 0) | (sky << 4));
}
private static int encodeTexture(float u, float v) {
return ((Math.round(u * TEXTURE_MAX_VALUE) & 0xFFFF) << 0) |
((Math.round(v * TEXTURE_MAX_VALUE) & 0xFFFF) << 16);
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\sodiumCompat\NvidiumOptionFlags.java
|
package me.cortex.nvidium.sodiumCompat;
import me.jellysquid.mods.sodium.client.gui.options.OptionFlag;
public class NvidiumOptionFlags {
public static OptionFlag REQUIRES_SHADER_RELOAD;
}
|
acedium
|
src\main\java\me\cortex\nvidium\sodiumCompat\RepackagedSectionOutput.java
|
package me.cortex.nvidium.sodiumCompat;
import me.jellysquid.mods.sodium.client.util.NativeBuffer;
import org.joml.Vector3i;
//Computed on the build thread instead of the render thread saving alot of 1% lows
public record RepackagedSectionOutput(int quads,
NativeBuffer geometry,
short[] offsets,
Vector3i min,
Vector3i size) {
public void delete() {
geometry.free();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\sodiumCompat\ShaderLoader.java
|
package me.cortex.nvidium.sodiumCompat;
import me.cortex.nvidium.Nvidium;
import me.cortex.nvidium.config.StatisticsLoggingLevel;
import me.cortex.nvidium.config.TranslucencySortingLevel;
import me.jellysquid.mods.sodium.client.gl.shader.ShaderConstants;
import me.jellysquid.mods.sodium.client.gl.shader.ShaderParser;
import net.minecraft.util.Identifier;
public class ShaderLoader {
public static String parse(Identifier path) {
var builder = ShaderConstants.builder();
if (Nvidium.IS_DEBUG) {
builder.add("DEBUG");
}
for (int i = 1; i <= Nvidium.config.statistics_level.ordinal(); i++) {
builder.add("STATISTICS_"+StatisticsLoggingLevel.values()[i].name());
}
for (int i = 1; i <= Nvidium.config.translucency_sorting_level.ordinal(); i++) {
builder.add("TRANSLUCENCY_SORTING_"+TranslucencySortingLevel.values()[i].name());
}
builder.add("TEXTURE_MAX_SCALE", String.valueOf(NvidiumCompactChunkVertex.TEXTURE_MAX_VALUE));
return ShaderParser.parseShader("#import <"+path.getNamespace()+":"+path.getPath()+">", builder.build());
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\sodiumCompat\SodiumResultCompatibility.java
|
package me.cortex.nvidium.sodiumCompat;
import it.unimi.dsi.fastutil.ints.IntArrays;
import it.unimi.dsi.fastutil.longs.LongArrays;
import me.cortex.nvidium.Nvidium;
import me.jellysquid.mods.sodium.client.model.quad.properties.ModelQuadFacing;
import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildOutput;
import me.jellysquid.mods.sodium.client.render.chunk.terrain.DefaultTerrainRenderPasses;
import me.jellysquid.mods.sodium.client.util.NativeBuffer;
import net.minecraft.client.MinecraftClient;
import net.minecraft.util.math.Vec3d;
import org.joml.Vector3f;
import org.joml.Vector3i;
import org.lwjgl.system.MemoryUtil;
public class SodiumResultCompatibility {
public static RepackagedSectionOutput repackage(ChunkBuildOutput result) {
int formatSize = 16;
int geometryBytes = result.meshes.values().stream().mapToInt(a->a.getVertexData().getLength()).sum();
var output = new NativeBuffer(geometryBytes);
var offsets = new short[8];
var min = new Vector3i(2000);
var max = new Vector3i(-2000);
packageSectionGeometry(formatSize, output, offsets, result, min, max);
Vector3i size;
{
min.x = Math.max(min.x, 0);
min.y = Math.max(min.y, 0);
min.z = Math.max(min.z, 0);
min.x = Math.min(min.x, 15);
min.y = Math.min(min.y, 15);
min.z = Math.min(min.z, 15);
max.x = Math.min(max.x, 16);
max.y = Math.min(max.y, 16);
max.z = Math.min(max.z, 16);
max.x = Math.max(max.x, 0);
max.y = Math.max(max.y, 0);
max.z = Math.max(max.z, 0);
size = new Vector3i(max.x - min.x - 1, max.y - min.y - 1, max.z - min.z - 1);
size.x = Math.min(15, Math.max(size.x, 0));
size.y = Math.min(15, Math.max(size.y, 0));
size.z = Math.min(15, Math.max(size.z, 0));
}
var repackagedGeometry = new RepackagedSectionOutput((geometryBytes/formatSize)/4, output, offsets, min, size);
//NvidiumGeometryReencoder.transpileGeometry(repackagedGeometry);
return repackagedGeometry;
}
private static void copyQuad(long from, long too) {
//Quads are 64 bytes big
for (long i = 0; i < 64; i+=8) {
MemoryUtil.memPutLong(too + i, MemoryUtil.memGetLong(from + i));
}
}
//Everything is /6*4 cause its in indices and we want verticies
private static void packageSectionGeometry(int formatSize, NativeBuffer output, short[] outOffsets, ChunkBuildOutput result, Vector3i min, Vector3i max) {
int offset = 0;
long outPtr = MemoryUtil.memAddress(output.getDirectBuffer());
//NOTE: mutates the input translucent geometry
var cameraPos = MinecraftClient.getInstance().gameRenderer.getCamera().getPos();
float cpx = (float) (cameraPos.x - (result.render.getChunkX()<<4));
float cpy = (float) (cameraPos.y - (result.render.getChunkY()<<4));
float cpz = (float) (cameraPos.z - (result.render.getChunkZ()<<4));
{//Project the camera pos onto the bounding outline of the chunk (-8 -> 24 for each axis)
float len = (float) Math.sqrt(cpx*cpx + cpy*cpy + cpz*cpz);
cpx *= 1/len;
cpy *= 1/len;
cpz *= 1/len;
//The max range of the camera can be is like 32 blocks away so just use that
len = Math.min(len, 32);
cpx *= len;
cpy *= len;
cpz *= len;
}
//Do translucent first
var translucentData = result.meshes.get(DefaultTerrainRenderPasses.TRANSLUCENT);
if (translucentData != null) {
int quadCount = 0;
for (int i = 0; i < 7; i++) {
var part = translucentData.getVertexRanges()[i];
quadCount += part != null?part.vertexCount()/4:0;
}
int quadId = 0;
long[] sortingData = new long[quadCount];
long[] srcs = new long[7];
for (int i = 0; i < 7; i++) {
var part = translucentData.getVertexRanges()[i];
if (part != null) {
long src = MemoryUtil.memAddress(translucentData.getVertexData().getDirectBuffer()) + (long) part.vertexStart() * formatSize;
srcs[i] = src;
float cx = 0;
float cy = 0;
float cz = 0;
//Update the meta bits of the model format
for (int j = 0; j < part.vertexCount(); j++) {
long base = src + (long) j * formatSize;
short flags = (short) 0b100;//Mipping, No alpha cut
MemoryUtil.memPutShort(base + 6L, flags);//Note: the 6 here is the offset into the vertex format
float x = decodePosition(MemoryUtil.memGetShort(base));
float y = decodePosition(MemoryUtil.memGetShort(base + 2));
float z = decodePosition(MemoryUtil.memGetShort(base + 4));
updateSectionBounds(min, max, x, y, z);
cx += x;
cy += y;
cz += z;
if ((j&3) == 3) {
//Compute the center point of the vertex
cx *= 1 / 4f;
cy *= 1 / 4f;
cz *= 1 / 4f;
//Distance to camera
float dx = cx-cpx;
float dy = cy-cpy;
float dz = cz-cpz;
float dist = dx*dx + dy*dy + dz*dz;
int sortDistance = (int) (dist*(1<<12));
//We pack the sorting data
long packedSortingData = (((long)sortDistance)<<32)|((((long) j>>2)<<3)|i);
sortingData[quadId++] = packedSortingData;
cx = 0;
cy = 0;
cz = 0;
}
}
}
}
if (quadId != sortingData.length) {
throw new IllegalStateException();
}
LongArrays.radixSort(sortingData);
for (int i = 0; i < sortingData.length; i++) {
long data = sortingData[i];
copyQuad(srcs[(int) (data&7)] + ((data>>3)&((1L<<29)-1))*4*formatSize, outPtr + ((sortingData.length-1)-i) * 4L * formatSize);
}
offset += quadCount;
}
outOffsets[7] = (short) offset;
var solid = result.meshes.get(DefaultTerrainRenderPasses.SOLID);
var cutout = result.meshes.get(DefaultTerrainRenderPasses.CUTOUT);
//Do all but translucent
for (int i = 0; i < 7; i++) {
int poff = offset;
if (solid != null) {
var part = solid.getVertexRanges()[i];
if (part != null) {
long src = MemoryUtil.memAddress(solid.getVertexData().getDirectBuffer()) + (long) part.vertexStart() * formatSize;
long dst = outPtr + offset * 4L * formatSize;
MemoryUtil.memCopy(src, dst, (long) part.vertexCount() * formatSize);
//Update the meta bits of the model format
for (int j = 0; j < part.vertexCount(); j++) {
long base = dst+ (long) j * formatSize;
short flags = (short) 0b100;//Mipping, No alpha cut
MemoryUtil.memPutShort(base + 6L, flags);//Note: the 6 here is the offset into the vertex format
updateSectionBounds(min, max, base);
}
offset += part.vertexCount()/4;
}
}
if (cutout != null) {
var part = cutout.getVertexRanges()[i];
if (part != null) {
long src = MemoryUtil.memAddress(cutout.getVertexData().getDirectBuffer()) + (long) part.vertexStart() * formatSize;
long dst = outPtr + offset * 4L * formatSize;
MemoryUtil.memCopy(src, dst, (long) part.vertexCount() * formatSize);
//Update the meta bits of the model format
for (int j = 0; j < part.vertexCount(); j++) {
long base = dst + (long) j * formatSize;
short sflags = MemoryUtil.memGetShort(base + 6L);
short mipbits = (short) ((sflags&(3<<1))>>1);
//mipping, remap 0.5 cut to 0.1 when iris is loaded
if (mipbits == 0b10 && IrisCheck.IRIS_LOADED) {
mipbits = 0b01;
}
short flags = (short) (((sflags&1)<<2) | mipbits);
MemoryUtil.memPutShort(base + 6L, flags);//Note: the 6 here is the offset into the vertex format
updateSectionBounds(min, max, base);
}
offset += part.vertexCount()/4;
}
}
outOffsets[i] = (short) (offset - poff);
}
if (offset*4*formatSize != output.getLength()) {
throw new IllegalStateException();
}
}
private static float decodePosition(short v) {
return Short.toUnsignedInt(v)*(1f/2048.0f)-8.0f;
}
private static void updateSectionBounds(Vector3i min, Vector3i max, long vertex) {
float x = decodePosition(MemoryUtil.memGetShort(vertex));
float y = decodePosition(MemoryUtil.memGetShort(vertex + 2));
float z = decodePosition(MemoryUtil.memGetShort(vertex + 4));
updateSectionBounds(min, max, x, y, z);
}
private static void updateSectionBounds(Vector3i min, Vector3i max, float x, float y, float z) {
min.x = (int) Math.min(min.x, Math.floor(x));
min.y = (int) Math.min(min.y, Math.floor(y));
min.z = (int) Math.min(min.z, Math.floor(z));
max.x = (int) Math.max(max.x, Math.ceil(x));
max.y = (int) Math.max(max.y, Math.ceil(y));
max.z = (int) Math.max(max.z, Math.ceil(z));
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\util\BufferArena.java
|
package me.cortex.nvidium.util;
import me.cortex.nvidium.Nvidium;
import me.cortex.nvidium.gl.RenderDevice;
import me.cortex.nvidium.gl.buffers.IDeviceMappedBuffer;
import me.cortex.nvidium.gl.buffers.PersistentSparseAddressableBuffer;
//TODO: make it not remove and immediatly deallocate the sparse pages, wait until the end of a frame to deallocate
// and do it intellegiently cause commiting/uncommiting pages is very expensive
public class BufferArena {
SegmentedManager segments = new SegmentedManager();
private final RenderDevice device;
public final IDeviceMappedBuffer buffer;
private long totalQuads;
private final int vertexFormatSize;
private final long memory_size;
public BufferArena(RenderDevice device, long memory, int vertexFormatSize) {
this.device = device;
this.vertexFormatSize = vertexFormatSize;
this.memory_size = memory;
if (Nvidium.SUPPORTS_PERSISTENT_SPARSE_ADDRESSABLE_BUFFER) {
buffer = device.createSparseBuffer(80000000000L);//Create a 80gb buffer
} else {
buffer = device.createDeviceOnlyMappedBuffer(memory);
}
//Reserve index 0
this.allocQuads(1);
}
public int allocQuads(int quadCount) {
totalQuads += quadCount;
int addr = (int) segments.alloc(quadCount);
if (buffer instanceof PersistentSparseAddressableBuffer psab) {
psab.ensureAllocated(Integer.toUnsignedLong(addr) * 4L * vertexFormatSize, quadCount * 4L * vertexFormatSize);
}
return addr;
}
public void free(int addr) {
int count = segments.free(addr);
totalQuads -= count;
if (buffer instanceof PersistentSparseAddressableBuffer psab) {
psab.deallocate(Integer.toUnsignedLong(addr) * 4L * vertexFormatSize, count * 4L * vertexFormatSize);
}
}
public long upload(UploadingBufferStream stream, int addr) {
return stream.upload(buffer, Integer.toUnsignedLong(addr)*4L*vertexFormatSize, (int) segments.getSize(addr)*4*vertexFormatSize);
}
public void delete() {
buffer.delete();
}
public int getAllocatedMB() {
if (buffer instanceof PersistentSparseAddressableBuffer psab) {
return (int) ((psab.getPagesCommitted() * PersistentSparseAddressableBuffer.PAGE_SIZE) / (1024 * 1024));
} else {
return (int) (memory_size/(1024*1024));
}
}
public int getUsedMB() {
return (int) ((totalQuads * vertexFormatSize * 4)/(1024*1024));
}
public long getMemoryUsed() {
if (buffer instanceof PersistentSparseAddressableBuffer psab) {
return (psab.getPagesCommitted() * PersistentSparseAddressableBuffer.PAGE_SIZE);
} else {
return memory_size;
}
}
public float getFragmentation() {
long expected = totalQuads * vertexFormatSize * 4;
return (float) ((double)expected/getMemoryUsed());
}
public boolean canReuse(int addr, int quads) {
return this.segments.getSize(addr) == quads;
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\util\DownloadTaskStream.java
|
package me.cortex.nvidium.util;
import it.unimi.dsi.fastutil.longs.LongArrayList;
import it.unimi.dsi.fastutil.longs.LongList;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectList;
import me.cortex.nvidium.gl.RenderDevice;
import me.cortex.nvidium.gl.buffers.Buffer;
import me.cortex.nvidium.gl.buffers.PersistentClientMappedBuffer;
import me.cortex.nvidium.util.SegmentedManager;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
//Download stream from gpu to cpu
//TODO: i think it needs to be one extra frame
public class DownloadTaskStream {
public interface IDownloadFinishedCallback {void accept(long addr);}
private record Download(long addr, IDownloadFinishedCallback callback) {}
private final SegmentedManager allocator = new SegmentedManager();
private final RenderDevice device;
private PersistentClientMappedBuffer buffer;//TODO: make it self resizing if full
private int cidx;
private final ObjectList<Download>[] allocations;
public DownloadTaskStream(RenderDevice device, int frames, long size) {
this.device = device;
allocator.setLimit(size);
buffer = device.createClientMappedBuffer(size);
TickableManager.register(this);
allocations = new ObjectList[frames];
for (int i = 0; i < frames; i++) {
allocations[i] = new ObjectArrayList<>();
}
}
public void download(Buffer source, long offset, int size, IDownloadFinishedCallback callback) {
long addr = allocator.alloc(size);
device.copyBuffer(source, buffer, offset, addr, size);
allocations[cidx].add(new Download(addr, callback));
}
void tick() {
cidx = (cidx+1)%allocations.length;
for (var download : allocations[cidx]) {
download.callback.accept(download.addr + buffer.clientAddress());
allocator.free(download.addr);
}
allocations[cidx].clear();
}
public void delete() {
TickableManager.remove(this);
buffer.delete();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\util\IdProvider.java
|
package me.cortex.nvidium.util;
import it.unimi.dsi.fastutil.ints.IntAVLTreeSet;
import it.unimi.dsi.fastutil.ints.IntSortedSet;
public class IdProvider {
private int cid = 0;
private final IntSortedSet free = new IntAVLTreeSet(Integer::compareTo);
public int provide() {
if (free.isEmpty()) {
return cid++;
}
int ret = free.firstInt();
free.remove(ret);
return ret;
}
public void release(int id) {
free.add(id);
while ((!free.isEmpty()) && free.lastInt()+1 == cid) {
free.remove(--cid);
}
}
public int maxIndex() {
return cid;
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\util\ResourceTracker.java
|
package me.cortex.nvidium.util;
import java.lang.ref.Cleaner;
public class ResourceTracker {
private static ResourceTracker TRACKER = new ResourceTracker();
private final Cleaner cleaner = Cleaner.create();
public void track(Object object, Runnable destructor) {
cleaner.register(object, ()->onObjectCleanup(destructor));
}
public static void watch(Object object, Runnable cleaner) {
TRACKER.track(object, cleaner);
}
private void onObjectCleanup(Runnable destructor) {
//TODO: Track cleanup
destructor.run();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\util\SegmentedManager.java
|
package me.cortex.nvidium.util;
import it.unimi.dsi.fastutil.longs.LongArrayList;
import it.unimi.dsi.fastutil.longs.LongList;
import it.unimi.dsi.fastutil.longs.LongRBTreeSet;
import java.util.Random;
//FIXME: NOTE: if there is a free block of size > 2^30 EVERYTHING BREAKS, need to either increase size
// or automatically split and manage multiple blocks which is very painful
//OR instead of addr, defer to a long[] and use indicies
//TODO: replace the LongAVLTreeSet with a custom implementation that doesnt cause allocations when searching
// and see if something like a RBTree is any better
public class SegmentedManager {
public static final long SIZE_LIMIT = -1;
private final int ADDR_BITS = 34;//This gives max size per allocation of 2^30 and max address of 2^39
private final int SIZE_BITS = 64 - ADDR_BITS;
private final long SIZE_MSK = (1L<<SIZE_BITS)-1;
private final long ADDR_MSK = (1L<<ADDR_BITS)-1;
private final LongRBTreeSet FREE = new LongRBTreeSet();//Size Address
private final LongRBTreeSet TAKEN = new LongRBTreeSet();//Address Size
private long sizeLimit = Long.MAX_VALUE;
private long totalSize;
//Flags
public boolean resized;//If the required memory of the entire buffer grew
public long getSize() {
return totalSize;
}
/*
public long allocFromLargest(int size) {//Allocates from the largest avalible block, this is useful for expanding later on
}*/
public long alloc(int size) {//TODO: add alignment support
if (size == 0) throw new IllegalArgumentException();
//This is stupid, iterator is not inclusive
var iter = FREE.iterator(((long) size << ADDR_BITS)-1);
if (!iter.hasNext()) {//No free space for allocation
//Create new allocation
resized = true;
long addr = totalSize;
if (totalSize+size>sizeLimit) {
return SIZE_LIMIT;
}
totalSize += size;
TAKEN.add((addr<<SIZE_BITS)|((long) size));
return addr;
} else {
long slot = iter.nextLong();
iter.remove();
if ((slot >>> ADDR_BITS) == size) {//If the allocation and slot is the same size, just add it to the taken
TAKEN.add((slot<<SIZE_BITS)|(slot >>> ADDR_BITS));
} else {
TAKEN.add(((slot&ADDR_MSK)<<SIZE_BITS)|size);
FREE.add((((slot >>> ADDR_BITS)-size)<<ADDR_BITS)|((slot&ADDR_MSK)+size));
}
resized = false;
return slot&ADDR_MSK;
}
}
public int free(long addr) {//Returns size of freed memory
addr &= ADDR_MSK;//encase addr stores shit in its upper bits
var iter = TAKEN.iterator(addr<<SIZE_BITS);//Dont need to include -1 as size != 0
long slot = iter.nextLong();
if (slot>>SIZE_BITS != addr) {
throw new IllegalStateException();
}
long size = slot&SIZE_MSK;
iter.remove();
//Note: if there is a previous entry, it means that it is guaranteed for the ending address to either
// be the addr, or indicate a free slot that needs to be merged
if (iter.hasPrevious()) {
long prevSlot = iter.previousLong();
long endAddr = (prevSlot>>>SIZE_BITS) + (prevSlot&SIZE_MSK);
if (endAddr != addr) {//It means there is a free slot that needs to get merged into
long delta = (addr - endAddr);
FREE.remove((delta<<ADDR_BITS)|endAddr);//Free the slot to be merged into
//Generate a new slot to get put into FREE
slot = (endAddr<<SIZE_BITS) | ((slot&SIZE_MSK) + delta);
}
iter.nextLong();//Need to reset the iter into its state
}//If there is no previous it means were at the start of the buffer, we might need to merge with block 0 if we are not block 0
else if (!FREE.isEmpty()) {// if free is not empty it means we must merge with block of free starting at 0
//if (addr != 0)//FIXME: this is very dodgy solution, if addr == 0 it means its impossible for there to be a previous element
if (FREE.remove(addr<<ADDR_BITS)) {//Attempt to remove block 0, this is very dodgy as it assumes block zero is 0 addr n size
slot = addr + size;//slot at address 0 and size of 0 block + new block
}
}
//If there is a next element it is guarenteed to either be the next block, or indicate that there is
// a block that needs to be merged into
if (iter.hasNext()) {
long nextSlot = iter.nextLong();
long endAddr = (slot>>>SIZE_BITS) + (slot&SIZE_MSK);
if (endAddr != nextSlot>>>SIZE_BITS) {//It means there is a memory block to be merged in FREE
long delta = ((nextSlot>>>SIZE_BITS) - endAddr);
FREE.remove((delta<<ADDR_BITS)|endAddr);
slot = (slot&(ADDR_MSK<<SIZE_BITS)) | ((slot&SIZE_MSK) + delta);
}
}// if there is no next block it means that we have reached the end of the allocation sections and we can shrink the buffer
else {
resized = true;
totalSize -= (slot&SIZE_MSK);
return (int) size;
}
resized = false;
//Need to swap around the slot to be in FREE format
slot = (slot>>>SIZE_BITS) | (slot<<ADDR_BITS);
FREE.add(slot);//Add the free slot into segments
return (int) size;
}
//Attempts to expand an allocation, returns true on success
public boolean expand(long addr, int extra) {
addr &= ADDR_MSK;//encase addr stores shit in its upper bits
var iter = TAKEN.iterator(addr<<SIZE_BITS);
if (!iter.hasNext()) {
return false;
}
long slot = iter.nextLong();
if (slot>>SIZE_BITS != addr) {
throw new IllegalStateException();
}
long updatedSlot = (slot & (ADDR_MSK << SIZE_BITS)) | ((slot & SIZE_MSK) + extra);
resized = false;
if (iter.hasNext()) {
long next = iter.nextLong();
long endAddr = (slot>>>SIZE_BITS)+(slot&SIZE_MSK);
long delta = (next>>>SIZE_BITS) - endAddr;
if (extra <= delta) {
FREE.remove((delta<<ADDR_BITS)|endAddr);//Should assert this
iter.previousLong();//FOR SOME REASON NEED TO DO IT TWICE I HAVE NO IDEA WHY
iter.previousLong();
iter.remove();//Remove the allocation so it can be updated
TAKEN.add(updatedSlot);//Update the taken allocation
if (extra != delta) {//More space than needed, need to add a new FREE block
FREE.add(((delta-extra)<<ADDR_BITS)|(endAddr+extra));
}
//else There is exactly enough free space, so removing the free block and updating the allocation is enough
return true;
} else {
return false;//Not enough room to expand
}
} else {//We are at the end of the buffer, we can expand as we like
if (totalSize+extra>sizeLimit)//If expanding and we would exceed the size limit, dont resize
return false;
iter.remove();
TAKEN.add(updatedSlot);
totalSize += extra;
resized = true;
return true;
}
}
public long getSize(long addr) {
addr &= ADDR_MSK;
var iter = TAKEN.iterator(addr << SIZE_BITS);
if (!iter.hasNext())
throw new IllegalArgumentException();
long slot = iter.nextLong();
if (slot>>SIZE_BITS != addr) {
throw new IllegalStateException();
}
return slot&SIZE_MSK;
}
public static void main(String[] args) {
/*
{
SegmentedManager m = new SegmentedManager();
long a = m.alloc(10);
long b = m.alloc(11);
long c = m.alloc(1);
System.out.println(m.expand(a, 1));
m.free(b);
System.out.println(m.expand(a, 1));
System.out.println(m.expand(a, 10));
System.out.println(m.expand(a, 1));
m.free(a);
m.free(c);
System.out.println(m.getSize());
}*/
/*
Random r = new Random(32);
SegmentedManager m = new SegmentedManager();
LongList l = new LongArrayList();
for (int i = 0; i < 5; i++) {
if (r.nextBoolean() || l.isEmpty()) {
long a = m.alloc(r.nextInt(1000) + 1);
l.add(a);
} else {
m.free(l.removeLong(r.nextInt(l.size())));
}
}
for (long a : l) {
m.free(a);
}
System.out.println(m.getSize());
*/
for (int j = 0; j < 10000; j++) {
Random r = new Random(j);
SegmentedManager m = new SegmentedManager();
LongList l = new LongArrayList();
for (int i = 0; i < 5000; i++) {
int ac = r.nextInt(3);
if ( ac ==0 || l.isEmpty()) {
long a = m.alloc(r.nextInt(1000) + 1);
l.add(a);
} else if (ac == 1) {
m.free(l.removeLong(r.nextInt(l.size())));
} else {
m.expand(l.getLong(r.nextInt(l.size())), r.nextInt(10) + 1);
}
}
for (long a : l) {
m.free(a);
}
if (m.getSize() != 0) {
System.out.println(j);
return;
}
}
}
public void setLimit(long size) {
this.sizeLimit = size;
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\util\TickableManager.java
|
package me.cortex.nvidium.util;
import java.lang.ref.WeakReference;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class TickableManager {
private static final Set<UploadingBufferStream> UPLOADERS = new LinkedHashSet<>();
private static final Set<DownloadTaskStream> DOWNLOADERS = new LinkedHashSet<>();
public static void register(UploadingBufferStream stream) {
UPLOADERS.add(stream);
}
public static void register(DownloadTaskStream stream) {
DOWNLOADERS.add(stream);
}
public static void remove(UploadingBufferStream stream) {
UPLOADERS.remove(stream);
}
public static void remove(DownloadTaskStream stream) {
DOWNLOADERS.remove(stream);
}
public static void TickAll() {//Should be called at the very end of the frame
var iter = UPLOADERS.iterator();
while (iter.hasNext()) {
iter.next().tick();
}
var iter2 = DOWNLOADERS.iterator();
while (iter2.hasNext()) {
iter2.next().tick();
}
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\util\UploadingBufferStream.java
|
package me.cortex.nvidium.util;
import it.unimi.dsi.fastutil.longs.LongArrayList;
import it.unimi.dsi.fastutil.longs.LongList;
import it.unimi.dsi.fastutil.objects.ReferenceArrayList;
import me.cortex.nvidium.gl.GlFence;
import me.cortex.nvidium.gl.RenderDevice;
import me.cortex.nvidium.gl.buffers.Buffer;
import me.cortex.nvidium.gl.buffers.PersistentClientMappedBuffer;
import java.lang.ref.WeakReference;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import static me.cortex.nvidium.util.SegmentedManager.SIZE_LIMIT;
import static org.lwjgl.opengl.ARBDirectStateAccess.glCopyNamedBufferSubData;
import static org.lwjgl.opengl.ARBDirectStateAccess.glFlushMappedNamedBufferRange;
import static org.lwjgl.opengl.ARBMapBufferRange.*;
import static org.lwjgl.opengl.GL11.glFinish;
import static org.lwjgl.opengl.GL11.glGetError;
import static org.lwjgl.opengl.GL42.glMemoryBarrier;
import static org.lwjgl.opengl.GL42C.GL_BUFFER_UPDATE_BARRIER_BIT;
import static org.lwjgl.opengl.GL44.GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT;
public class UploadingBufferStream {
private final SegmentedManager allocationArena = new SegmentedManager();
private final PersistentClientMappedBuffer uploadBuffer;
private final Deque<UploadFrame> frames = new ArrayDeque<>();
private final LongArrayList thisFrameAllocations = new LongArrayList();
private final Deque<UploadData> uploadList = new ArrayDeque<>();
private final LongArrayList flushList = new LongArrayList();
public UploadingBufferStream(RenderDevice device, long size) {
this.allocationArena.setLimit(size);
this.uploadBuffer = device.createClientMappedBuffer(size);
TickableManager.register(this);
}
private long caddr = -1;
private long offset = 0;
public long upload(Buffer buffer, long destOffset, long size) {
if (size > Integer.MAX_VALUE) {
throw new IllegalArgumentException();
}
long addr;
if (this.caddr == -1 || !this.allocationArena.expand(this.caddr, (int) size)) {
this.caddr = this.allocationArena.alloc((int) size);//TODO: replace with allocFromLargest
//If the upload stream is full, flush it and empty it
if (this.caddr == SIZE_LIMIT) {
this.commit();
int attempts = 10;
while (--attempts != 0 && this.caddr == SIZE_LIMIT) {
glFinish();
this.tick();
this.caddr = this.allocationArena.alloc((int) size);
}
if (this.caddr == SIZE_LIMIT) {
throw new IllegalStateException("Could not allocate memory segment big enough for upload even after force flush");
}
}
this.flushList.add(this.caddr);
this.offset = size;
addr = this.caddr;
} else {//Could expand the allocation so just update it
addr = this.caddr + this.offset;
this.offset += size;
}
if (this.caddr + size > this.uploadBuffer.size) {
throw new IllegalStateException();
}
this.uploadList.add(new UploadData(buffer, addr, destOffset, size));
return this.uploadBuffer.addr + addr;
}
public void commit() {
//First flush all the allocations and enqueue them to be freed
{
for (long alloc : flushList) {
glFlushMappedNamedBufferRange(this.uploadBuffer.getId(), alloc, this.allocationArena.getSize(alloc));
this.thisFrameAllocations.add(alloc);
}
this.flushList.clear();
}
glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
//Execute all the copies
for (var entry : this.uploadList) {
glCopyNamedBufferSubData(this.uploadBuffer.getId(), entry.target.getId(), entry.uploadOffset, entry.targetOffset, entry.size);
}
this.uploadList.clear();
glMemoryBarrier(GL_BUFFER_UPDATE_BARRIER_BIT);
this.caddr = -1;
this.offset = 0;
}
public void tick() {
this.commit();
if (!this.thisFrameAllocations.isEmpty()) {
this.frames.add(new UploadFrame(new GlFence(), new LongArrayList(this.thisFrameAllocations)));
this.thisFrameAllocations.clear();
}
while (!this.frames.isEmpty()) {
//Since the ordering of frames is the ordering of the gl commands if we encounter an unsignaled fence
// all the other fences should also be unsignaled
if (!this.frames.peek().fence.signaled()) {
break;
}
//Release all the allocations from the frame
var frame = this.frames.pop();
frame.allocations.forEach(allocationArena::free);
frame.fence.free();
}
}
public void delete() {
TickableManager.remove(this);
this.uploadBuffer.delete();
this.frames.forEach(frame->frame.fence.free());
}
private record UploadFrame(GlFence fence, LongArrayList allocations) {}
private record UploadData(Buffer target, long uploadOffset, long targetOffset, long size) {}
}
|
acedium
|
src\main\java\me\cortex\nvidium\gl\buffers\Buffer.java
|
package me.cortex.nvidium.gl.buffers;
import me.cortex.nvidium.gl.IResource;
public interface Buffer extends IResource {
int getId();
}
|
acedium
|
src\main\java\me\cortex\nvidium\gl\buffers\DeviceOnlyMappedBuffer.java
|
package me.cortex.nvidium.gl.buffers;
import me.cortex.nvidium.gl.GlObject;
import static org.lwjgl.opengl.ARBDirectStateAccess.glCreateBuffers;
import static org.lwjgl.opengl.ARBDirectStateAccess.glNamedBufferStorage;
import static org.lwjgl.opengl.GL15C.GL_READ_WRITE;
import static org.lwjgl.opengl.GL15C.glDeleteBuffers;
import static org.lwjgl.opengl.NVShaderBufferLoad.*;
public class DeviceOnlyMappedBuffer extends GlObject implements IDeviceMappedBuffer {
public final long size;
public final long addr;
public DeviceOnlyMappedBuffer(long size) {//TODO: Make the access flag be specified so more optimization go brr
super(glCreateBuffers());
this.size = size;
glNamedBufferStorage(id, size, 0);
long[] holder = new long[1];
glGetNamedBufferParameterui64vNV(id, GL_BUFFER_GPU_ADDRESS_NV, holder);
glMakeNamedBufferResidentNV(id, GL_READ_WRITE);
addr = holder[0];
if (addr == 0) {
throw new IllegalStateException();
}
}
@Override
public void delete() {
super.free0();
glMakeNamedBufferNonResidentNV(id);
glDeleteBuffers(id);
}
@Override
public long getDeviceAddress() {
return addr;
}
@Override
public void free() {
this.delete();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\gl\buffers\IClientMappedBuffer.java
|
package me.cortex.nvidium.gl.buffers;
public interface IClientMappedBuffer extends Buffer {
long clientAddress();
}
|
acedium
|
src\main\java\me\cortex\nvidium\gl\buffers\IDeviceMappedBuffer.java
|
package me.cortex.nvidium.gl.buffers;
public interface IDeviceMappedBuffer extends Buffer {
long getDeviceAddress();
}
|
acedium
|
src\main\java\me\cortex\nvidium\gl\buffers\PersistentClientMappedBuffer.java
|
package me.cortex.nvidium.gl.buffers;
import me.cortex.nvidium.gl.GlObject;
import static org.lwjgl.opengl.ARBDirectStateAccess.*;
import static org.lwjgl.opengl.GL30C.*;
import static org.lwjgl.opengl.GL44.GL_CLIENT_STORAGE_BIT;
import static org.lwjgl.opengl.GL44.GL_MAP_PERSISTENT_BIT;
import static org.lwjgl.opengl.NVShaderBufferLoad.*;
public class PersistentClientMappedBuffer extends GlObject implements IClientMappedBuffer {
public final long addr;
public final long size;
public PersistentClientMappedBuffer(long size) {
super(glCreateBuffers());
this.size = size;
glNamedBufferStorage(id, size, GL_MAP_PERSISTENT_BIT| (GL_CLIENT_STORAGE_BIT|GL_MAP_WRITE_BIT));//TODO: Make the other flags dynamic
addr = nglMapNamedBufferRange(id, 0, size, GL_MAP_PERSISTENT_BIT|(GL_MAP_UNSYNCHRONIZED_BIT|GL_MAP_FLUSH_EXPLICIT_BIT|GL_MAP_WRITE_BIT));
}
@Override
public long clientAddress() {
return addr;
}
@Override
public void delete() {
super.free0();
glUnmapNamedBuffer(id);
glMakeNamedBufferNonResidentNV(id);
glDeleteBuffers(id);
}
@Override
public void free() {
this.delete();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\gl\buffers\PersistentSparseAddressableBuffer.java
|
package me.cortex.nvidium.gl.buffers;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import me.cortex.nvidium.Nvidium;
import me.cortex.nvidium.gl.GlObject;
import org.lwjgl.opengl.ARBSparseBuffer;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL21;
import static org.lwjgl.opengl.ARBDirectStateAccess.glCreateBuffers;
import static org.lwjgl.opengl.ARBDirectStateAccess.glNamedBufferStorage;
import static org.lwjgl.opengl.ARBSparseBuffer.GL_SPARSE_STORAGE_BIT_ARB;
import static org.lwjgl.opengl.GL15C.GL_READ_WRITE;
import static org.lwjgl.opengl.GL15C.glDeleteBuffers;
import static org.lwjgl.opengl.NVShaderBufferLoad.*;
public class PersistentSparseAddressableBuffer extends GlObject implements IDeviceMappedBuffer {
public static long alignUp(long number, long alignment) {
long delta = number % alignment;
return delta == 0?number: number + (alignment - delta);
}
public final long addr;
public final long size;
//The reason the page size is now 1mb is cause the nv driver doesnt defrag the sparse allocations easily
// meaning smaller pages result in more fragmented memory and not happy for the driver
// 1mb seems to work well
public static final long PAGE_SIZE = 1<<20;//16
public PersistentSparseAddressableBuffer(long size) {
super(glCreateBuffers());
if (!Nvidium.SUPPORTS_PERSISTENT_SPARSE_ADDRESSABLE_BUFFER) {
throw new IllegalStateException();
}
this.size = alignUp(size, PAGE_SIZE);
glNamedBufferStorage(id, size, GL_SPARSE_STORAGE_BIT_ARB);
long[] holder = new long[1];
glMakeNamedBufferResidentNV(id, GL_READ_WRITE);
glGetNamedBufferParameterui64vNV(id, GL_BUFFER_GPU_ADDRESS_NV, holder);
addr = holder[0];
if (addr == 0) {
throw new IllegalStateException();
}
}
private static void doCommit(int buffer, long offset, long size, boolean commit) {
GL21.glBindBuffer(GL15.GL_ARRAY_BUFFER, buffer);
ARBSparseBuffer.glBufferPageCommitmentARB(GL15.GL_ARRAY_BUFFER, offset, size, commit);
}
private final Int2IntOpenHashMap allocationCount = new Int2IntOpenHashMap();
private void allocatePages(int page, int pageCount) {
doCommit(id, PAGE_SIZE * page, PAGE_SIZE * pageCount, true);
for (int i = 0; i < pageCount; i++) {
allocationCount.addTo(i+page,1);
}
}
private void deallocatePages(int page, int pageCount) {
for (int i = 0; i < pageCount; i++) {
int newCount = allocationCount.get(i+page) - 1;
if (newCount != 0) {
allocationCount.put(i+page, newCount);
} else {
allocationCount.remove(i+page);
doCommit(id, PAGE_SIZE * (page+i), PAGE_SIZE,false);
}
}
}
public int getPagesCommitted() {
return allocationCount.size();
}
public void ensureAllocated(long addr, long size) {
int pstart = (int) (addr/PAGE_SIZE);
int pend = (int) ((addr+size+PAGE_SIZE-1)/PAGE_SIZE);
allocatePages(pstart, pend-pstart);
}
public void deallocate(long addr, long size) {
int pstart = (int) (addr/PAGE_SIZE);
int pend = (int) ((addr+size+PAGE_SIZE-1)/PAGE_SIZE);
deallocatePages(pstart, pend-pstart);
}
@Override
public long getDeviceAddress() {
return addr;
}
public void delete() {
super.free0();
glMakeNamedBufferNonResidentNV(id);
glDeleteBuffers(id);
}
@Override
public void free() {
this.delete();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\gl\images\DepthOnlyFrameBuffer.java
|
package me.cortex.nvidium.gl.images;
import com.mojang.blaze3d.platform.GlConst;
import com.mojang.blaze3d.platform.GlStateManager;
import static org.lwjgl.opengl.ARBDirectStateAccess.*;
import static org.lwjgl.opengl.GL11C.GL_TEXTURE_2D;
import static org.lwjgl.opengl.GL11C.glDeleteTextures;
import static org.lwjgl.opengl.GL30C.*;
public class DepthOnlyFrameBuffer {
public final int width;
public final int height;
private final int fid;
private final int did;
public DepthOnlyFrameBuffer(int width, int height) {
this.width = width;
this.height = height;
fid = glCreateFramebuffers();
did = glCreateTextures(GL_TEXTURE_2D);
glTextureStorage2D(did, 1, GL_DEPTH_COMPONENT32F, width, height);
glNamedFramebufferTexture(fid, GL_DEPTH_ATTACHMENT, did, 0);
if (glCheckNamedFramebufferStatus(fid, GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
throw new IllegalStateException("ERROR: " + glCheckFramebufferStatus(GL_FRAMEBUFFER));
}
}
public int getDepthBuffer() {
return did;
}
public void bind(boolean setViewport) {
GlStateManager._glBindFramebuffer(GlConst.GL_FRAMEBUFFER, fid);
if (setViewport) {
GlStateManager._viewport(0, 0, width, height);
}
}
public void delete() {
glDeleteFramebuffers(fid);
glDeleteTextures(did);
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\gl\shader\IShaderProcessor.java
|
package me.cortex.nvidium.gl.shader;
public interface IShaderProcessor {
String process(ShaderType type, String source);
}
|
acedium
|
src\main\java\me\cortex\nvidium\gl\shader\Shader.java
|
package me.cortex.nvidium.gl.shader;
import me.cortex.nvidium.gl.GlObject;
import org.lwjgl.opengl.GL20C;
import java.util.HashMap;
import java.util.Map;
import static org.lwjgl.opengl.GL20.glDeleteProgram;
import static org.lwjgl.opengl.GL20.glUseProgram;
public class Shader extends GlObject {
private Shader(int program) {
super(program);
}
public static Builder make(IShaderProcessor processor) {
return new Builder(processor);
}
public static Builder make() {
return new Builder((aa,source)->source);
}
public void bind() {
glUseProgram(id);
}
public void delete() {
super.free0();
glDeleteProgram(id);
}
@Override
public void free() {
this.delete();
}
public static class Builder {
private final Map<ShaderType, String> sources = new HashMap<>();
private final IShaderProcessor processor;
private Builder(IShaderProcessor processor) {
this.processor = processor;
}
public Builder addSource(ShaderType type, String source) {
sources.put(type, processor.process(type, source));
return this;
}
public Shader compile() {
int program = GL20C.glCreateProgram();
int[] shaders = sources.entrySet().stream().mapToInt(a->createShader(a.getKey(), a.getValue())).toArray();
for (int i : shaders) {
GL20C.glAttachShader(program, i);
}
GL20C.glLinkProgram(program);
for (int i : shaders) {
GL20C.glDetachShader(program, i);
GL20C.glDeleteShader(i);
}
printProgramLinkLog(program);
verifyProgramLinked(program);
return new Shader(program);
}
private static void printProgramLinkLog(int program) {
String log = GL20C.glGetProgramInfoLog(program);
if (!log.isEmpty()) {
System.err.println(log);
}
}
private static void verifyProgramLinked(int program) {
int result = GL20C.glGetProgrami(program, GL20C.GL_LINK_STATUS);
if (result != GL20C.GL_TRUE) {
throw new RuntimeException("Shader program linking failed, see log for details");
}
}
private static int createShader(ShaderType type, String src) {
int shader = GL20C.glCreateShader(type.gl);
GL20C.glShaderSource(shader, src);
GL20C.glCompileShader(shader);
String log = GL20C.glGetShaderInfoLog(shader);
if (!log.isEmpty()) {
System.err.println(log);
}
int result = GL20C.glGetShaderi(shader, GL20C.GL_COMPILE_STATUS);
if (result != GL20C.GL_TRUE) {
GL20C.glDeleteShader(shader);
throw new RuntimeException("Shader compilation failed, see log for details");
}
return shader;
}
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\gl\shader\ShaderType.java
|
package me.cortex.nvidium.gl.shader;
import static org.lwjgl.opengl.GL20.GL_FRAGMENT_SHADER;
import static org.lwjgl.opengl.GL20.GL_VERTEX_SHADER;
import static org.lwjgl.opengl.GL43C.GL_COMPUTE_SHADER;
import static org.lwjgl.opengl.NVMeshShader.GL_MESH_SHADER_NV;
import static org.lwjgl.opengl.NVMeshShader.GL_TASK_SHADER_NV;
public enum ShaderType {
VERTEX(GL_VERTEX_SHADER),
FRAGMENT(GL_FRAGMENT_SHADER),
COMPUTE(GL_COMPUTE_SHADER),
MESH(GL_MESH_SHADER_NV),
TASK(GL_TASK_SHADER_NV);
public final int gl;
ShaderType(int glEnum) {
gl = glEnum;
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\minecraft\LightMapAccessor.java
|
package me.cortex.nvidium.mixin.minecraft;
import net.minecraft.client.render.LightmapTextureManager;
import net.minecraft.client.texture.NativeImageBackedTexture;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(LightmapTextureManager.class)
public interface LightMapAccessor {
@Accessor()
NativeImageBackedTexture getTexture();
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\minecraft\MixinBackgroundRenderer.java
|
package me.cortex.nvidium.mixin.minecraft;
import me.cortex.nvidium.Nvidium;
import net.minecraft.client.render.BackgroundRenderer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.Constant;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
@Mixin(BackgroundRenderer.class)
public class MixinBackgroundRenderer {
@ModifyConstant(method = "applyFog", constant = @Constant(floatValue = 192.0F))
private static float changeFog(float fog) {
if (Nvidium.IS_ENABLED) {
return 9999999f;
} else {
return fog;
}
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\minecraft\MixinGameRenderer.java
|
package me.cortex.nvidium.mixin.minecraft;
import me.cortex.nvidium.Nvidium;
import net.minecraft.client.render.GameRenderer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(GameRenderer.class)
public class MixinGameRenderer {
@Inject(method = "getFarPlaneDistance", at = @At("HEAD"), cancellable = true)
public void method_32796(CallbackInfoReturnable<Float> cir) {
if (Nvidium.IS_ENABLED) {
cir.setReturnValue(16 * 512f);
cir.cancel();
}
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\minecraft\MixinMinecraftClient.java
|
package me.cortex.nvidium.mixin.minecraft;
import me.cortex.nvidium.util.TickableManager;
import net.minecraft.client.MinecraftClient;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(MinecraftClient.class)
public class MixinMinecraftClient {
@Inject(method = "render", at = @At("TAIL"))
private void tickUploadThread(boolean tick, CallbackInfo ci) {
//TickableManager.TickAll();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\minecraft\MixinWindow.java
|
package me.cortex.nvidium.mixin.minecraft;
import me.cortex.nvidium.Nvidium;
import net.minecraft.client.WindowEventHandler;
import net.minecraft.client.WindowSettings;
import net.minecraft.client.util.MonitorTracker;
import net.minecraft.client.util.Window;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Window.class)
public class MixinWindow {
@Inject(method = "<init>", at = @At("TAIL"))
private void headInit(WindowEventHandler eventHandler, MonitorTracker monitorTracker, WindowSettings settings, String videoMode, String title, CallbackInfo ci) {
Nvidium.preWindowInit();
}
@Inject(method = "<init>", at = @At("TAIL"))
private void init(WindowEventHandler eventHandler, MonitorTracker monitorTracker, WindowSettings settings, String videoMode, String title, CallbackInfo ci) {
Nvidium.checkSystemIsCapable();
Nvidium.setupGLDebugCallback();
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\minecraft\MixinWorldRenderer.java
|
package me.cortex.nvidium.mixin.minecraft;
import me.cortex.nvidium.Nvidium;
import net.minecraft.client.render.GameRenderer;
import net.minecraft.client.render.WorldRenderer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(WorldRenderer.class)
public class MixinWorldRenderer {
@Redirect(method = "render", at = @At(value = "INVOKE", target = "Ljava/lang/Math;max(FF)F"))
private float redirectMax(float a, float b) {
if (Nvidium.IS_ENABLED) {
return a;
}
return Math.max(a, b);
}
@Redirect(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/GameRenderer;getViewDistance()F"))
private float changeRD(GameRenderer instance) {
float viewDistance = instance.getViewDistance();
if (Nvidium.IS_ENABLED) {
var dist = Nvidium.config.region_keep_distance * 16;
return dist == 32 * 16 ? viewDistance : (dist == 256 * 16 ? 9999999 : dist);
}
return viewDistance;
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\sodium\MixinChunkBuilder.java
|
package me.cortex.nvidium.mixin.sodium;
import me.cortex.nvidium.Nvidium;
import me.jellysquid.mods.sodium.client.render.chunk.compile.executor.ChunkBuilder;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import java.util.List;
@Mixin(value = ChunkBuilder.class, remap = false)
public class MixinChunkBuilder {
@Redirect(method = "getSchedulingBudget", at = @At(value = "INVOKE", target = "Ljava/util/List;size()I"))
private int moreSchedulingBudget(List<Thread> threads) {
int budget = threads.size();
if (Nvidium.IS_ENABLED && Nvidium.config.async_bfs) {
budget *= 3;
}
return budget;
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\sodium\MixinChunkBuilderMeshingTask.java
|
package me.cortex.nvidium.mixin.sodium;
import me.cortex.nvidium.Nvidium;
import me.cortex.nvidium.sodiumCompat.IRepackagedResult;
import me.cortex.nvidium.sodiumCompat.SodiumResultCompatibility;
import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildContext;
import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildOutput;
import me.jellysquid.mods.sodium.client.render.chunk.compile.tasks.ChunkBuilderMeshingTask;
import me.jellysquid.mods.sodium.client.util.task.CancellationToken;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(value = ChunkBuilderMeshingTask.class, remap = false)
public class MixinChunkBuilderMeshingTask {
@Inject(method = "execute(Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildContext;Lme/jellysquid/mods/sodium/client/util/task/CancellationToken;)Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildOutput;", at = @At("TAIL"))
private void repackageResults(ChunkBuildContext buildContext, CancellationToken cancellationToken, CallbackInfoReturnable<ChunkBuildOutput> cir) {
if (Nvidium.IS_ENABLED) {
var result = cir.getReturnValue();
if (result != null) {
((IRepackagedResult) result).set(SodiumResultCompatibility.repackage(result));
}
//TODO: here, delete the old sodium data to save on memory
}
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\sodium\MixinChunkBuildOutput.java
|
package me.cortex.nvidium.mixin.sodium;
import me.cortex.nvidium.sodiumCompat.IRepackagedResult;
import me.cortex.nvidium.sodiumCompat.RepackagedSectionOutput;
import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildOutput;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(value = ChunkBuildOutput.class, remap = false)
public class MixinChunkBuildOutput implements IRepackagedResult {
@Unique private RepackagedSectionOutput repackagedSectionOutput;
public RepackagedSectionOutput getOutput() {
return repackagedSectionOutput;
}
public void set(RepackagedSectionOutput output) {
repackagedSectionOutput = output;
}
@Inject(method = "delete", at = @At("HEAD"))
private void cleanup(CallbackInfo ci) {
if (repackagedSectionOutput != null) {
repackagedSectionOutput.delete();
}
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\sodium\MixinChunkJobQueue.java
|
package me.cortex.nvidium.mixin.sodium;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(targets = {"me.jellysquid.mods.sodium.client.render.chunk.compile.executor.ChunkJobQueue"},remap = false)
public class MixinChunkJobQueue {
@Redirect(method = "shutdown", at = @At(value = "INVOKE", target = "Ljava/lang/Runtime;availableProcessors()I"))
private int returnAlot(Runtime instance) {
return Integer.MAX_VALUE>>1;
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\sodium\MixinOptionFlag.java
|
package me.cortex.nvidium.mixin.sodium;
import me.cortex.nvidium.sodiumCompat.NvidiumOptionFlags;
import me.jellysquid.mods.sodium.client.gui.options.OptionFlag;
import org.apache.commons.lang3.ArrayUtils;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Mutable;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.gen.Invoker;
@Mixin(value = OptionFlag.class, remap = false)
public class MixinOptionFlag {
@Shadow
@Final
@Mutable
private static OptionFlag[] $VALUES = ArrayUtils.addAll(MixinOptionFlag.$VALUES, NvidiumOptionFlags.REQUIRES_SHADER_RELOAD);
public MixinOptionFlag() {
}
@Invoker("<init>")
public static OptionFlag optionFlagCreator(String internalName, int internalId) {
throw new AssertionError();
}
static {
NvidiumOptionFlags.REQUIRES_SHADER_RELOAD = optionFlagCreator("REQUIRES_SHADER_RELOAD", $VALUES.length);
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\sodium\MixinRenderRegionManager.java
|
package me.cortex.nvidium.mixin.sodium;
import me.cortex.nvidium.Nvidium;
import me.cortex.nvidium.NvidiumWorldRenderer;
import me.cortex.nvidium.sodiumCompat.INvidiumWorldRendererSetter;
import me.jellysquid.mods.sodium.client.gl.device.CommandList;
import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildOutput;
import me.jellysquid.mods.sodium.client.render.chunk.region.RenderRegion;
import me.jellysquid.mods.sodium.client.render.chunk.region.RenderRegionManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import java.util.Collection;
@Mixin(value = RenderRegionManager.class, remap = false)
public abstract class MixinRenderRegionManager implements INvidiumWorldRendererSetter {
@Shadow protected abstract void uploadMeshes(CommandList commandList, RenderRegion region, Collection<ChunkBuildOutput> results);
@Unique private NvidiumWorldRenderer renderer;
@Redirect(method = "uploadMeshes(Lme/jellysquid/mods/sodium/client/gl/device/CommandList;Ljava/util/Collection;)V", at = @At(value = "INVOKE", target = "Lme/jellysquid/mods/sodium/client/render/chunk/region/RenderRegionManager;uploadMeshes(Lme/jellysquid/mods/sodium/client/gl/device/CommandList;Lme/jellysquid/mods/sodium/client/render/chunk/region/RenderRegion;Ljava/util/Collection;)V"))
private void redirectUpload(RenderRegionManager instance, CommandList cmdList, RenderRegion pass, Collection<ChunkBuildOutput> uploadQueue) {
if (Nvidium.IS_ENABLED) {
uploadQueue.forEach(renderer::uploadBuildResult);
} else {
uploadMeshes(cmdList, pass, uploadQueue);
}
}
@Override
public void setWorldRenderer(NvidiumWorldRenderer renderer) {
this.renderer = renderer;
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\sodium\MixinRenderSection.java
|
package me.cortex.nvidium.mixin.sodium;
import it.unimi.dsi.fastutil.longs.Long2ReferenceMap;
import me.cortex.nvidium.Nvidium;
import me.cortex.nvidium.NvidiumWorldRenderer;
import me.cortex.nvidium.managers.AsyncOcclusionTracker;
import me.cortex.nvidium.sodiumCompat.INvidiumWorldRendererGetter;
import me.cortex.nvidium.sodiumCompat.INvidiumWorldRendererSetter;
import me.cortex.nvidium.sodiumCompat.IRenderSectionExtension;
import me.cortex.nvidium.sodiumCompat.IrisCheck;
import me.jellysquid.mods.sodium.client.gl.device.CommandList;
import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderMatrices;
import me.jellysquid.mods.sodium.client.render.chunk.ChunkUpdateType;
import me.jellysquid.mods.sodium.client.render.chunk.RenderSection;
import me.jellysquid.mods.sodium.client.render.chunk.RenderSectionManager;
import me.jellysquid.mods.sodium.client.render.chunk.region.RenderRegionManager;
import me.jellysquid.mods.sodium.client.render.chunk.terrain.DefaultTerrainRenderPasses;
import me.jellysquid.mods.sodium.client.render.chunk.terrain.TerrainRenderPass;
import me.jellysquid.mods.sodium.client.render.viewport.Viewport;
import net.minecraft.client.render.Camera;
import net.minecraft.client.world.ClientWorld;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
@Mixin(value = RenderSection.class, remap = false)
public class MixinRenderSection implements IRenderSectionExtension {
@Unique private volatile boolean isEnqueued;
@Unique private volatile boolean isSeen;
@Override
public boolean isSubmittedRebuild() {
return isEnqueued;
}
@Override
public void isSubmittedRebuild(boolean state) {
isEnqueued = state;
}
@Override
public boolean isSeen() {
return isSeen;
}
@Override
public void isSeen(boolean state) {
isSeen = state;
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\sodium\MixinRenderSectionManager.java
|
package me.cortex.nvidium.mixin.sodium;
import it.unimi.dsi.fastutil.longs.Long2ReferenceMap;
import me.cortex.nvidium.Nvidium;
import me.cortex.nvidium.NvidiumWorldRenderer;
import me.cortex.nvidium.managers.AsyncOcclusionTracker;
import me.cortex.nvidium.sodiumCompat.*;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import me.jellysquid.mods.sodium.client.gl.device.CommandList;
import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderMatrices;
import me.jellysquid.mods.sodium.client.render.chunk.ChunkUpdateType;
import me.jellysquid.mods.sodium.client.render.chunk.RenderSection;
import me.jellysquid.mods.sodium.client.render.chunk.RenderSectionManager;
import me.jellysquid.mods.sodium.client.render.chunk.region.RenderRegionManager;
import me.jellysquid.mods.sodium.client.render.chunk.terrain.DefaultTerrainRenderPasses;
import me.jellysquid.mods.sodium.client.render.chunk.terrain.TerrainRenderPass;
import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexType;
import me.jellysquid.mods.sodium.client.render.texture.SpriteUtil;
import me.jellysquid.mods.sodium.client.render.viewport.Viewport;
import net.minecraft.client.render.Camera;
import net.minecraft.client.world.ClientWorld;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.*;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
@Mixin(value = RenderSectionManager.class, remap = false)
public class MixinRenderSectionManager implements INvidiumWorldRendererGetter {
@Shadow @Final private RenderRegionManager regions;
@Shadow @Final private Long2ReferenceMap<RenderSection> sectionByPosition;
@Shadow private @NotNull Map<ChunkUpdateType, ArrayDeque<RenderSection>> rebuildLists;
@Shadow @Final private int renderDistance;
@Unique private NvidiumWorldRenderer renderer;
@Unique private Viewport viewport;
@Unique
private static void updateNvidiumIsEnabled() {
Nvidium.IS_ENABLED = (!Nvidium.FORCE_DISABLE) && Nvidium.IS_COMPATIBLE && IrisCheck.checkIrisShouldDisable();
}
@Inject(method = "<init>", at = @At("TAIL"))
private void init(ClientWorld world, int renderDistance, CommandList commandList, CallbackInfo ci) {
updateNvidiumIsEnabled();
if (Nvidium.IS_ENABLED) {
if (renderer != null)
throw new IllegalStateException("Cannot have multiple world renderers");
renderer = new NvidiumWorldRenderer(Nvidium.config.async_bfs?new AsyncOcclusionTracker(renderDistance, sectionByPosition, world, rebuildLists):null);
((INvidiumWorldRendererSetter)regions).setWorldRenderer(renderer);
}
}
@ModifyArg(method = "<init>", at = @At(value = "INVOKE", target = "Lme/jellysquid/mods/sodium/client/render/chunk/compile/executor/ChunkBuilder;<init>(Lnet/minecraft/client/world/ClientWorld;Lme/jellysquid/mods/sodium/client/render/chunk/vertex/format/ChunkVertexType;)V", remap = true), index = 1)
private ChunkVertexType modifyVertexType(ChunkVertexType vertexType) {
updateNvidiumIsEnabled();
if (Nvidium.IS_ENABLED) {
return NvidiumCompactChunkVertex.INSTANCE;
}
return vertexType;
}
@Inject(method = "destroy", at = @At("TAIL"))
private void destroy(CallbackInfo ci) {
if (Nvidium.IS_ENABLED) {
if (renderer == null)
throw new IllegalStateException("Pipeline already destroyed");
((INvidiumWorldRendererSetter)regions).setWorldRenderer(null);
renderer.delete();
renderer = null;
}
}
@Redirect(method = "onSectionRemoved", at = @At(value = "INVOKE", target = "Lme/jellysquid/mods/sodium/client/render/chunk/RenderSection;delete()V"))
private void deleteSection(RenderSection section) {
if (Nvidium.IS_ENABLED) {
if (Nvidium.config.region_keep_distance == 32) {
renderer.deleteSection(section);
}
}
section.delete();
}
@Inject(method = "update", at = @At("HEAD"))
private void trackViewport(Camera camera, Viewport viewport, int frame, boolean spectator, CallbackInfo ci) {
this.viewport = viewport;
}
@Inject(method = "renderLayer", at = @At("HEAD"), cancellable = true)
public void renderLayer(ChunkRenderMatrices matrices, TerrainRenderPass pass, double x, double y, double z, CallbackInfo ci) {
if (Nvidium.IS_ENABLED) {
ci.cancel();
pass.startDrawing();
if (pass == DefaultTerrainRenderPasses.SOLID) {
renderer.renderFrame(viewport, matrices, x, y, z);
} else if (pass == DefaultTerrainRenderPasses.TRANSLUCENT) {
renderer.renderTranslucent();
}
pass.endDrawing();
}
}
@Inject(method = "getDebugStrings", at = @At("HEAD"), cancellable = true)
private void redirectDebug(CallbackInfoReturnable<Collection<String>> cir) {
if (Nvidium.IS_ENABLED) {
var debugStrings = new ArrayList<String>();
renderer.addDebugInfo(debugStrings);
cir.setReturnValue(debugStrings);
cir.cancel();
}
}
@Override
public NvidiumWorldRenderer getRenderer() {
return renderer;
}
@Inject(method = "createTerrainRenderList", at = @At("HEAD"), cancellable = true)
private void redirectTerrainRenderList(Camera camera, Viewport viewport, int frame, boolean spectator, CallbackInfo ci) {
if (Nvidium.IS_ENABLED && Nvidium.config.async_bfs) {
ci.cancel();
}
}
@Redirect(method = "submitRebuildTasks", at = @At(value = "INVOKE", target = "Lme/jellysquid/mods/sodium/client/render/chunk/RenderSection;setPendingUpdate(Lme/jellysquid/mods/sodium/client/render/chunk/ChunkUpdateType;)V"))
private void injectEnqueueFalse(RenderSection instance, ChunkUpdateType type) {
instance.setPendingUpdate(type);
if (Nvidium.IS_ENABLED && Nvidium.config.async_bfs) {
//We need to reset the fact that its been submitted to the rebuild queue from the build queue
((IRenderSectionExtension) instance).isSubmittedRebuild(false);
}
}
@Unique
private boolean isSectionVisibleBfs(RenderSection section) {
//The reason why this is done is that since the bfs search is async it could be updating the frame counter with the next frame
// while some sections that arnt updated/ticked yet still have the old frame id
int delta = Math.abs(section.getLastVisibleFrame() - renderer.getAsyncFrameId());
return delta <= 1;
}
@Inject(method = "isSectionVisible", at = @At(value = "INVOKE", target = "Lme/jellysquid/mods/sodium/client/render/chunk/RenderSection;getLastVisibleFrame()I", shift = At.Shift.BEFORE), cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD)
private void redirectIsSectionVisible(int x, int y, int z, CallbackInfoReturnable<Boolean> cir, RenderSection render) {
if (Nvidium.IS_ENABLED && Nvidium.config.async_bfs) {
cir.setReturnValue(isSectionVisibleBfs(render));
}
}
@Inject(method = "tickVisibleRenders", at = @At("HEAD"), cancellable = true)
private void redirectAnimatedSpriteUpdates(CallbackInfo ci) {
if (Nvidium.IS_ENABLED && Nvidium.config.async_bfs && SodiumClientMod.options().performance.animateOnlyVisibleTextures) {
ci.cancel();
var sprites = renderer.getAnimatedSpriteSet();
if (sprites == null) {
return;
}
for (var sprite : sprites) {
SpriteUtil.markSpriteActive(sprite);
}
}
}
@Inject(method = "scheduleRebuild", at = @At(value = "INVOKE", target = "Lme/jellysquid/mods/sodium/client/render/chunk/RenderSection;setPendingUpdate(Lme/jellysquid/mods/sodium/client/render/chunk/ChunkUpdateType;)V", shift = At.Shift.AFTER), locals = LocalCapture.CAPTURE_FAILHARD)
private void instantReschedule(int x, int y, int z, boolean important, CallbackInfo ci, RenderSection section, ChunkUpdateType pendingUpdate) {
if (Nvidium.IS_ENABLED && Nvidium.config.async_bfs) {
var queue = rebuildLists.get(pendingUpdate);
//TODO:FIXME: this might result in the section being enqueued multiple times, if this gets executed, and the async search sees it at the exactly wrong moment
if (isSectionVisibleBfs(section) && queue.size() < pendingUpdate.getMaximumQueueSize()) {
((IRenderSectionExtension)section).isSubmittedRebuild(true);
rebuildLists.get(pendingUpdate).add(section);
}
}
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\sodium\MixinSodiumOptionsGUI.java
|
package me.cortex.nvidium.mixin.sodium;
import me.cortex.nvidium.NvidiumWorldRenderer;
import me.cortex.nvidium.config.ConfigGuiBuilder;
import me.cortex.nvidium.sodiumCompat.INvidiumWorldRendererGetter;
import me.jellysquid.mods.sodium.client.gui.SodiumOptionsGUI;
import me.jellysquid.mods.sodium.client.gui.options.*;
import me.jellysquid.mods.sodium.client.gui.options.storage.OptionStorage;
import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import java.util.*;
@Mixin(value = SodiumOptionsGUI.class, remap = false)
public class MixinSodiumOptionsGUI {
@Shadow @Final private List<OptionPage> pages;
@Inject(method = "<init>", at = @At("RETURN"))
private void addNvidiumOptions(Screen prevScreen, CallbackInfo ci) {
ConfigGuiBuilder.addNvidiumGui(pages);
}
@Inject(method = "applyChanges", at = @At("RETURN"), locals = LocalCapture.CAPTURE_FAILSOFT)
private void applyShaderReload(CallbackInfo ci, HashSet<OptionStorage<?>> dirtyStorages, EnumSet<OptionFlag> flags, MinecraftClient client) {
if (client.world != null) {
SodiumWorldRenderer swr = SodiumWorldRenderer.instanceNullable();
if (swr != null) {
NvidiumWorldRenderer pipeline = ((INvidiumWorldRendererGetter)((SodiumWorldRendererAccessor)swr).getRenderSectionManager()).getRenderer();
if (pipeline != null)
pipeline.reloadShaders();
}
}
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\sodium\MixinSodiumWorldRenderer.java
|
package me.cortex.nvidium.mixin.sodium;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import me.cortex.nvidium.Nvidium;
import me.cortex.nvidium.NvidiumWorldRenderer;
import me.cortex.nvidium.sodiumCompat.INvidiumWorldRendererGetter;
import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer;
import me.jellysquid.mods.sodium.client.render.chunk.RenderSectionManager;
import me.jellysquid.mods.sodium.client.render.viewport.Viewport;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.client.render.BlockBreakingInfo;
import net.minecraft.client.render.BufferBuilderStorage;
import net.minecraft.client.render.Camera;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.block.entity.BlockEntityRenderDispatcher;
import net.minecraft.client.util.math.MatrixStack;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.SortedSet;
@Mixin(value = SodiumWorldRenderer.class, remap = false)
public abstract class MixinSodiumWorldRenderer implements INvidiumWorldRendererGetter {
@Shadow private RenderSectionManager renderSectionManager;
@Shadow
protected static void renderBlockEntity(MatrixStack matrices, BufferBuilderStorage bufferBuilders, Long2ObjectMap<SortedSet<BlockBreakingInfo>> blockBreakingProgressions, float tickDelta, VertexConsumerProvider.Immediate immediate, double x, double y, double z, BlockEntityRenderDispatcher dispatcher, BlockEntity entity) {
}
@Inject(method = "setupTerrain", at = @At(value = "INVOKE", target = "Lme/jellysquid/mods/sodium/client/render/chunk/RenderSectionManager;needsUpdate()Z", shift = At.Shift.BEFORE))
private void injectTerrainSetup(Camera camera, Viewport viewport, int frame, boolean spectator, boolean updateChunksImmediately, CallbackInfo ci) {
if (Nvidium.IS_ENABLED && Nvidium.config.async_bfs) {
((INvidiumWorldRendererGetter)renderSectionManager).getRenderer().update(camera, viewport, frame, spectator);
}
}
@Inject(method = "renderBlockEntities(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/BufferBuilderStorage;Lit/unimi/dsi/fastutil/longs/Long2ObjectMap;FLnet/minecraft/client/render/VertexConsumerProvider$Immediate;DDDLnet/minecraft/client/render/block/entity/BlockEntityRenderDispatcher;)V", at = @At("HEAD"), cancellable = true, remap = true)
private void overrideEntityRenderer(MatrixStack matrices, BufferBuilderStorage bufferBuilders, Long2ObjectMap<SortedSet<BlockBreakingInfo>> blockBreakingProgressions, float tickDelta, VertexConsumerProvider.Immediate immediate, double x, double y, double z, BlockEntityRenderDispatcher blockEntityRenderer, CallbackInfo ci) {
if (Nvidium.IS_ENABLED && Nvidium.config.async_bfs) {
ci.cancel();
var sectionsWithEntities = ((INvidiumWorldRendererGetter)renderSectionManager).getRenderer().getSectionsWithEntities();
for (var section : sectionsWithEntities) {
if (section.isDisposed() || section.getCulledBlockEntities() == null)
continue;
for (var entity : section.getCulledBlockEntities()) {
renderBlockEntity(matrices, bufferBuilders, blockBreakingProgressions, tickDelta, immediate, x, y, z, blockEntityRenderer, entity);
}
}
}
}
@Override
public NvidiumWorldRenderer getRenderer() {
if (Nvidium.IS_ENABLED) {
return ((INvidiumWorldRendererGetter)renderSectionManager).getRenderer();
} else {
return null;
}
}
}
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 18