Jump to content

Recommended Posts

Posted

Heya, I translated JsonToNBt to something meaningful for my own purposes, thought i'd share it here.

Maybe it helps with the deobfuscation of that piece of code.

 

package tschallacka.whotookmycookies.nbt;

import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import java.util.Iterator;
import java.util.Stack;
import java.util.regex.Pattern;

import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTException;
import net.minecraft.nbt.NBTTagByte;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagDouble;
import net.minecraft.nbt.NBTTagFloat;
import net.minecraft.nbt.NBTTagInt;
import net.minecraft.nbt.NBTTagIntArray;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagLong;
import net.minecraft.nbt.NBTTagShort;
import net.minecraft.nbt.NBTTagString;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class JSONtoNBT
{
    private static final Logger logger = LogManager.getLogger();
    private static final Pattern isIntegerOrStringArray = Pattern.compile("\\[[-+\\d|,\\s]+\\]");
    private static final String __OBFID = "CL_00001232";
   /**
     * Get a compound tag from json string
     * @param input JSON String input
     * @return NBTTagCompound with the correct values 
     * @throws NBTException
     */
    public static NBTTagCompound getCompoundTagFromString(String input) throws NBTException
    {
        input = input.trim();
        // if the item starts with a { it's a compound object
        if (!input.startsWith("{"))
        {
            throw new NBTException("Invalid tag encountered, expected \'{\' as first char.");
        }
        else if (checkNumberOfTopTags(input) != 1)
        {
            throw new NBTException("Encountered multiple top tags, only one expected");
        }
        else
        {
            return (NBTTagCompound)toJSONCompound("tag", input).getNBTValue();
        }
    }

    static int checkNumberOfTopTags(String checkThis) throws NBTException
    {
        int encountered = 0;
        boolean flag = false;
        Stack stack = new Stack();

        for (int i = 0; i < checkThis.length(); ++i)
        {
            char c0 = checkThis.charAt(i);
            //char 34 = "
            if (c0 == 34)
            {
                if (isValidJSONString(checkThis, i))
                {
                    if (!flag)
                    {
                        throw new NBTException("Illegal use of \\\": " + checkThis);
                    }
                }
                else
                {
                    flag = !flag;
                }
            }
            else if (!flag)
            {
            	// 123 = {
            	// 91 = [
                if (c0 != 123 && c0 != 91)
                {
                	// 123 = {
                	// 125 = }
                    if (c0 == 125 && (stack.isEmpty() || ((Character)stack.pop()).charValue() != 123))
                    {
                        throw new NBTException("Unbalanced curly brackets {}: " + checkThis);
                    }
                    // 91 = [
                    // 93 = [
                    if (c0 == 93 && (stack.isEmpty() || ((Character)stack.pop()).charValue() != 91))
                    {
                        throw new NBTException("Unbalanced square brackets []: " + checkThis);
                    }
                }
                else
                {
                    if (stack.isEmpty())
                    {
                        ++encountered;
                    }

                    stack.push(Character.valueOf(c0));
                }
            }
        }

        if (flag)
        {
            throw new NBTException("Unbalanced quotation: " + checkThis);
        }
        else if (!stack.isEmpty())
        {
            throw new NBTException("Unbalanced brackets: " + checkThis);
        }
        else
        {
            if (encountered == 0 && !checkThis.isEmpty())
            {
                encountered = 1;
            }

            return encountered;
        }
    }
    /**
     * Takes any number of elements array but will only use the first two elements of the array.
     * Will throw an ArrayIndexIsOutOfBounds exception when an array < 2 elements is supplied
     * @param arrayInputString Element at first index is name of object. Element at second index is contents
     * @return JSONtoNBT.Any
     * @throws NBTException, ArrayIndexOutOfBoundsException
     */
    static JSONtoNBT.Any toJSONCompound(String ... arrayInputString) throws NBTException
    {
        return toJSONCompound(arrayInputString[0], arrayInputString[1]);
    }

    static JSONtoNBT.Any toJSONCompound(String name, String contents) throws NBTException
    {
        contents = contents.trim();
        String subContents;
        boolean flag;
        char character;

        if (contents.startsWith("{"))
        {
            contents = contents.substring(1, contents.length() - 1);
            JSONtoNBT.Compound compound;

            for (compound = new JSONtoNBT.Compound(name); contents.length() > 0; contents = contents.substring(subContents.length() + 1))
            {
                subContents = getValueFromJSONTag(contents, true);

                if (subContents.length() > 0)
                {
                    flag = false;
                    compound.arrayList.add(getJSONCompound(subContents, flag));
                }

                if (contents.length() < subContents.length() + 1)
                {
                    break;
                }

                character = contents.charAt(subContents.length());
                // 44 = "
                // 123 = {
                // 125 = }
                // 91 = [
                // 93 = ]
                if (character != 44 && character != 123 && character != 125 && character != 91 && character != 93)
                {
                    throw new NBTException("Unexpected token \'" + character + "\' at: " + contents.substring(subContents.length()));
                }
            }

            return compound;
        }
        else if (contents.startsWith("[") && !isIntegerOrStringArray.matcher(contents).matches())
        {
            contents = contents.substring(1, contents.length() - 1);
            JSONtoNBT.List list;

            for (list = new JSONtoNBT.List(name); contents.length() > 0; contents = contents.substring(subContents.length() + 1))
            {
                subContents = getValueFromJSONTag(contents, false);

                if (subContents.length() > 0)
                {
                    flag = true;
                    list.arrayList.add(getJSONCompound(subContents, flag));
                }

                if (contents.length() < subContents.length() + 1)
                {
                    break;
                }

                character = contents.charAt(subContents.length());

                if (character != 44 && character != 123 && character != 125 && character != 91 && character != 93)
                {
                    throw new NBTException("Unexpected token \'" + character + "\' at: " + contents.substring(subContents.length()));
                }
            }

            return list;
        }
        else
        {
            return new JSONtoNBT.Primitive(name, contents);
        }
    }
    /**
     * Takes the string and returns the Compound key => value pair
     * @param parseThis The string to retrieve the values from
     * @param errorMode Should we throw exceptions or not
     * @return JSONtoNBTAny key => value compound
     * @throws NBTException
     */
    private static JSONtoNBT.Any getJSONCompound(String parseThis, boolean errorMode) throws NBTException
    {
        String s1 = getKeyFromString(parseThis, errorMode);
        String s2 = getValueFromString(parseThis, errorMode);
        return toJSONCompound(new String[] {s1, s2});
    }
    /**
     * Gets the value from a JSON string
     * @param searchThis The string to search for first colon
     * @param errorMode Will throw exceptions if true, none if set to false
     * @return String Value
     * @throws NBTException on invalid JSON && errorModeSilent is set to true
     */
    private static String getValueFromJSONTag(String searchThis, boolean errorMode) throws NBTException
    {
        int locationOfColon = findCharacter(searchThis, ':');
        int locationOfComma = findCharacter(searchThis, ',');

        if (errorMode)
        {
            if (locationOfColon == -1)
            {
                throw new NBTException("Unable to locate name/value separator for string: " + searchThis);
            }

            if (locationOfComma != -1 && locationOfComma < locationOfColon)
            {
                throw new NBTException("Name error at: " + searchThis);
            }
        }
        else if (locationOfColon == -1 || locationOfColon > locationOfComma)
        {
            locationOfColon = -1;
        }

        return getValueToKey(searchThis, locationOfColon);
    }

    private static String getValueToKey(String parseThis, int startPos) throws NBTException
    {
        Stack stack = new Stack();
        int j = startPos + 1;
        boolean flag = false;
        boolean flag1 = false;
        boolean flag2 = false;

        for (int k = 0; j < parseThis.length(); ++j)
        {
            char character = parseThis.charAt(j);
            // 34 = "
            if (character == 34)
            {
                if (isValidJSONString(parseThis, j))
                {
                    if (!flag)
                    {
                        throw new NBTException("Illegal use of \\\": " + parseThis);
                    }
                }
                else
                {
                    flag = !flag;

                    if (flag && !flag2)
                    {
                        flag1 = true;
                    }

                    if (!flag)
                    {
                        k = j;
                    }
                }
            }
            else if (!flag)
            {
                if (character != 123 && character != 91)
                {
                	// 123 = {
                	// 125 = }
                    if (character == 125 && (stack.isEmpty() || ((Character)stack.pop()).charValue() != 123))
                    {
                        throw new NBTException("Unbalanced curly brackets {}: " + parseThis);
                    }
                    // 91 = [
                    // 93 = ]
                    if (character == 93 && (stack.isEmpty() || ((Character)stack.pop()).charValue() != 91))
                    {
                        throw new NBTException("Unbalanced square brackets []: " + parseThis);
                    }
                    // 44 = ,
                    if (character == 44 && stack.isEmpty())
                    {
                        return parseThis.substring(0, j);
                    }
                }
                else
                {
                    stack.push(Character.valueOf(character));
                }
            }

            if (!Character.isWhitespace(character))
            {
                if (!flag && flag1 && k != j)
                {
                    return parseThis.substring(0, k + 1);
                }

                flag2 = true;
            }
        }

        return parseThis.substring(0, j);
    }
    /**
     * Returns "" if it doesn't contain a key or contains a list/compound
     * @param parseThis The string to find the key from
     * @param errorMode Throws Exception if false when no key is found.
     * @return String key if found or string empty if not found
     * @throws NBTException
     */
    private static String getKeyFromString(String parseThis, boolean errorMode) throws NBTException
    {
        if (errorMode)
        {
            parseThis = parseThis.trim();

            if (parseThis.startsWith("{") || parseThis.startsWith("["))
            {
                return "";
            }
        }

        int i = findCharacter(parseThis, ':');

        if (i == -1)
        {
            if (errorMode)
            {
                return "";
            }
            else
            {
                throw new NBTException("Unable to locate name/value separator for string: " + parseThis);
            }
        }
        else
        {
            return parseThis.substring(0, i).trim();
        }
    }
    /**
     * Gets the value of the string.
     * @param parseThis The string to retrieve the value from
     * @param errorMode if set to false it will throw an error if it can't find a valid value location
     * @return String value str
     * @throws NBTException
     */
    private static String getValueFromString(String parseThis, boolean errorMode) throws NBTException
    {
        if (errorMode)
        {
            parseThis = parseThis.trim();

            if (parseThis.startsWith("{") || parseThis.startsWith("["))
            {
                return parseThis;
            }
        }

        int i = findCharacter(parseThis, ':');

        if (i == -1)
        {
            if (errorMode)
            {
                return parseThis;
            }
            else
            {
                throw new NBTException("Unable to locate name/value separator for string: " + parseThis);
            }
        }
        else
        {
            return parseThis.substring(i + 1).trim();
        }
    }

    private static int findCharacter(String input, char characterToFind)
    {
        int i = 0;

        for (boolean flag = true; i < input.length(); ++i)
        {
            char character = input.charAt(i);
            // 34 = "
            if (character == 34)
            {
                if (!isValidJSONString(input, i))
                {
                    flag = !flag;// good heavens... why not a break?
                }
            }
            else if (flag)
            {
                if (character == characterToFind)
                {
                    return i;
                }

                if (character == 123 || character == 91)
                {
                    return -1;
                }
            }
        }

        return -1;
    }

    private static boolean isValidJSONString(String parseThis, int locationToStart)
    {																		//92 = \
        return locationToStart > 0 && parseThis.charAt(locationToStart - 1) == 92 && !isValidJSONString(parseThis, locationToStart - 1);
    }

    abstract static class Any
        {
            protected String key;
            private static final String __OBFID = "CL_00001233";

            public abstract NBTBase getNBTValue();
        }

    static class Compound extends JSONtoNBT.Any
        {
            protected java.util.List arrayList = Lists.newArrayList();
            private static final String __OBFID = "CL_00001234";

            public Compound(String p_i45137_1_)
            {
                this.key = p_i45137_1_;
            }

            public NBTBase getNBTValue()
            {
                NBTTagCompound nbttagcompound = new NBTTagCompound();
                Iterator iterator = this.arrayList.iterator();

                while (iterator.hasNext())
                {
                    JSONtoNBT.Any any = (JSONtoNBT.Any)iterator.next();
                    nbttagcompound.setTag(any.key, any.getNBTValue());
                }

                return nbttagcompound;
            }
        }

    static class List extends JSONtoNBT.Any
        {
            protected java.util.List arrayList = Lists.newArrayList();
            private static final String __OBFID = "CL_00001235";

            public List(String keyValue)
            {
                this.key = keyValue;
            }

            public NBTBase getNBTValue()
            {
                NBTTagList nbttaglist = new NBTTagList();
                Iterator iterator = this.arrayList.iterator();

                while (iterator.hasNext())
                {
                    JSONtoNBT.Any any = (JSONtoNBT.Any)iterator.next();
                    nbttaglist.appendTag(any.getNBTValue());
                }

                return nbttaglist;
            }
        }

    static class Primitive extends JSONtoNBT.Any
        {
            private static final Pattern DOUBLE = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+[d|D]");
            private static final Pattern FLOAT = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+[f|F]");
            private static final Pattern BYTE = Pattern.compile("[-+]?[0-9]+[b|B]");
            private static final Pattern LONG = Pattern.compile("[-+]?[0-9]+[l|L]");
            private static final Pattern STRING = Pattern.compile("[-+]?[0-9]+[s|S]");
            private static final Pattern INTEGER = Pattern.compile("[-+]?[0-9]+");
            private static final Pattern SECRETDOUBLE = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+");
            private static final Splitter COMMASPLITTER = Splitter.on(',').omitEmptyStrings();
            protected String value;
            private static final String __OBFID = "CL_00001236";

            public Primitive(String key, String value)
            {
                this.key = key;
                this.value = value;
            }

            public NBTBase getNBTValue()
            {
                try
                {
                    if (DOUBLE.matcher(this.value).matches())
                    {
                        return new NBTTagDouble(Double.parseDouble(this.value.substring(0, this.value.length() - 1)));
                    }

                    if (FLOAT.matcher(this.value).matches())
                    {
                        return new NBTTagFloat(Float.parseFloat(this.value.substring(0, this.value.length() - 1)));
                    }

                    if (BYTE.matcher(this.value).matches())
                    {
                        return new NBTTagByte(Byte.parseByte(this.value.substring(0, this.value.length() - 1)));
                    }

                    if (LONG.matcher(this.value).matches())
                    {
                        return new NBTTagLong(Long.parseLong(this.value.substring(0, this.value.length() - 1)));
                    }

                    if (STRING.matcher(this.value).matches())
                    {
                        return new NBTTagShort(Short.parseShort(this.value.substring(0, this.value.length() - 1)));
                    }

                    if (INTEGER.matcher(this.value).matches())
                    {
                        return new NBTTagInt(Integer.parseInt(this.value));
                    }

                    if (SECRETDOUBLE.matcher(this.value).matches())
                    {
                        return new NBTTagDouble(Double.parseDouble(this.value));
                    }

                    if (this.value.equalsIgnoreCase("true") || this.value.equalsIgnoreCase("false"))
                    {
                        return new NBTTagByte((byte)(Boolean.parseBoolean(this.value) ? 1 : 0));
                    }
                }
                catch (NumberFormatException numberformatexception1)
                {
                    this.value = this.value.replaceAll("\\\\\"", "\"");
                    return new NBTTagString(this.value);
                }

                if (this.value.startsWith("[") && this.value.endsWith("]"))
                {
                    String s = this.value.substring(1, this.value.length() - 1);
                    String[] astring = (String[])Iterables.toArray(COMMASPLITTER.split(s), String.class);

                    try
                    {
                        int[] aint = new int[astring.length];

                        for (int j = 0; j < astring.length; ++j)
                        {
                            aint[j] = Integer.parseInt(astring[j].trim());
                        }

                        return new NBTTagIntArray(aint);
                    }
                    catch (NumberFormatException numberformatexception)
                    {
                        return new NBTTagString(this.value);
                    }
                }
                else
                {
                    if (this.value.startsWith("\"") && this.value.endsWith("\""))
                    {
                        this.value = this.value.substring(1, this.value.length() - 1);
                    }

                    this.value = this.value.replaceAll("\\\\\"", "\"");
                    StringBuilder stringbuilder = new StringBuilder();

                    for (int i = 0; i < this.value.length(); ++i)
                    {
                        if (i < this.value.length() - 1 && this.value.charAt(i) == 92 && this.value.charAt(i + 1) == 92)
                        {
                            stringbuilder.append('\\');
                            ++i;
                        }
                        else
                        {
                            stringbuilder.append(this.value.charAt(i));
                        }
                    }

                    return new NBTTagString(stringbuilder.toString());
                }
            }
        }
}

How much wood could a woodchuck chuck if a wood chuck could chuck wood - Guybrush Treepwood

 

I wrote my own mod ish... still a few bugs to fix. http://thaumcraft.duckdns.org/downloads/MagicCookies-1.0.6.4.jar

Posted

Can't find a quick manual so okay. I really dont have time for this to figure out.

I already lost an hour deciphering this, I have only precious time in my off hours work to get some modding done. I already shared it here. So it can be found by people who want it. But at this point in time im not spending my time on feeding it into the bot. I only have limited hours to work on my mods and I have so much to get done in the next two months.

 

So if a volunteer wants to feed it into the bot, be my guest. I want to spend my time otherwise.

 

My apologies if this is selfish.

How much wood could a woodchuck chuck if a wood chuck could chuck wood - Guybrush Treepwood

 

I wrote my own mod ish... still a few bugs to fix. http://thaumcraft.duckdns.org/downloads/MagicCookies-1.0.6.4.jar

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • the modpack keep crashing idk why,cause it never said anything about any mods causing it. crash log:https://drive.google.com/file/d/1iYKlUgvHUob8DjyRc3gqP_Viv_kSHO6L/view?usp=sharing mod list:https://drive.google.com/file/d/1MvMT-z9Jg2BITQ4uLshJ1uOh7q9EMBfC/view?usp=sharing but the server(anternos) works just fine
    • Hello, I am trying to make 2 recipes for a ruby. The first one is turning a block into a ruby and the other one is 9 nuggets into a ruby. But I keep on getting a error java.lang.IllegalStateException: Duplicate recipe rubymod:ruby   Any help would be great on how to fix it
    • Hello everyone, i'm new with programing Mods, and will need a lot of your help if possible,  Im trying to make a new GUI interface responsible to control the Droprate of game, it will control de loot drop and loot table for mobs and even blocks, but i try to make a simple Gui Screen, and wenever i try to use it, the game crash's with the error message in the subject, here is the code im using to:  IDE: IntelliJ Comunity - latest version Forge: 47.3.0 Minecraft version: 1.20.1 mapping_channel: parchment mapping_version=2023.09.03-1.20.1 Crash report link: https://pastebin.com/6dV8k1Fw   Code im using is:    package createchronical.droprateconfig; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import java.util.HashMap; import java.util.Map; public class ConfigScreen extends Screen { private static final ResourceLocation BACKGROUND_TEXTURE = new ResourceLocation("droprateconfig", "textures/gui/config_background.png"); // Mapa de mobs e itens com seus respectivos drop rates private final Map<String, Integer> dropRates = new HashMap<>(); public ConfigScreen() { super(Component.literal("Configurações de Drop Rate")); // Inicializa com valores de drop rate padrão dropRates.put("Zombie", 10); // Exemplo de mob dropRates.put("Creeper", 5); // Exemplo de mob dropRates.put("Iron Ore", 50); // Exemplo de item dropRates.put("Diamond", 2); // Exemplo de item } @Override protected void init() { // Cria um botão para cada mob/item e adiciona na tela int yOffset = this.height / 2 - 100; // Posicionamento inicial for (Map.Entry<String, Integer> entry : dropRates.entrySet()) { String itemName = entry.getKey(); int dropRate = entry.getValue(); // Cria um botão para cada mob/item this.addRenderableWidget(Button.builder( Component.literal(itemName + ": " + dropRate + "%"), button -> onDropRateButtonPressed(itemName) ).bounds(this.width / 2 - 100, yOffset, 200, 20).build()); yOffset += 25; // Incrementa a posição Y para o próximo botão } // Adiciona o botão de "Salvar Configurações" this.addRenderableWidget(Button.builder(Component.literal("Salvar Configurações"), button -> onSavePressed()) .bounds(this.width / 2 - 100, yOffset, 200, 20) .build()); } private void onDropRateButtonPressed(String itemName) { // Lógica para alterar o drop rate do item/mob selecionado // Aqui, vamos apenas incrementar o valor como exemplo int currentRate = dropRates.get(itemName); dropRates.put(itemName, currentRate + 5); // Aumenta o drop rate em 5% } private void onSavePressed() { // Lógica para salvar as configurações (temporariamente apenas na memória) // Vamos apenas imprimir para verificar dropRates.forEach((item, rate) -> { System.out.println("Item: " + item + " | Novo Drop Rate: " + rate + "%"); }); // Fecha a tela após salvar Screen pGuiScreen = null; assert this.minecraft != null; this.minecraft.setScreen(pGuiScreen); } @Override public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) { this.renderBackground(guiGraphics); guiGraphics.blit(BACKGROUND_TEXTURE, this.width / 2 - 128, this.height / 2 - 128, 0, 0, 256, 256, 256, 256); super.render(guiGraphics, mouseX, mouseY, partialTicks); } }  
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.