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;
}
}
}
|
acedium
|
src\main\java\me\cortex\nvidium\mixin\sodium\SodiumWorldRendererAccessor.java
|
package me.cortex.nvidium.mixin.sodium;
import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer;
import me.jellysquid.mods.sodium.client.render.chunk.RenderSectionManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(value = SodiumWorldRenderer.class, remap = false)
public interface SodiumWorldRendererAccessor {
@Accessor
RenderSectionManager getRenderSectionManager();
}
|
acedium
|
src\main\resources\assets\nvidium\lang\en_us.json
|
{
"nvidium.options.pages.nvidium" : "Nvidium",
"nvidium.options.region_keep_distance.name" : "Region Keep Distance",
"nvidium.options.region_keep_distance.tooltip" : "Distance to keep loaded regions",
"nvidium.options.automatic_memory_limit.name" : "Automatic memory limit",
"nvidium.options.automatic_memory_limit.tooltip" : "Automatically determines the memory limit to set given the amount of available vram on your system (Close and reopen settings to edit the max memory)",
"nvidium.options.max_gpu_memory.name" : "Max gpu memory",
"nvidium.options.max_gpu_memory.tooltip" : "Max gpu memory allowed, will start to cull chunks if this limit is hit",
"nvidium.options.enable_temporal_coherence.name" : "Enables temporal coherence",
"nvidium.options.enable_temporal_coherence.tooltip" : "Removes artifacting when turning around",
"nvidium.options.mb" : "%s Mbs",
"nvidium.options.translucency_sorting.name" : "Translucency Sorting",
"nvidium.options.translucency_sorting.tooltip" : "Translucency sorting level, each level has different performance impact and visual quality. \nNone:No translucency sorting, no impact, can look quite bad\nSections: Section level translucency sorting, brings translucency to the same level as sodium, minimal impact\nQuads: Incremental sorting, sorts geometry correctly over multiple frames, can cause visual weirdness while sorting",
"nvidium.options.translucency_sorting.none" : "None",
"nvidium.options.translucency_sorting.sections" : "Sections",
"nvidium.options.translucency_sorting.quads" : "Quads",
"nvidium.options.statistics_level.name" : "Statistics Level",
"nvidium.options.statistics_level.tooltip" : "Statistics logging level, tracks the visibility count of cull layers",
"nvidium.options.statistics_level.none" : "None",
"nvidium.options.statistics_level.frustum" : "Frustum",
"nvidium.options.statistics_level.regions" : "Regions",
"nvidium.options.statistics_level.sections" : "Sections",
"nvidium.options.statistics_level.quads" : "Quads",
"nvidium.options.async_bfs.name" : "Enable async bfs",
"nvidium.options.async_bfs.tooltip" : "Enables asynchronous bfs chunk section loading, greatly reduces the frame time when moving, more noticeable with higher render distances"
}
|
acedium
|
src\main\resources\assets\nvidium\shaders\occlusion\scene.glsl
|
#define Vertex uvec4
// this is cause in the section rasterizer you get less cache misses thus higher throughput
struct Section {
ivec4 header;
//Header.x -> 0-3=offsetx 4-7=sizex 8-31=chunk x
//Header.y -> 0-3=offsetz 4-7=sizez 8-31=chunk z
//Header.z -> 0-3=offsety 4-7=sizey 8-15=chunk y
//Header.w -> quad offset
ivec4 renderRanges;
};
struct Region {
uint64_t a;
uint64_t b;
};
ivec3 unpackRegionSize(Region region) {
return ivec3((region.a>>59)&7, region.a>>62, (region.a>>56)&7);
}
uint unpackRegionTransformId(Region region) {
return uint((region.b>>(64-24-10))&((1<<10)-1));
}
ivec3 unpackRegionPosition(Region region) {
//TODO: optimize
int x = int(int64_t(region.a<<(64-24-24))>>(64-24));
int y = (int(region.a)<<8)>>8;
int z = int(int64_t(region.b)>>(64-24));
return ivec3(x,y,z);
}
int unpackRegionCount(Region region) {
return int((region.a>>48)&255);
}
bool sectionEmpty(ivec4 header) {
header.y &= ~0x1FF<<17;
return header == ivec4(0);
}
layout(std140, binding=0) uniform SceneData {
//Need to basicly go in order of alignment
//align(16)
mat4 MVP;
ivec4 chunkPosition;
vec4 subchunkOffset;
vec4 fogColour;
//vec4 subChunkPosition;//The subChunkTranslation is already done inside the MVP
//align(8)
readonly restrict uint16_t *regionIndicies;//Pointer to block of memory at the end of the SceneData struct, also mapped to be a uniform
readonly restrict Region *regionData;
restrict Section *sectionData;
//NOTE: for the following, can make it so that region visibility actually uses section visibility array
restrict uint8_t *regionVisibility;
restrict uint8_t *sectionVisibility;
//Terrain command buffer, the first 4 bytes are actually the count
writeonly restrict uvec2 *terrainCommandBuffer;
writeonly restrict uvec2 *translucencyCommandBuffer;
readonly restrict uint16_t *sortingRegionList;
//TODO:FIXME: only apply non readonly to translucency mesh
restrict Vertex *terrainData;//readonly
//TODO: possibly make this a uniform instead of a buffer, but it might get quite large is the issue
readonly restrict mat4 *transformationArray;
//readonly restrict u64vec4 *terrainData;
//uvec4 *terrainData;
uint32_t *statistics_buffer;
float fogStart;
float fogEnd;
bool isCylindricalFog;
//align(2)
uint16_t regionCount;//Number of regions in regionIndicies
//align(1)
uint8_t frameId;
};
mat4 getRegionTransformation(Region region) {
return transformationArray[unpackRegionTransformId(region)];
}
|
acedium
|
src\main\resources\assets\nvidium\shaders\sorting\sorting_network.glsl
|
#ifndef SORTING_INDEX_TYPE
#define SORTING_INDEX_TYPE uint8_t
#endif
shared float threadBufferFloat[SORTING_NETWORK_SIZE];
shared SORTING_INDEX_TYPE threadBufferIndex[SORTING_NETWORK_SIZE];
void localSortA(const uint scaleBits) {
uint base = (gl_LocalInvocationID.x>>scaleBits)*(1<<(scaleBits+1));
uint offsetA = (gl_LocalInvocationID.x&((1<<scaleBits)-1));
uint offsetB = (1<<(scaleBits+1))-1-offsetA;
float a = threadBufferFloat[base + offsetA];
float b = threadBufferFloat[base + offsetB];
if (a < b) {
threadBufferFloat[base + offsetA] = b;
threadBufferFloat[base + offsetB] = a;
SORTING_INDEX_TYPE tmp = threadBufferIndex[base + offsetA];
threadBufferIndex[base + offsetA] = threadBufferIndex[base + offsetB];
threadBufferIndex[base + offsetB] = tmp;
}
barrier();
memoryBarrierShared();
}
void localSortB(const uint scaleBits) {
uint base = (gl_LocalInvocationID.x>>scaleBits)*(1<<(scaleBits+1));
base += (gl_LocalInvocationID.x&((1<<scaleBits)-1));
uint offset = 1<<scaleBits;
float a = threadBufferFloat[base];
float b = threadBufferFloat[base + offset];
if (a < b) {
threadBufferFloat[base] = b;
threadBufferFloat[base + offset] = a;
SORTING_INDEX_TYPE tmp = threadBufferIndex[base];
threadBufferIndex[base] = threadBufferIndex[base + offset];
threadBufferIndex[base + offset] = tmp;
}
barrier();
memoryBarrierShared();
}
void putSortingData(SORTING_INDEX_TYPE index, float data) {
threadBufferIndex[uint(index)] = index;
threadBufferFloat[uint(index)] = data;
}
float getSortingData(SORTING_INDEX_TYPE index) {
return threadBufferFloat[uint(index)];
}
|
acedium
|
src\main\resources\assets\nvidium\shaders\terrain\fog.glsl
|
float getFragDistance(bool isCylindrical, vec3 position) {
return isCylindrical?max(length(position.xz), abs(position.y)):length(position);
}
void computeFog(bool spherical, vec3 position, vec4 vertColour, vec4 fogColour, float fogStart, float fogEnd, out vec3 tint, out vec3 addin) {
float f = smoothstep(fogStart, fogEnd, getFragDistance(spherical, position));
f *= fogColour.a;
//vec4 result = fogColor*(1-f)+ tint * f * colour;
addin = fogColour.xyz * f;
tint = vertColour.xyz * (1 - f);
}
|
acedium
|
src\main\resources\assets\nvidium\shaders\terrain\mesh.glsl
|
#version 460
#extension GL_ARB_shading_language_include : enable
#pragma optionNV(unroll all)
#define UNROLL_LOOP
#extension GL_NV_mesh_shader : require
#extension GL_NV_gpu_shader5 : require
#extension GL_NV_bindless_texture : require
#extension GL_KHR_shader_subgroup_basic : require
#extension GL_KHR_shader_subgroup_ballot : require
#extension GL_KHR_shader_subgroup_vote : require
#import <nvidium:occlusion/scene.glsl>
#import <nvidium:terrain/fog.glsl>
#import <nvidium:terrain/vertex_format.glsl>
//It seems like for terrain at least, the sweat spot is ~16 quads per mesh invocation (even if the local size is not 32 )
layout(local_size_x = 16) in;
layout(triangles, max_vertices=64, max_primitives=32) out;
layout(location=1) out Interpolants {
f16vec2 uv;
f16vec3 tint;
f16vec3 addin;
} OUT[];
layout(location=5) perprimitiveNV out PerPrimData {
int8_t lodBias;
uint8_t alphaCutoff;
} per_prim_out[];
taskNV in Task {
vec3 origin;
uint baseOffset;
uint quadCount;
uint transformationId;
//Binary search indexs and data
uvec4 binIa;
uvec4 binIb;
uvec4 binVa;
uvec4 binVb;
};
layout(binding = 1) uniform sampler2D tex_light;
vec4 sampleLight(uvec2 uv) {
return vec4(texelFetch(tex_light, ivec2(uv), 0).rgb, 1);
}
void emitQuadIndicies() {
uint primBase = gl_LocalInvocationID.x * 6;
uint vertexBase = gl_LocalInvocationID.x<<2;
gl_PrimitiveIndicesNV[primBase+0] = vertexBase+0;
gl_PrimitiveIndicesNV[primBase+1] = vertexBase+1;
gl_PrimitiveIndicesNV[primBase+2] = vertexBase+2;
gl_PrimitiveIndicesNV[primBase+3] = vertexBase+2;
gl_PrimitiveIndicesNV[primBase+4] = vertexBase+3;
gl_PrimitiveIndicesNV[primBase+5] = vertexBase+0;
}
mat4 transformMat;
Vertex emitVertex(uint vertexBaseId, uint innerId) {
Vertex V = terrainData[vertexBaseId + innerId];
uint outId = (gl_LocalInvocationID.x<<2)+innerId;
vec3 pos = decodeVertexPosition(V)+origin;
gl_MeshVerticesNV[outId].gl_Position = MVP*(transformMat * vec4(pos,1.0));
//TODO: make this shared state between all the vertices?
float mippingBias = decodeVertexMippingBias(V);
float alphaCutoff = decodeVertexAlphaCutoff(V);
OUT[outId].uv = f16vec2(decodeVertexUV(V));
vec4 tint = decodeVertexColour(V);
tint *= sampleLight(decodeLightUV(V));
tint *= tint.w;
vec3 tintO;
vec3 addiO;
computeFog(isCylindricalFog, pos+subchunkOffset.xyz, tint, fogColour, fogStart, fogEnd, tintO, addiO);
OUT[outId].tint = f16vec3(tintO);
OUT[outId].addin = f16vec3(addiO);
return V;
}
void emitPerPrimativeData(Vertex V) {
int8_t lodBias = int8_t(clamp(decodeVertexMippingBias(V) * 16, -128, 127));
uint8_t alphaCutoff = uint8_t(decodeVertexAlphaCutoff(V) * 255);
per_prim_out[gl_LocalInvocationID.x<<1].lodBias = lodBias;
per_prim_out[(gl_LocalInvocationID.x<<1)|1].lodBias = lodBias;
per_prim_out[gl_LocalInvocationID.x<<1].alphaCutoff = alphaCutoff;
per_prim_out[(gl_LocalInvocationID.x<<1)|1].alphaCutoff = alphaCutoff;
}
//Do a binary search via global invocation index to determine the base offset
// Note, all threads in the work group are probably going to take the same path
uint getOffset() {
uint gii = gl_GlobalInvocationID.x;
//TODO: replace this with binary search
if (gii < binIa.x) {
return binVa.x + gii + baseOffset;
} else if (gii < binIa.y) {
return binVa.y + (gii - binIa.x) + baseOffset;
} else if (gii < binIa.z) {
return binVa.z + (gii - binIa.y) + baseOffset;
} else if (gii < binIa.w) {
return binVa.w + (gii - binIa.z) + baseOffset;
} else if (gii < binIb.x) {
return binVb.x + (gii - binIa.w) + baseOffset;
} else if (gii < binIb.y) {
return binVb.y + (gii - binIb.x) + baseOffset;
} else if (gii < binIb.z) {
return binVb.z + (gii - binIb.y) + baseOffset;
} else if (gii < binIb.w) {
return binVb.w + (gii - binIb.z) + baseOffset;
} else {
return uint(-1);
}
}
void main() {
uint id = getOffset();
//If its over, dont render
if (id == uint(-1)) {
return;
}
transformMat = transformationArray[transformationId];
emitQuadIndicies();
emitPerPrimativeData(emitVertex(id<<2, 0));
emitVertex(id<<2, 1);
emitVertex(id<<2, 2);
emitVertex(id<<2, 3);
if (gl_LocalInvocationID.x == 0) {
//Remaining quads in workgroup
gl_PrimitiveCountNV = min(uint(int(quadCount)-int(gl_WorkGroupID.x<<4))<<1, 32);//2 primatives per quad
}
}
|
acedium
|
src\main\resources\assets\nvidium\shaders\terrain\task.glsl
|
#version 460
#extension GL_ARB_shading_language_include : enable
#pragma optionNV(unroll all)
#define UNROLL_LOOP
#extension GL_NV_mesh_shader : require
#extension GL_NV_gpu_shader5 : require
#extension GL_NV_bindless_texture : require
#extension GL_KHR_shader_subgroup_basic : require
#extension GL_KHR_shader_subgroup_ballot : require
#extension GL_KHR_shader_subgroup_vote : require
#import <nvidium:occlusion/scene.glsl>
//This is 1 since each task shader workgroup -> multiple meshlets. its not each globalInvocation (afaik)
layout(local_size_x=1) in;
bool shouldRenderVisible(uint sectionId) {
return (sectionVisibility[sectionId]&uint8_t(1)) != uint8_t(0);
}
#import <nvidium:terrain/task_common.glsl>
void main() {
uint sectionId = gl_WorkGroupID.x;
if (!shouldRenderVisible(sectionId)) {
//Early exit if the section isnt visible
gl_TaskCountNV = 0;
return;
}
#ifdef STATISTICS_SECTIONS
atomicAdd(statistics_buffer+1, 1);
#endif
ivec4 header = sectionData[sectionId].header;
ivec3 chunk = ivec3(header.xyz)>>8;
chunk.y &= 0x1ff;
chunk.y <<= 32-9;
chunk.y >>= 32-9;
chunk -= chunkPosition.xyz;
origin = vec3(chunk<<4);
baseOffset = (uint)header.w;
populateTasks(chunk, uvec4(sectionData[sectionId].renderRanges));
transformationId = unpackRegionTransformId(regionData[sectionId>>8]);
#ifdef STATISTICS_QUADS
atomicAdd(statistics_buffer+2, quadCount);
#endif
}
|
acedium
|
src\main\resources\assets\nvidium\shaders\terrain\task_common.glsl
|
#define MESH_WORKLOAD_PER_INVOCATION 16
taskNV out Task {
vec3 origin;
uint baseOffset;
uint quadCount;
uint transformationId;
//Binary search indexs and data
uvec4 binIa;
uvec4 binIb;
uvec4 binVa;
uvec4 binVb;
};
void putBinData(inout uint idx, inout uint lastIndex, uint offset, uint nextOffset) {
uint len = nextOffset - offset;
uint id = idx++;
if (id < 4) {
binIa[id] = lastIndex + len;
binVa[id] = offset;
} else {
binIb[id - 4] = lastIndex + len;
binVb[id - 4] = offset;
}
lastIndex += len;
}
//Populate the tasks with respect to the chunk face visibility
void populateTasks(ivec3 relChunkPos, uvec4 ranges) {
//TODO: make the ranges cumulate up, this means that we can fit much much more data per chunk
// as the range will be spred across all the offsets since they are not the absolute offset
uint idx = 0;
uint lastIndex = 0;
binIa = uvec4(0);
binIb = uvec4(0);
uint fr = (ranges.w>>16)&0xFFFF;
if (relChunkPos.x <= 0) {
putBinData(idx, lastIndex, fr, fr + (ranges.x&0xFFFF));
}
fr += ranges.x&0xFFFF;
if (relChunkPos.y <= 0) {
putBinData(idx, lastIndex, fr, fr + ((ranges.x>>16)&0xFFFF));
}
fr += (ranges.x>>16)&0xFFFF;
if (relChunkPos.z <= 0) {
putBinData(idx, lastIndex, fr, fr + (ranges.y&0xFFFF));
}
fr += ranges.y&0xFFFF;
if (relChunkPos.x >= 0) {
putBinData(idx, lastIndex, fr, fr + ((ranges.y>>16)&0xFFFF));
}
fr += (ranges.y>>16)&0xFFFF;
if (relChunkPos.y >= 0) {
putBinData(idx, lastIndex, fr, fr + (ranges.z&0xFFFF));
}
fr += ranges.z&0xFFFF;
if (relChunkPos.z >= 0) {
putBinData(idx, lastIndex, fr, fr + ((ranges.z>>16)&0xFFFF));
}
fr += (ranges.z>>16)&0xFFFF;
//TODO: Put unsigned quads at the begining? since it should be cheaper
putBinData(idx, lastIndex, fr, fr + (ranges.w&0xFFFF));
quadCount = lastIndex;
//Emit enough mesh shaders such that max(gl_GlobalInvocationID.x)>=quadCount
gl_TaskCountNV = (lastIndex+MESH_WORKLOAD_PER_INVOCATION-1)/MESH_WORKLOAD_PER_INVOCATION;
}
|
acedium
|
src\main\resources\assets\nvidium\shaders\terrain\temporal_task.glsl
|
#version 460
//Temporal task shader
#extension GL_ARB_shading_language_include : enable
#pragma optionNV(unroll all)
#define UNROLL_LOOP
#extension GL_NV_mesh_shader : require
#extension GL_NV_gpu_shader5 : require
#extension GL_NV_bindless_texture : require
#extension GL_KHR_shader_subgroup_basic : require
#extension GL_KHR_shader_subgroup_ballot : require
#extension GL_KHR_shader_subgroup_vote : require
#import <nvidium:occlusion/scene.glsl>
//This is 1 since each task shader workgroup -> multiple meshlets. its not each globalInvocation (afaik)
layout(local_size_x=1) in;
bool shouldRenderVisible(uint sectionId) {
uint8_t data = sectionVisibility[sectionId];
return (data&uint8_t(3)) == uint8_t(1);//If the section was not visible last frame but is visible this frame, render it
}
#import <nvidium:terrain/task_common.glsl>
void main() {
uint sectionId = gl_WorkGroupID.x;
if (!shouldRenderVisible(sectionId)) {
//Early exit if the section isnt visible
gl_TaskCountNV = 0;
return;
}
ivec4 header = sectionData[sectionId].header;
ivec3 chunk = ivec3(header.xyz)>>8;
chunk.y &= 0x1ff;
chunk.y <<= 32-9;
chunk.y >>= 32-9;
chunk -= chunkPosition.xyz;
origin = vec3(chunk<<4);
baseOffset = (uint)header.w;
populateTasks(chunk, uvec4(sectionData[sectionId].renderRanges));
transformationId = unpackRegionTransformId(regionData[sectionId>>8]);
#ifdef STATISTICS_QUADS
atomicAdd(statistics_buffer+2, quadCount);
#endif
}
|
acedium
|
src\main\resources\assets\nvidium\shaders\terrain\vertex_format.glsl
|
#define MODEL_SCALE 32.0 / 65536.0
#define MODEL_ORIGIN 8.0
#define COLOR_SCALE 1.0 / 255.0
vec3 decodeVertexPosition(Vertex v) {
uvec3 packed_position = uvec3(
(v.x >> 0) & 0xFFFFu,
(v.x >> 16) & 0xFFFFu,
(v.y >> 0) & 0xFFFFu
);
return (vec3(packed_position) * MODEL_SCALE) - MODEL_ORIGIN;
}
vec4 decodeVertexColour(Vertex v) {
uvec3 packed_color = (uvec3(v.z) >> uvec3(0, 8, 16)) & uvec3(0xFFu);
return vec4(vec3(packed_color) * COLOR_SCALE, 1);
}
vec2 decodeVertexUV(Vertex v) {
return vec2(v.w&0xffff,v.w>>16)*(1f/(TEXTURE_MAX_SCALE));
}
float decodeVertexMippingBias(Vertex v) {
return ((v.y>>16)&4)==0?-8:0;
}
float decodeVertexAlphaCutoff(Vertex v) {
return (float[](0.0f, 0.1f,0.5f))[((v.y>>16)&int16_t(3))];
}
uvec2 decodeLightUV(Vertex v) {
return (uvec2(v.z) >> uvec2(24, 28)) & uvec2(0xFu);
}
|
acedium
|
src\main\resources\assets\nvidium\shaders\occlusion\region_raster\mesh.glsl
|
#version 460
#extension GL_ARB_shading_language_include : enable
#pragma optionNV(unroll all)
#define UNROLL_LOOP
#extension GL_NV_mesh_shader : require
#extension GL_NV_gpu_shader5 : require
#extension GL_NV_bindless_texture : require
#extension GL_NV_shader_buffer_load : require
#import <nvidium:occlusion/scene.glsl>
#define ADD_SIZE (0.1f/16)
//TODO: maybe do multiple cubes per workgroup? this would increase utilization of individual sm's
layout(local_size_x = 8) in;
layout(triangles, max_vertices=8, max_primitives=12) out;
const uint PILUTA[] = {0, 3, 6, 0, 1, 7, 4, 5};
const uint PILUTB[] = {1, 2, 6, 4, 0, 7, 6, 4};
const uint PILUTC[] = {2, 0, 4, 5, 1, 3, 7, 2};
const uint PILUTD[] = {1, 2, 0, 5, 5, 1, 7, 7};
const uint PILUTE[] = {6, 2, 3, 7};
void emitIndicies(int visIndex) {
gl_PrimitiveIndicesNV[(gl_LocalInvocationID.x<<2)|0] = PILUTA[gl_LocalInvocationID.x];
gl_PrimitiveIndicesNV[(gl_LocalInvocationID.x<<2)|1] = PILUTB[gl_LocalInvocationID.x];
gl_PrimitiveIndicesNV[(gl_LocalInvocationID.x<<2)|2] = PILUTC[gl_LocalInvocationID.x];
gl_PrimitiveIndicesNV[(gl_LocalInvocationID.x<<2)|3] = PILUTD[gl_LocalInvocationID.x];
gl_MeshPrimitivesNV[gl_LocalInvocationID.x].gl_PrimitiveID = visIndex;
}
void emitParital(int visIndex) {
gl_PrimitiveIndicesNV[(8*4)+gl_LocalInvocationID.x] = PILUTE[gl_LocalInvocationID.x];
gl_MeshPrimitivesNV[gl_LocalInvocationID.x+8].gl_PrimitiveID = visIndex;
gl_PrimitiveCountNV = 12;
}
void main() {
//FIXME: It might actually be more efficent to just upload the region data straight into the ubo
// this remove an entire level of indirection and also puts region data in the very fast path
Region data = regionData[regionIndicies[gl_WorkGroupID.x]];//fetch the region data
int visibilityIndex = (int)gl_WorkGroupID.x;
//If the region metadata was empty, return
if (data.a == uint64_t(-1)) {
regionVisibility[visibilityIndex] = uint8_t(0);
gl_PrimitiveCountNV = 0;
return;
}
ivec3 pos = unpackRegionPosition(data);
ivec3 size = unpackRegionSize(data);
vec3 start = pos - chunkPosition.xyz - ADD_SIZE;
vec3 end = start + 1 + size + (ADD_SIZE*2);
//TODO: Look into only doing 4 locals, for 2 reasons, its more effective for reducing duplicate computation and bandwidth
// it also means that each thread can emit 3 primatives, 9 indicies each
//can also do 8 threads then each thread emits a primative and 4 indicies each then the lower 4 emit 1 indice extra each
vec3 corner = vec3(((gl_LocalInvocationID.x&1)==0)?start.x:end.x, ((gl_LocalInvocationID.x&4)==0)?start.y:end.y, ((gl_LocalInvocationID.x&2)==0)?start.z:end.z);
corner *= 16.0f;
gl_MeshVerticesNV[gl_LocalInvocationID.x].gl_Position = MVP*(getRegionTransformation(data)*vec4(corner, 1.0));
emitIndicies(visibilityIndex);
if (gl_LocalInvocationID.x < 4) {
emitParital(visibilityIndex);
if (gl_LocalInvocationID.x == 0) {
bool cameraInRegion = all(lessThan(start*16+subchunkOffset.xyz, vec3(ADD_SIZE*16))) && all(lessThan(vec3(-ADD_SIZE*16), end*16+subchunkOffset.xyz));
regionVisibility[visibilityIndex] = cameraInRegion?uint8_t(1):uint8_t(0);
}
}
}
|
acedium
|
src\main\resources\assets\nvidium\shaders\occlusion\section_raster\fragment.glsl
|
#version 460
#extension GL_ARB_shading_language_include : enable
#pragma optionNV(unroll all)
#define UNROLL_LOOP
#extension GL_NV_gpu_shader5 : require
#extension GL_NV_bindless_texture : require
#extension GL_NV_shader_buffer_load : require
#import <nvidium:occlusion/scene.glsl>
layout(early_fragment_tests) in;
#ifdef DEBUG
layout(location = 0) out vec4 colour;
void main() {
uint uid = bitfieldReverse(gl_PrimitiveID*132471+123571);
colour = vec4(float((uid>>0)&7)/7, float((uid>>3)&7)/7, float((uid>>6)&7)/7, 1.0);
sectionVisibility[gl_PrimitiveID>>8] = uint8_t(gl_PrimitiveID);
}
#else
void main() {
sectionVisibility[gl_PrimitiveID>>8] = uint8_t(gl_PrimitiveID);
}
#endif
|
acedium
|
src\main\resources\assets\nvidium\shaders\occlusion\section_raster\mesh.glsl
|
#version 460
#extension GL_ARB_shading_language_include : enable
#pragma optionNV(unroll all)
#define UNROLL_LOOP
#extension GL_NV_mesh_shader : require
#extension GL_NV_gpu_shader5 : require
#extension GL_NV_bindless_texture : require
#extension GL_KHR_shader_subgroup_basic : require
#extension GL_KHR_shader_subgroup_ballot : require
#extension GL_KHR_shader_subgroup_vote : require
#import <nvidium:occlusion/scene.glsl>
#define ADD_SIZE (0.1f)
layout(local_size_x = 8) in;
layout(triangles, max_vertices=8, max_primitives=12) out;
taskNV in Task {
uint32_t _visOutBase;//Base output visibility index
uint32_t _offset;
mat4 regionTransform;
};
const uint PILUTA[] = {0, 3, 6, 0, 1, 7, 4, 5};
const uint PILUTB[] = {1, 2, 6, 4, 0, 7, 6, 4};
const uint PILUTC[] = {2, 0, 4, 5, 1, 3, 7, 2};
const uint PILUTD[] = {1, 2, 0, 5, 5, 1, 7, 7};
const uint PILUTE[] = {6, 2, 3, 7};
void emitIndicies(int visIndex) {
gl_PrimitiveIndicesNV[(gl_LocalInvocationID.x<<2)|0] = PILUTA[gl_LocalInvocationID.x];
gl_PrimitiveIndicesNV[(gl_LocalInvocationID.x<<2)|1] = PILUTB[gl_LocalInvocationID.x];
gl_PrimitiveIndicesNV[(gl_LocalInvocationID.x<<2)|2] = PILUTC[gl_LocalInvocationID.x];
gl_PrimitiveIndicesNV[(gl_LocalInvocationID.x<<2)|3] = PILUTD[gl_LocalInvocationID.x];
gl_MeshPrimitivesNV[gl_LocalInvocationID.x].gl_PrimitiveID = visIndex;
}
void emitParital(int visIndex) {
gl_PrimitiveIndicesNV[(8*4)+gl_LocalInvocationID.x] = PILUTE[gl_LocalInvocationID.x];
gl_MeshPrimitivesNV[gl_LocalInvocationID.x+8].gl_PrimitiveID = visIndex;
}
//TODO: Check if the section can be culled via fog
void main() {
int visibilityIndex = (int)(_visOutBase|gl_WorkGroupID.x);
uint8_t lastData = sectionVisibility[visibilityIndex];
// this is almost 100% guarenteed not needed afaik
//barrier();
ivec4 header = sectionData[_offset|gl_WorkGroupID.x].header;
//If the section header was empty or the hide section bit is set, return
//NOTE: technically this has the infinitly small probability of not rendering a block if the block is located at
// 0,0,0 the only block in the chunk and the first thing in the buffer
// to fix, also check that the ranges are null
if (sectionEmpty(header) || (header.y&(1<<17)) != 0) {
if (gl_LocalInvocationID.x == 0) {
sectionVisibility[visibilityIndex] = uint8_t(0);
gl_PrimitiveCountNV = 0;
}
return;
}
vec3 mins = (header.xyz&0xF)-ADD_SIZE;
vec3 maxs = mins+((header.xyz>>4)&0xF)+1+(ADD_SIZE*2);
ivec3 chunk = ivec3(header.xyz)>>8;
chunk.y &= 0x1ff;
chunk.y <<= 32-9;
chunk.y >>= 32-9;
ivec3 relativeChunkPos = (chunk - chunkPosition.xyz);
vec3 corner = vec3(relativeChunkPos<<4);
vec3 cornerCopy = corner;
//TODO: try mix instead or something other than just ternaries, i think they get compiled to a cmov type instruction but not sure
corner += vec3(((gl_LocalInvocationID.x&1)==0)?mins.x:maxs.x, ((gl_LocalInvocationID.x&4)==0)?mins.y:maxs.y, ((gl_LocalInvocationID.x&2)==0)?mins.z:maxs.z);
gl_MeshVerticesNV[gl_LocalInvocationID.x].gl_Position = (MVP*(regionTransform*vec4(corner, 1.0)));
int prim_payload = (visibilityIndex<<8)|int(((uint(lastData))<<1)&0xff)|1;
emitIndicies(prim_payload);
if (gl_LocalInvocationID.x < 4) {
emitParital(prim_payload);
}
if (gl_LocalInvocationID.x == 0) {
cornerCopy += subchunkOffset.xyz;
vec3 minPos = mins + cornerCopy;
vec3 maxPos = maxs + cornerCopy;
bool isInSection = all(lessThan(minPos, vec3(ADD_SIZE))) && all(lessThan(vec3(-ADD_SIZE), maxPos));
//Shift and set, this gives us a bonus of having the last 8 frames as visibility history
sectionVisibility[visibilityIndex] = uint8_t(lastData<<1) | uint8_t(isInSection?1:0);//Inject visibility aswell
//sectionVisibility[visibilityIndex] = uint8_t(lastData<<1) | uint8_t(0);
gl_PrimitiveCountNV = 12;
}
}
|
acedium
|
src\main\resources\assets\nvidium\shaders\occlusion\section_raster\task.glsl
|
#version 460
#extension GL_ARB_shading_language_include : enable
#pragma optionNV(unroll all)
#define UNROLL_LOOP
#extension GL_NV_mesh_shader : require
#extension GL_NV_gpu_shader5 : require
#extension GL_NV_bindless_texture : require
#extension GL_KHR_shader_subgroup_basic : require
#extension GL_KHR_shader_subgroup_ballot : require
#extension GL_KHR_shader_subgroup_vote : require
#import <nvidium:occlusion/scene.glsl>
//This is 1 since each task shader workgroup -> multiple meshlets. its not each globalInvocation (afaik)
layout(local_size_x=1) in;
taskNV out Task {
uint32_t _visOutBase;// The base offset for the visibility output of the shader
uint32_t _offset;//start offset for regions (can/should probably be a uint16 since this is just the region id << 8)
//uint64_t bitcheck[4];//TODO: MAYBE DO THIS, each bit is whether there a section at that index, doing so is faster than pulling metadata to check if a section is valid or not
mat4 regionTransform;
};
void main() {
//TODO: see whats faster, atomicAdd (for mdic) or dispatching alot of empty calls (mdi)
//TODO: experiment with emitting 8 workgroups with the 8th always being 0
// doing so would enable to batch memory write 2 commands
// thus taking 4 mem moves instead of 7
//Emit 7 workloads per chunk
uint cmdIdx = gl_WorkGroupID.x;
uint transCmdIdx = (uint(regionCount) - gl_WorkGroupID.x) - 1;
//Early exit if the region wasnt visible
if (regionVisibility[gl_WorkGroupID.x] == uint8_t(0)) {
terrainCommandBuffer[cmdIdx] = uvec2(0);
translucencyCommandBuffer[transCmdIdx] = uvec2(0);
gl_TaskCountNV = 0;
return;
}
#ifdef STATISTICS_REGIONS
atomicAdd(statistics_buffer, 1);
#endif
//FIXME: It might actually be more efficent to just upload the region data straight into the ubo
uint32_t offset = regionIndicies[gl_WorkGroupID.x];
Region data = regionData[offset];
int count = unpackRegionCount(data)+1;
//Write in order
_visOutBase = offset<<8;//This makes checking visibility very fast and quick in the compute shader
_offset = offset<<8;
regionTransform = getRegionTransformation(data);
gl_TaskCountNV = count;
terrainCommandBuffer[cmdIdx] = uvec2(uint32_t(count), _visOutBase);
//TODO: add a bit to the region header to determine whether or not a region has any translucent
// sections, if it doesnt, write 0 to the command buffer
translucencyCommandBuffer[transCmdIdx] = uvec2(uint32_t(count), _visOutBase);
}
|
acedium
|
src\main\resources\assets\nvidium\shaders\occlusion\queries\region\mesh.glsl
|
#version 460
#extension GL_ARB_shading_language_include : enable
#pragma optionNV(unroll all)
#define UNROLL_LOOP
#extension GL_NV_mesh_shader : require
#extension GL_NV_gpu_shader5 : require
#extension GL_NV_bindless_texture : require
#extension GL_NV_shader_buffer_load : require
#import <nvidium:occlusion/scene.glsl>
#define ADD_SIZE (0.1f/16)
//TODO: maybe do multiple cubes per workgroup? this would increase utilization of individual sm's
layout(local_size_x = 8) in;
layout(triangles, max_vertices=8, max_primitives=12) out;
const uint PILUTA[] = {0, 3, 6, 0, 1, 7, 4, 5};
const uint PILUTB[] = {1, 2, 6, 4, 0, 7, 6, 4};
const uint PILUTC[] = {2, 0, 4, 5, 1, 3, 7, 2};
const uint PILUTD[] = {1, 2, 0, 5, 5, 1, 7, 7};
const uint PILUTE[] = {6, 2, 3, 7};
void emitIndicies(int visIndex) {
gl_PrimitiveIndicesNV[(gl_LocalInvocationID.x<<2)|0] = PILUTA[gl_LocalInvocationID.x];
gl_PrimitiveIndicesNV[(gl_LocalInvocationID.x<<2)|1] = PILUTB[gl_LocalInvocationID.x];
gl_PrimitiveIndicesNV[(gl_LocalInvocationID.x<<2)|2] = PILUTC[gl_LocalInvocationID.x];
gl_PrimitiveIndicesNV[(gl_LocalInvocationID.x<<2)|3] = PILUTD[gl_LocalInvocationID.x];
gl_MeshPrimitivesNV[gl_LocalInvocationID.x].gl_PrimitiveID = visIndex;
}
void emitParital(int visIndex) {
gl_PrimitiveIndicesNV[(8*4)+gl_LocalInvocationID.x] = PILUTE[gl_LocalInvocationID.x];
gl_MeshPrimitivesNV[gl_LocalInvocationID.x+8].gl_PrimitiveID = visIndex;
gl_PrimitiveCountNV = 12;
}
void main() {
//FIXME: It might actually be more efficent to just upload the region data straight into the ubo
// this remove an entire level of indirection and also puts region data in the very fast path
Region data = regionData[regionIndicies[gl_WorkGroupID.x]];//fetch the region data
vec3 start = unpackRegionPosition(data) - chunkPosition.xyz - ADD_SIZE;
vec3 end = start + 1 + unpackRegionSize(data) + (ADD_SIZE*2);
//TODO: Look into only doing 4 locals, for 2 reasons, its more effective for reducing duplicate computation and bandwidth
// it also means that each thread can emit 3 primatives, 9 indicies each
//can also do 8 threads then each thread emits a primative and 4 indicies each then the lower 4 emit 1 indice extra each
vec3 corner = vec3(((gl_LocalInvocationID.x&1)==0)?start.x:end.x, ((gl_LocalInvocationID.x&4)==0)?start.y:end.y, ((gl_LocalInvocationID.x&2)==0)?start.z:end.z);
corner *= 16.0f;
gl_MeshVerticesNV[gl_LocalInvocationID.x].gl_Position = MVP*(getRegionTransformation(data)*vec4(corner, 1.0));
int visibilityIndex = (int)gl_WorkGroupID.x;
regionVisibility[visibilityIndex] = uint8_t(0);
emitIndicies(visibilityIndex);
if (gl_LocalInvocationID.x < 4) {
emitParital(visibilityIndex);
}
}
|
acedium
|
src\main\resources\assets\nvidium\shaders\terrain\translucent\mesh.glsl
|
#version 460
#extension GL_ARB_shading_language_include : enable
#pragma optionNV(unroll all)
#define UNROLL_LOOP
#extension GL_NV_mesh_shader : require
#extension GL_NV_gpu_shader5 : require
#extension GL_NV_bindless_texture : require
#extension GL_KHR_shader_subgroup_basic : require
#extension GL_KHR_shader_subgroup_ballot : require
#extension GL_KHR_shader_subgroup_vote : require
#import <nvidium:occlusion/scene.glsl>
#import <nvidium:terrain/fog.glsl>
#import <nvidium:terrain/vertex_format.glsl>
#ifdef TRANSLUCENCY_SORTING_QUADS
vec3 depthPos = vec3(0);
shared float depthBuffers[32];
#endif
layout(local_size_x = 32) in;
layout(triangles, max_vertices=128, max_primitives=64) out;
//originAndBaseData.w is in quad count space, so is endIdx
taskNV in Task {
vec4 originAndBaseData;
uint quadCount;
#ifdef TRANSLUCENCY_SORTING_QUADS
uint8_t jiggle;
#endif
};
layout(location=1) out Interpolants {
f16vec3 tint;
f16vec3 addin;
f16vec2 uv;
} OUT[];
layout(binding = 1) uniform sampler2D tex_light;
vec4 sampleLight(uvec2 uv) {
return vec4(texelFetch(tex_light, ivec2(uv), 0).rgb, 1);
}
void emitQuadIndicies() {
uint primBase = gl_LocalInvocationID.x * 6;
uint vertexBase = gl_LocalInvocationID.x<<2;
gl_PrimitiveIndicesNV[primBase+0] = vertexBase+0;
gl_PrimitiveIndicesNV[primBase+1] = vertexBase+1;
gl_PrimitiveIndicesNV[primBase+2] = vertexBase+2;
gl_PrimitiveIndicesNV[primBase+3] = vertexBase+2;
gl_PrimitiveIndicesNV[primBase+4] = vertexBase+3;
gl_PrimitiveIndicesNV[primBase+5] = vertexBase+0;
}
void emitVertex(uint vertexBaseId, uint innerId) {
Vertex V = terrainData[vertexBaseId + innerId];
uint outId = (gl_LocalInvocationID.x<<2)+innerId;
vec3 pos = decodeVertexPosition(V)+originAndBaseData.xyz;
gl_MeshVerticesNV[outId].gl_Position = MVP*vec4(pos,1.0);
OUT[outId].uv = f16vec2(decodeVertexUV(V));
vec4 tint = decodeVertexColour(V);
tint *= sampleLight(decodeLightUV(V));
tint *= tint.w;
vec3 tintO;
vec3 addiO;
vec3 exactPos = pos+subchunkOffset.xyz;
computeFog(isCylindricalFog, exactPos, tint, fogColour, fogStart, fogEnd, tintO, addiO);
OUT[outId].tint = f16vec3(tintO);
OUT[outId].addin = f16vec3(addiO);
#ifdef TRANSLUCENCY_SORTING_QUADS
depthPos += exactPos;
#endif
}
#ifdef TRANSLUCENCY_SORTING_QUADS
void swapQuads(uint idxA, uint idxB) {
if (idxA == idxB) {
return;
}
Vertex A0 = terrainData[(idxA<<2)+0];
Vertex A1 = terrainData[(idxA<<2)+1];
Vertex A2 = terrainData[(idxA<<2)+2];
Vertex A3 = terrainData[(idxA<<2)+3];
Vertex B0 = terrainData[(idxB<<2)+0];
Vertex B1 = terrainData[(idxB<<2)+1];
Vertex B2 = terrainData[(idxB<<2)+2];
Vertex B3 = terrainData[(idxB<<2)+3];
//groupMemoryBarrier();
//memoryBarrier();
//barrier();
terrainData[(idxA<<2)+0] = B0;
terrainData[(idxA<<2)+1] = B1;
terrainData[(idxA<<2)+2] = B2;
terrainData[(idxA<<2)+3] = B3;
terrainData[(idxB<<2)+0] = A0;
terrainData[(idxB<<2)+1] = A1;
terrainData[(idxB<<2)+2] = A2;
terrainData[(idxB<<2)+3] = A3;
//groupMemoryBarrier();
//memoryBarrier();
//barrier();
}
void performTranslucencySort() {
uint baseQuadPtr = floatBitsToUint(originAndBaseData.w) + (gl_WorkGroupID.x<<5);
float depth = dot(depthPos, depthPos) * ((1/4f)*(1/4f));
depthBuffers[gl_LocalInvocationID.x] = depth;
if (gl_GlobalInvocationID.x < jiggle) {
//If we are in the jiggle index dont attempt to swap else we start rendering garbage data
depthBuffers[gl_LocalInvocationID.x] = -9999f;
}
groupMemoryBarrier();
memoryBarrier();
barrier();
//TODO: use subgroup ballot to check if all the quads are already sorted, if they are dont perform sort op
//Only use 16 threads to sort all 32 data
if (gl_LocalInvocationID.x < 16) {
uint idA = (gl_LocalInvocationID.x<<1);
uint idB = (gl_LocalInvocationID.x<<1)+1;
float a = depthBuffers[idA];
float b = depthBuffers[idB];
if (a > 0.0001f && b > 0.0001f && a < b) {
swapQuads(idA + baseQuadPtr, idB + baseQuadPtr);
}
}
}
#endif
//TODO: extra per quad culling
void main() {
#ifdef TRANSLUCENCY_SORTING_QUADS
depthBuffers[gl_LocalInvocationID.x] = -99999999f;
#endif
if ((gl_GlobalInvocationID.x)>=quadCount) { //If its over the quad count, dont render
return;
}
emitQuadIndicies();
//Each pair of meshlet invokations emits 4 vertices each and 2 primative each
uint id = (floatBitsToUint(originAndBaseData.w) + gl_GlobalInvocationID.x)<<2;
#ifdef TRANSLUCENCY_SORTING_QUADS
//If we are at the start, dont want to render as it contains garbled data (out of bounds)
if (gl_GlobalInvocationID.x < jiggle) {
gl_MeshVerticesNV[(gl_LocalInvocationID.x<<2)+0].gl_Position = vec4(1,1,1,-1);
gl_MeshVerticesNV[(gl_LocalInvocationID.x<<2)+1].gl_Position = vec4(1,1,1,-1);
gl_MeshVerticesNV[(gl_LocalInvocationID.x<<2)+2].gl_Position = vec4(1,1,1,-1);
gl_MeshVerticesNV[(gl_LocalInvocationID.x<<2)+3].gl_Position = vec4(1,1,1,-1);
} else {
emitVertex(id, 0);
emitVertex(id, 1);
emitVertex(id, 2);
emitVertex(id, 3);
}
barrier();
memoryBarrierShared();
performTranslucencySort();
int meta = 2;
#else
emitVertex(id, 0);
emitVertex(id, 1);
emitVertex(id, 2);
emitVertex(id, 3);
int meta = int(gl_GlobalInvocationID.x);
#endif
gl_MeshPrimitivesNV[(gl_LocalInvocationID.x<<1)].gl_PrimitiveID = meta;
gl_MeshPrimitivesNV[(gl_LocalInvocationID.x<<1)|1].gl_PrimitiveID = meta;
if (gl_LocalInvocationID.x == 0) {
//Remaining quads in workgroup
gl_PrimitiveCountNV = min(uint(int(quadCount)-int(gl_WorkGroupID.x<<5))<<1, 64);//2 primatives per quad
}
}
|
acedium
|
src\main\resources\assets\nvidium\shaders\terrain\translucent\task.glsl
|
#version 460
#extension GL_ARB_shading_language_include : enable
#pragma optionNV(unroll all)
#define UNROLL_LOOP
#extension GL_NV_mesh_shader : require
#extension GL_NV_gpu_shader5 : require
#extension GL_NV_bindless_texture : require
#extension GL_KHR_shader_subgroup_basic : require
#extension GL_KHR_shader_subgroup_ballot : require
#extension GL_KHR_shader_subgroup_vote : require
#import <nvidium:occlusion/scene.glsl>
#define MESH_WORKLOAD_PER_INVOCATION 32
//This is 1 since each task shader workgroup -> multiple meshlets. its not each globalInvocation (afaik)
layout(local_size_x=1) in;
//In here add an array that is then "logged" on in the mesh shader to find the draw data
taskNV out Task {
vec4 originAndBaseData;
uint quadCount;
#ifdef TRANSLUCENCY_SORTING_QUADS
uint8_t jiggle;
#endif
};
bool shouldRender(uint sectionId) {
//Check visibility
return (sectionVisibility[sectionId]&uint8_t(1)) != uint8_t(0);
}
void main() {
uint sectionId = gl_WorkGroupID.x;
#ifdef TRANSLUCENCY_SORTING_SECTIONS
//Compute indirection for translucency sorting
{
ivec4 header = sectionData[sectionId].header;
//If the section is empty, we dont care about it at all, so ignore it and return
if (sectionEmpty(header)) {
return;
}
//Compute the redirected section index
sectionId &= ~0xFF;
sectionId |= uint((header.y>>18)&0xFF);
}
#endif
if (!shouldRender(sectionId)) {
//Early exit if the section isnt visible
//TODO: also early exit if there are no translucents to render
gl_TaskCountNV = 0;
return;
}
ivec4 header = sectionData[sectionId].header;
uint baseDataOffset = (uint)header.w;
ivec3 chunk = ivec3(header.xyz)>>8;
chunk.y &= 0x1ff;
chunk.y <<= 32-9;
chunk.y >>= 32-9;
originAndBaseData.xyz = vec3((chunk - chunkPosition.xyz)<<4);
quadCount = ((sectionData[sectionId].renderRanges.w>>16)&0xFFFF);
#ifdef TRANSLUCENCY_SORTING_QUADS
jiggle = uint8_t(min(quadCount>>1,(uint(frameId)&1)));//Jiggle by 1 quads (either 0 or 1)//*15
//jiggle = uint8_t(0);
quadCount += jiggle;
originAndBaseData.w = uintBitsToFloat(baseDataOffset - uint(jiggle));
#else
originAndBaseData.w = uintBitsToFloat(baseDataOffset);
#endif
//Emit enough mesh shaders such that max(gl_GlobalInvocationID.x)>=quadCount
gl_TaskCountNV = (quadCount+MESH_WORKLOAD_PER_INVOCATION-1)/MESH_WORKLOAD_PER_INVOCATION;
#ifdef STATISTICS_QUADS
atomicAdd(statistics_buffer+2, quadCount);
#endif
#ifdef STATISTICS_SECTIONS
atomicAdd(statistics_buffer+1, 1);
#endif
}
|
AdvancedChatCore
|
build.gradle
|
plugins {
id 'fabric-loom' version '1.0-SNAPSHOT'
id 'maven-publish'
id "io.freefair.lombok" version "6.0.0-m2"
}
apply from: 'https://raw.githubusercontent.com/DarkKronicle/GradleScripts/main/gradle/publish.gradle'
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
archivesBaseName = project.archives_base_name
version = "${project.minecraft_version}-${project.mod_version}"
group = project.maven_group
Properties additionalProperties = new Properties()
if (file("extra.properties").exists()) {
additionalProperties.load(file("extra.properties").newReader())
}
repositories {
mavenCentral()
maven { url 'https://masa.dy.fi/maven' }
maven { url 'https://maven.terraformersmc.com/releases/' }
maven { url 'https://jitpack.io' }
}
dependencies {
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_api_version}"
modImplementation "fi.dy.masa.malilib:malilib-fabric-1.19.4:${project.malilib_version}"
modCompileOnly "com.terraformersmc:modmenu:5.0.1"
implementation "com.github.DarkKronicle.Konstruct:addons:${project.konstruct_version}"
implementation "com.github.DarkKronicle.Konstruct:core:${project.konstruct_version}"
implementation 'com.electronwill.night-config:toml:3.6.5'
// Transitive
include 'com.electronwill.night-config:toml:3.6.5'
include 'com.electronwill.night-config:core:3.6.5'
include "com.github.DarkKronicle.Konstruct:addons:${project.konstruct_version}"
include "com.github.DarkKronicle.Konstruct:core:${project.konstruct_version}"
implementation "org.mariuszgromada.math:MathParser.org-mXparser:${project.mxparser_version}"
include "org.mariuszgromada.math:MathParser.org-mXparser:${project.mxparser_version}"
implementation "io.github.maowimpl:owo:${project.owo_version}"
include "io.github.maowimpl:owo:${project.owo_version}"
implementation 'org.apache.commons:commons-csv:1.8'
include 'org.apache.commons:commons-csv:1.8'
}
processResources {
inputs.property "version", project.version
filesMatching("fabric.mod.json") {
expand "version": project.version
}
}
tasks.withType(JavaCompile).configureEach {
it.options.encoding = "UTF-8"
it.options.release = 17
}
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = "sources"
from sourceSets.main.allSource
}
jar {
from "LICENSE.txt"
}
tasks.register('downloadExtra') {
def f = new File('./src/main/resources/swear_words.csv')
if (!f.exists()) {
new URL('https://raw.githubusercontent.com/surge-ai/profanity/main/profanity_en.csv').withInputStream{ i -> f.withOutputStream{ it << i }}
}
}
assemble {
dependsOn 'downloadExtra'
}
// configure the maven publication
publishing {
publications {
mavenJava(MavenPublication) {
// add all the jars that should be included when publishing to maven
artifact(remapJar) {
builtBy remapJar
}
artifact(sourcesJar) {
builtBy remapSourcesJar
}
}
}
// select the repositories you want to publish to
repositories {
// uncomment to publish to the local maven
// mavenLocal()
}
}
|
AdvancedChatCore
|
settings.gradle
|
pluginManagement {
repositories {
maven {
name = 'Fabric'
url = 'https://maven.fabricmc.net/'
}
gradlePluginPortal()
mavenCentral()
}
}
|
AdvancedChatCore
|
src\main\resources\advancedchatcore.mixins.json
|
{
"required": true,
"package": "io.github.darkkronicle.advancedchatcore.mixin",
"compatibilityLevel": "JAVA_8",
"mixins": [
"MixinClientPlayerEntity"
],
"client": [
"MixinChatHud",
"MixinChatHudInvoker",
"MixinChatScreen",
"MixinKeyboard",
"MixinMinecraftClient",
"MixinSleepingChatScreen",
"MixinMessageIndicator"
],
"injectors": {
"defaultRequire": 1
}
}
|
AdvancedChatCore
|
src\main\resources\fabric.mod.json
|
{
"schemaVersion": 1,
"id": "advancedchatcore",
"version": "${version}",
"name": "AdvancedChatCore",
"description": "The core of all AdvancedChat features",
"authors": [
"DarkKronicle"
],
"contact": {
"homepage": "https://www.curseforge.com/minecraft/mc-mods/advancedchatcore",
"sources": "https://github.com/DarkKronicle/AdvancedChatCore",
"issues": "https://github.com/DarkKronicle/AdvancedChatCore/issues",
"discord": "https://discord.gg/WnaE3uZxDA"
},
"license": "MPL-v2",
"icon": "assets/advancedchatcore/icon.png",
"environment": "*",
"entrypoints": {
"client": [
"io.github.darkkronicle.advancedchatcore.AdvancedChatCore"
],
"modmenu": [
"io.github.darkkronicle.advancedchatcore.config.gui.ModMenuImpl"
]
},
"mixins": [
"advancedchatcore.mixins.json"
],
"depends": {
"fabricloader": ">=0.14.18",
"fabric": "*",
"minecraft": ">=1.19.4",
"malilib": ">=0.15.2"
},
"custom": {
"modmenu": {
"links": {
"modmenu.discord": "https://discord.gg/WnaE3uZxDA"
}
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\AdvancedChatCore.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore;
import fi.dy.masa.malilib.event.InitializationHandler;
import fi.dy.masa.malilib.gui.GuiBase;
import io.github.darkkronicle.advancedchatcore.chat.AdvancedSleepingChatScreen;
import io.github.darkkronicle.advancedchatcore.util.Colors;
import io.github.darkkronicle.advancedchatcore.util.SyncTaskQueue;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.util.Random;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.minecraft.client.MinecraftClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@Environment(EnvType.CLIENT)
public class AdvancedChatCore implements ClientModInitializer {
public static final String MOD_ID = "advancedchatcore";
/**
* Whether or not messages should be sent to the HUD. Used for other modules overwriting HUD.
*/
public static boolean FORWARD_TO_HUD = true;
/**
* Whether or not the default chat suggestor should be created. Used for modules overwriting the
* suggestor.
*/
public static boolean CREATE_SUGGESTOR = true;
public static final Logger LOGGER = LogManager.getLogger(MOD_ID);
private static final Random RANDOM = new Random();
private static final String[] RANDOM_STRINGS = {
"yes", "maybe", "no", "potentially", "hello", "goodbye", "tail", "pop", "water",
"headphone", "head", "scissor", "paper", "burger", "clock", "peg", "speaker",
"computer", "mouse", "mat", "keyboard", "soda", "mac", "cheese", "home",
"pillow", "couch", "drums", "drumstick", "math", "Euler", "Chronos", "DarkKronicle",
"Kron", "pain", "suffer", "bridge", "Annevdl", "MaLiLib", "pog", "music",
"pants", "glockenspiel", "marimba", "chimes", "vibraphone", "vibe", "snare",
"monkeymode", "shades", "cactus", "shaker", "pit", "band", "percussion",
"foot", "leg", "Kurt", "bruh", "gamer", "gaming"
};
@Override
public void onInitializeClient() {
// Important to get first since configuration options depend on colors
Colors.getInstance().load();
InitializationHandler.getInstance().registerInitializationHandler(new InitHandler());
MinecraftClient client = MinecraftClient.getInstance();
ClientTickEvents.START_CLIENT_TICK.register(
s -> {
// Allow for delayed tasks to be added
SyncTaskQueue.getInstance().update(s.inGameHud.getTicks());
// Make sure we're not in the sleeping screen while awake
if (client.currentScreen instanceof AdvancedSleepingChatScreen
&& !client.player.isSleeping()) {
GuiBase.openGui(null);
}
});
}
/**
* Get's a resource from src/resources. Works in a emulated environment.
*
* @param path Path from the resources to get
* @return Stream of the resource
* @throws URISyntaxException If the resource doesn't exist
* @throws IOException Can't be opened
*/
public static InputStream getResource(String path) throws URISyntaxException, IOException {
URI uri = Thread.currentThread().getContextClassLoader().getResource(path).toURI();
if (!uri.getScheme().equals("file")) {
// it's not a file
return Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
} else {
// it's a file - try to access it directly!
return new FileInputStream(Paths.get(uri).toFile());
}
}
/**
* Get's a random string.
*
* @return Random generated string.
*/
public static String getRandomString() {
return RANDOM_STRINGS[RANDOM.nextInt(RANDOM_STRINGS.length)];
}
/**
* Returns the server address that the client is currently connected to.
* @return The server address if connected, 'singleplayer' if singleplayer, 'none' if none.
*/
public static String getServer() {
MinecraftClient client = MinecraftClient.getInstance();
if (client.isInSingleplayer()) {
return "singleplayer";
}
if (client.getCurrentServerEntry() == null) {
return "none";
}
return client.getCurrentServerEntry().address;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\InitHandler.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore;
import fi.dy.masa.malilib.config.ConfigManager;
import fi.dy.masa.malilib.config.IConfigBase;
import fi.dy.masa.malilib.config.options.ConfigHotkey;
import fi.dy.masa.malilib.event.InputEventHandler;
import fi.dy.masa.malilib.gui.GuiBase;
import fi.dy.masa.malilib.interfaces.IInitializationHandler;
import fi.dy.masa.malilib.util.InfoUtils;
import io.github.darkkronicle.advancedchatcore.chat.*;
import io.github.darkkronicle.advancedchatcore.config.ConfigStorage;
import io.github.darkkronicle.advancedchatcore.config.gui.GuiConfig;
import io.github.darkkronicle.advancedchatcore.config.gui.GuiConfigHandler;
import io.github.darkkronicle.advancedchatcore.config.gui.TabSupplier;
import io.github.darkkronicle.advancedchatcore.finder.CustomFinder;
import io.github.darkkronicle.advancedchatcore.finder.custom.ProfanityFinder;
import io.github.darkkronicle.advancedchatcore.hotkeys.InputHandler;
import io.github.darkkronicle.advancedchatcore.util.ProfanityUtil;
import io.github.darkkronicle.advancedchatcore.util.StringInsert;
import io.github.darkkronicle.advancedchatcore.util.StringMatch;
import io.github.darkkronicle.advancedchatcore.util.TextUtil;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.text.Text;
import java.util.*;
@Environment(EnvType.CLIENT)
public class InitHandler implements IInitializationHandler {
@Override
public void registerModHandlers() {
// Setup modules
ModuleHandler.getInstance().registerModules();
ConfigManager.getInstance()
.registerConfigHandler(AdvancedChatCore.MOD_ID, new ConfigStorage());
// Setup chat history
MessageDispatcher.getInstance().register(new ChatHistoryProcessor(), -1);
GuiConfigHandler.getInstance().addTab(
GuiConfigHandler.children(
"advancedchatcore",
"advancedchat.tab.advancedchatcore",
GuiConfigHandler.wrapOptions(
"core_general",
"advancedchatcore.tab.general",
ConfigStorage.General.OPTIONS.stream().map((saveableConfig) -> (IConfigBase) saveableConfig.config).toList()
),
GuiConfigHandler.wrapOptions(
"chatscreen",
"advancedchatcore.tab.chatscreen",
ConfigStorage.ChatScreen.OPTIONS.stream().map((saveableConfig) -> (IConfigBase) saveableConfig.config).toList()
))
);
ProfanityUtil.getInstance().loadConfigs();
MessageDispatcher.getInstance().registerPreFilter(text -> {
if (ConfigStorage.General.FILTER_PROFANITY.config.getBooleanValue()) {
List<StringMatch> profanity =
ProfanityUtil.getInstance().getBadWords(text.getString(), (float) ConfigStorage.General.PROFANITY_ABOVE.config.getDoubleValue(), ConfigStorage.General.PROFANITY_ON_WORD_BOUNDARIES.config.getBooleanValue());
if (profanity.size() == 0) {
return Optional.empty();
}
Map<StringMatch, StringInsert> insertions =
new HashMap<>();
for (StringMatch bad : profanity) {
insertions.put(bad, (current, match) ->
Text.literal("*".repeat(bad.end - bad.start)).fillStyle(current.getStyle())
);
}
text = TextUtil.replaceStrings(text, insertions);
return Optional.of(text);
}
return Optional.empty();
}, -1);
// This constructs the default chat suggestor
ChatScreenSectionHolder.getInstance()
.addSectionSupplier(
(advancedChatScreen -> {
if (AdvancedChatCore.CREATE_SUGGESTOR) {
return new DefaultChatSuggestor(advancedChatScreen);
}
return null;
}));
CustomFinder.getInstance()
.register(
ProfanityFinder::new,
"profanity",
"advancedchatcore.findtype.custom.profanity",
"advancedchatcore.findtype.custom.info.profanity");
InputHandler.getInstance().addDisplayName("core_general", "advancedchatcore.config.tab.hotkeysgeneral");
InputHandler.getInstance().add("core_general", ConfigStorage.Hotkeys.OPEN_CHAT.config, (action, key) -> {
if (MinecraftClient.getInstance().world == null) {
return true;
}
GuiBase.openGui(new AdvancedChatScreen(""));
return true;
});
InputHandler.getInstance().add("core_general", ConfigStorage.Hotkeys.OPEN_CHAT_WITH_LAST.config, (action, key) -> {
if (MinecraftClient.getInstance().world == null) {
return true;
}
GuiBase.openGui(new AdvancedChatScreen(0));
return true;
});
InputHandler.getInstance().add("core_general", ConfigStorage.Hotkeys.OPEN_CHAT_FREE_MOVEMENT.config, (action, key) -> {
if (MinecraftClient.getInstance().world == null) {
return true;
}
// Manually update stuff so that movement keys are continued to be pressed
MinecraftClient client = MinecraftClient.getInstance();
if (client.currentScreen != null) {
client.currentScreen.removed();
}
client.currentScreen = new AdvancedChatScreen(true);
client.mouse.unlockCursor();
client.currentScreen.init(client, client.getWindow().getScaledWidth(), client.getWindow().getScaledHeight());
client.skipGameRender = false;;
client.updateWindowTitle();
return true;
});
InputHandler.getInstance().add("core_general", ConfigStorage.Hotkeys.TOGGLE_PERMANENT.config, (action, key) -> {
AdvancedChatScreen.PERMANENT_FOCUS = !AdvancedChatScreen.PERMANENT_FOCUS;
InfoUtils.printActionbarMessage("advancedchatcore.message.togglepermanent");
return true;
});
InputHandler.getInstance().add("core_general", ConfigStorage.Hotkeys.OPEN_SETTINGS.config, (action, key) -> {
GuiBase.openGui(new GuiConfig());
return true;
});
ModuleHandler.getInstance().load();
InputEventHandler.getKeybindManager().registerKeybindProvider(InputHandler.getInstance());
InputEventHandler.getInputManager().registerKeyboardInputHandler(InputHandler.getInstance());
InputEventHandler.getInputManager().registerMouseInputHandler(InputHandler.getInstance());
List<TabSupplier> children = new ArrayList<>();
for (Map.Entry<String, List<ConfigHotkey>> hotkeys : InputHandler.getInstance().getHotkeys().entrySet()) {
List<IConfigBase> configs = hotkeys.getValue().stream().map(hotkey -> (IConfigBase) hotkey).toList();
children.add(GuiConfigHandler.wrapOptions(hotkeys.getKey(), InputHandler.getInstance().getDisplayName(hotkeys.getKey()), configs));
}
GuiConfigHandler.getInstance().addTab(
GuiConfigHandler.children(
"hotkeys",
"advancedchat.tab.hotkeys",
children.toArray(new TabSupplier[0])
)
);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\Module.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore;
import java.util.Collection;
import lombok.Value;
import net.fabricmc.loader.api.metadata.Person;
@Value
public class Module {
/** The Mod ID of the module */
String modId;
/** A {@link Collection} of {@link Person}'s */
Collection<Person> authors;
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\ModuleHandler.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import fi.dy.masa.malilib.interfaces.IInitializationHandler;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Value;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.fabricmc.loader.api.metadata.CustomValue;
public class ModuleHandler {
private static final ModuleHandler INSTANCE = new ModuleHandler();
@Getter private final List<Module> modules = new ArrayList<>();
private ModuleHandler() {}
private List<LoadOrder> toLoad = new ArrayList<>();
public static ModuleHandler getInstance() {
return INSTANCE;
}
public void registerModules() {
modules.clear();
for (ModContainer mod : FabricLoader.getInstance().getAllMods()) {
// Check if in "custom" it has "acmodule": true
CustomValue acData = mod.getMetadata().getCustomValue("acmodule");
if (acData == null) {
continue;
}
if (acData.getType() == CustomValue.CvType.BOOLEAN && acData.getAsBoolean()) {
// Add the module
modules.add(new Module(mod.getMetadata().getId(), mod.getMetadata().getAuthors()));
}
}
}
public void registerInitHandler(String name, int priority, IInitializationHandler handler) {
toLoad.add(new LoadOrder(name, priority, handler));
}
/** Do not call */
public void load() {
Collections.sort(toLoad);
for (LoadOrder load : toLoad) {
load.getHandler().registerModHandlers();
}
toLoad = null;
}
/**
* Retrieves a {@link Module} based off of a mod ID.
*
* <p>This is useful for incompatible features or enabling others.
*
* @param modID Mod id of the mod
* @return An optional containing the module if found.
*/
public Optional<Module> fromId(String modID) {
for (Module m : modules) {
if (m.getModId().equals(modID)) {
return Optional.of(m);
}
}
return Optional.empty();
}
@AllArgsConstructor
@Value
public static class LoadOrder implements Comparable<LoadOrder> {
String name;
Integer order;
IInitializationHandler handler;
@Override
public int compareTo(ModuleHandler.LoadOrder o) {
int compared = order.compareTo(o.order);
if (compared == 0) {
return name.compareTo(o.getName());
}
return compared;
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\chat\AdvancedChatScreen.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.chat;
import fi.dy.masa.malilib.gui.GuiBase;
import fi.dy.masa.malilib.gui.button.ButtonBase;
import fi.dy.masa.malilib.util.KeyCodes;
import io.github.darkkronicle.advancedchatcore.AdvancedChatCore;
import io.github.darkkronicle.advancedchatcore.config.ConfigStorage;
import io.github.darkkronicle.advancedchatcore.config.gui.GuiConfigHandler;
import io.github.darkkronicle.advancedchatcore.gui.IconButton;
import io.github.darkkronicle.advancedchatcore.interfaces.AdvancedChatScreenSection;
import io.github.darkkronicle.advancedchatcore.util.Color;
import io.github.darkkronicle.advancedchatcore.util.RowList;
import lombok.Getter;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.hud.ChatHud;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.MutableText;
import net.minecraft.text.Style;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.MathHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class AdvancedChatScreen extends GuiBase {
public static boolean PERMANENT_FOCUS = false;
private String finalHistory = "";
private int messageHistorySize = -1;
private int startHistory = -1;
private boolean passEvents = false;
/** Chat field at the bottom of the screen */
@Getter protected AdvancedTextField chatField;
/** What the chat box started out with */
@Getter private String originalChatText = "";
private static String last = "";
private final List<AdvancedChatScreenSection> sections = new ArrayList<>();
@Getter
private final RowList<ButtonBase> rightSideButtons = new RowList<>();
@Getter
private final RowList<ButtonBase> leftSideButtons = new RowList<>();
@Override
protected void closeGui(boolean showParent) {
if (ConfigStorage.ChatScreen.PERSISTENT_TEXT.config.getBooleanValue()) {
last = chatField.getText();
}
super.closeGui(showParent);
}
public AdvancedChatScreen() {
super();
setupSections();
}
public AdvancedChatScreen(boolean passEvents) {
this();
this.passEvents = passEvents;
}
public AdvancedChatScreen(int indexOfLast) {
this();
startHistory = indexOfLast;
}
public AdvancedChatScreen(String originalChatText) {
this();
this.originalChatText = originalChatText;
}
private void setupSections() {
for (Function<AdvancedChatScreen, AdvancedChatScreenSection> supplier : ChatScreenSectionHolder.getInstance().getSectionSuppliers()) {
AdvancedChatScreenSection section = supplier.apply(this);
if (section != null) {
sections.add(section);
}
}
}
private Color getColor() {
return ConfigStorage.ChatScreen.COLOR.config.get();
}
public void resetCurrentMessage() {
this.messageHistorySize = this.client.inGameHud.getChatHud().getMessageHistory().size();
}
@Override
public boolean charTyped(char charIn, int modifiers) {
if (passEvents) {
return true;
}
return super.charTyped(charIn, modifiers);
}
public void initGui() {
super.initGui();
this.rightSideButtons.clear();
this.leftSideButtons.clear();
resetCurrentMessage();
this.chatField =
new AdvancedTextField(
this.textRenderer,
4,
this.height - 12,
this.width - 10,
12,
Text.translatable("chat.editBox")) {
protected MutableText getNarrationMessage() {
return null;
}
};
if (ConfigStorage.ChatScreen.MORE_TEXT.config.getBooleanValue()) {
this.chatField.setMaxLength(64000);
} else {
this.chatField.setMaxLength(256);
}
this.chatField.setDrawsBackground(false);
if (!this.originalChatText.equals("")) {
this.chatField.setText(this.originalChatText);
} else if (ConfigStorage.ChatScreen.PERSISTENT_TEXT.config.getBooleanValue()
&& !last.equals("")) {
this.chatField.setText(last);
}
this.chatField.setChangedListener(this::onChatFieldUpdate);
// Add settings button
rightSideButtons.add("settings", new IconButton(0, 0, 14, 64, new Identifier(AdvancedChatCore.MOD_ID, "textures/gui/settings.png"), (button) -> GuiBase.openGui(GuiConfigHandler.getInstance().getDefaultScreen())));
this.addSelectableChild(this.chatField);
this.setInitialFocus(this.chatField);
for (AdvancedChatScreenSection section : sections) {
section.initGui();
}
int originalX = client.getWindow().getScaledWidth() - 1;
int y = client.getWindow().getScaledHeight() - 30;
for (int i = 0; i < rightSideButtons.rowSize(); i++) {
List<ButtonBase> buttonList = rightSideButtons.get(i);
int maxHeight = 0;
int x = originalX;
for (ButtonBase button : buttonList) {
maxHeight = Math.max(maxHeight, button.getHeight());
x -= button.getWidth() + 1;
button.setPosition(x, y);
addButton(button, null);
}
y -= maxHeight + 1;
}
originalX = 1;
y = client.getWindow().getScaledHeight() - 30;
for (int i = 0; i < leftSideButtons.rowSize(); i++) {
List<ButtonBase> buttonList = leftSideButtons.get(i);
int maxHeight = 0;
int x = originalX;
for (ButtonBase button : buttonList) {
maxHeight = Math.max(maxHeight, button.getHeight());
button.setPosition(x, y);
addButton(button, null);
x += button.getWidth() + 1;
}
y -= maxHeight + 1;
}
if (startHistory >= 0) {
setChatFromHistory(-startHistory - 1);
}
}
public void resize(MinecraftClient client, int width, int height) {
String string = this.chatField.getText();
this.init(client, width, height);
this.setText(string);
for (AdvancedChatScreenSection section : sections) {
section.resize(width, height);
}
}
@Override
public void removed() {
for (AdvancedChatScreenSection section : sections) {
section.removed();
}
}
public void tick() {
this.chatField.tick();
}
private void onChatFieldUpdate(String chatText) {
String string = this.chatField.getText();
for (AdvancedChatScreenSection section : sections) {
section.onChatFieldUpdate(chatText, string);
}
}
@Override
public boolean keyReleased(int keyCode, int scanCode, int modifiers) {
if (passEvents) {
InputUtil.Key key = InputUtil.fromKeyCode(keyCode, scanCode);
KeyBinding.setKeyPressed(key, false);
}
return false;
}
public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
if (!passEvents) {
for (AdvancedChatScreenSection section : sections) {
if (section.keyPressed(keyCode, scanCode, modifiers)) {
return true;
}
}
if (super.keyPressed(keyCode, scanCode, modifiers)) {
return true;
}
}
if (keyCode == KeyCodes.KEY_ESCAPE) {
// Exit out
GuiBase.openGui(null);
return true;
}
if (keyCode == KeyCodes.KEY_ENTER || keyCode == KeyCodes.KEY_KP_ENTER) {
String string = this.chatField.getText().trim();
// Strip message and send
MessageSender.getInstance().sendMessage(string);
this.chatField.setText("");
last = "";
// Exit
GuiBase.openGui(null);
return true;
}
if (keyCode == KeyCodes.KEY_UP) {
// Go through previous history
this.setChatFromHistory(-1);
return true;
}
if (keyCode == KeyCodes.KEY_DOWN) {
// Go through previous history
this.setChatFromHistory(1);
return true;
}
if (keyCode == KeyCodes.KEY_PAGE_UP) {
// Scroll
client.inGameHud
.getChatHud()
.scroll(this.client.inGameHud.getChatHud().getVisibleLineCount() - 1);
return true;
}
if (keyCode == KeyCodes.KEY_PAGE_DOWN) {
// Scroll
client.inGameHud
.getChatHud()
.scroll(-this.client.inGameHud.getChatHud().getVisibleLineCount() + 1);
return true;
}
if (passEvents) {
this.chatField.setText("");
InputUtil.Key key = InputUtil.fromKeyCode(keyCode, scanCode);
KeyBinding.setKeyPressed(key, true);
KeyBinding.onKeyPressed(key);
return true;
}
return false;
}
public boolean mouseScrolled(double mouseX, double mouseY, double amount) {
if (amount > 1.0D) {
amount = 1.0D;
}
if (amount < -1.0D) {
amount = -1.0D;
}
for (AdvancedChatScreenSection section : sections) {
if (section.mouseScrolled(mouseX, mouseY, amount)) {
return true;
}
}
if (!hasShiftDown()) {
amount *= 7.0D;
}
// Send to hud to scroll
client.inGameHud.getChatHud().scroll((int) amount);
return true;
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
for (AdvancedChatScreenSection section : sections) {
if (section.mouseClicked(mouseX, mouseY, button)) {
return true;
}
}
ChatHud hud = client.inGameHud.getChatHud();
if (hud.mouseClicked(mouseX, mouseY)) {
return true;
}
Style style = hud.getTextStyleAt(mouseX, mouseY);
if (style != null && style.getClickEvent() != null) {
if (this.handleTextClick(style)) {
return true;
}
}
return (this.chatField.mouseClicked(mouseX, mouseY, button)
|| super.mouseClicked(mouseX, mouseY, button));
}
@Override
public boolean mouseReleased(double mouseX, double mouseY, int mouseButton) {
for (AdvancedChatScreenSection section : sections) {
if (section.mouseReleased(mouseX, mouseY, mouseButton)) {
return true;
}
}
return super.mouseReleased(mouseX, mouseY, mouseButton);
}
@Override
public boolean mouseDragged(
double mouseX, double mouseY, int button, double deltaX, double deltaY) {
for (AdvancedChatScreenSection section : sections) {
if (section.mouseDragged(mouseX, mouseY, button, deltaX, deltaY)) {
return true;
}
}
return super.mouseDragged(mouseX, mouseY, button, deltaX, deltaY);
}
@Override
protected void insertText(String text, boolean override) {
if (override) {
this.chatField.setText(text);
} else {
this.chatField.write(text);
}
}
public void setChatFromHistory(int i) {
int targetIndex = this.messageHistorySize + i;
int maxIndex = this.client.inGameHud.getChatHud().getMessageHistory().size();
targetIndex = MathHelper.clamp(targetIndex, 0, maxIndex);
if (targetIndex != this.messageHistorySize) {
if (targetIndex == maxIndex) {
this.messageHistorySize = maxIndex;
this.chatField.setText(this.finalHistory);
} else {
if (this.messageHistorySize == maxIndex) {
this.finalHistory = this.chatField.getText();
}
String hist = this.client.inGameHud.getChatHud().getMessageHistory().get(targetIndex);
this.chatField.setText(hist);
for (AdvancedChatScreenSection section : sections) {
section.setChatFromHistory(hist);
}
this.messageHistorySize = targetIndex;
}
}
}
@Override
public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
ChatHud hud = client.inGameHud.getChatHud();
this.setFocused(this.chatField);
this.chatField.setFocused(true);
this.chatField.render(matrixStack, mouseX, mouseY, partialTicks);
super.render(matrixStack, mouseX, mouseY, partialTicks);
for (AdvancedChatScreenSection section : sections) {
section.render(matrixStack, mouseX, mouseY, partialTicks);
}
Style style = hud.getTextStyleAt(mouseX, mouseY);
if (style != null && style.getHoverEvent() != null) {
this.renderTextHoverEffect(matrixStack, style, mouseX, mouseY);
}
}
@Override
protected void drawScreenBackground(int mouseX, int mouseY) {
}
private void setText(String text) {
this.chatField.setText(text);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\chat\AdvancedSleepingChatScreen.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.chat;
import fi.dy.masa.malilib.gui.GuiBase;
import fi.dy.masa.malilib.gui.button.ButtonGeneric;
import fi.dy.masa.malilib.util.KeyCodes;
import fi.dy.masa.malilib.util.StringUtils;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.network.packet.c2s.play.ClientCommandC2SPacket;
public class AdvancedSleepingChatScreen extends AdvancedChatScreen {
public AdvancedSleepingChatScreen() {
super("");
}
public void initGui() {
super.initGui();
ButtonGeneric stopSleep =
new ButtonGeneric(
this.width / 2 - 100,
this.height - 40,
200,
20,
StringUtils.translate("multiplayer.stopSleeping"));
this.addButton(stopSleep, (button, mouseButton) -> stopSleeping());
}
public void onClose() {
this.stopSleeping();
}
public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
if (keyCode == KeyCodes.KEY_ESCAPE) {
this.stopSleeping();
} else if (keyCode == KeyCodes.KEY_ENTER || keyCode == KeyCodes.KEY_KP_ENTER) {
String string = this.chatField.getText().trim();
if (!string.isEmpty()) {
MessageSender.getInstance().sendMessage(string);
}
this.chatField.setText("");
this.client.inGameHud.getChatHud().resetScroll();
// Prevents really weird interactions with chat history
resetCurrentMessage();
return true;
}
return super.keyPressed(keyCode, scanCode, modifiers);
}
private void stopSleeping() {
ClientPlayNetworkHandler clientPlayNetworkHandler = this.client.player.networkHandler;
clientPlayNetworkHandler.sendPacket(
new ClientCommandC2SPacket(
this.client.player, ClientCommandC2SPacket.Mode.STOP_SLEEPING));
GuiBase.openGui(null);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.