### Java Constructor and Initializer Examples Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This Java code illustrates the concepts of constructors and static initializers (constructors). It shows how to define a class with a constructor (`Example()`) and a static block (`static {}`), both of which are used to initialize class fields. These constructs are relevant when localizing strings found within them. ```java ## Example.java ... private String name; // 这是Example类定义的全局变量(或称为字段) private String desc; public Example() { // 与类名相同的方法即为构造方法。内部类也可能有构造方法 this.name = “Example Text”; ... } static { // 类似static{...}的方法体即为构造器。这个方法会在类初始化时静态初始化全局变量值 this.desc = “Example Description.” ... } private String modVersion = “1.0.0”; // 这种直接初始化全局变量值的写法也视为位于构造器内 // 以上代码中desc的初始化方法与modVersion的初始化方法是等效的 ... ``` -------------------------------- ### Java: Example Method Return Value Mapping Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This Java code snippet from Example.java shows a method `getName` that returns a String. The accompanying JSON documentation demonstrates how to map the return value of this method for potential modification using the 'R' prefix in the `local` field. ```java public static String getName() { String result = ...; ... return result; } ``` -------------------------------- ### Java Code Structure Example (Vault Patcher) Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This snippet demonstrates the expected structure for Java code files when working with Vault Patcher. It highlights how to denote filenames and includes comments, noting that comments in JSON are not valid. ```java ## test.java // 第一行由##开头,用于区分文件名 // 以.java结尾代表mod反编译代码,以.json结尾代表配置文件或其他 // 第一行没有其他作用,也不在代码中生效,请勿误用 ... // 三个点(省略号)代表此处有被省略的内容 System.out.printIn(“Hello world!”) // 注意,我们使用双斜杠表示注释内容,实际上JSON文件中不能使用这种方式注释 // 注释文本仅作代码介绍或解析使用,不要将我的注释添加到你的代码中 ``` -------------------------------- ### Log: Vault Patcher Ordinal Identification Example Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This is an example log entry (`latest.log`) from Vault Patcher during debug mode. It shows the output format used to identify translation replacements. The critical information here is the `ordinal` value, indicated by `[24]`, which corresponds to the specific instance of the `GresearchName` variable being targeted in the `renderHover` method. ```log [254月2025 00:53:49.818] [modloading-worker-0/INFO] [VaultPatcher/]: [VaultPatcher] Trying replacing! Backpacks -> 小背包 in iskallia/vault/client/gui/screen/player/legacy/widget.ResearchWidget [24] | TranslationInfo{targetClassInfo=TargetClassInfo{name='iskallia.vault.client.gui.screen.player.legacy.widget.ResearchWidget', method='renderHover', local='GresearchName', ordinal=-1, matchMode=FULL, localMode=GLOBAL_VARIABLE}, pairs={['Backpacks'='小背包']}} ... ``` -------------------------------- ### Implement a Custom VaultPatcher Plugin in Java Source: https://context7.com/3093fengming/vaultpatcher/llms.txt This Java code defines an example plugin implementing the VaultPatcherPlugin interface. It includes methods for plugin identification, lifecycle management (start, end), configuration loading, module loading, and class transformation hooks. ```java public class ExamplePlugin implements VaultPatcherPlugin { @Override public String getName() { return "Example Plugin"; } @Override public void start(Path mcPath) { System.out.println("Plugin starting at: " + mcPath); } @Override public void onLoadConfig(Phase phase) { if (phase == Phase.BEFORE) { // Modify config before loading } else { // Post-process after loading } } @Override public void onLoadModule(VaultPatcherModule module, Phase phase) { // Hook into module loading } @Override public void onTransformClass(ClassNode classNode, Phase phase) { if (phase == Phase.BEFORE) { // Pre-process class before transformation } else { // Post-process after transformation } } @Override public void end() { System.out.println("Plugin cleanup"); } } ``` -------------------------------- ### JSON Structure for Translation Data Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_start This JSON structure defines the basic format for storing translation information. It specifies the target class name (`name`) and a list of key-value pairs (`p`) representing the original string (`k`) and its replacement (`v`). This is fundamental for the VaultPatcher's ASM functionality. ```json { "t": { "name": "" }, "p": [ { "k": "", "v": "" }, { "k": "", "v": "" } ] } ``` -------------------------------- ### JSON Entry for Java TextComponent Translation Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This JSON structure shows how to create a translation entry for the Java 'TextComponent' example. The 'target_class' specifies the nested class 'DungeonDoorTileEntity$Difficulty', and the 'key' field contains the exact string 'Difficulty: %s' found in the Java code. The 'value' field holds the translated string '难度:%s'. ```json { "target_class": { "name": "iskallia.vault.block.entity.DungeonDoorTileEntity$Difficulty" }, "key": "Difficulty: %s", "value": "难度:%s" } ``` -------------------------------- ### JSON Comment Example in Vault Patcher Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This JSON snippet illustrates how to include comments within a Vault Patcher module file. The '_comment' key allows for adding explanatory text directly into the JSON, which can help in organizing translation data, clarifying logic, or documenting important points for future maintenance. Comments should not be the first entry in the file. ```json { "_comment": "这是一条模块文件中的注释" } ``` -------------------------------- ### Java Code for Component.literal (1.19+) Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This Java code snippet shows the modern method for creating literal text components in Minecraft versions 1.19 and above. The 'Component.literal("Example Text")' pattern is used to define strings that can be targeted for translation. This method is often searched for when extracting hardcoded text. ```java Component.literal("Example Text"); ``` -------------------------------- ### Java TextComponent Example for Translation Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This Java code snippet demonstrates how a translatable string is embedded within a 'TextComponent'. The 'Difficulty: %s' string is identified as a target for translation. The associated JSON entry would map this key to its localized value, preserving format specifiers like '%s'. ```java public static class Difficulty { ... public Component getDisplay() { return (new TextComponent("Difficulty: %s".formatted(this.getName()))) .m_130948_(Style.f_131099_.m_131148_(TextColor.m_131266_(this.getColor()))); // 这里要替换的是显示难度的文本 } } ``` -------------------------------- ### JSON: Mapping Method Return Value in Example.java Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This JSON snippet illustrates mapping the return value of the `getName` method in `Example.java`. The `local` field with the prefix 'R' is used to target the method's return value, providing a way to reference or modify it. ```json { "name": "com.dricetea.examplemod.Example", "method": "getName", "local": "Rresult" } ``` -------------------------------- ### VaultPatcher 配置文件示例 (JSON) Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_configs 这是VaultPatcher的示例配置文件,定义了需要加载的模块、全局类、应用模组以及调试模式的设置。它展示了如何配置VP加载和管理补丁。 ```json { "mods": [ "example" ], "classes": [], "apply_mods": [], "debug_mode": { "is_enable": true, "use_cache": true, "export_class": false, "output_format": " -> in [] | ", "output_mode": 0 } } ``` -------------------------------- ### Java Code for Player Event Handling with Localization Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This Java code snippet demonstrates event handling for player actions within a game, specifically focusing on player completion, bailing, or failing a 'Vault'. It uses a switch statement to determine the outcome message and includes placeholders for objectives. This code is the source for localization in the `ClassicListenersLogic.java` file. ```java ## ClassicListenersLogic.java public void initServer(VirtualWorld world, Vault vault) { CommonEvents.PLAYER_REGEN.register(this, (data) -> { ... }); CommonEvents.LISTENER_LEAVE.register(this, (data) -> { ... String var10002; switch (completion) { case COMPLETED -> var10002 = " completed a " + objective + "Vault!"; case BAILED -> var10002 = " survived a " + objective + "Vault."; case FAILED -> var10002 = " was defeated in a " + objective + "Vault."; default -> throw new IncompatibleClassChangeError(); // 需替换的即为这里标为粗体的6处(5种)文本 } ... }); } ``` -------------------------------- ### JSON Configuration for ClassicListenersLogic Localization Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This JSON configuration is used for localizing strings within the `ClassicListenersLogic.java` file. It targets a specific lambda method (`lambda$initServer$1`) and provides pairs of English keys and their corresponding Chinese translations for player actions related to Vaults. ```json { "target_class": { "name": "iskallia.vault.core.vault.player.ClassicListenersLogic", "method": "lambda$initServer$1" }, "pairs": [ { "key": "Vault!", "value": "宝库世界!" }, { "key": "Vault.", "value": "宝库世界。" }, { "key": " was defeated in a ", "value": "被击败并离开了" }, { "key": " completed a ", "value": "完成了" }, { "key": " survived a ", "value": "成功存活并离开了" } ] } ``` -------------------------------- ### Java: Render Hover Tooltip Logic in ResearchWidget Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This Java code snippet from ResearchWidget.java handles the rendering of hover tooltips. It dynamically displays research requirements and unlock restrictions based on game state and configurations. It utilizes helper classes like FormattedCharSequence and TooltipUtil for text formatting and rendering. ```java private void renderHover(PoseStack matrixStack, int mouseX, int mouseY, float partialTicks) { if (this.m_5953_((double)mouseX, (double)mouseY)) { List tTip = new ArrayList(); tTip.add(FormattedCharSequence.m_13714_(this.researchName, Style.f_131099_)); // 这里调用了全局变量researchName List conflicts; if (this.locked) { conflicts = ModConfigs.SKILL_GATES.getGates().getDependencyResearches(this.researchName); if (!conflicts.isEmpty()) { String tTipRequirement = ModConfigs.SKILL_GATES.getGates().hasEitherSkillGate(this.getResearchName()) ? " any of" : ""; // 构造局部变量tTipRequirement tTip.add(FormattedCharSequence.m_13714_("Requires" + tTipRequirement + ":", Style.f_131099_.m_131140_(ChatFormatting.RED))); // 这里调用了局部变量tTipRequirement conflicts.forEach((research) -> { // 当前类中第2个lambda tTip.add(FormattedCharSequence.m_13714_("- " + research.getName(), Style.f_131099_.m_131140_(ChatFormatting.RED))); // 这里调用了方法getName的返回值 }); } } conflicts = ModConfigs.SKILL_GATES.getGates().getLockedByResearches(this.researchName); if (!conflicts.isEmpty()) { tTip.add(FormattedCharSequence.m_13714_("Cannot be unlocked alongside:", Style.f_131099_.m_131140_(ChatFormatting.RED))); conflicts.forEach((research) -> { // 当前类中第3个lambda tTip.add(FormattedCharSequence.m_13714_("- " + research.getName(), Style.f_131099_.m_131140_(ChatFormatting.RED))); // 这里也调用了方法getName的返回值 }); } TooltipUtil.renderTooltip(matrixStack, tTip, mouseX, mouseY, Integer.MAX_VALUE, Integer.MAX_VALUE); RenderSystem.m_69478_(); } } ``` -------------------------------- ### Initialize VaultPatcher (Java) Source: https://context7.com/3093fengming/vaultpatcher/llms.txt Initializes the VaultPatcher library with the Minecraft path and version. It loads configurations, plugins, patches, and modules, and provides access to platform information, client status, and a logger. Debug information can be logged if debug mode is enabled. ```java import java.nio.file.Path; import java.nio.file.Paths; import org.slf4j.Logger; // Initialize VaultPatcher during mod loader startup Path mcPath = Paths.get("/home/user/.minecraft"); String mcVersion = "1.19.2"; VaultPatcher.init(mcPath, mcVersion); // Access loaded information Platform platform = VaultPatcher.platform; // FABRIC, FORGE, etc. boolean isClient = VaultPatcher.isClient; Logger logger = VaultPatcher.LOGGER; // Debug logging (only prints if debug mode enabled) VaultPatcher.debugInfo("Initialization complete for version: {}", mcVersion); ``` -------------------------------- ### Batch Script: Decompiling Large JAR Files with JDec Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This batch script (`start.cmd`) is used to decompile large JAR files using the Java Decompiler (JDec) tool. It takes the mod JAR file as input and outputs the decompiled code to a specified directory. This is an alternative to Recaf when dealing with very large or complex mods that may cause issues with standard decompilation tools. ```batch java -jar java-decompiler.jar ".\ori\the_vault-1.18.2-3.17.2.3954.jar" .\out ``` -------------------------------- ### Perform Runtime String Pattern Matching in Java Source: https://context7.com/3093fengming/vaultpatcher/llms.txt This Java code demonstrates runtime string matching using the `MatchUtils` class. It initializes a `Pairs` object in dynamic mode and uses it to match an input string against predefined patterns, returning the translated or matched string. ```java // Dynamic mode uses pattern matching Pairs dynamicPairs = new Pairs(true); // true = dynamic mode dynamicPairs.setKey("Player %s joined"); dynamicPairs.setValue("@player.join"); // @ prefix = pattern match // Runtime matching String input = "Player Steve joined the game"; String matched = MatchUtils.matchPairs(dynamicPairs, input, false); // Returns translated pattern-matched string ``` -------------------------------- ### Vault Patcher Module File Structure (the_vault_vp.json) Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This JSON snippet outlines the basic structure for a Vault Patcher module file. It includes metadata like author, name, description, and the associated mod ID, followed by an array for translation entries. ```json ## the_vault_vp.json [ // 模块文件的第一个内容是文件的基本信息,格式如下 { “authors”: “DrIceTea”, // 汉化作者名,不会影响汉化效果,可中文 “name”: “The Vault 硬编码汉化”, // 模块内容命名,不影响汉化效果 “desc”: “宝藏猎人核心模组汉化v1.0-教程版”, // 模块内容描述,不影响汉化效果 “mods”: “the_vault”, // 对应的mod的信息,可随意填写 // 建议使用mod的命名空间(modid) “dynamic”: false, // 是否启用动态替换,一般为false “i18n”: false // 是否启用i18n功能 }, // 这里留出空行,后续编写翻译信息就在此处继续编写 ] // 结尾一定注意补好中括号 ``` -------------------------------- ### Configure String Replacement using LdcNodeHandler JSON Source: https://context7.com/3093fengming/vaultpatcher/llms.txt This JSON configuration defines parameters for the LdcNodeHandler to replace string constants within bytecode. It specifies target classes, method, and a list of key-value pairs for string replacements. ```json { "target_classes": ["com/example/ItemTooltip"], "info": { "method": "getTooltip", "ordinal": 2 // Replace only the 3rd string constant }, "pairs": [ {"key": "Damage: %d", "value": "gui.damage"} ] } ``` -------------------------------- ### Initialize and Utilize Caching System in Java Source: https://context7.com/3093fengming/vaultpatcher/llms.txt This Java code initializes the caching system and demonstrates checking the cache for a class before transforming it. If a valid cache entry exists, it uses the cached version; otherwise, it transforms the class and updates the cache. ```java // Initialize cache system Path cachePath = Utils.getVpPath().resolve("cache"); Caches.init(cachePath); // Check cache before transforming String className = "com/example/MyClass"; ClassCache cache = Caches.getClassCache(className); if (cache != null && !cache.updated(classNode)) { // Use cached version ClassNode cachedNode = cache.take(); Utils.deepCopyClass(classNode, cachedNode); } else { // Transform and update cache transformer.accept(classNode); if (cache != null) { cache.put(classNode, originalBytes); } else { Caches.addClassCache(className, classNode); } } ``` -------------------------------- ### JSON: Module Configuration for Ordinal Testing Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This JSON snippet defines a module configuration file (`the_vault_vp_ordinalTest.json`) used for testing translation overrides and obtaining ordinal values. It specifies target class information, including the method and local variable to be patched, along with key-value pairs for translation. This file is crucial for the debugging process to identify specific translation points. ```json [ { “authors”: “DrIceTea”, “name”: “The Vault 硬编码汉化测试”, “desc”: “宝藏猎人核心模组汉化v1.0-教程版-提取ordinal测试”, “mods”: “the_vault”, “dynamic”: false, “i18n”: false }, { “target_class”: { "name": "iskallia.vault.client.gui.screen.player.legacy.widget.ResearchWidget", "method": "renderHover", "local": "GresearchName" }, “key”: “Backpacks”, “value”: “小背包” } ] ``` -------------------------------- ### JSON: Vault Patcher Main Configuration with Debug Mode Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This JSON snippet shows the main configuration file (`config.json`) for Vault Patcher. It highlights the essential settings for enabling debug mode, which is required for obtaining ordinal values. Key parameters include enabling debug mode, disabling cache, and specifying an `output_format` to clearly display replacement information, including the ordinal. ```json { “mods”: [ “the_vault_vp_ordinalTest” // 我们只使用这一个模块文件 ], “class_patch”: false, “debug_mode”: { “is_enable”: true, // 必须启用调试模式 “use_cache”: false, // 必须不使用缓存 “output_format”: “ -> in [] | ”, // output_format为最重要的获取ordinal的值,建议和我的内容保持一致 ... // 其余内容同前 } } ``` -------------------------------- ### Vault Patcher Core Configuration (config.json) Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This JSON defines the core configuration for the Vault Patcher Mod. It specifies which module files to load, enables or disables class patching, and configures debug mode settings like enabling output, cache usage, and output format. ```json ## config.json { “mods”: [ “the_vault_vp”, // 这里换成你之后创建的模块文件的文件名 “xnet_vp” // 如果有多个想要使用的模块文件,像这样用逗号隔开,每个文件一行 // 强烈建议每个mod只使用一个模块文件;如果有些mod的模块文件巨大无比,可以按固定原则拆分 ], “class_patch”: false, // 反编译汉化不涉及此功能,默认为false “debug_mode”: { “is_enable”: true, // 是否启用调试模式,汉化测试时应设置为true “use_cache”: false, // 是否使用缓存,汉化测试时设为false以节省调试步骤,正式发布应改为true “output_format”: “ -> in [] | ”, // output_format代表调试模式下翻译信息的输出结果,这里示例的是VP生成的默认值 “output_mode”: 0, “hide_pairs”: 7, “output_node_debug”: false, “export_class”: false, “missing_warn”: true } } ``` -------------------------------- ### JSON Configuration for DungeonDoorTileEntity Localization Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This JSON snippet configures localization for the 'DungeonDoorTileEntity' class in the game. It specifies the target class and method for translation, mapping English keys to Chinese values. It's used to modify in-game text related to difficulty settings. ```json { "target_class": { "name": "iskallia.vault.block.entity.DungeonDoorTileEntity$Difficulty", "method": "getDisplay" }, "key": "Difficulty: %s", "value": "难度:%s" } ``` -------------------------------- ### Configure Dynamic String Matching Module in JSON Source: https://context7.com/3093fengming/vaultpatcher/llms.txt This JSON configuration enables dynamic string matching for a module, allowing for flexible runtime replacements based on patterns. It specifies target classes and pairs of keys (patterns) to values (replacement keys or patterns). ```json { "name": "Dynamic Module", "dynamic": true, "i18n": false } { "target_classes": ["com/example/Messages"], "pairs": [ {"key": "Player %s joined", "value": "@player.join"}, {"key": "Error: @", "value": "@error.prefix"} ] } ``` -------------------------------- ### Create and Access Translation Pairs (Java) Source: https://context7.com/3093fengming/vaultpatcher/llms.txt Programmatically creates and manages translation pairs for VaultPatcher modules. This Java code demonstrates how to instantiate a `Pairs` object, set key-value mappings for string replacement, and retrieve the translation map or specific translated values. ```java import java.util.HashMap; // Load module from JSON file VaultPatcherModule module = new VaultPatcherModule("example.json"); module.read(); // Programmatically create Pairs Pairs pairs = new Pairs(false); // false = static mode pairs.setKey("Original Text"); pairs.setValue("Translated Text"); pairs.setKey("Another Text"); pairs.setValue("Another Translation"); // Access pairs HashMap map = pairs.getMap(); String translated = pairs.getValue("Original Text"); // "Translated Text" ``` -------------------------------- ### JSON Configuration for Target Classes and Translations Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This JSON structure defines target classes and their methods for patching, alongside key-value pairs for text translations. The 'target_classes' array specifies which parts of the code to hook into, while the 'pairs' array provides original text ('key') and its translated version ('value'). This format is used for localizing game content. ```json { "target_classes": [ { "name": "iskallia.vault.client.gui.helper.FontHelper", "method": "drawStringWithBorder", "local": "Vtext" }, { "name": "iskallia.vault.client.gui.screen.player.legacy.widget.ResearchWidget", "method": "renderHover", "local": "GresearchName", "ordinal": 24 }, { "name": "iskallia.vault.client.gui.screen.player.legacy.widget.ResearchWidget", "method": "lambda$renderHover$1", "local": "MgetName" }, { "name": "iskallia.vault.research.StageManager" }, { "name": "iskallia.vault.item.KnowledgeBrewItem", "local": "Vresearch" } ], "pairs": [ { "key": "Backpacks", "value": "小背包" }, { "key": "Big Backpacks", "value": "大背包" } ] } ``` -------------------------------- ### JSON: Mapping Lambda Return Value in ResearchWidget Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This JSON snippet demonstrates how to map the return value of the `getName` method called within a lambda expression in the `renderHover` method of `ResearchWidget`. The `local` field with the prefix 'M' is used to denote a method's return value within the current class context. ```json { "name": "iskallia.vault.client.gui.screen.player.legacy.widget.ResearchWidget", "method": "lambda$renderHover$1", "local": "MgetName" } ``` -------------------------------- ### JSON: Main Configuration with Debug Mode Disabled Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This JSON snippet shows the main configuration file (`config.json`) after the debugging process is complete. Debug mode is now disabled (`"is_enable": false`), and cache is enabled (`"use_cache": true`) for improved performance during subsequent game launches. This configuration is used for the final release of the hardcoded localization. ```json { ... “debug_mode”: { “is_enable”: false, // 不启用调试模式 “use_cache”: true, // 启用VP缓存,可以加快第2次及之后的游戏启动速度 ... } ... } ``` -------------------------------- ### JSON: Final Module Configuration with Ordinal Value Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This JSON snippet represents the finalized module configuration file (`the_vault_vp.json`) after obtaining the correct ordinal value. The `ordinal` parameter is now set to `24`, ensuring that the translation override for 'Backpacks' is applied specifically to the first instance of `GresearchName` in the `renderHover` method, as identified in the log. ```json { “target_class”: { “name”: “iskallia.vault.client.gui.screen.player.legacy.widget.ResearchWidget”, “method”: “renderHover”, “local": “GresearchName”, “ordinal”: 24 // 注意ordinal直接为Integer格式,因此不需要引号 }, “pairs”: [ { “key”: “Backpacks”, “value”: “小背包” }, ... // 其他键值对 ] }, ... ``` -------------------------------- ### Configure Internationalization Module for Localization in JSON Source: https://context7.com/3093fengming/vaultpatcher/llms.txt This JSON configuration sets up a module for internationalization (i18n), enabling the linking of hardcoded text replacements to Minecraft's language files for proper localization. It includes a flag for i18n and pairs of hardcoded text to translation keys. ```json { "name": "I18n Module", "i18n": true } { "pairs": [ {"key": "Hardcoded Text", "value": "mod.translation.key"} ] } ``` -------------------------------- ### Initialize and Apply Class Patches in Java Source: https://context7.com/3093fengming/vaultpatcher/llms.txt This snippet demonstrates how to initialize the ClassPatcher with a specified patch directory and apply patches to original class bytes. It checks if a patched version exists and returns the transformed bytecode. ```java // Initialize class patcher Path patchPath = Utils.getVpPath().resolve("patch"); ClassPatcher.init(patchPath); // Place .class files in: .minecraft/vaultpatcher_asm/patch/com/example/MyClass.class // Check for patch and apply ClassNode originalClass = new ClassNode(); ClassReader reader = new ClassReader(originalBytes); reader.accept(originalClass, 0); ClassNode patched = ClassPatcher.patch(originalClass); if (patched != originalClass) { // Class was patched, use patched version ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); patched.accept(writer); return writer.toByteArray(); } ``` -------------------------------- ### JSON: Mapping Local Variable 'tTipRequirement' in ResearchWidget Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This JSON snippet illustrates mapping the local variable `tTipRequirement` within the `renderHover` method of `ResearchWidget`. The `local` field with the prefix 'V' targets a local variable, enabling its value to be referenced and potentially modified. ```json { "target_class": { "name": "iskallia.vault.client.gui.screen.player.legacy.widget.ResearchWidget", "method": "renderHover", "local": "VtTipRequirement" }, "key": " any of", "value": "任意" } ``` -------------------------------- ### Manage VaultPatcher Configuration (Java) Source: https://context7.com/3093fengming/vaultpatcher/llms.txt Manages VaultPatcher's configuration, reading it from a standard config file and allowing programmatic access and modification of values such as target mods, classes, default language, and class patching enablement. Changes can be saved back to the configuration file. ```java import java.nio.file.Path; import java.util.List; // Read configuration from standard config directory Path configPath = mcPath.resolve("config").resolve("vaultpatcher_asm"); VaultPatcherConfig.readConfig(configPath); // Access configuration values List mods = VaultPatcherConfig.getMods(); // ["example_mod"] List classes = VaultPatcherConfig.getClasses(); // ["com.example.MyClass"] List applyMods = VaultPatcherConfig.getApplyMods(); // ["target_mod"] String defaultLanguage = VaultPatcherConfig.getDefaultLanguage(); // "en_us" boolean enableClassPatch = VaultPatcherConfig.isEnableClassPatch(); // true DebugMode debug = VaultPatcherConfig.getDebugMode(); // Modify and save configuration VaultPatcherConfig.mods.add("new_module"); VaultPatcherConfig.enableClassPatch = true; VaultPatcherConfig.save(); ``` -------------------------------- ### Load and Retrieve Localized Text in Java Source: https://context7.com/3093fengming/vaultpatcher/llms.txt This Java code snippet shows how to load Minecraft's language files using the `I18n` class and retrieve localized text based on a translation key. The `getValue` method returns the appropriate translated string according to the game's language settings. ```java // Load language files Path mcPath = Paths.get(".minecraft"); I18n.load(mcPath); // Values are resolved from language files String translationKey = "mod.translation.key"; String localized = I18n.getValue(translationKey); // Returns actual translated text based on game language setting ``` -------------------------------- ### Transform Java Classes with VaultPatcher (Java) Source: https://context7.com/3093fengming/vaultpatcher/llms.txt Applies VaultPatcher's bytecode transformation to Java classes. This involves setting up a `VPClassTransformer` with `TranslationInfo` and then using ASM's `ClassReader` and `ClassWriter` to read, transform, and write the modified class bytecode. ```java import java.util.HashSet; import java.util.Set; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.tree.ClassNode; // Setup transformer with translation info Set infos = new HashSet<>(); TranslationInfo.Mutable mutable = new TranslationInfo.Mutable("com/example/MyClass"); mutable.setPairs(pairs); mutable.setTargetClassInfo(targetClassInfo); infos.add(mutable.toImmutable()); VPClassTransformer transformer = new VPClassTransformer(infos); // Apply transformation to a ClassNode ClassNode classNode = new ClassNode(); ClassReader reader = new ClassReader(classBytes); reader.accept(classNode, 0); transformer.accept(classNode); // Transforms the class // Export transformed bytecode ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); classNode.accept(writer); byte[] transformedBytes = writer.toByteArray(); ``` -------------------------------- ### Java: Conditional Variable Access in ResearchWidget Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This Java snippet demonstrates the `renderHover` method in `ResearchWidget.java`. It shows how the global variable `researchName` is accessed multiple times, with some accesses intended for display and others for logical operations. The challenge is to selectively override `researchName` for display without affecting its use in subsequent logic. ```java private final String researchName; // 这是一个String类型的全局变量 ... private void renderHover(PoseStack matrixStack, int mouseX, int mouseY, float partialTicks) { if (this.m_5953_((double)mouseX, (double)mouseY)) { List tTip = new ArrayList(); tTip.add(FormattedCharSequence.m_13714_(this.researchName, Style.f_131099_)); // 这里调用了全局变量researchName List conflicts; if (this.locked) { conflicts = ModConfigs.SKILL_GATES.getGates().getDependencyResearches(this.researchName); // 这里也调用了全局变量researchName ... } conflicts = ModConfigs.SKILL_GATES.getGates().getLockedByResearches(this.researchName); // 这里也调用了全局变量researchName ... } } ``` -------------------------------- ### Define Translation Modules (JSON) Source: https://context7.com/3093fengming/vaultpatcher/llms.txt Defines translation modules for VaultPatcher. This JSON structure specifies module metadata like name, authors, and target mods. It also includes a 'pairs' section for direct string replacement, mapping original keys to translation values, and can target specific classes and methods for transformation. ```json [ { "name": "Example Module", "authors": ["FengMing"], "mods": ["example_mod"], "dynamic": false, "i18n": true }, { "target_classes": ["com/example/MyClass"], "info": { "method": "getMessage", "ordinal": 0, "local": "" }, "pairs": [ {"key": "Hello World", "value": "translation.hello"}, {"key": "Error: File not found", "value": "translation.error.file"} ] } ] ``` -------------------------------- ### Vault Patcher Translation Entry Structure (JSON) Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This JSON structure defines a single translation entry for Vault Patcher. It specifies the target class and method where the text is located, and a list of key-value pairs for original and translated text. ```json { “target_class”: { “name”: “iskallia.vault.gear.VaultGearRarity”, “method”: “getDisplayName”, “local”: “Mcapitalize”, “ordinal”: 21 }, “pairs”: [ { “key”: “Scrappy”, “value”: “破烂” }, { “key”: “Common”, “value”: “普通” }, { “key”: “Rare”, “value”: “稀有” } ] } ``` -------------------------------- ### JSON: Mapping Global Variable 'researchName' in ResearchWidget Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_zbc This JSON snippet shows how to map the global variable `researchName` within the `renderHover` method of `ResearchWidget`. The `local` field with the prefix 'G' is used to specify a global (instance) variable. ```json { "name": "iskallia.vault.client.gui.screen.player.legacy.widget.ResearchWidget", "method": "renderHover", "local": "GresearchName" } ``` -------------------------------- ### Enable Class Patching in config.json Source: https://github.com/3093fengming/vaultpatcher/wiki/zh_cn_patch This JSON configuration snippet shows how to enable the class patching feature by setting the 'class_patch' attribute to true in the config.json file. This setting is crucial for the vaultpatcher to apply bytecode modifications to mods. ```json { "mods": [ "example" ], "debug_mode": { "is_enable": true, "use_cache": false, "export_class": false, "output_format": " -> in [] | ", "output_mode": 0 }, "class_patch": true } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.