[ci skip] spotlessApply with the new settings

This commit is contained in:
Raven Szewczyk committed 2023-01-30 10:33:49 +00:00
1 parent 318c107957
commit a4515fbef8
115 files changed
+1261 -1062

No files matched your search

+23 -19
View File
@@ -2,17 +2,20 @@ package codechicken.lib.asm;
import static org.objectweb.asm.tree.AbstractInsnNode.*;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableMap;
import java.util.*;
import java.util.Map.Entry;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableMap;
public class ASMBlock {
public InsnListSection list;
private BiMap<String, LabelNode> labels;
@@ -44,22 +47,21 @@ public class ASMBlock {
}
public void replaceLabels(Map<LabelNode, LabelNode> labelMap, Set<LabelNode> usedLabels) {
for (AbstractInsnNode insn : list)
switch (insn.getType()) {
case LABEL:
AbstractInsnNode insn2 = insn.clone(labelMap);
if (insn2 == insn) // identity mapping
for (AbstractInsnNode insn : list) switch (insn.getType()) {
case LABEL:
AbstractInsnNode insn2 = insn.clone(labelMap);
if (insn2 == insn) // identity mapping
continue;
if (usedLabels.contains(insn2))
throw new IllegalStateException("LabelNode cannot be a part of two InsnLists");
list.replace(insn, insn2);
break;
case JUMP_INSN:
case FRAME:
case LOOKUPSWITCH_INSN:
case TABLESWITCH_INSN:
list.replace(insn, insn.clone(labelMap));
}
if (usedLabels.contains(insn2))
throw new IllegalStateException("LabelNode cannot be a part of two InsnLists");
list.replace(insn, insn2);
break;
case JUMP_INSN:
case FRAME:
case LOOKUPSWITCH_INSN:
case TABLESWITCH_INSN:
list.replace(insn, insn.clone(labelMap));
}
for (Entry<LabelNode, LabelNode> entry : labelMap.entrySet()) {
String key = labels.inverse().get(entry.getKey());
@@ -78,6 +80,7 @@ public class ASMBlock {
/**
* Pulls all common labels from other into this
*
* @return this
*/
public ASMBlock mergeLabels(ASMBlock other) {
@@ -99,6 +102,7 @@ public class ASMBlock {
/**
* Like mergeLabels but pulls insns from other list into this so LabelNodes can be transferred
*
* @return this
*/
public ASMBlock pullLabels(ASMBlock other) {
@@ -125,7 +129,7 @@ public class ASMBlock {
HashMap<LabelNode, LabelNode> labelMap = new HashMap<LabelNode, LabelNode>();
for (int i = 0, k = 0; i < list.size() && k < list2.size(); ) {
for (int i = 0, k = 0; i < list.size() && k < list2.size();) {
AbstractInsnNode insn1 = list.get(i);
if (!InsnComparator.insnImportant(insn1, cFlowLabels1)) {
i++;
@@ -1,7 +1,5 @@
package codechicken.lib.asm;
import codechicken.lib.config.ConfigFile;
import codechicken.lib.config.DefaultingConfigFile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@@ -9,6 +7,7 @@ import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.ClassReader;
@@ -19,16 +18,18 @@ import org.objectweb.asm.util.ASMifier;
import org.objectweb.asm.util.Textifier;
import org.objectweb.asm.util.TraceClassVisitor;
import codechicken.lib.config.ConfigFile;
import codechicken.lib.config.DefaultingConfigFile;
public class ASMHelper {
public static ConfigFile config = loadConfig();
public static Logger logger = LogManager.getLogger("CCL ASM");
private static ConfigFile loadConfig() {
try { // weak reference for environments without FML
File mcDir = (File) ((Object[]) Class.forName("cpw.mods.fml.relauncher.FMLInjectionData")
.getMethod("data")
.invoke(null))
[6];
File mcDir = (File) ((Object[]) Class.forName("cpw.mods.fml.relauncher.FMLInjectionData").getMethod("data")
.invoke(null))[6];
File file = new File(mcDir, "config/CodeChickenLib.cfg");
if (ObfMapping.obfuscated) return new DefaultingConfigFile(file);
else return new ConfigFile(file).setComment("CodeChickenLib development configuration file.");
@@ -38,6 +39,7 @@ public class ASMHelper {
}
public static interface Acceptor {
public void accept(ClassVisitor cv) throws IOException;
}
@@ -80,27 +82,30 @@ public class ASMHelper {
return new InsnListSection(list).copy(labelMap).list;
}
public static List<TryCatchBlockNode> cloneTryCatchBlocks(
Map<LabelNode, LabelNode> labelMap, List<TryCatchBlockNode> tcblocks) {
public static List<TryCatchBlockNode> cloneTryCatchBlocks(Map<LabelNode, LabelNode> labelMap,
List<TryCatchBlockNode> tcblocks) {
ArrayList<TryCatchBlockNode> clone = new ArrayList<TryCatchBlockNode>();
for (TryCatchBlockNode node : tcblocks)
clone.add(new TryCatchBlockNode(
labelMap.get(node.start), labelMap.get(node.end), labelMap.get(node.handler), node.type));
for (TryCatchBlockNode node : tcblocks) clone.add(
new TryCatchBlockNode(
labelMap.get(node.start),
labelMap.get(node.end),
labelMap.get(node.handler),
node.type));
return clone;
}
public static List<LocalVariableNode> cloneLocals(
Map<LabelNode, LabelNode> labelMap, List<LocalVariableNode> locals) {
public static List<LocalVariableNode> cloneLocals(Map<LabelNode, LabelNode> labelMap,
List<LocalVariableNode> locals) {
ArrayList<LocalVariableNode> clone = new ArrayList<LocalVariableNode>(locals.size());
for (LocalVariableNode node : locals)
clone.add(new LocalVariableNode(
node.name,
node.desc,
node.signature,
labelMap.get(node.start),
labelMap.get(node.end),
node.index));
for (LocalVariableNode node : locals) clone.add(
new LocalVariableNode(
node.name,
node.desc,
node.signature,
labelMap.get(node.start),
labelMap.get(node.end),
node.index));
return clone;
}
@@ -123,9 +128,8 @@ public class ASMHelper {
int found = -1;
for (LocalVariableNode node : list) {
if (node.name.equals(name)) {
if (found >= 0)
throw new RuntimeException(
"Duplicate local variable: " + name + " not coded to handle this scenario.");
if (found >= 0) throw new RuntimeException(
"Duplicate local variable: " + name + " not coded to handle this scenario.");
found = node.index;
}
@@ -140,8 +144,8 @@ public class ASMHelper {
replacement.accept(original);
}
public static void dump(
Acceptor acceptor, File file, boolean filterImportant, boolean sortLocals, boolean textify) {
public static void dump(Acceptor acceptor, File file, boolean filterImportant, boolean sortLocals,
boolean textify) {
try {
if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
if (!file.exists()) file.createNewFile();
@@ -158,50 +162,36 @@ public class ASMHelper {
}
public static void dump(Acceptor acceptor, File file, boolean filterImportant, boolean sortLocals) {
dump(
acceptor,
file,
filterImportant,
sortLocals,
config.getTag("textify").getBooleanValue(true));
dump(acceptor, file, filterImportant, sortLocals, config.getTag("textify").getBooleanValue(true));
}
public static void dump(final byte[] bytes, File file, boolean filterImportant, boolean sortLocals) {
dump(
new Acceptor() {
@Override
public void accept(ClassVisitor cv) {
new ClassReader(bytes).accept(cv, ClassReader.EXPAND_FRAMES);
}
},
file,
filterImportant,
sortLocals);
dump(new Acceptor() {
@Override
public void accept(ClassVisitor cv) {
new ClassReader(bytes).accept(cv, ClassReader.EXPAND_FRAMES);
}
}, file, filterImportant, sortLocals);
}
public static void dump(final InputStream is, File file, boolean filterImportant, boolean sortLocals) {
dump(
new Acceptor() {
@Override
public void accept(ClassVisitor cv) throws IOException {
new ClassReader(is).accept(cv, ClassReader.EXPAND_FRAMES);
}
},
file,
filterImportant,
sortLocals);
dump(new Acceptor() {
@Override
public void accept(ClassVisitor cv) throws IOException {
new ClassReader(is).accept(cv, ClassReader.EXPAND_FRAMES);
}
}, file, filterImportant, sortLocals);
}
public static void dump(final ClassNode cnode, File file, boolean filterImportant, boolean sortLocals) {
dump(
new Acceptor() {
@Override
public void accept(ClassVisitor cv) {
cnode.accept(cv);
}
},
file,
filterImportant,
sortLocals);
dump(new Acceptor() {
@Override
public void accept(ClassVisitor cv) {
cnode.accept(cv);
}
}, file, filterImportant, sortLocals);
}
}
@@ -6,6 +6,7 @@ import net.minecraft.launchwrapper.Launch;
* Initialisation class for using this package. Call this on coremod load
*/
public class ASMInit {
private static boolean initialised = false;
public static void init() {
@@ -8,9 +8,11 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import org.objectweb.asm.tree.*;
public class ASMReader {
public static Map<String, Integer> opCodes = new HashMap<String, Integer>();
public static byte[] TYPE;
@@ -235,9 +237,7 @@ public class ASMReader {
case METHOD_INSN:
StringBuilder sb = new StringBuilder();
for (int i = 1; i < split.length; i++) sb.append(split[i]);
insn = ObfMapping.fromDesc(sb.toString())
.toClassloading()
.toInsn(opcode);
insn = ObfMapping.fromDesc(sb.toString()).toClassloading().toInsn(opcode);
break;
case INVOKE_DYNAMIC_INSN:
throw new Exception("Found INVOKEDYNAMIC while reading");
@@ -3,6 +3,7 @@ package codechicken.lib.asm;
import org.objectweb.asm.ClassWriter;
public class CC_ClassWriter extends ClassWriter {
private final boolean runtime;
public CC_ClassWriter(int flags) {
@@ -1,23 +1,29 @@
package codechicken.lib.asm;
import cpw.mods.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.objectweb.asm.tree.ClassNode;
import cpw.mods.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
/**
* This is added as a class transformer if CodeChickenCore is installed. Adding it as a class transformer will speed evaluation up slightly by automatically caching superclasses when they are first loaded.
* This is added as a class transformer if CodeChickenCore is installed. Adding it as a class transformer will speed
* evaluation up slightly by automatically caching superclasses when they are first loaded.
*/
public class ClassHeirachyManager implements IClassTransformer {
static {
ASMInit.init();
}
public static class SuperCache {
String superclass;
public HashSet<String> parents = new HashSet<String>();
private boolean flattened;
@@ -51,9 +57,7 @@ public class ClassHeirachyManager implements IClassTransformer {
public static String unKey(String name) {
if (ObfMapping.obfuscated)
name = FMLDeobfuscatingRemapper.INSTANCE
.unmap(name.replace('.', '/'))
.replace('/', '.');
name = FMLDeobfuscatingRemapper.INSTANCE.unmap(name.replace('.', '/')).replace('/', '.');
return name;
}
@@ -70,7 +74,7 @@ public class ClassHeirachyManager implements IClassTransformer {
SuperCache cache = declareClass(name);
if (cache == null) // just can't handle this
return false;
return false;
cache.flatten();
return cache.parents.contains(superclass);
@@ -85,15 +89,13 @@ public class ClassHeirachyManager implements IClassTransformer {
try {
byte[] bytes = cl.getClassBytes(unKey(name));
if (bytes != null) cache = declareASM(bytes);
} catch (Exception e) {
}
} catch (Exception e) {}
if (cache != null) return cache;
try {
cache = declareReflection(name);
} catch (ClassNotFoundException e) {
}
} catch (ClassNotFoundException e) {}
return cache;
}
@@ -6,7 +6,9 @@ import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.MethodNode;
public class ImportantInsnVisitor extends ClassVisitor {
public class ImportantInsnMethodVisitor extends MethodVisitor {
MethodVisitor delegate;
public ImportantInsnMethodVisitor(int access, String name, String desc, String signature, String[] exceptions) {
@@ -2,12 +2,15 @@ package codechicken.lib.asm;
import static org.objectweb.asm.tree.AbstractInsnNode.*;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import java.util.*;
import org.objectweb.asm.tree.*;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
public class InsnComparator {
public static boolean varInsnEqual(VarInsnNode insn1, VarInsnNode insn2) {
return insn1.var == -1 || insn2.var == -1 || insn1.var == insn2.var;
}
@@ -107,6 +110,7 @@ public class InsnComparator {
Set<LabelNode> controlFlowLabels = getControlFlowLabels(list);
Map<LabelNode, LabelNode> labelMap = Maps.asMap(controlFlowLabels, new Function<LabelNode, LabelNode>() {
@Override
public LabelNode apply(LabelNode input) {
return input;
@@ -138,8 +142,8 @@ public class InsnComparator {
return find(new InsnListSection(haystack), needle);
}
public static InsnListSection matches(
InsnListSection haystack, InsnListSection needle, Set<LabelNode> controlFlowLabels) {
public static InsnListSection matches(InsnListSection haystack, InsnListSection needle,
Set<LabelNode> controlFlowLabels) {
int h = 0, n = 0;
for (; h < haystack.size() && n < needle.size(); h++) {
AbstractInsnNode insn = haystack.get(h);
@@ -155,9 +159,8 @@ public class InsnComparator {
public static InsnListSection findOnce(InsnListSection haystack, InsnListSection needle) {
List<InsnListSection> list = find(haystack, needle);
if (list.size() != 1)
throw new RuntimeException(
"Needle found " + list.size() + " times in Haystack:\n" + haystack + "\n\n" + needle);
if (list.size() != 1) throw new RuntimeException(
"Needle found " + list.size() + " times in Haystack:\n" + haystack + "\n\n" + needle);
return list.get(0);
}
@@ -9,6 +9,7 @@ import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.*;
import org.objectweb.asm.util.Textifier;
@@ -18,7 +19,9 @@ import org.objectweb.asm.util.TraceMethodVisitor;
* A section of an InsnList, may become invalid if the insn list is modified
*/
public class InsnListSection implements Iterable<AbstractInsnNode> {
private class InsnListSectionIterator implements Iterator<AbstractInsnNode> {
int i = 0;
@Override
@@ -143,6 +146,7 @@ public class InsnListSection implements Iterable<AbstractInsnNode> {
/**
* Removes leading and trailing labels and line number nodes that don't affect control flow
*
* @return this
*/
public InsnListSection trim(Set<LabelNode> controlFlowLabels) {
@@ -167,34 +171,31 @@ public class InsnListSection implements Iterable<AbstractInsnNode> {
public HashMap<LabelNode, LabelNode> identityLabelMap() {
HashMap<LabelNode, LabelNode> labelMap = new HashMap<LabelNode, LabelNode>();
for (AbstractInsnNode insn : this)
switch (insn.getType()) {
case LABEL:
labelMap.put((LabelNode) insn, (LabelNode) insn);
break;
case JUMP_INSN:
labelMap.put(((JumpInsnNode) insn).label, ((JumpInsnNode) insn).label);
break;
case LOOKUPSWITCH_INSN:
LookupSwitchInsnNode linsn = (LookupSwitchInsnNode) insn;
labelMap.put(linsn.dflt, linsn.dflt);
for (LabelNode label : linsn.labels) labelMap.put(label, label);
break;
case TABLESWITCH_INSN:
TableSwitchInsnNode tinsn = (TableSwitchInsnNode) insn;
labelMap.put(tinsn.dflt, tinsn.dflt);
for (LabelNode label : tinsn.labels) labelMap.put(label, label);
break;
case FRAME:
FrameNode fnode = (FrameNode) insn;
if (fnode.local != null)
for (Object o : fnode.local)
if (o instanceof LabelNode) labelMap.put((LabelNode) o, (LabelNode) o);
if (fnode.stack != null)
for (Object o : fnode.stack)
if (o instanceof LabelNode) labelMap.put((LabelNode) o, (LabelNode) o);
break;
}
for (AbstractInsnNode insn : this) switch (insn.getType()) {
case LABEL:
labelMap.put((LabelNode) insn, (LabelNode) insn);
break;
case JUMP_INSN:
labelMap.put(((JumpInsnNode) insn).label, ((JumpInsnNode) insn).label);
break;
case LOOKUPSWITCH_INSN:
LookupSwitchInsnNode linsn = (LookupSwitchInsnNode) insn;
labelMap.put(linsn.dflt, linsn.dflt);
for (LabelNode label : linsn.labels) labelMap.put(label, label);
break;
case TABLESWITCH_INSN:
TableSwitchInsnNode tinsn = (TableSwitchInsnNode) insn;
labelMap.put(tinsn.dflt, tinsn.dflt);
for (LabelNode label : tinsn.labels) labelMap.put(label, label);
break;
case FRAME:
FrameNode fnode = (FrameNode) insn;
if (fnode.local != null)
for (Object o : fnode.local) if (o instanceof LabelNode) labelMap.put((LabelNode) o, (LabelNode) o);
if (fnode.stack != null)
for (Object o : fnode.stack) if (o instanceof LabelNode) labelMap.put((LabelNode) o, (LabelNode) o);
break;
}
return labelMap;
}
@@ -1,12 +1,14 @@
package codechicken.lib.asm;
import java.util.Set;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.LocalVariablesSorter;
public class LocalVariablesSorterVisitor extends ClassVisitor {
public Set<ObfMapping> methods;
public String owner;
@@ -4,13 +4,16 @@ import static codechicken.lib.asm.ASMHelper.*;
import java.io.File;
import java.util.*;
import org.objectweb.asm.*;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodNode;
public class ModularASMTransformer {
public static class ClassNodeTransformerList {
List<ClassNodeTransformer> transformers = new LinkedList<ClassNodeTransformer>();
HashSet<ObfMapping> methodsToSort = new HashSet<ObfMapping>();
@@ -45,6 +48,7 @@ public class ModularASMTransformer {
}
public abstract static class ClassNodeTransformer {
public int writeFlags;
public ClassNodeTransformer(int writeFlags) {
@@ -63,6 +67,7 @@ public class ModularASMTransformer {
}
public abstract static class MethodTransformer extends ClassNodeTransformer {
public final ObfMapping method;
public MethodTransformer(ObfMapping method) {
@@ -90,6 +95,7 @@ public class ModularASMTransformer {
}
public static class MethodWriter extends ClassNodeTransformer {
public final int access;
public final ObfMapping method;
public final String[] exceptions;
@@ -148,6 +154,7 @@ public class ModularASMTransformer {
}
public static class MethodInjector extends MethodTransformer {
public ASMBlock needle;
public ASMBlock injection;
public boolean before;
@@ -184,8 +191,14 @@ public class ModularASMTransformer {
else mv.instructions.add(injection.rawListCopy());
} else {
for (InsnListSection key : InsnComparator.findN(mv.instructions, needle.list)) {
logger.debug("Injecting " + (before ? "before" : "after") + " method " + method + " @ " + key.start
+ " - " + key.end);
logger.debug(
"Injecting " + (before ? "before" : "after")
+ " method "
+ method
+ " @ "
+ key.start
+ " - "
+ key.end);
ASMBlock injectBlock = injection.copy().mergeLabels(needle.applyLabels(key));
if (before) key.insertBefore(injectBlock.list.list);
@@ -196,6 +209,7 @@ public class ModularASMTransformer {
}
public static class MethodReplacer extends MethodTransformer {
public ASMBlock needle;
public ASMBlock replacement;
@@ -225,6 +239,7 @@ public class ModularASMTransformer {
}
public static class FieldWriter extends ClassNodeTransformer {
public final ObfMapping field;
public final int access;
public final Object value;
@@ -1,29 +1,37 @@
package codechicken.lib.asm;
import codechicken.lib.config.ConfigTag;
import com.google.common.base.Charsets;
import com.google.common.base.Objects;
import com.google.common.io.LineProcessor;
import com.google.common.io.Resources;
import cpw.mods.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import cpw.mods.fml.relauncher.FMLInjectionData;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.*;
import net.minecraft.launchwrapper.Launch;
import net.minecraftforge.common.ForgeVersion;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.commons.Remapper;
import org.objectweb.asm.tree.*;
import codechicken.lib.config.ConfigTag;
import com.google.common.base.Charsets;
import com.google.common.base.Objects;
import com.google.common.io.LineProcessor;
import com.google.common.io.Resources;
import cpw.mods.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import cpw.mods.fml.relauncher.FMLInjectionData;
public class ObfMapping {
public static class ObfRemapper extends Remapper {
private HashMap<String, String> fields = new HashMap<String, String>();
private HashMap<String, String> funcs = new HashMap<String, String>();
@@ -33,27 +41,20 @@ public class ObfMapping {
Field rawMethodMapsField = FMLDeobfuscatingRemapper.class.getDeclaredField("rawMethodMaps");
rawFieldMapsField.setAccessible(true);
rawMethodMapsField.setAccessible(true);
Map<String, Map<String, String>> rawFieldMaps =
(Map<String, Map<String, String>>) rawFieldMapsField.get(FMLDeobfuscatingRemapper.INSTANCE);
Map<String, Map<String, String>> rawMethodMaps =
(Map<String, Map<String, String>>) rawMethodMapsField.get(FMLDeobfuscatingRemapper.INSTANCE);
Map<String, Map<String, String>> rawFieldMaps = (Map<String, Map<String, String>>) rawFieldMapsField
.get(FMLDeobfuscatingRemapper.INSTANCE);
Map<String, Map<String, String>> rawMethodMaps = (Map<String, Map<String, String>>) rawMethodMapsField
.get(FMLDeobfuscatingRemapper.INSTANCE);
if (rawFieldMaps == null)
throw new IllegalStateException(
"codechicken.lib.asm.ObfMapping loaded too early. Make sure all references are in or after the asm transformer load stage");
if (rawFieldMaps == null) throw new IllegalStateException(
"codechicken.lib.asm.ObfMapping loaded too early. Make sure all references are in or after the asm transformer load stage");
for (Map<String, String> map : rawFieldMaps.values())
for (Entry<String, String> entry : map.entrySet())
if (entry.getValue().startsWith("field"))
fields.put(
entry.getValue(),
entry.getKey().substring(0, entry.getKey().indexOf(':')));
for (Entry<String, String> entry : map.entrySet()) if (entry.getValue().startsWith("field"))
fields.put(entry.getValue(), entry.getKey().substring(0, entry.getKey().indexOf(':')));
for (Map<String, String> map : rawMethodMaps.values())
for (Entry<String, String> entry : map.entrySet())
if (entry.getValue().startsWith("func"))
funcs.put(
entry.getValue(),
entry.getKey().substring(0, entry.getKey().indexOf('(')));
for (Entry<String, String> entry : map.entrySet()) if (entry.getValue().startsWith("func"))
funcs.put(entry.getValue(), entry.getKey().substring(0, entry.getKey().indexOf('(')));
} catch (Exception e) {
throw new RuntimeException(e);
@@ -87,9 +88,9 @@ public class ObfMapping {
}
public static class MCPRemapper extends Remapper implements LineProcessor<Void> {
public static File[] getConfFiles() {
ConfigTag tag = ASMHelper.config
.getTag("mappingDir")
ConfigTag tag = ASMHelper.config.getTag("mappingDir")
.setComment("Path to directory holding packaged.srg, fields.csv and methods.csv for mcp remapping");
for (int i = 0; i < DIR_GUESSES + DIR_ASKS; i++) {
File dir = confDirectoryGuess(i, tag);
@@ -125,13 +126,19 @@ public class ObfMapping {
case 3:
return new File(
System.getProperty("user.home"),
".gradle/caches/minecraft/net/minecraftforge/forge/" + FMLInjectionData.data()[4] + "-"
+ ForgeVersion.getVersion() + "/unpacked/conf");
".gradle/caches/minecraft/net/minecraftforge/forge/" + FMLInjectionData.data()[4]
+ "-"
+ ForgeVersion.getVersion()
+ "/unpacked/conf");
case 4:
return new File(
System.getProperty("user.home"),
".gradle/caches/minecraft/net/minecraftforge/forge/" + FMLInjectionData.data()[4] + "-"
+ ForgeVersion.getVersion() + "-" + FMLInjectionData.data()[4] + "/unpacked/conf");
".gradle/caches/minecraft/net/minecraftforge/forge/" + FMLInjectionData.data()[4]
+ "-"
+ ForgeVersion.getVersion()
+ "-"
+ FMLInjectionData.data()[4]
+ "/unpacked/conf");
case 5:
final String gradleCsvDir = System.getProperty("net.minecraftforge.gradle.GradleStart.csvDir");
return gradleCsvDir != null ? new File(gradleCsvDir) : null;
@@ -160,7 +167,7 @@ public class ObfMapping {
File fields = new File(mapDir, "fields.csv");
if (!fields.exists()) throw new RuntimeException("Could not find fields.csv");
return new File[] {srgs, methods, fields};
return new File[] { srgs, methods, fields };
}
private HashMap<String, String> fields = new HashMap<String, String>();
@@ -218,8 +225,7 @@ public class ObfMapping {
boolean obf = true;
try {
obf = Launch.classLoader.getClassBytes("net.minecraft.world.World") == null;
} catch (IOException ignored) {
}
} catch (IOException ignored) {}
obfuscated = obf;
if (!obf) loadMCPRemapper();
}
@@ -1,16 +1,20 @@
package codechicken.lib.colour;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.lwjgl.opengl.GL11;
import codechicken.lib.config.ConfigTag.IConfigType;
import codechicken.lib.math.MathHelper;
import codechicken.lib.util.Copyable;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.lwjgl.opengl.GL11;
public abstract class Colour implements Copyable<Colour> {
public static IConfigType<Colour> configRGB = new IConfigType<Colour>() {
@Override
public String configValue(Colour entry) {
String s = Long.toString(((long) entry.rgb()) << 32 >>> 32, 16);
@@ -23,12 +27,11 @@ public abstract class Colour implements Copyable<Colour> {
@Override
public Colour valueOf(String text) throws Exception {
Matcher matcherRGB = patternRGB.matcher(text.replaceAll("\\s", ""));
if (matcherRGB.matches())
return new ColourRGBA(
Integer.parseInt(matcherRGB.group(1)),
Integer.parseInt(matcherRGB.group(2)),
Integer.parseInt(matcherRGB.group(3)),
0xFF);
if (matcherRGB.matches()) return new ColourRGBA(
Integer.parseInt(matcherRGB.group(1)),
Integer.parseInt(matcherRGB.group(2)),
Integer.parseInt(matcherRGB.group(3)),
0xFF);
int hex = (int) Long.parseLong(text.replace("0x", ""), 16);
return new ColourRGBA(hex << 8 | 0xFF);
@@ -1,6 +1,7 @@
package codechicken.lib.colour;
public class ColourARGB extends Colour {
public ColourARGB(int colour) {
super((colour >> 16) & 0xFF, (colour >> 8) & 0xFF, colour & 0xFF, (colour >> 24) & 0xFF);
}
@@ -1,6 +1,7 @@
package codechicken.lib.colour;
public class ColourRGBA extends Colour {
public ColourRGBA(int colour) {
super((colour >> 24) & 0xFF, (colour >> 16) & 0xFF, (colour >> 8) & 0xFF, colour & 0xFF);
}
@@ -1,11 +1,14 @@
package codechicken.lib.colour;
import java.awt.image.BufferedImage;
import net.minecraft.util.ResourceLocation;
import codechicken.lib.math.MathHelper;
import codechicken.lib.render.TextureUtils;
import java.awt.image.BufferedImage;
import net.minecraft.util.ResourceLocation;
public class CustomGradient {
public int[] gradient;
public CustomGradient(ResourceLocation textureFile) {
@@ -3,7 +3,8 @@ package codechicken.lib.config;
import java.io.*;
public class ConfigFile extends ConfigTagParent {
public static final byte[] crlf = new byte[] {0xD, 0xA};
public static final byte[] crlf = new byte[] { 0xD, 0xA };
public File file;
private boolean loading;
@@ -3,7 +3,9 @@ package codechicken.lib.config;
import java.io.PrintWriter;
public class ConfigTag extends ConfigTagParent {
public interface IConfigType<T> {
public String configValue(T entry);
public T valueOf(String text) throws Exception;
@@ -80,8 +82,7 @@ public class ConfigTag extends ConfigTagParent {
public int getIntValue(int defaultValue) {
try {
if (value != null) return getIntValue();
} catch (NumberFormatException ignored) {
}
} catch (NumberFormatException ignored) {}
setIntValue(defaultValue);
return defaultValue;
@@ -98,8 +99,7 @@ public class ConfigTag extends ConfigTagParent {
public boolean getBooleanValue(boolean defaultValue) {
try {
if (value != null) return getBooleanValue();
} catch (NumberFormatException ignored) {
}
} catch (NumberFormatException ignored) {}
setBooleanValue(defaultValue);
return defaultValue;
@@ -112,8 +112,7 @@ public class ConfigTag extends ConfigTagParent {
public int getHexValue(int defaultValue) {
try {
if (value != null) return getHexValue();
} catch (NumberFormatException ignored) {
}
} catch (NumberFormatException ignored) {}
setHexValue(defaultValue);
return defaultValue;
@@ -130,8 +129,7 @@ public class ConfigTag extends ConfigTagParent {
public <T> T get(IConfigType<T> type, T defaultValue) {
try {
if (value != null) return get(type);
} catch (Exception ignored) {
}
} catch (Exception ignored) {}
set(type, defaultValue);
return defaultValue;
@@ -7,7 +7,9 @@ import java.util.*;
import java.util.Map.Entry;
public abstract class ConfigTagParent {
public static class TagOrderComparator implements Comparator<ConfigTag> {
int sortMode;
public TagOrderComparator(int sortMode) {
@@ -40,8 +42,8 @@ public abstract class ConfigTagParent {
*/
public int sortMode = 0;
/**
* The mode for determining when child tags should leave a blank line between them and the one above
* 0 = never, 1 = when braced, 2 = always
* The mode for determining when child tags should leave a blank line between them and the one above 0 = never, 1 =
* when braced, 2 = always
*/
public int newlinemode = 1;
@@ -147,9 +149,7 @@ public abstract class ConfigTagParent {
else comment = comment + "\n" + line.substring(1);
} else if (line.contains("=")) {
String qualifiedname = line.substring(0, line.indexOf("="));
getTag(qualifiedname)
.onLoaded()
.setComment(comment)
getTag(qualifiedname).onLoaded().setComment(comment)
.setValue(line.substring(line.indexOf("=") + 1));
comment = "";
bracequalifier = qualifiedname;
@@ -3,6 +3,7 @@ package codechicken.lib.config;
import java.io.File;
public class DefaultingConfigFile extends ConfigFile {
public DefaultingConfigFile(File file) {
super();
if (file.exists()) load(file);
@@ -6,6 +6,7 @@ import java.util.HashMap;
import java.util.Map.Entry;
public class SimpleProperties {
public HashMap<String, String> propertyMap = new HashMap<String, String>();
public File propertyFile;
public boolean saveOnChange = false;
@@ -32,8 +33,8 @@ public class SimpleProperties {
loading = true;
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(new FileInputStream(propertyFile), encoding));
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(propertyFile), encoding));
while (true) {
String read = reader.readLine();
if (read == null) break;
@@ -1,11 +1,13 @@
package codechicken.lib.data;
import codechicken.lib.vec.BlockCoord;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.FluidStack;
import codechicken.lib.vec.BlockCoord;
public interface MCDataInput {
public long readLong();
public int readInt();
@@ -3,6 +3,7 @@ package codechicken.lib.data;
import java.io.InputStream;
public class MCDataInputStream extends InputStream {
private MCDataInput in;
public MCDataInputStream(MCDataInput in) {
@@ -1,11 +1,13 @@
package codechicken.lib.data;
import codechicken.lib.vec.BlockCoord;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.FluidStack;
import codechicken.lib.vec.BlockCoord;
public interface MCDataOutput {
public MCDataOutput writeLong(long l);
public MCDataOutput writeInt(int i);
@@ -3,6 +3,7 @@ package codechicken.lib.data;
import java.io.OutputStream;
public class MCDataOutputStream extends OutputStream {
private MCDataOutput out;
public MCDataOutputStream(MCDataOutput out) {
@@ -1,24 +1,28 @@
package codechicken.lib.data;
import codechicken.lib.vec.BlockCoord;
import com.google.common.base.Charsets;
import cpw.mods.fml.common.network.ByteBufUtils;
import java.io.DataOutput;
import java.io.IOException;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.FluidStack;
import org.apache.commons.lang3.Validate;
import codechicken.lib.vec.BlockCoord;
import com.google.common.base.Charsets;
import cpw.mods.fml.common.network.ByteBufUtils;
public class MCDataOutputWrapper implements MCDataOutput {
/**
* Mimics ByteBufUtils
* Write an integer using variable length encoding.
* Mimics ByteBufUtils Write an integer using variable length encoding.
*
* @param to The buffer to write to
* @param i The integer to write
* @param i The integer to write
*/
public static void writeVarInt(DataOutput to, int i) throws IOException {
while ((i & 0x80) != 0) {
@@ -30,11 +34,10 @@ public class MCDataOutputWrapper implements MCDataOutput {
}
/**
* Mimics ByteBufUtils
* Write an extended short using a short and a byte if necessary
* Mimics ByteBufUtils Write an extended short using a short and a byte if necessary
*
* @param to The buffer to write to
* @param s The short to write, less than 0x7FFFFF
* @param s The short to write, less than 0x7FFFFF
*/
public static void writeVarShort(DataOutput to, int s) throws IOException {
int low = s & 0x7FFF;
@@ -45,16 +48,17 @@ public class MCDataOutputWrapper implements MCDataOutput {
}
/**
* Mimics ByteBufUtils
* Write a String with UTF8 byte encoding to the buffer.
* It is encoded as <varint length>[<UTF8 char bytes>]
* @param to the data output to write to
* Mimics ByteBufUtils Write a String with UTF8 byte encoding to the buffer. It is encoded as <varint length>[<UTF8
* char bytes>]
*
* @param to the data output to write to
* @param string The string to write
*/
public static void writeUTF8String(DataOutput to, String string) throws IOException {
byte[] utf8Bytes = string.getBytes(Charsets.UTF_8);
Validate.isTrue(
ByteBufUtils.varIntByteCount(utf8Bytes.length) < 3, "The string is too long for this encoding.");
ByteBufUtils.varIntByteCount(utf8Bytes.length) < 3,
"The string is too long for this encoding.");
writeVarInt(to, utf8Bytes.length);
to.write(utf8Bytes);
}
@@ -1,12 +1,14 @@
package codechicken.lib.gui;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.ResourceLocation;
import codechicken.lib.render.CCRenderState;
import codechicken.lib.render.TextureDataHolder;
import codechicken.lib.render.TextureUtils;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.ResourceLocation;
public class Canvas9Seg {
public final ResourceLocation tex;
public float[] seg_u = new float[4];
public float[] seg_v = new float[4];
@@ -65,8 +67,8 @@ public class Canvas9Seg {
CCRenderState.reset();
CCRenderState.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};
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);
@@ -1,11 +1,10 @@
package codechicken.lib.gui;
import codechicken.lib.math.MathHelper;
import codechicken.lib.render.CCRenderState;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
@@ -13,12 +12,18 @@ import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import codechicken.lib.math.MathHelper;
import codechicken.lib.render.CCRenderState;
public class GuiDraw {
public static class GuiHook extends Gui {
public void setZLevel(float f) {
zLevel = f;
}
@@ -135,6 +140,7 @@ public class GuiDraw {
private static List<ITooltipLineHandler> tipLineHandlers = new ArrayList<ITooltipLineHandler>();
public static interface ITooltipLineHandler {
public Dimension getSize();
public void draw(int x, int y);
@@ -166,8 +172,7 @@ public class GuiDraw {
for (int i = 0; i < list.size(); i++) {
String s = list.get(i);
ITooltipLineHandler line = getTipLine(s);
Dimension d = line != null
? line.getSize()
Dimension d = line != null ? line.getSize()
: new Dimension(
font.getStringWidth(s),
list.get(i).endsWith(TOOLTIP_LINESPACE) && i + 1 < list.size() ? 12 : 10);
@@ -1,13 +1,9 @@
package codechicken.lib.inventory;
import codechicken.lib.packet.PacketCustom;
import codechicken.lib.packet.PacketCustom.IClientPacketHandler;
import codechicken.lib.packet.PacketCustom.IServerPacketHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -18,19 +14,27 @@ import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.network.play.INetHandlerPlayClient;
import net.minecraft.network.play.INetHandlerPlayServer;
import org.apache.logging.log4j.LogManager;
import codechicken.lib.packet.PacketCustom;
import codechicken.lib.packet.PacketCustom.IClientPacketHandler;
import codechicken.lib.packet.PacketCustom.IServerPacketHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
/**
* Clean container implementation with a few extra features.
* Easy shift-click handling.
* Hooks for slot clicks, large stack sizes and some networking.
* Clean container implementation with a few extra features. Easy shift-click handling. Hooks for slot clicks, large
* stack sizes and some networking.
*/
public abstract class ContainerExtended extends Container implements ICrafting {
private static final String netChannel = "CCL:Container";
private static int nextNetworkID = 0;
static {
PacketCustom.assignHandler(netChannel, new IClientPacketHandler() {
@Override
public void handlePacket(PacketCustom packet, Minecraft mc, INetHandlerPlayClient handler) {
Container cont = mc.thePlayer.openContainer;
@@ -42,6 +46,7 @@ public abstract class ContainerExtended extends Container implements ICrafting {
}
});
PacketCustom.assignHandler(netChannel, new IServerPacketHandler() {
@Override
public void handlePacket(PacketCustom packet, EntityPlayerMP sender, INetHandlerPlayServer handler) {
Container cont = sender.openContainer;
@@ -87,8 +92,8 @@ public abstract class ContainerExtended extends Container implements ICrafting {
sendContainerAndContentsToPlayer(container, list, playerCrafters);
}
public void sendContainerAndContentsToPlayer(
Container container, List<ItemStack> list, List<EntityPlayerMP> playerCrafters) {
public void sendContainerAndContentsToPlayer(Container container, List<ItemStack> list,
List<EntityPlayerMP> playerCrafters) {
LinkedList<ItemStack> largeStacks = new LinkedList<ItemStack>();
for (int i = 0; i < list.size(); i++) {
ItemStack stack = list.get(i);
@@ -159,8 +164,7 @@ public abstract class ContainerExtended extends Container implements ICrafting {
Slot slot = (Slot) inventorySlots.get(slotIndex);
ItemStack slotStack = slot.getStack();
if (slotStack != null
&& slotStack.getItem() == stack.getItem()
if (slotStack != null && slotStack.getItem() == stack.getItem()
&& (!stack.getHasSubtypes() || stack.getItemDamage() == slotStack.getItemDamage())
&& ItemStack.areItemStackTagsEqual(stack, slotStack)) {
int totalStackSize = slotStack.stackSize + stack.stackSize;
@@ -211,7 +215,8 @@ public abstract class ContainerExtended extends Container implements ICrafting {
}
/**
* Called when slotIndex is shift clicked on. Recommended implementation is to call mergeItemStack based on slotIndex
* Called when slotIndex is shift clicked on. Recommended implementation is to call mergeItemStack based on
* slotIndex
*
* @param stack The stack in the clicked slot
* @return True if one or more items were moved from this slots into other slots
@@ -225,9 +230,8 @@ public abstract class ContainerExtended extends Container implements ICrafting {
}
protected void bindPlayerInventory(InventoryPlayer inventoryPlayer, int x, int y) {
for (int row = 0; row < 3; row++)
for (int col = 0; col < 9; col++)
addSlotToContainer(new Slot(inventoryPlayer, col + row * 9 + 9, x + col * 18, y + row * 18));
for (int row = 0; row < 3; row++) for (int col = 0; col < 9; col++)
addSlotToContainer(new Slot(inventoryPlayer, col + row * 9 + 9, x + col * 18, y + row * 18));
for (int slot = 0; slot < 9; slot++) addSlotToContainer(new Slot(inventoryPlayer, slot, x + slot * 18, y + 58));
}
@@ -241,15 +245,15 @@ public abstract class ContainerExtended extends Container implements ICrafting {
}
/**
* @param type An identifying number for the packet type between 2 and 0x79 inclusive. 1 is reserved for synchronising networkIDs
* @param type An identifying number for the packet type between 2 and 0x79 inclusive. 1 is reserved for
* synchronising networkIDs
* @return A packet on the CCL inventory channel that will be recieved by this container on the other network side
*/
public PacketCustom getPacket(int type) {
if (netID == 0)
LogManager.getLogger("CodeChickenLib").error("Tried to get packet for container with 0 network ID");
if (type == 1)
throw new IllegalArgumentException(
"Packet type 1 is reserved for network synchronisation in ContainerExtended");
if (type == 1) throw new IllegalArgumentException(
"Packet type 1 is reserved for network synchronisation in ContainerExtended");
return new PacketCustom(netChannel, type).writeInt(netID);
}
@@ -1,19 +1,22 @@
package codechicken.lib.inventory;
import codechicken.lib.packet.PacketCustom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.Container;
import net.minecraft.item.ItemStack;
import codechicken.lib.packet.PacketCustom;
public abstract class ContainerSynchronised extends ContainerExtended {
private ArrayList<IContainerSyncVar> syncVars = new ArrayList<IContainerSyncVar>();
/**
* Create a packet to be used to send a synced variable update.
* Calls getPacket. Can be overriden to add extra identifying data or change the type (default 2)
* Create a packet to be used to send a synced variable update. Calls getPacket. Can be overriden to add extra
* identifying data or change the type (default 2)
*/
public PacketCustom createSyncPacket() {
return getPacket(2);
@@ -36,8 +39,8 @@ public abstract class ContainerSynchronised extends ContainerExtended {
}
@Override
public void sendContainerAndContentsToPlayer(
Container container, List<ItemStack> list, List<EntityPlayerMP> playerCrafters) {
public void sendContainerAndContentsToPlayer(Container container, List<ItemStack> list,
List<EntityPlayerMP> playerCrafters) {
super.sendContainerAndContentsToPlayer(container, list, playerCrafters);
for (int i = 0; i < syncVars.size(); i++) {
IContainerSyncVar var = syncVars.get(i);
@@ -3,6 +3,7 @@ package codechicken.lib.inventory;
import codechicken.lib.packet.PacketCustom;
public interface IContainerSyncVar {
public boolean changed();
public void reset();
@@ -3,6 +3,7 @@ package codechicken.lib.inventory;
import codechicken.lib.packet.PacketCustom;
public abstract class IntegerSync implements IContainerSyncVar {
public int c_value;
@Override
@@ -8,6 +8,7 @@ import net.minecraft.item.ItemStack;
* Creates a copy of an IInventory for extended simulation
*/
public class InventoryCopy implements IInventory {
public boolean[] accessible;
public ItemStack[] items;
public IInventory inv;
@@ -9,6 +9,7 @@ import net.minecraft.nbt.NBTTagCompound;
* IInventory implementation which saves and loads from an NBT tag
*/
public class InventoryNBT implements IInventory {
protected ItemStack[] items;
protected NBTTagCompound tag;
@@ -8,6 +8,7 @@ import net.minecraft.item.ItemStack;
* Inventory wrapper for unified ISided/IInventory access
*/
public class InventoryRange {
public IInventory inv;
public int side;
public ISidedInventory sidedInv;
@@ -8,6 +8,7 @@ import net.minecraft.item.ItemStack;
* Simple IInventory implementation with an array of items, name and maximum stack size
*/
public class InventorySimple implements IInventory {
public ItemStack[] items;
public int limit;
public String name;
@@ -1,7 +1,5 @@
package codechicken.lib.inventory;
import codechicken.lib.vec.Vector3;
import com.google.common.base.Objects;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
@@ -17,7 +15,12 @@ import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import codechicken.lib.vec.Vector3;
import com.google.common.base.Objects;
public class InventoryUtils {
/**
* Constructor for ItemStack with tag
*/
@@ -167,8 +170,7 @@ public class InventoryUtils {
ItemStack base = inv.inv.getStackInSlot(slot);
if (!canStack(base, stack) || !inv.canInsertItem(slot, stack)) return 0;
int fit = base != null
? incrStackSize(base, inv.inv.getInventoryStackLimit() - base.stackSize)
int fit = base != null ? incrStackSize(base, inv.inv.getInventoryStackLimit() - base.stackSize)
: inv.inv.getInventoryStackLimit();
return Math.min(fit, stack.stackSize);
}
@@ -227,8 +229,7 @@ public class InventoryUtils {
public static boolean areStacksIdentical(ItemStack stack1, ItemStack stack2) {
if (stack1 == null || stack2 == null) return stack1 == stack2;
return stack1.getItem() == stack2.getItem()
&& stack1.getItemDamage() == stack2.getItemDamage()
return stack1.getItem() == stack2.getItem() && stack1.getItemDamage() == stack2.getItemDamage()
&& stack1.stackSize == stack2.stackSize
&& Objects.equal(stack1.getTagCompound(), stack2.getTagCompound());
}
@@ -244,36 +245,30 @@ public class InventoryUtils {
return (IInventory) tile;
}
public static final ForgeDirection[] chestSides =
new ForgeDirection[] {ForgeDirection.WEST, ForgeDirection.EAST, ForgeDirection.NORTH, ForgeDirection.SOUTH};
public static final ForgeDirection[] chestSides = new ForgeDirection[] { ForgeDirection.WEST, ForgeDirection.EAST,
ForgeDirection.NORTH, ForgeDirection.SOUTH };
public static IInventory getChest(TileEntityChest chest) {
for (ForgeDirection fside : chestSides) {
if (chest.getWorldObj()
.getBlock(
chest.xCoord + fside.offsetX,
chest.yCoord + fside.offsetY,
chest.zCoord + fside.offsetZ)
.getBlock(chest.xCoord + fside.offsetX, chest.yCoord + fside.offsetY, chest.zCoord + fside.offsetZ)
== chest.getBlockType())
return new InventoryLargeChest(
"container.chestDouble",
(TileEntityChest) chest.getWorldObj()
.getTileEntity(
chest.xCoord + fside.offsetX,
chest.yCoord + fside.offsetY,
chest.zCoord + fside.offsetZ),
(TileEntityChest) chest.getWorldObj().getTileEntity(
chest.xCoord + fside.offsetX,
chest.yCoord + fside.offsetY,
chest.zCoord + fside.offsetZ),
chest);
}
return chest;
}
public static boolean canStack(ItemStack stack1, ItemStack stack2) {
return stack1 == null
|| stack2 == null
return stack1 == null || stack2 == null
|| (stack1.getItem() == stack2.getItem()
&& (!stack2.getHasSubtypes() || stack2.getItemDamage() == stack1.getItemDamage())
&& ItemStack.areItemStackTagsEqual(stack2, stack1))
&& stack1.isStackable();
&& (!stack2.getHasSubtypes() || stack2.getItemDamage() == stack1.getItemDamage())
&& ItemStack.areItemStackTagsEqual(stack2, stack1)) && stack1.isStackable();
}
/**
@@ -2,16 +2,18 @@ package codechicken.lib.inventory;
import static codechicken.lib.inventory.InventoryUtils.actualDamage;
import com.google.common.base.Objects;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.oredict.OreDictionary;
import com.google.common.base.Objects;
/**
* Comparable ItemStack with a hashCode implementation.
*/
public class ItemKey implements Comparable<ItemKey> {
public ItemStack stack;
private int hashcode = 0;
@@ -37,15 +39,13 @@ public class ItemKey implements Comparable<ItemKey> {
if (!(obj instanceof ItemKey)) return false;
ItemKey k = (ItemKey) obj;
return stack.getItem() == k.stack.getItem()
&& actualDamage(stack) == actualDamage(k.stack)
return stack.getItem() == k.stack.getItem() && actualDamage(stack) == actualDamage(k.stack)
&& Objects.equal(stack.stackTagCompound, k.stack.stackTagCompound);
}
@Override
public int hashCode() {
return hashcode != 0
? hashcode
return hashcode != 0 ? hashcode
: (hashcode = Objects.hashCode(stack.getItem(), actualDamage(stack), stack.stackTagCompound));
}
@@ -5,6 +5,7 @@ import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
public class SlotDummy extends SlotHandleClicks {
public final int stackLimit;
public SlotDummy(IInventory inv, int slot, int x, int y) {
@@ -5,6 +5,7 @@ import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
public class SlotDummyOutput extends SlotHandleClicks {
public SlotDummyOutput(IInventory inv, int slot, int x, int y) {
super(inv, slot, x, y);
}
@@ -6,6 +6,7 @@ import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
public abstract class SlotHandleClicks extends Slot {
public SlotHandleClicks(IInventory inv, int slot, int x, int y) {
super(inv, slot, x, y);
}
@@ -6,6 +6,7 @@ import codechicken.lib.vec.Rotation;
import codechicken.lib.vec.Vector3;
public class LC implements Copyable<LC> {
public int side;
public float fa;
public float fb;
@@ -1,16 +1,19 @@
package codechicken.lib.lighting;
import codechicken.lib.colour.ColourRGBA;
import codechicken.lib.render.CCRenderState;
import codechicken.lib.vec.BlockCoord;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.world.IBlockAccess;
import codechicken.lib.colour.ColourRGBA;
import codechicken.lib.render.CCRenderState;
import codechicken.lib.vec.BlockCoord;
/**
* Note that when using the class as a vertex transformer, the vertices are assumed to be within the BB (x, y, z) -> (x+1, y+1, z+1)
* Note that when using the class as a vertex transformer, the vertices are assumed to be within the BB (x, y, z) ->
* (x+1, y+1, z+1)
*/
public class LightMatrix implements CCRenderState.IVertexOperation {
public static final int operationIndex = CCRenderState.registerOperation();
public int computed = 0;
@@ -27,55 +30,26 @@ public class LightMatrix implements CCRenderState.IVertexOperation {
/**
* The 9 positions in the sample array for each side, sides >= 6 are centered on sample 13 (the block itself)
*/
public static final int[][] ssamplem = new int[][] {
{0, 1, 2, 3, 4, 5, 6, 7, 8},
{18, 19, 20, 21, 22, 23, 24, 25, 26},
{0, 9, 18, 1, 10, 19, 2, 11, 20},
{6, 15, 24, 7, 16, 25, 8, 17, 26},
{0, 3, 6, 9, 12, 15, 18, 21, 24},
{2, 5, 8, 11, 14, 17, 20, 23, 26},
{9, 10, 11, 12, 13, 14, 15, 16, 17},
{9, 10, 11, 12, 13, 14, 15, 16, 17},
{3, 12, 21, 4, 13, 22, 5, 14, 23},
{3, 12, 21, 4, 13, 22, 5, 14, 23},
{1, 4, 7, 10, 13, 16, 19, 22, 25},
{1, 4, 7, 10, 13, 16, 19, 22, 25},
{13, 13, 13, 13, 13, 13, 13, 13, 13}
};
public static final int[][] ssamplem = new int[][] { { 0, 1, 2, 3, 4, 5, 6, 7, 8 },
{ 18, 19, 20, 21, 22, 23, 24, 25, 26 }, { 0, 9, 18, 1, 10, 19, 2, 11, 20 },
{ 6, 15, 24, 7, 16, 25, 8, 17, 26 }, { 0, 3, 6, 9, 12, 15, 18, 21, 24 },
{ 2, 5, 8, 11, 14, 17, 20, 23, 26 }, { 9, 10, 11, 12, 13, 14, 15, 16, 17 },
{ 9, 10, 11, 12, 13, 14, 15, 16, 17 }, { 3, 12, 21, 4, 13, 22, 5, 14, 23 },
{ 3, 12, 21, 4, 13, 22, 5, 14, 23 }, { 1, 4, 7, 10, 13, 16, 19, 22, 25 },
{ 1, 4, 7, 10, 13, 16, 19, 22, 25 }, { 13, 13, 13, 13, 13, 13, 13, 13, 13 } };
public static final int[][] qsamplem = new int[][] { // the positions in the side sample array for each corner
{0, 1, 3, 4},
{5, 1, 2, 4},
{6, 7, 3, 4},
{5, 7, 8, 4}
};
public static final float[] sideao = new float[] {
0.5F, 1F, 0.8F, 0.8F, 0.6F, 0.6F,
0.5F, 1F, 0.8F, 0.8F, 0.6F, 0.6F,
1F
};
{ 0, 1, 3, 4 }, { 5, 1, 2, 4 }, { 6, 7, 3, 4 }, { 5, 7, 8, 4 } };
public static final float[] sideao = new float[] { 0.5F, 1F, 0.8F, 0.8F, 0.6F, 0.6F, 0.5F, 1F, 0.8F, 0.8F, 0.6F,
0.6F, 1F };
/*static
{
int[][] os = new int[][]{
{0,-1,0},
{0, 1,0},
{0,0,-1},
{0,0, 1},
{-1,0,0},
{ 1,0,0}};
for(int s = 0; s < 12; s++)
{
int[] d0 = s < 6 ? new int[]{os[s][0]+1, os[s][1]+1, os[s][2]+1} : new int[]{1, 1, 1};
int[] d1 = os[((s&0xE)+3)%6];
int[] d2 = os[((s&0xE)+5)%6];
for(int a = -1; a <= 1; a++)
for(int b = -1; b <= 1; b++)
ssamplem[s][(a+1)*3+b+1] = (d0[1]+d1[1]*a+d2[1]*b)*9+(d0[2]+d1[2]*a+d2[2]*b)*3+(d0[0]+d1[0]*a+d2[0]*b);
}
System.out.println(Arrays.deepToString(ssamplem));
}*/
/*
* static { int[][] os = new int[][]{ {0,-1,0}, {0, 1,0}, {0,0,-1}, {0,0, 1}, {-1,0,0}, { 1,0,0}}; for(int s = 0; s
* < 12; s++) { int[] d0 = s < 6 ? new int[]{os[s][0]+1, os[s][1]+1, os[s][2]+1} : new int[]{1, 1, 1}; int[] d1 =
* os[((s&0xE)+3)%6]; int[] d2 = os[((s&0xE)+5)%6]; for(int a = -1; a <= 1; a++) for(int b = -1; b <= 1; b++)
* ssamplem[s][(a+1)*3+b+1] = (d0[1]+d1[1]*a+d2[1]*b)*9+(d0[2]+d1[2]*a+d2[2]*b)*3+(d0[0]+d1[0]*a+d2[0]*b); }
* System.out.println(Arrays.deepToString(ssamplem)); }
*/
public void locate(IBlockAccess a, int x, int y, int z) {
access = a;
@@ -5,9 +5,11 @@ import codechicken.lib.vec.Rotation;
import codechicken.lib.vec.Vector3;
public class LightModel implements CCRenderState.IVertexOperation {
public static final int operationIndex = CCRenderState.registerOperation();
public static class Light {
public Vector3 ambient = new Vector3();
public Vector3 diffuse = new Vector3();
public Vector3 position;
@@ -30,8 +32,7 @@ public class LightModel implements CCRenderState.IVertexOperation {
public static LightModel standardLightModel;
static {
standardLightModel = new LightModel()
.setAmbient(new Vector3(0.4, 0.4, 0.4))
standardLightModel = new LightModel().setAmbient(new Vector3(0.4, 0.4, 0.4))
.addLight(new Light(new Vector3(0.2, 1, -0.7)).setDiffuse(new Vector3(0.6, 0.6, 0.6)))
.addLight(new Light(new Vector3(-0.2, 1, 0.7)).setDiffuse(new Vector3(0.6, 0.6, 0.6)));
}
@@ -71,8 +72,7 @@ public class LightModel implements CCRenderState.IVertexOperation {
if (n_colour.z > 1) n_colour.z = 1;
n_colour.multiply((colour >>> 24) / 255D, (colour >> 16 & 0xFF) / 255D, (colour >> 8 & 0xFF) / 255D);
return (int) (n_colour.x * 255) << 24
| (int) (n_colour.y * 255) << 16
return (int) (n_colour.x * 255) << 24 | (int) (n_colour.y * 255) << 16
| (int) (n_colour.z * 255) << 8
| colour & 0xFF;
}
@@ -1,11 +1,13 @@
package codechicken.lib.lighting;
import codechicken.lib.render.CCRenderState;
import codechicken.lib.vec.BlockCoord;
import net.minecraft.block.Block;
import net.minecraft.world.IBlockAccess;
import codechicken.lib.render.CCRenderState;
import codechicken.lib.vec.BlockCoord;
public class PlanarLightMatrix extends PlanarLightModel {
public static final int operationIndex = CCRenderState.registerOperation();
public static PlanarLightMatrix instance = new PlanarLightMatrix();
@@ -29,8 +31,8 @@ public class PlanarLightMatrix extends PlanarLightModel {
public int brightness(int side) {
if ((sampled & 1 << side) == 0) {
Block b = access.getBlock(pos.x, pos.y, pos.z);
brightness[side] = access.getLightBrightnessForSkyBlocks(
pos.x, pos.y, pos.z, b.getLightValue(access, pos.x, pos.y, pos.z));
brightness[side] = access
.getLightBrightnessForSkyBlocks(pos.x, pos.y, pos.z, b.getLightValue(access, pos.x, pos.y, pos.z));
sampled |= 1 << side;
}
return brightness[side];
@@ -7,6 +7,7 @@ import codechicken.lib.render.CCRenderState;
* Faster precomputed version of LightModel that only works for axis planar sides
*/
public class PlanarLightModel implements CCRenderState.IVertexOperation {
public static PlanarLightModel standardLightModel = LightModel.standardLightModel.reducePlanar();
public int[] colours;
@@ -1,14 +1,16 @@
package codechicken.lib.lighting;
import net.minecraft.block.Block;
import net.minecraft.world.IBlockAccess;
import codechicken.lib.render.CCRenderState;
import codechicken.lib.vec.BlockCoord;
import net.minecraft.block.Block;
import net.minecraft.world.IBlockAccess;
/**
* Faster precomputed version of LightModel that only works for axis planar sides
*/
public class SimpleBrightnessModel implements CCRenderState.IVertexOperation {
public static final int operationIndex = CCRenderState.registerOperation();
public static SimpleBrightnessModel instance = new SimpleBrightnessModel();
@@ -29,8 +31,8 @@ public class SimpleBrightnessModel implements CCRenderState.IVertexOperation {
if ((sampled & 1 << side) == 0) {
c.set(pos).offset(side);
Block block = access.getBlock(c.x, c.y, c.z);
samples[side] =
access.getLightBrightnessForSkyBlocks(c.x, c.y, c.z, block.getLightValue(access, c.x, c.y, c.z));
samples[side] = access
.getLightBrightnessForSkyBlocks(c.x, c.y, c.z, block.getLightValue(access, c.x, c.y, c.z));
sampled |= 1 << side;
}
return samples[side];
@@ -1,6 +1,7 @@
package codechicken.lib.math;
public class MathHelper {
public static final double phi = 1.618033988749894;
public static final double pi = Math.PI;
public static final double todeg = 57.29577951308232;
@@ -27,8 +28,8 @@ public class MathHelper {
}
/**
* @param a The value
* @param b The value to approach
* @param a The value
* @param b The value to approach
* @param max The maximum step
* @return the closed value to b no less than max from a
*/
@@ -37,8 +38,8 @@ public class MathHelper {
}
/**
* @param a The value
* @param b The value to approach
* @param a The value
* @param b The value to approach
* @param max The maximum step
* @return the closed value to b no less than max from a
*/
@@ -67,8 +68,8 @@ public class MathHelper {
}
/**
* @param a The value
* @param b The value to approach
* @param a The value
* @param b The value to approach
* @param ratio The ratio to reduce the difference by
* @return a+(b-a)*ratio
*/
@@ -77,10 +78,10 @@ public class MathHelper {
}
/**
* @param a The value
* @param b The value to approach
* @param a The value
* @param b The value to approach
* @param ratio The ratio to reduce the difference by
* @param cap The maximum amount to advance by
* @param cap The maximum amount to advance by
* @return a+(b-a)*ratio
*/
public static double approachExp(double a, double b, double ratio, double cap) {
@@ -90,11 +91,11 @@ public class MathHelper {
}
/**
* @param a The value
* @param b The value to approach
* @param a The value
* @param b The value to approach
* @param ratio The ratio to reduce the difference by
* @param c The value to retreat from
* @param kick The difference when a == c
* @param c The value to retreat from
* @param kick The difference when a == c
* @return
*/
public static double retreatExp(double a, double b, double c, double ratio, double kick) {
@@ -106,8 +107,8 @@ public class MathHelper {
/**
*
* @param value The value
* @param min The min value
* @param max The max value
* @param min The min value
* @param max The max value
* @return The clipped value between min and max
*/
public static double clip(double value, double min, double max) {
@@ -1,5 +1,6 @@
package codechicken.lib.packet;
public interface ICustomPacketTile {
public void handleDescriptionPacket(PacketCustom packet);
}
@@ -1,27 +1,10 @@
package codechicken.lib.packet;
import codechicken.lib.data.MCDataInput;
import codechicken.lib.data.MCDataOutput;
import codechicken.lib.vec.BlockCoord;
import com.google.common.collect.Maps;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.network.*;
import cpw.mods.fml.common.network.handshake.NetworkDispatcher;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import java.util.EnumMap;
import java.util.List;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -41,14 +24,39 @@ import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import codechicken.lib.data.MCDataInput;
import codechicken.lib.data.MCDataOutput;
import codechicken.lib.vec.BlockCoord;
import com.google.common.collect.Maps;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.network.*;
import cpw.mods.fml.common.network.handshake.NetworkDispatcher;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
public final class PacketCustom implements MCDataInput, MCDataOutput {
public static interface ICustomPacketHandler {}
public static interface ICustomPacketHandler {
}
public interface IClientPacketHandler extends ICustomPacketHandler {
public void handlePacket(PacketCustom packetCustom, Minecraft mc, INetHandlerPlayClient handler);
}
public interface IServerPacketHandler extends ICustomPacketHandler {
public void handlePacket(PacketCustom packetCustom, EntityPlayerMP sender, INetHandlerPlayServer handler);
}
@@ -56,6 +64,7 @@ public final class PacketCustom implements MCDataInput, MCDataOutput {
@ChannelHandler.Sharable
public static class CustomInboundHandler extends SimpleChannelInboundHandler<FMLProxyPacket> {
public EnumMap<Side, CustomHandler> handlers = Maps.newEnumMap(Side.class);
@Override
@@ -66,19 +75,20 @@ public final class PacketCustom implements MCDataInput, MCDataOutput {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FMLProxyPacket msg) throws Exception {
handlers.get(ctx.channel().attr(NetworkRegistry.CHANNEL_SOURCE).get())
.handle(
ctx.channel().attr(NetworkRegistry.NET_HANDLER).get(),
ctx.channel().attr(NetworkRegistry.FML_CHANNEL).get(),
new PacketCustom(msg.payload()));
handlers.get(ctx.channel().attr(NetworkRegistry.CHANNEL_SOURCE).get()).handle(
ctx.channel().attr(NetworkRegistry.NET_HANDLER).get(),
ctx.channel().attr(NetworkRegistry.FML_CHANNEL).get(),
new PacketCustom(msg.payload()));
}
}
private static interface CustomHandler {
public void handle(INetHandler handler, String channel, PacketCustom packet) throws Exception;
}
public static class ClientInboundHandler implements CustomHandler {
private IClientPacketHandler handler;
public ClientInboundHandler(ICustomPacketHandler handler) {
@@ -94,6 +104,7 @@ public final class PacketCustom implements MCDataInput, MCDataOutput {
}
public static class ServerInboundHandler implements CustomHandler {
private IServerPacketHandler handler;
public ServerInboundHandler(ICustomPacketHandler handler) {
@@ -102,18 +113,21 @@ public final class PacketCustom implements MCDataInput, MCDataOutput {
@Override
public void handle(INetHandler netHandler, String channel, PacketCustom packet) throws Exception {
if (netHandler instanceof NetHandlerPlayServer)
handler.handlePacket(
packet, ((NetHandlerPlayServer) netHandler).playerEntity, (INetHandlerPlayServer) netHandler);
if (netHandler instanceof NetHandlerPlayServer) handler.handlePacket(
packet,
((NetHandlerPlayServer) netHandler).playerEntity,
(INetHandlerPlayServer) netHandler);
else System.err.println("Invalid INetHandler for PacketCustom on channel: " + channel);
}
}
public static interface IHandshakeHandler {
public void handshakeRecieved(NetHandlerPlayServer netHandler);
}
public static class HandshakeInboundHandler extends ChannelInboundHandlerAdapter {
public IHandshakeHandler handler;
public HandshakeInboundHandler(IHandshakeHandler handler) {
@@ -124,9 +138,7 @@ public final class PacketCustom implements MCDataInput, MCDataOutput {
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof NetworkHandshakeEstablished) {
INetHandler netHandler = ((NetworkDispatcher) ctx.channel()
.attr(FMLOutboundHandler.FML_MESSAGETARGETARGS)
.get())
.getNetHandler();
.attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).get()).getNetHandler();
if (netHandler instanceof NetHandlerPlayServer)
handler.handshakeRecieved((NetHandlerPlayServer) netHandler);
} else ctx.fireUserEventTriggered(evt);
@@ -136,14 +148,12 @@ public final class PacketCustom implements MCDataInput, MCDataOutput {
public static String channelName(Object channelKey) {
if (channelKey instanceof String) return (String) channelKey;
ModContainer mc = channelKey instanceof ModContainer
? (ModContainer) channelKey
ModContainer mc = channelKey instanceof ModContainer ? (ModContainer) channelKey
: FMLCommonHandler.instance().findContainerFor(channelKey);
if (mc != null) {
String s = mc.getModId();
if (s.length() > 20)
throw new IllegalArgumentException(
"Mod ID (" + s + ") too long for use as channel (20 chars). Use a string identifier");
if (s.length() > 20) throw new IllegalArgumentException(
"Mod ID (" + s + ") too long for use as channel (20 chars). Use a string identifier");
return s;
}
@@ -160,9 +170,7 @@ public final class PacketCustom implements MCDataInput, MCDataOutput {
String channelName = channelName(channelKey);
Side side = handler instanceof IServerPacketHandler ? Side.SERVER : Side.CLIENT;
FMLEmbeddedChannel channel = getOrCreateChannel(channelName, side);
channel.attr(cclHandler)
.get()
.handlers
channel.attr(cclHandler).get().handlers
.put(side, side == Side.SERVER ? new ServerInboundHandler(handler) : new ClientInboundHandler(handler));
}
@@ -225,7 +233,7 @@ public final class PacketCustom implements MCDataInput, MCDataOutput {
ByteBuf out = Unpooled.buffer(len + 5);
int clen = deflater.deflate(out.array(), 5, len);
if (clen >= len - 5 || !deflater.finished()) // not worth compressing, gets larger
return;
return;
out.setByte(0, type | 0x80);
out.setInt(1, len);
@@ -475,7 +483,7 @@ public final class PacketCustom implements MCDataInput, MCDataOutput {
public static void sendToPlayer(Packet packet, EntityPlayer player) {
if (player == null) sendToClients(packet);
else ((EntityPlayerMP) player).playerNetServerHandler.sendPacket(packet);
else((EntityPlayerMP) player).playerNetServerHandler.sendPacket(packet);
}
public void sendToClients() {
@@ -508,14 +516,15 @@ public final class PacketCustom implements MCDataInput, MCDataOutput {
public static void sendToChunk(Packet packet, World world, int chunkX, int chunkZ) {
PlayerManager playerManager = ((WorldServer) world).getPlayerManager();
for (EntityPlayerMP player :
(List<EntityPlayerMP>) MinecraftServer.getServer().getConfigurationManager().playerEntityList)
for (EntityPlayerMP player : (List<EntityPlayerMP>) MinecraftServer.getServer()
.getConfigurationManager().playerEntityList)
if (playerManager.isPlayerWatchingChunk(player, chunkX, chunkZ)) sendToPlayer(packet, player);
/* Commented until forge accepts access tranformer request
PlayerInstance p = ((WorldServer) world).getPlayerManager().getOrCreateChunkWatcher(chunkX, chunkZ, false);
if (p != null)
p.sendToAllPlayersWatchingChunk(packet);*/
/*
* Commented until forge accepts access tranformer request PlayerInstance p = ((WorldServer)
* world).getPlayerManager().getOrCreateChunkWatcher(chunkX, chunkZ, false); if (p != null)
* p.sendToAllPlayersWatchingChunk(packet);
*/
}
public void sendToOps() {
@@ -523,8 +532,8 @@ public final class PacketCustom implements MCDataInput, MCDataOutput {
}
public static void sendToOps(Packet packet) {
for (EntityPlayerMP player :
(List<EntityPlayerMP>) MinecraftServer.getServer().getConfigurationManager().playerEntityList)
for (EntityPlayerMP player : (List<EntityPlayerMP>) MinecraftServer.getServer()
.getConfigurationManager().playerEntityList)
if (MinecraftServer.getServer().getConfigurationManager().func_152596_g(player.getGameProfile()))
sendToPlayer(packet, player);
}
@@ -5,6 +5,7 @@ import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
public class ExtendedMOP extends MovingObjectPosition implements Comparable<ExtendedMOP> {
public Object data;
/**
* The square distance from the start of the raytrace.
@@ -3,6 +3,7 @@ package codechicken.lib.raytracer;
import codechicken.lib.vec.Cuboid6;
public class IndexedCuboid6 extends Cuboid6 {
public Object data;
public IndexedCuboid6(Object data, Cuboid6 cuboid) {
@@ -1,12 +1,7 @@
package codechicken.lib.raytracer;
import codechicken.lib.math.MathHelper;
import codechicken.lib.vec.BlockCoord;
import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Vector3;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
@@ -16,7 +11,15 @@ import net.minecraft.util.MovingObjectPosition.MovingObjectType;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import codechicken.lib.math.MathHelper;
import codechicken.lib.vec.BlockCoord;
import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Vector3;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class RayTracer {
private Vector3 vec = new Vector3();
private Vector3 vec2 = new Vector3();
@@ -62,17 +65,20 @@ public class RayTracer {
case 0:
case 1:
if (!MathHelper.between(cuboid.min.x, hit.x, cuboid.max.x)
|| !MathHelper.between(cuboid.min.z, hit.z, cuboid.max.z)) return;
|| !MathHelper.between(cuboid.min.z, hit.z, cuboid.max.z))
return;
break;
case 2:
case 3:
if (!MathHelper.between(cuboid.min.x, hit.x, cuboid.max.x)
|| !MathHelper.between(cuboid.min.y, hit.y, cuboid.max.y)) return;
|| !MathHelper.between(cuboid.min.y, hit.y, cuboid.max.y))
return;
break;
case 4:
case 5:
if (!MathHelper.between(cuboid.min.y, hit.y, cuboid.max.y)
|| !MathHelper.between(cuboid.min.z, hit.z, cuboid.max.z)) return;
|| !MathHelper.between(cuboid.min.z, hit.z, cuboid.max.z))
return;
break;
}
@@ -114,8 +120,8 @@ public class RayTracer {
return c_hit;
}
public MovingObjectPosition rayTraceCuboids(
Vector3 start, Vector3 end, List<IndexedCuboid6> cuboids, BlockCoord pos, Block block) {
public MovingObjectPosition rayTraceCuboids(Vector3 start, Vector3 end, List<IndexedCuboid6> cuboids,
BlockCoord pos, Block block) {
MovingObjectPosition mop = rayTraceCuboids(start, end, cuboids);
if (mop != null) {
mop.typeOfHit = MovingObjectType.BLOCK;
@@ -160,8 +166,8 @@ public class RayTracer {
public static Vec3 getCorrectedHeadVec(EntityPlayer player) {
Vec3 v = Vec3.createVectorHelper(player.posX, player.posY, player.posZ);
if (player.worldObj.isRemote) {
v.yCoord +=
player.getEyeHeight() - player.getDefaultEyeHeight(); // compatibility with eye height changing mods
v.yCoord += player.getEyeHeight() - player.getDefaultEyeHeight(); // compatibility with eye height changing
// mods
} else {
v.yCoord += player.getEyeHeight();
if (player instanceof EntityPlayerMP && player.isSneaking()) v.yCoord -= 0.08;
@@ -174,8 +180,7 @@ public class RayTracer {
}
public static double getBlockReachDistance(EntityPlayer player) {
return player.worldObj.isRemote
? getBlockReachDistance_client()
return player.worldObj.isRemote ? getBlockReachDistance_client()
: player instanceof EntityPlayerMP ? getBlockReachDistance_server((EntityPlayerMP) player) : 5D;
}
@@ -5,9 +5,11 @@ import codechicken.lib.render.CCRenderState.VertexAttribute;
import codechicken.lib.vec.Cuboid6;
public class BlockRenderer {
public static class BlockFace implements CCRenderState.IVertexSource {
public Vertex5[] verts = new Vertex5[] {new Vertex5(), new Vertex5(), new Vertex5(), new Vertex5()};
public LC[] lightCoords = new LC[] {new LC(), new LC(), new LC(), new LC()};
public Vertex5[] verts = new Vertex5[] { new Vertex5(), new Vertex5(), new Vertex5(), new Vertex5() };
public LC[] lightCoords = new LC[] { new LC(), new LC(), new LC(), new LC() };
public boolean lcComputed = false;
public int side;
@@ -119,6 +121,7 @@ public class BlockRenderer {
}
public static class FullBlock implements CCRenderState.IVertexSource {
public Vertex5[] verts = CCModel.quadModel(24).generateBlock(0, Cuboid6.full).verts;
public LC[] lightCoords = new LC[24];
@@ -156,31 +159,32 @@ public class BlockRenderer {
/**
* Renders faces of a block-like model based on a sideMask. Eg for side 2, verts 8-11 will be rendered
*
* @param sideMask A mask of faces not to render
*/
public static void renderFaces(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();
}
for (int s = 0; s < 6; s++) if ((sideMask & 1 << s) == 0) {
CCRenderState.setVertexRange(s * 4, (s + 1) * 4);
CCRenderState.render();
}
}
private static BlockFace face = new BlockFace();
/**
* Renders faces of a cuboid with texture coordinates mapped to match a standard minecraft block
* @param bounds The bounding cuboid to render
*
* @param bounds The bounding cuboid to render
* @param sideMask A mask of faces not to render
*/
public static void renderCuboid(Cuboid6 bounds, int sideMask) {
if (sideMask == 0x3F) return;
CCRenderState.setModel(face);
for (int s = 0; s < 6; s++)
if ((sideMask & 1 << s) == 0) {
face.loadCuboidFace(bounds, s);
CCRenderState.render();
}
for (int s = 0; s < 6; s++) if ((sideMask & 1 << s) == 0) {
face.loadCuboidFace(bounds, s);
CCRenderState.render();
}
}
}
+101 -101
View File
@@ -2,6 +2,14 @@ package codechicken.lib.render;
import static codechicken.lib.vec.Rotation.sideRotations;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import codechicken.lib.lighting.LC;
import codechicken.lib.lighting.LightModel;
import codechicken.lib.render.uv.UV;
@@ -9,15 +17,11 @@ import codechicken.lib.render.uv.UVTransformation;
import codechicken.lib.render.uv.UVTranslation;
import codechicken.lib.util.Copyable;
import codechicken.lib.vec.*;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
private static class PositionNormalEntry {
public Vector3 pos;
public LinkedList<Vector3> normals = new LinkedList<Vector3>();
@@ -83,33 +87,23 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
/**
* Each pixel corresponds to one unit of position when generating the model
* @param i Vertex index to start generating at
*
* @param i Vertex index to start generating at
* @param x1 The minX bound of the box
* @param y1 The minY bound of the box
* @param z1 The minZ bound of the box
* @param w The width of the box
* @param h The height of the box
* @param d The depth of the box
* @param w The width of the box
* @param h The height of the box
* @param d The depth of the box
* @param tx The distance of the top left corner of the texture map from the left in pixels
* @param ty The distance of the top left corner of the texture map from the top in pixels
* @param tw The width of the texture in pixels
* @param th The height of the texture in pixels
* @param f The scale of the model, pixels per block, normally 16
* @param f The scale of the model, pixels per block, normally 16
* @return The generated model
*/
public CCModel generateBox(
int i,
double x1,
double y1,
double z1,
double w,
double h,
double d,
double tx,
double ty,
double tw,
double th,
double f) {
public CCModel generateBox(int i, double x1, double y1, double z1, double w, double h, double d, double tx,
double ty, double tw, double th, double f) {
double u1, v1, u2, v2;
double x2 = x1 + w;
double y2 = y1 + h;
@@ -186,7 +180,8 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
/**
* Generates a box, uv mapped to be the same as a minecraft block with the same bounds
* @param i The vertex index to start generating at
*
* @param i The vertex index to start generating at
* @param bounds The bounds of the block, 0 to 1
* @return The generated model. When rendering an icon will need to be supplied for the UV transformation.
*/
@@ -196,7 +191,14 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
public CCModel generateBlock(int i, Cuboid6 bounds, int mask) {
return generateBlock(
i, bounds.min.x, bounds.min.y, bounds.min.z, bounds.max.x, bounds.max.y, bounds.max.z, mask);
i,
bounds.min.x,
bounds.min.y,
bounds.min.z,
bounds.max.x,
bounds.max.y,
bounds.max.z,
mask);
}
public CCModel generateBlock(int i, double x1, double y1, double z1, double x2, double y2, double z2) {
@@ -205,13 +207,14 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
/**
* Generates a box, uv mapped to be the same as a minecraft block with the same bounds
* @param i The vertex index to start generating at
* @param x1 minX
* @param y1 minY
* @param z1 minZ
* @param x2 maxX
* @param y2 maxY
* @param z2 maxZ
*
* @param i The vertex index to start generating at
* @param x1 minX
* @param y1 minY
* @param z1 minZ
* @param x2 maxX
* @param y2 maxY
* @param z2 maxZ
* @param mask A bitmask of sides NOT to generate. I high bit at index s means side s will not be generated
* @return The generated model. When rendering an icon will need to be supplied for the UV transformation.
*/
@@ -292,10 +295,11 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
}
/**
* Computes the normals of all faces in the model.
* Uses the cross product of the vectors along 2 sides of the face
* @param start The first vertex to generate normals for
* @param length The number of vertices to generate normals for. Note this must be a multiple of 3 for triangles or 4 for quads
* Computes the normals of all faces in the model. Uses the cross product of the vectors along 2 sides of the face
*
* @param start The first vertex to generate normals for
* @param length The number of vertices to generate normals for. Note this must be a multiple of 3 for triangles or
* 4 for quads
* @return The model
*/
public CCModel computeNormals(int start, int length) {
@@ -315,8 +319,9 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
}
/**
* Computes lighting using the normals add a light model
* If the model is rotated, the lighting will no longer be valid
* Computes lighting using the normals add a light model If the model is rotated, the lighting will no longer be
* valid
*
* @return The model
*/
public CCModel computeLighting(LightModel light) {
@@ -338,6 +343,7 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
/**
* Computes the minecraft lighting coordinates for use with a LightMatrix
*
* @return The model
*/
public CCModel computeLightCoords() {
@@ -349,19 +355,18 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
/**
* Averages all normals at the same position to produce a smooth lighting effect.
*
* @return The model
*/
public CCModel smoothNormals() {
ArrayList<PositionNormalEntry> map = new ArrayList<PositionNormalEntry>();
Vector3[] normals = normals();
nextvert:
for (int k = 0; k < verts.length; k++) {
nextvert: for (int k = 0; k < verts.length; k++) {
Vector3 vec = verts[k].vec;
for (PositionNormalEntry e : map)
if (e.positionEqual(vec)) {
e.addNormal(normals[k]);
continue nextvert;
}
for (PositionNormalEntry e : map) if (e.positionEqual(vec)) {
e.addNormal(normals[k]);
continue nextvert;
}
map.add(new PositionNormalEntry(vec).addNormal(normals[k]));
}
@@ -397,14 +402,12 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
public CCModel expand(int extraVerts) {
int newLen = verts.length + extraVerts;
verts = Arrays.copyOf(verts, newLen);
for (int i = 0; i < attributes.size(); i++)
if (attributes.get(i) != null)
attributes.set(
i,
CCRenderState.copyOf(
(CCRenderState.VertexAttribute) CCRenderState.getAttribute(i),
attributes.get(i),
newLen));
for (int i = 0; i < attributes.size(); i++) if (attributes.get(i) != null) attributes.set(
i,
CCRenderState.copyOf(
(CCRenderState.VertexAttribute) CCRenderState.getAttribute(i),
attributes.get(i),
newLen));
return this;
}
@@ -427,9 +430,10 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
/**
* Renders vertices start through start+length-1 of the model
*
* @param start The first vertex index to render
* @param end The vertex index to render until
* @param ops Operations to apply
* @param end The vertex index to render until
* @param ops Operations to apply
*/
public void render(int start, int end, CCRenderState.IVertexOperation... ops) {
CCRenderState.setPipeline(this, start, end, ops);
@@ -481,8 +485,9 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
/**
* Parses vertices, texture coords, normals and polygons from a WaveFront Obj file
* @param input An input stream to a obj file
* @param vertexMode The vertex mode to create the model for (GL_TRIANGLES or GL_QUADS)
*
* @param input An input stream to a obj file
* @param vertexMode The vertex mode to create the model for (GL_TRIANGLES or GL_QUADS)
* @param coordSystem The cooridnate system transformation to apply
* @return A map of group names to models
* @throws IOException
@@ -584,25 +589,25 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
/**
* Parses vertices, texture coords, normals and polygons from a WaveFront Obj file
*
* @param res The resource for the obj file
* @return A map of group names to models
*/
public static Map<String, CCModel> parseObjModels(ResourceLocation res) {
return parseObjModels(res, 4, null);
}
/**
* Parses vertices, texture coords, normals and polygons from a WaveFront Obj file
* @param res The resource for the obj file
*
* @param res The resource for the obj file
* @param coordSystem The cooridnate system transformation to apply
* @return A map of group names to models
*/
public static Map<String, CCModel> parseObjModels(ResourceLocation res, Transformation coordSystem) {
try {
return parseObjModels(
Minecraft.getMinecraft()
.getResourceManager()
.getResource(res)
.getInputStream(),
Minecraft.getMinecraft().getResourceManager().getResource(res).getInputStream(),
4,
coordSystem);
} catch (IOException e) {
@@ -612,19 +617,17 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
/**
* Parses vertices, texture coords, normals and polygons from a WaveFront Obj file
* @param res The resource for the obj file
* @param vertexMode The vertex mode to create the model for (GL_TRIANGLES or GL_QUADS)
*
* @param res The resource for the obj file
* @param vertexMode The vertex mode to create the model for (GL_TRIANGLES or GL_QUADS)
* @param coordSystem The cooridnate system transformation to apply
* @return A map of group names to models
*/
public static Map<String, CCModel> parseObjModels(
ResourceLocation res, int vertexMode, Transformation coordSystem) {
public static Map<String, CCModel> parseObjModels(ResourceLocation res, int vertexMode,
Transformation coordSystem) {
try {
return parseObjModels(
Minecraft.getMinecraft()
.getResourceManager()
.getResource(res)
.getInputStream(),
Minecraft.getMinecraft().getResourceManager().getResource(res).getInputStream(),
vertexMode,
coordSystem);
} catch (Exception e) {
@@ -632,8 +635,8 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
}
}
public static CCModel createModel(
List<Vector3> verts, List<Vector3> uvs, List<Vector3> normals, int vertexMode, List<int[]> polys) {
public static CCModel createModel(List<Vector3> verts, List<Vector3> uvs, List<Vector3> normals, int vertexMode,
List<int[]> polys) {
int vp = vertexMode == 7 ? 4 : 3;
if (polys.size() < vp || polys.size() % vp != 0)
throw new IllegalArgumentException("Invalid number of vertices for model: " + polys.size());
@@ -725,8 +728,7 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
}
/**
* Brings the UV coordinates of each face closer to the center UV by d.
* Useful for fixing texture seams
* Brings the UV coordinates of each face closer to the center UV by d. Useful for fixing texture seams
*/
public CCModel shrinkUVs(double d) {
for (int k = 0; k < verts.length; k += vp) {
@@ -760,21 +762,20 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
public static void copy(CCModel src, int srcpos, CCModel dst, int destpos, int length) {
for (int k = 0; k < length; k++) dst.verts[destpos + k] = src.verts[srcpos + k].copy();
for (int i = 0; i < src.attributes.size(); i++)
if (src.attributes.get(i) != null)
CCRenderState.arrayCopy(
src.attributes.get(i),
srcpos,
dst.getOrAllocate(CCRenderState.getAttribute(i)),
destpos,
length);
for (int i = 0; i < src.attributes.size(); i++) if (src.attributes.get(i) != null) CCRenderState.arrayCopy(
src.attributes.get(i),
srcpos,
dst.getOrAllocate(CCRenderState.getAttribute(i)),
destpos,
length);
}
/**
* Generate models rotated to the other 5 sides of the block
*
* @param models An array of 6 models
* @param side The side of this model
* @param point The rotation point
* @param side The side of this model
* @param point The rotation point
*/
public static void generateSidedModels(CCModel[] models, int side, Vector3 point) {
for (int s = 0; s < 6; s++) {
@@ -786,9 +787,10 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
/**
* Generate models rotated to the other 3 horizontal of the block
*
* @param models An array of 4 models
* @param side The side of this model
* @param point The rotation point
* @param side The side of this model
* @param point The rotation point
*/
public static void generateSidedModelsH(CCModel[] models, int side, Vector3 point) {
for (int s = 2; s < 6; s++) {
@@ -804,6 +806,7 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
/**
* Generates copies of faces with clockwise vertices
*
* @return The model
*/
public static CCModel generateBackface(CCModel src, int srcpos, CCModel dst, int destpos, int length) {
@@ -811,17 +814,15 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
if (srcpos % vp != 0 || destpos % vp != 0 || length % vp != 0)
throw new IllegalArgumentException("Vertices do not align with polygons");
int[][] o = new int[][] {{0, 0}, {1, vp - 1}, {2, vp - 2}, {3, vp - 3}};
int[][] o = new int[][] { { 0, 0 }, { 1, vp - 1 }, { 2, vp - 2 }, { 3, vp - 3 } };
for (int i = 0; i < length; i++) {
int b = (i / vp) * vp;
int d = i % vp;
int di = destpos + b + o[d][1];
int si = srcpos + b + o[d][0];
dst.verts[di] = src.verts[si].copy();
for (int a = 0; a < src.attributes.size(); a++)
if (src.attributes.get(a) != null)
CCRenderState.arrayCopy(
src.attributes.get(a), si, dst.getOrAllocate(CCRenderState.getAttribute(a)), di, 1);
for (int a = 0; a < src.attributes.size(); a++) if (src.attributes.get(a) != null) CCRenderState
.arrayCopy(src.attributes.get(a), si, dst.getOrAllocate(CCRenderState.getAttribute(a)), di, 1);
if (dst.normals() != null && dst.normals()[di] != null) dst.normals()[di].negate();
}
@@ -829,8 +830,8 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
}
/**
* Generates sided copies of vertices into this model.
* Assumes that your model has been generated at vertex side*(numVerts/6)
* Generates sided copies of vertices into this model. Assumes that your model has been generated at vertex
* side*(numVerts/6)
*/
public CCModel generateSidedParts(int side, Vector3 point) {
if (verts.length % (6 * vp) != 0)
@@ -847,8 +848,8 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
}
/**
* Generates sided copies of vertices into this model.
* Assumes that your model has been generated at vertex side*(numVerts/4)
* Generates sided copies of vertices into this model. Assumes that your model has been generated at vertex
* side*(numVerts/4)
*/
public CCModel generateSidedPartsH(int side, Vector3 point) {
if (verts.length % (4 * vp) != 0)
@@ -885,11 +886,10 @@ public class CCModel implements CCRenderState.IVertexSource, Copyable<CCModel> {
}
Vector3[] normals = normals();
if (normals != null)
for (int k = 0; k < length; k++) {
normals[destpos + k] = normals[srcpos + k].copy();
t.applyN(normals[destpos + k]);
}
if (normals != null) for (int k = 0; k < length; k++) {
normals[destpos + k] = normals[srcpos + k].copy();
t.applyN(normals[destpos + k]);
}
return this;
}
@@ -5,6 +5,7 @@ import static codechicken.lib.math.MathHelper.phi;
import codechicken.lib.vec.*;
public class CCModelLibrary {
public static CCModel icosahedron4;
public static CCModel icosahedron7;
@@ -68,20 +69,12 @@ public class CCModelLibrary {
icosahedron7.computeNormals().smoothNormals();
}
private static void addIcosahedronTriangle(
Vector3 vec1,
double u1,
double v1,
Vector3 vec2,
double u2,
double v2,
Vector3 vec3,
double u3,
double v3) {
private static void addIcosahedronTriangle(Vector3 vec1, double u1, double v1, Vector3 vec2, double u2, double v2,
Vector3 vec3, double u3, double v3) {
icosahedron4.verts[i * 3] = icosahedron7.verts[i * 4] = new Vertex5(vec1, u1, v1);
icosahedron4.verts[i * 3 + 1] = icosahedron7.verts[i * 4 + 1] = new Vertex5(vec2, u2, v2);
icosahedron4.verts[i * 3 + 2] =
icosahedron7.verts[i * 4 + 2] = icosahedron7.verts[i * 4 + 3] = new Vertex5(vec3, u3, v3);
icosahedron4.verts[i * 3
+ 2] = icosahedron7.verts[i * 4 + 2] = icosahedron7.verts[i * 4 + 3] = new Vertex5(vec3, u3, v3);
i++;
}
@@ -1,11 +1,14 @@
package codechicken.lib.render;
import java.util.ArrayList;
import codechicken.lib.render.CCRenderState.IVertexOperation;
import codechicken.lib.render.CCRenderState.VertexAttribute;
import java.util.ArrayList;
public class CCRenderPipeline {
public class PipelineBuilder {
public PipelineBuilder add(IVertexOperation op) {
ops.add(op);
return this;
@@ -27,6 +30,7 @@ public class CCRenderPipeline {
}
private class PipelineNode {
public ArrayList<PipelineNode> deps = new ArrayList<PipelineNode>();
public IVertexOperation op;
@@ -81,9 +85,8 @@ public class CCRenderPipeline {
boolean loaded = op.load();
if (loaded) loading.op = op;
if (op instanceof VertexAttribute)
if (loaded) attribs.add((VertexAttribute) op);
else ((VertexAttribute) op).active = false;
if (op instanceof VertexAttribute) if (loaded) attribs.add((VertexAttribute) op);
else((VertexAttribute) op).active = false;
}
for (int i = 0; i < nodes.size(); i++) nodes.get(i).add();
@@ -1,5 +1,13 @@
package codechicken.lib.render;
import java.util.ArrayList;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.IBlockAccess;
import codechicken.lib.colour.ColourRGBA;
import codechicken.lib.lighting.LC;
import codechicken.lib.lighting.LightMatrix;
@@ -7,18 +15,13 @@ import codechicken.lib.util.Copyable;
import codechicken.lib.vec.Rotation;
import codechicken.lib.vec.Transformation;
import codechicken.lib.vec.Vector3;
import java.util.ArrayList;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.IBlockAccess;
/**
* 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. Rendering operations are written to avoid object allocations by reusing
* static variables.
*/
public class CCRenderState {
private static int nextOperationIndex;
public static int registerOperation() {
@@ -33,6 +36,7 @@ public class CCRenderState {
* Represents an operation to be run for each vertex that operates on and modifies the current state
*/
public static 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
@@ -45,8 +49,9 @@ public class CCRenderState {
public void 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
* 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();
}
@@ -63,15 +68,18 @@ public class CCRenderState {
}
/**
* Management class for a vertex attrute such as colour, normal etc
* This class should handle the loading of the attrute from an array provided by IVertexSource.getAttributes or the computation of this attrute from others
* Management class for a vertex attrute such as colour, normal etc This class should handle the loading of the
* attrute from an array provided by IVertexSource.getAttributes or the computation of this attrute from others
*
* @param <T> The array type for this attrute eg. int[], Vector3[]
*/
public abstract static class VertexAttribute<T> implements IVertexOperation {
public final int attributeIndex = registerVertexAttribute(this);
private final int operationIndex = registerOperation();
/**
* Set to true when the attrute is part of the pipeline. Should only be managed by CCRenderState when constructing the pipeline
* Set to true when the attrute is part of the pipeline. Should only be managed by CCRenderState when
* constructing the pipeline
*/
public boolean active = false;
@@ -102,18 +110,21 @@ public class CCRenderState {
}
public static interface IVertexSource {
public Vertex5[] getVertices();
/**
* Gets an array of vertex attrutes
*
* @param attr The vertex attrute to get
* @param <T> The attrute array type
* @param <T> The attrute array type
* @return An array, or null if not computed
*/
public <T> T getAttributes(VertexAttribute<T> 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
* @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);
@@ -124,6 +135,7 @@ public class CCRenderState {
}
public static VertexAttribute<Vector3[]> normalAttrib = new VertexAttribute<Vector3[]>() {
private Vector3[] normalRef;
@Override
@@ -151,6 +163,7 @@ public class CCRenderState {
}
};
public static VertexAttribute<int[]> colourAttrib = new VertexAttribute<int[]>() {
private int[] colourRef;
@Override
@@ -171,6 +184,7 @@ public class CCRenderState {
}
};
public static VertexAttribute<int[]> lightingAttrib = new VertexAttribute<int[]>() {
private int[] colourRef;
@Override
@@ -196,6 +210,7 @@ public class CCRenderState {
}
};
public static VertexAttribute<int[]> sideAttrib = new VertexAttribute<int[]>() {
private int[] sideRef;
@Override
@@ -222,6 +237,7 @@ public class CCRenderState {
* Uses the position of the lightmatrix to compute LC if not provided
*/
public static VertexAttribute<LC[]> lightCoordAttrib = new VertexAttribute<LC[]>() {
private LC[] lcRef;
private Vector3 vec = new Vector3(); // for computation
private Vector3 pos = new Vector3();
@@ -337,12 +353,11 @@ public class CCRenderState {
public static void writeVert() {
if (hasNormal) Tessellator.instance.setNormal((float) normal.x, (float) normal.y, (float) normal.z);
if (hasColour)
Tessellator.instance.setColorRGBA(
colour >>> 24,
colour >> 16 & 0xFF,
colour >> 8 & 0xFF,
alphaOverride >= 0 ? alphaOverride : colour & 0xFF);
if (hasColour) Tessellator.instance.setColorRGBA(
colour >>> 24,
colour >> 16 & 0xFF,
colour >> 8 & 0xFF,
alphaOverride >= 0 ? alphaOverride : colour & 0xFF);
if (hasBrightness) Tessellator.instance.setBrightness(brightness);
Tessellator.instance.addVertexWithUV(vert.vec.x, vert.vec.y, vert.vec.z, vert.uv.u, vert.uv.v);
}
@@ -401,12 +416,11 @@ public class CCRenderState {
public static void startDrawing(int mode) {
Tessellator.instance.startDrawing(mode);
if (hasColour)
Tessellator.instance.setColorRGBA(
colour >>> 24,
colour >> 16 & 0xFF,
colour >> 8 & 0xFF,
alphaOverride >= 0 ? alphaOverride : colour & 0xFF);
if (hasColour) Tessellator.instance.setColorRGBA(
colour >>> 24,
colour >> 16 & 0xFF,
colour >> 8 & 0xFF,
alphaOverride >= 0 ? alphaOverride : colour & 0xFF);
if (hasBrightness) Tessellator.instance.setBrightness(brightness);
}
@@ -3,6 +3,7 @@ package codechicken.lib.render;
import codechicken.lib.colour.ColourRGBA;
public class ColourMultiplier implements CCRenderState.IVertexOperation {
private static ColourMultiplier instance = new ColourMultiplier(-1);
public static ColourMultiplier instance(int colour) {
@@ -1,14 +1,16 @@
package codechicken.lib.render;
import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Vector3;
import net.minecraft.client.particle.EffectRenderer;
import net.minecraft.client.particle.EntityFX;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Vector3;
public class EntityDigIconFX extends EntityFX {
public EntityDigIconFX(World world, double x, double y, double z, double dx, double dy, double dz, IIcon icon) {
super(world, x, y, z, dx, dy, dz);
particleIcon = icon;
@@ -42,8 +44,8 @@ public class EntityDigIconFX extends EntityFX {
* copy pasted from EntityDiggingFX
*/
@Override
public void renderParticle(
Tessellator par1Tessellator, float par2, float par3, float par4, float par5, float par6, float par7) {
public void renderParticle(Tessellator par1Tessellator, float par2, float par3, float par4, float par5, float par6,
float par7) {
float f6 = (particleTextureIndexX + particleTextureJitterX / 4.0F) / 16.0F;
float f7 = f6 + 0.015609375F;
float f8 = (particleTextureIndexY + particleTextureJitterY / 4.0F) / 16.0F;
@@ -63,17 +65,33 @@ public class EntityDigIconFX extends EntityFX {
float f14 = 1.0F;
par1Tessellator.setColorOpaque_F(f14 * particleRed, f14 * particleGreen, f14 * particleBlue);
par1Tessellator.addVertexWithUV(
f11 - par3 * f10 - par6 * f10, f12 - par4 * f10, f13 - par5 * f10 - par7 * f10, f6, f9);
f11 - par3 * f10 - par6 * f10,
f12 - par4 * f10,
f13 - par5 * f10 - par7 * f10,
f6,
f9);
par1Tessellator.addVertexWithUV(
f11 - par3 * f10 + par6 * f10, f12 + par4 * f10, f13 - par5 * f10 + par7 * f10, f6, f8);
f11 - par3 * f10 + par6 * f10,
f12 + par4 * f10,
f13 - par5 * f10 + par7 * f10,
f6,
f8);
par1Tessellator.addVertexWithUV(
f11 + par3 * f10 + par6 * f10, f12 + par4 * f10, f13 + par5 * f10 + par7 * f10, f7, f8);
f11 + par3 * f10 + par6 * f10,
f12 + par4 * f10,
f13 + par5 * f10 + par7 * f10,
f7,
f8);
par1Tessellator.addVertexWithUV(
f11 + par3 * f10 - par6 * f10, f12 - par4 * f10, f13 + par5 * f10 - par7 * f10, f7, f9);
f11 + par3 * f10 - par6 * f10,
f12 - par4 * f10,
f13 + par5 * f10 - par7 * f10,
f7,
f9);
}
public static void addBlockHitEffects(
World world, Cuboid6 bounds, int side, IIcon icon, EffectRenderer effectRenderer) {
public static void addBlockHitEffects(World world, Cuboid6 bounds, int side, IIcon icon,
EffectRenderer effectRenderer) {
float border = 0.1F;
Vector3 diff = bounds.max.copy().subtract(bounds.min).add(-2 * border);
diff.x *= world.rand.nextDouble();
@@ -88,13 +106,13 @@ public class EntityDigIconFX extends EntityFX {
if (side == 4) diff.x = bounds.min.x - border;
if (side == 5) diff.x = bounds.max.x + border;
effectRenderer.addEffect(new EntityDigIconFX(world, pos.x, pos.y, pos.z, 0, 0, 0, icon)
.multiplyVelocity(0.2F)
.multipleParticleScaleBy(0.6F));
effectRenderer.addEffect(
new EntityDigIconFX(world, pos.x, pos.y, pos.z, 0, 0, 0, icon).multiplyVelocity(0.2F)
.multipleParticleScaleBy(0.6F));
}
public static void addBlockDestroyEffects(
World world, Cuboid6 bounds, IIcon[] icons, EffectRenderer effectRenderer) {
public static void addBlockDestroyEffects(World world, Cuboid6 bounds, IIcon[] icons,
EffectRenderer effectRenderer) {
Vector3 diff = bounds.max.copy().subtract(bounds.min);
Vector3 center = bounds.min.copy().add(bounds.max).multiply(0.5);
Vector3 density = diff.copy().multiply(4);
@@ -102,13 +120,12 @@ public class EntityDigIconFX extends EntityFX {
density.y = Math.ceil(density.y);
density.z = Math.ceil(density.z);
for (int i = 0; i < density.x; ++i)
for (int j = 0; j < density.y; ++j)
for (int k = 0; k < density.z; ++k) {
double x = bounds.min.x + (i + 0.5) * diff.x / density.x;
double y = bounds.min.y + (j + 0.5) * diff.y / density.y;
double z = bounds.min.z + (k + 0.5) * diff.z / density.z;
effectRenderer.addEffect(new EntityDigIconFX(
for (int i = 0; i < density.x; ++i) for (int j = 0; j < density.y; ++j) for (int k = 0; k < density.z; ++k) {
double x = bounds.min.x + (i + 0.5) * diff.x / density.x;
double y = bounds.min.y + (j + 0.5) * diff.y / density.y;
double z = bounds.min.z + (k + 0.5) * diff.z / density.z;
effectRenderer.addEffect(
new EntityDigIconFX(
world,
x,
y,
@@ -117,6 +134,6 @@ public class EntityDigIconFX extends EntityFX {
y - center.y,
z - center.z,
icons[world.rand.nextInt(icons.length)]));
}
}
}
}
@@ -3,9 +3,11 @@ package codechicken.lib.render;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
public class FontUtils {
public static FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer;
public static void drawCenteredString(String s, int xCenter, int y, int colour) {
@@ -16,7 +18,7 @@ public class FontUtils {
fontRenderer.drawString(s, xRight - fontRenderer.getStringWidth(s), y, colour);
}
public static final String[] prefixes = new String[] {"K", "M", "G"};
public static final String[] prefixes = new String[] { "K", "M", "G" };
public static void drawItemQuantity(int x, int y, ItemStack item, String quantity, int mode) {
if (item == null || (quantity == null && item.stackSize <= 1)) return;
@@ -1,5 +1,6 @@
package codechicken.lib.render;
public interface IFaceRenderer {
public void renderFace(Vertex5[] face, int side);
}
@@ -1,6 +1,7 @@
package codechicken.lib.render;
public class ManagedTextureFX extends TextureFX {
public boolean changed;
public ManagedTextureFX(int size, String name) {
@@ -5,6 +5,7 @@ import net.minecraft.client.resources.IResourceManager;
import net.minecraft.util.ResourceLocation;
public class PlaceholderTexture extends TextureAtlasSprite {
protected PlaceholderTexture(String par1) {
super(par1);
}
@@ -1,21 +1,27 @@
package codechicken.lib.render;
import codechicken.lib.render.uv.UV;
import codechicken.lib.render.uv.UVScale;
import codechicken.lib.vec.*;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import javax.imageio.ImageIO;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.util.IIcon;
import net.minecraft.util.ResourceLocation;
import codechicken.lib.render.uv.UV;
import codechicken.lib.render.uv.UVScale;
import codechicken.lib.vec.*;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
public class QBImporter {
private static class ImagePackNode {
Rectangle4i rect;
ImagePackNode child1;
ImagePackNode child2;
@@ -83,11 +89,10 @@ public class QBImporter {
while (true) {
boolean packed = true;
for (QBImage img : images)
if (!node.pack(img)) {
packed = false;
break;
}
for (QBImage img : images) if (!node.pack(img)) {
packed = false;
break;
}
if (packed) return node;
@@ -108,16 +113,16 @@ public class QBImporter {
child2.write(img);
} else if (packed != null) {
ImageTransform t = packed.packT;
for (int u = 0; u < rect.w; u++)
for (int v = 0; v < rect.h; v++) {
int rgba = t.access(packed, u, v);
img.setRGB(u + rect.x, v + rect.y, rgba >>> 8 | rgba << 24);
}
for (int u = 0; u < rect.w; u++) for (int v = 0; v < rect.h; v++) {
int rgba = t.access(packed, u, v);
img.setRGB(u + rect.x, v + rect.y, rgba >>> 8 | rgba << 24);
}
}
}
}
private static class ImageTransform {
int transform;
public ImageTransform(int i) {
@@ -166,6 +171,7 @@ public class QBImporter {
}
public static class QBImage implements Comparable<QBImage> {
int[][] data;
ImageTransform packT;
Rectangle4i packSlot;
@@ -190,16 +196,14 @@ public class QBImporter {
}
public ImageTransform transformTo(QBImage img) {
if (width() == img.width() && height() == img.height())
for (int i = 0; i < 4; i++) {
ImageTransform t = new ImageTransform(i);
if (equals(img, t)) return t;
}
if (width() == img.height() && height() == img.width())
for (int i = 4; i < 8; i++) {
ImageTransform t = new ImageTransform(i);
if (equals(img, t)) return t;
}
if (width() == img.width() && height() == img.height()) for (int i = 0; i < 4; i++) {
ImageTransform t = new ImageTransform(i);
if (equals(img, t)) return t;
}
if (width() == img.height() && height() == img.width()) for (int i = 4; i < 8; i++) {
ImageTransform t = new ImageTransform(i);
if (equals(img, t)) return t;
}
return null;
}
@@ -220,13 +224,10 @@ public class QBImporter {
}
private static final int[][] vertOrder = new int[][] { // clockwise because MC is left handed
{3, 0},
{1, 0},
{1, 2},
{3, 2}
};
{ 3, 0 }, { 1, 0 }, { 1, 2 }, { 3, 2 } };
public static class QBQuad {
public Vertex5[] verts = new Vertex5[4];
public QBImage image = new QBImage();
public ImageTransform t = new ImageTransform();
@@ -247,8 +248,7 @@ public class QBImporter {
QBQuad quad = new QBQuad(side);
quad.image = img;
Transformation t = new Scale(-1, 1, -1)
.with(Rotation.sideOrientation(side, 0))
Transformation t = new Scale(-1, 1, -1).with(Rotation.sideOrientation(side, 0))
.with(new Translation(new Vector3().setSide(side, d)));
quad.verts[0] = new Vertex5(flat.x, 0, flat.y, 0, 0);
quad.verts[1] = new Vertex5(flat.x + flat.w, 0, flat.y, 1, 0);
@@ -268,6 +268,7 @@ public class QBImporter {
}
public static class QBCuboid {
public QBMatrix mat;
public CuboidCoord c;
public int sides;
@@ -281,8 +282,7 @@ public class QBImporter {
public static boolean intersects(QBCuboid a, QBCuboid b) {
CuboidCoord c = a.c;
CuboidCoord d = b.c;
return c.min.x <= d.max.x
&& d.min.x <= c.max.x
return c.min.x <= d.max.x && d.min.x <= c.max.x
&& c.min.y <= d.max.y
&& d.min.y <= c.max.y
&& c.min.z <= d.max.z
@@ -301,8 +301,7 @@ public class QBImporter {
for (int a = 0; a < 6; a += 2) {
int a1 = (a + 2) % 6;
int a2 = (a + 4) % 6;
if (c.getSide(a1 + 1) <= d.getSide(a1 + 1)
&& c.getSide(a1) >= d.getSide(a1)
if (c.getSide(a1 + 1) <= d.getSide(a1 + 1) && c.getSide(a1) >= d.getSide(a1)
&& c.getSide(a2 + 1) <= d.getSide(a2 + 1)
&& c.getSide(a2) >= d.getSide(a2)) {
@@ -350,16 +349,16 @@ public class QBImporter {
BlockCoord b = BlockCoord.fromAxes(ia);
BlockCoord bU = BlockCoord.sideOffsets[sideU];
BlockCoord bV = BlockCoord.sideOffsets[sideV];
for (int u = 0; u < image.width(); u++)
for (int v = 0; v < image.height(); v++)
image.data[u][v] =
mat.matrix[b.x + bU.x * u + bV.x * v][b.y + bU.y * u + bV.y * v][b.z + bU.z * u + bV.z * v];
for (int u = 0; u < image.width(); u++) for (int v = 0; v < image.height(); v++)
image.data[u][v] = mat.matrix[b.x + bU.x * u + bV.x * v][b.y + bU.y * u + bV.y * v][b.z + bU.z * u
+ bV.z * v];
return quad;
}
}
public static class QBMatrix {
public String name;
public BlockCoord pos;
public BlockCoord size;
@@ -395,12 +394,10 @@ public class QBImporter {
}
public void convertBGRAtoRGBA() {
for (int z = 0; z < size.z; z++)
for (int y = 0; y < size.y; y++)
for (int x = 0; x < size.x; x++) {
int i = matrix[x][y][z];
matrix[x][y][z] = Integer.reverseBytes(i >>> 8) | i & 0xFF;
}
for (int z = 0; z < size.z; z++) for (int y = 0; y < size.y; y++) for (int x = 0; x < size.x; x++) {
int i = matrix[x][y][z];
matrix[x][y][z] = Integer.reverseBytes(i >>> 8) | i & 0xFF;
}
}
private boolean voxelFull(boolean[][][] solid, CuboidCoord c) {
@@ -434,10 +431,8 @@ public class QBImporter {
for (int z = 0; z < size.z; z++)
for (int y = 0; y < size.y; y++) for (int x = 0; x < size.x; x++) solid[x][y][z] = matrix[x][y][z] != 0;
for (int x = 0; x < size.x; x++)
for (int z = 0; z < size.z; z++)
for (int y = 0; y < size.y; y++)
if (solid[x][y][z]) list.add(expand(solid, new BlockCoord(x, y, z)));
for (int x = 0; x < size.x; x++) for (int z = 0; z < size.z; z++)
for (int y = 0; y < size.y; y++) if (solid[x][y][z]) list.add(expand(solid, new BlockCoord(x, y, z)));
for (int i = 0; i < list.size(); i++)
for (int j = i + 1; j < list.size(); j++) QBCuboid.clip(list.get(i), list.get(j));
@@ -468,9 +463,8 @@ public class QBImporter {
int side = key & 7;
Rectangle4i rect = null;
for (QBQuad q : plane)
if (rect == null) rect = q.flatten();
else rect.include(q.flatten());
for (QBQuad q : plane) if (rect == null) rect = q.flatten();
else rect.include(q.flatten());
QBImage img = new QBImage();
img.data = new int[rect.w][rect.h];
@@ -528,6 +522,7 @@ public class QBImporter {
public static final int SCALEMC = 8;
public static class QBModel {
public QBMatrix[] matrices;
public boolean rightHanded;
@@ -551,8 +546,7 @@ public class QBImporter {
}
}
if (mergeTextures)
images.add(ImagePackNode.pack(qbImages, squareTextures).toImage());
if (mergeTextures) images.add(ImagePackNode.pack(qbImages, squareTextures).toImage());
RasterisedModel m = new RasterisedModel(images);
for (int i = 0; i < matrices.length; i++) {
@@ -565,7 +559,9 @@ public class QBImporter {
}
public static class RasterisedModel {
private class Holder {
CCModel m;
int img;
@@ -594,9 +590,10 @@ public class QBImporter {
public IIcon getIcon(String key, IIconRegister r, String iconName) {
int img = map.get(key).img;
if (icons[img] != null && !iconName.equals(icons[img]))
throw new IllegalArgumentException("Attempted to get a previously registered icon by a different name: "
+ icons[img] + ", " + iconName);
if (icons[img] != null && !iconName.equals(icons[img])) throw new IllegalArgumentException(
"Attempted to get a previously registered icon by a different name: " + icons[img]
+ ", "
+ iconName);
if (icons[img] != null) return r.registerIcon(iconName);
icons[img] = iconName;
@@ -622,9 +619,8 @@ public class QBImporter {
if (images.size() < map.size())
exportImg(images.get(0), new File(imgDir, objFile.getName().replaceAll("(.+)\\..+", "$1.png")));
else
for (Map.Entry<String, Holder> e : map.entrySet())
exportImg(images.get(e.getValue().img), new File(imgDir, e.getKey() + ".png"));
else for (Map.Entry<String, Holder> e : map.entrySet())
exportImg(images.get(e.getValue().img), new File(imgDir, e.getKey() + ".png"));
} catch (IOException e) {
throw new RuntimeException(e);
@@ -674,10 +670,7 @@ public class QBImporter {
public static QBModel loadQB(ResourceLocation res) {
try {
return loadQB(Minecraft.getMinecraft()
.getResourceManager()
.getResource(res)
.getInputStream());
return loadQB(Minecraft.getMinecraft().getResourceManager().getResource(res).getInputStream());
} catch (Exception e) {
throw new RuntimeException("failed to load model: " + res, e);
}
@@ -3,9 +3,6 @@ package codechicken.lib.render;
import static net.minecraftforge.client.IItemRenderer.ItemRenderType.ENTITY;
import static net.minecraftforge.client.IItemRenderer.ItemRendererHelper.BLOCK_3D;
import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Rectangle4i;
import codechicken.lib.vec.Vector3;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
@@ -20,11 +17,18 @@ import net.minecraftforge.client.IItemRenderer;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import org.lwjgl.opengl.GL11;
import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Rectangle4i;
import codechicken.lib.vec.Vector3;
public class RenderUtils {
static Vector3[] vectors = new Vector3[8];
static RenderItem uniformRenderItem = new RenderItem() {
public boolean shouldBob() {
return false;
}
@@ -40,8 +44,8 @@ public class RenderUtils {
entityItem.hoverStart = 0;
}
public static void renderFluidQuad(
Vector3 point1, Vector3 point2, Vector3 point3, Vector3 point4, IIcon icon, double res) {
public static void renderFluidQuad(Vector3 point1, Vector3 point2, Vector3 point3, Vector3 point4, IIcon icon,
double res) {
renderFluidQuad(
point2,
vectors[0].set(point4).subtract(point1),
@@ -52,10 +56,11 @@ public class RenderUtils {
/**
* Draws a tessellated quadrilateral bottom to top, left to right
*
* @param base The bottom left corner of the quad
* @param wide The bottom of the quad
* @param high The left side of the quad
* @param res Units per icon
* @param res Units per icon
*/
public static void renderFluidQuad(Vector3 base, Vector3 wide, Vector3 high, IIcon icon, double res) {
Tessellator t = Tessellator.instance;
@@ -84,10 +89,18 @@ public class RenderUtils {
Vector3 dy2 = vectors[5].set(high).multiply((y + ry) / hlen);
t.addVertexWithUV(
base.x + dx1.x + dy2.x, base.y + dx1.y + dy2.y, base.z + dx1.z + dy2.z, u1, v2 - ry / res * dv);
base.x + dx1.x + dy2.x,
base.y + dx1.y + dy2.y,
base.z + dx1.z + dy2.z,
u1,
v2 - ry / res * dv);
t.addVertexWithUV(base.x + dx1.x + dy1.x, base.y + dx1.y + dy1.y, base.z + dx1.z + dy1.z, u1, v2);
t.addVertexWithUV(
base.x + dx2.x + dy1.x, base.y + dx2.y + dy1.y, base.z + dx2.z + dy1.z, u1 + rx / res * du, v2);
base.x + dx2.x + dy1.x,
base.y + dx2.y + dy1.y,
base.z + dx2.z + dy1.z,
u1 + rx / res * du,
v2);
t.addVertexWithUV(
base.x + dx2.x + dy2.x,
base.y + dx2.y + dy2.y,
@@ -183,9 +196,9 @@ public class RenderUtils {
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};
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 };
Tessellator tessellator = Tessellator.instance;
switch (side) {
@@ -260,14 +273,15 @@ public class RenderUtils {
}
/**
* Renders a fluid within a bounding box.
* If the fluid is a liquid it will render as a normal tank with height equal to density/bound.height.
* If the fluid is a gas, it will render the full box with an alpha equal to density.
* Renders a fluid within a bounding box. If the fluid is a liquid it will render as a normal tank with height equal
* to density/bound.height. If the fluid is a gas, it will render the full box with an alpha equal to density.
* Warning, bound will be mutated if the fluid is a liquid
* @param stack The fluid to render.
* @param bound The box within which the fluid is contained.
* @param density The volume of fluid / the capacity of the tank. For gases this determines the alpha, for liquids this determines the height.
* @param res The resolution to render at.
*
* @param stack The fluid to render.
* @param bound The box within which the fluid is contained.
* @param density The volume of fluid / the capacity of the tank. For gases this determines the alpha, for liquids
* this determines the height.
* @param res The resolution to render at.
*/
public static void renderFluidCuboid(FluidStack stack, Cuboid6 bound, double density, double res) {
if (!shouldRenderFluid(stack)) return;
@@ -315,6 +329,7 @@ public class RenderUtils {
/**
* Renders items and blocks in the world at 0,0,0 with transformations that size them appropriately
*
* @param spin The spin angle of the item around the y axis in degrees
*/
public static void renderItemUniform(ItemStack item, double spin) {
@@ -323,8 +338,7 @@ public class RenderUtils {
boolean larger = false;
if (item.getItem() instanceof ItemBlock
&& RenderBlocks.renderItemIn3d(
Block.getBlockFromItem(item.getItem()).getRenderType())) {
&& RenderBlocks.renderItemIn3d(Block.getBlockFromItem(item.getItem()).getRenderType())) {
int renderType = Block.getBlockFromItem(item.getItem()).getRenderType();
larger = !(renderType == 1 || renderType == 19 || renderType == 12 || renderType == 2);
} else if (is3D) {
@@ -6,12 +6,14 @@ import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.lwjgl.opengl.ARBShaderObjects;
import org.lwjgl.opengl.ARBVertexShader;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.vector.Matrix4f;
public class ShaderProgram {
int programID;
public ShaderProgram() {
@@ -1,18 +1,22 @@
package codechicken.lib.render;
import codechicken.lib.render.TextureUtils.IIconSelfRegister;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.ArrayList;
import java.util.HashMap;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.util.IIcon;
import net.minecraft.util.ResourceLocation;
import codechicken.lib.render.TextureUtils.IIconSelfRegister;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class SpriteSheetManager {
@SideOnly(Side.CLIENT)
public static class SpriteSheet implements IIconSelfRegister {
private int tilesX;
private int tilesY;
private ArrayList<Integer> newSprites = new ArrayList<Integer>();
@@ -65,9 +69,8 @@ public class SpriteSheetManager {
public IIcon getSprite(int index) {
IIcon i = sprites[index];
if (i == null)
throw new IllegalArgumentException(
"Sprite at index: " + index + " from texture file " + resource + " was not preloaded.");
if (i == null) throw new IllegalArgumentException(
"Sprite at index: " + index + " from texture file " + resource + " was not preloaded.");
return i;
}
@@ -3,6 +3,7 @@ package codechicken.lib.render;
import java.awt.image.BufferedImage;
public class TextureDataHolder {
public int width;
public int height;
public int[] data;
@@ -1,12 +1,14 @@
package codechicken.lib.render;
import net.minecraft.client.Minecraft;
import codechicken.lib.render.SpriteSheetManager.SpriteSheet;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.Minecraft;
@SideOnly(Side.CLIENT)
public class TextureFX {
public int[] imageData;
public int tileSizeBase = 16;
public int tileSizeSquare = 256;
@@ -1,11 +1,8 @@
package codechicken.lib.render;
import codechicken.lib.render.SpriteSheetManager.SpriteSheet;
import codechicken.lib.render.TextureUtils.IIconSelfRegister;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
@@ -16,8 +13,14 @@ import net.minecraft.client.resources.data.AnimationMetadataSection;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.util.ResourceLocation;
import codechicken.lib.render.SpriteSheetManager.SpriteSheet;
import codechicken.lib.render.TextureUtils.IIconSelfRegister;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class TextureSpecial extends TextureAtlasSprite implements IIconSelfRegister {
// sprite sheet fields
private int spriteIndex;
private SpriteSheet spriteSheet;
@@ -99,8 +102,8 @@ public class TextureSpecial extends TextureAtlasSprite implements IIconSelfRegis
}
@Override
public void loadSprite(
BufferedImage[] images, AnimationMetadataSection animationMeta, boolean anisotropicFiltering) {
public void loadSprite(BufferedImage[] images, AnimationMetadataSection animationMeta,
boolean anisotropicFiltering) {
rawWidth = images[0].getWidth();
rawHeight = images[0].getHeight();
super.loadSprite(images, animationMeta, anisotropicFiltering);
@@ -1,13 +1,12 @@
package codechicken.lib.render;
import codechicken.lib.colour.Colour;
import codechicken.lib.colour.ColourARGB;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.client.renderer.texture.TextureManager;
@@ -16,11 +15,18 @@ import net.minecraft.util.IIcon;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.common.MinecraftForge;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import codechicken.lib.colour.Colour;
import codechicken.lib.colour.ColourARGB;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
public class TextureUtils {
public static interface IIconSelfRegister {
public void registerIcons(IIconRegister register);
public int atlasIndex();
@@ -57,10 +63,7 @@ public class TextureUtils {
}
public static InputStream getTextureResource(ResourceLocation textureFile) throws IOException {
return Minecraft.getMinecraft()
.getResourceManager()
.getResource(textureFile)
.getInputStream();
return Minecraft.getMinecraft().getResourceManager().getResource(textureFile).getInputStream();
}
public static BufferedImage loadBufferedImage(ResourceLocation textureFile) {
@@ -83,24 +86,14 @@ public class TextureUtils {
return Minecraft.getMinecraft().renderEngine;
}
public static void copySubImg(
int[] fromTex,
int fromWidth,
int fromX,
int fromY,
int width,
int height,
int[] toTex,
int toWidth,
int toX,
int toY) {
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++) {
int fp = (y + fromY) * fromWidth + x + fromX;
int tp = (y + toX) * toWidth + x + toX;
public static void copySubImg(int[] fromTex, int fromWidth, int fromX, int fromY, int width, int height,
int[] toTex, int toWidth, int toX, int toY) {
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) {
int fp = (y + fromY) * fromWidth + x + fromX;
int tp = (y + toX) * toWidth + x + toX;
toTex[tp] = fromTex[fp];
}
toTex[tp] = fromTex[fp];
}
}
public static void bindAtlas(int atlasIndex) {
@@ -148,7 +141,8 @@ public class TextureUtils {
}
/**
* Uses an empty placeholder texture to tell if the map has been reloaded since the last call to refresh texture and the texture with name needs to be reacquired to be valid
* Uses an empty placeholder texture to tell if the map has been reloaded since the last call to refresh texture and
* the texture with name needs to be reacquired to be valid
*/
public static boolean refreshTexture(TextureMap map, String name) {
if (map.getTextureExtry(name) == null) {
@@ -1,15 +1,17 @@
package codechicken.lib.render;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import codechicken.lib.render.uv.UV;
import codechicken.lib.render.uv.UVTransformation;
import codechicken.lib.util.Copyable;
import codechicken.lib.vec.Transformation;
import codechicken.lib.vec.Vector3;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class Vertex5 implements Copyable<Vertex5> {
public Vector3 vec;
public UV uv;
@@ -62,9 +64,19 @@ public class Vertex5 implements Copyable<Vertex5> {
public String toString() {
MathContext cont = new MathContext(4, RoundingMode.HALF_UP);
return "Vertex: (" + new BigDecimal(vec.x, cont) + ", " + new BigDecimal(vec.y, cont) + ", "
+ new BigDecimal(vec.z, cont) + ") " + "(" + new BigDecimal(uv.u, cont) + ", "
+ new BigDecimal(uv.v, cont) + ") (" + uv.tex + ")";
return "Vertex: (" + new BigDecimal(vec.x, cont)
+ ", "
+ new BigDecimal(vec.y, cont)
+ ", "
+ new BigDecimal(vec.z, cont)
+ ") "
+ "("
+ new BigDecimal(uv.u, cont)
+ ", "
+ new BigDecimal(uv.v, cont)
+ ") ("
+ uv.tex
+ ")";
}
public Vertex5 apply(Transformation t) {
@@ -1,9 +1,11 @@
package codechicken.lib.render.uv;
import codechicken.lib.vec.IrreversibleTransformationException;
import net.minecraft.util.IIcon;
import codechicken.lib.vec.IrreversibleTransformationException;
public class IconTransformation extends UVTransformation {
public IIcon icon;
public IconTransformation(IIcon icon) {
@@ -1,9 +1,11 @@
package codechicken.lib.render.uv;
import codechicken.lib.vec.IrreversibleTransformationException;
import net.minecraft.util.IIcon;
import codechicken.lib.vec.IrreversibleTransformationException;
public class MultiIconTransformation extends UVTransformation {
public IIcon[] icons;
public MultiIconTransformation(IIcon... icons) {
@@ -1,11 +1,13 @@
package codechicken.lib.render.uv;
import codechicken.lib.util.Copyable;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import codechicken.lib.util.Copyable;
public class UV implements Copyable<UV> {
public double u;
public double v;
public int tex;
@@ -1,11 +1,13 @@
package codechicken.lib.render.uv;
import codechicken.lib.math.MathHelper;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import codechicken.lib.math.MathHelper;
public class UVRotation extends UVTransformation {
public double angle;
/**
@@ -5,6 +5,7 @@ import java.math.MathContext;
import java.math.RoundingMode;
public class UVScale extends UVTransformation {
double su;
double sv;
@@ -8,11 +8,14 @@ import codechicken.lib.vec.ITransformation;
*/
public abstract class UVTransformation extends ITransformation<UV, UVTransformation>
implements CCRenderState.IVertexOperation {
public static final int operationIndex = CCRenderState.registerOperation();
public UVTransformation at(UV point) {
return new UVTransformationList(
new UVTranslation(-point.u, -point.v), this, new UVTranslation(point.u, point.v));
new UVTranslation(-point.u, -point.v),
this,
new UVTranslation(point.u, point.v));
}
public UVTransformationList with(UVTransformation t) {
@@ -4,6 +4,7 @@ import java.util.ArrayList;
import java.util.Iterator;
public class UVTransformationList extends UVTransformation {
private ArrayList<UVTransformation> transformations = new ArrayList<UVTransformation>();
public UVTransformationList(UVTransformation... transforms) {
@@ -69,8 +70,7 @@ public class UVTransformationList extends UVTransformation {
@Override
public UVTransformation inverse() {
UVTransformationList rev = new UVTransformationList();
for (int i = transformations.size() - 1; i >= 0; i--)
rev.with(transformations.get(i).inverse());
for (int i = transformations.size() - 1; i >= 0; i--) rev.with(transformations.get(i).inverse());
return rev;
}
@@ -1,11 +1,13 @@
package codechicken.lib.render.uv;
import codechicken.lib.math.MathHelper;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import codechicken.lib.math.MathHelper;
public class UVTranslation extends UVTransformation {
public double du;
public double dv;
@@ -12,13 +12,11 @@ import java.util.LinkedList;
import java.util.List;
public class LibDownloader {
private static String[] libs = new String[] {
"org/ow2/asm/asm-debug-all/5.0.3/asm-debug-all-5.0.3.jar",
"com/google/guava/guava/14.0/guava-14.0.jar",
"net/sf/jopt-simple/jopt-simple/4.5/jopt-simple-4.5.jar",
"org/apache/logging/log4j/log4j-core/2.0-beta9/log4j-core-2.0-beta9.jar",
"org/apache/logging/log4j/log4j-api/2.0-beta9/log4j-api-2.0-beta9.jar"
};
private static String[] libs = new String[] { "org/ow2/asm/asm-debug-all/5.0.3/asm-debug-all-5.0.3.jar",
"com/google/guava/guava/14.0/guava-14.0.jar", "net/sf/jopt-simple/jopt-simple/4.5/jopt-simple-4.5.jar",
"org/apache/logging/log4j/log4j-core/2.0-beta9/log4j-core-2.0-beta9.jar",
"org/apache/logging/log4j/log4j-api/2.0-beta9/log4j-api-2.0-beta9.jar" };
private static File libDir = new File("lib");
private static ByteBuffer downloadBuffer = ByteBuffer.allocateDirect(1 << 23);
@@ -35,10 +33,9 @@ public class LibDownloader {
private static void addPaths(String[] libs) {
try {
URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader();
Method m_addURL = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] {URL.class});
Method m_addURL = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
m_addURL.setAccessible(true);
for (String lib : libs)
m_addURL.invoke(cl, new File(libDir, fileName(lib)).toURI().toURL());
for (String lib : libs) m_addURL.invoke(cl, new File(libDir, fileName(lib)).toURI().toURL());
} catch (Exception e) {
throw new RuntimeException("Failed to add libraries to classpath", e);
}
@@ -1,7 +1,7 @@
package codechicken.lib.tool;
import codechicken.lib.asm.ASMHelper;
import java.util.Iterator;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
@@ -10,8 +10,12 @@ import org.objectweb.asm.commons.RemappingMethodAdapter;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import codechicken.lib.asm.ASMHelper;
public class MCStripTransformer {
public static class ReferenceDetector extends Remapper {
boolean found = false;
@Override
+2 -1
View File
@@ -1,11 +1,12 @@
package codechicken.lib.tool;
public class Main {
public static void main(String[] args) {
LibDownloader.load();
try {
Class<?> c_toolMain = new StripClassLoader().loadClass("codechicken.lib.tool.ToolMain");
c_toolMain.getDeclaredMethod("main", String[].class).invoke(null, new Object[] {args});
c_toolMain.getDeclaredMethod("main", String[].class).invoke(null, new Object[] { args });
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -7,6 +7,7 @@ import java.net.URL;
import java.net.URLClassLoader;
public class StripClassLoader extends URLClassLoader {
public StripClassLoader() {
super(new URL[0], StripClassLoader.class.getClassLoader());
}
@@ -3,7 +3,9 @@ package codechicken.lib.tool;
import codechicken.lib.tool.module.ModuleQBConverter;
public class ToolMain {
public static interface Module {
public void main(String[] args);
public String name();
@@ -11,7 +13,7 @@ public class ToolMain {
public void printHelp();
}
public static Module[] modules = new Module[] {new ModuleQBConverter()};
public static Module[] modules = new Module[] { new ModuleQBConverter() };
private static void printHelp() {
System.out.println("Usage: [module] [args]");
@@ -22,19 +24,17 @@ public class ToolMain {
public static void main(String[] args) {
if (args.length > 0) {
for (Module m : modules)
if (args[0].equals(m.name())) {
String[] args2 = new String[args.length - 1];
System.arraycopy(args, 1, args2, 0, args2.length);
m.main(args2);
for (Module m : modules) if (args[0].equals(m.name())) {
String[] args2 = new String[args.length - 1];
System.arraycopy(args, 1, args2, 0, args2.length);
m.main(args2);
return;
}
if (args[0].equals("-h") && args.length >= 2) {
for (Module m : modules) if (args[1].equals(m.name())) {
m.printHelp();
return;
}
if (args[0].equals("-h") && args.length >= 2) {
for (Module m : modules)
if (args[1].equals(m.name())) {
m.printHelp();
return;
}
}
}
printHelp();
@@ -1,12 +1,14 @@
package codechicken.lib.tool.module;
import codechicken.lib.tool.ToolMain;
import java.io.IOException;
import joptsimple.OptionException;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import codechicken.lib.tool.ToolMain;
public abstract class JOptModule implements ToolMain.Module {
OptionParser parser = new OptionParser();
@Override
@@ -2,22 +2,19 @@ package codechicken.lib.tool.module;
import static java.util.Arrays.asList;
import codechicken.lib.render.QBImporter;
import java.io.File;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import codechicken.lib.render.QBImporter;
public class ModuleQBConverter extends JOptModule {
public ModuleQBConverter() {
parser.acceptsAll(asList("?", "h", "help"), "Show the help");
parser.acceptsAll(asList("i", "input"), "comma separated list of paths to models (.qb or directories)")
.withRequiredArg()
.ofType(File.class)
.withValuesSeparatedBy(',')
.required();
parser.acceptsAll(asList("o", "out"), "Output Directory")
.withRequiredArg()
.ofType(File.class);
.withRequiredArg().ofType(File.class).withValuesSeparatedBy(',').required();
parser.acceptsAll(asList("o", "out"), "Output Directory").withRequiredArg().ofType(File.class);
parser.acceptsAll(
asList("o2", "textureplanes"),
"2nd level optimisation. Merges coplanar polygons. Increases texture size");
@@ -1,5 +1,6 @@
package codechicken.lib.util;
public interface Copyable<T> {
public T copy();
}
@@ -3,6 +3,7 @@ package codechicken.lib.util;
import net.minecraft.util.StatCollector;
public class LangProxy {
public final String namespace;
public LangProxy(String namespace) {
@@ -1,39 +1,39 @@
package codechicken.lib.vec;
public class AxisCycle {
public static Transformation[] cycles = new Transformation[] {
new RedundantTransformation(),
new VariableTransformation(new Matrix4(0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1)) {
@Override
public void apply(Vector3 vec) {
double d0 = vec.x;
double d1 = vec.y;
double d2 = vec.z;
vec.x = d2;
vec.y = d0;
vec.z = d1;
}
@Override
public Transformation inverse() {
return cycles[2];
}
},
new VariableTransformation(new Matrix4(0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1)) {
@Override
public void apply(Vector3 vec) {
double d0 = vec.x;
double d1 = vec.y;
double d2 = vec.z;
vec.x = d1;
vec.y = d2;
vec.z = d0;
}
public static Transformation[] cycles = new Transformation[] { new RedundantTransformation(),
new VariableTransformation(new Matrix4(0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1)) {
@Override
public Transformation inverse() {
return cycles[1];
}
}
};
@Override
public void apply(Vector3 vec) {
double d0 = vec.x;
double d1 = vec.y;
double d2 = vec.z;
vec.x = d2;
vec.y = d0;
vec.z = d1;
}
@Override
public Transformation inverse() {
return cycles[2];
}
}, new VariableTransformation(new Matrix4(0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1)) {
@Override
public void apply(Vector3 vec) {
double d0 = vec.x;
double d1 = vec.y;
double d2 = vec.z;
vec.x = d1;
vec.y = d2;
vec.z = d0;
}
@Override
public Transformation inverse() {
return cycles[1];
}
} };
}
@@ -1,10 +1,12 @@
package codechicken.lib.vec;
import net.minecraft.tileentity.TileEntity;
import codechicken.lib.math.MathHelper;
import codechicken.lib.util.Copyable;
import net.minecraft.tileentity.TileEntity;
public class BlockCoord implements Comparable<BlockCoord>, Copyable<BlockCoord> {
public int x;
public int y;
public int z;
@@ -162,17 +164,11 @@ public class BlockCoord implements Comparable<BlockCoord>, Copyable<BlockCoord>
return this;
}
public static final BlockCoord[] sideOffsets = new BlockCoord[] {
new BlockCoord(0, -1, 0),
new BlockCoord(0, 1, 0),
new BlockCoord(0, 0, -1),
new BlockCoord(0, 0, 1),
new BlockCoord(-1, 0, 0),
new BlockCoord(1, 0, 0)
};
public static final BlockCoord[] sideOffsets = new BlockCoord[] { new BlockCoord(0, -1, 0), new BlockCoord(0, 1, 0),
new BlockCoord(0, 0, -1), new BlockCoord(0, 0, 1), new BlockCoord(-1, 0, 0), new BlockCoord(1, 0, 0) };
public int[] intArray() {
return new int[] {x, y, z};
return new int[] { x, y, z };
}
public BlockCoord copy() {
+17 -6
View File
@@ -1,13 +1,16 @@
package codechicken.lib.vec;
import codechicken.lib.util.Copyable;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import net.minecraft.block.Block;
import net.minecraft.util.AxisAlignedBB;
import codechicken.lib.util.Copyable;
public class Cuboid6 implements Copyable<Cuboid6> {
public static Cuboid6 full = new Cuboid6(0, 0, 0, 1, 1, 1);
public Vector3 min;
@@ -84,8 +87,7 @@ public class Cuboid6 implements Copyable<Cuboid6> {
}
public boolean intersects(Cuboid6 b) {
return max.x - 1E-5 > b.min.x
&& b.max.x - 1E-5 > min.x
return max.x - 1E-5 > b.min.x && b.max.x - 1E-5 > min.x
&& max.y - 1E-5 > b.min.y
&& b.max.y - 1E-5 > min.y
&& max.z - 1E-5 > b.min.z
@@ -108,9 +110,18 @@ public class Cuboid6 implements Copyable<Cuboid6> {
public String toString() {
MathContext cont = new MathContext(4, RoundingMode.HALF_UP);
return "Cuboid: (" + new BigDecimal(min.x, cont) + ", " + new BigDecimal(min.y, cont) + ", "
+ new BigDecimal(min.z, cont) + ") -> (" + new BigDecimal(max.x, cont) + ", "
+ new BigDecimal(max.y, cont) + ", " + new BigDecimal(max.z, cont) + ")";
return "Cuboid: (" + new BigDecimal(min.x, cont)
+ ", "
+ new BigDecimal(min.y, cont)
+ ", "
+ new BigDecimal(min.z, cont)
+ ") -> ("
+ new BigDecimal(max.x, cont)
+ ", "
+ new BigDecimal(max.y, cont)
+ ", "
+ new BigDecimal(max.z, cont)
+ ")";
}
public Cuboid6 enclose(Vector3 vec) {
@@ -1,10 +1,13 @@
package codechicken.lib.vec;
import codechicken.lib.util.Copyable;
import java.util.Iterator;
import net.minecraft.util.AxisAlignedBB;
import codechicken.lib.util.Copyable;
public class CuboidCoord implements Iterable<BlockCoord>, Copyable<CuboidCoord> {
public BlockCoord min;
public BlockCoord max;
@@ -42,7 +45,7 @@ public class CuboidCoord implements Iterable<BlockCoord>, Copyable<CuboidCoord>
public CuboidCoord expand(int side, int amount) {
if (side % 2 == 0) // negative side
min = min.offset(side, amount);
min = min.offset(side, amount);
else max = max.offset(side, amount);
return this;
}
@@ -125,7 +128,9 @@ public class CuboidCoord implements Iterable<BlockCoord>, Copyable<CuboidCoord>
public Vector3 getCenterVec() {
return new Vector3(
min.x + (max.x - min.x + 1) / 2D, min.y + (max.y - min.y + 1) / 2D, min.z + (max.z - min.z + 1) / 2D);
min.x + (max.x - min.x + 1) / 2D,
min.y + (max.y - min.y + 1) / 2D,
min.z + (max.z - min.z + 1) / 2D);
}
public BlockCoord getCenter(BlockCoord store) {
@@ -142,7 +147,7 @@ public class CuboidCoord implements Iterable<BlockCoord>, Copyable<CuboidCoord>
}
public int[] intArray() {
return new int[] {min.x, min.y, min.z, max.x, max.y, max.z};
return new int[] { min.x, min.y, min.z, max.x, max.y, max.z };
}
public CuboidCoord copy() {
@@ -197,6 +202,7 @@ public class CuboidCoord implements Iterable<BlockCoord>, Copyable<CuboidCoord>
public Iterator<BlockCoord> iterator() {
return new Iterator<BlockCoord>() {
BlockCoord b = null;
public boolean hasNext() {
@@ -2,10 +2,12 @@ package codechicken.lib.vec;
/**
* Abstract supertype for any VectorN transformation
* @param <Vector> The vector type
*
* @param <Vector> The vector type
* @param <Transformation> The transformation type
*/
public abstract class ITransformation<Vector, Transformation extends ITransformation> {
/**
* Applies this transformation to vec
*/
@@ -18,20 +20,22 @@ public abstract class ITransformation<Vector, Transformation extends ITransforma
public abstract Transformation at(Vector point);
/**
* Creates a TransformationList composed of this transformation followed by t
* If this is a TransformationList, the transformation will be appended and this returned
* Creates a TransformationList composed of this transformation followed by t If this is a TransformationList, the
* transformation will be appended and this returned
*/
public abstract Transformation with(Transformation t);
/**
* Returns a simplified transformation that performs this, followed by next. If such a transformation does not exist, returns null
* Returns a simplified transformation that performs this, followed by next. If such a transformation does not
* exist, returns null
*/
public Transformation merge(Transformation next) {
return null;
}
/**
* Returns true if this transformation is redundant, eg. Scale(1, 1, 1), Translation(0, 0, 0) or Rotation(0, a, b, c)
* Returns true if this transformation is redundant, eg. Scale(1, 1, 1), Translation(0, 0, 0) or Rotation(0, a, b,
* c)
*/
public boolean isRedundant() {
return false;
@@ -2,6 +2,7 @@ package codechicken.lib.vec;
@SuppressWarnings("serial")
public class IrreversibleTransformationException extends RuntimeException {
public ITransformation t;
public IrreversibleTransformationException(ITransformation t) {
+5 -4
View File
@@ -1,6 +1,7 @@
package codechicken.lib.vec;
public class Line3 {
public static final double tol = 0.0001D;
public Vector3 pt1;
@@ -27,18 +28,18 @@ public class Line3 {
double div = zD2 * xD1 - xD2 * zD1;
if (div == 0) // lines are parallel
return false;
return false;
double ua = (xD2 * zD3 - zD2 * xD3) / div;
store.set(line1.pt1.x + ua * xD1, 0, line1.pt1.z + ua * zD1);
if (store.x >= Math.min(line1.pt1.x, line1.pt2.x) - tol
&& store.x >= Math.min(line2.pt1.x, line2.pt2.x) - tol
if (store.x >= Math.min(line1.pt1.x, line1.pt2.x) - tol && store.x >= Math.min(line2.pt1.x, line2.pt2.x) - tol
&& store.z >= Math.min(line1.pt1.z, line1.pt2.z) - tol
&& store.z >= Math.min(line2.pt1.z, line2.pt2.z) - tol
&& store.x <= Math.max(line1.pt1.x, line1.pt2.x) + tol
&& store.x <= Math.max(line2.pt1.x, line2.pt2.x) + tol
&& store.z <= Math.max(line1.pt1.z, line1.pt2.z) + tol
&& store.z <= Math.max(line2.pt1.z, line2.pt2.z) + tol) return true;
&& store.z <= Math.max(line2.pt1.z, line2.pt2.z) + tol)
return true;
return false;
}
+47 -46
View File
@@ -1,19 +1,22 @@
package codechicken.lib.vec;
import codechicken.lib.util.Copyable;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.DoubleBuffer;
import org.lwjgl.opengl.GL11;
import codechicken.lib.util.Copyable;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class Matrix4 extends Transformation implements Copyable<Matrix4> {
private static DoubleBuffer glBuf =
ByteBuffer.allocateDirect(16 * 8).order(ByteOrder.nativeOrder()).asDoubleBuffer();
private static DoubleBuffer glBuf = ByteBuffer.allocateDirect(16 * 8).order(ByteOrder.nativeOrder())
.asDoubleBuffer();
// m<row><column>
public double m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33;
@@ -22,23 +25,8 @@ public class Matrix4 extends Transformation implements Copyable<Matrix4> {
m00 = m11 = m22 = m33 = 1;
}
public Matrix4(
double d00,
double d01,
double d02,
double d03,
double d10,
double d11,
double d12,
double d13,
double d20,
double d21,
double d22,
double d23,
double d30,
double d31,
double d32,
double d33) {
public Matrix4(double d00, double d01, double d02, double d03, double d10, double d11, double d12, double d13,
double d20, double d21, double d22, double d23, double d30, double d31, double d32, double d33) {
m00 = d00;
m01 = d01;
m02 = d02;
@@ -315,14 +303,41 @@ public class Matrix4 extends Transformation implements Copyable<Matrix4> {
@Override
public String toString() {
MathContext cont = new MathContext(4, RoundingMode.HALF_UP);
return "[" + new BigDecimal(m00, cont) + "," + new BigDecimal(m01, cont) + "," + new BigDecimal(m02, cont) + ","
+ new BigDecimal(m03, cont) + "]\n" + "["
+ new BigDecimal(m10, cont) + "," + new BigDecimal(m11, cont) + "," + new BigDecimal(m12, cont) + ","
+ new BigDecimal(m13, cont) + "]\n" + "["
+ new BigDecimal(m20, cont) + "," + new BigDecimal(m21, cont) + "," + new BigDecimal(m22, cont) + ","
+ new BigDecimal(m23, cont) + "]\n" + "["
+ new BigDecimal(m30, cont) + "," + new BigDecimal(m31, cont) + "," + new BigDecimal(m32, cont) + ","
+ new BigDecimal(m33, cont) + "]";
return "[" + new BigDecimal(m00, cont)
+ ","
+ new BigDecimal(m01, cont)
+ ","
+ new BigDecimal(m02, cont)
+ ","
+ new BigDecimal(m03, cont)
+ "]\n"
+ "["
+ new BigDecimal(m10, cont)
+ ","
+ new BigDecimal(m11, cont)
+ ","
+ new BigDecimal(m12, cont)
+ ","
+ new BigDecimal(m13, cont)
+ "]\n"
+ "["
+ new BigDecimal(m20, cont)
+ ","
+ new BigDecimal(m21, cont)
+ ","
+ new BigDecimal(m22, cont)
+ ","
+ new BigDecimal(m23, cont)
+ "]\n"
+ "["
+ new BigDecimal(m30, cont)
+ ","
+ new BigDecimal(m31, cont)
+ ","
+ new BigDecimal(m32, cont)
+ ","
+ new BigDecimal(m33, cont)
+ "]";
}
public Matrix4 apply(Transformation t) {
@@ -333,22 +348,8 @@ public class Matrix4 extends Transformation implements Copyable<Matrix4> {
@Override
@SideOnly(Side.CLIENT)
public void glApply() {
glBuf.put(m00)
.put(m10)
.put(m20)
.put(m30)
.put(m01)
.put(m11)
.put(m21)
.put(m31)
.put(m02)
.put(m12)
.put(m22)
.put(m32)
.put(m03)
.put(m13)
.put(m23)
.put(m33);
glBuf.put(m00).put(m10).put(m20).put(m30).put(m01).put(m11).put(m21).put(m31).put(m02).put(m12).put(m22)
.put(m32).put(m03).put(m13).put(m23).put(m33);
glBuf.flip();
GL11.glMultMatrix(glBuf);
}
+12 -4
View File
@@ -1,12 +1,14 @@
package codechicken.lib.vec;
import codechicken.lib.math.MathHelper;
import codechicken.lib.util.Copyable;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import codechicken.lib.math.MathHelper;
import codechicken.lib.util.Copyable;
public class Quat implements Copyable<Quat> {
public double x;
public double y;
public double z;
@@ -128,8 +130,14 @@ public class Quat implements Copyable<Quat> {
public String toString() {
MathContext cont = new MathContext(4, RoundingMode.HALF_UP);
return "Quat(" + new BigDecimal(s, cont) + ", " + new BigDecimal(x, cont) + ", " + new BigDecimal(y, cont)
+ ", " + new BigDecimal(z, cont) + ")";
return "Quat(" + new BigDecimal(s, cont)
+ ", "
+ new BigDecimal(x, cont)
+ ", "
+ new BigDecimal(y, cont)
+ ", "
+ new BigDecimal(z, cont)
+ ")";
}
public Rotation rotation() {
@@ -1,6 +1,7 @@
package codechicken.lib.vec;
public class Rectangle4i {
public int x;
public int y;
public int w;
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff. Show more