001/* 002 * This file is part of Baritone. 003 * 004 * Baritone is free software: you can redistribute it and/or modify 005 * it under the terms of the GNU Lesser General Public License as published by 006 * the Free Software Foundation, either version 3 of the License, or 007 * (at your option) any later version. 008 * 009 * Baritone is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 012 * GNU Lesser General Public License for more details. 013 * 014 * You should have received a copy of the GNU Lesser General Public License 015 * along with Baritone. If not, see <https://www.gnu.org/licenses/>. 016 */ 017 018package baritone.api.utils; 019 020import net.minecraft.block.Block; 021import net.minecraft.util.ResourceLocation; 022 023import java.util.HashMap; 024import java.util.Map; 025 026public class BlockUtils { 027 028 private static transient Map<String, Block> resourceCache = new HashMap<>(); 029 030 public static String blockToString(Block block) { 031 ResourceLocation loc = Block.REGISTRY.getNameForObject(block); 032 String name = loc.getPath(); // normally, only write the part after the minecraft: 033 if (!loc.getNamespace().equals("minecraft")) { 034 // Baritone is running on top of forge with mods installed, perhaps? 035 name = loc.toString(); // include the namespace with the colon 036 } 037 return name; 038 } 039 040 public static Block stringToBlockRequired(String name) { 041 Block block = stringToBlockNullable(name); 042 043 if (block == null) { 044 throw new IllegalArgumentException(String.format("Invalid block name %s", name)); 045 } 046 047 return block; 048 } 049 050 public static Block stringToBlockNullable(String name) { 051 // do NOT just replace this with a computeWithAbsent, it isn't thread safe 052 Block block = resourceCache.get(name); // map is never mutated in place so this is safe 053 if (block != null) { 054 return block; 055 } 056 if (resourceCache.containsKey(name)) { 057 return null; // cached as null 058 } 059 block = Block.getBlockFromName(name.contains(":") ? name : "minecraft:" + name); 060 Map<String, Block> copy = new HashMap<>(resourceCache); // read only copy is safe, wont throw concurrentmodification 061 copy.put(name, block); 062 resourceCache = copy; 063 return block; 064 } 065 066 private BlockUtils() {} 067}