| 1 | package net.minecraft.nbt;
|
| 2 |
|
| 3 | import com.google.common.annotations.VisibleForTesting;
|
| 4 | import com.google.common.base.Splitter;
|
| 5 | import com.google.common.collect.Comparators;
|
| 6 | import com.google.common.collect.ImmutableMap;
|
| 7 | import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
| 8 | import com.mojang.logging.LogUtils;
|
| 9 | import com.mojang.serialization.Codec;
|
| 10 | import com.mojang.serialization.Dynamic;
|
| 11 | import it.unimi.dsi.fastutil.objects.Object2IntMap;
|
| 12 | import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
|
| 13 | import java.util.Comparator;
|
| 14 | import java.util.List;
|
| 15 | import java.util.Map;
|
| 16 | import java.util.Optional;
|
| 17 | import java.util.Map.Entry;
|
| 18 | import java.util.function.Function;
|
| 19 | import java.util.stream.Collectors;
|
| 20 | import net.minecraft.SharedConstants;
|
| 21 | import net.minecraft.core.Holder;
|
| 22 | import net.minecraft.core.HolderGetter;
|
| 23 | import net.minecraft.core.registries.BuiltInRegistries;
|
| 24 | import net.minecraft.core.registries.Registries;
|
| 25 | import net.minecraft.network.chat.Component;
|
| 26 | import net.minecraft.resources.ResourceKey;
|
| 27 | import net.minecraft.world.level.block.Block;
|
| 28 | import net.minecraft.world.level.block.Blocks;
|
| 29 | import net.minecraft.world.level.block.state.BlockState;
|
| 30 | import net.minecraft.world.level.block.state.StateDefinition;
|
| 31 | import net.minecraft.world.level.block.state.StateHolder;
|
| 32 | import net.minecraft.world.level.block.state.properties.Property;
|
| 33 | import net.minecraft.world.level.storage.ValueOutput;
|
| 34 | import org.jspecify.annotations.Nullable;
|
| 35 | import org.slf4j.Logger;
|
| 36 |
|
| 37 | public final class NbtUtils {
|
| 38 | private static final Comparator<ListTag> YXZ_LISTTAG_INT_COMPARATOR = Comparator.<ListTag>comparingInt(list -> list.getIntOr(1, 0))
|
| 39 | .thenComparingInt(list -> list.getIntOr(0, 0))
|
| 40 | .thenComparingInt(list -> list.getIntOr(2, 0));
|
| 41 | private static final Comparator<ListTag> YXZ_LISTTAG_DOUBLE_COMPARATOR = Comparator.<ListTag>comparingDouble(list -> list.getDoubleOr(1, 0.0))
|
| 42 | .thenComparingDouble(list -> list.getDoubleOr(0, 0.0))
|
| 43 | .thenComparingDouble(list -> list.getDoubleOr(2, 0.0));
|
| 44 | private static final Codec<ResourceKey<Block>> BLOCK_NAME_CODEC = ResourceKey.codec(Registries.BLOCK);
|
| 45 | public static final String SNBT_DATA_TAG = "data";
|
| 46 | private static final char PROPERTIES_START = '{';
|
| 47 | private static final char PROPERTIES_END = '}';
|
| 48 | private static final String ELEMENT_SEPARATOR = ",";
|
| 49 | private static final char KEY_VALUE_SEPARATOR = ':';
|
| 50 | private static final Splitter COMMA_SPLITTER = Splitter.on(",");
|
| 51 | private static final Splitter COLON_SPLITTER = Splitter.on(':').limit(2);
|
| 52 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 53 | private static final int NOT_FOUND = -1;
|
| 54 | private static final int BLOCK_STATE_ID_PROPERTIES_RENAME_VERSION = 5006;
|
| 55 | public static final String LEGACY_BLOCK_STATE_ID_TAG = "Name";
|
| 56 | public static final String LEGACY_BLOCKSTATE_PROPERTY_TAG = "Properties";
|
| 57 |
|
| 58 | private NbtUtils() {
|
| 59 | }
|
| 60 |
|
| 61 | @VisibleForTesting
|
| 62 | public static boolean compareNbt(final @Nullable Tag expected, final @Nullable Tag actual, final boolean partialListMatches) {
|
| 63 | if (expected == actual) {
|
| 64 | return true;
|
| 65 | }
|
| 66 |
|
| 67 | if (expected == null) {
|
| 68 | return true;
|
| 69 | }
|
| 70 |
|
| 71 | if (actual == null) {
|
| 72 | return false;
|
| 73 | }
|
| 74 |
|
| 75 | if (!expected.getClass().equals(actual.getClass())) {
|
| 76 | return false;
|
| 77 | }
|
| 78 |
|
| 79 | if (expected instanceof CompoundTag expectedCompound) {
|
| 80 | CompoundTag actualCompound = (CompoundTag)actual;
|
| 81 | if (actualCompound.size() < expectedCompound.size()) {
|
| 82 | return false;
|
| 83 | }
|
| 84 |
|
| 85 | for (Entry<String, Tag> entry : expectedCompound.entrySet()) {
|
| 86 | Tag tag = entry.getValue();
|
| 87 | if (!compareNbt(tag, actualCompound.get(entry.getKey()), partialListMatches)) {
|
| 88 | return false;
|
| 89 | }
|
| 90 | }
|
| 91 |
|
| 92 | return true;
|
| 93 | } else if (expected instanceof ListTag expectedList && partialListMatches) {
|
| 94 | ListTag actualList = (ListTag)actual;
|
| 95 | if (expectedList.isEmpty()) {
|
| 96 | return actualList.isEmpty();
|
| 97 | }
|
| 98 |
|
| 99 | if (actualList.size() < expectedList.size()) {
|
| 100 | return false;
|
| 101 | }
|
| 102 |
|
| 103 | for (Tag tag : expectedList) {
|
| 104 | boolean found = false;
|
| 105 |
|
| 106 | for (Tag value : actualList) {
|
| 107 | if (compareNbt(tag, value, partialListMatches)) {
|
| 108 | found = true;
|
| 109 | break;
|
| 110 | }
|
| 111 | }
|
| 112 |
|
| 113 | if (!found) {
|
| 114 | return false;
|
| 115 | }
|
| 116 | }
|
| 117 |
|
| 118 | return true;
|
| 119 | } else {
|
| 120 | return expected.equals(actual);
|
| 121 | }
|
| 122 | }
|
| 123 |
|
| 124 | public static BlockState readBlockState(final HolderGetter<Block> blocks, final CompoundTag tag) {
|
| 125 | Optional<? extends Holder<Block>> blockHolder = tag.read("id", BLOCK_NAME_CODEC).flatMap(blocks::get);
|
| 126 | if (blockHolder.isEmpty()) {
|
| 127 | return Blocks.AIR.defaultBlockState();
|
| 128 | }
|
| 129 |
|
| 130 | Block block = blockHolder.get().value();
|
| 131 | BlockState result = block.defaultBlockState();
|
| 132 | Optional<CompoundTag> properties = tag.getCompound("properties");
|
| 133 | if (properties.isPresent()) {
|
| 134 | StateDefinition<Block, BlockState> definition = block.getStateDefinition();
|
| 135 |
|
| 136 | for (String key : properties.get().keySet()) {
|
| 137 | Property<?> property = definition.getProperty(key);
|
| 138 | if (property != null) {
|
| 139 | result = setValueHelper(result, property, key, properties.get(), tag);
|
| 140 | }
|
| 141 | }
|
| 142 | }
|
| 143 |
|
| 144 | return result;
|
| 145 | }
|
| 146 |
|
| 147 | private static <S extends StateHolder<?, S>, T extends Comparable<T>> S setValueHelper(
|
| 148 | final S result, final Property<T> property, final String key, final CompoundTag properties, final CompoundTag tag
|
| 149 | ) {
|
| 150 | Optional<T> value = properties.getString(key).flatMap(property::getValue);
|
| 151 | if (value.isPresent()) {
|
| 152 | return result.setValue(property, value.get());
|
| 153 | }
|
| 154 |
|
| 155 | LOGGER.warn("Unable to read property: {} with value: {} for blockstate: {}", key, properties.get(key), tag);
|
| 156 | return result;
|
| 157 | }
|
| 158 |
|
| 159 | private static void writeStateProperties(final StateHolder<?, ?> state, final CompoundTag tag) {
|
| 160 | if (!state.isSingletonState()) {
|
| 161 | CompoundTag properties = new CompoundTag();
|
| 162 | state.getValues().forEach(value -> properties.putString(value.property().getName(), value.valueName()));
|
| 163 | tag.put("properties", properties);
|
| 164 | }
|
| 165 | }
|
| 166 |
|
| 167 | public static CompoundTag writeBlockState(final BlockState state) {
|
| 168 | CompoundTag tag = new CompoundTag();
|
| 169 | tag.putString("id", BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString());
|
| 170 | writeStateProperties(state, tag);
|
| 171 | return tag;
|
| 172 | }
|
| 173 |
|
| 174 | public static Component toPrettyComponent(final Tag tag) {
|
| 175 | return new TextComponentTagVisitor("").visit(tag);
|
| 176 | }
|
| 177 |
|
| 178 | public static String structureToSnbt(final CompoundTag structure) {
|
| 179 | return new SnbtPrinterTagVisitor().visit(packStructureTemplate(structure));
|
| 180 | }
|
| 181 |
|
| 182 | public static CompoundTag snbtToStructure(final String snbt) throws CommandSyntaxException {
|
| 183 | return unpackStructureTemplate(TagParser.parseCompoundFully(snbt));
|
| 184 | }
|
| 185 |
|
| 186 | @VisibleForTesting
|
| 187 | static CompoundTag packStructureTemplate(final CompoundTag snbt) {
|
| 188 | int templateVersion = getDataVersion(snbt);
|
| 189 | Optional<ListTag> palettes = snbt.getList("palettes");
|
| 190 | ListTag palette;
|
| 191 | if (palettes.isPresent()) {
|
| 192 | palette = palettes.get().getListOrEmpty(0);
|
| 193 | } else {
|
| 194 | palette = snbt.getListOrEmpty("palette");
|
| 195 | }
|
| 196 |
|
| 197 | ListTag deflatedPalette = palette.compoundStream()
|
| 198 | .map(compound -> packBlockState(compound, templateVersion))
|
| 199 | .map(StringTag::valueOf)
|
| 200 | .collect(Collectors.toCollection(ListTag::new));
|
| 201 | snbt.put("palette", deflatedPalette);
|
| 202 | if (palettes.isPresent()) {
|
| 203 | ListTag newPalettes = new ListTag();
|
| 204 | palettes.get().stream().flatMap(tag -> tag.asList().stream()).forEach(oldPalette -> {
|
| 205 | CompoundTag newPalette = new CompoundTag();
|
| 206 |
|
| 207 | for (int i = 0; i < oldPalette.size(); i++) {
|
| 208 | newPalette.putString(deflatedPalette.getString(i).orElseThrow(), packBlockState(oldPalette.getCompound(i).orElseThrow(), templateVersion));
|
| 209 | }
|
| 210 |
|
| 211 | newPalettes.add(newPalette);
|
| 212 | });
|
| 213 | snbt.put("palettes", newPalettes);
|
| 214 | }
|
| 215 |
|
| 216 | Optional<ListTag> oldEntities = snbt.getList("entities");
|
| 217 | if (oldEntities.isPresent()) {
|
| 218 | ListTag newEntities = oldEntities.get()
|
| 219 | .compoundStream()
|
| 220 | .sorted(Comparator.comparing(tag -> tag.getList("pos"), Comparators.emptiesLast(YXZ_LISTTAG_DOUBLE_COMPARATOR)))
|
| 221 | .collect(Collectors.toCollection(ListTag::new));
|
| 222 | snbt.put("entities", newEntities);
|
| 223 | }
|
| 224 |
|
| 225 | ListTag blockData = snbt.getList("blocks")
|
| 226 | .stream()
|
| 227 | .flatMap(ListTag::compoundStream)
|
| 228 | .sorted(Comparator.comparing(tag -> tag.getList("pos"), Comparators.emptiesLast(YXZ_LISTTAG_INT_COMPARATOR)))
|
| 229 | .peek(block -> block.putString("state", deflatedPalette.getString(block.getIntOr("state", 0)).orElseThrow()))
|
| 230 | .collect(Collectors.toCollection(ListTag::new));
|
| 231 | snbt.put("data", blockData);
|
| 232 | snbt.remove("blocks");
|
| 233 | return snbt;
|
| 234 | }
|
| 235 |
|
| 236 | @VisibleForTesting
|
| 237 | static CompoundTag unpackStructureTemplate(final CompoundTag template) {
|
| 238 | int templateVersion = getDataVersion(template);
|
| 239 | ListTag packedPalette = template.getListOrEmpty("palette");
|
| 240 | Map<String, Tag> palette = packedPalette.stream()
|
| 241 | .flatMap(tag -> tag.asString().stream())
|
| 242 | .collect(ImmutableMap.toImmutableMap(Function.identity(), compound -> unpackBlockState(compound, templateVersion)));
|
| 243 | Optional<ListTag> oldPalettes = template.getList("palettes");
|
| 244 | if (oldPalettes.isPresent()) {
|
| 245 | template.put(
|
| 246 | "palettes",
|
| 247 | oldPalettes.get()
|
| 248 | .compoundStream()
|
| 249 | .map(
|
| 250 | oldPalette -> palette.keySet()
|
| 251 | .stream()
|
| 252 | .map(key -> oldPalette.getString(key).orElseThrow())
|
| 253 | .map(compound -> unpackBlockState(compound, templateVersion))
|
| 254 | .collect(Collectors.toCollection(ListTag::new))
|
| 255 | )
|
| 256 | .collect(Collectors.toCollection(ListTag::new))
|
| 257 | );
|
| 258 | template.remove("palette");
|
| 259 | } else {
|
| 260 | template.put("palette", palette.values().stream().collect(Collectors.toCollection(ListTag::new)));
|
| 261 | }
|
| 262 |
|
| 263 | Optional<ListTag> maybeBlocks = template.getList("data");
|
| 264 | if (maybeBlocks.isPresent()) {
|
| 265 | Object2IntMap<String> paletteToId = new Object2IntOpenHashMap<>();
|
| 266 | paletteToId.defaultReturnValue(-1);
|
| 267 |
|
| 268 | for (int i = 0; i < packedPalette.size(); i++) {
|
| 269 | paletteToId.put(packedPalette.getString(i).orElseThrow(), i);
|
| 270 | }
|
| 271 |
|
| 272 | ListTag blocks = maybeBlocks.get();
|
| 273 |
|
| 274 | for (int i = 0; i < blocks.size(); i++) {
|
| 275 | CompoundTag block = blocks.getCompound(i).orElseThrow();
|
| 276 | String stateName = block.getString("state").orElseThrow();
|
| 277 | int stateId = paletteToId.getInt(stateName);
|
| 278 | if (stateId == -1) {
|
| 279 | throw new IllegalStateException("Entry " + stateName + " missing from palette");
|
| 280 | }
|
| 281 |
|
| 282 | block.putInt("state", stateId);
|
| 283 | }
|
| 284 |
|
| 285 | template.put("blocks", blocks);
|
| 286 | template.remove("data");
|
| 287 | }
|
| 288 |
|
| 289 | return template;
|
| 290 | }
|
| 291 |
|
| 292 | @VisibleForTesting
|
| 293 | static String packBlockState(final CompoundTag compound, final int version) {
|
| 294 | String idTag;
|
| 295 | String propertiesTag;
|
| 296 | if (version >= 5006) {
|
| 297 | idTag = "id";
|
| 298 | propertiesTag = "properties";
|
| 299 | } else {
|
| 300 | idTag = "Name";
|
| 301 | propertiesTag = "Properties";
|
| 302 | }
|
| 303 |
|
| 304 | StringBuilder builder = new StringBuilder(compound.getString(idTag).orElseThrow());
|
| 305 | compound.getCompound(propertiesTag)
|
| 306 | .ifPresent(
|
| 307 | properties -> {
|
| 308 | String keyValues = properties.entrySet()
|
| 309 | .stream()
|
| 310 | .sorted(Entry.comparingByKey())
|
| 311 | .map(entry -> entry.getKey() + ":" + entry.getValue().asString().orElseThrow())
|
| 312 | .collect(Collectors.joining(","));
|
| 313 | builder.append('{').append(keyValues).append('}');
|
| 314 | }
|
| 315 | );
|
| 316 | return builder.toString();
|
| 317 | }
|
| 318 |
|
| 319 | @VisibleForTesting
|
| 320 | static CompoundTag unpackBlockState(final String compound, final int version) {
|
| 321 | CompoundTag tag = new CompoundTag();
|
| 322 | int openIndex = compound.indexOf(123);
|
| 323 | CompoundTag properties = new CompoundTag();
|
| 324 | String name;
|
| 325 | if (openIndex >= 0) {
|
| 326 | name = compound.substring(0, openIndex);
|
| 327 | if (openIndex + 2 <= compound.length()) {
|
| 328 | String values = compound.substring(openIndex + 1, compound.indexOf(125, openIndex));
|
| 329 | COMMA_SPLITTER.split(values).forEach(keyValue -> {
|
| 330 | List<String> parts = COLON_SPLITTER.splitToList(keyValue);
|
| 331 | if (parts.size() == 2) {
|
| 332 | properties.putString(parts.get(0), parts.get(1));
|
| 333 | } else {
|
| 334 | LOGGER.error("Something went wrong parsing: '{}' -- incorrect gamedata!", compound);
|
| 335 | }
|
| 336 | });
|
| 337 | }
|
| 338 | } else {
|
| 339 | name = compound;
|
| 340 | }
|
| 341 |
|
| 342 | if (version >= 5006) {
|
| 343 | tag.putString("id", name);
|
| 344 | if (!properties.isEmpty()) {
|
| 345 | tag.put("properties", properties);
|
| 346 | }
|
| 347 | } else {
|
| 348 | tag.putString("Name", name);
|
| 349 | if (!properties.isEmpty()) {
|
| 350 | tag.put("Properties", properties);
|
| 351 | }
|
| 352 | }
|
| 353 |
|
| 354 | return tag;
|
| 355 | }
|
| 356 |
|
| 357 | public static CompoundTag addCurrentDataVersion(final CompoundTag tag) {
|
| 358 | int version = SharedConstants.getCurrentVersion().dataVersion().version();
|
| 359 | return addDataVersion(tag, version);
|
| 360 | }
|
| 361 |
|
| 362 | public static CompoundTag addDataVersion(final CompoundTag tag, final int version) {
|
| 363 | tag.putInt("DataVersion", version);
|
| 364 | return tag;
|
| 365 | }
|
| 366 |
|
| 367 | public static <T> Dynamic<T> addDataVersion(final Dynamic<T> tag, final int version) {
|
| 368 | return tag.set("DataVersion", tag.createInt(version));
|
| 369 | }
|
| 370 |
|
| 371 | public static void addCurrentDataVersion(final ValueOutput output) {
|
| 372 | int version = SharedConstants.getCurrentVersion().dataVersion().version();
|
| 373 | addDataVersion(output, version);
|
| 374 | }
|
| 375 |
|
| 376 | public static void addDataVersion(final ValueOutput output, final int version) {
|
| 377 | output.putInt("DataVersion", version);
|
| 378 | }
|
| 379 |
|
| 380 | public static int getDataVersion(final CompoundTag tag) {
|
| 381 | return getDataVersion(tag, -1);
|
| 382 | }
|
| 383 |
|
| 384 | public static int getDataVersion(final CompoundTag tag, final int _default) {
|
| 385 | return tag.getIntOr("DataVersion", _default);
|
| 386 | }
|
| 387 |
|
| 388 | public static int getDataVersion(final Dynamic<?> dynamic) {
|
| 389 | return getDataVersion(dynamic, -1);
|
| 390 | }
|
| 391 |
|
| 392 | public static int getDataVersion(final Dynamic<?> dynamic, final int _default) {
|
| 393 | return dynamic.get("DataVersion").asInt(_default);
|
| 394 | }
|
| 395 | }
|
| 396 |
|