Added BiomeMask.java and updated minor parts of miscellaneous files

Dieser Commit ist enthalten in:
MattBDev 2020-08-24 22:04:56 -04:00
Ursprung 02886b0387
Commit a9d37fc6e5
45 geänderte Dateien mit 595 neuen und 187 gelöschten Zeilen

Datei anzeigen

@ -19,12 +19,17 @@
package com.sk89q.worldedit; package com.sk89q.worldedit;
import com.sk89q.worldedit.extension.input.DisallowedUsageException;
/** /**
* Thrown when a disallowed item is used. * Thrown when a disallowed item is used.
*
* @deprecated Use {@link DisallowedUsageException}
*/ */
@Deprecated
public class DisallowedItemException extends WorldEditException { public class DisallowedItemException extends WorldEditException {
private String type; private final String type;
public DisallowedItemException(String type) { public DisallowedItemException(String type) {
this.type = type; this.type = type;

Datei anzeigen

@ -22,6 +22,7 @@ package com.sk89q.worldedit;
/** /**
* Thrown when an invalid item is specified. * Thrown when an invalid item is specified.
*/ */
@Deprecated
public class InvalidItemException extends DisallowedItemException { public class InvalidItemException extends DisallowedItemException {
public InvalidItemException(String type, String message) { public InvalidItemException(String type, String message) {

Datei anzeigen

@ -19,9 +19,14 @@
package com.sk89q.worldedit; package com.sk89q.worldedit;
import com.sk89q.worldedit.util.formatting.text.TranslatableComponent;
/** /**
* Raised when a world is missing but is required. * Raised when a world is missing but is required.
*/ */
public class MissingWorldException extends WorldEditException { public class MissingWorldException extends WorldEditException {
public MissingWorldException() {
super(TranslatableComponent.of("worldedit.error.missing-world"));
}
} }

Datei anzeigen

@ -19,6 +19,10 @@
package com.sk89q.worldedit; package com.sk89q.worldedit;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.TranslatableComponent;
import com.sk89q.worldedit.world.item.ItemType;
/** /**
* Raised when an item is used when a block was expected. * Raised when an item is used when a block was expected.
*/ */
@ -28,7 +32,7 @@ public class NotABlockException extends WorldEditException {
* Create a new instance. * Create a new instance.
*/ */
public NotABlockException() { public NotABlockException() {
super("This item is not a block."); super(TranslatableComponent.of("worldedit.error.not-a-block"));
} }
/** /**
@ -36,8 +40,9 @@ public class NotABlockException extends WorldEditException {
* *
* @param input the input that was used * @param input the input that was used
*/ */
@Deprecated
public NotABlockException(String input) { public NotABlockException(String input) {
super("The item '" + input + "' is not a block."); super(TranslatableComponent.of("worldedit.error.not-a-block.item", TextComponent.of(input)));
} }
/** /**
@ -45,8 +50,17 @@ public class NotABlockException extends WorldEditException {
* *
* @param input the input that was used * @param input the input that was used
*/ */
@Deprecated
public NotABlockException(int input) { public NotABlockException(int input) {
super("The item with the ID " + input + " is not a block."); super(TranslatableComponent.of("worldedit.error.not-a-block.item", TextComponent.of(input)));
} }
/**
* Create a new instance.
*
* @param input the input that was used
*/
public NotABlockException(ItemType input) {
super(TranslatableComponent.of("worldedit.error.not-a-block.item", input.getRichName()));
}
} }

Datei anzeigen

@ -19,12 +19,15 @@
package com.sk89q.worldedit; package com.sk89q.worldedit;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.TranslatableComponent;
/** /**
* Thrown when an unknown direction is specified or detected. * Thrown when an unknown direction is specified or detected.
*/ */
public class UnknownDirectionException extends WorldEditException { public class UnknownDirectionException extends WorldEditException {
private String dir; private final String dir;
/** /**
* Create a new instance. * Create a new instance.
@ -32,7 +35,7 @@ public class UnknownDirectionException extends WorldEditException {
* @param dir the input that was tried * @param dir the input that was tried
*/ */
public UnknownDirectionException(String dir) { public UnknownDirectionException(String dir) {
super("Unknown direction: " + dir); super(TranslatableComponent.of("worldedit.error.unknown-direction", TextComponent.of(dir)));
this.dir = dir; this.dir = dir;
} }

Datei anzeigen

@ -22,9 +22,10 @@ package com.sk89q.worldedit;
/** /**
* Thrown when no item exist by the ID. * Thrown when no item exist by the ID.
*/ */
@Deprecated
public class UnknownItemException extends WorldEditException { public class UnknownItemException extends WorldEditException {
private String type; private final String type;
/** /**
* Create a new instance. * Create a new instance.

Datei anzeigen

@ -23,11 +23,13 @@ import com.google.common.base.Splitter;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.command.util.SuggestionHelper; import com.sk89q.worldedit.command.util.SuggestionHelper;
import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.NoMatchException;
import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.function.mask.BiomeMask2D; import com.sk89q.worldedit.function.mask.BiomeMask;
import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.mask.Masks;
import com.sk89q.worldedit.internal.registry.InputParser; import com.sk89q.worldedit.internal.registry.InputParser;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.TranslatableComponent;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import java.util.Arrays; import java.util.Arrays;
@ -72,11 +74,11 @@ public class BiomeMaskParser extends InputParser<Mask> {
for (String biomeName : Splitter.on(",").split(input.substring(1))) { for (String biomeName : Splitter.on(",").split(input.substring(1))) {
BiomeType biome = BiomeType.REGISTRY.get(biomeName); BiomeType biome = BiomeType.REGISTRY.get(biomeName);
if (biome == null) { if (biome == null) {
throw new InputParseException("Unknown biome '" + biomeName + '\''); throw new NoMatchException(TranslatableComponent.of("worldedit.error.unknown-biome", TextComponent.of(biomeName)));
} }
biomes.add(biome); biomes.add(biome);
} }
return Masks.asMask(new BiomeMask2D(context.requireExtent(), biomes)); return new BiomeMask(context.requireExtent(), biomes);
} }
} }

Datei anzeigen

@ -24,7 +24,6 @@ import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operation;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.Location;
@ -83,7 +82,7 @@ public class NullExtent implements Extent {
} }
@Override @Override
public BiomeType getBiome(BlockVector2 position) { public BiomeType getBiome(BlockVector3 position) {
return BiomeTypes.THE_VOID; return BiomeTypes.THE_VOID;
} }
@ -104,7 +103,7 @@ public class NullExtent implements Extent {
} }
@Override @Override
public boolean setBiome(BlockVector2 position, BiomeType biome) { public boolean setBiome(BlockVector3 position, BiomeType biome) {
return false; return false;
} }

Datei anzeigen

@ -26,7 +26,6 @@ import com.sk89q.worldedit.internal.util.DeprecationUtil;
import com.sk89q.worldedit.internal.util.NonAbstractForCompatibility; import com.sk89q.worldedit.internal.util.NonAbstractForCompatibility;
import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.MutableBlockVector2;
import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.math.MutableBlockVector3;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockStateHolder;
@ -89,7 +88,7 @@ public interface OutputExtent {
default boolean setBiome(int x, int y, int z, BiomeType biome) { default boolean setBiome(int x, int y, int z, BiomeType biome) {
DeprecationUtil.checkDelegatingOverride(getClass()); DeprecationUtil.checkDelegatingOverride(getClass());
return setBiome(MutableBlockVector2.get(x, z), biome); return setBiome(MutableBlockVector3.get(x, y, z), biome);
} }
/** /**

Datei anzeigen

@ -36,9 +36,10 @@ import com.sk89q.worldedit.util.Direction.Flag;
import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.entity.EntityTypes; import com.sk89q.worldedit.world.entity.EntityTypes;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.UUID; import java.util.UUID;
import static com.google.common.base.Preconditions.checkNotNull;
/** /**
* Copies entities provided to the function to the provided destination * Copies entities provided to the function to the provided destination
* {@code Extent}. * {@code Extent}.
@ -133,9 +134,9 @@ public class ExtentEntityCopy implements EntityFunction {
} }
Vector3 newDirection; Vector3 newDirection;
newDirection = transform.isIdentity() ? newDirection = transform.isIdentity()
entity.getLocation().getDirection() ? entity.getLocation().getDirection()
: transform.apply(location.getDirection()).subtract(transform.apply(Vector3.ZERO)).normalize(); : transform.apply(location.getDirection()).subtract(transform.apply(Vector3.ZERO)).normalize();
newLocation = new Location(destination, newPosition.add(to.round().add(0.5, 0.5, 0.5)), newDirection); newLocation = new Location(destination, newPosition.add(to.round().add(0.5, 0.5, 0.5)), newDirection);
// Some entities store their position data in NBT // Some entities store their position data in NBT
@ -148,7 +149,7 @@ public class ExtentEntityCopy implements EntityFunction {
UUID uuid = null; UUID uuid = null;
if (tag.containsKey("UUID")) { if (tag.containsKey("UUID")) {
int[] arr = tag.getIntArray("UUID"); int[] arr = tag.getIntArray("UUID");
uuid = new UUID((long)arr[0] << 32 | (arr[1] & 0xFFFFFFFFL), (long)arr[2] << 32 | (arr[3] & 0xFFFFFFFFL)); uuid = new UUID((long) arr[0] << 32 | (arr[1] & 0xFFFFFFFFL), (long) arr[2] << 32 | (arr[3] & 0xFFFFFFFFL));
} else if (tag.containsKey("UUIDMost")) { } else if (tag.containsKey("UUIDMost")) {
uuid = new UUID(tag.getLong("UUIDMost"), tag.getLong("UUIDLeast")); uuid = new UUID(tag.getLong("UUIDMost"), tag.getLong("UUIDLeast"));
} else if (tag.containsKey("PersistentIDMSB")) { } else if (tag.containsKey("PersistentIDMSB")) {

Datei anzeigen

@ -47,7 +47,7 @@ public class Deform implements Contextual<Operation> {
private Extent destination; private Extent destination;
private Region region; private Region region;
private String expression; private String expression;
private Mode mode = Mode.UNIT_CUBE; private Mode mode;
private Vector3 offset = Vector3.ZERO; private Vector3 offset = Vector3.ZERO;
public Deform(String expression) { public Deform(String expression) {
@ -65,8 +65,8 @@ public class Deform implements Contextual<Operation> {
public Deform(Extent destination, Region region, String expression, Mode mode) { public Deform(Extent destination, Region region, String expression, Mode mode) {
checkNotNull(destination, "destination"); checkNotNull(destination, "destination");
checkNotNull(region, "region"); checkNotNull(region, "region");
checkNotNull(expression, "expression");
checkNotNull(mode, "mode"); checkNotNull(mode, "mode");
checkNotNull(expression, "expression");
this.destination = destination; this.destination = destination;
this.region = region; this.region = region;
this.expression = expression; this.expression = expression;
@ -138,9 +138,15 @@ public class Deform implements Contextual<Operation> {
zero = max.add(min).multiply(0.5); zero = max.add(min).multiply(0.5);
unit = max.subtract(zero); unit = max.subtract(zero);
if (unit.getX() == 0) unit = unit.withX(1.0); if (unit.getX() == 0) {
if (unit.getY() == 0) unit = unit.withY(1.0); unit = unit.withX(1.0);
if (unit.getZ() == 0) unit = unit.withZ(1.0); }
if (unit.getY() == 0) {
unit = unit.withY(1.0);
}
if (unit.getZ() == 0) {
unit = unit.withZ(1.0);
}
break; break;
case RAW_COORD: case RAW_COORD:
zero = Vector3.ZERO; zero = Vector3.ZERO;

Datei anzeigen

@ -0,0 +1,105 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.function.mask;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.biome.BiomeType;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Tests true if the biome at applied points is the same as the one given.
*/
public class BiomeMask extends AbstractMask {
private final Extent extent;
private final Set<BiomeType> biomes = new HashSet<>();
/**
* Create a new biome mask.
*
* @param extent the extent
* @param biomes a list of biomes to match
*/
public BiomeMask(Extent extent, Collection<BiomeType> biomes) {
checkNotNull(extent);
checkNotNull(biomes);
this.extent = extent;
this.biomes.addAll(biomes);
}
/**
* Create a new biome mask.
*
* @param extent the extent
* @param biome an array of biomes to match
*/
public BiomeMask(Extent extent, BiomeType... biome) {
this(extent, Arrays.asList(checkNotNull(biome)));
}
/**
* Add the given biomes to the list of criteria.
*
* @param biomes a list of biomes
*/
public void add(Collection<BiomeType> biomes) {
checkNotNull(biomes);
this.biomes.addAll(biomes);
}
/**
* Add the given biomes to the list of criteria.
*
* @param biome an array of biomes
*/
public void add(BiomeType... biome) {
add(Arrays.asList(checkNotNull(biome)));
}
/**
* Get the list of biomes that are tested with.
*
* @return a list of biomes
*/
public Collection<BiomeType> getBiomes() {
return biomes;
}
@Override
public boolean test(BlockVector3 vector) {
BiomeType biome = extent.getBiome(vector);
return biomes.contains(biome);
}
@Nullable
@Override
public Mask2D toMask2D() {
return null;
}
}

Datei anzeigen

@ -32,7 +32,10 @@ import static com.google.common.base.Preconditions.checkNotNull;
/** /**
* Tests true if the biome at applied points is the same as the one given. * Tests true if the biome at applied points is the same as the one given.
*
* @deprecated use {@link BiomeMask} as biomes are now 3D.
*/ */
@Deprecated
public class BiomeMask2D extends AbstractMask2D { public class BiomeMask2D extends AbstractMask2D {
private final Extent extent; private final Extent extent;

Datei anzeigen

@ -36,9 +36,9 @@ public final class Constants {
static { static {
NO_COPY_ENTITY_NBT_FIELDS = Collections.unmodifiableList(Arrays.asList( NO_COPY_ENTITY_NBT_FIELDS = Collections.unmodifiableList(Arrays.asList(
//"UUIDLeast", "UUIDMost", // Bukkit and Vanilla //UUID values need to be set manully to a new UUID "UUIDLeast", "UUIDMost", "UUID", // Bukkit and Vanilla
"WorldUUIDLeast", "WorldUUIDMost" // Bukkit and Vanilla "WorldUUIDLeast", "WorldUUIDMost", // Bukkit and Vanilla
//"PersistentIDMSB", "PersistentIDLSB" // Forge //UUID values need to be set manully to a new UUID "PersistentIDMSB", "PersistentIDLSB" // Forge
)); ));
} }
@ -67,5 +67,4 @@ public final class Constants {
*/ */
public static final int DATA_VERSION_MC_1_16 = 2566; public static final int DATA_VERSION_MC_1_16 = 2566;
} }

Datei anzeigen

@ -25,20 +25,23 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
public class SchematicsEventListener { public class SchematicsEventListener {
private static final Logger LOGGER = LoggerFactory.getLogger(SchematicsEventListener.class); private static final Logger LOGGER = LoggerFactory.getLogger(SchematicsEventListener.class);
@Subscribe @Subscribe
public void onConfigLoad(ConfigurationLoadEvent event) { public void onConfigLoad(ConfigurationLoadEvent event) {
Path config = event.getConfiguration().getWorkingDirectory().toPath(); Path config = event.getConfiguration().getWorkingDirectory().toPath();
try { try {
Files.createDirectories(config.resolve(event.getConfiguration().saveDir)); Files.createDirectories(config.resolve(event.getConfiguration().saveDir));
} catch (IOException e) { } catch (FileAlreadyExistsException e) {
LOGGER.warn("Failed to create schematics directory", e); LOGGER.debug("Schematic directory exists as file. Possible symlink.", e);
} catch (IOException e) {
LOGGER.warn("Failed to create schematics directory", e);
}
} }
} }
}

Datei anzeigen

@ -246,7 +246,7 @@ public class CraftScriptContext extends CraftScriptEnvironment {
* @throws FilenameException if there is a problem with the name of the file * @throws FilenameException if there is a problem with the name of the file
*/ */
public File getSafeOpenFile(String folder, String filename, String defaultExt, String... exts) throws FilenameException { public File getSafeOpenFile(String folder, String filename, String defaultExt, String... exts) throws FilenameException {
File dir = controller.getWorkingDirectoryFile(folder); File dir = controller.getWorkingDirectoryPath(folder).toFile();
return controller.getSafeOpenFile(player, dir, filename, defaultExt, exts); return controller.getSafeOpenFile(player, dir, filename, defaultExt, exts);
} }
@ -267,7 +267,7 @@ public class CraftScriptContext extends CraftScriptEnvironment {
* @throws FilenameException if there is a problem with the name of the file * @throws FilenameException if there is a problem with the name of the file
*/ */
public File getSafeSaveFile(String folder, String filename, String defaultExt, String... exts) throws FilenameException { public File getSafeSaveFile(String folder, String filename, String defaultExt, String... exts) throws FilenameException {
File dir = controller.getWorkingDirectoryFile(folder); File dir = controller.getWorkingDirectoryPath(folder).toFile();
return controller.getSafeSaveFile(player, dir, filename, defaultExt, exts); return controller.getSafeSaveFile(player, dir, filename, defaultExt, exts);
} }

Datei anzeigen

@ -47,7 +47,8 @@ public final class Enums {
for (String val : values) { for (String val : values) {
try { try {
return Enum.valueOf(enumType, val); return Enum.valueOf(enumType, val);
} catch (IllegalArgumentException ignored) {} } catch (IllegalArgumentException ignored) {
}
} }
return null; return null;
} }

Datei anzeigen

@ -65,8 +65,8 @@ public final class FileDialogUtil {
} }
private static class ExtensionFilter extends FileFilter { private static class ExtensionFilter extends FileFilter {
private Set<String> exts; private final Set<String> exts;
private String desc; private final String desc;
private ExtensionFilter(String[] exts) { private ExtensionFilter(String[] exts) {
this.exts = new HashSet<>(Arrays.asList(exts)); this.exts = new HashSet<>(Arrays.asList(exts));

Datei anzeigen

@ -25,7 +25,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
public final class GuavaUtil { public final class GuavaUtil {
private GuavaUtil() {} private GuavaUtil() {
}
public static <T> T firstNonNull(@Nullable T first, @Nullable T second) { public static <T> T firstNonNull(@Nullable T first, @Nullable T second) {
return first != null ? first : checkNotNull(second); return first != null ? first : checkNotNull(second);

Datei anzeigen

@ -36,6 +36,7 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.nio.file.Path;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Properties; import java.util.Properties;
@ -55,14 +56,25 @@ public class PropertiesConfiguration extends LocalConfiguration {
/** /**
* Construct the object. The configuration isn't loaded yet. * Construct the object. The configuration isn't loaded yet.
* *
* @param path the path tot he configuration * @param path the path to the configuration
*/ */
public PropertiesConfiguration(File path) { public PropertiesConfiguration(Path path) {
this.path = path; this.path = path.toFile();
properties = new Properties(); properties = new Properties();
} }
/**
* Construct the object. The configuration isn't loaded yet.
*
* @param path the path to the configuration
* @deprecated Use {@link PropertiesConfiguration#PropertiesConfiguration(Path)}
*/
@Deprecated
public PropertiesConfiguration(File path) {
this(path.toPath());
}
@Override @Override
public void load() { public void load() {
try (InputStream stream = new FileInputStream(path)) { try (InputStream stream = new FileInputStream(path)) {
@ -82,6 +94,7 @@ public class PropertiesConfiguration extends LocalConfiguration {
new HashSet<>(getStringSet("limits.allowed-data-cycle-blocks", null)); new HashSet<>(getStringSet("limits.allowed-data-cycle-blocks", null));
defaultChangeLimit = getInt("default-max-changed-blocks", defaultChangeLimit); defaultChangeLimit = getInt("default-max-changed-blocks", defaultChangeLimit);
maxChangeLimit = getInt("max-changed-blocks", maxChangeLimit); maxChangeLimit = getInt("max-changed-blocks", maxChangeLimit);
defaultVerticalHeight = getInt("default-vertical-height", defaultVerticalHeight);
defaultMaxPolygonalPoints = getInt("default-max-polygon-points", defaultMaxPolygonalPoints); defaultMaxPolygonalPoints = getInt("default-max-polygon-points", defaultMaxPolygonalPoints);
maxPolygonalPoints = getInt("max-polygon-points", maxPolygonalPoints); maxPolygonalPoints = getInt("max-polygon-points", maxPolygonalPoints);
defaultMaxPolyhedronPoints = getInt("default-max-polyhedron-points", defaultMaxPolyhedronPoints); defaultMaxPolyhedronPoints = getInt("default-max-polyhedron-points", defaultMaxPolyhedronPoints);
@ -97,7 +110,7 @@ public class PropertiesConfiguration extends LocalConfiguration {
wandItem = getString("wand-item", wandItem); wandItem = getString("wand-item", wandItem);
try { try {
wandItem = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(wandItem)).getId(); wandItem = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(wandItem)).getId();
} catch (Throwable e) { } catch (Throwable ignored) {
} }
superPickaxeDrop = getBool("super-pickaxe-drop-items", superPickaxeDrop); superPickaxeDrop = getBool("super-pickaxe-drop-items", superPickaxeDrop);
superPickaxeManyDrop = getBool("super-pickaxe-many-drop-items", superPickaxeManyDrop); superPickaxeManyDrop = getBool("super-pickaxe-many-drop-items", superPickaxeManyDrop);
@ -107,7 +120,7 @@ public class PropertiesConfiguration extends LocalConfiguration {
navigationWand = getString("nav-wand-item", navigationWand); navigationWand = getString("nav-wand-item", navigationWand);
try { try {
navigationWand = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(navigationWand)).getId(); navigationWand = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(navigationWand)).getId();
} catch (Throwable e) { } catch (Throwable ignored) {
} }
navigationWandMaxDistance = getInt("nav-wand-distance", navigationWandMaxDistance); navigationWandMaxDistance = getInt("nav-wand-distance", navigationWandMaxDistance);
navigationUseGlass = getBool("nav-use-glass", navigationUseGlass); navigationUseGlass = getBool("nav-use-glass", navigationUseGlass);

Datei anzeigen

@ -24,7 +24,8 @@ import java.util.Locale;
public enum SideEffect { public enum SideEffect {
LIGHTING(State.ON), LIGHTING(State.ON),
NEIGHBORS(State.ON), NEIGHBORS(State.ON),
VALIDATION(State.ON), UPDATE(State.ON),
VALIDATION(State.OFF),
ENTITY_AI(State.OFF), ENTITY_AI(State.OFF),
EVENTS(State.OFF); EVENTS(State.OFF);

Datei anzeigen

@ -71,7 +71,9 @@ public class SideEffectSet {
/** /**
* Gets whether this side effect is not off. * Gets whether this side effect is not off.
* *
* <p>
* This returns whether it is either delayed or on. * This returns whether it is either delayed or on.
* </p>
* *
* @param effect The side effect * @param effect The side effect
* @return Whether it should apply * @return Whether it should apply

Datei anzeigen

@ -41,7 +41,8 @@ public class TargetBlock {
private final Extent world; private final Extent world;
private int maxDistance; private int maxDistance;
private double checkDistance, curDistance; private double checkDistance;
private double curDistance;
private BlockVector3 targetPos = BlockVector3.ZERO; private BlockVector3 targetPos = BlockVector3.ZERO;
private Vector3 targetPosDouble = Vector3.ZERO; private Vector3 targetPosDouble = Vector3.ZERO;
private BlockVector3 prevPos = BlockVector3.ZERO; private BlockVector3 prevPos = BlockVector3.ZERO;
@ -53,16 +54,20 @@ public class TargetBlock {
private Mask solidMask; private Mask solidMask;
/** /**
* Constructor requiring a player, uses default values * Constructor requiring a player, uses default values.
* *
* @param player player to work with * @param player player to work with
*/ */
public TargetBlock(Player player) { public TargetBlock(Player player) {
this(player, 300, 0.2); this.world = player.getWorld();
this.setValues(player.getLocation().toVector(), player.getLocation().getYaw(), player.getLocation().getPitch(),
300, 1.65, 0.2);
this.stopMask = new ExistingBlockMask(world);
this.solidMask = new SolidBlockMask(world);
} }
/** /**
* Constructor requiring a player, max distance and a checking distance * Constructor requiring a player, max distance and a checking distance.
* *
* @param player Player to work with * @param player Player to work with
* @param maxDistance how far it checks for blocks * @param maxDistance how far it checks for blocks
@ -108,27 +113,27 @@ public class TargetBlock {
} }
/** /**
* Set the values, all constructors uses this function * Set the values, all constructors uses this function.
* *
* @param loc location of the view * @param loc location of the view
* @param xRotation the X rotation * @param rotationX the X rotation
* @param yRotation the Y rotation * @param rotationY the Y rotation
* @param maxDistance how far it checks for blocks * @param maxDistance how far it checks for blocks
* @param viewHeight where the view is positioned in y-axis * @param viewHeight where the view is positioned in y-axis
* @param checkDistance how often to check for blocks, the smaller the more precise * @param checkDistance how often to check for blocks, the smaller the more precise
*/ */
private void setValues(Vector3 loc, double xRotation, double yRotation, int maxDistance, double viewHeight, double checkDistance) { private void setValues(Vector3 loc, double rotationX, double rotationY, int maxDistance, double viewHeight, double checkDistance) {
this.maxDistance = maxDistance; this.maxDistance = maxDistance;
this.checkDistance = checkDistance; this.checkDistance = checkDistance;
this.curDistance = 0; this.curDistance = 0;
xRotation = (xRotation + 90) % 360; rotationX = (rotationX + 90) % 360;
yRotation *= -1; rotationY *= -1;
double h = (checkDistance * Math.cos(Math.toRadians(yRotation))); double h = (checkDistance * Math.cos(Math.toRadians(rotationY)));
offset = Vector3.at((h * Math.cos(Math.toRadians(xRotation))), offset = Vector3.at((h * Math.cos(Math.toRadians(rotationX))),
(checkDistance * Math.sin(Math.toRadians(yRotation))), (checkDistance * Math.sin(Math.toRadians(rotationY))),
(h * Math.sin(Math.toRadians(xRotation)))); (h * Math.sin(Math.toRadians(rotationX))));
targetPosDouble = loc.add(0, viewHeight, 0); targetPosDouble = loc.add(0, viewHeight, 0);
targetPos = targetPosDouble.toBlockPoint(); targetPos = targetPosDouble.toBlockPoint();
@ -145,7 +150,7 @@ public class TargetBlock {
boolean searchForLastBlock = true; boolean searchForLastBlock = true;
Location lastBlock = null; Location lastBlock = null;
while (getNextBlock() != null) { while (getNextBlock() != null) {
if (stopMask.test(world, targetPos)) { if (stopMask.test(targetPos)) {
break; break;
} else { } else {
if (searchForLastBlock) { if (searchForLastBlock) {
@ -168,7 +173,8 @@ public class TargetBlock {
*/ */
public Location getTargetBlock() { public Location getTargetBlock() {
//noinspection StatementWithEmptyBody //noinspection StatementWithEmptyBody
while (getNextBlock() != null && !stopMask.test(world, targetPos)) ; while (getNextBlock() != null && !stopMask.test(targetPos)) {
}
return getCurrentBlock(); return getCurrentBlock();
} }
@ -180,12 +186,13 @@ public class TargetBlock {
*/ */
public Location getSolidTargetBlock() { public Location getSolidTargetBlock() {
//noinspection StatementWithEmptyBody //noinspection StatementWithEmptyBody
while (getNextBlock() != null && !solidMask.test(world, targetPos)) ; while (getNextBlock() != null && !solidMask.test(targetPos)) {
}
return getCurrentBlock(); return getCurrentBlock();
} }
/** /**
* Get next block * Get next block.
* *
* @return next block position * @return next block position
*/ */
@ -211,7 +218,7 @@ public class TargetBlock {
} }
/** /**
* Returns the current block along the line of vision * Returns the current block along the line of vision.
* *
* @return block position * @return block position
*/ */
@ -224,7 +231,7 @@ public class TargetBlock {
} }
/** /**
* Returns the previous block in the aimed path * Returns the previous block in the aimed path.
* *
* @return block position * @return block position
*/ */
@ -235,15 +242,18 @@ public class TargetBlock {
public Location getAnyTargetBlockFace() { public Location getAnyTargetBlockFace() {
getAnyTargetBlock(); getAnyTargetBlock();
Location current = getCurrentBlock(); Location current = getCurrentBlock();
if (current != null) if (current != null) {
return current.setDirection(current.toVector().subtract(getPreviousBlock().toVector())); return current.setDirection(current.toVector().subtract(getPreviousBlock().toVector()));
else } else {
return new Location(world, targetPos.toVector3(), Float.NaN, Float.NaN); return new Location(world, targetPos.toVector3(), Float.NaN, Float.NaN);
}
} }
public Location getTargetBlockFace() { public Location getTargetBlockFace() {
getTargetBlock(); getTargetBlock();
if (getCurrentBlock() == null) return null; if (getCurrentBlock() == null) {
return null;
}
return getCurrentBlock().setDirection(getCurrentBlock().toVector().subtract(getPreviousBlock().toVector())); return getCurrentBlock().setDirection(getCurrentBlock().toVector().subtract(getPreviousBlock().toVector()));
} }

Datei anzeigen

@ -170,7 +170,7 @@ public class TreeGenerator {
private static final Random RANDOM = new Random(); private static final Random RANDOM = new Random();
/** /**
* Makes a terrible looking pine tree. * Makes a terrible looking pine tree.
* *
* @param basePosition the base position * @param basePosition the base position

Datei anzeigen

@ -36,7 +36,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
public class WeightedChoice<T> { public class WeightedChoice<T> {
private final Function<T, ? extends Number> function; private final Function<T, ? extends Number> function;
private double target; private final double target;
private double best; private double best;
private T current; private T current;

Datei anzeigen

@ -61,6 +61,9 @@ public class YAMLConfiguration extends LocalConfiguration {
maxChangeLimit = Math.max(-1, maxChangeLimit = Math.max(-1,
config.getInt("limits.max-blocks-changed.maximum", maxChangeLimit)); config.getInt("limits.max-blocks-changed.maximum", maxChangeLimit));
defaultVerticalHeight = Math.max(1,
config.getInt("limits.vertical-height.default", defaultVerticalHeight));
defaultMaxPolygonalPoints = Math.max(-1, defaultMaxPolygonalPoints = Math.max(-1,
config.getInt("limits.max-polygonal-points.default", defaultMaxPolygonalPoints)); config.getInt("limits.max-polygonal-points.default", defaultMaxPolygonalPoints));
maxPolygonalPoints = Math.max(-1, maxPolygonalPoints = Math.max(-1,

Datei anzeigen

@ -20,6 +20,7 @@
package com.sk89q.worldedit.util.auth; package com.sk89q.worldedit.util.auth;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.util.formatting.text.Component;
/** /**
* Raised when authorization is not granted. * Raised when authorization is not granted.
@ -29,10 +30,20 @@ public class AuthorizationException extends WorldEditException {
public AuthorizationException() { public AuthorizationException() {
} }
public AuthorizationException(Component message) {
super(message);
}
@Deprecated
public AuthorizationException(String message) { public AuthorizationException(String message) {
super(message); super(message);
} }
public AuthorizationException(Component message, Throwable cause) {
super(message, cause);
}
@Deprecated
public AuthorizationException(String message, Throwable cause) { public AuthorizationException(String message, Throwable cause) {
super(message, cause); super(message, cause);
} }

Datei anzeigen

@ -20,10 +20,16 @@
package com.sk89q.worldedit.util.formatting.component; package com.sk89q.worldedit.util.formatting.component;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.util.formatting.text.Component;
public class InvalidComponentException extends WorldEditException { public class InvalidComponentException extends WorldEditException {
@Deprecated
public InvalidComponentException(String message) { public InvalidComponentException(String message) {
super(message); super(message);
} }
public InvalidComponentException(Component message) {
super(message);
}
} }

Datei anzeigen

@ -19,14 +19,20 @@
package com.sk89q.worldedit.util.io.file; package com.sk89q.worldedit.util.io.file;
import com.sk89q.worldedit.util.formatting.text.Component;
public class FileSelectionAbortedException extends FilenameException { public class FileSelectionAbortedException extends FilenameException {
public FileSelectionAbortedException() { public FileSelectionAbortedException() {
super(""); super("");
} }
@Deprecated
public FileSelectionAbortedException(String msg) { public FileSelectionAbortedException(String msg) {
super("", msg); super("", msg);
} }
public FileSelectionAbortedException(Component msg) {
super("", msg);
}
} }

Datei anzeigen

@ -20,16 +20,23 @@
package com.sk89q.worldedit.util.io.file; package com.sk89q.worldedit.util.io.file;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.util.formatting.text.Component;
public class FilenameException extends WorldEditException { public class FilenameException extends WorldEditException {
private String filename; private final String filename;
public FilenameException(String filename) { public FilenameException(String filename) {
super(); super();
this.filename = filename; this.filename = filename;
} }
public FilenameException(String filename, Component msg) {
super(msg);
this.filename = filename;
}
@Deprecated
public FilenameException(String filename, String msg) { public FilenameException(String filename, String msg) {
super(msg); super(msg);
this.filename = filename; this.filename = filename;

Datei anzeigen

@ -19,12 +19,19 @@
package com.sk89q.worldedit.util.io.file; package com.sk89q.worldedit.util.io.file;
import com.sk89q.worldedit.util.formatting.text.Component;
public class FilenameResolutionException extends FilenameException { public class FilenameResolutionException extends FilenameException {
public FilenameResolutionException(String filename) { public FilenameResolutionException(String filename) {
super(filename); super(filename);
} }
public FilenameResolutionException(String filename, Component msg) {
super(filename, msg);
}
@Deprecated
public FilenameResolutionException(String filename, String msg) { public FilenameResolutionException(String filename, String msg) {
super(filename, msg); super(filename, msg);
} }

Datei anzeigen

@ -19,12 +19,19 @@
package com.sk89q.worldedit.util.io.file; package com.sk89q.worldedit.util.io.file;
import com.sk89q.worldedit.util.formatting.text.Component;
public class InvalidFilenameException extends FilenameException { public class InvalidFilenameException extends FilenameException {
public InvalidFilenameException(String filename) { public InvalidFilenameException(String filename) {
super(filename); super(filename);
} }
public InvalidFilenameException(String filename, Component msg) {
super(filename, msg);
}
@Deprecated
public InvalidFilenameException(String filename, String msg) { public InvalidFilenameException(String filename, String msg) {
super(filename, msg); super(filename, msg);
} }

Datei anzeigen

@ -22,9 +22,14 @@ package com.sk89q.worldedit.util.io.file;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.Streams; import com.google.common.collect.Streams;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.Arrays; import java.util.Arrays;
import java.util.Comparator;
import java.util.Deque; import java.util.Deque;
import java.util.Spliterator; import java.util.Spliterator;
import java.util.stream.IntStream; import java.util.stream.IntStream;
@ -32,6 +37,20 @@ import java.util.stream.Stream;
public class MorePaths { public class MorePaths {
public static Comparator<Path> oldestFirst() {
return Comparator.comparing(x -> {
try {
return Files.getLastModifiedTime(x);
} catch (IOException e) {
return FileTime.from(Instant.EPOCH);
}
});
}
public static Comparator<Path> newestFirst() {
return oldestFirst().reversed();
}
/** /**
* Starting with the first path element, add elements until reaching this path. * Starting with the first path element, add elements until reaching this path.
*/ */

Datei anzeigen

@ -19,9 +19,12 @@
package com.sk89q.worldedit.util.io.file; package com.sk89q.worldedit.util.io.file;
import org.jetbrains.annotations.Nullable;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -64,6 +67,80 @@ public class SafeFiles {
return name.substring(0, name.length() - 1); return name.substring(0, name.length() - 1);
} }
/**
* Recursively uses {@link #tryHardToDelete(Path)} to cleanup directories before deleting them.
*
* @param directory the directory to delete
* @throws IOException if an error occurs trying to delete the directory
*/
public static void tryHardToDeleteDir(Path directory) throws IOException {
if (!Files.isDirectory(directory)) {
if (!Files.exists(directory)) {
return;
}
throw new IOException(directory + " is not a directory");
}
try (Stream<Path> files = Files.list(directory)) {
for (Iterator<Path> iter = files.iterator(); iter.hasNext(); ) {
Path next = iter.next();
if (Files.isDirectory(next)) {
tryHardToDeleteDir(next);
} else {
tryHardToDelete(next);
}
}
}
tryHardToDelete(directory);
}
/**
* Tries to delete a path. If it fails the first time, uses an implementation detail to try
* and make it possible to delete the path, and then tries again. If that fails, throws an
* {@link IOException} with both errors.
*
* @param path the path to delete
* @throws IOException if the path could not be deleted after multiple attempts
*/
public static void tryHardToDelete(Path path) throws IOException {
IOException suppressed = tryDelete(path);
if (suppressed == null) {
return;
}
// This is copied from Ant (see org.apache.tools.ant.util.FileUtils.tryHardToDelete).
// It mentions that there is a bug in the Windows JDK implementations that this is a valid
// workaround for. I've been unable to find a definitive reference to this bug.
// The thinking is that if this is good enough for Ant, it's good enough for us.
System.gc();
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
IOException suppressed2 = tryDelete(path);
if (suppressed2 == null) {
return;
}
IOException ex = new IOException("Failed to delete " + path, suppressed2);
ex.addSuppressed(suppressed);
throw ex;
}
@Nullable
private static IOException tryDelete(Path path) {
try {
Files.deleteIfExists(path);
if (Files.exists(path)) {
return new IOException(path + " still exists after deleting");
}
return null;
} catch (IOException e) {
return e;
}
}
private SafeFiles() { private SafeFiles() {
} }
} }

Datei anzeigen

@ -68,7 +68,7 @@ public class DynamicStreamHandler extends StreamHandler {
handler.setFilter(filter); handler.setFilter(filter);
try { try {
handler.setEncoding(encoding); handler.setEncoding(encoding);
} catch (UnsupportedEncodingException ignore) { } catch (UnsupportedEncodingException ignored) {
} }
handler.setLevel(level); handler.setLevel(level);
} }

Datei anzeigen

@ -19,6 +19,9 @@
package com.sk89q.worldedit.util.net; package com.sk89q.worldedit.util.net;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.google.common.net.UrlEscapers;
import com.sk89q.worldedit.util.io.Closer; import com.sk89q.worldedit.util.io.Closer;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
@ -31,19 +34,16 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.net.URLEncoder; import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import static com.google.common.base.Preconditions.checkState;
public class HttpRequest implements Closeable { public class HttpRequest implements Closeable {
@ -89,9 +89,21 @@ public class HttpRequest implements Closeable {
* @param form the form * @param form the form
* @return this object * @return this object
*/ */
public HttpRequest bodyForm(Form form) { public HttpRequest bodyUrlEncodedForm(Form form) {
contentType = "application/x-www-form-urlencoded"; contentType = "application/x-www-form-urlencoded";
body = form.toString().getBytes(); body = form.toUrlEncodedString().getBytes(StandardCharsets.UTF_8);
return this;
}
/**
* Submit form data.
*
* @param form the form
* @return this object
*/
public HttpRequest bodyMultipartForm(Form form) {
contentType = "multipart/form-data;boundary=" + form.getFormDataSeparator();
body = form.toFormDataString().getBytes(StandardCharsets.UTF_8);
return this; return this;
} }
@ -155,8 +167,9 @@ public class HttpRequest implements Closeable {
out.close(); out.close();
} }
inputStream = conn.getResponseCode() == HttpURLConnection.HTTP_OK ? inputStream = conn.getResponseCode() == HttpURLConnection.HTTP_OK
conn.getInputStream() : conn.getErrorStream(); ? conn.getInputStream()
: conn.getErrorStream();
successful = true; successful = true;
} finally { } finally {
@ -202,13 +215,6 @@ public class HttpRequest implements Closeable {
return conn.getResponseCode(); return conn.getResponseCode();
} }
public String getSingleHeaderValue(String header) {
checkState(conn != null, "No connection has been made");
// maybe we should check for multi-header?
return conn.getHeaderField(header);
}
/** /**
* Get the input stream. * Get the input stream.
* *
@ -223,8 +229,9 @@ public class HttpRequest implements Closeable {
* *
* @return the buffered response * @return the buffered response
* @throws java.io.IOException on I/O error * @throws java.io.IOException on I/O error
* @throws InterruptedException on interruption
*/ */
public BufferedResponse returnContent() throws IOException { public BufferedResponse returnContent() throws IOException, InterruptedException {
if (inputStream == null) { if (inputStream == null) {
throw new IllegalArgumentException("No input stream available"); throw new IllegalArgumentException("No input stream available");
} }
@ -247,8 +254,9 @@ public class HttpRequest implements Closeable {
* @param file the file * @param file the file
* @return this object * @return this object
* @throws java.io.IOException on I/O error * @throws java.io.IOException on I/O error
* @throws InterruptedException on interruption
*/ */
public HttpRequest saveContent(File file) throws IOException { public HttpRequest saveContent(File file) throws IOException, InterruptedException {
Closer closer = Closer.create(); Closer closer = Closer.create();
try { try {
@ -269,8 +277,9 @@ public class HttpRequest implements Closeable {
* @param out the output stream * @param out the output stream
* @return this object * @return this object
* @throws java.io.IOException on I/O error * @throws java.io.IOException on I/O error
* @throws InterruptedException on interruption
*/ */
public HttpRequest saveContent(OutputStream out) throws IOException { public HttpRequest saveContent(OutputStream out) throws IOException, InterruptedException {
BufferedInputStream bis; BufferedInputStream bis;
try { try {
@ -301,8 +310,10 @@ public class HttpRequest implements Closeable {
} }
@Override @Override
public void close() throws IOException { public void close() {
if (conn != null) conn.disconnect(); if (conn != null) {
conn.disconnect();
}
} }
/** /**
@ -366,18 +377,24 @@ public class HttpRequest implements Closeable {
url.getPath(), url.getQuery(), url.getRef()); url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL(); url = uri.toURL();
return url; return url;
} catch (MalformedURLException e) { } catch (MalformedURLException | URISyntaxException e) {
return existing;
} catch (URISyntaxException e) {
return existing; return existing;
} }
} }
/** /**
* Used with {@link #bodyForm(Form)}. * Used with {@link #bodyUrlEncodedForm(Form)}.
*/ */
public final static class Form { public static final class Form {
public final List<String> elements = new ArrayList<>();
private static final Joiner.MapJoiner URL_ENCODER = Joiner.on('&')
.withKeyValueSeparator('=');
private static final Joiner CRLF_JOINER = Joiner.on("\r\n");
public final Map<String, String> elements = new LinkedHashMap<>();
private final String formDataSeparator = "EngineHubFormData"
+ ThreadLocalRandom.current().nextInt(10000, 99999);
private Form() { private Form() {
} }
@ -390,30 +407,45 @@ public class HttpRequest implements Closeable {
* @return this object * @return this object
*/ */
public Form add(String key, String value) { public Form add(String key, String value) {
try { elements.put(key, value);
elements.add(URLEncoder.encode(key, "UTF-8") + return this;
"=" + URLEncoder.encode(value, "UTF-8"));
return this;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
} }
@Override public String getFormDataSeparator() {
public String toString() { return formDataSeparator;
}
public String toFormDataString() {
String separatorWithDashes = "--" + formDataSeparator;
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
boolean first = true;
for (String element : elements) { for (Map.Entry<String, String> element : elements.entrySet()) {
if (first) { CRLF_JOINER.appendTo(
first = false; builder,
} else { separatorWithDashes,
builder.append("&"); "Content-Disposition: form-data; name=\"" + element.getKey() + "\"",
} "",
builder.append(element); element.getValue(),
""
);
} }
builder.append(separatorWithDashes).append("--");
return builder.toString(); return builder.toString();
} }
public String toUrlEncodedString() {
return URL_ENCODER.join(
elements.entrySet().stream()
.map(e -> Maps.immutableEntry(
UrlEscapers.urlFormParameterEscaper().escape(e.getKey()),
UrlEscapers.urlFormParameterEscaper().escape(e.getValue())
))
.iterator()
);
}
/** /**
* Create a new form. * Create a new form.
* *

Datei anzeigen

@ -27,13 +27,9 @@ import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.util.Map; import java.util.Map;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EngineHubPaste implements Paster { public class EngineHubPaste implements Paster {
private static final Pattern URL_PATTERN = Pattern.compile("https?://.+$");
private static final Gson GSON = new Gson(); private static final Gson GSON = new Gson();
@Override @Override
@ -50,31 +46,34 @@ public class EngineHubPaste implements Paster {
@Override @Override
public URL call() throws IOException, InterruptedException { public URL call() throws IOException, InterruptedException {
URL initialUrl = HttpRequest.url("https://paste.enginehub.org/signed_paste");
SignedPasteResponse response = GSON.fromJson(HttpRequest.get(initialUrl)
.execute()
.expectResponseCode(200)
.returnContent()
.asString("UTF-8"), TypeToken.get(SignedPasteResponse.class).getType());
HttpRequest.Form form = HttpRequest.Form.create(); HttpRequest.Form form = HttpRequest.Form.create();
form.add("content", content); for (Map.Entry<String, String> entry : response.uploadFields.entrySet()) {
form.add("from", "enginehub"); form.add(entry.getKey(), entry.getValue());
URL url = HttpRequest.url("https://paste.enginehub.org/paste");
String result = HttpRequest.post(url)
.bodyForm(form)
.execute()
.expectResponseCode(200)
.returnContent()
.asString("UTF-8").trim();
Map<Object, Object> object = GSON.fromJson(result, new TypeToken<Map<Object, Object>>() {
}.getType());
if (object != null) {
String urlString = String.valueOf(object.get("url"));
Matcher m = URL_PATTERN.matcher(urlString);
if (m.matches()) {
return new URL(urlString);
}
} }
form.add("file", content);
throw new IOException("Failed to save paste; instead, got: " + result); URL url = HttpRequest.url(response.uploadUrl);
// If this succeeds, it will not return any data aside from a 204 status.
HttpRequest.post(url)
.bodyMultipartForm(form)
.execute()
.expectResponseCode(200, 204);
return new URL(response.viewUrl);
} }
} }
private static final class SignedPasteResponse {
String viewUrl;
String uploadUrl;
Map<String, String> uploadFields;
}
} }

Datei anzeigen

@ -65,11 +65,11 @@ public class FileNameDateTimeParser implements SnapshotDateTimeParser {
private static final String SEP = "[ \\-_:]"; private static final String SEP = "[ \\-_:]";
private static final Pattern BASIC_FILTER = Pattern.compile( private static final Pattern BASIC_FILTER = Pattern.compile(
"^(?<year>\\d{4})" + SEP + "(?<month>\\d{1,2})" + SEP + "(?<day>\\d{1,2})" + "^(?<year>\\d{4})" + SEP + "(?<month>\\d{1,2})" + SEP + "(?<day>\\d{1,2})"
// Optionally: // Optionally:
"(?:" + "[ \\-_:T]" + + "(?:" + "[ \\-_:T]"
"(?<hour>\\d{1,2})" + SEP + "(?<minute>\\d{1,2})" + SEP + "(?<second>\\d{1,2})" + + "(?<hour>\\d{1,2})" + SEP + "(?<minute>\\d{1,2})" + SEP + "(?<second>\\d{1,2})"
")?" + ")?"
); );
private FileNameDateTimeParser() { private FileNameDateTimeParser() {

Datei anzeigen

@ -33,6 +33,7 @@ public interface BiomeData {
* *
* @return the biome's name * @return the biome's name
*/ */
@Deprecated
String getName(); String getName();
} }

Datei anzeigen

@ -108,7 +108,7 @@ public class BaseBlock implements BlockStateHolder<BaseBlock>, TileEntityBlock {
} }
/** /**
* Gets a map of state to statevalue * Gets a map of state to state values.
* *
* @return The state map * @return The state map
*/ */

Datei anzeigen

@ -20,44 +20,63 @@
package com.sk89q.worldedit.world.block; package com.sk89q.worldedit.world.block;
/** /**
* Stores a list of categories of Block Types. * Stores a list of common {@link BlockCategory BlockCategories}.
*
* @see BlockCategory
*/ */
@SuppressWarnings("unused")
public final class BlockCategories { public final class BlockCategories {
public static final BlockCategory ACACIA_LOGS = get("minecraft:acacia_logs"); public static final BlockCategory ACACIA_LOGS = get("minecraft:acacia_logs");
public static final BlockCategory ANVIL = get("minecraft:anvil"); public static final BlockCategory ANVIL = get("minecraft:anvil");
public static final BlockCategory BAMBOO_PLANTABLE_ON = get("minecraft:bamboo_plantable_on"); public static final BlockCategory BAMBOO_PLANTABLE_ON = get("minecraft:bamboo_plantable_on");
public static final BlockCategory BANNERS = get("minecraft:banners"); public static final BlockCategory BANNERS = get("minecraft:banners");
public static final BlockCategory BASE_STONE_NETHER = get("minecraft:base_stone_nether"); public static final BlockCategory BASE_STONE_NETHER = get("minecraft:base_stone_nether");
public static final BlockCategory BASE_STONE_OVERWORLD = get("minecraft:base_stone_overworld"); public static final BlockCategory BASE_STONE_OVERWORLD = get("minecraft:base_stone_overworld");
public static final BlockCategory BEACON_BASE_BLOCKS = get("minecraft:beacon_base_blocks");
public static final BlockCategory BEDS = get("minecraft:beds"); public static final BlockCategory BEDS = get("minecraft:beds");
public static final BlockCategory BEE_GROWABLES = get("minecraft:bee_growables"); public static final BlockCategory BEE_GROWABLES = get("minecraft:bee_growables");
public static final BlockCategory BEEHIVES = get("minecraft:beehives"); public static final BlockCategory BEEHIVES = get("minecraft:beehives");
public static final BlockCategory BIRCH_LOGS = get("minecraft:birch_logs"); public static final BlockCategory BIRCH_LOGS = get("minecraft:birch_logs");
public static final BlockCategory BUTTONS = get("minecraft:buttons"); public static final BlockCategory BUTTONS = get("minecraft:buttons");
public static final BlockCategory CAMPFIRES = get("minecraft:campfires");
public static final BlockCategory CARPETS = get("minecraft:carpets"); public static final BlockCategory CARPETS = get("minecraft:carpets");
public static final BlockCategory CLIMBABLE = get("minecraft:climbable");
public static final BlockCategory CORAL_BLOCKS = get("minecraft:coral_blocks"); public static final BlockCategory CORAL_BLOCKS = get("minecraft:coral_blocks");
public static final BlockCategory CORAL_PLANTS = get("minecraft:coral_plants"); public static final BlockCategory CORAL_PLANTS = get("minecraft:coral_plants");
public static final BlockCategory CORALS = get("minecraft:corals"); public static final BlockCategory CORALS = get("minecraft:corals");
public static final BlockCategory CRIMSON_STEMS = get("minecraft:crimson_stems");
public static final BlockCategory CROPS = get("minecraft:crops"); public static final BlockCategory CROPS = get("minecraft:crops");
public static final BlockCategory DARK_OAK_LOGS = get("minecraft:dark_oak_logs"); public static final BlockCategory DARK_OAK_LOGS = get("minecraft:dark_oak_logs");
@Deprecated public static final BlockCategory DIRT_LIKE = get("minecraft:dirt_like"); @Deprecated public static final BlockCategory DIRT_LIKE = get("minecraft:dirt_like");
public static final BlockCategory DOORS = get("minecraft:doors"); public static final BlockCategory DOORS = get("minecraft:doors");
public static final BlockCategory DRAGON_IMMUNE = get("minecraft:dragon_immune"); public static final BlockCategory DRAGON_IMMUNE = get("minecraft:dragon_immune");
public static final BlockCategory ENDERMAN_HOLDABLE = get("minecraft:enderman_holdable"); public static final BlockCategory ENDERMAN_HOLDABLE = get("minecraft:enderman_holdable");
public static final BlockCategory FENCE_GATES = get("minecraft:fence_gates");
public static final BlockCategory FENCES = get("minecraft:fences"); public static final BlockCategory FENCES = get("minecraft:fences");
public static final BlockCategory FIRE = get("minecraft:fire");
public static final BlockCategory FLOWER_POTS = get("minecraft:flower_pots"); public static final BlockCategory FLOWER_POTS = get("minecraft:flower_pots");
public static final BlockCategory FLOWERS = get("minecraft:flowers"); public static final BlockCategory FLOWERS = get("minecraft:flowers");
public static final BlockCategory GOLD_ORES = get("minecraft:gold_ores");
public static final BlockCategory GUARDED_BY_PIGLINS = get("minecraft:guarded_by_piglins");
public static final BlockCategory HOGLIN_REPELLENTS = get("minecraft:hoglin_repellents");
public static final BlockCategory ICE = get("minecraft:ice"); public static final BlockCategory ICE = get("minecraft:ice");
public static final BlockCategory IMPERMEABLE = get("minecraft:impermeable"); public static final BlockCategory IMPERMEABLE = get("minecraft:impermeable");
public static final BlockCategory INFINIBURN_END = get("minecraft:infiniburn_end");
public static final BlockCategory INFINIBURN_NETHER = get("minecraft:infiniburn_nether");
public static final BlockCategory INFINIBURN_OVERWORLD = get("minecraft:infiniburn_overworld");
public static final BlockCategory JUNGLE_LOGS = get("minecraft:jungle_logs"); public static final BlockCategory JUNGLE_LOGS = get("minecraft:jungle_logs");
public static final BlockCategory LEAVES = get("minecraft:leaves"); public static final BlockCategory LEAVES = get("minecraft:leaves");
public static final BlockCategory LOGS = get("minecraft:logs"); public static final BlockCategory LOGS = get("minecraft:logs");
public static final BlockCategory LOGS_THAT_BURN = get("minecraft:logs_that_burn"); public static final BlockCategory LOGS_THAT_BURN = get("minecraft:logs_that_burn");
public static final BlockCategory MUSHROOM_GROW_BLOCK = get("minecraft:mushroom_grow_block"); public static final BlockCategory MUSHROOM_GROW_BLOCK = get("minecraft:mushroom_grow_block");
public static final BlockCategory NON_FLAMMABLE_WOOD = get("minecraft:non_flammable_wood");
public static final BlockCategory NYLIUM = get("minecraft:nylium");
public static final BlockCategory OAK_LOGS = get("minecraft:oak_logs"); public static final BlockCategory OAK_LOGS = get("minecraft:oak_logs");
public static final BlockCategory PIGLIN_REPELLENTS = get("minecraft:piglin_repellents");
public static final BlockCategory PLANKS = get("minecraft:planks"); public static final BlockCategory PLANKS = get("minecraft:planks");
public static final BlockCategory PORTALS = get("minecraft:portals"); public static final BlockCategory PORTALS = get("minecraft:portals");
public static final BlockCategory PRESSURE_PLATES = get("minecraft:pressure_plates");
public static final BlockCategory PREVENT_MOB_SPAWNING_INSIDE = get("minecraft:prevent_mob_spawning_inside");
public static final BlockCategory RAILS = get("minecraft:rails"); public static final BlockCategory RAILS = get("minecraft:rails");
public static final BlockCategory SAND = get("minecraft:sand"); public static final BlockCategory SAND = get("minecraft:sand");
public static final BlockCategory SAPLINGS = get("minecraft:saplings"); public static final BlockCategory SAPLINGS = get("minecraft:saplings");
@ -65,18 +84,27 @@ public final class BlockCategories {
public static final BlockCategory SIGNS = get("minecraft:signs"); public static final BlockCategory SIGNS = get("minecraft:signs");
public static final BlockCategory SLABS = get("minecraft:slabs"); public static final BlockCategory SLABS = get("minecraft:slabs");
public static final BlockCategory SMALL_FLOWERS = get("minecraft:small_flowers"); public static final BlockCategory SMALL_FLOWERS = get("minecraft:small_flowers");
public static final BlockCategory SOUL_FIRE_BASE_BLOCKS = get("minecraft:soul_fire_base_blocks");
public static final BlockCategory SOUL_SPEED_BLOCKS = get("minecraft:soul_speed_blocks");
public static final BlockCategory SPRUCE_LOGS = get("minecraft:spruce_logs"); public static final BlockCategory SPRUCE_LOGS = get("minecraft:spruce_logs");
public static final BlockCategory STAIRS = get("minecraft:stairs"); public static final BlockCategory STAIRS = get("minecraft:stairs");
public static final BlockCategory STANDING_SIGNS = get("minecraft:standing_signs"); public static final BlockCategory STANDING_SIGNS = get("minecraft:standing_signs");
public static final BlockCategory STONE_BRICKS = get("minecraft:stone_bricks"); public static final BlockCategory STONE_BRICKS = get("minecraft:stone_bricks");
public static final BlockCategory STONE_PRESSURE_PLATES = get("minecraft:stone_pressure_plates");
public static final BlockCategory STRIDER_WARM_BLOCKS = get("minecraft:strider_warm_blocks");
public static final BlockCategory TALL_FLOWERS = get("minecraft:tall_flowers"); public static final BlockCategory TALL_FLOWERS = get("minecraft:tall_flowers");
public static final BlockCategory TRAPDOORS = get("minecraft:trapdoors"); public static final BlockCategory TRAPDOORS = get("minecraft:trapdoors");
public static final BlockCategory UNDERWATER_BONEMEALS = get("minecraft:underwater_bonemeals"); public static final BlockCategory UNDERWATER_BONEMEALS = get("minecraft:underwater_bonemeals");
public static final BlockCategory UNSTABLE_BOTTOM_CENTER = get("minecraft:unstable_bottom_center");
public static final BlockCategory VALID_SPAWN = get("minecraft:valid_spawn"); public static final BlockCategory VALID_SPAWN = get("minecraft:valid_spawn");
public static final BlockCategory WALL_CORALS = get("minecraft:wall_corals"); public static final BlockCategory WALL_CORALS = get("minecraft:wall_corals");
public static final BlockCategory WALL_POST_OVERRIDE = get("minecraft:wall_post_override");
public static final BlockCategory WALL_SIGNS = get("minecraft:wall_signs"); public static final BlockCategory WALL_SIGNS = get("minecraft:wall_signs");
public static final BlockCategory WALLS = get("minecraft:walls"); public static final BlockCategory WALLS = get("minecraft:walls");
public static final BlockCategory WARPED_STEMS = get("minecraft:warped_stems");
public static final BlockCategory WART_BLOCKS = get("minecraft:wart_blocks");
public static final BlockCategory WITHER_IMMUNE = get("minecraft:wither_immune"); public static final BlockCategory WITHER_IMMUNE = get("minecraft:wither_immune");
public static final BlockCategory WITHER_SUMMON_BASE_BLOCKS = get("minecraft:wither_summon_base_blocks");
public static final BlockCategory WOODEN_BUTTONS = get("minecraft:wooden_buttons"); public static final BlockCategory WOODEN_BUTTONS = get("minecraft:wooden_buttons");
public static final BlockCategory WOODEN_DOORS = get("minecraft:wooden_doors"); public static final BlockCategory WOODEN_DOORS = get("minecraft:wooden_doors");
public static final BlockCategory WOODEN_FENCES = get("minecraft:wooden_fences"); public static final BlockCategory WOODEN_FENCES = get("minecraft:wooden_fences");
@ -85,16 +113,18 @@ public final class BlockCategories {
public static final BlockCategory WOODEN_STAIRS = get("minecraft:wooden_stairs"); public static final BlockCategory WOODEN_STAIRS = get("minecraft:wooden_stairs");
public static final BlockCategory WOODEN_TRAPDOORS = get("minecraft:wooden_trapdoors"); public static final BlockCategory WOODEN_TRAPDOORS = get("minecraft:wooden_trapdoors");
public static final BlockCategory WOOL = get("minecraft:wool"); public static final BlockCategory WOOL = get("minecraft:wool");
public static final BlockCategory FIRE = get("minecraft:fire");
private BlockCategories() { private BlockCategories() {
} }
private static BlockCategory get(final String id) { /**
BlockCategory blockCategory = BlockCategory.REGISTRY.get(id); * Gets the {@link BlockCategory} associated with the given id.
if (blockCategory == null) { */
public static BlockCategory get(String id) {
BlockCategory entry = BlockCategory.REGISTRY.get(id);
if (entry == null) {
return new BlockCategory(id); return new BlockCategory(id);
} }
return blockCategory; return entry;
} }
} }

Datei anzeigen

@ -112,6 +112,7 @@ public class BlockType implements Keyed, Pattern {
* *
* @return The name, or ID * @return The name, or ID
*/ */
@Deprecated
public String getName() { public String getName() {
String name = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getRegistries().getBlockRegistry().getName(this); String name = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getRegistries().getBlockRegistry().getName(this);
if (name == null) { if (name == null) {
@ -133,7 +134,9 @@ public class BlockType implements Keyed, Pattern {
*/ */
@Deprecated @Deprecated
public BlockState withPropertyId(int propertyId) { public BlockState withPropertyId(int propertyId) {
if (settings.stateOrdinals == null) return settings.defaultState; if (settings.stateOrdinals == null) {
return settings.defaultState;
}
return BlockTypesCache.states[settings.stateOrdinals[propertyId]]; return BlockTypesCache.states[settings.stateOrdinals[propertyId]];
} }
@ -207,7 +210,9 @@ public class BlockType implements Keyed, Pattern {
* @return All possible states * @return All possible states
*/ */
public List<BlockState> getAllStates() { public List<BlockState> getAllStates() {
if (settings.stateOrdinals == null) return Collections.singletonList(getDefaultState()); if (settings.stateOrdinals == null) {
return Collections.singletonList(getDefaultState());
}
return IntStream.of(settings.stateOrdinals).filter(i -> i != -1).mapToObj(i -> BlockTypesCache.states[i]).collect(Collectors.toList()); return IntStream.of(settings.stateOrdinals).filter(i -> i != -1).mapToObj(i -> BlockTypesCache.states[i]).collect(Collectors.toList());
} }
@ -268,8 +273,10 @@ public class BlockType implements Keyed, Pattern {
/** /**
* Gets the legacy ID. Needed for legacy reasons. * Gets the legacy ID. Needed for legacy reasons.
*
* <p> * <p>
* DO NOT USE THIS. * DO NOT USE THIS.
* </p>
* *
* @return legacy id or 0, if unknown * @return legacy id or 0, if unknown
*/ */
@ -279,10 +286,17 @@ public class BlockType implements Keyed, Pattern {
return combinedId == null ? 0 : combinedId; return combinedId == null ? 0 : combinedId;
} }
@Deprecated
public int getLegacyId() {
return computeLegacy(0);
}
/** /**
* The internal index of this type. * The internal index of this type.
*
* <p> * <p>
* This number is not necessarily consistent across restarts. * This number is not necessarily consistent across restarts.
* </p>
* *
* @return internal id * @return internal id
*/ */
@ -323,15 +337,12 @@ public class BlockType implements Keyed, Pattern {
return new SingleBlockTypeMask(extent, this); return new SingleBlockTypeMask(extent, this);
} }
@Deprecated
public int getLegacyId() {
return computeLegacy(0);
}
/** /**
* Gets the legacy data. Needed for legacy reasons. * Gets the legacy data. Needed for legacy reasons.
*
* <p> * <p>
* DO NOT USE THIS. * DO NOT USE THIS.
* </p>
* *
* @return legacy data or 0, if unknown * @return legacy data or 0, if unknown
*/ */

Datei anzeigen

@ -33,8 +33,11 @@ import java.util.stream.Stream;
import javax.annotation.Nullable; import javax.annotation.Nullable;
/** /**
* Stores a list of common Block String IDs. * Stores a list of common {@link BlockType BlockTypes}.
*
* @see BlockType
*/ */
@SuppressWarnings("unused")
public final class BlockTypes { public final class BlockTypes {
// Doesn't really matter what the hardcoded values are, as FAWE will update it on load // Doesn't really matter what the hardcoded values are, as FAWE will update it on load
@Nullable public static final BlockType __RESERVED__ = init(); // Placeholder for null index (i.e. when block types are represented as primitives) @Nullable public static final BlockType __RESERVED__ = init(); // Placeholder for null index (i.e. when block types are represented as primitives)
@ -820,6 +823,7 @@ public final class BlockTypes {
CharSequence fullName = joined.init(BlockType.REGISTRY.getDefaultNamespace(), ':', name); CharSequence fullName = joined.init(BlockType.REGISTRY.getDefaultNamespace(), ':', name);
return BlockType.REGISTRY.getMap().get(fullName); return BlockType.REGISTRY.getMap().get(fullName);
} }
static { static {
fieldsTmp = null; fieldsTmp = null;
joined = null; joined = null;
@ -835,14 +839,20 @@ public final class BlockTypes {
final String inputLower = type.toLowerCase(Locale.ROOT); final String inputLower = type.toLowerCase(Locale.ROOT);
String input = inputLower; String input = inputLower;
if (!input.split("\\[", 2)[0].contains(":")) input = "minecraft:" + input; if (!input.split("\\[", 2)[0].contains(":")) {
input = "minecraft:" + input;
}
BlockType result = BlockType.REGISTRY.get(input); BlockType result = BlockType.REGISTRY.get(input);
if (result != null) return result; if (result != null) {
return result;
}
try { try {
BlockStateHolder<BlockState> block = LegacyMapper.getInstance().getBlockFromLegacy(input); BlockStateHolder<BlockState> block = LegacyMapper.getInstance().getBlockFromLegacy(input);
if (block != null) return block.getBlockType(); if (block != null) {
} catch (NumberFormatException | IndexOutOfBoundsException e) { return block.getBlockType();
}
} catch (NumberFormatException | IndexOutOfBoundsException ignored) {
} }
throw new SuggestInputParseException("Does not match a valid block type: " + inputLower, inputLower, () -> Stream.of(BlockTypesCache.values) throw new SuggestInputParseException("Does not match a valid block type: " + inputLower, inputLower, () -> Stream.of(BlockTypesCache.values)
@ -857,8 +867,11 @@ public final class BlockTypes {
return BlockTypesCache.$NAMESPACES; return BlockTypesCache.$NAMESPACES;
} }
/**
* Gets the {@link BlockType} associated with the given id.
*/
@Nullable @Nullable
public static BlockType get(final String id) { public static BlockType get(String id) {
return BlockType.REGISTRY.get(id); return BlockType.REGISTRY.get(id);
} }

Datei anzeigen

@ -29,7 +29,7 @@ import com.sk89q.worldedit.world.block.BaseBlock;
public interface Chunk { public interface Chunk {
/** /**
* Get a block; * Get a block.
* *
* @param position the position of the block * @param position the position of the block
* @return block the block * @return block the block

Datei anzeigen

@ -43,19 +43,19 @@ import java.util.Map;
*/ */
public class OldChunk implements Chunk { public class OldChunk implements Chunk {
private CompoundTag rootTag; private final CompoundTag rootTag;
private byte[] blocks; private final byte[] blocks;
private byte[] data; private final byte[] data;
private int rootX; private final int rootX;
private int rootZ; private final int rootZ;
private Map<BlockVector3, Map<String,Tag>> tileEntities; private Map<BlockVector3, Map<String, Tag>> tileEntities;
/** /**
* Construct the chunk with a compound tag. * Construct the chunk with a compound tag.
* *
* @param tag the tag * @param tag the tag
* @throws DataException * @throws DataException if there is an error getting the chunk data
*/ */
public OldChunk(CompoundTag tag) throws DataException { public OldChunk(CompoundTag tag) throws DataException {
rootTag = tag; rootTag = tag;
@ -71,7 +71,7 @@ public class OldChunk implements Chunk {
+ "to be " + size + " bytes; found " + blocks.length); + "to be " + size + " bytes; found " + blocks.length);
} }
if (data.length != (size/2)) { if (data.length != (size / 2)) {
throw new InvalidFormatException("Chunk block data byte array " throw new InvalidFormatException("Chunk block data byte array "
+ "expected to be " + size + " bytes; found " + data.length); + "expected to be " + size + " bytes; found " + data.length);
} }
@ -80,7 +80,7 @@ public class OldChunk implements Chunk {
/** /**
* Used to load the tile entities. * Used to load the tile entities.
* *
* @throws DataException * @throws DataException if there is an error getting the chunk data
*/ */
private void populateTileEntities() throws DataException { private void populateTileEntities() throws DataException {
List<Tag> tags = NBTUtils.getChildTag( List<Tag> tags = NBTUtils.getChildTag(
@ -119,6 +119,8 @@ public class OldChunk implements Chunk {
z = ((IntTag) entry.getValue()).getValue(); z = ((IntTag) entry.getValue()).getValue();
} }
break; break;
default:
break;
} }
values.put(entry.getKey(), entry.getValue()); values.put(entry.getKey(), entry.getValue());
@ -136,7 +138,7 @@ public class OldChunk implements Chunk {
* *
* @param position the position * @param position the position
* @return a tag * @return a tag
* @throws DataException * @throws DataException if there is an error getting the chunk data
*/ */
private CompoundTag getBlockTileEntity(BlockVector3 position) throws DataException { private CompoundTag getBlockTileEntity(BlockVector3 position) throws DataException {
if (tileEntities == null) { if (tileEntities == null) {
@ -152,8 +154,11 @@ public class OldChunk implements Chunk {
@Override @Override
public BaseBlock getBlock(BlockVector3 position) throws DataException { public BaseBlock getBlock(BlockVector3 position) throws DataException {
if(position.getY() >= 128) return BlockTypes.VOID_AIR.getDefaultState().toBaseBlock(); if (position.getY() >= 128) {
int id, dataVal; return BlockTypes.VOID_AIR.getDefaultState().toBaseBlock();
}
int id;
int dataVal;
int x = position.getX() - rootX * 16; int x = position.getX() - rootX * 16;
int y = position.getY(); int y = position.getY();