General cleanup

This commit is contained in:
themode 2020-10-22 12:55:53 +02:00
parent 47677766ca
commit 3cb880cf80
62 changed files with 182 additions and 201 deletions

View File

@ -35,7 +35,7 @@ public class AdvancementTab implements Viewable {
protected ByteBuf createBuffer; protected ByteBuf createBuffer;
// the packet used to clear the tab (used to remove it and to update an advancement) // the packet used to clear the tab (used to remove it and to update an advancement)
// will never change (since the root identifier is always the same) // will never change (since the root identifier is always the same)
protected ByteBuf removeBuffer; protected final ByteBuf removeBuffer;
protected AdvancementTab(String rootIdentifier, AdvancementRoot root) { protected AdvancementTab(String rootIdentifier, AdvancementRoot root) {
this.root = root; this.root = root;

View File

@ -47,10 +47,8 @@ public class NotificationCenter {
* @param players the collection of players to send the notification to * @param players the collection of players to send the notification to
*/ */
public static void send(Notification notification, Collection<Player> players) { public static void send(Notification notification, Collection<Player> players) {
// Can't use PacketWriterUtils before we need the packets to come in the correct order // Can't use PacketWriterUtils because we need the packets to come in the correct order
players.forEach(player -> { players.forEach(player -> send(notification, player));
send(notification, player);
});
} }
/** /**

View File

@ -27,18 +27,18 @@ import static net.minestom.server.MinecraftServer.*;
*/ */
public final class BenchmarkManager { public final class BenchmarkManager {
public static ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); public static final ThreadMXBean THREAD_MX_BEAN = ManagementFactory.getThreadMXBean();
private static List<String> threads = new ArrayList<>(); private static final List<String> THREADS = new ArrayList<>();
static { static {
threadMXBean.setThreadContentionMonitoringEnabled(true); THREAD_MX_BEAN.setThreadContentionMonitoringEnabled(true);
threadMXBean.setThreadCpuTimeEnabled(true); THREAD_MX_BEAN.setThreadCpuTimeEnabled(true);
threads.add(THREAD_NAME_MAIN_UPDATE); THREADS.add(THREAD_NAME_MAIN_UPDATE);
threads.add(THREAD_NAME_PACKET_WRITER); THREADS.add(THREAD_NAME_PACKET_WRITER);
threads.add(THREAD_NAME_BLOCK_BATCH); THREADS.add(THREAD_NAME_BLOCK_BATCH);
threads.add(THREAD_NAME_SCHEDULER); THREADS.add(THREAD_NAME_SCHEDULER);
threads.add(THREAD_NAME_TICK); THREADS.add(THREAD_NAME_TICK);
} }
private final Long2LongMap lastCpuTimeMap = new Long2LongOpenHashMap(); private final Long2LongMap lastCpuTimeMap = new Long2LongOpenHashMap();
@ -85,7 +85,7 @@ public final class BenchmarkManager {
} }
public void addThreadMonitor(String threadName) { public void addThreadMonitor(String threadName) {
threads.add(threadName); THREADS.add(threadName);
} }
/** /**
@ -119,11 +119,11 @@ public final class BenchmarkManager {
} }
private void refreshData() { private void refreshData() {
ThreadInfo[] threadInfo = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds()); ThreadInfo[] threadInfo = THREAD_MX_BEAN.getThreadInfo(THREAD_MX_BEAN.getAllThreadIds());
for (ThreadInfo threadInfo2 : threadInfo) { for (ThreadInfo threadInfo2 : threadInfo) {
final String name = threadInfo2.getThreadName(); final String name = threadInfo2.getThreadName();
boolean shouldBenchmark = false; boolean shouldBenchmark = false;
for (String thread : threads) { for (String thread : THREADS) {
if (name.startsWith(thread)) { if (name.startsWith(thread)) {
shouldBenchmark = true; shouldBenchmark = true;
break; break;
@ -141,8 +141,8 @@ public final class BenchmarkManager {
final long blockedTime = threadInfo2.getBlockedTime(); final long blockedTime = threadInfo2.getBlockedTime();
final long waitedTime = threadInfo2.getWaitedTime(); final long waitedTime = threadInfo2.getWaitedTime();
final long cpuTime = threadMXBean.getThreadCpuTime(id); final long cpuTime = THREAD_MX_BEAN.getThreadCpuTime(id);
final long userTime = threadMXBean.getThreadUserTime(id); final long userTime = THREAD_MX_BEAN.getThreadUserTime(id);
lastCpuTimeMap.put(id, cpuTime); lastCpuTimeMap.put(id, cpuTime);
lastUserTimeMap.put(id, userTime); lastUserTimeMap.put(id, userTime);

View File

@ -21,7 +21,7 @@ import java.util.List;
*/ */
public class RichMessage extends JsonMessage { public class RichMessage extends JsonMessage {
private List<RichComponent> components = new ArrayList<>(); private final List<RichComponent> components = new ArrayList<>();
private RichComponent currentComponent; private RichComponent currentComponent;
/** /**
@ -214,8 +214,8 @@ public class RichMessage extends JsonMessage {
*/ */
private static class RichComponent { private static class RichComponent {
private ColoredText text; private final ColoredText text;
private FormatRetention formatRetention; private final FormatRetention formatRetention;
private ChatClickEvent clickEvent; private ChatClickEvent clickEvent;
private ChatHoverEvent hoverEvent; private ChatHoverEvent hoverEvent;
private String insertion; private String insertion;

View File

@ -5,8 +5,8 @@ package net.minestom.server.chat;
*/ */
public class TranslatableText { public class TranslatableText {
private String code; private final String code;
private String[] arguments; private final String[] arguments;
private TranslatableText(String code, String[] arguments) { private TranslatableText(String code, String[] arguments) {
this.code = code; this.code = code;

View File

@ -11,7 +11,7 @@ import net.minestom.server.utils.Vector;
public class BoundingBox { public class BoundingBox {
private final Entity entity; private final Entity entity;
private float x, y, z; private final float x, y, z;
/** /**
* Creates a {@link BoundingBox} linked to an {@link Entity} and with a specific size. * Creates a {@link BoundingBox} linked to an {@link Entity} and with a specific size.

View File

@ -37,10 +37,10 @@ public final class CommandManager {
private boolean running; private boolean running;
private ConsoleSender consoleSender = new ConsoleSender(); private final ConsoleSender consoleSender = new ConsoleSender();
private CommandDispatcher dispatcher = new CommandDispatcher(); private final CommandDispatcher dispatcher = new CommandDispatcher();
private Map<String, CommandProcessor> commandProcessorMap = new HashMap<>(); private final Map<String, CommandProcessor> commandProcessorMap = new HashMap<>();
public CommandManager() { public CommandManager() {
running = true; running = true;

View File

@ -36,8 +36,8 @@ public abstract class EntityCreature extends LivingEntity {
private IPath path; private IPath path;
private Position pathPosition; private Position pathPosition;
protected List<GoalSelector> goalSelectors = new ArrayList<>(); protected final List<GoalSelector> goalSelectors = new ArrayList<>();
protected List<TargetSelector> targetSelectors = new ArrayList<>(); protected final List<TargetSelector> targetSelectors = new ArrayList<>();
private GoalSelector currentGoalSelector; private GoalSelector currentGoalSelector;
private Entity target; private Entity target;

View File

@ -74,7 +74,7 @@ public class Player extends LivingEntity implements CommandSender {
private boolean answerKeepAlive; private boolean answerKeepAlive;
private String username; private String username;
protected PlayerConnection playerConnection; protected final PlayerConnection playerConnection;
protected final Set<Entity> viewableEntities = new CopyOnWriteArraySet<>(); protected final Set<Entity> viewableEntities = new CopyOnWriteArraySet<>();
private int latency; private int latency;
@ -490,7 +490,7 @@ public class Player extends LivingEntity implements CommandSender {
/** /**
* Respawns the player by sending a {@link RespawnPacket} to the player and teleporting him * Respawns the player by sending a {@link RespawnPacket} to the player and teleporting him
* to {@link #getRespawnPoint()}. It also resetso fire and his health * to {@link #getRespawnPoint()}. It also resets fire and his health
*/ */
public void respawn() { public void respawn() {
if (!isDead()) if (!isDead())
@ -694,7 +694,7 @@ public class Player extends LivingEntity implements CommandSender {
* Sends a legacy message with the specified color char. * Sends a legacy message with the specified color char.
* *
* @param text the text with the legacy color formatting * @param text the text with the legacy color formatting
* @param colorChar the color charactero * @param colorChar the color character
*/ */
public void sendLegacyMessage(String text, char colorChar) { public void sendLegacyMessage(String text, char colorChar) {
ColoredText coloredText = ColoredText.ofLegacy(text, colorChar); ColoredText coloredText = ColoredText.ofLegacy(text, colorChar);

View File

@ -5,7 +5,7 @@ import net.minestom.server.entity.EntityCreature;
public abstract class GoalSelector { public abstract class GoalSelector {
protected EntityCreature entityCreature; protected final EntityCreature entityCreature;
public GoalSelector(EntityCreature entityCreature) { public GoalSelector(EntityCreature entityCreature) {
this.entityCreature = entityCreature; this.entityCreature = entityCreature;

View File

@ -10,8 +10,8 @@ public class DoNothingGoal extends GoalSelector {
private static final Random RANDOM = new Random(); private static final Random RANDOM = new Random();
private long time; private final long time;
private float chance; private final float chance;
private long startTime; private long startTime;
/** /**

View File

@ -9,14 +9,14 @@ import net.minestom.server.utils.time.CooldownUtils;
import net.minestom.server.utils.time.TimeUnit; import net.minestom.server.utils.time.TimeUnit;
/** /**
* Attack the entity's target ({@link EntityCreature#getTarget()}) OR the closest entity * Attacks the entity's target ({@link EntityCreature#getTarget()}) OR the closest entity
* which can be targeted with the entity {@link TargetSelector} * which can be targeted with the entity {@link TargetSelector}.
*/ */
public class MeleeAttackGoal extends GoalSelector { public class MeleeAttackGoal extends GoalSelector {
private long lastHit; private long lastHit;
private int delay; private final int delay;
private TimeUnit timeUnit; private final TimeUnit timeUnit;
private boolean stop; private boolean stop;

View File

@ -12,8 +12,8 @@ public class RandomStrollGoal extends GoalSelector {
private static final long DELAY = 2500; private static final long DELAY = 2500;
private int radius; private final int radius;
private List<Position> closePositions; private final List<Position> closePositions;
private long lastStroll; private long lastStroll;

View File

@ -7,11 +7,11 @@ import net.minestom.server.entity.damage.DamageType;
import net.minestom.server.entity.damage.EntityDamage; import net.minestom.server.entity.damage.EntityDamage;
/** /**
* Target the last damager of this entity * Targets the last damager of this entity.
*/ */
public class LastEntityDamagerTarget extends TargetSelector { public class LastEntityDamagerTarget extends TargetSelector {
private float range; private final float range;
public LastEntityDamagerTarget(EntityCreature entityCreature, float range) { public LastEntityDamagerTarget(EntityCreature entityCreature, float range) {
super(entityCreature); super(entityCreature);

View File

@ -12,8 +12,8 @@ import java.util.function.Consumer;
public class FakePlayer extends Player { public class FakePlayer extends Player {
private FakePlayerOption option; private final FakePlayerOption option;
private FakePlayerController fakePlayerController; private final FakePlayerController fakePlayerController;
private FakePlayer(UUID uuid, String username, FakePlayerOption option) { private FakePlayer(UUID uuid, String username, FakePlayerOption option) {
super(uuid, username, new FakePlayerConnection()); super(uuid, username, new FakePlayerConnection());
@ -40,9 +40,7 @@ public class FakePlayer extends Player {
public static void initPlayer(UUID uuid, String username, FakePlayerOption option, Consumer<FakePlayer> scheduledCallback) { public static void initPlayer(UUID uuid, String username, FakePlayerOption option, Consumer<FakePlayer> scheduledCallback) {
final FakePlayer fakePlayer = new FakePlayer(uuid, username, option); final FakePlayer fakePlayer = new FakePlayer(uuid, username, option);
fakePlayer.addEventCallback(PlayerLoginEvent.class, event -> { fakePlayer.addEventCallback(PlayerLoginEvent.class, event -> MinecraftServer.getSchedulerManager().buildTask(() -> scheduledCallback.accept(fakePlayer)).delay(1, TimeUnit.TICK).schedule());
MinecraftServer.getSchedulerManager().buildTask(() -> scheduledCallback.accept(fakePlayer)).delay(1, TimeUnit.TICK).schedule();
});
} }
/** /**

View File

@ -16,11 +16,11 @@ import net.minestom.server.utils.BlockPosition;
import net.minestom.server.utils.inventory.PlayerInventoryUtils; import net.minestom.server.utils.inventory.PlayerInventoryUtils;
/** /**
* This class act as a client controller for {@link FakePlayer} * This class act as a client controller for {@link FakePlayer}.
*/ */
public class FakePlayerController { public class FakePlayerController {
private FakePlayer fakePlayer; private final FakePlayer fakePlayer;
public FakePlayerController(FakePlayer fakePlayer) { public FakePlayerController(FakePlayer fakePlayer) {
this.fakePlayer = fakePlayer; this.fakePlayer = fakePlayer;

View File

@ -9,8 +9,8 @@ import net.minestom.server.instance.Chunk;
public class PFColumnarSpace implements IColumnarSpace { public class PFColumnarSpace implements IColumnarSpace {
private final ColumnarOcclusionFieldList occlusionFieldList = new ColumnarOcclusionFieldList(this); private final ColumnarOcclusionFieldList occlusionFieldList = new ColumnarOcclusionFieldList(this);
private PFInstanceSpace instanceSpace; private final PFInstanceSpace instanceSpace;
private Chunk chunk; private final Chunk chunk;
public PFColumnarSpace(PFInstanceSpace instanceSpace, Chunk chunk) { public PFColumnarSpace(PFInstanceSpace instanceSpace, Chunk chunk) {

View File

@ -11,8 +11,8 @@ import java.util.concurrent.ConcurrentHashMap;
public class PFInstanceSpace implements IInstanceSpace { public class PFInstanceSpace implements IInstanceSpace {
private Instance instance; private final Instance instance;
private Map<Chunk, PFColumnarSpace> chunkSpaceMap = new ConcurrentHashMap<>(); private final Map<Chunk, PFColumnarSpace> chunkSpaceMap = new ConcurrentHashMap<>();
public PFInstanceSpace(Instance instance) { public PFInstanceSpace(Instance instance) {
this.instance = instance; this.instance = instance;

View File

@ -10,7 +10,7 @@ import net.minestom.server.utils.Position;
public class PFPathingEntity implements IPathingEntity { public class PFPathingEntity implements IPathingEntity {
private EntityCreature entity; private final EntityCreature entity;
private float searchRange; private float searchRange;
private Position targetPosition; private Position targetPosition;

View File

@ -14,7 +14,7 @@ import java.util.function.Consumer;
// "You have to set both Orientation and Yaw/Pitch accordingly, otherwise it will not work." // "You have to set both Orientation and Yaw/Pitch accordingly, otherwise it will not work."
public class EntityItemFrame extends ObjectEntity { public class EntityItemFrame extends ObjectEntity {
private ItemFrameOrientation orientation; private final ItemFrameOrientation orientation;
private ItemStack itemStack; private ItemStack itemStack;
private Rotation rotation; private Rotation rotation;

View File

@ -5,7 +5,7 @@ import net.minestom.server.event.Event;
public class EntityDeathEvent extends Event { public class EntityDeathEvent extends Event {
private Entity entity; private final Entity entity;
// TODO cause // TODO cause
public EntityDeathEvent(Entity entity) { public EntityDeathEvent(Entity entity) {
@ -13,6 +13,8 @@ public class EntityDeathEvent extends Event {
} }
/** /**
* Get the killed entity,
*
* @return the entity that died * @return the entity that died
*/ */
public Entity getEntity() { public Entity getEntity() {

View File

@ -9,8 +9,8 @@ import net.minestom.server.item.ItemStack;
*/ */
public class EntityItemMergeEvent extends CancellableEvent { public class EntityItemMergeEvent extends CancellableEvent {
private ItemEntity source; private final ItemEntity source;
private ItemEntity merged; private final ItemEntity merged;
private ItemStack result; private ItemStack result;

View File

@ -6,7 +6,7 @@ import net.minestom.server.utils.Vector;
public class EntityVelocityEvent extends CancellableEvent { public class EntityVelocityEvent extends CancellableEvent {
private Entity entity; private final Entity entity;
private Vector velocity; private Vector velocity;
public EntityVelocityEvent(Entity entity, Vector velocity) { public EntityVelocityEvent(Entity entity, Vector velocity) {

View File

@ -7,9 +7,9 @@ import net.minestom.server.utils.item.ItemStackUtils;
public class ArmorEquipEvent extends Event { public class ArmorEquipEvent extends Event {
private Entity entity; private final Entity entity;
private ItemStack armorItem; private ItemStack armorItem;
private ArmorSlot armorSlot; private final ArmorSlot armorSlot;
public ArmorEquipEvent(Entity entity, ItemStack armorItem, ArmorSlot armorSlot) { public ArmorEquipEvent(Entity entity, ItemStack armorItem, ArmorSlot armorSlot) {
this.entity = entity; this.entity = entity;

View File

@ -5,7 +5,7 @@ import net.minestom.server.item.ItemStack;
public class ItemDropEvent extends CancellableEvent { public class ItemDropEvent extends CancellableEvent {
private ItemStack itemStack; private final ItemStack itemStack;
public ItemDropEvent(ItemStack itemStack) { public ItemDropEvent(ItemStack itemStack) {
this.itemStack = itemStack; this.itemStack = itemStack;

View File

@ -6,7 +6,7 @@ import net.minestom.server.item.ItemStack;
public class ItemUpdateStateEvent extends Event { public class ItemUpdateStateEvent extends Event {
private Player player; private final Player player;
private final Player.Hand hand; private final Player.Hand hand;
private final ItemStack itemStack; private final ItemStack itemStack;
private boolean handAnimation; private boolean handAnimation;

View File

@ -5,7 +5,7 @@ import net.minestom.server.event.CancellableEvent;
public class PickupExperienceEvent extends CancellableEvent { public class PickupExperienceEvent extends CancellableEvent {
private ExperienceOrb experienceOrb; private final ExperienceOrb experienceOrb;
private short experienceCount; private short experienceCount;
public PickupExperienceEvent(ExperienceOrb experienceOrb) { public PickupExperienceEvent(ExperienceOrb experienceOrb) {

View File

@ -5,7 +5,7 @@ import net.minestom.server.item.ItemStack;
public class PickupItemEvent extends CancellableEvent { public class PickupItemEvent extends CancellableEvent {
private ItemStack itemStack; private final ItemStack itemStack;
public PickupItemEvent(ItemStack itemStack) { public PickupItemEvent(ItemStack itemStack) {
this.itemStack = itemStack; this.itemStack = itemStack;

View File

@ -9,10 +9,10 @@ public class PlayerBlockBreakEvent extends CancellableEvent {
private final Player player; private final Player player;
private BlockPosition blockPosition; private final BlockPosition blockPosition;
private short blockStateId; private final short blockStateId;
private CustomBlock customBlock; private final CustomBlock customBlock;
private short resultBlockStateId; private short resultBlockStateId;
private short resultCustomBlockId; private short resultCustomBlockId;

View File

@ -12,8 +12,8 @@ import net.minestom.server.utils.BlockPosition;
public class PlayerBlockInteractEvent extends CancellableEvent { public class PlayerBlockInteractEvent extends CancellableEvent {
private final Player player; private final Player player;
private BlockPosition blockPosition; private final BlockPosition blockPosition;
private Player.Hand hand; private final Player.Hand hand;
private final BlockFace blockFace; private final BlockFace blockFace;
/** /**

View File

@ -17,8 +17,8 @@ public class PlayerBlockPlaceEvent extends CancellableEvent {
private final Player player; private final Player player;
private short blockStateId; private short blockStateId;
private short customBlockId; private short customBlockId;
private BlockPosition blockPosition; private final BlockPosition blockPosition;
private Player.Hand hand; private final Player.Hand hand;
private boolean consumeBlock; private boolean consumeBlock;

View File

@ -15,7 +15,7 @@ import java.util.function.Function;
public class PlayerChatEvent extends CancellableEvent { public class PlayerChatEvent extends CancellableEvent {
private final Player sender; private final Player sender;
private Collection<Player> recipients; private final Collection<Player> recipients;
private String message; private String message;
private Function<PlayerChatEvent, RichMessage> chatFormat; private Function<PlayerChatEvent, RichMessage> chatFormat;

View File

@ -135,7 +135,7 @@ public class MinestomOverwriteClassLoader extends URLClassLoader {
return true; return true;
} }
private Class<?> define(String name, byte[] bytes, boolean resolve) throws ClassNotFoundException { private Class<?> define(String name, byte[] bytes, boolean resolve) {
Class<?> defined = defineClass(name, bytes, 0, bytes.length); Class<?> defined = defineClass(name, bytes, 0, bytes.length);
log.trace("Loaded with code modifiers: " + name); log.trace("Loaded with code modifiers: " + name);
if (resolve) { if (resolve) {

View File

@ -46,7 +46,7 @@ public class GlobalPropertyServiceMinestom implements IGlobalPropertyService {
@Override @Override
public IPropertyKey resolveKey(String name) { public IPropertyKey resolveKey(String name) {
return keys.computeIfAbsent(name, k -> new BasicProperty(k)); return keys.computeIfAbsent(name, BasicProperty::new);
} }
@Override @Override

View File

@ -35,7 +35,7 @@ public class MinestomBytecodeProvider implements IClassBytecodeProvider {
} }
@Override @Override
public ClassNode getClassNode(String name, boolean runTransformers) throws ClassNotFoundException, IOException { public ClassNode getClassNode(String name, boolean runTransformers) throws ClassNotFoundException {
return loadNode(name, runTransformers); return loadNode(name, runTransformers);
} }
} }

View File

@ -59,7 +59,7 @@ class LootTableContainer {
} }
} }
private class Entry { private static class Entry {
private ConditionContainer[] conditions; private ConditionContainer[] conditions;
private String type; private String type;
private String name; private String name;

View File

@ -5,7 +5,6 @@ import net.minestom.server.gamedata.loottables.LootTable;
import net.minestom.server.gamedata.loottables.LootTableEntryType; import net.minestom.server.gamedata.loottables.LootTableEntryType;
import net.minestom.server.gamedata.loottables.LootTableFunction; import net.minestom.server.gamedata.loottables.LootTableFunction;
import net.minestom.server.gamedata.loottables.LootTableManager; import net.minestom.server.gamedata.loottables.LootTableManager;
import net.minestom.server.item.Material;
import net.minestom.server.registry.Registries; import net.minestom.server.registry.Registries;
import net.minestom.server.utils.NamespaceID; import net.minestom.server.utils.NamespaceID;

View File

@ -18,14 +18,14 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
/** /**
* Handles loading and caching of tags * Handles loading and caching of tags.
*/ */
public class TagManager { public class TagManager {
private static final Logger LOGGER = LoggerFactory.getLogger(TagManager.class); private static final Logger LOGGER = LoggerFactory.getLogger(TagManager.class);
private final Gson gson; private final Gson gson;
private Map<NamespaceID, Tag> cache = new ConcurrentHashMap<>(); private final Map<NamespaceID, Tag> cache = new ConcurrentHashMap<>();
private List<RequiredTag> requiredTags = new LinkedList<>(); private final List<RequiredTag> requiredTags = new LinkedList<>();
public TagManager() { public TagManager() {
gson = new GsonBuilder() gson = new GsonBuilder()

View File

@ -58,8 +58,8 @@ public abstract class Chunk implements Viewable, DataContainer {
public static final int BIOME_COUNT = 1024; // 4x4x4 blocks group public static final int BIOME_COUNT = 1024; // 4x4x4 blocks group
protected final Instance instance; protected final Instance instance;
protected Biome[] biomes; protected final Biome[] biomes;
protected int chunkX, chunkZ; protected final int chunkX, chunkZ;
// Options // Options
private final boolean shouldGenerate; private final boolean shouldGenerate;
@ -70,7 +70,7 @@ public abstract class Chunk implements Viewable, DataContainer {
private ByteBuf fullDataPacket; private ByteBuf fullDataPacket;
protected volatile boolean loaded = true; protected volatile boolean loaded = true;
protected Set<Player> viewers = new CopyOnWriteArraySet<>(); protected final Set<Player> viewers = new CopyOnWriteArraySet<>();
// Path finding // Path finding
protected PFColumnarSpace columnarSpace; protected PFColumnarSpace columnarSpace;

View File

@ -45,15 +45,15 @@ public class DynamicChunk extends Chunk {
// Used to get all blocks with data (no null) // Used to get all blocks with data (no null)
// Key is still chunk coordinates (see #getBlockIndex) // Key is still chunk coordinates (see #getBlockIndex)
protected Int2ObjectMap<Data> blocksData = new Int2ObjectOpenHashMap<>(); protected final Int2ObjectMap<Data> blocksData = new Int2ObjectOpenHashMap<>();
// Contains CustomBlocks' block index which are updatable // Contains CustomBlocks' block index which are updatable
protected IntSet updatableBlocks = new IntOpenHashSet(); protected final IntSet updatableBlocks = new IntOpenHashSet();
// (block index)/(last update in ms) // (block index)/(last update in ms)
protected Int2LongMap updatableBlocksLastUpdate = new Int2LongOpenHashMap(); protected final Int2LongMap updatableBlocksLastUpdate = new Int2LongOpenHashMap();
// Block entities // Block entities
protected Set<Integer> blockEntities = new CopyOnWriteArraySet<>(); protected final Set<Integer> blockEntities = new CopyOnWriteArraySet<>();
public DynamicChunk(Instance instance, Biome[] biomes, int chunkX, int chunkZ) { public DynamicChunk(Instance instance, Biome[] biomes, int chunkX, int chunkZ) {
super(instance, biomes, chunkX, chunkZ, true); super(instance, biomes, chunkX, chunkZ, true);

View File

@ -22,7 +22,7 @@ import java.util.concurrent.atomic.AtomicInteger;
*/ */
public class BlockBatch implements InstanceBatch { public class BlockBatch implements InstanceBatch {
private InstanceContainer instance; private final InstanceContainer instance;
private final Map<Chunk, List<BlockData>> data = new HashMap<>(); private final Map<Chunk, List<BlockData>> data = new HashMap<>();
@ -90,9 +90,7 @@ public class BlockBatch implements InstanceBatch {
// Execute the callback if this was the last chunk to process // Execute the callback if this was the last chunk to process
if (isLast) { if (isLast) {
if (callback != null) { if (callback != null) {
instance.scheduleNextTick(inst -> { instance.scheduleNextTick(inst -> callback.run());
callback.run();
});
} }
} }

View File

@ -9,12 +9,12 @@ import java.util.Map;
public class BlockManager { public class BlockManager {
// custom block id -> custom block // custom block id -> custom block
private CustomBlock[] customBlocksInternalId = new CustomBlock[Short.MAX_VALUE]; private final CustomBlock[] customBlocksInternalId = new CustomBlock[Short.MAX_VALUE];
// custom block identifier -> custom block // custom block identifier -> custom block
private Map<String, CustomBlock> customBlocksId = new HashMap<>(); private final Map<String, CustomBlock> customBlocksId = new HashMap<>();
// block id -> block placement rule // block id -> block placement rule
private BlockPlacementRule[] placementRules = new BlockPlacementRule[Short.MAX_VALUE]; private final BlockPlacementRule[] placementRules = new BlockPlacementRule[Short.MAX_VALUE];
/** /**
* Registers a {@link CustomBlock}. * Registers a {@link CustomBlock}.

View File

@ -8,7 +8,7 @@ import net.minestom.server.utils.BlockPosition;
public abstract class BlockPlacementRule { public abstract class BlockPlacementRule {
private short blockId; private final short blockId;
public BlockPlacementRule(short blockId) { public BlockPlacementRule(short blockId) {
this.blockId = blockId; this.blockId = blockId;

View File

@ -9,7 +9,7 @@ import net.minestom.server.utils.BlockPosition;
public class AxisPlacementRule extends BlockPlacementRule { public class AxisPlacementRule extends BlockPlacementRule {
Block block; protected final Block block;
public AxisPlacementRule(Block block) { public AxisPlacementRule(Block block) {
super(block); super(block);

View File

@ -7,10 +7,10 @@ import net.minestom.server.item.Enchantment;
public class EnchantmentTableInventory extends Inventory { public class EnchantmentTableInventory extends Inventory {
private short[] levelRequirements = new short[EnchantmentSlot.values().length]; private final short[] levelRequirements = new short[EnchantmentSlot.values().length];
private short seed; private short seed;
private short[] enchantmentShown = new short[EnchantmentSlot.values().length]; private final short[] enchantmentShown = new short[EnchantmentSlot.values().length];
private short[] enchantmentLevel = new short[EnchantmentSlot.values().length]; private final short[] enchantmentLevel = new short[EnchantmentSlot.values().length];
public EnchantmentTableInventory(String title) { public EnchantmentTableInventory(String title) {
super(InventoryType.ENCHANTMENT, title); super(InventoryType.ENCHANTMENT, title);

View File

@ -10,7 +10,7 @@ import java.util.Map;
public class EnchantedBookMeta implements ItemMeta { public class EnchantedBookMeta implements ItemMeta {
private Map<Enchantment, Short> storedEnchantmentMap = new HashMap<>(); private final Map<Enchantment, Short> storedEnchantmentMap = new HashMap<>();
/** /**
* Gets the stored enchantment map. * Gets the stored enchantment map.

View File

@ -202,10 +202,10 @@ public class MapMeta implements ItemMeta {
} }
public static class MapDecoration { public static class MapDecoration {
private String id; private final String id;
private byte type; private final byte type;
private byte x, z; private final byte x, z;
private double rotation; private final double rotation;
public MapDecoration(String id, byte type, byte x, byte z, double rotation) { public MapDecoration(String id, byte type, byte x, byte z, double rotation) {
this.id = id; this.id = id;

View File

@ -21,7 +21,7 @@ import java.util.concurrent.CopyOnWriteArrayList;
public class PotionMeta implements ItemMeta { public class PotionMeta implements ItemMeta {
private PotionType potionType; private PotionType potionType;
private List<CustomPotionEffect> customPotionEffects = new CopyOnWriteArrayList<>(); private final List<CustomPotionEffect> customPotionEffects = new CopyOnWriteArrayList<>();
private boolean hasColor; private boolean hasColor;
private byte red, green, blue; private byte red, green, blue;

View File

@ -83,9 +83,7 @@ public class UseItemListener {
// Eating code, contains the eating time customisation // Eating code, contains the eating time customisation
PlayerPreEatEvent playerPreEatEvent = new PlayerPreEatEvent(player, itemStack, player.getDefaultEatingTime()); PlayerPreEatEvent playerPreEatEvent = new PlayerPreEatEvent(player, itemStack, player.getDefaultEatingTime());
player.callCancellableEvent(PlayerPreEatEvent.class, playerPreEatEvent, () -> { player.callCancellableEvent(PlayerPreEatEvent.class, playerPreEatEvent, () -> player.refreshEating(true, playerPreEatEvent.getEatingTime()));
player.refreshEating(true, playerPreEatEvent.getEatingTime());
});
} }
if (itemAnimationType != null) { if (itemAnimationType != null) {

View File

@ -14,7 +14,7 @@ public class PacketListenerManager {
private static final ConnectionManager CONNECTION_MANAGER = MinecraftServer.getConnectionManager(); private static final ConnectionManager CONNECTION_MANAGER = MinecraftServer.getConnectionManager();
private Map<Class<? extends ClientPlayPacket>, PacketListenerConsumer> listeners = new ConcurrentHashMap<>(); private final Map<Class<? extends ClientPlayPacket>, PacketListenerConsumer> listeners = new ConcurrentHashMap<>();
public PacketListenerManager() { public PacketListenerManager() {
setListener(ClientKeepAlivePacket.class, KeepAliveListener::listener); setListener(ClientKeepAlivePacket.class, KeepAliveListener::listener);

View File

@ -19,17 +19,17 @@ import java.util.function.Function;
*/ */
public final class ConnectionManager { public final class ConnectionManager {
private Set<Player> players = new CopyOnWriteArraySet<>(); private final Set<Player> players = new CopyOnWriteArraySet<>();
private Map<PlayerConnection, Player> connectionPlayerMap = Collections.synchronizedMap(new HashMap<>()); private final Map<PlayerConnection, Player> connectionPlayerMap = Collections.synchronizedMap(new HashMap<>());
// All the consumers to call once a packet is received // All the consumers to call once a packet is received
private List<PacketConsumer> receivePacketConsumers = new CopyOnWriteArrayList<>(); private final List<PacketConsumer> receivePacketConsumers = new CopyOnWriteArrayList<>();
// The uuid provider once a player login // The uuid provider once a player login
private UuidProvider uuidProvider; private UuidProvider uuidProvider;
// The player provider to have your own Player implementation // The player provider to have your own Player implementation
private PlayerProvider playerProvider; private PlayerProvider playerProvider;
// The consumers to call once a player connect, mostly used to init events // The consumers to call once a player connect, mostly used to init events
private List<Consumer<Player>> playerInitializations = new CopyOnWriteArrayList<>(); private final List<Consumer<Player>> playerInitializations = new CopyOnWriteArrayList<>();
/** /**
* Gets the {@link Player} linked to a {@link PlayerConnection}. * Gets the {@link Player} linked to a {@link PlayerConnection}.

View File

@ -15,7 +15,7 @@ public class LegacyPingHandler extends ChannelInboundHandlerAdapter {
private ByteBuf buf; private ByteBuf buf;
@Override @Override
public void channelRead(ChannelHandlerContext ctx, Object object) throws Exception { public void channelRead(ChannelHandlerContext ctx, Object object) {
ByteBuf buf = (ByteBuf) object; ByteBuf buf = (ByteBuf) object;
if (this.buf != null) { if (this.buf != null) {

View File

@ -11,7 +11,7 @@ import java.util.List;
public class PacketDecoder extends ByteToMessageDecoder { public class PacketDecoder extends ByteToMessageDecoder {
@Override @Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> list) throws Exception { protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> list) {
if (buf.readableBytes() > 0) { if (buf.readableBytes() > 0) {
list.add(new InboundPacket(Utils.readVarInt(buf), buf)); list.add(new InboundPacket(Utils.readVarInt(buf), buf));
} }

View File

@ -9,7 +9,7 @@ import net.minestom.server.utils.PacketUtils;
public class PacketEncoder extends MessageToByteEncoder<ServerPacket> { public class PacketEncoder extends MessageToByteEncoder<ServerPacket> {
@Override @Override
protected void encode(ChannelHandlerContext ctx, ServerPacket packet, ByteBuf buf) throws Exception { protected void encode(ChannelHandlerContext ctx, ServerPacket packet, ByteBuf buf) {
PacketUtils.writePacket(buf, packet); PacketUtils.writePacket(buf, packet);
} }

View File

@ -8,9 +8,9 @@ import java.util.UUID;
public class ChatMessagePacket implements ServerPacket { public class ChatMessagePacket implements ServerPacket {
private String jsonMessage; public String jsonMessage;
private Position position; public Position position;
private UUID uuid; public UUID uuid;
public ChatMessagePacket(String jsonMessage, Position position, UUID uuid) { public ChatMessagePacket(String jsonMessage, Position position, UUID uuid) {
this.jsonMessage = jsonMessage; this.jsonMessage = jsonMessage;

View File

@ -20,8 +20,7 @@ public class WindowItemsPacket implements ServerPacket {
} }
writer.writeShort((short) items.length); writer.writeShort((short) items.length);
for (int i = 0; i < items.length; i++) { for (ItemStack item : items) {
ItemStack item = items[i];
writer.writeItemStack(item); writer.writeItemStack(item);
} }
} }

View File

@ -35,7 +35,7 @@ public class WorldBorderPacket implements ServerPacket {
public static class WBSetSize extends WBAction { public static class WBSetSize extends WBAction {
public double diameter; public final double diameter;
public WBSetSize(double diameter) { public WBSetSize(double diameter) {
this.diameter = diameter; this.diameter = diameter;
@ -49,9 +49,9 @@ public class WorldBorderPacket implements ServerPacket {
public static class WBLerpSize extends WBAction { public static class WBLerpSize extends WBAction {
public double oldDiameter; public final double oldDiameter;
public double newDiameter; public final double newDiameter;
public long speed; public final long speed;
public WBLerpSize(double oldDiameter, double newDiameter, long speed) { public WBLerpSize(double oldDiameter, double newDiameter, long speed) {
this.oldDiameter = oldDiameter; this.oldDiameter = oldDiameter;
@ -69,7 +69,7 @@ public class WorldBorderPacket implements ServerPacket {
public static class WBSetCenter extends WBAction { public static class WBSetCenter extends WBAction {
public double x, z; public final double x, z;
public WBSetCenter(double x, double z) { public WBSetCenter(double x, double z) {
this.x = x; this.x = x;
@ -85,13 +85,13 @@ public class WorldBorderPacket implements ServerPacket {
public static class WBInitialize extends WBAction { public static class WBInitialize extends WBAction {
public double x, z; public final double x, z;
public double oldDiameter; public final double oldDiameter;
public double newDiameter; public final double newDiameter;
public long speed; public final long speed;
public int portalTeleportBoundary; public final int portalTeleportBoundary;
public int warningTime; public final int warningTime;
public int warningBlocks; public final int warningBlocks;
public WBInitialize(double x, double z, double oldDiameter, double newDiameter, long speed, public WBInitialize(double x, double z, double oldDiameter, double newDiameter, long speed,
int portalTeleportBoundary, int warningTime, int warningBlocks) { int portalTeleportBoundary, int warningTime, int warningBlocks) {
@ -120,7 +120,7 @@ public class WorldBorderPacket implements ServerPacket {
public static class WBSetWarningTime extends WBAction { public static class WBSetWarningTime extends WBAction {
public int warningTime; public final int warningTime;
public WBSetWarningTime(int warningTime) { public WBSetWarningTime(int warningTime) {
this.warningTime = warningTime; this.warningTime = warningTime;
@ -134,7 +134,7 @@ public class WorldBorderPacket implements ServerPacket {
public static class WBSetWarningBlocks extends WBAction { public static class WBSetWarningBlocks extends WBAction {
public int warningBlocks; public final int warningBlocks;
public WBSetWarningBlocks(int warningBlocks) { public WBSetWarningBlocks(int warningBlocks) {
this.warningBlocks = warningBlocks; this.warningBlocks = warningBlocks;

View File

@ -7,10 +7,7 @@ import it.unimi.dsi.fastutil.longs.LongSet;
import net.minestom.server.instance.Instance; import net.minestom.server.instance.Instance;
import net.minestom.server.utils.chunk.ChunkUtils; import net.minestom.server.utils.chunk.ChunkUtils;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future; import java.util.concurrent.Future;
@ -78,7 +75,7 @@ public class PerGroupChunkProvider extends ThreadProvider {
} }
// The size of the final list, used as the initial capacity // The size of the final list, used as the initial capacity
final int size = neighboursGroups.stream().mapToInt(value -> value.size()).sum() + 1; final int size = neighboursGroups.stream().mapToInt(Set::size).sum() + 1;
// Represent the merged group of all the neighbours // Represent the merged group of all the neighbours
LongSet finalGroup = new LongArraySet(size); LongSet finalGroup = new LongArraySet(size);
@ -135,9 +132,7 @@ public class PerGroupChunkProvider extends ThreadProvider {
})); }));
// Update all the chunks // Update all the chunks
instanceMap.keySet().forEach(chunksIndexes -> { instanceMap.keySet().forEach(chunksIndexes -> futures.add(pool.submit(() -> {
futures.add(pool.submit(() -> {
// Wait for the instance to be updated // Wait for the instance to be updated
// Needed because the instance tick is used to unload waiting chunks // Needed because the instance tick is used to unload waiting chunks
try { try {
@ -148,8 +143,7 @@ public class PerGroupChunkProvider extends ThreadProvider {
// Tick all this chunk group // Tick all this chunk group
chunksIndexes.forEach((long chunkIndex) -> processChunkTick(instance, chunkIndex, time)); chunksIndexes.forEach((long chunkIndex) -> processChunkTick(instance, chunkIndex, time));
})); })));
});
}); });
return futures; return futures;
} }

View File

@ -12,11 +12,11 @@ import java.util.Map;
import java.util.concurrent.Future; import java.util.concurrent.Future;
/** /**
* Separate work between instance (1 instance = 1 thread execution) * Separates work between instance (1 instance = 1 thread execution).
*/ */
public class PerInstanceThreadProvider extends ThreadProvider { public class PerInstanceThreadProvider extends ThreadProvider {
private Map<Instance, LongSet> instanceChunkMap = new HashMap<>(); private final Map<Instance, LongSet> instanceChunkMap = new HashMap<>();
@Override @Override
public void onInstanceCreate(Instance instance) { public void onInstanceCreate(Instance instance) {
@ -49,15 +49,12 @@ public class PerInstanceThreadProvider extends ThreadProvider {
public List<Future<?>> update(long time) { public List<Future<?>> update(long time) {
List<Future<?>> futures = new ArrayList<>(); List<Future<?>> futures = new ArrayList<>();
instanceChunkMap.forEach((instance, chunkIndexes) -> { instanceChunkMap.forEach((instance, chunkIndexes) -> futures.add(pool.submit(() -> {
futures.add(pool.submit(() -> {
// Tick instance // Tick instance
updateInstance(instance, time); updateInstance(instance, time);
// Tick chunks // Tick chunks
chunkIndexes.forEach((long chunkIndex) -> processChunkTick(instance, chunkIndex, time)); chunkIndexes.forEach((long chunkIndex) -> processChunkTick(instance, chunkIndex, time));
})); })));
});
return futures; return futures;
} }

View File

@ -43,8 +43,7 @@ public final class ArrayUtils {
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
final long aValue = a[i]; final long aValue = a[i];
boolean contains = false; boolean contains = false;
for (int n = 0; n < b.length; n++) { for (final long bValue : b) {
final long bValue = b[n];
if (bValue == aValue) { if (bValue == aValue) {
contains = true; contains = true;
break; break;

View File

@ -4,7 +4,6 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Objects; import java.util.Objects;
import java.util.regex.Pattern;
/** /**
* Represents a namespaced ID * Represents a namespaced ID

View File

@ -135,8 +135,8 @@ public final class Utils {
} }
final long[] data = encodeBlocks(blocksData, bitsPerEntry); final long[] data = encodeBlocks(blocksData, bitsPerEntry);
writeVarIntBuf(buffer, data.length); writeVarIntBuf(buffer, data.length);
for (int i = 0; i < data.length; i++) { for (long datum : data) {
buffer.writeLong(data[i]); buffer.writeLong(datum);
} }
} }