PlotSquared/Core/src/main/java/com/plotsquared/core/util/BlockUtil.java

143 lines
4.9 KiB
Java
Raw Normal View History

/*
* PlotSquared, a land and world management plugin for Minecraft.
* Copyright (C) IntellectualSites <https://intellectualsites.com>
* Copyright (C) IntellectualSites 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/>.
*/
2020-04-15 21:26:54 +02:00
package com.plotsquared.core.util;
2019-11-04 20:55:55 +01:00
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.internal.registry.InputParser;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.block.FuzzyBlockState;
import com.sk89q.worldedit.world.registry.LegacyMapper;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
2019-11-04 20:55:55 +01:00
import java.util.Map;
2020-07-19 14:49:26 +02:00
/**
* {@link BlockState} related utility methods
*/
2019-11-04 20:55:55 +01:00
public final class BlockUtil {
2020-07-19 14:49:26 +02:00
private static final ParserContext PARSER_CONTEXT = new ParserContext();
private static final InputParser<BaseBlock> PARSER;
2019-11-04 20:55:55 +01:00
Pull/2693 (#2694) * Commit WIP flag work. * More ported flag types, and additions to the flag API. * Make PlotFlag more generic to allow generic flag creation * Pull Captions methods into a Caption interface. * Port MusicFlag * Port flight flag * Port UntrustedVisitFlag * Port DenyExitFlag * Remove paper suggestion * Make ListFlag lists immutable * Update Flag containers. Add javadocs. Add missing methods. * Port description flag * Port greeting and farewell flags * Port weather flag * Move getExample implementation to BooleanFlag * Port reserved flags * Port all boolean flags. * Remove unused flag types * Invert liquid-flow flag * Find the real (legacy) flag name * Change NOITFY -> NOTIFY in Captions * Make IntegerFlag extendable * Port integer flags * Update Flag command to current API state * Begin remaking flag command * Create DoubleFlag + extract common parsing stuff * Supply arguments in flag parse exceptions * Implement missing flag subcommands * Update Flag command to current API state * Implement PriceFlag * Port deny-teleport * Port gamemode flags * Port BreakFlag * Port PlaceFlag * Port UseFlag * Remove old unused flag constants * Port blocked-cmds flag * Fix entity util * Port TimeFlag * Use CaptionUtility for formatting * Port keep flag * Fix imports * Reformat code * Remove unused classes * Fix MainUtil.java * Remove FlagCmd * Add flag info header and footer * Comment out flag related stuff in SchematicHandler * Remove FlagManager * Finalize Plot.java * Finalize PlotArea.java * Finalize PlotListener * Fix API issues * Fix a bunch of compile errors * Fix `/plot flag remove` * Fix initialization of GlobalFlagContainer * Apply API changes to events * Update SQLManager to new API * Invert default value for DenyExitFlag * Replace flag.getValue().toString() with flag.toString() * Make FlagContainer instance in Plot final * Fix various command issues * Clean up PlotSettings * Don't show internal flags in flag list * Fix `/plot flag add` * Remove the info inventory as it's 100% broken * Add plot info entries and fix up the default format * Fix default flag state in Captions * 781c200 part 2 * Fix odd grammar in captions * Fix odd grammar in captions v2 * Add create table statements for plot_flags * Remove old flag references in SQLManager * Use the new plot_flags table * Add tab completion to `/plot flag` * Improve parse error handling * Make flag permission check recognize parse exceptions * Initial progress towards flag conversion * Fix minor issues * Don't validate flags during flag conversion * Allow unrecognized flags to be parsed * Filter out internal flags from command sugguestions * Use the wrong caption when there's no plot description set * Limit command suggestions for boolean flags * Make blocktypelistflags accept blockcategories * Require categories to be prefixed with '#' and fix some minor display issues * Fix plot database conversion * Update PlotFlagEvent.java Updated return description * Fix command annotation wrapping * Add FLAG_UPDATE event for FlagContainer listeners * Make getParentContainer nullable * Document castUnsafe in FlagContainer * Document FlagContainer constructors * Add missing documentation to FlagContainer * Document FlagParseException * Fix wording in FlagContainer javadoc * Document InternalFlag * Document PlotFlag * Minor changes * Remove revisit comments Co-authored-by: Hannes Greule <SirYwell@users.noreply.github.com> Co-authored-by: NotMyFault <mc.cache@web.de> Co-authored-by: Matt <4009945+MattBDev@users.noreply.github.com>
2020-02-24 18:42:02 +01:00
static {
2019-11-04 20:55:55 +01:00
PARSER_CONTEXT.setRestricted(false);
PARSER_CONTEXT.setPreferringWildcard(false);
PARSER_CONTEXT.setTryLegacy(true);
PARSER = WorldEdit.getInstance().getBlockFactory().getParsers().get(0);
}
Pull/2693 (#2694) * Commit WIP flag work. * More ported flag types, and additions to the flag API. * Make PlotFlag more generic to allow generic flag creation * Pull Captions methods into a Caption interface. * Port MusicFlag * Port flight flag * Port UntrustedVisitFlag * Port DenyExitFlag * Remove paper suggestion * Make ListFlag lists immutable * Update Flag containers. Add javadocs. Add missing methods. * Port description flag * Port greeting and farewell flags * Port weather flag * Move getExample implementation to BooleanFlag * Port reserved flags * Port all boolean flags. * Remove unused flag types * Invert liquid-flow flag * Find the real (legacy) flag name * Change NOITFY -> NOTIFY in Captions * Make IntegerFlag extendable * Port integer flags * Update Flag command to current API state * Begin remaking flag command * Create DoubleFlag + extract common parsing stuff * Supply arguments in flag parse exceptions * Implement missing flag subcommands * Update Flag command to current API state * Implement PriceFlag * Port deny-teleport * Port gamemode flags * Port BreakFlag * Port PlaceFlag * Port UseFlag * Remove old unused flag constants * Port blocked-cmds flag * Fix entity util * Port TimeFlag * Use CaptionUtility for formatting * Port keep flag * Fix imports * Reformat code * Remove unused classes * Fix MainUtil.java * Remove FlagCmd * Add flag info header and footer * Comment out flag related stuff in SchematicHandler * Remove FlagManager * Finalize Plot.java * Finalize PlotArea.java * Finalize PlotListener * Fix API issues * Fix a bunch of compile errors * Fix `/plot flag remove` * Fix initialization of GlobalFlagContainer * Apply API changes to events * Update SQLManager to new API * Invert default value for DenyExitFlag * Replace flag.getValue().toString() with flag.toString() * Make FlagContainer instance in Plot final * Fix various command issues * Clean up PlotSettings * Don't show internal flags in flag list * Fix `/plot flag add` * Remove the info inventory as it's 100% broken * Add plot info entries and fix up the default format * Fix default flag state in Captions * 781c200 part 2 * Fix odd grammar in captions * Fix odd grammar in captions v2 * Add create table statements for plot_flags * Remove old flag references in SQLManager * Use the new plot_flags table * Add tab completion to `/plot flag` * Improve parse error handling * Make flag permission check recognize parse exceptions * Initial progress towards flag conversion * Fix minor issues * Don't validate flags during flag conversion * Allow unrecognized flags to be parsed * Filter out internal flags from command sugguestions * Use the wrong caption when there's no plot description set * Limit command suggestions for boolean flags * Make blocktypelistflags accept blockcategories * Require categories to be prefixed with '#' and fix some minor display issues * Fix plot database conversion * Update PlotFlagEvent.java Updated return description * Fix command annotation wrapping * Add FLAG_UPDATE event for FlagContainer listeners * Make getParentContainer nullable * Document castUnsafe in FlagContainer * Document FlagContainer constructors * Add missing documentation to FlagContainer * Document FlagParseException * Fix wording in FlagContainer javadoc * Document InternalFlag * Document PlotFlag * Minor changes * Remove revisit comments Co-authored-by: Hannes Greule <SirYwell@users.noreply.github.com> Co-authored-by: NotMyFault <mc.cache@web.de> Co-authored-by: Matt <4009945+MattBDev@users.noreply.github.com>
2020-02-24 18:42:02 +01:00
private BlockUtil() {
}
2020-07-19 14:49:26 +02:00
/**
* Get a {@link BlockState} from a legacy id
*
* @param id Legacy ID
* @return Block state, or {@code null}
*/
2021-01-10 00:01:48 +01:00
public static @Nullable BlockState get(final int id) {
2019-11-04 20:55:55 +01:00
return LegacyMapper.getInstance().getBlockFromLegacy(id);
}
2020-07-19 14:49:26 +02:00
/**
* Get a {@link BlockState} from a legacy id-data pair
*
* @param id Legacy ID
2020-07-19 14:49:26 +02:00
* @param data Legacy data
* @return Block state, or {@code null}
*/
2021-01-10 00:01:48 +01:00
public static @Nullable BlockState get(final int id, final int data) {
2019-11-04 20:55:55 +01:00
return LegacyMapper.getInstance().getBlockFromLegacy(id, data);
}
2020-07-19 14:49:26 +02:00
/**
* Get a {@link BlockState} from its ID
*
* @param id String or integer ID
2021-01-10 00:01:48 +01:00
* @return Parsed block state, or {@code null} if none
* could be parsed
2020-07-19 14:49:26 +02:00
*/
2021-01-10 00:01:48 +01:00
public static @Nullable BlockState get(final @NonNull String id) {
2019-11-04 20:55:55 +01:00
if (id.length() == 1 && id.charAt(0) == '*') {
return FuzzyBlockState.builder().type(BlockTypes.AIR).build();
}
2022-01-20 21:01:38 +01:00
String mutableId;
2021-08-18 11:58:18 +02:00
mutableId = id.toLowerCase();
BlockType type = BlockTypes.get(mutableId);
2019-11-04 20:55:55 +01:00
if (type != null) {
return type.getDefaultState();
}
2021-08-18 11:58:18 +02:00
if (Character.isDigit(mutableId.charAt(0))) {
String[] split = mutableId.split(":");
2019-11-04 20:55:55 +01:00
if (MathMan.isInteger(split[0])) {
if (split.length == 2) {
if (MathMan.isInteger(split[1])) {
return get(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
}
} else {
return get(Integer.parseInt(split[0]));
}
}
}
try {
2021-01-10 00:01:48 +01:00
BaseBlock block = PARSER.parseFromInput(mutableId, PARSER_CONTEXT);
2019-11-04 20:55:55 +01:00
return block.toImmutableState();
} catch (InputParseException e) {
return null;
}
}
2020-07-19 14:49:26 +02:00
/**
* Parse a comma delimited list of block states
*
* @param commaDelimited List of block states
* @return Parsed block states
*/
2021-01-10 00:01:48 +01:00
public static @NonNull BlockState[] parse(final @NonNull String commaDelimited) {
2020-07-19 14:49:26 +02:00
final String[] split = commaDelimited.split(",(?![^\\(\\[]*[\\]\\)])");
final BlockState[] result = new BlockState[split.length];
2019-11-04 20:55:55 +01:00
for (int i = 0; i < split.length; i++) {
result[i] = get(split[i]);
}
return result;
}
2020-07-19 14:49:26 +02:00
/**
* Deserialize a serialized {@link BlockState}
*
* @param map Serialized block state
* @return Deserialized block state, or {@code null} if the map is
* not a properly serialized block state
2020-07-19 14:49:26 +02:00
*/
2021-01-10 00:01:48 +01:00
public static @Nullable BlockState deserialize(final @NonNull Map<String, Object> map) {
2019-11-04 20:55:55 +01:00
if (map.containsKey("material")) {
final Object object = map.get("material");
return get(object.toString());
}
return null;
}
}