001/*
002 * PlotSquared, a land and world management plugin for Minecraft.
003 * Copyright (C) IntellectualSites <https://intellectualsites.com>
004 * Copyright (C) IntellectualSites team and contributors
005 *
006 * This program is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 *
011 * This program is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU General Public License for more details.
015 *
016 * You should have received a copy of the GNU General Public License
017 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
018 */
019package com.plotsquared.core.util;
020
021import com.plotsquared.core.PlotSquared;
022import com.plotsquared.core.configuration.caption.Caption;
023import com.plotsquared.core.location.Location;
024import com.plotsquared.core.player.PlotPlayer;
025import com.plotsquared.core.plot.Plot;
026import com.plotsquared.core.util.task.RunnableVal;
027import com.sk89q.jnbt.CompoundTag;
028import com.sk89q.jnbt.IntTag;
029import com.sk89q.jnbt.NBTInputStream;
030import com.sk89q.jnbt.NBTOutputStream;
031import com.sk89q.jnbt.Tag;
032import com.sk89q.worldedit.math.BlockVector2;
033import com.sk89q.worldedit.regions.CuboidRegion;
034import com.sk89q.worldedit.world.World;
035import com.sk89q.worldedit.world.biome.BiomeType;
036import com.sk89q.worldedit.world.block.BlockState;
037import com.sk89q.worldedit.world.block.BlockType;
038import com.sk89q.worldedit.world.entity.EntityType;
039import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
040import org.checkerframework.checker.index.qual.NonNegative;
041import org.checkerframework.checker.nullness.qual.NonNull;
042import org.checkerframework.checker.nullness.qual.Nullable;
043
044import java.io.ByteArrayOutputStream;
045import java.io.File;
046import java.io.FileInputStream;
047import java.io.IOException;
048import java.io.OutputStream;
049import java.net.URL;
050import java.util.Collection;
051import java.util.HashMap;
052import java.util.HashSet;
053import java.util.Map;
054import java.util.Set;
055import java.util.UUID;
056import java.util.function.Consumer;
057import java.util.function.IntConsumer;
058import java.util.zip.GZIPInputStream;
059import java.util.zip.GZIPOutputStream;
060import java.util.zip.ZipEntry;
061import java.util.zip.ZipOutputStream;
062
063public abstract class WorldUtil {
064
065    /**
066     * {@return whether the given location is valid in the world}
067     * @param location the location to check
068     * @since 7.3.6
069     */
070    public static boolean isValidLocation(Location location) {
071        return Math.abs(location.getX()) < 30000000 && Math.abs(location.getZ()) < 30000000;
072    }
073
074    /**
075     * Set the biome in a region
076     *
077     * @param world  World name
078     * @param region Region
079     * @param biome  Biome
080     * @since 6.6.0
081     */
082    public static void setBiome(String world, final CuboidRegion region, BiomeType biome) {
083        PlotSquared.platform().worldUtil().setBiomes(world, region, biome);
084    }
085
086    /**
087     * Check if a given world name corresponds to a real world
088     *
089     * @param worldName World name
090     * @return {@code true} if there exists a world with the given world name,
091     *         {@code false} if not
092     */
093    public abstract boolean isWorld(@NonNull String worldName);
094
095    /**
096     * @param location Sign location
097     * @return Sign content (or an empty string array if the block is not a sign)
098     * @deprecated May result in synchronous chunk loading
099     */
100    @Deprecated
101    public @NonNull
102    abstract String[] getSignSynchronous(@NonNull Location location);
103
104    /**
105     * Get the world spawn location
106     *
107     * @param world World name
108     * @return World spawn location
109     */
110    public @NonNull
111    abstract Location getSpawn(@NonNull String world);
112
113    /**
114     * Set the world spawn location
115     *
116     * @param location New spawn
117     */
118    public abstract void setSpawn(@NonNull Location location);
119
120    /**
121     * Save a world
122     *
123     * @param world World name
124     */
125    public abstract void saveWorld(@NonNull String world);
126
127    /**
128     * Get a string comparison with the closets block state matching a given string
129     *
130     * @param name Block name
131     * @return Comparison result containing the closets matching block
132     */
133    public @NonNull
134    abstract StringComparison<BlockState>.ComparisonResult getClosestBlock(@NonNull String name);
135
136    /**
137     * Set the block at the specified location to a sign, with given text
138     *
139     * @param location     Block location
140     * @param lines        Sign text
141     * @param replacements Text replacements
142     */
143    public abstract void setSign(
144            @NonNull Location location,
145            @NonNull Caption[] lines,
146            @NonNull TagResolver... replacements
147    );
148
149    /**
150     * Get the biome in a given chunk, asynchronously
151     *
152     * @param world  World
153     * @param x      Chunk X coordinate
154     * @param z      Chunk Z coordinate
155     * @param result Result consumer
156     */
157    public abstract void getBiome(@NonNull String world, int x, int z, @NonNull Consumer<BiomeType> result);
158
159    /**
160     * Get the biome in a given chunk, asynchronously
161     *
162     * @param world World
163     * @param x     Chunk X coordinate
164     * @param z     Chunk Z coordinate
165     * @return Biome
166     * @deprecated Use {@link #getBiome(String, int, int, Consumer)}
167     */
168    @Deprecated
169    public @NonNull
170    abstract BiomeType getBiomeSynchronous(@NonNull String world, int x, int z);
171
172    /**
173     * Get the block at a given location (asynchronously)
174     *
175     * @param location Block location
176     * @param result   Result consumer
177     */
178    public abstract void getBlock(@NonNull Location location, @NonNull Consumer<BlockState> result);
179
180    /**
181     * Checks if the block smaller as a slab
182     * @param location Block location
183     * @return true if it smaller as a slab
184     */
185    public abstract boolean isSmallBlock(@NonNull Location location);
186
187    /**
188     * Get the block at a given location (synchronously)
189     *
190     * @param location Block location
191     * @return Result
192     * @deprecated Use {@link #getBlock(Location, Consumer)}
193     */
194    @Deprecated
195    public @NonNull
196    abstract BlockState getBlockSynchronous(@NonNull Location location);
197
198    /**
199     * Get the Y coordinate of the highest non-air block in the world, asynchronously
200     *
201     * @param world  World name
202     * @param x      X coordinate
203     * @param z      Z coordinate
204     * @param result Result consumer
205     */
206    public abstract void getHighestBlock(@NonNull String world, int x, int z, @NonNull IntConsumer result);
207
208    /**
209     * Get the Y coordinate of the highest non-air block in the world, synchronously
210     *
211     * @param world World name
212     * @param x     X coordinate
213     * @param z     Z coordinate
214     * @return Result
215     * @deprecated Use {@link #getHighestBlock(String, int, int, IntConsumer)}
216     */
217    @Deprecated
218    @NonNegative
219    public abstract int getHighestBlockSynchronous(@NonNull String world, int x, int z);
220
221    /**
222     * Set the biome in a region
223     *
224     * @param worldName World name
225     * @param region    Region
226     * @param biome     New biome
227     */
228    public void setBiomes(@NonNull String worldName, @NonNull CuboidRegion region, @NonNull BiomeType biome) {
229        final World world = getWeWorld(worldName);
230        region.forEach(bv -> world.setBiome(bv, biome));
231    }
232
233    /**
234     * Get the WorldEdit {@link com.sk89q.worldedit.world.World} corresponding to a world name
235     *
236     * @param world World name
237     * @return World object
238     */
239    public abstract com.sk89q.worldedit.world.@NonNull World getWeWorld(@NonNull String world);
240
241    /**
242     * Refresh (resend) chunk to player. Usually after setting the biome
243     *
244     * @param x     Chunk x location
245     * @param z     Chunk z location
246     * @param world World of the chunk
247     */
248    public abstract void refreshChunk(int x, int z, String world);
249
250    /**
251     * The legacy web interface is deprecated for removal in favor of Arkitektonika.
252     */
253    @Deprecated(forRemoval = true, since = "6.11.0")
254    public void upload(
255            final @NonNull Plot plot,
256            final @Nullable UUID uuid,
257            final @Nullable String file,
258            final @NonNull RunnableVal<URL> whenDone
259    ) {
260        plot.getHome(home -> SchematicHandler.upload(uuid, file, "zip", new RunnableVal<>() {
261            @Override
262            public void run(OutputStream output) {
263                try (final ZipOutputStream zos = new ZipOutputStream(output)) {
264                    File dat = getDat(plot.getWorldName());
265                    Location spawn = getSpawn(plot.getWorldName());
266                    if (dat != null) {
267                        ZipEntry ze = new ZipEntry("world" + File.separator + dat.getName());
268                        zos.putNextEntry(ze);
269                        try (NBTInputStream nis = new NBTInputStream(new GZIPInputStream(new FileInputStream(dat)))) {
270                            Map<String, Tag> tag = ((CompoundTag) nis.readNamedTag().getTag()).getValue();
271                            Map<String, Tag> newMap = new HashMap<>();
272                            for (Map.Entry<String, Tag> entry : tag.entrySet()) {
273                                if (!entry.getKey().equals("Data")) {
274                                    newMap.put(entry.getKey(), entry.getValue());
275                                    continue;
276                                }
277                                Map<String, Tag> data = new HashMap<>(((CompoundTag) entry.getValue()).getValue());
278                                data.put("SpawnX", new IntTag(home.getX()));
279                                data.put("SpawnY", new IntTag(home.getY()));
280                                data.put("SpawnZ", new IntTag(home.getZ()));
281                                newMap.put("Data", new CompoundTag(data));
282                            }
283                            try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
284                                try (NBTOutputStream out = new NBTOutputStream(new GZIPOutputStream(baos, true))) {
285                                    //TODO Find what this should be called
286                                    out.writeNamedTag("Schematic????", new CompoundTag(newMap));
287                                }
288                                zos.write(baos.toByteArray());
289                            }
290                        }
291                    }
292                    setSpawn(spawn);
293                    byte[] buffer = new byte[1024];
294                    Set<BlockVector2> added = new HashSet<>();
295                    for (Plot current : plot.getConnectedPlots()) {
296                        Location bot = current.getBottomAbs();
297                        Location top = current.getTopAbs();
298                        int brx = bot.getX() >> 9;
299                        int brz = bot.getZ() >> 9;
300                        int trx = top.getX() >> 9;
301                        int trz = top.getZ() >> 9;
302                        Set<BlockVector2> files = getChunkChunks(bot.getWorldName());
303                        for (BlockVector2 mca : files) {
304                            if (mca.getX() >= brx && mca.getX() <= trx && mca.getZ() >= brz && mca.getZ() <= trz && !added.contains(
305                                    mca)) {
306                                final File file = getMcr(plot.getWorldName(), mca.getX(), mca.getZ());
307                                if (file != null) {
308                                    //final String name = "r." + (x - cx) + "." + (z - cz) + ".mca";
309                                    String name = file.getName();
310                                    final ZipEntry ze = new ZipEntry("world" + File.separator + "region" + File.separator + name);
311                                    zos.putNextEntry(ze);
312                                    added.add(mca);
313                                    try (FileInputStream in = new FileInputStream(file)) {
314                                        int len;
315                                        while ((len = in.read(buffer)) > 0) {
316                                            zos.write(buffer, 0, len);
317                                        }
318                                    }
319                                    zos.closeEntry();
320                                }
321                            }
322                        }
323                    }
324                    zos.closeEntry();
325                    zos.flush();
326                    zos.finish();
327                } catch (IOException e) {
328                    e.printStackTrace();
329                }
330            }
331        }, whenDone));
332    }
333
334    final @Nullable File getDat(final @NonNull String world) {
335        File file = new File(PlotSquared.platform().worldContainer() + File.separator + world + File.separator + "level.dat");
336        if (file.exists()) {
337            return file;
338        }
339        return null;
340    }
341
342    @Nullable
343    private File getMcr(final @NonNull String world, final int x, final int z) {
344        final File file =
345                new File(
346                        PlotSquared.platform().worldContainer(),
347                        world + File.separator + "region" + File.separator + "r." + x + '.' + z + ".mca"
348                );
349        if (file.exists()) {
350            return file;
351        }
352        return null;
353    }
354
355
356    public Set<BlockVector2> getChunkChunks(String world) {
357        File folder = new File(PlotSquared.platform().worldContainer(), world + File.separator + "region");
358        File[] regionFiles = folder.listFiles();
359        if (regionFiles == null) {
360            throw new RuntimeException("Could not find worlds folder: " + folder + " ? (no read access?)");
361        }
362        HashSet<BlockVector2> chunks = new HashSet<>();
363        for (File file : regionFiles) {
364            String name = file.getName();
365            if (name.endsWith("mca")) {
366                String[] split = name.split("\\.");
367                try {
368                    int x = Integer.parseInt(split[1]);
369                    int z = Integer.parseInt(split[2]);
370                    BlockVector2 loc = BlockVector2.at(x, z);
371                    chunks.add(loc);
372                } catch (NumberFormatException ignored) {
373                }
374            }
375        }
376        return chunks;
377    }
378
379    /**
380     * Check if two blocks are the same type)
381     *
382     * @param block1 First block
383     * @param block2 Second block
384     * @return {@code true} if the blocks have the same type, {@code false} if not
385     */
386    public abstract boolean isBlockSame(@NonNull BlockState block1, @NonNull BlockState block2);
387
388    /**
389     * Get the player health
390     *
391     * @param player Player
392     * @return Non-negative health
393     */
394    @NonNegative
395    public abstract double getHealth(@NonNull PlotPlayer<?> player);
396
397    /**
398     * Set the player health
399     *
400     * @param player Player health
401     * @param health Non-negative health
402     */
403    public abstract void setHealth(@NonNull PlotPlayer<?> player, @NonNegative double health);
404
405    /**
406     * Get the player food level
407     *
408     * @param player Player
409     * @return Non-negative food level
410     */
411    @NonNegative
412    public abstract int getFoodLevel(@NonNull PlotPlayer<?> player);
413
414    /**
415     * Set the player food level
416     *
417     * @param player    Player food level
418     * @param foodLevel Non-negative food level
419     */
420    public abstract void setFoodLevel(@NonNull PlotPlayer<?> player, @NonNegative int foodLevel);
421
422    /**
423     * Get all entity types belonging to an entity category
424     *
425     * @param category Entity category
426     * @return Set containing all entities belonging to the given category
427     */
428    public @NonNull
429    abstract Set<EntityType> getTypesInCategory(@NonNull String category);
430
431    /**
432     * Get all recognized tile entity types
433     *
434     * @return Collection containing all known tile entity types
435     */
436    public @NonNull
437    abstract Collection<BlockType> getTileEntityTypes();
438
439    /**
440     * Get the tile entity count in a chunk
441     *
442     * @param world World
443     * @param chunk Chunk coordinates
444     * @return Tile entity count
445     */
446    @NonNegative
447    public abstract int getTileEntityCount(@NonNull String world, @NonNull BlockVector2 chunk);
448
449}