├── .gitignore ├── src ├── main │ └── kotlin │ │ └── sexy │ │ └── kostya │ │ └── enodia │ │ ├── pathfinding │ │ ├── Passibility.kt │ │ ├── PathfindingResult.kt │ │ ├── PathfindingCapabilities.kt │ │ └── PathfindingTask.kt │ │ ├── provider │ │ ├── cache │ │ │ ├── ChunkSectionCache.kt │ │ │ ├── EmptyChunkSectionCache.kt │ │ │ ├── NotEmptyChunkSectionCache.kt │ │ │ └── CachedBlockStateProvider.kt │ │ ├── immutable │ │ │ ├── ImmutableBlockStateProviderFactory.kt │ │ │ └── ImmutableBlockStateProvider.kt │ │ ├── BlockStateProviderFactory.kt │ │ ├── mutable │ │ │ ├── MutableBlockStateProviderFactory.kt │ │ │ └── MutableBlockStateProvider.kt │ │ └── BlockStateProvider.kt │ │ ├── movement │ │ ├── importance │ │ │ ├── UnimportantMovementImportance.kt │ │ │ ├── TeleportationMovementImportance.kt │ │ │ └── MovementImportance.kt │ │ ├── MovementProcessingHub.kt │ │ ├── MovementProcessor.kt │ │ └── MovementProcessorImpl.kt │ │ ├── util │ │ ├── ObjectPool.kt │ │ └── ReusablePoint.kt │ │ └── EnodiaPF.kt └── test │ └── kotlin │ └── sexy │ └── kostya │ └── enodia │ ├── EnodiaEntity.kt │ └── TestServer.kt ├── pom.xml ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/* 2 | *.iml 3 | target/ -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/pathfinding/Passibility.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.pathfinding 2 | 3 | enum class Passibility : Comparable { 4 | Safe, 5 | Undesirable, 6 | Dangerous, 7 | Impassible 8 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/provider/cache/ChunkSectionCache.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.provider.cache 2 | 3 | sealed interface ChunkSectionCache { 4 | 5 | operator fun set(x: Int, y: Int, z: Int, mask: Int) 6 | 7 | operator fun get(x: Int, y: Int, z: Int): Int 8 | 9 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/provider/cache/EmptyChunkSectionCache.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.provider.cache 2 | 3 | import sexy.kostya.enodia.provider.BlockStateProvider 4 | 5 | object EmptyChunkSectionCache : ChunkSectionCache { 6 | 7 | override fun set(x: Int, y: Int, z: Int, mask: Int) {} 8 | 9 | override fun get(x: Int, y: Int, z: Int) = BlockStateProvider.NotCollideable 10 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/provider/immutable/ImmutableBlockStateProviderFactory.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.provider.immutable 2 | 3 | import net.minestom.server.instance.Instance 4 | import sexy.kostya.enodia.provider.BlockStateProviderFactory 5 | 6 | class ImmutableBlockStateProviderFactory : BlockStateProviderFactory(HashMap()) { 7 | 8 | override fun initializeProvider(instance: Instance) = ImmutableBlockStateProvider(instance) 9 | } -------------------------------------------------------------------------------- /src/test/kotlin/sexy/kostya/enodia/EnodiaEntity.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia 2 | 3 | import net.minestom.server.entity.Entity 4 | import net.minestom.server.entity.EntityType 5 | import sexy.kostya.enodia.movement.MovementProcessor 6 | 7 | class EnodiaEntity( 8 | entityType: EntityType 9 | ) : Entity(entityType) { 10 | 11 | var movementProcessor: MovementProcessor? = null 12 | 13 | override fun update(time: Long) { 14 | super.update(time) 15 | movementProcessor?.tick(time) 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/pathfinding/PathfindingResult.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.pathfinding 2 | 3 | import sexy.kostya.enodia.util.ReusablePoint 4 | 5 | data class PathfindingResult( 6 | val status: Status, 7 | val path: List, 8 | val cancellationReason: CancellationReason? = null 9 | ) { 10 | 11 | enum class CancellationReason { 12 | TIMED_OUT, 13 | OUTDATED 14 | } 15 | 16 | enum class Status { 17 | FAILED, 18 | CANCELLED, 19 | PARTIAL, 20 | COMPLETED 21 | } 22 | 23 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/provider/immutable/ImmutableBlockStateProvider.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.provider.immutable 2 | 3 | import net.minestom.server.instance.Instance 4 | import net.minestom.server.instance.block.Block 5 | import sexy.kostya.enodia.provider.cache.CachedBlockStateProvider 6 | 7 | class ImmutableBlockStateProvider(instance: Instance) : CachedBlockStateProvider(instance) { 8 | 9 | override fun onBlockChanged(x: Int, y: Int, z: Int, block: Block) { 10 | throw IllegalStateException("block can not be changed within immutable block state provider") 11 | } 12 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/movement/importance/UnimportantMovementImportance.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.movement.importance 2 | 3 | import net.minestom.server.entity.Entity 4 | import sexy.kostya.enodia.util.ReusablePoint 5 | import java.time.Duration 6 | 7 | class UnimportantMovementImportance( 8 | averageExecutionTime: Long, 9 | maxExecutionTime: Long 10 | ) : MovementImportance(averageExecutionTime, maxExecutionTime) { 11 | 12 | constructor(averageExecutionTime: Duration, maxExecutionTime: Duration) : this( 13 | averageExecutionTime.toMillis(), 14 | maxExecutionTime.toMillis() 15 | ) 16 | 17 | override fun onPathCalculationFailed(entity: Entity, destination: ReusablePoint) = false 18 | 19 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/provider/BlockStateProviderFactory.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.provider 2 | 3 | import net.minestom.server.instance.Instance 4 | 5 | abstract class BlockStateProviderFactory

( 6 | private val instanceProviders: MutableMap 7 | ) { 8 | 9 | protected abstract fun initializeProvider(instance: Instance): P 10 | 11 | fun create(instance: Instance): P { 12 | val provider = initializeProvider(instance) 13 | instanceProviders[instance] = provider 14 | return provider 15 | } 16 | 17 | operator fun get(instance: Instance) = instanceProviders[instance]!! 18 | 19 | open fun remove(instance: Instance) = instanceProviders.remove(instance) 20 | 21 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/provider/mutable/MutableBlockStateProviderFactory.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.provider.mutable 2 | 3 | import net.minestom.server.instance.Instance 4 | import sexy.kostya.enodia.provider.BlockStateProviderFactory 5 | import java.util.concurrent.ConcurrentHashMap 6 | 7 | class MutableBlockStateProviderFactory : BlockStateProviderFactory(ConcurrentHashMap()) { 8 | 9 | override fun initializeProvider(instance: Instance): MutableBlockStateProvider { 10 | val provider = MutableBlockStateProvider(instance) 11 | provider.register() 12 | return provider 13 | } 14 | 15 | override fun remove(instance: Instance): MutableBlockStateProvider? { 16 | val result = super.remove(instance) 17 | result?.unregister() 18 | return result 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/pathfinding/PathfindingCapabilities.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.pathfinding 2 | 3 | data class PathfindingCapabilities( 4 | /** 5 | * if set to true, entity will not be scared of going through the igniting environment (lava, fire, magma, etc). 6 | */ 7 | val fireResistant: Boolean, 8 | /** 9 | * if set to true, entity will try to avoid any kind of liquids. 10 | */ 11 | val aquaphobic: Boolean, 12 | /** 13 | * if set to true, entity will not be able to move outside of liquids. 14 | */ 15 | val aquatic: Boolean, 16 | /** 17 | * it set to true, entity can fly. 18 | */ 19 | val avian: Boolean 20 | ) { 21 | 22 | companion object { 23 | 24 | val Default = PathfindingCapabilities( 25 | fireResistant = false, 26 | aquaphobic = true, 27 | aquatic = false, 28 | avian = false 29 | ) 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/util/ObjectPool.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.util 2 | 3 | import org.jctools.queues.MpmcUnboundedXaddArrayQueue 4 | import java.lang.ref.SoftReference 5 | 6 | class ObjectPool( 7 | private val creator: () -> T, 8 | private val sanitizer: (T) -> Unit, 9 | maxSize: Int 10 | ) { 11 | 12 | private val pool = MpmcUnboundedXaddArrayQueue>(maxSize) 13 | 14 | fun acquire(): T { 15 | var ref: SoftReference 16 | while (true) { 17 | ref = pool.poll() ?: break 18 | return ref.get() ?: continue 19 | } 20 | return creator() 21 | } 22 | 23 | fun release(item: T) { 24 | sanitizer(item) 25 | pool.offer(SoftReference(item)) 26 | } 27 | 28 | inline fun use(crossinline action: (T) -> Unit) { 29 | val item = acquire() 30 | try { 31 | action(item) 32 | } finally { 33 | release(item) 34 | } 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/movement/importance/TeleportationMovementImportance.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.movement.importance 2 | 3 | import net.minestom.server.coordinate.Pos 4 | import net.minestom.server.entity.Entity 5 | import sexy.kostya.enodia.util.ReusablePoint 6 | import java.time.Duration 7 | 8 | class TeleportationMovementImportance( 9 | averageExecutionTime: Long, 10 | maxExecutionTime: Long 11 | ) : MovementImportance(averageExecutionTime, maxExecutionTime) { 12 | 13 | constructor(averageExecutionTime: Duration, maxExecutionTime: Duration) : this( 14 | averageExecutionTime.toMillis(), 15 | maxExecutionTime.toMillis() 16 | ) 17 | 18 | override fun onPathCalculationFailed(entity: Entity, destination: ReusablePoint): Boolean { 19 | entity.teleport( 20 | Pos( 21 | destination.x.toDouble(), 22 | destination.y.toDouble(), 23 | destination.z.toDouble(), 24 | entity.position.yaw, 25 | entity.position.pitch 26 | ) 27 | ) 28 | return true 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/util/ReusablePoint.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.util 2 | 3 | import net.minestom.server.coordinate.Point 4 | import kotlin.math.sqrt 5 | 6 | class ReusablePoint private constructor() : AutoCloseable { 7 | 8 | companion object { 9 | 10 | private val Pool = ObjectPool(::ReusablePoint, {}, 1024) 11 | 12 | operator fun get(x: Float, y: Float, z: Float): ReusablePoint { 13 | val result = Pool.acquire() 14 | result.x = x 15 | result.y = y 16 | result.z = z 17 | return result 18 | } 19 | 20 | fun fromPoint(point: Point) = this[ 21 | point.x().toFloat(), 22 | point.y().toFloat(), 23 | point.z().toFloat() 24 | ] 25 | 26 | } 27 | 28 | var x = 0F 29 | var y = 0F 30 | var z = 0F 31 | 32 | fun release() = Pool.release(this) 33 | 34 | fun distanceSquared(other: ReusablePoint): Float { 35 | val dx = x - other.x 36 | val dy = y - other.y 37 | val dz = z - other.z 38 | return dx * dx + dy * dy + dz * dz 39 | } 40 | 41 | fun distance(other: ReusablePoint) = sqrt(distanceSquared(other)) 42 | 43 | fun samePoint(other: ReusablePoint) = x.compareTo(other.x) == 0 && y.compareTo(other.y) == 0 && z.compareTo(other.z) == 0 44 | 45 | override fun close() = release() 46 | 47 | override fun toString() = "ReusablePoint(x=$x, y=$y, z=$z)" 48 | 49 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/movement/importance/MovementImportance.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.movement.importance 2 | 3 | import net.minestom.server.entity.Entity 4 | import sexy.kostya.enodia.util.ReusablePoint 5 | import java.time.Duration 6 | 7 | abstract class MovementImportance( 8 | val averageExecutionTime: Long, 9 | val maxExecutionTime: Long 10 | ) { 11 | 12 | constructor(averageExecutionTime: Duration, maxExecutionTime: Duration) : this( 13 | averageExecutionTime.toMillis(), 14 | maxExecutionTime.toMillis() 15 | ) 16 | 17 | companion object { 18 | 19 | val UNIMPORTANT: MovementImportance = UnimportantMovementImportance( 20 | Duration.ofMillis(25), 21 | Duration.ofMillis(50) 22 | ) 23 | val IMPORTANT: MovementImportance = TeleportationMovementImportance( 24 | Duration.ofMillis(50), 25 | Duration.ofMillis(250) 26 | ) 27 | val EXTREME: MovementImportance = TeleportationMovementImportance( 28 | Duration.ofMillis(250), 29 | Duration.ofMillis(250) 30 | ) 31 | 32 | } 33 | 34 | /** 35 | * @param entity - entity for which path calculation failed. 36 | * @param destination - destination point that had to be the ending point of the path. 37 | * @return if the movement processor should stop trying to calculate the given path. 38 | */ 39 | abstract fun onPathCalculationFailed(entity: Entity, destination: ReusablePoint): Boolean 40 | 41 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/movement/MovementProcessingHub.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.movement 2 | 3 | import net.minestom.server.entity.Entity 4 | import sexy.kostya.enodia.EnodiaPF 5 | import sexy.kostya.enodia.pathfinding.PathfindingCapabilities 6 | import sexy.kostya.enodia.util.ReusablePoint 7 | import java.util.concurrent.Executors 8 | 9 | class MovementProcessingHub internal constructor( 10 | internal val pf: EnodiaPF, 11 | threads: Int, 12 | internal val maxRetries: Int = 5, 13 | internal val entitySpeedGetter: (Entity) -> Float, 14 | internal val entityContinueFollowing: (entity: Entity, target: Entity, distanceSquared: Float) -> Boolean 15 | ) { 16 | 17 | private var counter = 0 18 | internal val movementExecutor = Executors.newFixedThreadPool(threads) { 19 | val thread = Thread(it, "EnodiaPF-MovementHandler-${++counter}") 20 | thread.isDaemon = true 21 | thread 22 | } 23 | internal val cancellationExecutor = Executors.newScheduledThreadPool(1) { 24 | val thread = Thread(it, "EnodiaPF-MovementCanceller") 25 | thread.isDaemon = true 26 | thread 27 | } 28 | 29 | fun createMovementProcessor(entity: Entity, pathfindingCapabilities: PathfindingCapabilities): MovementProcessor = MovementProcessorImpl( 30 | entity, 31 | pathfindingCapabilities, 32 | this, 33 | pf.blockStateProviderFactory[entity.instance ?: throw IllegalArgumentException("could not initialize movement processor for entity that's not in any instance")] 34 | ) 35 | 36 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/movement/MovementProcessor.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.movement 2 | 3 | import net.minestom.server.Tickable 4 | import net.minestom.server.coordinate.Point 5 | import net.minestom.server.entity.Entity 6 | import sexy.kostya.enodia.movement.importance.MovementImportance 7 | 8 | interface MovementProcessor : Tickable { 9 | 10 | /** 11 | * Dispatch a command to calculate the path to the destination point and to move to it. 12 | * @param destination - the destination point. 13 | * @param importance - indicates how much time engine is allowed to take on path calculation. 14 | * @param range - the maximum distance from the destination point path is allowed to be diverged in order to 15 | * count as complete. 16 | * @return whether movement process has started. 17 | */ 18 | fun goTo(destination: Point, importance: MovementImportance, range: Float = 1F): Boolean 19 | 20 | /** 21 | * Dispatch a command to start following the given entity. 22 | * @param target - the entity to follow. 23 | * @param importance - indicates how much time engine is allowed to take on path calculation. 24 | * @param range - the maximum distance from the destination point path is allowed to be diverged in order to 25 | * count as complete. 26 | * @return whether movement process has started. 27 | */ 28 | fun goTo(target: Entity, importance: MovementImportance, range: Float = 1F): Boolean 29 | 30 | /** 31 | * Check whether processor is doing something. 32 | * @return if there's some path that's currently calculating for that entity or if it has already been 33 | * calculated and entity is following it. 34 | */ 35 | fun isActive(): Boolean 36 | 37 | /** 38 | * Cancel all active path calculations and completely reset the movement state of the processor. 39 | * @param clearPath - if set to false, entity will continue following part of the previous path that has already 40 | * been calculated. 41 | */ 42 | fun stop(clearPath: Boolean = true) 43 | 44 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/provider/cache/NotEmptyChunkSectionCache.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.provider.cache 2 | 3 | class NotEmptyChunkSectionCache : ChunkSectionCache { 4 | 5 | private val data = ByteArray(1536) 6 | 7 | override fun set(x: Int, y: Int, z: Int, mask: Int) { 8 | val index = index(x, y, z) 9 | val pos = index.shr(3) * 3 10 | when (index and 7) { 11 | 0 -> data[pos] = data[pos].toInt().and(0b111.inv()).or(mask).toByte() 12 | 1 -> data[pos] = data[pos].toInt().and(0b111000.inv()).or(mask shl 3).toByte() 13 | 14 | 2 -> { 15 | data[pos] = data[pos].toInt().and(0b11000000.inv()).or(mask.and(0x3).shl(6)).toByte() 16 | data[pos + 1] = data[pos + 1].toInt().and(0b1.inv()).or(mask shr 2).toByte() 17 | } 18 | 19 | 3 -> data[pos + 1] = data[pos + 1].toInt().and(0b1110.inv()).or(mask shl 1).toByte() 20 | 4 -> data[pos + 1] = data[pos + 1].toInt().and(0b1110000.inv()).or(mask shl 4).toByte() 21 | 22 | 5 -> { 23 | data[pos + 1] = data[pos + 1].toInt().and(0b10000000.inv()).or(mask.and(0x1).shl(7)).toByte() 24 | data[pos + 2] = data[pos + 2].toInt().and(0b11.inv()).or(mask shr 1).toByte() 25 | } 26 | 27 | 6 -> data[pos + 2] = data[pos + 2].toInt().and(0b11100.inv()).or(mask shl 2).toByte() 28 | else -> data[pos + 2] = data[pos + 2].toInt().and(0b11100000.inv()).or(mask shl 5).toByte() 29 | } 30 | } 31 | 32 | override fun get(x: Int, y: Int, z: Int): Int { 33 | val index = index(x, y, z) 34 | val pos = index.shr(3) * 3 35 | return when (index and 7) { 36 | 0 -> data[pos].toInt().and(0b111) 37 | 1 -> data[pos].toInt().and(0b111000).shr(3) 38 | 39 | 2 -> { 40 | data[pos].toInt().and(0b11000000).shr(6) or 41 | data[pos + 1].toInt().and(0b1).shl(2) 42 | } 43 | 44 | 3 -> data[pos + 1].toInt().and(0b1110).shr(1) 45 | 4 -> data[pos + 1].toInt().and(0b1110000).shr(4) 46 | 47 | 5 -> { 48 | data[pos + 1].toInt().and(0b10000000).shr(7) or 49 | data[pos + 2].toInt().and(0b11).shl(1) 50 | } 51 | 52 | 6 -> data[pos + 2].toInt().and(0b11100).shr(2) 53 | else -> data[pos + 2].toInt().and(0b11100000).shr(5) 54 | } 55 | } 56 | 57 | private fun index(x: Int, y: Int, z: Int) = x or (y shl 4) or (z shl 8) 58 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/provider/cache/CachedBlockStateProvider.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.provider.cache 2 | 3 | import it.unimi.dsi.fastutil.ints.Int2ObjectMap 4 | import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap 5 | import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap 6 | import net.minestom.server.instance.Chunk 7 | import net.minestom.server.instance.Instance 8 | import net.minestom.server.instance.block.Block 9 | import net.minestom.server.utils.chunk.ChunkUtils 10 | import sexy.kostya.enodia.provider.BlockStateProvider 11 | 12 | abstract class CachedBlockStateProvider(protected val instance: Instance) : BlockStateProvider { 13 | 14 | @Volatile 15 | protected var cache = Long2ObjectOpenHashMap>() 16 | 17 | @Synchronized 18 | override fun loadChunk(chunk: Chunk) { 19 | val index = ChunkUtils.getChunkIndex(chunk.chunkX, chunk.chunkZ) 20 | if (cache.containsKey(index)) { 21 | return 22 | } 23 | val sections = Int2ObjectOpenHashMap() 24 | for (sectionIndex in chunk.minSection until chunk.maxSection) { 25 | val section = chunk.getSection(sectionIndex) 26 | val palette = section.blockPalette() 27 | sections[sectionIndex] = if (palette.count() == 0) { 28 | EmptyChunkSectionCache 29 | } else { 30 | NotEmptyChunkSectionCache().apply { 31 | palette.getAllPresent { x, y, z, blockStateId -> 32 | val block = Block.fromStateId(blockStateId.toShort()) 33 | this[x, y, z] = if (block == null) BlockStateProvider.Solid else BlockStateProvider.createMaskFromBlock(block) 34 | } 35 | } 36 | } 37 | } 38 | val copiedCache = Long2ObjectOpenHashMap(cache) 39 | copiedCache[index] = sections 40 | cache = copiedCache 41 | } 42 | 43 | @Synchronized 44 | override fun unloadChunk(chunk: Chunk) { 45 | val index = ChunkUtils.getChunkIndex(chunk.chunkX, chunk.chunkZ) 46 | if (!cache.containsKey(index)) { 47 | return 48 | } 49 | val copiedCache = Long2ObjectOpenHashMap(cache) 50 | copiedCache.remove(index) 51 | cache = copiedCache 52 | } 53 | 54 | override fun getBlockState(x: Int, y: Int, z: Int): Block { 55 | if (!instance.isChunkLoaded(ChunkUtils.getChunkCoordinate(x), ChunkUtils.getChunkCoordinate(z))) { 56 | return Block.STONE 57 | } 58 | return instance.getBlock(x, y, z) 59 | } 60 | 61 | override fun getBlockMask(x: Int, y: Int, z: Int): Int { 62 | val sections = cache[ChunkUtils.getChunkIndex(x shr 4, z shr 4)] ?: return BlockStateProvider.Solid 63 | val section = sections[ChunkUtils.getChunkCoordinate(y)] ?: return BlockStateProvider.Solid 64 | return section[x and 0xF, y and 0xF, z and 0xF] 65 | } 66 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/provider/mutable/MutableBlockStateProvider.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.provider.mutable 2 | 3 | import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap 4 | import net.minestom.server.event.EventNode 5 | import net.minestom.server.event.player.PlayerBlockBreakEvent 6 | import net.minestom.server.event.player.PlayerBlockPlaceEvent 7 | import net.minestom.server.event.trait.InstanceEvent 8 | import net.minestom.server.instance.Instance 9 | import net.minestom.server.instance.block.Block 10 | import net.minestom.server.utils.chunk.ChunkUtils 11 | import sexy.kostya.enodia.provider.BlockStateProvider 12 | import sexy.kostya.enodia.provider.cache.CachedBlockStateProvider 13 | import sexy.kostya.enodia.provider.cache.EmptyChunkSectionCache 14 | import sexy.kostya.enodia.provider.cache.NotEmptyChunkSectionCache 15 | 16 | class MutableBlockStateProvider(instance: Instance) : CachedBlockStateProvider(instance) { 17 | 18 | private lateinit var blockPlaceNode: EventNode 19 | private lateinit var blockBreakNode: EventNode 20 | 21 | internal fun register() { 22 | blockPlaceNode = instance.eventNode().addListener(PlayerBlockPlaceEvent::class.java) { event -> 23 | val pos = event.blockPosition 24 | onBlockChanged(pos.blockX(), pos.blockY(), pos.blockZ(), event.block) 25 | } 26 | blockBreakNode = instance.eventNode().addListener(PlayerBlockBreakEvent::class.java) { event -> 27 | val pos = event.blockPosition 28 | onBlockChanged(pos.blockX(), pos.blockY(), pos.blockZ(), event.resultBlock) 29 | } 30 | } 31 | 32 | internal fun unregister() { 33 | instance.eventNode().removeChild(blockPlaceNode) 34 | instance.eventNode().removeChild(blockBreakNode) 35 | } 36 | 37 | @Synchronized 38 | override fun onBlockChanged(x: Int, y: Int, z: Int, block: Block) { 39 | val chunkX = ChunkUtils.getChunkCoordinate(x) 40 | val chunkZ = ChunkUtils.getChunkCoordinate(z) 41 | val index = ChunkUtils.getChunkIndex(chunkX, chunkZ) 42 | if (!cache.containsKey(index)) { 43 | val chunk = instance.getChunk(chunkX, chunkZ) ?: throw IllegalStateException("block changed in unloaded chunk") 44 | loadChunk(chunk) 45 | return 46 | } 47 | val sections = cache[index]!! 48 | val sectionIndex = ChunkUtils.getChunkCoordinate(y) 49 | var section = sections[sectionIndex] 50 | if (section == null || section == EmptyChunkSectionCache) { 51 | section = NotEmptyChunkSectionCache() 52 | sections[sectionIndex] = section 53 | } 54 | section[ 55 | x and 15, 56 | y and 15, 57 | z and 15 58 | ] = BlockStateProvider.createMaskFromBlock(block) 59 | 60 | val copiedCache = Long2ObjectOpenHashMap(cache) 61 | copiedCache[index] = sections 62 | cache = copiedCache 63 | } 64 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | sexy.kostya 8 | enodia-pf 9 | 1.0.1 10 | 11 | 12 | 17 13 | 17 14 | 1.7.10 15 | RinesThaix 16 | 98fe53273e979d2a3d0f58960fbd3473d658a2aa 17 | 18 | 19 | 20 | 21 | mavenCentral 22 | https://repo1.maven.org/maven2/ 23 | 24 | 25 | jitpack.io 26 | https://jitpack.io 27 | 28 | 29 | 30 | 31 | 32 | org.jetbrains.kotlin 33 | kotlin-stdlib-jdk8 34 | ${kotlin.version} 35 | 36 | 37 | org.jetbrains.kotlin 38 | kotlin-test 39 | ${kotlin.version} 40 | test 41 | 42 | 43 | 44 | com.github.${minestom.repository} 45 | Minestom 46 | ${minestom.commit} 47 | provided 48 | 49 | 50 | org.jboss.shrinkwrap.resolver 51 | shrinkwrap-resolver-depchain 52 | 53 | 54 | 55 | 56 | org.jctools 57 | jctools-core 58 | 3.3.0 59 | 60 | 61 | checker-qual 62 | org.checkerframework 63 | 64 | 65 | 66 | 67 | 68 | 69 | src/main/kotlin 70 | 71 | 72 | org.jetbrains.kotlin 73 | kotlin-maven-plugin 74 | ${kotlin.version} 75 | 76 | 77 | compile 78 | compile 79 | 80 | compile 81 | 82 | 83 | 84 | test-compile 85 | test-compile 86 | 87 | test-compile 88 | 89 | 90 | 91 | 92 | 1.8 93 | 94 | 95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /src/test/kotlin/sexy/kostya/enodia/TestServer.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia 2 | 3 | import net.minestom.server.MinecraftServer 4 | import net.minestom.server.attribute.Attribute 5 | import net.minestom.server.command.builder.Command 6 | import net.minestom.server.command.builder.arguments.ArgumentType 7 | import net.minestom.server.coordinate.Pos 8 | import net.minestom.server.coordinate.Vec 9 | import net.minestom.server.entity.* 10 | import net.minestom.server.event.player.PlayerLoginEvent 11 | import net.minestom.server.instance.block.Block 12 | import sexy.kostya.enodia.movement.importance.MovementImportance 13 | import sexy.kostya.enodia.pathfinding.PathfindingCapabilities 14 | import kotlin.math.max 15 | 16 | fun main() { 17 | val server = MinecraftServer.init() 18 | 19 | val enodia = EnodiaPF.forMutableWorlds() 20 | val hub = enodia.initializeMovementProcessingHub( 21 | max(2, Runtime.getRuntime().availableProcessors()), 22 | 5, 23 | { if (it is LivingEntity) it.getAttributeValue(Attribute.MOVEMENT_SPEED) else Attribute.MOVEMENT_SPEED.defaultValue }, 24 | { _, _, _ -> true } 25 | ) 26 | 27 | val instance = MinecraftServer.getInstanceManager().createInstanceContainer() 28 | instance.setGenerator { 29 | val mod = it.modifier() 30 | mod.fillHeight(0, 20, Block.STONE) 31 | mod.fillHeight(20, 21, Block.GRASS_BLOCK) 32 | if (it.absoluteStart().x() == 16.0 && it.absoluteStart().z() == 16.0) { 33 | mod.fill( 34 | Vec(16.0, 1.0, 16.0), 35 | Vec(31.0, 21.0, 31.0), 36 | Block.WATER 37 | ) 38 | } 39 | } 40 | 41 | MinecraftServer.getGlobalEventHandler().addListener(PlayerLoginEvent::class.java) { 42 | it.setSpawningInstance(instance) 43 | it.player.respawnPoint = Pos(0.0, 21.0, 0.0, 0F, 0F) 44 | it.player.gameMode = GameMode.CREATIVE 45 | } 46 | 47 | val entities = mutableListOf() 48 | 49 | MinecraftServer.getCommandManager().register(Command("enodia").apply { 50 | addSubcommand(Command("add").apply { 51 | val typeArg = ArgumentType.Word("type").from("default", "aquatic", "not-aquaphobic", "avian") 52 | addSyntax({ sender, ctx -> 53 | if (sender !is Player) { 54 | return@addSyntax 55 | } 56 | val type: EntityType 57 | val capabilities: PathfindingCapabilities 58 | when (ctx[typeArg]) { 59 | "aquatic" -> { 60 | type = EntityType.DOLPHIN 61 | capabilities = PathfindingCapabilities.Default.copy(aquatic = true, aquaphobic = false) 62 | } 63 | "not-aquaphobic" -> { 64 | type = EntityType.DROWNED 65 | capabilities = PathfindingCapabilities.Default.copy(aquaphobic = false) 66 | } 67 | "avian" -> { 68 | type = EntityType.BEE 69 | capabilities = PathfindingCapabilities.Default.copy(avian = true) 70 | } 71 | else -> { 72 | type = EntityType.IRON_GOLEM 73 | capabilities = PathfindingCapabilities.Default 74 | } 75 | } 76 | val entity = EnodiaEntity(type) 77 | entity.setInstance(instance, sender.position).thenRun { 78 | entity.movementProcessor = hub.createMovementProcessor(entity, capabilities) 79 | synchronized(entities) { 80 | entities.add(entity) 81 | } 82 | } 83 | }, typeArg) 84 | }) 85 | addSubcommand(Command("remove", "rem").apply { 86 | addSyntax({_, _ -> 87 | synchronized(entities) { 88 | entities.removeLastOrNull()?.remove() 89 | } 90 | }) 91 | }) 92 | addSubcommand(Command("follow").apply { 93 | addSyntax({ sender, _ -> 94 | if (sender !is Player) { 95 | return@addSyntax 96 | } 97 | synchronized(entities) { 98 | entities.forEach { it.movementProcessor!!.goTo(sender, MovementImportance.UNIMPORTANT, 2F) } 99 | } 100 | }) 101 | }) 102 | addSubcommand(Command("stop").apply { 103 | addSyntax({ _, _ -> 104 | synchronized(entities) { 105 | entities.forEach { it.movementProcessor!!.stop(true) } 106 | } 107 | }) 108 | }) 109 | }) 110 | 111 | server.start("127.0.0.1", 25565) 112 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Enodia Path Finding Engine 2 | 3 | [![Watch preview video](https://img.youtube.com/vi/HmJu0Xa9F-0/0.jpg)](https://youtu.be/HmJu0Xa9F-0) 4 | 5 | **EnodiaPF** is a highly optimized asynchronous [Minestom](https://github.com/Minestom/Minestom) pathfinding engine. Being inspired by [Hydrazine](https://github.com/MadMartian/hydrazine-path-finding) and [Krystilize's](https://github.com/KrystilizeNevaDies) work, it takes on many of their aspects. As for Hydrazine, this is an incrementally progressive A* pathfinding engine that trades-off accuracy for significant boosts in path-finding performance by distributing A* graph computation across time and then rotation the graph on an as-needed basis as the subject entity physically traverses through path points derived from it. Thanks to this, in the game world it can: 6 | 1. If the destination is a long distance from the start, the path can be calculated in parts, with a new part only starting to be calculated when the entity made a certain progression on the previous part. 7 | 2. If an entity follows another entity and the destination point is constantly changing, the path will be recalculating online, but only if it is really necessary. 8 | 9 | Moreover, unlike its ancestors, the implementation of this engine focuses on maximizing its own performance, which is achieved by the following concepts: 10 | 1. Engine is asynchronous. Path recalculation for each entity is independent of each other. Moreover, for the same point of arrival of one entity, several pathfinding tasks can be running. Results of their executions will be accumulated together to ensure eventual consistency of the finalized path. 11 | 2. The process of path recalculation is not simple, and therefore may entail excessive use of non-infinite resources. All the code was written with an eye on that factor of influence: many internal things consist of primitives or pools of reusable objects to reduce memory allocations; and the number of synchronizations is minimized. For example, all the data from the instance (world) needed for the pathfinder is stored in a special cache, where exactly 3 bits are allocated per each block. This not only reduces the number of synchronizations to zero in case of immutable worlds, but also significantly reduces the amount of RAM required for the engine to function. 12 | 13 | Despite the fact trading-off accuracy for performance seems to be working pretty well, inaccurate path-finding is not always desirable. This engine provides you with an opportunity of specifying the maximum execution time that could be taken by the engine to calculate a path. Beyond that, it leaves you with a possibility to run custom logic in cases when path couldn't be calculated after certain amount of times or whether there is no valid path at all. 14 | 15 | ## Pathfinding 16 | The engine could be used as a pure pathfinder or also as a movement processor. 17 | 18 | To start with pathfinding, first initialize a `EnodiaPF` class by calling `EnodiaPF.forMutableWorlds()` or `EnodiaPF.forImmutableWorlds()`. 19 | All you need to do next is to call `enodia#createPathfindingTask` with various arguments to initialize the pathfinding task, and after that - call `task.run()`. 20 | You can do it in asynchronous environment, and the result will contain information about the path itself and also whether calculated path is complete, partial or if it was cancelled from the outside: yes, you can also asynchronously stop task execution at any moment of time by invoking `task.cancel()`. 21 | 22 | ### Capabilities 23 | Engine supports the following pathfinding capabilities that could be setup for an entity: 24 | - Fire Resistant - if set to true, entity will not be scared of going through the igniting environment (like lava, fire, magma). 25 | - Aquaphobic - if set to true, entity will try to avoid any kind of liquids. 26 | - Aquatic - if set to true, entity will not be able to move outside of liquids. 27 | - Avian - if set to true, entity can fly. 28 | 29 | ### Issues 30 | - Jumping is not supported. 31 | - Climbing up on ladder/liana/etc is not supported. 32 | - If it is the shortest way for the entity to go down, it does not take the height into account and therefore may die if falling damage is enabled. 33 | - Instead of natural descent from high altitudes, levitation occurs. 34 | - Sometimes entities can end up in extremely unnatural positions (for example, walk right through a mountain). 35 | - Entities are "floating" over liquids. 36 | 37 | ## Movement Processing 38 | Engine's movement processing part is what utilizes pathfinder and makes entities move. 39 | 40 | Unlike Hydrazine, EnodiaPF does not have an inbuilt Minestom API to be used. Therefore, there are some requirements you must follow in order to ensure engine is functioning well: 41 | 1. You are not allowed to manipulate entity's no-gravity option. The engine will do it itself. 42 | 2. Movement processor is a `Tickable`, so you need to tick it within `Entity#update(time)` method. 43 | 44 | The concept is as simple as follows: for every entity you can initialize a corresponding movement processor, which has the following methods: 45 | - `MovementProcessor#goTo(Point destination, Importance importance, float range)` - a command to calculate the path to the destination point. The importance indicates how much time engine is allowed to take on path calculation, which custom logic should be invoked on path calculation failure, and the range is the maximum distance from the destination point path is allowed to be diverged in order to count as complete. 46 | - `MovementProcessor#goTo(Entity target, Importance importance, float range)` - a command to start following the given entity. 47 | - `MovementProcessor#isActive` - whether there's some path that's currently calculating for that entity or if it has already been calculated and entity is following it. 48 | - `MovementProcessor#stop` - cancel all active path calculations and completely reset the movement state. 49 | 50 | There is also an example server that's included within test sources. Enjoy it! -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/provider/BlockStateProvider.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.provider 2 | 3 | import net.minestom.server.collision.BoundingBox 4 | import net.minestom.server.coordinate.Point 5 | import net.minestom.server.coordinate.Vec 6 | import net.minestom.server.entity.Entity 7 | import net.minestom.server.instance.Chunk 8 | import net.minestom.server.instance.block.Block 9 | import sexy.kostya.enodia.pathfinding.Passibility 10 | import sexy.kostya.enodia.pathfinding.PathfindingCapabilities 11 | import kotlin.math.floor 12 | 13 | interface BlockStateProvider { 14 | 15 | companion object { 16 | 17 | const val NotCollideable = 0x00 18 | const val Liquid = 0x01 19 | const val Solid = 0x02 20 | const val Complex = 0x03 21 | const val StateMask = 0x03 22 | 23 | const val FireBit = 0x04 24 | 25 | fun createMaskFromBlock(block: Block): Int { 26 | if (block == Block.AIR) { 27 | return NotCollideable 28 | } 29 | when (block.key().value()) { 30 | "water" -> return Liquid 31 | "lava" -> return Liquid or FireBit 32 | "fire", "soul_fire" -> return NotCollideable or FireBit 33 | } 34 | val inFire = if (block == Block.MAGMA_BLOCK) FireBit else 0 35 | val shape = block.registry().collisionShape() 36 | return if (Vec.ZERO.samePoint(shape.relativeStart()) && Vec.ONE.samePoint(shape.relativeEnd())) { 37 | if (block.isSolid) { 38 | Solid 39 | } else { 40 | NotCollideable 41 | } 42 | } else { 43 | Complex 44 | } or inFire 45 | } 46 | } 47 | 48 | fun loadChunk(chunk: Chunk) 49 | 50 | fun unloadChunk(chunk: Chunk) 51 | 52 | fun onBlockChanged(x: Int, y: Int, z: Int, block: Block) 53 | 54 | fun getBlockState(x: Int, y: Int, z: Int): Block 55 | 56 | fun getBlockMask(x: Int, y: Int, z: Int): Int 57 | 58 | fun getPassibility( 59 | entity: Entity, 60 | step: Float, 61 | capabilities: PathfindingCapabilities, 62 | x: Float, 63 | y: Float, 64 | z: Float 65 | ): Passibility { 66 | val bb = entity.boundingBox.contract(.1, 0.0, .1) 67 | return getPassibility( 68 | bb, 69 | step, 70 | capabilities, 71 | x, y, z, 72 | x, y, z 73 | ) 74 | } 75 | 76 | fun getPassibility( 77 | bb: BoundingBox, 78 | step: Float, 79 | capabilities: PathfindingCapabilities, 80 | parentX: Float, 81 | parentY: Float, 82 | parentZ: Float, 83 | x: Float, 84 | y: Float, 85 | z: Float 86 | ): Passibility { 87 | val bbMin = bb.relativeStart() 88 | val bbMax = bb.relativeEnd() 89 | 90 | val fromX = floor(bbMin.x() + x + .01F).toInt() 91 | val fromY = floor(bbMin.y() + y + .01F).toInt() 92 | val fromZ = floor(bbMin.z() + z + .01F).toInt() 93 | val toX = floor(bbMax.x() + x - .01F).toInt() 94 | val toY = floor(bbMax.y() + y - .01F).toInt() 95 | val toZ = floor(bbMax.z() + z - .01F).toInt() 96 | 97 | var inFire = false 98 | var inLiquid = false 99 | var pos: Point? = null 100 | for (bx in fromX..toX) { 101 | for (by in fromY - 1..toY) { 102 | val within = by != fromY - 1 103 | for (bz in fromZ..toZ) { 104 | val mask = getBlockMask(bx, by, bz) 105 | val state = mask and StateMask 106 | if (within && state == Solid) { 107 | return Passibility.Impassible 108 | } 109 | if (state == Complex) { 110 | val block = getBlockState(bx, by, bz) 111 | val blockPos = Vec(bx.toDouble(), by.toDouble() - step, bz.toDouble()) 112 | if (pos == null) { 113 | pos = Vec(x.toDouble(), y.toDouble(), z.toDouble()) 114 | } 115 | if (block.registry().collisionShape().intersectBox(pos.sub(blockPos), bb)) { 116 | return Passibility.Impassible 117 | } 118 | } else if (within && state == Liquid) { 119 | inLiquid = true 120 | } 121 | if (within && !capabilities.fireResistant && (mask and FireBit) != 0) { 122 | inFire = true 123 | } 124 | } 125 | } 126 | } 127 | if (inLiquid && inFire) { 128 | return Passibility.Impassible 129 | } 130 | val passibility = when { 131 | inFire -> Passibility.Dangerous 132 | inLiquid -> when { 133 | capabilities.aquaphobic -> Passibility.Dangerous 134 | capabilities.aquatic -> Passibility.Safe 135 | else -> Passibility.Undesirable 136 | } 137 | else -> when { 138 | capabilities.aquatic -> return Passibility.Impassible 139 | else -> Passibility.Safe 140 | } 141 | } 142 | if (!inLiquid && parentY <= y && !capabilities.avian) { 143 | val by = floor(bb.minY() + y - step).toInt() 144 | for (bx in fromX..toX) { 145 | for (bz in fromZ..toZ) { 146 | val mask = getBlockMask(bx, by, bz) 147 | val state = mask and StateMask 148 | if (state == Solid) { 149 | return passibility 150 | } 151 | if (state == Complex) { 152 | val block = getBlockState(bx, by, bz) 153 | val blockPos = Vec(bx.toDouble(), by.toDouble() + step, bz.toDouble()) 154 | if (pos == null) { 155 | pos = Vec(x.toDouble(), y.toDouble(), z.toDouble()) 156 | } 157 | if (block.registry().collisionShape().intersectBox(pos.sub(blockPos), bb)) { 158 | return passibility 159 | } 160 | } 161 | } 162 | } 163 | return Passibility.Impassible 164 | } 165 | return passibility 166 | } 167 | 168 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/EnodiaPF.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia 2 | 3 | import net.minestom.server.MinecraftServer 4 | import net.minestom.server.collision.BoundingBox 5 | import net.minestom.server.coordinate.Point 6 | import net.minestom.server.coordinate.Pos 7 | import net.minestom.server.entity.Entity 8 | import net.minestom.server.event.instance.InstanceChunkLoadEvent 9 | import net.minestom.server.event.instance.InstanceChunkUnloadEvent 10 | import net.minestom.server.event.instance.InstanceRegisteredEvent 11 | import net.minestom.server.event.instance.InstanceUnregisteredEvent 12 | import net.minestom.server.instance.Instance 13 | import sexy.kostya.enodia.movement.MovementProcessingHub 14 | import sexy.kostya.enodia.pathfinding.PathfindingCapabilities 15 | import sexy.kostya.enodia.pathfinding.PathfindingTask 16 | import sexy.kostya.enodia.provider.BlockStateProvider 17 | import sexy.kostya.enodia.provider.BlockStateProviderFactory 18 | import sexy.kostya.enodia.provider.immutable.ImmutableBlockStateProviderFactory 19 | import sexy.kostya.enodia.provider.mutable.MutableBlockStateProviderFactory 20 | import sexy.kostya.enodia.util.ReusablePoint 21 | 22 | class EnodiaPF(internal val blockStateProviderFactory: BlockStateProviderFactory<*>) { 23 | 24 | companion object { 25 | 26 | fun forMutableWorlds() = EnodiaPF(MutableBlockStateProviderFactory()) 27 | 28 | fun forImmutableWorlds() = EnodiaPF(ImmutableBlockStateProviderFactory()) 29 | 30 | } 31 | 32 | var debug = false 33 | 34 | init { 35 | MinecraftServer.getGlobalEventHandler().addListener(InstanceRegisteredEvent::class.java) { instanceEvent -> 36 | val instance = instanceEvent.instance 37 | val provider = blockStateProviderFactory.create(instance) 38 | instance.eventNode().addListener(InstanceChunkLoadEvent::class.java) { chunkEvent -> 39 | provider.loadChunk(chunkEvent.chunk) 40 | } 41 | instance.eventNode().addListener(InstanceChunkUnloadEvent::class.java) { chunkEvent -> 42 | provider.unloadChunk(chunkEvent.chunk) 43 | } 44 | } 45 | MinecraftServer.getGlobalEventHandler().addListener(InstanceUnregisteredEvent::class.java) { instanceEvent -> 46 | blockStateProviderFactory.remove(instanceEvent.instance) 47 | } 48 | } 49 | 50 | /** 51 | * @param start - point from where we start to calculate our path. 52 | * @param end - destination point. 53 | * @param range - the distance to the end point we need to reach to consider the calculation of the path completed. 54 | * @param step - distance between points within the calculated path. 55 | * Decreasing it's value results is more points in the path. 56 | * Increasing it results in less accurate navigation. 57 | * @param instance - the instance we're calculating path in. 58 | * @param capabilities - pathfinding capabilities of an entity. 59 | * @param boundingBox - bounding box of an entity. 60 | * @param entityPadding - allowable threshold for bounding box collision check. 61 | * @param maxRangeFromStart - the maximum distance path is allowed to go away from the starting point. 62 | */ 63 | fun createPathfindingTask( 64 | start: Point, 65 | end: Point, 66 | range: Float, 67 | step: Float, 68 | instance: Instance, 69 | capabilities: PathfindingCapabilities, 70 | boundingBox: BoundingBox, 71 | entityPadding: Float = .1F, 72 | maxRangeFromStart: Float = start.distance(end).toFloat() * 2F 73 | ) = createPathfindingTask( 74 | ReusablePoint.fromPoint(start), 75 | ReusablePoint.fromPoint(end), 76 | range, 77 | step, 78 | blockStateProviderFactory[instance], 79 | capabilities, 80 | boundingBox, 81 | entityPadding, 82 | maxRangeFromStart 83 | ) 84 | 85 | /** 86 | * @param start - point from where we start to calculate our path. 87 | * @param end - destination point. 88 | * @param range - the distance to the end point we need to reach to consider the calculation of the path completed. 89 | * @param step - distance between points within the calculated path. 90 | * Decreasing it's value results is more points in the path. 91 | * Increasing it results in less accurate navigation. 92 | * @param blockStateProvider - block state provider of the instance we're calculating path in. 93 | * @param capabilities - pathfinding capabilities of an entity. 94 | * @param boundingBox - bounding box of an entity. 95 | * @param entityPadding - allowable threshold for bounding box collision check. 96 | * @param maxRangeFromStart - the maximum distance path is allowed to go away from the starting point. 97 | */ 98 | fun createPathfindingTask( 99 | start: ReusablePoint, 100 | end: ReusablePoint, 101 | range: Float, 102 | step: Float, 103 | blockStateProvider: BlockStateProvider, 104 | capabilities: PathfindingCapabilities, 105 | boundingBox: BoundingBox, 106 | entityPadding: Float = .1F, 107 | maxRangeFromStart: Float = start.distance(end) * 2F 108 | ) = PathfindingTask( 109 | start, 110 | end, 111 | range, 112 | step, 113 | blockStateProvider, 114 | capabilities, 115 | boundingBox, 116 | entityPadding, 117 | maxRangeFromStart, 118 | debug 119 | ) 120 | 121 | /** 122 | * @param threads - amount of threads for movement concurrent calculation and execution. 123 | * Recommended value is max(2, Runtime.getRuntime().availableProcessors()). 124 | * @param maxRetries - in case we were unable to calculate complete path to the destination point, 125 | * how many times should we retry before giving up. Increasing it may drastically increase 126 | * CPU usage. 127 | * @param entitySpeedGetter - function to retrieve entity's speed. 128 | * @param entityContinueFollowing - function (may be null) to understand whether we want to continue following 129 | * given target. Default value restricts following of target that's not 130 | * within 24 blocks range, because path calculation complexity increases 131 | * quadratically with distance. 132 | */ 133 | fun initializeMovementProcessingHub( 134 | threads: Int, 135 | maxRetries: Int, 136 | entitySpeedGetter: (Entity) -> Float, 137 | entityContinueFollowing: (entity: Entity, target: Entity, distanceSquared: Float) -> Boolean = { _, _, ds -> ds <= 24 * 24 } 138 | ) = MovementProcessingHub(this, threads, maxRetries, entitySpeedGetter, entityContinueFollowing) 139 | 140 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/pathfinding/PathfindingTask.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.pathfinding 2 | 3 | import it.unimi.dsi.fastutil.ints.* 4 | import net.minestom.server.MinecraftServer 5 | import net.minestom.server.collision.BoundingBox 6 | import net.minestom.server.particle.Particle 7 | import net.minestom.server.particle.ParticleCreator 8 | import net.minestom.server.utils.PacketUtils 9 | import sexy.kostya.enodia.provider.BlockStateProvider 10 | import sexy.kostya.enodia.util.ReusablePoint 11 | import kotlin.math.* 12 | 13 | class PathfindingTask internal constructor( 14 | start: ReusablePoint, 15 | end: ReusablePoint, 16 | rawRequiredRange: Float, 17 | step: Float, 18 | private val blockStateProvider: BlockStateProvider, 19 | private val capabilities: PathfindingCapabilities, 20 | bb: BoundingBox, 21 | entityPadding: Float = .1F, 22 | maxRangeFromStart: Float = start.distance(end) * 2F, 23 | private val debug: Boolean = false 24 | ) { 25 | 26 | companion object { 27 | 28 | private const val MaxRange = 25F 29 | private const val MinStep = .05F 30 | private const val SignAbs = (MaxRange / MinStep).toInt() 31 | private const val CoordinateOffset = SignAbs shl 1 32 | private const val CoordinateOffsetSquared = CoordinateOffset * CoordinateOffset 33 | private const val MaxCoordinate = CoordinateOffsetSquared * CoordinateOffset 34 | } 35 | 36 | private val partial: Boolean 37 | private val fullDistance = start.distance(end) 38 | private val maxDistanceFromStartSquared: Float 39 | private val maxDistanceFromEnd: Float 40 | private val requiredRange = max(rawRequiredRange, MinStep) 41 | private val step = max(min(.25F, min(requiredRange, step)), MinStep) 42 | private val stepSquared: Float 43 | 44 | private val startX = start.x 45 | private val startY = start.y 46 | private val startZ = start.z 47 | private val baseDeltaX = (start.x - end.x) 48 | private val baseDeltaY = (start.y - end.y) 49 | private val baseDeltaZ = (start.z - end.z) 50 | 51 | private val bb = bb.contract(entityPadding.toDouble(), 0.0, entityPadding.toDouble()) 52 | 53 | private val relatives = IntArrayList(26) 54 | 55 | @Volatile 56 | private var cancelled: PathfindingResult.CancellationReason? = null 57 | 58 | init { 59 | require(requiredRange >= MinStep) { "Required range can't be less than $MinStep" } 60 | this.stepSquared = this.step * this.step 61 | val maxDistanceFromStart = min(maxRangeFromStart, MaxRange) 62 | if (fullDistance - requiredRange <= MaxRange) { 63 | partial = false 64 | maxDistanceFromEnd = requiredRange 65 | } else { 66 | partial = true 67 | maxDistanceFromEnd = fullDistance - requiredRange - MaxRange 68 | } 69 | maxDistanceFromStartSquared = maxDistanceFromStart * maxDistanceFromStart 70 | 71 | if (capabilities.avian || capabilities.aquatic) { 72 | for (dy in 1 downTo -1) { 73 | for (dx in -1..1) { 74 | for (dz in -1..1) { 75 | if (dx == 0 && dy == 0 && dz == 0) { 76 | continue 77 | } 78 | relatives.add(relative(dx, dy, dz)) 79 | } 80 | } 81 | } 82 | } else { 83 | val oneDy = ceil(1F / this.step).toInt() 84 | val halfDy = ceil(.5F / this.step).toInt() 85 | for (dx in -1..1) { 86 | for (dz in -1..1) { 87 | relatives.add(relative(dx, -oneDy, dz)) 88 | relatives.add(relative(dx, -halfDy, dz)) 89 | relatives.add(relative(dx, -1, dz)) 90 | if (dx == 0 && dz == 0) { 91 | continue 92 | } 93 | relatives.add(relative(dx, 0, dz)) 94 | relatives.add(relative(dx, oneDy, dz)) 95 | relatives.add(relative(dx, halfDy, dz)) 96 | } 97 | } 98 | } 99 | } 100 | 101 | fun run(): PathfindingResult { 102 | val passibilities = Int2ObjectOpenHashMap() 103 | val cameFrom = Int2IntOpenHashMap() 104 | cameFrom.defaultReturnValue(-1) 105 | val visited = IntOpenHashSet() 106 | val queue = IntHeapPriorityQueue { indexA, indexB -> 107 | val passibilityComparison = passibilities[indexA].compareTo(passibilities[indexB]) 108 | if (passibilityComparison != 0) { 109 | passibilityComparison 110 | } else { 111 | val priceA = sqrt(indexA.distanceSquaredToStart()) + 2 * sqrt(indexA.distanceSquaredToEnd()) 112 | val priceB = sqrt(indexB.distanceSquaredToStart()) + 2 * sqrt(indexB.distanceSquaredToEnd()) 113 | priceA.compareTo(priceB) 114 | } 115 | } 116 | val startIndex = index(0, 0, 0) 117 | passibilities[startIndex] = Passibility.Safe 118 | queue.enqueue(startIndex) 119 | var best = startIndex 120 | var bestDist = 1000000F 121 | var bestPassibility = Passibility.Impassible 122 | while (!queue.isEmpty) { 123 | if (cancelled != null) { 124 | return PathfindingResult( 125 | PathfindingResult.Status.CANCELLED, 126 | if (cancelled == PathfindingResult.CancellationReason.TIMED_OUT) reconstructPath(cameFrom, best) else emptyList(), 127 | cancelled 128 | ) 129 | } 130 | val current = queue.dequeueInt() 131 | val currentX = ((current % CoordinateOffset) - SignAbs) * step 132 | val trimmed = current / CoordinateOffset 133 | val currentY = ((trimmed % CoordinateOffset) - SignAbs) * step 134 | val currentZ = (((trimmed / CoordinateOffset) % CoordinateOffset) - SignAbs) * step 135 | 136 | if (debug) { 137 | PacketUtils.sendGroupedPacket( 138 | MinecraftServer.getConnectionManager().onlinePlayers, 139 | ParticleCreator.createParticlePacket( 140 | Particle.FLAME, 141 | (startX + currentX).toDouble(), 142 | (startY + currentY).toDouble(), 143 | (startZ + currentZ).toDouble(), 144 | 0F, 0F, 0F, 145 | 1 146 | ) 147 | ) 148 | } 149 | 150 | val distanceToEndSquared = 151 | (baseDeltaX + currentX).pow(2) + (baseDeltaY + currentY).pow(2) + (baseDeltaZ + currentZ).pow(2) 152 | val distanceToEnd = sqrt(distanceToEndSquared) 153 | if (distanceToEnd <= maxDistanceFromEnd && current.getPassibility(null, null, null) != Passibility.Impassible) { 154 | return PathfindingResult( 155 | if (partial) PathfindingResult.Status.PARTIAL else PathfindingResult.Status.COMPLETED, 156 | reconstructPath(cameFrom, current) 157 | ) 158 | } 159 | if (currentX * currentX + currentY * currentY + currentZ * currentZ >= maxDistanceFromStartSquared) { 160 | continue 161 | } 162 | val currentPassibility = passibilities[current] 163 | if (distanceToEndSquared < bestDist || currentPassibility < bestPassibility) { 164 | best = current 165 | bestDist = distanceToEndSquared 166 | bestPassibility = currentPassibility 167 | } 168 | val iterator = relatives.intIterator() 169 | while (iterator.hasNext()) { 170 | val relative = current + iterator.nextInt() 171 | if (relative < 0 || relative >= MaxCoordinate) { 172 | continue 173 | } 174 | if (visited.contains(relative) || passibilities.containsKey(relative)) { 175 | continue 176 | } 177 | val passibility = relative.getPassibility(startX + currentX, startY + currentY, startZ + currentZ) 178 | if (passibility == Passibility.Impassible) { 179 | continue 180 | } 181 | passibilities[relative] = maxOf(currentPassibility, passibility) 182 | queue.enqueue(relative) 183 | cameFrom[relative] = current 184 | } 185 | visited.add(current) 186 | } 187 | return PathfindingResult(PathfindingResult.Status.FAILED, reconstructPath(cameFrom, best)) 188 | } 189 | 190 | fun cancel(reason: PathfindingResult.CancellationReason) { 191 | cancelled = reason 192 | } 193 | 194 | private fun reconstructPath(cameFrom: Int2IntMap, endIndex: Int): List { 195 | val indexedPath = IntArrayList() 196 | var current = endIndex 197 | while (current != -1) { 198 | indexedPath.add(current) 199 | current = cameFrom[current] 200 | } 201 | if (indexedPath.size == 1) { 202 | return emptyList() 203 | } 204 | if (indexedPath.size == 2) { 205 | return listOf(indexedPath.first().toPoint()) 206 | } 207 | indexedPath.removeLast() 208 | indexedPath.reverse() 209 | 210 | if (true) { 211 | return indexedPath.map { it.toPoint() } 212 | } 213 | 214 | val result = ArrayList(indexedPath.size) 215 | val iterator = indexedPath.intIterator() 216 | val first = iterator.nextInt() 217 | var px = (first % CoordinateOffset) - SignAbs 218 | val pt = first / CoordinateOffset 219 | var py = (pt % CoordinateOffset) - SignAbs 220 | var pz = ((pt / CoordinateOffset) % CoordinateOffset) - SignAbs 221 | var dirX = -100 222 | var dirY = -100 223 | var dirZ = -100 224 | while (iterator.hasNext()) { 225 | val index = iterator.nextInt() 226 | val nx = (index % CoordinateOffset) - SignAbs 227 | val nt = index / CoordinateOffset 228 | val ny = (nt % CoordinateOffset) - SignAbs 229 | val nz = ((nt / CoordinateOffset) % CoordinateOffset) - SignAbs 230 | 231 | val dx = nx - px 232 | val dy = ny - py 233 | val dz = nz - pz 234 | if (dx != dirX || dy != dirY || dz != dirZ) { 235 | result.add( 236 | ReusablePoint[ 237 | (startX + px * step), 238 | (startY + py * step), 239 | (startZ + pz * step), 240 | ] 241 | ) 242 | dirX = dx 243 | dirY = dy 244 | dirZ = dz 245 | } 246 | px = nx 247 | py = ny 248 | pz = nz 249 | } 250 | val endX = startX + px * step 251 | val initialEndY = startY + py * step 252 | var endY = initialEndY 253 | val endZ = startZ + pz * step 254 | while (blockStateProvider.getPassibility( 255 | bb, 256 | step, 257 | capabilities, 258 | endX, endY, endZ, 259 | endX, endY, endZ 260 | ) == Passibility.Impassible && endY >= initialEndY - 10F 261 | ) { 262 | endY -= MinStep 263 | } 264 | if (endY < initialEndY - 10F) { 265 | endY = initialEndY 266 | } 267 | result.add(ReusablePoint[endX, endY, endZ]) 268 | return result 269 | } 270 | 271 | private fun index(dx: Int, dy: Int, dz: Int) = 272 | (dx + SignAbs) + CoordinateOffset * ((dy + SignAbs) + CoordinateOffset * (dz + SignAbs)) 273 | 274 | private fun relative(dx: Int, dy: Int, dz: Int) = 275 | if (dx == 0) { 276 | if (dy == 0) { 277 | if (dz == 0) { 278 | 0 279 | } else { 280 | CoordinateOffsetSquared * dz 281 | } 282 | } else { 283 | if (dz == 0) { 284 | CoordinateOffset * dy 285 | } else { 286 | CoordinateOffset * (dy + CoordinateOffset * dz) 287 | } 288 | } 289 | } else { 290 | if (dy == 0) { 291 | if (dz == 0) { 292 | dx 293 | } else { 294 | dx + CoordinateOffsetSquared * dz 295 | } 296 | } else { 297 | if (dz == 0) { 298 | dx + CoordinateOffset * dy 299 | } else { 300 | dx + CoordinateOffset * (dy + CoordinateOffset * dz) 301 | } 302 | } 303 | } 304 | 305 | private fun Int.distanceSquaredToEnd(): Float { 306 | val dx = (this % CoordinateOffset) - SignAbs 307 | val trimmed = this / CoordinateOffset 308 | val dy = (trimmed % CoordinateOffset) - SignAbs 309 | val dz = ((trimmed / CoordinateOffset) % CoordinateOffset) - SignAbs 310 | 311 | val x = baseDeltaX + dx * step 312 | val y = baseDeltaY + dy * step 313 | val z = baseDeltaZ + dz * step 314 | return x * x + y * y + z * z 315 | } 316 | 317 | private fun Int.distanceSquaredToStart(): Float { 318 | val dx = (this % CoordinateOffset) - SignAbs 319 | val trimmed = this / CoordinateOffset 320 | val dy = (trimmed % CoordinateOffset) - SignAbs 321 | val dz = ((trimmed / CoordinateOffset) % CoordinateOffset) - SignAbs 322 | 323 | val x = dx * step 324 | val y = dy * step 325 | val z = dz * step 326 | return x * x + y * y + z * z 327 | } 328 | 329 | private fun Int.toPoint(): ReusablePoint { 330 | val dx = (this % CoordinateOffset) - SignAbs 331 | val trimmed = this / CoordinateOffset 332 | val dy = (trimmed % CoordinateOffset) - SignAbs 333 | val dz = ((trimmed / CoordinateOffset) % CoordinateOffset) - SignAbs 334 | 335 | return ReusablePoint[ 336 | startX + dx * step, 337 | startY + dy * step, 338 | startZ + dz * step 339 | ] 340 | } 341 | 342 | private fun Int.getPassibility(parentX: Float?, parentY: Float?, parentZ: Float?): Passibility { 343 | val dx = (this % CoordinateOffset) - SignAbs 344 | val trimmed = this / CoordinateOffset 345 | val dy = (trimmed % CoordinateOffset) - SignAbs 346 | val dz = ((trimmed / CoordinateOffset) % CoordinateOffset) - SignAbs 347 | val x = startX + dx * step 348 | val y = startY + dy * step 349 | val z = startZ + dz * step 350 | return blockStateProvider.getPassibility( 351 | bb, step, capabilities, 352 | parentX ?: x, parentY ?: y, parentZ ?: z, 353 | x, y, z 354 | ) 355 | } 356 | 357 | } -------------------------------------------------------------------------------- /src/main/kotlin/sexy/kostya/enodia/movement/MovementProcessorImpl.kt: -------------------------------------------------------------------------------- 1 | package sexy.kostya.enodia.movement 2 | 3 | import net.minestom.server.MinecraftServer 4 | import net.minestom.server.coordinate.Point 5 | import net.minestom.server.coordinate.Pos 6 | import net.minestom.server.entity.Entity 7 | import net.minestom.server.utils.position.PositionUtils 8 | import sexy.kostya.enodia.movement.importance.MovementImportance 9 | import sexy.kostya.enodia.pathfinding.PathfindingCapabilities 10 | import sexy.kostya.enodia.pathfinding.PathfindingResult 11 | import sexy.kostya.enodia.pathfinding.PathfindingTask 12 | import sexy.kostya.enodia.provider.BlockStateProvider 13 | import sexy.kostya.enodia.util.ReusablePoint 14 | import java.util.concurrent.TimeUnit 15 | import kotlin.math.atan2 16 | import kotlin.math.cos 17 | import kotlin.math.sin 18 | import kotlin.math.sqrt 19 | 20 | class MovementProcessorImpl internal constructor( 21 | private val entity: Entity, 22 | private val pathfindingCapabilities: PathfindingCapabilities, 23 | private val hub: MovementProcessingHub, 24 | private val blockStateProvider: BlockStateProvider 25 | ) : MovementProcessor { 26 | 27 | private val step = entity.boundingBox.width().coerceAtMost(entity.boundingBox.depth()).toFloat() / 2F 28 | private var path = mutableListOf() 29 | private var pathIndex = 0 30 | private var pathLength = 0F 31 | 32 | private var inProgress: PathfindingTask? = null 33 | 34 | private var lastDestination: ReusablePoint? = null 35 | private var lastTarget: Entity? = null 36 | private var lastImportance: MovementImportance? = null 37 | private var lastRange: Float = 0F 38 | 39 | init { 40 | if (pathfindingCapabilities.avian || pathfindingCapabilities.aquatic) { 41 | entity.setNoGravity(true) 42 | } 43 | } 44 | 45 | override fun tick(time: Long) { 46 | val lastTarget = lastTarget 47 | if (lastTarget != null && (lastTarget.isRemoved || lastTarget.instance != entity.instance)) { 48 | stop() 49 | return 50 | } 51 | when { 52 | path.size == 0 -> return 53 | 54 | pathIndex == path.size -> { 55 | if (inProgress == null) { 56 | if (lastTarget != null) { 57 | val lastImportance = lastImportance!! 58 | val lastRange = lastRange 59 | clearLastData(true) 60 | goTo(lastTarget, lastImportance, lastRange) 61 | } else { 62 | clearLastData(true) 63 | } 64 | } 65 | } 66 | 67 | else -> { 68 | if (inProgress == null && lastTarget != null) { 69 | val last = path.last() 70 | val actual = getEntityPosition(lastTarget) 71 | if (actual == null) { 72 | stop() 73 | return 74 | } 75 | val range = lastRange 76 | val importance = lastImportance!! 77 | 78 | val dist = last.distanceSquared(actual) 79 | if (dist > range * range) { 80 | val currentPosition = ReusablePoint.fromPoint(entity.position) 81 | if (pathLength + sqrt(dist) > 1.5 * currentPosition.distance(actual)) { 82 | stop(false) 83 | goTo(lastTarget, importance, range) 84 | return 85 | } 86 | currentPosition.release() 87 | initialize(last, { getEntityPosition(lastTarget) }, range, importance, 0, false) 88 | } 89 | } 90 | move() 91 | } 92 | } 93 | } 94 | 95 | private fun move() { 96 | if (pathIndex >= path.size) { 97 | return 98 | } 99 | var speed = hub.entitySpeedGetter(entity) 100 | var dest = path[pathIndex] 101 | var pos = ReusablePoint.fromPoint(entity.position) 102 | while (true) { 103 | val dx = dest.x - pos.x 104 | val dy = dest.y - pos.y 105 | val dz = dest.z - pos.z 106 | val distance = sqrt(dx * dx + dz * dz) 107 | if (speed > distance) { 108 | pos.release() 109 | pos = dest 110 | if (++pathIndex == path.size) { 111 | break 112 | } 113 | dest = path[pathIndex] 114 | speed -= distance 115 | } else if (speed == distance) { 116 | pos.release() 117 | pos = dest 118 | pathIndex++ 119 | break 120 | } else { 121 | val radians = atan2(dz, dx) 122 | pos.x += speed * cos(radians) 123 | pos.y += dy 124 | pos.z += speed * sin(radians) 125 | break 126 | } 127 | } 128 | val from = entity.position 129 | val dx = pos.x - from.x 130 | val dz = pos.z - from.z 131 | entity.refreshPosition( 132 | Pos( 133 | pos.x.toDouble(), 134 | pos.y.toDouble(), 135 | pos.z.toDouble(), 136 | PositionUtils.getLookYaw(dx, dz), 137 | 0F 138 | ) 139 | ) 140 | } 141 | 142 | override fun goTo(destination: Point, importance: MovementImportance, range: Float): Boolean { 143 | if (hub.entitySpeedGetter(entity) <= 0F) { 144 | return false 145 | } 146 | val reusableDestination = ReusablePoint.fromPoint(destination) 147 | if (lastDestination != null && lastDestination!!.samePoint(reusableDestination) && lastImportance == importance && lastRange == range) { 148 | reusableDestination.release() 149 | return false 150 | } 151 | stop() 152 | lastDestination = reusableDestination 153 | lastImportance = importance 154 | lastRange = range 155 | 156 | return initialize(ReusablePoint.fromPoint(entity.position), { reusableDestination }, range, importance, 0, false) 157 | } 158 | 159 | override fun goTo(target: Entity, importance: MovementImportance, range: Float): Boolean { 160 | if (lastTarget === target && lastImportance == importance && lastRange == range) { 161 | return false 162 | } 163 | if (hub.entitySpeedGetter(entity) <= 0F) { 164 | return false 165 | } 166 | stop() 167 | lastTarget = target 168 | lastImportance = importance 169 | lastRange = range 170 | 171 | return initialize(ReusablePoint.fromPoint(entity.position), { getEntityPosition(target) }, range, importance, 0, false) 172 | } 173 | 174 | private fun initialize( 175 | from: ReusablePoint, 176 | destination: () -> ReusablePoint?, 177 | range: Float, 178 | importance: MovementImportance, 179 | retries: Int, 180 | useMaxTime: Boolean 181 | ): Boolean { 182 | if (retries == hub.maxRetries) { 183 | importance.onPathCalculationFailed(entity, destination() ?: return false) 184 | return true 185 | } 186 | 187 | val nextDestination = destination() ?: return false 188 | if (inProgress != null) { 189 | inProgress?.cancel(PathfindingResult.CancellationReason.OUTDATED) 190 | inProgress = null 191 | } 192 | ReusablePoint.fromPoint(entity.position).use { currentPosition -> 193 | val distanceSquared = currentPosition.distanceSquared(nextDestination) 194 | if (distanceSquared <= range * range) { 195 | clearLastData(true) 196 | return true 197 | } 198 | val lastTarget = lastTarget 199 | val continueFollowing = hub.entityContinueFollowing 200 | if (lastTarget != null && !continueFollowing(entity, lastTarget, distanceSquared)) { 201 | clearLastData(true) 202 | importance.onPathCalculationFailed(entity, nextDestination) 203 | return true 204 | } 205 | } 206 | val task = hub.pf.createPathfindingTask( 207 | from, 208 | nextDestination, 209 | range, 210 | step, 211 | blockStateProvider, 212 | pathfindingCapabilities, 213 | entity.boundingBox, 214 | ) 215 | inProgress = task 216 | hub.movementExecutor.execute { 217 | try { 218 | val result = task.run() 219 | entity.scheduleNextTick { 220 | if (inProgress === task) { 221 | processResult(result, destination, range, importance, retries, useMaxTime) 222 | } 223 | } 224 | } catch (t: Throwable) { 225 | MinecraftServer.LOGGER.error("Could not run pathfinding", t) 226 | } 227 | } 228 | hub.cancellationExecutor.schedule({ 229 | task.cancel(PathfindingResult.CancellationReason.TIMED_OUT) 230 | }, if (useMaxTime) importance.maxExecutionTime else importance.averageExecutionTime, TimeUnit.MILLISECONDS) 231 | return true 232 | } 233 | 234 | private fun processResult( 235 | result: PathfindingResult, 236 | destination: () -> ReusablePoint?, 237 | range: Float, 238 | importance: MovementImportance, 239 | retries: Int, 240 | useMaxTime: Boolean 241 | ) { 242 | if (result.path.isNotEmpty()) { 243 | if (pathIndex == path.size) { 244 | path.clear() 245 | path.addAll(result.path) 246 | pathIndex = 0 247 | ReusablePoint.fromPoint(entity.position).use { 248 | pathLength = result.path.length(it) 249 | } 250 | } else if (pathIndex != 0) { 251 | path = path.subList(pathIndex, path.size) 252 | path.addAll(result.path) 253 | pathIndex = 0 254 | ReusablePoint.fromPoint(entity.position).use { 255 | pathLength = path.length(it) 256 | } 257 | } else { 258 | path += result.path 259 | pathLength += result.path.length(path.last()) 260 | } 261 | } 262 | inProgress = null 263 | when (result.status) { 264 | PathfindingResult.Status.FAILED -> { 265 | if (result.path.isEmpty()) { 266 | destination()?.let { importance.onPathCalculationFailed(entity, it) } 267 | stop() 268 | } else { 269 | initialize(path.last(), destination, range, importance, retries + 1, false) 270 | } 271 | } 272 | 273 | PathfindingResult.Status.CANCELLED -> { 274 | if (result.cancellationReason == PathfindingResult.CancellationReason.TIMED_OUT) { 275 | if (result.path.isEmpty()) { 276 | if (useMaxTime || importance.averageExecutionTime == importance.maxExecutionTime) { 277 | stop(destination()?.let { importance.onPathCalculationFailed(entity, it) } == true) 278 | } else { 279 | initialize( 280 | path.lastOrNull() ?: ReusablePoint.fromPoint(entity.position), 281 | destination, 282 | range, 283 | importance, 284 | retries + 1, 285 | true 286 | ) 287 | } 288 | } else { 289 | initialize(path.last(), destination, range, importance, retries + 1, false) 290 | } 291 | } 292 | } 293 | 294 | PathfindingResult.Status.PARTIAL -> { 295 | if (result.path.isEmpty() && destination()?.let { importance.onPathCalculationFailed(entity, it) } == true) { 296 | stop() 297 | } else { 298 | initialize(path.last(), destination, range, importance, retries + 1, false) 299 | } 300 | } 301 | 302 | PathfindingResult.Status.COMPLETED -> { 303 | val last = result.path.lastOrNull() ?: return 304 | val dest = destination() ?: return 305 | if (last.distanceSquared(dest) > range * range) { 306 | val currentPosition = ReusablePoint.fromPoint(entity.position) 307 | if (pathLength + last.distance(dest) > 1.5 * currentPosition.distance(dest)) { 308 | val lastTarget = lastTarget 309 | if (lastTarget != null) { 310 | stop(false) 311 | goTo(lastTarget, importance, range) 312 | } 313 | } else { 314 | currentPosition.release() 315 | initialize(last, destination, range, importance, 0, false) 316 | } 317 | } 318 | } 319 | } 320 | } 321 | 322 | override fun isActive() = pathIndex != path.size || inProgress != null 323 | 324 | override fun stop(clearPath: Boolean) { 325 | cancelTaskInProgress() 326 | clearLastData(clearPath) 327 | } 328 | 329 | private fun cancelTaskInProgress() { 330 | val inProgress = inProgress 331 | if (inProgress != null) { 332 | inProgress.cancel(PathfindingResult.CancellationReason.OUTDATED) 333 | this.inProgress = null 334 | } 335 | } 336 | 337 | private fun clearLastData(clearPath: Boolean) { 338 | if (clearPath) { 339 | for (i in pathIndex until path.size) { 340 | path[i].release() 341 | } 342 | path.clear() 343 | pathIndex = 0 344 | pathLength = 0F 345 | } 346 | 347 | lastDestination = null 348 | lastTarget = null 349 | lastImportance = null 350 | lastRange = 0F 351 | } 352 | 353 | private fun getEntityPosition(target: Entity): ReusablePoint? { 354 | if (target.instance != entity.instance) { 355 | return null 356 | } 357 | val pos = ReusablePoint.fromPoint(target.position) 358 | if (pathfindingCapabilities.avian) { 359 | pos.y += target.eyeHeight.toFloat() 360 | } 361 | return pos 362 | } 363 | 364 | private fun List.length(from: ReusablePoint): Float { 365 | var result = 0F 366 | var current = from 367 | for (next in this) { 368 | result += current.distance(next) 369 | current = next 370 | } 371 | return result 372 | } 373 | } --------------------------------------------------------------------------------