Compare commits

..
80 changed files with 896 additions and 3221 deletions

No files matched your search

-3
View File
@@ -186,8 +186,6 @@ DependencyHandlerScope.of(dependencies).apply {
compileOnly("mega:fluidlogged-mc1.7.10:0.1.2")
compileOnly("com.github.GTNewHorizons:LiquidLogged:0.2.0:dev") { isTransitive = false }
compileOnly("com.cardinalstar.cubicchunks:CubicChunks1710:v0.1.5-alpha:dev") { isTransitive = false }
}
@@ -212,7 +210,6 @@ afterEvaluate {
glsmTestFixtures(testFixtures(project(":glsm")) as ModuleDependency) { isTransitive = false }
testCompileOnly(testFixtures(project(":glsm")))
testImplementation("mega:fluidlogged-mc1.7.10:0.1.2")
testImplementation("com.github.GTNewHorizons:LiquidLogged:0.2.0:dev") { isTransitive = false }
testRuntimeOnly(libs.fastutil)
testRuntimeOnly(libs.joml)
@@ -66,8 +66,6 @@ public final class SystemProperties {
public static final String FLYBY_COMMANDS = System.getProperty("angelica.flyby.commands", "");
public static final String FLYBY_ORIGIN = System.getProperty("angelica.flyby.origin", "");
public static final Integer FLYBY_DIMENSION = Integer.getInteger("angelica.flyby.dimension");
public static final String FLYBY_BIOME = System.getProperty("angelica.flyby.biome", "");
public static final boolean FLYBY_SURVIVAL = Boolean.getBoolean("angelica.flyby.survival");
public static final FlybyPacing FLYBY_PACING = parseEnum("angelica.flyby.pacing", FlybyPacing.UNCAPPED, FlybyPacing.UNCAPPED, FlybyPacing.class);
public static final FlybyWeather FLYBY_WEATHER = parseEnum("angelica.flyby.weather", FlybyWeather.CLEAR, FlybyWeather.CLEAR, FlybyWeather.class);
public static final FlybyCamera FLYBY_CAMERA = parseEnum("angelica.flyby.camera", FlybyCamera.FIRST_PERSON, FlybyCamera.FIRST_PERSON, FlybyCamera.class);
@@ -108,13 +108,11 @@ public final class FFPUniformBlock {
public static final int FOG_PARAMS = vec4("u_FogParams");
public static final int FOG_COLOR = vec4("u_FogColor");
// Weather columns, for Instancing.WEATHER. 0 = (translate.xyz, 1/radius),
// 1 = (cameraFrac.xy, partialTicks, age), 2 = (vanillaTick, providerTick, rainStrength, providerAge),
// 3 = (provider 1/radius, unused, unused, unused).
// Rain and snow, for Instancing.WEATHER. 0 = (translate.xyz, 1/radius),
// 1 = (cameraFrac.xy, partialTicks, age), 2 = (rainScroll, snowScroll, rainStrength, unused).
public static final int WEATHER_PARAMS_0 = vec4("u_WeatherParams0");
public static final int WEATHER_PARAMS_1 = vec4("u_WeatherParams1");
public static final int WEATHER_PARAMS_2 = vec4("u_WeatherParams2");
public static final int WEATHER_PARAMS_3 = vec4("u_WeatherParams3");
public static final int SIZE;
public static final String GLSL_DECL;
@@ -39,16 +39,17 @@ public final class InstancedGlslHelpers {
vec2 {p}wColumn = {span}.xy;
float {p}wBottom = {span}.z;
float {p}wTop = {span}.w;
float {p}wLightV = floor({params}.x / 65536.0);
vec2 {p}wLightmap = vec2({params}.x - {p}wLightV * 65536.0, {p}wLightV);
bool {p}wProvider = {params}.w > 0.5;
vec2 {p}wLightmap = {params}.xy;
float {p}wHash = {params}.z;
bool {p}wSnow = {params}.w > 0.5;
vec3 {p}wTranslate = {p}WeatherParams0.xyz;
float {p}wInvRadius = {p}wProvider ? {p}WeatherParams3.x : {p}WeatherParams0.w;
float {p}wInvRadius = {p}WeatherParams0.w;
vec2 {p}wCameraFrac = {p}WeatherParams1.xy;
float {p}wPartialTicks = {p}WeatherParams1.z;
float {p}wAge = {p}wProvider ? {p}WeatherParams2.w : {p}WeatherParams1.w;
float {p}wTick = {p}wProvider ? {p}WeatherParams2.y : {p}WeatherParams2.x;
float {p}wStrength = {p}wProvider ? 1.0 : {p}WeatherParams2.z;
float {p}wAge = {p}WeatherParams1.w;
float {p}wRainScroll = {p}WeatherParams2.x;
float {p}wSnowScroll = {p}WeatherParams2.y;
float {p}wStrength = {p}WeatherParams2.z;
vec2 {p}wHalfWidth = vec2(-{p}wColumn.y, {p}wColumn.x) * (0.5 / sqrt(dot({p}wColumn, {p}wColumn)));
vec2 {p}wCornerXZ = {p}wColumn + vec2(0.5) + ({corner}.x * 2.0 - 1.0) * {p}wHalfWidth;
@@ -57,13 +58,22 @@ public final class InstancedGlslHelpers {
float {p}wDistance = length({p}wColumn + vec2(0.5) - {p}wCameraFrac) * {p}wInvRadius;
float {p}wFade = 1.0 - {p}wDistance * {p}wDistance;
float {p}wScroll = (mod({p}wTick + {params}.y, {layer}.x) + {p}wPartialTicks) / {layer}.x * {params}.z;
vec2 {p}wDrift = vec2({jitter}.x + {p}wAge * {layer}.y * {jitter}.y, {jitter}.z + {p}wAge * {layer}.z * {jitter}.w);
float {p}wAlpha = {p}wFade * {layer}.w + 0.5;
float {p}wScroll;
vec2 {p}wDrift;
float {p}wAlpha;
if ({p}wSnow) {
{p}wScroll = ({p}wSnowScroll + {p}wPartialTicks) / 512.0;
{p}wDrift = vec2({jitter}.x + {p}wAge * 0.01 * {jitter}.y, {jitter}.z + {p}wAge * {jitter}.w * 0.001);
{p}wAlpha = {p}wFade * 0.3 + 0.5;
} else {
{p}wScroll = (mod({p}wRainScroll + {p}wHash, 32.0) + {p}wPartialTicks) / 32.0 * (3.0 + {jitter}.x);
{p}wDrift = vec2(0.0);
{p}wAlpha = {p}wFade * 0.5 + 0.5;
}
{tex0} = vec4({corner}.x + {p}wDrift.x, {p}wCornerY * 0.25 + {p}wScroll + {p}wDrift.y, 0.0, 1.0);
{tex1} = vec4({p}wLightmap, 0.0, 1.0);
{color} = floor(clamp(vec4({colorAttr}.rgb, {p}wAlpha * {colorAttr}.a * {p}wStrength), 0.0, 1.0) * 255.0) / 255.0;""";
{color} = vec4(1.0, 1.0, 1.0, {p}wAlpha * {p}wStrength);""";
public static String weatherPrologue(String uniformPrefix, String attribPrefix, String corner,
String vertex, String color, String tex0, String tex1, String sep) {
@@ -72,8 +82,6 @@ public final class InstancedGlslHelpers {
.replace("{span}", attribPrefix + "InstColumnSpan")
.replace("{jitter}", attribPrefix + "InstJitter")
.replace("{params}", attribPrefix + "InstWeatherParams")
.replace("{layer}", attribPrefix + "InstWeatherLayer")
.replace("{colorAttr}", attribPrefix + "InstWeatherColor")
.replace("{corner}", corner)
.replace("{vertex}", vertex)
.replace("{color}", color)
@@ -117,8 +125,6 @@ public final class InstancedGlslHelpers {
decls.add(decl(WeatherInstancedAttribs.LOC_COLUMN_SPAN, "vec4", prefix + "InstColumnSpan"));
decls.add(decl(WeatherInstancedAttribs.LOC_JITTER, "vec4", prefix + "InstJitter"));
decls.add(decl(WeatherInstancedAttribs.LOC_PARAMS, "vec4", prefix + "InstWeatherParams"));
decls.add(decl(WeatherInstancedAttribs.LOC_COLOR, "vec4", prefix + "InstWeatherColor"));
decls.add(decl(WeatherInstancedAttribs.LOC_LAYER, "vec4", prefix + "InstWeatherLayer"));
}
}
return decls.toArray(String[]::new);
@@ -391,9 +391,8 @@ public class Uniforms {
WeatherParams.translateZ, WeatherParams.invRadius);
putVec4(FFPUniformBlock.WEATHER_PARAMS_1, WeatherParams.cameraFracX, WeatherParams.cameraFracZ,
WeatherParams.partialTicks, WeatherParams.age);
putVec4(FFPUniformBlock.WEATHER_PARAMS_2, WeatherParams.vanillaTick, WeatherParams.providerTick,
WeatherParams.rainStrength, WeatherParams.providerAge);
putVec4(FFPUniformBlock.WEATHER_PARAMS_3, WeatherParams.providerInvRadius, 0.0f, 0.0f, 0.0f);
putVec4(FFPUniformBlock.WEATHER_PARAMS_2, WeatherParams.rainScroll, WeatherParams.snowScroll,
WeatherParams.rainStrength, 0.0f);
}
private void putVec4(int offset, Vector4f v) {
@@ -3,76 +3,31 @@ package com.gtnewhorizons.angelica.glsm.ffp;
import com.gtnewhorizons.angelica.glsm.GLSMVertexInput;
import org.lwjgl.opengl.GL11;
import java.nio.ByteBuffer;
/**
* One weather column per instance.
* One rain or snow column per instance.
*/
public final class WeatherInstancedAttribs {
public static final int LOC_COLUMN_SPAN = ParticleInstancedAttribs.LOC_CENTER_HALF;
public static final int LOC_JITTER = ParticleInstancedAttribs.LOC_UV;
public static final int LOC_PARAMS = InstancedAttribs.LOC_COLOR;
public static final int LOC_COLOR = InstancedAttribs.LOC_ROW2;
public static final int LOC_LAYER = InstancedAttribs.LOC_OVERLAY;
public static final int OFFSET_COLUMN_SPAN = 0;
public static final int OFFSET_JITTER = 16;
public static final int OFFSET_PARAMS = 32;
public static final int OFFSET_COLOR = 48;
public static final int OFFSET_LAYER = 64;
public static final int STRIDE = 80;
public static final int RAIN_PERIOD = 32;
public static final float RAIN_SCROLL_BASE = 3.0F;
public static final float RAIN_FADE = 0.5F;
public static final int SNOW_PERIOD = 512;
public static final float SNOW_U_DRIFT = 0.01F;
public static final float SNOW_V_DRIFT = 0.001F;
public static final float SNOW_FADE = 0.3F;
public static final float SOURCE_VANILLA = 0.0F;
public static final float SOURCE_PROVIDER = 1.0F;
public static void putColumn(ByteBuffer data, int index, float x, float z, float bottom, float top, float uBase, float uDrift,
float vBase, float vDrift, float brightness, int scrollOffset, float scrollScale, float source, float r, float g, float b,
float a, int period, float uDriftScale, float vDriftScale, float fadeScale) {
final int base = index * STRIDE;
data.putFloat(base + OFFSET_COLUMN_SPAN, x);
data.putFloat(base + OFFSET_COLUMN_SPAN + 4, z);
data.putFloat(base + OFFSET_COLUMN_SPAN + 8, bottom);
data.putFloat(base + OFFSET_COLUMN_SPAN + 12, top);
data.putFloat(base + OFFSET_JITTER, uBase);
data.putFloat(base + OFFSET_JITTER + 4, uDrift);
data.putFloat(base + OFFSET_JITTER + 8, vBase);
data.putFloat(base + OFFSET_JITTER + 12, vDrift);
data.putFloat(base + OFFSET_PARAMS, brightness);
data.putFloat(base + OFFSET_PARAMS + 4, scrollOffset & (period - 1));
data.putFloat(base + OFFSET_PARAMS + 8, scrollScale);
data.putFloat(base + OFFSET_PARAMS + 12, source);
data.putFloat(base + OFFSET_COLOR, r);
data.putFloat(base + OFFSET_COLOR + 4, g);
data.putFloat(base + OFFSET_COLOR + 8, b);
data.putFloat(base + OFFSET_COLOR + 12, a);
data.putFloat(base + OFFSET_LAYER, period);
data.putFloat(base + OFFSET_LAYER + 4, uDriftScale);
data.putFloat(base + OFFSET_LAYER + 8, vDriftScale);
data.putFloat(base + OFFSET_LAYER + 12, fadeScale);
}
public static final int STRIDE = 48;
public static void pointInstanceAttribs(long base) {
GLSMVertexInput.glVertexAttribPointer(LOC_COLUMN_SPAN, 4, GL11.GL_FLOAT, false, STRIDE, base + OFFSET_COLUMN_SPAN);
GLSMVertexInput.glVertexAttribPointer(LOC_JITTER, 4, GL11.GL_FLOAT, false, STRIDE, base + OFFSET_JITTER);
GLSMVertexInput.glVertexAttribPointer(LOC_PARAMS, 4, GL11.GL_FLOAT, false, STRIDE, base + OFFSET_PARAMS);
GLSMVertexInput.glVertexAttribPointer(LOC_COLOR, 4, GL11.GL_FLOAT, false, STRIDE, base + OFFSET_COLOR);
GLSMVertexInput.glVertexAttribPointer(LOC_LAYER, 4, GL11.GL_FLOAT, false, STRIDE, base + OFFSET_LAYER);
}
static void enableInstanceArrays() {
InstancedAttribs.enableInstanced(LOC_COLUMN_SPAN);
InstancedAttribs.enableInstanced(LOC_JITTER);
InstancedAttribs.enableInstanced(LOC_PARAMS);
InstancedAttribs.enableInstanced(LOC_COLOR);
InstancedAttribs.enableInstanced(LOC_LAYER);
}
private WeatherInstancedAttribs() {}
@@ -1,7 +1,7 @@
package com.gtnewhorizons.angelica.glsm.ffp;
/**
* The per-frame half of the weather column instancing, set once per frame.
* The per-frame half of the rain and snow instancing, set once per weather draw.
*/
public final class WeatherParams {
@@ -15,14 +15,9 @@ public final class WeatherParams {
public static float partialTicks;
public static float age;
public static float vanillaTick;
public static float providerTick;
public static float rainScroll;
public static float snowScroll;
public static float rainStrength;
public static float providerAge;
public static float providerInvRadius;
public static final int TICK_WRAP = 1024;
public static int generation;
@@ -30,7 +25,7 @@ public final class WeatherParams {
public static void set(float translateX, float translateY, float translateZ, float invRadius,
float cameraFracX, float cameraFracZ, float partialTicks, float age,
int vanillaTick, float rainStrength, int providerTick, float providerAge, float providerInvRadius) {
float rainScroll, float snowScroll, float rainStrength) {
WeatherParams.translateX = translateX;
WeatherParams.translateY = translateY;
WeatherParams.translateZ = translateZ;
@@ -39,11 +34,9 @@ public final class WeatherParams {
WeatherParams.cameraFracZ = cameraFracZ;
WeatherParams.partialTicks = partialTicks;
WeatherParams.age = age;
WeatherParams.vanillaTick = vanillaTick & (TICK_WRAP - 1);
WeatherParams.providerTick = providerTick & (TICK_WRAP - 1);
WeatherParams.rainScroll = rainScroll;
WeatherParams.snowScroll = snowScroll;
WeatherParams.rainStrength = rainStrength;
WeatherParams.providerAge = providerAge;
WeatherParams.providerInvRadius = providerInvRadius;
generation++;
}
}
@@ -11,7 +11,7 @@ import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* The four corners every weather column is expanded from. x picks the end of the billboard, y picks
* The four corners every rain and snow column is expanded from. x picks the end of the billboard, y picks
* the bottom or top edge.
*/
public final class WeatherQuadMesh {
@@ -49,6 +49,14 @@ public final class WeatherQuadMesh {
return vao;
}
public static void bindInstanceBuffer(int bufferId) {
GLSMVertexInput.glBindVertexArray(vao());
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, bufferId);
WeatherInstancedAttribs.pointInstanceAttribs(0L);
GLSMVertexInput.glBindVertexArray(0);
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
}
public static void delete() {
if (vbo != 0) {
GLSMBuffers.glDeleteBuffers(vbo);
@@ -100,7 +100,6 @@ class InstancedFFPDrawGLTest {
CubeParityFixture.disableDirectionalLight();
CubeParityFixture.deleteResources();
ParticleParityFixture.deleteResources();
WeatherParityFixture.deleteResources();
if (templateVbo != 0) { GLSMBuffers.glDeleteBuffers(templateVbo); templateVbo = 0; }
if (instanceVbo != 0) { GLSMBuffers.glDeleteBuffers(instanceVbo); instanceVbo = 0; }
if (vao != 0) { GLSMVertexInput.glDeleteVertexArrays(vao); vao = 0; }
@@ -197,27 +196,6 @@ class InstancedFFPDrawGLTest {
ParticleParityFixture.assertPixelParity(reference, instanced, PARITY_SIZE, 0xFF000000, pixel -> "0x" + Integer.toHexString(pixel));
}
@Test
void weatherColumnsMatchTessellatedReference() {
GLSMRasterizer.glViewport(0, 0, PARITY_SIZE, PARITY_SIZE);
WeatherParityFixture.setupScene();
FfpFixture.activateFfp();
final WeatherParityFixture.Spec[] specs = WeatherParityFixture.specs();
FfpFixture.clear();
WeatherParityFixture.drawReference(specs);
final int[] reference = FfpFixture.readRegion(PARITY_SIZE);
FfpFixture.clear();
WeatherParityFixture.drawInstanced(specs);
final int[] instanced = FfpFixture.readRegion(PARITY_SIZE);
assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "parity draws must not raise a GL error");
WeatherParityFixture.assertPixelParity(reference, instanced, PARITY_SIZE, 0xFF000000, pixel -> "0x" + Integer.toHexString(pixel));
}
@Test
void entityAttribSelectsColorPerInstance() {
GLSMRasterizer.glViewport(0, 0, INTEGER_WIDTH, INTEGER_HEIGHT);
@@ -1,292 +0,0 @@
package com.gtnewhorizons.angelica.glsm.ffp;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags;
import com.gtnewhorizons.angelica.glsm.GLSMBlend;
import com.gtnewhorizons.angelica.glsm.GLSMBuffers;
import com.gtnewhorizons.angelica.glsm.GLSMDraws;
import com.gtnewhorizons.angelica.glsm.GLSMEnable;
import com.gtnewhorizons.angelica.glsm.GLSMMatrices;
import com.gtnewhorizons.angelica.glsm.GLSMPrograms;
import com.gtnewhorizons.angelica.glsm.GLSMTextures;
import com.gtnewhorizons.angelica.glsm.GLSMVertexInput;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL15;
import java.nio.ByteBuffer;
import java.util.function.IntFunction;
public final class WeatherParityFixture {
public record Spec(float x, float z, float bottom, float top, float uBase, float uDrift, float vBase, float vDrift,
int brightness, int scrollOffset, float scrollScale, float source,
float r, float g, float b, float a, int period, float uDriftScale, float vDriftScale, float fadeScale) {}
private static final int TICK = 2650;
private static final float PARTIAL_TICKS = 0.375f;
private static final float TRANSLATE_X = 0.37f;
private static final float TRANSLATE_Y = -62.25f;
private static final float TRANSLATE_Z = -0.61f;
private static final float INV_RADIUS = 1.0f / 6.0f;
private static final float CAMERA_FRAC_X = 0.3f;
private static final float CAMERA_FRAC_Z = 0.7f;
private static final float STRENGTH = 0.8f;
private static final int PROVIDER_TICK = 1777;
private static final float PROVIDER_INV_RADIUS = 1.0f / 9.0f;
private static final float[] CORNER_X = { 0.0f, 1.0f, 1.0f, 0.0f };
private static final float[] CORNER_Y = { 0.0f, 0.0f, 1.0f, 1.0f };
private static final int REF_STRIDE = 44;
private static int referenceVao;
private static int referenceVbo;
private static int instanceVbo;
private static int weatherTexture;
private static int lightmapTexture;
private WeatherParityFixture() {}
private static Spec rain(float x, float z, float bottom, float top, float j0, int hash, int brightness) {
return new Spec(x, z, bottom, top, 0f, 0f, 0f, 0f, brightness, hash, WeatherInstancedAttribs.RAIN_SCROLL_BASE + j0, WeatherInstancedAttribs.SOURCE_VANILLA,
1f, 1f, 1f, 1f, WeatherInstancedAttribs.RAIN_PERIOD, 0f, 0f, WeatherInstancedAttribs.RAIN_FADE);
}
private static Spec snow(float x, float z, float bottom, float top, float j0, float j1, float j2, float j3, int brightness) {
return new Spec(x, z, bottom, top, j0, j1, j2, j3, brightness, 0, 1f, WeatherInstancedAttribs.SOURCE_VANILLA,
1f, 1f, 1f, 1f, WeatherInstancedAttribs.SNOW_PERIOD, WeatherInstancedAttribs.SNOW_U_DRIFT, WeatherInstancedAttribs.SNOW_V_DRIFT,
WeatherInstancedAttribs.SNOW_FADE);
}
private static Spec provider(float x, float z, float bottom, float top, float uBase, float uDrift, float vBase, float vDrift,
int brightness, int scrollOffset, float scrollScale, float r, float g, float b, float a,
int period, float uDriftScale, float vDriftScale, float fadeScale) {
return new Spec(x, z, bottom, top, uBase, uDrift, vBase, vDrift, brightness, scrollOffset, scrollScale, WeatherInstancedAttribs.SOURCE_PROVIDER, r, g, b, a,
period, uDriftScale, vDriftScale, fadeScale);
}
public static Spec[] specs() {
return new Spec[] {
rain(-4f, -3f, 58f, 66f, 0.31f, 5, 0x00F00030),
rain(2f, -4f, 60f, 67f, 0.77f, 19, 0x00A000D0),
rain(-2f, 3f, 57f, 65f, 0.05f, 62, 0x0060F0A0),
rain(4f, 2f, 59f, 64f, 0.58f, 11, 0x00D01090),
rain(1f, 4f, 56f, 66f, 0.93f, 24, 0x0080C0F0),
snow(-5f, 1f, 58f, 66f, 0.12f, 0.47f, 0.83f, 0.29f, 0x00E02070),
snow(3f, -2f, 60f, 68f, 0.66f, 0.91f, 0.18f, 0.74f, 0x00B0B0B0),
snow(-1f, -5f, 57f, 63f, 0.39f, 0.25f, 0.52f, 0.96f, 0x0040E0C0),
snow(5f, 4f, 59f, 67f, 0.84f, 0.63f, 0.07f, 0.41f, 0x00F0F0F0),
snow(-3f, 5f, 55f, 65f, 0.22f, 0.78f, 0.35f, 0.58f, 0x00109050),
provider(-5f, -4f, 58f, 66f, 0.14f, 0.52f, 0.71f, 0.33f, 0x00C06040, 0, 1f, 1f, 1f, 1f, 1f, 512, 0.03f, 0.001f, 0.3f),
provider(4f, -3f, 59f, 67f, 0.61f, 0.27f, 0.09f, 0.88f, 0x00F020B0, 0, 1f, 1f, 1f, 1f, 1f, 512, 0.03f, 0.001f, 0.3f),
provider(-4f, 2f, 57f, 65f, 0.42f, 0.36f, 0.64f, 0.19f, 0x0090D070, 0, 0f, 0.12f, 0.27f, 0.18f, 2.0f, 512, 0.03f, 0.003f, 0f),
provider(2f, 5f, 60f, 66f, 0.83f, 0.74f, 0.25f, 0.57f, 0x0050A0E0, 0, 0f, 0.29f, 0.14f, 0.21f, 2.0f, 512, 0.03f, 0.003f, 0f),
provider(-2f, -5f, 56f, 64f, 0.07f, 0.45f, 0.93f, 0.62f, 0x00B0F040, 0, -1f, 0.83f, 0.92f, 0.88f, 1f, 1024, 0.001f, 0.001f, 0.3f),
provider(5f, 1f, 58f, 68f, 0.55f, 0.16f, 0.38f, 0.81f, 0x007070F0, 0, -1f, 0.97f, 0.86f, 0.81f, 1f, 1024, 0.001f, 0.001f, 0.3f),
provider(-5f, 4f, 59f, 66f, 0f, 0.68f, 0f, 0.23f, 0x00E0E050, 0, -1f, 1f, 1f, 1f, 0.35f, 512, 0f, 0.01f, 0.3f),
provider(3f, 3f, 57f, 67f, 0f, 0.49f, 0f, 0.91f, 0x0030C0A0, 0, -1f, 1f, 1f, 1f, 0.82f, 512, 0f, 0.01f, 0.3f),
provider(0f, -4f, 58f, 65f, 0.26f, 0.12f, 0.67f, 0.44f, 0x00A0A0A0, 21, 3.46f, 1f, 1f, 1f, 1f, 32, 0f, 0f, 0.3f),
provider(1f, 3f, 60f, 66f, 0.89f, 0.31f, 0.15f, 0.76f, 0x00F0A040, 7, 3.81f, 1f, 1f, 1f, 1f, 32, 0f, 0f, 0.3f),
provider(-3f, 0f, 56f, 67f, 0.33f, 0.85f, 0.48f, 0.13f, 0x00D0D0D0, 0, 1f, 1f, 1f, 1f, 0.24f, 512, 0.01f, 0.01f, 0.3f),
provider(0f, 5f, 58f, 64f, 0.72f, 0.04f, 0.59f, 0.97f, 0x0010F0F0, 0, 1f, 1f, 1f, 1f, 0.67f, 512, 0.01f, 0.01f, 0.3f),
};
}
private static float mod(float x, float y) {
return x - y * (float) Math.floor(x / y);
}
public static void setupScene() {
GLSMEnable.glDisable(GL11.GL_FOG);
GLSMEnable.glDisable(GL11.GL_ALPHA_TEST);
GLSMEnable.glDisable(GL11.GL_DEPTH_TEST);
GLSMEnable.glDisable(GL11.GL_CULL_FACE);
GLSMEnable.glDisable(GL11.GL_LIGHTING);
GLSMEnable.glEnable(GL11.GL_BLEND);
GLSMBlend.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLSMMatrices.glMatrixMode(GL11.GL_PROJECTION);
GLSMMatrices.glLoadIdentity();
GLSMMatrices.glOrtho(-8.0, 8.0, -8.0, 8.0, -64.0, 64.0);
GLSMMatrices.glMatrixMode(GL11.GL_MODELVIEW);
GLSMMatrices.glLoadIdentity();
GLSMMatrices.glRotatef(30.0f, 1.0f, 0.0f, 0.0f);
GLSMMatrices.glRotatef(35.0f, 0.0f, 1.0f, 0.0f);
lightmapTexture = createTexture(GL13.GL_TEXTURE1, 16, GL11.GL_LINEAR, GL11.GL_CLAMP);
GLSMMatrices.glMatrixMode(GL11.GL_TEXTURE);
GLSMMatrices.glLoadIdentity();
GLSMMatrices.glScalef(0.00390625f, 0.00390625f, 0.00390625f);
GLSMMatrices.glTranslatef(8.0f, 8.0f, 8.0f);
GLSMMatrices.glMatrixMode(GL11.GL_MODELVIEW);
weatherTexture = createTexture(GL13.GL_TEXTURE0, 4, GL11.GL_NEAREST, GL11.GL_REPEAT);
GLSMMatrices.glMatrixMode(GL11.GL_TEXTURE);
GLSMMatrices.glLoadIdentity();
GLSMMatrices.glMatrixMode(GL11.GL_MODELVIEW);
}
private static int createTexture(int unit, int size, int filter, int wrap) {
final int id = GLSMTextures.glGenTextures();
GLSMTextures.glActiveTexture(unit);
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, id);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, filter);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, filter);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, wrap);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, wrap);
final ByteBuffer texels = BufferUtils.createByteBuffer(size * size * 4);
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
texels.put((byte) (40 + x * (200 / size)));
texels.put((byte) (40 + y * (200 / size)));
texels.put((byte) (255 - (x + y) * (100 / size)));
texels.put((byte) 255);
}
}
texels.flip();
GLSMTextures.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, size, size, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, texels);
GLSMEnable.glEnable(GL11.GL_TEXTURE_2D);
return id;
}
private static void putVertex(ByteBuffer data, float px, float py, float pz, float r, float g, float b, float a,
float u, float v, float lmX, float lmY) {
final int base = data.position();
data.putFloat(base, px);
data.putFloat(base + 4, py);
data.putFloat(base + 8, pz);
data.putFloat(base + 12, r);
data.putFloat(base + 16, g);
data.putFloat(base + 20, b);
data.putFloat(base + 24, a);
data.putFloat(base + 28, u);
data.putFloat(base + 32, v);
data.putFloat(base + 36, lmX);
data.putFloat(base + 40, lmY);
data.position(base + REF_STRIDE);
}
private static float tessellatorByte(float channel) {
final int value = (int) (channel * 255.0F);
return Math.max(0, Math.min(255, value)) / 255.0f;
}
private static void addColumn(ByteBuffer data, Spec s) {
final boolean provider = s.source() == WeatherInstancedAttribs.SOURCE_PROVIDER;
final int tick = provider ? PROVIDER_TICK : TICK;
final float age = tick + PARTIAL_TICKS;
final float invRadius = provider ? PROVIDER_INV_RADIUS : INV_RADIUS;
final float strength = provider ? 1.0f : STRENGTH;
final float halfScale = 0.5f / (float) Math.sqrt(s.x() * s.x() + s.z() * s.z());
final float halfX = -s.z() * halfScale;
final float halfZ = s.x() * halfScale;
final float dx = s.x() + 0.5f - CAMERA_FRAC_X;
final float dz = s.z() + 0.5f - CAMERA_FRAC_Z;
final float distance = (float) Math.sqrt(dx * dx + dz * dz) * invRadius;
final float fade = 1.0f - distance * distance;
final float scroll = (mod((float) tick + s.scrollOffset(), s.period()) + PARTIAL_TICKS) / s.period() * s.scrollScale();
final float driftU = s.uBase() + age * s.uDriftScale() * s.uDrift();
final float driftV = s.vBase() + age * s.vDriftScale() * s.vDrift();
final float alpha = fade * s.fadeScale() + 0.5f;
final float r = tessellatorByte(s.r());
final float g = tessellatorByte(s.g());
final float b = tessellatorByte(s.b());
final float a = tessellatorByte(alpha * s.a() * strength);
final float lmX = s.brightness() & 0xFFFF;
final float lmY = s.brightness() >> 16 & 0xFFFF;
for (int i = 0; i < 4; i++) {
final float side = CORNER_X[i] * 2.0f - 1.0f;
final float cornerX = s.x() + 0.5f + side * halfX;
final float cornerZ = s.z() + 0.5f + side * halfZ;
final float cornerY = s.bottom() * (1.0f - CORNER_Y[i]) + s.top() * CORNER_Y[i];
putVertex(data, cornerX + TRANSLATE_X, cornerY + TRANSLATE_Y, cornerZ + TRANSLATE_Z, r, g, b, a,
CORNER_X[i] + driftU, cornerY * 0.25f + scroll + driftV, lmX, lmY);
}
}
private static ByteBuffer buildReferenceData(Spec[] specs) {
final ByteBuffer data = BufferUtils.createByteBuffer(specs.length * 4 * REF_STRIDE);
for (Spec s : specs) {
addColumn(data, s);
}
data.flip();
return data;
}
public static void drawReference(Spec[] specs) {
final ByteBuffer data = buildReferenceData(specs);
if (referenceVao == 0) referenceVao = GLSMVertexInput.glGenVertexArrays();
GLSMVertexInput.glBindVertexArray(referenceVao);
if (referenceVbo == 0) referenceVbo = GLSMBuffers.glGenBuffers();
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, referenceVbo);
GLSMBuffers.glBufferData(GL15.GL_ARRAY_BUFFER, data, GL15.GL_STREAM_DRAW);
FfpFixture.attrib(0, 3, GL11.GL_FLOAT, false, REF_STRIDE, 0);
FfpFixture.attrib(1, 4, GL11.GL_FLOAT, false, REF_STRIDE, 12);
FfpFixture.attrib(2, 2, GL11.GL_FLOAT, false, REF_STRIDE, 28);
FfpFixture.attrib(3, 2, GL11.GL_FLOAT, false, REF_STRIDE, 36);
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
VAOManager.setCurrentVertexFlags(VertexFlags.COLOR_BIT | VertexFlags.TEXTURE_BIT | VertexFlags.BRIGHTNESS_BIT);
GLSMDraws.glDrawArrays(GL11.GL_QUADS, 0, specs.length * 4);
GLSMVertexInput.glBindVertexArray(0);
}
public static void drawInstanced(Spec[] specs) {
final ByteBuffer records = BufferUtils.createByteBuffer(specs.length * WeatherInstancedAttribs.STRIDE);
for (int i = 0; i < specs.length; i++) {
final Spec s = specs[i];
WeatherInstancedAttribs.putColumn(records, i, s.x(), s.z(), s.bottom(), s.top(), s.uBase(), s.uDrift(), s.vBase(), s.vDrift(),
s.brightness(), s.scrollOffset(), s.scrollScale(), s.source(), s.r(), s.g(), s.b(), s.a(),
s.period(), s.uDriftScale(), s.vDriftScale(), s.fadeScale());
}
WeatherParams.set(TRANSLATE_X, TRANSLATE_Y, TRANSLATE_Z, INV_RADIUS, CAMERA_FRAC_X, CAMERA_FRAC_Z,
PARTIAL_TICKS, TICK + PARTIAL_TICKS, TICK, STRENGTH, PROVIDER_TICK, PROVIDER_TICK + PARTIAL_TICKS, PROVIDER_INV_RADIUS);
GLSMVertexInput.glBindVertexArray(WeatherQuadMesh.vao());
if (instanceVbo == 0) instanceVbo = GLSMBuffers.glGenBuffers();
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, instanceVbo);
GLSMBuffers.glBufferData(GL15.GL_ARRAY_BUFFER, records, GL15.GL_STREAM_DRAW);
WeatherInstancedAttribs.pointInstanceAttribs(0L);
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
VAOManager.setCurrentVertexFlags(WeatherQuadMesh.VERTEX_FLAGS);
GLSMPrograms.setFfpInstancing(Instancing.WEATHER);
GLSMDraws.glDrawArraysInstanced(GL11.GL_TRIANGLE_FAN, 0, WeatherQuadMesh.VERTEX_COUNT, specs.length);
GLSMPrograms.setFfpInstancing(Instancing.NONE);
GLSMVertexInput.glBindVertexArray(0);
}
public static void assertPixelParity(int[] reference, int[] instanced, int size, int background, IntFunction<String> describe) {
FfpFixture.assertPixelParity("instanced weather columns", reference, instanced, size, background, 16, 0, describe);
}
public static void deleteResources() {
if (instanceVbo != 0) {
GLSMBuffers.glDeleteBuffers(instanceVbo);
instanceVbo = 0;
}
if (referenceVbo != 0) {
GLSMBuffers.glDeleteBuffers(referenceVbo);
referenceVbo = 0;
}
if (referenceVao != 0) {
GLSMVertexInput.glDeleteVertexArrays(referenceVao);
referenceVao = 0;
}
if (weatherTexture != 0) {
GLSMTextures.glDeleteTextures(weatherTexture);
weatherTexture = 0;
}
if (lightmapTexture != 0) {
GLSMTextures.glDeleteTextures(lightmapTexture);
lightmapTexture = 0;
}
WeatherQuadMesh.delete();
}
}
-2
View File
@@ -11,8 +11,6 @@
# extra - passed through to gradle; -Dangelica.* reaches the client (e.g. -Dangelica.flyby.timeOfDay=1500).
# -Dangelica.flyby.camera=FIRST_PERSON|THIRD_PERSON_BACK|THIRD_PERSON_FRONT (default FIRST_PERSON).
# -Dangelica.flyby.dimension=<id> moves the player there first (1 = End), after world saving is off.
# -Dangelica.flyby.biome=<name> pins the origin to the 44x44-block area of that biome nearest to 0,0 (BiomeGenBase.biomeName), searched in the target dimension.
# -Dangelica.flyby.survival=true runs the flight in survival with flying and no damage, restoring the original game mode afterwards.
# -PclientJvmVendor=adoptium (macOS) picks the JVM vendor for runClient17/21/25.
#
# FLYBY_SPEED - blocks per tick. (0.5 ~= creative flight).
@@ -0,0 +1,83 @@
# Translucent TESR ordering scene for a generated superflat (windows-flyby-kit/make_world.py). Needs
# -Dangelica.debug.testBlocks=true. $x $y $z is the flight start; ground-standing level is $y-2. Start facing south (yaw 0),
# pitch 15. Blocks: test_tesr_provider (0 translucent red, 1 additive purple), test_tesr_model (0 box pane,
# 1 Tessellator pane, 2 stacked A/B/A panes), test_tesr_decal, test_tesr_glow; metadata + 8 draws in the solid pass.
gamerule doMobSpawning false
# translucent pass: three rows, materials shifted per row so every column stacks three different ones
setblock $x-2 $y $z+6 angelica:test_tesr_provider 0 replace
setblock $x-1 $y $z+6 angelica:test_tesr_provider 1 replace
setblock $x+0 $y $z+6 angelica:test_tesr_model 0 replace
setblock $x+1 $y $z+6 angelica:test_tesr_model 1 replace
setblock $x-2 $y $z+8 angelica:test_tesr_provider 1 replace
setblock $x-1 $y $z+8 angelica:test_tesr_model 0 replace
setblock $x+0 $y $z+8 angelica:test_tesr_model 1 replace
setblock $x+1 $y $z+8 angelica:test_tesr_provider 0 replace
setblock $x-2 $y $z+10 angelica:test_tesr_model 0 replace
setblock $x-1 $y $z+10 angelica:test_tesr_model 1 replace
setblock $x+0 $y $z+10 angelica:test_tesr_provider 0 replace
setblock $x+1 $y $z+10 angelica:test_tesr_provider 1 replace
# solid pass: the same rows two blocks higher
setblock $x-2 $y+2 $z+6 angelica:test_tesr_provider 8 replace
setblock $x-1 $y+2 $z+6 angelica:test_tesr_provider 9 replace
setblock $x+0 $y+2 $z+6 angelica:test_tesr_model 8 replace
setblock $x+1 $y+2 $z+6 angelica:test_tesr_model 9 replace
setblock $x-2 $y+2 $z+8 angelica:test_tesr_provider 9 replace
setblock $x-1 $y+2 $z+8 angelica:test_tesr_model 8 replace
setblock $x+0 $y+2 $z+8 angelica:test_tesr_model 9 replace
setblock $x+1 $y+2 $z+8 angelica:test_tesr_provider 8 replace
setblock $x-2 $y+2 $z+10 angelica:test_tesr_model 8 replace
setblock $x-1 $y+2 $z+10 angelica:test_tesr_model 9 replace
setblock $x+0 $y+2 $z+10 angelica:test_tesr_provider 8 replace
setblock $x+1 $y+2 $z+10 angelica:test_tesr_provider 9 replace
# one tile entity submitting translucent A, additive B, translucent A; a depth-equal decal
setblock $x-7 $y $z+8 angelica:test_tesr_model 2 replace
setblock $x-7 $y+1 $z+8 angelica:test_tesr_decal 0 replace
# light blue glass wall: glow and provider panes in front, a provider pane behind. The panes behind the wall and
# under the water show only when block entities draw before translucent terrain.
setblock $x+5 $y-1 $z+14 stained_glass 3 replace
setblock $x+5 $y $z+14 stained_glass 3 replace
setblock $x+5 $y+1 $z+14 stained_glass 3 replace
setblock $x+6 $y-1 $z+14 stained_glass 3 replace
setblock $x+6 $y $z+14 stained_glass 3 replace
setblock $x+6 $y+1 $z+14 stained_glass 3 replace
setblock $x+7 $y-1 $z+14 stained_glass 3 replace
setblock $x+7 $y $z+14 stained_glass 3 replace
setblock $x+7 $y+1 $z+14 stained_glass 3 replace
setblock $x+8 $y-1 $z+14 stained_glass 3 replace
setblock $x+8 $y $z+14 stained_glass 3 replace
setblock $x+8 $y+1 $z+14 stained_glass 3 replace
setblock $x+9 $y-1 $z+14 stained_glass 3 replace
setblock $x+9 $y $z+14 stained_glass 3 replace
setblock $x+9 $y+1 $z+14 stained_glass 3 replace
setblock $x+6 $y $z+13 angelica:test_tesr_glow 0 replace
setblock $x+8 $y $z+13 angelica:test_tesr_provider 0 replace
setblock $x+7 $y $z+15 angelica:test_tesr_provider 0 replace
# water pool with a provider pane under the surface
setblock $x-10 $y-4 $z+12 water 0 replace
setblock $x-10 $y-3 $z+12 water 0 replace
setblock $x-10 $y-4 $z+13 water 0 replace
setblock $x-10 $y-3 $z+13 water 0 replace
setblock $x-10 $y-4 $z+14 water 0 replace
setblock $x-10 $y-3 $z+14 water 0 replace
setblock $x-9 $y-4 $z+12 water 0 replace
setblock $x-9 $y-3 $z+12 water 0 replace
setblock $x-9 $y-4 $z+13 water 0 replace
setblock $x-9 $y-3 $z+13 water 0 replace
setblock $x-9 $y-4 $z+14 water 0 replace
setblock $x-9 $y-3 $z+14 water 0 replace
setblock $x-8 $y-4 $z+12 water 0 replace
setblock $x-8 $y-3 $z+12 water 0 replace
setblock $x-8 $y-4 $z+13 water 0 replace
setblock $x-8 $y-3 $z+13 water 0 replace
setblock $x-8 $y-4 $z+14 water 0 replace
setblock $x-8 $y-3 $z+14 water 0 replace
setblock $x-9 $y-4 $z+13 angelica:test_tesr_provider 0 replace
# control: a lone pane with sky behind it
setblock $x+5 $y+2 $z+8 angelica:test_tesr_provider 0 replace
@@ -1,61 +0,0 @@
package com.gtnewhorizons.angelica.api.dynamiclights;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.dynamiclights.PositionalLightSource;
public final class DynamicLightsApi {
private DynamicLightsApi() {}
/** True when dynamic lights are on (the setting is on, and there's no shaderpack or shader force is on). */
public static boolean isEnabled() {
return DynamicLights.isEnabled();
}
/**
* True when lights made with this {@link PositionalLight#setLitUnderShaderpacks} setting give light right now. With
* true that's whenever dynamic lights are on, shaderpack or not.
*/
public static boolean isEnabled(boolean litUnderShaderpacks) {
return DynamicLights.isEnabled(litUnderShaderpacks);
}
/** A new light, off until it gets a luminance. */
public static PositionalLight createLight() {
return new PositionalLightSource();
}
/**
* Calls the visitor for every dynamic light within radius blocks of the point that gives light right now, entities
* included. Positional lights are passed as themselves, other lights as null. Under a shaderpack without shader
* force that's only the lights lit under shaderpacks.
*/
public static void forEachLightNear(double x, double y, double z, double radius, LightVisitor visitor) {
if (!DynamicLights.isActive()) return;
DynamicLights.get().forEachSourceNear(x, y, z, radius, source -> visitor.visit(
source instanceof PositionalLight light ? light : null,
source.angelica$getDynamicLightX(),
source.angelica$getDynamicLightY(),
source.angelica$getDynamicLightZ(),
source.angelica$getLuminance()));
}
/** How bright a held torch reach dynamic light of this luminance is at this distance, 0 past 7.75 blocks. */
public static double lightLevelAt(int luminance, double distance) {
return DynamicLights.falloff(luminance, distance);
}
/**
* How bright a dynamic light of this luminance and reach (see {@link PositionalLight#setReach}) is at this distance.
* Other lights from {@link #forEachLightNear} come with null and light like {@link PositionalLight#TORCH_REACH}.
*/
public static double lightLevelAt(int luminance, float reach, double distance) {
return DynamicLights.falloff(luminance, reach, distance);
}
@FunctionalInterface
public interface LightVisitor {
void visit(PositionalLight light, double x, double y, double z, int luminance);
}
}
@@ -1,54 +0,0 @@
package com.gtnewhorizons.angelica.api.dynamiclights;
/**
* A dynamic light at a position, for moving things that aren't entities. Make one with
* {@link DynamicLightsApi#createLight}. Lights terrain and entities like a held torch, so only while dynamic lights are
* on (see {@link #setLitUnderShaderpacks} for shaderpacks). Main thread only.
*/
public interface PositionalLight {
/** Moves the light. Cheap enough to call every frame, chunks only rebuild once it's moved a bit. */
void setPosition(double x, double y, double z);
/** Brightness 0-15. 0 switches it off. */
void setLuminance(int luminance);
double getX();
double getY();
double getZ();
int getLuminance();
/**
* Under a shaderpack dynamic lights only show with the player's shader force option, since packs do their own
* held item and entity light. A light that stands in for real blocks (a rendered structure's lamps) has nothing
* else to light the world round it, so set this and it lights things under a pack too, like it does without one.
* Dynamic lights turned off still means off. False by default.
*/
void setLitUnderShaderpacks(boolean lit);
boolean isLitUnderShaderpacks();
/** {@link #setReach} for Angelica's held torch falloff, the default. */
float TORCH_REACH = -1;
/**
* How far it lights at full brightness, 0-15, like block light: a luminance 15 light falls 15 / reach levels a
* block, so 15 lights exactly like a real block of that luminance and smaller reaches fade out sooner. Dimmer lights
* get as far as their luminance allows. {@link #TORCH_REACH} (the default) lights like a held torch instead,
* straight down to nothing at 7.75 blocks whatever the luminance. Fractions are fine, e.g. for a lamp in something
* drawn at an eighth of its size. Like a move under 0.1 blocks, a change under 0.1 doesn't rebuild the terrain it
* lights.
* <p>
* Further costs more: a moving light rebuilds every chunk section its light gets into, up to 27 at reach 15 against
* 8 or so for a torch, and never more than 8 at reach 7 or less.
*/
void setReach(float reach);
float getReach();
/** Switches it off for good and drops it from Angelica's lights. */
void remove();
}
@@ -1,4 +0,0 @@
@API(owner = "angelica", provides = "angelica|dynamiclights", apiVersion = "1")
package com.gtnewhorizons.angelica.api.dynamiclights;
import cpw.mods.fml.common.API;
@@ -1,72 +0,0 @@
package com.gtnewhorizons.angelica.api.particles;
import net.coderbot.iris.layer.GbufferPrograms;
import net.minecraft.client.particle.EntityFX;
import java.util.Arrays;
/** For mods that draw particles themselves or change their size. */
public final class ParticleRendering {
private ParticleRendering() {}
/** A size factor per particle, 1 for a normal one. */
@FunctionalInterface
public interface RenderScale {
float of(EntityFX fx);
}
private static final RenderScale[] NO_SCALES = new RenderScale[0];
// Swapped for a new array on every change, so the per particle read is one field and a length check
private static volatile RenderScale[] renderScales = NO_SCALES;
/**
* Scales the particles Angelica batches straight from their fields without calling {@code renderParticle}, which
* is the ones that don't override it plus the vanilla and BoP ones it knows. Particles that do go through
* {@code renderParticle} keep whatever size that gives, so scale those there. Every source added gets asked about
* every batched particle and the factors multiply, so return 1 for particles that aren't yours.
*/
public static synchronized void addRenderScale(RenderScale source) {
for (RenderScale existing : renderScales) {
if (existing == source) return;
}
final RenderScale[] next = Arrays.copyOf(renderScales, renderScales.length + 1);
next[next.length - 1] = source;
renderScales = next;
}
public static synchronized void removeRenderScale(RenderScale source) {
final RenderScale[] old = renderScales;
for (int i = 0; i < old.length; i++) {
if (old[i] != source) continue;
final RenderScale[] next = new RenderScale[old.length - 1];
System.arraycopy(old, 0, next, 0, i);
System.arraycopy(old, i + 1, next, i, old.length - i - 1);
renderScales = next.length == 0 ? NO_SCALES : next;
return;
}
}
/** The size factor for this particle from every {@link #addRenderScale} source, 1 without any. */
public static float renderScale(EntityFX fx) {
final RenderScale[] sources = renderScales;
if (sources.length == 0) return 1;
float scale = 1;
for (RenderScale source : sources) scale *= source.of(fx);
return scale;
}
/**
* Particles drawn outside the effect renderer (e.g. a mod's own list) get the pack's particle program between this
* and {@link #endParticleDraw}, like the world's particles. Pass the returned token to the end call. Nests. Without
* a pack nothing changes.
*/
public static int beginParticleDraw() {
return GbufferPrograms.beginParticles();
}
public static void endParticleDraw(int token) {
GbufferPrograms.endParticles(token);
}
}
@@ -1,4 +0,0 @@
@API(owner = "angelica", provides = "angelica|particles", apiVersion = "1")
package com.gtnewhorizons.angelica.api.particles;
import cpw.mods.fml.common.API;
@@ -1,20 +0,0 @@
package com.gtnewhorizons.angelica.api.shadows;
/**
* Draws extra geometry into the shaderpack shadow map, for things that should cast shadows but aren't terrain or
* entities. RenderWorldLastEvent geometry never gets there, and TESRs only do when the pack shadows block entities.
* Register with {@link ShadowCasters#register}.
*/
@FunctionalInterface
public interface ShadowCaster {
/**
* Called once per shadow pass for each stage, with the shadow modelview loaded and the block entity shadow program
* bound. Positions are relative to the camera position passed in, so translate by worldX - cameraX etc. Put back
* any GL state you change.
*
* @param stage {@link ShadowStage#SOLID} with the other solid shadows, {@link ShadowStage#TRANSLUCENT} after
* translucent terrain for things the pack should tint light through instead of blocking it
*/
void renderShadow(ShadowStage stage, double cameraX, double cameraY, double cameraZ, float partialTicks);
}
@@ -1,44 +0,0 @@
package com.gtnewhorizons.angelica.api.shadows;
import com.gtnewhorizons.angelica.AngelicaMod;
import net.coderbot.iris.pipeline.ShadowRenderer;
import java.util.concurrent.CopyOnWriteArrayList;
/** Where {@link ShadowCaster}s are registered. Main thread only. */
public final class ShadowCasters {
private static final CopyOnWriteArrayList<ShadowCaster> CASTERS = new CopyOnWriteArrayList<>();
private ShadowCasters() {}
public static void register(ShadowCaster caster) {
CASTERS.addIfAbsent(caster);
}
public static void unregister(ShadowCaster caster) {
CASTERS.remove(caster);
}
/** True while the shaderpack shadow pass is drawing, e.g. to skip work in a TESR that also feeds a caster. */
public static boolean isRenderingShadows() {
return ShadowRenderer.ACTIVE;
}
public static boolean hasCasters() {
return !CASTERS.isEmpty();
}
/** Internal, called by the shadow renderer with its state set up. A caster that throws is dropped. */
public static void renderAll(ShadowStage stage, double cameraX, double cameraY, double cameraZ,
float partialTicks) {
for (ShadowCaster caster : CASTERS) {
try {
caster.renderShadow(stage, cameraX, cameraY, cameraZ, partialTicks);
} catch (Throwable t) {
AngelicaMod.LOGGER.error("Shadow caster {} threw, removing it", caster, t);
CASTERS.remove(caster);
}
}
}
}
@@ -1,8 +0,0 @@
package com.gtnewhorizons.angelica.api.shadows;
public enum ShadowStage {
/** After the shadow pass's entities and tile entities, before translucent depth is split off. */
SOLID,
/** After translucent terrain. Only runs when the pack draws translucent shadows. */
TRANSLUCENT
}
@@ -1,4 +0,0 @@
@API(owner = "angelica", provides = "angelica|shadows", apiVersion = "1")
package com.gtnewhorizons.angelica.api.shadows;
import cpw.mods.fml.common.API;
@@ -1,108 +0,0 @@
package com.gtnewhorizons.angelica.api.terrain;
import com.gtnewhorizons.angelica.rendering.celeritas.VertexArrayQuadView;
import com.gtnewhorizons.angelica.rendering.celeritas.light.LightDataCache;
import com.gtnewhorizons.angelica.rendering.celeritas.light.VanillaDiffuseProvider;
import net.minecraft.client.Minecraft;
import net.minecraft.world.IBlockAccess;
import org.embeddedt.embeddium.impl.model.light.LightPipeline;
import org.embeddedt.embeddium.impl.model.light.data.LightDataAccess;
import org.embeddedt.embeddium.impl.model.light.data.QuadLightData;
import org.embeddedt.embeddium.impl.model.light.flat.FlatLightPipeline;
import org.embeddedt.embeddium.impl.model.light.smooth.SmoothLightPipeline;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFlags;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
import org.embeddedt.embeddium.impl.util.QuadUtil;
/**
* Per-vertex AO and lightmap for block quads, worked out like the chunk mesher lights terrain (same light pipeline and
* light data) but over any block access. For mods baking block geometry outside the chunk renderer.
* <p>
* Not thread safe, use one per thread. Light data is cached per 16 block region, so quads from the same region in a
* row are cheapest. The cache doesn't notice world changes, call {@link #reset} before each bake.
*/
public final class TerrainLighter {
private final LightDataCache cache = new LightDataCache();
private final SmoothLightPipeline smooth;
private final FlatLightPipeline flat;
private final ChunkVertexEncoder.Vertex[] vertices = ChunkVertexEncoder.Vertex.uninitializedQuad();
private final VertexArrayQuadView quad = new VertexArrayQuadView(vertices);
private final QuadLightData out = new QuadLightData();
private int regionX = Integer.MIN_VALUE, regionY, regionZ;
// The last fluid quad, to spot the back face vanilla draws straight after it
private ModelQuadFacing fluidLightFace;
private final float[] fluidXyz = new float[12];
private static final int[] REVERSED = { 0, 3, 2, 1 };
public TerrainLighter(IBlockAccess world) {
cache.setWorld(world);
smooth = new SmoothLightPipeline(cache, VanillaDiffuseProvider.INSTANCE, true);
flat = new FlatLightPipeline(cache, VanillaDiffuseProvider.INSTANCE, true);
}
/** Drops the cached light data so the next quad reads the world again. Call it before each bake. */
public void reset() {
regionX = Integer.MIN_VALUE;
fluidLightFace = null;
}
/**
* Lights one quad of the block at x, y, z.
*
* @param xyz the four corners as x y z, in the block access's coordinates and the quad's vertex order
* @param shade also multiply in the face's directional shading, like terrain unless the pack turns it off.
* False gives AO alone
* @param fluid the block is a fluid (see {@code TerrainRendering.isFluid}). Lit like the mesher lights fluids,
* where the back face vanilla draws right after each face gets its light from the same side as
* the front. Pass a block's quads in the order they were made. Only use the light for fluids,
* the mesher gives them no AO
* @param brightness out, per vertex AO (times shading if asked), 0 to 1
* @param light out, per vertex lightmap, {@code sky << 16 | block}, each 0-240
*/
public void light(float[] xyz, int x, int y, int z, boolean shade, boolean fluid, float[] brightness,
int[] light) {
final int rx = x & ~15, ry = y & ~15, rz = z & ~15;
if (rx != regionX || ry != regionY || rz != regionZ) {
regionX = rx;
regionY = ry;
regionZ = rz;
cache.reset(rx, ry, rz);
}
smooth.reset();
flat.reset();
for (int i = 0; i < 4; i++) {
vertices[i].x = xyz[i * 3];
vertices[i].y = xyz[i * 3 + 1];
vertices[i].z = xyz[i * 3 + 2];
}
final boolean flippedCopy = fluid && fluidLightFace != null && isReversedFluidQuad(xyz);
quad.setup(QuadUtil.calculateNormal(vertices), x, y, z, fluid ? ModelQuadFlags.IS_VANILLA_SHADED : 0,
flippedCopy ? fluidLightFace : null);
// Same rule as the mesher, smooth lighting on and the block doesn't give off light
final boolean smoothLighting = Minecraft.getMinecraft().gameSettings.ambientOcclusion != 0
&& LightDataAccess.unpackLU(cache.get(x, y, z)) == 0;
final LightPipeline pipeline = smoothLighting ? smooth : flat;
pipeline.calculate(quad, x, y, z, out, quad.getCullFace(), quad.getLightFace(), shade, true);
System.arraycopy(out.br, 0, brightness, 0, 4);
System.arraycopy(out.lm, 0, light, 0, 4);
if (fluid && !flippedCopy) {
fluidLightFace = quad.getLightFace();
System.arraycopy(xyz, 0, fluidXyz, 0, 12);
} else if (!fluid) {
fluidLightFace = null;
}
}
private boolean isReversedFluidQuad(float[] xyz) {
for (int i = 0; i < 4; i++) {
final int src = REVERSED[i] * 3;
if (xyz[i * 3] != fluidXyz[src] || xyz[i * 3 + 1] != fluidXyz[src + 1]
|| xyz[i * 3 + 2] != fluidXyz[src + 2]) {
return false;
}
}
return true;
}
}
@@ -1,340 +0,0 @@
package com.gtnewhorizons.angelica.api.terrain;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.api.glstate.GLState;
import com.gtnewhorizons.angelica.api.shaders.ShaderPacks;
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import com.gtnewhorizons.angelica.rendering.BlockMaterialAttribute;
import com.gtnewhorizons.angelica.rendering.StateAwareTessellator;
import com.gtnewhorizons.angelica.rendering.celeritas.BlockRenderLayer;
import com.gtnewhorizons.angelica.utils.AnimationsRenderUtils;
import com.prupe.mcpatcher.mal.block.RenderBlocksUtils;
import net.coderbot.iris.Iris;
import net.coderbot.iris.block_rendering.BlockMaterialMapping;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.gl.shader.ProgramCreator;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
import net.coderbot.iris.pipeline.WorldRenderingPhase;
import net.coderbot.iris.shadows.ShadowRenderingState;
import net.coderbot.iris.uniforms.LocalGridFrame;
import net.minecraft.block.Block;
import net.minecraft.block.BlockDoublePlant;
import net.minecraft.block.BlockDynamicLiquid;
import net.minecraft.block.BlockStaticLiquid;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.world.IBlockAccess;
import org.joml.Matrix4f;
import java.util.Map;
/**
* For mods that bake block geometry outside the chunk renderer (moving structures, in-world previews) and want it to
* look like terrain, shaderpacks included.
* <p>
* Under a shaderpack terrain gets the pack's terrain programs, its block.properties materials (mc_Entity) and the
* pack's own AO and directional shading. Draw between {@link #beginTerrainDraw} and {@link #endTerrainDraw} to get the
* terrain programs, and use the getters here to bake the way the pack wants. Without a shaderpack nothing changes.
*/
public final class TerrainRendering {
private static int terrainDrawDepth;
private static boolean terrainDrawPushed;
private static int localGridId;
private TerrainRendering() {}
/**
* Draws until {@link #endTerrainDraw} use the pack's terrain program instead of the one for the current phase
* (entities, block entities). Main thread, end it in a finally block. Nests, the outermost call picks the program.
*
* @param translucent true for render pass 1 geometry (glass, water), false for solid and cutout
*/
public static void beginTerrainDraw(boolean translucent) {
if (terrainDrawDepth++ > 0) return;
terrainDrawPushed = ShaderPacks.isInUse();
if (terrainDrawPushed) {
GbufferPrograms.pushOverridePhase(translucent ? WorldRenderingPhase.TERRAIN_TRANSLUCENT : WorldRenderingPhase.TERRAIN_CUTOUT);
}
}
public static void endTerrainDraw() {
if (terrainDrawDepth == 0) return;
// While the terrain program is still bound, so it gets the real uniforms back
if (terrainDrawDepth == 1) endLocalGrid();
if (--terrainDrawDepth > 0) return;
if (terrainDrawPushed) GbufferPrograms.popOverridePhase();
terrainDrawPushed = false;
}
/** Internal, start of each frame. Ends a terrain draw that never got ended (e.g. the caller threw). */
public static void resetForFrame() {
if (terrainDrawDepth == 0) return;
AngelicaMod.LOGGER.warn("A terrain draw was never ended, ending it");
LocalGridFrame.end();
if (terrainDrawPushed) GbufferPrograms.popOverridePhase();
terrainDrawPushed = false;
terrainDrawDepth = 0;
}
/**
* Call inside {@link #beginTerrainDraw}, in a try-with-resources. Until the grid is closed or the terrain draw
* ends, the pack sees the current modelview's model space as the world. For geometry drawn rotated or off the block
* grid: packs pick out parts of some blocks by where a pixel is inside its world block (cauldron water, end portal
* frame eyes), and off the grid that lands in the wrong spot.
* <p>
* Only the uniforms a pack works out world space from change (camera, matrices, upPosition, eyePosition and the
* like), plus the pack's own custom uniforms made from them. View space and shadows come out the same. Model space
* up counts as up. Draws in between must use the modelview it was started with.
* <p>
* Does nothing without a pack, in the shadow pass, on the SDL GPU backend, if a grid is already on or if the
* modelview can't be inverted. Packs that go by at_midBlock instead get it right from the vertex data alone, see
* {@link #getMidBlockAttributeLocation}.
*
* @return the grid, {@link LocalGrid#isActive} says whether it's on
*/
public static LocalGrid beginLocalGrid() {
if (!terrainDrawPushed || LocalGridFrame.isActive() || BackendManager.RENDER_BACKEND.isSDLGPU()
|| ShadowRenderingState.areShadowsCurrentlyBeingRendered()) {
return LocalGrid.OFF;
}
final Matrix4f modelView = GLState.getModelViewMatrix(new Matrix4f());
if (!LocalGridFrame.begin(modelView)) return LocalGrid.OFF;
refreshBoundUniforms();
return new LocalGrid(++localGridId, modelView);
}
private static void endLocalGrid() {
if (!LocalGridFrame.isActive()) return;
LocalGridFrame.end();
refreshBoundUniforms();
}
// The camera and matrix uniforms are only worked out once a frame, so work them out again and push them to the
// terrain program (binding it first if it's still pending)
private static void refreshBoundUniforms() {
GLSMHooks.resolvePendingProgram();
if (Iris.getPipelineManager().getPipelineNullable() instanceof DeferredWorldRenderingPipeline drp) {
drp.refreshUniforms(LocalGridFrame.UNIFORMS);
}
}
/**
* True when the pack wants AO in the vertex color's alpha instead of multiplied into the color, so it can apply it
* itself. Put the AO from {@link TerrainLighter} in alpha when this is set.
*/
public static boolean usesSeparateAo() {
return ShaderPacks.isInUse() && BlockRenderingSettings.INSTANCE.shouldUseSeparateAo();
}
/**
* True when the chunk mesher runs its own light pipeline over terrain, the same one {@link TerrainLighter} runs. It
* only relights the faces {@link #isSmoothLit} marks (and fluids under a pack), everything else keeps the light it
* was baked with. AO goes in the color's alpha when {@link #usesSeparateAo}, multiplied into the color otherwise.
*/
public static boolean usesTerrainLighting() {
return ShaderPacks.isInUse() || BlockRenderingSettings.INSTANCE.shouldUseSeparateAo()
|| ClientProxy.options().quality.useCeleritasSmoothLighting;
}
/** True when the pack does its own directional shading, so terrain is baked without vanilla's per-face shading. */
public static boolean disablesDirectionalShading() {
return ShaderPacks.isInUse() && BlockRenderingSettings.INSTANCE.shouldDisableDirectionalShading();
}
/**
* The Forge render pass the pack moves this block to (e.g. {@code layer.translucent} in block.properties), or -1 if
* it doesn't move it or there's no pack. The chunk mesher only draws a moved block in that pass, so do the same.
*/
public static int getRenderPassOverride(Block block) {
if (!ShaderPacks.isInUse()) return -1;
final Map<Block, BlockRenderLayer> overrides = BlockRenderingSettings.INSTANCE.getBlockTypeIds();
if (overrides == null) return -1;
final BlockRenderLayer layer = overrides.get(block);
return layer == null ? -1 : layer.toVanillaPass();
}
/** The pack's block.properties id for this block, -1 if it's unmapped or there's no pack. */
public static int getBlockMaterialId(Block block, int metadata) {
return ShaderPacks.isInUse() ? BlockMaterialAttribute.blockMaterialId(block, metadata) : -1;
}
/**
* The id the chunk mesher gives this block where it stands, which isn't always the plain lookup. A fluid with no
* entry uses its still or flowing twin's, grass under snow gets the pack's snowy entry and the top half of a double
* plant is looked up as the plant its bottom half says. -1 if it's unmapped or there's no pack.
*/
public static int getBlockMaterialId(IBlockAccess world, Block block, int metadata, int x, int y, int z) {
if (!ShaderPacks.isInUse()) return -1;
if (isFluid(block)) {
int id = BlockMaterialAttribute.blockMaterialId(block, metadata);
if (id == -1) {
Block twin = null;
if (block instanceof BlockStaticLiquid) twin = Block.getBlockById(Block.getIdFromBlock(block) - 1);
else if (block instanceof BlockDynamicLiquid) twin = Block.getBlockById(Block.getIdFromBlock(block) + 1);
if (twin != null) id = BlockMaterialAttribute.blockMaterialId(twin, metadata);
}
return id;
}
int effectiveMeta = metadata;
if (BlockRenderingSettings.INSTANCE.hasSnowyEntries()
&& BlockRenderingSettings.INSTANCE.getSnowyBlocks().contains(block)
&& RenderBlocksUtils.isSnowCovered(world, x, y, z)) {
effectiveMeta |= BlockMaterialMapping.SNOWY_META_BIT;
} else if (block instanceof BlockDoublePlant doublePlant && BlockDoublePlant.func_149887_c(metadata)) {
effectiveMeta = 0x8 | (doublePlant.func_149885_e(world, x, y, z) & 7);
}
return BlockMaterialAttribute.blockMaterialId(block, effectiveMeta);
}
/**
* What the chunk mesher counts as a fluid, water or lava material. Under a pack it lights fluid quads with its
* light pipeline but leaves out the AO, pass that on to {@link TerrainLighter#light}.
*/
public static boolean isFluid(Block block) {
final Material material = block.getMaterial();
return material == Material.water || material == Material.lava;
}
/**
* While on, RenderBlocks draws into this tessellator like it does for the chunk mesher. Pass the one it draws into
* ({@code Tessellator.instance} on the main thread). Standard blocks that would take vanilla's smooth lighting path
* are drawn flat instead, with no AO or face shading, and their vertices get marked (see {@link #isSmoothLit}).
* Light those with {@link TerrainLighter} and leave the rest alone, that's all the mesher does. Only kicks in when
* the mesher would do it too: smooth lighting with Celeritas smooth lighting on, or a pack using separate AO. Turn
* it off again in a finally block.
*/
public static void setMeshing(Tessellator tessellator, boolean meshing) {
((StateAwareTessellator) tessellator).angelica$setCeleritasMeshing(meshing);
}
/**
* True while the vertices being added are from a face the chunk mesher would relight (see {@link #setMeshing}),
* vanilla's smooth lighting path or a renderer that asked for the same. Check it per vertex as they're added.
*/
public static boolean isSmoothLit(Tessellator tessellator) {
return ((StateAwareTessellator) tessellator).angelica$isAppliedAo();
}
/** True while the vertices being added are from a renderer that wants no directional shading on them. */
public static boolean hasNoDirectionalShading(Tessellator tessellator) {
return ((StateAwareTessellator) tessellator).angelica$isNoDirectionalShading();
}
/**
* Vertex attribute location the pack's programs read mc_Entity from. Bake two shorts per vertex here, the material
* id and 0 (1 for fluids, like the mesher). Only bind it while a shaderpack is in use.
*/
public static int getMaterialAttributeLocation() {
return ProgramCreator.MC_ENTITY;
}
/**
* Vertex attribute location the pack's programs read mc_midTexCoord from, the middle of the vertex's sprite. Packs
* use it for sprite bounds (e.g. POM). Two floats per vertex. Only bind it while a shaderpack is in use, and
* between {@link #beginOwnExtendedAttributes} and {@link #endOwnExtendedAttributes}.
*/
public static int getMidTexCoordAttributeLocation() {
return ProgramCreator.MC_MID_TEX_COORD;
}
/**
* Vertex attribute location the pack's programs read at_tangent from. Four floats per vertex, xyz plus w for the
* handedness. Same rules as {@link #getMidTexCoordAttributeLocation}.
*/
public static int getTangentAttributeLocation() {
return ProgramCreator.AT_TANGENT;
}
/**
* Vertex attribute location the pack's programs read at_midBlock from. Four bytes per vertex, not normalized: the
* offset from the vertex to the middle of its block times 64, then the block's light emission (0-15). Bake the
* offset in model space and packs that use it get blocks right even off the grid, no {@link #beginLocalGrid}
* needed. Only bind it while a shaderpack is in use.
*/
public static int getMidBlockAttributeLocation() {
return ProgramCreator.AT_MIDBLOCK;
}
/**
* Angelica fills in mc_midTexCoord and at_tangent itself for client array draws out of a VBO, guessing from the
* buffer layout, and binds that over whatever the draw set. Draws until {@link #endOwnExtendedAttributes} bring
* their own and are left alone. Nests, main thread.
*/
public static void beginOwnExtendedAttributes() {
FfpExtendedAttribs.beginInternalDraw();
}
public static void endOwnExtendedAttributes() {
FfpExtendedAttribs.endInternalDraw();
}
/**
* Angelica only animates sprites it saw drawn this frame, and geometry baked once and drawn from a buffer never
* goes through the tessellator again. This records the sprites used on this thread until it's closed.
* Call {@link SpriteCapture#markUsed} each frame the baked geometry is drawn. Close it on the same thread, in a
* finally block.
*/
public static SpriteCapture captureSprites() {
return new SpriteCapture(AnimationsRenderUtils.captureSprites());
}
/** See {@link #beginLocalGrid}. */
public static final class LocalGrid implements AutoCloseable {
private static final LocalGrid OFF = new LocalGrid(0, null);
private static boolean warnedModelView;
private final int id;
private final Matrix4f modelView;
private LocalGrid(int id, Matrix4f modelView) {
this.id = id;
this.modelView = modelView;
}
public boolean isActive() {
return id != 0 && id == localGridId && LocalGridFrame.isActive();
}
/** Ends it. Does nothing if it never started or the terrain draw already ended it. */
@Override
public void close() {
if (!isActive()) return;
// The one rule callers can break without noticing. Only catches a modelview left changed, not one changed
// and put back, but that's cheap enough to always check
if (!warnedModelView && !GLState.getModelViewMatrix(new Matrix4f()).equals(modelView, 1e-4f)) {
warnedModelView = true;
AngelicaMod.LOGGER.warn("Modelview changed during a local grid, draws in it have to use the one it "
+ "started with", new Throwable());
}
endLocalGrid();
}
}
/** See {@link #captureSprites}. */
public static final class SpriteCapture implements AutoCloseable {
private final AnimationsRenderUtils.SpriteCapture capture;
private SpriteCapture(AnimationsRenderUtils.SpriteCapture capture) {
this.capture = capture;
}
/** Marks the recorded sprites as drawn this frame so they keep animating. */
public void markUsed() {
capture.markUsed();
}
/** Stops recording. The sprites recorded so far stay. */
@Override
public void close() {
capture.close();
}
}
}
@@ -1,4 +0,0 @@
@API(owner = "angelica", provides = "angelica|terrain", apiVersion = "1")
package com.gtnewhorizons.angelica.api.terrain;
import cpw.mods.fml.common.API;
@@ -1,21 +0,0 @@
package com.gtnewhorizons.angelica.api.weather;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.entity.EntityLivingBase;
public interface WeatherColumnProvider {
// False suppresses vanilla rain and snow in this dimension.
boolean rendersVanillaWeather();
// Called each instanced weather frame before columnRevision and collectColumns; returns the tick counter that drives scroll and drift.
int beginFrame(WorldClient world, EntityLivingBase view, float partialTicks);
// Must change whenever any collected column changes; columns are re-collected only then or when the dimension or the player's block X/Z changes.
int columnRevision();
// Finite positive block distance d0 in alpha = ((1 - (d / d0)^2) * fadeScale + 0.5) * a.
float fadeRadius();
void collectColumns(WeatherColumnSink sink);
}
@@ -1,12 +0,0 @@
package com.gtnewhorizons.angelica.api.weather;
import net.minecraft.util.ResourceLocation;
public interface WeatherColumnSink {
// scrollPeriod is a power of two no greater than 1024.
void beginLayer(ResourceLocation texture, int scrollPeriod, float uDriftScale, float vDriftScale, float fadeScale);
// x and z are world block coordinates; brightness is a packed lightmap coordinate below 2^24.
void column(int x, int z, float bottom, float top, float uBase, float uDrift, float vBase, float vDrift, int brightness, int scrollOffset, float scrollScale, float r, float g, float b, float a);
}
@@ -1,4 +0,0 @@
@API(owner = "angelica", provides = "angelica|weather", apiVersion = "1")
package com.gtnewhorizons.angelica.api.weather;
import cpw.mods.fml.common.API;
@@ -1,59 +0,0 @@
package com.gtnewhorizons.angelica.api.world;
import com.gtnewhorizons.angelica.AngelicaMod;
import net.minecraftforge.client.MinecraftForgeClient;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* A spot in the world pass for mods that draw their own world geometry (moving structures, previews, effects).
* <p>
* Forge's {@code RenderWorldLastEvent} fires after Angelica has run the pack's composite and final passes, so anything
* drawn there misses the pack's lighting, fog and shadows. Drawers registered here run right after block entities,
* once per Forge render pass, with the pack's block entity program active like for a TESR. Without a pack they still
* run there.
* <p>
* The modelview is the camera's like for TESRs, so draw relative to the camera
* ({@code TileEntityRendererDispatcher.staticPlayerX/Y/Z}). Put back any GL state you change. Main thread only.
*/
public final class WorldDrawStage {
/** Draws world geometry for one Forge render pass. */
@FunctionalInterface
public interface Drawer {
/**
* @param pass Forge render pass, 0 for solid and cutout, 1 for translucent. Same as
* {@code MinecraftForgeClient.getRenderPass()}
* @param partialTicks the frame's partial ticks
*/
void draw(int pass, float partialTicks);
}
private static final CopyOnWriteArrayList<Drawer> drawers = new CopyOnWriteArrayList<>();
private WorldDrawStage() {}
public static void register(Drawer drawer) {
drawers.addIfAbsent(drawer);
}
public static void unregister(Drawer drawer) {
drawers.remove(drawer);
}
/** Internal, called by Angelica's renderer after block entities. */
public static void run(float partialTicks) {
if (drawers.isEmpty()) return;
final int pass = MinecraftForgeClient.getRenderPass();
for (Drawer drawer : drawers) {
try {
drawer.draw(pass, partialTicks);
} catch (Throwable t) {
// One broken drawer shouldn't take the frame down or spam the log every frame
drawers.remove(drawer);
AngelicaMod.LOGGER.error("World drawer {} threw, removed it", drawer, t);
}
}
}
}
@@ -1,4 +0,0 @@
@API(owner = "angelica", provides = "angelica|world", apiVersion = "1")
package com.gtnewhorizons.angelica.api.world;
import cpw.mods.fml.common.API;
@@ -0,0 +1,45 @@
package com.gtnewhorizons.angelica.common;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import java.util.function.Supplier;
public class BlockTesrTranslucentTest extends Block {
private final Supplier<TileEntity> tile;
public BlockTesrTranslucentTest(Supplier<TileEntity> tile) {
super(Material.glass);
this.tile = tile;
setHardness(0.3f);
setLightOpacity(0);
}
@Override
public boolean isOpaqueCube() {
return false;
}
@Override
public boolean renderAsNormalBlock() {
return false;
}
@Override
public int getRenderType() {
return -1;
}
@Override
public boolean hasTileEntity(int metadata) {
return true;
}
@Override
public TileEntity createTileEntity(World world, int metadata) {
return tile.get();
}
}
@@ -0,0 +1,30 @@
package com.gtnewhorizons.angelica.common;
import net.minecraft.tileentity.TileEntity;
public abstract class TileTesrTranslucentTest extends TileEntity {
private static final int SOLID_PASS = 8;
public int variant() {
return getBlockMetadata() & ~SOLID_PASS;
}
@Override
public boolean shouldRenderInPass(int pass) {
return pass == ((getBlockMetadata() & SOLID_PASS) != 0 ? 0 : 1);
}
@Override
public boolean canUpdate() {
return false;
}
public static class Provider extends TileTesrTranslucentTest {}
public static class Model extends TileTesrTranslucentTest {}
public static class Decal extends TileTesrTranslucentTest {}
public static class Glow extends TileTesrTranslucentTest {}
}
@@ -30,7 +30,6 @@ public class ModStatus {
public static boolean isBaublesLoaded;
public static boolean isCosmeticArmorReworkedLoaded;
public static boolean isFluidLoggedLoaded;
public static boolean isLiquidLoggedLoaded;
public static boolean isCubicChunksLoaded;
public static boolean isBOPLoaded;
public static boolean isEtFuturumLoaded;
@@ -52,7 +51,6 @@ public class ModStatus {
isBaublesLoaded = Loader.isModLoaded("Baubles");
isCosmeticArmorReworkedLoaded = Loader.isModLoaded("cosmeticarmorreworked");
isFluidLoggedLoaded = Loader.isModLoaded("fluidlogged");
isLiquidLoggedLoaded = Loader.isModLoaded("liquidlogged");
isCubicChunksLoaded = Loader.isModLoaded("cubicchunks");
isEtFuturumLoaded = Loader.isModLoaded("etfuturum");
@@ -14,7 +14,6 @@ import com.gtnewhorizons.angelica.rendering.FpsReducer;
import com.gtnewhorizons.angelica.rendering.FramePacer;
import com.gtnewhorizons.angelica.rendering.IsbrhTestRenderer;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer;
import com.prupe.mcpatcher.mal.biome.BiomeAPI;
import com.sun.management.OperatingSystemMXBean;
import com.sun.management.ThreadMXBean;
import cpw.mods.fml.client.FMLClientHandler;
@@ -25,7 +24,6 @@ import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.client.gui.GuiMainMenu;
import net.minecraft.client.gui.GuiSelectWorld;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.integrated.IntegratedServer;
import net.minecraft.server.MinecraftServer;
@@ -36,12 +34,8 @@ import net.minecraft.util.IChatComponent;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ScreenShotHelper;
import net.minecraft.world.MinecraftException;
import net.minecraft.world.Teleporter;
import net.minecraft.world.World;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldServer;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.biome.WorldChunkManager;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.storage.ThreadedFileIOBase;
@@ -72,8 +66,6 @@ public final class FlybyRunner {
private enum State { IDLE, WAITING, PREPARING, WARMUP, RUNNING, SETTLE, EXITING, MENU, DONE }
private static final int BIOME_WINDOW = 11;
private static final int BIOME_SEARCH_CELLS = 512;
private static final int EXIT_TICKS = 20;
private static final int SETTLE_TICKS = 40;
private static final int MENU_SETTLE_TICKS = 20;
@@ -101,16 +93,6 @@ public final class FlybyRunner {
private final AtomicReference<String> pendingDimensionPlayer = new AtomicReference<>();
private boolean dimensionRequested;
private volatile boolean dimensionAbandoned;
private final AtomicReference<String> pendingBiomePlayer = new AtomicReference<>();
private boolean biomeRequested;
private volatile boolean biomeAbandoned;
private volatile FlybyOrigin biomeOrigin;
private BiomeGenBase[] biomeScratch;
private volatile boolean survivalRestoreRequested;
private boolean survivalApplied;
private String survivalPlayerName;
private String survivalWorld;
private WorldSettings.GameType survivalRestoreType;
private FlybyRequest activeRequest;
private String[] sceneCommands = NO_COMMANDS;
private volatile boolean sceneClearRequested;
@@ -247,10 +229,6 @@ public final class FlybyRunner {
this.exitWhenDone = false;
this.dimensionRequested = false;
this.dimensionAbandoned = false;
this.biomeRequested = false;
this.biomeAbandoned = false;
this.biomeOrigin = null;
if (SystemProperties.FLYBY_SURVIVAL) this.survivalRestoreRequested = true;
this.jfr = false;
this.armed = false;
this.fixedOrigin = null;
@@ -327,7 +305,6 @@ public final class FlybyRunner {
return;
}
if (this.awaitingDimension(mc, player)) return;
if (this.awaitingBiome(mc, player)) return;
this.begin(mc, player);
}
case PREPARING -> {
@@ -413,26 +390,6 @@ public final class FlybyRunner {
return true;
}
private boolean awaitingBiome(Minecraft mc, EntityClientPlayerMP player) {
final String biome = SystemProperties.FLYBY_BIOME;
if (!this.startedFromProperties || biome.isEmpty() || this.biomeAbandoned) return false;
final FlybyOrigin found = this.biomeOrigin;
if (found != null) {
this.fixedOrigin = this.fixedOrigin == null ? found : new FlybyOrigin(found.x(), found.z(), this.fixedOrigin.yaw());
return false;
}
if (mc.getIntegratedServer() == null) {
LOGGER.warn("Flyby: not singleplayer, ignoring biome '{}'", biome);
this.biomeAbandoned = true;
return false;
}
if (!this.biomeRequested) {
this.biomeRequested = true;
this.pendingBiomePlayer.set(player.getCommandSenderName());
}
return true;
}
private void overridePauseOnLostFocus(Minecraft mc) {
if (this.pauseOnLostFocusOverridden) return;
this.pauseOnLostFocusSaved = mc.gameSettings.pauseOnLostFocus;
@@ -700,7 +657,7 @@ public final class FlybyRunner {
public void onServerTick(TickEvent.ServerTickEvent event) {
if (event.phase != TickEvent.Phase.END) return;
final boolean clear = this.sceneClearRequested;
if (!clear && this.pendingRequest.get() == null && this.pendingDimensionPlayer.get() == null && this.pendingBiomePlayer.get() == null && !this.survivalRestoreRequested && this.sceneDeferred.isEmpty()) return;
if (!clear && this.pendingRequest.get() == null && this.pendingDimensionPlayer.get() == null && this.sceneDeferred.isEmpty()) return;
final MinecraftServer server = MinecraftServer.getServer();
if (server == null) return;
@@ -713,23 +670,10 @@ public final class FlybyRunner {
LOGGER.warn("Flyby: no server player named '{}', staying in the current dimension", traveller);
this.dimensionAbandoned = true;
} else {
final int dimension = SystemProperties.FLYBY_DIMENSION;
final WorldServer target = server.worldServerForDimension(dimension);
server.getConfigurationManager().transferPlayerToDimension(player, dimension,
target.provider.hasNoSky ? target.getDefaultTeleporter() : new SurfaceTeleporter(target));
server.getConfigurationManager().transferPlayerToDimension(player, SystemProperties.FLYBY_DIMENSION);
}
}
final String seeker = this.pendingBiomePlayer.getAndSet(null);
if (seeker != null) {
this.findBiome(server, seeker);
}
if (this.survivalRestoreRequested) {
this.survivalRestoreRequested = false;
this.restoreGameType(server);
}
if (clear) {
this.sceneClearRequested = false;
this.clearScene(server);
@@ -744,104 +688,11 @@ public final class FlybyRunner {
final double feetY = this.flightFeetY(server, request);
request.feetY().complete(feetY);
this.applyFreeze(server);
if (SystemProperties.FLYBY_SURVIVAL) {
if (this.survivalApplied) {
LOGGER.warn("Flyby: game mode restore pending for world '{}', flying without survival", this.survivalWorld);
} else {
this.applySurvival(server, request.playerName());
}
}
if (request.scene()) {
this.runScene(server, request, feetY);
}
}
private void applySurvival(MinecraftServer server, String playerName) {
final EntityPlayerMP player = server.getConfigurationManager().func_152612_a(playerName);
if (player == null) {
LOGGER.warn("Flyby: no server player named '{}', staying in the current game mode", playerName);
return;
}
this.survivalRestoreType = player.theItemInWorldManager.getGameType();
player.setGameType(WorldSettings.GameType.SURVIVAL);
player.capabilities.allowFlying = player.capabilities.isFlying = player.capabilities.disableDamage = true;
player.sendPlayerAbilities();
this.survivalApplied = true;
this.survivalPlayerName = playerName;
this.survivalWorld = server.getFolderName();
}
private void restoreGameType(MinecraftServer server) {
if (!this.survivalApplied) return;
final EntityPlayerMP player = server.getFolderName().equals(this.survivalWorld)
? server.getConfigurationManager().func_152612_a(this.survivalPlayerName) : null;
if (player == null) {
this.survivalRestoreRequested = true;
return;
}
player.setGameType(this.survivalRestoreType);
this.survivalApplied = false;
}
private void findBiome(MinecraftServer server, String playerName) {
final String name = SystemProperties.FLYBY_BIOME;
final EntityPlayerMP player = server.getConfigurationManager().func_152612_a(playerName);
if (player == null) {
LOGGER.warn("Flyby: no server player named '{}', ignoring biome '{}'", playerName, name);
this.biomeAbandoned = true;
return;
}
final BiomeGenBase target = BiomeAPI.findBiomeByName(name);
if (target == null) {
LOGGER.error("Flyby: unknown biome '{}'", name);
this.biomeAbandoned = true;
return;
}
final FlybyOrigin found = this.scanForBiome(player.worldObj.getWorldChunkManager(), target);
this.biomeScratch = null;
if (found == null) {
LOGGER.error("Flyby: biome '{}' not found within {} blocks", name, BIOME_SEARCH_CELLS * 4);
this.biomeAbandoned = true;
return;
}
LOGGER.info("Flyby: biome '{}' found at {} {}", name, found.x(), found.z());
this.biomeOrigin = found;
}
private FlybyOrigin scanForBiome(WorldChunkManager manager, BiomeGenBase target) {
FlybyOrigin found = this.scanStrip(manager, target, 0, 0, 0, 0);
for (int r = 1; found == null && r <= BIOME_SEARCH_CELLS; r++) {
found = this.scanStrip(manager, target, -r, -r, r, -r);
if (found == null) found = this.scanStrip(manager, target, -r, r, r, r);
if (found == null) found = this.scanStrip(manager, target, -r, 1 - r, -r, r - 1);
if (found == null) found = this.scanStrip(manager, target, r, 1 - r, r, r - 1);
}
return found;
}
private FlybyOrigin scanStrip(WorldChunkManager manager, BiomeGenBase target, int minX, int minZ, int maxX, int maxZ) {
final int half = BIOME_WINDOW / 2;
final int width = maxX - minX + BIOME_WINDOW;
this.biomeScratch = manager.getBiomesForGeneration(this.biomeScratch, minX - half, minZ - half, width, maxZ - minZ + BIOME_WINDOW);
for (int cz = minZ; cz <= maxZ; cz++) {
for (int cx = minX; cx <= maxX; cx++) {
if (this.windowMatches(target, width, minX - half, minZ - half, cx, cz)) return new FlybyOrigin(cx * 4 + 2, cz * 4 + 2, 0.0F);
}
}
return null;
}
private boolean windowMatches(BiomeGenBase target, int width, int originX, int originZ, int cx, int cz) {
final int half = BIOME_WINDOW / 2;
for (int dz = -half; dz <= half; dz++) {
final int row = (cz + dz - originZ) * width - originX + cx;
for (int dx = -half; dx <= half; dx++) {
if (this.biomeScratch[row + dx] != target) return false;
}
}
return true;
}
private void discardWorldChanges(MinecraftServer server) {
if (worldChangesDiscarded) return;
@@ -1013,7 +864,6 @@ public final class FlybyRunner {
private void finish(Minecraft mc, EntityClientPlayerMP player) {
this.state = State.SETTLE;
if (SystemProperties.FLYBY_SURVIVAL) this.survivalRestoreRequested = true;
this.tick = 0;
final long elapsedNs = System.nanoTime() - this.runStartNs;
Tracy.sectionLeave(this.legSection);
@@ -1290,7 +1140,6 @@ public final class FlybyRunner {
this.sceneClearRequested = this.sceneCommands.length > 0;
this.restorePacing(mc);
}
if (SystemProperties.FLYBY_SURVIVAL) this.survivalRestoreRequested = true;
}
public boolean startedFromProperties() {
@@ -1298,20 +1147,4 @@ public final class FlybyRunner {
}
private record FlybyRequest(double[] pathX, double[] pathZ, double originX, double originZ, double parkedFeetY, String playerName, boolean sampleTerrain, boolean scene, CompletableFuture<Double> feetY) {}
private static final class SurfaceTeleporter extends Teleporter {
private final WorldServer world;
SurfaceTeleporter(WorldServer world) {
super(world);
this.world = world;
}
@Override
public void placeInPortal(Entity entity, double x, double y, double z, float yaw) {
final int top = this.world.getTopSolidOrLiquidBlock(MathHelper.floor_double(entity.posX), MathHelper.floor_double(entity.posZ));
entity.setLocationAndAngles(entity.posX, top > 0 ? top : entity.posY, entity.posZ, entity.rotationYaw, entity.rotationPitch);
entity.motionX = entity.motionY = entity.motionZ = 0.0;
}
}
}
@@ -22,7 +22,7 @@ public final class AngelicaEntries {
}
public static void dynamicLights(DebugScreenDisplayer displayer, DebugContext context) {
if (!DynamicLights.configEnabled || !DynamicLights.isActive()) return;
if (!DynamicLights.configEnabled || !DynamicLights.isEnabled()) return;
final DynamicLights lights = DynamicLights.get();
final DebugFact fact = displayer.fact(DebugGroup.ANGELICA, "Dynamic Lights");
fact.value(lights.getLightSourcesCount()).text(" sources, ").value(lights.getLastUpdateCount()).text(" updated");
@@ -40,7 +40,6 @@ import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Consumer;
import java.util.function.Predicate;
public class DynamicLights {
@@ -54,50 +53,18 @@ public class DynamicLights {
public static final boolean configEnabled = AngelicaConfig.enableDynamicLights;
private static final double MAX_RADIUS = 7.75;
private static final double MAX_RADIUS_SQUARED = MAX_RADIUS * MAX_RADIUS;
private final Set<IDynamicLightSource> dynamicLightSources = new ObjectOpenHashSet<>();
private static final IDynamicLightSource[] NO_SOURCES = new IDynamicLightSource[0];
private IDynamicLightSource[] lightSourceArray = NO_SOURCES;
// The sources that light things under a shaderpack without shader force, see isActive
private IDynamicLightSource[] shaderpackSourceArray = NO_SOURCES;
private IDynamicLightSource[] lightSourceArray = new IDynamicLightSource[0];
private final ReentrantReadWriteLock lightSourcesLock = new ReentrantReadWriteLock();
private volatile int lightSourceCount = 0;
private volatile int shaderpackSourceCount = 0;
private final ChunkRebuildManager chunkRebuildManager = new ChunkRebuildManager();
private long lastUpdate = System.currentTimeMillis();
private int lastUpdateCount = 0;
// Which sources gave light at the last update: 0 none, 1 the ones lit under shaderpacks, 2 all of them
private int litState = -1;
/** Must be called under write lock. */
private void rebuildLightSourceArray() {
this.lightSourceArray = this.dynamicLightSources.toArray(NO_SOURCES);
int count = 0;
for (IDynamicLightSource source : this.lightSourceArray) {
if (source.angelica$isLitUnderShaderpacks()) count++;
}
final IDynamicLightSource[] shaderpackSources = new IDynamicLightSource[count];
int i = 0;
for (IDynamicLightSource source : this.lightSourceArray) {
if (source.angelica$isLitUnderShaderpacks()) shaderpackSources[i++] = source;
}
this.shaderpackSourceArray = shaderpackSources;
this.shaderpackSourceCount = count;
}
/** The sources that give light right now. Call under the read lock. */
private IDynamicLightSource[] activeSources() {
if (isEnabled()) return this.lightSourceArray;
return configEnabled && Mode.isEnabled() ? this.shaderpackSourceArray : NO_SOURCES;
}
/** A tracked source changed whether it's lit under shaderpacks. */
public void onShaderpackLitChanged(IDynamicLightSource lightSource) {
this.lightSourcesLock.writeLock().lock();
try {
if (this.dynamicLightSources.contains(lightSource)) rebuildLightSourceArray();
} finally {
this.lightSourcesLock.writeLock().unlock();
}
this.lightSourceArray = this.dynamicLightSources.toArray(new IDynamicLightSource[0]);
}
public static DynamicLights get() {
@@ -114,22 +81,6 @@ public class DynamicLights {
(ShaderForce || !IrisApi.getInstance().isShaderPackInUse());
}
/**
* True when a light that's lit under shaderpacks (or not, see {@link IDynamicLightSource#angelica$isLitUnderShaderpacks})
* gives light right now. Those only skip the shaderpack check, dynamic lights turned off still means off.
*/
public static boolean isEnabled(boolean litUnderShaderpacks) {
return isEnabled() || litUnderShaderpacks && configEnabled && Mode.isEnabled();
}
/**
* True when any light gives light right now: all of them ({@link #isEnabled()}), or only the ones lit under
* shaderpacks when a pack turned the rest off. What the light pipeline checks before it does any dynamic light work.
*/
public static boolean isActive() {
return isEnabled() || configEnabled && Mode.isEnabled() && get().shaderpackSourceCount > 0;
}
public boolean hasLightSources() {
return lightSourceCount > 0;
}
@@ -148,13 +99,7 @@ public class DynamicLights {
* @param renderer the renderer
*/
public void updateAll(@NotNull IDynamicLightWorldRenderer renderer) {
final int state = isEnabled() ? 2 : configEnabled && Mode.isEnabled() ? 1 : 0;
if (state != this.litState) {
if (this.litState != -1) relightAll(renderer);
this.litState = state;
}
if (!isActive())
if (!isEnabled())
return;
final long now = System.currentTimeMillis();
@@ -184,7 +129,7 @@ public class DynamicLights {
}
this.lightSourcesLock.readLock().lock();
for (var lightSource : activeSources()) {
for (var lightSource : this.lightSourceArray) {
// Entity type filter
if (!EntityLightConfig.isEntityTypeEnabled(lightSource)) {
continue;
@@ -206,23 +151,6 @@ public class DynamicLights {
}
}
/**
* The player switched dynamic lights, shader force or the shaderpack, so which sources give light changed. The
* sections they lit rebuild, and every source starts over on its next update. Without this a light that went dark
* stays in the terrain until something else rebuilds it, and one that sits still never comes back.
*/
private void relightAll(@NotNull IDynamicLightWorldRenderer renderer) {
this.lightSourcesLock.readLock().lock();
try {
for (IDynamicLightSource source : this.lightSourceArray) {
source.angelica$scheduleTrackedChunksRebuild(renderer);
source.angelica$resetDynamicLight();
}
} finally {
this.lightSourcesLock.readLock().unlock();
}
}
public int getLastUpdateCount() {
return this.lastUpdateCount;
}
@@ -317,7 +245,7 @@ public class DynamicLights {
}
}
this.lightSourceCount = 0;
rebuildLightSourceArray();
this.lightSourceArray = new IDynamicLightSource[0];
this.lightSourcesLock.writeLock().unlock();
}
@@ -354,7 +282,7 @@ public class DynamicLights {
public double getDynamicLightLevel(int x, int y, int z) {
double result = 0;
this.lightSourcesLock.readLock().lock();
for (var lightSource : activeSources()) {
for (var lightSource : this.lightSourceArray) {
result = maxDynamicLightLevel(x, y, z, lightSource, result);
}
this.lightSourcesLock.readLock().unlock();
@@ -368,7 +296,7 @@ public class DynamicLights {
public double getDynamicLightLevel(double x, double y, double z) {
double result = 0;
this.lightSourcesLock.readLock().lock();
for (var lightSource : activeSources()) {
for (var lightSource : this.lightSourceArray) {
result = maxDynamicLightLevelExact(x, y, z, lightSource, result);
}
this.lightSourcesLock.readLock().unlock();
@@ -389,11 +317,14 @@ public class DynamicLights {
final double dz = z - lightSource.angelica$getDynamicLightZ() + 0.5;
final double distanceSquared = dx * dx + dy * dy + dz * dz;
// Held torch reach is 7.75 because else we would have to update more chunks and that's not a good idea.
// Lights that ask for more get it (see angelica$getReach), and rebuild more chunks for it.
final double lightLevel = levelAt(lightSource, luminance, distanceSquared);
if (lightLevel > currentLightLevel) {
return lightLevel;
// 7.75 because else we would have to update more chunks and that's not a good idea.
// 15 (max range for blocks) would be too much and a bit cheaty.
if (distanceSquared <= MAX_RADIUS_SQUARED) {
final double multiplier = 1.0 - Math.sqrt(distanceSquared) / MAX_RADIUS;
final double lightLevel = multiplier * (double) luminance;
if (lightLevel > currentLightLevel) {
return lightLevel;
}
}
}
return currentLightLevel;
@@ -411,9 +342,12 @@ public class DynamicLights {
final double dz = z - lightSource.angelica$getDynamicLightZ();
final double distanceSquared = dx * dx + dy * dy + dz * dz;
final double lightLevel = levelAt(lightSource, luminance, distanceSquared);
if (lightLevel > currentLightLevel) {
return lightLevel;
if (distanceSquared <= MAX_RADIUS_SQUARED) {
final double multiplier = 1.0 - Math.sqrt(distanceSquared) / MAX_RADIUS;
final double lightLevel = multiplier * (double) luminance;
if (lightLevel > currentLightLevel) {
return lightLevel;
}
}
}
return currentLightLevel;
@@ -436,7 +370,7 @@ public class DynamicLights {
}
public static int addDynamicLight(IBlockAccess world, int x, int y, int z, int lightmap) {
if (!isActive()) return lightmap;
if (!isEnabled()) return lightmap;
final DynamicLights dl = get();
if (!dl.hasLightSources()) return lightmap;
final double dynamicLightLevel = dl.getDynamicLightLevel(x, y, z);
@@ -444,81 +378,27 @@ public class DynamicLights {
return lightmap;
}
/**
* Calls the consumer for every lit light source within radius of the point. Runs on a snapshot of the sources, so
* the consumer may add or remove lights.
*/
public void forEachSourceNear(double x, double y, double z, double radius, Consumer<IDynamicLightSource> consumer) {
final IDynamicLightSource[] sources;
this.lightSourcesLock.readLock().lock();
try {
sources = activeSources();
} finally {
this.lightSourcesLock.readLock().unlock();
}
final double radiusSq = radius * radius;
for (IDynamicLightSource source : sources) {
if (source.angelica$getLuminance() <= 0) continue;
final double dx = source.angelica$getDynamicLightX() - x;
final double dy = source.angelica$getDynamicLightY() - y;
final double dz = source.angelica$getDynamicLightZ() - z;
if (dx * dx + dy * dy + dz * dz <= radiusSq) consumer.accept(source);
}
}
/** Light level of a source of this luminance at this distance, with the held torch reach. */
public static double falloff(int luminance, double distance) {
return falloff(luminance, -1, distance);
}
/**
* Light level of a source of this luminance and reach (see {@link IDynamicLightSource#angelica$getReach}) at this
* distance.
*/
public static double falloff(int luminance, float reach, double distance) {
if (luminance <= 0 || reach == 0) return 0;
// Held torch: straight down to 0 at 7.75 blocks, whatever the luminance
if (reach < 0) return distance > MAX_RADIUS ? 0 : (1.0 - distance / MAX_RADIUS) * luminance;
// Like block light: down 15 / reach levels a block, so 15 is vanilla
return Math.max(0, luminance - distance * 15.0 / reach);
}
/** How far the source's light gets at its current luminance, 0 when it's dark. */
public static double reachOf(@NotNull IDynamicLightSource source) {
final int luminance = source.angelica$getLuminance();
if (luminance <= 0) return 0;
final float reach = source.angelica$getReach();
return reach < 0 ? MAX_RADIUS : reach * luminance / 15.0;
}
private static double levelAt(@NotNull IDynamicLightSource source, int luminance, double distanceSquared) {
final double reach = reachOf(source);
if (distanceSquared >= reach * reach) return 0;
return falloff(luminance, source.angelica$getReach(), Math.sqrt(distanceSquared));
}
public List<IDynamicLightSource> getSourcesForChunk(int chunkMinX, int chunkMinY, int chunkMinZ) {
// Chunk center
final double centerX = chunkMinX + 8.0;
final double centerY = chunkMinY + 8.0;
final double centerZ = chunkMinZ + 8.0;
// Smooth lighting reads the cells a block outside the section too, and the middle of the furthest of those is
// sqrt(3) * 8.5 ≈ 14.72 from the chunk center. Plus the source's reach (7.75 for a held torch), slightly padded
// for safety
// Max distance from chunk center to any corner is sqrt(3) * 8 ≈ 13.86
// Add MAX_RADIUS to get the search radius (13.86 + 7.75)^2 ≈ 467
final double searchRadiusSq = 470.0; // Slightly padded for safety
List<IDynamicLightSource> result = null;
this.lightSourcesLock.readLock().lock();
try {
for (var source : activeSources()) {
for (var source : this.lightSourceArray) {
final double dx = source.angelica$getDynamicLightX() - centerX;
final double dy = source.angelica$getDynamicLightY() - centerY;
final double dz = source.angelica$getDynamicLightZ() - centerZ;
final double distSq = dx * dx + dy * dy + dz * dz;
final double searchRadius = 14.8 + reachOf(source);
if (distSq <= searchRadius * searchRadius) {
if (distSq <= searchRadiusSq) {
if (result == null) {
result = new ArrayList<>();
}
@@ -536,7 +416,7 @@ public class DynamicLights {
int accum = 0;
this.lightSourcesLock.readLock().lock();
try {
for (var lightSource : activeSources()) {
for (var lightSource : this.lightSourceArray) {
accum = accumulateSourceRGB(x, y, z, lightSource, accum);
}
} finally {
@@ -566,8 +446,9 @@ public class DynamicLights {
final double dz = z - source.angelica$getDynamicLightZ();
final double distSq = dx * dx + dy * dy + dz * dz;
final double multiplier = levelAt(source, luminance, distSq) / luminance;
if (multiplier <= 0) return accum;
if (distSq > MAX_RADIUS_SQUARED) return accum;
final double multiplier = 1.0 - Math.sqrt(distSq) / MAX_RADIUS;
final int r = (int) (BlockLightProvider.unpackR(rgb) * multiplier);
final int g = (int) (BlockLightProvider.unpackG(rgb) * multiplier);
final int b = (int) (BlockLightProvider.unpackB(rgb) * multiplier);
@@ -44,24 +44,6 @@ public interface IDynamicLightSource {
return DynamicLights.isEnabled() && DynamicLights.get().containsLightSource(this);
}
/**
* Whether this gives light under a shaderpack without the player's shader force option, for lights that stand in
* for real blocks a pack has no other way to light. False for entities and held items, the pack does those.
*/
default boolean angelica$isLitUnderShaderpacks() {
return false;
}
/**
* How far a luminance 15 light of this source gets, 0-15, falling 15 / reach levels a block like block light (15
* is vanilla). -1 for Angelica's held torch falloff, straight down to 0 at 7.75 blocks. The source has to track and
* rebuild every chunk section its light gets into (plus a block, smooth lighting reads the cells next to a face),
* see {@link DynamicLights#reachOf}.
*/
default float angelica$getReach() {
return -1;
}
/**
* Sets whether the dynamic light is enabled or not.
* <p>
@@ -1,202 +0,0 @@
package com.gtnewhorizons.angelica.dynamiclights;
import com.gtnewhorizon.gtnhlib.blockpos.BlockPos;
import com.gtnewhorizon.gtnhlib.blockpos.IBlockPos;
import com.gtnewhorizons.angelica.api.dynamiclights.PositionalLight;
import it.unimi.dsi.fastutil.longs.LongIterator;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import net.minecraft.util.MathHelper;
import org.jetbrains.annotations.NotNull;
/**
* {@link PositionalLight} for mods. Tracks chunks like entity lights do (see MixinEntity), but only the sections its
* light gets into, worked out from its reach: 8 or fewer up to reach 7, mostly 8 for a held torch, up to 27 for a long
* one. Plus the ones it left.
*/
public final class PositionalLightSource implements IDynamicLightSource, PositionalLight {
private volatile double x, y, z;
private volatile int luminance;
private volatile boolean litUnderShaderpacks;
private volatile float reach = TORCH_REACH;
private boolean removed;
private int lastLuminance;
private float lastReach = TORCH_REACH;
private double prevX, prevY, prevZ;
private LongOpenHashSet tracked = new LongOpenHashSet();
private LongOpenHashSet prevTracked = new LongOpenHashSet();
@Override
public void setPosition(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
// Also adds it back after a world unload drops Angelica's lights
syncTracking();
}
@Override
public void setLuminance(int luminance) {
if (removed) return;
this.luminance = Math.max(0, Math.min(15, luminance));
syncTracking();
}
@Override
public double getX() {
return x;
}
@Override
public double getY() {
return y;
}
@Override
public double getZ() {
return z;
}
@Override
public int getLuminance() {
return luminance;
}
@Override
public void setLitUnderShaderpacks(boolean lit) {
if (litUnderShaderpacks == lit) return;
litUnderShaderpacks = lit;
DynamicLights.get().onShaderpackLitChanged(this);
// It may have just gone dark (or lit) under a pack. Redo its chunks either way, the next update puts the light
// back in where it still counts
angelica$resetDynamicLight();
final IDynamicLightWorldRenderer renderer = DynamicLights.getActiveRenderer();
if (renderer != null) angelica$scheduleTrackedChunksRebuild(renderer);
}
@Override
public void setReach(float reach) {
// Anything under 0 (or NaN) is the held torch
this.reach = reach >= 0 ? Math.min(15, reach) : TORCH_REACH;
}
@Override
public float getReach() {
return reach;
}
@Override
public float angelica$getReach() {
return reach;
}
@Override
public boolean isLitUnderShaderpacks() {
return litUnderShaderpacks;
}
@Override
public boolean angelica$isLitUnderShaderpacks() {
return litUnderShaderpacks;
}
@Override
public void remove() {
if (removed) return;
removed = true;
luminance = 0;
syncTracking();
}
// In Angelica's lights while lit and out of them otherwise, dynamic lights on or not. DynamicLights.updateTracking
// only removes while they're on, and re-adds on every call while they're off
private void syncTracking() {
final DynamicLights lights = DynamicLights.get();
final boolean lit = luminance > 0;
if (lit == lights.containsLightSource(this)) return;
angelica$resetDynamicLight();
if (lit) lights.addLightSource(this);
else lights.removeLightSource(this);
}
@Override
public double angelica$getDynamicLightX() {
return x;
}
@Override
public double angelica$getDynamicLightY() {
return y;
}
@Override
public double angelica$getDynamicLightZ() {
return z;
}
@Override
public void angelica$resetDynamicLight() {
lastLuminance = 0;
}
@Override
public int angelica$getLuminance() {
return luminance;
}
@Override
public void angelica$dynamicLightTick() {}
@Override
public boolean angelica$updateDynamicLight(@NotNull IDynamicLightWorldRenderer renderer) {
final double x = this.x, y = this.y, z = this.z;
final int luminance = this.luminance;
final float reach = this.reach;
// Small changes in reach count like small moves, a structure being scaled changes it every frame
if (Math.abs(x - prevX) <= 0.1 && Math.abs(y - prevY) <= 0.1 && Math.abs(z - prevZ) <= 0.1
&& luminance == lastLuminance && Math.abs(reach - lastReach) <= 0.1) {
return false;
}
prevX = x;
prevY = y;
prevZ = z;
lastLuminance = luminance;
lastReach = reach;
final LongOpenHashSet newTracked = prevTracked;
newTracked.clear();
// Every section the light gets into, plus a block: smooth lighting on a face reads the cells in front of it,
// which can be in the next section. Reach is at most 15, so never past the sections right next to this one
final double far = DynamicLights.reachOf(this) + 1;
if (far > 1) {
final int cx = MathHelper.floor_double(x) >> 4, cy = MathHelper.floor_double(y) >> 4,
cz = MathHelper.floor_double(z) >> 4;
final int x0 = x - (cx << 4) < far ? -1 : 0, x1 = ((cx + 1) << 4) - x < far ? 1 : 0;
final int y0 = y - (cy << 4) < far ? -1 : 0, y1 = ((cy + 1) << 4) - y < far ? 1 : 0;
final int z0 = z - (cz << 4) < far ? -1 : 0, z1 = ((cz + 1) << 4) - z < far ? 1 : 0;
for (int dx = x0; dx <= x1; dx++) {
for (int dy = y0; dy <= y1; dy++) {
for (int dz = z0; dz <= z1; dz++) track(renderer, new BlockPos(cx + dx, cy + dy, cz + dz), newTracked);
}
}
}
// Whatever's left in the old set is out of range now
angelica$scheduleTrackedChunksRebuild(renderer);
prevTracked = tracked;
tracked = newTracked;
return true;
}
private void track(IDynamicLightWorldRenderer renderer, IBlockPos chunk, LongOpenHashSet newTracked) {
DynamicLights.scheduleChunkRebuild(renderer, chunk);
DynamicLights.updateTrackedChunks(chunk, tracked, newTracked);
}
@Override
public void angelica$scheduleTrackedChunksRebuild(@NotNull IDynamicLightWorldRenderer renderer) {
final LongIterator it = tracked.iterator();
while (it.hasNext()) DynamicLights.scheduleChunkRebuildForRemoval(renderer, it.nextLong());
}
}
@@ -900,18 +900,6 @@ public enum Mixins implements IMixins {
"MixinBlockTFMagicLeaves"
))
),
NOTFINE_BIOMES_O_PLENTY_COMPAT(new MixinBuilder()
.setPhase(Phase.LATE)
.setApplyIf(() -> AngelicaConfig.enableNotFineFeatures)
.addRequiredMod(TargetedMod.BIOMES_O_PLENTY)
.addClientMixins(addPrefix("notfine.leaves.biomesoplenty.",
"MixinBlockBOPLeaves",
"MixinBlockBOPColorizedLeaves",
"MixinBlockBOPAppleLeaves",
"MixinBlockBOPPersimmonLeaves",
"MixinColorizedLeavesRenderer"
))
),
ET_FUTURUM_ELYTRA_CAPE(new MixinBuilder("Set custom item ID for elytra with cape texture")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.ET_FUTURUM_REQUIEM)
@@ -304,7 +304,7 @@ public final class TracyFramePlots {
Tracy.plotInt(P_QUEUE_TASKS_RAN, AngelicaRenderQueue.getLastFrameTasksRan());
Tracy.plotInt(P_QUEUE_TIME_NS, AngelicaRenderQueue.getLastFrameTimeNs());
if (DynamicLights.isActive()) {
if (DynamicLights.isEnabled()) {
final DynamicLights dl = DynamicLights.get();
Tracy.plotInt(P_DYN_LIGHT_SOURCES, dl.getLightSourcesCount());
Tracy.plotInt(P_DYN_UPDATES, dl.getLastUpdateCount());
@@ -40,6 +40,7 @@ import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.common.BlockError;
import com.gtnewhorizons.angelica.common.BlockIsbrhTest;
import com.gtnewhorizons.angelica.common.TileEntityClipPlaneTest;
import com.gtnewhorizons.angelica.common.TileTesrTranslucentTest;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.compat.bettercrashes.BetterCrashesCompat;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
@@ -75,6 +76,7 @@ import com.gtnewhorizons.angelica.rendering.ClipPlaneTestRenderer;
import com.gtnewhorizons.angelica.rendering.FpsReducer;
import com.gtnewhorizons.angelica.rendering.FramePacer;
import com.gtnewhorizons.angelica.rendering.IsbrhTestRenderer;
import com.gtnewhorizons.angelica.rendering.TesrTranslucentTestRenderers;
import com.gtnewhorizons.angelica.rendering.TextureSamplers;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasSetup;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer;
@@ -150,6 +152,10 @@ public final class ClientProxy extends CommonProxy {
BlockIsbrhTest.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(BlockIsbrhTest.renderId, new IsbrhTestRenderer());
ClientRegistry.bindTileEntitySpecialRenderer(TileEntityClipPlaneTest.class, new ClipPlaneTestRenderer());
ClientRegistry.bindTileEntitySpecialRenderer(TileTesrTranslucentTest.Provider.class, new TesrTranslucentTestRenderers.Provider());
ClientRegistry.bindTileEntitySpecialRenderer(TileTesrTranslucentTest.Model.class, new TesrTranslucentTestRenderers.Model());
ClientRegistry.bindTileEntitySpecialRenderer(TileTesrTranslucentTest.Decal.class, new TesrTranslucentTestRenderers.Decal());
ClientRegistry.bindTileEntitySpecialRenderer(TileTesrTranslucentTest.Glow.class, new TesrTranslucentTestRenderers.Glow());
}
AngelicaJar.configureShaderDiskCache(event.getSourceFile());
if (AngelicaConfig.enableIris) {
@@ -2,13 +2,18 @@ package com.gtnewhorizons.angelica.proxy;
import com.gtnewhorizons.angelica.common.BlockClipPlaneTest;
import com.gtnewhorizons.angelica.common.BlockIsbrhTest;
import com.gtnewhorizons.angelica.common.BlockTesrTranslucentTest;
import com.gtnewhorizons.angelica.common.BlockTest;
import com.gtnewhorizons.angelica.common.TileEntityClipPlaneTest;
import com.gtnewhorizons.angelica.common.TileTesrTranslucentTest;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.tileentity.TileEntity;
import java.util.function.Supplier;
public class CommonProxy {
@@ -18,9 +23,18 @@ public class CommonProxy {
GameRegistry.registerBlock(new BlockIsbrhTest(), "test_isbrh");
GameRegistry.registerBlock(new BlockClipPlaneTest(), "test_clip_plane");
GameRegistry.registerTileEntity(TileEntityClipPlaneTest.class, "angelica:test_clip_plane");
registerTesrTest("test_tesr_provider", TileTesrTranslucentTest.Provider.class, TileTesrTranslucentTest.Provider::new);
registerTesrTest("test_tesr_model", TileTesrTranslucentTest.Model.class, TileTesrTranslucentTest.Model::new);
registerTesrTest("test_tesr_decal", TileTesrTranslucentTest.Decal.class, TileTesrTranslucentTest.Decal::new);
registerTesrTest("test_tesr_glow", TileTesrTranslucentTest.Glow.class, TileTesrTranslucentTest.Glow::new);
}
}
private static void registerTesrTest(String name, Class<? extends TileEntity> tile, Supplier<TileEntity> factory) {
GameRegistry.registerBlock(new BlockTesrTranslucentTest(factory), name);
GameRegistry.registerTileEntity(tile, "angelica:" + name);
}
public void init(FMLInitializationEvent event) {}
public void postInit(FMLPostInitializationEvent event) {}
@@ -134,12 +134,29 @@ public final class WeatherColumns {
return height[slotOf(x, z)];
}
public int hashAt(int x, int z) {
return hash[slotOf(x, z)];
}
public float temperatureAt(int x, int z, int y) {
final int slot = slotOf(x, z);
if (y <= 64) return temperatureBelow65[slot];
return temperatureAtReference[slot] - (y - TEMPERATURE_REFERENCE_Y) * TEMPERATURE_PER_BLOCK;
}
public int lightAt(WorldClient world, int x, int z, int y) {
final int slot = slotOf(x, z);
if (lightY[slot] != y) {
lightY[slot] = y;
light[slot] = world.getLightBrightnessForSkyBlocks(x, y, z, 0);
}
return light[slot];
}
public float jitterAt(int x, int z, int index) {
return jitter[slotOf(x, z) * 4 + index];
}
private int slotOf(int x, int z) {
return Math.floorMod(x, size) * size + Math.floorMod(z, size);
}
@@ -1,7 +1,5 @@
package com.gtnewhorizons.angelica.render;
import com.gtnewhorizons.angelica.api.weather.WeatherColumnProvider;
import com.gtnewhorizons.angelica.api.weather.WeatherColumnSink;
import com.gtnewhorizons.angelica.compat.dragonapi.DragonAPICompat;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.config.SystemProperties;
@@ -29,30 +27,27 @@ import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.particle.EntityRainFX;
import net.minecraft.client.particle.EntitySmokeFX;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.biome.WorldChunkManager;
import net.minecraftforge.client.IRenderHandler;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.Random;
/**
* Replaces EntityRenderer.renderRainSnow.
*
* <p>The whole grid is one instanced draw per layer: vanilla rain, vanilla snow, and each provider layer. Everything that varies per frame
* <p>The whole grid is one instanced draw per precipitation type. Everything that varies per frame
* (billboard axis, distance falloff, texture scroll, snow drift) happens in the vertex shader, and the
* instance buffer is only rebuilt when the camera changes block or {@link WeatherColumns} actually
* resamples something. Per-column data comes from that cache rather than being recomputed every frame.
* {@link WeatherColumnProvider} columns are collected from the provider instead, and re-collected only when its revision,
* the dimension, or the player's block X/Z changes.
*/
public final class WeatherRenderer {
@@ -68,18 +63,17 @@ public final class WeatherRenderer {
private static final long P_REBUILDS = Tracy.plotHandle("weather.rebuilds");
private static final long P_PARTICLE_MICROS = Tracy.plotHandle("weather.particleMicros");
private static final long P_PARTICLES_SPAWNED = Tracy.plotHandle("weather.particlesSpawned");
private static final long P_PROVIDER_COLUMNS = Tracy.plotHandle("weather.providerColumns");
private static final long P_PROVIDER_DRAWS = Tracy.plotHandle("weather.providerDraws");
private static final long P_PROVIDER_REBUILDS = Tracy.plotHandle("weather.providerRebuilds");
private static final long P_LEGACY_HANDLER = Tracy.plotHandle("weather.legacyHandler");
private static final WeatherColumns columns = new WeatherColumns();
private static float[] axisX;
private static float[] axisZ;
private static final WeatherBatch VANILLA = new WeatherBatch();
private static final WeatherBatch PROVIDER = new WeatherBatch();
private static int instanceBuffer;
private static ByteBuffer instanceData;
private static int instanceCapacity;
private static int instanceCount;
private static int rainInstances;
private static int builtRevision = Integer.MIN_VALUE;
private static int builtX = Integer.MIN_VALUE;
@@ -90,32 +84,6 @@ public final class WeatherRenderer {
private static int builtCameraY = Integer.MIN_VALUE;
private static boolean rebuiltThisFrame;
private static int builtProviderRevision = Integer.MIN_VALUE;
private static int builtProviderDimension = Integer.MIN_VALUE;
private static int builtProviderX = Integer.MIN_VALUE;
private static int builtProviderZ = Integer.MIN_VALUE;
private static boolean providerRebuiltThisFrame;
private static int frameQuads;
private static int frameDrawCalls;
private static int providerColumns;
private static int providerDraws;
private static boolean legacyHandler;
private static int entityBlockX;
private static int entityBlockY;
private static int entityBlockZ;
private static double cameraX;
private static double cameraY;
private static double cameraZ;
private static int cameraBlockY;
private static double viewPosX;
private static double viewPosZ;
private static int updateCount;
private static int radius;
private static float rainStrength;
private static float partialTicks;
private static final int PARTICLE_RADIUS = 10;
private static final Random particleRandom = new Random();
private static int rainSoundCounter;
@@ -213,180 +181,180 @@ public final class WeatherRenderer {
}
public static boolean render(float partialTicks) {
final long startNanos = System.nanoTime();
if (!AngelicaConfig.enableInstancedWeather) return false;
frameQuads = 0;
frameDrawCalls = 0;
providerColumns = 0;
providerDraws = 0;
legacyHandler = false;
final boolean handled = renderFrame(partialTicks);
report(startNanos);
return handled;
}
private static boolean renderFrame(float partialTicks) {
final Minecraft mc = Minecraft.getMinecraft();
final WorldClient world = mc.theWorld;
final IRenderHandler handler = world.provider.getWeatherRenderer();
final WeatherColumnProvider provider;
if (handler == null) {
if (DragonAPICompat.forcingSeasonalSnow) return false;
provider = null;
} else if (handler instanceof WeatherColumnProvider columnProvider) {
provider = columnProvider;
} else {
return useLegacyHandler();
final long startNanos = System.nanoTime();
if (!AngelicaConfig.enableInstancedWeather) return false;
if (world.provider.getWeatherRenderer() != null) {
Tracy.plot(P_STRENGTH, 0.0);
report(0, 0, startNanos);
return false;
}
if (DragonAPICompat.forcingSeasonalSnow) {
report(0, 0, startNanos);
return false;
}
final float rainStrength = world.getRainStrength(partialTicks);
Tracy.plot(P_STRENGTH, rainStrength);
rainStrength = provider == null || provider.rendersVanillaWeather() ? world.getRainStrength(partialTicks) : 0.0F;
radius = SettingsManager.downfallDistance;
final boolean vanillaActive = rainStrength > 0.0F && radius > 0;
if (provider == null && !vanillaActive) {
Tracy.plot(P_STRENGTH, rainStrength);
final int radius = SettingsManager.downfallDistance;
if (rainStrength <= 0.0F || radius <= 0) {
report(0, 0, startNanos);
return true;
}
buildAxisTable();
final EntityLivingBase view = mc.renderViewEntity;
final int entityBlockX = MathHelper.floor_double(view.posX);
final int entityBlockY = MathHelper.floor_double(view.posY);
final int entityBlockZ = MathHelper.floor_double(view.posZ);
final double cameraX = view.lastTickPosX + (view.posX - view.lastTickPosX) * partialTicks;
final double cameraY = view.lastTickPosY + (view.posY - view.lastTickPosY) * partialTicks;
final double cameraZ = view.lastTickPosZ + (view.posZ - view.lastTickPosZ) * partialTicks;
final int cameraBlockY = MathHelper.floor_double(cameraY);
final int updateCount = ((EntityRendererAccessor) mc.entityRenderer).getRendererUpdateCount();
columns.update(world, entityBlockX, entityBlockZ, radius, updateCount);
final DeferredWorldRenderingPipeline deferred = deferredPipeline();
if (deferred != null && !deferred.supportsInstancing(Instancing.WEATHER)) {
renderTessellator(mc, world, view, partialTicks, rainStrength, radius, updateCount,
entityBlockX, entityBlockY, entityBlockZ, cameraX, cameraY, cameraZ, cameraBlockY, startNanos);
return true;
}
final EntityLivingBase view = mc.renderViewEntity;
WeatherRenderer.partialTicks = partialTicks;
entityBlockX = MathHelper.floor_double(view.posX);
entityBlockY = MathHelper.floor_double(view.posY);
entityBlockZ = MathHelper.floor_double(view.posZ);
cameraX = view.lastTickPosX + (view.posX - view.lastTickPosX) * partialTicks;
cameraY = view.lastTickPosY + (view.posY - view.lastTickPosY) * partialTicks;
cameraZ = view.lastTickPosZ + (view.posZ - view.lastTickPosZ) * partialTicks;
cameraBlockY = MathHelper.floor_double(cameraY);
viewPosX = view.posX;
viewPosZ = view.posZ;
updateCount = ((EntityRendererAccessor) mc.entityRenderer).getRendererUpdateCount();
final DeferredWorldRenderingPipeline deferred = deferredPipeline();
mc.entityRenderer.enableLightmap(partialTicks);
GLSMRasterizer.disableCull();
GLSMCurrentAttribs.glNormal3f(0.0F, 1.0F, 0.0F);
GLSMBlend.enableBlend();
GLSMBlend.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
GLSMDepthStencilAlpha.glAlphaFunc(GL11.GL_GREATER, 0.1F);
GLSMCurrentAttribs.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
final boolean instanced;
if (deferred == null) {
instanced = true;
} else if (deferred.supportsInstancing(Instancing.WEATHER)) {
deferred.rebindCurrentPass();
instanced = deferred.hasInstancedVariant(Instancing.WEATHER);
} else {
instanced = false;
}
if (provider != null && !instanced) {
exitState(mc, partialTicks);
return useLegacyHandler();
}
Tracy.plot(P_STRENGTH, rainStrength);
if (vanillaActive) {
buildAxisTable();
columns.update(world, entityBlockX, entityBlockZ, radius, updateCount);
if (instanced) {
final boolean rebuild = SystemProperties.WEATHER_REBUILD_ALWAYS
|| updateCount - builtUpdateCount >= REBUILD_TICKS
|| columns.revision() != builtRevision
|| entityBlockX != builtX || entityBlockY != builtY || entityBlockZ != builtZ
|| cameraBlockY != builtCameraY
|| radius != builtRadius;
if (rebuild) {
VANILLA.begin(entityBlockX, entityBlockZ, WeatherInstancedAttribs.SOURCE_VANILLA);
VANILLA.beginLayer(RAIN_TEXTURE, WeatherInstancedAttribs.RAIN_PERIOD, 0.0F, 0.0F, WeatherInstancedAttribs.RAIN_FADE);
writeColumns(world, true);
VANILLA.beginLayer(SNOW_TEXTURE, WeatherInstancedAttribs.SNOW_PERIOD, WeatherInstancedAttribs.SNOW_U_DRIFT, WeatherInstancedAttribs.SNOW_V_DRIFT, WeatherInstancedAttribs.SNOW_FADE);
writeColumns(world, false);
VANILLA.upload();
builtCameraY = cameraBlockY;
builtRevision = columns.revision();
builtX = entityBlockX;
builtY = entityBlockY;
builtZ = entityBlockZ;
builtRadius = radius;
builtUpdateCount = updateCount;
}
rebuiltThisFrame = rebuild;
} else {
renderTessellator(mc, world);
}
}
int providerTick = 0;
float providerAge = 0.0F;
float providerInvRadius = 0.0F;
if (provider != null) {
providerTick = provider.beginFrame(world, view, partialTicks);
final int revision = provider.columnRevision();
final float fadeRadius = provider.fadeRadius();
if (!Float.isFinite(fadeRadius) || fadeRadius <= 0.0F) {
throw new IllegalArgumentException("Weather fade radius must be finite and positive");
}
final int dimension = world.provider.dimensionId;
if (SystemProperties.WEATHER_REBUILD_ALWAYS
|| revision != builtProviderRevision || dimension != builtProviderDimension
|| entityBlockX != builtProviderX || entityBlockZ != builtProviderZ) {
PROVIDER.begin(entityBlockX, entityBlockZ, WeatherInstancedAttribs.SOURCE_PROVIDER);
provider.collectColumns(PROVIDER);
PROVIDER.upload();
builtProviderRevision = revision;
builtProviderDimension = dimension;
builtProviderX = entityBlockX;
builtProviderZ = entityBlockZ;
providerRebuiltThisFrame = true;
}
providerAge = providerTick + partialTicks;
providerInvRadius = 1.0F / fadeRadius;
}
if (instanced && (vanillaActive && VANILLA.count > 0 || provider != null && PROVIDER.count > 0)) {
WeatherParams.set((float) (entityBlockX - cameraX), (float) -cameraY, (float) (entityBlockZ - cameraZ),
radius > 0 ? 1.0F / radius : 0.0F,
(float) (viewPosX - entityBlockX), (float) (viewPosZ - entityBlockZ), partialTicks,
updateCount + partialTicks,
updateCount, rainStrength, providerTick, providerAge, providerInvRadius);
GLSMVertexInput.glBindVertexArray(WeatherQuadMesh.vao());
if (deferred == null) GLSMPrograms.setFfpInstancing(Instancing.WEATHER);
if (vanillaActive) {
frameDrawCalls += VANILLA.draw(mc, deferred);
frameQuads += VANILLA.count;
}
if (provider != null) {
providerDraws = PROVIDER.draw(mc, deferred);
providerColumns = PROVIDER.count;
}
if (deferred == null) GLSMPrograms.setFfpInstancing(Instancing.NONE);
GLSMVertexInput.glBindVertexArray(0);
if (deferred != null) deferred.rebindCurrentPass();
}
exitState(mc, partialTicks);
renderInstanced(mc, world, view, deferred, partialTicks, rainStrength, radius, updateCount,
entityBlockX, entityBlockY, entityBlockZ, cameraX, cameraY, cameraZ, cameraBlockY, startNanos);
return true;
}
private static boolean useLegacyHandler() {
Tracy.plot(P_STRENGTH, 0.0);
legacyHandler = true;
return false;
}
private static void exitState(Minecraft mc, float partialTicks) {
GLSMRasterizer.enableCull();
GLSMBlend.disableBlend();
GLSMDepthStencilAlpha.glAlphaFunc(GL11.GL_GREATER, 0.1F);
mc.entityRenderer.disableLightmap(partialTicks);
}
private static DeferredWorldRenderingPipeline deferredPipeline() {
if (!AngelicaConfig.enableIris || !Iris.enabled) return null;
return Iris.getPipelineManager().getPipelineNullable() instanceof DeferredWorldRenderingPipeline pipeline
? pipeline : null;
}
private static void writeColumns(WorldClient world, boolean wantRain) {
private static void renderInstanced(Minecraft mc, WorldClient world, EntityLivingBase view,
DeferredWorldRenderingPipeline deferred, float partialTicks, float rainStrength, int radius,
int updateCount, int entityBlockX, int entityBlockY, int entityBlockZ, double cameraX,
double cameraY, double cameraZ, int cameraBlockY, long startNanos) {
final boolean rebuild = SystemProperties.WEATHER_REBUILD_ALWAYS
|| updateCount - builtUpdateCount >= REBUILD_TICKS
|| columns.revision() != builtRevision
|| entityBlockX != builtX || entityBlockY != builtY || entityBlockZ != builtZ
|| cameraBlockY != builtCameraY
|| radius != builtRadius;
if (rebuild) {
rebuildInstances(world, radius, entityBlockX, entityBlockY, entityBlockZ, cameraBlockY);
builtCameraY = cameraBlockY;
builtRevision = columns.revision();
builtX = entityBlockX;
builtY = entityBlockY;
builtZ = entityBlockZ;
builtRadius = radius;
builtUpdateCount = updateCount;
}
rebuiltThisFrame = rebuild;
if (instanceCount == 0) {
report(0, 0, startNanos);
return;
}
if (deferred != null) {
deferred.rebindCurrentPass();
if (!deferred.hasInstancedVariant(Instancing.WEATHER)) {
renderTessellator(mc, world, view, partialTicks, rainStrength, radius, updateCount,
entityBlockX, entityBlockY, entityBlockZ, cameraX, cameraY, cameraZ, cameraBlockY, startNanos);
return;
}
}
WeatherParams.set((float) (entityBlockX - cameraX), (float) -cameraY, (float) (entityBlockZ - cameraZ),
1.0F / radius,
(float) (view.posX - entityBlockX), (float) (view.posZ - entityBlockZ), partialTicks,
updateCount + partialTicks,
updateCount & 31, updateCount & 511, rainStrength);
mc.entityRenderer.enableLightmap(partialTicks);
GLSMRasterizer.disableCull();
GLSMCurrentAttribs.glNormal3f(0.0F, 1.0F, 0.0F);
GLSMBlend.enableBlend();
OpenGlHelper.glBlendFunc(770, 771, 1, 0);
GLSMDepthStencilAlpha.glAlphaFunc(GL11.GL_GREATER, 0.1F);
GLSMCurrentAttribs.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
int drawCalls = 0;
drawCalls += drawRange(mc, deferred, RAIN_TEXTURE, 0, rainInstances);
drawCalls += drawRange(mc, deferred, SNOW_TEXTURE, rainInstances, instanceCount - rainInstances);
GLSMRasterizer.enableCull();
GLSMBlend.disableBlend();
GLSMDepthStencilAlpha.glAlphaFunc(GL11.GL_GREATER, 0.1F);
mc.entityRenderer.disableLightmap(partialTicks);
report(instanceCount, drawCalls, startNanos);
}
private static int drawRange(Minecraft mc, DeferredWorldRenderingPipeline deferred,
ResourceLocation texture, int first, int count) {
if (count <= 0) return 0;
mc.getTextureManager().bindTexture(texture);
if (deferred != null) {
deferred.rebindCurrentPass();
if (!deferred.hasInstancedVariant(Instancing.WEATHER)) return 0;
deferred.bindInstancedVariant(Instancing.WEATHER);
}
GLSMVertexInput.glBindVertexArray(WeatherQuadMesh.vao());
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, instanceBuffer);
WeatherInstancedAttribs.pointInstanceAttribs((long) first * WeatherInstancedAttribs.STRIDE);
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
VAOManager.setCurrentVertexFlags(WeatherQuadMesh.VERTEX_FLAGS);
if (deferred == null) GLSMPrograms.setFfpInstancing(Instancing.WEATHER);
GLSMDraws.glDrawArraysInstanced(GL11.GL_TRIANGLE_FAN, 0, WeatherQuadMesh.VERTEX_COUNT, count);
GLSMPrograms.setFfpInstancing(Instancing.NONE);
GLSMVertexInput.glBindVertexArray(0);
if (deferred != null) deferred.rebindCurrentPass();
return 1;
}
private static void rebuildInstances(WorldClient world, int radius, int entityBlockX, int entityBlockY,
int entityBlockZ, int cameraBlockY) {
final int slots = (radius * 2 + 1) * (radius * 2 + 1);
final int stride = WeatherInstancedAttribs.STRIDE;
if (instanceCapacity < slots) {
instanceCapacity = slots;
instanceData = ByteBuffer.allocateDirect(slots * stride).order(ByteOrder.nativeOrder());
if (instanceBuffer == 0) instanceBuffer = GLSMBuffers.glGenBuffers();
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, instanceBuffer);
GLSMBuffers.glBufferData(GL15.GL_ARRAY_BUFFER, (long) slots * stride, GL15.GL_DYNAMIC_DRAW);
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
WeatherQuadMesh.bindInstanceBuffer(instanceBuffer);
}
int count = writeColumns(world, radius, entityBlockX, entityBlockY, entityBlockZ, cameraBlockY, true, 0);
rainInstances = count;
count = writeColumns(world, radius, entityBlockX, entityBlockY, entityBlockZ, cameraBlockY, false, count);
instanceCount = count;
if (count == 0) return;
instanceData.position(0);
instanceData.limit(count * stride);
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, instanceBuffer);
GLSMBuffers.glBufferSubData(GL15.GL_ARRAY_BUFFER, 0L, instanceData);
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
instanceData.clear();
}
private static int writeColumns(WorldClient world, int radius, int entityBlockX, int entityBlockY,
int entityBlockZ, int cameraBlockY, boolean wantRain, int count) {
final int stride = WeatherInstancedAttribs.STRIDE;
final WorldChunkManager chunkManager = world.getWorldChunkManager();
for (int z = entityBlockZ - radius; z <= entityBlockZ + radius; z++) {
for (int x = entityBlockX - radius; x <= entityBlockX + radius; x++) {
@@ -403,48 +371,68 @@ public final class WeatherRenderer {
if (rain != wantRain) continue;
final int lightY = Math.max(precipitationHeight, cameraBlockY);
final int light = columns.lightAtSlot(world, slot, x, z, lightY);
int brightness = columns.lightAtSlot(world, slot, x, z, lightY);
if (!rain) brightness = (brightness * 3 + 15728880) / 4;
final float j0 = columns.jitterAtSlot(slot, 0);
VANILLA.put(x, z, bottom, top,
rain ? 0.0F : j0, rain ? 0.0F : columns.jitterAtSlot(slot, 1),
rain ? 0.0F : columns.jitterAtSlot(slot, 2), rain ? 0.0F : columns.jitterAtSlot(slot, 3),
rain ? light : snowBrightness(light), rain ? columns.hashAtSlot(slot) : 0,
rain ? WeatherInstancedAttribs.RAIN_SCROLL_BASE + j0 : 1.0F,
1.0F, 1.0F, 1.0F, 1.0F);
final int base = count * stride;
instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_COLUMN_SPAN, x - entityBlockX);
instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_COLUMN_SPAN + 4, z - entityBlockZ);
instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_COLUMN_SPAN + 8, bottom);
instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_COLUMN_SPAN + 12, top);
instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_JITTER, columns.jitterAtSlot(slot, 0));
instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_JITTER + 4, columns.jitterAtSlot(slot, 1));
instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_JITTER + 8, columns.jitterAtSlot(slot, 2));
instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_JITTER + 12, columns.jitterAtSlot(slot, 3));
instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_PARAMS, brightness & 0xFFFF);
instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_PARAMS + 4, brightness >> 16 & 0xFFFF);
instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_PARAMS + 8, columns.hashAtSlot(slot) & 31);
instanceData.putFloat(base + WeatherInstancedAttribs.OFFSET_PARAMS + 12, rain ? 0.0F : 1.0F);
count++;
}
}
return count;
}
private static void renderTessellator(Minecraft mc, WorldClient world) {
private static void renderTessellator(Minecraft mc, WorldClient world, EntityLivingBase view,
float partialTicks, float rainStrength, int radius, int updateCount, int entityBlockX,
int entityBlockY, int entityBlockZ, double cameraX, double cameraY, double cameraZ,
int cameraBlockY, long startNanos) {
mc.entityRenderer.enableLightmap(partialTicks);
final float age = updateCount + partialTicks;
GLSMRasterizer.disableCull();
GLSMCurrentAttribs.glNormal3f(0.0F, 1.0F, 0.0F);
GLSMBlend.enableBlend();
OpenGlHelper.glBlendFunc(770, 771, 1, 0);
GLSMDepthStencilAlpha.glAlphaFunc(GL11.GL_GREATER, 0.1F);
GLSMCurrentAttribs.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
final Tessellator tessellator = Tessellator.instance;
final WorldChunkManager chunkManager = world.getWorldChunkManager();
int bound = -1;
int quads = 0;
int drawCalls = 0;
for (int z = entityBlockZ - radius; z <= entityBlockZ + radius; z++) {
for (int x = entityBlockX - radius; x <= entityBlockX + radius; x++) {
final int slot = columns.slotAt(x, z);
if (!columns.precipitatesAtSlot(slot)) continue;
if (!columns.precipitates(x, z)) continue;
final int precipitationHeight = columns.heightAtSlot(slot);
final int precipitationHeight = columns.heightAt(x, z);
final int bottom = Math.max(entityBlockY - radius, precipitationHeight);
final int top = Math.max(entityBlockY + radius, precipitationHeight);
if (bottom == top) continue;
final int lightY = Math.max(precipitationHeight, cameraBlockY);
final int light = columns.lightAtSlot(world, slot, x, z, lightY);
final float temperature = columns.temperatureAtSlot(slot, bottom);
final boolean rain = chunkManager.getTemperatureAtHeight(temperature, precipitationHeight) >= 0.15F;
final float temperature = columns.temperatureAt(x, z, bottom);
final boolean rain = world.getWorldChunkManager()
.getTemperatureAtHeight(temperature, precipitationHeight) >= 0.15F;
final int axis = (z - entityBlockZ + 16) * 32 + x - entityBlockX + 16;
final float halfX = axisX[axis] * 0.5F;
final float halfZ = axisZ[axis] * 0.5F;
final double offsetX = (x + 0.5F) - viewPosX;
final double offsetZ = (z + 0.5F) - viewPosZ;
final double offsetX = (x + 0.5F) - view.posX;
final double offsetZ = (z + 0.5F) - view.posZ;
final float distance = MathHelper.sqrt_double(offsetX * offsetX + offsetZ * offsetZ) / radius;
if (rain) {
@@ -457,12 +445,13 @@ public final class WeatherRenderer {
mc.getTextureManager().bindTexture(RAIN_TEXTURE);
tessellator.startDrawingQuads();
}
final float scroll = ((updateCount + columns.hashAtSlot(slot) & WeatherInstancedAttribs.RAIN_PERIOD - 1) + partialTicks)
/ WeatherInstancedAttribs.RAIN_PERIOD * (WeatherInstancedAttribs.RAIN_SCROLL_BASE + columns.jitterAtSlot(slot, 0));
tessellator.setBrightness(light);
final float scroll = ((updateCount + columns.hashAt(x, z) & 31) + partialTicks) / 32.0F
* (3.0F + columns.jitterAt(x, z, 0));
tessellator.setBrightness(columns.lightAt(world, x, z, lightY));
tessellator.setColorRGBA_F(1.0F, 1.0F, 1.0F,
((1.0F - distance * distance) * WeatherInstancedAttribs.RAIN_FADE + 0.5F) * rainStrength);
emit(tessellator, x, z, bottom, top, halfX, halfZ, scroll, 0.0F, 0.0F);
((1.0F - distance * distance) * 0.5F + 0.5F) * rainStrength);
emit(tessellator, x, z, bottom, top, halfX, halfZ, scroll, 0.0F, 0.0F,
cameraX, cameraY, cameraZ);
} else {
if (bound != 1) {
if (bound == 0) {
@@ -473,14 +462,14 @@ public final class WeatherRenderer {
mc.getTextureManager().bindTexture(SNOW_TEXTURE);
tessellator.startDrawingQuads();
}
final float scroll = ((updateCount & WeatherInstancedAttribs.SNOW_PERIOD - 1) + partialTicks)
/ WeatherInstancedAttribs.SNOW_PERIOD;
final float driftU = columns.jitterAtSlot(slot, 0) + age * WeatherInstancedAttribs.SNOW_U_DRIFT * columns.jitterAtSlot(slot, 1);
final float driftV = columns.jitterAtSlot(slot, 2) + age * columns.jitterAtSlot(slot, 3) * WeatherInstancedAttribs.SNOW_V_DRIFT;
tessellator.setBrightness(snowBrightness(light));
final float scroll = ((updateCount & 511) + partialTicks) / 512.0F;
final float driftU = columns.jitterAt(x, z, 0) + age * 0.01F * columns.jitterAt(x, z, 1);
final float driftV = columns.jitterAt(x, z, 2) + age * columns.jitterAt(x, z, 3) * 0.001F;
tessellator.setBrightness((columns.lightAt(world, x, z, lightY) * 3 + 15728880) / 4);
tessellator.setColorRGBA_F(1.0F, 1.0F, 1.0F,
((1.0F - distance * distance) * WeatherInstancedAttribs.SNOW_FADE + 0.5F) * rainStrength);
emit(tessellator, x, z, bottom, top, halfX, halfZ, scroll, driftU, driftV);
((1.0F - distance * distance) * 0.3F + 0.5F) * rainStrength);
emit(tessellator, x, z, bottom, top, halfX, halfZ, scroll, driftU, driftV,
cameraX, cameraY, cameraZ);
}
quads++;
}
@@ -491,16 +480,16 @@ public final class WeatherRenderer {
drawCalls++;
}
frameQuads += quads;
frameDrawCalls += drawCalls;
}
GLSMRasterizer.enableCull();
GLSMBlend.disableBlend();
GLSMDepthStencilAlpha.glAlphaFunc(GL11.GL_GREATER, 0.1F);
mc.entityRenderer.disableLightmap(partialTicks);
private static int snowBrightness(int light) {
return (light * 3 + 15728880) / 4;
report(quads, drawCalls, startNanos);
}
private static void emit(Tessellator tessellator, int x, int z, int bottom, int top, float halfX,
float halfZ, float scroll, float driftU, float driftV) {
float halfZ, float scroll, float driftU, float driftV, double cameraX, double cameraY, double cameraZ) {
tessellator.setTranslation(-cameraX, -cameraY, -cameraZ);
tessellator.addVertexWithUV(x - halfX + 0.5D, bottom, z - halfZ + 0.5D, driftU, bottom / 4.0F + scroll + driftV);
tessellator.addVertexWithUV(x + halfX + 0.5D, bottom, z + halfZ + 0.5D, 1.0F + driftU, bottom / 4.0F + scroll + driftV);
@@ -509,17 +498,12 @@ public final class WeatherRenderer {
tessellator.setTranslation(0.0D, 0.0D, 0.0D);
}
private static void report(long startNanos) {
Tracy.plotInt(P_QUADS, frameQuads);
Tracy.plotInt(P_DRAW_CALLS, frameDrawCalls);
private static void report(int quads, int drawCalls, long startNanos) {
Tracy.plotInt(P_QUADS, quads);
Tracy.plotInt(P_DRAW_CALLS, drawCalls);
Tracy.plotInt(P_REBUILDS, rebuiltThisFrame ? 1 : 0);
Tracy.plotInt(P_PROVIDER_COLUMNS, providerColumns);
Tracy.plotInt(P_PROVIDER_DRAWS, providerDraws);
Tracy.plotInt(P_PROVIDER_REBUILDS, providerRebuiltThisFrame ? 1 : 0);
Tracy.plotInt(P_LEGACY_HANDLER, legacyHandler ? 1 : 0);
Tracy.plot(P_MICROS, (System.nanoTime() - startNanos) / 1000.0);
rebuiltThisFrame = false;
providerRebuiltThisFrame = false;
}
private static void buildAxisTable() {
@@ -538,145 +522,14 @@ public final class WeatherRenderer {
}
public static void clear() {
VANILLA.release();
PROVIDER.release();
WeatherQuadMesh.delete();
builtRevision = Integer.MIN_VALUE;
builtX = Integer.MIN_VALUE;
builtY = Integer.MIN_VALUE;
builtZ = Integer.MIN_VALUE;
builtRadius = -1;
builtUpdateCount = Integer.MIN_VALUE;
builtCameraY = Integer.MIN_VALUE;
builtProviderRevision = Integer.MIN_VALUE;
builtProviderDimension = Integer.MIN_VALUE;
builtProviderX = Integer.MIN_VALUE;
builtProviderZ = Integer.MIN_VALUE;
}
private static final class WeatherBatch implements WeatherColumnSink {
private static final int STRIDE = WeatherInstancedAttribs.STRIDE;
private static final int MIN_CAPACITY = 256;
private ByteBuffer data;
private int capacity;
private int count;
private ResourceLocation[] textures = new ResourceLocation[4];
private int[] firsts = new int[4];
private int layers;
private int originX;
private int originZ;
private float source;
private int period;
private float uDriftScale;
private float vDriftScale;
private float fadeScale;
private int buffer;
private int bufferCapacity;
void begin(int originX, int originZ, float source) {
this.originX = originX;
this.originZ = originZ;
this.source = source;
Arrays.fill(textures, 0, layers, null);
layers = 0;
count = 0;
}
void upload() {
if (count == 0) return;
if (buffer == 0) buffer = GLSMBuffers.glGenBuffers();
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, buffer);
if (bufferCapacity < count) {
bufferCapacity = capacity;
GLSMBuffers.glBufferData(GL15.GL_ARRAY_BUFFER, (long) bufferCapacity * STRIDE, GL15.GL_DYNAMIC_DRAW);
}
data.position(0);
data.limit(count * STRIDE);
GLSMBuffers.glBufferSubData(GL15.GL_ARRAY_BUFFER, 0L, data);
data.clear();
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
}
int draw(Minecraft mc, DeferredWorldRenderingPipeline deferred) {
int draws = 0;
for (int layer = 0; layer < layers; layer++) {
final int first = firsts[layer];
final int layerCount = (layer + 1 < layers ? firsts[layer + 1] : count) - first;
if (layerCount == 0) continue;
mc.getTextureManager().bindTexture(textures[layer]);
if (deferred != null) deferred.bindInstancedVariant(Instancing.WEATHER);
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, buffer);
WeatherInstancedAttribs.pointInstanceAttribs((long) first * STRIDE);
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
VAOManager.setCurrentVertexFlags(WeatherQuadMesh.VERTEX_FLAGS);
GLSMDraws.glDrawArraysInstanced(GL11.GL_TRIANGLE_FAN, 0, WeatherQuadMesh.VERTEX_COUNT, layerCount);
draws++;
}
return draws;
}
void release() {
begin(0, 0, 0.0F);
data = null;
capacity = 0;
if (buffer != 0) {
GLSMBuffers.glDeleteBuffers(buffer);
buffer = 0;
}
bufferCapacity = 0;
}
@Override
public void beginLayer(ResourceLocation texture, int scrollPeriod, float uDriftScale, float vDriftScale, float fadeScale) {
if (texture == null) throw new IllegalArgumentException("Weather layer texture must not be null");
if (scrollPeriod < 1 || scrollPeriod > WeatherParams.TICK_WRAP || (scrollPeriod & scrollPeriod - 1) != 0) {
throw new IllegalArgumentException("Weather layer scroll period must be a power of two between 1 and " + WeatherParams.TICK_WRAP);
}
if (!Float.isFinite(uDriftScale) || !Float.isFinite(vDriftScale) || !Float.isFinite(fadeScale)) {
throw new IllegalArgumentException("Weather layer scales must be finite");
}
if (layers == textures.length) {
textures = Arrays.copyOf(textures, layers * 2);
firsts = Arrays.copyOf(firsts, layers * 2);
}
textures[layers] = texture;
firsts[layers] = count;
layers++;
period = scrollPeriod;
this.uDriftScale = uDriftScale;
this.vDriftScale = vDriftScale;
this.fadeScale = fadeScale;
}
@Override
public void column(int x, int z, float bottom, float top, float uBase, float uDrift, float vBase, float vDrift,
int brightness, int scrollOffset, float scrollScale, float r, float g, float b, float a) {
if (layers == 0) throw new IllegalStateException("Weather column written before beginLayer");
if (brightness < 0 || brightness >= 1 << 24) {
throw new IllegalArgumentException("Weather column brightness must be a packed lightmap coordinate below 2^24");
}
put(x, z, bottom, top, uBase, uDrift, vBase, vDrift, brightness, scrollOffset, scrollScale, r, g, b, a);
}
void put(int x, int z, float bottom, float top, float uBase, float uDrift, float vBase, float vDrift, int brightness, int scrollOffset, float scrollScale, float r, float g, float b, float a) {
if (count == capacity) grow();
WeatherInstancedAttribs.putColumn(data, count, x - originX, z - originZ, bottom, top, uBase, uDrift, vBase, vDrift, brightness, scrollOffset, scrollScale, source, r, g, b, a, period, uDriftScale, vDriftScale, fadeScale);
count++;
}
private void grow() {
final int grownCapacity = Math.max(MIN_CAPACITY, capacity * 2);
final ByteBuffer grown = ByteBuffer.allocateDirect(grownCapacity * STRIDE).order(ByteOrder.nativeOrder());
if (count > 0) {
data.position(0);
data.limit(count * STRIDE);
grown.put(data);
grown.clear();
}
data = grown;
capacity = grownCapacity;
if (instanceBuffer != 0) {
GLSMBuffers.glDeleteBuffers(instanceBuffer);
instanceBuffer = 0;
}
instanceData = null;
instanceCapacity = 0;
instanceCount = 0;
rainInstances = 0;
}
}
@@ -15,15 +15,6 @@ public interface StateAwareTessellator {
void angelica$setAppliedAo(boolean flag);
void angelica$setNoDirectionalShading(boolean flag);
/// The state the next vertex gets. False for tessellators that don't track it.
default boolean angelica$isAppliedAo() {
return false;
}
default boolean angelica$isNoDirectionalShading() {
return false;
}
/// Sets whether we're doing terrain meshing as part of celeritas -- collects additional information.
///
/// Enables per-vertex AO state collection into [#angelica$getVertexStates()].
@@ -0,0 +1,215 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
import com.gtnewhorizons.angelica.api.tesr.TesrMeshProvider;
import com.gtnewhorizons.angelica.api.tesr.TesrMeshSink;
import com.gtnewhorizons.angelica.common.TileTesrTranslucentTest;
import com.gtnewhorizons.angelica.glsm.GLSMBlend;
import com.gtnewhorizons.angelica.glsm.GLSMCurrentAttribs;
import com.gtnewhorizons.angelica.glsm.GLSMDepthStencilAlpha;
import com.gtnewhorizons.angelica.glsm.GLSMEnable;
import com.gtnewhorizons.angelica.glsm.GLSMMatrices;
import com.gtnewhorizons.angelica.utils.WorkaroundUtils;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.tileentity.TileEntity;
import org.lwjgl.opengl.GL11;
public final class TesrTranslucentTestRenderers {
private static final double HALF = 0.4375;
private TesrTranslucentTestRenderers() {}
private static void pane(Tessellator t, double half) {
rect(t, -half, -half, half, half);
}
private static void rect(Tessellator t, double x0, double y0, double x1, double y1) {
t.setNormal(0f, 0f, -1f);
t.addVertexWithUV(0.5 + x0, 0.5 + y0, 0.5, 0, 1);
t.addVertexWithUV(0.5 + x0, 0.5 + y1, 0.5, 0, 0);
t.addVertexWithUV(0.5 + x1, 0.5 + y1, 0.5, 1, 0);
t.addVertexWithUV(0.5 + x1, 0.5 + y0, 0.5, 1, 1);
}
private static void drawPane(double half) {
final Tessellator t = Tessellator.instance;
t.startDrawingQuads();
pane(t, half);
t.draw();
}
private static void apply(TesrMaterial material) {
if (material.transparency() == TesrMaterial.Transparency.ADDITIVE) {
GLSMBlend.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE);
} else {
GLSMBlend.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
GLSMCurrentAttribs.glColor4f(material.colorRed(), material.colorGreen(), material.colorBlue(), material.colorAlpha());
}
private abstract static class PaneRenderer extends TileEntitySpecialRenderer {
void begin(double x, double y, double z) {
bindTexture(WorkaroundUtils.GL_TEXTURE_2D_WORKAROUND);
GLSMMatrices.glPushMatrix();
GLSMMatrices.glTranslated(x, y, z);
GLSMEnable.glDisable(GL11.GL_CULL_FACE);
GLSMEnable.glEnable(GL11.GL_BLEND);
}
static void end() {
GLSMCurrentAttribs.glColor4f(1f, 1f, 1f, 1f);
GLSMBlend.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLSMEnable.glDisable(GL11.GL_BLEND);
GLSMEnable.glEnable(GL11.GL_CULL_FACE);
GLSMMatrices.glPopMatrix();
}
}
public static final class Provider extends PaneRenderer implements TesrMeshProvider {
private static final TesrMaterial[] MATERIALS = {
TesrMaterial.builder().color(1f, 0f, 0f, 0.5f).translucent().noCull().build(),
TesrMaterial.builder().color(0.5f, 0f, 0.5f, 1f).additive().noCull().build() };
private static final Object[] KEYS = { new Object(), new Object() };
private static int kind(TileEntity te) {
return ((TileTesrTranslucentTest) te).variant() == 1 ? 1 : 0;
}
@Override
public Object angelica$meshKey(TileEntity te) {
return KEYS[kind(te)];
}
@Override
public void angelica$build(TesrMeshSink sink, TileEntity te) {
pane(sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, WorkaroundUtils.GL_TEXTURE_2D_WORKAROUND, MATERIALS[kind(te)]), HALF);
}
@Override
public void renderTileEntityAt(TileEntity te, double x, double y, double z, float partialTicks) {
begin(x, y, z);
apply(MATERIALS[kind(te)]);
drawPane(HALF);
end();
}
}
public static final class Model extends PaneRenderer {
private static final TesrMaterial TRANSLUCENT_GREEN = TesrMaterial.builder().color(0f, 1f, 0f, 0.5f).translucent().build();
private static final TesrMaterial TRANSLUCENT_YELLOW = TesrMaterial.builder().color(1f, 1f, 0f, 0.5f).translucent().build();
private static final TesrMaterial TRANSLUCENT_MAGENTA = TesrMaterial.builder().color(1f, 0f, 1f, 0.5f).translucent().build();
private static final TesrMaterial ADDITIVE_CYAN = TesrMaterial.builder().color(0f, 0.6f, 0.6f, 1f).additive().build();
private final ModelBase model = new ModelBase() {};
private final ModelRenderer base = new ModelRenderer(model, 0, 0);
private final ModelRenderer pane = paneAt(0f);
private final ModelRenderer paneFar = paneAt(0.16f);
private final ModelRenderer paneNear = paneAt(-0.16f);
public Model() {
base.addBox(-1f, 7f, -1f, 2, 1, 2);
}
private ModelRenderer paneAt(float z) {
final ModelRenderer renderer = new ModelRenderer(model, 0, 0);
renderer.addBox(-7f, -7f, z, 14, 14, 0);
return renderer;
}
@Override
public void renderTileEntityAt(TileEntity te, double x, double y, double z, float partialTicks) {
final float scale = 1f / 16f;
bindTexture(WorkaroundUtils.GL_TEXTURE_2D_WORKAROUND);
GLSMMatrices.glPushMatrix();
GLSMMatrices.glTranslated(x + 0.5, y + 0.5, z + 0.5);
GLSMCurrentAttribs.glColor4f(1f, 1f, 1f, 1f);
base.render(scale);
GLSMEnable.glEnable(GL11.GL_BLEND);
switch (((TileTesrTranslucentTest) te).variant()) {
case 0 -> {
apply(TRANSLUCENT_GREEN);
pane.render(scale);
}
case 1 -> {
apply(TRANSLUCENT_YELLOW);
GLSMMatrices.glTranslated(-0.5, -0.5, -0.5);
drawPane(HALF);
}
default -> {
apply(TRANSLUCENT_MAGENTA);
paneFar.render(scale);
apply(ADDITIVE_CYAN);
pane.render(scale);
apply(TRANSLUCENT_GREEN);
paneNear.render(scale);
}
}
end();
}
}
public static final class Decal extends PaneRenderer implements TesrMeshProvider {
private static final TesrMaterial WRITER = TesrMaterial.builder().color(1f, 1f, 1f, 0.5f).translucent().noCull().build();
private static final TesrMaterial DECAL = TesrMaterial.builder().color(0f, 0f, 0f, 0.8f).translucent().depthEqual().noCull().build();
private static final Object KEY = new Object();
private static final double INNER = HALF / 2;
private static void writer(Tessellator t) {
rect(t, -HALF, INNER, HALF, HALF);
rect(t, -HALF, -HALF, HALF, -INNER);
rect(t, -HALF, -INNER, -INNER, INNER);
rect(t, INNER, -INNER, HALF, INNER);
pane(t, INNER);
}
@Override
public Object angelica$meshKey(TileEntity te) {
return KEY;
}
@Override
public void angelica$build(TesrMeshSink sink, TileEntity te) {
writer(sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, WorkaroundUtils.GL_TEXTURE_2D_WORKAROUND, WRITER));
pane(sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, WorkaroundUtils.GL_TEXTURE_2D_WORKAROUND, DECAL), INNER);
}
@Override
public void renderTileEntityAt(TileEntity te, double x, double y, double z, float partialTicks) {
begin(x, y, z);
apply(WRITER);
final Tessellator t = Tessellator.instance;
t.startDrawingQuads();
writer(t);
t.draw();
GLSMDepthStencilAlpha.glDepthFunc(GL11.GL_EQUAL);
apply(DECAL);
drawPane(INNER);
GLSMDepthStencilAlpha.glDepthFunc(GL11.GL_LEQUAL);
end();
}
}
public static final class Glow extends PaneRenderer {
private static final TesrMaterial TRANSLUCENT_ORANGE = TesrMaterial.builder().color(1f, 0.5f, 0f, 0.6f).translucent().build();
@Override
public void renderTileEntityAt(TileEntity te, double x, double y, double z, float partialTicks) {
begin(x, y, z);
apply(TRANSLUCENT_ORANGE);
GLSMDepthStencilAlpha.glDepthMask(false);
drawPane(HALF);
GLSMDepthStencilAlpha.glDepthMask(true);
end();
}
}
}
@@ -112,7 +112,7 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
}
public void setupDynamicLights(int chunkOriginX, int chunkOriginY, int chunkOriginZ) {
if (DynamicLights.isActive()) {
if (DynamicLights.isEnabled()) {
this.dynamicLightsInstance = DynamicLights.get();
this.chunkLightSources = dynamicLightsInstance.getSourcesForChunk(chunkOriginX, chunkOriginY, chunkOriginZ);
} else {
@@ -14,16 +14,12 @@ import com.gtnewhorizons.angelica.rendering.celeritas.iris.ContextAwareChunkVert
import com.gtnewhorizons.angelica.rendering.celeritas.threading.RenderPassHelper;
import com.gtnewhorizons.angelica.rendering.celeritas.world.WorldSlice;
import com.gtnewhorizons.angelica.rendering.tesr.SectionBuiltBlockEntity;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.utils.NaturalTextureUtils;
import com.gtnewhorizons.liquidlogged.api.LiquidLoggedAPI;
import com.gtnewhorizons.liquidlogged.api.LiquidLoggedRenderAPI;
import com.prupe.mcpatcher.mal.block.RenderBlocksUtils;
import it.unimi.dsi.fastutil.floats.FloatArrayList;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap;
import mega.fluidlogged.api.FLBlockAccess;
import net.coderbot.iris.block_rendering.BlockMaterialMapping;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.block_rendering.NbtConditionalIdMap;
@@ -43,7 +39,6 @@ import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.ReportedException;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.fluids.Fluid;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildBuffers;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildContext;
@@ -259,13 +254,39 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
final boolean canRenderOffThread = !handoff || !isDeferred(deferredMask, x, y, z);
renderBlockPasses(block, meta, x, y, z, canRenderOffThread, blockTypeIds, deferredBlocks, tessellator, renderBlocks, buffers, buildContext, blockRenderContext, minX, minY, minZ, teMap, currentTick);
// Check for shader pack override
final BlockRenderLayer override = blockTypeIds != null ? blockTypeIds.get(block) : null;
int deferredPasses = 0;
Material deferredOverride = null;
// FluidLogged stores the fluid apart from the block, and this loop only sees the block
final Block loggedFluid = getLoggedFluidBlock(region, x, y, z);
if (loggedFluid != null) {
if (reportingSlice != null) reportingSlice.setRenderingBlock(loggedFluid);
renderBlockPasses(loggedFluid, 0, x, y, z, canRenderOffThread, blockTypeIds, deferredBlocks, tessellator, renderBlocks, buffers, buildContext, blockRenderContext, minX, minY, minZ, teMap, currentTick);
for (int pass = 0; pass < AngelicaChunkBuildContext.NUM_PASSES; pass++) {
final boolean canRender;
Material materialOverride = null;
if (override != null) {
// Shader pack override controls both pass and material
canRender = (pass == override.toVanillaPass());
if (canRender) {
materialOverride = buffers.getRenderPassConfiguration().getMaterialForRenderType(override);
}
} else {
// Normal block rendering
canRender = !canRenderOffThread || block.canRenderInPass(pass);
}
if (canRender) {
final boolean isShaderPackOverride = materialOverride != null;
if (!canRenderOffThread) {
deferredPasses |= 1 << pass;
deferredOverride = materialOverride;
continue;
}
renderBlock(block, meta, x, y, z, pass, tessellator, renderBlocks, buffers, buildContext, blockRenderContext, minX, minY, minZ, materialOverride, isShaderPackOverride, teMap, currentTick);
}
}
if (deferredPasses != 0) {
deferredBlocks.add(new DeferredBlock(x, y, z, block, meta, deferredPasses, deferredOverride));
}
if (block.isOpaqueCube()) {
@@ -324,11 +345,7 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) {
final Block block = region.getBlock(minX + x, minY + y, minZ + z);
if (block == Blocks.air) {
continue;
}
final Block loggedFluid = getLoggedFluidBlock(region, minX + x, minY + y, minZ + z);
if (!canRenderOffThread(block) || (loggedFluid != null && !canRenderOffThread(loggedFluid))) {
if (block != Blocks.air && !canRenderOffThread(block)) {
final int bit = (y << 8) | (z << 4) | x;
mask[bit >>> 6] |= 1L << bit;
any = true;
@@ -344,18 +361,6 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
return (mask[bit >>> 6] & (1L << bit)) != 0;
}
private static Block getLoggedFluidBlock(IBlockAccess region, int x, int y, int z) {
final Fluid fluid;
if (ModStatus.isLiquidLoggedLoaded) {
fluid = LiquidLoggedAPI.getFluid(region, x, y, z);
} else if (ModStatus.isFluidLoggedLoaded && region instanceof FLBlockAccess fluidAccess) {
fluid = fluidAccess.fl$getFluid(x, y, z);
} else {
return null;
}
return fluid != null ? fluid.getBlock() : null;
}
ChunkJobResult<ChunkBuildOutput> captureDeferred(DeferredSectionMesh m) {
final long start = System.nanoTime();
@@ -492,43 +497,6 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
return new ChunkBuildOutput(this.render, renderData, meshes, this.buildTime);
}
private void renderBlockPasses(Block block, int meta, int x, int y, int z, boolean canRenderOffThread, Map<Block, BlockRenderLayer> blockTypeIds, List<DeferredBlock> deferredBlocks, Tessellator tessellator, RenderBlocks renderBlocks, ChunkBuildBuffers buffers, AngelicaChunkBuildContext buildContext, BlockRenderContext blockRenderContext, int originX, int originY, int originZ, NbtConditionalIdMap<Block> teMap, long currentTick) {
// Check for shader pack override
final BlockRenderLayer override = blockTypeIds != null ? blockTypeIds.get(block) : null;
int deferredPasses = 0;
Material deferredOverride = null;
for (int pass = 0; pass < AngelicaChunkBuildContext.NUM_PASSES; pass++) {
final boolean canRender;
Material materialOverride = null;
if (override != null) {
// Shader pack override controls both pass and material
canRender = (pass == override.toVanillaPass());
if (canRender) {
materialOverride = buffers.getRenderPassConfiguration().getMaterialForRenderType(override);
}
} else {
// Normal block rendering
canRender = !canRenderOffThread || block.canRenderInPass(pass);
}
if (canRender) {
final boolean isShaderPackOverride = materialOverride != null;
if (!canRenderOffThread) {
deferredPasses |= 1 << pass;
deferredOverride = materialOverride;
continue;
}
renderBlock(block, meta, x, y, z, pass, tessellator, renderBlocks, buffers, buildContext, blockRenderContext, originX, originY, originZ, materialOverride, isShaderPackOverride, teMap, currentTick);
}
}
if (deferredPasses != 0) {
deferredBlocks.add(new DeferredBlock(x, y, z, block, meta, deferredPasses, deferredOverride));
}
}
protected void renderBlock(Block block, int metadata, int x, int y, int z, int pass, Tessellator tessellator, RenderBlocks renderBlocks, ChunkBuildBuffers buffers, AngelicaChunkBuildContext buildContext, BlockRenderContext blockRenderContext, int originX, int originY, int originZ, Material materialOverride, boolean isShaderPackOverride, NbtConditionalIdMap<Block> teMap, long currentTick) {
final Material passMaterial = resolvePassMaterial(block, pass, buffers, materialOverride);
final int teBlockId = resolveTeBlockId(teMap, renderBlocks.blockAccess, block, metadata, x, y, z, buffers, pass, materialOverride, currentTick);
@@ -619,14 +587,7 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
if (applyNaturalTex) { renderBlocks.uvRotateTop = NaturalTextureUtils.getTopRotation(x, y, z); }
tessellator.startDrawingQuads();
// A block that differs from the cell's own block is the fluid stored in it
final boolean storedFluid = ModStatus.isLiquidLoggedLoaded && renderBlocks.blockAccess.getBlock(x, y, z) != block;
if (storedFluid) LiquidLoggedRenderAPI.beginStoredFluid();
try {
renderBlocks.renderBlockByRenderType(block, x, y, z);
} finally {
if (storedFluid) LiquidLoggedRenderAPI.endStoredFluid();
}
renderBlocks.renderBlockByRenderType(block, x, y, z);
if (applyNaturalTex) { renderBlocks.uvRotateTop = 0; } // Reset
}
@@ -1,8 +1,6 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import com.gtnewhorizons.angelica.compat.bop.FogBiomeCache;
@@ -95,9 +93,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
private final ObjectArrayList<TileEntity> frameTEs = new ObjectArrayList<>();
private final ObjectArrayList<TileEntity> frameOverride = new ObjectArrayList<>();
// For sorting transparent TESRs
private final TileEntityOrderer tileEntityOrderer = new TileEntityOrderer();
private final ArrayList<TileEntity> sortedTileEntities = new ArrayList<>();
private final TileEntityDepthOrder depthOrder = new TileEntityDepthOrder();
private CeleritasWorldRenderer(Minecraft mc) {
// Private constructor for singleton
@@ -172,7 +168,6 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
DynamicLights.setActiveRenderer(null);
this.frameTEs.clear();
this.frameOverride.clear();
this.sortedTileEntities.clear();
ShadowRenderer.visibleTileEntities.clear();
ShadowRenderer.globalTileEntities.clear();
TesrLifecycle.reset();
@@ -298,7 +293,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
IrisShaderProviderHolder.shouldUseFaceCulling());
}
if (DynamicLights.isActive() && DynamicLights.FrustumCullingEnabled) {
if (DynamicLights.isEnabled() && DynamicLights.FrustumCullingEnabled) {
DynamicLights.get().processChunkRebuilds(viewport);
}
}
@@ -331,7 +326,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
super.setupShadowTerrain(playerViewport, shadowViewport, cameraState, frame, spectator);
if (DynamicLights.isActive() && DynamicLights.FrustumCullingEnabled) {
if (DynamicLights.isEnabled() && DynamicLights.FrustumCullingEnabled) {
DynamicLights.get().processChunkRebuilds(shadowViewport);
}
@@ -442,6 +437,9 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
this.teTransform = null;
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_DISPATCH);
try {
if (ClientProxy.options().performance.translucencySorting) {
depthOrder.sortBackToFront(frameTEs, teCamX, teCamY, teCamZ);
}
for (int i = 0; i < frameTEs.size(); i++) {
final TileEntity te = frameTEs.get(i);
if (!(te instanceof OverridesShouldRenderInPass)) {
@@ -461,20 +459,13 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
} else {
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_DISPATCH);
try {
sortedTileEntities.clear();
for (int i = 0; i < frameOverride.size(); i++) {
final TileEntity te = frameOverride.get(i);
if (te.shouldRenderInPass(pass)) {
sortedTileEntities.add(te);
dispatchTE(te, partialTicks);
count++;
}
}
if (sortedTileEntities.size() > 1 && ClientProxy.options().performance.translucencySorting) {
sortedTileEntities.sort(tileEntityOrderer.setLastCameraState(lastCameraState));
}
for (int i = 0; i < sortedTileEntities.size(); i++) {
dispatchTE(sortedTileEntities.get(i), partialTicks);
}
count = sortedTileEntities.size();
} finally {
if (Tracy.ENABLED) Tracy.endZone();
}
@@ -673,27 +664,4 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
return this;
}
}
private static class TileEntityOrderer implements Comparator<TileEntity> {
public CameraState lastCameraState;
public TileEntityOrderer() {
super();
}
public TileEntityOrderer setLastCameraState(CameraState lastCameraState) {
this.lastCameraState = lastCameraState;
return this;
}
@Override
public int compare(TileEntity te1, TileEntity te2) {
final double x = this.lastCameraState.x();
final double y = this.lastCameraState.y();
final double z = this.lastCameraState.z();
final double d1 = te1.getDistanceFrom(x, y, z);
final double d2 = te2.getDistanceFrom(x, y, z);
return Double.compare(d2, d1);
}
}
}
@@ -0,0 +1,79 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.minecraft.tileentity.TileEntity;
import java.util.Arrays;
final class TileEntityDepthOrder {
private static final int RADIX_BITS = 8;
private static final int BUCKETS = 1 << RADIX_BITS;
private final int[] counts = new int[BUCKETS];
private int[] keys = new int[0];
private int[] keysScratch = new int[0];
private int[] order = new int[0];
private int[] orderScratch = new int[0];
private TileEntity[] entities = new TileEntity[0];
void sortBackToFront(ObjectArrayList<TileEntity> list, double camX, double camY, double camZ) {
final int n = list.size();
if (n < 2) return;
final Object[] source = list.elements();
if (keys.length < n) {
final int capacity = source.length;
keys = new int[capacity];
keysScratch = new int[capacity];
order = new int[capacity];
orderScratch = new int[capacity];
entities = new TileEntity[capacity];
}
for (int i = 0; i < n; i++) {
final TileEntity te = (TileEntity) source[i];
final double dx = te.xCoord + 0.5 - camX;
final double dy = te.yCoord + 0.5 - camY;
final double dz = te.zCoord + 0.5 - camZ;
keys[i] = Integer.MAX_VALUE - Float.floatToRawIntBits((float) (dx * dx + dy * dy + dz * dz));
order[i] = i;
entities[i] = te;
}
final int[] sorted = sortOrder(n);
for (int i = 0; i < n; i++) {
source[i] = entities[sorted[i]];
entities[sorted[i]] = null;
}
}
private int[] sortOrder(int n) {
int[] keyIn = keys, keyOut = keysScratch;
int[] idxIn = order, idxOut = orderScratch;
for (int shift = 0; shift < Integer.SIZE; shift += RADIX_BITS) {
Arrays.fill(counts, 0);
for (int i = 0; i < n; i++) counts[(keyIn[i] >>> shift) & (BUCKETS - 1)]++;
if (counts[(keyIn[0] >>> shift) & (BUCKETS - 1)] == n) continue;
int sum = 0;
for (int b = 0; b < BUCKETS; b++) {
final int c = counts[b];
counts[b] = sum;
sum += c;
}
for (int i = 0; i < n; i++) {
final int dst = counts[(keyIn[i] >>> shift) & (BUCKETS - 1)]++;
keyOut[dst] = keyIn[i];
idxOut[dst] = idxIn[i];
}
final int[] k = keyIn;
keyIn = keyOut;
keyOut = k;
final int[] x = idxIn;
idxIn = idxOut;
idxOut = x;
}
keys = keyIn;
keysScratch = keyOut;
order = idxIn;
orderScratch = idxOut;
return idxIn;
}
}
@@ -32,7 +32,6 @@ import com.gtnewhorizons.angelica.rendering.celeritas.SmoothBiomeColorCache;
import com.gtnewhorizons.angelica.rendering.celeritas.world.cloned.ChunkRenderContext;
import com.gtnewhorizons.angelica.rendering.celeritas.world.cloned.ClonedChunkSection;
import com.gtnewhorizons.angelica.rendering.celeritas.world.cloned.ClonedChunkSectionCache;
import com.gtnewhorizons.liquidlogged.api.LiquidLoggedBlockAccess;
import cpw.mods.fml.common.Optional;
import mega.fluidlogged.api.FLBlockAccess;
@@ -46,11 +45,8 @@ import mega.fluidlogged.api.FLBlockAccess;
*
* Object pooling should be used to avoid huge allocations as this class contains many large arrays.
*/
@Optional.InterfaceList({
@Optional.Interface(iface = "mega.fluidlogged.api.FLBlockAccess", modid = "fluidlogged"),
@Optional.Interface(iface = "com.gtnewhorizons.liquidlogged.api.LiquidLoggedBlockAccess", modid = "liquidlogged")
})
public class WorldSlice implements IBlockAccessExtended, FLBlockAccess, LiquidLoggedBlockAccess {
@Optional.Interface(iface = "mega.fluidlogged.api.FLBlockAccess", modid = "fluidlogged")
public class WorldSlice implements IBlockAccessExtended, FLBlockAccess {
private static final EnumSkyBlock[] LIGHT_TYPES = EnumSkyBlock.values();
@@ -183,7 +179,7 @@ public class WorldSlice implements IBlockAccessExtended, FLBlockAccess, LiquidLo
this.lightArrays = new NibbleArray[SECTION_TABLE_ARRAY_SIZE][LIGHT_TYPES.length];
this.sectionLightData = new SectionLightData[SECTION_TABLE_ARRAY_SIZE];
if (ModStatus.isFluidLoggedLoaded || ModStatus.isLiquidLoggedLoaded) {
if (ModStatus.isFluidLoggedLoaded) {
this.fluidArrays = new Fluid[SECTION_TABLE_ARRAY_SIZE][];
} else {
this.fluidArrays = null;
@@ -197,7 +193,7 @@ public class WorldSlice implements IBlockAccessExtended, FLBlockAccess, LiquidLo
Arrays.fill(this.blockArrays[i], Blocks.air);
this.metadataArrays[i] = new int[SECTION_BLOCK_COUNT];
if (this.fluidArrays != null) {
if (ModStatus.isFluidLoggedLoaded && this.fluidArrays != null) {
this.fluidArrays[i] = new Fluid[SECTION_BLOCK_COUNT];
}
}
@@ -227,7 +223,7 @@ public class WorldSlice implements IBlockAccessExtended, FLBlockAccess, LiquidLo
Arrays.fill(this.biomeData, null);
// Pre-filter dynamic light sources for this chunk section
if (DynamicLights.isActive()) {
if (DynamicLights.isEnabled()) {
this.dynamicLightsInstance = DynamicLights.get();
this.chunkLightSources = dynamicLightsInstance.getSourcesForChunk(this.origin.getMinX(), this.origin.getMinY(), this.origin.getMinZ());
} else {
@@ -243,7 +239,7 @@ public class WorldSlice implements IBlockAccessExtended, FLBlockAccess, LiquidLo
this.unpackBlockData(this.blockArrays[idx], this.metadataArrays[idx], section, context.getVolume());
if (this.fluidArrays != null) {
if (ModStatus.isFluidLoggedLoaded && this.fluidArrays != null) {
this.unpackFluidLoggedData(this.fluidArrays[idx], section, context.getVolume());
}
@@ -461,12 +457,6 @@ public class WorldSlice implements IBlockAccessExtended, FLBlockAccess, LiquidLo
return this.fluidArrays[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)][getLocalBlockIndex(relX & 15, relY & 15, relZ & 15)];
}
// LiquidLogged API support
public @Nullable Fluid liquidlogged$getFluid(int x, int y, int z) {
return fl$getFluid(x, y, z);
}
public void fl$setFluid(int x, int y, int z, @Nullable Fluid fluid) {
throw new UnsupportedOperationException("Cannot set fluids in a world slice. WorldSlice is read-only");
}
@@ -9,8 +9,6 @@ import com.gtnewhorizons.angelica.compat.cubicchunks.CubicChunksAPI;
import com.gtnewhorizons.angelica.compat.mojang.ChunkSectionPos;
import com.gtnewhorizons.angelica.mixins.interfaces.IChunkTileEntityMapHolder;
import com.gtnewhorizons.angelica.utils.ConcurrentTileEntityMap;
import com.gtnewhorizons.liquidlogged.api.LiquidLoggedAPI;
import com.gtnewhorizons.liquidlogged.api.SectionFluidsView;
import it.unimi.dsi.fastutil.shorts.Short2ObjectOpenHashMap;
import mega.fluidlogged.internal.mixin.hook.FLSubChunk;
@@ -43,9 +41,6 @@ public class ClonedChunkSection {
private SectionLightData sectionLightData;
private final Short2ObjectOpenHashMap<TileEntity> tileEntities;
// Fluids stored in blocks by LiquidLogged, indexed y << 8 | z << 4 | x; null when the section holds none
private Fluid[] liquidLoggedFluids;
private long lastUsedTimestamp = Long.MAX_VALUE;
int refs;
@@ -84,10 +79,6 @@ public class ClonedChunkSection {
this.data.copyFrom(chunk, section);
}
if (ModStatus.isLiquidLoggedLoaded) {
copyLiquidLoggedFluids(section);
}
copyBlockEntities(chunk, pos);
fillBiomeData(chunk);
@@ -139,22 +130,7 @@ public class ClonedChunkSection {
return data.getExtBlockMetadata(x, y, z);
}
private void copyLiquidLoggedFluids(ExtendedBlockStorage section) {
final SectionFluidsView view = LiquidLoggedAPI.getSection(section);
if (view == null || view.isEmpty()) {
this.liquidLoggedFluids = null;
return;
}
if (this.liquidLoggedFluids == null) {
this.liquidLoggedFluids = new Fluid[SECTION_BLOCK_LENGTH * SECTION_BLOCK_LENGTH * SECTION_BLOCK_LENGTH];
}
view.copyTo(this.liquidLoggedFluids);
}
public Fluid getFluid(int x, int y, int z) {
if (ModStatus.isLiquidLoggedLoaded) {
return this.liquidLoggedFluids != null ? this.liquidLoggedFluids[y << 8 | z << 4 | x] : null;
}
if (ModStatus.isFluidLoggedLoaded) {
return ((FLSubChunk) data).fl$getFluid(x, y, z);
}
@@ -1,7 +1,6 @@
package com.gtnewhorizons.angelica.rendering.particles;
import com.gtnewhorizons.angelica.rendering.RenderFailures;
import com.gtnewhorizons.angelica.api.particles.ParticleRendering;
import com.gtnewhorizons.angelica.client.rendering.DeferredDrawBatcher;
import com.gtnewhorizons.angelica.glsm.GLSMAttribStack;
import com.gtnewhorizons.angelica.glsm.GLSMBuffers;
@@ -139,8 +138,6 @@ public final class ParticleInstancer {
STATE.sample();
SCRATCH.brightness = runTessellator.brightness;
if (!descriptor.describe(fx, partialTicks, SCRATCH, STATE)) return;
// Drawn from its fields, so a mod's size factor goes on here. The capture path below gets it from renderParticle
SCRATCH.half *= ParticleRendering.renderScale(fx);
runTessellator.color = SCRATCH.colorABGR;
runTessellator.hasColor = true;
@@ -30,12 +30,6 @@ public class SmoothFloat {
private float cachedHalfLifeDown;
private float cachedDecayDown;
// What the accumulator was at the start of this frame. Custom uniforms can be evaluated again mid-frame (see
// LocalGridFrame), and each of those calls has to smooth from the same point instead of stepping again.
private int frame = -1;
private float frameStartAccumulator;
private boolean frameStartHasInitialValue;
/**
* Computes an exponential decay factor based on the given decay constant and time value
*
@@ -64,16 +58,6 @@ public class SmoothFloat {
* Takes one value from the unsmoothed value sequence, and smooths it into our accumulator
*/
public float updateAndGet(float value, float halfLifeUp, float halfLifeDown) {
final int now = SystemTimeUniforms.COUNTER.getAsInt();
if (now != frame) {
frame = now;
frameStartAccumulator = accumulator;
frameStartHasInitialValue = hasInitialValue;
} else {
accumulator = frameStartAccumulator;
hasInitialValue = frameStartHasInitialValue;
}
if (halfLifeUp != cachedHalfLifeUp) {
cachedHalfLifeUp = halfLifeUp;
if (halfLifeUp == 0.0f) {
@@ -967,15 +967,6 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return current;
}
/** Evaluates these built-in uniforms again and pushes them to the bound pass, see LocalGridFrame. */
public void refreshUniforms(String[] names) {
customUniforms.refreshInputs(names);
if (current != null && current.liveProgram != null
&& GLSMPrograms.getActiveProgram() == current.liveProgram.getProgramId()) {
current.pushCustomUniforms();
}
}
public int getActivePassProgramId() {
if (current == null) return -1;
final Program p = current.boundProgram();
@@ -1506,10 +1497,6 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
}
void pushCustomUniforms() {
DeferredWorldRenderingPipeline.this.customUniforms.push(liveProgram == program ? this : liveProgram);
}
private void bindSelected() {
final Program selected = select(activeInstancing, GLSMRasterizer.clipEmulationActive());
liveProgram = selected;
@@ -1,8 +1,6 @@
package net.coderbot.iris.pipeline;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizons.angelica.api.shadows.ShadowCasters;
import com.gtnewhorizons.angelica.api.shadows.ShadowStage;
import com.gtnewhorizons.angelica.compat.mojang.Camera;
import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil;
import com.gtnewhorizons.angelica.compat.toremove.MatrixStack;
@@ -871,24 +869,6 @@ public class ShadowRenderer {
profiler.endSection();
}
private void renderShadowCasters(ShadowStage stage, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float partialTicks) {
if (!ShadowCasters.hasCasters()) return;
try (GLDebug.Scope s = GLDebug.scope("shadow:casters")) {
GLSMMatrices.glPushMatrix();
MODELVIEW_BUFFER.clear().rewind();
modelView.peek().getModel().get(MODELVIEW_BUFFER);
GLSMMatrices.glLoadMatrix(MODELVIEW_BUFFER);
GbufferPrograms.beginBlockEntities();
GbufferPrograms.setBlockEntityDefaults();
try {
ShadowCasters.renderAll(stage, cameraX, cameraY, cameraZ, partialTicks);
} finally {
GbufferPrograms.endBlockEntities();
GLSMMatrices.glPopMatrix();
}
}
}
public void renderShadows(EntityRenderer levelRenderer, Camera playerCamera) {
final Minecraft mc = Minecraft.getMinecraft();
final RenderGlobal rg = mc.renderGlobal;
@@ -1047,9 +1027,6 @@ public class ShadowRenderer {
}
}
// Mod geometry that should shadow like terrain, so not tied to the pack's block entity shadow setting
renderShadowCasters(ShadowStage.SOLID, modelView, entityX, entityY, entityZ, tickDelta);
profiler.endStartSection("iris_shadow_draw_entities");
// NB: Don't try to draw the translucent parts of entities afterwards. It'll cause problems since some
@@ -1067,7 +1044,6 @@ public class ShadowRenderer {
try (GLDebug.Scope s = GLDebug.scope("shadow:translucent")) {
rg.sortAndRender(mc.renderViewEntity, 1, playerCamera.getPartialTicks());
}
renderShadowCasters(ShadowStage.TRANSLUCENT, modelView, entityX, entityY, entityZ, tickDelta);
}
// Note: Apparently tripwire isn't rendered in the shadow pass.
@@ -41,7 +41,6 @@ class CoreTransformHelper {
transformer.injectVariable("uniform vec4 iris_WeatherParams0;");
transformer.injectVariable("uniform vec4 iris_WeatherParams1;");
transformer.injectVariable("uniform vec4 iris_WeatherParams2;");
transformer.injectVariable("uniform vec4 iris_WeatherParams3;");
transformer.injectVariable("vec4 iris_Vertex;");
transformer.injectVariable("vec4 iris_Color;");
transformer.injectVariable("vec4 iris_MultiTexCoord0;");
@@ -29,7 +29,6 @@ public class CameraUniforms {
public static void addCameraUniforms(UniformHolder uniforms, FrameUpdateNotifier notifier) {
final CameraPositionTracker tracker = new CameraPositionTracker(notifier);
LocalGridFrame.trackCamera(tracker);
uniforms
.uniform1f(ONCE, "near", () -> 0.05)
@@ -44,7 +44,6 @@ public class IrisInternalUniforms {
private static final Vector4f WEATHER_0 = new Vector4f();
private static final Vector4f WEATHER_1 = new Vector4f();
private static final Vector4f WEATHER_2 = new Vector4f();
private static final Vector4f WEATHER_3 = new Vector4f();
public static void addWeatherUniforms(DynamicUniformHolder uniforms) {
uniforms.uniform4f(PER_FRAME, "iris_WeatherParams0", () -> WEATHER_0.set(
@@ -52,9 +51,7 @@ public class IrisInternalUniforms {
uniforms.uniform4f(PER_FRAME, "iris_WeatherParams1", () -> WEATHER_1.set(
WeatherParams.cameraFracX, WeatherParams.cameraFracZ, WeatherParams.partialTicks, WeatherParams.age));
uniforms.uniform4f(PER_FRAME, "iris_WeatherParams2", () -> WEATHER_2.set(
WeatherParams.vanillaTick, WeatherParams.providerTick, WeatherParams.rainStrength, WeatherParams.providerAge));
uniforms.uniform4f(PER_FRAME, "iris_WeatherParams3", () -> WEATHER_3.set(
WeatherParams.providerInvRadius, 0.0f, 0.0f, 0.0f));
WeatherParams.rainScroll, WeatherParams.snowScroll, WeatherParams.rainStrength, 0.0f));
}
public static void addFogUniforms(DynamicUniformHolder uniforms, FogMode fogMode) {
@@ -1,260 +0,0 @@
package net.coderbot.iris.uniforms;
import org.joml.Matrix3d;
import org.joml.Matrix4f;
import org.joml.Matrix4fc;
import org.joml.Vector3d;
import org.joml.Vector3dc;
import org.joml.Vector3f;
import org.joml.Vector3fc;
import org.joml.Vector3ic;
import org.joml.Vector4f;
import org.joml.Vector4fc;
import java.util.HashMap;
import java.util.Map;
import java.util.function.DoubleSupplier;
import java.util.function.DoubleUnaryOperator;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
/**
* Lets a draw's own model space stand in for the world's block grid, for geometry drawn rotated or off the grid
* (structures, previews).
* <p>
* Packs pick out parts of some blocks by where a pixel is inside its world block, {@code fract(playerPos +
* cameraPosition)}, e.g. the water in a cauldron or the eye of an end portal frame. Off the grid that cuts through the
* block in the wrong place. While this is active the uniforms describe a world where the draw's model coordinates are
* world coordinates, moved by whole blocks to stay near the real position. View space, clip space and the shadow map
* come out exactly the same, so only what a pack works out in world space changes.
* <p>
* Every uniform that changes is in the remap tables below, keyed by name. The custom uniform input holder wraps those
* suppliers when it's built (see the wrap methods), so the uniform classes themselves don't know about any of this. A
* new world space uniform only needs a line here. The uniforms are worked out once a frame, so starting or ending this
* works them out again and pushes them to the bound program, see {@link #UNIFORMS}.
*/
public final class LocalGridFrame {
private static final Map<String, UnaryOperator<Vector3d>> VEC3D = new HashMap<>();
private static final Map<String, UnaryOperator<Vector3fc>> VEC3F = new HashMap<>();
private static final Map<String, UnaryOperator<Vector3ic>> VEC3I = new HashMap<>();
private static final Map<String, UnaryOperator<Vector4fc>> VEC4F = new HashMap<>();
private static final Map<String, UnaryOperator<Matrix4fc>> MATRIX = new HashMap<>();
private static final Map<String, DoubleUnaryOperator> DOUBLE = new HashMap<>();
/** Every uniform that changes under the frame. */
public static final String[] UNIFORMS;
private static boolean active;
private static CameraUniforms.CameraPositionTracker tracker;
// Model to player space is T = V^-1 * M, linear part L and translation t. Everything below comes from that
private static final Matrix4f postfix = new Matrix4f();
private static final Matrix4f postfixInverse = new Matrix4f();
private static final Matrix3d linearInverse = new Matrix3d();
private static final Vector3d eye = new Vector3d();
private static final Vector3d modelCamera = new Vector3d();
private static final Vector3d modelOrigin = new Vector3d();
private static final Vector4f up = new Vector4f();
// What the remaps hand back. Like the suppliers they wrap (CameraUniforms and MatrixUniforms keep scratch objects
// too), a value is only good until the next remap runs. The cached uniforms in the input holder all copy it
// straight away, anything new that takes a wrapped supplier has to do the same
private static final Matrix4f scratch = new Matrix4f();
private static final Vector3d current = new Vector3d();
private static final Vector3d previous = new Vector3d();
private static final Vector3d point = new Vector3d();
private static final Vector3d offset = new Vector3d();
private static final Vector3d direction = new Vector3d();
private static final Vector3f offset3f = new Vector3f();
private static final Vector4f offset4f = new Vector4f();
static {
// World positions. The shifted ones keep Iris's shift, the unshifted ones read the real camera directly
VEC3D.put("cameraPosition", LocalGridFrame::camera);
DOUBLE.put("eyeAltitude", y -> Math.rint(y + modelOrigin.y) + modelCamera.y);
VEC3D.put("previousCameraPosition", real -> tracker == null ? real
: previousCamera(tracker.getCurrentCameraPosition(), real));
VEC3I.put("cameraPositionInt", real -> CameraUniforms.getCameraPositionInt(unshiftedCamera()));
VEC3F.put("cameraPositionFract", real -> CameraUniforms.getCameraPositionFract(unshiftedCamera()));
VEC3I.put("previousCameraPositionInt", real -> tracker == null ? real
: CameraUniforms.getCameraPositionInt(unshiftedPreviousCamera()));
VEC3F.put("previousCameraPositionFract", real -> tracker == null ? real
: CameraUniforms.getCameraPositionFract(unshiftedPreviousCamera()));
VEC3D.put("eyePosition", real -> worldPosition(CameraUniforms.getUnshiftedCameraPosition(), real));
// Offsets from the unshifted camera
VEC3D.put("relativeEyePosition", LocalGridFrame::offset);
VEC3D.put("relativeVehiclePosition", LocalGridFrame::offset);
// -256 on every axis means nothing is selected
VEC3F.put("currentSelectedBlockPos", real -> real.x() == -256.0f && real.y() == -256.0f && real.z() == -256.0f
? real : offset3f.set(offset(point.set(real.x(), real.y(), real.z()))));
// w is 0 when there's no bolt
VEC4F.put("lightningBoltPosition", real -> {
if (real.w() == 0.0f) return real;
final Vector3d moved = offset(point.set(real.x(), real.y(), real.z()));
return offset4f.set((float) moved.x, (float) moved.y, (float) moved.z, real.w());
});
// Directions in the world
VEC3D.put("playerLookVector", LocalGridFrame::direction);
VEC3D.put("playerBodyVector", LocalGridFrame::direction);
VEC3D.put("vehicleLookVector", LocalGridFrame::direction);
// View space, so only up changes
VEC4F.put("upPosition", real -> up);
// Matrices that take world space positions relative to the camera
MATRIX.put("gbufferModelView", LocalGridFrame::modelView);
MATRIX.put("gbufferPreviousModelView", LocalGridFrame::modelView);
MATRIX.put("shadowModelView", LocalGridFrame::modelView);
MATRIX.put("gbufferModelViewInverse", LocalGridFrame::modelViewInverse);
MATRIX.put("shadowModelViewInverse", LocalGridFrame::modelViewInverse);
UNIFORMS = Stream.of(VEC3D, VEC3F, VEC3I, VEC4F, MATRIX, DOUBLE).flatMap(m -> m.keySet().stream())
.toArray(String[]::new);
}
private LocalGridFrame() {}
public static boolean isActive() {
return active;
}
/** The pipeline's camera tracker, for the uniforms that need the camera rather than their own value. */
static void trackCamera(CameraUniforms.CameraPositionTracker cameraTracker) {
tracker = cameraTracker;
}
/**
* @param drawModelView the modelview the geometry is drawn with
* @return false when it can't be done (a modelview that can't be inverted)
*/
public static boolean begin(Matrix4fc drawModelView) {
final Matrix4f view = new Matrix4f(MatrixUniforms.getGbufferModelView());
final Matrix4f viewInverse = new Matrix4f(view).invert();
final Matrix4f model = new Matrix4f(viewInverse).mul(drawModelView);
if (!Float.isFinite(model.determinant()) || Math.abs(model.determinant3x3()) < 1e-8f) return false;
// The camera's eye in player space, and in model space
eye.set(viewInverse.m30(), viewInverse.m31(), viewInverse.m32());
final Matrix3d linear = new Matrix3d(model.m00(), model.m01(), model.m02(), model.m10(), model.m11(),
model.m12(), model.m20(), model.m21(), model.m22());
linearInverse.set(linear).invert();
modelOrigin.set(model.m30(), model.m31(), model.m32());
modelCamera.set(eye).sub(modelOrigin);
linearInverse.transform(modelCamera);
// gbufferModelView' = V * translate(eye) * L, so V' * (p - camera) lands where M * p does
postfix.identity().translate((float) eye.x, (float) eye.y, (float) eye.z)
.mul(new Matrix4f().set3x3(model));
postfix.invert(postfixInverse);
// Model space up in view space, 100 long like the real upPosition
final Vector3f modelUp = model.transformDirection(new Vector3f(0, 1, 0)).normalize(100);
view.transformDirection(modelUp);
up.set(modelUp, 0);
active = true;
return true;
}
public static void end() {
active = false;
}
// The wrap methods are for the custom uniform input holder, each hands back the supplier with the remap applied
// while the frame is active, or the same supplier if that uniform doesn't change
public static Supplier<Vector3d> wrap3d(String name, Supplier<Vector3d> real) {
return wrap(VEC3D.get(name), real);
}
public static Supplier<Vector3fc> wrap3f(String name, Supplier<Vector3fc> real) {
return wrap(VEC3F.get(name), real);
}
public static Supplier<Vector3ic> wrap3i(String name, Supplier<Vector3ic> real) {
return wrap(VEC3I.get(name), real);
}
public static Supplier<Vector4fc> wrap4f(String name, Supplier<Vector4fc> real) {
return wrap(VEC4F.get(name), real);
}
public static Supplier<Matrix4fc> wrapMatrix(String name, Supplier<Matrix4fc> real) {
return wrap(MATRIX.get(name), real);
}
public static DoubleSupplier wrapDouble(String name, DoubleSupplier real) {
final DoubleUnaryOperator remap = DOUBLE.get(name);
if (remap == null) return real;
return () -> active ? remap.applyAsDouble(real.getAsDouble()) : real.getAsDouble();
}
private static <T> Supplier<T> wrap(UnaryOperator<T> remap, Supplier<T> real) {
if (remap == null) return real;
return () -> active ? remap.apply(real.get()) : real.get();
}
/** Where the model origin really is, rounded to whole blocks, so the frame's world stays near the real one. */
private static Vector3d shift(Vector3dc realCamera, Vector3d dest) {
return dest.set(
Math.rint(realCamera.x() + modelOrigin.x),
Math.rint(realCamera.y() + modelOrigin.y),
Math.rint(realCamera.z() + modelOrigin.z));
}
/** cameraPosition (or its unshifted twin) for a real one. */
private static Vector3d camera(Vector3d realCamera) {
return shift(realCamera, current).add(modelCamera);
}
private static Vector3d unshiftedCamera() {
return camera(CameraUniforms.getUnshiftedCameraPosition());
}
private static Vector3d unshiftedPreviousCamera() {
final Vector3d realPrevious = tracker.getPreviousCameraPositionUnshifted();
return previousCamera(CameraUniforms.getUnshiftedCameraPosition(), realPrevious);
}
/** previousCameraPosition, from the camera's last step turned into model space. */
private static Vector3d previousCamera(Vector3d realCamera, Vector3d realPrevious) {
previous.set(realCamera).sub(realPrevious);
linearInverse.transform(previous);
return previous.negate().add(camera(realCamera));
}
/** A real world position (eyePosition) moved into the frame's world, against the unshifted camera. */
private static Vector3d worldPosition(Vector3dc realCamera, Vector3dc realPosition) {
point.set(realPosition).sub(realCamera).sub(modelOrigin);
linearInverse.transform(point);
return shift(realCamera, current).add(point);
}
/**
* An offset from the unshifted camera (relativeEyePosition and co), as the same offset in the frame's world. Works
* out to {@link #worldPosition} minus the unshifted cameraPosition.
*/
private static Vector3d offset(Vector3d realOffset) {
return linearInverse.transform(offset.set(realOffset).sub(eye));
}
/** A world space direction turned into model space, same length. */
private static Vector3d direction(Vector3d real) {
final double length = real.length();
if (length == 0) return real;
return linearInverse.transform(direction.set(real)).normalize(length);
}
/** gbufferModelView, gbufferPreviousModelView or shadowModelView for a real one. */
private static Matrix4fc modelView(Matrix4fc real) {
return scratch.set(real).mul(postfix);
}
/** Their inverses, (R * P)^-1 = P^-1 * R^-1 for the real inverse. */
private static Matrix4fc modelViewInverse(Matrix4fc realInverse) {
return scratch.set(postfixInverse).mul(realInverse);
}
}
@@ -22,7 +22,7 @@ public final class MatrixUniforms {
}
private static final Matrix4f GBUFFER_MODELVIEW_SCRATCH = new Matrix4f();
static Matrix4fc getGbufferModelView() {
private static Matrix4fc getGbufferModelView() {
final Matrix4fc raw = RenderingState.INSTANCE.getModelViewMatrix();
final Entity view = Minecraft.getMinecraft().renderViewEntity;
if (view == null) {
@@ -48,7 +48,7 @@ public final class PerFrameUniformBlockHarvester {
"gbufferModelView", "gbufferModelViewInverse", "gbufferPreviousModelView",
"gbufferProjection", "gbufferProjectionInverse", "gbufferPreviousProjection",
"fogColor", "iris_FogColor", "iris_FogStart", "iris_FogEnd", "iris_FogDensity",
"iris_WeatherParams0", "iris_WeatherParams1", "iris_WeatherParams2", "iris_WeatherParams3");
"iris_WeatherParams0", "iris_WeatherParams1", "iris_WeatherParams2");
/**
* @param primary manifest whose entry order defines the block layout
@@ -8,7 +8,6 @@ import net.coderbot.iris.gl.uniform.FloatSupplier;
import net.coderbot.iris.gl.uniform.UniformHolder;
import com.gtnewhorizons.angelica.glsm.shader.UniformType;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.uniforms.LocalGridFrame;
import net.coderbot.iris.uniforms.custom.cached.BooleanCachedUniform;
import net.coderbot.iris.uniforms.custom.cached.CachedUniform;
import net.coderbot.iris.uniforms.custom.cached.Float2VectorCachedUniform;
@@ -95,8 +94,7 @@ public class CustomUniformFixedInputUniformsHolder {
@Override
public Builder uniform1f(UniformUpdateFrequency updateFrequency, String name, DoubleSupplier value) {
final DoubleSupplier wrapped = LocalGridFrame.wrapDouble(name, value);
return this.put(name, new FloatCachedUniform(name, updateFrequency, () -> (float) wrapped.getAsDouble()));
return this.put(name, new FloatCachedUniform(name, updateFrequency, () -> (float) value.getAsDouble()));
}
@Override
@@ -121,13 +119,11 @@ public class CustomUniformFixedInputUniformsHolder {
@Override
public Builder uniform3f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3fc> value) {
value = LocalGridFrame.wrap3f(name, value);
return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, value));
}
@Override
public Builder uniform3i(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3ic> value) {
value = LocalGridFrame.wrap3i(name, value);
return this.put(name, new Int3VectorCachedUniform(name, updateFrequency, value));
}
@@ -138,10 +134,9 @@ public class CustomUniformFixedInputUniformsHolder {
@Override
public Builder uniformTruncated3f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector4fc> value) {
final Supplier<Vector4fc> wrapped = LocalGridFrame.wrap4f(name, value);
Vector3f held = new Vector3f();
return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, () -> {
final Vector4fc vec = wrapped.get();
final Vector4fc vec = value.get();
held.set(vec.x(), vec.y(), vec.z());
return held;
}));
@@ -149,10 +144,9 @@ public class CustomUniformFixedInputUniformsHolder {
@Override
public UniformHolder uniform3d(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3d> value) {
final Supplier<Vector3d> wrapped = LocalGridFrame.wrap3d(name, value);
Vector3f held = new Vector3f();
return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, () -> {
Vector3d vec = wrapped.get();
Vector3d vec = value.get();
held.set(vec.x(), vec.y(), vec.z());
return held;
}));
@@ -160,10 +154,9 @@ public class CustomUniformFixedInputUniformsHolder {
@Override
public UniformHolder uniform4f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector4fc> value) {
final Supplier<Vector4fc> wrapped = LocalGridFrame.wrap4f(name, value);
Vector4f held = new Vector4f();
return this.put(name, new Float4VectorCachedUniform(name, updateFrequency, () -> {
final Vector4fc vec = wrapped.get();
final Vector4fc vec = value.get();
held.set(vec.x(), vec.y(), vec.z(), vec.w());
return held;
}));
@@ -182,7 +175,6 @@ public class CustomUniformFixedInputUniformsHolder {
@Override
public UniformHolder uniformMatrix(
UniformUpdateFrequency updateFrequency, String name, Supplier<Matrix4fc> value) {
value = LocalGridFrame.wrapMatrix(name, value);
return this.put(name, new Float4MatrixCachedUniform(name, updateFrequency, value));
}
@@ -48,9 +48,6 @@ public class CustomUniforms implements FunctionContext {
private final Object2LongOpenHashMap<Object> lastPushedGen = new Object2LongOpenHashMap<>();
private long generation;
private String[] refreshNames;
private CachedUniform[] refreshOrder;
private static final long PLOT_CUSTOM_PUSHED = Tracy.ENABLED ? Tracy.plotHandle("iris.customPushed") : 0;
private static final long PLOT_CUSTOM_SKIPPED = Tracy.ENABLED ? Tracy.plotHandle("iris.customSkipped") : 0;
private int pushedThisFrame;
@@ -257,41 +254,6 @@ public class CustomUniforms implements FunctionContext {
}
}
/**
* Evaluates these built-in uniforms again mid-frame, along with every custom uniform made from them, so the next
* push picks them up (see LocalGridFrame).
*/
public void refreshInputs(String[] names) {
if (names != refreshNames) {
refreshNames = names;
refreshOrder = readersInOrder(names);
}
for (CachedUniform uniform : refreshOrder) {
uniform.update();
}
generation++;
}
// The named inputs that are still used and every custom uniform that reads them, directly or not, in the order
// they're evaluated. uniformOrder is already sorted so each uniform comes after what it reads.
private CachedUniform[] readersInOrder(String[] names) {
final Set<CachedUniform> affected = new ObjectOpenHashSet<>();
for (String name : names) {
final CachedUniform uniform = this.inputHolder.getUniform(name);
if (uniform != null) affected.add(uniform);
}
final List<CachedUniform> ordered = new ObjectArrayList<>();
for (CachedUniform uniform : this.uniformOrder) {
if (!affected.contains(uniform)) {
final List<CachedUniform> dependencies = this.dependsOn.get(uniform);
if (dependencies == null || dependencies.stream().noneMatch(affected::contains)) continue;
affected.add(uniform);
}
ordered.add(uniform);
}
return ordered.toArray(new CachedUniform[0]);
}
public void push(Object pass) {
final PassUniforms pu = this.locationMap.get(pass);
if (pu == null) return;
@@ -15,7 +15,7 @@ public class MixinItemRenderer {
@Surround.Return
private int angelica$dynamiclights_renderItemInFirstPersonResult(int lightmap, WorldClient theWorld, int posX, int posY, int posZ){
if (DynamicLights.isActive()) {
if (DynamicLights.isEnabled()) {
final DynamicLights dl = DynamicLights.get();
if (dl.hasLightSources()) {
final double dynamicLightLevel = dl.getDynamicLightLevel(posX, posY, posZ);
@@ -189,7 +189,7 @@ public abstract class MixinLightDataAccess implements ExtLightDataAccess {
int brgb = provider.getBlockLightRGB(blockAccess, x, y, z);
final int srgb = provider.getSkyLightRGB(blockAccess, x, y, z);
if (DynamicLights.isActive()) {
if (DynamicLights.isEnabled()) {
final int dlRGB = DynamicLights.get().getDynamicLightRGB(x + 0.5, y + 0.5, z + 0.5);
if (dlRGB != 0) {
brgb = angelica$mergeMaxRGB(brgb, dlRGB);
@@ -1,7 +1,6 @@
package com.gtnewhorizons.angelica.mixins.early.celeritas.terrain;
import com.gtnewhorizons.angelica.client.rendering.AngelicaFogService;
import com.gtnewhorizons.angelica.api.world.WorldDrawStage;
import com.gtnewhorizons.angelica.compat.mojang.Camera;
import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil;
import com.gtnewhorizons.angelica.event.RenderChunkEvent;
@@ -285,8 +284,6 @@ public class MixinRenderGlobal implements IRenderGlobalExt {
}
final int blockEntitiesRendered = this.celeritas$renderer.renderBlockEntities(partialTicks);
if (Tracy.ENABLED) Tracy.plotInt(P_BLOCK_ENTITIES_RENDERED, blockEntitiesRendered);
// Mods drawing their own world geometry, still in the block entity phase so a shaderpack lights it
WorldDrawStage.run(partialTicks);
if (Iris.enabled) {
GbufferPrograms.endBlockEntities();
}
@@ -68,10 +68,7 @@ public abstract class MixinRenderBlocks implements ExtCeleritasRenderBlocks {
private boolean renderingPlainCube;
@Surround(method = "renderBlockByRenderType", id = "plainCube",
at = {
@At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/RenderBlocks;renderStandardBlock(Lnet/minecraft/block/Block;III)Z"),
// LOTR's coremod swaps the call for its natural-blocks wrapper, which ends in renderStandardBlock
@At(value = "INVOKE", target = "Llotr/common/coremod/LOTRReplacedMethods$BlockRendering;renderStandardBlock(Lnet/minecraft/client/renderer/RenderBlocks;Lnet/minecraft/block/Block;III)Z", remap = false) },
at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/RenderBlocks;renderStandardBlock(Lnet/minecraft/block/Block;III)Z"),
require = 1)
private void angelica$enterPlainCube() {
@Surround.Carry final boolean wasPlainCube = this.renderingPlainCube;
@@ -103,16 +103,6 @@ public class MixinTessellator implements StateAwareTessellator, BiomeBlendTessel
this.angelica$noDirectionalShading = flag;
}
@Override
public boolean angelica$isAppliedAo() {
return this.appliedAo;
}
@Override
public boolean angelica$isNoDirectionalShading() {
return this.angelica$noDirectionalShading;
}
@Override
public int[] angelica$getVertexStates() {
return this.vertexStates.elements();
@@ -1,6 +1,5 @@
package com.gtnewhorizons.angelica.mixins.early.shaders;
import com.gtnewhorizons.angelica.api.terrain.TerrainRendering;
import com.gtnewhorizons.angelica.compat.mojang.Camera;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.experimental.surround.Surround;
@@ -56,8 +55,6 @@ public abstract class MixinEntityRenderer implements IResourceManagerReloadListe
SystemTimeUniforms.TIMER.beginFrame(System.nanoTime());
Program.unbind();
// Before the frame's uniforms are worked out, so a stuck local grid can't leak into them
TerrainRendering.resetForFrame();
mc.mcProfiler.startSection("iris_prepare_pipeline");
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().preparePipeline(Iris.getCurrentDimensionName());
@@ -33,17 +33,12 @@ public abstract class MixinRenderBlockConnectedTexturesEthereal extends RenderBl
block.setBlockBoundsBasedOnState(getFakeRender().blockAccess, x, y, z);
getFakeRender().setRenderBoundsFromBlock(block);
boolean render = getFakeRender().renderStandardBlock(block, x, y, z);
try {
newFakeRenderEthereal.setWorld(renderer.blockAccess);
newFakeRenderEthereal.curBlock = getFakeRender().curBlock;
newFakeRenderEthereal.curMeta = getFakeRender().curMeta;
double h = 0.05D;
newFakeRenderEthereal.setRenderBounds(h, h, h, 1.0D - h, 1.0D - h, 1.0D - h);
render &= newFakeRenderEthereal.renderStandardBlock(block, x, y, z);
} finally {
getFakeRender().setWorld(null);
newFakeRenderEthereal.setWorld(null);
}
newFakeRenderEthereal.setWorld(renderer.blockAccess);
newFakeRenderEthereal.curBlock = getFakeRender().curBlock;
newFakeRenderEthereal.curMeta = getFakeRender().curMeta;
double h = 0.05D;
newFakeRenderEthereal.setRenderBounds(h, h, h, 1.0D - h, 1.0D - h, 1.0D - h);
render &= newFakeRenderEthereal.renderStandardBlock(block, x, y, z);
return render;
}
}
@@ -1,39 +0,0 @@
package com.gtnewhorizons.angelica.mixins.late.notfine.leaves.biomesoplenty;
import biomesoplenty.common.blocks.BlockBOPAppleLeaves;
import jss.notfine.util.LeafRenderUtil;
import net.minecraft.block.BlockLeavesBase;
import net.minecraft.block.material.Material;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(value = BlockBOPAppleLeaves.class)
public abstract class MixinBlockBOPAppleLeaves extends BlockLeavesBase {
@Shadow(remap = false)
private IIcon[][] textures;
@Override
public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) {
final int meta = world.getBlockMetadata(x, y, z);
final int type = meta & 3;
return textures[LeafRenderUtil.selectRenderMode(world, x, y, z, side) ? 1 : 0][type];
}
/**
* @author NotFine
* @reason Support new leaf rendering modes on Biomes O' Plenty leaves.
*/
@Overwrite
public boolean shouldSideBeRendered(IBlockAccess world, int x, int y, int z, int side) {
return LeafRenderUtil.shouldSideBeRendered(world, x, y, z, side);
}
private MixinBlockBOPAppleLeaves(Material material, boolean fancy) {
super(material, fancy);
}
}
@@ -1,51 +0,0 @@
package com.gtnewhorizons.angelica.mixins.late.notfine.leaves.biomesoplenty;
import biomesoplenty.common.blocks.BlockBOPColorizedLeaves;
import biomesoplenty.common.blocks.BlockBOPColorizedLeaves.ColourizedLeafCategory;
import jss.notfine.util.LeafRenderUtil;
import net.minecraft.block.BlockLeavesBase;
import net.minecraft.block.material.Material;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(value = BlockBOPColorizedLeaves.class)
public abstract class MixinBlockBOPColorizedLeaves extends BlockLeavesBase {
@Shadow(remap = false)
private IIcon[][] textures;
@Shadow(remap = false)
@Final
private static String[] leaves;
@Shadow(remap = false)
@Final
private ColourizedLeafCategory category;
@Override
public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) {
final int meta = world.getBlockMetadata(x, y, z);
int type = (meta & 3) + category.ordinal() * 4;
if (type >= leaves.length) {
type = 0;
}
return textures[LeafRenderUtil.selectRenderMode(world, x, y, z, side) ? 1 : 0][type];
}
/**
* @author NotFine
* @reason Support new leaf rendering modes on Biomes O' Plenty leaves.
*/
@Overwrite
public boolean shouldSideBeRendered(IBlockAccess world, int x, int y, int z, int side) {
return LeafRenderUtil.shouldSideBeRendered(world, x, y, z, side);
}
private MixinBlockBOPColorizedLeaves(Material material, boolean fancy) {
super(material, fancy);
}
}
@@ -1,51 +0,0 @@
package com.gtnewhorizons.angelica.mixins.late.notfine.leaves.biomesoplenty;
import biomesoplenty.common.blocks.BlockBOPLeaves;
import biomesoplenty.common.blocks.BlockBOPLeaves.LeafCategory;
import jss.notfine.util.LeafRenderUtil;
import net.minecraft.block.BlockLeavesBase;
import net.minecraft.block.material.Material;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(value = BlockBOPLeaves.class)
public abstract class MixinBlockBOPLeaves extends BlockLeavesBase {
@Shadow(remap = false)
private IIcon[][] textures;
@Shadow(remap = false)
@Final
private static String[] leaves;
@Shadow(remap = false)
@Final
private LeafCategory category;
@Override
public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) {
final int meta = world.getBlockMetadata(x, y, z);
int type = (meta & 3) + category.ordinal() * 4;
if (type >= leaves.length) {
type = 0;
}
return textures[LeafRenderUtil.selectRenderMode(world, x, y, z, side) ? 1 : 0][type];
}
/**
* @author NotFine
* @reason Support new leaf rendering modes on Biomes O' Plenty leaves.
*/
@Overwrite
public boolean shouldSideBeRendered(IBlockAccess world, int x, int y, int z, int side) {
return LeafRenderUtil.shouldSideBeRendered(world, x, y, z, side);
}
private MixinBlockBOPLeaves(Material material, boolean fancy) {
super(material, fancy);
}
}
@@ -1,39 +0,0 @@
package com.gtnewhorizons.angelica.mixins.late.notfine.leaves.biomesoplenty;
import biomesoplenty.common.blocks.BlockBOPPersimmonLeaves;
import jss.notfine.util.LeafRenderUtil;
import net.minecraft.block.BlockLeavesBase;
import net.minecraft.block.material.Material;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(value = BlockBOPPersimmonLeaves.class)
public abstract class MixinBlockBOPPersimmonLeaves extends BlockLeavesBase {
@Shadow(remap = false)
private IIcon[][] textures;
@Override
public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) {
final int meta = world.getBlockMetadata(x, y, z);
final int type = meta & 3;
return textures[LeafRenderUtil.selectRenderMode(world, x, y, z, side) ? 1 : 0][type];
}
/**
* @author NotFine
* @reason Support new leaf rendering modes on Biomes O' Plenty leaves.
*/
@Overwrite
public boolean shouldSideBeRendered(IBlockAccess world, int x, int y, int z, int side) {
return LeafRenderUtil.shouldSideBeRendered(world, x, y, z, side);
}
private MixinBlockBOPPersimmonLeaves(Material material, boolean fancy) {
super(material, fancy);
}
}
@@ -1,33 +0,0 @@
package com.gtnewhorizons.angelica.mixins.late.notfine.leaves.biomesoplenty;
import biomesoplenty.client.render.blocks.ColorizedLeavesRenderer;
import com.llamalad7.mixinextras.sugar.Local;
import com.prupe.mcpatcher.mal.block.RenderBlocksUtils;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.init.Blocks;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(value = ColorizedLeavesRenderer.class, remap = false)
public abstract class MixinColorizedLeavesRenderer {
@Redirect(
method = "renderWorldBlock",
at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/RenderBlocks;renderStandardBlock(Lnet/minecraft/block/Block;III)Z", remap = true))
private boolean angelica$renderOverlayWithLeafCulling(RenderBlocks renderer, Block block, int x, int y, int z, @Local(argsOnly = true) Block leaf) {
if (block != Blocks.stone) {
return renderer.renderStandardBlock(block, x, y, z);
}
RenderBlocksUtils.setupColorMultiplier(block, renderer.blockAccess, x, y, z, renderer.hasOverrideBlockTexture(), 1f, 1f, 1f);
if (Minecraft.isAmbientOcclusionEnabled() && leaf.getLightValue() == 0) {
return renderer.partialRenderBounds
? renderer.renderStandardBlockWithAmbientOcclusionPartial(leaf, x, y, z, 1f, 1f, 1f)
: renderer.renderStandardBlockWithAmbientOcclusion(leaf, x, y, z, 1f, 1f, 1f);
}
return renderer.renderStandardBlockWithColorMultiplier(leaf, x, y, z, 1f, 1f, 1f);
}
}
@@ -1,81 +0,0 @@
package com.gtnewhorizons.angelica.dynamiclights;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class DynamicLightsFalloffTest {
private static final double EPS = 1e-9;
@Test
void reachFifteenIsVanillaBlockLight() {
// A real block of luminance L lights L - distance
for (int luminance = 1; luminance <= 15; luminance++) {
for (int d = 0; d <= 16; d++) {
assertEquals(Math.max(0, luminance - d), DynamicLights.falloff(luminance, 15, d), EPS);
}
}
}
@Test
void shorterReachFadesSooner() {
assertEquals(15, DynamicLights.falloff(15, 5, 0), EPS);
assertEquals(6, DynamicLights.falloff(15, 5, 3), EPS);
assertEquals(0, DynamicLights.falloff(15, 5, 5), EPS);
assertEquals(0, DynamicLights.falloff(15, 5, 6), EPS);
}
@Test
void torchReachIsTheOldFalloff() {
assertEquals(15, DynamicLights.falloff(15, -1, 0), EPS);
assertEquals((1 - 4 / 7.75) * 15, DynamicLights.falloff(15, -1, 4), EPS);
assertEquals(0, DynamicLights.falloff(15, -1, 7.8), EPS);
assertEquals(DynamicLights.falloff(12, -1, 3), DynamicLights.falloff(12, 3), EPS);
}
@Test
void zeroReachOrLuminanceGivesNothing() {
assertEquals(0, DynamicLights.falloff(15, 0, 0), EPS);
assertEquals(0, DynamicLights.falloff(0, 15, 0), EPS);
}
@Test
void fractionalReach() {
// An eighth size glowstone: 15 / 1.875 = 8 levels a block
assertEquals(15, DynamicLights.falloff(15, 1.875f, 0), EPS);
assertEquals(7, DynamicLights.falloff(15, 1.875f, 1), EPS);
assertEquals(0, DynamicLights.falloff(15, 1.875f, 1.875), EPS);
assertEquals(0, DynamicLights.falloff(15, 1.875f, 2), EPS);
}
@Test
void reachOfFollowsLuminance() {
final PositionalLightSource light = new PositionalLightSource();
assertEquals(0, DynamicLights.reachOf(light), EPS);
light.setReach(15);
setLuminanceWithoutTracking(light, 15);
assertEquals(15, DynamicLights.reachOf(light), EPS);
setLuminanceWithoutTracking(light, 6);
assertEquals(6, DynamicLights.reachOf(light), EPS);
light.setReach(-1);
assertEquals(7.75, DynamicLights.reachOf(light), EPS);
light.setReach(99);
assertEquals(15, light.getReach(), EPS);
light.setReach(1.875f);
assertEquals(0.75, DynamicLights.reachOf(light), EPS);
light.setReach(-0.5f);
assertEquals(-1, light.getReach(), EPS);
}
// setLuminance adds the light to Angelica's lights, which needs a game. The field is all reachOf reads
private static void setLuminanceWithoutTracking(PositionalLightSource light, int luminance) {
try {
final java.lang.reflect.Field f = PositionalLightSource.class.getDeclaredField("luminance");
f.setAccessible(true);
f.setInt(light, luminance);
} catch (ReflectiveOperationException e) {
throw new AssertionError(e);
}
}
}
@@ -1,166 +0,0 @@
package com.gtnewhorizons.angelica.dynamiclights;
import com.gtnewhorizon.gtnhlib.util.CoordinatePacker;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** A positional light has to rebuild every chunk section its light shows up in, and the ones it leaves. */
class PositionalLightTrackingTest {
private static final float[] REACHES = { -1, 0.4f, 1, 1.875f, 5, 7, 7.5f, 8, 11, 15 };
private static final int[] LUMINANCES = { 1, 6, 11, 15 };
// Section middles, edges and corners, and either side of the middle where a torch reach just gets out both ways
private static final double[] OFFSETS = { 0, 0.05, 0.6, 3, 7.3, 8, 8.7, 13, 15.4, 15.95 };
private boolean frustumCulling;
@BeforeEach
void rebuildStraightAway() {
// Otherwise rebuilds queue up in the rebuild manager until a frame runs
frustumCulling = DynamicLights.FrustumCullingEnabled;
DynamicLights.FrustumCullingEnabled = false;
}
@AfterEach
void restore() {
DynamicLights.FrustumCullingEnabled = frustumCulling;
}
@Test
void rebuildsEverySectionTheLightGetsInto() {
for (float reach : REACHES) {
for (int luminance : LUMINANCES) {
for (double ox : OFFSETS) {
for (double oy : OFFSETS) {
for (double oz : OFFSETS) {
check(reach, luminance, -32 + ox, 64 + oy, 160 + oz);
}
}
}
}
}
}
private static void check(float reach, int luminance, double x, double y, double z) {
final PositionalLightSource light = new PositionalLightSource();
light.setReach(reach);
set(light, "luminance", luminance);
set(light, "x", x);
set(light, "y", y);
set(light, "z", z);
final Recorder rebuilt = new Recorder();
assertTrue(light.angelica$updateDynamicLight(rebuilt));
final String what = "reach " + reach + " luminance " + luminance + " at " + x + " " + y + " " + z;
final int cx = (int) Math.floor(x) >> 4, cy = (int) Math.floor(y) >> 4, cz = (int) Math.floor(z) >> 4;
for (int dx = -2; dx <= 2; dx++) {
for (int dy = -2; dy <= 2; dy++) {
for (int dz = -2; dz <= 2; dz++) {
final boolean tracked = rebuilt.sections.contains(CoordinatePacker.pack(cx + dx, cy + dy, cz + dz));
if (tracked) {
assertTrue(Math.max(Math.abs(dx), Math.max(Math.abs(dy), Math.abs(dz))) <= 1, what);
} else {
assertFalse(lights(light, cx + dx, cy + dy, cz + dz),
what + " misses section " + dx + " " + dy + " " + dz);
}
}
}
}
if (reach >= 0 && reach <= 7) assertTrue(rebuilt.sections.size() <= 8, what);
}
// What the mesher reads for a section: the light in the middle of each of its cells and the cells a block outside
// it (smooth lighting reads those for faces on the edge)
private static boolean lights(PositionalLightSource light, int sx, int sy, int sz) {
for (int x = -1; x <= 16; x++) {
for (int y = -1; y <= 16; y++) {
for (int z = -1; z <= 16; z++) {
if (DynamicLights.maxDynamicLightLevel((sx << 4) + x, (sy << 4) + y, (sz << 4) + z, light, 0) > 0) {
return true;
}
}
}
}
return false;
}
@Test
void rebuildsWhatItLeaves() {
final PositionalLightSource light = new PositionalLightSource();
light.setReach(5);
set(light, "luminance", 15);
set(light, "x", 8.0);
set(light, "y", 8.0);
set(light, "z", 8.0);
final Recorder first = new Recorder();
light.angelica$updateDynamicLight(first);
assertEquals(1, first.sections.size());
// Three sections along, nothing in common with where it was
set(light, "x", 56.0);
final Recorder second = new Recorder();
assertTrue(light.angelica$updateDynamicLight(second));
assertTrue(second.sections.contains(CoordinatePacker.pack(0, 0, 0)), "the section it left");
assertTrue(second.sections.contains(CoordinatePacker.pack(3, 0, 0)), "the section it went to");
assertEquals(2, second.sections.size());
}
@Test
void sittingStillRebuildsNothing() {
final PositionalLightSource light = new PositionalLightSource();
set(light, "luminance", 15);
set(light, "x", 8.0);
set(light, "y", 8.0);
set(light, "z", 8.0);
final Recorder rebuilt = new Recorder();
assertTrue(light.angelica$updateDynamicLight(rebuilt));
rebuilt.sections.clear();
assertFalse(light.angelica$updateDynamicLight(rebuilt));
assertTrue(rebuilt.sections.isEmpty());
// A new reach counts as a change
light.setReach(15);
assertTrue(light.angelica$updateDynamicLight(rebuilt));
assertEquals(27, rebuilt.sections.size());
// A tiny one doesn't, like a tiny move
rebuilt.sections.clear();
light.setReach(14.95f);
assertFalse(light.angelica$updateDynamicLight(rebuilt));
assertTrue(rebuilt.sections.isEmpty());
}
private static final class Recorder implements IDynamicLightWorldRenderer {
final LongOpenHashSet sections = new LongOpenHashSet();
@Override
public void scheduleRebuildForChunk(int x, int y, int z, boolean important) {
sections.add(CoordinatePacker.pack(x, y, z));
}
@Override
public boolean isActive() {
return true;
}
}
// The setters add the light to Angelica's lights, which needs a game. Tracking only reads the fields
private static void set(PositionalLightSource light, String field, Object value) {
try {
final Field f = PositionalLightSource.class.getDeclaredField(field);
f.setAccessible(true);
f.set(light, value);
} catch (ReflectiveOperationException e) {
throw new AssertionError(e);
}
}
}
@@ -0,0 +1,31 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.minecraft.tileentity.TileEntity;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
class TileEntityDepthOrderTest {
private static TileEntity at(int x, int y, int z) {
final TileEntity te = new TileEntity();
te.xCoord = x;
te.yCoord = y;
te.zCoord = z;
return te;
}
@Test
void sortsFarthestFirstAndKeepsTiesInListOrder() {
final TileEntity near = at(0, 0, 2);
final TileEntity far = at(0, 0, 181);
final TileEntity mid = at(0, 0, 5);
final TileEntity midOpposite = at(0, 0, -5);
final ObjectArrayList<TileEntity> list = new ObjectArrayList<>(Arrays.asList(near, far, mid, midOpposite));
new TileEntityDepthOrder().sortBackToFront(list, 0.5, 0.5, 0.5);
assertEquals(Arrays.asList(far, mid, midOpposite, near), list);
}
}
@@ -322,16 +322,6 @@ class IrisInstancingGLTest {
link("particleVariant", result);
}
@Test
void weatherVariantLinks() {
final Map<PatchShaderType, String> result = TransformPatcher.patchAttributesInstanced(PARTICLE_VERTEX, null, null, null, PARTICLE_FRAGMENT, TEX_LM, false, Instancing.WEATHER);
assertNotNull(result);
final String v = result.get(PatchShaderType.VERTEX);
assertNotNull(v);
assertTrue(v.startsWith("#version 330"), () -> "expected a 3.3 core vertex shader:\n" + v);
link("weatherVariant", result);
}
@Test
void templateVariantCompilesAndLinksWithGeometryStage() {
final Map<PatchShaderType, String> result = TransformPatcher.patchAttributesInstanced(TEMPLATE_VERTEX, TEMPLATE_GEOMETRY, null, null, TEMPLATE_FRAGMENT, TEX_LM, false, Instancing.TEMPLATE);
@@ -6,7 +6,6 @@ import com.gtnewhorizons.angelica.glsm.ffp.CubeInstancedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import com.gtnewhorizons.angelica.glsm.ffp.ParticleInstancedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.WeatherInstancedAttribs;
import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler;
import com.gtnewhorizons.angelica.glsm.testutil.ClipTestSupport;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
@@ -428,24 +427,7 @@ class AttributeTransformerInstancedTest {
assertFalse(byLocation.containsKey(7), "location 7 is unused");
for (final int loc : byLocation.keySet()) {
assertTrue(loc < ImmediateExtendedAttribHandler.LOC_MC_ENTITY || loc == ImmediateExtendedAttribHandler.LOC_ENTITY_IDS, "unexpected attribute location " + loc + " declared for the particle variant");
}
}
@Test
void weatherVariantDeclaresTheFiveColumnAttributesAtTheStatedLocations() {
final String v = instancedVertex(PARTICLE_VERTEX, Instancing.WEATHER);
final Map<Integer, String> byLocation = attributeLocations(v);
assertEquals(VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation(), locationOf(byLocation, "iris_WeatherCorner"));
assertEquals(WeatherInstancedAttribs.LOC_COLUMN_SPAN, locationOf(byLocation, "iris_InstColumnSpan"));
assertEquals(WeatherInstancedAttribs.LOC_JITTER, locationOf(byLocation, "iris_InstJitter"));
assertEquals(WeatherInstancedAttribs.LOC_COLOR, locationOf(byLocation, "iris_InstWeatherColor"));
assertEquals(WeatherInstancedAttribs.LOC_PARAMS, locationOf(byLocation, "iris_InstWeatherParams"));
assertEquals(WeatherInstancedAttribs.LOC_LAYER, locationOf(byLocation, "iris_InstWeatherLayer"));
for (final int loc : byLocation.keySet()) {
assertTrue(loc < ImmediateExtendedAttribHandler.LOC_MC_ENTITY || loc == ImmediateExtendedAttribHandler.LOC_ENTITY_IDS, "unexpected attribute location " + loc + " declared for the weather variant");
assertTrue(loc < 11 || loc == ImmediateExtendedAttribHandler.LOC_ENTITY_IDS, "unexpected attribute location " + loc + " declared for the particle variant");
}
}