com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat Java Examples

The following examples show how to use com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SchematicHelper.java    From FunnyGuilds with Apache License 2.0 8 votes vote down vote up
public static boolean pasteSchematic(File schematicFile, Location location, boolean withAir) {
    try {
        Vector pasteLocation = new Vector(location.getX(), location.getY(), location.getZ());
        World pasteWorld = new BukkitWorld(location.getWorld());
        WorldData pasteWorldData = pasteWorld.getWorldData();

        Clipboard clipboard = ClipboardFormat.SCHEMATIC.getReader(new FileInputStream(schematicFile)).read(pasteWorldData);
        ClipboardHolder clipboardHolder = new ClipboardHolder(clipboard, pasteWorldData);

        EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(pasteWorld, -1);

        Operation operation = clipboardHolder
                .createPaste(editSession, pasteWorldData)
                .to(pasteLocation)
                .ignoreAirBlocks(!withAir)
                .build();

        Operations.completeLegacy(operation);
        return true;
    }
    catch (IOException | MaxChangedBlocksException e) {
        FunnyGuilds.getInstance().getPluginLogger().error("Could not paste schematic: " + schematicFile.getAbsolutePath(), e);
        return false;
    }
}
 
Example #2
Source File: SchematicCommands.java    From FastAsyncWorldedit with GNU General Public License v3.0 6 votes vote down vote up
@Command(aliases = {"formats", "listformats", "f"}, desc = "List available formats", max = 0)
@CommandPermissions("worldedit.schematic.formats")
public void formats(final Actor actor) throws WorldEditException {
    BBC.SCHEMATIC_FORMAT.send(actor);
    Message m = new Message(BBC.SCHEMATIC_FORMAT).newline();
    String baseCmd = Commands.getAlias(SchematicCommands.class, "schematic") + " " + Commands.getAlias(SchematicCommands.class, "save");
    boolean first = true;
    for (final ClipboardFormat format : ClipboardFormat.values()) {
        StringBuilder builder = new StringBuilder();
        builder.append(format.name()).append(": ");
        for (final String lookupName : format.getAliases()) {
            if (!first) {
                builder.append(", ");
            }
            builder.append(lookupName);
            first = false;
        }
        String cmd = baseCmd + " " + format.name() + " <filename>";
        m.text(builder).suggestTip(cmd).newline();
        first = true;
    }
    m.send(actor);
}
 
Example #3
Source File: ClipboardFormats.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Not public API, only used by SchematicCommands.
 * It is not in SchematicCommands because it may rely on internal register calls.
 */
public static String[] getFileExtensionArray() {
    List<String> exts = new ArrayList<>();
    HashMultimap<String, ClipboardFormat> map = HashMultimap.create();
    for (ClipboardFormat format : ClipboardFormat.values()) {
        exts.add(format.getExtension());
    }
    return exts.toArray(new String[exts.size()]);
}
 
Example #4
Source File: PasteSchematicEvent.java    From BetonQuest with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Void execute(String playerID) throws QuestRuntimeException {
    try {
        Location location = loc.getLocation(playerID);
        ClipboardFormat format = ClipboardFormats.findByFile(file);
        if (format == null) {
            throw new IOException("Unknown Schematic Format");
        }

        Clipboard clipboard;
        try (ClipboardReader reader = format.getReader(new FileInputStream(file))) {
            clipboard = reader.read();
        }


        try (EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(BukkitAdapter.adapt(location.getWorld()), -1)) {
            Operation operation = new ClipboardHolder(clipboard)
                    .createPaste(editSession)
                    .to(BukkitAdapter.asBlockVector(location))
                    .ignoreAirBlocks(noAir)
                    .build();

            Operations.complete(operation);
        }
    } catch (IOException | WorldEditException e) {
        LogUtils.getLogger().log(Level.WARNING, "Error while pasting a schematic: " + e.getMessage());
        LogUtils.logThrowable(e);
    }
    return null;
}
 
Example #5
Source File: WorldEditHandler.java    From uSkyBlock with GNU General Public License v3.0 5 votes vote down vote up
public static void loadIslandSchematic(final File file, final Location origin, PlayerPerk playerPerk) {
    log.finer("Trying to load schematic " + file);
    if (file == null || !file.exists() || !file.canRead()) {
        LogUtil.log(Level.WARNING, "Unable to load schematic " + file);
    }
    boolean noAir = false;
    BlockVector3 to = BlockVector3.at(origin.getBlockX(), origin.getBlockY(), origin.getBlockZ());
    EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(new BukkitWorld(origin.getWorld()), -1);
    editSession.setFastMode(true);
    ProtectedRegion region = WorldGuardHandler.getIslandRegionAt(origin);
    if (region != null) {
        editSession.setMask(new RegionMask(getRegion(origin.getWorld(), region)));
    }
    try {
        ClipboardFormat clipboardFormat = ClipboardFormats.findByFile(file);
        try (InputStream in = new FileInputStream(file)) {
            Clipboard clipboard = clipboardFormat.getReader(in).read();
            Operation operation = new ClipboardHolder(clipboard)
                    .createPaste(editSession)
                    .to(to)
                    .ignoreAirBlocks(noAir)
                    .build();
            Operations.completeBlindly(operation);
        }
        editSession.flushSession();
    } catch (IOException e) {
        log.log(Level.INFO, "Unable to paste schematic " + file, e);
    }
}
 
Example #6
Source File: PatternCommands.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Command(
        aliases = {"#fullcopy"},
        desc = "Places your full clipboard at each block",
        usage = "[schem|folder|url=#copy] [rotate=false] [flip=false]",
        min = 0,
        max = 2
)
public Pattern fullcopy(Player player, Extent extent, LocalSession session, @Optional("#copy") String location, @Optional("false") boolean rotate, @Optional("false") boolean flip) throws EmptyClipboardException, InputParseException, IOException {
    List<ClipboardHolder> clipboards;
    switch (location.toLowerCase()) {
        case "#copy":
        case "#clipboard":
            ClipboardHolder clipboard = session.getExistingClipboard();
            if (clipboard == null) {
                throw new InputParseException("To use #fullcopy, please first copy something to your clipboard");
            }
            if (!rotate && !flip) {
                return new FullClipboardPattern(extent, clipboard.getClipboard());
            }
            clipboards = Collections.singletonList(clipboard);
            break;
        default:
            MultiClipboardHolder multi = ClipboardFormat.SCHEMATIC.loadAllFromInput(player, player.getWorld().getWorldData(), location, true);
            clipboards = multi != null ? multi.getHolders() : null;
            break;
    }
    if (clipboards == null) {
        throw new InputParseException("#fullcopy:<source>");
    }
    return new RandomFullClipboardPattern(extent, player.getWorld().getWorldData(), clipboards, rotate, flip);
}
 
Example #7
Source File: SchematicCommands.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Command(
        aliases = {"loadall"},
        usage = "[<format>] <filename|url>",
        help = "Load multiple clipboards\n" +
                "The -r flag will apply random rotation",
        desc = "Load multiple clipboards (paste will randomly choose one)"
)
@Deprecated
@CommandPermissions({"worldedit.clipboard.load", "worldedit.schematic.load", "worldedit.schematic.upload"})
public void loadall(final Player player, final LocalSession session, @Optional("schematic") final String formatName, final String filename, @Switch('r') boolean randomRotate) throws FilenameException {
    final ClipboardFormat format = ClipboardFormat.findByAlias(formatName);
    if (format == null) {
        BBC.CLIPBOARD_INVALID_FORMAT.send(player, formatName);
        return;
    }
    try {
        WorldData wd = player.getWorld().getWorldData();

        MultiClipboardHolder all = format.loadAllFromInput(player, wd, filename, true);
        if (all != null) {
            session.addClipboard(all);
            BBC.SCHEMATIC_LOADED.send(player, filename);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #8
Source File: BrushCommands.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Command(
        aliases = {"populateschematic", "populateschem", "popschem", "pschem", "ps"},
        usage = "<mask> <file|folder|url> [radius=30] [points=5]",
        desc = "Scatter a schematic on a surface",
        help =
                "Chooses the scatter schematic brush.\n" +
                        "The -r flag will apply random rotation",
        flags = "r",
        min = 2,
        max = 4
)
@CommandPermissions("worldedit.brush.populateschematic")
public BrushSettings scatterSchemBrush(Player player, EditSession editSession, LocalSession session, Mask mask, String clipboard, @Optional("30") Expression radius, @Optional("50") double density, @Switch('r') boolean rotate, CommandContext context) throws WorldEditException {
    checkMaxBrushRadius(radius);


    try {
        MultiClipboardHolder clipboards = ClipboardFormat.SCHEMATIC.loadAllFromInput(player, player.getWorld().getWorldData(), clipboard, true);
        if (clipboards == null) {
            BBC.SCHEMATIC_NOT_FOUND.send(player, clipboard);
            return null;
        }
        List<ClipboardHolder> holders = clipboards.getHolders();
        if (holders == null) {
            BBC.SCHEMATIC_NOT_FOUND.send(player, clipboard);
            return null;
        }

        return set(session, context,
                new PopulateSchem(mask, holders, (int) density, rotate))
                .setSize(radius);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #9
Source File: CuboidClipboard.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructs the clipboard.
 *
 * @param size   the dimensions of the clipboard (should be at least 1 on every dimension)
 * @param origin the origin point where the copy was made, which must be the
 *               {@link CuboidRegion#getMinimumPoint()} relative to the copy
 * @param offset the offset from the minimum point of the copy where the user was
 */
public CuboidClipboard(Vector size, Vector origin, Vector offset) {
    checkNotNull(size);
    checkNotNull(origin);
    checkNotNull(offset);
    MainUtil.warnDeprecated(BlockArrayClipboard.class, ClipboardFormat.class);
    this.origin = origin;
    this.offset = offset;
    this.size = size;
    this.dx = size.getBlockX();
    this.dxz = dx * size.getBlockZ();
    ids = new byte[dx * size.getBlockZ() * ((size.getBlockY() + 15) >> 4)][];
    nbtMap = new HashMap<>();
}
 
Example #10
Source File: CuboidClipboard.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructs the clipboard.
 *
 * @param size   the dimensions of the clipboard (should be at least 1 on every dimension)
 * @param origin the origin point where the copy was made, which must be the
 *               {@link CuboidRegion#getMinimumPoint()} relative to the copy
 */
public CuboidClipboard(Vector size, Vector origin) {
    checkNotNull(size);
    checkNotNull(origin);
    MainUtil.warnDeprecated(BlockArrayClipboard.class, ClipboardFormat.class);
    this.origin = origin;
    this.offset = new Vector();
    this.size = size;
    this.dx = size.getBlockX();
    this.dxz = dx * size.getBlockZ();
    ids = new byte[dx * size.getBlockZ() * ((size.getBlockY() + 15) >> 4)][];
    nbtMap = new HashMap<>();
}
 
Example #11
Source File: CuboidClipboard.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructs the clipboard.
 *
 * @param size the dimensions of the clipboard (should be at least 1 on every dimension)
 */
public CuboidClipboard(Vector size) {
    checkNotNull(size);
    MainUtil.warnDeprecated(BlockArrayClipboard.class, ClipboardFormat.class);
    origin = new Vector();
    offset = new Vector();
    this.size = size;
    this.dx = size.getBlockX();
    this.dxz = dx * size.getBlockZ();
    ids = new byte[dx * size.getBlockZ() * ((size.getBlockY() + 15) >> 4)][];
    nbtMap = new HashMap<>();
}
 
Example #12
Source File: WorldEdit7.java    From IridiumSkyblock with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void paste(File file, Location location, Island island) {
    try {
        ClipboardFormat format = ClipboardFormats.findByFile(file);
        ClipboardReader reader = format.getReader(new FileInputStream(file));
        Clipboard clipboard = reader.read();
        try (EditSession editSession = com.sk89q.worldedit.WorldEdit.getInstance().getEditSessionFactory().getEditSession(new BukkitWorld(location.getWorld()), -1)) {
            Operation operation = new ClipboardHolder(clipboard)
                    .createPaste(editSession)
                    .to(BlockVector3.at(location.getX(), location.getY(), location.getZ()))
                    .copyEntities(true)
                    .ignoreAirBlocks(true)
                    .build();
            Operations.complete(operation);
        }
    } catch (Exception e) {
        IridiumSkyblock.getInstance().getLogger().warning("Failed to paste schematic using worldedit");
        IridiumSkyblock.schematic.paste(file, location, island);
    }
}
 
Example #13
Source File: ClipboardFormats.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return a multimap from a file extension to the potential matching formats.
 */
public static Multimap<String, ClipboardFormat> getFileExtensionMap() {
    HashMultimap<String, ClipboardFormat> map = HashMultimap.create();
    for (ClipboardFormat format : ClipboardFormat.values()) {
        map.put(format.getExtension(), format);
    }
    return map;
}
 
Example #14
Source File: ClipboardFormats.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Detect the format of given a file.
 *
 * @param file
 *            the file
 * @return the format, otherwise null if one cannot be detected
 */
@Nullable
public static ClipboardFormat findByFile(File file) {
    checkNotNull(file);

    for (ClipboardFormat format : ClipboardFormat.values()) {
        if (format.isFormat(file)) {
            return format;
        }
    }

    return null;
}
 
Example #15
Source File: CFICommands.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Command(
        aliases = {"schem", "schematic", "schems", "schematics", "addschems"},
        usage = "[url] <mask> <file|folder|url> <rarity> <distance> <rotate=true>",
        desc = "Populate schematics",
        help = "Populate a schematic on the terrain\n" +
                " - Change the mask (e.g. angle mask) to only place the schematic in specific locations.\n" +
                " - The rarity is a value between 0 and 100.\n" +
                " - The distance is the spacing between each schematic"
)
@CommandPermissions("worldedit.anvil.cfi")
public void schem(FawePlayer fp, @Optional BufferedImage imageMask, Mask mask, String schematic, int rarity, int distance, boolean rotate) throws ParameterException, IOException, WorldEditException {
    HeightMapMCAGenerator gen = assertSettings(fp).getGenerator();

    World world = fp.getWorld();
    WorldData wd = world.getWorldData();
    MultiClipboardHolder multi = ClipboardFormat.SCHEMATIC.loadAllFromInput(fp.getPlayer(), wd, schematic, true);
    if (multi == null) {
        return;
    }
    if (imageMask == null) {
        gen.addSchems(mask, wd, multi.getHolders(), rarity, distance, rotate);
    } else {
        gen.addSchems(imageMask, mask, wd, multi.getHolders(), rarity, distance, rotate);
    }
    msg("Added schematics!").send(fp);
    populate(fp);
}
 
Example #16
Source File: Schematic.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Save this schematic to a stream
 *
 * @param stream
 * @param format
 * @throws IOException
 */
public void save(OutputStream stream, ClipboardFormat format) throws IOException {
    checkNotNull(stream);
    checkNotNull(format);
    try (ClipboardWriter writer = format.getWriter(stream)) {
        writer.write(clipboard, clipboard.getRegion().getWorld().getWorldData());
    }
}
 
Example #17
Source File: Schematic.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
public void save(File file, ClipboardFormat format) throws IOException {
    checkNotNull(file);
    checkNotNull(format);
    if (!file.exists()) {
        File parent = file.getParentFile();
        if (parent != null) {
            parent.mkdirs();
        }
        file.createNewFile();
    }
    save(new FileOutputStream(file), format);
}
 
Example #18
Source File: LazyClipboardHolder.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a new instance with the given clipboard.
 *
 * @param worldData the mapping of blocks, entities, and so on
 */
public LazyClipboardHolder(URI uri, ByteSource source, ClipboardFormat format, WorldData worldData, UUID uuid) {
    super(uri, EmptyClipboard.INSTANCE, worldData);
    this.source = source;
    this.format = format;
    this.uuid = uuid != null ? uuid : UUID.randomUUID();
}
 
Example #19
Source File: SchematicHandler13.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
public static ArrayList<Integer> pasteSchematic(Location loc, String path) throws Exception{
	Bukkit.getLogger().info("[UhcCore] Pasting "+path);
	File schematic = new File(path);
       World world = BukkitAdapter.adapt(loc.getWorld());

       ClipboardFormat format = ClipboardFormats.findByFile(schematic);
       ClipboardReader reader = format.getReader(new FileInputStream(schematic));
       Clipboard clipboard = reader.read();

       EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(world, -1);

       enableWatchdog(editSession);

       Operation operation = new ClipboardHolder(clipboard)
               .createPaste(editSession)
               .to(BlockVector3.at(loc.getX(), loc.getY(), loc.getZ()))
               .ignoreAirBlocks(false)
               .build();

       Operations.complete(operation);
       editSession.flushSession();

	ArrayList<Integer> dimensions = new ArrayList<>();
	dimensions.add(clipboard.getDimensions().getY());
	dimensions.add(clipboard.getDimensions().getX());
	dimensions.add(clipboard.getDimensions().getZ());
	
	Bukkit.getLogger().info("[UhcCore] Successfully pasted '"+path+"' at "+loc.getBlockX()+" "+loc.getBlockY()+" "+loc.getBlockZ());
	return dimensions;
}
 
Example #20
Source File: ClipboardFormats.java    From FastAsyncWorldedit with GNU General Public License v3.0 4 votes vote down vote up
public static Collection<ClipboardFormat> getAll() {
    return Arrays.asList(ClipboardFormat.values());
}
 
Example #21
Source File: WEHook.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
public static Region pasteWithWE(Player p, File file) {
    Location<World> loc = p.getLocation();
    Region r = null;

    if (p.getLocation().getBlockRelative(Direction.DOWN).getBlock().getType().equals(BlockTypes.WATER) ||
            p.getLocation().getBlockRelative(Direction.DOWN).getBlock().getType().equals(BlockTypes.FLOWING_WATER)) {
        RedProtect.get().lang.sendMessage(p, "playerlistener.region.needground");
        return null;
    }

    SpongePlayer sp = SpongeWorldEdit.inst().wrapPlayer(p);
    SpongeWorld ws = SpongeWorldEdit.inst().getWorld(p.getWorld());

    LocalSession session = SpongeWorldEdit.inst().getSession(p);

    Closer closer = Closer.create();
    try {
        ClipboardFormat format = ClipboardFormat.findByAlias("schematic");
        FileInputStream fis = closer.register(new FileInputStream(file));
        BufferedInputStream bis = closer.register(new BufferedInputStream(fis));
        ClipboardReader reader = format.getReader(bis);

        WorldData worldData = ws.getWorldData();
        Clipboard clipboard = reader.read(ws.getWorldData());
        session.setClipboard(new ClipboardHolder(clipboard, worldData));

        Vector bmin = clipboard.getMinimumPoint();
        Vector bmax = clipboard.getMaximumPoint();

        Location<World> min = loc.add(bmin.getX(), bmin.getY(), bmin.getZ());
        Location<World> max = loc.add(bmax.getX(), bmax.getY(), bmax.getZ());

        PlayerRegion leader = new PlayerRegion(p.getUniqueId().toString(), p.getName());
        RegionBuilder rb2 = new DefineRegionBuilder(p, min, max, "", leader, new HashSet<>(), false);
        if (rb2.ready()) {
            r = rb2.build();
        }

        ClipboardHolder holder = session.getClipboard();

        Operation op = holder.createPaste(session.createEditSession(sp), ws.getWorldData()).to(session.getPlacementPosition(sp)).build();
        Operations.completeLegacy(op);
    } catch (IOException | EmptyClipboardException | IncompleteRegionException | MaxChangedBlocksException e) {
        CoreUtil.printJarVersion();
        e.printStackTrace();
    }

    return r;
}
 
Example #22
Source File: ClipboardFormats.java    From FastAsyncWorldedit with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Find the clipboard format named by the given alias.
 *
 * @param alias
 *            the alias
 * @return the format, otherwise null if none is matched
 */
@Nullable
public static ClipboardFormat findByAlias(String alias) {
    return ClipboardFormat.findByAlias(alias);
}
 
Example #23
Source File: FaweAPI.java    From FastAsyncWorldedit with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Just forwards to ClipboardFormat.SCHEMATIC.load(file)
 *
 * @param file
 * @return
 * @see com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat
 * @see com.boydti.fawe.object.schematic.Schematic
 */
public static Schematic load(File file) throws IOException {
    return ClipboardFormat.SCHEMATIC.load(file);
}
 
Example #24
Source File: FaweAPI.java    From FastAsyncWorldedit with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Upload the clipboard to the configured web interface
 *
 * @param clipboard The clipboard (may not be null)
 * @param format    The format to use (some formats may not be supported)
 * @return The download URL or null
 */
public static URL upload(final Clipboard clipboard, final ClipboardFormat format) {
    return format.uploadAnonymous(clipboard);
}