Skip to content

Commit

Permalink
You can load and save a schematic file now. Still gotta setup ability…
Browse files Browse the repository at this point in the history
… to use commands as a console actor.
  • Loading branch information
me4502 committed Jul 15, 2019
1 parent 0cab6ea commit c045299
Show file tree
Hide file tree
Showing 12 changed files with 345 additions and 66 deletions.
1 change: 1 addition & 0 deletions config/checkstyle/import-control.xml
Expand Up @@ -49,6 +49,7 @@

<subpackage name="cli">
<allow pkg="org.apache.logging.log4j"/>
<allow pkg="org.apache.commons.cli" />
</subpackage>

<subpackage name="forge">
Expand Down
Expand Up @@ -32,21 +32,29 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Nullable;

public class CLIBlockRegistry extends BundledBlockRegistry {

private Property<?> createProperty(String type, String key, List<?> values) {
private Property<?> createProperty(String type, String key, List<String> values) {
switch (type) {
case "int":
return new IntegerProperty(key, (List<Integer>) values);
case "bool":
return new BooleanProperty(key, (List<Boolean>) values);
case "enum":
return new EnumProperty(key, (List<String>) values);
case "dir":
return new DirectionalProperty(key, (List<Direction>) values);
case "int": {
List<Integer> fixedValues = values.stream().map(Integer::parseInt).collect(Collectors.toList());
return new IntegerProperty(key, fixedValues);
}
case "bool": {
List<Boolean> fixedValues = values.stream().map(Boolean::parseBoolean).collect(Collectors.toList());
return new BooleanProperty(key, fixedValues);
}
case "enum": {
return new EnumProperty(key, values);
}
case "direction": {
List<Direction> fixedValues = values.stream().map(String::toUpperCase).map(Direction::valueOf).collect(Collectors.toList());
return new DirectionalProperty(key, fixedValues);
}
default:
throw new RuntimeException("Failed to create property");
}
Expand All @@ -58,9 +66,7 @@ private Property<?> createProperty(String type, String key, List<?> values) {
Map<String, FileRegistries.BlockProperty> properties = CLIWorldEdit.inst.getFileRegistries().getDataFile().blocks.get(blockType.getId()).properties;
Map<String, Property<?>> worldEditProperties = new HashMap<>();

properties.forEach((name, prop) -> {
worldEditProperties.put(name, createProperty(prop.type, name, prop.values));
});
properties.forEach((name, prop) -> worldEditProperties.put(name, createProperty(prop.type, name, prop.values)));

return worldEditProperties;
}
Expand Down
Expand Up @@ -67,24 +67,29 @@ public void printRaw(String msg) {
}
}

public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_RESET = "\u001B[0m";

@Override
public void print(String msg) {
for (String part : msg.split("\n")) {
sender.info("\u00A7d" + part);
sender.info(ANSI_PURPLE + part + ANSI_RESET);
}
}

@Override
public void printDebug(String msg) {
for (String part : msg.split("\n")) {
sender.debug("\u00A77" + part);
sender.debug(ANSI_GREEN + part + ANSI_RESET);
}
}

@Override
public void printError(String msg) {
for (String part : msg.split("\n")) {
sender.error("\u00A7c" + part);
sender.error(ANSI_RED + part + ANSI_RESET);
}
}

Expand Down
Expand Up @@ -25,17 +25,12 @@

public class CLIConfiguration extends PropertiesConfiguration {

public boolean creativeEnable = false;
public boolean cheatMode = false;

public CLIConfiguration(CLIWorldEdit mod) {
super(new File(mod.getWorkingDir() + File.separator + "worldedit.properties"));
}

@Override
protected void loadExtra() {
creativeEnable = getBool("use-in-creative", false);
cheatMode = getBool("cheat-mode", false);
}

@Override
Expand Down
Expand Up @@ -39,6 +39,9 @@
class CLIPlatform extends AbstractPlatform {

private final CLIWorldEdit mod;
private int dataVersion = -1;

private List<World> worlds = new ArrayList<>();

CLIPlatform(CLIWorldEdit mod) {
this.mod = mod;
Expand All @@ -51,8 +54,11 @@ public Registries getRegistries() {

@Override
public int getDataVersion() {
// TODO Determine from loaded file.
return 1968;
return dataVersion;
}

public void setDataVersion(int dataVersion) {
this.dataVersion = dataVersion;
}

@Override
Expand All @@ -77,7 +83,7 @@ public int schedule(long delay, long period, Runnable task) {

@Override
public List<? extends World> getWorlds() {
return new ArrayList<>();
return worlds;
}

@Nullable
Expand Down Expand Up @@ -130,4 +136,8 @@ public Map<Capability, Preference> getCapabilities() {
capabilities.put(Capability.WORLD_EDITING, Preference.PREFERRED);
return capabilities;
}

public void addWorld(World world) {
worlds.add(world);
}
}
107 changes: 77 additions & 30 deletions worldedit-cli/src/main/java/com/sk89q/worldedit/cli/CLIWorldEdit.java
Expand Up @@ -21,16 +21,22 @@

import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.cli.data.FileRegistries;
import com.sk89q.worldedit.cli.schematic.ClipboardWorld;
import com.sk89q.worldedit.event.platform.CommandEvent;
import com.sk89q.worldedit.event.platform.PlatformReadyEvent;
import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.extent.clipboard.io.BuiltInClipboardFormat;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter;
import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.util.FileDialogUtil;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockCategory;
import com.sk89q.worldedit.world.block.BlockState;
Expand All @@ -43,11 +49,11 @@
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
Expand Down Expand Up @@ -75,32 +81,9 @@ public class CLIWorldEdit {

public CLIWorldEdit() {
inst = this;

onInitialize();

onStarted();

run();

onStopped();
}

public void onInitialize() {
// Setup working directory
workingDir = new File("worldedit").toPath();
if (!Files.exists(workingDir)) {
try {
Files.createDirectory(workingDir);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

LOGGER.info("WorldEdit CLI (version " + getInternalVersion() + ") is loaded");
}

private void setupPlatform() {
this.platform = new CLIPlatform(this);
this.fileRegistries = new FileRegistries(this);
this.fileRegistries.loadDataFiles();

Expand Down Expand Up @@ -165,6 +148,21 @@ public void setupRegistries() {
}
}

public void onInitialized() {
// Setup working directory
workingDir = new File("worldedit").toPath();
if (!Files.exists(workingDir)) {
try {
Files.createDirectory(workingDir);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

this.platform = new CLIPlatform(this);
LOGGER.info("WorldEdit CLI (version " + getInternalVersion() + ") is loaded");
}

public void onStarted() {
setupPlatform();

Expand Down Expand Up @@ -227,9 +225,41 @@ String getInternalVersion() {
public void run() {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.equalsIgnoreCase("stop")) {
commandSender.print("Stopping!");
return;
}
if (line.startsWith("save")) {
String[] bits = line.split(" ");
if (bits.length == 0) {
commandSender.print("Usage: save <filename>");
return;
}
World world = platform.getWorlds().get(0);
if (world instanceof ClipboardWorld) {
File file = null;
if (bits.length >= 2) {
file = new File(bits[1]);
} else {
file = FileDialogUtil.showSaveDialog(new String[]{"schem"});
}
if (file == null) {
commandSender.printError("Please choose a file.");
return;
}
try(ClipboardWriter writer = BuiltInClipboardFormat.SPONGE_SCHEMATIC.getWriter(new FileOutputStream(file))) {
writer.write((Clipboard) world);
} catch (IOException e) {
e.printStackTrace();
}
}

return;
}
WorldEdit.getInstance().getEventBus().post(new CommandEvent(
commandSender,
scanner.nextLine()
line
));
}
}
Expand All @@ -239,6 +269,9 @@ public static void main(String[] args) {
options.addRequiredOption("f", "file", false, "The file to load in. Either a schematic, or a level.dat in a world folder.");
CommandLineParser parser = new DefaultParser();

CLIWorldEdit worldEdit = new CLIWorldEdit();
worldEdit.onInitialized();

try {
CommandLine cmd = parser.parse(options, args);
String fileArg = cmd.getOptionValue('f');
Expand All @@ -254,16 +287,30 @@ public static void main(String[] args) {
if (file.getName().endsWith(".dat")) {

} else if (file.getName().endsWith(".schem")) {
Clipboard clipboard = ClipboardFormats.findByFile(file)
.getReader(Files.newInputStream(file.toPath(), StandardOpenOption.READ))
.read();
ClipboardFormat format = ClipboardFormats.findByFile(file);
if (format == null) {
throw new IOException("Unknown clipboard format for file.");
}
ClipboardReader clipboardReader = format
.getReader(Files.newInputStream(file.toPath(), StandardOpenOption.READ));
int dataVersion = clipboardReader.getDataVersion()
.orElseThrow(() -> new IllegalArgumentException("Failed to obtain data version from schematic."));
worldEdit.platform.setDataVersion(dataVersion);
worldEdit.onStarted();
ClipboardWorld world = new ClipboardWorld(
format.getReader(Files.newInputStream(file.toPath(), StandardOpenOption.READ)).read(),
file.getName()
);
worldEdit.platform.addWorld(world);
} else {
throw new IllegalArgumentException("Unknown file provided!");
}

new CLIWorldEdit();
} catch (ParseException | IOException e) {
worldEdit.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
worldEdit.onStopped();
}
}
}

0 comments on commit c045299

Please sign in to comment.