Skip to content

Commit

Permalink
minor tweaks and debugging entity direction problem
Browse files Browse the repository at this point in the history
  • Loading branch information
mworzala committed Sep 5, 2022
1 parent 0998efa commit d214502
Show file tree
Hide file tree
Showing 5 changed files with 173 additions and 23 deletions.
107 changes: 88 additions & 19 deletions modules/development/src/main/java/unnamed/mmo/server/dev/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,32 @@

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.mattworzala.debug.DebugMessage;
import com.mattworzala.debug.Layer;
import com.mattworzala.debug.shape.Line;
import com.mojang.serialization.JsonOps;
import net.kyori.adventure.audience.Audience;
import net.minestom.server.MinecraftServer;
import net.minestom.server.adventure.MinestomAdventure;
import net.minestom.server.coordinate.Pos;
import net.minestom.server.coordinate.Vec;
import net.minestom.server.entity.Entity;
import net.minestom.server.entity.GameMode;
import net.minestom.server.entity.Player;
import net.minestom.server.event.GlobalEventHandler;
import net.minestom.server.event.player.PlayerLoginEvent;
import net.minestom.server.event.player.PlayerPacketOutEvent;
import net.minestom.server.event.player.PlayerSpawnEvent;
import net.minestom.server.extras.MojangAuth;
import net.minestom.server.instance.Instance;
import net.minestom.server.instance.InstanceManager;
import net.minestom.server.instance.block.Block;
import net.minestom.server.network.packet.server.*;
import net.minestom.server.network.packet.server.play.EntityHeadLookPacket;
import net.minestom.server.network.packet.server.play.EntityPositionAndRotationPacket;
import net.minestom.server.potion.Potion;
import net.minestom.server.potion.PotionEffect;
import net.minestom.server.utils.NamespaceID;
import net.minestom.server.world.DimensionType;
import unnamed.mmo.blocks.BlockInteracter;
import unnamed.mmo.blocks.ore.Ore;
Expand All @@ -40,12 +52,14 @@
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

public class Main {

public static void main(String[] args) {
System.setProperty("minestom.terminal.disabled", "true");
System.setProperty("minestom.viewable-packet", "false");

MinecraftServer server = MinecraftServer.init();

Expand Down Expand Up @@ -83,35 +97,90 @@ public static void main(String[] args) {


//todo test entity
// JsonElement json = JsonParser.parseString("""
// {
// "type": "unnamed:selector",
// "children": {
// "q.has_target": {
// "type": "unnamed:follow_target"
// },
// "": {
// "type": "unnamed:sequence",
// "children": [
// {
// "type": "unnamed:wander_in_region"
// },
// {
// "type": "unnamed:idle",
// "time": 5
// }
// ],
//
// "canInterrupt": true
// }
// }
// }""");
JsonElement json = JsonParser.parseString("""
{
"type": "unnamed:selector",
"children": {
"q.has_target": {
"type": "unnamed:follow_target"
"type": "unnamed:sequence",
"children": [
{
"type": "unnamed:wander_in_region"
},
"": {
"type": "unnamed:sequence",
"children": [
{
"type": "unnamed:wander_in_region"
},
{
"type": "unnamed:idle",
"time": 5
}
],
"canInterrupt": true
{
"type": "unnamed:idle",
"time": 20
}
}
]
}""");
Task task = JsonOps.INSTANCE.withDecoder(SelectorTask.Spec.CODEC)
Task task = JsonOps.INSTANCE.withDecoder(Task.Spec.CODEC)
.apply(json).getOrThrow(false, System.err::println).getFirst().create();
UnnamedEntity entity = new UnnamedEntity(task);
entity.setInstance(instance, new Pos(0, 40, 0))
.thenAccept(unused -> System.out.println("Spawned"));
});
eventHandler.addListener(PlayerPacketOutEvent.class, event -> {
SendablePacket packet = event.getPacket();
if (packet instanceof CachedPacket cached)
packet = cached.packet();
if (packet instanceof FramedPacket framed)
packet = framed.packet();
if (packet instanceof LazyPacket lazy)
packet = lazy.packet();
String name = packet.getClass().getSimpleName();
if (packet.getClass().getSimpleName().contains("Entity")) {
if (name.equals("EntityVelocityPacket")) return;
if (name.equals("EntityPositionPacket")) return;
System.out.println(packet.getClass().getSimpleName());

if (packet instanceof EntityHeadLookPacket headLook) {
Vec dir = new Pos(0, 0, 0, headLook.yaw(), 0).direction();
Pos entityPos = Entity.getEntity(headLook.entityId()).getPosition();
DebugMessage.builder()
.set(NamespaceID.from(ThreadLocalRandom.current().nextDouble() + ""), new Line.Builder()
.point(entityPos.asVec())
.point(dir.mul(2).add(entityPos.asVec()))
.layer(Layer.TOP)
.color(0xFFFFFF00)
.build())
.build()
.sendTo(Audience.audience(MinecraftServer.getConnectionManager().getOnlinePlayers()));
}
if (packet instanceof EntityPositionAndRotationPacket posAndRot) {
Vec dir = new Pos(0, 0, 0, posAndRot.yaw(), posAndRot.pitch()).direction();
Pos entityPos = Entity.getEntity(posAndRot.entityId()).getPosition();
DebugMessage.builder()
.set(NamespaceID.from(ThreadLocalRandom.current().nextDouble() + ""), new Line.Builder()
.point(entityPos.asVec())
.point(dir.mul(2).add(entityPos.asVec()))
.layer(Layer.TOP)
.color(0xFFFF00FF)
.build())
.build()
.sendTo(Audience.audience(MinecraftServer.getConnectionManager().getOnlinePlayers()));
}
}
});

BaseCommandRegister.registerCommands();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class SingleTaskBrain implements Brain {

public SingleTaskBrain(@NotNull Entity entity, @NotNull Task task) {
this.entity = entity;
this.navigator = Navigator.motionSlime(entity);
this.navigator = Navigator.motion(entity);
this.task = task;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package unnamed.mmo.entity.motion;

import com.mattworzala.debug.DebugMessage;
import com.mattworzala.debug.Layer;
import com.mattworzala.debug.shape.Box;
import com.mattworzala.debug.shape.Line;
import com.mattworzala.debug.shape.OutlineBox;
import net.minestom.server.attribute.Attribute;
import net.minestom.server.collision.CollisionUtils;
import net.minestom.server.coordinate.Point;
Expand All @@ -9,6 +14,7 @@
import net.minestom.server.entity.LivingEntity;
import net.minestom.server.instance.Chunk;
import net.minestom.server.instance.Instance;
import net.minestom.server.utils.NamespaceID;
import net.minestom.server.utils.position.PositionUtils;
import net.minestom.server.utils.time.Cooldown;
import net.minestom.server.utils.time.TimeUnit;
Expand All @@ -17,12 +23,14 @@
import unnamed.mmo.entity.brain.navigator.Navigator;

import java.time.Duration;
import java.util.ArrayList;

/**
* Consumes paths from a {@link Pathfinder} to navigate an {@link net.minestom.server.entity.Entity} in an instance.
*/
public final class MotionNavigator implements Navigator {
private final Cooldown jumpCooldown = new Cooldown(Duration.of(40, TimeUnit.SERVER_TICK));
private final Cooldown debugCooldown = new Cooldown(Duration.of(1, TimeUnit.SERVER_TICK));
private final Entity entity;

private Point goal = null;
Expand Down Expand Up @@ -96,9 +104,15 @@ public void tick(long time) {
float minDistance = 0.8f; //todo move me
if (entity.getDistance(goal) < minDistance) {
reset();
sendDebugData();
return;
}

if (debugCooldown.isReady(time)) {
debugCooldown.refreshLastUpdate(time);
sendDebugData();
}

Point current = index < path.size() ? path.get(index) : goal;

float movementSpeed = 0.1f;
Expand Down Expand Up @@ -132,10 +146,73 @@ private boolean moveTowards(@NotNull Point direction, double speed) {
final double speedZ = Math.sin(radians) * speed;
final float yaw = PositionUtils.getLookYaw(dx, dz);
final float pitch = PositionUtils.getLookPitch(dx, dy, dz);

// Prevent ghosting
final var physicsResult = CollisionUtils.handlePhysics(entity, new Vec(speedX, speedY, speedZ));
this.entity.refreshPosition(Pos.fromPoint(physicsResult.newPosition()).withView(yaw, pitch));
return physicsResult.collisionX() || physicsResult.collisionY() || physicsResult.collisionZ();
}


// SECTION: Debug rendering
// Eventually this should be only in the dev server. Just don't currently have a way to do a "mixin" here.
// Probably will have some way to set the entity provider somewhere.

private @NotNull String debugNamespace(){
return "debug_" + entity.getUuid();
}

private void sendDebugData() {
var builder = DebugMessage.builder()
.clear(debugNamespace());

addPathfinderDebugData(builder);
addTargetPoint(builder);

// Send the server side view

builder.set(NamespaceID.from(debugNamespace(), "view_dir"), new Line.Builder()
.point(entity.getPosition().asVec())
.point(entity.getPosition().direction().mul(2).add(entity.getPosition().asVec()))
.color(0xFFFFFFFF)
.layer(Layer.TOP)
.build());

builder.build()
.sendTo(entity.getViewersAsAudience());
}

private void addPathfinderDebugData(DebugMessage.Builder builder) {
if (path == null) return;
var nodes = path.nodes();
var linePoints = new ArrayList<Vec>();

for (int i = index; i < nodes.size(); i++) {
var pos = Vec.fromPoint(nodes.get(i));
builder.set(
debugNamespace() + ":pf_node_" + i,
new Box(pos.sub(0.4, 0.0, 0.4), pos.add(0.4, 0.1, 0.4), 0x331CB2F5, Layer.TOP)
);
linePoints.add(pos.withY(y -> y + 0.05));
}
builder.set(
debugNamespace() + ":pf_path",
new Line(linePoints, 10f, 0xFF1CB2F5, Layer.TOP)
);
}

private void addTargetPoint(DebugMessage.Builder builder) {
if (goal == null) return;
builder.set(
debugNamespace() + ":pf_target",
new OutlineBox.Builder()
.block(goal.blockX(), goal.blockY(), goal.blockZ(), 0)
.color(0x55FF0000)
.layer(Layer.TOP)
.colorLine(0xFFFF0000)
.layerLine(Layer.TOP)
.build()
);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@ public void tick(long time) {
movementSpeed = livingEntity.getAttribute(Attribute.MOVEMENT_SPEED).getBaseValue();
}

// Alternative way to do this movement:
// - rotate towards the target pos each tick (interpolated probably, though the client interpolation might be enough)
// - jump in facing direction occasionally

// Move towards the current target, trying to jump if stuck
if (jumpCooldown.isReady(time)) {
moveTowards(current, movementSpeed);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@

import net.minestom.server.collision.BoundingBox;
import net.minestom.server.coordinate.Point;
import net.minestom.server.instance.Instance;
import net.minestom.server.instance.block.Block;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import unnamed.mmo.entity.motion.util.PhysicsUtil;

import java.util.*;

Expand Down Expand Up @@ -93,8 +91,10 @@ public interface Pathfinder {
result.add(0, current);
}

Path path = new Path(result);
//todo optimize the path
path = PathOptimizer.STRING_PULL.optimize(path, world, bb);

return new Path(result);
return path;
};
}

0 comments on commit d214502

Please sign in to comment.