Skip to content

Commit

Permalink
Add Tickable interface (GeyserMC#1790)
Browse files Browse the repository at this point in the history
* Add Tickable interface

By having a tickable interface, we're only dedicating one thread to ticking entities and running tasks as opposed to several. This will also help with implementing world border support.

* removeEntity already clears tickableEntities for us

* Only tick the entity if it's not being ticked
  • Loading branch information
Camotoy authored Jan 5, 2021
1 parent b638931 commit 0641800
Show file tree
Hide file tree
Showing 9 changed files with 183 additions and 142 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ public ItemedFireballEntity(long entityId, long geyserId, EntityType entityType,
}

@Override
protected void updatePosition(GeyserSession session) {
public void tick(GeyserSession session) {
position = position.add(motion);
// TODO: While this reduces latency in position updating (needed for better fireball reflecting),
// TODO: movement is incredibly stiff. See if the MoveEntityDeltaPacket in 1.16.100 fixes this, and if not,
// TODO: only use this laggy movement for fireballs that be reflected
// TODO: movement is incredibly stiff.
// TODO: Only use this laggy movement for fireballs that be reflected
moveAbsoluteImmediate(session, position, rotation, false, true);
float drag = getDrag(session);
motion = motion.add(acceleration).mul(drag);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,50 +33,35 @@
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.world.block.BlockTranslator;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
* Used as a class for any object-like entity that moves as a projectile
*/
public class ThrowableEntity extends Entity {
public class ThrowableEntity extends Entity implements Tickable {

private Vector3f lastPosition;
/**
* Updates the position for the Bedrock client.
*
* Java clients assume the next positions of moving items. Bedrock needs to be explicitly told positions
*/
protected ScheduledFuture<?> positionUpdater;

public ThrowableEntity(long entityId, long geyserId, EntityType entityType, Vector3f position, Vector3f motion, Vector3f rotation) {
super(entityId, geyserId, entityType, position, motion, rotation);
this.lastPosition = position;
}

/**
* Updates the position for the Bedrock client.
*
* Java clients assume the next positions of moving items. Bedrock needs to be explicitly told positions
*/
@Override
public void spawnEntity(GeyserSession session) {
super.spawnEntity(session);
positionUpdater = session.getConnector().getGeneralThreadPool().scheduleAtFixedRate(() -> {
if (session.isClosed()) {
positionUpdater.cancel(true);
return;
}
updatePosition(session);
}, 0, 50, TimeUnit.MILLISECONDS);
}

protected void moveAbsoluteImmediate(GeyserSession session, Vector3f position, Vector3f rotation, boolean isOnGround, boolean teleported) {
super.moveAbsolute(session, position, rotation, isOnGround, teleported);
}

protected void updatePosition(GeyserSession session) {
public void tick(GeyserSession session) {
super.moveRelative(session, motion.getX(), motion.getY(), motion.getZ(), rotation, onGround);
float drag = getDrag(session);
float gravity = getGravity();
motion = motion.mul(drag).down(gravity);
}

protected void moveAbsoluteImmediate(GeyserSession session, Vector3f position, Vector3f rotation, boolean isOnGround, boolean teleported) {
super.moveAbsolute(session, position, rotation, isOnGround, teleported);
}

/**
* Get the gravity of this entity type. Used for applying gravity while the entity is in motion.
*
Expand Down Expand Up @@ -140,7 +125,6 @@ protected boolean isInWater(GeyserSession session) {

@Override
public boolean despawnEntity(GeyserSession session) {
positionUpdater.cancel(true);
if (entityType == EntityType.THROWN_ENDERPEARL) {
LevelEventPacket particlePacket = new LevelEventPacket();
particlePacket.setType(LevelEventType.PARTICLE_TELEPORT);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright (c) 2019-2021 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/

package org.geysermc.connector.entity;

import org.geysermc.connector.network.session.GeyserSession;

/**
* Implemented onto anything that should have code ran every Minecraft tick - 50 milliseconds.
*/
public interface Tickable {
void tick(GeyserSession session);
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,12 @@
import com.nukkitx.protocol.bedrock.packet.AddEntityPacket;
import com.nukkitx.protocol.bedrock.packet.EntityEventPacket;
import lombok.Data;
import org.geysermc.connector.entity.Tickable;
import org.geysermc.connector.entity.living.InsentientEntity;
import org.geysermc.connector.entity.type.EntityType;
import org.geysermc.connector.network.session.GeyserSession;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class EnderDragonEntity extends InsentientEntity {
public class EnderDragonEntity extends InsentientEntity implements Tickable {
/**
* The Ender Dragon has multiple hit boxes, which
* are each its own invisible entity
Expand All @@ -63,8 +61,6 @@ public class EnderDragonEntity extends InsentientEntity {

private boolean hovering;

private ScheduledFuture<?> partPositionUpdater;

public EnderDragonEntity(long entityId, long geyserId, EntityType entityType, Vector3f position, Vector3f motion, Vector3f rotation) {
super(entityId, geyserId, entityType, position, motion, rotation);

Expand Down Expand Up @@ -130,24 +126,23 @@ public void spawnEntity(GeyserSession session) {
segmentHistory[i].y = position.getY();
}

partPositionUpdater = session.getConnector().getGeneralThreadPool().scheduleAtFixedRate(() -> {
pushSegment();
updateBoundingBoxes(session);
}, 0, 50, TimeUnit.MILLISECONDS);

session.getConnector().getLogger().debug("Spawned entity " + entityType + " at location " + position + " with id " + geyserId + " (java id " + entityId + ")");
}

@Override
public boolean despawnEntity(GeyserSession session) {
partPositionUpdater.cancel(true);

for (EnderDragonPartEntity part : allParts) {
part.despawnEntity(session);
}
return super.despawnEntity(session);
}

@Override
public void tick(GeyserSession session) {
pushSegment();
updateBoundingBoxes(session);
}

/**
* Updates the positions of the Ender Dragon's multiple bounding boxes
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import com.github.steveice10.mc.protocol.data.game.statistic.Statistic;
import com.github.steveice10.mc.protocol.data.game.window.VillagerTrade;
import com.github.steveice10.mc.protocol.packet.handshake.client.HandshakePacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPositionPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPositionRotationPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientTeleportConfirmPacket;
import com.github.steveice10.mc.protocol.packet.login.server.LoginSuccessPacket;
Expand Down Expand Up @@ -64,6 +65,7 @@
import org.geysermc.common.window.CustomFormWindow;
import org.geysermc.common.window.FormWindow;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.entity.Tickable;
import org.geysermc.connector.command.CommandSender;
import org.geysermc.connector.common.AuthType;
import org.geysermc.connector.entity.Entity;
Expand Down Expand Up @@ -94,6 +96,7 @@
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@Getter
public class GeyserSession implements CommandSender {
Expand Down Expand Up @@ -245,10 +248,10 @@ public class GeyserSession implements CommandSender {
private ScheduledFuture<?> bucketScheduledFuture;

/**
* Sends a movement packet every three seconds if the player hasn't moved. Prevents timeouts when AFK in certain instances.
* Used to send a movement packet every three seconds if the player hasn't moved. Prevents timeouts when AFK in certain instances.
*/
@Setter
private ScheduledFuture<?> movementSendIfIdle;
private long lastMovementTimestamp = System.currentTimeMillis();

/**
* Controls whether the daylight cycle gamerule has been sent to the client, so the sun/moon remain motionless.
Expand Down Expand Up @@ -328,6 +331,11 @@ public class GeyserSession implements CommandSender {
private List<UUID> selectedEmotes = new ArrayList<>();
private final Set<UUID> emotes = new HashSet<>();

/**
* The thread that will run every 50 milliseconds - one Minecraft tick.
*/
private ScheduledFuture<?> tickThread = null;

private MinecraftProtocol protocol;

public GeyserSession(GeyserConnector connector, BedrockServerSession bedrockServerSession) {
Expand Down Expand Up @@ -458,6 +466,9 @@ public void authenticate(String username, String password) {
connector.getLogger().info(LanguageUtils.getLocaleStringLog("geyser.auth.floodgate.loaded_key"));
}

// Start ticking
tickThread = connector.getGeneralThreadPool().scheduleAtFixedRate(this::tick, 50, 50, TimeUnit.MILLISECONDS);

downstream = new Client(remoteServer.getAddress(), remoteServer.getPort(), protocol, new TcpSessionFactory());
if (connector.getConfig().getRemote().isUseProxyProtocol()) {
downstream.getSession().setFlag(BuiltinFlags.ENABLE_CLIENT_PROXY_PROTOCOL, true);
Expand Down Expand Up @@ -584,6 +595,8 @@ public void disconnect(String reason) {
}
}

tickThread.cancel(true);

this.chunkCache = null;
this.entityCache = null;
this.effectCache = null;
Expand All @@ -598,6 +611,28 @@ public void close() {
disconnect(LanguageUtils.getPlayerLocaleString("geyser.network.close", getClientData().getLanguageCode()));
}

/**
* Called every 50 milliseconds - one Minecraft tick.
*/
public void tick() {
// Check to see if the player's position needs updating - a position update should be sent once every 3 seconds
if (spawned && (System.currentTimeMillis() - lastMovementTimestamp) > 3000) {
// Recalculate in case something else changed position
Vector3d position = collisionManager.adjustBedrockPosition(playerEntity.getPosition(), playerEntity.isOnGround());
// A null return value cancels the packet
if (position != null) {
ClientPlayerPositionPacket packet = new ClientPlayerPositionPacket(playerEntity.isOnGround(),
position.getX(), position.getY(), position.getZ());
sendDownstreamPacket(packet);
}
lastMovementTimestamp = System.currentTimeMillis();
}

for (Tickable entity : entityCache.getTickableEntities()) {
entity.tick(this);
}
}

public void setAuthenticationData(AuthData authData) {
this.authData = authData;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import it.unimi.dsi.fastutil.longs.*;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import lombok.Getter;
import org.geysermc.connector.entity.Tickable;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.player.PlayerEntity;
import org.geysermc.connector.network.session.GeyserSession;
Expand All @@ -40,17 +41,21 @@
* for that player (e.g. seeing vanished players from /vanish)
*/
public class EntityCache {
private GeyserSession session;
private final GeyserSession session;

@Getter
private Long2ObjectMap<Entity> entities = Long2ObjectMaps.synchronize(new Long2ObjectOpenHashMap<>());
/**
* A list of all entities that must be ticked.
*/
private final List<Tickable> tickableEntities = Collections.synchronizedList(new ArrayList<>());
private Long2LongMap entityIdTranslations = Long2LongMaps.synchronize(new Long2LongOpenHashMap());
private Map<UUID, PlayerEntity> playerEntities = Collections.synchronizedMap(new HashMap<>());
private Map<UUID, BossBar> bossBars = Collections.synchronizedMap(new HashMap<>());
private Long2LongMap cachedPlayerEntityLinks = Long2LongMaps.synchronize(new Long2LongOpenHashMap());
private final Long2LongMap cachedPlayerEntityLinks = Long2LongMaps.synchronize(new Long2LongOpenHashMap());

@Getter
private AtomicLong nextEntityId = new AtomicLong(2L);
private final AtomicLong nextEntityId = new AtomicLong(2L);

public EntityCache(GeyserSession session) {
this.session = session;
Expand All @@ -59,6 +64,11 @@ public EntityCache(GeyserSession session) {
public void spawnEntity(Entity entity) {
if (cacheEntity(entity)) {
entity.spawnEntity(session);

if (entity instanceof Tickable) {
// Start ticking it
tickableEntities.add((Tickable) entity);
}
}
}

Expand All @@ -76,6 +86,10 @@ public boolean removeEntity(Entity entity, boolean force) {
if (entity != null && entity.isValid() && (force || entity.despawnEntity(session))) {
long geyserId = entityIdTranslations.remove(entity.getEntityId());
entities.remove(geyserId);

if (entity instanceof Tickable) {
tickableEntities.remove(entity);
}
return true;
}
return false;
Expand Down Expand Up @@ -152,4 +166,8 @@ public long getCachedPlayerEntityLink(long playerId) {
public void addCachedPlayerEntityLink(long playerId, long linkedEntityId) {
cachedPlayerEntityLinks.put(playerId, linkedEntityId);
}

public List<Tickable> getTickableEntities() {
return tickableEntities;
}
}
Loading

0 comments on commit 0641800

Please sign in to comment.