001 package net.minecraftforge.common; 002 003 import java.io.DataInputStream; 004 import java.io.File; 005 import java.io.FileInputStream; 006 import java.io.IOException; 007 import java.util.HashSet; 008 import java.util.LinkedHashSet; 009 import java.util.LinkedList; 010 import java.util.List; 011 import java.util.Map; 012 import java.util.Set; 013 import java.util.UUID; 014 import java.util.logging.Level; 015 016 import com.google.common.cache.Cache; 017 import com.google.common.cache.CacheBuilder; 018 import com.google.common.collect.ArrayListMultimap; 019 import com.google.common.collect.BiMap; 020 import com.google.common.collect.HashBiMap; 021 import com.google.common.collect.HashMultimap; 022 import com.google.common.collect.ImmutableList; 023 import com.google.common.collect.ImmutableSet; 024 import com.google.common.collect.ImmutableSetMultimap; 025 import com.google.common.collect.LinkedHashMultimap; 026 import com.google.common.collect.ListMultimap; 027 import com.google.common.collect.Lists; 028 import com.google.common.collect.MapMaker; 029 import com.google.common.collect.Maps; 030 import com.google.common.collect.Multimap; 031 import com.google.common.collect.Multiset; 032 import com.google.common.collect.SetMultimap; 033 import com.google.common.collect.Sets; 034 import com.google.common.collect.TreeMultiset; 035 036 import cpw.mods.fml.common.FMLLog; 037 import cpw.mods.fml.common.Loader; 038 import cpw.mods.fml.common.ModContainer; 039 040 import net.minecraft.src.Chunk; 041 import net.minecraft.src.ChunkCoordIntPair; 042 import net.minecraft.src.CompressedStreamTools; 043 import net.minecraft.src.Entity; 044 import net.minecraft.src.EntityPlayer; 045 import net.minecraft.src.MathHelper; 046 import net.minecraft.src.NBTBase; 047 import net.minecraft.src.NBTTagCompound; 048 import net.minecraft.src.NBTTagList; 049 import net.minecraft.src.World; 050 import net.minecraft.src.WorldServer; 051 import net.minecraftforge.common.ForgeChunkManager.Ticket; 052 053 /** 054 * Manages chunkloading for mods. 055 * 056 * The basic principle is a ticket based system. 057 * 1. Mods register a callback {@link #setForcedChunkLoadingCallback(Object, LoadingCallback)} 058 * 2. Mods ask for a ticket {@link #requestTicket(Object, World, Type)} and then hold on to that ticket. 059 * 3. Mods request chunks to stay loaded {@link #forceChunk(Ticket, ChunkCoordIntPair)} or remove chunks from force loading {@link #unforceChunk(Ticket, ChunkCoordIntPair)}. 060 * 4. When a world unloads, the tickets associated with that world are saved by the chunk manager. 061 * 5. When a world loads, saved tickets are offered to the mods associated with the tickets. The {@link Ticket#getModData()} that is set by the mod should be used to re-register 062 * chunks to stay loaded (and maybe take other actions). 063 * 064 * The chunkloading is configurable at runtime. The file "config/forgeChunkLoading.cfg" contains both default configuration for chunkloading, and a sample individual mod 065 * specific override section. 066 * 067 * @author cpw 068 * 069 */ 070 public class ForgeChunkManager 071 { 072 private static int defaultMaxCount; 073 private static int defaultMaxChunks; 074 private static boolean overridesEnabled; 075 076 private static Map<World, Multimap<String, Ticket>> tickets = new MapMaker().weakKeys().makeMap(); 077 private static Map<String, Integer> ticketConstraints = Maps.newHashMap(); 078 private static Map<String, Integer> chunkConstraints = Maps.newHashMap(); 079 080 private static SetMultimap<String, Ticket> playerTickets = HashMultimap.create(); 081 082 private static Map<String, LoadingCallback> callbacks = Maps.newHashMap(); 083 084 private static Map<World, SetMultimap<ChunkCoordIntPair,Ticket>> forcedChunks = new MapMaker().weakKeys().makeMap(); 085 private static BiMap<UUID,Ticket> pendingEntities = HashBiMap.create(); 086 087 private static Map<World,Cache<Long, Chunk>> dormantChunkCache = new MapMaker().weakKeys().makeMap(); 088 089 private static File cfgFile; 090 private static Configuration config; 091 private static int playerTicketLength; 092 private static int dormantChunkCacheSize; 093 /** 094 * All mods requiring chunkloading need to implement this to handle the 095 * re-registration of chunk tickets at world loading time 096 * 097 * @author cpw 098 * 099 */ 100 public interface LoadingCallback 101 { 102 /** 103 * Called back when tickets are loaded from the world to allow the 104 * mod to re-register the chunks associated with those tickets. The list supplied 105 * here is truncated to length prior to use. Tickets unwanted by the 106 * mod must be disposed of manually unless the mod is an OrderedLoadingCallback instance 107 * in which case, they will have been disposed of by the earlier callback. 108 * 109 * @param tickets The tickets to re-register. The list is immutable and cannot be manipulated directly. Copy it first. 110 * @param world the world 111 */ 112 public void ticketsLoaded(List<Ticket> tickets, World world); 113 } 114 115 /** 116 * This is a special LoadingCallback that can be implemented as well as the 117 * LoadingCallback to provide access to additional behaviour. 118 * Specifically, this callback will fire prior to Forge dropping excess 119 * tickets. Tickets in the returned list are presumed ordered and excess will 120 * be truncated from the returned list. 121 * This allows the mod to control not only if they actually <em>want</em> a ticket but 122 * also their preferred ticket ordering. 123 * 124 * @author cpw 125 * 126 */ 127 public interface OrderedLoadingCallback extends LoadingCallback 128 { 129 /** 130 * Called back when tickets are loaded from the world to allow the 131 * mod to decide if it wants the ticket still, and prioritise overflow 132 * based on the ticket count. 133 * WARNING: You cannot force chunks in this callback, it is strictly for allowing the mod 134 * to be more selective in which tickets it wishes to preserve in an overflow situation 135 * 136 * @param tickets The tickets that you will want to select from. The list is immutable and cannot be manipulated directly. Copy it first. 137 * @param world The world 138 * @param maxTicketCount The maximum number of tickets that will be allowed. 139 * @return A list of the tickets this mod wishes to continue using. This list will be truncated 140 * to "maxTicketCount" size after the call returns and then offered to the other callback 141 * method 142 */ 143 public List<Ticket> ticketsLoaded(List<Ticket> tickets, World world, int maxTicketCount); 144 } 145 public enum Type 146 { 147 148 /** 149 * For non-entity registrations 150 */ 151 NORMAL, 152 /** 153 * For entity registrations 154 */ 155 ENTITY 156 } 157 public static class Ticket 158 { 159 private String modId; 160 private Type ticketType; 161 private LinkedHashSet<ChunkCoordIntPair> requestedChunks; 162 private NBTTagCompound modData; 163 private World world; 164 private int maxDepth; 165 private String entityClazz; 166 private int entityChunkX; 167 private int entityChunkZ; 168 private Entity entity; 169 private String player; 170 171 Ticket(String modId, Type type, World world) 172 { 173 this.modId = modId; 174 this.ticketType = type; 175 this.world = world; 176 this.maxDepth = getMaxChunkDepthFor(modId); 177 this.requestedChunks = Sets.newLinkedHashSet(); 178 } 179 180 Ticket(String modId, Type type, World world, EntityPlayer player) 181 { 182 this(modId, type, world); 183 if (player != null) 184 { 185 this.player = player.getEntityName(); 186 } 187 else 188 { 189 FMLLog.log(Level.SEVERE, "Attempt to create a player ticket without a valid player"); 190 throw new RuntimeException(); 191 } 192 } 193 /** 194 * The chunk list depth can be manipulated up to the maximal grant allowed for the mod. This value is configurable. Once the maximum is reached, 195 * the least recently forced chunk, by original registration time, is removed from the forced chunk list. 196 * 197 * @param depth The new depth to set 198 */ 199 public void setChunkListDepth(int depth) 200 { 201 if (depth > getMaxChunkDepthFor(modId) || (depth <= 0 && getMaxChunkDepthFor(modId) > 0)) 202 { 203 FMLLog.warning("The mod %s tried to modify the chunk ticket depth to: %d, its allowed maximum is: %d", modId, depth, getMaxChunkDepthFor(modId)); 204 } 205 else 206 { 207 this.maxDepth = depth; 208 } 209 } 210 /** 211 * Get the maximum chunk depth size 212 * 213 * @return The maximum chunk depth size 214 */ 215 public int getMaxChunkListDepth() 216 { 217 return getMaxChunkDepthFor(modId); 218 } 219 220 /** 221 * Bind the entity to the ticket for {@link Type#ENTITY} type tickets. Other types will throw a runtime exception. 222 * 223 * @param entity The entity to bind 224 */ 225 public void bindEntity(Entity entity) 226 { 227 if (ticketType!=Type.ENTITY) 228 { 229 throw new RuntimeException("Cannot bind an entity to a non-entity ticket"); 230 } 231 this.entity = entity; 232 } 233 234 /** 235 * Retrieve the {@link NBTTagCompound} that stores mod specific data for the chunk ticket. 236 * Example data to store would be a TileEntity or Block location. This is persisted with the ticket and 237 * provided to the {@link LoadingCallback} for the mod. It is recommended to use this to recover 238 * useful state information for the forced chunks. 239 * 240 * @return The custom compound tag for mods to store additional chunkloading data 241 */ 242 public NBTTagCompound getModData() 243 { 244 if (this.modData == null) 245 { 246 this.modData = new NBTTagCompound(); 247 } 248 return modData; 249 } 250 251 /** 252 * Get the entity associated with this {@link Type#ENTITY} type ticket 253 * @return 254 */ 255 public Entity getEntity() 256 { 257 return entity; 258 } 259 260 /** 261 * Is this a player associated ticket rather than a mod associated ticket? 262 * 263 * @return 264 */ 265 public boolean isPlayerTicket() 266 { 267 return player != null; 268 } 269 270 /** 271 * Get the player associated with this ticket 272 * @return 273 */ 274 public String getPlayerName() 275 { 276 return player; 277 } 278 } 279 280 static void loadWorld(World world) 281 { 282 ArrayListMultimap<String, Ticket> newTickets = ArrayListMultimap.<String, Ticket>create(); 283 tickets.put(world, newTickets); 284 285 SetMultimap<ChunkCoordIntPair,Ticket> forcedChunkMap = LinkedHashMultimap.create(); 286 forcedChunks.put(world, forcedChunkMap); 287 288 if (!(world instanceof WorldServer)) 289 { 290 return; 291 } 292 293 dormantChunkCache.put(world, CacheBuilder.newBuilder().maximumSize(dormantChunkCacheSize).<Long, Chunk>build()); 294 WorldServer worldServer = (WorldServer) world; 295 File chunkDir = worldServer.getChunkSaveLocation(); 296 File chunkLoaderData = new File(chunkDir, "forcedchunks.dat"); 297 298 if (chunkLoaderData.exists() && chunkLoaderData.isFile()) 299 { 300 ArrayListMultimap<String, Ticket> loadedTickets = ArrayListMultimap.<String, Ticket>create(); 301 ArrayListMultimap<String, Ticket> playerLoadedTickets = ArrayListMultimap.<String, Ticket>create(); 302 NBTTagCompound forcedChunkData; 303 try 304 { 305 forcedChunkData = CompressedStreamTools.read(chunkLoaderData); 306 } 307 catch (IOException e) 308 { 309 FMLLog.log(Level.WARNING, e, "Unable to read forced chunk data at %s - it will be ignored", chunkLoaderData.getAbsolutePath()); 310 return; 311 } 312 NBTTagList ticketList = forcedChunkData.getTagList("TicketList"); 313 for (int i = 0; i < ticketList.tagCount(); i++) 314 { 315 NBTTagCompound ticketHolder = (NBTTagCompound) ticketList.tagAt(i); 316 String modId = ticketHolder.getString("Owner"); 317 boolean isPlayer = "Forge".equals(modId); 318 319 if (!isPlayer && !Loader.isModLoaded(modId)) 320 { 321 FMLLog.warning("Found chunkloading data for mod %s which is currently not available or active - it will be removed from the world save", modId); 322 continue; 323 } 324 325 if (!isPlayer && !callbacks.containsKey(modId)) 326 { 327 FMLLog.warning("The mod %s has registered persistent chunkloading data but doesn't seem to want to be called back with it - it will be removed from the world save", modId); 328 continue; 329 } 330 331 NBTTagList tickets = ticketHolder.getTagList("Tickets"); 332 for (int j = 0; j < tickets.tagCount(); j++) 333 { 334 NBTTagCompound ticket = (NBTTagCompound) tickets.tagAt(j); 335 modId = ticket.hasKey("ModId") ? ticket.getString("ModId") : modId; 336 Type type = Type.values()[ticket.getByte("Type")]; 337 byte ticketChunkDepth = ticket.getByte("ChunkListDepth"); 338 Ticket tick = new Ticket(modId, type, world); 339 if (ticket.hasKey("ModData")) 340 { 341 tick.modData = ticket.getCompoundTag("ModData"); 342 } 343 if (ticket.hasKey("Player")) 344 { 345 tick.player = ticket.getString("Player"); 346 playerLoadedTickets.put(tick.modId, tick); 347 playerTickets.put(tick.player, tick); 348 } 349 else 350 { 351 loadedTickets.put(modId, tick); 352 } 353 if (type == Type.ENTITY) 354 { 355 tick.entityChunkX = ticket.getInteger("chunkX"); 356 tick.entityChunkZ = ticket.getInteger("chunkZ"); 357 UUID uuid = new UUID(ticket.getLong("PersistentIDMSB"), ticket.getLong("PersistentIDLSB")); 358 // add the ticket to the "pending entity" list 359 pendingEntities.put(uuid, tick); 360 } 361 } 362 } 363 364 for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values())) 365 { 366 if (tick.ticketType == Type.ENTITY && tick.entity == null) 367 { 368 // force the world to load the entity's chunk 369 // the load will come back through the loadEntity method and attach the entity 370 // to the ticket 371 world.getChunkFromChunkCoords(tick.entityChunkX, tick.entityChunkZ); 372 } 373 } 374 for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values())) 375 { 376 if (tick.ticketType == Type.ENTITY && tick.entity == null) 377 { 378 FMLLog.warning("Failed to load persistent chunkloading entity %s from store.", pendingEntities.inverse().get(tick)); 379 loadedTickets.remove(tick.modId, tick); 380 } 381 } 382 pendingEntities.clear(); 383 // send callbacks 384 for (String modId : loadedTickets.keySet()) 385 { 386 LoadingCallback loadingCallback = callbacks.get(modId); 387 int maxTicketLength = getMaxTicketLengthFor(modId); 388 List<Ticket> tickets = loadedTickets.get(modId); 389 if (loadingCallback instanceof OrderedLoadingCallback) 390 { 391 OrderedLoadingCallback orderedLoadingCallback = (OrderedLoadingCallback) loadingCallback; 392 tickets = orderedLoadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world, maxTicketLength); 393 } 394 if (tickets.size() > maxTicketLength) 395 { 396 FMLLog.warning("The mod %s has too many open chunkloading tickets %d. Excess will be dropped", modId, tickets.size()); 397 tickets.subList(maxTicketLength, tickets.size()).clear(); 398 } 399 ForgeChunkManager.tickets.get(world).putAll(modId, tickets); 400 loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world); 401 } 402 for (String modId : playerLoadedTickets.keySet()) 403 { 404 LoadingCallback loadingCallback = callbacks.get(modId); 405 List<Ticket> tickets = playerLoadedTickets.get(modId); 406 ForgeChunkManager.tickets.get(world).putAll("Forge", tickets); 407 loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world); 408 } 409 } 410 } 411 412 /** 413 * Set a chunkloading callback for the supplied mod object 414 * 415 * @param mod The mod instance registering the callback 416 * @param callback The code to call back when forced chunks are loaded 417 */ 418 public static void setForcedChunkLoadingCallback(Object mod, LoadingCallback callback) 419 { 420 ModContainer container = getContainer(mod); 421 if (container == null) 422 { 423 FMLLog.warning("Unable to register a callback for an unknown mod %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod)); 424 return; 425 } 426 427 callbacks.put(container.getModId(), callback); 428 } 429 430 /** 431 * Discover the available tickets for the mod in the world 432 * 433 * @param mod The mod that will own the tickets 434 * @param world The world 435 * @return The count of tickets left for the mod in the supplied world 436 */ 437 public static int ticketCountAvailableFor(Object mod, World world) 438 { 439 ModContainer container = getContainer(mod); 440 if (container!=null) 441 { 442 String modId = container.getModId(); 443 int allowedCount = getMaxTicketLengthFor(modId); 444 return allowedCount - tickets.get(world).get(modId).size(); 445 } 446 else 447 { 448 return 0; 449 } 450 } 451 452 private static ModContainer getContainer(Object mod) 453 { 454 ModContainer container = Loader.instance().getModObjectList().inverse().get(mod); 455 return container; 456 } 457 458 private static int getMaxTicketLengthFor(String modId) 459 { 460 int allowedCount = ticketConstraints.containsKey(modId) && overridesEnabled ? ticketConstraints.get(modId) : defaultMaxCount; 461 return allowedCount; 462 } 463 464 private static int getMaxChunkDepthFor(String modId) 465 { 466 int allowedCount = chunkConstraints.containsKey(modId) && overridesEnabled ? chunkConstraints.get(modId) : defaultMaxChunks; 467 return allowedCount; 468 } 469 470 public static Ticket requestPlayerTicket(Object mod, EntityPlayer player, World world, Type type) 471 { 472 ModContainer mc = getContainer(mod); 473 if (mc == null) 474 { 475 FMLLog.log(Level.SEVERE, "Failed to locate the container for mod instance %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod)); 476 return null; 477 } 478 if (playerTickets.get(player.getEntityName()).size()>playerTicketLength) 479 { 480 FMLLog.warning("Unable to assign further chunkloading tickets to player %s (on behalf of mod %s)", player.getEntityName(), mc.getModId()); 481 return null; 482 } 483 Ticket ticket = new Ticket(mc.getModId(),type,world,player); 484 playerTickets.put(player.getEntityName(), ticket); 485 tickets.get(world).put("Forge", ticket); 486 return ticket; 487 } 488 /** 489 * Request a chunkloading ticket of the appropriate type for the supplied mod 490 * 491 * @param mod The mod requesting a ticket 492 * @param world The world in which it is requesting the ticket 493 * @param type The type of ticket 494 * @return A ticket with which to register chunks for loading, or null if no further tickets are available 495 */ 496 public static Ticket requestTicket(Object mod, World world, Type type) 497 { 498 ModContainer container = getContainer(mod); 499 if (container == null) 500 { 501 FMLLog.log(Level.SEVERE, "Failed to locate the container for mod instance %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod)); 502 return null; 503 } 504 String modId = container.getModId(); 505 if (!callbacks.containsKey(modId)) 506 { 507 FMLLog.severe("The mod %s has attempted to request a ticket without a listener in place", modId); 508 throw new RuntimeException("Invalid ticket request"); 509 } 510 511 int allowedCount = ticketConstraints.containsKey(modId) ? ticketConstraints.get(modId) : defaultMaxCount; 512 513 if (tickets.get(world).get(modId).size() >= allowedCount) 514 { 515 FMLLog.info("The mod %s has attempted to allocate a chunkloading ticket beyond it's currently allocated maximum : %d", modId, allowedCount); 516 return null; 517 } 518 Ticket ticket = new Ticket(modId, type, world); 519 tickets.get(world).put(modId, ticket); 520 521 return ticket; 522 } 523 524 /** 525 * Release the ticket back to the system. This will also unforce any chunks held by the ticket so that they can be unloaded and/or stop ticking. 526 * 527 * @param ticket The ticket to release 528 */ 529 public static void releaseTicket(Ticket ticket) 530 { 531 if (ticket == null) 532 { 533 return; 534 } 535 if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket)) 536 { 537 return; 538 } 539 if (ticket.requestedChunks!=null) 540 { 541 for (ChunkCoordIntPair chunk : ImmutableSet.copyOf(ticket.requestedChunks)) 542 { 543 unforceChunk(ticket, chunk); 544 } 545 } 546 if (ticket.isPlayerTicket()) 547 { 548 playerTickets.remove(ticket.player, ticket); 549 tickets.get(ticket.world).remove("Forge",ticket); 550 } 551 else 552 { 553 tickets.get(ticket.world).remove(ticket.modId, ticket); 554 } 555 } 556 557 /** 558 * Force the supplied chunk coordinate to be loaded by the supplied ticket. If the ticket's {@link Ticket#maxDepth} is exceeded, the least 559 * recently registered chunk is unforced and may be unloaded. 560 * It is safe to force the chunk several times for a ticket, it will not generate duplication or change the ordering. 561 * 562 * @param ticket The ticket registering the chunk 563 * @param chunk The chunk to force 564 */ 565 public static void forceChunk(Ticket ticket, ChunkCoordIntPair chunk) 566 { 567 if (ticket == null || chunk == null) 568 { 569 return; 570 } 571 if (ticket.ticketType == Type.ENTITY && ticket.entity == null) 572 { 573 throw new RuntimeException("Attempted to use an entity ticket to force a chunk, without an entity"); 574 } 575 if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket)) 576 { 577 FMLLog.severe("The mod %s attempted to force load a chunk with an invalid ticket. This is not permitted.", ticket.modId); 578 return; 579 } 580 ticket.requestedChunks.add(chunk); 581 forcedChunks.get(ticket.world).put(chunk, ticket); 582 if (ticket.maxDepth > 0 && ticket.requestedChunks.size() > ticket.maxDepth) 583 { 584 ChunkCoordIntPair removed = ticket.requestedChunks.iterator().next(); 585 unforceChunk(ticket,removed); 586 } 587 } 588 589 /** 590 * Reorganize the internal chunk list so that the chunk supplied is at the *end* of the list 591 * This helps if you wish to guarantee a certain "automatic unload ordering" for the chunks 592 * in the ticket list 593 * 594 * @param ticket The ticket holding the chunk list 595 * @param chunk The chunk you wish to push to the end (so that it would be unloaded last) 596 */ 597 public static void reorderChunk(Ticket ticket, ChunkCoordIntPair chunk) 598 { 599 if (ticket == null || chunk == null || !ticket.requestedChunks.contains(chunk)) 600 { 601 return; 602 } 603 ticket.requestedChunks.remove(chunk); 604 ticket.requestedChunks.add(chunk); 605 } 606 /** 607 * Unforce the supplied chunk, allowing it to be unloaded and stop ticking. 608 * 609 * @param ticket The ticket holding the chunk 610 * @param chunk The chunk to unforce 611 */ 612 public static void unforceChunk(Ticket ticket, ChunkCoordIntPair chunk) 613 { 614 if (ticket == null || chunk == null) 615 { 616 return; 617 } 618 ticket.requestedChunks.remove(chunk); 619 forcedChunks.get(ticket.world).remove(chunk, ticket); 620 } 621 622 static void loadConfiguration() 623 { 624 for (String mod : config.categories.keySet()) 625 { 626 if (mod.equals("Forge") || mod.equals("defaults")) 627 { 628 continue; 629 } 630 Property modTC = config.get(mod, "maximumTicketCount", 200); 631 Property modCPT = config.get(mod, "maximumChunksPerTicket", 25); 632 ticketConstraints.put(mod, modTC.getInt(200)); 633 chunkConstraints.put(mod, modCPT.getInt(25)); 634 } 635 config.save(); 636 } 637 638 /** 639 * The list of persistent chunks in the world. This set is immutable. 640 * @param world 641 * @return 642 */ 643 public static SetMultimap<ChunkCoordIntPair, Ticket> getPersistentChunksFor(World world) 644 { 645 return forcedChunks.containsKey(world) ? ImmutableSetMultimap.copyOf(forcedChunks.get(world)) : ImmutableSetMultimap.<ChunkCoordIntPair,Ticket>of(); 646 } 647 648 static void saveWorld(World world) 649 { 650 // only persist persistent worlds 651 if (!(world instanceof WorldServer)) { return; } 652 WorldServer worldServer = (WorldServer) world; 653 File chunkDir = worldServer.getChunkSaveLocation(); 654 File chunkLoaderData = new File(chunkDir, "forcedchunks.dat"); 655 656 NBTTagCompound forcedChunkData = new NBTTagCompound(); 657 NBTTagList ticketList = new NBTTagList(); 658 forcedChunkData.setTag("TicketList", ticketList); 659 660 Multimap<String, Ticket> ticketSet = tickets.get(worldServer); 661 for (String modId : ticketSet.keySet()) 662 { 663 NBTTagCompound ticketHolder = new NBTTagCompound(); 664 ticketList.appendTag(ticketHolder); 665 666 ticketHolder.setString("Owner", modId); 667 NBTTagList tickets = new NBTTagList(); 668 ticketHolder.setTag("Tickets", tickets); 669 670 for (Ticket tick : ticketSet.get(modId)) 671 { 672 NBTTagCompound ticket = new NBTTagCompound(); 673 ticket.setByte("Type", (byte) tick.ticketType.ordinal()); 674 ticket.setByte("ChunkListDepth", (byte) tick.maxDepth); 675 if (tick.isPlayerTicket()) 676 { 677 ticket.setString("ModId", tick.modId); 678 ticket.setString("Player", tick.player); 679 } 680 if (tick.modData != null) 681 { 682 ticket.setCompoundTag("ModData", tick.modData); 683 } 684 if (tick.ticketType == Type.ENTITY && tick.entity != null) 685 { 686 ticket.setInteger("chunkX", MathHelper.floor_double(tick.entity.chunkCoordX)); 687 ticket.setInteger("chunkZ", MathHelper.floor_double(tick.entity.chunkCoordZ)); 688 ticket.setLong("PersistentIDMSB", tick.entity.getPersistentID().getMostSignificantBits()); 689 ticket.setLong("PersistentIDLSB", tick.entity.getPersistentID().getLeastSignificantBits()); 690 tickets.appendTag(ticket); 691 } 692 else if (tick.ticketType != Type.ENTITY) 693 { 694 tickets.appendTag(ticket); 695 } 696 } 697 } 698 try 699 { 700 CompressedStreamTools.write(forcedChunkData, chunkLoaderData); 701 } 702 catch (IOException e) 703 { 704 FMLLog.log(Level.WARNING, e, "Unable to write forced chunk data to %s - chunkloading won't work", chunkLoaderData.getAbsolutePath()); 705 return; 706 } 707 } 708 709 static void loadEntity(Entity entity) 710 { 711 UUID id = entity.getPersistentID(); 712 Ticket tick = pendingEntities.get(id); 713 if (tick != null) 714 { 715 tick.bindEntity(entity); 716 pendingEntities.remove(id); 717 } 718 } 719 720 public static void putDormantChunk(long coords, Chunk chunk) 721 { 722 Cache<Long, Chunk> cache = dormantChunkCache.get(chunk.worldObj); 723 if (cache != null) 724 { 725 cache.put(coords, chunk); 726 } 727 } 728 729 public static Chunk fetchDormantChunk(long coords, World world) 730 { 731 Cache<Long, Chunk> cache = dormantChunkCache.get(world); 732 return cache == null ? null : cache.getIfPresent(coords); 733 } 734 735 static void captureConfig(File configDir) 736 { 737 cfgFile = new File(configDir,"forgeChunkLoading.cfg"); 738 config = new Configuration(cfgFile, true); 739 config.categories.clear(); 740 try 741 { 742 config.load(); 743 } 744 catch (Exception e) 745 { 746 File dest = new File(cfgFile.getParentFile(),"forgeChunkLoading.cfg.bak"); 747 if (dest.exists()) 748 { 749 dest.delete(); 750 } 751 cfgFile.renameTo(dest); 752 FMLLog.log(Level.SEVERE, e, "A critical error occured reading the forgeChunkLoading.cfg file, defaults will be used - the invalid file is backed up at forgeChunkLoading.cfg.bak"); 753 } 754 config.addCustomCategoryComment("defaults", "Default configuration for forge chunk loading control"); 755 Property maxTicketCount = config.get("defaults", "maximumTicketCount", 200); 756 maxTicketCount.comment = "The default maximum ticket count for a mod which does not have an override\n" + 757 "in this file. This is the number of chunk loading requests a mod is allowed to make."; 758 defaultMaxCount = maxTicketCount.getInt(200); 759 760 Property maxChunks = config.get("defaults", "maximumChunksPerTicket", 25); 761 maxChunks.comment = "The default maximum number of chunks a mod can force, per ticket, \n" + 762 "for a mod without an override. This is the maximum number of chunks a single ticket can force."; 763 defaultMaxChunks = maxChunks.getInt(25); 764 765 Property playerTicketCount = config.get("defaults", "playetTicketCount", 500); 766 playerTicketCount.comment = "The number of tickets a player can be assigned instead of a mod. This is shared across all mods and it is up to the mods to use it."; 767 playerTicketLength = playerTicketCount.getInt(500); 768 769 Property dormantChunkCacheSizeProperty = config.get("defaults", "dormantChunkCacheSize", 0); 770 dormantChunkCacheSizeProperty.comment = "Unloaded chunks can first be kept in a dormant cache for quicker\n" + 771 "loading times. Specify the size of that cache here"; 772 dormantChunkCacheSize = dormantChunkCacheSizeProperty.getInt(0); 773 FMLLog.info("Configured a dormant chunk cache size of %d", dormantChunkCacheSizeProperty.getInt(0)); 774 775 Property modOverridesEnabled = config.get("defaults", "enabled", true); 776 modOverridesEnabled.comment = "Are mod overrides enabled?"; 777 overridesEnabled = modOverridesEnabled.getBoolean(true); 778 779 config.addCustomCategoryComment("Forge", "Sample mod specific control section.\n" + 780 "Copy this section and rename the with the modid for the mod you wish to override.\n" + 781 "A value of zero in either entry effectively disables any chunkloading capabilities\n" + 782 "for that mod"); 783 784 Property sampleTC = config.get("Forge", "maximumTicketCount", 200); 785 sampleTC.comment = "Maximum ticket count for the mod. Zero disables chunkloading capabilities."; 786 sampleTC = config.get("Forge", "maximumChunksPerTicket", 25); 787 sampleTC.comment = "Maximum chunks per ticket for the mod."; 788 for (String mod : config.categories.keySet()) 789 { 790 if (mod.equals("Forge") || mod.equals("defaults")) 791 { 792 continue; 793 } 794 Property modTC = config.get(mod, "maximumTicketCount", 200); 795 Property modCPT = config.get(mod, "maximumChunksPerTicket", 25); 796 } 797 } 798 799 800 public static Map<String,Property> getConfigMapFor(Object mod) 801 { 802 ModContainer container = getContainer(mod); 803 if (container != null) 804 { 805 Map<String, Property> map = config.categories.get(container.getModId()); 806 if (map == null) 807 { 808 map = Maps.newHashMap(); 809 config.categories.put(container.getModId(), map); 810 } 811 return map; 812 } 813 814 return null; 815 } 816 817 public static void addConfigProperty(Object mod, String propertyName, String value, Property.Type type) 818 { 819 ModContainer container = getContainer(mod); 820 if (container != null) 821 { 822 Map<String, Property> props = config.categories.get(container.getModId()); 823 props.put(propertyName, new Property(propertyName, value, type)); 824 } 825 } 826 }