Skip to content

Commit

Permalink
Feat: Удален патч setBlock(повышения производительности)
Browse files Browse the repository at this point in the history
- Добавлена команда tps
- Добавлены новые изменения в Nukkit-Mot
  • Loading branch information
Reider745 committed Jul 23, 2024
1 parent 2315fd5 commit 48a97a6
Show file tree
Hide file tree
Showing 11 changed files with 61 additions and 113 deletions.
1 change: 1 addition & 0 deletions README-RU.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ threading_additional_thread_count: 8
+ state — выводит стейты блока по рантайм идентификатору
+ profilecallback [enabled] [showParameters] — отладка и профайлинг калбеков
+ dimensions_list - выводит список измерений
+ tps - отображает нагрузку на tick inner core

> Все команды предназначены для операторов и не могут быть вызваны игроками.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ threading_additional_thread_count: 8
+ state — outputs block statuses by the runtime ID
+ profilecallback [enabled] [showParameters] — debugging and profiling of callbacks
+ dimensions_list - displays a list of dimensions
+ tps - displays the load on the tick inner core

> All commands are for operators and cannot be called by players.
Expand Down
Binary file modified iclibs/Nukkit-MOT-SNAPSHOT.jar
Binary file not shown.
1 change: 1 addition & 0 deletions src/main/java/com/reider745/commands/CommandsHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ public static void init() {
map.register(tag, new CallbackProfilingCommand());
map.register(tag, new GetAllPlayersIdCommand());
map.register(tag, new DimensionsList());
map.register(tag, new TpsCommand());
}
}
31 changes: 31 additions & 0 deletions src/main/java/com/reider745/commands/TpsCommand.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.reider745.commands;

import cn.nukkit.command.Command;
import cn.nukkit.command.CommandSender;

public class TpsCommand extends Command {
public static long[] innerCoreTimes = new long[20];
public static long[] nukkitTimes = new long[20];
public TpsCommand() {
super("tps");
}

@Override
public boolean execute(CommandSender commandSender, String s, String[] strings) {
if(!commandSender.isOp())
return false;

long innerCoreSum = 0;
for(long time : innerCoreTimes)
innerCoreSum += Math.min(20, 1000 / time);

long nukkitSum = 0;
for(long time : nukkitTimes)
nukkitSum += Math.min(20, 1000 / time);

commandSender.sendMessage("Inner core tps: "+(innerCoreSum/20.0f));
commandSender.sendMessage("Nukkit tps: "+(nukkitSum/20.0f));

return true;
}
}
6 changes: 2 additions & 4 deletions src/main/java/com/reider745/entity/EntityMethod.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,8 @@ public static long getIdForEntity(Entity entity){
public static Player fetchOnline(long entity) {
Map<UUID, Player> players = Server.getInstance().getOnlinePlayers();

Iterator<Map.Entry<UUID, Player>> it = players.entrySet().iterator();
while (it.hasNext()){
Map.Entry<UUID, Player> entry = it.next();
if(entry.getValue().getId() == entity)
for (Map.Entry<UUID, Player> entry : players.entrySet()) {
if (entry.getValue().getId() == entity)
return entry.getValue();
}

Expand Down
20 changes: 9 additions & 11 deletions src/main/java/com/reider745/event/EventListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,6 @@ protected void updateBlocks(Level level, double x, double y, double z, boolean s
level.sendBlocks(players, new Vector3[]{new Vector3(x, y, z)}, UpdateBlockPacket.FLAG_ALL);
}

public static final LinkedHashMap<UUID, Vector3> itemUseVector = new LinkedHashMap<>();

@EventHandler(priority = EventPriority.HIGHEST)
public void onInteract(PlayerInteractEvent event) {
if (event.equals(dealingEvent) || Boolean.TRUE.equals(dealingEvent)) {
Expand All @@ -111,7 +109,7 @@ public void onInteract(PlayerInteractEvent event) {
final Player player = event.getPlayer();

if (event.getAction() == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK) {
final Vector3 pos = itemUseVector.get(player.getUniqueId());
final Vector3 pos = event.getTouchVector();

pos.x = Math.abs(pos.x) + block.x;
pos.y = Math.abs(pos.y) + block.y;
Expand Down Expand Up @@ -413,17 +411,17 @@ public void onPickupItem(InventoryPickupItemEvent event) {
consumeEvent(event, () -> NativeCallback.onEntityPickUpDrop(entity, dropEntity, count));
}

/*@EventHandler(priority = EventPriority.HIGHEST)
public void onBlockUpdate(BlockGrowEvent event) {
final Block block = event.getBlock();
final Block newBlock = event.getNewState();
final Level level = block.getLevel();
@EventHandler(priority = EventPriority.HIGHEST)
public void onBlockChange(BlockChangeEvent event){
final Block block = event.getBlockPrevious();
final Block newBlock = event.getBlock();
final Level level = newBlock.getLevel();

consumeEvent(event,
() -> NativeCallback.onBlockChanged((int) block.x, (int) block.y, (int) block.z, block.getId(),
() -> NativeCallback.onBlockChanged((int) newBlock.x, (int) newBlock.y, (int) newBlock.z, block.getId(),
block.getDamage(), newBlock.getId(), newBlock.getDamage(), FakeDimensions.getFakeIdForLevel(level),
newBlock.getFullId(), block.getLevel()));
}*/
newBlock.getFullId(), level));
}

@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityTeleport(EntityTeleportEvent event) {
Expand Down
80 changes: 0 additions & 80 deletions src/main/java/com/reider745/hooks/LevelHooks.java
Original file line number Diff line number Diff line change
Expand Up @@ -218,11 +218,6 @@ public static Item useBreakOn(Level level, Vector3 vector, BlockFace face, Item
return item;
}

@Inject
public static void useItemOn(Level self, Vector3 vector3, Item item, BlockFace face, float fx, float fy, float fz, Player player, boolean sound){
EventListener.itemUseVector.put(player.getUniqueId(), new Vector3(fx, fy, fz));
}

@Inject(className = "cn.nukkit.level.EnumLevel")
public static void initLevels(){
DimensionsMethods.initLevels();
Expand Down Expand Up @@ -358,79 +353,4 @@ public static Map<String, Object> getGeneratorOptions(BaseLevelProvider provider
}
};
}

@Inject
public static boolean setBlock(Level self, int x, int y, int z, int layer, Block block, boolean direct, boolean update){
if (!self.isYInRange(y) || layer < 0 || layer > self.requireProvider().getMaximumLayer()) {
return false;
}
BaseFullChunk chunk = self.getChunk(x >> 4, z >> 4, true);
Block blockPrevious;
blockPrevious = chunk.getAndSetBlock(x & 0xF, y, z & 0xF, layer, block);
if (blockPrevious.getFullId() == block.getFullId()) {
return false;
}
block.x = x;
block.y = y;
block.z = z;
block.level = self;
block.layer = layer;

try {
final Int2ObjectMap<Consumer<Block>> callbackBlockSet = ReflectHelper.getField(self, "callbackBlockSet");
for (Consumer<Block> callback : callbackBlockSet.values()) {
callback.accept(block);
}
} catch (Exception e) {
Server.getInstance().getLogger().error("Error while calling block set callback", e);
}

int cx = x >> 4;
int cz = z >> 4;

if (direct) {
self.sendBlocks(self.getChunkPlayers(cx, cz).values().toArray(Player.EMPTY_ARRAY), new Block[]{block}, UpdateBlockPacket.FLAG_ALL_PRIORITY, block.layer);
} else {
ReflectHelper.<Void>invoke(self, "addBlockChange", new Object[]{
Level.chunkHash(cx, cz), x, y, z
}, long.class, int.class, int.class, int.class);
}

for (ChunkLoader loader : self.getChunkLoaders(cx, cz)) {
loader.onBlockChanged(block);
}
if (update) {
if (blockPrevious.isTransparent() != block.isTransparent() || blockPrevious.getLightLevel() != block.getLightLevel()) {
self.addLightUpdate(x, y, z);
}
//TODO: Молимся бакам что-бы тут нечего не сломалось, при первойже возможности переписать этот участок
try {
NativeCallback.onBlockChanged(x, y, z,
blockPrevious.getId(), blockPrevious.getDamage(),
block.getId(), block.getDamage(),
FakeDimensions.getFakeIdForLevel(self),
0,
self
);
}catch (Exception ignore){
ignore.printStackTrace();
}

BlockUpdateEvent ev = new BlockUpdateEvent(block);
self.getServer().getPluginManager().callEvent(ev);
if (!ev.isCancelled()) {
for (Entity entity : self.getNearbyEntities(new SimpleAxisAlignedBB(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1))) {
entity.scheduleUpdate();
}
block = ev.getBlock();
block.onUpdate(Level.BLOCK_UPDATE_NORMAL);
block.getLevelBlockAtLayer(layer == 0 ? 1 : 0).onUpdate(Level.BLOCK_UPDATE_NORMAL);
if (block.isTransparent()) {
self.antiXrayOnBlockChange(null, block, 1);
}
self.updateAround(new Vector3(x, y, z));
}
}
return true;
}
}
1 change: 0 additions & 1 deletion src/main/java/com/reider745/hooks/PlayerHooks.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ public static ConnectedClient getForPlayer(Player player) {
@Inject(type = TypeHook.BEFORE_NOT_REPLACE)
public static void close(Player player, TextContainer message, String reason, boolean notify) {
NetworkHooks.close(player);
EventListener.itemUseVector.remove(player.getUniqueId());
ConnectedClient client = getForPlayer(player);
try {
if (client != null)
Expand Down
11 changes: 11 additions & 0 deletions src/main/java/com/reider745/hooks/ServerHooks.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import com.reider745.api.hooks.TypeHook;
import com.reider745.api.hooks.annotation.Inject;
import com.reider745.api.hooks.annotation.Hooks;
import com.reider745.commands.TpsCommand;
import com.reider745.entity.EntityMotion;
import com.reider745.event.EventListener;
import com.zhekasmirnov.horizon.runtime.logger.Logger;
Expand Down Expand Up @@ -71,13 +72,22 @@ public static boolean getPropertyBoolean(Server server, String variable, Object
};
}

private static long start_pre = 0;

@Inject
public static void checkTickUpdates(Server server, int tick) {
int indexTime = server.getTick() % 20;
TpsCommand.nukkitTimes[indexTime] = System.currentTimeMillis() - start_pre;

try {
try {
long start = System.currentTimeMillis();

EntityMotion.tick();
NativeCallback.onTick();

TpsCommand.innerCoreTimes[indexTime] = System.currentTimeMillis() - start;

EventListener.isFirstTickEnd = true;
} catch (Exception e) {
Logger.warning("IC-TICK", e.getCause());
Expand All @@ -86,6 +96,7 @@ public static void checkTickUpdates(Server server, int tick) {
Logger.warning("IC-TICK", e);
}

start_pre = System.currentTimeMillis();
}

@Inject(type = TypeHook.AFTER)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public boolean isAvailable() {

public void execute(Runnable runnable) {
if (executor != null) {
executor.execute(runnable);
executor.submit(runnable);
} else {
runnable.run();
}
Expand All @@ -60,7 +60,7 @@ public void execute(Runnable runnable) {
public void execute(Collection<Runnable> runnables) {
if (executor != null) {
for (Runnable runnable : runnables) {
executor.execute(runnable);
executor.submit(runnable);
}
} else {
for (Runnable runnable : runnables) {
Expand All @@ -72,23 +72,11 @@ public void execute(Collection<Runnable> runnables) {
public void blockUntilExecuted() {
if (executor != null) {
try {
// execute all runnables on main thread as well
BlockingQueue<Runnable> queue = executor.getQueue();
while (queue.size() > 0) {
Runnable runnable = queue.poll(0, TimeUnit.MILLISECONDS);
if (runnable != null) {
runnable.run();
} else {
break;
}
}
// wait until additional threads complete
while (executor.getActiveCount() > 0) {
Thread.sleep(2);
}
} catch (InterruptedException e) {
while(executor.awaitTermination(1, TimeUnit.MILLISECONDS)){}
}catch (InterruptedException e){
e.printStackTrace();
}

}
}
}

0 comments on commit 48a97a6

Please sign in to comment.