Angelica 2.0

* GLStateManagerService & RenderSystemService
* Wire up Celeritas
* Iris working
* Dynamic lights working
* Goodbye Sodium 0.2
* Add Multi-Threading for check meshing again
This commit is contained in:
Jason Mitchell authored and Jason Mitchell committed 2026-01-07 13:22:16 -08:00
1 parent e5e8250d44
commit be90a01725
354 files changed
+5257 -15599

No files matched your search

+13 -1
View File
@@ -12,6 +12,9 @@ import cpw.mods.fml.common.gameevent.InputEvent;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import lombok.Getter;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import net.coderbot.iris.celeritas.IrisCeleritasShaderProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder;
import net.coderbot.iris.config.IrisConfig;
import net.coderbot.iris.gl.shader.StandardMacros;
import net.coderbot.iris.gui.screen.ShaderPackScreen;
@@ -31,7 +34,7 @@ import net.coderbot.iris.shaderpack.option.OptionSet;
import net.coderbot.iris.shaderpack.option.Profile;
import net.coderbot.iris.shaderpack.option.values.MutableOptionValues;
import net.coderbot.iris.shaderpack.option.values.OptionValues;
import net.coderbot.iris.sodium.block_context.BlockContextHolder;
import net.coderbot.iris.block_context.BlockContextHolder;
import net.coderbot.iris.texture.pbr.PBRTextureManager;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
@@ -378,6 +381,11 @@ public class Iris {
return;
}
// Register the Celeritas shader provider for Iris integration (only when Celeritas is enabled)
if (AngelicaConfig.enableCeleritas) {
IrisShaderProviderHolder.setProvider(new IrisCeleritasShaderProvider());
}
// Warm up the threadpool so shader transformations are faster when we need them
ShaderTransformExecutor.warmup();
@@ -402,6 +410,8 @@ public class Iris {
// See: https://github.com/IrisShaders/Iris/issues/323
lastDimension = DimensionId.OVERWORLD;
Iris.getPipelineManager().preparePipeline(DimensionId.OVERWORLD);
BlockRenderingSettings.INSTANCE.reloadRendererIfRequired();
}
public static void toggleShaders(Minecraft minecraft, boolean enabled) throws IOException {
@@ -704,6 +714,8 @@ public class Iris {
// https://github.com/IrisShaders/Iris/issues/1330
if (Minecraft.getMinecraft().theWorld != null) {
Iris.getPipelineManager().preparePipeline(Iris.getCurrentDimension());
BlockRenderingSettings.INSTANCE.reloadRendererIfRequired();
}
}
@@ -0,0 +1,19 @@
package net.coderbot.iris.block_context;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import net.minecraft.block.Block;
public class BlockContextHolder {
private final Object2IntMap<Block> blockMatches;
public int blockId;
public short renderType;
public BlockContextHolder(Object2IntMap<Block> blockMatches) {
this.blockMatches = blockMatches;
}
public void set(Block block, short renderType) {
this.renderType = renderType;
this.blockId = blockMatches.getOrDefault(block, -1);
}
}
@@ -6,6 +6,7 @@ import it.unimi.dsi.fastutil.objects.Object2IntMap;
import lombok.Getter;
import net.coderbot.iris.shaderpack.materialmap.NamespacedId;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
@@ -37,6 +38,15 @@ public class BlockRenderingSettings {
reloadRequired = false;
}
public void reloadRendererIfRequired() {
if (isReloadRequired()) {
if (Minecraft.getMinecraft().renderGlobal != null) {
Minecraft.getMinecraft().renderGlobal.loadRenderers();
}
clearReloadRequired();
}
}
@Nullable
public Object2IntMap<Block> getBlockMatches() {
return blockMatches;
@@ -0,0 +1,216 @@
package net.coderbot.iris.celeritas;
import com.google.common.collect.ImmutableSet;
import lombok.Getter;
import lombok.experimental.Accessors;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.blending.BlendModeOverride;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.coderbot.iris.gl.program.ProgramImages;
import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.program.ProgramUniforms;
import net.coderbot.iris.pipeline.PatchedShaderPrinter;
import net.coderbot.iris.pipeline.transform.PatchShaderType;
import net.coderbot.iris.rendertarget.RenderTargets;
import net.coderbot.iris.uniforms.CommonUniforms;
import net.coderbot.iris.uniforms.builtin.BuiltinReplacementUniforms;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import org.jetbrains.annotations.Nullable;
import java.util.EnumMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.IntFunction;
public class CeleritasTerrainPipeline {
private final EnumMap<IrisTerrainPass, PassInfo> passInfoMap = new EnumMap<>(IrisTerrainPass.class);
@Getter
private final CustomUniforms customUniforms;
private final IntFunction<ProgramSamplers> createTerrainSamplers;
private final IntFunction<ProgramSamplers> createShadowSamplers;
private final IntFunction<ProgramImages> createTerrainImages;
private final IntFunction<ProgramImages> createShadowImages;
@Getter
@Accessors(fluent = true)
public static final class PassInfo {
private final EnumMap<PatchShaderType, Optional<String>> sources = new EnumMap<>(PatchShaderType.class);
private GlFramebuffer framebuffer;
private BlendModeOverride blendModeOverride;
private float alphaReference;
private PassInfo() {
for (PatchShaderType type : PatchShaderType.VALUES) {
sources.put(type, Optional.empty());
}
}
private void setSource(PatchShaderType type, @Nullable String source) {
sources.put(type, Optional.ofNullable(source));
}
}
public CeleritasTerrainPipeline(
IntFunction<ProgramSamplers> createTerrainSamplers,
IntFunction<ProgramSamplers> createShadowSamplers,
IntFunction<ProgramImages> createTerrainImages,
IntFunction<ProgramImages> createShadowImages,
CustomUniforms customUniforms,
String terrainSourceName,
String translucentSourceName,
String shadowSourceName,
CompletableFuture<Map<PatchShaderType, String>> terrainFuture,
CompletableFuture<Map<PatchShaderType, String>> translucentFuture,
CompletableFuture<Map<PatchShaderType, String>> shadowFuture,
RenderTargets renderTargets,
ImmutableSet<Integer> flippedAfterPrepare,
ImmutableSet<Integer> flippedAfterTranslucent,
@Nullable GlFramebuffer shadowFramebuffer,
int[] terrainDrawBuffers
) {
this.customUniforms = customUniforms;
// Initialize PassInfo for each pass
for (IrisTerrainPass pass : IrisTerrainPass.VALUES) {
passInfoMap.put(pass, new PassInfo());
}
// Process terrain shaders (used for GBUFFER_SOLID and GBUFFER_CUTOUT)
if (terrainFuture != null) {
try {
final Map<PatchShaderType, String> result = terrainFuture.join();
final PassInfo solidInfo = passInfoMap.get(IrisTerrainPass.GBUFFER_SOLID);
final PassInfo cutoutInfo = passInfoMap.get(IrisTerrainPass.GBUFFER_CUTOUT);
solidInfo.setSource(PatchShaderType.VERTEX, result.get(PatchShaderType.VERTEX));
solidInfo.setSource(PatchShaderType.GEOMETRY, result.get(PatchShaderType.GEOMETRY));
solidInfo.setSource(PatchShaderType.FRAGMENT, result.get(PatchShaderType.FRAGMENT));
cutoutInfo.setSource(PatchShaderType.VERTEX, result.get(PatchShaderType.VERTEX));
cutoutInfo.setSource(PatchShaderType.GEOMETRY, result.get(PatchShaderType.GEOMETRY));
cutoutInfo.setSource(PatchShaderType.FRAGMENT, result.get(PatchShaderType.FRAGMENT));
PatchedShaderPrinter.debugPatchedShaders(terrainSourceName + "_celeritas",
result.get(PatchShaderType.VERTEX), result.get(PatchShaderType.GEOMETRY), result.get(PatchShaderType.FRAGMENT));
} catch (Exception e) {
Iris.logger.error("Failed to transform terrain shader for Celeritas: {}", terrainSourceName, e);
throw new RuntimeException("Shader transformation failed for " + terrainSourceName, e);
}
}
// Process translucent shaders (used for GBUFFER_TRANSLUCENT)
if (translucentFuture != null) {
try {
final Map<PatchShaderType, String> result = translucentFuture.join();
final PassInfo translucentInfo = passInfoMap.get(IrisTerrainPass.GBUFFER_TRANSLUCENT);
translucentInfo.setSource(PatchShaderType.VERTEX, result.get(PatchShaderType.VERTEX));
translucentInfo.setSource(PatchShaderType.GEOMETRY, result.get(PatchShaderType.GEOMETRY));
translucentInfo.setSource(PatchShaderType.FRAGMENT, result.get(PatchShaderType.FRAGMENT));
PatchedShaderPrinter.debugPatchedShaders(translucentSourceName + "_celeritas",
result.get(PatchShaderType.VERTEX), result.get(PatchShaderType.GEOMETRY), result.get(PatchShaderType.FRAGMENT));
} catch (Exception e) {
Iris.logger.error("Failed to transform translucent shader for Celeritas: {}", translucentSourceName, e);
throw new RuntimeException("Shader transformation failed for " + translucentSourceName, e);
}
}
// Process shadow shaders (used for SHADOW and SHADOW_CUTOUT)
if (shadowFuture != null) {
try {
final Map<PatchShaderType, String> result = shadowFuture.join();
final PassInfo shadowInfo = passInfoMap.get(IrisTerrainPass.SHADOW);
final PassInfo shadowCutoutInfo = passInfoMap.get(IrisTerrainPass.SHADOW_CUTOUT);
shadowInfo.setSource(PatchShaderType.VERTEX, result.get(PatchShaderType.VERTEX));
shadowInfo.setSource(PatchShaderType.GEOMETRY, result.get(PatchShaderType.GEOMETRY));
shadowInfo.setSource(PatchShaderType.FRAGMENT, result.get(PatchShaderType.FRAGMENT));
shadowCutoutInfo.setSource(PatchShaderType.VERTEX, result.get(PatchShaderType.VERTEX));
shadowCutoutInfo.setSource(PatchShaderType.GEOMETRY, result.get(PatchShaderType.GEOMETRY));
shadowCutoutInfo.setSource(PatchShaderType.FRAGMENT, result.get(PatchShaderType.FRAGMENT));
PatchedShaderPrinter.debugPatchedShaders(shadowSourceName + "_celeritas",
result.get(PatchShaderType.VERTEX), result.get(PatchShaderType.GEOMETRY), result.get(PatchShaderType.FRAGMENT));
} catch (Exception e) {
Iris.logger.error("Failed to transform shadow shader for Celeritas: {}", shadowSourceName, e);
throw new RuntimeException("Shader transformation failed for " + shadowSourceName, e);
}
}
// Set up framebuffers for each pass
// Shadow passes use the shadow framebuffer
if (shadowFramebuffer != null) {
passInfoMap.get(IrisTerrainPass.SHADOW).framebuffer = shadowFramebuffer;
passInfoMap.get(IrisTerrainPass.SHADOW_CUTOUT).framebuffer = shadowFramebuffer;
}
// GBuffer passes use render target framebuffers
if (renderTargets != null && terrainDrawBuffers != null) {
final GlFramebuffer solidFb = renderTargets.createGbufferFramebuffer(flippedAfterPrepare, terrainDrawBuffers);
final GlFramebuffer translucentFb = renderTargets.createGbufferFramebuffer(flippedAfterTranslucent, terrainDrawBuffers);
passInfoMap.get(IrisTerrainPass.GBUFFER_SOLID).framebuffer = solidFb;
passInfoMap.get(IrisTerrainPass.GBUFFER_CUTOUT).framebuffer = solidFb;
passInfoMap.get(IrisTerrainPass.GBUFFER_TRANSLUCENT).framebuffer = translucentFb;
}
// Set blend mode overrides
passInfoMap.get(IrisTerrainPass.GBUFFER_SOLID).blendModeOverride = BlendModeOverride.OFF;
passInfoMap.get(IrisTerrainPass.GBUFFER_CUTOUT).blendModeOverride = BlendModeOverride.OFF;
passInfoMap.get(IrisTerrainPass.GBUFFER_TRANSLUCENT).blendModeOverride = null; // Default blending
passInfoMap.get(IrisTerrainPass.SHADOW).blendModeOverride = BlendModeOverride.OFF;
passInfoMap.get(IrisTerrainPass.SHADOW_CUTOUT).blendModeOverride = BlendModeOverride.OFF;
// Set alpha references
passInfoMap.get(IrisTerrainPass.GBUFFER_SOLID).alphaReference = 0.0f;
passInfoMap.get(IrisTerrainPass.GBUFFER_CUTOUT).alphaReference = 0.1f;
passInfoMap.get(IrisTerrainPass.GBUFFER_TRANSLUCENT).alphaReference = 0.0f;
passInfoMap.get(IrisTerrainPass.SHADOW).alphaReference = 0.0f;
passInfoMap.get(IrisTerrainPass.SHADOW_CUTOUT).alphaReference = 0.1f;
this.createTerrainSamplers = createTerrainSamplers;
this.createShadowSamplers = createShadowSamplers;
this.createTerrainImages = createTerrainImages;
this.createShadowImages = createShadowImages;
}
public PassInfo getPassInfo(IrisTerrainPass pass) {
return passInfoMap.get(pass);
}
public ProgramUniforms.Builder initUniforms(int programId) {
final ProgramUniforms.Builder uniforms = ProgramUniforms.builder("<celeritas shaders>", programId);
CommonUniforms.addDynamicUniforms(uniforms);
customUniforms.assignTo(uniforms);
BuiltinReplacementUniforms.addBuiltinReplacementUniforms(uniforms);
return uniforms;
}
public boolean hasShadowPass() {
return createShadowSamplers != null;
}
public ProgramSamplers initTerrainSamplers(int programId) {
return createTerrainSamplers.apply(programId);
}
public ProgramSamplers initShadowSamplers(int programId) {
return createShadowSamplers.apply(programId);
}
public ProgramImages initTerrainImages(int programId) {
return createTerrainImages.apply(programId);
}
public ProgramImages initShadowImages(int programId) {
return createShadowImages.apply(programId);
}
}
@@ -0,0 +1,159 @@
package net.coderbot.iris.celeritas;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.blending.BlendModeOverride;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.pipeline.transform.PatchShaderType;
import net.coderbot.iris.shadows.ShadowRenderingState;
import org.embeddedt.embeddium.impl.gl.GlObject;
import org.embeddedt.embeddium.impl.gl.shader.GlProgram;
import org.embeddedt.embeddium.impl.gl.shader.GlShader;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderInterface;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.jetbrains.annotations.Nullable;
import java.util.EnumMap;
import java.util.Locale;
import java.util.Optional;
public class IrisCeleritasChunkProgramOverrides {
private final EnumMap<IrisTerrainPass, GlProgram<IrisCeleritasChunkShaderInterface>> programs = new EnumMap<>(IrisTerrainPass.class);
private boolean shadersCreated = false;
private int versionCounterForShaderReload = -1;
@Nullable
private GlShader createVertexShader(IrisTerrainPass pass, CeleritasTerrainPipeline pipeline) {
final CeleritasTerrainPipeline.PassInfo info = pipeline.getPassInfo(pass);
final Optional<String> source = info.sources().get(PatchShaderType.VERTEX);
return source.map(s -> new GlShader(ShaderType.VERTEX,
"iris:celeritas-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".vsh", s))
.orElse(null);
}
@Nullable
private GlShader createGeometryShader(IrisTerrainPass pass, CeleritasTerrainPipeline pipeline) {
final CeleritasTerrainPipeline.PassInfo info = pipeline.getPassInfo(pass);
final Optional<String> source = info.sources().get(PatchShaderType.GEOMETRY);
return source.map(s -> new GlShader(ShaderType.GEOM,
"iris:celeritas-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".gsh", s))
.orElse(null);
}
@Nullable
private GlShader createFragmentShader(IrisTerrainPass pass, CeleritasTerrainPipeline pipeline) {
final CeleritasTerrainPipeline.PassInfo info = pipeline.getPassInfo(pass);
final Optional<String> source = info.sources().get(PatchShaderType.FRAGMENT);
return source.map(s -> new GlShader(ShaderType.FRAGMENT,
"iris:celeritas-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".fsh", s))
.orElse(null);
}
@Nullable
private GlProgram<IrisCeleritasChunkShaderInterface> createShader(IrisTerrainPass pass, CeleritasTerrainPipeline pipeline, RenderPassConfiguration<?> configuration) {
final GlShader vertShader = createVertexShader(pass, pipeline);
final GlShader geomShader = createGeometryShader(pass, pipeline);
final GlShader fragShader = createFragmentShader(pass, pipeline);
if (vertShader == null || fragShader == null) {
if (vertShader != null) vertShader.delete();
if (geomShader != null) geomShader.delete();
if (fragShader != null) fragShader.delete();
return null;
}
try {
final GlProgram.Builder builder = GlProgram.builder("iris:celeritas-chunk-" + pass.getName());
builder.attachShader(vertShader);
if (geomShader != null) {
builder.attachShader(geomShader);
}
builder.attachShader(fragShader);
// Bind all attributes from the vertex format (includes base + Iris extended attributes)
final var vertexType =pass.toTerrainPass(configuration).vertexType();
int attrIndex = 0;
for (var attr : vertexType.getVertexFormat().getAttributes()) {
builder.bindAttribute(attr.getName(), attrIndex++);
}
// Get blend from PassInfo
final CeleritasTerrainPipeline.PassInfo passInfo = pipeline.getPassInfo(pass);
final BlendModeOverride blendOverride = passInfo.blendModeOverride();
return builder.link(context -> new IrisCeleritasChunkShaderInterface(((GlObject) context).handle(), context, pipeline, pass.isShadow(), blendOverride, pipeline.getCustomUniforms()));
} finally {
vertShader.delete();
if (geomShader != null) geomShader.delete();
fragShader.delete();
}
}
/**
* Create shaders for all Iris terrain passes.
*/
public void createShaders(CeleritasTerrainPipeline pipeline, RenderPassConfiguration<?> configuration) {
if (pipeline != null) {
for (IrisTerrainPass pass : IrisTerrainPass.VALUES) {
if (pass.isShadow() && !pipeline.hasShadowPass()) {
this.programs.put(pass, null);
continue;
}
this.programs.put(pass, createShader(pass, pipeline, configuration));
}
} else {
deleteShaders();
}
shadersCreated = true;
}
@Nullable
public GlProgram<? extends ChunkShaderInterface> getProgramOverride(TerrainRenderPass pass, RenderPassConfiguration<?> configuration) {
// Check for shader pack reload
if (versionCounterForShaderReload != Iris.getPipelineManager().getVersionCounterForSodiumShaderReload()) {
versionCounterForShaderReload = Iris.getPipelineManager().getVersionCounterForSodiumShaderReload();
deleteShaders();
}
final WorldRenderingPipeline worldPipeline = Iris.getPipelineManager().getPipelineNullable();
CeleritasTerrainPipeline celeritasPipeline = null;
if (worldPipeline != null) {
celeritasPipeline = worldPipeline.getCeleritasTerrainPipeline();
}
if (!shadersCreated) {
createShaders(celeritasPipeline, configuration);
}
if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) {
if (celeritasPipeline != null && !celeritasPipeline.hasShadowPass()) {
throw new IllegalStateException("Shadow program requested, but shader pack has no shadow pass");
}
return programs.get(pass.supportsFragmentDiscard() ?
IrisTerrainPass.SHADOW_CUTOUT : IrisTerrainPass.SHADOW);
} else {
if (pass.supportsFragmentDiscard()) {
return programs.get(IrisTerrainPass.GBUFFER_CUTOUT);
} else if (pass.isReverseOrder()) {
return programs.get(IrisTerrainPass.GBUFFER_TRANSLUCENT);
} else {
return programs.get(IrisTerrainPass.GBUFFER_SOLID);
}
}
}
public void deleteShaders() {
for (GlProgram<?> program : programs.values()) {
if (program != null) {
program.delete();
}
}
programs.clear();
shadersCreated = false;
}
}
@@ -0,0 +1,199 @@
package net.coderbot.iris.celeritas;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.mixins.interfaces.EntityRendererAccessor;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.blending.BlendModeOverride;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.samplers.IrisSamplers;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.DynamicTexture;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import net.coderbot.iris.gl.program.ProgramImages;
import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.program.ProgramUniforms;
import net.coderbot.iris.shadows.ShadowRenderingState;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import org.embeddedt.embeddium.impl.gl.shader.ShaderBindingContext;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat3v;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix3f;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix4f;
import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderInterface;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderTextureSlot;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix3f;
import org.joml.Matrix4f;
import org.joml.Matrix4fc;
public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface {
@Nullable
private final GlUniformMatrix4f uniformModelViewMatrix;
@Nullable
private final GlUniformMatrix4f uniformModelViewMatrixInverse;
@Nullable
private final GlUniformMatrix4f uniformProjectionMatrix;
@Nullable
private final GlUniformMatrix4f uniformProjectionMatrixInverse;
@Nullable
private final GlUniformMatrix3f uniformNormalMatrix;
@Nullable
private final GlUniformFloat3v uniformRegionOffset;
// Iris program state
private final ProgramUniforms irisProgramUniforms;
private final ProgramSamplers irisProgramSamplers;
private final ProgramImages irisProgramImages;
private final CustomUniforms customUniforms;
// Rendering state
private final BlendModeOverride blendModeOverride;
// Stored matrices for inverse and normal matrix computation
private final Matrix4f projectionMatrixInverse = new Matrix4f();
private final Matrix4f modelViewMatrixInverse = new Matrix4f();
private final Matrix3f normalMatrix = new Matrix3f();
public IrisCeleritasChunkShaderInterface(int handle, ShaderBindingContext context, CeleritasTerrainPipeline pipeline, boolean isShadowPass, BlendModeOverride blendModeOverride, CustomUniforms customUniforms) {
this.uniformModelViewMatrix = context.bindUniformIfPresent("iris_ModelViewMatrix", GlUniformMatrix4f::new);
this.uniformModelViewMatrixInverse = context.bindUniformIfPresent("iris_ModelViewMatrixInverse", GlUniformMatrix4f::new);
this.uniformProjectionMatrix = context.bindUniformIfPresent("iris_ProjectionMatrix", GlUniformMatrix4f::new);
this.uniformProjectionMatrixInverse = context.bindUniformIfPresent("iris_ProjectionMatrixInverse", GlUniformMatrix4f::new);
this.uniformNormalMatrix = context.bindUniformIfPresent("iris_NormalMatrix", GlUniformMatrix3f::new);
this.uniformRegionOffset = context.bindUniformIfPresent("u_RegionOffset", GlUniformFloat3v::new);
this.blendModeOverride = blendModeOverride;
this.customUniforms = customUniforms;
final ProgramUniforms.Builder builder = pipeline.initUniforms(handle);
customUniforms.mapholderToPass(builder, this);
this.irisProgramUniforms = builder.buildUniforms();
this.irisProgramSamplers = isShadowPass ? pipeline.initShadowSamplers(handle) : pipeline.initTerrainSamplers(handle);
this.irisProgramImages = isShadowPass ? pipeline.initShadowImages(handle) : pipeline.initTerrainImages(handle);
}
@Override
public void setupState(TerrainRenderPass pass) {
bindFramebuffer(pass);
if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) {
GLStateManager.disableCull();
}
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + IrisSamplers.ALBEDO_TEXTURE_UNIT);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().getTextureMapBlocks().getGlTextureId());
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + IrisSamplers.LIGHTMAP_TEXTURE_UNIT);
final DynamicTexture lightmapTexture = ((EntityRendererAccessor) Minecraft.getMinecraft().entityRenderer).getLightmapTexture();
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, lightmapTexture.getGlTextureId());
if (blendModeOverride != null) {
blendModeOverride.apply();
}
if (irisProgramUniforms != null) {
irisProgramUniforms.update();
}
if (irisProgramSamplers != null) {
irisProgramSamplers.update();
}
if (irisProgramImages != null) {
irisProgramImages.update();
}
customUniforms.push(this);
}
@Override
public void restoreState() {
if (blendModeOverride != null) {
BlendModeOverride.restore();
}
ProgramUniforms.clearActiveUniforms();
ProgramSamplers.clearActiveSamplers();
}
@Override
public GlPrimitiveType getPrimitiveType() {
return GlPrimitiveType.QUADS;
}
@Override
public void setProjectionMatrix(Matrix4fc matrix) {
if (uniformProjectionMatrix != null) {
uniformProjectionMatrix.set(matrix);
}
if (uniformProjectionMatrixInverse != null) {
projectionMatrixInverse.set(matrix);
projectionMatrixInverse.invert();
uniformProjectionMatrixInverse.set(projectionMatrixInverse);
}
}
@Override
public void setModelViewMatrix(Matrix4fc modelView) {
if (uniformModelViewMatrix != null) {
uniformModelViewMatrix.set(modelView);
}
if (uniformModelViewMatrixInverse != null) {
modelViewMatrixInverse.set(modelView);
modelViewMatrixInverse.invert();
uniformModelViewMatrixInverse.set(modelViewMatrixInverse);
}
if (uniformNormalMatrix != null) {
normalMatrix.set(modelView);
normalMatrix.invert();
normalMatrix.transpose();
uniformNormalMatrix.set(normalMatrix);
}
}
@Override
public void setRegionOffset(float x, float y, float z) {
if (uniformRegionOffset != null) {
uniformRegionOffset.set(x, y, z);
}
}
@Override
public void setTextureSlot(ChunkShaderTextureSlot slot, int val) {
// No-op - Iris manages texture state internally
}
private void bindFramebuffer(TerrainRenderPass pass) {
final CeleritasTerrainPipeline pipeline = getCeleritasTerrainPipeline();
if (pipeline == null) {
return;
}
final boolean isShadow = ShadowRenderingState.areShadowsCurrentlyBeingRendered();
final IrisTerrainPass irisPass;
if (isShadow) {
irisPass = pass.supportsFragmentDiscard() ? IrisTerrainPass.SHADOW_CUTOUT : IrisTerrainPass.SHADOW;
} else if (pass.isReverseOrder()) {
irisPass = IrisTerrainPass.GBUFFER_TRANSLUCENT;
} else if (pass.supportsFragmentDiscard()) {
irisPass = IrisTerrainPass.GBUFFER_CUTOUT;
} else {
irisPass = IrisTerrainPass.GBUFFER_SOLID;
}
final GlFramebuffer framebuffer = pipeline.getPassInfo(irisPass).framebuffer();
if (framebuffer != null) {
framebuffer.bind();
}
}
@org.jetbrains.annotations.Nullable
private CeleritasTerrainPipeline getCeleritasTerrainPipeline() {
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
return pipeline != null ? pipeline.getCeleritasTerrainPipeline() : null;
}
}
@@ -0,0 +1,82 @@
package net.coderbot.iris.celeritas;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.iris.IrisExtendedChunkVertexType;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import net.coderbot.iris.Iris;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.shadows.ShadowRenderingState;
import net.minecraft.block.Block;
import org.embeddedt.embeddium.impl.gl.shader.GlProgram;
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderInterface;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
import com.gtnewhorizons.angelica.compat.toremove.RenderLayer;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
public class IrisCeleritasShaderProvider implements IrisShaderProvider {
private static final IrisExtendedChunkVertexType EXTENDED_VERTEX_TYPE = new IrisExtendedChunkVertexType();
private final IrisCeleritasChunkProgramOverrides overrides = new IrisCeleritasChunkProgramOverrides();
private RenderPassConfiguration<?> renderPassConfiguration;
@Override
public boolean isShadersEnabled() {
return Iris.getCurrentPack().isPresent();
}
@Override
public boolean isShadowPass() {
return ShadowRenderingState.areShadowsCurrentlyBeingRendered();
}
@Override
public boolean shouldUseFaceCulling() {
return !ShadowRenderingState.areShadowsCurrentlyBeingRendered();
}
@Override
@Nullable
public GlProgram<? extends ChunkShaderInterface> getShaderOverride(TerrainRenderPass pass) {
if (!isShadersEnabled() || renderPassConfiguration == null) {
return null;
}
return overrides.getProgramOverride(pass, renderPassConfiguration);
}
@Override
public ChunkVertexType getVertexType(ChunkVertexType defaultType) {
if (isShadersEnabled() && BlockRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat()) {
return EXTENDED_VERTEX_TYPE;
}
return defaultType;
}
@Override
public void setRenderPassConfiguration(RenderPassConfiguration<?> configuration) {
this.renderPassConfiguration = configuration;
}
@Override
@Nullable
public Map<Block, RenderLayer> getBlockTypeIds() {
return BlockRenderingSettings.INSTANCE.getBlockTypeIds();
}
@Override
@Nullable
public Object2IntMap<Block> getBlockMatches() {
return BlockRenderingSettings.INSTANCE.getBlockMatches();
}
public void deleteShaders() {
overrides.deleteShaders();
}
public IrisCeleritasChunkProgramOverrides getOverrides() {
return overrides;
}
}
@@ -0,0 +1,48 @@
package net.coderbot.iris.celeritas;
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
public enum IrisTerrainPass {
SHADOW("shadow"),
SHADOW_CUTOUT("shadow"),
GBUFFER_SOLID("gbuffers_terrain"),
GBUFFER_CUTOUT("gbuffers_terrain_cutout"),
GBUFFER_TRANSLUCENT("gbuffers_water");
public static final IrisTerrainPass[] VALUES = values();
private final String name;
IrisTerrainPass(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean isShadow() {
return this == SHADOW || this == SHADOW_CUTOUT;
}
public TerrainRenderPass toTerrainPass(RenderPassConfiguration<?> config) {
return switch (this) {
case SHADOW, GBUFFER_SOLID -> config.defaultSolidMaterial().pass;
case SHADOW_CUTOUT, GBUFFER_CUTOUT -> config.defaultCutoutMippedMaterial().pass;
case GBUFFER_TRANSLUCENT -> config.defaultTranslucentMaterial().pass;
};
}
public static IrisTerrainPass fromTerrainPass(TerrainRenderPass pass, boolean isShadow) {
if (isShadow) {
return pass.supportsFragmentDiscard() ? SHADOW_CUTOUT : SHADOW;
} else if (pass.supportsFragmentDiscard()) {
return GBUFFER_CUTOUT;
} else if (pass.isReverseOrder()) {
return GBUFFER_TRANSLUCENT;
} else {
return GBUFFER_SOLID;
}
}
}
@@ -40,8 +40,6 @@ public class IrisDebugScreenHandler {
if (mc.gameSettings.showDebugInfo) {
event.right.add(Math.min(event.right.size(), 2), "Direct Buffers: +" + iris$humanReadableByteCountBin(iris$directPool.getMemoryUsed()));
event.right.add("");
if (Iris.getIrisConfig().areShadersEnabled()) {
event.right.add("[" + Iris.MODNAME + "] Shaderpack: " + Iris.getCurrentPackName() + (Iris.isFallback() ? " (fallback)" : ""));
Iris.getCurrentPack().ifPresent(pack -> event.right.add("[" + Iris.MODNAME + "] " + pack.getProfileInfo()));
@@ -12,6 +12,7 @@ public enum FeatureFlags {
PER_BUFFER_BLENDING(() -> true, RenderSystem::supportsBufferBlending),
COMPUTE_SHADERS(() -> true, RenderSystem::supportsCompute),
ENTITY_TRANSLUCENT(() -> true, () -> true),
BLOCK_EMISSION_ATTRIBUTE(() -> true, () -> true),
UNKNOWN(() -> false, () -> false);
private final BooleanSupplier irisRequirement;
@@ -1,18 +1,9 @@
package net.coderbot.iris.gl.state;
/**
* Holds some standard update notifiers for various elements of GL state. Currently, this class has a few listeners for
* fog-related values.
* Holds update notifiers for PBR texture changes.
*/
public class StateUpdateNotifiers {
public static ValueUpdateNotifier fogToggleNotifier;
public static ValueUpdateNotifier fogModeNotifier;
public static ValueUpdateNotifier fogStartNotifier;
public static ValueUpdateNotifier fogEndNotifier;
public static ValueUpdateNotifier fogDensityNotifier;
public static ValueUpdateNotifier blendFuncNotifier;
public static ValueUpdateNotifier bindTextureNotifier;
public static ValueUpdateNotifier normalTextureChangeNotifier;
public static ValueUpdateNotifier specularTextureChangeNotifier;
public static ValueUpdateNotifier phaseChangeNotifier;
}
@@ -1,12 +1,14 @@
package net.coderbot.iris.gl.state;
/**
* A
* A notifier that can trigger uniform updates when values change.
*/
public interface ValueUpdateNotifier {
/** No-op notifier for uniforms that are polled per-frame rather than push-notified */
ValueUpdateNotifier NONE = listener -> {};
/**
* Sets up a listener with this notifier. Whenever the underlying value of
* @param listener
* Sets up a listener with this notifier.
*/
void setListener(Runnable listener);
}
@@ -3,7 +3,6 @@ package net.coderbot.iris.layer;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.gl.shader.ProgramCreator;
import net.coderbot.iris.gl.state.StateUpdateNotifiers;
import net.coderbot.iris.pipeline.WorldRenderingPhase;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import org.lwjgl.opengl.GL20;
@@ -12,7 +11,6 @@ public class GbufferPrograms {
private static boolean entities;
private static boolean blockEntities;
private static boolean outline;
private static Runnable phaseChangeListener;
private static void checkReentrancy() {
if (entities || blockEntities || outline) {
@@ -98,12 +96,6 @@ public class GbufferPrograms {
}
}
public static void runPhaseChangeNotifier() {
if (phaseChangeListener != null) {
phaseChangeListener.run();
}
}
public static void setupSpecialRenderCondition(SpecialCondition override) {
Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setSpecialCondition(override));
}
@@ -112,10 +104,6 @@ public class GbufferPrograms {
Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setSpecialCondition(null));
}
static {
StateUpdateNotifiers.phaseChangeNotifier = listener -> phaseChangeListener = listener;
}
public static void init() {
// Empty initializer to run static
}
@@ -9,6 +9,7 @@ import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import com.gtnewhorizons.angelica.rendering.RenderingState;
import net.coderbot.iris.Iris;
import net.coderbot.iris.block_rendering.BlockMaterialMapping;
import net.coderbot.iris.celeritas.CeleritasTerrainPipeline;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.gbuffer_overrides.matching.ProgramTable;
@@ -128,7 +129,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private final ImmutableSet<Integer> flippedAfterPrepare;
private final ImmutableSet<Integer> flippedAfterTranslucent;
private final SodiumTerrainPipeline sodiumTerrainPipeline;
private final CeleritasTerrainPipeline celeritasTerrainPipeline;
private final Map<Pair<String, InputAvailability>, Map<PatchShaderType, String>> attributeTransforms;
@@ -181,9 +182,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
final Optional<ProgramSource> translucentSource = first(programs.getGbuffersWater(), terrainSource);
final Optional<ProgramSource> shadowSource = programs.getShadow();
final CompletableFuture<Map<PatchShaderType, String>> sodiumTerrainFuture = terrainSource.map(DeferredWorldRenderingPipeline::submitSodiumTerrainTransform).orElse(null);
final CompletableFuture<Map<PatchShaderType, String>> sodiumTranslucentFuture = translucentSource.map(DeferredWorldRenderingPipeline::submitSodiumTerrainTransform).orElse(null);
final CompletableFuture<Map<PatchShaderType, String>> sodiumShadowFuture = shadowSource.map(DeferredWorldRenderingPipeline::submitSodiumTerrainTransform).orElse(null);
// Celeritas terrain transform futures
final CompletableFuture<Map<PatchShaderType, String>> celeritasTerrainFuture = terrainSource.map(DeferredWorldRenderingPipeline::submitCeleritasTerrainTransform).orElse(null);
final CompletableFuture<Map<PatchShaderType, String>> celeritasTranslucentFuture = translucentSource.map(DeferredWorldRenderingPipeline::submitCeleritasTerrainTransform).orElse(null);
final CompletableFuture<Map<PatchShaderType, String>> celeritasShadowFuture = shadowSource.map(DeferredWorldRenderingPipeline::submitCeleritasTerrainTransform).orElse(null);
this.cloudSetting = programs.getPackDirectives().getCloudSetting();
this.shouldRenderUnderwaterOverlay = programs.getPackDirectives().underwaterOverlay();
@@ -392,7 +394,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
this.clearPassesFull = ClearPassCreator.createClearPasses(renderTargets, true, programs.getPackDirectives().getRenderTargetDirectives());
this.clearPasses = ClearPassCreator.createClearPasses(renderTargets, false, programs.getPackDirectives().getRenderTargetDirectives());
// SodiumTerrainPipeline setup follows.
// Terrain pipeline sampler/image factory setup follows.
Supplier<ImmutableSet<Integer>> flipped = () -> isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent;
@@ -450,13 +452,22 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return builder.build();
};
this.sodiumTerrainPipeline = new SodiumTerrainPipeline(this, programs, createTerrainSamplers,
final GlFramebuffer celeritasShadowFb = (shadowRenderTargets != null && shadowRenderer != null)
? shadowRenderTargets.createShadowFramebuffer(shadowRenderTargets.snapshot(), new int[] {0, 1})
: null;
final int[] celeritasTerrainDrawBuffers = terrainSource
.map(source -> source.getDirectives().getDrawBuffers())
.orElse(new int[] {0});
this.celeritasTerrainPipeline = new CeleritasTerrainPipeline(createTerrainSamplers,
shadowRenderer == null ? null : createShadowTerrainSamplers, createTerrainImages,
shadowRenderer == null ? null : createShadowTerrainImages, this.customUniforms,
terrainSource.map(ProgramSource::getName).orElse(null),
translucentSource.map(ProgramSource::getName).orElse(null),
shadowSource.map(ProgramSource::getName).orElse(null),
sodiumTerrainFuture, sodiumTranslucentFuture, sodiumShadowFuture);
celeritasTerrainFuture, celeritasTranslucentFuture, celeritasShadowFuture,
renderTargets, flippedAfterPrepare, flippedAfterTranslucent,
celeritasShadowFb, celeritasTerrainDrawBuffers);
}
private RenderTargets getRenderTargets() {
@@ -585,11 +596,6 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return;
}
if (sodiumTerrainRendering) {
beginPass(table.match(getCondition(getPhase()), new InputAvailability(true, true)));
return;
}
beginPass(table.match(getCondition(getPhase()), inputs));
}
@@ -796,11 +802,11 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
GL11.glViewport(0, 0, main.framebufferWidth, main.framebufferHeight);
}
if (program != null && !sodiumTerrainRendering) {
if (program != null) {
program.use();
}
DeferredWorldRenderingPipeline.this.customUniforms.push(this);
DeferredWorldRenderingPipeline.this.customUniforms.push(this);
if (alphaTestOverride != null) {
alphaTestOverride.apply();
@@ -1094,6 +1100,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
if (shadowRenderer != null) {
isRenderingShadow = true;
matchPass(); // Ensure shadow shader is bound for entity rendering
shadowRenderer.renderShadows(levelRenderer, playerCamera);
@@ -1208,8 +1215,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
@Override
public SodiumTerrainPipeline getSodiumTerrainPipeline() {
return sodiumTerrainPipeline;
public CeleritasTerrainPipeline getCeleritasTerrainPipeline() {
return celeritasTerrainPipeline;
}
@Override
@@ -1226,49 +1233,28 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return phase;
}
boolean sodiumTerrainRendering = false;
@Override
public void syncProgram() {
matchPass();
}
@Override
public void beginSodiumTerrainRendering() {
sodiumTerrainRendering = true;
syncProgram();
}
@Override
public void endSodiumTerrainRendering() {
sodiumTerrainRendering = false;
current = null;
syncProgram();
}
@Override
public void setOverridePhase(WorldRenderingPhase phase) {
this.overridePhase = phase;
GbufferPrograms.runPhaseChangeNotifier();
matchPass();
}
@Override
public void setPhase(WorldRenderingPhase phase) {
this.phase = phase;
GbufferPrograms.runPhaseChangeNotifier();
matchPass();
}
@Override
public void setInputs(InputAvailability availability) {
this.inputs = availability;
matchPass();
}
@Override
public void setSpecialCondition(SpecialCondition special) {
this.special = special;
matchPass();
}
@Override
@@ -1344,8 +1330,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return futures;
}
private static CompletableFuture<Map<PatchShaderType, String>> submitSodiumTerrainTransform(ProgramSource source) {
return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchSodiumTerrain(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null)));
private static CompletableFuture<Map<PatchShaderType, String>> submitCeleritasTerrainTransform(ProgramSource source) {
return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchCeleritasTerrain(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null)));
}
@SafeVarargs
@@ -2,6 +2,7 @@ package net.coderbot.iris.pipeline;
import com.gtnewhorizons.angelica.compat.mojang.Camera;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.celeritas.CeleritasTerrainPipeline;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.gbuffer_overrides.state.RenderTargetStateListener;
@@ -50,16 +51,6 @@ public class FixedFunctionWorldRenderingPipeline implements WorldRenderingPipeli
return WorldRenderingPhase.NONE;
}
@Override
public void beginSodiumTerrainRendering() {
}
@Override
public void endSodiumTerrainRendering() {
}
@Override
public void setOverridePhase(WorldRenderingPhase phase) {
@@ -80,11 +71,6 @@ public class FixedFunctionWorldRenderingPipeline implements WorldRenderingPipeli
}
@Override
public void syncProgram() {
}
@Override
public RenderTargetStateListener getRenderTargetStateListener() {
return RenderTargetStateListener.NOP;
@@ -126,7 +112,7 @@ public class FixedFunctionWorldRenderingPipeline implements WorldRenderingPipeli
}
@Override
public SodiumTerrainPipeline getSodiumTerrainPipeline() {
public CeleritasTerrainPipeline getCeleritasTerrainPipeline() {
// no shaders to override
return null;
}
@@ -3,10 +3,8 @@ package net.coderbot.iris.pipeline;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import lombok.Getter;
import net.coderbot.iris.Iris;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.shaderpack.DimensionId;
import net.coderbot.iris.uniforms.SystemTimeUniforms;
import net.minecraft.client.Minecraft;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
@@ -36,14 +34,6 @@ public class PipelineManager {
Iris.logger.info("Creating pipeline for dimension {}", currentDimension);
pipeline = pipelineFactory.apply(currentDimension);
pipelinesPerDimension.put(currentDimension, pipeline);
if (BlockRenderingSettings.INSTANCE.isReloadRequired()) {
if (Minecraft.getMinecraft().renderGlobal != null) {
Minecraft.getMinecraft().renderGlobal.loadRenderers();
}
BlockRenderingSettings.INSTANCE.clearReloadRequired();
}
} else {
pipeline = pipelinesPerDimension.get(currentDimension);
}
@@ -3,17 +3,19 @@ package net.coderbot.iris.pipeline;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizons.angelica.compat.mojang.Camera;
import com.gtnewhorizons.angelica.compat.toremove.MatrixStack;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.rendering.RenderingState;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer;
import net.coderbot.iris.Iris;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.gui.option.IrisVideoSettings;
import net.coderbot.iris.shaderpack.OptionalBoolean;
import net.coderbot.iris.shaderpack.PackDirectives;
@@ -41,8 +43,11 @@ import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.profiler.Profiler;
import net.minecraft.tileentity.TileEntity;
import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil;
import org.embeddedt.embeddium.impl.render.viewport.ViewportProvider;
import org.joml.Matrix4f;
import org.joml.Vector3dc;
import org.joml.Vector3f;
@@ -58,9 +63,15 @@ public class ShadowRenderer {
public static final Matrix4f MODELVIEW = new Matrix4f();
public static final FloatBuffer MODELVIEW_BUFFER = BufferUtils.createFloatBuffer(16);
public static final Matrix4f PROJECTION = new Matrix4f();
public static List<TileEntity> visibleTileEntities;
public static List<TileEntity> globalTileEntities;
public static final List<TileEntity> visibleTileEntities = new ArrayList<>();
public static final List<TileEntity> globalTileEntities = new ArrayList<>();
public static boolean ACTIVE = false;
private static final Comparator<Entity> ENTITY_CLASS_COMPARATOR = Comparator.comparingInt(a -> System.identityHashCode(a.getClass()));
private static final NonCullingFrustum NON_CULLING_FRUSTUM = new NonCullingFrustum();
private static final CullEverythingFrustum CULL_EVERYTHING_FRUSTUM = new CullEverythingFrustum();
public static ShadowRenderTargets CURRENT_TARGETS = null;
private final float halfPlaneLength;
private final float renderDistanceMultiplier;
private final float entityShadowDistanceMultiplier;
@@ -76,16 +87,27 @@ public class ShadowRenderer {
private final boolean shouldRenderPlayer;
private final boolean shouldRenderBlockEntities;
private final float sunPathRotation;
// private final RenderBuffers buffers;
// private final RenderBuffersExt renderBuffersExt;
private final List<MipmapPass> mipmapPasses = new ArrayList<>();
private final String debugStringOverall;
private FrustumHolder terrainFrustumHolder;
private FrustumHolder entityFrustumHolder;
private String debugStringTerrain = "(unavailable)";
private int renderedShadowEntities = 0;
private int renderedShadowTileEntities = 0;
private Profiler profiler;
private final List<Entity> renderedEntitiesList = new ArrayList<>(64);
private final MatrixStack shadowModelView = new MatrixStack();
private final CelestialUniforms celestialUniforms;
private final AdvancedShadowCullingFrustum cachedAdvancedFrustum = new AdvancedShadowCullingFrustum();
private final Vector3f shadowLightVectorCache = new Vector3f();
private BoxCuller cachedBoxCuller;
private BoxCullingFrustum cachedBoxCullingFrustum;
private BoxCuller cachedAdvancedBoxCuller;
private BoxCuller cachedTileEntityCuller;
private double lastBoxCullerDistance = -1;
private double lastAdvancedBoxCullerDistance = -1;
private double lastTileEntityCullerDistance = -1;
public ShadowRenderer(ProgramSource shadow, PackDirectives directives, ShadowRenderTargets shadowRenderTargets) {
@@ -123,6 +145,7 @@ public class ShadowRenderer {
}
this.sunPathRotation = directives.getSunPathRotation();
this.celestialUniforms = new CelestialUniforms(this.sunPathRotation);
// this.buffers = new RenderBuffers();
//
@@ -154,6 +177,13 @@ public class ShadowRenderer {
return modelView;
}
private MatrixStack getShadowModelView() {
final Vector3dc cameraPos = CameraUniforms.getUnshiftedCameraPosition();
shadowModelView.reset();
ShadowMatrices.createModelViewMatrix(shadowModelView, getShadowAngle(), this.intervalSize, this.sunPathRotation, cameraPos.x(), cameraPos.y(), cameraPos.z());
return shadowModelView;
}
private static WorldClient getLevel() {
return Objects.requireNonNull(Minecraft.getMinecraft().theWorld);
}
@@ -271,15 +301,14 @@ public class ShadowRenderer {
distanceInfo = Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16
+ " blocks (capped by normal render distance)";
cullingInfo = "disabled " + reason;
return holder.setInfo(new NonCullingFrustum(), distanceInfo, cullingInfo);
return holder.setInfo(NON_CULLING_FRUSTUM, distanceInfo, cullingInfo);
} else {
distanceInfo = distance + " blocks (set by shader pack)";
cullingInfo = "distance only " + reason;
BoxCuller boxCuller = new BoxCuller(distance);
holder.setInfo(new BoxCullingFrustum(boxCuller), distanceInfo, cullingInfo);
holder.setInfo(getOrCreateBoxCullingFrustum(distance), distanceInfo, cullingInfo);
}
} else {
BoxCuller boxCuller;
final BoxCuller boxCuller;
double distance = halfPlaneLength * renderMultiplier;
String setter = "(set by shader pack)";
@@ -300,30 +329,65 @@ public class ShadowRenderer {
if (distance == 0.0) {
cullingInfo = "no shadows rendered";
holder.setInfo(new CullEverythingFrustum(), distanceInfo, cullingInfo);
return holder.setInfo(CULL_EVERYTHING_FRUSTUM, distanceInfo, cullingInfo);
}
boxCuller = new BoxCuller(distance);
boxCuller = getOrCreateAdvancedBoxCuller(distance);
}
cullingInfo = "Advanced Frustum Culling enabled";
Vector4f shadowLightPosition = new CelestialUniforms(sunPathRotation).getShadowLightPositionInWorldSpace();
final Vector4f shadowLightPosition = celestialUniforms.getShadowLightPositionInWorldSpace();
shadowLightVectorCache.set(shadowLightPosition.x(), shadowLightPosition.y(), shadowLightPosition.z());
shadowLightVectorCache.normalize();
Vector3f shadowLightVectorFromOrigin =
new Vector3f(shadowLightPosition.x(), shadowLightPosition.y(), shadowLightPosition.z());
shadowLightVectorFromOrigin.normalize();
return holder.setInfo(new AdvancedShadowCullingFrustum(RenderingState.INSTANCE.getModelViewMatrix(), RenderingState.INSTANCE.getProjectionMatrix(),
shadowLightVectorFromOrigin, boxCuller), distanceInfo, cullingInfo);
cachedAdvancedFrustum.init(RenderingState.INSTANCE.getModelViewMatrix(), RenderingState.INSTANCE.getProjectionMatrix(), shadowLightVectorCache, boxCuller);
return holder.setInfo(cachedAdvancedFrustum, distanceInfo, cullingInfo);
}
return holder;
}
private BoxCullingFrustum getOrCreateBoxCullingFrustum(double distance) {
if (cachedBoxCuller == null) {
cachedBoxCuller = new BoxCuller(distance);
cachedBoxCullingFrustum = new BoxCullingFrustum(cachedBoxCuller);
lastBoxCullerDistance = distance;
} else if (lastBoxCullerDistance != distance) {
cachedBoxCuller.setMaxDistance(distance);
lastBoxCullerDistance = distance;
}
return cachedBoxCullingFrustum;
}
private BoxCuller getOrCreateAdvancedBoxCuller(double distance) {
if (cachedAdvancedBoxCuller == null) {
cachedAdvancedBoxCuller = new BoxCuller(distance);
lastAdvancedBoxCullerDistance = distance;
} else if (lastAdvancedBoxCullerDistance != distance) {
cachedAdvancedBoxCuller.setMaxDistance(distance);
lastAdvancedBoxCullerDistance = distance;
}
return cachedAdvancedBoxCuller;
}
private BoxCuller getOrCreateTileEntityCuller(double distance) {
if (cachedTileEntityCuller == null) {
cachedTileEntityCuller = new BoxCuller(distance);
lastTileEntityCullerDistance = distance;
} else if (lastTileEntityCullerDistance != distance) {
cachedTileEntityCuller.setMaxDistance(distance);
lastTileEntityCullerDistance = distance;
}
return cachedTileEntityCuller;
}
private void setupGlState(Matrix4f projMatrix) {
// Bind shadow framebuffer and set viewport to shadow resolution
targets.getDepthSourceFb().bind();
GL11.glViewport(0, 0, resolution, resolution);
// Set up our projection matrix and load it into the legacy matrix stack
RenderSystem.setupProjectionMatrix(projMatrix);
@@ -343,6 +407,11 @@ public class ShadowRenderer {
// Make sure to unload the projection matrix
RenderSystem.restoreProjectionMatrix();
// Restore main framebuffer and viewport
Minecraft mc = Minecraft.getMinecraft();
mc.getFramebuffer().bindFramebuffer(false);
GL11.glViewport(0, 0, mc.displayWidth, mc.displayHeight);
}
private void copyPreTranslucentDepth() {
@@ -352,80 +421,112 @@ public class ShadowRenderer {
}
private void renderEntities(EntityRenderer levelRenderer, Frustrum frustum, Object bufferSource, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float tickDelta) {
int shadowEntities = 0;
profiler.startSection("cull");
List<Entity> renderedEntities = new ArrayList<>(32);
renderedEntitiesList.clear();
final boolean playerIsSpectator = GameModeUtil.isSpectator();
final EntityPlayer player = Minecraft.getMinecraft().thePlayer;
// TODO: I'm sure that this can be improved / optimized.
// TODO: Entity culling
for (Entity entity : getLevel().loadedEntityList) {
if (false/*!dispatcher.shouldRender(entity, frustum, cameraX, cameraY, cameraZ) || entity.isSpectator()*/) {
continue;
}
if (playerIsSpectator && entity == player) continue;
renderedEntities.add(entity);
if (!entity.ignoreFrustumCheck && !frustum.isBoundingBoxInFrustum(entity.boundingBox)) continue;
renderedEntitiesList.add(entity);
}
profiler.endStartSection("sort");
// TODO: Render
// Sort the entities by type first in order to allow vanilla's entity batching system to work better.
renderedEntities.sort(Comparator.comparingInt(entity -> entity.getClass().hashCode()));
renderedEntitiesList.sort(ENTITY_CLASS_COMPARATOR);
profiler.endStartSection("build geometry");
// TODO: Render
setupEntityShadowState(modelView, cameraX, cameraY, cameraZ);
try {
for (Entity entity : renderedEntitiesList) {
RenderManager.instance.renderEntitySimple(entity, tickDelta);
}
} finally {
teardownEntityShadowState();
}
renderedShadowEntities = renderedEntitiesList.size();
profiler.endSection();
}
// Saved RenderManager position for shadow pass
private double savedRenderPosX, savedRenderPosY, savedRenderPosZ;
private void setupEntityShadowState(MatrixStack modelView, double cameraX, double cameraY, double cameraZ) {
savedRenderPosX = RenderManager.renderPosX;
savedRenderPosY = RenderManager.renderPosY;
savedRenderPosZ = RenderManager.renderPosZ;
RenderManager.renderPosX = cameraX;
RenderManager.renderPosY = cameraY;
RenderManager.renderPosZ = cameraZ;
GLStateManager.glEnable(GL11.GL_POLYGON_OFFSET_FILL);
GLStateManager.glPolygonOffset(1.0f, 1.0f);
GL11.glPushMatrix();
MODELVIEW_BUFFER.clear().rewind();
modelView.peek().getModel().get(MODELVIEW_BUFFER);
GL11.glLoadMatrix(MODELVIEW_BUFFER);
for (Entity entity : renderedEntities) {
RenderManager.instance.renderEntitySimple(entity, tickDelta);
shadowEntities++;
}
}
private void teardownEntityShadowState() {
GL11.glPopMatrix();
renderedShadowEntities = shadowEntities;
GLStateManager.glDisable(GL11.GL_POLYGON_OFFSET_FILL);
GLStateManager.glPolygonOffset(0.0f, 0.0f);
profiler.endSection();
}
RenderManager.renderPosX = savedRenderPosX;
RenderManager.renderPosY = savedRenderPosY;
RenderManager.renderPosZ = savedRenderPosZ;
}
private void renderPlayerEntity(EntityRenderer levelRenderer, Frustrum frustum, Object bufferSource, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float tickDelta) {
profiler.startSection("cull");
Entity player = Minecraft.getMinecraft().thePlayer;
// TODO: Entity culling
// if (!dispatcher.shouldRender(player, frustum, cameraX, cameraY, cameraZ) || player.isSpectator()) {
// return;
// }
// Skip if spectating or outside frustum
if (GameModeUtil.isSpectator()) {
profiler.endSection();
renderedShadowEntities = 0;
return;
}
if (!player.ignoreFrustumCheck && !frustum.isBoundingBoxInFrustum(player.boundingBox)) {
profiler.endSection();
renderedShadowEntities = 0;
return;
}
profiler.endStartSection("build geometry");
int shadowEntities = 0;
GL11.glPushMatrix();
MODELVIEW_BUFFER.clear().rewind();
modelView.peek().getModel().get(MODELVIEW_BUFFER);
GL11.glLoadMatrix(MODELVIEW_BUFFER);
setupEntityShadowState(modelView, cameraX, cameraY, cameraZ);
try {
if (player.riddenByEntity != null) {
RenderManager.instance.renderEntitySimple(player.riddenByEntity, tickDelta);
shadowEntities++;
}
if (player.riddenByEntity != null) {
RenderManager.instance.renderEntitySimple(player.riddenByEntity, tickDelta);
shadowEntities++;
}
if (player.ridingEntity != null) {
RenderManager.instance.renderEntitySimple(player.ridingEntity, tickDelta);
shadowEntities++;
}
if (player.ridingEntity != null) {
RenderManager.instance.renderEntitySimple(player.ridingEntity, tickDelta);
shadowEntities++;
}
RenderManager.instance.renderEntitySimple(player, tickDelta);
GL11.glPopMatrix();
shadowEntities++;
RenderManager.instance.renderEntitySimple(player, tickDelta);
shadowEntities++;
} finally {
teardownEntityShadowState();
}
renderedShadowEntities = shadowEntities;
@@ -453,7 +554,8 @@ public class ShadowRenderer {
int shadowTileEntities = 0;
BoxCuller culler = null;
if (hasEntityFrustum) {
culler = new BoxCuller(halfPlaneLength * (renderDistanceMultiplier * entityShadowDistanceMultiplier));
double distance = halfPlaneLength * (renderDistanceMultiplier * entityShadowDistanceMultiplier);
culler = getOrCreateTileEntityCuller(distance);
culler.setPosition(cameraX, cameraY, cameraZ);
}
@@ -462,6 +564,9 @@ public class ShadowRenderer {
modelView.peek().getModel().get(MODELVIEW_BUFFER);
GL11.glLoadMatrix(MODELVIEW_BUFFER);
GbufferPrograms.beginBlockEntities();
GbufferPrograms.setBlockEntityDefaults();
for (TileEntity tileEntity : visibleTileEntities) {
if (hasEntityFrustum && (culler.isCulled(tileEntity.xCoord - 1, tileEntity.yCoord - 1, tileEntity.zCoord - 1, tileEntity.xCoord + 1, tileEntity.yCoord + 1, tileEntity.zCoord + 1))) {
continue;
@@ -479,6 +584,7 @@ public class ShadowRenderer {
shadowTileEntities++;
}
GbufferPrograms.endBlockEntities();
GLStateManager.glPopMatrix();
renderedShadowTileEntities = shadowTileEntities;
@@ -496,17 +602,18 @@ public class ShadowRenderer {
profiler.endStartSection("shadows");
ACTIVE = true;
CURRENT_TARGETS = this.targets;
// NB: We store the previous player buffers in order to be able to allow mods rendering entities in the shadow pass (Flywheel) to use the shadow buffers instead.
// TODO: Render
// RenderBuffers playerBuffers = levelRenderer.getRenderBuffers();
// levelRenderer.setRenderBuffers(buffers);
visibleTileEntities = new ArrayList<>();
globalTileEntities = new ArrayList<>();
visibleTileEntities.clear();
globalTileEntities.clear();
// Create our camera
final MatrixStack modelView = createShadowModelView(this.sunPathRotation, this.intervalSize);
final MatrixStack modelView = getShadowModelView();
MODELVIEW.set(modelView.peek().getModel());
final Matrix4f shadowProjection;
@@ -549,6 +656,11 @@ public class ShadowRenderer {
// ((LevelRenderer) levelRenderer).needsUpdate();
// levelRenderer.setShouldRegenerateClouds(regenerateClouds);
// Mark the shadow graph as needing update before terrain setup
// Modern Celeritas does this to ensure the shadow render lists get populated
com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer.getInstance()
.getRenderSectionManager().markGraphDirty();
// Execute the vanilla terrain setup / culling routines using our shadow frustum.
mc.renderGlobal.clipRenderersByFrustum(terrainFrustumHolder.getFrustum(), playerCamera.getPartialTicks());
@@ -567,6 +679,9 @@ public class ShadowRenderer {
rg.sortAndRender(mc.thePlayer, 0, playerCamera.getPartialTicks());
}
// Reset viewport in case terrain rendering changed it
GL11.glViewport(0, 0, resolution, resolution);
profiler.endStartSection("entities");
// Get the current tick delta. Normally this is the same as client.getTickDelta(), but when the game is paused,
@@ -587,6 +702,11 @@ public class ShadowRenderer {
Frustrum entityShadowFrustum = entityFrustumHolder.getFrustum();
entityShadowFrustum.setPosition(cameraX, cameraY, cameraZ);
// Set viewport for entity visibility checks during shadow pass (matches modern Celeritas)
if (AngelicaConfig.enableCeleritas) {
CeleritasWorldRenderer.getInstance().setCurrentViewport(((ViewportProvider)entityShadowFrustum).sodium$createViewport());
}
// Render nearby entities
if (shouldRenderEntities) {
@@ -623,8 +743,6 @@ public class ShadowRenderer {
// renderBuffersExt.endLevelRendering();
// }
debugStringTerrain = SodiumWorldRenderer.getInstance().getChunksDebugString();
profiler.endStartSection("generate mipmaps");
generateMipmaps();
@@ -638,17 +756,19 @@ public class ShadowRenderer {
}
ACTIVE = false;
CURRENT_TARGETS = null;
profiler.endSection();
profiler.endStartSection("updatechunks");
}
public void addDebugText(List<String> messages) {
messages.add("[" + Iris.MODNAME + "] Shadow Maps: " + debugStringOverall);
messages.add("[" + Iris.MODNAME + "] Shadow Distance Terrain: " + terrainFrustumHolder.getDistanceInfo() + " Entity: " + entityFrustumHolder.getDistanceInfo());
messages.add("[" + Iris.MODNAME + "] Shadow Culling Terrain: " + terrainFrustumHolder.getCullingInfo() + " Entity: " + entityFrustumHolder.getCullingInfo());
messages.add("[" + Iris.MODNAME + "] Shadow Terrain: " + debugStringTerrain + (shouldRenderTerrain ? "" : " (no terrain) ") + (shouldRenderTranslucent ? "" : "(no translucent)"));
messages.add("[" + Iris.MODNAME + "] Shadow Entities: " + getEntitiesDebugString());
messages.add("[" + Iris.MODNAME + "] Shadow Block Entities: " + getTileEntitiesDebugString());
messages.add("[" + Iris.MODNAME + " - Shadow Pass]");
messages.add(" Shadow Maps: " + debugStringOverall);
messages.add(" Shadow Distance Terrain: " + terrainFrustumHolder.getDistanceInfo() + " Entity: " + entityFrustumHolder.getDistanceInfo());
messages.add(" Shadow Culling Terrain: " + terrainFrustumHolder.getCullingInfo() + " Entity: " + entityFrustumHolder.getCullingInfo());
messages.add(" Shadow Terrain: " + CeleritasWorldRenderer.getInstance().getChunksDebugString() + (shouldRenderTerrain ? "" : " (no terrain) ") + (shouldRenderTranslucent ? "" : "(no translucent)"));
messages.add(" Shadow Entities: " + getEntitiesDebugString());
messages.add(" Shadow Block Entities: " + getTileEntitiesDebugString());
// if (buffers instanceof DrawCallTrackingRenderBuffers drawCallTracker && (shouldRenderEntities || shouldRenderPlayer)) {
// messages.add("[" + Iris.MODNAME + "] Shadow Entity Batching: " + BatchingDebugMessageHelper.getDebugMessage(drawCallTracker));
@@ -1,189 +0,0 @@
package net.coderbot.iris.pipeline;
import lombok.Getter;
import net.coderbot.iris.gl.program.ProgramImages;
import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.program.ProgramUniforms;
import net.coderbot.iris.pipeline.transform.PatchShaderType;
import net.coderbot.iris.shaderpack.ProgramSet;
import net.coderbot.iris.uniforms.CommonUniforms;
import net.coderbot.iris.uniforms.ExternallyManagedUniforms;
import net.coderbot.iris.uniforms.builtin.BuiltinReplacementUniforms;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.IntFunction;
import net.coderbot.iris.Iris;
public class SodiumTerrainPipeline {
Optional<String> terrainVertex = Optional.empty();
Optional<String> terrainGeometry = Optional.empty();
Optional<String> terrainFragment = Optional.empty();
Optional<String> translucentVertex = Optional.empty();
Optional<String> translucentGeometry = Optional.empty();
Optional<String> translucentFragment = Optional.empty();
Optional<String> shadowVertex = Optional.empty();
Optional<String> shadowGeometry = Optional.empty();
Optional<String> shadowFragment = Optional.empty();
//GlFramebuffer framebuffer;
ProgramSet programSet;
@Getter
private final CustomUniforms customUniforms;
private final WorldRenderingPipeline parent;
private final IntFunction<ProgramSamplers> createTerrainSamplers;
private final IntFunction<ProgramSamplers> createShadowSamplers;
private final IntFunction<ProgramImages> createTerrainImages;
private final IntFunction<ProgramImages> createShadowImages;
public SodiumTerrainPipeline(WorldRenderingPipeline parent,
ProgramSet programSet, IntFunction<ProgramSamplers> createTerrainSamplers,
IntFunction<ProgramSamplers> createShadowSamplers,
IntFunction<ProgramImages> createTerrainImages,
IntFunction<ProgramImages> createShadowImages, CustomUniforms customUniforms,
String terrainSourceName,
String translucentSourceName,
String shadowSourceName,
CompletableFuture<Map<PatchShaderType, String>> terrainFuture,
CompletableFuture<Map<PatchShaderType, String>> translucentFuture,
CompletableFuture<Map<PatchShaderType, String>> shadowFuture) {
this.parent = Objects.requireNonNull(parent);
this.programSet = programSet;
this.customUniforms = customUniforms;
if (terrainFuture != null) {
try {
Map<PatchShaderType, String> result = terrainFuture.join();
terrainVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX));
terrainGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY));
terrainFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT));
PatchedShaderPrinter.debugPatchedShaders(terrainSourceName + "_sodium",
terrainVertex.orElse(null), terrainGeometry.orElse(null), terrainFragment.orElse(null));
} catch (Exception e) {
Iris.logger.error("Failed to transform terrain shader: {}", terrainSourceName, e);
throw new RuntimeException("Shader transformation failed for " + terrainSourceName, e);
}
}
if (translucentFuture != null) {
try {
Map<PatchShaderType, String> result = translucentFuture.join();
translucentVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX));
translucentGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY));
translucentFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT));
PatchedShaderPrinter.debugPatchedShaders(translucentSourceName + "_sodium",
translucentVertex.orElse(null), translucentGeometry.orElse(null), translucentFragment.orElse(null));
} catch (Exception e) {
Iris.logger.error("Failed to transform translucent shader: {}", translucentSourceName, e);
throw new RuntimeException("Shader transformation failed for " + translucentSourceName, e);
}
}
if (shadowFuture != null) {
try {
Map<PatchShaderType, String> result = shadowFuture.join();
shadowVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX));
shadowGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY));
shadowFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT));
PatchedShaderPrinter.debugPatchedShaders(shadowSourceName + "_sodium",
shadowVertex.orElse(null), shadowGeometry.orElse(null), shadowFragment.orElse(null));
} catch (Exception e) {
Iris.logger.error("Failed to transform shadow shader: {}", shadowSourceName, e);
throw new RuntimeException("Shader transformation failed for " + shadowSourceName, e);
}
}
this.createTerrainSamplers = createTerrainSamplers;
this.createShadowSamplers = createShadowSamplers;
this.createTerrainImages = createTerrainImages;
this.createShadowImages = createShadowImages;
}
public Optional<String> getTerrainVertexShaderSource() {
return terrainVertex;
}
public Optional<String> getTerrainGeometryShaderSource() {
return terrainGeometry;
}
public Optional<String> getTerrainFragmentShaderSource() {
return terrainFragment;
}
public Optional<String> getTranslucentVertexShaderSource() {
return translucentVertex;
}
public Optional<String> getTranslucentGeometryShaderSource() {
return translucentGeometry;
}
public Optional<String> getTranslucentFragmentShaderSource() {
return translucentFragment;
}
public Optional<String> getShadowVertexShaderSource() {
return shadowVertex;
}
public Optional<String> getShadowGeometryShaderSource() {
return shadowGeometry;
}
public Optional<String> getShadowFragmentShaderSource() {
return shadowFragment;
}
public ProgramUniforms.Builder initUniforms(int programId) {
ProgramUniforms.Builder uniforms = ProgramUniforms.builder("<sodium shaders>", programId);
CommonUniforms.addDynamicUniforms(uniforms);
customUniforms.assignTo(uniforms);
ExternallyManagedUniforms.addExternallyManagedUniforms116(uniforms);
BuiltinReplacementUniforms.addBuiltinReplacementUniforms(uniforms);
return uniforms;
}
public boolean hasShadowPass() {
return createShadowSamplers != null;
}
public ProgramSamplers initTerrainSamplers(int programId) {
return createTerrainSamplers.apply(programId);
}
public ProgramSamplers initShadowSamplers(int programId) {
return createShadowSamplers.apply(programId);
}
public ProgramImages initTerrainImages(int programId) {
return createTerrainImages.apply(programId);
}
public ProgramImages initShadowImages(int programId) {
return createShadowImages.apply(programId);
}
/*public void bindFramebuffer() {
this.framebuffer.bind();
}
public void unbindFramebuffer() {
GlStateManager.bindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
}*/
}
@@ -4,6 +4,7 @@ import com.gtnewhorizons.angelica.compat.mojang.Camera;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.gbuffer_overrides.state.RenderTargetStateListener;
import net.coderbot.iris.celeritas.CeleritasTerrainPipeline;
import net.coderbot.iris.shaderpack.CloudSetting;
import net.coderbot.iris.uniforms.FrameUpdateNotifier;
import net.minecraft.client.renderer.EntityRenderer;
@@ -19,13 +20,10 @@ public interface WorldRenderingPipeline {
WorldRenderingPhase getPhase();
void beginSodiumTerrainRendering();
void endSodiumTerrainRendering();
void setOverridePhase(WorldRenderingPhase phase);
void setPhase(WorldRenderingPhase phase);
void setInputs(InputAvailability availability);
void setSpecialCondition(SpecialCondition special);
void syncProgram();
RenderTargetStateListener getRenderTargetStateListener();
int getCurrentNormalTexture();
@@ -39,7 +37,7 @@ public interface WorldRenderingPipeline {
void finalizeLevelRendering();
void destroy();
SodiumTerrainPipeline getSodiumTerrainPipeline();
CeleritasTerrainPipeline getCeleritasTerrainPipeline();
FrameUpdateNotifier getFrameUpdateNotifier();
boolean shouldDisableVanillaEntityShadows();
@@ -0,0 +1,112 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Transformer;
import java.util.HashMap;
import java.util.Map;
import static net.coderbot.iris.pipeline.transform.PatchShaderType.FRAGMENT;
import static net.coderbot.iris.pipeline.transform.PatchShaderType.VERTEX;
class CeleritasTransformer {
public static void transform(Transformer transformer, Parameters parameters) {
switch (parameters.type) {
// For Celeritas patching, treat fragment and geometry the same
case FRAGMENT:
case GEOMETRY:
transformFragment(transformer, parameters);
break;
case VERTEX:
transformVertex(transformer, parameters);
break;
default:
throw new IllegalStateException("Unexpected Celeritas terrain patching shader type: " + parameters.type);
}
}
public static void transformVertex(Transformer transformer, Parameters parameters) {
transformer.injectVariable("uniform vec3 u_RegionOffset;"); // Per-region offset from setRegionOffset()
transformer.injectVariable("vec4 iris_LightTexCoord;");
transformer.injectFunction("vec4 iris_ftransform() { return gl_ModelViewProjectionMatrix * _celeritas_getVertexPosition(); }");
transformer.injectFunction(
"vec4 _celeritas_getVertexPosition() { " +
"return vec4(_vert_position + u_RegionOffset + _get_draw_translation(_draw_id), 1.0); }");
transformer.injectFunction(
"void _celeritas_init() { " +
"_vert_init(); " +
"iris_LightTexCoord = vec4(vec2(_vert_tex_light_coord), 0.0, 1.0); }");
transformer.prependMain("_celeritas_init();");
transformShared(transformer, parameters);
final Map<String, String> vertexReplacements = new HashMap<>();
vertexReplacements.put("gl_Vertex", "_celeritas_getVertexPosition()");
vertexReplacements.put("gl_MultiTexCoord0", "vec4(_vert_tex_diffuse_coord, 0.0, 1.0)");
vertexReplacements.put("gl_MultiTexCoord1", "iris_LightTexCoord");
vertexReplacements.put("gl_MultiTexCoord2", "iris_LightTexCoord");
vertexReplacements.forEach(transformer::replaceExpression);
final Map<String, String> vertexRenames = new HashMap<>();
vertexRenames.put("gl_Color", "_vert_color");
vertexRenames.put("ftransform", "iris_ftransform");
vertexRenames.put("gl_Normal", "iris_Normal");
vertexRenames.put("chunkOffset", "u_RegionOffset");
transformer.rename(vertexRenames);
transformer.injectVariable("in vec3 iris_Normal;");
}
public static void transformFragment(Transformer transformer, Parameters parameters) {
// interestingly there is nothing that isn't shared
transformShared(transformer, parameters);
}
private static void transformShared(Transformer transformer, Parameters parameters) {
transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;");
transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;");
transformer.injectVariable("uniform mat4 iris_ProjectionMatrix;");
transformer.injectVariable("uniform mat4 iris_ProjectionMatrixInverse;");
transformer.injectVariable("uniform mat3 iris_NormalMatrix;");
transformer.injectVariable("uniform mat4 iris_LightmapTextureMatrix;");
final Map<String, String> renames = new HashMap<>();
renames.put("gl_ModelViewMatrix", "iris_ModelViewMatrix");
renames.put("gl_ModelViewMatrixInverse", "iris_ModelViewMatrixInverse");
renames.put("gl_ProjectionMatrix", "iris_ProjectionMatrix");
renames.put("gl_ProjectionMatrixInverse", "iris_ProjectionMatrixInverse");
renames.put("gl_NormalMatrix", "iris_NormalMatrix");
transformer.rename(renames);
final Map<String, String> sharedReplacements = new HashMap<>();
sharedReplacements.put("gl_TextureMatrix[0]", "mat4(1.0)");
sharedReplacements.put("gl_TextureMatrix[1]", "iris_LightmapTextureMatrix");
sharedReplacements.put("gl_ModelViewProjectionMatrix", "(iris_ProjectionMatrix * iris_ModelViewMatrix)");
sharedReplacements.forEach(transformer::replaceExpression);
transformFog(transformer, parameters);
}
private static void transformFog(Transformer transformer, Parameters parameters) {
transformer.injectVariable("uniform float iris_FogDensity;");
transformer.injectVariable("uniform float iris_FogStart;");
transformer.injectVariable("uniform float iris_FogEnd;");
transformer.injectVariable("uniform vec4 iris_FogColor;");
transformer.injectFunction("struct iris_FogParameters { vec4 color; float density; float start; float end; float scale; };");
transformer.injectFunction(
"iris_FogParameters iris_Fog = iris_FogParameters(iris_FogColor, iris_FogDensity, " +
"iris_FogStart, iris_FogEnd, 1.0 / (iris_FogEnd - iris_FogStart));");
final Map<String, String> fogRenames = new HashMap<>();
fogRenames.put("gl_Fog", "iris_Fog");
fogRenames.put("gl_FogFragCoord", "iris_FogFragCoord");
transformer.rename(fogRenames);
if (parameters.type == VERTEX) {
transformer.injectVariable("out float iris_FogFragCoord;");
transformer.prependMain("iris_FogFragCoord = 0.0;");
} else if (parameters.type == FRAGMENT) {
transformer.injectVariable("in float iris_FogFragCoord;");
}
}
}
@@ -2,6 +2,6 @@ package net.coderbot.iris.pipeline.transform;
public enum Patch {
ATTRIBUTES,
SODIUM_TERRAIN,
CELERITAS_TERRAIN,
COMPOSITE
}
@@ -7,6 +7,8 @@ public enum PatchShaderType {
GEOMETRY(ShaderType.GEOMETRY),
FRAGMENT(ShaderType.FRAGMENT);
public static final PatchShaderType[] VALUES = values();
public final ShaderType glShaderType;
private PatchShaderType(ShaderType glShaderType) {
@@ -1,6 +1,7 @@
package net.coderbot.iris.pipeline.transform;
import com.google.common.base.Stopwatch;
import com.gtnewhorizons.angelica.rendering.celeritas.iris.IrisExtendedChunkVertexType;
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.shader.ShaderType;
@@ -8,6 +9,8 @@ import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
import org.taumc.glsl.ShaderParser;
import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLLexer;
@@ -139,7 +142,7 @@ public class ShaderTransformer {
Stopwatch watch = Stopwatch.createStarted();
for (PatchShaderType type : PatchShaderType.values()) {
for (PatchShaderType type : PatchShaderType.VALUES) {
parameters.type = type;
if (inputs.get(type) == null) {
continue;
@@ -205,11 +208,18 @@ public class ShaderTransformer {
CompatibilityTransformer.transformGrouped(types, parameters);
for (var entry : types.entrySet()) {
final Transformer transformer = entry.getValue();
final String header = prepatched.get(entry.getKey());
String header = prepatched.get(entry.getKey());
// For Celeritas terrain vertex shaders, inject chunk_vertex.glsl header
if (patchType == Patch.CELERITAS_TERRAIN && entry.getKey() == PatchShaderType.VERTEX) {
header += computeCeleritasHeader();
}
final String finalHeader = header;
final StringBuilder formattedShaderBuilder = new StringBuilder();
transformer.mutateTree(tree -> {
formattedShaderBuilder.append(getFormattedShader(tree, header));
formattedShaderBuilder.append(getFormattedShader(tree, finalHeader));
});
String formattedShader = formattedShaderBuilder.toString();
@@ -250,8 +260,12 @@ public class ShaderTransformer {
private static void doTransform(Transformer transformer, Patch patchType, Parameters parameters, String profile, int versionInt) {
switch (patchType) {
case SODIUM_TERRAIN:
SodiumTransformer.transform(transformer, parameters);
case CELERITAS_TERRAIN:
CeleritasTransformer.transform(transformer, parameters);
// Handle mc_midTexCoord for Celeritas
patchMultiTexCoord3(transformer, parameters);
replaceMidTexCoord(transformer, IrisExtendedChunkVertexType.MID_TEX_SCALE);
applyIntelHd4000Workaround(transformer);
break;
case COMPOSITE:
CompositeDepthTransformer.transform(transformer);
@@ -326,6 +340,21 @@ public class ShaderTransformer {
}
}
private static String computeCeleritasHeader() {
final ShaderConstants constants = ShaderConstants.builder()
.add("VERT_POS_SCALE", "1.0")
.add("VERT_POS_OFFSET", "0.0")
.add("VERT_TEX_SCALE", "1.0")
.build();
final String chunkVertexHeader = org.embeddedt.embeddium.impl.gl.shader.ShaderParser.parseShader(
ShaderLoader.getShaderSource("sodium:include/chunk_vertex.glsl"),
ShaderLoader::getShaderSource,
constants);
return "\n\n" + chunkVertexHeader + "\n\n";
}
public static String getFormattedShader(ParseTree tree, String string) {
StringBuilder sb = new StringBuilder(string + "\n");
String[] tabHolder = {""};
@@ -1,86 +0,0 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Transformer;
import java.util.HashMap;
import java.util.Map;
class SodiumTransformer {
public static void transform(Transformer transformer, Parameters parameters) {
switch (parameters.type) {
// For Sodium patching, treat fragment and geometry the same
case FRAGMENT:
case GEOMETRY:
transformFragment(transformer, parameters);
break;
case VERTEX:
transformVertex(transformer, parameters);
break;
default:
throw new IllegalStateException("Unexpected Sodium terrain patching shader type: " + parameters.type);
}
}
/**
* Transforms vertex shaders.
*/
public static void transformVertex(Transformer transformer, Parameters parameters) {
transformer.injectVariable("attribute vec3 iris_Pos;");
transformer.injectVariable("attribute vec4 iris_Color;");
transformer.injectVariable("attribute vec2 iris_TexCoord;");
transformer.injectVariable("attribute vec2 iris_LightCoord;");
transformer.injectVariable("attribute vec3 iris_Normal;");
transformer.injectVariable("uniform vec3 u_ModelScale;");
transformer.injectVariable("uniform vec2 u_TextureScale;");
transformer.injectVariable("attribute vec4 iris_ModelOffset;");
transformer.injectFunction("vec4 iris_LightTexCoord = vec4(iris_LightCoord, 0, 1);");
transformer.injectFunction("vec4 ftransform() { return gl_ModelViewProjectionMatrix * gl_Vertex; }");
transformShared(transformer, parameters);
Map<String, String> vertexReplacements = new HashMap<>();
vertexReplacements.put("gl_Vertex", "vec4((iris_Pos * u_ModelScale) + iris_ModelOffset.xyz, 1.0)");
vertexReplacements.put("gl_MultiTexCoord0", "vec4(iris_TexCoord * u_TextureScale, 0.0, 1.0)");
vertexReplacements.put("gl_MultiTexCoord1", "iris_LightTexCoord");
vertexReplacements.put("gl_MultiTexCoord2", "iris_LightTexCoord");
vertexReplacements.forEach(transformer::replaceExpression);
Map<String, String> vertexRenames = new HashMap<>();
vertexRenames.put("gl_Color", "iris_Color");
vertexRenames.put("gl_Normal", "iris_Normal");
vertexRenames.put("ftransform", "iris_ftransform");
transformer.rename(vertexRenames);
}
/**
* Transforms fragment shaders. The fragment shader does only the shared things
* from the vertex shader.
*/
public static void transformFragment(Transformer transformer, Parameters parameters) {
// interestingly there is nothing that isn't shared
transformShared(transformer, parameters);
}
/**
* Does the things that transformVertex and transformFragment have in common.
*/
private static void transformShared(Transformer transformer, Parameters parameters) {
transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;");
transformer.injectVariable("uniform mat4 u_ModelViewProjectionMatrix;");
transformer.injectVariable("uniform mat4 iris_NormalMatrix;");
transformer.injectVariable("uniform mat4 iris_LightmapTextureMatrix;");
Map<String, String> renames = new HashMap<>();
renames.put("gl_ModelViewMatrix", "iris_ModelViewMatrix");
renames.put("gl_ModelViewProjectionMatrix", "u_ModelViewProjectionMatrix");
transformer.rename(renames);
Map<String, String> sharedReplacements = new HashMap<>();
sharedReplacements.put("gl_NormalMatrix", "mat3(iris_NormalMatrix)");
sharedReplacements.put("gl_TextureMatrix[0]", "mat4(1.0)");
sharedReplacements.put("gl_TextureMatrix[1]", "iris_LightmapTextureMatrix");
sharedReplacements.forEach(transformer::replaceExpression);
}
}
@@ -113,8 +113,8 @@ public class TransformPatcher {
return transform(vertex, geometry, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs));
}
public static Map<PatchShaderType, String> patchSodiumTerrain(String vertex, String geometry, String fragment) {
return transform(vertex, geometry, fragment, new Parameters(Patch.SODIUM_TERRAIN));
public static Map<PatchShaderType, String> patchCeleritasTerrain(String vertex, String geometry, String fragment) {
return transform(vertex, geometry, fragment, new Parameters(Patch.CELERITAS_TERRAIN));
}
public static Map<PatchShaderType, String> patchComposite(String vertex, String geometry, String fragment) {
@@ -3,7 +3,7 @@ package net.coderbot.iris.shadows.frustum;
import net.minecraft.util.AxisAlignedBB;
public class BoxCuller {
private final double maxDistance;
private double maxDistance;
private double minAllowedX;
private double maxAllowedX;
@@ -16,6 +16,10 @@ public class BoxCuller {
this.maxDistance = maxDistance;
}
public void setMaxDistance(double maxDistance) {
this.maxDistance = maxDistance;
}
public void setPosition(double cameraX, double cameraY, double cameraZ) {
this.minAllowedX = cameraX - maxDistance;
this.maxAllowedX = cameraX + maxDistance;
@@ -39,10 +43,19 @@ public class BoxCuller {
return true;
}
if (maxZ < this.minAllowedZ || minZ > this.maxAllowedZ) {
return maxZ < this.minAllowedZ || minZ > this.maxAllowedZ;
}
// View-relative coordinates version
public boolean isCulledViewRelative(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
if (maxX < -this.maxDistance || minX > this.maxDistance) {
return true;
}
return false;
if (maxY < -this.maxDistance || minY > this.maxDistance) {
return true;
}
return maxZ < -this.maxDistance || minZ > this.maxDistance;
}
}
@@ -2,22 +2,26 @@ package net.coderbot.iris.shadows.frustum;
import net.minecraft.client.renderer.culling.Frustrum;
import net.minecraft.util.AxisAlignedBB;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.render.viewport.ViewportProvider;
import org.embeddedt.embeddium.impl.render.viewport.frustum.Frustum;
import org.joml.Vector3d;
public class CullEverythingFrustum extends Frustrum {
// for Sodium
public boolean fastAabbTest(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return false;
}
// For Immersive Portals
// We return false here since isVisible is going to return false anyways.
public boolean canDetermineInvisible(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) {
return false;
}
public class CullEverythingFrustum extends Frustrum implements ViewportProvider, Frustum {
private final Vector3d position = new Vector3d();
@Override
public boolean isBoundingBoxInFrustum(AxisAlignedBB aabb) {
return false;
}
@Override
public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return false;
}
@Override
public Viewport sodium$createViewport() {
return new Viewport(this, position.set(xPosition, yPosition, zPosition));
}
}
@@ -3,8 +3,12 @@ package net.coderbot.iris.shadows.frustum.advanced;
import net.coderbot.iris.shadows.frustum.BoxCuller;
import net.minecraft.client.renderer.culling.Frustrum;
import net.minecraft.util.AxisAlignedBB;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.render.viewport.ViewportProvider;
import org.embeddedt.embeddium.impl.render.viewport.frustum.Frustum;
import org.joml.Math;
import org.joml.Matrix4f;
import org.joml.Vector3d;
import org.joml.Vector3f;
import org.joml.Vector4f;
@@ -28,7 +32,7 @@ import org.joml.Vector4f;
* are not sensitive to the specific internal ordering of planes and corners, in order to avoid potential bugs at the
* cost of slightly more computations.</p>
*/
public class AdvancedShadowCullingFrustum extends Frustrum {
public class AdvancedShadowCullingFrustum extends Frustrum implements ViewportProvider, Frustum {
private static final int MAX_CLIPPING_PLANES = 13;
/**
@@ -59,30 +63,47 @@ public class AdvancedShadowCullingFrustum extends Frustrum {
* </ul>
* </p>
*/
private static final Vector3f scratch3a = new Vector3f();
private static final Vector3f scratch3b = new Vector3f();
private static final Vector3f scratch3c = new Vector3f();
private static final Vector3f scratch3d = new Vector3f();
private static final Vector3f scratch3e = new Vector3f();
private static final Vector3f scratch3f = new Vector3f();
private final Vector4f[] planes = new Vector4f[MAX_CLIPPING_PLANES];
private int planeCount = 0;
// The center coordinates of this frustum.
private double x;
private double y;
private double z;
private final Vector3f shadowLightVectorFromOrigin = new Vector3f();
private BoxCuller boxCuller;
private final Vector3d position = new Vector3d();
private final Vector3f shadowLightVectorFromOrigin;
private final BoxCuller boxCuller;
private final BaseClippingPlanes baseClippingPlanes = new BaseClippingPlanes();
private final boolean[] isBackArray = new boolean[6];
public AdvancedShadowCullingFrustum(Matrix4f playerView, Matrix4f playerProjection, Vector3f shadowLightVectorFromOrigin,
BoxCuller boxCuller) {
this.shadowLightVectorFromOrigin = shadowLightVectorFromOrigin;
BaseClippingPlanes baseClippingPlanes = new BaseClippingPlanes(playerView, playerProjection);
boolean[] isBack = addBackPlanes(baseClippingPlanes);
addEdgePlanes(baseClippingPlanes, isBack);
public AdvancedShadowCullingFrustum() {
for (int i = 0; i < MAX_CLIPPING_PLANES; i++) {
planes[i] = new Vector4f();
}
}
public void init(Matrix4f playerView, Matrix4f playerProjection, Vector3f shadowLightVector, BoxCuller boxCuller) {
this.shadowLightVectorFromOrigin.set(shadowLightVector);
this.boxCuller = boxCuller;
this.planeCount = 0;
baseClippingPlanes.init(playerView, playerProjection);
addBackPlanes(baseClippingPlanes, isBackArray);
addEdgePlanes(baseClippingPlanes, isBackArray);
}
private void addPlane(Vector4f plane) {
planes[planeCount] = plane;
planes[planeCount].set(plane);
planeCount += 1;
}
private void addPlane(float x, float y, float z, float w) {
planes[planeCount].set(x, y, z, w);
planeCount += 1;
}
@@ -91,24 +112,23 @@ public class AdvancedShadowCullingFrustum extends Frustrum {
* This can eliminate many chunks, especially if the player is staring at the shadow light
* (sun / moon).
*/
private boolean[] addBackPlanes(BaseClippingPlanes baseClippingPlanes) {
Vector4f[] planes = baseClippingPlanes.getPlanes();
boolean[] isBack = new boolean[planes.length];
private void addBackPlanes(BaseClippingPlanes baseClippingPlanes, boolean[] isBack) {
final Vector4f[] basePlanes = baseClippingPlanes.getPlanes();
for (int planeIndex = 0; planeIndex < planes.length; planeIndex++) {
Vector4f plane = planes[planeIndex];
Vector3f planeNormal = truncate(plane);
for (int planeIndex = 0; planeIndex < basePlanes.length; planeIndex++) {
final Vector4f plane = basePlanes[planeIndex];
truncate(plane, scratch3a);
// Find back planes by looking for planes with a normal vector that points
// in the same general direction as the vector pointing from the origin to the shadow light
//
// That is, the angle between those two vectors is less than or equal to 90 degrees,
// meaning that the dot product is positive or zero.
float dot = planeNormal.dot(shadowLightVectorFromOrigin);
final float dot = scratch3a.dot(shadowLightVectorFromOrigin);
boolean back = dot > 0.0;
boolean edge = dot == 0.0;
final boolean back = dot > 0.0;
final boolean edge = dot == 0.0;
// TODO: audit behavior when the dot product is zero
isBack[planeIndex] = back;
@@ -117,21 +137,18 @@ public class AdvancedShadowCullingFrustum extends Frustrum {
addPlane(plane);
}
}
return isBack;
}
private void addEdgePlanes(BaseClippingPlanes baseClippingPlanes, boolean[] isBack) {
Vector4f[] planes = baseClippingPlanes.getPlanes();
final Vector4f[] planes = baseClippingPlanes.getPlanes();
for (int planeIndex = 0; planeIndex < planes.length; planeIndex++) {
if (!isBack[planeIndex]) {
continue;
}
Vector4f plane = planes[planeIndex];
NeighboringPlaneSet neighbors = NeighboringPlaneSet.forPlane(planeIndex);
final Vector4f plane = planes[planeIndex];
final NeighboringPlaneSet neighbors = NeighboringPlaneSet.forPlane(planeIndex);
if (!isBack[neighbors.getPlane0()]) {
addEdgePlane(plane, planes[neighbors.getPlane0()]);
@@ -151,40 +168,33 @@ public class AdvancedShadowCullingFrustum extends Frustrum {
}
}
private Vector3f truncate(Vector4f base) {
return new Vector3f(base.x(), base.y(), base.z());
}
private Vector4f extend(Vector3f base, float w) {
return new Vector4f(base.x(), base.y(), base.z(), w);
private Vector3f truncate(Vector4f base, Vector3f dest) {
return dest.set(base.x(), base.y(), base.z());
}
private float lengthSquared(Vector3f v) {
float x = v.x();
float y = v.y();
float z = v.z();
final float x = v.x();
final float y = v.y();
final float z = v.z();
return x * x + y * y + z * z;
}
private Vector3f cross(Vector3f first, Vector3f second) {
Vector3f result = new Vector3f(first.x(), first.y(), first.z());
result.cross(second);
return result;
private Vector3f cross(Vector3f first, Vector3f second, Vector3f dest) {
return dest.set(first).cross(second);
}
private void addEdgePlane(Vector4f backPlane4, Vector4f frontPlane4) {
Vector3f backPlaneNormal = truncate(backPlane4);
Vector3f frontPlaneNormal = truncate(frontPlane4);
final Vector3f backPlaneNormal = truncate(backPlane4, scratch3a);
final Vector3f frontPlaneNormal = truncate(frontPlane4, scratch3b);
// vector along the intersection of the two planes
Vector3f intersection = cross(backPlaneNormal, frontPlaneNormal);
final Vector3f intersection = cross(backPlaneNormal, frontPlaneNormal, scratch3c);
// compute edge plane normal, we want the normal vector of the edge plane
// to always be perpendicular to the shadow light vector (since that's
// what makes it an edge plane!)
Vector3f edgePlaneNormal = cross(intersection, shadowLightVectorFromOrigin);
final Vector3f edgePlaneNormal = cross(intersection, shadowLightVectorFromOrigin, scratch3d);
// At this point, we have a normal vector for our new edge plane, but we don't
// have a value for distance (d). We can solve for it with a little algebra,
@@ -204,16 +214,15 @@ public class AdvancedShadowCullingFrustum extends Frustrum {
// Fortunately, we can compute that point. If we create a plane passing through the origin
// with a normal vector parallel to the intersection line, then the intersection
// of all 3 planes will be a point on the line of intersection between the two planes we care about.
Vector3f point;
final Vector3f point;
{
// "Line of intersection between two planes"
// https://stackoverflow.com/a/32410473 by ideasman42, CC BY-SA 3.0
// (a modified version of "Intersection of 2-planes" from Graphics Gems 1, page 305
// NB: We can assume that the intersection vector has a non-zero length.
Vector3f ixb = cross(intersection, backPlaneNormal);
Vector3f fxi = cross(frontPlaneNormal, intersection);
final Vector3f ixb = cross(intersection, backPlaneNormal, scratch3e);
final Vector3f fxi = cross(frontPlaneNormal, intersection, scratch3f);
ixb.mul(-frontPlane4.w());
fxi.mul(-backPlane4.w());
@@ -225,54 +234,23 @@ public class AdvancedShadowCullingFrustum extends Frustrum {
}
// Now that we have a point and a normal vector, we can make a plane.
// dot(normal, (x, y, z) - point) = 0
// a(x - point.x) + b(y - point.y) + c(z - point.z) = 0
// d = a * point.x + b * point.y + c * point.z = dot(normal, point)
// w = -d
Vector4f plane;
{
// dot(normal, (x, y, z) - point) = 0
// a(x - point.x) + b(y - point.y) + c(z - point.z) = 0
// d = a * point.x + b * point.y + c * point.z = dot(normal, point)
// w = -d
float d = edgePlaneNormal.dot(point);
float w = -d;
plane = extend(edgePlaneNormal, w);
}
// Check and make sure our point is actually on all 3 planes.
// This can be removed in production but it's good to check for now while we're still testing.
/*{
float dp0 = plane.dotProduct(extend(point, 1.0F));
float dp1 = frontPlane4.dotProduct(extend(point, 1.0F));
float dp2 = backPlane4.dotProduct(extend(point, 1.0F));
if (Math.abs(dp0) > 0.0005) {
throw new IllegalStateException("dp0 should be zero, but was " + dp0);
}
if (Math.abs(dp1) > 0.0005) {
throw new IllegalStateException("dp1 should be zero, but was " + dp1);
}
if (Math.abs(dp2) > 0.0005) {
throw new IllegalStateException("dp2 should be zero, but was " + dp2);
}
}*/
addPlane(plane);
final float d = edgePlaneNormal.dot(point);
addPlane(edgePlaneNormal.x(), edgePlaneNormal.y(), edgePlaneNormal.z(), -d);
}
// Note: These functions are copied & modified from the vanilla Frustum class.
@Override
public void setPosition(double cameraX, double cameraY, double cameraZ) {
super.setPosition(cameraX, cameraY, cameraZ);
if (this.boxCuller != null) {
boxCuller.setPosition(cameraX, cameraY, cameraZ);
}
this.x = cameraX;
this.y = cameraY;
this.z = cameraZ;
}
@Override
@@ -284,77 +262,40 @@ public class AdvancedShadowCullingFrustum extends Frustrum {
return this.isVisible(aabb.minX, aabb.minY, aabb.minZ, aabb.maxX, aabb.maxY, aabb.maxZ);
}
// For Sodium
// TODO: change this to respect intersections on 1.18+!
public boolean fastAabbTest(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
if (boxCuller != null && boxCuller.isCulled(minX, minY, minZ, maxX, maxY, maxZ)) {
// Embeddium Frustum interface - receives view-relative coords
@Override
public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
if (boxCuller != null && boxCuller.isCulledViewRelative(minX, minY, minZ, maxX, maxY, maxZ)) {
return false;
}
return isVisible(minX, minY, minZ, maxX, maxY, maxZ);
return checkCornerVisibility(minX, minY, minZ, maxX, maxY, maxZ);
}
// For Immersive Portals
// TODO: Figure out if IP culling can somehow be compatible with Iris culling.
public boolean canDetermineInvisible(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) {
return false;
@Override
public Viewport sodium$createViewport() {
return new Viewport(this, position.set(xPosition, yPosition, zPosition));
}
private boolean isVisible(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) {
float f = (float)(minX - this.x);
float g = (float)(minY - this.y);
float h = (float)(minZ - this.z);
float i = (float)(maxX - this.x);
float j = (float)(maxY - this.y);
float k = (float)(maxZ - this.z);
return this.checkCornerVisibility(f, g, h, i, j, k) != 0;
return this.checkCornerVisibility((float)(minX - xPosition), (float)(minY - yPosition), (float)(minZ - zPosition),
(float)(maxX - xPosition), (float)(maxY - yPosition), (float)(maxZ - zPosition));
}
/**
* Checks corner visibility.
* @param minX Minimum X value of the AABB.
* @param minY Minimum Y value of the AABB.
* @param minZ Minimum Z value of the AABB.
* @param maxX Maximum X value of the AABB.
* @param maxY Maximum Y value of the AABB.
* @param maxZ Maximum Z value of the AABB.
* @return 0 if nothing is visible, 1 if everything is visible, 2 if only some corners are visible.
*/
private int checkCornerVisibility(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
float outsideBoundX;
float outsideBoundY;
float outsideBoundZ;
// view-relative coordinates.
private boolean checkCornerVisibility(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
for (int i = 0; i < planeCount; ++i) {
Vector4f plane = this.planes[i];
final Vector4f plane = this.planes[i];
// Check if plane is inside or intersecting.
// This is ported from JOML's FrustumIntersection.
if (plane.x() < 0) {
outsideBoundX = minX;
} else {
outsideBoundX = maxX;
}
if (plane.y() < 0) {
outsideBoundY = minY;
} else {
outsideBoundY = maxY;
}
if (plane.z() < 0) {
outsideBoundZ = minZ;
} else {
outsideBoundZ = maxZ;
}
final float outsideBoundX = plane.x() < 0 ? minX : maxX;
final float outsideBoundY = plane.y() < 0 ? minY : maxY;
final float outsideBoundZ = plane.z() < 0 ? minZ : maxZ;
if (Math.fma(plane.x(), outsideBoundX, Math.fma(plane.y(), outsideBoundY, plane.z() * outsideBoundZ)) < -plane.w()) {
return 0;
return false;
}
}
return 2;
return true;
}
}
@@ -5,34 +5,34 @@ import org.joml.Vector4f;
public class BaseClippingPlanes {
private final Vector4f[] planes = new Vector4f[6];
private final Matrix4f transformScratch = new Matrix4f();
public BaseClippingPlanes(Matrix4f playerView, Matrix4f playerProjection) {
this.init(playerView, playerProjection);
public BaseClippingPlanes() {
for (int i = 0; i < planes.length; i++) {
planes[i] = new Vector4f();
}
}
private void init(Matrix4f view, Matrix4f projection) {
public void init(Matrix4f view, Matrix4f projection) {
// Transform = Transpose(Projection x View)
transformScratch.set(projection);
transformScratch.mul(view);
transformScratch.transpose();
Matrix4f transform = new Matrix4f(projection);
transform.mul(view);
transform.transpose();
planes[0] = transform(transform, -1, 0, 0);
planes[1] = transform(transform, 1, 0, 0);
planes[2] = transform(transform, 0, -1, 0);
planes[3] = transform(transform, 0, 1, 0);
transform(transformScratch, -1, 0, 0, planes[0]);
transform(transformScratch, 1, 0, 0, planes[1]);
transform(transformScratch, 0, -1, 0, planes[2]);
transform(transformScratch, 0, 1, 0, planes[3]);
// FAR clipping plane
planes[4] = transform(transform, 0, 0, -1);
transform(transformScratch, 0, 0, -1, planes[4]);
// NEAR clipping plane
planes[5] = transform(transform, 0, 0, 1);
transform(transformScratch, 0, 0, 1, planes[5]);
}
private static Vector4f transform(Matrix4f transform, float x, float y, float z) {
Vector4f vector4f = new Vector4f(x, y, z, 1.0F);
vector4f.mul(transform);
vector4f.normalize();
return vector4f;
private static void transform(Matrix4f transform, float x, float y, float z, Vector4f dest) {
dest.set(x, y, z, 1.0F);
dest.mul(transform);
dest.normalize();
}
public Vector4f[] getPlanes() {
@@ -3,9 +3,14 @@ package net.coderbot.iris.shadows.frustum.fallback;
import net.coderbot.iris.shadows.frustum.BoxCuller;
import net.minecraft.client.renderer.culling.Frustrum;
import net.minecraft.util.AxisAlignedBB;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.render.viewport.ViewportProvider;
import org.embeddedt.embeddium.impl.render.viewport.frustum.Frustum;
import org.joml.Vector3d;
public class BoxCullingFrustum extends Frustrum {
public class BoxCullingFrustum extends Frustrum implements ViewportProvider, Frustum {
private final BoxCuller boxCuller;
private final Vector3d position = new Vector3d();
public BoxCullingFrustum(BoxCuller boxCuller) {
this.boxCuller = boxCuller;
@@ -13,25 +18,22 @@ public class BoxCullingFrustum extends Frustrum {
@Override
public void setPosition(double cameraX, double cameraY, double cameraZ) {
super.setPosition(cameraX, cameraY, cameraZ);
boxCuller.setPosition(cameraX, cameraY, cameraZ);
}
// for Sodium
// TODO: Better way to do this... Maybe we shouldn't be using a frustum for the box culling in the first place!
public boolean fastAabbTest(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return !boxCuller.isCulled(minX, minY, minZ, maxX, maxY, maxZ);
}
// For Immersive Portals
// NB: The shadow culling in Immersive Portals must be disabled, because when Advanced Shadow Frustum Culling
// is not active, we are at a point where we can make no assumptions how the shader pack uses the shadow
// pass beyond what it already tells us. So we cannot use any extra fancy culling methods.
public boolean canDetermineInvisible(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) {
return false;
}
@Override
public boolean isBoundingBoxInFrustum(AxisAlignedBB aabb) {
return !boxCuller.isCulled(aabb);
}
@Override
public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return !boxCuller.isCulledViewRelative(minX, minY, minZ, maxX, maxY, maxZ);
}
@Override
public Viewport sodium$createViewport() {
return new Viewport(this, position.set(xPosition, yPosition, zPosition));
}
}
@@ -2,25 +2,26 @@ package net.coderbot.iris.shadows.frustum.fallback;
import net.minecraft.client.renderer.culling.Frustrum;
import net.minecraft.util.AxisAlignedBB;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.render.viewport.ViewportProvider;
import org.embeddedt.embeddium.impl.render.viewport.frustum.Frustum;
import org.joml.Vector3d;
public class NonCullingFrustum extends Frustrum {
// for Sodium
public boolean fastAabbTest(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return true;
}
// For Immersive Portals
// NB: The shadow culling in Immersive Portals must be disabled, because when Advanced Shadow Frustum Culling
// is not active, we are at a point where we can make no assumptions how the shader pack uses the shadow
// pass beyond what it already tells us. So we cannot use any extra fancy culling methods.
public boolean canDetermineInvisible(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) {
return false;
}
public class NonCullingFrustum extends Frustrum implements ViewportProvider, Frustum {
private final Vector3d position = new Vector3d();
@Override
public boolean isBoundingBoxInFrustum(AxisAlignedBB aabb) {
return true;
}
@Override
public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return true;
}
@Override
public Viewport sodium$createViewport() {
return new Viewport(this, position.set(xPosition, yPosition, zPosition));
}
}
@@ -1,16 +0,0 @@
package net.coderbot.iris.sodium;
import me.jellysquid.mods.sodium.client.gl.shader.ShaderBindingPoint;
/**
* Defines Iris-specific chunk shader binding points.
*
* NB: Make sure this doesn't collide with anything in {@link me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkShaderBindingPoints}
*/
public class IrisChunkShaderBindingPoints {
public static final ShaderBindingPoint NORMAL = new ShaderBindingPoint(5);
public static final ShaderBindingPoint TANGENT = new ShaderBindingPoint(6);
public static final ShaderBindingPoint MID_TEX_COORD = new ShaderBindingPoint(7);
public static final ShaderBindingPoint BLOCK_ID = new ShaderBindingPoint(8);
public static final ShaderBindingPoint MID_BLOCK = new ShaderBindingPoint(9);
}
@@ -1,39 +0,0 @@
Y directional_shading
Y MixinSmoothLightPipeline.java
Y MixinFlatLightPipeline.java
* shader_overrides
* ShaderTypeAccessor.java
Y MixinChunkRenderShaderBackend.java
Y MixinShaderType.java
Y MixinChunkProgram.java
Y MixinChunkRenderManager.java
* shadow_map
Y MixinSodiumWorldRenderer.java
Y MixinGameRendererContext.java
Y MixinChunkRenderManager.java
* block_id
Y MixinChunkRenderRebuildTask.java
Y MixinChunkBuildBuffers.java
* pbr_animation
* MixinTextureAtlasSprite.java
* vertex_format
* entity
* MixinBufferBuilder_ExtendedVertexFormatCompat.java // Unclear
Y MixinSodiumWorldRenderer.java
Y MixinChunkOneshotGraphicsState.java
N GlVertexAttributeFormatAccessor.java
Y MixinMultidrawChunkRenderBackend.java
Y MixinChunkMeshAttribute.java
Y MixinGlVertexFormatBuilder.java
N ChunkMeshAttributeAccessor.java
* separate_ao
* MixinBlockRenderer.java
* MixinFluidRenderer.java
* MixinBufferBuilder_IntrinsicSeparateAo.java
* options
X MixinSodiumGameOptionPages.java
X MixinOptionImpl.java
X MixinSodiumGameOptions.java
X MixinSodiumOptionsGUI.java
X MixinChunkRenderManager.java
* IrisSodiumCompatMixinPlugin.java
@@ -1,47 +0,0 @@
package net.coderbot.iris.sodium.block_context;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntMaps;
import net.minecraft.block.Block;
public class BlockContextHolder {
private final Object2IntMap<Block> blockMatches;
public int localPosX;
public int localPosY;
public int localPosZ;
public short blockId;
public short renderType;
public BlockContextHolder() {
this.blockMatches = Object2IntMaps.emptyMap();
this.blockId = -1;
this.renderType = -1;
}
public BlockContextHolder(Object2IntMap<Block> idMap) {
this.blockMatches = idMap;
this.blockId = -1;
this.renderType = -1;
}
public void setLocalPos(int localPosX, int localPosY, int localPosZ) {
this.localPosX = localPosX;
this.localPosY = localPosY;
this.localPosZ = localPosZ;
}
public void set(Block block, short renderType) {
this.blockId = (short) this.blockMatches.getOrDefault(block, -1);
this.renderType = renderType;
}
public void reset() {
this.blockId = -1;
this.renderType = -1;
this.localPosX = 0;
this.localPosY = 0;
this.localPosZ = 0;
}
}
@@ -1,11 +0,0 @@
package net.coderbot.iris.sodium.block_context;
import net.minecraft.block.Block;
public interface ChunkBuildBuffersExt {
void iris$setLocalPos(int localPosX, int localPosY, int localPosZ);
void iris$setMaterialId(Block block, short renderType);
void iris$resetBlockContext();
}
@@ -1,5 +0,0 @@
package net.coderbot.iris.sodium.block_context;
public interface ContextAwareVertexWriter {
void iris$setContextHolder(BlockContextHolder holder);
}
@@ -1,8 +0,0 @@
package net.coderbot.iris.sodium.shader_overrides;
import com.gtnewhorizons.angelica.compat.toremove.MatrixStack;
import me.jellysquid.mods.sodium.client.render.chunk.passes.BlockRenderPass;
public interface ChunkRenderBackendExt {
void iris$begin(MatrixStack matrixStack, BlockRenderPass pass);
}
@@ -1,109 +0,0 @@
package net.coderbot.iris.sodium.shader_overrides;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack.*;
import com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack;
import com.gtnewhorizons.angelica.compat.toremove.MatrixStack;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import java.nio.FloatBuffer;
import me.jellysquid.mods.sodium.client.gl.device.RenderDevice;
import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkProgram;
import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkShaderFogComponent;
import net.coderbot.iris.gl.program.ProgramImages;
import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.program.ProgramUniforms;
import net.coderbot.iris.pipeline.SodiumTerrainPipeline;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import net.minecraft.util.ResourceLocation;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
public class IrisChunkProgram extends ChunkProgram {
// Uniform variable binding indexes
private final int uModelViewMatrix;
private final int uNormalMatrix;
@Nullable
private final ProgramUniforms irisProgramUniforms;
@Nullable
private final ProgramSamplers irisProgramSamplers;
@Nullable
private final ProgramImages irisProgramImages;
private CustomUniforms customUniforms;
public IrisChunkProgram(RenderDevice owner, ResourceLocation name, int handle, boolean isShadowPass, SodiumTerrainPipeline pipeline, CustomUniforms customUniforms) {
super(owner, name, handle, ChunkShaderFogComponent.None::new);
this.uModelViewMatrix = this.getUniformLocation("iris_ModelViewMatrix");
this.uNormalMatrix = this.getUniformLocation("iris_NormalMatrix");
this.customUniforms = customUniforms;
ProgramUniforms.Builder builder = pipeline.initUniforms(handle);
customUniforms.mapholderToPass(builder, this);
this.irisProgramUniforms = builder.buildUniforms();
this.irisProgramSamplers
= isShadowPass? pipeline.initShadowSamplers(handle) : pipeline.initTerrainSamplers(handle);
this.irisProgramImages = isShadowPass ? pipeline.initShadowImages(handle) : pipeline.initTerrainImages(handle);
}
@Override
public void setup(MatrixStack matrixStack, float modelScale, float textureScale) {
super.setup(matrixStack, modelScale, textureScale);
if (irisProgramUniforms != null) {
irisProgramUniforms.update();
}
if (irisProgramSamplers != null) {
irisProgramSamplers.update();
}
if (irisProgramImages != null) {
irisProgramImages.update();
}
Matrix4f modelViewMatrix = matrixStack.peek().getModel();
Matrix4f normalMatrix = new Matrix4f(matrixStack.peek().getModel());
normalMatrix.invert();
normalMatrix.transpose();
uniformMatrix(uModelViewMatrix, modelViewMatrix);
uniformMatrix(uNormalMatrix, normalMatrix);
customUniforms.push(this);
}
@Override
public int getUniformLocation(String name) {
// NB: We pass through calls involving u_ModelViewProjectionMatrix, u_ModelScale, and u_TextureScale, since
// currently patched Iris shader programs use those.
if ("iris_BlockTex".equals(name) || "iris_LightTex".equals(name)) {
// Not relevant for Iris shader programs
return -1;
}
try {
return super.getUniformLocation(name);
} catch (NullPointerException e) {
// Suppress getUniformLocation
return -1;
}
}
private void uniformMatrix(int location, Matrix4f matrix) {
if (location == -1) {
return;
}
try (MemoryStack stack = stackPush()) {
FloatBuffer buffer = stack.mallocFloat(16);
matrix.get(buffer);
RenderSystem.uniformMatrix4fv(location, false, buffer);
}
}
}
@@ -1,205 +0,0 @@
package net.coderbot.iris.sodium.shader_overrides;
import me.jellysquid.mods.sodium.client.gl.device.RenderDevice;
import me.jellysquid.mods.sodium.client.gl.shader.GlProgram;
import me.jellysquid.mods.sodium.client.gl.shader.GlShader;
import me.jellysquid.mods.sodium.client.gl.shader.ShaderConstants;
import me.jellysquid.mods.sodium.client.gl.shader.ShaderType;
import me.jellysquid.mods.sodium.client.render.chunk.passes.BlockRenderPass;
import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkProgram;
import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkShaderBindingPoints;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.program.ProgramImages;
import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.program.ProgramUniforms;
import net.coderbot.iris.pipeline.SodiumTerrainPipeline;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.shadows.ShadowRenderingState;
import net.coderbot.iris.sodium.IrisChunkShaderBindingPoints;
import net.minecraft.util.ResourceLocation;
import org.jetbrains.annotations.Nullable;
import java.util.EnumMap;
import java.util.Locale;
import java.util.Optional;
public class IrisChunkProgramOverrides {
private static final ShaderConstants EMPTY_CONSTANTS = ShaderConstants.builder().build();
private final EnumMap<IrisTerrainPass, ChunkProgram> programs = new EnumMap<>(IrisTerrainPass.class);
private int versionCounterForSodiumShaderReload = -1;
private GlShader createVertexShader(RenderDevice device, IrisTerrainPass pass, SodiumTerrainPipeline pipeline) {
Optional<String> irisVertexShader;
if (pass == IrisTerrainPass.SHADOW) {
irisVertexShader = pipeline.getShadowVertexShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_SOLID) {
irisVertexShader = pipeline.getTerrainVertexShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) {
irisVertexShader = pipeline.getTranslucentVertexShaderSource();
} else {
throw new IllegalArgumentException("Unknown pass type " + pass);
}
String source = irisVertexShader.orElse(null);
if (source == null) {
return null;
}
return new GlShader(device, ShaderType.VERTEX, new ResourceLocation("iris",
"sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".vsh"), source, EMPTY_CONSTANTS);
}
private GlShader createGeometryShader(RenderDevice device, IrisTerrainPass pass, SodiumTerrainPipeline pipeline) {
Optional<String> irisGeometryShader;
if (pass == IrisTerrainPass.SHADOW) {
irisGeometryShader = pipeline.getShadowGeometryShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_SOLID) {
irisGeometryShader = pipeline.getTerrainGeometryShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) {
irisGeometryShader = pipeline.getTranslucentGeometryShaderSource();
} else {
throw new IllegalArgumentException("Unknown pass type " + pass);
}
String source = irisGeometryShader.orElse(null);
if (source == null) {
return null;
}
return new GlShader(device, IrisShaderTypes.GEOMETRY, new ResourceLocation("iris",
"sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".gsh"), source, EMPTY_CONSTANTS);
}
private GlShader createFragmentShader(RenderDevice device, IrisTerrainPass pass, SodiumTerrainPipeline pipeline) {
Optional<String> irisFragmentShader;
if (pass == IrisTerrainPass.SHADOW) {
irisFragmentShader = pipeline.getShadowFragmentShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_SOLID) {
irisFragmentShader = pipeline.getTerrainFragmentShaderSource();
} else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) {
irisFragmentShader = pipeline.getTranslucentFragmentShaderSource();
} else {
throw new IllegalArgumentException("Unknown pass type " + pass);
}
String source = irisFragmentShader.orElse(null);
if (source == null) {
return null;
}
return new GlShader(device, ShaderType.FRAGMENT, new ResourceLocation("iris",
"sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".fsh"), source, EMPTY_CONSTANTS);
}
@Nullable
private ChunkProgram createShader(RenderDevice device, IrisTerrainPass pass, SodiumTerrainPipeline pipeline) {
GlShader vertShader = createVertexShader(device, pass, pipeline);
GlShader geomShader = createGeometryShader(device, pass, pipeline);
GlShader fragShader = createFragmentShader(device, pass, pipeline);
if (vertShader == null || fragShader == null) {
if (vertShader != null) {
vertShader.delete();
}
if (geomShader != null) {
geomShader.delete();
}
if (fragShader != null) {
fragShader.delete();
}
// TODO: Partial shader programs?
return null;
}
try {
GlProgram.Builder builder = GlProgram.builder(new ResourceLocation("sodium", "chunk_shader_for_"
+ pass.getName()));
if (geomShader != null) {
builder.attachShader(geomShader);
}
return builder.attachShader(vertShader)
.attachShader(fragShader)
.bindAttribute("iris_Pos", ChunkShaderBindingPoints.POSITION)
.bindAttribute("iris_Color", ChunkShaderBindingPoints.COLOR)
.bindAttribute("iris_TexCoord", ChunkShaderBindingPoints.TEX_COORD)
.bindAttribute("iris_LightCoord", ChunkShaderBindingPoints.LIGHT_COORD)
.bindAttribute("iris_Normal", IrisChunkShaderBindingPoints.NORMAL)
.bindAttribute("at_tangent", IrisChunkShaderBindingPoints.TANGENT)
.bindAttribute("mc_midTexCoord", IrisChunkShaderBindingPoints.MID_TEX_COORD)
.bindAttribute("mc_Entity", IrisChunkShaderBindingPoints.BLOCK_ID)
.bindAttribute("at_midBlock", IrisChunkShaderBindingPoints.MID_BLOCK)
.bindAttribute("iris_ModelOffset", ChunkShaderBindingPoints.MODEL_OFFSET)
.build((program, name) -> new IrisChunkProgram(device, program, name, pass == IrisTerrainPass.SHADOW, pipeline, pipeline.getCustomUniforms()));
} finally {
vertShader.delete();
if (geomShader != null) {
geomShader.delete();
}
fragShader.delete();
}
}
public void createShaders(SodiumTerrainPipeline sodiumTerrainPipeline, RenderDevice device) {
if (sodiumTerrainPipeline != null) {
for (IrisTerrainPass pass : IrisTerrainPass.values()) {
if (pass == IrisTerrainPass.SHADOW && !sodiumTerrainPipeline.hasShadowPass()) {
this.programs.put(pass, null);
continue;
}
this.programs.put(pass, createShader(device, pass, sodiumTerrainPipeline));
}
} else {
this.programs.clear();
}
}
@Nullable
public ChunkProgram getProgramOverride(RenderDevice device, BlockRenderPass pass) {
WorldRenderingPipeline worldRenderingPipeline = Iris.getPipelineManager().getPipelineNullable();
SodiumTerrainPipeline sodiumTerrainPipeline = null;
if (worldRenderingPipeline != null) {
sodiumTerrainPipeline = worldRenderingPipeline.getSodiumTerrainPipeline();
}
if (versionCounterForSodiumShaderReload != Iris.getPipelineManager().getVersionCounterForSodiumShaderReload()) {
versionCounterForSodiumShaderReload = Iris.getPipelineManager().getVersionCounterForSodiumShaderReload();
deleteShaders();
createShaders(sodiumTerrainPipeline, device);
}
if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) {
if (sodiumTerrainPipeline != null && !sodiumTerrainPipeline.hasShadowPass()) {
throw new IllegalStateException("Shadow program requested, but the pack does not have a shadow pass?");
}
return this.programs.get(IrisTerrainPass.SHADOW);
} else {
return this.programs.get(pass.isTranslucent() ? IrisTerrainPass.GBUFFER_TRANSLUCENT : IrisTerrainPass.GBUFFER_SOLID);
}
}
public void deleteShaders() {
for (ChunkProgram program : this.programs.values()) {
if (program != null) {
program.delete();
}
}
this.programs.clear();
}
}
@@ -1,7 +0,0 @@
package net.coderbot.iris.sodium.shader_overrides;
import me.jellysquid.mods.sodium.client.gl.shader.ShaderType;
public class IrisShaderTypes {
public static ShaderType GEOMETRY = ShaderType.GEOMETRY;
}
@@ -1,17 +0,0 @@
package net.coderbot.iris.sodium.shader_overrides;
public enum IrisTerrainPass {
SHADOW("shadow"),
GBUFFER_SOLID("gbuffers_terrain"),
GBUFFER_TRANSLUCENT("gbuffers_water");
private final String name;
IrisTerrainPass(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
@@ -1,5 +0,0 @@
package net.coderbot.iris.sodium.shadow_map;
public interface SwappableChunkRenderManager {
void iris$swapVisibilityState();
}
@@ -1,9 +0,0 @@
package net.coderbot.iris.sodium.vertex_format;
import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexAttributeFormat;
import org.lwjgl.opengl.GL11;
public class IrisGlVertexAttributeFormat {
public static final GlVertexAttributeFormat BYTE = new GlVertexAttributeFormat(GL11.GL_BYTE, 1);
public static final GlVertexAttributeFormat SHORT = new GlVertexAttributeFormat(GL11.GL_SHORT, 2);
}
@@ -1,7 +0,0 @@
package net.coderbot.iris.sodium.vertex_format;
import net.coderbot.iris.sodium.vertex_format.terrain_xhfp.XHFPModelVertexType;
public class IrisModelVertexFormats {
public static final XHFPModelVertexType MODEL_VERTEX_XHFP = new XHFPModelVertexType();
}
@@ -1,66 +0,0 @@
package net.coderbot.iris.sodium.vertex_format.entity_xhfp;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*;
import net.coderbot.iris.vertices.IrisQuadView;
import java.nio.ByteBuffer;
public abstract class QuadViewEntity implements IrisQuadView {
long writePointer;
int stride;
@Override
public float x(int index) {
return getFloat(writePointer - stride * (3L - index));
}
@Override
public float y(int index) {
return getFloat(writePointer + 4 - stride * (3L - index));
}
@Override
public float z(int index) {
return getFloat(writePointer + 8 - stride * (3L - index));
}
@Override
public float u(int index) {
return getFloat(writePointer + 16 - stride * (3L - index));
}
@Override
public float v(int index) {
return getFloat(writePointer + 20 - stride * (3L - index));
}
abstract float getFloat(long writePointer);
public static class QuadViewEntityUnsafe extends QuadViewEntity {
public void setup(long writePointer, int stride) {
this.writePointer = writePointer;
this.stride = stride;
}
@Override
float getFloat(long writePointer) {
return memGetFloat(writePointer);
}
}
public static class QuadViewEntityNio extends QuadViewEntity {
private ByteBuffer buffer;
public void setup(ByteBuffer buffer, int writePointer, int stride) {
this.buffer = buffer;
this.writePointer = writePointer;
this.stride = stride;
}
@Override
float getFloat(long writePointer) {
return buffer.getFloat((int) writePointer);
}
}
}
@@ -1,74 +0,0 @@
package net.coderbot.iris.sodium.vertex_format.terrain_xhfp;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*;
import net.coderbot.iris.vertices.IrisQuadView;
import java.nio.ByteBuffer;
public abstract class QuadViewTerrain implements IrisQuadView {
long writePointer;
int stride;
@Override
public float x(int index) {
return normalizeVertexPositionShortAsFloat(getShort(writePointer - stride * (3L - index)));
}
@Override
public float y(int index) {
return normalizeVertexPositionShortAsFloat(getShort(writePointer + 2 - stride * (3L - index)));
}
@Override
public float z(int index) {
return normalizeVertexPositionShortAsFloat(getShort(writePointer + 4 - stride * (3L - index)));
}
@Override
public float u(int index) {
return normalizeVertexTextureShortAsFloat(getShort(writePointer + 12 - stride * (3L - index)));
}
@Override
public float v(int index) {
return normalizeVertexTextureShortAsFloat(getShort(writePointer + 14 - stride * (3L - index)));
}
private static float normalizeVertexTextureShortAsFloat(short value) {
return (value & 0xFFFF) * (1.0f / 32768.0f);
}
private static float normalizeVertexPositionShortAsFloat(short value) {
return (value & 0xFFFF) * (1.0f / 65535.0f);
}
abstract short getShort(long writePointer);
public static class QuadViewTerrainUnsafe extends QuadViewTerrain {
public void setup(long writePointer, int stride) {
this.writePointer = writePointer;
this.stride = stride;
}
@Override
short getShort(long writePointer) {
return memGetShort(writePointer);
}
}
public static class QuadViewTerrainNio extends QuadViewTerrain {
private ByteBuffer buffer;
public void setup(ByteBuffer buffer, int writePointer, int stride) {
this.buffer = buffer;
this.writePointer = writePointer;
this.stride = stride;
}
@Override
short getShort(long writePointer) {
return buffer.getShort((int) writePointer);
}
}
}
@@ -1,149 +0,0 @@
package net.coderbot.iris.sodium.vertex_format.terrain_xhfp;
import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView;
import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferWriterNio;
import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink;
import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexUtil;
import net.coderbot.iris.sodium.block_context.BlockContextHolder;
import net.coderbot.iris.sodium.block_context.ContextAwareVertexWriter;
import net.coderbot.iris.sodium.vertex_format.IrisModelVertexFormats;
import net.coderbot.iris.vertices.ExtendedDataHelper;
import net.coderbot.iris.vertices.NormalHelper;
import org.joml.Vector3f;
import java.nio.ByteBuffer;
import static net.coderbot.iris.sodium.vertex_format.terrain_xhfp.XHFPModelVertexType.STRIDE;
public class XHFPModelVertexBufferWriterNio extends VertexBufferWriterNio implements ModelVertexSink, ContextAwareVertexWriter {
private final QuadViewTerrain.QuadViewTerrainNio quad = new QuadViewTerrain.QuadViewTerrainNio();
private final Vector3f normal = new Vector3f();
private BlockContextHolder contextHolder;
private int vertexCount;
private float uSum;
private float vSum;
public XHFPModelVertexBufferWriterNio(VertexBufferView backingBuffer) {
super(backingBuffer, IrisModelVertexFormats.MODEL_VERTEX_XHFP);
}
@Override
public void writeQuad(float x, float y, float z, int color, float u, float v, int light, int shaderBlockId) {
uSum += u;
vSum += v;
this.writeQuadInternal(
ModelVertexUtil.denormalizeVertexPositionFloatAsShort(x),
ModelVertexUtil.denormalizeVertexPositionFloatAsShort(y),
ModelVertexUtil.denormalizeVertexPositionFloatAsShort(z),
color,
ModelVertexUtil.denormalizeVertexTextureFloatAsShort(u),
ModelVertexUtil.denormalizeVertexTextureFloatAsShort(v),
light,
shaderBlockId != -1 ? (short)shaderBlockId : contextHolder.blockId,
contextHolder.renderType,
ExtendedDataHelper.computeMidBlock(x, y, z, contextHolder.localPosX, contextHolder.localPosY, contextHolder.localPosZ)
);
}
private void writeQuadInternal(short x, short y, short z, int color, short u, short v, int light, short materialId,
short renderType, int packedMidBlock) {
int i = this.writeOffset;
vertexCount++;
// NB: uSum and vSum must already be incremented outside of this function.
ByteBuffer buffer = this.byteBuffer;
buffer.putShort(i, x);
buffer.putShort(i + 2, y);
buffer.putShort(i + 4, z);
buffer.putInt(i + 8, color);
buffer.putShort(i + 12, u);
buffer.putShort(i + 14, v);
buffer.putShort(i + 16, (short) (light & 0xFFFF));
buffer.putShort(i + 18, (short) (light >> 16 & 0xFFFF));
// NB: We don't set midTexCoord, normal, and tangent here, they will be filled in later.
// block ID: We only set the first 2 values, any legacy shaders using z or w will get filled in based on the GLSL spec
// https://www.khronos.org/opengl/wiki/Vertex_Specification#Vertex_format
// TODO: can we pack this into one short?
buffer.putShort(i + 36, materialId);
buffer.putShort(i + 38, renderType);
buffer.putInt(i + 40, packedMidBlock);
if (vertexCount == 4) {
vertexCount = 0;
// FIXME
// The following logic is incorrect because OpenGL denormalizes shorts by dividing by 65535. The atlas is
// based on power-of-two values and so a normalization factor that is not a power of two causes the values
// used in the shader to be off by enough to cause visual errors. These are most noticeable on 1.18 with POM
// on block edges.
//
// The only reliable way that this can be fixed is to apply the same shader transformations to midTexCoord
// as Sodium does to the regular texture coordinates - dividing them by the correct power-of-two value inside
// of the shader instead of letting OpenGL value normalization do the division. However, this requires
// fragile patching that is not yet possible.
//
// As a temporary solution, the normalized shorts have been replaced with regular floats, but this takes up
// an extra 4 bytes per vertex.
// NB: Be careful with the math here! A previous bug was caused by midU going negative as a short, which
// was sign-extended into midTexCoord, causing midV to have garbage (likely NaN data). If you're touching
// this code, be aware of that, and don't introduce those kinds of bugs!
//
// Also note that OpenGL takes shorts in the range of [0, 65535] and transforms them linearly to [0.0, 1.0],
// so multiply by 65535, not 65536.
//
// TODO: Does this introduce precision issues? Do we need to fall back to floats here? This might break
// with high resolution texture packs.
// int midU = (int)(65535.0F * Math.min(uSum * 0.25f, 1.0f)) & 0xFFFF;
// int midV = (int)(65535.0F * Math.min(vSum * 0.25f, 1.0f)) & 0xFFFF;
// int midTexCoord = (midV << 16) | midU;
uSum *= 0.25f;
vSum *= 0.25f;
buffer.putFloat(i + 20, uSum);
buffer.putFloat(i + 20 - STRIDE, uSum);
buffer.putFloat(i + 20 - STRIDE * 2, uSum);
buffer.putFloat(i + 20 - STRIDE * 3, uSum);
buffer.putFloat(i + 24, vSum);
buffer.putFloat(i + 24 - STRIDE, vSum);
buffer.putFloat(i + 24 - STRIDE * 2, vSum);
buffer.putFloat(i + 24 - STRIDE * 3, vSum);
uSum = 0;
vSum = 0;
// normal computation
// Implementation based on the algorithm found here:
// https://github.com/IrisShaders/ShaderDoc/blob/master/vertex-format-extensions.md#surface-normal-vector
quad.setup(buffer, i, STRIDE);
NormalHelper.computeFaceNormal(normal, quad);
int packedNormal = NormalHelper.packNormal(normal, 0.0f);
buffer.putInt(i + 32, packedNormal);
buffer.putInt(i + 32 - STRIDE, packedNormal);
buffer.putInt(i + 32 - STRIDE * 2, packedNormal);
buffer.putInt(i + 32 - STRIDE * 3, packedNormal);
int tangent = NormalHelper.computeTangent(normal.x, normal.y, normal.z, quad);
buffer.putInt(i + 28, tangent);
buffer.putInt(i + 28 - STRIDE, tangent);
buffer.putInt(i + 28 - STRIDE * 2, tangent);
buffer.putInt(i + 28 - STRIDE * 3, tangent);
}
this.advance();
}
@Override
public void iris$setContextHolder(BlockContextHolder holder) {
this.contextHolder = holder;
}
}
@@ -1,148 +0,0 @@
package net.coderbot.iris.sodium.vertex_format.terrain_xhfp;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*;
import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView;
import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferWriterUnsafe;
import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink;
import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexUtil;
import net.coderbot.iris.sodium.block_context.BlockContextHolder;
import net.coderbot.iris.sodium.block_context.ContextAwareVertexWriter;
import net.coderbot.iris.sodium.vertex_format.IrisModelVertexFormats;
import net.coderbot.iris.vertices.ExtendedDataHelper;
import net.coderbot.iris.vertices.NormalHelper;
import org.joml.Vector3f;
import static net.coderbot.iris.sodium.vertex_format.terrain_xhfp.XHFPModelVertexType.STRIDE;
public class XHFPModelVertexBufferWriterUnsafe extends VertexBufferWriterUnsafe implements ModelVertexSink, ContextAwareVertexWriter {
private final QuadViewTerrain.QuadViewTerrainUnsafe quad = new QuadViewTerrain.QuadViewTerrainUnsafe();
private final Vector3f normal = new Vector3f();
private BlockContextHolder contextHolder;
private int vertexCount;
private float uSum;
private float vSum;
public XHFPModelVertexBufferWriterUnsafe(VertexBufferView backingBuffer) {
super(backingBuffer, IrisModelVertexFormats.MODEL_VERTEX_XHFP);
}
@Override
public void writeQuad(float x, float y, float z, int color, float u, float v, int light, int shaderBlockId) {
uSum += u;
vSum += v;
this.writeQuadInternal(
ModelVertexUtil.denormalizeVertexPositionFloatAsShort(x),
ModelVertexUtil.denormalizeVertexPositionFloatAsShort(y),
ModelVertexUtil.denormalizeVertexPositionFloatAsShort(z),
color,
ModelVertexUtil.denormalizeVertexTextureFloatAsShort(u),
ModelVertexUtil.denormalizeVertexTextureFloatAsShort(v),
light,
shaderBlockId != -1 ? (short)shaderBlockId : contextHolder.blockId,
contextHolder.renderType,
ExtendedDataHelper.computeMidBlock(x, y, z, contextHolder.localPosX, contextHolder.localPosY, contextHolder.localPosZ)
);
}
private void writeQuadInternal(short x, short y, short z, int color, short u, short v, int light, short materialId,
short renderType, int packedMidBlock) {
long i = this.writePointer;
vertexCount++;
// NB: uSum and vSum must already be incremented outside of this function.
memPutShort(i, x);
memPutShort(i + 2, y);
memPutShort(i + 4, z);
memPutInt(i + 8, color);
memPutShort(i + 12, u);
memPutShort(i + 14, v);
memPutShort(i + 16, (short) (light & 0xFFFF));
memPutShort(i + 18, (short) (light >> 16 & 0xFFFF));
// NB: We don't set midTexCoord, normal, and tangent here, they will be filled in later.
// block ID: We only set the first 2 values, any legacy shaders using z or w will get filled in based on the GLSL spec
// https://www.khronos.org/opengl/wiki/Vertex_Specification#Vertex_format
// TODO: can we pack this into one short?
memPutShort(i + 36, materialId);
memPutShort(i + 38, renderType);
memPutInt(i + 40, packedMidBlock);
if (vertexCount == 4) {
vertexCount = 0;
// FIXME
// The following logic is incorrect because OpenGL denormalizes shorts by dividing by 65535. The atlas is
// based on power-of-two values and so a normalization factor that is not a power of two causes the values
// used in the shader to be off by enough to cause visual errors. These are most noticeable on 1.18 with POM
// on block edges.
//
// The only reliable way that this can be fixed is to apply the same shader transformations to midTexCoord
// as Sodium does to the regular texture coordinates - dividing them by the correct power-of-two value inside
// of the shader instead of letting OpenGL value normalization do the division. However, this requires
// fragile patching that is not yet possible.
//
// As a temporary solution, the normalized shorts have been replaced with regular floats, but this takes up
// an extra 4 bytes per vertex.
// NB: Be careful with the math here! A previous bug was caused by midU going negative as a short, which
// was sign-extended into midTexCoord, causing midV to have garbage (likely NaN data). If you're touching
// this code, be aware of that, and don't introduce those kinds of bugs!
//
// Also note that OpenGL takes shorts in the range of [0, 65535] and transforms them linearly to [0.0, 1.0],
// so multiply by 65535, not 65536.
//
// TODO: Does this introduce precision issues? Do we need to fall back to floats here? This might break
// with high resolution texture packs.
// int midU = (int)(65535.0F * Math.min(uSum * 0.25f, 1.0f)) & 0xFFFF;
// int midV = (int)(65535.0F * Math.min(vSum * 0.25f, 1.0f)) & 0xFFFF;
// int midTexCoord = (midV << 16) | midU;
uSum *= 0.25f;
vSum *= 0.25f;
memPutFloat(i + 20, uSum);
memPutFloat(i + 20 - STRIDE, uSum);
memPutFloat(i + 20 - STRIDE * 2, uSum);
memPutFloat(i + 20 - STRIDE * 3, uSum);
memPutFloat(i + 24, vSum);
memPutFloat(i + 24 - STRIDE, vSum);
memPutFloat(i + 24 - STRIDE * 2, vSum);
memPutFloat(i + 24 - STRIDE * 3, vSum);
uSum = 0;
vSum = 0;
// normal computation
// Implementation based on the algorithm found here:
// https://github.com/IrisShaders/ShaderDoc/blob/master/vertex-format-extensions.md#surface-normal-vector
quad.setup(i, STRIDE);
NormalHelper.computeFaceNormal(normal, quad);
int packedNormal = NormalHelper.packNormal(normal, 0.0f);
memPutInt(i + 32, packedNormal);
memPutInt(i + 32 - STRIDE, packedNormal);
memPutInt(i + 32 - STRIDE * 2, packedNormal);
memPutInt(i + 32 - STRIDE * 3, packedNormal);
int tangent = NormalHelper.computeTangent(normal.x, normal.y, normal.z, quad);
memPutInt(i + 28, tangent);
memPutInt(i + 28 - STRIDE, tangent);
memPutInt(i + 28 - STRIDE * 2, tangent);
memPutInt(i + 28 - STRIDE * 3, tangent);
}
this.advance();
}
@Override
public void iris$setContextHolder(BlockContextHolder holder) {
this.contextHolder = holder;
}
}
@@ -1,62 +0,0 @@
package net.coderbot.iris.sodium.vertex_format.terrain_xhfp;
import com.gtnewhorizons.angelica.compat.toremove.VertexConsumer;
import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexAttributeFormat;
import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexFormat;
import me.jellysquid.mods.sodium.client.model.vertex.buffer.VertexBufferView;
import me.jellysquid.mods.sodium.client.model.vertex.type.BlittableVertexType;
import me.jellysquid.mods.sodium.client.model.vertex.type.ChunkVertexType;
import me.jellysquid.mods.sodium.client.render.chunk.format.ChunkMeshAttribute;
import me.jellysquid.mods.sodium.client.render.chunk.format.ModelVertexSink;
import net.coderbot.iris.sodium.vertex_format.IrisGlVertexAttributeFormat;
/**
* Like HFPModelVertexType, but extended to support Iris. The extensions aren't particularly efficient right now.
*/
public class XHFPModelVertexType implements ChunkVertexType {
public static final int STRIDE = 44;
public static final GlVertexFormat<ChunkMeshAttribute> VERTEX_FORMAT = GlVertexFormat.builder(ChunkMeshAttribute.class, STRIDE)
.addElement(ChunkMeshAttribute.POSITION, 0, GlVertexAttributeFormat.UNSIGNED_SHORT, 3, false)
.addElement(ChunkMeshAttribute.COLOR, 8, GlVertexAttributeFormat.UNSIGNED_BYTE, 4, true)
.addElement(ChunkMeshAttribute.TEXTURE, 12, GlVertexAttributeFormat.UNSIGNED_SHORT, 2, false)
.addElement(ChunkMeshAttribute.LIGHT, 16, GlVertexAttributeFormat.UNSIGNED_SHORT, 2, false)
.addElement(ChunkMeshAttribute.MID_TEX_COORD, 20, GlVertexAttributeFormat.FLOAT, 2, false)
.addElement(ChunkMeshAttribute.TANGENT, 28, IrisGlVertexAttributeFormat.BYTE, 4, true)
.addElement(ChunkMeshAttribute.NORMAL, 32, IrisGlVertexAttributeFormat.BYTE, 3, true)
.addElement(ChunkMeshAttribute.BLOCK_ID, 36, IrisGlVertexAttributeFormat.SHORT, 2, false)
.addElement(ChunkMeshAttribute.MID_BLOCK, 40, IrisGlVertexAttributeFormat.BYTE, 3, false)
.build();
public static final float MODEL_SCALE = (32.0f / 65536.0f);
public static final float TEXTURE_SCALE = (1.0f / 32768.0f);
@Override
public ModelVertexSink createFallbackWriter(VertexConsumer consumer) {
throw new UnsupportedOperationException();
}
@Override
public ModelVertexSink createBufferWriter(VertexBufferView buffer, boolean direct) {
return direct ? new XHFPModelVertexBufferWriterUnsafe(buffer) : new XHFPModelVertexBufferWriterNio(buffer);
}
@Override
public BlittableVertexType<ModelVertexSink> asBlittable() {
return this;
}
@Override
public GlVertexFormat<ChunkMeshAttribute> getCustomVertexFormat() {
return VERTEX_FORMAT;
}
@Override
public float getModelScale() {
return MODEL_SCALE;
}
@Override
public float getTextureScale() {
return TEXTURE_SCALE;
}
}
@@ -16,7 +16,11 @@ import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME;
* @see <a href="https://github.com/IrisShaders/ShaderDoc/blob/master/uniforms.md#celestial-bodies">Uniforms: Celestial bodies</a>
*/
public final class CelestialUniforms {
private static final Vector4f upPositionCache = new Vector4f();
private static final Matrix4f upMatrixCache = new Matrix4f();
private final Vector4f positionCache = new Vector4f();
private final Matrix4f celestialMatrixCache = new Matrix4f();
private final float sunPathRotation;
public CelestialUniforms(float sunPathRotation) {
@@ -70,56 +74,55 @@ public final class CelestialUniforms {
}
private Vector4f getCelestialPositionInWorldSpace(float y) {
final Vector4f position = new Vector4f(0.0F, y, 0.0F, 0.0F);
positionCache.set(0.0F, y, 0.0F, 0.0F);
// TODO: Deduplicate / remove this function.
final Matrix4f celestial = new Matrix4f().identity();
celestialMatrixCache.identity();
// This is the same transformation applied by renderSky, however, it's been moved to here.
// This is because we need the result of it before it's actually performed in vanilla.
celestial.rotateY(-90.F * Constants.DEGREES_TO_RADIANS);
celestial.rotateZ(sunPathRotation * Constants.DEGREES_TO_RADIANS);
celestial.rotateX(getSkyAngle() * 360.0F * Constants.DEGREES_TO_RADIANS);
celestialMatrixCache.rotateY(-90.F * Constants.DEGREES_TO_RADIANS);
celestialMatrixCache.rotateZ(sunPathRotation * Constants.DEGREES_TO_RADIANS);
celestialMatrixCache.rotateX(getSkyAngle() * 360.0F * Constants.DEGREES_TO_RADIANS);
celestial.transform(position);
celestialMatrixCache.transform(positionCache);
return position;
return positionCache;
}
private Vector4f getCelestialPosition(float y) {
Vector4f position = new Vector4f(0.0F, y, 0.0F, 0.0F);
positionCache.set(0.0F, y, 0.0F, 0.0F);
final Matrix4f celestial = new Matrix4f(RenderingState.INSTANCE.getModelViewMatrix());
celestialMatrixCache.set(RenderingState.INSTANCE.getModelViewMatrix());
// This is the same transformation applied by renderSky, however, it's been moved to here.
// This is because we need the result of it before it's actually performed in vanilla.
celestial.rotateY(-90.F * Constants.DEGREES_TO_RADIANS);
celestial.rotateZ(sunPathRotation * Constants.DEGREES_TO_RADIANS);
celestial.rotateX(getSkyAngle() * 360.0F * Constants.DEGREES_TO_RADIANS);
celestialMatrixCache.rotateY(-90.F * Constants.DEGREES_TO_RADIANS);
celestialMatrixCache.rotateZ(sunPathRotation * Constants.DEGREES_TO_RADIANS);
celestialMatrixCache.rotateX(getSkyAngle() * 360.0F * Constants.DEGREES_TO_RADIANS);
position = celestial.transform(position);
celestialMatrixCache.transform(positionCache);
return position;
return positionCache;
}
private static Vector4f getUpPosition() {
Vector4f upVector = new Vector4f(0.0F, 100.0F, 0.0F, 0.0F);
upPositionCache.set(0.0F, 100.0F, 0.0F, 0.0F);
// Get the current model view matrix, since that is the basis of the celestial model view matrix
final Matrix4f preCelestial = new Matrix4f(RenderingState.INSTANCE.getModelViewMatrix());
upMatrixCache.set(RenderingState.INSTANCE.getModelViewMatrix());
// Apply the fixed -90.0F degrees rotation to mirror the same transformation in renderSky.
// But, notably, skip the rotation by the skyAngle.
preCelestial.rotateY(-90.F * Constants.DEGREES_TO_RADIANS);
upMatrixCache.rotateY(-90.F * Constants.DEGREES_TO_RADIANS);
// Use this matrix to transform the vector.
upVector = preCelestial.transform(upVector);
upMatrixCache.transform(upPositionCache);
return upVector;
return upPositionCache;
}
public static boolean isDay() {
// Determine whether it is day or night based on the sky angle.
//
// World#isDay appears to do some nontrivial calculations that appear to not entirely work for us here.
return getSunAngle() <= 0.5;
}
@@ -7,7 +7,7 @@ import com.gtnewhorizons.angelica.glsm.texture.TextureInfo;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import com.gtnewhorizons.angelica.glsm.texture.TextureTracker;
import com.gtnewhorizons.angelica.mixins.interfaces.EntityRendererAccessor;
import net.coderbot.iris.gl.state.StateUpdateNotifiers;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import net.coderbot.iris.gl.uniform.DynamicUniformHolder;
import net.coderbot.iris.gl.uniform.UniformHolder;
import net.coderbot.iris.layer.GbufferPrograms;
@@ -68,11 +68,10 @@ public final class CommonUniforms {
ExternallyManagedUniforms.addExternallyManagedUniforms116(uniforms);
IdMapUniforms.addEntityIdMapUniforms(uniforms);
FogUniforms.addFogUniforms(uniforms);
IrisInternalUniforms.addFogUniforms(uniforms);
// TODO: OptiFine doesn't think that atlasSize is a "dynamic" uniform,
// but we do. How will custom uniforms depending on atlasSize work?
uniforms.uniform2i("atlasSize", () -> {
final int glId = GLStateManager.getBoundTextureForServerState();
final int glId = GLStateManager.getBoundTextureForServerState(0);
final AbstractTexture texture = TextureTracker.INSTANCE.getTexture(glId);
if (texture instanceof TextureMap) {
@@ -81,15 +80,15 @@ public final class CommonUniforms {
}
return ZERO_VECTOR_2i;
}, StateUpdateNotifiers.bindTextureNotifier);
}, ValueUpdateNotifier.NONE);
uniforms.uniform2i("gtextureSize", () -> {
final int glId = GLStateManager.getBoundTextureForServerState();
final int glId = GLStateManager.getBoundTextureForServerState(0);
final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(glId);
return new Vector2i(info.getWidth(), info.getHeight());
}, StateUpdateNotifiers.bindTextureNotifier);
}, ValueUpdateNotifier.NONE);
uniforms.uniform4i("blendFunc", () -> {
if(GLStateManager.getBlendMode().isEnabled()) {
@@ -97,9 +96,9 @@ public final class CommonUniforms {
return new Vector4i(blend.getSrcRgb(), blend.getDstRgb(), blend.getSrcAlpha(), blend.getDstAlpha());
}
return ZERO_VECTOR_4i;
}, StateUpdateNotifiers.blendFuncNotifier);
}, ValueUpdateNotifier.NONE);
uniforms.uniform1i("renderStage", () -> GbufferPrograms.getCurrentPhase().ordinal(), StateUpdateNotifiers.phaseChangeNotifier);
uniforms.uniform1i("renderStage", () -> GbufferPrograms.getCurrentPhase().ordinal(), ValueUpdateNotifier.NONE);
uniforms.uniform4f("entityColor", CapturedRenderingState.INSTANCE::getCurrentEntityColor, CapturedRenderingState.INSTANCE.getEntityColorNotifier());
@@ -12,8 +12,6 @@ public class ExternallyManagedUniforms {
addMat4(uniformHolder, "iris_ModelViewMatrix");
addMat4(uniformHolder, "u_ModelViewProjectionMatrix");
addMat4(uniformHolder, "iris_NormalMatrix");
// 1.21.6+
uniformHolder.externallyManagedUniform("heavyFog", UniformType.BOOL);
}
@@ -24,42 +22,7 @@ public class ExternallyManagedUniforms {
uniformHolder.externallyManagedUniform("u_TextureScale", UniformType.VEC2);
}
public static void addExternallyManagedUniforms117(UniformHolder uniformHolder) {
addExternallyManagedUniforms(uniformHolder);
// Sodium
addFloat(uniformHolder, "iris_FogStart");
addFloat(uniformHolder, "iris_FogEnd");
addVec4(uniformHolder, "iris_FogColor");
addMat4(uniformHolder, "iris_ProjectionMatrix");
addFloat(uniformHolder, "u_TextureScale");
addFloat(uniformHolder, "u_ModelScale");
addFloat(uniformHolder, "iris_ModelOffset");
uniformHolder.externallyManagedUniform("iris_CameraTranslation", UniformType.VEC3);
// Vanilla
uniformHolder.externallyManagedUniform("iris_TextureMat", UniformType.MAT4);
uniformHolder.externallyManagedUniform("iris_ModelViewMat", UniformType.MAT4);
uniformHolder.externallyManagedUniform("iris_ProjMat", UniformType.MAT4);
uniformHolder.externallyManagedUniform("iris_ChunkOffset", UniformType.VEC3);
uniformHolder.externallyManagedUniform("iris_ColorModulator", UniformType.VEC4);
uniformHolder.externallyManagedUniform("iris_FogStart", UniformType.FLOAT);
uniformHolder.externallyManagedUniform("iris_FogEnd", UniformType.FLOAT);
uniformHolder.externallyManagedUniform("iris_FogDensity", UniformType.FLOAT);
uniformHolder.externallyManagedUniform("iris_LineWidth", UniformType.FLOAT);
uniformHolder.externallyManagedUniform("iris_ScreenSize", UniformType.VEC2);
uniformHolder.externallyManagedUniform("iris_FogColor", UniformType.VEC4);
}
private static void addMat4(UniformHolder uniformHolder, String name) {
uniformHolder.externallyManagedUniform(name, UniformType.MAT4);
}
private static void addVec4(UniformHolder uniformHolder, String name) {
uniformHolder.externallyManagedUniform(name, UniformType.VEC4);
}
private static void addFloat(UniformHolder uniformHolder, String name) {
uniformHolder.externallyManagedUniform(name, UniformType.FLOAT);
}
}
@@ -1,7 +1,7 @@
package net.coderbot.iris.uniforms;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import net.coderbot.iris.gl.state.StateUpdateNotifiers;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import net.coderbot.iris.gl.uniform.DynamicUniformHolder;
public class FogUniforms {
@@ -14,24 +14,12 @@ public class FogUniforms {
if(!GLStateManager.getFogMode().isEnabled()) return 0;
return GLStateManager.getFogState().getFogMode();
}, listener -> {
StateUpdateNotifiers.fogToggleNotifier.setListener(listener);
StateUpdateNotifiers.fogModeNotifier.setListener(listener);
});
}, ValueUpdateNotifier.NONE);
uniforms.uniform1f("fogDensity", () -> GLStateManager.getFogState().getDensity(), listener -> {
StateUpdateNotifiers.fogToggleNotifier.setListener(listener);
StateUpdateNotifiers.fogDensityNotifier.setListener(listener);
});
uniforms.uniform1f("fogDensity", () -> GLStateManager.getFogState().getDensity(), ValueUpdateNotifier.NONE);
uniforms.uniform1f("fogStart", () -> GLStateManager.getFogState().getStart(), listener -> {
StateUpdateNotifiers.fogToggleNotifier.setListener(listener);
StateUpdateNotifiers.fogStartNotifier.setListener(listener);
});
uniforms.uniform1f("fogStart", () -> GLStateManager.getFogState().getStart(), ValueUpdateNotifier.NONE);
uniforms.uniform1f("fogEnd", () -> GLStateManager.getFogState().getEnd(), listener -> {
StateUpdateNotifiers.fogToggleNotifier.setListener(listener);
StateUpdateNotifiers.fogEndNotifier.setListener(listener);
});
uniforms.uniform1f("fogEnd", () -> GLStateManager.getFogState().getEnd(), ValueUpdateNotifier.NONE);
}
}
@@ -0,0 +1,31 @@
package net.coderbot.iris.uniforms;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import net.coderbot.iris.gl.uniform.DynamicUniformHolder;
import org.joml.Vector3d;
import org.joml.Vector4f;
import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME;
public class IrisInternalUniforms {
private static final Vector4f FOG_COLOR = new Vector4f();
private IrisInternalUniforms() {
}
public static void addFogUniforms(DynamicUniformHolder uniforms) {
uniforms.uniform4f(PER_FRAME, "iris_FogColor", () -> {
final Vector3d color = GLStateManager.getFogState().getFogColor();
return FOG_COLOR.set((float) color.x, (float) color.y, (float) color.z, GLStateManager.getFogState().getFogAlpha());
});
uniforms
.uniform1f(PER_FRAME, "iris_FogStart", () -> GLStateManager.getFogState().getStart())
.uniform1f(PER_FRAME, "iris_FogEnd", () -> GLStateManager.getFogState().getEnd())
.uniform1f(PER_FRAME, "iris_FogDensity", () -> Math.max(0.0F, GLStateManager.getFogState().getDensity()));
uniforms
.uniform1f(PER_FRAME, "iris_currentAlphaTest", () -> GLStateManager.getAlphaState().getReference())
.uniform1f(PER_FRAME, "alphaTestRef", () -> GLStateManager.getAlphaState().getReference());
}
}
@@ -44,14 +44,6 @@ public abstract class NormalHelper {
* Expects convex quads with all points co-planar.
*/
public static void computeFaceNormal(@NotNull Vector3f saveTo, IrisQuadView q) {
// final Direction nominalFace = q.nominalFace();
//
// if (GeometryHelper.isQuadParallelToFace(nominalFace, q)) {
// Vec3i vec = nominalFace.getVector();
// saveTo.set(vec.getX(), vec.getY(), vec.getZ());
// return;
// }
final float x0 = q.x(0);
final float y0 = q.y(0);
final float z0 = q.z(0);
@@ -76,7 +68,7 @@ public abstract class NormalHelper {
float normY = dz0 * dx1 - dx0 * dz1;
float normZ = dx0 * dy1 - dy0 * dx1;
float l = (float) Math.sqrt(normX * normX + normY * normY + normZ * normZ);
final float l = (float) Math.sqrt(normX * normX + normY * normY + normZ * normZ);
if (l != 0) {
normX /= l;
@@ -93,14 +85,6 @@ public abstract class NormalHelper {
* <p>Assumes counter-clockwise winding order, which is the norm.
*/
public static void computeFaceNormalTri(@NotNull Vector3f saveTo, TriView t) {
// final Direction nominalFace = q.nominalFace();
//
// if (GeometryHelper.isQuadParallelToFace(nominalFace, q)) {
// Vec3i vec = nominalFace.getVector();
// saveTo.set(vec.getX(), vec.getY(), vec.getZ());
// return;
// }
final float x0 = t.x(0);
final float y0 = t.y(0);
final float z0 = t.z(0);
@@ -155,9 +139,9 @@ public abstract class NormalHelper {
// project v onto normal
// offset v by the projection to get the point on the plane
// project x0, y0, z0 onto normal
float d0 = x0 * normalX + y0 * normalY + z0 * normalZ;
float d1 = x1 * normalX + y1 * normalY + z1 * normalZ;
float d2 = x2 * normalX + y2 * normalY + z2 * normalZ;
final float d0 = x0 * normalX + y0 * normalY + z0 * normalZ;
final float d1 = x1 * normalX + y1 * normalY + z1 * normalZ;
final float d2 = x2 * normalX + y2 * normalY + z2 * normalZ;
// offset x, y, z by the projection to get the projected point on the normal plane
x0 -= d0 * normalX;
@@ -173,30 +157,30 @@ public abstract class NormalHelper {
z2 -= d2 * normalZ;
float edge1x = x1 - x0;
float edge1y = y1 - y0;
float edge1z = z1 - z0;
final float edge1x = x1 - x0;
final float edge1y = y1 - y0;
final float edge1z = z1 - z0;
float edge2x = x2 - x0;
float edge2y = y2 - y0;
float edge2z = z2 - z0;
final float edge2x = x2 - x0;
final float edge2y = y2 - y0;
final float edge2z = z2 - z0;
float u0 = t.u(0);
float v0 = t.v(0);
final float u0 = t.u(0);
final float v0 = t.v(0);
float u1 = t.u(1);
float v1 = t.v(1);
final float u1 = t.u(1);
final float v1 = t.v(1);
float u2 = t.u(2);
float v2 = t.v(2);
final float u2 = t.u(2);
final float v2 = t.v(2);
float deltaU1 = u1 - u0;
float deltaV1 = v1 - v0;
float deltaU2 = u2 - u0;
float deltaV2 = v2 - v0;
final float deltaU1 = u1 - u0;
final float deltaV1 = v1 - v0;
final float deltaU2 = u2 - u0;
final float deltaV2 = v2 - v0;
float fdenom = deltaU1 * deltaV2 - deltaU2 * deltaV1;
float f;
final float fdenom = deltaU1 * deltaV2 - deltaU2 * deltaV1;
final float f;
if (fdenom == 0.0) {
f = 1.0f;
@@ -207,7 +191,7 @@ public abstract class NormalHelper {
float tangentx = f * (deltaV2 * edge1x - deltaV1 * edge2x);
float tangenty = f * (deltaV2 * edge1y - deltaV1 * edge2y);
float tangentz = f * (deltaV2 * edge1z - deltaV1 * edge2z);
float tcoeff = rsqrt(tangentx * tangentx + tangenty * tangenty + tangentz * tangentz);
final float tcoeff = rsqrt(tangentx * tangentx + tangenty * tangenty + tangentz * tangentz);
tangentx *= tcoeff;
tangenty *= tcoeff;
tangentz *= tcoeff;
@@ -215,7 +199,7 @@ public abstract class NormalHelper {
float bitangentx = f * (-deltaU2 * edge1x + deltaU1 * edge2x);
float bitangenty = f * (-deltaU2 * edge1y + deltaU1 * edge2y);
float bitangentz = f * (-deltaU2 * edge1z + deltaU1 * edge2z);
float bitcoeff = rsqrt(bitangentx * bitangentx + bitangenty * bitangenty + bitangentz * bitangentz);
final float bitcoeff = rsqrt(bitangentx * bitangentx + bitangenty * bitangenty + bitangentz * bitangentz);
bitangentx *= bitcoeff;
bitangenty *= bitcoeff;
bitangentz *= bitcoeff;
@@ -230,12 +214,12 @@ public abstract class NormalHelper {
// such as vector cross products! The calculation for pbitangentz
// used to be broken because it multiplied values in the wrong order.
float pbitangentx = tangenty * normalZ - tangentz * normalY;
float pbitangenty = tangentz * normalX - tangentx * normalZ;
float pbitangentz = tangentx * normalY - tangenty * normalX;
final float pbitangentx = tangenty * normalZ - tangentz * normalY;
final float pbitangenty = tangentz * normalX - tangentx * normalZ;
final float pbitangentz = tangentx * normalY - tangenty * normalX;
float dot = (bitangentx * pbitangentx) + (bitangenty * pbitangenty) + (bitangentz * pbitangentz);
float tangentW;
final float dot = (bitangentx * pbitangentx) + (bitangenty * pbitangenty) + (bitangentz * pbitangentz);
final float tangentW;
if (dot < 0) {
tangentW = -1.0F;
@@ -248,42 +232,42 @@ public abstract class NormalHelper {
public static int computeTangent(float normalX, float normalY, float normalZ, TriView t) {
// Capture all of the relevant vertex positions
float x0 = t.x(0);
float y0 = t.y(0);
float z0 = t.z(0);
final float x0 = t.x(0);
final float y0 = t.y(0);
final float z0 = t.z(0);
float x1 = t.x(1);
float y1 = t.y(1);
float z1 = t.z(1);
final float x1 = t.x(1);
final float y1 = t.y(1);
final float z1 = t.z(1);
float x2 = t.x(2);
float y2 = t.y(2);
float z2 = t.z(2);
final float x2 = t.x(2);
final float y2 = t.y(2);
final float z2 = t.z(2);
float edge1x = x1 - x0;
float edge1y = y1 - y0;
float edge1z = z1 - z0;
final float edge1x = x1 - x0;
final float edge1y = y1 - y0;
final float edge1z = z1 - z0;
float edge2x = x2 - x0;
float edge2y = y2 - y0;
float edge2z = z2 - z0;
final float edge2x = x2 - x0;
final float edge2y = y2 - y0;
final float edge2z = z2 - z0;
float u0 = t.u(0);
float v0 = t.v(0);
final float u0 = t.u(0);
final float v0 = t.v(0);
float u1 = t.u(1);
float v1 = t.v(1);
final float u1 = t.u(1);
final float v1 = t.v(1);
float u2 = t.u(2);
float v2 = t.v(2);
final float u2 = t.u(2);
final float v2 = t.v(2);
float deltaU1 = u1 - u0;
float deltaV1 = v1 - v0;
float deltaU2 = u2 - u0;
float deltaV2 = v2 - v0;
final float deltaU1 = u1 - u0;
final float deltaV1 = v1 - v0;
final float deltaU2 = u2 - u0;
final float deltaV2 = v2 - v0;
float fdenom = deltaU1 * deltaV2 - deltaU2 * deltaV1;
float f;
final float fdenom = deltaU1 * deltaV2 - deltaU2 * deltaV1;
final float f;
if (fdenom == 0.0) {
f = 1.0f;
@@ -294,7 +278,7 @@ public abstract class NormalHelper {
float tangentx = f * (deltaV2 * edge1x - deltaV1 * edge2x);
float tangenty = f * (deltaV2 * edge1y - deltaV1 * edge2y);
float tangentz = f * (deltaV2 * edge1z - deltaV1 * edge2z);
float tcoeff = rsqrt(tangentx * tangentx + tangenty * tangenty + tangentz * tangentz);
final float tcoeff = rsqrt(tangentx * tangentx + tangenty * tangenty + tangentz * tangentz);
tangentx *= tcoeff;
tangenty *= tcoeff;
tangentz *= tcoeff;
@@ -302,7 +286,7 @@ public abstract class NormalHelper {
float bitangentx = f * (-deltaU2 * edge1x + deltaU1 * edge2x);
float bitangenty = f * (-deltaU2 * edge1y + deltaU1 * edge2y);
float bitangentz = f * (-deltaU2 * edge1z + deltaU1 * edge2z);
float bitcoeff = rsqrt(bitangentx * bitangentx + bitangenty * bitangenty + bitangentz * bitangentz);
final float bitcoeff = rsqrt(bitangentx * bitangentx + bitangenty * bitangenty + bitangentz * bitangentz);
bitangentx *= bitcoeff;
bitangenty *= bitcoeff;
bitangentz *= bitcoeff;
@@ -317,12 +301,12 @@ public abstract class NormalHelper {
// such as vector cross products! The calculation for pbitangentz
// used to be broken because it multiplied values in the wrong order.
float pbitangentx = tangenty * normalZ - tangentz * normalY;
float pbitangenty = tangentz * normalX - tangentx * normalZ;
float pbitangentz = tangentx * normalY - tangenty * normalX;
final float pbitangentx = tangenty * normalZ - tangentz * normalY;
final float pbitangenty = tangentz * normalX - tangentx * normalZ;
final float pbitangentz = tangentx * normalY - tangenty * normalX;
float dot = (bitangentx * pbitangentx) + (bitangenty * pbitangenty) + (bitangentz * pbitangentz);
float tangentW;
final float dot = (bitangentx * pbitangentx) + (bitangenty * pbitangenty) + (bitangentz * pbitangentz);
final float tangentW;
if (dot < 0) {
tangentW = -1.0F;