From 14983449e86dbc38346e73a531d71148da3312fd Mon Sep 17 00:00:00 2001 From: Jason Mitchell Date: Sun, 24 Dec 2023 10:07:13 -0800 Subject: [PATCH] Angelica Support - Static -> Instanced (#14) Static -> Instanced * Now significantly more thread safe --- build.gradle | 30 +- gradle.properties | 10 +- .../lib/asm/ClassConstantPoolParser.java | 109 ++++++ .../java/codechicken/lib/asm/ObfMapping.java | 8 +- .../lib/asm/RedirectorTransformer.java | 207 +++++++++++ .../java/codechicken/lib/gui/Canvas9Seg.java | 12 +- .../codechicken/lib/lighting/LightMatrix.java | 16 +- .../codechicken/lib/lighting/LightModel.java | 12 +- .../lib/lighting/PlanarLightMatrix.java | 10 +- .../lib/lighting/PlanarLightModel.java | 12 +- .../lib/lighting/SimpleBrightnessModel.java | 12 +- .../codechicken/lib/render/BlockRenderer.java | 40 ++- .../java/codechicken/lib/render/CCModel.java | 35 +- .../lib/render/CCRenderPipeline.java | 53 ++- .../codechicken/lib/render/CCRenderState.java | 322 ++++++++++++------ .../lib/render/ColourMultiplier.java | 14 +- .../codechicken/lib/render/RenderUtils.java | 42 ++- .../lib/render/uv/UVTransformation.java | 6 +- .../java/codechicken/lib/vec/BlockCoord.java | 18 +- .../codechicken/lib/vec/Transformation.java | 10 +- 20 files changed, 742 insertions(+), 236 deletions(-) create mode 100644 src/main/java/codechicken/lib/asm/ClassConstantPoolParser.java create mode 100644 src/main/java/codechicken/lib/asm/RedirectorTransformer.java diff --git a/build.gradle b/build.gradle index 4e31dc8..bdbaeb9 100644 --- a/build.gradle +++ b/build.gradle @@ -1,4 +1,4 @@ -//version: 1700844281 +//version: 1702141377 /* DO NOT CHANGE THIS FILE! Also, you may replace this file at any time if there is an update available. @@ -28,27 +28,12 @@ import java.util.concurrent.TimeUnit buildscript { repositories { - mavenCentral() - - maven { - name 'forge' - url 'https://maven.minecraftforge.net' - } maven { // GTNH RetroFuturaGradle and ASM Fork name "GTNH Maven" url "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" allowInsecureProtocol = true } - maven { - name 'sonatype' - url 'https://oss.sonatype.org/content/repositories/snapshots/' - } - maven { - name 'Scala CI dependencies' - url 'https://repo1.maven.org/maven2/' - } - mavenLocal() } } @@ -69,7 +54,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.24' + id 'com.gtnewhorizons.retrofuturagradle' version '1.3.26' } print("You might want to check out './gradlew :faq' if your build fails.\n") @@ -628,7 +613,7 @@ repositories { } maven { name = "ic2" - url = getURL("https://maven.ic2.player.to/", "https://maven2.ic2.player.to/") + url = getURL("https://maven2.ic2.player.to/", "https://maven.ic2.player.to/") content { includeGroup "net.industrial-craft" } @@ -687,6 +672,8 @@ configurations.all { substitute module('com.github.GTNewHorizons:SpongePoweredMixin') using module(mixinProviderSpecNoClassifer) withClassifier("dev") because("Unimixins replaces other mixin mods") substitute module('com.github.GTNewHorizons:SpongeMixins') using module(mixinProviderSpecNoClassifer) withClassifier("dev") because("Unimixins replaces other mixin mods") substitute module('io.github.legacymoddingmc:unimixins') using module(mixinProviderSpecNoClassifer) withClassifier("dev") because("Our previous unimixins upload was missing the dev classifier") + + substitute module('org.scala-lang:scala-library:2.11.1') using module('org.scala-lang:scala-library:2.11.5') because('To allow mixing with Java 8 targets') } } @@ -793,12 +780,12 @@ ext.java17PatchDependenciesCfg = configurations.create("java17PatchDependencies" } dependencies { - def lwjgl3ifyVersion = '1.5.1' + def lwjgl3ifyVersion = '1.5.7' if (modId != 'lwjgl3ify') { java17Dependencies("com.github.GTNewHorizons:lwjgl3ify:${lwjgl3ifyVersion}") } if (modId != 'hodgepodge') { - java17Dependencies('com.github.GTNewHorizons:Hodgepodge:2.3.17') + java17Dependencies('com.github.GTNewHorizons:Hodgepodge:2.3.35') } java17PatchDependencies("com.github.GTNewHorizons:lwjgl3ify:${lwjgl3ifyVersion}:forgePatches") {transitive = false} @@ -1310,7 +1297,7 @@ def addCurseForgeRelation(String type, String name) { // Updating -def buildscriptGradleVersion = "8.2.1" +def buildscriptGradleVersion = "8.5" tasks.named('wrapper', Wrapper).configure { gradleVersion = buildscriptGradleVersion @@ -1621,3 +1608,4 @@ if (file('addon.late.local.gradle.kts').exists()) { } else if (file('addon.late.local.gradle').exists()) { apply from: 'addon.late.local.gradle' } + diff --git a/gradle.properties b/gradle.properties index 1c509df..24279a2 100644 --- a/gradle.properties +++ b/gradle.properties @@ -21,6 +21,15 @@ forgeVersion = 10.13.4.1614 # Do you need to test how your custom blocks interacts with a player that is not the owner? -> leave name empty developmentEnvironmentUserName = Developer +# Enables using modern java syntax (up to version 17) via Jabel, while still targetting JVM 8. +# See https://github.com/bsideup/jabel for details on how this works. +enableModernJavaSyntax = true + +# Enables injecting missing generics into the decompiled source code for a better coding experience +# Turns most publically visible List, Map, etc. into proper List, Map types +enableGenericInjection = true + + # Define a source file of your project with: # public static final String VERSION = "GRADLETOKEN_VERSION"; # The string's content will be replaced with your mod's version when compiled. You should use this to specify your mod's @@ -87,4 +96,3 @@ modrinthProjectId = codechickenlib-unofficial # and the name is the Modrinth project or version slug/id of the other mod. # modrinthRelations = - diff --git a/src/main/java/codechicken/lib/asm/ClassConstantPoolParser.java b/src/main/java/codechicken/lib/asm/ClassConstantPoolParser.java new file mode 100644 index 0000000..299e185 --- /dev/null +++ b/src/main/java/codechicken/lib/asm/ClassConstantPoolParser.java @@ -0,0 +1,109 @@ +package codechicken.lib.asm; + +/*** + * This Class is derived from the ASM ClassReader + *

+ * ASM: a very small and fast Java bytecode manipulation framework Copyright (c) 2000-2011 INRIA, France Telecom All + * rights reserved. + *

+ * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation and/or other materials provided with the + * distribution. 3. Neither the name of the copyright holders nor the names of its contributors may be used to endorse + * or promote products derived from this software without specific prior written permission. + *

+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.nio.charset.StandardCharsets; + +import org.objectweb.asm.Opcodes; + +/** + * Using this class to search for a (single) String reference is > 40 times faster than parsing a class with a + * ClassReader + ClassNode while using way less RAM + */ +public class ClassConstantPoolParser { + + private static final int UTF8 = 1; + private static final int INT = 3; + private static final int FLOAT = 4; + private static final int LONG = 5; + private static final int DOUBLE = 6; + private static final int FIELD = 9; + private static final int METH = 10; + private static final int IMETH = 11; + private static final int NAME_TYPE = 12; + private static final int HANDLE = 15; + private static final int INDY = 18; + + private final byte[][] BYTES_TO_SEARCH; + + public ClassConstantPoolParser(String... strings) { + BYTES_TO_SEARCH = new byte[strings.length][]; + for (int i = 0; i < BYTES_TO_SEARCH.length; i++) { + BYTES_TO_SEARCH[i] = strings[i].getBytes(StandardCharsets.UTF_8); + } + } + + /** + * Returns true if the constant pool of the class represented by this byte array contains one of the Strings we are + * looking for + */ + public boolean find(byte[] basicClass) { + if (basicClass == null || basicClass.length == 0) { + return false; + } + // checks the class version + if (readShort(6, basicClass) > Opcodes.V1_8) { + return false; + } + // parses the constant pool + int n = readUnsignedShort(8, basicClass); + int index = 10; + for (int i = 1; i < n; ++i) { + int size; + switch (basicClass[index]) { + case FIELD, METH, IMETH, INT, FLOAT, NAME_TYPE, INDY -> size = 5; + case LONG, DOUBLE -> { + size = 9; + ++i; + } + case UTF8 -> { + final int strLen = readUnsignedShort(index + 1, basicClass); + size = 3 + strLen; + label: for (byte[] bytes : BYTES_TO_SEARCH) { + if (strLen == bytes.length) { + for (int j = index + 3; j < index + 3 + strLen; j++) { + if (basicClass[j] != bytes[j - (index + 3)]) { + break label; + } + } + return true; + } + } + } + case HANDLE -> size = 4; + default -> size = 3; + } + index += size; + } + return false; + } + + private static short readShort(final int index, byte[] basicClass) { + return (short) (((basicClass[index] & 0xFF) << 8) | (basicClass[index + 1] & 0xFF)); + } + + private static int readUnsignedShort(final int index, byte[] basicClass) { + return ((basicClass[index] & 0xFF) << 8) | (basicClass[index + 1] & 0xFF); + } + +} diff --git a/src/main/java/codechicken/lib/asm/ObfMapping.java b/src/main/java/codechicken/lib/asm/ObfMapping.java index f8ccb92..27ca913 100644 --- a/src/main/java/codechicken/lib/asm/ObfMapping.java +++ b/src/main/java/codechicken/lib/asm/ObfMapping.java @@ -36,8 +36,8 @@ public class ObfMapping { public static class ObfRemapper extends Remapper { - private HashMap fields = new HashMap(); - private HashMap funcs = new HashMap(); + private final HashMap fields = new HashMap<>(); + private final HashMap funcs = new HashMap<>(); public ObfRemapper() { try { @@ -174,8 +174,8 @@ public class ObfMapping { return new File[] { srgs, methods, fields }; } - private HashMap fields = new HashMap(); - private HashMap funcs = new HashMap(); + private final HashMap fields = new HashMap<>(); + private final HashMap funcs = new HashMap<>(); public MCPRemapper() { File[] mappings = getConfFiles(); diff --git a/src/main/java/codechicken/lib/asm/RedirectorTransformer.java b/src/main/java/codechicken/lib/asm/RedirectorTransformer.java new file mode 100644 index 0000000..0d9d107 --- /dev/null +++ b/src/main/java/codechicken/lib/asm/RedirectorTransformer.java @@ -0,0 +1,207 @@ +package codechicken.lib.asm; + +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import net.minecraft.launchwrapper.IClassTransformer; +import net.minecraft.launchwrapper.Launch; + +import org.apache.commons.io.FileUtils; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.util.ASMifier; +import org.objectweb.asm.util.Textifier; +import org.objectweb.asm.util.TraceClassVisitor; + +public class RedirectorTransformer implements IClassTransformer { + + private static final boolean DUMP_CLASSES = Boolean.parseBoolean(System.getProperty("ccl.dumpClass", "false")); + private static final String RenderStateClass = "codechicken/lib/render/CCRenderState"; + private static final Set redirectedFields = new HashSet<>(); + private static final Set redirectedSimpleMethods = new HashSet<>(); + private static final Set redirectedMethods = new HashSet<>(); + private static final ClassConstantPoolParser cstPoolParser; + + static { + Collections.addAll( + redirectedFields, + "pipeline", + "model", + "firstVertexIndex", + "lastVertexIndex", + "vertexIndex", + "baseColour", + "alphaOverride", + "useNormals", + "computeLighting", + "useColour", + "lightMatrix", + "vert", + "hasNormal", + "normal", + "hasColour", + "colour", + "hasBrightness", + "brightness", + "side", + "lc" + + ); + Collections.addAll(redirectedSimpleMethods, "reset", "pullLightmap", "pushLightmap", "setDynamic", "draw"); + Collections.addAll( + redirectedMethods, + "setPipeline", + "bindModel", + "setModel", + "setVertexRange", + "render", + "runPipeline", + "writeVert", + "setNormal", + "setColour", + "setBrightness", + "startDrawing"); + + cstPoolParser = new ClassConstantPoolParser(RenderStateClass); + } + + @Override + public byte[] transform(String name, String transformedName, byte[] basicClass) { + if (!cstPoolParser.find(basicClass)) { + return basicClass; + } + + final ClassReader cr = new ClassReader(basicClass); + final ClassNode cn = new ClassNode(); + cr.accept(cn, 0); + boolean changed = false; + + for (MethodNode mn : cn.methods) { + for (AbstractInsnNode node : mn.instructions.toArray()) { + if (node instanceof FieldInsnNode fNode) { + if (node.getOpcode() == Opcodes.GETSTATIC && redirectedFields.contains(fNode.name) + && fNode.owner.equals(RenderStateClass)) { + mn.instructions.insertBefore( + fNode, + new MethodInsnNode( + Opcodes.INVOKESTATIC, + fNode.owner, + "instance", + "()Lcodechicken/lib/render/CCRenderState;")); + fNode.setOpcode(Opcodes.GETFIELD); + changed = true; + } else if (node.getOpcode() == Opcodes.PUTSTATIC + && (redirectedFields.contains(fNode.name) && fNode.owner.equals(RenderStateClass))) { + InsnList beforePut = new InsnList(); + beforePut.add( + new MethodInsnNode( + Opcodes.INVOKESTATIC, + fNode.owner, + "instance", + "()Lcodechicken/lib/render/CCRenderState;")); + beforePut.add(new InsnNode(Opcodes.SWAP)); + mn.instructions.insertBefore(fNode, beforePut); + fNode.setOpcode(Opcodes.PUTFIELD); + changed = true; + + } + } else if (node.getOpcode() == Opcodes.INVOKESTATIC && node instanceof MethodInsnNode mNode) { + if (redirectedMethods.contains(mNode.name) && mNode.owner.equals(RenderStateClass)) { + mNode.name = mNode.name + "Static"; + changed = true; + } else if (redirectedSimpleMethods.contains(mNode.name) && mNode.owner.equals(RenderStateClass)) { + mn.instructions.insertBefore( + mNode, + new MethodInsnNode( + Opcodes.INVOKESTATIC, + mNode.owner, + "instance", + "()Lcodechicken/lib/render/CCRenderState;")); + mNode.setOpcode(Opcodes.INVOKEVIRTUAL); + changed = true; + } + } + } + } + + if (changed) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cn.accept(cw); + final byte[] bytes = cw.toByteArray(); + if (DUMP_CLASSES) { + saveTransformedClass(bytes, transformedName); + saveTransformedClass(basicClass, transformedName + "_original"); + } + return bytes; + } + return basicClass; + } + + private File outputDir = null; + + private void saveTransformedClass(final byte[] data, final String transformedName) { + if (!DUMP_CLASSES) { + return; + } + + if (outputDir == null) { + outputDir = new File(Launch.minecraftHome, "ASM_REDIRECTOR"); + try { + FileUtils.deleteDirectory(outputDir); + } catch (IOException ignored) {} + if (!outputDir.exists()) { + // noinspection ResultOfMethodCallIgnored + outputDir.mkdirs(); + } + } + + final String fileName = transformedName.replace('.', File.separatorChar); + final File classFile = new File(outputDir, fileName + ".class"); + final File bytecodeFile = new File(outputDir, fileName + "_BYTE.txt"); + final File asmifiedFile = new File(outputDir, fileName + "_ASM.txt"); + final File outDir = classFile.getParentFile(); + if (!outDir.exists()) { + outDir.mkdirs(); + } + if (classFile.exists()) { + classFile.delete(); + } + try (final OutputStream output = Files.newOutputStream(classFile.toPath())) { + output.write(data); + } catch (IOException e) { + e.printStackTrace(); + } + if (bytecodeFile.exists()) { + bytecodeFile.delete(); + } + try (final OutputStream output = Files.newOutputStream(bytecodeFile.toPath())) { + final ClassReader classReader = new ClassReader(data); + classReader.accept(new TraceClassVisitor(null, new Textifier(), new PrintWriter(output)), 0); + } catch (IOException e) { + e.printStackTrace(); + } + if (asmifiedFile.exists()) { + asmifiedFile.delete(); + } + try (final OutputStream output = Files.newOutputStream(asmifiedFile.toPath())) { + final ClassReader classReader = new ClassReader(data); + classReader.accept(new TraceClassVisitor(null, new ASMifier(), new PrintWriter(output)), 0); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/codechicken/lib/gui/Canvas9Seg.java b/src/main/java/codechicken/lib/gui/Canvas9Seg.java index 4c16368..15b3f22 100644 --- a/src/main/java/codechicken/lib/gui/Canvas9Seg.java +++ b/src/main/java/codechicken/lib/gui/Canvas9Seg.java @@ -62,16 +62,20 @@ public class Canvas9Seg { t.addVertexWithUV(sw[u + 1], sh[v], 0, seg_u[u + 1], seg_v[v]); } - public void draw(int x, int y, int w, int h) { + public void draw(CCRenderState state, int x, int y, int w, int h) { CCRenderState.changeTexture(tex); - CCRenderState.reset(); - CCRenderState.startDrawing(); + state.reset(); + state.startDrawing(); int[] sw = new int[] { x, x + seg_w[0], x + w - seg_w[2], x + w }; int[] sh = new int[] { y, y + seg_h[0], y + h - seg_h[2], y + h }; for (int seg = 0; seg < 9; seg++) drawSeg(sw, sh, seg); - CCRenderState.draw(); + state.draw(); + } + + public void draw(int x, int y, int w, int h) { + draw(CCRenderState.instance(), x, y, w, h); } } diff --git a/src/main/java/codechicken/lib/lighting/LightMatrix.java b/src/main/java/codechicken/lib/lighting/LightMatrix.java index 59f2e7a..d6fe986 100644 --- a/src/main/java/codechicken/lib/lighting/LightMatrix.java +++ b/src/main/java/codechicken/lib/lighting/LightMatrix.java @@ -114,22 +114,22 @@ public class LightMatrix implements CCRenderState.IVertexOperation { } @Override - public boolean load() { - if (!CCRenderState.computeLighting) return false; + public boolean load(CCRenderState state) { + if (!state.computeLighting) return false; - CCRenderState.pipeline.addDependency(CCRenderState.colourAttrib); - CCRenderState.pipeline.addDependency(CCRenderState.lightCoordAttrib); + state.pipeline.addDependency(state.colourAttrib); + state.pipeline.addDependency(state.lightCoordAttrib); return true; } @Override - public void operate() { - LC lc = CCRenderState.lc; + public void operate(CCRenderState state) { + LC lc = state.lc; float[] a = ao(lc.side); float f = (a[0] * lc.fa + a[1] * lc.fb + a[2] * lc.fc + a[3] * lc.fd); int[] b = brightness(lc.side); - CCRenderState.setColour(ColourRGBA.multiplyC(CCRenderState.colour, f)); - CCRenderState.setBrightness((int) (b[0] * lc.fa + b[1] * lc.fb + b[2] * lc.fc + b[3] * lc.fd) & 0xFF00FF); + state.setColour(ColourRGBA.multiplyC(state.colour, f)); + state.setBrightness((int) (b[0] * lc.fa + b[1] * lc.fb + b[2] * lc.fc + b[3] * lc.fd) & 0xFF00FF); } @Override diff --git a/src/main/java/codechicken/lib/lighting/LightModel.java b/src/main/java/codechicken/lib/lighting/LightModel.java index 6134fe1..8766737 100644 --- a/src/main/java/codechicken/lib/lighting/LightModel.java +++ b/src/main/java/codechicken/lib/lighting/LightModel.java @@ -78,17 +78,17 @@ public class LightModel implements CCRenderState.IVertexOperation { } @Override - public boolean load() { - if (!CCRenderState.computeLighting) return false; + public boolean load(CCRenderState state) { + if (!state.computeLighting) return false; - CCRenderState.pipeline.addDependency(CCRenderState.normalAttrib); - CCRenderState.pipeline.addDependency(CCRenderState.colourAttrib); + state.pipeline.addDependency(CCRenderState.normalAttrib); + state.pipeline.addDependency(CCRenderState.colourAttrib); return true; } @Override - public void operate() { - CCRenderState.setColour(apply(CCRenderState.colour, CCRenderState.normal)); + public void operate(CCRenderState state) { + state.setColour(apply(state.colour, state.normal)); } @Override diff --git a/src/main/java/codechicken/lib/lighting/PlanarLightMatrix.java b/src/main/java/codechicken/lib/lighting/PlanarLightMatrix.java index cbbcb17..798d382 100644 --- a/src/main/java/codechicken/lib/lighting/PlanarLightMatrix.java +++ b/src/main/java/codechicken/lib/lighting/PlanarLightMatrix.java @@ -39,15 +39,15 @@ public class PlanarLightMatrix extends PlanarLightModel { } @Override - public boolean load() { - CCRenderState.pipeline.addDependency(CCRenderState.sideAttrib); + public boolean load(CCRenderState state) { + state.pipeline.addDependency(CCRenderState.sideAttrib); return true; } @Override - public void operate() { - super.operate(); - CCRenderState.setBrightness(brightness(CCRenderState.side)); + public void operate(CCRenderState state) { + super.operate(state); + state.setBrightness(brightness(state.side)); } @Override diff --git a/src/main/java/codechicken/lib/lighting/PlanarLightModel.java b/src/main/java/codechicken/lib/lighting/PlanarLightModel.java index f745373..280d962 100644 --- a/src/main/java/codechicken/lib/lighting/PlanarLightModel.java +++ b/src/main/java/codechicken/lib/lighting/PlanarLightModel.java @@ -17,17 +17,17 @@ public class PlanarLightModel implements CCRenderState.IVertexOperation { } @Override - public boolean load() { - if (!CCRenderState.computeLighting) return false; + public boolean load(CCRenderState state) { + if (!state.computeLighting) return false; - CCRenderState.pipeline.addDependency(CCRenderState.sideAttrib); - CCRenderState.pipeline.addDependency(CCRenderState.colourAttrib); + state.pipeline.addDependency(CCRenderState.sideAttrib); + state.pipeline.addDependency(CCRenderState.colourAttrib); return true; } @Override - public void operate() { - CCRenderState.setColour(ColourRGBA.multiply(CCRenderState.colour, colours[CCRenderState.side])); + public void operate(CCRenderState state) { + state.setColour(ColourRGBA.multiply(state.colour, colours[state.side])); } @Override diff --git a/src/main/java/codechicken/lib/lighting/SimpleBrightnessModel.java b/src/main/java/codechicken/lib/lighting/SimpleBrightnessModel.java index 7158594..c557993 100644 --- a/src/main/java/codechicken/lib/lighting/SimpleBrightnessModel.java +++ b/src/main/java/codechicken/lib/lighting/SimpleBrightnessModel.java @@ -18,8 +18,8 @@ public class SimpleBrightnessModel implements CCRenderState.IVertexOperation { public BlockCoord pos = new BlockCoord(); private int sampled = 0; - private int[] samples = new int[6]; - private BlockCoord c = new BlockCoord(); + private final int[] samples = new int[6]; + private final BlockCoord c = new BlockCoord(); public void locate(IBlockAccess a, int x, int y, int z) { access = a; @@ -39,14 +39,14 @@ public class SimpleBrightnessModel implements CCRenderState.IVertexOperation { } @Override - public boolean load() { - CCRenderState.pipeline.addDependency(CCRenderState.sideAttrib); + public boolean load(CCRenderState state) { + state.pipeline.addDependency(CCRenderState.sideAttrib); return true; } @Override - public void operate() { - CCRenderState.setBrightness(sample(CCRenderState.side)); + public void operate(CCRenderState state) { + state.setBrightness(sample(state.side)); } @Override diff --git a/src/main/java/codechicken/lib/render/BlockRenderer.java b/src/main/java/codechicken/lib/render/BlockRenderer.java index 3c2ef39..09f7a8b 100644 --- a/src/main/java/codechicken/lib/render/BlockRenderer.java +++ b/src/main/java/codechicken/lib/render/BlockRenderer.java @@ -29,8 +29,8 @@ public class BlockRenderer { } @Override - public void prepareVertex() { - CCRenderState.side = side; + public void prepareVertex(CCRenderState state) { + state.side = side; } public BlockFace computeLightCoords() { @@ -145,16 +145,21 @@ public class BlockRenderer { } @Override - public void prepareVertex() { - CCRenderState.side = CCRenderState.vertexIndex >> 2; + public void prepareVertex(CCRenderState state) { + state.side = state.vertexIndex >> 2; } } public static FullBlock fullBlock = new FullBlock(); + // public static void renderFullBlock(int sideMask) { + public static void renderFullBlock(CCRenderState state, int sideMask) { + state.setModel(fullBlock); + renderFaces(state, sideMask); + } + public static void renderFullBlock(int sideMask) { - CCRenderState.setModel(fullBlock); - renderFaces(sideMask); + renderFullBlock(CCRenderState.instance(), sideMask); } /** @@ -162,15 +167,20 @@ public class BlockRenderer { * * @param sideMask A mask of faces not to render */ - public static void renderFaces(int sideMask) { + // public static void renderFaces(int sideMask) { + public static void renderFaces(CCRenderState state, int sideMask) { if (sideMask == 0x3F) return; for (int s = 0; s < 6; s++) if ((sideMask & 1 << s) == 0) { - CCRenderState.setVertexRange(s * 4, (s + 1) * 4); - CCRenderState.render(); + state.setVertexRange(s * 4, (s + 1) * 4); + state.render(); } } - private static BlockFace face = new BlockFace(); + public static void renderFaces(int sideMask) { + renderFaces(CCRenderState.instance(), sideMask); + } + + private static final BlockFace face = new BlockFace(); /** * Renders faces of a cuboid with texture coordinates mapped to match a standard minecraft block @@ -178,13 +188,17 @@ public class BlockRenderer { * @param bounds The bounding cuboid to render * @param sideMask A mask of faces not to render */ - public static void renderCuboid(Cuboid6 bounds, int sideMask) { + public static void renderCuboid(CCRenderState state, Cuboid6 bounds, int sideMask) { if (sideMask == 0x3F) return; - CCRenderState.setModel(face); + state.setModel(face); for (int s = 0; s < 6; s++) if ((sideMask & 1 << s) == 0) { face.loadCuboidFace(bounds, s); - CCRenderState.render(); + state.render(); } } + + public static void renderCuboid(Cuboid6 bounds, int sideMask) { + renderCuboid(CCRenderState.instance(), bounds, sideMask); + } } diff --git a/src/main/java/codechicken/lib/render/CCModel.java b/src/main/java/codechicken/lib/render/CCModel.java index 649045c..b9a5e4b 100644 --- a/src/main/java/codechicken/lib/render/CCModel.java +++ b/src/main/java/codechicken/lib/render/CCModel.java @@ -32,6 +32,7 @@ import codechicken.lib.vec.Transformation; import codechicken.lib.vec.TransformationList; import codechicken.lib.vec.Vector3; +@SuppressWarnings("ForLoopReplaceableByForEach") public class CCModel implements CCRenderState.IVertexSource, Copyable { private static class PositionNormalEntry { @@ -88,7 +89,7 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable { } @Override - public void prepareVertex() {} + public void prepareVertex(CCRenderState state) {} public T getOrAllocate(CCRenderState.VertexAttribute attrib) { T array = getAttributes(attrib); @@ -426,20 +427,36 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable { return this; } + public void render(CCRenderState state, double x, double y, double z, double u, double v) { + render(state, new Vector3(x, y, z).translation(), new UVTranslation(u, v)); + } + public void render(double x, double y, double z, double u, double v) { - render(new Vector3(x, y, z).translation(), new UVTranslation(u, v)); + render(CCRenderState.instance(), new Vector3(x, y, z).translation(), new UVTranslation(u, v)); + } + + public void render(CCRenderState state, double x, double y, double z, UVTransformation u) { + render(state, new Vector3(x, y, z).translation(), u); } public void render(double x, double y, double z, UVTransformation u) { - render(new Vector3(x, y, z).translation(), u); + render(CCRenderState.instance(), new Vector3(x, y, z).translation(), u); + } + + public void render(CCRenderState state, Transformation t, double u, double v) { + render(state, t, new UVTranslation(u, v)); } public void render(Transformation t, double u, double v) { - render(t, new UVTranslation(u, v)); + render(CCRenderState.instance(), t, new UVTranslation(u, v)); + } + + public void render(CCRenderState state, CCRenderState.IVertexOperation... ops) { + render(state, 0, verts.length, ops); } public void render(CCRenderState.IVertexOperation... ops) { - render(0, verts.length, ops); + render(CCRenderState.instance(), 0, verts.length, ops); } /** @@ -449,9 +466,13 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable { * @param end The vertex index to render until * @param ops Operations to apply */ + public void render(CCRenderState state, int start, int end, CCRenderState.IVertexOperation... ops) { + state.setPipeline(this, start, end, ops); + state.render(); + } + public void render(int start, int end, CCRenderState.IVertexOperation... ops) { - CCRenderState.setPipeline(this, start, end, ops); - CCRenderState.render(); + render(CCRenderState.instance(), start, end, ops); } public static CCModel quadModel(int numVerts) { diff --git a/src/main/java/codechicken/lib/render/CCRenderPipeline.java b/src/main/java/codechicken/lib/render/CCRenderPipeline.java index 5e7113d..9d9d521 100644 --- a/src/main/java/codechicken/lib/render/CCRenderPipeline.java +++ b/src/main/java/codechicken/lib/render/CCRenderPipeline.java @@ -1,21 +1,45 @@ package codechicken.lib.render; import java.util.ArrayList; +import java.util.Collections; import codechicken.lib.render.CCRenderState.IVertexOperation; import codechicken.lib.render.CCRenderState.VertexAttribute; +@SuppressWarnings("ForLoopReplaceableByForEach") public class CCRenderPipeline { + private final CCRenderState renderState; + private final PipelineBuilder builder; + + public CCRenderPipeline(CCRenderState renderState) { + this.renderState = renderState; + builder = new PipelineBuilder(renderState); + } + + public CCRenderPipeline() { + this(CCRenderState.instance()); + } + public class PipelineBuilder { + private final CCRenderState renderState; + + public PipelineBuilder(CCRenderState renderState) { + this.renderState = renderState; + } + + public PipelineBuilder() { + this(CCRenderState.instance()); + } + public PipelineBuilder add(IVertexOperation op) { ops.add(op); return this; } public PipelineBuilder add(IVertexOperation... ops) { - for (int i = 0; i < ops.length; i++) CCRenderPipeline.this.ops.add(ops[i]); + Collections.addAll(CCRenderPipeline.this.ops, ops); return this; } @@ -25,13 +49,13 @@ public class CCRenderPipeline { public void render() { rebuild(); - CCRenderState.render(); + renderState.render(); } } private class PipelineNode { - public ArrayList deps = new ArrayList(); + public ArrayList deps = new ArrayList<>(); public IVertexOperation op; public void add() { @@ -44,12 +68,11 @@ public class CCRenderPipeline { } } - private ArrayList attribs = new ArrayList(); - private ArrayList ops = new ArrayList(); - private ArrayList nodes = new ArrayList(); - private ArrayList sorted = new ArrayList(); + private final ArrayList attribs = new ArrayList<>(); + private final ArrayList ops = new ArrayList<>(); + private final ArrayList nodes = new ArrayList<>(); + private final ArrayList sorted = new ArrayList<>(); private PipelineNode loading; - private PipelineBuilder builder = new PipelineBuilder(); public void setPipeline(IVertexOperation... ops) { this.ops.clear(); @@ -69,20 +92,20 @@ public class CCRenderPipeline { } public void rebuild() { - if (ops.isEmpty() || CCRenderState.model == null) return; + if (ops.isEmpty() || this.renderState.model == null) return; // ensure enough nodes for all ops - while (nodes.size() < CCRenderState.operationCount()) nodes.add(new PipelineNode()); + while (nodes.size() < this.renderState.operationCount()) nodes.add(new PipelineNode()); unbuild(); - if (CCRenderState.useNormals) addAttribute(CCRenderState.normalAttrib); - if (CCRenderState.useColour) addAttribute(CCRenderState.colourAttrib); - if (CCRenderState.computeLighting) addAttribute(CCRenderState.lightingAttrib); + if (this.renderState.useNormals) addAttribute(this.renderState.normalAttrib); + if (this.renderState.useColour) addAttribute(this.renderState.colourAttrib); + if (this.renderState.computeLighting) addAttribute(this.renderState.lightingAttrib); for (int i = 0; i < ops.size(); i++) { IVertexOperation op = ops.get(i); loading = nodes.get(op.operationID()); - boolean loaded = op.load(); + boolean loaded = op.load(renderState); if (loaded) loading.op = op; if (op instanceof VertexAttribute) if (loaded) attribs.add((VertexAttribute) op); @@ -109,7 +132,7 @@ public class CCRenderPipeline { } public void operate() { - for (int i = 0; i < sorted.size(); i++) sorted.get(i).operate(); + for (int i = 0; i < sorted.size(); i++) sorted.get(i).operate(renderState); } public PipelineBuilder builder() { diff --git a/src/main/java/codechicken/lib/render/CCRenderState.java b/src/main/java/codechicken/lib/render/CCRenderState.java index 9f110e3..39655f0 100644 --- a/src/main/java/codechicken/lib/render/CCRenderState.java +++ b/src/main/java/codechicken/lib/render/CCRenderState.java @@ -17,11 +17,27 @@ import codechicken.lib.vec.Transformation; import codechicken.lib.vec.Vector3; /** - * The core of the CodeChickenLib render system. Rendering operations are written to avoid object allocations by reusing - * static variables. + * The core of the CodeChickenLib render system. Where possible assign a local var of CCRenderState to avoid millions of + * calls to instance(); Uses a ThreadLocal system to assign each thread their own CCRenderState so we can use it in + * Multithreaded chunk batching. + *

+ * Backported from CCL - 1.16.x */ + public class CCRenderState { + public final CCRenderPipeline pipeline; + + private static final ThreadLocal instances = ThreadLocal.withInitial(CCRenderState::new); + + private CCRenderState() { + pipeline = new CCRenderPipeline(this); + } + + public static CCRenderState instance() { + return instances.get(); + } + private static int nextOperationIndex; public static int registerOperation() { @@ -35,28 +51,43 @@ public class CCRenderState { /** * Represents an operation to be run for each vertex that operates on and modifies the current state */ - public static interface IVertexOperation { + public interface IVertexOperation { /** * Load any required references and add dependencies to the pipeline based on the current model (may be null) * Return false if this operation is redundant in the pipeline with the given model */ - public boolean load(); + default boolean load() { + // Existing code will will override this method so it shouldn't infinite loop + // Default it only for new state aware code + return load(CCRenderState.instance()); + } + + default boolean load(CCRenderState state) { + // New code will override this and not inplement load() so we shouldn't infinite loop + return load(); + } /** * Perform the operation on the current render state */ - public void operate(); + default void operate() { + operate(CCRenderState.instance()); + } + + default void operate(CCRenderState state) { + operate(); + } /** * Get the unique id representing this type of operation. Duplicate operation IDs within the pipeline may have * unexpected results. ID shoulld be obtained from CCRenderState.registerOperation() and stored in a static * variable */ - public int operationID(); + int operationID(); } - private static ArrayList> vertexAttributes = new ArrayList>(); + private static ArrayList> vertexAttributes = new ArrayList<>(); private static int registerVertexAttribute(VertexAttribute attr) { vertexAttributes.add(attr); @@ -109,9 +140,9 @@ public class CCRenderState { return dst; } - public static interface IVertexSource { + public interface IVertexSource { - public Vertex5[] getVertices(); + Vertex5[] getVertices(); /** * Gets an array of vertex attrutes @@ -120,21 +151,25 @@ public class CCRenderState { * @param The attrute array type * @return An array, or null if not computed */ - public T getAttributes(VertexAttribute attr); + T getAttributes(VertexAttribute attr); /** * @return True if the specified attrute is provided by this model, either by returning an array from * getAttributes or by setting the state in prepareVertex */ - public boolean hasAttribute(VertexAttribute attr); + boolean hasAttribute(VertexAttribute attr); /** * Callback to set CCRenderState for a vertex before the pipeline runs */ - public void prepareVertex(); + void prepareVertex(CCRenderState state); + + default void prepareVertex() { + prepareVertex(CCRenderState.instance()); + } } - public static VertexAttribute normalAttrib = new VertexAttribute() { + public static VertexAttribute normalAttrib = new VertexAttribute<>() { private Vector3[] normalRef; @@ -144,12 +179,12 @@ public class CCRenderState { } @Override - public boolean load() { - normalRef = model.getAttributes(this); - if (model.hasAttribute(this)) return normalRef != null; + public boolean load(CCRenderState state) { + normalRef = state.model.getAttributes(this); + if (state.model.hasAttribute(this)) return normalRef != null; - if (model.hasAttribute(sideAttrib)) { - pipeline.addDependency(sideAttrib); + if (state.model.hasAttribute(sideAttrib)) { + state.pipeline.addDependency(sideAttrib); return true; } throw new IllegalStateException( @@ -157,12 +192,12 @@ public class CCRenderState { } @Override - public void operate() { - if (normalRef != null) setNormal(normalRef[vertexIndex]); - else setNormal(Rotation.axes[side]); + public void operate(CCRenderState state) { + if (normalRef != null) state.setNormal(normalRef[state.vertexIndex]); + else state.setNormal(Rotation.axes[state.side]); } }; - public static VertexAttribute colourAttrib = new VertexAttribute() { + public static VertexAttribute colourAttrib = new VertexAttribute<>() { private int[] colourRef; @@ -172,18 +207,18 @@ public class CCRenderState { } @Override - public boolean load() { - colourRef = model.getAttributes(this); - return colourRef != null || !model.hasAttribute(this); + public boolean load(CCRenderState state) { + colourRef = state.model.getAttributes(this); + return colourRef != null || !state.model.hasAttribute(this); } @Override - public void operate() { - if (colourRef != null) setColour(ColourRGBA.multiply(baseColour, colourRef[vertexIndex])); - else setColour(baseColour); + public void operate(CCRenderState state) { + if (colourRef != null) state.setColour(ColourRGBA.multiply(state.baseColour, colourRef[state.vertexIndex])); + else state.setColour(state.baseColour); } }; - public static VertexAttribute lightingAttrib = new VertexAttribute() { + public static VertexAttribute lightingAttrib = new VertexAttribute<>() { private int[] colourRef; @@ -193,23 +228,23 @@ public class CCRenderState { } @Override - public boolean load() { - if (!computeLighting || !useColour || !model.hasAttribute(this)) return false; + public boolean load(CCRenderState state) { + if (!state.computeLighting || !state.useColour || !state.model.hasAttribute(this)) return false; - colourRef = model.getAttributes(this); + colourRef = state.model.getAttributes(this); if (colourRef != null) { - pipeline.addDependency(colourAttrib); + state.pipeline.addDependency(colourAttrib); return true; } return false; } @Override - public void operate() { - setColour(ColourRGBA.multiply(colour, colourRef[vertexIndex])); + public void operate(CCRenderState state) { + state.setColour(ColourRGBA.multiply(state.colour, colourRef[state.vertexIndex])); } }; - public static VertexAttribute sideAttrib = new VertexAttribute() { + public static VertexAttribute sideAttrib = new VertexAttribute<>() { private int[] sideRef; @@ -219,28 +254,28 @@ public class CCRenderState { } @Override - public boolean load() { - sideRef = model.getAttributes(this); - if (model.hasAttribute(this)) return sideRef != null; + public boolean load(CCRenderState state) { + sideRef = state.model.getAttributes(this); + if (state.model.hasAttribute(this)) return sideRef != null; - pipeline.addDependency(normalAttrib); + state.pipeline.addDependency(normalAttrib); return true; } @Override - public void operate() { - if (sideRef != null) side = sideRef[vertexIndex]; - else side = CCModel.findSide(normal); + public void operate(CCRenderState state) { + if (sideRef != null) state.side = sideRef[state.vertexIndex]; + else state.side = CCModel.findSide(state.normal); } }; /** * Uses the position of the lightmatrix to compute LC if not provided */ - public static VertexAttribute lightCoordAttrib = new VertexAttribute() { + public static VertexAttribute lightCoordAttrib = new VertexAttribute<>() { private LC[] lcRef; - private Vector3 vec = new Vector3(); // for computation - private Vector3 pos = new Vector3(); + private final Vector3 vec = new Vector3(); // for computation + private final Vector3 pos = new Vector3(); @Override public LC[] newArray(int length) { @@ -248,52 +283,54 @@ public class CCRenderState { } @Override - public boolean load() { - lcRef = model.getAttributes(this); - if (model.hasAttribute(this)) return lcRef != null; + public boolean load(CCRenderState state) { + lcRef = state.model.getAttributes(this); + if (state.model.hasAttribute(this)) return lcRef != null; - pos.set(lightMatrix.pos.x, lightMatrix.pos.y, lightMatrix.pos.z); - pipeline.addDependency(sideAttrib); - pipeline.addRequirement(Transformation.operationIndex); + pos.set(state.lightMatrix.pos.x, state.lightMatrix.pos.y, state.lightMatrix.pos.z); + state.pipeline.addDependency(sideAttrib); + state.pipeline.addRequirement(Transformation.operationIndex); return true; } @Override - public void operate() { - if (lcRef != null) lc.set(lcRef[vertexIndex]); - else lc.compute(vec.set(vert.vec).sub(pos), side); + public void operate(CCRenderState state) { + if (lcRef != null) state.lc.set(lcRef[state.vertexIndex]); + else state.lc.compute(vec.set(state.vert.vec).sub(pos), state.side); } }; // pipeline state - public static IVertexSource model; - public static int firstVertexIndex; - public static int lastVertexIndex; - public static int vertexIndex; - public static CCRenderPipeline pipeline = new CCRenderPipeline(); + public IVertexSource model; + + public int firstVertexIndex; + public int lastVertexIndex; + public int vertexIndex; // context - public static int baseColour; - public static int alphaOverride; - public static boolean useNormals; - public static boolean computeLighting; - public static boolean useColour; - public static LightMatrix lightMatrix = new LightMatrix(); + public int baseColour; + public int alphaOverride; + public boolean useNormals; + public boolean computeLighting; + public boolean useColour; + public LightMatrix lightMatrix = new LightMatrix(); // vertex outputs - public static Vertex5 vert = new Vertex5(); - public static boolean hasNormal; - public static Vector3 normal = new Vector3(); - public static boolean hasColour; - public static int colour; - public static boolean hasBrightness; - public static int brightness; + public Vertex5 vert = new Vertex5(); + public boolean hasNormal; + public Vector3 normal = new Vector3(); + + public boolean hasColour; + public int colour; + + public boolean hasBrightness; + public int brightness; // attrute storage - public static int side; - public static LC lc = new LC(); + public int side; + public LC lc = new LC(); - public static void reset() { + public void reset() { model = null; pipeline.reset(); useNormals = hasNormal = hasBrightness = hasColour = false; @@ -301,57 +338,102 @@ public class CCRenderState { baseColour = alphaOverride = -1; } - public static void setPipeline(IVertexOperation... ops) { + public void setPipeline(IVertexOperation... ops) { pipeline.setPipeline(ops); } - public static void setPipeline(IVertexSource model, int start, int end, IVertexOperation... ops) { + @Deprecated + public static void setPipelineStatic(IVertexOperation... ops) { + instance().setPipeline(ops); + } + + public void setPipeline(IVertexSource model, int start, int end, IVertexOperation... ops) { pipeline.reset(); setModel(model, start, end); pipeline.setPipeline(ops); } - public static void bindModel(IVertexSource model) { - if (CCRenderState.model != model) { - CCRenderState.model = model; + @Deprecated + public static void setPipelineStatic(IVertexSource model, int start, int end, IVertexOperation... ops) { + instance().setPipeline(model, start, end, ops); + } + + public void bindModel(IVertexSource model) { + if (this.model != model) { + this.model = model; pipeline.rebuild(); } } - public static void setModel(IVertexSource source) { + @Deprecated + public static void bindModelStatic(IVertexSource model) { + instance().bindModel(model); + } + + public void setModel(IVertexSource source) { setModel(source, 0, source.getVertices().length); } - public static void setModel(IVertexSource source, int start, int end) { + @Deprecated + public static void setModelStatic(IVertexSource source) { + instance().setModel(source); + } + + public void setModel(IVertexSource source, int start, int end) { bindModel(source); setVertexRange(start, end); } - public static void setVertexRange(int start, int end) { + @Deprecated + public static void setModelStatic(IVertexSource source, int start, int end) { + instance().setModel(source, start, end); + } + + public void setVertexRange(int start, int end) { firstVertexIndex = start; lastVertexIndex = end; } - public static void render(IVertexOperation... ops) { + @Deprecated + public static void setVertexRangeStatic(int start, int end) { + instance().setVertexRange(start, end); + } + + public void render(IVertexOperation... ops) { setPipeline(ops); render(); } - public static void render() { + @Deprecated + public static void renderStatic(IVertexOperation... ops) { + instance().render(ops); + } + + public void render() { Vertex5[] verts = model.getVertices(); for (vertexIndex = firstVertexIndex; vertexIndex < lastVertexIndex; vertexIndex++) { - model.prepareVertex(); + model.prepareVertex(this); vert.set(verts[vertexIndex]); runPipeline(); writeVert(); } } - public static void runPipeline() { + @Deprecated + public static void renderStatic() { + instance().render(); + } + + public void runPipeline() { pipeline.operate(); } - public static void writeVert() { + @Deprecated + public static void runPipelineStatic() { + instance().runPipeline(); + } + + public void writeVert() { if (hasNormal) Tessellator.instance.setNormal((float) normal.x, (float) normal.y, (float) normal.z); if (hasColour) Tessellator.instance.setColorRGBA( colour >>> 24, @@ -362,42 +444,72 @@ public class CCRenderState { Tessellator.instance.addVertexWithUV(vert.vec.x, vert.vec.y, vert.vec.z, vert.uv.u, vert.uv.v); } - public static void setNormal(double x, double y, double z) { + @Deprecated + public static void writeVertStatic() { + instance().writeVert(); + } + + public void setNormal(double x, double y, double z) { hasNormal = true; normal.set(x, y, z); } - public static void setNormal(Vector3 n) { + @Deprecated + public static void setNormalStatic(double x, double y, double z) { + instance().setNormal(x, y, z); + } + + public void setNormal(Vector3 n) { hasNormal = true; normal.set(n); } - public static void setColour(int c) { + @Deprecated + public static void setNormalStatic(Vector3 n) { + instance().setNormal(n); + } + + public void setColour(int c) { hasColour = true; colour = c; } - public static void setBrightness(int b) { + @Deprecated + public static void setColourStatic(int c) { + instance().setColour(c); + } + + public void setBrightness(int b) { hasBrightness = true; brightness = b; } - public static void setBrightness(IBlockAccess world, int x, int y, int z) { + @Deprecated + public static void setBrightnessStatic(int b) { + instance().setBrightness(b); + } + + public void setBrightness(IBlockAccess world, int x, int y, int z) { setBrightness(world.getBlock(x, y, z).getMixedBrightnessForBlock(world, x, y, z)); } - public static void pullLightmap() { + @Deprecated + public static void setBrightnessStatic(IBlockAccess world, int x, int y, int z) { + instance().setBrightness(world, x, y, z); + } + + public void pullLightmap() { setBrightness((int) OpenGlHelper.lastBrightnessY << 16 | (int) OpenGlHelper.lastBrightnessX); } - public static void pushLightmap() { + public void pushLightmap() { OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, brightness & 0xFFFF, brightness >>> 16); } /** * Compact helper for setting dynamic rendering context. Uses normals and doesn't compute lighting */ - public static void setDynamic() { + public void setDynamic() { useNormals = true; computeLighting = false; } @@ -410,11 +522,16 @@ public class CCRenderState { Minecraft.getMinecraft().renderEngine.bindTexture(texture); } - public static void startDrawing() { + public void startDrawing() { startDrawing(7); } - public static void startDrawing(int mode) { + @Deprecated + public static void startDrawingStatic() { + instance().startDrawing(); + } + + public void startDrawing(int mode) { Tessellator.instance.startDrawing(mode); if (hasColour) Tessellator.instance.setColorRGBA( colour >>> 24, @@ -424,7 +541,12 @@ public class CCRenderState { if (hasBrightness) Tessellator.instance.setBrightness(brightness); } - public static void draw() { + @Deprecated + public static void startDrawingStatic(int mode) { + instance().startDrawing(mode); + } + + public void draw() { Tessellator.instance.draw(); } } diff --git a/src/main/java/codechicken/lib/render/ColourMultiplier.java b/src/main/java/codechicken/lib/render/ColourMultiplier.java index dd42364..292048c 100644 --- a/src/main/java/codechicken/lib/render/ColourMultiplier.java +++ b/src/main/java/codechicken/lib/render/ColourMultiplier.java @@ -4,9 +4,11 @@ import codechicken.lib.colour.ColourRGBA; public class ColourMultiplier implements CCRenderState.IVertexOperation { - private static ColourMultiplier instance = new ColourMultiplier(-1); + private static final ThreadLocal instances = ThreadLocal + .withInitial(() -> new ColourMultiplier(-1)); public static ColourMultiplier instance(int colour) { + ColourMultiplier instance = instances.get(); instance.colour = colour; return instance; } @@ -19,19 +21,19 @@ public class ColourMultiplier implements CCRenderState.IVertexOperation { } @Override - public boolean load() { + public boolean load(CCRenderState state) { if (colour == -1) { - CCRenderState.setColour(-1); + state.setColour(-1); return false; } - CCRenderState.pipeline.addDependency(CCRenderState.colourAttrib); + state.pipeline.addDependency(state.colourAttrib); return true; } @Override - public void operate() { - CCRenderState.setColour(ColourRGBA.multiply(CCRenderState.colour, colour)); + public void operate(CCRenderState state) { + state.setColour(ColourRGBA.multiply(state.colour, colour)); } @Override diff --git a/src/main/java/codechicken/lib/render/RenderUtils.java b/src/main/java/codechicken/lib/render/RenderUtils.java index aec0443..c0c4a37 100644 --- a/src/main/java/codechicken/lib/render/RenderUtils.java +++ b/src/main/java/codechicken/lib/render/RenderUtils.java @@ -151,7 +151,7 @@ public class RenderUtils { var2.draw(); } - public static void renderFluidCuboid(Cuboid6 bound, IIcon tex, double res) { + public static void renderFluidCuboid(CCRenderState state, Cuboid6 bound, IIcon tex, double res) { renderFluidQuad( // bottom new Vector3(bound.min.x, bound.min.y, bound.min.z), new Vector3(bound.max.x, bound.min.y, bound.min.z), @@ -196,6 +196,10 @@ public class RenderUtils { res); } + public static void renderFluidCuboid(Cuboid6 bound, IIcon tex, double res) { + renderFluidCuboid(CCRenderState.instance(), bound, tex, res); + } + public static void renderBlockOverlaySide(int x, int y, int z, int side, double tx1, double tx2, double ty1, double ty2) { double[] points = new double[] { x - 0.009, x + 1.009, y - 0.009, y + 1.009, z - 0.009, z + 1.009 }; @@ -249,17 +253,21 @@ public class RenderUtils { * @param stack The fluid stack to render * @return The icon of the fluid */ - public static IIcon prepareFluidRender(FluidStack stack, int alpha) { + public static IIcon prepareFluidRender(CCRenderState state, FluidStack stack, int alpha) { GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); Fluid fluid = stack.getFluid(); - CCRenderState.setColour(fluid.getColor(stack) << 8 | alpha); + state.setColour(fluid.getColor(stack) << 8 | alpha); TextureUtils.bindAtlas(fluid.getSpriteNumber()); return TextureUtils.safeIcon(fluid.getIcon(stack)); } + public static IIcon prepareFluidRender(FluidStack stack, int alpha) { + return prepareFluidRender(CCRenderState.instance(), stack, alpha); + } + /** * Re-enables lighting and disables blending. */ @@ -283,21 +291,27 @@ public class RenderUtils { * this determines the height. * @param res The resolution to render at. */ - public static void renderFluidCuboid(FluidStack stack, Cuboid6 bound, double density, double res) { + public static void renderFluidCuboid(CCRenderState state, FluidStack stack, Cuboid6 bound, double density, + double res) { if (!shouldRenderFluid(stack)) return; int alpha = 255; if (stack.getFluid().isGaseous()) alpha = (int) (fluidDensityToAlpha(density) * 255); else bound.max.y = bound.min.y + (bound.max.y - bound.min.y) * density; - IIcon tex = prepareFluidRender(stack, alpha); - CCRenderState.startDrawing(); - renderFluidCuboid(bound, tex, res); - CCRenderState.draw(); + IIcon tex = prepareFluidRender(state, stack, alpha); + state.startDrawing(); + renderFluidCuboid(state, bound, tex, res); + state.draw(); postFluidRender(); } - public static void renderFluidGauge(FluidStack stack, Rectangle4i rect, double density, double res) { + public static void renderFluidCuboid(FluidStack stack, Cuboid6 bound, double density, double res) { + renderFluidCuboid(CCRenderState.instance(), stack, bound, density, res); + } + + public static void renderFluidGauge(CCRenderState state, FluidStack stack, Rectangle4i rect, double density, + double res) { if (!shouldRenderFluid(stack)) return; int alpha = 255; @@ -308,18 +322,22 @@ public class RenderUtils { rect.h = height; } - IIcon tex = prepareFluidRender(stack, alpha); - CCRenderState.startDrawing(); + IIcon tex = prepareFluidRender(state, stack, alpha); + state.startDrawing(); renderFluidQuad( new Vector3(rect.x, rect.y + rect.h, 0), new Vector3(rect.w, 0, 0), new Vector3(0, -rect.h, 0), tex, res); - CCRenderState.draw(); + state.draw(); postFluidRender(); } + public static void renderFluidGauge(FluidStack stack, Rectangle4i rect, double density, double res) { + renderFluidGauge(CCRenderState.instance(), stack, rect, density, res); + } + /** * Renders items and blocks in the world at 0,0,0 with transformations that size them appropriately */ diff --git a/src/main/java/codechicken/lib/render/uv/UVTransformation.java b/src/main/java/codechicken/lib/render/uv/UVTransformation.java index 8e96173..d7ca168 100644 --- a/src/main/java/codechicken/lib/render/uv/UVTransformation.java +++ b/src/main/java/codechicken/lib/render/uv/UVTransformation.java @@ -23,13 +23,13 @@ public abstract class UVTransformation extends ITransformation, Copyable public BlockCoord setSide(int s, int v) { switch (s) { - case 0: - case 1: - y = v; - break; - case 2: - case 3: - z = v; - break; - case 4: - case 5: - x = v; - break; - default: - throw new IndexOutOfBoundsException("Switch Falloff"); + case 0, 1 -> y = v; + case 2, 3 -> z = v; + case 4, 5 -> x = v; + default -> throw new IndexOutOfBoundsException("Switch Falloff"); } return this; } diff --git a/src/main/java/codechicken/lib/vec/Transformation.java b/src/main/java/codechicken/lib/vec/Transformation.java index 7d9aa72..a7cca46 100644 --- a/src/main/java/codechicken/lib/vec/Transformation.java +++ b/src/main/java/codechicken/lib/vec/Transformation.java @@ -38,15 +38,15 @@ public abstract class Transformation extends ITransformation