    001package net.minecraft.world.gen;
    002
    003import java.io.IOException;
    004import java.util.ArrayList;
    005import java.util.HashSet;
    006import java.util.Iterator;
    007import java.util.List;
    008import java.util.Set;
    009
    010import net.minecraftforge.common.DimensionManager;
    011import net.minecraftforge.common.ForgeChunkManager;
    012
    013import cpw.mods.fml.common.registry.GameRegistry;
    014import net.minecraft.crash.CrashReport;
    015import net.minecraft.crash.CrashReportCategory;
    016import net.minecraft.entity.EnumCreatureType;
    017import net.minecraft.util.ChunkCoordinates;
    018import net.minecraft.util.IProgressUpdate;
    019import net.minecraft.util.LongHashMap;
    020import net.minecraft.util.ReportedException;
    021import net.minecraft.world.ChunkCoordIntPair;
    022import net.minecraft.world.ChunkPosition;
    023import net.minecraft.world.MinecraftException;
    024import net.minecraft.world.World;
    025import net.minecraft.world.WorldServer;
    026import net.minecraft.world.chunk.Chunk;
    027import net.minecraft.world.chunk.EmptyChunk;
    028import net.minecraft.world.chunk.IChunkProvider;
    029import net.minecraft.world.chunk.storage.IChunkLoader;
    030
    031public class ChunkProviderServer implements IChunkProvider
    032{
    033    /**
    034     * used by unload100OldestChunks to iterate the loadedChunkHashMap for unload (underlying assumption, first in,
    035     * first out)
    036     */
    037    private Set chunksToUnload = new HashSet();
    038    private Chunk defaultEmptyChunk;
    039    private IChunkProvider currentChunkProvider;
    040    public IChunkLoader currentChunkLoader;
    041
    042    /**
    043     * if this is false, the defaultEmptyChunk will be returned by the provider
    044     */
    045    public boolean loadChunkOnProvideRequest = true;
    046    private LongHashMap loadedChunkHashMap = new LongHashMap();
    047    private List loadedChunks = new ArrayList();
    048    private WorldServer worldObj;
    049
    050    public ChunkProviderServer(WorldServer par1WorldServer, IChunkLoader par2IChunkLoader, IChunkProvider par3IChunkProvider)
    051    {
    052        this.defaultEmptyChunk = new EmptyChunk(par1WorldServer, 0, 0);
    053        this.worldObj = par1WorldServer;
    054        this.currentChunkLoader = par2IChunkLoader;
    055        this.currentChunkProvider = par3IChunkProvider;
    056    }
    057
    058    /**
    059     * Checks to see if a chunk exists at x, y
    060     */
    061    public boolean chunkExists(int par1, int par2)
    062    {
    063        return this.loadedChunkHashMap.containsItem(ChunkCoordIntPair.chunkXZ2Int(par1, par2));
    064    }
    065
    066    /**
    067     * marks chunk for unload by "unload100OldestChunks"  if there is no spawn point, or if the center of the chunk is
    068     * outside 200 blocks (x or z) of the spawn
    069     */
    070    public void unloadChunksIfNotNearSpawn(int par1, int par2)
    071    {
    072        if (this.worldObj.provider.canRespawnHere() && DimensionManager.shouldLoadSpawn(this.worldObj.provider.dimensionId))
    073        {
    074            ChunkCoordinates chunkcoordinates = this.worldObj.getSpawnPoint();
    075            int k = par1 * 16 + 8 - chunkcoordinates.posX;
    076            int l = par2 * 16 + 8 - chunkcoordinates.posZ;
    077            short short1 = 128;
    078
    079            if (k < -short1 || k > short1 || l < -short1 || l > short1)
    080            {
    081                this.chunksToUnload.add(Long.valueOf(ChunkCoordIntPair.chunkXZ2Int(par1, par2)));
    082            }
    083        }
    084        else
    085        {
    086            this.chunksToUnload.add(Long.valueOf(ChunkCoordIntPair.chunkXZ2Int(par1, par2)));
    087        }
    088    }
    089
    090    /**
    091     * marks all chunks for unload, ignoring those near the spawn
    092     */
    093    public void unloadAllChunks()
    094    {
    095        Iterator iterator = this.loadedChunks.iterator();
    096
    097        while (iterator.hasNext())
    098        {
    099            Chunk chunk = (Chunk)iterator.next();
    100            this.unloadChunksIfNotNearSpawn(chunk.xPosition, chunk.zPosition);
    101        }
    102    }
    103
    104    /**
    105     * loads or generates the chunk at the chunk location specified
    106     */
    107    public Chunk loadChunk(int par1, int par2)
    108    {
    109        long k = ChunkCoordIntPair.chunkXZ2Int(par1, par2);
    110        this.chunksToUnload.remove(Long.valueOf(k));
    111        Chunk chunk = (Chunk)this.loadedChunkHashMap.getValueByKey(k);
    112
    113        if (chunk == null)
    114        {
    115            chunk = ForgeChunkManager.fetchDormantChunk(k, this.worldObj);
    116            if (chunk == null)
    117            {
    118                chunk = this.safeLoadChunk(par1, par2);
    119            }
    120
    121            if (chunk == null)
    122            {
    123                if (this.currentChunkProvider == null)
    124                {
    125                    chunk = this.defaultEmptyChunk;
    126                }
    127                else
    128                {
    129                    try
    130                    {
    131                        chunk = this.currentChunkProvider.provideChunk(par1, par2);
    132                    }
    133                    catch (Throwable throwable)
    134                    {
    135                        CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Exception generating new chunk");
    136                        CrashReportCategory crashreportcategory = crashreport.makeCategory("Chunk to be generated");
    137                        crashreportcategory.addCrashSection("Location", String.format("%d,%d", new Object[] {Integer.valueOf(par1), Integer.valueOf(par2)}));
    138                        crashreportcategory.addCrashSection("Position hash", Long.valueOf(k));
    139                        crashreportcategory.addCrashSection("Generator", this.currentChunkProvider.makeString());
    140                        throw new ReportedException(crashreport);
    141                    }
    142                }
    143            }
    144
    145            this.loadedChunkHashMap.add(k, chunk);
    146            this.loadedChunks.add(chunk);
    147
    148            if (chunk != null)
    149            {
    150                chunk.onChunkLoad();
    151            }
    152
    153            chunk.populateChunk(this, this, par1, par2);
    154        }
    155
    156        return chunk;
    157    }
    158
    159    /**
    160     * Will return back a chunk, if it doesn't exist and its not a MP client it will generates all the blocks for the
    161     * specified chunk from the map seed and chunk seed
    162     */
    163    public Chunk provideChunk(int par1, int par2)
    164    {
    165        Chunk chunk = (Chunk)this.loadedChunkHashMap.getValueByKey(ChunkCoordIntPair.chunkXZ2Int(par1, par2));
    166        return chunk == null ? (!this.worldObj.findingSpawnPoint && !this.loadChunkOnProvideRequest ? this.defaultEmptyChunk : this.loadChunk(par1, par2)) : chunk;
    167    }
    168
    169    /**
    170     * used by loadChunk, but catches any exceptions if the load fails.
    171     */
    172    private Chunk safeLoadChunk(int par1, int par2)
    173    {
    174        if (this.currentChunkLoader == null)
    175        {
    176            return null;
    177        }
    178        else
    179        {
    180            try
    181            {
    182                Chunk chunk = this.currentChunkLoader.loadChunk(this.worldObj, par1, par2);
    183
    184                if (chunk != null)
    185                {
    186                    chunk.lastSaveTime = this.worldObj.getTotalWorldTime();
    187
    188                    if (this.currentChunkProvider != null)
    189                    {
    190                        this.currentChunkProvider.recreateStructures(par1, par2);
    191                    }
    192                }
    193
    194                return chunk;
    195            }
    196            catch (Exception exception)
    197            {
    198                exception.printStackTrace();
    199                return null;
    200            }
    201        }
    202    }
    203
    204    /**
    205     * used by saveChunks, but catches any exceptions if the save fails.
    206     */
    207    private void safeSaveExtraChunkData(Chunk par1Chunk)
    208    {
    209        if (this.currentChunkLoader != null)
    210        {
    211            try
    212            {
    213                this.currentChunkLoader.saveExtraChunkData(this.worldObj, par1Chunk);
    214            }
    215            catch (Exception exception)
    216            {
    217                exception.printStackTrace();
    218            }
    219        }
    220    }
    221
    222    /**
    223     * used by saveChunks, but catches any exceptions if the save fails.
    224     */
    225    private void safeSaveChunk(Chunk par1Chunk)
    226    {
    227        if (this.currentChunkLoader != null)
    228        {
    229            try
    230            {
    231                par1Chunk.lastSaveTime = this.worldObj.getTotalWorldTime();
    232                this.currentChunkLoader.saveChunk(this.worldObj, par1Chunk);
    233            }
    234            catch (IOException ioexception)
    235            {
    236                ioexception.printStackTrace();
    237            }
    238            catch (MinecraftException minecraftexception)
    239            {
    240                minecraftexception.printStackTrace();
    241            }
    242        }
    243    }
    244
    245    /**
    246     * Populates chunk with ores etc etc
    247     */
    248    public void populate(IChunkProvider par1IChunkProvider, int par2, int par3)
    249    {
    250        Chunk chunk = this.provideChunk(par2, par3);
    251
    252        if (!chunk.isTerrainPopulated)
    253        {
    254            chunk.isTerrainPopulated = true;
    255
    256            if (this.currentChunkProvider != null)
    257            {
    258                this.currentChunkProvider.populate(par1IChunkProvider, par2, par3);
    259                GameRegistry.generateWorld(par2, par3, worldObj, currentChunkProvider, par1IChunkProvider);
    260                chunk.setChunkModified();
    261            }
    262        }
    263    }
    264
    265    /**
    266     * Two modes of operation: if passed true, save all Chunks in one go.  If passed false, save up to two chunks.
    267     * Return true if all chunks have been saved.
    268     */
    269    public boolean saveChunks(boolean par1, IProgressUpdate par2IProgressUpdate)
    270    {
    271        int i = 0;
    272
    273        for (int j = 0; j < this.loadedChunks.size(); ++j)
    274        {
    275            Chunk chunk = (Chunk)this.loadedChunks.get(j);
    276
    277            if (par1)
    278            {
    279                this.safeSaveExtraChunkData(chunk);
    280            }
    281
    282            if (chunk.needsSaving(par1))
    283            {
    284                this.safeSaveChunk(chunk);
    285                chunk.isModified = false;
    286                ++i;
    287
    288                if (i == 24 && !par1)
    289                {
    290                    return false;
    291                }
    292            }
    293        }
    294
    295        if (par1)
    296        {
    297            if (this.currentChunkLoader == null)
    298            {
    299                return true;
    300            }
    301
    302            this.currentChunkLoader.saveExtraData();
    303        }
    304
    305        return true;
    306    }
    307
    308    /**
    309     * Unloads chunks that are marked to be unloaded. This is not guaranteed to unload every such chunk.
    310     */
    311    public boolean unloadQueuedChunks()
    312    {
    313        if (!this.worldObj.canNotSave)
    314        {
    315            for (ChunkCoordIntPair forced : this.worldObj.getPersistentChunks().keySet())
    316            {
    317                this.chunksToUnload.remove(ChunkCoordIntPair.chunkXZ2Int(forced.chunkXPos, forced.chunkZPos));
    318            }
    319
    320            for (int i = 0; i < 100; ++i)
    321            {
    322                if (!this.chunksToUnload.isEmpty())
    323                {
    324                    Long olong = (Long)this.chunksToUnload.iterator().next();
    325                    Chunk chunk = (Chunk)this.loadedChunkHashMap.getValueByKey(olong.longValue());
    326                    chunk.onChunkUnload();
    327                    this.safeSaveChunk(chunk);
    328                    this.safeSaveExtraChunkData(chunk);
    329                    this.chunksToUnload.remove(olong);
    330                    this.loadedChunkHashMap.remove(olong.longValue());
    331                    this.loadedChunks.remove(chunk);
    332                    ForgeChunkManager.putDormantChunk(ChunkCoordIntPair.chunkXZ2Int(chunk.xPosition, chunk.zPosition), chunk);
    333                    if(loadedChunks.size() == 0 && ForgeChunkManager.getPersistentChunksFor(this.worldObj).size() == 0 && !DimensionManager.shouldLoadSpawn(this.worldObj.provider.dimensionId)) {
    334                        DimensionManager.unloadWorld(this.worldObj.provider.dimensionId);
    335                        return currentChunkProvider.unloadQueuedChunks();
    336                    }
    337                }
    338            }
    339
    340            if (this.currentChunkLoader != null)
    341            {
    342                this.currentChunkLoader.chunkTick();
    343            }
    344        }
    345
    346        return this.currentChunkProvider.unloadQueuedChunks();
    347    }
    348
    349    /**
    350     * Returns if the IChunkProvider supports saving.
    351     */
    352    public boolean canSave()
    353    {
    354        return !this.worldObj.canNotSave;
    355    }
    356
    357    /**
    358     * Converts the instance data to a readable string.
    359     */
    360    public String makeString()
    361    {
    362        return "ServerChunkCache: " + this.loadedChunkHashMap.getNumHashElements() + " Drop: " + this.chunksToUnload.size();
    363    }
    364
    365    /**
    366     * Returns a list of creatures of the specified type that can spawn at the given location.
    367     */
    368    public List getPossibleCreatures(EnumCreatureType par1EnumCreatureType, int par2, int par3, int par4)
    369    {
    370        return this.currentChunkProvider.getPossibleCreatures(par1EnumCreatureType, par2, par3, par4);
    371    }
    372
    373    /**
    374     * Returns the location of the closest structure of the specified type. If not found returns null.
    375     */
    376    public ChunkPosition findClosestStructure(World par1World, String par2Str, int par3, int par4, int par5)
    377    {
    378        return this.currentChunkProvider.findClosestStructure(par1World, par2Str, par3, par4, par5);
    379    }
    380
    381    public int getLoadedChunkCount()
    382    {
    383        return this.loadedChunkHashMap.getNumHashElements();
    384    }
    385
    386    public void recreateStructures(int par1, int par2) {}
    387}