The Mergening (#13)

* ThreadedTessellator -> RenderBlocks instance Tessellator
* Plus a CME workaround until I can figure out why it's happening
* One inject with multiple methods instead of two injects
* Add AF's Tessellator#reset mixin
Fixes screen flashing when chunks are being built
* Thread Saftey
* Make each tesselator use its own ByteBuffer
* Don't make RecyclingList a static variable 🤦
* Add some additions via ITessellatorInstance
* Stop using builtin updateRenderers
* Remove a few unused things in MixinTessellator
* Remove useless casting due to implementing the interface
* Overwrite some more rendering methods to ensure they're not used
* Implement IBlockAccess on WorldSlice
* Currently just proxies to the World... need to get it to use the local cache
* Make WorldSlice use its copied values instead of using the world
* block, meta, and light.  Still need TODO biome
* Finish making WorldSlice thread safe
* Remove last unsafe this.world accesses
* Copy biomeData
* Implement getTileEntity(), and getBiomeGenForCoords()
* Remove unused 1.16+ classes - Biome, Colorizer, and ColorBlender related
* Cache worldHeight instead of asking the provider every time
* Debug Screen updates
* Disable Culling for now (until it works)
* Tessellator Updates
* Use one instance on the main thread, and individual instances on every other thread
* Prevent draw() and buffer.reset() on non singleton instance
* Misc cleanup, maybe better growBuffer?
* Fixing splash screen and GUI issues by excluding SplashProgress from GLStateManager transformer
* Update docs
* Fixing a one line in SodiumWorldRenderer that allows the game setting for the distance at which entities will render. Hope it's not too bad mitch :)
* TileEntites now render
* Less silly transparency
* Removing clamp implementation because I missed the one in mathhelper
* Initial sodium entity smooth lighting
* Fix entity smooth lighting
* Fix lerp uses and use render layers properly (#17)
* Remove some uses of blockstate + patch FluidState
* Fix lerp
* Enable Sodium fluid rendering
* Update FluidRenderer.java
* Rewind buffers when copying
* Fix multidraw
* Force cutout on all non-translucent blocks
* Let vanilla handle render pass state
* Rewrite render layer check to use Forge 1.7 hook
* Fix skylight handling
* Fix flickering
* Clone TEs correctly
* Fixing entityDistMulti (I think)
* Fix TEs rendering on the wrong pass
* Buff max render distance to 32
Pretty useless since the integrated server stalls instantly, but our renderer supports it
* Fix fog
* Fix render distance changes being ignored
* Implement entity culling
* Block face culling
* Re-enable occlusion culling
* Fix x/z coordinate mixup when indexing biome arrays
Partially fixes wrong biome colors, but at chunk edges it's still wrong because
neighboring chunks aren't accessed
* Make a copy of biome data
The old code seemed to work fine but this should be safer
* Make CompatMemoryUtil#memReallocDirect preserve buffer position
LWJGL3's MemoryUtil#memRealloc does this, see its javadoc.
Fixes screen flashing and this error getting printed when indirect buffer grows:
GL_INVALID_OPERATION error generated. Bound draw indirect buffer is not large enough.
* Use biome data of neighboring chunk sections
Fixes wrong colors at chunk edges
* Re-enable fog culling
* Tile entity culling
* Remove some unneeded Sodium code
* Massive code cleanup
* Avoids errors when usin lwjglxdebug
* Bump hodgepodge dep
* Add AngelicaConfig
* Add Mixin to disable MC's builtin checkGLError
* Add configs for iris/sodium
* Iris work
* Move some StateNotifiers to GLStateManager
* Remove some redundant mixins based on sodium/angelica work and rendering state captures
* Add Iris DebugScreenHandler
* rm archaicfix's occlusion renderer and threaded updates
* Implemented Sodium's GUI and a couple of setting fixes (#20)
* Ported Sodium's GUI
* Correct AO
* Fixed Vignette
* Re-enable DirectMemoryAccess
* Adds some code from lwjgl3 in CompatMemoryUtil.java
* Re-add *Unsafe classes
* Remove MixinWorldRenderer
* Add NEID (mixin pr) support
* Only shadow runtime module of antlr4
Reduces jar size by 11 mb
* Update NotFine
* Make LongHashMap actually perform like a hash map
* Options GUI Fixes and some option implementations (#22)
* Correct useNoErrorGLContext option
* Added translucency sorting option
* Implemented Particle Culling
gives real fps boost, however, it's not as big as i thought

* Begin implementing animateOnlyVisibleTextures
* Correct Donation page opening
* Fixed Shift + P
Now it uses NotFine's GUI, but it think that NotFine's GUI should be rewrited for using other config options
* Correct URL's for Linux
* second code cleanup in particle culling
* Fix incorrect TE map population
* Add optional assertMainThread behind `-Dangelica.assertMainThread=true`
* Add back air optimization, but only apply to vanilla air
* Implement more options (#23)
* Combine free regions in GlBufferArena
* Clear global block entity list when initializing renderer
* AF, CompileStubs, and SplashProgress
Remove most of ArchaicFix
* Move a few mixins over to angelica
* Disable if org.lwjgl.util.Debug is set
* Only enable Iris/lwjgl debug callbacks if org.lwjgl.util.Debug is set
* Rewrite Tessellator hacks - now using a ThreadLocal instead of only patching RenderBlocks
* Reenable AF mixins, switch to cached debug var, disable incompatible mixins
* Remove AF deps and a late mixin that was missed
* Add Iris Sodium Compat impl
* Fix Sodium GLProgram to use ResourceLocation instead of Identifier
* Start applying Iris -> Sodium Mixins
* Make NotFine menu open if holding shift
* Fixed Tessellators in production env
* Finish Sodium Fluid Renderer (#24)
* Init and pass Sodium LightPipelines
* Remove registry lookup and refactor WorldUtil
* Hook up lighting pipeline
* Patch fluid velocity
* It's alive! Sodium Fluid Renderer is alive!
* Fix face culling not taking third person camera offset into account
* rewrite ACTEntityRenderer to stop transforming ALL the classes
* use ClassConstantPoolParser in TessellatorTransformer to speed up search for Tessellator references
* use ClassConstantPoolParser in GLStateManagerTransformer to speed up search for class references
* rewrite GLStateManagerTransformer and TessellatorTransformer
* merge GLStateManagerTransfor and TessellatorTransformer into one Transformer
* Fixed smooth lighting rendering
* Iris block_id Mixins & BlockStateIdMap initial impl for 1.7.10
* Fix running with lwjgl debug flag & Cleanup old ShadersMod transformers
* Initialize GLStateManager via Mixins instead of all in the static block
* Clean up chunk load/unload tracking, fix chunks rendering without neighbors sometimes
* Fix occlusion culler not re-running after important uploads

Backport of https://github.com/CaffeineMC/sodium-fabric/pull/755

* Add chunks to queues without going through occlusion culler

Partially reverts the previous chunk tracking commit, because
that logic will reintroduce https://github.com/CaffeineMC/sodium-fabric/issues/605

As long as we only rebuild with neighbors present, we shouldn't
see the visual seams
* Extremely primitive synchronization approach for ISBRH
* Use factory for Spdium menu createElement outputs
This will allow NotFine to use Sodium menu elements and vice versa in a future commit.
* Splash Screen Compat
* Separate remaining NamedState enums
* NotFine but it loads Sodium pages
* Hook up NotFine optimizations
* Hook up some NotFine features
* copy over hud caching code from hodgepodge
* backport glstatemanager mixin
* Track thread that currently owns the GL Context in addition to the main thread.
* First pass over FontRenderer, 1300->1400 FPS on my GPU when showing F3
Done:
 - A batching vertex buffer builder for font output
 - Reduction in drawcalls from 1-3 per character to 1 per font atlas switch
 - Mixin to draw the entire F3 screen in one batch, instead of separate batches per line
TODO:
 - Switch drawing to a VBO
 - Cache string meshes across frames
 - Cache string width calculations used for layouts
 - Multidraw to reduce draw calls even further
* Add JVM flag to bypass GL state caching
* Push/Pop Attrib Hacks -- to be evolved later
* Fix FontRenderer+SplashScreen combo
* HUDCaching tweaks
* Add license
* Jabba Compat, and reset tesselator state even if the chunk render thread blows up
* Initial Xaero's World Map + Minimap Support
* Disable Fastcraft & Optifine if present
* Iris Progress
* Wire up more Iris mixins, informing pipeline stages.  Still not rendering anything visible.
* Don't try to transform the server
* Avoid running biome generator on client in singleplayer
* Call world biome retrieval methods instead of copying array directly (#25)
* Shaders now do something!
* Shadow Pass work
* First shadow pass renders; however it moves all around when moving the camera...
* Second shadow pass not running because it makes everything very very dark instead of just rendering translucents
* Actually use the ShadowRenderer Model View when running the shadow pass...
* Enable Sodium SmoothLightPipeline & Iris useSeparateAo
* Avoid repeatedly copying biome data on each Y level (#27)
* Celestial Rotation fixes
* Water progress
* Uniforms audit
* Lightmap workaround
* PBR compiling, stuck on Normal and Specular textures being added in
* Shaderpack selection "works"; ShaderOptions TODO
* Hud caching angelica (#28)
* Potential hud-caching fix
* Shader Options almost working
** Clicking on everything doesn't yet work, and the visuals are slightly off
* Entity shadows seem to be working
* Move glint fix to Mixin
* Rework mouse handling for ShaderPackConfig
* Stop centering shader options vertically
* Angelica pbr (#31)
* Only use Sodium light pipeline if useSeparateAo is on
Sodium pipeline is still very buggy, so isolate it to Iris-only
for now
* Fix region sorting for translucency
* Open Shaderpack now works on Linux
* RM Shadersmod
* Initial iris scrollbar clicking
* Punt unsupported ISBRHs to the main thread
* Delete the ISBRH lock, shouldn't be needed anymore
* Render GT blocks on main thread
* Require CCC 1.2.0+
* Depend on CCC 1.2
* Fix TESRs not being tracked for blocks rendered on main thread
* Cut down number of runtime dependencies, enable CoreTweaks in dev by default
* Add modern F3 background
* Pull over some hodgepodge mixins


---------

Co-authored-by: makamys <[email protected]>
Co-authored-by: embeddedt <[email protected]>
Co-authored-by: rjnasers <[email protected]>
Co-authored-by: ah-OOG-ah <[email protected]>
Co-authored-by: Ryan Nasers <[email protected]>
Co-authored-by: Rad <[email protected]>
Co-authored-by: Bogdan <[email protected]>
Co-authored-by: Caedis <[email protected]>
Co-authored-by: jss2a98aj <[email protected]>
Co-authored-by: Alexdoru <[email protected]>
Co-authored-by: Raven Szewczyk <[email protected]>
Co-authored-by: mist475 <[email protected]>
Co-authored-by: Ryan Nasers <[email protected]>
This commit is contained in:
942 files changed
+65828 -8640

No files matched your search

@@ -0,0 +1,95 @@
package net.coderbot.iris.gl.program;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.GlResource;
import net.coderbot.iris.gl.IrisRenderSystem;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import org.joml.Vector2f;
import org.joml.Vector3i;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL43;
import java.nio.IntBuffer;
public final class ComputeProgram extends GlResource {
private final ProgramUniforms uniforms;
private final ProgramSamplers samplers;
private final ProgramImages images;
private Vector3i absoluteWorkGroups;
private Vector2f relativeWorkGroups;
// private int[] localSize;
private IntBuffer localSizeBuffer;
private float cachedWidth;
private float cachedHeight;
private Vector3i cachedWorkGroups;
ComputeProgram(int program, ProgramUniforms uniforms, ProgramSamplers samplers, ProgramImages images) {
super(program);
localSizeBuffer = BufferUtils.createIntBuffer(3);
// localSize = new int[3];
IrisRenderSystem.getProgramiv(program, GL43.GL_COMPUTE_WORK_GROUP_SIZE, localSizeBuffer);
this.uniforms = uniforms;
this.samplers = samplers;
this.images = images;
}
public void setWorkGroupInfo(Vector2f relativeWorkGroups, Vector3i absoluteWorkGroups) {
this.relativeWorkGroups = relativeWorkGroups;
this.absoluteWorkGroups = absoluteWorkGroups;
}
public Vector3i getWorkGroups(float width, float height) {
if (cachedWidth != width || cachedHeight != height || cachedWorkGroups == null) {
this.cachedWidth = width;
this.cachedHeight = height;
if (this.absoluteWorkGroups != null) {
this.cachedWorkGroups = this.absoluteWorkGroups;
} else if (relativeWorkGroups != null) {
// TODO: This is my best guess at what Optifine does. Can this be confirmed?
// Do not use actual localSize here, apparently that's not what we want.
this.cachedWorkGroups = new Vector3i((int) Math.ceil(Math.ceil((width * relativeWorkGroups.x)) / localSizeBuffer.get(0)), (int) Math.ceil(Math.ceil((height * relativeWorkGroups.y)) / localSizeBuffer.get(1)), 1);
} else {
this.cachedWorkGroups = new Vector3i((int) Math.ceil(width / localSizeBuffer.get(0)), (int) Math.ceil(height / localSizeBuffer.get(1)), 1);
}
}
return cachedWorkGroups;
}
public void dispatch(float width, float height) {
GL20.glUseProgram(getGlId());
uniforms.update();
samplers.update();
images.update();
if (!Iris.getPipelineManager().getPipeline().map(WorldRenderingPipeline::allowConcurrentCompute).orElse(false)) {
IrisRenderSystem.memoryBarrier(40);
}
IrisRenderSystem.dispatchCompute(getWorkGroups(width, height));
}
public static void unbind() {
ProgramUniforms.clearActiveUniforms();
GL20.glUseProgram(0);
}
public void destroyInternal() {
GL20.glDeleteProgram(getGlId());
}
/**
* @return the OpenGL ID of this program.
* @deprecated this should be encapsulated eventually
*/
@Deprecated
public int getProgramId() {
return getGlId();
}
public int getActiveImages() {
return images.getActiveImages();
}
}
@@ -0,0 +1,19 @@
package net.coderbot.iris.gl.program;
public class GlUniform1iCall {
private final int location;
private final int value;
public GlUniform1iCall(int location, int value) {
this.location = location;
this.value = value;
}
public int getLocation() {
return location;
}
public int getValue() {
return value;
}
}
@@ -0,0 +1,49 @@
package net.coderbot.iris.gl.program;
import net.coderbot.iris.gl.GlResource;
import org.lwjgl.opengl.GL20;
public final class Program extends GlResource {
private final ProgramUniforms uniforms;
private final ProgramSamplers samplers;
private final ProgramImages images;
Program(int program, ProgramUniforms uniforms, ProgramSamplers samplers, ProgramImages images) {
super(program);
this.uniforms = uniforms;
this.samplers = samplers;
this.images = images;
}
public void use() {
GL20.glUseProgram(getGlId());
uniforms.update();
samplers.update();
images.update();
}
public static void unbind() {
ProgramUniforms.clearActiveUniforms();
ProgramSamplers.clearActiveSamplers();
GL20.glUseProgram(0);
}
public void destroyInternal() {
GL20.glDeleteProgram(getGlId());
}
/**
* @return the OpenGL ID of this program.
* @deprecated this should be encapsulated eventually
*/
@Deprecated
public int getProgramId() {
return getGlId();
}
public int getActiveImages() {
return images.getActiveImages();
}
}
@@ -0,0 +1,131 @@
package net.coderbot.iris.gl.program;
import com.google.common.collect.ImmutableSet;
import net.coderbot.iris.gl.IrisRenderSystem;
import net.coderbot.iris.gl.image.ImageHolder;
import net.coderbot.iris.gl.sampler.SamplerHolder;
import net.coderbot.iris.gl.shader.GlShader;
import net.coderbot.iris.gl.shader.ProgramCreator;
import net.coderbot.iris.gl.shader.ShaderType;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import net.coderbot.iris.gl.texture.InternalTextureFormat;
import org.jetbrains.annotations.Nullable;
import java.util.function.IntSupplier;
public class ProgramBuilder extends ProgramUniforms.Builder implements SamplerHolder, ImageHolder {
private final int program;
private final ProgramSamplers.Builder samplers;
private final ProgramImages.Builder images;
private ProgramBuilder(String name, int program, ImmutableSet<Integer> reservedTextureUnits) {
super(name, program);
this.program = program;
this.samplers = ProgramSamplers.builder(program, reservedTextureUnits);
this.images = ProgramImages.builder(program);
}
public void bindAttributeLocation(int index, String name) {
IrisRenderSystem.bindAttributeLocation(program, index, name);
}
public static ProgramBuilder begin(String name, @Nullable String vertexSource, @Nullable String geometrySource,
@Nullable String fragmentSource, ImmutableSet<Integer> reservedTextureUnits) {
GlShader vertex;
GlShader geometry;
GlShader fragment;
vertex = buildShader(ShaderType.VERTEX, name + ".vsh", vertexSource);
if (geometrySource != null) {
geometry = buildShader(ShaderType.GEOMETRY, name + ".gsh", geometrySource);
} else {
geometry = null;
}
fragment = buildShader(ShaderType.FRAGMENT, name + ".fsh", fragmentSource);
int programId;
if (geometry != null) {
programId = ProgramCreator.create(name, vertex, geometry, fragment);
} else {
programId = ProgramCreator.create(name, vertex, fragment);
}
vertex.destroy();
if (geometry != null) {
geometry.destroy();
}
fragment.destroy();
return new ProgramBuilder(name, programId, reservedTextureUnits);
}
public static ProgramBuilder beginCompute(String name, @Nullable String source, ImmutableSet<Integer> reservedTextureUnits) {
if (!IrisRenderSystem.supportsCompute()) {
throw new IllegalStateException("This PC does not support compute shaders, but it's attempting to be used???");
}
GlShader compute = buildShader(ShaderType.COMPUTE, name + ".csh", source);
int programId = ProgramCreator.create(name, compute);
compute.destroy();
return new ProgramBuilder(name, programId, reservedTextureUnits);
}
public Program build() {
return new Program(program, super.buildUniforms(), this.samplers.build(), this.images.build());
}
public ComputeProgram buildCompute() {
return new ComputeProgram(program, super.buildUniforms(), this.samplers.build(), this.images.build());
}
private static GlShader buildShader(ShaderType shaderType, String name, @Nullable String source) {
try {
return new GlShader(shaderType, name, source);
} catch (RuntimeException e) {
throw new RuntimeException("Failed to compile " + shaderType + " shader for program " + name, e);
}
}
@Override
public void addExternalSampler(int textureUnit, String... names) {
samplers.addExternalSampler(textureUnit, names);
}
@Override
public boolean hasSampler(String name) {
return samplers.hasSampler(name);
}
@Override
public boolean addDefaultSampler(IntSupplier sampler, String... names) {
return samplers.addDefaultSampler(sampler, names);
}
@Override
public boolean addDynamicSampler(IntSupplier sampler, String... names) {
return samplers.addDynamicSampler(sampler, names);
}
public boolean addDynamicSampler(IntSupplier sampler, ValueUpdateNotifier notifier, String... names) {
return samplers.addDynamicSampler(sampler, notifier, names);
}
@Override
public boolean hasImage(String name) {
return images.hasImage(name);
}
@Override
public void addTextureImage(IntSupplier textureID, InternalTextureFormat internalFormat, String name) {
images.addTextureImage(textureID, internalFormat, name);
}
}
@@ -0,0 +1,99 @@
package net.coderbot.iris.gl.program;
import com.google.common.collect.ImmutableList;
import net.coderbot.iris.gl.IrisRenderSystem;
import net.coderbot.iris.gl.image.ImageBinding;
import net.coderbot.iris.gl.image.ImageHolder;
import net.coderbot.iris.gl.image.ImageLimits;
import net.coderbot.iris.gl.texture.InternalTextureFormat;
import org.lwjgl.opengl.GL20;
import java.util.ArrayList;
import java.util.List;
import java.util.function.IntSupplier;
public class ProgramImages {
private final ImmutableList<ImageBinding> imageBindings;
private List<GlUniform1iCall> initializer;
private ProgramImages(ImmutableList<ImageBinding> imageBindings, List<GlUniform1iCall> initializer) {
this.imageBindings = imageBindings;
this.initializer = initializer;
}
public void update() {
if (initializer != null) {
for (GlUniform1iCall call : initializer) {
IrisRenderSystem.uniform1i(call.getLocation(), call.getValue());
}
initializer = null;
}
for (ImageBinding imageBinding : imageBindings) {
imageBinding.update();
}
}
public int getActiveImages() {
return imageBindings.size();
}
public static Builder builder(int program) {
return new Builder(program);
}
public static final class Builder implements ImageHolder {
private final int program;
private final ImmutableList.Builder<ImageBinding> images;
private final List<GlUniform1iCall> calls;
private int nextImageUnit;
private final int maxImageUnits;
private Builder(int program) {
this.program = program;
this.images = ImmutableList.builder();
this.calls = new ArrayList<>();
this.nextImageUnit = 0;
this.maxImageUnits = ImageLimits.get().getMaxImageUnits();
}
@Override
public boolean hasImage(String name) {
return GL20.glGetUniformLocation(program, name) != -1;
}
@Override
public void addTextureImage(IntSupplier textureID, InternalTextureFormat internalFormat, String name) {
int location = GL20.glGetUniformLocation(program, name);
if (location == -1) {
return;
}
if (nextImageUnit >= maxImageUnits) {
if (maxImageUnits == 0) {
throw new IllegalStateException("Image units are not supported on this platform, but a shader" +
" program attempted to reference " + name + ".");
} else {
throw new IllegalStateException("No more available texture units while activating image " + name + "." +
" Only " + maxImageUnits + " image units are available.");
}
}
if (internalFormat == InternalTextureFormat.RGBA) {
// Internal detail of Optifine: Set RGBA8 if RGBA is selected, as RGBA is not valid for images.
internalFormat = InternalTextureFormat.RGBA8;
}
images.add(new ImageBinding(nextImageUnit, internalFormat.getGlFormat(), textureID));
calls.add(new GlUniform1iCall(location, nextImageUnit));
nextImageUnit += 1;
}
public ProgramImages build() {
return new ProgramImages(images.build(), calls);
}
}
}
@@ -0,0 +1,295 @@
package net.coderbot.iris.gl.program;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.gl.IrisRenderSystem;
import net.coderbot.iris.gl.sampler.SamplerBinding;
import net.coderbot.iris.gl.sampler.SamplerHolder;
import net.coderbot.iris.gl.sampler.SamplerLimits;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import net.coderbot.iris.shaderpack.PackRenderTargetDirectives;
import org.lwjgl.opengl.GL13;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.IntSupplier;
public class ProgramSamplers {
private static ProgramSamplers active;
private final ImmutableList<SamplerBinding> samplerBindings;
private final ImmutableList<ValueUpdateNotifier> notifiersToReset;
private List<GlUniform1iCall> initializer;
private ProgramSamplers(ImmutableList<SamplerBinding> samplerBindings, ImmutableList<ValueUpdateNotifier> notifiersToReset, List<GlUniform1iCall> initializer) {
this.samplerBindings = samplerBindings;
this.notifiersToReset = notifiersToReset;
this.initializer = initializer;
}
public void update() {
if (active != null) {
active.removeListeners();
}
active = this;
if (initializer != null) {
for (GlUniform1iCall call : initializer) {
IrisRenderSystem.uniform1i(call.getLocation(), call.getValue());
}
initializer = null;
}
// We need to keep the active texture intact, since if we mess it up
// in the middle of RenderType setup, bad things will happen.
int activeTexture = GLStateManager.getActiveTexture();
for (SamplerBinding samplerBinding : samplerBindings) {
samplerBinding.update();
}
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + activeTexture);
}
public void removeListeners() {
active = null;
for (ValueUpdateNotifier notifier : notifiersToReset) {
notifier.setListener(null);
}
}
public static void clearActiveSamplers() {
if (active != null) {
active.removeListeners();
}
}
public static Builder builder(int program, Set<Integer> reservedTextureUnits) {
return new Builder(program, reservedTextureUnits);
}
public static CustomTextureSamplerInterceptor customTextureSamplerInterceptor(SamplerHolder samplerHolder, Object2ObjectMap<String, IntSupplier> customTextureIds) {
return customTextureSamplerInterceptor(samplerHolder, customTextureIds, ImmutableSet.of());
}
public static CustomTextureSamplerInterceptor customTextureSamplerInterceptor(SamplerHolder samplerHolder, Object2ObjectMap<String, IntSupplier> customTextureIds, ImmutableSet<Integer> flippedAtLeastOnceSnapshot) {
return new CustomTextureSamplerInterceptor(samplerHolder, customTextureIds, flippedAtLeastOnceSnapshot);
}
public static final class Builder implements SamplerHolder {
private final int program;
private final ImmutableSet<Integer> reservedTextureUnits;
private final ImmutableList.Builder<SamplerBinding> samplers;
private final ImmutableList.Builder<ValueUpdateNotifier> notifiersToReset;
private final List<GlUniform1iCall> calls;
private int remainingUnits;
private int nextUnit;
private Builder(int program, Set<Integer> reservedTextureUnits) {
this.program = program;
this.reservedTextureUnits = ImmutableSet.copyOf(reservedTextureUnits);
this.samplers = ImmutableList.builder();
this.notifiersToReset = ImmutableList.builder();
this.calls = new ArrayList<>();
int maxTextureUnits = SamplerLimits.get().getMaxTextureUnits();
for (int unit : reservedTextureUnits) {
if (unit >= maxTextureUnits) {
throw new IllegalStateException("Cannot mark texture unit " + unit + " as reserved because that " +
"texture unit isn't available on this system! Only " + maxTextureUnits +
" texture units are available.");
}
}
this.remainingUnits = maxTextureUnits - reservedTextureUnits.size();
this.nextUnit = 0;
while (reservedTextureUnits.contains(nextUnit)) {
nextUnit += 1;
}
//System.out.println("Begin building samplers. Reserved texture units are " + reservedTextureUnits +
// ", next texture unit is " + nextUnit + ", there are " + remainingUnits + " units remaining.");
}
@Override
public void addExternalSampler(int textureUnit, String... names) {
if (!reservedTextureUnits.contains(textureUnit)) {
throw new IllegalArgumentException("Cannot add an externally-managed sampler for texture unit " +
textureUnit + " since it isn't in the set of reserved texture units.");
}
for (String name : names) {
int location = IrisRenderSystem.getUniformLocation(program, name);
if (location == -1) {
// There's no active sampler with this particular name in the program.
continue;
}
// Set up this sampler uniform to use this particular texture unit.
//System.out.println("Binding external sampler " + name + " to texture unit " + textureUnit);
calls.add(new GlUniform1iCall(location, textureUnit));
}
}
@Override
public boolean hasSampler(String name) {
return IrisRenderSystem.getUniformLocation(program, name) != -1;
}
@Override
public boolean addDefaultSampler(IntSupplier sampler, String... names) {
if (nextUnit != 0) {
// TODO: Relax this restriction!
throw new IllegalStateException("Texture unit 0 is already used.");
}
return addDynamicSampler(sampler, true, null, names);
}
/**
* Adds a sampler
* @return false if this sampler is not active, true if at least one of the names referred to an active sampler
*/
@Override
public boolean addDynamicSampler(IntSupplier sampler, String... names) {
return addDynamicSampler(sampler, false, null, names);
}
/**
* Adds a sampler
* @return false if this sampler is not active, true if at least one of the names referred to an active sampler
*/
@Override
public boolean addDynamicSampler(IntSupplier sampler, ValueUpdateNotifier notifier, String... names) {
notifiersToReset.add(notifier);
return addDynamicSampler(sampler, false, notifier, names);
}
private boolean addDynamicSampler(IntSupplier sampler, boolean used, ValueUpdateNotifier notifier, String... names) {
for (String name : names) {
int location = IrisRenderSystem.getUniformLocation(program, name);
if (location == -1) {
// There's no active sampler with this particular name in the program.
continue;
}
// Make sure that we aren't out of texture units.
if (remainingUnits <= 0) {
throw new IllegalStateException("No more available texture units while activating sampler " + name);
}
//System.out.println("Binding dynamic sampler " + name + " to texture unit " + nextUnit);
// Set up this sampler uniform to use this particular texture unit.
calls.add(new GlUniform1iCall(location, nextUnit));
// And mark this texture unit as used.
used = true;
}
if (!used) {
return false;
}
samplers.add(new SamplerBinding(nextUnit, sampler, notifier));
remainingUnits -= 1;
nextUnit += 1;
while (remainingUnits > 0 && reservedTextureUnits.contains(nextUnit)) {
nextUnit += 1;
}
//System.out.println("The next unit is " + nextUnit + ", there are " + remainingUnits + " units remaining.");
return true;
}
public ProgramSamplers build() {
return new ProgramSamplers(samplers.build(), notifiersToReset.build(), calls);
}
}
public static final class CustomTextureSamplerInterceptor implements SamplerHolder {
private final SamplerHolder samplerHolder;
private final Object2ObjectMap<String, IntSupplier> customTextureIds;
private final ImmutableSet<String> deactivatedOverrides;
private CustomTextureSamplerInterceptor(SamplerHolder samplerHolder, Object2ObjectMap<String, IntSupplier> customTextureIds, ImmutableSet<Integer> flippedAtLeastOnceSnapshot) {
this.samplerHolder = samplerHolder;
this.customTextureIds = customTextureIds;
ImmutableSet.Builder<String> deactivatedOverrides = new ImmutableSet.Builder<>();
for (int deactivatedOverride : flippedAtLeastOnceSnapshot) {
deactivatedOverrides.add("colortex" + deactivatedOverride);
if (deactivatedOverride < PackRenderTargetDirectives.LEGACY_RENDER_TARGETS.size()) {
deactivatedOverrides.add(PackRenderTargetDirectives.LEGACY_RENDER_TARGETS.get(deactivatedOverride));
}
}
this.deactivatedOverrides = deactivatedOverrides.build();
}
private IntSupplier getOverride(IntSupplier existing, String... names) {
for (String name : names) {
if (customTextureIds.containsKey(name) && !deactivatedOverrides.contains(name)) {
return customTextureIds.get(name);
}
}
return existing;
}
@Override
public void addExternalSampler(int textureUnit, String... names) {
IntSupplier override = getOverride(null, names);
if (override != null) {
if (textureUnit == 0) {
samplerHolder.addDefaultSampler(override, names);
} else {
samplerHolder.addDynamicSampler(override, names);
}
} else {
samplerHolder.addExternalSampler(textureUnit, names);
}
}
@Override
public boolean hasSampler(String name) {
return samplerHolder.hasSampler(name);
}
@Override
public boolean addDefaultSampler(IntSupplier sampler, String... names) {
sampler = getOverride(sampler, names);
return samplerHolder.addDefaultSampler(sampler, names);
}
@Override
public boolean addDynamicSampler(IntSupplier sampler, String... names) {
sampler = getOverride(sampler, names);
return samplerHolder.addDynamicSampler(sampler, names);
}
@Override
public boolean addDynamicSampler(IntSupplier sampler, ValueUpdateNotifier notifier, String... names) {
sampler = getOverride(sampler, names);
return samplerHolder.addDynamicSampler(sampler, notifier, names);
}
}
}
@@ -0,0 +1,361 @@
package net.coderbot.iris.gl.program;
import com.google.common.collect.ImmutableList;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.IrisRenderSystem;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import net.coderbot.iris.gl.uniform.DynamicLocationalUniformHolder;
import net.coderbot.iris.gl.uniform.Uniform;
import net.coderbot.iris.gl.uniform.UniformHolder;
import net.coderbot.iris.gl.uniform.UniformType;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.uniforms.SystemTimeUniforms;
import net.minecraft.client.Minecraft;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.ARBShaderImageLoadStore;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.OptionalInt;
public class ProgramUniforms {
private static ProgramUniforms active;
private final ImmutableList<Uniform> perTick;
private final ImmutableList<Uniform> perFrame;
private final ImmutableList<Uniform> dynamic;
private final ImmutableList<ValueUpdateNotifier> notifiersToReset;
private ImmutableList<Uniform> once;
long lastTick = -1;
int lastFrame = -1;
public ProgramUniforms(ImmutableList<Uniform> once, ImmutableList<Uniform> perTick, ImmutableList<Uniform> perFrame,
ImmutableList<Uniform> dynamic, ImmutableList<ValueUpdateNotifier> notifiersToReset) {
this.once = once;
this.perTick = perTick;
this.perFrame = perFrame;
this.dynamic = dynamic;
this.notifiersToReset = notifiersToReset;
}
private void updateStage(ImmutableList<Uniform> uniforms) {
for (Uniform uniform : uniforms) {
uniform.update();
}
}
private static long getCurrentTick() {
return Objects.requireNonNull(Minecraft.getMinecraft().theWorld).getWorldTime();
}
public void update() {
if (active != null) {
active.removeListeners();
}
active = this;
updateStage(dynamic);
if (once != null) {
updateStage(once);
updateStage(perTick);
updateStage(perFrame);
lastTick = getCurrentTick();
once = null;
return;
}
long currentTick = getCurrentTick();
if (lastTick != currentTick) {
lastTick = currentTick;
updateStage(perTick);
}
// TODO: Move the frame counter to a different place?
int currentFrame = SystemTimeUniforms.COUNTER.getAsInt();
if (lastFrame != currentFrame) {
lastFrame = currentFrame;
updateStage(perFrame);
}
}
public void removeListeners() {
active = null;
for (ValueUpdateNotifier notifier : notifiersToReset) {
notifier.setListener(null);
}
}
public static void clearActiveUniforms() {
if (active != null) {
active.removeListeners();
}
}
public static Builder builder(String name, int program) {
return new Builder(name, program);
}
public static class Builder implements DynamicLocationalUniformHolder {
private final String name;
private final int program;
private final Map<Integer, String> locations;
private final Map<String, Uniform> once;
private final Map<String, Uniform> perTick;
private final Map<String, Uniform> perFrame;
private final Map<String, Uniform> dynamic;
private final Map<String, UniformType> uniformNames;
private final Map<String, UniformType> externalUniformNames;
private final List<ValueUpdateNotifier> notifiersToReset;
protected Builder(String name, int program) {
this.name = name;
this.program = program;
locations = new HashMap<>();
once = new HashMap<>();
perTick = new HashMap<>();
perFrame = new HashMap<>();
dynamic = new HashMap<>();
uniformNames = new HashMap<>();
externalUniformNames = new HashMap<>();
notifiersToReset = new ArrayList<>();
}
@Override
public Builder addUniform(UniformUpdateFrequency updateFrequency, Uniform uniform) {
Objects.requireNonNull(uniform);
if(uniform == null) {
throw new NullPointerException("uniform");
}
switch (updateFrequency) {
case ONCE:
once.put(locations.get(uniform.getLocation()), uniform);
break;
case PER_TICK:
perTick.put(locations.get(uniform.getLocation()), uniform);
break;
case PER_FRAME:
perFrame.put(locations.get(uniform.getLocation()), uniform);
break;
}
return this;
}
@Override
public OptionalInt location(String name, UniformType type) {
int id = IrisRenderSystem.getUniformLocation(program, name);
if (id == -1) {
return OptionalInt.empty();
}
// TODO: Temporary hack until custom uniforms are merged.
if ((!locations.containsKey(id) && !uniformNames.containsKey(name)) || name.equals("framemod8")) {
locations.put(id, name);
uniformNames.put(name, type);
} else {
Iris.logger.warn("[" + this.name + "] Duplicate uniform: " + type.toString().toLowerCase() + " " + name);
return OptionalInt.empty();
}
return OptionalInt.of(id);
}
public ProgramUniforms buildUniforms() {
// Check for any unsupported uniforms and warn about them so that we can easily figure out what uniforms we need to add.
final int activeUniforms = GL20.glGetProgrami(program, GL20.GL_ACTIVE_UNIFORMS);
IntBuffer sizeType = BufferUtils.createIntBuffer(2);
for (int index = 0; index < activeUniforms; index++) {
final String name = IrisRenderSystem.getActiveUniform(program, index, 128, sizeType);
if (name.isEmpty()) {
// No further information available.
continue;
}
final int size = sizeType.get(0);
final int type = sizeType.get(1);
UniformType provided = uniformNames.get(name);
final UniformType expected = getExpectedType(type);
if (provided == null && !name.startsWith("gl_")) {
final String typeName = getTypeName(type);
if (isSampler(type) || isImage(type)) {
// don't print a warning, samplers and images are managed elsewhere.
// TODO: Detect unsupported samplers/images?
continue;
}
final UniformType externalProvided = externalUniformNames.get(name);
if (externalProvided != null) {
if (externalProvided != expected) {
String expectedName;
if (expected != null) {
expectedName = expected.toString();
} else {
expectedName = "(unsupported type: " + getTypeName(type) + ")";
}
Iris.logger.error("[" + this.name + "] Wrong uniform type for externally-managed uniform " + name + ": " + externalProvided + " is provided but the program expects " + expectedName + ".");
}
continue;
}
if (size == 1) {
Iris.logger.warn("[" + this.name + "] Unsupported uniform: " + typeName + " " + name);
} else {
Iris.logger.warn("[" + this.name + "] Unsupported uniform: " + name + " of size " + size + " and type " + typeName);
}
continue;
}
// TODO: This is an absolutely horrific hack, but is needed until custom uniforms work.
if ("framemod8".equals(name) && expected == UniformType.FLOAT && provided == UniformType.INT) {
SystemTimeUniforms.addFloatFrameMod8Uniform(this);
provided = UniformType.FLOAT;
}
if (provided != null && provided != expected) {
String expectedName;
if (expected != null) {
expectedName = expected.toString();
} else {
expectedName = "(unsupported type: " + getTypeName(type) + ")";
}
Iris.logger.error("[" + this.name + "] Wrong uniform type for " + name + ": Iris is providing " + provided + " but the program expects " + expectedName + ". Disabling that uniform.");
once.remove(name);
perTick.remove(name);
perFrame.remove(name);
dynamic.remove(name);
}
}
return new ProgramUniforms(ImmutableList.copyOf(once.values()), ImmutableList.copyOf(perTick.values()), ImmutableList.copyOf(perFrame.values()),
ImmutableList.copyOf(dynamic.values()), ImmutableList.copyOf(notifiersToReset));
}
@Override
public Builder addDynamicUniform(Uniform uniform, ValueUpdateNotifier notifier) {
Objects.requireNonNull(uniform);
if(notifier == null){
Iris.logger.info("notifier is null: " + uniform.getLocation());
}
Objects.requireNonNull(notifier);
dynamic.put(locations.get(uniform.getLocation()), uniform);
notifiersToReset.add(notifier);
return this;
}
@Override
public UniformHolder externallyManagedUniform(String name, UniformType type) {
externalUniformNames.put(name, type);
return this;
}
}
private static String getTypeName(int type) {
return switch(type) {
case GL11.GL_FLOAT -> "float";
case GL11.GL_INT -> "int";
case GL20.GL_FLOAT_MAT4 -> "mat4";
case GL20.GL_FLOAT_VEC4 -> "vec4";
case GL20.GL_FLOAT_MAT3 -> "mat3";
case GL20.GL_FLOAT_VEC3 -> "vec3";
case GL20.GL_FLOAT_MAT2 -> "mat2";
case GL20.GL_FLOAT_VEC2 -> "vec2";
case GL20.GL_INT_VEC2 -> "ivec2";
case GL20.GL_INT_VEC4 -> "ivec4";
case GL20.GL_SAMPLER_3D -> "sampler3D";
case GL20.GL_SAMPLER_2D -> "sampler2D";
case GL30.GL_UNSIGNED_INT_SAMPLER_2D -> "usampler2D";
case GL30.GL_UNSIGNED_INT_SAMPLER_3D -> "usampler3D";
case GL20.GL_SAMPLER_1D -> "sampler1D";
case GL20.GL_SAMPLER_2D_SHADOW -> "sampler2DShadow";
case GL20.GL_SAMPLER_1D_SHADOW -> "sampler1DShadow";
case ARBShaderImageLoadStore.GL_IMAGE_2D -> "image2D";
case ARBShaderImageLoadStore.GL_IMAGE_3D -> "image3D";
default -> "(unknown:" + type + ")";
};
}
private static UniformType getExpectedType(int type) {
return switch (type) {
case GL11.GL_FLOAT -> UniformType.FLOAT;
case GL11.GL_INT -> UniformType.INT;
case GL20.GL_FLOAT_MAT4 -> UniformType.MAT4;
case GL20.GL_FLOAT_VEC4 -> UniformType.VEC4;
case GL20.GL_INT_VEC4 -> UniformType.VEC4I;
case GL20.GL_FLOAT_VEC3 -> UniformType.VEC3;
case GL20.GL_FLOAT_MAT3 -> null;
case GL20.GL_INT_VEC3 -> null;
case GL20.GL_FLOAT_MAT2 -> null;
case GL20.GL_FLOAT_VEC2 -> UniformType.VEC2;
case GL20.GL_INT_VEC2 -> UniformType.VEC2I;
case GL20.GL_SAMPLER_3D -> UniformType.INT;
case GL20.GL_SAMPLER_2D -> UniformType.INT;
case GL30.GL_UNSIGNED_INT_SAMPLER_2D -> UniformType.INT;
case GL30.GL_UNSIGNED_INT_SAMPLER_3D -> UniformType.INT;
case GL20.GL_SAMPLER_1D -> UniformType.INT;
case GL20.GL_SAMPLER_2D_SHADOW -> UniformType.INT;
case GL20.GL_SAMPLER_1D_SHADOW -> UniformType.INT;
default -> null;
};
}
private static boolean isSampler(int type) {
return type == GL20.GL_SAMPLER_1D
|| type == GL20.GL_SAMPLER_2D
|| type == GL30.GL_UNSIGNED_INT_SAMPLER_2D
|| type == GL30.GL_UNSIGNED_INT_SAMPLER_3D
|| type == GL20.GL_SAMPLER_3D
|| type == GL20.GL_SAMPLER_1D_SHADOW
|| type == GL20.GL_SAMPLER_2D_SHADOW;
}
private static boolean isImage(int type) {
return type == ARBShaderImageLoadStore.GL_IMAGE_1D
|| type == ARBShaderImageLoadStore.GL_IMAGE_2D
|| type == ARBShaderImageLoadStore.GL_UNSIGNED_INT_IMAGE_1D
|| type == ARBShaderImageLoadStore.GL_UNSIGNED_INT_IMAGE_2D
|| type == ARBShaderImageLoadStore.GL_UNSIGNED_INT_IMAGE_3D
|| type == ARBShaderImageLoadStore.GL_INT_IMAGE_1D
|| type == ARBShaderImageLoadStore.GL_INT_IMAGE_2D
|| type == ARBShaderImageLoadStore.GL_INT_IMAGE_3D
|| type == ARBShaderImageLoadStore.GL_IMAGE_3D
|| type == ARBShaderImageLoadStore.GL_IMAGE_1D_ARRAY
|| type == ARBShaderImageLoadStore.GL_IMAGE_2D_ARRAY;
}
}