@SuppressWarnings("unchecked") public BannerCustomItem(Material material, Config config, PlaceholderRegistry placeholders) { super(material, config, placeholders); this.baseColor = config.getDye("baseColor"); Collection<Map<String, Object>> rawPatterns = (Collection<Map<String, Object>>) config.getCollection("patterns"); patterns = new ArrayList<>(); if(rawPatterns != null) { for (Map<String, Object> p : rawPatterns) { Config sub = Config.wrap(p); DyeColor color = sub.getDyeRequired("color"); PatternType type = PatternType.getByIdentifier(sub.getStringRequired("pattern")); if (type == null) { Uppercore.logger().severe("Cannot find pattern identifier \"" + p.get("pattern") + "\""); type = PatternType.BASE; } patterns.add(new Pattern(color, type)); } } }
@Override public void change(Event e, Object[] delta, @NotNull Changer.ChangeMode mode) { ItemStack i = item.getSingle(e); if (i == null) { return; } if (i.getType() == Material.BANNER || i.getType() == Material.SHIELD) { BannerMeta meta = ((BannerMeta) i.getItemMeta()); switch (mode) { case ADD: Arrays.asList(((Pattern[]) delta)).forEach(meta::addPattern); break; case SET: meta.setPatterns(Arrays.asList(((Pattern[]) delta))); break; case DELETE: case RESET: for (int j = 1; j <= meta.numberOfPatterns(); j++) { meta.removePattern(j); } break; } i.setItemMeta(meta); } }
@Override public void change(Event e, Object[] delta, @NotNull Changer.ChangeMode mode) { Block b = block.getSingle(e); if (b == null) { return; } if (b.getType() == Material.BANNER) { Banner banner = (Banner) b.getState(); Pattern[] patterns = (Pattern[]) delta; switch (mode) { case ADD: Arrays.asList(patterns).forEach(banner::addPattern); break; case SET: banner.setPatterns(Arrays.asList(patterns)); break; case DELETE: case RESET: for (int i = 1; i <= banner.numberOfPatterns(); i++) banner.removePattern(i); break; } banner.update(true, false); } }
public static BannerMeta parseMncPattern(@NotNull String mnc) { if (mnc.matches("[a-p]a([a-p][b-zA-M])+")) { List<String> groups = StringUtils.sizedSplitString(mnc, 2, true); BannerMeta meta = emptyBannerMeta(); meta.setBaseColor(colorFromMnc(mnc.charAt(0))); for (String str : groups.subList(1, groups.size())) { if (!str.isEmpty()) { meta.addPattern(new Pattern(colorFromMnc(str.toCharArray()[0]), patternTypeFromMnc(str.toCharArray()[1]) )); } } return meta; } return null; }
/** * Set a {@link Pattern} on the banner item at the specified index. * <p/> * If the index is below 0 nothing will happen, * if it's too high the pattern will be added on the end instead. * <p/> * Items: {@link Material#BANNER} * * @param index The index to set the pattern at. * @param pattern Pattern to set on the banner. * @return this instance. */ public EItem setPattern(Integer index, Pattern pattern) { if (index < 0) { return this; } ItemMeta meta = getItemMeta(); if (meta instanceof BannerMeta) { if (((BannerMeta)meta).getPatterns().size() > index) { ((BannerMeta)meta).setPattern(index, pattern); } else { ((BannerMeta)meta).addPattern(pattern); } setItemMeta(meta); } return this; }
/** Handles banners; only base color (as patterns would be too much data) */ private void handleBanner(JsonWriter out, BannerMeta meta) throws IOException { DyeColor baseColor = meta.getBaseColor(); // Due to SPIGOT-746, we sometimes have to get the base color from pattern 0... if (baseColor == null) { List<Pattern> patterns = meta.getPatterns(); if (patterns.size() <= 0) return; else baseColor = patterns.get(0).getColor(); } if (baseColor != null) out.name("baseColor").value( baseColor.toString() ); out.name("patternCount").value( meta.numberOfPatterns() ); }
static public void saveBanner(Player player, ItemStack banner) { //只處理旗幟 if (!BannerUtil.isBanner(banner)) { player.sendMessage(MessageUtil.format(true, "&c" + tl("io.save-failed"))); return; } //設定檔 String fileName = getFileName(player); FileConfiguration config = KConfigManager.get(fileName); //索引值(時間戳記,不會重複) String key = String.valueOf(System.currentTimeMillis()); //旗幟資訊 BannerMeta bm = (BannerMeta) banner.getItemMeta(); //儲存 config.set(key + ".color", banner.getDurability()); List<String> patternList = new ArrayList<>(); for (Pattern pattern : bm.getPatterns()) { patternList.add(pattern.getPattern().getIdentifier() + ":" + pattern.getColor().toString()); } if (patternList.size() > 0) { config.set(key + ".patterns", patternList); } KConfigManager.save(fileName); //訊息 player.sendMessage(MessageUtil.format(true, "&a" + tl("io.save-success"))); }
/** * Adds {@link Pattern}s to this banner, assuming it is a banner. * <p /> * <b>UNSAFE</b> * * @param patterns patterns to add * * @return this item builder instance, for chaining */ public ItemBuilder bannerAdd(Pattern... patterns) { if (patterns == null) { if (!this.failSilently) { throw new IllegalArgumentException("patterns cannot be null."); } return this; } if (isBannerMeta()) { try { for (Pattern pattern : patterns) { if (pattern != null) { ((BannerMeta) this.itemMeta).addPattern(pattern); } else { throw new NullPointerException("pattern element is null."); } } } catch (Exception e) { if (!this.failSilently) { e.printStackTrace(); } } } return this; }
/** * A method to serialize banner meta to a JSONObject. Saves the base color, each pattern color, and each * pattern type. * * @param banner The BannerMeta to serialize * @return The JSONObject representation of the BannerMeta, or null if an exception occurred */ public static JSONObject serializeBanner(BannerMeta banner) { try { JSONObject root = new JSONObject(); if (banner.getBaseColor() != null) root.put("base-color", banner.getBaseColor().getDyeData()); JSONArray colors = new JSONArray(); JSONArray patternTypes = new JSONArray(); for (Pattern pattern : banner.getPatterns()) { colors.put(pattern.getColor().getDyeData()); patternTypes.put(pattern.getPattern().getIdentifier()); } root.put("colors", colors); root.put("pattern-types", patternTypes); return root; } catch (JSONException ex) { ex.printStackTrace(); return null; } }
/** * A method to deserialize a BannerMeta object from a JSONObject. This method assumes that the JSONArrays containing * the colors and pattern types are the same length. * * @param json The JSONObject of the BannerMeta to deserialize * @return The BannerMeta or null if an exception occurs */ public static BannerMeta getBannerMeta(JSONObject json) { try { BannerMeta dummy = (BannerMeta) new ItemStack(Material.BANNER).getItemMeta(); if (json.has("base-color")) dummy.setBaseColor(DyeColor.getByDyeData(Byte.parseByte("" + json.get("base-color")))); JSONArray colors = json.getJSONArray("colors"); JSONArray patternTypes = json.getJSONArray("pattern-types"); for (int i = 0; i < colors.length(); i++) { dummy.addPattern(new Pattern(DyeColor.getByDyeData(Integer.valueOf((int) colors.get(i)).byteValue()), PatternType.getByIdentifier(patternTypes.getString(i)))); } return dummy; } catch (JSONException ex) { ex.printStackTrace(); return null; } }
@Override public boolean update(boolean force, boolean applyPhysics) { boolean result = super.update(force, applyPhysics); if (result) { banner.color = base.getDyeData(); NBTTagList newPatterns = new NBTTagList(); for (Pattern p : patterns) { NBTTagCompound compound = new NBTTagCompound(); compound.setInt("Color", p.getColor().getDyeData()); compound.setString("Pattern", p.getPattern().getIdentifier()); newPatterns.add(compound); } banner.patterns = newPatterns; banner.update(); } return result; }
CraftMetaBanner(NBTTagCompound tag) { super(tag); if (!tag.hasKey("BlockEntityTag")) { return; } NBTTagCompound entityTag = tag.getCompound("BlockEntityTag"); base = entityTag.hasKey(BASE.NBT) ? DyeColor.getByDyeData((byte) entityTag.getInt(BASE.NBT)) : null; if (entityTag.hasKey(PATTERNS.NBT)) { NBTTagList patterns = entityTag.getList(PATTERNS.NBT, 10); for (int i = 0; i < Math.min(patterns.size(), 20); i++) { NBTTagCompound p = patterns.get(i); this.patterns.add(new Pattern(DyeColor.getByDyeData((byte) p.getInt(COLOR.NBT)), PatternType.getByIdentifier(p.getString(PATTERN.NBT)))); } } }
CraftMetaBanner(Map<String, Object> map) { super(map); String baseStr = SerializableMeta.getString(map, BASE.BUKKIT, true); if (baseStr != null) { base = DyeColor.valueOf(baseStr); } Iterable<?> rawPatternList = SerializableMeta.getObject(Iterable.class, map, PATTERNS.BUKKIT, true); if (rawPatternList == null) { return; } for (Object obj : rawPatternList) { if (!(obj instanceof Pattern)) { throw new IllegalArgumentException("Object in pattern list is not valid. " + obj.getClass()); } addPattern((Pattern) obj); } }
@Override void applyToItem(NBTTagCompound tag) { super.applyToItem(tag); NBTTagCompound entityTag = new NBTTagCompound(); if (base != null) { entityTag.setInt(BASE.NBT, base.getDyeData()); } NBTTagList newPatterns = new NBTTagList(); for (Pattern p : patterns) { NBTTagCompound compound = new NBTTagCompound(); compound.setInt(COLOR.NBT, p.getColor().getDyeData()); compound.setString(PATTERN.NBT, p.getPattern().getIdentifier()); newPatterns.add(compound); } entityTag.set(PATTERNS.NBT, newPatterns); tag.set("BlockEntityTag", entityTag); }
private static Map<String, Object> serializeBanner(Banner banner) { Map<String, Object> serializedBanner = new LinkedHashMap<>(); if (banner != null) { DyeColor baseDyeColor = banner.getBaseColor(); if (baseDyeColor != null) { serializedBanner.put("Base", Utilities.serializeColor(baseDyeColor.getColor())); } List<Pattern> bannerPatterns = banner.getPatterns(); if (bannerPatterns != null && !bannerPatterns.isEmpty()) { Map<String, Map<String, Object>> serializedPatterns = new LinkedHashMap<>(); for (int patternIndex = 0; patternIndex < bannerPatterns.size(); patternIndex++) { Pattern bannerPattern = bannerPatterns.get(patternIndex); Map<String, Object> serializedPattern = new LinkedHashMap<>(); if (bannerPattern.getColor() != null) { serializedPattern.put("Color", Utilities.serializeColor(bannerPattern.getColor().getColor())); } serializedPattern.put("Pattern", StringUtilities.capitalizeFully(bannerPattern.getPattern().name().replace('_', ' '))); serializedPatterns.put("Pattern " + (patternIndex + 1), serializedPattern); } serializedBanner.put("Patterns", serializedPatterns); } } return serializedBanner; }
private static Map<String, Object> serializeBanner(BannerMeta bannerMeta) { Map<String, Object> serializedBanner = new LinkedHashMap<>(); if (bannerMeta != null) { DyeColor baseDyeColor = bannerMeta.getBaseColor(); if (baseDyeColor != null) { serializedBanner.put("Base", Utilities.serializeColor(baseDyeColor.getColor())); } List<Pattern> bannerPatterns = bannerMeta.getPatterns(); if (bannerPatterns != null && !bannerPatterns.isEmpty()) { Map<String, Map<String, Object>> serializedPatterns = new LinkedHashMap<>(); int patternIndex = 1; for (Pattern bannerPattern : bannerPatterns) { Map<String, Object> serializedPattern = new LinkedHashMap<>(); if (bannerPattern.getColor() != null) { serializedPattern.put("Color", Utilities.serializeColor(bannerPattern.getColor().getColor())); } serializedPattern.put("Pattern", StringUtilities.capitalizeFully(bannerPattern.getPattern().name().replace('_', ' '))); serializedPatterns.put("Pattern " + patternIndex++, serializedPattern); } serializedBanner.put("Patterns", serializedPatterns); } } return serializedBanner; }
@Override public boolean update(boolean force, boolean applyPhysics) { boolean result = (isPlaced()) ? super.update(force, applyPhysics) : true; if (result) { banner.color = base.getDyeData(); NBTTagList newPatterns = new NBTTagList(); for (Pattern p : patterns) { NBTTagCompound compound = new NBTTagCompound(); compound.setInt("Color", p.getColor().getDyeData()); compound.setString("Pattern", p.getPattern().getIdentifier()); newPatterns.add(compound); } banner.patterns = newPatterns; banner.update(); } return result; }
private int getSkriptRevision() { String postfix = (String) ReflectionUtils.getInstanceField(Skript.getVersion(), "postfix"); if (postfix == null) return -1; java.util.regex.Pattern pat = java.util.regex.Pattern.compile("dev(\\d+).?"); Matcher m = pat.matcher(postfix); int rev; try { rev = m.matches() ? Integer.parseInt(m.group(1)) : -1; } catch (NumberFormatException e) { rev = -1; } return rev; }
@NotNull @Override protected ItemStack[] get(Event event) { ItemStack banner = new ItemStack(type); BannerMeta meta = (BannerMeta) banner.getItemMeta(); meta.setBaseColor(CollectionUtils.getRandom(DyeColor.values())); for (int i = 0; i < new Random().nextInt(7); i++) meta.addPattern(new Pattern(CollectionUtils.getRandom(DyeColor.values()), CollectionUtils.getRandom(PatternType.values()) )); banner.setItemMeta(meta); return new ItemStack[]{banner}; }
@Nullable @Override protected Pattern[] get(Event e) { Color c = color.getSingle(e); PatternType p = pattern.getSingle(e); if (c == null || p == null) { return null; } return new Pattern[]{new Pattern(c.getWoolColor(), p)}; }
@Nullable @Override protected Pattern[] get(Event e) { ItemStack i = item.getSingle(e); if (i == null) { return null; } if (i.getType() == Material.BANNER || i.getType() == Material.SHIELD) { return ((BannerMeta) i.getItemMeta()).getPatterns().stream().toArray(Pattern[]::new); } return null; }
@Nullable @Override public Class<?>[] acceptChange(Changer.ChangeMode mode) { if (mode == Changer.ChangeMode.DELETE || mode == Changer.ChangeMode.RESET) { return CollectionUtils.array(Pattern.class); } else if (mode == Changer.ChangeMode.ADD || mode == Changer.ChangeMode.SET) { return CollectionUtils.array(Pattern[].class); } return null; }
@Override public boolean init(Expression<?>[] expr, int i, Kleenean kleenean, @NotNull SkriptParser.ParseResult parseResult) { mat = parseResult.mark == 0 ? Material.BANNER : Material.SHIELD; patterns = (Expression<Pattern>) expr[0]; color = (Expression<Color>) expr[1]; return true; }
@Nullable @Override protected Pattern[] get(Event e) { Block b = block.getSingle(e); if (b == null) { return null; } if (b.getType() == Material.STANDING_BANNER || b.getType() == Material.WALL_BANNER) { return ((Banner) b.getState()).getPatterns().stream().toArray(Pattern[]::new); } return null; }
@Nullable @Override public Class<?>[] acceptChange(Changer.ChangeMode mode) { if (mode == Changer.ChangeMode.DELETE || mode == Changer.ChangeMode.RESET) { return CollectionUtils.array(Pattern.class); } else if (mode == Changer.ChangeMode.ADD || mode == Changer.ChangeMode.SET) { return CollectionUtils.array(Pattern[].class); } else { return null; } }
public static String toMncPattern(@NotNull BannerMeta meta) { List<String> stringList = new ArrayList<>(); stringList.add(colorToMnc(meta.getBaseColor()) + "a"); for (Pattern pattern : meta.getPatterns()) { stringList.add(new String(new char[]{colorToMnc(pattern.getColor()), patternTypeToMnc(pattern.getPattern())})); } return StringUtils.join(stringList.toArray(new String[stringList.size()])); }
@Override public void read(DataInputStream input) throws IOException { DyeColor color = DyeColor.getByDyeData(input.readByte()); PatternType patternType = PatternType.getByIdentifier(input.readUTF()); setValue(new Pattern(color, patternType)); }
public static Pattern craftPanner(ConfigurationSection section) { if(section == null) { Error.INVALID.add(); return null; } else { DyeColor dyeColor = dyeFrom(section.getString("COLOR"), true); PatternType patt = Utils.matchEnum(PatternType.values(), section.getString("TYPE"), true); return new Pattern(dyeColor, patt); } }
/** * Get the list of banner {@link Pattern}s from the banner item. * <p/> * Items: {@link Material#BANNER} * * @return List of {@link Pattern}s (Empty list when no banner) */ public List<Pattern> getPatterns() { ItemMeta meta = getItemMeta(); if (meta instanceof BannerMeta) { return ((BannerMeta)meta).getPatterns(); } return new ArrayList<>(); }
/** * Get the {@link Pattern} from the banner item at the specified index. * <p/> * If the index is below 0 or too high this will return null. * <p/> * Items: {@link Material#BANNER} * * @param index The index of the pattern to get. * @return The {@link Pattern} at the specified index from the banner item. ({@code null} when no banner or invalid index) */ public Pattern getPattern(int index) { if (index < 0) { return null; } ItemMeta meta = getItemMeta(); if (meta instanceof BannerMeta) { if (index >= ((BannerMeta)meta).numberOfPatterns()) { return null; } return ((BannerMeta)meta).getPattern(index); } return null; }
/** * Add a {@link Pattern} on the banner item. * <p/> * Items: {@link Material#BANNER} * * @param pattern Pattern to add on the banner. * @return this instance. */ public EItem addPattern(Pattern pattern) { ItemMeta meta = getItemMeta(); if (meta instanceof BannerMeta) { ((BannerMeta)meta).addPattern(pattern); setItemMeta(meta); } return this; }
/** * Set the {@link Pattern}s on the banner item. * <p/> * Items: {@link Material#BANNER} * * @param patterns Patterns to set on the banner. * @return this instance. */ public EItem setPatterns(List<Pattern> patterns) { ItemMeta meta = getItemMeta(); if (meta instanceof BannerMeta) { ((BannerMeta)meta).setPatterns(patterns); setItemMeta(meta); } return this; }
@SuppressWarnings("deprecation") public static Optional<String> serializeState(BlockState state) { YamlConfiguration yaml = new YamlConfiguration(); // http://minecraft.gamepedia.com/Block_entity was used as a reference for this method if (state instanceof InventoryHolder) { yaml.set(INVENTORY_KEY, InventoryHelper.serializeInventory(((InventoryHolder) state).getInventory())); } if (state instanceof Sign) { yaml.set(SIGN_LINES_KEY, Arrays.asList(((Sign) state).getLines())); } else if (Support.BANNER && state instanceof Banner) { yaml.set(BANNER_BASE_COLOR_KEY, ((Banner) state).getBaseColor().name()); ConfigurationSection patternSection = yaml.createSection(BANNER_PATTERNS_KEY); List<Pattern> patterns = ((Banner) state).getPatterns(); for (int i = 0; i < patterns.size(); i++) { ConfigurationSection subSection = patternSection.createSection("" + i); subSection.set(BANNER_PATTERN_COLOR_KEY, patterns.get(i).getColor().name()); subSection.set(BANNER_PATTERN_TYPE_KEY, patterns.get(i).getPattern().name()); } } else if (state instanceof CreatureSpawner) { yaml.set(SPAWNER_TYPE_KEY, ((CreatureSpawner) state).getSpawnedType().name()); yaml.set(SPAWNER_DELAY_KEY, ((CreatureSpawner) state).getDelay()); } else if (state instanceof NoteBlock) { yaml.set(NOTE_OCTAVE_KEY, ((NoteBlock) state).getNote().getOctave()); yaml.set(NOTE_TONE_KEY, ((NoteBlock) state).getNote().getTone().name()); } else if (state instanceof Jukebox) { if (((Jukebox) state).isPlaying()) { yaml.set(JUKEBOX_DISC_KEY, ((Jukebox) state).getPlaying()); } } else if (state instanceof Skull) { yaml.set(SKULL_OWNER_KEY, ((Skull) state).getOwner()); yaml.set(SKULL_ROTATION_KEY, ((Skull) state).getRotation().name()); } else if (state instanceof CommandBlock) { yaml.set(COMMAND_NAME_KEY, ((CommandBlock) state).getName()); yaml.set(COMMAND_CMD_KEY, ((CommandBlock) state).getCommand()); } else if (state instanceof FlowerPot) { yaml.set(FLOWER_TYPE_KEY, ((FlowerPot) state).getContents().getItemType().name()); yaml.set(FLOWER_DATA_KEY, ((FlowerPot) state).getContents().getData()); } if (yaml.getKeys(false).size() > 0) { return Optional.of(yaml.saveToString()); } return Optional.absent(); }
private static ItemStack loadBanner(Player player, String key) { //設定檔 String fileName = getFileName(player); FileConfiguration config = KConfigManager.get(fileName); //檢查是否為物品 ItemStack banner = null; //檢查是否為正確格式 if (config.isInt(key + ".color") && (!config.contains(key + ".patterns") || config.isList(key + ".patterns"))) { //嘗試以新格式讀取 try { //建立旗幟 banner = new ItemStack(Material.BANNER, 1, (short) config.getInt(key + ".color")); BannerMeta bm = (BannerMeta) banner.getItemMeta(); //新增Patterns if (config.contains(key + ".patterns")) { List<String> patternsList = config.getStringList(key + ".patterns"); for (String str : patternsList) { String strPattern = str.split(":")[0]; String strColor = str.split(":")[1]; Pattern pattern = new Pattern(DyeColor.valueOf(strColor), PatternType.getByIdentifier(strPattern)); bm.addPattern(pattern); } banner.setItemMeta(bm); } //將key藏於Lore bm.setLore(Collections.singletonList(HiddenStringUtil.encodeString(key))); banner.setItemMeta(bm); } catch (Exception e) { banner = null; } } //只處理旗幟 if (!BannerUtil.isBanner(banner)) { return null; } return banner; }
/** * A method to deserialize a BannerMeta object from a JSONObject. This method assumes that the JSONArrays containing * the colors and pattern types are the same length. * * @param json The JSONObject of the BannerMeta to deserialize * @return The BannerMeta */ public static BannerMeta getBannerMeta(JsonObject json) { BannerMeta dummy = (BannerMeta) new ItemStack(Material.BANNER).getItemMeta(); if (json.has("base-color")) dummy.setBaseColor(DyeColor.getByDyeData(Byte.parseByte("" + json.get("base-color")))); JsonArray colors = json.getAsJsonArray("colors"); JsonArray patternTypes = json.getAsJsonArray("pattern-types"); for (int i = 0; i < colors.size() - 1; i++) { dummy.addPattern(new Pattern(DyeColor.getByDyeData(Integer.valueOf(colors.get(i).getAsInt()).byteValue()), PatternType.getByIdentifier(patternTypes.get(i).getAsString()))); } return dummy; }
/** * Adds a {@link Pattern} to a specific index to this banner, assuming it is a banner. * <p /> * <b>UNSAFE</b> * * @param index index to set * @param pattern pattern to add * * @return this item builder instance, for chaining */ public ItemBuilder bannerSet(int index, Pattern pattern) { if (isBannerMeta()) { try { ((BannerMeta) this.itemMeta).setPattern(index, pattern); } catch (Exception e) { if (!this.failSilently) { e.printStackTrace(); } } } return this; }
/** * Sets this banner's patterns, assuming it is a banner. * <p /> * <b>UNSAFE</b> * * @param patterns patterns to set * * @return this item builder instance, for chaining */ public ItemBuilder bannerSet(List<Pattern> patterns) { if (isBannerMeta()) { try { ((BannerMeta) this.itemMeta).setPatterns(patterns); } catch (Exception e) { if (!this.failSilently) { e.printStackTrace(); } } } return this; }