Compare commits

...
Author SHA1 Message Date
Jason Mitchell c211d90faf Off thread safe blocks (#177)
* Whitelist carpentersblocks for off main thread rendering

* Add bounds checking to WorldSlice,

* Add preliminary `IThreadSafeISBRH` support

* Update TODO

* Adjust min y

* remove unnecessary try/catch

* * Keep track of what should be rendered on the main thread
* Update AngelicaBlockSafetyRegistry to handle vanilla blocks, and ISBHR's

* of -> set
2024-01-12 18:31:01 -08:00
Jason Mitchell 537eb06b66 Respect animation speedup config (#180) 2024-01-11 08:05:26 -08:00
Darren Eberly 93b03847df Only use BatchedFontRenderer when not in a display list compilation (#174) 2024-01-09 09:28:31 -05:00
Darren EberlyandJason Mitchell 85e44369bb Handle state changes for display lists correctly in GLSM (#168)
* Handle state changes in display lists correctly in GLSM

* Add some documentation so it's slightly more clear as to what's happening

---------

Co-authored-by: Jason Mitchell <[email protected]>
2024-01-08 21:48:15 +00:00
Raven Szewczyk fbc1b1b440 [ci skip] upgraded build system 2024-01-08 21:23:33 +00:00
embeddedt 97152a6ace Clear event phase before reusing object (#170) 2024-01-08 16:11:35 -05:00
makamysandJason Mitchell 3cde764d33 Update BS (#165)
* Update BS

Ran `updateBuildscript` and manually copied in the new `settings.gradle`

* Update build.gradle

---------

Co-authored-by: Jason Mitchell <[email protected]>
2024-01-08 03:25:38 +00:00
Jason Mitchell 45b20efc45 Change where the offset is reset (#159)
* Change where the offset is reset
* Debug log and rm dead code
2024-01-07 18:58:48 -08:00
22 changed files with 249 additions and 244 deletions

No files matched your search

+3 -3
View File
@@ -1,4 +1,4 @@
//version: 1704135167
//version: 1704650211
/*
DO NOT CHANGE THIS FILE!
Also, you may replace this file at any time if there is an update available.
@@ -53,7 +53,7 @@ plugins {
id 'com.diffplug.spotless' version '6.13.0' apply false // 6.13.0 is the last jvm8 supporting version
id 'com.modrinth.minotaur' version '2.+' apply false
id 'com.matthewprenger.cursegradle' version '1.4.0' apply false
id 'com.gtnewhorizons.retrofuturagradle' version '1.3.26'
id 'com.gtnewhorizons.retrofuturagradle' version '1.3.27'
}
print("You might want to check out './gradlew :faq' if your build fails.\n")
@@ -786,7 +786,7 @@ dependencies {
java17Dependencies("com.github.GTNewHorizons:lwjgl3ify:${lwjgl3ifyVersion}")
}
if (modId != 'hodgepodge') {
java17Dependencies('com.github.GTNewHorizons:Hodgepodge:2.4.4')
java17Dependencies('com.github.GTNewHorizons:Hodgepodge:2.3.35')
}
java17PatchDependencies("com.github.GTNewHorizons:lwjgl3ify:${lwjgl3ifyVersion}:forgePatches") {transitive = false}
Binary file not shown.
+2 -1
View File
@@ -1,6 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+13 -9
View File
@@ -83,7 +83,8 @@ done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -130,10 +131,13 @@ location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
@@ -141,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
@@ -149,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@@ -198,11 +202,11 @@ fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
+5 -6
View File
@@ -4,10 +4,9 @@ pluginManagement {
maven {
// RetroFuturaGradle
name "GTNH Maven"
url "http://jenkins.usrv.eu:8081/nexus/content/groups/public/"
allowInsecureProtocol = true
url "https://nexus.gtnewhorizons.com/repository/public/"
mavenContent {
includeGroup("com.gtnewhorizons.retrofuturagradle")
includeGroupByRegex("com\\.gtnewhorizons\\..+")
}
}
gradlePluginPortal()
@@ -17,12 +16,12 @@ pluginManagement {
}
plugins {
id 'com.diffplug.blowdryerSetup' version '1.6.0'
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.4.0' // Provides java toolchains
id 'com.diffplug.blowdryerSetup' version '1.7.1'
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.7.0' // Provides java toolchains
}
blowdryerSetup {
repoSubfolder 'gtnhShared'
github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.2.0')
github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.2.2')
//devLocal '.' // Use this when testing config updates locally
}
@@ -47,6 +47,10 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns
public void setOffset(BlockPos pos) {
this.offset.set(pos);
}
public void resetOffset() {
this.offset.zero();
}
static {
Field rbs = ReflectionHelper.findField(Tessellator.class, "rawBufferSize");
@@ -106,12 +110,6 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns
return i;
}
@Override
public void reset() {
super.reset();
this.offset.zero();
}
@Override
public void discard() {
isDrawing = false;
@@ -232,4 +230,5 @@ public class CapturingTessellator extends Tessellator implements ITessellatorIns
}
}
}
}
@@ -80,6 +80,9 @@ public class BlockPos extends Vector3i {
return l;
}
public BlockPos set(long packedPos) {
return set(unpackLongX(packedPos), unpackLongY(packedPos), unpackLongZ(packedPos));
}
public static int unpackLongX(long packedPos) {
return (int)(packedPos << 64 - BIT_SHIFT_X - SIZE_BITS_X >> 64 - SIZE_BITS_X);
@@ -55,6 +55,7 @@ import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.AbstractMap;
import java.util.Map;
import java.util.Set;
@@ -133,6 +134,9 @@ public class GLStateManager {
StateUpdateNotifiers.fogEndNotifier = listener -> fogEndListener = listener;
StateUpdateNotifiers.fogDensityNotifier = listener -> fogDensityListener = listener;
}
if(BYPASS_CACHE) {
LOGGER.info("GLStateManager cache bypassed");
}
}
public static void assertMainThread() {
@@ -729,6 +733,7 @@ public class GLStateManager {
glListMode = mode;
GL11.glNewList(list, mode);
for(IStateStack<?> stack : Feature.maskToFeatures(GL11.GL_ALL_ATTRIB_BITS)) {
// Feature Stack, copy of current feature state
glListStates.put(stack, (ISettableState<?>) ((ISettableState<?>)stack).copy());
}
if(glListMode == GL11.GL_COMPILE) {
@@ -743,8 +748,10 @@ public class GLStateManager {
final Set<Map.Entry<IStateStack<?>, ISettableState<?>>> changedStates = new ObjectArraySet<>();
for(Map.Entry<IStateStack<?>, ISettableState<?>> entry : glListStates.entrySet()) {
// If the current stack state is different than the copy of the state at the start
if(!((ISettableState<?>)entry.getKey()).sameAs(entry.getValue())) {
changedStates.add(entry);
// Then we want to put into the change set the stack and the copy of the state now
changedStates.add(new AbstractMap.SimpleEntry<>(entry.getKey(), (ISettableState<?>) ((ISettableState<?>) entry.getKey()).copy()));
}
}
if(changedStates.size() != 0) {
@@ -766,6 +773,7 @@ public class GLStateManager {
GL11.glCallList(list);
if(glListChanges.containsKey(list)) {
for(Map.Entry<IStateStack<?>, ISettableState<?>> entry : glListChanges.get(list)) {
// Set the stack to the cached state at the end of the call list compilation
((ISettableState<?>)entry.getKey()).set(entry.getValue());
}
}
@@ -919,4 +927,8 @@ public class GLStateManager {
public static int getActiveTextureUnit() {
return activeTextureUnit.topInt();
}
public static int getListMode() {
return glListMode;
}
}
@@ -1,144 +0,0 @@
package com.gtnewhorizons.angelica.glsm.states;
import org.joml.Matrix4f;
import org.joml.Matrix4fStack;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
public class MatrixState {
public MatrixMode mode = MatrixMode.NONE;
public final Matrix4fStack projectionMatrix;
public final Matrix4fStack modelViewMatrix;
public MatrixState() {
projectionMatrix = new Matrix4fStack(GL11.glGetInteger(GL11.GL_MAX_PROJECTION_STACK_DEPTH));
modelViewMatrix = new Matrix4fStack(GL11.glGetInteger(GL11.GL_MAX_MODELVIEW_STACK_DEPTH));
}
public void identity() {
switch (mode) {
case MODELVIEW -> modelViewMatrix.identity();
case PROJECTION -> projectionMatrix.identity();
default -> {
}
}
}
public void setMode(int mode) {
switch (mode) {
case GL11.GL_MODELVIEW -> this.mode = MatrixMode.MODELVIEW;
case GL11.GL_PROJECTION -> this.mode = MatrixMode.PROJECTION;
case GL11.GL_TEXTURE -> this.mode = MatrixMode.TEXTURE;
default -> throw new RuntimeException("Unsupported matrix mode: " + mode);
}
}
public void translate(float x, float y, float z) {
switch (mode) {
case MODELVIEW -> modelViewMatrix.translate(x, y, z);
case PROJECTION -> projectionMatrix.translate(x, y, z);
default -> {
}
}
}
public void scale(float x, float y, float z) {
switch (mode) {
case MODELVIEW -> modelViewMatrix.scale(x, y, z);
case PROJECTION -> projectionMatrix.scale(x, y, z);
default -> {
}
}
}
private final Matrix4f tempMatrix = new Matrix4f();
public void multiply(FloatBuffer matrix) {
tempMatrix.set(matrix);
switch (mode) {
case MODELVIEW -> modelViewMatrix.mul(tempMatrix);
case PROJECTION -> projectionMatrix.mul(tempMatrix);
default -> {
}
}
}
public void multiply(Matrix4f matrix) {
switch (mode) {
case MODELVIEW -> modelViewMatrix.mul(matrix);
case PROJECTION -> projectionMatrix.mul(matrix);
default -> {
}
}
}
public void rotate(float angle, float x, float y, float z) {
switch (mode) {
case MODELVIEW -> modelViewMatrix.rotate(angle, x, y, z);
case PROJECTION -> projectionMatrix.rotate(angle, x, y, z);
default -> {
}
}
}
public void ortho(double left, double right, double bottom, double top, double zNear, double zFar) {
switch (mode) {
case MODELVIEW -> modelViewMatrix.ortho((float) left, (float) right, (float) bottom, (float) top, (float) zNear, (float) zFar);
case PROJECTION -> projectionMatrix.ortho((float) left, (float) right, (float) bottom, (float) top, (float) zNear, (float) zFar);
default -> {
}
}
}
public void frustum(double left, double right, double bottom, double top, double zNear, double zFar) {
switch (mode) {
case MODELVIEW -> modelViewMatrix.frustum((float) left, (float) right, (float) bottom, (float) top, (float) zNear, (float) zFar);
case PROJECTION -> projectionMatrix.frustum((float) left, (float) right, (float) bottom, (float) top, (float) zNear, (float) zFar);
default -> {
}
}
}
public void push() {
switch (mode) {
case MODELVIEW -> modelViewMatrix.pushMatrix();
case PROJECTION -> projectionMatrix.pushMatrix();
default -> {
}
}
}
public void pop() {
switch (mode) {
case MODELVIEW -> modelViewMatrix.popMatrix();
case PROJECTION -> projectionMatrix.popMatrix();
default -> {
}
}
}
public void perspective(float fovy, float aspect, float zNear, float zFar) {
switch (mode) {
case MODELVIEW -> modelViewMatrix.perspective(fovy, aspect, zNear, zFar);
case PROJECTION -> projectionMatrix.perspective(fovy, aspect, zNear, zFar);
default -> {
}
}
}
enum MatrixMode {
NONE,
MODELVIEW,
PROJECTION,
TEXTURE
}
@Override
public boolean equals(Object state) {
if (this == state) return true;
if (!(state instanceof MatrixState matrixState)) return false;
return mode == matrixState.mode && projectionMatrix.equals(matrixState.projectionMatrix) && modelViewMatrix.equals(matrixState.modelViewMatrix);
}
}
@@ -0,0 +1,8 @@
package com.gtnewhorizons.angelica.interfaces;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
public interface IThreadSafeISBRH extends ISimpleBlockRenderingHandler {
IThreadSafeISBRH getThreadLocal();
}
@@ -87,7 +87,7 @@ public enum Mixins {
SODIUM(new Builder("Sodium").addTargetedMod(TargetedMod.VANILLA).setSide(Side.CLIENT)
.setPhase(Phase.EARLY).setApplyIf(() -> AngelicaConfig.enableSodium).addMixinClasses(
"sodium.MixinChunkProviderClient"
"sodium.MixinChunkProviderClient"
,"sodium.MixinBlock"
,"sodium.AccessorBiomeColorEvent"
,"sodium.MixinBiomeGenBase"
@@ -113,6 +113,7 @@ public enum Mixins {
,"sodium.MixinTileEntityRendererDispatcher"
,"sodium.MixinLongHashMap"
,"sodium.MixinRender"
,"sodium.MixinRenderingRegistry"
)
),
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.fontrenderer;
import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.mixins.interfaces.FontRendererAccessor;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.texture.TextureManager;
@@ -15,6 +16,7 @@ import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.Random;
@@ -125,12 +127,30 @@ public abstract class MixinFontRenderer implements FontRendererAccessor {
}
/**
* @author eigenraven
* @reason Replace with more sensible batched rendering and optimize some operations
* Only allow using the batched renderer if we are not in an OpenGL Display List
* Batched font renderer is not compatible with display lists, and won't really
* help performance when display lists are already being used anyway.
*/
@Overwrite
public int drawString(String text, int x, int y, int argb, boolean dropShadow)
@Inject(method = "drawString(Ljava/lang/String;IIIZ)I", at = @At("HEAD"), cancellable = true)
public void angelica$BatchedFontRendererDrawString(String text, int x, int y, int argb, boolean dropShadow, CallbackInfoReturnable<Integer> cir)
{
if (GLStateManager.getListMode() == 0) {
cir.setReturnValue(angelica$drawStringBatched(text, x, y, argb, dropShadow));
}
}
/**
* See above explanation about batched renderer in display lists.
*/
@Inject(method = "renderString", at = @At("HEAD"), cancellable = true)
public void angelica$BatchedFontRendererRenderString(String text, int x, int y, int argb, boolean dropShadow, CallbackInfoReturnable<Integer> cir) {
if (GLStateManager.getListMode() == 0) {
cir.setReturnValue(angelica$drawStringBatched(text, x, y, argb, dropShadow));
}
}
@Override
public int angelica$drawStringBatched(String text, int x, int y, int argb, boolean dropShadow) {
if (text == null)
{
return 0;
@@ -158,15 +178,6 @@ public abstract class MixinFontRenderer implements FontRendererAccessor {
}
}
/**
* @author eigenraven
* @reason Replace with more sensible batched rendering and optimize some operations
*/
@Overwrite
public int renderString(String text, int x, int y, int argb, boolean dropShadow) {
return drawString(text, x, y, argb, dropShadow);
}
@Override
public BatchingFontRenderer angelica$getBatcher() {
return angelica$batcher;
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.mixins.early.sodium;
import com.gtnewhorizons.angelica.utils.EventUtils;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraftforge.event.terraingen.BiomeEvent;
import org.spongepowered.asm.mixin.Mixin;
@@ -19,6 +20,7 @@ public class MixinBiomeGenBase {
@Unique
private void prepareEvent(BiomeEvent.BiomeColor event, int defaultColor) {
event.newColor = defaultColor;
EventUtils.clearPhase(event);
((AccessorBiomeColorEvent)event).setOriginalColor(defaultColor);
}
@@ -0,0 +1,32 @@
package com.gtnewhorizons.angelica.mixins.early.sodium;
import com.gtnewhorizons.angelica.interfaces.IThreadSafeISBRH;
import com.gtnewhorizons.angelica.mixins.interfaces.IRenderingRegistryExt;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import cpw.mods.fml.client.registry.RenderingRegistry;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import java.util.Map;
@Mixin(value = RenderingRegistry.class, remap = false)
public class MixinRenderingRegistry implements IRenderingRegistryExt {
@Shadow private Map<Integer, ISimpleBlockRenderingHandler> blockRenderers;
@Override
public ISimpleBlockRenderingHandler getISBRH(int modelId) {
return this.blockRenderers.get(modelId);
}
@WrapOperation(method = { "renderWorldBlock", "renderInventoryBlock", "renderItemAsFull3DBlock" }, at = @At(value="INVOKE", target="Ljava/util/Map;get(Ljava/lang/Object;)Ljava/lang/Object;"))
private Object getWrapped(Map<Integer, ISimpleBlockRenderingHandler> instance, Object modelId, Operation<ISimpleBlockRenderingHandler> original) {
final ISimpleBlockRenderingHandler res = original.call(instance, modelId);
if(res instanceof IThreadSafeISBRH isbhr) {
return isbhr.getThreadLocal();
}
return res;
}
}
@@ -4,6 +4,9 @@ import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer;
import net.minecraft.util.ResourceLocation;
public interface FontRendererAccessor {
int angelica$drawStringBatched(String text, int x, int y, int argb, boolean dropShadow);
BatchingFontRenderer angelica$getBatcher();
void angelica$bindTexture(ResourceLocation location);
@@ -0,0 +1,7 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
public interface IRenderingRegistryExt {
ISimpleBlockRenderingHandler getISBRH(int modelId);
}
@@ -1,5 +1,10 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizons.angelica.interfaces.IThreadSafeISBRH;
import com.gtnewhorizons.angelica.mixins.interfaces.IRenderingRegistryExt;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.versioning.ComparableVersion;
import it.unimi.dsi.fastutil.objects.Reference2BooleanMap;
import it.unimi.dsi.fastutil.objects.Reference2BooleanOpenHashMap;
import net.minecraft.block.Block;
@@ -7,41 +12,45 @@ import net.minecraft.block.Block;
import java.util.concurrent.locks.StampedLock;
public class AngelicaBlockSafetyRegistry {
private static final Reference2BooleanMap<Block> SAFETY_MAP = new Reference2BooleanOpenHashMap<>();
private static final Reference2BooleanMap<Block> BLOCK_SAFETY_MAP = new Reference2BooleanOpenHashMap<>();
private static final Reference2BooleanMap<Block> ISBRH_SAFETY_MAP = new Reference2BooleanOpenHashMap<>();
private static final StampedLock LOCK = new StampedLock();
public static boolean canBlockRenderOffThread(Block block) {
public static boolean canBlockRenderOffThread(Block block, boolean checkISBRH) {
final long stamp = LOCK.readLock();
final Reference2BooleanMap<Block> map = checkISBRH ? ISBRH_SAFETY_MAP : BLOCK_SAFETY_MAP;
boolean isOffThread, shouldPopulate;
try {
isOffThread = SAFETY_MAP.getBoolean(block);
isOffThread = map.getBoolean(block);
if (isOffThread) {
return true; // no need to check if 'false' was due to not being populated
}
shouldPopulate = !SAFETY_MAP.containsKey(block);
shouldPopulate = !map.containsKey(block);
} finally {
LOCK.unlock(stamp);
}
if(shouldPopulate) {
isOffThread = populateCanRenderOffThread(block);
isOffThread = populateCanRenderOffThread(block, map);
}
return isOffThread;
}
private static boolean populateCanRenderOffThread(Block block) {
final boolean canBeOffThread = !(block.getClass().getName().startsWith("gregtech."));
private static boolean populateCanRenderOffThread(Block block, Reference2BooleanMap<Block> map) {
@SuppressWarnings("deprecation")
final boolean canBeOffThread = map == ISBRH_SAFETY_MAP ? ((IRenderingRegistryExt)RenderingRegistry.instance()).getISBRH(block.getRenderType()) instanceof IThreadSafeISBRH : !(block.getClass().getName().startsWith("gregtech."));
final long stamp = LOCK.writeLock();
try {
SAFETY_MAP.put(block, canBeOffThread);
map.put(block, canBeOffThread);
} finally {
LOCK.unlock(stamp);
}
return canBeOffThread;
}
}
@@ -0,0 +1,28 @@
package com.gtnewhorizons.angelica.utils;
import cpw.mods.fml.common.eventhandler.Event;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.relauncher.ReflectionHelper;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
public class EventUtils {
private static final MethodHandle EVENT_PHASE;
static {
try {
EVENT_PHASE = MethodHandles.publicLookup().unreflectSetter(ReflectionHelper.findField(Event.class, "phase"));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static void clearPhase(Event e) {
try {
EVENT_PHASE.invokeExact(e, (EventPriority)null);
} catch(Throwable ex) {
throw new RuntimeException(ex);
}
}
}
@@ -6,6 +6,7 @@ import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.mixins.interfaces.ITexturesCache;
import com.gtnewhorizons.angelica.rendering.AngelicaBlockSafetyRegistry;
import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue;
import it.unimi.dsi.fastutil.longs.LongArrayFIFOQueue;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import me.jellysquid.mods.sodium.client.render.chunk.ChunkGraphicsState;
import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderContainer;
@@ -89,20 +90,21 @@ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkR
private boolean rendersOffThread(Block block) {
final int type = block.getRenderType();
return type < 42 && type != 22 && AngelicaBlockSafetyRegistry.canBlockRenderOffThread(block);
return (type < 42 && type != 22 && AngelicaBlockSafetyRegistry.canBlockRenderOffThread(block, false)) || AngelicaBlockSafetyRegistry.canBlockRenderOffThread(block, true);
}
private void handleRenderBlocksTextures(RenderBlocks rb, ChunkRenderData.Builder builder) {
if(!AngelicaConfig.speedupAnimations || !(rb instanceof ITexturesCache)) return;
for(IIcon texture : ((ITexturesCache)rb).getRenderedTextures()) {
if(texture instanceof TextureAtlasSprite) {
builder.addSprite((TextureAtlasSprite)texture);
if(texture instanceof TextureAtlasSprite textureAtlasSprite) {
builder.addSprite(textureAtlasSprite);
}
}
}
@Override
public ChunkBuildResult<T> performBuild(ChunkRenderCacheLocal cache, ChunkBuildBuffers buffers, CancellationSource cancellationSource) {
// COMPATIBLITY NOTE: Oculus relies on the LVT of this method being unchanged, at least in 16.5
final ChunkRenderData.Builder renderData = new ChunkRenderData.Builder();
final ChunkOcclusionDataBuilder occluder = new ChunkOcclusionDataBuilder();
final ChunkRenderBounds.Builder bounds = new ChunkRenderBounds.Builder();
@@ -118,9 +120,10 @@ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkR
final int baseY = this.render.getOriginY();
final int baseZ = this.render.getOriginZ();
final BlockPos.Mutable pos = new BlockPos.Mutable();
final BlockPos pos = new BlockPos();
final BlockPos renderOffset = this.offset;
final LongArrayFIFOQueue mainThreadBlocks = new LongArrayFIFOQueue();
boolean hasMainThreadBlocks = false;
for (int relY = 0; relY < 16; relY++) {
@@ -158,6 +161,7 @@ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkR
}
}
} else {
mainThreadBlocks.enqueue(pos.asLong());
hasMainThreadBlocks = true;
}
@@ -198,7 +202,7 @@ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkR
if(hasMainThreadBlocks) {
// Render the other blocks on the main thread
try {
CompletableFuture.runAsync(() -> this.performMainBuild(cache, buffers, cancellationSource, bounds, renderData), AngelicaRenderQueue.executor()).get();
CompletableFuture.runAsync(() -> this.performMainBuild(cache, buffers, cancellationSource, bounds, renderData, mainThreadBlocks), AngelicaRenderQueue.executor()).get();
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
return null;
@@ -228,54 +232,51 @@ public class ChunkRenderRebuildTask<T extends ChunkGraphicsState> extends ChunkR
/**
* Render the blocks that should be rendered on the main thread.
*
* TODO: Deduplicate this with the main method above.
*/
private void performMainBuild(ChunkRenderCacheLocal cache, ChunkBuildBuffers buffers, CancellationSource cancellationSource, ChunkRenderBounds.Builder bounds, ChunkRenderData.Builder renderData) {
private void performMainBuild(ChunkRenderCacheLocal cache, ChunkBuildBuffers buffers, CancellationSource cancellationSource, ChunkRenderBounds.Builder bounds, ChunkRenderData.Builder renderData, LongArrayFIFOQueue mainThreadBlocks) {
final WorldSlice slice = cache.getWorldSlice();
final BlockPos.Mutable pos = new BlockPos.Mutable();
final BlockPos pos = new BlockPos();
final int baseX = this.render.getOriginX();
final int baseY = this.render.getOriginY();
final int baseZ = this.render.getOriginZ();
final BlockPos renderOffset = this.offset;
final RenderBlocks rb = new RenderBlocks(slice.getWorld());
for (int relY = 0; relY < 16; relY++) {
while(!mainThreadBlocks.isEmpty()) {
final long longPos = mainThreadBlocks.dequeueLong();
if (cancellationSource.isCancelled()) {
return;
}
for (int relZ = 0; relZ < 16; relZ++) {
for (int relX = 0; relX < 16; relX++) {
final Block block = slice.getBlockRelative(relX + 16, relY + 16, relZ + 16);
pos.set(longPos);
final int relX = pos.getX() - baseX;
final int relY = pos.getY() - baseY;
final int relZ = pos.getZ() - baseZ;
final Block block = slice.getBlockRelative(relX + 16, relY + 16, relZ + 16);
// Only render blocks that need main thread assistance
if (block.getMaterial() == Material.air || rendersOffThread(block)) {
continue;
// Only render blocks that need main thread assistance
if (block.getMaterial() == Material.air || rendersOffThread(block)) {
continue;
}
// TODO: Collect data on which render types are hitting this code path most often so mods can be updated slowly
final int meta = slice.getBlockMetadataRelative(relX + 16, relY + 16, relZ + 16);
buffers.setRenderOffset(pos.x - renderOffset.getX(), pos.y - renderOffset.getY(), pos.z - renderOffset.getZ());
if(AngelicaConfig.enableIris) buffers.iris$setLocalPos(relX, relY, relZ);
// Do regular block rendering
for (BlockRenderPass pass : BlockRenderPass.VALUES) {
if (block.canRenderInPass(pass.ordinal()) && (!AngelicaConfig.enableSodiumFluidRendering || !(block instanceof IFluidBlock))) {
final long seed = MathUtil.hashPos(pos.x, pos.y, pos.z);
if(AngelicaConfig.enableIris) buffers.iris$setMaterialId(block, ExtendedDataHelper.BLOCK_RENDER_TYPE);
if (cache.getBlockRenderer().renderModel(slice.getWorld(), rb, block, meta, pos, buffers.get(pass), true, seed)) {
bounds.addBlock(relX, relY, relZ);
}
// TODO: Collect data on which render types are hitting this code path most often
// so mods can be updated slowly
final int meta = slice.getBlockMetadataRelative(relX + 16, relY + 16, relZ + 16);
pos.set(baseX + relX, baseY + relY, baseZ + relZ);
buffers.setRenderOffset(pos.x - renderOffset.getX(), pos.y - renderOffset.getY(), pos.z - renderOffset.getZ());
if(AngelicaConfig.enableIris) buffers.iris$setLocalPos(relX, relY, relZ);
// Do regular block rendering
for (BlockRenderPass pass : BlockRenderPass.VALUES) {
if (block.canRenderInPass(pass.ordinal()) && (!AngelicaConfig.enableSodiumFluidRendering || !(block instanceof IFluidBlock))) {
final long seed = MathUtil.hashPos(pos.x, pos.y, pos.z);
if(AngelicaConfig.enableIris) buffers.iris$setMaterialId(block, ExtendedDataHelper.BLOCK_RENDER_TYPE);
if (cache.getBlockRenderer().renderModel(slice.getWorld(), rb, block, meta, pos, buffers.get(pass), true, seed)) {
bounds.addBlock(relX, relY, relZ);
}
}
}
if(AngelicaConfig.enableIris) buffers.iris$resetBlockContext();
}
}
if(AngelicaConfig.enableIris) buffers.iris$resetBlockContext();
}
handleRenderBlocksTextures(rb, renderData);
@@ -58,10 +58,11 @@ public class BlockRenderer {
final CapturingTessellator tess = (CapturingTessellator) TessellatorManager.get();
tess.startDrawingQuads();
// RenderBlocks adds the subchunk-relative coordinates as the offset, cancel it out here
tess.setOffset(pos);
tess.setOffset(pos);
renderBlocks.renderBlockByRenderType(block, pos.x, pos.y, pos.z);
final List<Quad> quads = TessellatorManager.stopCapturingToPooledQuads();
tess.resetOffset();
for (ModelQuadFacing facing : ModelQuadFacing.VALUES) {
this.random.setSeed(seed);
@@ -95,6 +95,7 @@ public class FluidRenderer {
int posZ = pos.z;
Fluid fluid = ((IFluidBlock) block).getFluid();
if(fluid == null) return false;
// Check for occluded sides; if everything is occluded, don't render
boolean sfUp = this.isFluidOccluded(world, posX, posY, posZ, ForgeDirection.UP, fluid);
@@ -88,6 +88,8 @@ public class WorldSlice implements IBlockAccess {
@Getter
private ChunkSectionPos origin;
StructureBoundingBox volume;
public static ChunkRenderContext prepare(World world, ChunkSectionPos origin, ClonedChunkSectionCache sectionCache) {
final Chunk chunk = world.getChunkFromChunkCoords(origin.x, origin.z);
final ExtendedBlockStorage section = chunk.getBlockStorageArray()[origin.y];
@@ -156,6 +158,7 @@ public class WorldSlice implements IBlockAccess {
public void copyData(ChunkRenderContext context) {
this.origin = context.getOrigin();
this.sections = context.getSections();
this.volume = context.getVolume();
this.baseX = (this.origin.x - NEIGHBOR_CHUNK_RADIUS) << 4;
this.baseY = (this.origin.y - NEIGHBOR_CHUNK_RADIUS) << 4;
@@ -167,7 +170,7 @@ public class WorldSlice implements IBlockAccess {
for (int z = 0; z < SECTION_LENGTH; z++) {
final int idx = getLocalSectionIndex(x, y, z);
ClonedChunkSection section = this.sections[idx];
final ClonedChunkSection section = this.sections[idx];
this.unpackBlockData(this.blockArrays[idx], this.metadataArrays[idx], section, context.getVolume());
this.biomeData[idx] = section.getBiomeData();
@@ -227,11 +230,15 @@ public class WorldSlice implements IBlockAccess {
@Override
public BiomeGenBase getBiomeGenForCoords(int x, int z) {
if (!blockBoxContains(this.volume, x, volume.minY, z)) {
return BiomeGenBase.plains;
}
final int relX = x - this.baseX;
final int relY = 0;
final int relZ = z - this.baseZ;
BiomeGenBase biome = this.biomeData[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)]
final BiomeGenBase biome = this.biomeData[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)]
[(x & 15) | (z & 15) << 4];
// can be null if biome wasn't generated yet
return biome == null ? BiomeGenBase.plains : biome;
@@ -274,7 +281,7 @@ public class WorldSlice implements IBlockAccess {
}
private void unpackBlockDataR(Block[] blocks, int metas[], ClonedChunkSection section, StructureBoundingBox box) {
ChunkSectionPos pos = section.getPosition();
final ChunkSectionPos pos = section.getPosition();
final int minBlockX = Math.max(box.minX, pos.getMinX());
final int maxBlockX = Math.min(box.maxX, pos.getMaxX());
@@ -306,6 +313,10 @@ public class WorldSlice implements IBlockAccess {
}
public Block getBlock(int x, int y, int z) {
if (!blockBoxContains(this.volume, x, y, z)) {
return Blocks.air;
}
final int relX = x - this.baseX;
final int relY = y - this.baseY;
final int relZ = z - this.baseZ;
@@ -322,6 +333,9 @@ public class WorldSlice implements IBlockAccess {
@Override
public int getBlockMetadata(int x, int y, int z) {
if (!blockBoxContains(this.volume, x, y, z)) {
return 0;
}
final int relX = x - this.baseX;
final int relY = y - this.baseY;
final int relZ = z - this.baseZ;
@@ -331,22 +345,27 @@ public class WorldSlice implements IBlockAccess {
@Override
public TileEntity getTileEntity(int x, int y, int z) {
int relX = x - this.baseX;
int relY = y - this.baseY;
int relZ = z - this.baseZ;
if (!blockBoxContains(this.volume, x, y, z)) {
return null;
}
final int relX = x - this.baseX;
final int relY = y - this.baseY;
final int relZ = z - this.baseZ;
return this.sections[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)].getBlockEntity(relX & 15, relY & 15, relZ & 15);
}
public int getLightLevel(EnumSkyBlock type, int x, int y, int z) {
if (!blockBoxContains(this.volume, x, y, z)) {
return 0;
}
y = MathHelper.clamp_int(y, 0, 255);
int relX = x - this.baseX;
int relY = y - this.baseY;
int relZ = z - this.baseZ;
NibbleArray lightArray = this.lightArrays[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)][type.ordinal()];
final int relX = x - this.baseX;
final int relY = y - this.baseY;
final int relZ = z - this.baseZ;
final NibbleArray lightArray = this.lightArrays[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)][type.ordinal()];
if (lightArray == null) {
// If the array is null, it means the dimension for the current world does not support that light type
return this.defaultLightValues[type.ordinal()];
@@ -385,4 +404,12 @@ public class WorldSlice implements IBlockAccess {
public World getWorld() {
return this.world;
}
private static boolean blockBoxContains(StructureBoundingBox box, int x, int y, int z) {
return x >= box.minX &&
x <= box.maxX &&
y >= box.minY &&
y <= box.maxY &&
z >= box.minZ &&
z <= box.maxZ;
}
}