Skip to content

Commit

Permalink
Codestyle stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
Hermanoid committed Jan 14, 2024
1 parent 62de768 commit 29d7341
Show file tree
Hide file tree
Showing 4 changed files with 116 additions and 93 deletions.
6 changes: 5 additions & 1 deletion src/main/java/com/hermanoid/nerd/NEI_NERD_Config.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package com.hermanoid.nerd;

import com.hermanoid.nerd.info_extractors.GTDefaultRecipeInfoExtractor;

import codechicken.nei.api.API;
import codechicken.nei.api.IConfigureNEI;
import com.hermanoid.nerd.info_extractors.GTDefaultRecipeInfoExtractor;

// This class is automatically discovered by a system in NotEnoughItems
@SuppressWarnings("unused")
public class NEI_NERD_Config implements IConfigureNEI {

@Override
public void loadConfig() {
RecipeDumper recipeDumper = new RecipeDumper("tools.dump.recipes");
Expand Down
78 changes: 38 additions & 40 deletions src/main/java/com/hermanoid/nerd/RecipeDumper.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,12 @@ public RecipeDumper(String name) {
public int totalQueries = -1;
public int dumpedQueries = -1;
private boolean dumpActive = false;
private Timer timer = new Timer();
private final Timer timer = new Timer();

private final Multimap<String, IRecipeInfoExtractor> recipeInfoExtractors = HashMultimap.create();

public void registerRecipeInfoExtractor(IRecipeInfoExtractor extractor){
for(String id : extractor.getCompatibleHandlers())
recipeInfoExtractors.put(id, extractor);
public void registerRecipeInfoExtractor(IRecipeInfoExtractor extractor) {
for (String id : extractor.getCompatibleHandlers()) recipeInfoExtractors.put(id, extractor);
}

@Override
Expand Down Expand Up @@ -87,19 +86,20 @@ private JsonArray stacksToJsonArray(List<PositionedStack> stacks) {
return arr;
}

private static class QueryResult{
private static class QueryResult {

public ItemStack targetStack;
public List<ICraftingHandler> handlers;
}

private QueryResult performQuery(ItemStack targetStack){
private QueryResult performQuery(ItemStack targetStack) {
QueryResult result = new QueryResult();
result.targetStack = targetStack;
result.handlers = GuiCraftingRecipe.getCraftingHandlers("item", targetStack);
return result;
}

private JsonObject extractJsonRecipeData(QueryResult queryResult){
private JsonObject extractJsonRecipeData(QueryResult queryResult) {
// Gather item details (don't grab everything... you can dump items if you want more details)
// These columns will be repeated many times in the output, so don't write more than needed.

Expand Down Expand Up @@ -128,8 +128,8 @@ private JsonObject extractJsonRecipeData(QueryResult queryResult){
if (handler.getResultStack(recipeIndex) != null) {
recipeDump.add("out_item", stackToDetailedJson(handler.getResultStack(recipeIndex).item));
}
if(recipeInfoExtractors.containsKey(handlerId)){
for(IRecipeInfoExtractor extractor : recipeInfoExtractors.get(handlerId)){
if (recipeInfoExtractors.containsKey(handlerId)) {
for (IRecipeInfoExtractor extractor : recipeInfoExtractors.get(handlerId)) {
recipeDump.add(extractor.getSlug(), extractor.extractInfo(handler, recipeIndex));
}
}
Expand All @@ -145,12 +145,10 @@ private JsonObject extractJsonRecipeData(QueryResult queryResult){
public Stream<JsonObject> getQueryDumps(List<ItemStack> items) {
// Parallelization doesn't help a *lot* but it is like a 2x speedup so I'll take it
return items.parallelStream()
.map(this::performQuery)
.map(this::extractJsonRecipeData);
.map(this::performQuery)
.map(this::extractJsonRecipeData);
}



@Override
public String renderName() {
return translateN(name);
Expand All @@ -174,17 +172,19 @@ public String modeButtonText() {
@Override
public Iterable<String[]> dump(int mode) {
// A little crunchy, I'll admit
throw new NotImplementedException("Recipe Dumper overrides the base DataDumper's dumping functionality in dumpTo(file)! dump() should never be called.");
throw new NotImplementedException(
"Recipe Dumper overrides the base DataDumper's dumping functionality in dumpTo(file)! dump() should never be called.");
}

@Override
public void dumpTo(File file) throws IOException {
if (getMode() != 1) { throw new RuntimeException("RecipeDumper received an unexpected mode! There should only be one mode: JSON");}
public void dumpTo(File file) {
if (getMode() != 1) {
throw new RuntimeException("RecipeDumper received an unexpected mode! There should only be one mode: JSON");
}
dumpJson(file);
}

private void doDumpJson(File file){
final String[] header = header();
private void doDumpJson(File file) {
final FileWriter writer;
final JsonWriter jsonWriter;
final Gson gson = new Gson();
Expand All @@ -198,13 +198,14 @@ private void doDumpJson(File file){

jsonWriter.beginObject();
jsonWriter.setIndent(" ");
jsonWriter.name("version").value(version);
jsonWriter.name("version")
.value(version);

jsonWriter.name("queries").beginArray();
jsonWriter.name("queries")
.beginArray();
Object lock = new Object();
getQueryDumps(items).forEach(obj ->
{
synchronized (lock){
getQueryDumps(items).forEach(obj -> {
synchronized (lock) {
gson.toJson(obj, jsonWriter);
dumpedQueries++;
}
Expand All @@ -223,40 +224,37 @@ private void doDumpJson(File file){
}

// If you don't wanna hold all this crap in memory at once, you're going to have to work for it.
public void dumpJson(File file) throws IOException {
if(dumpActive){
NEIClientUtils.printChatMessage(new ChatComponentTranslation(
"nei.options.tools.dump.recipes.duplicate"
));
public void dumpJson(File file) {
if (dumpActive) {
NEIClientUtils.printChatMessage(new ChatComponentTranslation("nei.options.tools.dump.recipes.duplicate"));
return;
}
dumpActive = true;
TimerTask progressTask = getProgressTask();
Thread workerThread = new Thread(()-> {
try{
Thread workerThread = new Thread(() -> {
try {
doDumpJson(file);
}finally{
} finally {
dumpActive = false;
progressTask.cancel();
}
NEIClientUtils.printChatMessage(new ChatComponentTranslation(
"nei.options.tools.dump.recipes.complete"
));
NEIClientUtils.printChatMessage(new ChatComponentTranslation("nei.options.tools.dump.recipes.complete"));
});
workerThread.start();
}

@NotNull
private TimerTask getProgressTask() {
TimerTask progressTask = new TimerTask() {

@Override
public void run() {
NEIClientUtils.printChatMessage(new ChatComponentTranslation(
"nei.options.tools.dump.recipes.progress",
dumpedQueries,
totalQueries,
(float)dumpedQueries/totalQueries*100
));
NEIClientUtils.printChatMessage(
new ChatComponentTranslation(
"nei.options.tools.dump.recipes.progress",
dumpedQueries,
totalQueries,
(float) dumpedQueries / totalQueries * 100));
}
};
timer.schedule(progressTask, 0, progressInterval);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@

import codechicken.nei.recipe.ICraftingHandler;
import codechicken.nei.util.NBTJson;
import com.google.gson.*;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSerializationContext;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import gregtech.api.enums.Materials;
import gregtech.api.util.GT_Recipe;
Expand All @@ -19,39 +26,43 @@
import java.util.Set;

public class GTDefaultRecipeInfoExtractor implements IRecipeInfoExtractor {

private static class GTRecipeExclusionStrategy implements ExclusionStrategy {
private final static Set<String> badFields = new HashSet<String>(Arrays.asList(
// Unnecessary/bulky info
"recipeCategory",
"stackTraces",
"owners",
// Rely on other dumping logic for inputs and outputs;
// auto-dumping Minecraft ItemStacks causes recursion into some nasty places
// I could make an adapter, but the generic NEI inputs/outputs logic covers these items no problemo
"mInputs",
"mOutputs",
// FluidStack things
// Icons are very large, not wise to have stored every time we dump an item
"stillIconResourceLocation",
"flowingIconResourceLocation",
"stillIcon",
"flowingIcon",
// There's a recursive fluid definition here
"registeredFluid",
// The automatic serializer doesn't like the rarity enum, I dunno why
"rarity",
// I don't think a fluid's corresponding block is useful, and it causes breaky recursion
"block",
// Some recipes are GT_Recipe_WithAlt, which have more evil ItemStacks we can't serialize.
"mOreDictAlt"

));
List<Type> badTypes = Arrays.asList(
GT_NEI_DefaultHandler.class,
ItemStack.class,
FluidStack.class,
Materials.class // Pops up in metadata (contains lots of images and such)
);

private final static Set<String> badFields = new HashSet<>(
Arrays.asList(
// Unnecessary/bulky info
"recipeCategory",
"stackTraces",
"owners",
// Rely on other dumping logic for inputs and outputs;
// auto-dumping Minecraft ItemStacks causes recursion into some nasty places
// I could make an adapter, but the generic NEI inputs/outputs logic covers these items no problemo
"mInputs",
"mOutputs",
// FluidStack things
// Icons are very large, not wise to have stored every time we dump an item
"stillIconResourceLocation",
"flowingIconResourceLocation",
"stillIcon",
"flowingIcon",
// There's a recursive fluid definition here
"registeredFluid",
// The automatic serializer doesn't like the rarity enum, I dunno why
"rarity",
// I don't think a fluid's corresponding block is useful, and it causes breaky recursion
"block",
// Some recipes are GT_Recipe_WithAlt, which have more evil ItemStacks we can't serialize.
"mOreDictAlt"

));
List<Type> badTypes = Arrays
.asList(GT_NEI_DefaultHandler.class, ItemStack.class, FluidStack.class, Materials.class // Pops up in
// metadata
// (contains lots of
// images and such)
);

@Override
public boolean shouldSkipField(FieldAttributes f) {

Expand All @@ -64,38 +75,46 @@ public boolean shouldSkipClass(Class<?> clazz) {
}
}

private class FluidStackSerializer implements JsonSerializer<FluidStack>{
private static final Type fluidType = new TypeToken<Fluid>(){}.getType();
private class FluidStackSerializer implements JsonSerializer<FluidStack> {

private static final Type fluidType = new TypeToken<Fluid>() {}.getType();

@Override
public JsonElement serialize(FluidStack src, Type typeOfSrc, JsonSerializationContext context) {
// Fluids have some goofy unserializable things, similar to ItemStacks
JsonObject root = new JsonObject();
root.addProperty("amount", src.amount);
if(src.tag != null){
if (src.tag != null) {
root.add("tag", NBTJson.toJsonObject(src.tag));
}
// Some fluids (like water) are defined using anonymous types
// I think that specifying the type for GT_Fluids would throw away information,
// but for non-GT_Fluids, we'll need to un-anonymize this beeswax.
JsonObject fluid = null;
if(src.getFluid().getClass().equals(GT_Fluid.class)){
JsonObject fluid;
if (src.getFluid()
.getClass()
.equals(GT_Fluid.class)) {
fluid = (JsonObject) gson.toJsonTree(src.getFluid());
}else{
} else {
fluid = (JsonObject) gson.toJsonTree(src.getFluid(), fluidType);
}
// Manually serialize rarity bc wierdness
fluid.addProperty("rarity", src.getFluid().getRarity().toString());
fluid.addProperty(
"rarity",
src.getFluid()
.getRarity()
.toString());
// Slap on some info that's only available via method calls
fluid.addProperty("id", src.getFluidID());
root.add("fluid", fluid);


return root;
}
}

private Gson gson;
public GTDefaultRecipeInfoExtractor(){
private final Gson gson;

public GTDefaultRecipeInfoExtractor() {
gson = new GsonBuilder()
// We might be only doing serializations, but GSON will still create
// a type adapter and get stuck in nasty recursion/type access land
Expand All @@ -109,24 +128,24 @@ public GTDefaultRecipeInfoExtractor(){
@Override
public JsonElement extractInfo(ICraftingHandler handler, int recipeIndex) {
GT_NEI_DefaultHandler gthandler = (GT_NEI_DefaultHandler) handler;
GT_Recipe recipe = gthandler.getCache().get(recipeIndex).mRecipe;
try{
GT_Recipe recipe = gthandler.getCache()
.get(recipeIndex).mRecipe;
try {
return gson.toJsonTree(recipe);
}catch(Exception e){
} catch (Exception e) {
System.out.println("O poop");
return null;
}
}

@Override
public String[] getCompatibleHandlers() {
return new String[]{ "gregtech.nei.GT_NEI_DefaultHandler" };
return new String[] { "gregtech.nei.GT_NEI_DefaultHandler" };
}

@Override
public String getSlug() {
return "greg_data";
}


}
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package com.hermanoid.nerd.info_extractors;

import codechicken.nei.recipe.ICraftingHandler;
import com.google.gson.JsonElement;

import codechicken.nei.recipe.ICraftingHandler;

public interface IRecipeInfoExtractor {
public JsonElement extractInfo(ICraftingHandler handler, int recipeIndex);

public String[] getCompatibleHandlers();
JsonElement extractInfo(ICraftingHandler handler, int recipeIndex);

String[] getCompatibleHandlers();

public String getSlug();
String getSlug();
}

0 comments on commit 29d7341

Please sign in to comment.