Improve entity viewer iterator creation

This commit is contained in:
themode 2022-03-01 04:21:16 +01:00
parent fa5fe8f208
commit 45fe2f1ac9

View File

@ -1,6 +1,7 @@
package net.minestom.server.entity;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import net.minestom.server.MinecraftServer;
@ -46,7 +47,8 @@ final class EntityView {
}
}
entity.updateNewViewer(player);
}, player -> {
},
player -> {
// Remove viewable
var lock1 = player.getEntityId() < entity.getEntityId() ? player : entity;
var lock2 = lock1 == entity ? player : entity;
@ -106,21 +108,18 @@ final class EntityView {
}
public void handleAutoViewAddition(Entity entity) {
handleAutoView(entity, viewerOption.addition, viewableOption.addition, false);
handleAutoView(entity, viewerOption.addition, viewableOption.addition);
}
public void handleAutoViewRemoval(Entity entity) {
handleAutoView(entity, viewerOption.removal, viewableOption.removal, true);
handleAutoView(entity, viewerOption.removal, viewableOption.removal);
}
private void handleAutoView(Entity entity, Consumer<Entity> viewer, Consumer<Player> viewable,
boolean requirement) {
private void handleAutoView(Entity entity, Consumer<Entity> viewer, Consumer<Player> viewable) {
if (this.entity instanceof Player && viewerOption.isAuto() && entity.isAutoViewable()) {
assert viewerOption.isRegistered(entity) == requirement : "Entity is already registered";
if (viewer != null) viewer.accept(entity); // Send packet to this player
}
if (entity instanceof Player player && player.autoViewEntities() && viewableOption.isAuto()) {
assert viewableOption.isRegistered(player) == requirement : "Entity is already registered";
if (viewable != null) viewable.accept(player); // Send packet to the range-visible player
}
}
@ -231,12 +230,20 @@ final class EntityView {
final class SetImpl extends AbstractSet<Player> {
@Override
public @NotNull Iterator<Player> iterator() {
Player[] players;
synchronized (mutex) {
return viewableOption.bitSet.intStream()
.mapToObj(operand -> (Player) Entity.getEntity(operand))
.toList().iterator();
var bitSet = viewableOption.bitSet;
players = new Player[bitSet.size()];
int i = 0;
for (IntIterator it = bitSet.intIterator(); it.hasNext(); ) {
final int id = it.nextInt();
final Player player = (Player) Entity.getEntity(id);
assert player != null;
players[i++] = player;
}
}
return Arrays.asList(players).iterator();
}
@Override
public int size() {
@ -259,12 +266,5 @@ final class EntityView {
return viewableOption.isRegistered(player);
}
}
@Override
public void forEach(Consumer<? super Player> action) {
synchronized (mutex) {
viewableOption.bitSet.forEach((int id) -> action.accept((Player) Entity.getEntity(id)));
}
}
}
}