Search in sources :

Example 6 with EventVO

use of org.pepsoft.worldpainter.vo.EventVO in project WorldPainter by Captain-Chaos.

the class JavaWorldMerger method merge.

public void merge(File backupDir, ProgressReceiver progressReceiver) throws IOException, ProgressReceiver.OperationCancelled {
    logger.info("Merging world " + world.getName() + " with map at " + levelDatFile.getParentFile());
    // Read existing level.dat file and perform sanity checks
    Level level = performSanityChecks(false);
    // Record start of export
    long start = System.currentTimeMillis();
    // Backup existing level
    File worldDir = levelDatFile.getParentFile();
    if (!worldDir.renameTo(backupDir)) {
        throw new FileInUseException("Could not move " + worldDir + " to " + backupDir);
    }
    if (!worldDir.mkdirs()) {
        throw new IOException("Could not create " + worldDir);
    }
    // Set the world to the same Minecraft version as the existing map, in
    // case it has changed. This affects the type of chunks created in the
    // first pass
    int version = level.getVersion();
    Platform platform = (version == SUPPORTED_VERSION_1) ? DefaultPlugin.JAVA_MCREGION : DefaultPlugin.JAVA_ANVIL;
    world.setPlatform(platform);
    // Modify it if necessary and write it to the the new level
    if ((selectedDimensions == null) || selectedDimensions.contains(DIM_NORMAL)) {
        Dimension surfaceDimension = world.getDimension(DIM_NORMAL);
        level.setSeed(surfaceDimension.getMinecraftSeed());
        Point spawnPoint = world.getSpawnPoint();
        level.setSpawnX(spawnPoint.x);
        level.setSpawnY(Math.max(surfaceDimension.getIntHeightAt(spawnPoint), surfaceDimension.getWaterLevelAt(spawnPoint)));
        level.setSpawnZ(spawnPoint.y);
    }
    // Save the level.dat file. This will also create a session.lock file, hopefully kicking out any Minecraft
    // instances which may have the map open:
    level.save(worldDir);
    // Copy everything that we are not going to generate
    File[] files = backupDir.listFiles();
    // noinspection ConstantConditions // Cannot happen because we previously loaded level.dat from it
    for (File file : files) {
        if ((!file.getName().equalsIgnoreCase("level.dat")) && (!file.getName().equalsIgnoreCase("level.dat_old")) && (!file.getName().equalsIgnoreCase("session.lock")) && (((selectedDimensions != null) && (!selectedDimensions.contains(DIM_NORMAL))) || (!file.getName().equalsIgnoreCase("region"))) && (!file.getName().equalsIgnoreCase("maxheight.txt")) && (!file.getName().equalsIgnoreCase("Height.txt")) && (((selectedDimensions != null) && (!selectedDimensions.contains(DIM_NETHER))) || (!file.getName().equalsIgnoreCase("DIM-1"))) && (((selectedDimensions != null) && (!selectedDimensions.contains(DIM_END))) || (!file.getName().equalsIgnoreCase("DIM1")))) {
            if (file.isFile()) {
                FileUtils.copyFileToDir(file, worldDir);
            } else if (file.isDirectory()) {
                FileUtils.copyDir(file, new File(worldDir, file.getName()));
            } else {
                logger.warn("Not copying " + file + "; not a regular file or directory");
            }
        }
    }
    if ((selectedDimensions == null) ? (world.getDimension(DIM_NORMAL) != null) : selectedDimensions.contains(DIM_NORMAL)) {
        mergeDimension(worldDir, backupDir, world.getDimension(DIM_NORMAL), platform, progressReceiver);
    }
    if ((selectedDimensions == null) ? (world.getDimension(DIM_NETHER) != null) : selectedDimensions.contains(DIM_NETHER)) {
        mergeDimension(worldDir, backupDir, world.getDimension(DIM_NETHER), platform, progressReceiver);
    }
    if ((selectedDimensions == null) ? (world.getDimension(DIM_END) != null) : selectedDimensions.contains(DIM_END)) {
        mergeDimension(worldDir, backupDir, world.getDimension(DIM_END), platform, progressReceiver);
    }
    // Update the session.lock file, hopefully kicking out any Minecraft instances which may have tried to open the
    // map in the mean time:
    File sessionLockFile = new File(worldDir, "session.lock");
    try (DataOutputStream sessionOut = new DataOutputStream(new FileOutputStream(sessionLockFile))) {
        sessionOut.writeLong(System.currentTimeMillis());
    }
    // Record the merge in the world history
    if (selectedDimensions == null) {
        world.addHistoryEntry(HistoryEntry.WORLD_MERGED_FULL, level.getName(), worldDir);
    } else {
        String dimNames = selectedDimensions.stream().map(dim -> {
            switch(dim) {
                case DIM_NORMAL:
                    return "Surface";
                case DIM_NETHER:
                    return "Nether";
                case DIM_END:
                    return "End";
                default:
                    return Integer.toString(dim);
            }
        }).collect(Collectors.joining(", "));
        world.addHistoryEntry(HistoryEntry.WORLD_MERGED_PARTIAL, level.getName(), worldDir, dimNames);
    }
    if (!levelDatFile.equals(world.getMergedWith())) {
        world.setMergedWith(levelDatFile);
    }
    // Log an event
    Configuration config = Configuration.getInstance();
    if (config != null) {
        EventVO event = new EventVO(EVENT_KEY_ACTION_MERGE_WORLD).duration(System.currentTimeMillis() - start);
        event.setAttribute(EventVO.ATTRIBUTE_TIMESTAMP, new Date(start));
        event.setAttribute(ATTRIBUTE_KEY_MAX_HEIGHT, world.getMaxHeight());
        event.setAttribute(ATTRIBUTE_KEY_PLATFORM, world.getPlatform().displayName);
        event.setAttribute(ATTRIBUTE_KEY_MAP_FEATURES, world.isMapFeatures());
        event.setAttribute(ATTRIBUTE_KEY_GAME_TYPE_NAME, world.getGameType().name());
        event.setAttribute(ATTRIBUTE_KEY_ALLOW_CHEATS, world.isAllowCheats());
        event.setAttribute(ATTRIBUTE_KEY_GENERATOR, world.getGenerator().name());
        if (world.getPlatform().equals(DefaultPlugin.JAVA_ANVIL) && (world.getGenerator() == Generator.FLAT)) {
            event.setAttribute(ATTRIBUTE_KEY_GENERATOR_OPTIONS, world.getGeneratorOptions());
        }
        if ((selectedDimensions == null) || selectedDimensions.contains(DIM_NORMAL)) {
            Dimension surfaceDimension = world.getDimension(0);
            event.setAttribute(ATTRIBUTE_KEY_TILES, surfaceDimension.getTiles().size());
            logLayers(surfaceDimension, event, "");
        }
        if (world.getImportedFrom() == null) {
            event.setAttribute(ATTRIBUTE_KEY_IMPORTED_WORLD, false);
        }
        config.logEvent(event);
    }
}
Also used : FileInUseException(org.pepsoft.worldpainter.util.FileInUseException) java.util(java.util) org.pepsoft.minecraft(org.pepsoft.minecraft) BLOCKS(org.pepsoft.minecraft.Block.BLOCKS) EventVO(org.pepsoft.worldpainter.vo.EventVO) ParallelProgressManager(org.pepsoft.util.ParallelProgressManager) org.pepsoft.worldpainter.layers(org.pepsoft.worldpainter.layers) NBTOutputStream(org.jnbt.NBTOutputStream) SubProgressReceiver(org.pepsoft.util.SubProgressReceiver) PlatformManager(org.pepsoft.worldpainter.plugins.PlatformManager) org.pepsoft.worldpainter.exporting(org.pepsoft.worldpainter.exporting) ThreadFactory(java.util.concurrent.ThreadFactory) ExecutorService(java.util.concurrent.ExecutorService) org.pepsoft.worldpainter(org.pepsoft.worldpainter) Constants(org.pepsoft.worldpainter.Constants) HistoryEntry(org.pepsoft.worldpainter.history.HistoryEntry) FileInUseException(org.pepsoft.worldpainter.util.FileInUseException) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) NBTInputStream(org.jnbt.NBTInputStream) Dimension(org.pepsoft.worldpainter.Dimension) java.awt(java.awt) TimeUnit(java.util.concurrent.TimeUnit) CompoundTag(org.jnbt.CompoundTag) List(java.util.List) java.io(java.io) Constants(org.pepsoft.minecraft.Constants) ProgressReceiver(org.pepsoft.util.ProgressReceiver) Tag(org.jnbt.Tag) FileUtils(org.pepsoft.util.FileUtils) Pattern(java.util.regex.Pattern) Dimension(org.pepsoft.worldpainter.Dimension) EventVO(org.pepsoft.worldpainter.vo.EventVO)

Example 7 with EventVO

use of org.pepsoft.worldpainter.vo.EventVO in project WorldPainter by Captain-Chaos.

the class JavaWorldExporter method export.

@Override
public Map<Integer, ChunkFactory.Stats> export(File baseDir, String name, File backupDir, ProgressReceiver progressReceiver) throws IOException, ProgressReceiver.OperationCancelled {
    // Sanity checks
    if ((selectedTiles == null) && (selectedDimensions != null)) {
        throw new IllegalArgumentException("Exporting a subset of dimensions not supported");
    }
    // Backup existing level
    File worldDir = new File(baseDir, FileUtils.sanitiseName(name));
    logger.info("Exporting world " + world.getName() + " to map at " + worldDir);
    if (worldDir.isDirectory()) {
        if (backupDir != null) {
            logger.info("Directory already exists; backing up to " + backupDir);
            if (!worldDir.renameTo(backupDir)) {
                throw new FileInUseException("Could not move " + worldDir + " to " + backupDir);
            }
        } else {
            throw new IllegalStateException("Directory already exists and no backup directory specified");
        }
    }
    // Record start of export
    long start = System.currentTimeMillis();
    // Export dimensions
    Dimension dim0 = world.getDimension(0);
    Level level = new Level(world.getMaxHeight(), world.getPlatform());
    level.setSeed(dim0.getMinecraftSeed());
    level.setName(name);
    Point spawnPoint = world.getSpawnPoint();
    level.setSpawnX(spawnPoint.x);
    level.setSpawnY(Math.max(dim0.getIntHeightAt(spawnPoint), dim0.getWaterLevelAt(spawnPoint)));
    level.setSpawnZ(spawnPoint.y);
    if (world.getGameType() == GameType.HARDCORE) {
        level.setGameType(GAME_TYPE_SURVIVAL);
        level.setHardcore(true);
        level.setDifficulty(DIFFICULTY_HARD);
        level.setDifficultyLocked(true);
        level.setAllowCommands(false);
    } else {
        level.setGameType(world.getGameType().ordinal());
        level.setHardcore(false);
        level.setDifficulty(world.getDifficulty());
        level.setAllowCommands(world.isAllowCheats());
    }
    Dimension.Border dim0Border = dim0.getBorder();
    boolean endlessBorder = (dim0Border != null) && dim0Border.isEndless();
    if (endlessBorder) {
        StringBuilder generatorOptions = new StringBuilder("3;");
        switch(dim0Border) {
            case ENDLESS_LAVA:
            case ENDLESS_WATER:
                boolean bottomless = dim0.isBottomless();
                int borderLevel = dim0.getBorderLevel();
                int oceanDepth = Math.min(borderLevel / 2, 20);
                int dirtDepth = borderLevel - oceanDepth - (bottomless ? 1 : 0);
                if (!bottomless) {
                    generatorOptions.append("1*minecraft:bedrock,");
                }
                generatorOptions.append(dirtDepth);
                generatorOptions.append("*minecraft:dirt,");
                generatorOptions.append(oceanDepth);
                generatorOptions.append((dim0Border == Dimension.Border.ENDLESS_WATER) ? "*minecraft:water;0;" : "*minecraft:lava;1;");
                break;
            case ENDLESS_VOID:
                generatorOptions.append("1*minecraft:air;1;");
                break;
        }
        generatorOptions.append(DEFAULT_GENERATOR_OPTIONS);
        level.setMapFeatures(false);
        level.setGenerator(Generator.FLAT);
        level.setGeneratorOptions(generatorOptions.toString());
    } else {
        level.setMapFeatures(world.isMapFeatures());
        level.setGenerator(world.getGenerator());
    }
    if (world.getPlatform().equals(DefaultPlugin.JAVA_ANVIL)) {
        if ((!endlessBorder) && (world.getGenerator() == Generator.FLAT) && (world.getGeneratorOptions() != null)) {
            level.setGeneratorOptions(world.getGeneratorOptions());
        }
        World2.BorderSettings borderSettings = world.getBorderSettings();
        level.setBorderCenterX(borderSettings.getCentreX());
        level.setBorderCenterZ(borderSettings.getCentreY());
        level.setBorderSize(borderSettings.getSize());
        level.setBorderSafeZone(borderSettings.getSafeZone());
        level.setBorderWarningBlocks(borderSettings.getWarningBlocks());
        level.setBorderWarningTime(borderSettings.getWarningTime());
        level.setBorderSizeLerpTarget(borderSettings.getSizeLerpTarget());
        level.setBorderSizeLerpTime(borderSettings.getSizeLerpTime());
        level.setBorderDamagePerBlock(borderSettings.getDamagePerBlock());
    }
    // Save the level.dat file. This will also create a session.lock file, hopefully kicking out any Minecraft
    // instances which may have the map open:
    level.save(worldDir);
    Map<Integer, ChunkFactory.Stats> stats = new HashMap<>();
    int selectedDimension;
    if (selectedTiles == null) {
        selectedDimension = -1;
        boolean first = true;
        for (Dimension dimension : world.getDimensions()) {
            if (dimension.getDim() < 0) {
                // dimension, so skip it
                continue;
            }
            if (first) {
                first = false;
            } else if (progressReceiver != null) {
                progressReceiver.reset();
            }
            stats.put(dimension.getDim(), exportDimension(worldDir, dimension, world.getPlatform(), progressReceiver));
        }
    } else {
        selectedDimension = selectedDimensions.iterator().next();
        stats.put(selectedDimension, exportDimension(worldDir, world.getDimension(selectedDimension), world.getPlatform(), progressReceiver));
    }
    // Update the session.lock file, hopefully kicking out any Minecraft instances which may have tried to open the
    // map in the mean time:
    File sessionLockFile = new File(worldDir, "session.lock");
    try (DataOutputStream sessionOut = new DataOutputStream(new FileOutputStream(sessionLockFile))) {
        sessionOut.writeLong(System.currentTimeMillis());
    }
    // Record the export in the world history
    if (selectedTiles == null) {
        world.addHistoryEntry(HistoryEntry.WORLD_EXPORTED_FULL, name, worldDir);
    } else {
        world.addHistoryEntry(HistoryEntry.WORLD_EXPORTED_PARTIAL, name, worldDir, world.getDimension(selectedDimension).getName());
    }
    // Log an event
    Configuration config = Configuration.getInstance();
    if (config != null) {
        EventVO event = new EventVO(EVENT_KEY_ACTION_EXPORT_WORLD).duration(System.currentTimeMillis() - start);
        event.setAttribute(EventVO.ATTRIBUTE_TIMESTAMP, new Date(start));
        event.setAttribute(ATTRIBUTE_KEY_MAX_HEIGHT, world.getMaxHeight());
        event.setAttribute(ATTRIBUTE_KEY_PLATFORM, world.getPlatform().displayName);
        event.setAttribute(ATTRIBUTE_KEY_MAP_FEATURES, world.isMapFeatures());
        event.setAttribute(ATTRIBUTE_KEY_GAME_TYPE_NAME, world.getGameType().name());
        event.setAttribute(ATTRIBUTE_KEY_ALLOW_CHEATS, world.isAllowCheats());
        event.setAttribute(ATTRIBUTE_KEY_GENERATOR, world.getGenerator().name());
        if (world.getPlatform().equals(DefaultPlugin.JAVA_ANVIL) && (world.getGenerator() == Generator.FLAT)) {
            event.setAttribute(ATTRIBUTE_KEY_GENERATOR_OPTIONS, world.getGeneratorOptions());
        }
        Dimension dimension = world.getDimension(0);
        event.setAttribute(ATTRIBUTE_KEY_TILES, dimension.getTiles().size());
        logLayers(dimension, event, "");
        dimension = world.getDimension(1);
        if (dimension != null) {
            event.setAttribute(ATTRIBUTE_KEY_NETHER_TILES, dimension.getTiles().size());
            logLayers(dimension, event, "nether.");
        }
        dimension = world.getDimension(2);
        if (dimension != null) {
            event.setAttribute(ATTRIBUTE_KEY_END_TILES, dimension.getTiles().size());
            logLayers(dimension, event, "end.");
        }
        if (selectedDimension != -1) {
            event.setAttribute(ATTRIBUTE_KEY_EXPORTED_DIMENSION, selectedDimension);
            event.setAttribute(ATTRIBUTE_KEY_EXPORTED_DIMENSION_TILES, selectedTiles.size());
        }
        if (world.getImportedFrom() != null) {
            event.setAttribute(ATTRIBUTE_KEY_IMPORTED_WORLD, true);
        }
        config.logEvent(event);
    }
    return stats;
}
Also used : FileInUseException(org.pepsoft.worldpainter.util.FileInUseException) DataOutputStream(java.io.DataOutputStream) Dimension(org.pepsoft.worldpainter.Dimension) FileOutputStream(java.io.FileOutputStream) Level(org.pepsoft.minecraft.Level) File(java.io.File) EventVO(org.pepsoft.worldpainter.vo.EventVO)

Example 8 with EventVO

use of org.pepsoft.worldpainter.vo.EventVO in project WorldPainter by Captain-Chaos.

the class AboutDialog method donate.

private void donate() {
    try {
        DesktopUtils.open(new URL("https://www.worldpainter.net/donate/paypal"));
        Configuration config = Configuration.getInstance();
        config.setDonationStatus(Configuration.DonationStatus.DONATED);
        JOptionPane.showMessageDialog(this, strings.getString("the.donation.paypal.page.has.been.opened"), strings.getString("thank.you"), JOptionPane.INFORMATION_MESSAGE);
        config.logEvent(new EventVO(Constants.EVENT_KEY_DONATION_DONATE).addTimestamp());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) URL(java.net.URL) EventVO(org.pepsoft.worldpainter.vo.EventVO)

Example 9 with EventVO

use of org.pepsoft.worldpainter.vo.EventVO in project WorldPainter by Captain-Chaos.

the class App method newWorld.

private void newWorld() {
    if (!saveIfNecessary()) {
        return;
    }
    Configuration config = Configuration.getInstance();
    final NewWorldDialog dialog = new NewWorldDialog(this, strings.getString("generated.world"), World2.DEFAULT_OCEAN_SEED, config.getDefaultPlatform(), DIM_NORMAL, config.getDefaultMaxHeight());
    dialog.setVisible(true);
    if (!dialog.isCancelled()) {
        // Free up memory of the world and the undo buffer
        setWorld(null);
        if (!dialog.checkMemoryRequirements(this)) {
            return;
        }
        World2 newWorld = ProgressDialog.executeTask(this, new ProgressTask<World2>() {

            @Override
            public String getName() {
                return strings.getString("creating.new.world");
            }

            @Override
            public World2 execute(ProgressReceiver progressReceiver) throws OperationCancelled {
                return dialog.getSelectedWorld(progressReceiver);
            }
        });
        if (newWorld == null) {
            // Operation cancelled by user
            return;
        }
        // Log an event
        EventVO event = new EventVO(EVENT_KEY_ACTION_NEW_WORLD).addTimestamp();
        event.setAttribute(ATTRIBUTE_KEY_MAX_HEIGHT, newWorld.getMaxHeight());
        event.setAttribute(ATTRIBUTE_KEY_TILES, newWorld.getDimension(0).getTiles().size());
        config.logEvent(event);
        setWorld(newWorld);
        lastSelectedFile = null;
        disableImportedWorldOperation();
    }
}
Also used : OperationCancelled(org.pepsoft.util.ProgressReceiver.OperationCancelled) EventVO(org.pepsoft.worldpainter.vo.EventVO)

Example 10 with EventVO

use of org.pepsoft.worldpainter.vo.EventVO in project WorldPainter by Captain-Chaos.

the class App method open.

public void open(final File file) {
    logger.info("Loading world " + file.getAbsolutePath());
    // Free up memory of the world and the undo buffer
    setWorld(null);
    final World2 newWorld = ProgressDialog.executeTask(this, new ProgressTask<World2>() {

        @Override
        public String getName() {
            return strings.getString("loading.world");
        }

        @Override
        public World2 execute(ProgressReceiver progressReceiver) throws OperationCancelled {
            try {
                WorldIO worldIO = new WorldIO();
                worldIO.load(new FileInputStream(file));
                World2 world = worldIO.getWorld();
                world.addHistoryEntry(HistoryEntry.WORLD_LOADED, file);
                if (logger.isDebugEnabled() && (world.getMetadata() != null)) {
                    logMetadataAsDebug(world.getMetadata());
                }
                return world;
            } catch (UnloadableWorldException e) {
                logger.error("Could not load world from file " + file, e);
                if (e.getMetadata() != null) {
                    logMetadataAsError(e.getMetadata());
                }
                reportUnloadableWorldException(e);
                return null;
            } catch (IOException e) {
                throw new RuntimeException("I/O error while loading world", e);
            }
        }

        private void appendMetadata(StringBuilder sb, Map<String, Object> metadata) {
            for (Map.Entry<String, Object> entry : metadata.entrySet()) {
                switch(entry.getKey()) {
                    case World2.METADATA_KEY_WP_VERSION:
                        sb.append("Saved with WorldPainter ").append(entry.getValue());
                        String build = (String) metadata.get(World2.METADATA_KEY_WP_BUILD);
                        if (build != null) {
                            sb.append(" (").append(build).append(')');
                        }
                        sb.append('\n');
                        break;
                    case World2.METADATA_KEY_TIMESTAMP:
                        sb.append("Saved on ").append(SimpleDateFormat.getDateTimeInstance().format((Date) entry.getValue())).append('\n');
                        break;
                    case World2.METADATA_KEY_PLUGINS:
                        String[][] plugins = (String[][]) entry.getValue();
                        for (String[] plugin : plugins) {
                            sb.append("Plugin: ").append(plugin[0]).append(" (").append(plugin[1]).append(")\n");
                        }
                        break;
                }
            }
        }

        private void logMetadataAsDebug(Map<String, Object> metadata) {
            StringBuilder sb = new StringBuilder("Metadata from world file:\n");
            appendMetadata(sb, metadata);
            logger.debug(sb.toString());
        }

        private void logMetadataAsError(Map<String, Object> metadata) {
            StringBuilder sb = new StringBuilder("Metadata from world file:\n");
            appendMetadata(sb, metadata);
            logger.error(sb.toString());
        }

        private void reportUnloadableWorldException(UnloadableWorldException e) {
            try {
                String text;
                if (e.getMetadata() != null) {
                    StringBuilder sb = new StringBuilder("WorldPainter could not load the file. The cause may be one of:\n" + "\n" + "* The file is damaged or corrupted\n" + "* The file was created with a newer version of WorldPainter\n" + "* The file was created using WorldPainter plugins which you do not have\n" + "\n");
                    appendMetadata(sb, e.getMetadata());
                    text = sb.toString();
                } else {
                    text = "WorldPainter could not load the file. The cause may be one of:\n" + "\n" + "* The file is not a WorldPainter world\n" + "* The file is damaged or corrupted\n" + "* The file was created with a newer version of WorldPainter\n" + "* The file was created using WorldPainter plugins which you do not have";
                }
                SwingUtilities.invokeAndWait(() -> showMessageDialog(App.this, text, strings.getString("file.damaged"), ERROR_MESSAGE));
            } catch (InterruptedException e2) {
                throw new RuntimeException("Thread interrupted while reporting unloadable file " + file, e2);
            } catch (InvocationTargetException e2) {
                throw new RuntimeException("Invocation target exception while reporting unloadable file " + file, e2);
            }
        }
    }, false);
    if (newWorld == null) {
        // The file was damaged
        return;
    }
    if (!isBackupFile(file)) {
        lastSelectedFile = file;
    } else {
        lastSelectedFile = null;
    }
    // Log an event
    Configuration config = Configuration.getInstance();
    EventVO event = new EventVO(EVENT_KEY_ACTION_OPEN_WORLD).addTimestamp();
    event.setAttribute(ATTRIBUTE_KEY_MAX_HEIGHT, newWorld.getMaxHeight());
    Dimension loadedDimension = newWorld.getDimension(0);
    event.setAttribute(ATTRIBUTE_KEY_TILES, loadedDimension.getTiles().size());
    logLayers(loadedDimension, event, "");
    loadedDimension = newWorld.getDimension(1);
    if (loadedDimension != null) {
        event.setAttribute(ATTRIBUTE_KEY_NETHER_TILES, loadedDimension.getTiles().size());
        logLayers(loadedDimension, event, "nether.");
    }
    loadedDimension = newWorld.getDimension(2);
    if (loadedDimension != null) {
        event.setAttribute(ATTRIBUTE_KEY_END_TILES, loadedDimension.getTiles().size());
        logLayers(loadedDimension, event, "end.");
    }
    if (newWorld.getImportedFrom() != null) {
        event.setAttribute(ATTRIBUTE_KEY_IMPORTED_WORLD, true);
    }
    config.logEvent(event);
    Set<World2.Warning> warnings = newWorld.getWarnings();
    if ((warnings != null) && (!warnings.isEmpty())) {
        for (World2.Warning warning : warnings) {
            switch(warning) {
                case AUTO_BIOMES_DISABLED:
                    if (showOptionDialog(this, "Automatic Biomes were previously enabled for this world but have been disabled.\nPress More Info for more information, including how to reenable it.", "Automatic Biomes Disabled", DEFAULT_OPTION, WARNING_MESSAGE, null, new Object[] { "More Info", "OK" }, "OK") == 0) {
                        try {
                            DesktopUtils.open(new URL("https://www.worldpainter.net/doc/legacy/newautomaticbiomes"));
                        } catch (MalformedURLException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    break;
                case AUTO_BIOMES_ENABLED:
                    if (showOptionDialog(this, "Automatic Biomes were previously disabled for this world but have been enabled.\nPress More Info for more information, including how to disable it.", "Automatic Biomes Enabled", DEFAULT_OPTION, WARNING_MESSAGE, null, new Object[] { "More Info", "OK" }, "OK") == 0) {
                        try {
                            DesktopUtils.open(new URL("https://www.worldpainter.net/doc/legacy/newautomaticbiomes"));
                        } catch (MalformedURLException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    break;
            }
        }
    }
    if (newWorld.isAskToConvertToAnvil() && (newWorld.getMaxHeight() == DEFAULT_MAX_HEIGHT_1) && (newWorld.getImportedFrom() == null)) {
        if (showConfirmDialog(this, strings.getString("this.world.is.128.blocks.high"), strings.getString("convert.world.height"), YES_NO_OPTION) == YES_OPTION) {
            ChangeHeightDialog.resizeWorld(newWorld, HeightTransform.IDENTITY, DEFAULT_MAX_HEIGHT_2, this);
            newWorld.addHistoryEntry(HistoryEntry.WORLD_MAX_HEIGHT_CHANGED, DEFAULT_MAX_HEIGHT_2);
            // with the old format
            if (newWorld.getPlatform() != null) {
                newWorld.setPlatform(DefaultPlugin.JAVA_ANVIL);
            }
            // Log event
            config.logEvent(new EventVO(EVENT_KEY_ACTION_MIGRATE_HEIGHT).addTimestamp());
        }
        // Don't ask again, no matter what the user answered
        newWorld.setAskToConvertToAnvil(false);
    }
    if (newWorld.isAskToRotate() && (newWorld.getUpIs() == Direction.WEST) && (newWorld.getImportedFrom() == null)) {
        if (showConfirmDialog(this, strings.getString("this.world.was.created.when.north.was.to.the.right"), strings.getString("rotate.world"), YES_NO_OPTION) == YES_OPTION) {
            ProgressDialog.executeTask(this, new ProgressTask<java.lang.Void>() {

                @Override
                public String getName() {
                    return strings.getString("rotating.world");
                }

                @Override
                public java.lang.Void execute(ProgressReceiver progressReceiver) throws OperationCancelled {
                    newWorld.transform(CoordinateTransform.ROTATE_CLOCKWISE_270_DEGREES, progressReceiver);
                    for (Dimension dimension : newWorld.getDimensions()) {
                        newWorld.addHistoryEntry(HistoryEntry.WORLD_DIMENSION_ROTATED, dimension.getName(), 270);
                    }
                    return null;
                }
            }, false);
            // Log event
            config.logEvent(new EventVO(EVENT_KEY_ACTION_MIGRATE_ROTATION).addTimestamp());
        }
        // Don't ask again, no matter what the user answered
        newWorld.setAskToRotate(false);
    }
    // Make sure the world name is always the same as the file name, to
    // avoid confusion, unless the only difference is illegal filename
    // characters changed into underscores. Do this here as well as when
    // saving, because the file might have been renamed
    String name = isBackupFile(file) ? getOriginalFile(file).getName() : file.getName();
    int p = name.lastIndexOf('.');
    if (p != -1) {
        name = name.substring(0, p);
    }
    String worldName = newWorld.getName();
    if (worldName.length() != name.length()) {
        newWorld.setName(name);
    } else {
        for (int i = 0; i < name.length(); i++) {
            if ((name.charAt(i) != '_') && (name.charAt(i) != worldName.charAt(i))) {
                newWorld.setName(name);
                break;
            }
        }
    }
    newWorld.setDirty(false);
    setWorld(newWorld);
    addRecentlyUsedWorld(file);
    if (newWorld.getImportedFrom() != null) {
        enableImportedWorldOperation();
    } else {
        disableImportedWorldOperation();
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) URL(java.net.URL) HistoryEntry(org.pepsoft.worldpainter.history.HistoryEntry) Void(java.lang.Void) EventVO(org.pepsoft.worldpainter.vo.EventVO) OperationCancelled(org.pepsoft.util.ProgressReceiver.OperationCancelled) InvocationTargetException(java.lang.reflect.InvocationTargetException) Paint(org.pepsoft.worldpainter.painting.Paint)

Aggregations

EventVO (org.pepsoft.worldpainter.vo.EventVO)12 URL (java.net.URL)5 MalformedURLException (java.net.MalformedURLException)4 File (java.io.File)3 List (java.util.List)3 OperationCancelled (org.pepsoft.util.ProgressReceiver.OperationCancelled)3 Dimension (org.pepsoft.worldpainter.Dimension)3 java.awt (java.awt)2 Void (java.lang.Void)2 java.util (java.util)2 SubProgressReceiver (org.pepsoft.util.SubProgressReceiver)2 HistoryEntry (org.pepsoft.worldpainter.history.HistoryEntry)2 Paint (org.pepsoft.worldpainter.painting.Paint)2 FileInUseException (org.pepsoft.worldpainter.util.FileInUseException)2 LoggerContext (ch.qos.logback.classic.LoggerContext)1 JoranConfigurator (ch.qos.logback.classic.joran.JoranConfigurator)1 JoranException (ch.qos.logback.core.joran.spi.JoranException)1 StatusPrinter (ch.qos.logback.core.util.StatusPrinter)1 LookAndFeelFactory (com.jidesoft.plaf.LookAndFeelFactory)1 Lm (com.jidesoft.utils.Lm)1