summaryrefslogtreecommitdiffstats
path: root/nms-patches/MinecraftServer.patch
blob: 9c4cc3821ec62b13e92c8ac67594c9d6786d76d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
--- a/net/minecraft/server/MinecraftServer.java
+++ b/net/minecraft/server/MinecraftServer.java
@@ -59,6 +59,14 @@
 import org.apache.commons.lang3.Validate;
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
+// CraftBukkit start
+import jline.console.ConsoleReader;
+import joptsimple.OptionSet;
+import org.bukkit.Bukkit;
+import org.bukkit.craftbukkit.CraftServer;
+import org.bukkit.craftbukkit.Main;
+import org.bukkit.event.server.ServerLoadEvent;
+// CraftBukkit end
 
 public abstract class MinecraftServer implements IAsyncTaskHandler, IMojangStatistics, ICommandListener, Runnable {
 
@@ -129,7 +137,21 @@
     private boolean forceUpgrade;
     private float ap;
 
-    public MinecraftServer(@Nullable File file, Proxy proxy, DataFixer datafixer, CommandDispatcher commanddispatcher, YggdrasilAuthenticationService yggdrasilauthenticationservice, MinecraftSessionService minecraftsessionservice, GameProfileRepository gameprofilerepository, UserCache usercache) {
+    // CraftBukkit start
+    public org.bukkit.craftbukkit.CraftServer server;
+    public OptionSet options;
+    public org.bukkit.command.ConsoleCommandSender console;
+    public org.bukkit.command.RemoteConsoleCommandSender remoteConsole;
+    public ConsoleReader reader;
+    public static int currentTick = (int) (System.currentTimeMillis() / 50);
+    public final Thread primaryThread;
+    public java.util.Queue<Runnable> processQueue = new java.util.concurrent.ConcurrentLinkedQueue<Runnable>();
+    public int autosavePeriod;
+    public File bukkitDataPackFolder;
+    public CommandDispatcher vanillaCommandDispatcher;
+    // CraftBukkit end
+
+    public MinecraftServer(OptionSet options, Proxy proxy, DataFixer datafixer, CommandDispatcher commanddispatcher, YggdrasilAuthenticationService yggdrasilauthenticationservice, MinecraftSessionService minecraftsessionservice, GameProfileRepository gameprofilerepository, UserCache usercache) {
         this.ac = new ResourceManager(EnumResourcePackType.SERVER_DATA);
         this.resourcePackRepository = new ResourcePackRepository(ResourcePackLoader::new);
         this.ag = new CraftingManager();
@@ -140,22 +162,51 @@
         this.al = new AdvancementDataWorld();
         this.am = new CustomFunctionData(this);
         this.c = proxy;
-        this.commandDispatcher = commanddispatcher;
+        this.commandDispatcher = this.vanillaCommandDispatcher = commanddispatcher; // CraftBukkit
         this.U = yggdrasilauthenticationservice;
         this.V = minecraftsessionservice;
         this.W = gameprofilerepository;
         this.X = usercache;
-        this.universe = file;
-        this.l = file == null ? null : new ServerConnection(this);
-        this.convertable = file == null ? null : new WorldLoaderServer(file.toPath(), file.toPath().resolve("../backups"), datafixer);
+        // this.universe = file; // CraftBukkit
+        this.l = new ServerConnection(this); // CraftBukkit
+        // this.convertable = file == null ? null : new WorldLoaderServer(file.toPath(), file.toPath().resolve("../backups"), datafixer); // CraftBukkit - moved to DedicatedServer.init
         this.dataConverterManager = datafixer;
         this.ac.a((IResourcePackListener) this.ah);
         this.ac.a((IResourcePackListener) this.ag);
         this.ac.a((IResourcePackListener) this.ak);
         this.ac.a((IResourcePackListener) this.am);
         this.ac.a((IResourcePackListener) this.al);
+        // CraftBukkit start
+        this.options = options;
+        // Try to see if we're actually running in a terminal, disable jline if not
+        if (System.console() == null && System.getProperty("jline.terminal") == null) {
+            System.setProperty("jline.terminal", "jline.UnsupportedTerminal");
+            Main.useJline = false;
+        }
+
+        try {
+            reader = new ConsoleReader(System.in, System.out);
+            reader.setExpandEvents(false); // Avoid parsing exceptions for uncommonly used event designators
+        } catch (Throwable e) {
+            try {
+                // Try again with jline disabled for Windows users without C++ 2008 Redistributable
+                System.setProperty("jline.terminal", "jline.UnsupportedTerminal");
+                System.setProperty("user.language", "en");
+                Main.useJline = false;
+                reader = new ConsoleReader(System.in, System.out);
+                reader.setExpandEvents(false);
+            } catch (IOException ex) {
+                LOGGER.warn((String) null, ex);
+            }
+        }
+        Runtime.getRuntime().addShutdownHook(new org.bukkit.craftbukkit.util.ServerShutdownThread(this));
+
+        this.serverThread = primaryThread = new Thread(this, "Server thread"); // Moved from main
     }
 
+    public abstract PropertyManager getPropertyManager();
+    // CraftBukkit end
+
     public abstract boolean init() throws IOException;
 
     public void convertWorld(String s) {
@@ -180,11 +231,11 @@
         }
 
         if (this.forceUpgrade) {
-            MinecraftServer.LOGGER.info("Forcing world upgrade!");
-            WorldData worlddata = this.getConvertable().c(this.getWorld());
+            MinecraftServer.LOGGER.info("Forcing world upgrade! {}", s); // CraftBukkit
+            WorldData worlddata = this.getConvertable().c(s); // CraftBukkit
 
             if (worlddata != null) {
-                WorldUpgrader worldupgrader = new WorldUpgrader(this.getWorld(), this.getConvertable(), worlddata);
+                WorldUpgrader worldupgrader = new WorldUpgrader(s, this.getConvertable(), worlddata); // CraftBukkit
                 IChatBaseComponent ichatbasecomponent = null;
 
                 while (!worldupgrader.b()) {
@@ -223,8 +274,9 @@
     }
 
     public void a(String s, String s1, long i, WorldType worldtype, JsonElement jsonelement) {
-        this.convertWorld(s);
+        // this.convertWorld(s); // CraftBukkit - moved down
         this.b((IChatBaseComponent) (new ChatMessage("menu.loadingLevel", new Object[0])));
+        /* CraftBukkit start - Remove ticktime arrays and worldsettings
         IDataManager idatamanager = this.getConvertable().a(s, this);
 
         this.a(this.getWorld(), idatamanager);
@@ -249,54 +301,144 @@
         }
 
         this.a(idatamanager.getDirectory(), worlddata);
-        PersistentCollection persistentcollection = new PersistentCollection(idatamanager);
+        */
+        int worldCount = 3;
 
-        this.a(idatamanager, persistentcollection, worlddata, worldsettings);
-        this.a(this.getDifficulty());
-        this.a(persistentcollection);
-    }
+        for (int j = 0; j < worldCount; ++j) {
+            WorldServer world;
+            WorldData worlddata;
+            byte dimension = 0;
+
+            if (j == 1) {
+                if (getAllowNether()) {
+                    dimension = -1;
+                } else {
+                    continue;
+                }
+            }
 
-    protected void a(IDataManager idatamanager, PersistentCollection persistentcollection, WorldData worlddata, WorldSettings worldsettings) {
-        if (this.L()) {
-            this.worldServer.put(DimensionManager.OVERWORLD, (new DemoWorldServer(this, idatamanager, persistentcollection, worlddata, DimensionManager.OVERWORLD, this.methodProfiler)).i_());
-        } else {
-            this.worldServer.put(DimensionManager.OVERWORLD, (new WorldServer(this, idatamanager, persistentcollection, worlddata, DimensionManager.OVERWORLD, this.methodProfiler)).i_());
-        }
+            if (j == 2) {
+                if (server.getAllowEnd()) {
+                    dimension = 1;
+                } else {
+                    continue;
+                }
+            }
 
-        WorldServer worldserver = this.getWorldServer(DimensionManager.OVERWORLD);
+            String worldType = org.bukkit.World.Environment.getEnvironment(dimension).toString().toLowerCase();
+            String name = (dimension == 0) ? s : s + "_" + worldType;
+            this.convertWorld(name); // Run conversion now
+
+            org.bukkit.generator.ChunkGenerator gen = this.server.getGenerator(name);
+            WorldSettings worldsettings = new WorldSettings(i, this.getGamemode(), this.getGenerateStructures(), this.isHardcore(), worldtype);
+            worldsettings.setGeneratorSettings(jsonelement);
+
+            if (j == 0) {
+                IDataManager idatamanager = new ServerNBTManager(server.getWorldContainer(), s1, this, this.dataConverterManager);
+                worlddata = idatamanager.getWorldData();
+                if (worlddata == null) {
+                    worlddata = new WorldData(worldsettings, s1);
+                }
+                worlddata.checkName(s1); // CraftBukkit - Migration did not rewrite the level.dat; This forces 1.8 to take the last loaded world as respawn (in this case the end)
+                this.a(idatamanager.getDirectory(), worlddata);
+                PersistentCollection persistentcollection = new PersistentCollection(idatamanager);
 
-        worldserver.a(worldsettings);
-        worldserver.addIWorldAccess(new WorldManager(this, worldserver));
-        if (!this.H()) {
-            worldserver.getWorldData().setGameType(this.getGamemode());
-        }
+                if (this.L()) {
+                    world = (WorldServer) (new DemoWorldServer(this, idatamanager, persistentcollection, worlddata, DimensionManager.OVERWORLD, this.methodProfiler)).i_();
+                } else {
+                    world = (WorldServer) (new WorldServer(this, idatamanager, persistentcollection, worlddata, DimensionManager.OVERWORLD, this.methodProfiler, org.bukkit.World.Environment.getEnvironment(dimension), gen)).i_();
+                }
 
-        SecondaryWorldServer secondaryworldserver = (new SecondaryWorldServer(this, idatamanager, DimensionManager.NETHER, worldserver, this.methodProfiler)).b();
+                world.a(worldsettings);
+                this.server.scoreboardManager = new org.bukkit.craftbukkit.scoreboard.CraftScoreboardManager(this, world.getScoreboard());
+            } else {
+                String dim = "DIM" + dimension;
 
-        this.worldServer.put(DimensionManager.NETHER, secondaryworldserver);
-        secondaryworldserver.addIWorldAccess(new WorldManager(this, secondaryworldserver));
-        if (!this.H()) {
-            secondaryworldserver.getWorldData().setGameType(this.getGamemode());
-        }
+                File newWorld = new File(new File(name), dim);
+                File oldWorld = new File(new File(s), dim);
 
-        SecondaryWorldServer secondaryworldserver1 = (new SecondaryWorldServer(this, idatamanager, DimensionManager.THE_END, worldserver, this.methodProfiler)).b();
+                if ((!newWorld.isDirectory()) && (oldWorld.isDirectory())) {
+                    MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder required ----");
+                    MinecraftServer.LOGGER.info("Unfortunately due to the way that Minecraft implemented multiworld support in 1.6, Bukkit requires that you move your " + worldType + " folder to a new location in order to operate correctly.");
+                    MinecraftServer.LOGGER.info("We will move this folder for you, but it will mean that you need to move it back should you wish to stop using Bukkit in the future.");
+                    MinecraftServer.LOGGER.info("Attempting to move " + oldWorld + " to " + newWorld + "...");
+
+                    if (newWorld.exists()) {
+                        MinecraftServer.LOGGER.warn("A file or folder already exists at " + newWorld + "!");
+                        MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----");
+                    } else if (newWorld.getParentFile().mkdirs()) {
+                        if (oldWorld.renameTo(newWorld)) {
+                            MinecraftServer.LOGGER.info("Success! To restore " + worldType + " in the future, simply move " + newWorld + " to " + oldWorld);
+                            // Migrate world data too.
+                            try {
+                                com.google.common.io.Files.copy(new File(new File(s), "level.dat"), new File(new File(name), "level.dat"));
+                                org.apache.commons.io.FileUtils.copyDirectory(new File(new File(s), "data"), new File(new File(name), "data"));
+                            } catch (IOException exception) {
+                                MinecraftServer.LOGGER.warn("Unable to migrate world data.");
+                            }
+                            MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder complete ----");
+                        } else {
+                            MinecraftServer.LOGGER.warn("Could not move folder " + oldWorld + " to " + newWorld + "!");
+                            MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----");
+                        }
+                    } else {
+                        MinecraftServer.LOGGER.warn("Could not create path for " + newWorld + "!");
+                        MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----");
+                    }
+                }
 
-        this.worldServer.put(DimensionManager.THE_END, secondaryworldserver1);
-        secondaryworldserver1.addIWorldAccess(new WorldManager(this, secondaryworldserver1));
-        if (!this.H()) {
-            secondaryworldserver1.getWorldData().setGameType(this.getGamemode());
-        }
+                IDataManager idatamanager = new ServerNBTManager(server.getWorldContainer(), name, this, this.dataConverterManager);
+                // world =, b0 to dimension, s1 to name, added Environment and gen
+                worlddata = idatamanager.getWorldData();
+                if (worlddata == null) {
+                    worlddata = new WorldData(worldsettings, name);
+                }
+                worlddata.checkName(name); // CraftBukkit - Migration did not rewrite the level.dat; This forces 1.8 to take the last loaded world as respawn (in this case the end)
+                world = (WorldServer) new SecondaryWorldServer(this, idatamanager, DimensionManager.a(dimension), this.getWorldServer(DimensionManager.OVERWORLD), this.methodProfiler, worlddata, org.bukkit.World.Environment.getEnvironment(dimension), gen).b();
+            }
+
+            this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldInitEvent(world.getWorld()));
+
+            world.addIWorldAccess(new WorldManager(this, world));
+            if (!this.H()) {
+                world.getWorldData().setGameType(this.getGamemode());
+            }
+
+            this.worldServer.put(world.dimension, world);
+            this.getPlayerList().setPlayerFileData(world);
 
-        this.getPlayerList().setPlayerFileData(worldserver);
-        if (worlddata.P() != null) {
-            this.aP().a(worlddata.P());
+            if (worlddata.P() != null) {
+                this.aP().a(worlddata.P());
+            }
         }
+        this.a(this.getDifficulty());
+        this.a(this.getWorldServer(DimensionManager.OVERWORLD).worldMaps);
+        // CraftBukkit end
 
     }
 
     protected void a(File file, WorldData worlddata) {
         this.resourcePackRepository.a((ResourcePackSource) (new ResourcePackSourceVanilla()));
         this.resourcePackFolder = new ResourcePackSourceFolder(new File(file, "datapacks"));
+        // CraftBukkit start
+        bukkitDataPackFolder = new File(new File(file, "datapacks"), "bukkit");
+        if (!bukkitDataPackFolder.exists()) {
+            bukkitDataPackFolder.mkdirs();
+        }
+        File mcMeta = new File(bukkitDataPackFolder, "pack.mcmeta");
+        if (!mcMeta.exists()) {
+            try {
+                com.google.common.io.Files.write("{\n"
+                        + "    \"pack\": {\n"
+                        + "        \"description\": \"Data pack for resources provided by Bukkit plugins\",\n"
+                        + "        \"pack_format\": 1\n"
+                        + "    }\n"
+                        + "}", mcMeta, com.google.common.base.Charsets.UTF_8);
+            } catch (IOException ex) {
+                throw new RuntimeException("Could not initialize Bukkit datapack", ex);
+            }
+        }
+        // CraftBukkit end
         this.resourcePackRepository.a((ResourcePackSource) this.resourcePackFolder);
         this.resourcePackRepository.a();
         ArrayList arraylist = Lists.newArrayList();
@@ -325,42 +467,52 @@
         boolean flag4 = true;
 
         this.b((IChatBaseComponent) (new ChatMessage("menu.generatingTerrain", new Object[0])));
-        WorldServer worldserver = this.getWorldServer(DimensionManager.OVERWORLD);
 
-        MinecraftServer.LOGGER.info("Preparing start region for dimension " + DimensionManager.a(worldserver.worldProvider.getDimensionManager()));
-        BlockPosition blockposition = worldserver.getSpawn();
-        ArrayList arraylist = Lists.newArrayList();
-        Set set = Sets.newConcurrentHashSet();
+        // CraftBukkit start - fire WorldLoadEvent and handle whether or not to keep the spawn in memory
         Stopwatch stopwatch = Stopwatch.createStarted();
-
-        for (int i = -192; i <= 192 && this.isRunning(); i += 16) {
-            for (int j = -192; j <= 192 && this.isRunning(); j += 16) {
-                arraylist.add(new ChunkCoordIntPair(blockposition.getX() + i >> 4, blockposition.getZ() + j >> 4));
+        for (WorldServer worldserver : this.getWorlds()) {
+            MinecraftServer.LOGGER.info("Preparing start region for level " + worldserver.dimension + " (Seed: " + worldserver.getSeed() + ")");
+            if (!worldserver.getWorld().getKeepSpawnInMemory()) {
+                continue;
             }
 
-            CompletableFuture completablefuture = worldserver.getChunkProviderServer().a((Iterable) arraylist, (chunk) -> {
-                set.add(chunk.getPos());
-            });
+            BlockPosition blockposition = worldserver.getSpawn();
+            ArrayList arraylist = Lists.newArrayList();
+            Set set = Sets.newConcurrentHashSet();
+
+            for (int i = -192; i <= 192 && this.isRunning(); i += 16) {
+                for (int j = -192; j <= 192 && this.isRunning(); j += 16) {
+                    arraylist.add(new ChunkCoordIntPair(blockposition.getX() + i >> 4, blockposition.getZ() + j >> 4));
+                }
 
-            while (!completablefuture.isDone()) {
-                try {
-                    completablefuture.get(1L, TimeUnit.SECONDS);
-                } catch (InterruptedException interruptedexception) {
-                    throw new RuntimeException(interruptedexception);
-                } catch (ExecutionException executionexception) {
-                    if (executionexception.getCause() instanceof RuntimeException) {
-                        throw (RuntimeException) executionexception.getCause();
-                    }
+                CompletableFuture completablefuture = worldserver.getChunkProviderServer().a((Iterable) arraylist, (chunk) -> {
+                    set.add(chunk.getPos());
+                });
+
+                while (!completablefuture.isDone()) {
+                    try {
+                        completablefuture.get(1L, TimeUnit.SECONDS);
+                    } catch (InterruptedException interruptedexception) {
+                        throw new RuntimeException(interruptedexception);
+                    } catch (ExecutionException executionexception) {
+                        if (executionexception.getCause() instanceof RuntimeException) {
+                            throw (RuntimeException) executionexception.getCause();
+                        }
 
-                    throw new RuntimeException(executionexception.getCause());
-                } catch (TimeoutException timeoutexception) {
-                    this.a(new ChatMessage("menu.preparingSpawn", new Object[0]), set.size() * 100 / 625);
+                        throw new RuntimeException(executionexception.getCause());
+                    } catch (TimeoutException timeoutexception) {
+                        this.a(new ChatMessage("menu.preparingSpawn", new Object[0]), set.size() * 100 / 625);
+                    }
                 }
-            }
 
-            this.a(new ChatMessage("menu.preparingSpawn", new Object[0]), set.size() * 100 / 625);
+                this.a(new ChatMessage("menu.preparingSpawn", new Object[0]), set.size() * 100 / 625);
+            }
         }
 
+        for (WorldServer world : this.getWorlds()) {
+            this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldLoadEvent(world.getWorld()));
+        }
+        // CraftBukkit end
         MinecraftServer.LOGGER.info("Time elapsed: {} ms", Long.valueOf(stopwatch.elapsed(TimeUnit.MILLISECONDS)));
         Iterator iterator = DimensionManager.b().iterator();
 
@@ -419,6 +571,10 @@
     protected void l() {
         this.w = null;
         this.x = 0;
+        // CraftBukkit Start
+        this.server.enablePlugins(org.bukkit.plugin.PluginLoadOrder.POSTWORLD);
+        this.server.getPluginManager().callEvent(new ServerLoadEvent(ServerLoadEvent.LoadType.STARTUP));
+        // CraftBukkit end
     }
 
     protected void saveChunks(boolean flag) {
@@ -442,8 +598,24 @@
 
     }
 
-    protected void stop() {
+    // CraftBukkit start
+    private boolean hasStopped = false;
+    private final Object stopLock = new Object();
+    // CraftBukkit end
+
+    public void stop() throws ExceptionWorldConflict { // CraftBukkit - added throws
+        // CraftBukkit start - prevent double stopping on multiple threads
+        synchronized(stopLock) {
+            if (hasStopped) return;
+            hasStopped = true;
+        }
+        // CraftBukkit end
         MinecraftServer.LOGGER.info("Stopping server");
+        // CraftBukkit start
+        if (this.server != null) {
+            this.server.disablePlugins();
+        }
+        // CraftBukkit end
         if (this.getServerConnection() != null) {
             this.getServerConnection().b();
         }
@@ -452,6 +624,7 @@
             MinecraftServer.LOGGER.info("Saving players");
             this.s.savePlayers();
             this.s.u();
+            try { Thread.sleep(100); } catch (InterruptedException ex) {} // CraftBukkit - SPIGOT-625 - give server at least a chance to send packets
         }
 
         MinecraftServer.LOGGER.info("Saving worlds");
@@ -516,11 +689,13 @@
                     if (i > 2000L && this.aa - this.Q >= 15000L) {
                         long j = i / 50L;
 
+                        if (server.getWarnOnOverload()) // CraftBukkit
                         MinecraftServer.LOGGER.warn("Can\'t keep up! Is the server overloaded? Running {}ms or {} ticks behind", Long.valueOf(i), Long.valueOf(j));
                         this.aa += j * 50L;
                         this.Q = this.aa;
                     }
 
+                    MinecraftServer.currentTick = (int) (System.currentTimeMillis() / 50); // CraftBukkit
                     this.a(this::aT);
                     this.aa += 50L;
 
@@ -559,6 +734,12 @@
             } catch (Throwable throwable1) {
                 MinecraftServer.LOGGER.error("Exception stopping the server", throwable1);
             } finally {
+                // CraftBukkit start - Restore terminal to original settings
+                try {
+                    reader.getTerminal().restore();
+                } catch (Exception ignored) {
+                }
+                // CraftBukkit end
                 this.t();
             }
 
@@ -627,7 +808,7 @@
             this.m.b().a(agameprofile);
         }
 
-        if (this.ticks % 900 == 0) {
+        if (autosavePeriod > 0 && this.ticks % autosavePeriod == 0) { // CraftBukkit
             this.methodProfiler.a("save");
             this.s.savePlayers();
             this.saveChunks(true);
@@ -653,6 +834,7 @@
     }
 
     public void b(BooleanSupplier booleansupplier) {
+        this.server.getScheduler().mainThreadHeartbeat(this.ticks); // CraftBukkit
         this.methodProfiler.a("jobs");
 
         FutureTask futuretask;
@@ -665,23 +847,40 @@
         this.getFunctionData().Y_();
         this.methodProfiler.c("levels");
 
-        WorldServer worldserver;
+        // CraftBukkit start
+        // Run tasks that are waiting on processing
+        while (!processQueue.isEmpty()) {
+            processQueue.remove().run();
+        }
+
+        org.bukkit.craftbukkit.chunkio.ChunkIOExecutor.tick();
+
+        // Send time updates to everyone, it will get the right time from the world the player is in.
+        if (this.ticks % 20 == 0) {
+            for (int i = 0; i < this.getPlayerList().players.size(); ++i) {
+                EntityPlayer entityplayer = (EntityPlayer) this.getPlayerList().players.get(i);
+                entityplayer.playerConnection.sendPacket(new PacketPlayOutUpdateTime(entityplayer.world.getTime(), entityplayer.getPlayerTime(), entityplayer.world.getGameRules().getBoolean("doDaylightCycle"))); // Add support for per player time
+            }
+        }
+
+        // WorldServer worldserver; // CraftBukkit - dropped down
         long i;
 
-        for (Iterator iterator = this.getWorlds().iterator(); iterator.hasNext();((long[]) this.e.computeIfAbsent(worldserver.worldProvider.getDimensionManager(), (dimensionmanager) -> {
-            return new long[100];
-        }))[this.ticks % 100] = SystemUtils.c() - i) {
-            worldserver = (WorldServer) iterator.next();
+        // CraftBukkit - dropTickTime
+        for (Iterator iterator = this.getWorlds().iterator(); iterator.hasNext();) {
+             WorldServer worldserver = (WorldServer) iterator.next();
             i = SystemUtils.c();
-            if (worldserver.worldProvider.getDimensionManager() == DimensionManager.OVERWORLD || this.getAllowNether()) {
+            if (true || worldserver.worldProvider.getDimensionManager() == DimensionManager.OVERWORLD || this.getAllowNether()) { // CraftBukkit
                 this.methodProfiler.a(() -> {
                     return worldserver.getWorldData().getName();
                 });
+                /* Drop global time updates
                 if (this.ticks % 20 == 0) {
                     this.methodProfiler.a("timeSync");
                     this.s.a((Packet) (new PacketPlayOutUpdateTime(worldserver.getTime(), worldserver.getDayTime(), worldserver.getGameRules().getBoolean("doDaylightCycle"))), worldserver.worldProvider.getDimensionManager());
                     this.methodProfiler.e();
                 }
+                // CraftBukkit end */
 
                 this.methodProfiler.a("tick");
 
@@ -732,10 +931,11 @@
         this.k.add(itickable);
     }
 
-    public static void main(String[] astring) {
+    public static void main(final OptionSet options) { // CraftBukkit - replaces main(String[] astring)
         DispenserRegistry.c();
 
         try {
+            /* CraftBukkit start - Replace everything
             boolean flag = true;
             String s = null;
             String s1 = ".";
@@ -783,13 +983,16 @@
                     ++j;
                 }
             }
+            */ // CraftBukkit end
 
+            String s1 = "."; // PAIL?
             YggdrasilAuthenticationService yggdrasilauthenticationservice = new YggdrasilAuthenticationService(Proxy.NO_PROXY, UUID.randomUUID().toString());
             MinecraftSessionService minecraftsessionservice = yggdrasilauthenticationservice.createMinecraftSessionService();
             GameProfileRepository gameprofilerepository = yggdrasilauthenticationservice.createProfileRepository();
             UserCache usercache = new UserCache(gameprofilerepository, new File(s1, MinecraftServer.a.getName()));
-            final DedicatedServer dedicatedserver = new DedicatedServer(new File(s1), DataConverterRegistry.a(), yggdrasilauthenticationservice, minecraftsessionservice, gameprofilerepository, usercache);
+            final DedicatedServer dedicatedserver = new DedicatedServer(options, DataConverterRegistry.a(), yggdrasilauthenticationservice, minecraftsessionservice, gameprofilerepository, usercache);
 
+            /* CraftBukkit start
             if (s != null) {
                 dedicatedserver.h(s);
             }
@@ -827,6 +1030,29 @@
 
             thread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(MinecraftServer.LOGGER));
             Runtime.getRuntime().addShutdownHook(thread);
+            */
+
+            if (options.has("port")) {
+                int port = (Integer) options.valueOf("port");
+                if (port > 0) {
+                    dedicatedserver.setPort(port);
+                }
+            }
+
+            if (options.has("universe")) {
+                dedicatedserver.universe = (File) options.valueOf("universe");
+            }
+
+            if (options.has("world")) {
+                dedicatedserver.setWorld((String) options.valueOf("world"));
+            }
+
+            if (options.has("forceUpgrade")) {
+                dedicatedserver.setForceUpgrade(true);
+            }
+
+            dedicatedserver.primaryThread.start();
+            // CraftBukkit end
         } catch (Exception exception) {
             MinecraftServer.LOGGER.fatal("Failed to start the minecraft server", exception);
         }
@@ -838,11 +1064,13 @@
     }
 
     public void v() {
+        /* CraftBukkit start - prevent abuse
         this.serverThread = new Thread(this, "Server thread");
         this.serverThread.setUncaughtExceptionHandler((thread, throwable) -> {
             MinecraftServer.LOGGER.error(throwable);
         });
         this.serverThread.start();
+        // CraftBukkit end */
     }
 
     public File c(String s) {
@@ -882,7 +1110,7 @@
     }
 
     public boolean isDebugging() {
-        return false;
+        return this.getPropertyManager().getBoolean("debug", false); // CraftBukkit - don't hardcode
     }
 
     public void f(String s) {
@@ -897,7 +1125,7 @@
     }
 
     public String getServerModName() {
-        return "vanilla";
+        return server.getName(); // CraftBukkit - cb > vanilla!
     }
 
     public CrashReport b(CrashReport crashreport) {
@@ -933,7 +1161,7 @@
     }
 
     public boolean D() {
-        return this.universe != null;
+        return true; // CraftBukkit
     }
 
     public void sendMessage(IChatBaseComponent ichatbasecomponent) {
@@ -1073,7 +1301,7 @@
     public abstract boolean Q();
 
     public boolean getOnlineMode() {
-        return this.onlineMode;
+        return server.getOnlineMode(); // CraftBukkit
     }
 
     public void setOnlineMode(boolean flag) {
@@ -1233,7 +1461,7 @@
 
     public <V> ListenableFuture<V> a(Callable<V> callable) {
         Validate.notNull(callable);
-        if (!this.isMainThread() && !this.isStopped()) {
+        if (!this.isMainThread()) { // CraftBukkit && !this.isStopped()) {
             ListenableFutureTask listenablefuturetask = ListenableFutureTask.create(callable);
 
             this.f.add(listenablefuturetask);
@@ -1304,8 +1532,8 @@
 
             if (!worlddata.N().contains(resourcepackloader.e()) && !arraylist.contains(resourcepackloader)) {
                 MinecraftServer.LOGGER.info("Found new data pack {}, loading it automatically", resourcepackloader.e());
-                resourcepackloader.h().a(arraylist, resourcepackloader, (resourcepackloader) -> {
-                    return resourcepackloader;
+                resourcepackloader.h().a(arraylist, resourcepackloader, (resourcepackloader1) -> { // CraftBukkit - decompile error
+                    return resourcepackloader1; // CraftBukkit - decompile error
                 }, false);
             }
         }
@@ -1314,7 +1542,7 @@
         ArrayList arraylist1 = Lists.newArrayList();
 
         this.resourcePackRepository.d().forEach((resourcepackloader) -> {
-            list.add(resourcepackloader.d());
+            arraylist1.add(resourcepackloader.d()); // CraftBukkit - decompile error
         });
         this.ac.a((List) arraylist1);
         worlddata.O().clear();
@@ -1416,4 +1644,11 @@
             return 0;
         }
     }
+
+    // CraftBukkit start
+    @Deprecated
+    public static MinecraftServer getServer() {
+        return (Bukkit.getServer() instanceof CraftServer) ? ((CraftServer) Bukkit.getServer()).getServer() : null;
+    }
+    // CraftBukkit end
 }