| 1 | /*
|
| 2 | * This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
|
| 3 | *
|
| 4 | * Copyright (c) 2015 - 2026 CCBlueX
|
| 5 | *
|
| 6 | * LiquidBounce is free software: you can redistribute it and/or modify
|
| 7 | * it under the terms of the GNU General Public License as published by
|
| 8 | * the Free Software Foundation, either version 3 of the License, or
|
| 9 | * (at your option) any later version.
|
| 10 | *
|
| 11 | * LiquidBounce is distributed in the hope that it will be useful,
|
| 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 14 | * GNU General Public License for more details.
|
| 15 | *
|
| 16 | * You should have received a copy of the GNU General Public License
|
| 17 | * along with LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
|
| 18 | */
|
| 19 |
|
| 20 | @file:Suppress("TooManyFunctions")
|
| 21 |
|
| 22 | package net.ccbluex.liquidbounce.utils.block
|
| 23 |
|
| 24 | import com.google.common.base.Predicates
|
| 25 | import net.ccbluex.fastutil.weightedFilterSortedByAtMost
|
| 26 | import it.unimi.dsi.fastutil.booleans.BooleanObjectPair
|
| 27 | import it.unimi.dsi.fastutil.ints.IntCollection
|
| 28 | import it.unimi.dsi.fastutil.ints.IntLongPair
|
| 29 | import it.unimi.dsi.fastutil.longs.LongOpenHashSet
|
| 30 | import net.ccbluex.liquidbounce.event.EventManager
|
| 31 | import net.ccbluex.liquidbounce.event.events.BlockBreakingProgressEvent
|
| 32 | import net.ccbluex.liquidbounce.features.addon.AddonApi
|
| 33 | import net.ccbluex.liquidbounce.render.FULL_BOX
|
| 34 | import net.ccbluex.liquidbounce.utils.aiming.data.Rotation
|
| 35 | import net.ccbluex.liquidbounce.utils.block.targetfinding.BlockOffsetOptions
|
| 36 | import net.ccbluex.liquidbounce.utils.block.targetfinding.BlockPlacementTargetFindingOptions
|
| 37 | import net.ccbluex.liquidbounce.utils.block.targetfinding.CenterTargetPositionFactory
|
| 38 | import net.ccbluex.liquidbounce.utils.block.targetfinding.FaceHandlingOptions
|
| 39 | import net.ccbluex.liquidbounce.utils.block.targetfinding.PlayerLocationOnPlacement
|
| 40 | import net.ccbluex.liquidbounce.utils.block.targetfinding.findBestBlockPlacementTarget
|
| 41 | import net.ccbluex.liquidbounce.utils.client.interaction
|
| 42 | import net.ccbluex.liquidbounce.utils.client.isOlderThan1_21_2
|
| 43 | import net.ccbluex.liquidbounce.utils.client.mc
|
| 44 | import net.ccbluex.liquidbounce.utils.client.player
|
| 45 | import net.ccbluex.liquidbounce.utils.client.world
|
| 46 | import net.ccbluex.liquidbounce.utils.math.boundsOrNull
|
| 47 | import net.ccbluex.liquidbounce.utils.math.distanceToSqr
|
| 48 | import net.ccbluex.liquidbounce.utils.math.iterator
|
| 49 | import net.ccbluex.liquidbounce.utils.math.plus
|
| 50 | import net.ccbluex.liquidbounce.utils.math.sq
|
| 51 | import net.ccbluex.liquidbounce.utils.network.useItem
|
| 52 | import net.ccbluex.liquidbounce.utils.raytracing.traceFromPlayer
|
| 53 | import net.minecraft.core.BlockPos
|
| 54 | import net.minecraft.core.Direction
|
| 55 | import net.minecraft.core.TypedInstance
|
| 56 | import net.minecraft.core.Vec3i
|
| 57 | import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket
|
| 58 | import net.minecraft.tags.BlockTags
|
| 59 | import net.minecraft.world.InteractionHand
|
| 60 | import net.minecraft.world.InteractionResult
|
| 61 | import net.minecraft.world.InteractionResult.Success
|
| 62 | import net.minecraft.world.InteractionResult.SwingSource
|
| 63 | import net.minecraft.world.entity.Entity
|
| 64 | import net.minecraft.world.entity.EntitySelector
|
| 65 | import net.minecraft.world.entity.boss.enderdragon.EndCrystal
|
| 66 | import net.minecraft.world.item.ItemStack
|
| 67 | import net.minecraft.world.item.context.BlockPlaceContext
|
| 68 | import net.minecraft.world.level.BlockGetter
|
| 69 | import net.minecraft.world.level.ClipContext
|
| 70 | import net.minecraft.world.level.block.AbstractChestBlock
|
| 71 | import net.minecraft.world.level.block.AbstractFurnaceBlock
|
| 72 | import net.minecraft.world.level.block.AnvilBlock
|
| 73 | import net.minecraft.world.level.block.BarrelBlock
|
| 74 | import net.minecraft.world.level.block.BeaconBlock
|
| 75 | import net.minecraft.world.level.block.BedBlock
|
| 76 | import net.minecraft.world.level.block.BellBlock
|
| 77 | import net.minecraft.world.level.block.Block
|
| 78 | import net.minecraft.world.level.block.Blocks
|
| 79 | import net.minecraft.world.level.block.BrewingStandBlock
|
| 80 | import net.minecraft.world.level.block.ButtonBlock
|
| 81 | import net.minecraft.world.level.block.CakeBlock
|
| 82 | import net.minecraft.world.level.block.CandleCakeBlock
|
| 83 | import net.minecraft.world.level.block.CartographyTableBlock
|
| 84 | import net.minecraft.world.level.block.CaveVines
|
| 85 | import net.minecraft.world.level.block.CaveVinesBlock
|
| 86 | import net.minecraft.world.level.block.CaveVinesPlantBlock
|
| 87 | import net.minecraft.world.level.block.ChestBlock
|
| 88 | import net.minecraft.world.level.block.ComparatorBlock
|
| 89 | import net.minecraft.world.level.block.ComposterBlock
|
| 90 | import net.minecraft.world.level.block.CrafterBlock
|
| 91 | import net.minecraft.world.level.block.CraftingTableBlock
|
| 92 | import net.minecraft.world.level.block.DaylightDetectorBlock
|
| 93 | import net.minecraft.world.level.block.DecoratedPotBlock
|
| 94 | import net.minecraft.world.level.block.DispenserBlock
|
| 95 | import net.minecraft.world.level.block.DoorBlock
|
| 96 | import net.minecraft.world.level.block.DoubleBlockCombiner
|
| 97 | import net.minecraft.world.level.block.DragonEggBlock
|
| 98 | import net.minecraft.world.level.block.EnchantingTableBlock
|
| 99 | import net.minecraft.world.level.block.FenceGateBlock
|
| 100 | import net.minecraft.world.level.block.FlowerPotBlock
|
| 101 | import net.minecraft.world.level.block.GameMasterBlock
|
| 102 | import net.minecraft.world.level.block.GrindstoneBlock
|
| 103 | import net.minecraft.world.level.block.HopperBlock
|
| 104 | import net.minecraft.world.level.block.HorizontalDirectionalBlock
|
| 105 | import net.minecraft.world.level.block.JukeboxBlock
|
| 106 | import net.minecraft.world.level.block.LecternBlock
|
| 107 | import net.minecraft.world.level.block.LeverBlock
|
| 108 | import net.minecraft.world.level.block.LightBlock
|
| 109 | import net.minecraft.world.level.block.NoteBlock
|
| 110 | import net.minecraft.world.level.block.RedStoneWireBlock
|
| 111 | import net.minecraft.world.level.block.RepeaterBlock
|
| 112 | import net.minecraft.world.level.block.RespawnAnchorBlock
|
| 113 | import net.minecraft.world.level.block.ShulkerBoxBlock
|
| 114 | import net.minecraft.world.level.block.StonecutterBlock
|
| 115 | import net.minecraft.world.level.block.SupportType
|
| 116 | import net.minecraft.world.level.block.SweetBerryBushBlock
|
| 117 | import net.minecraft.world.level.block.TrapDoorBlock
|
| 118 | import net.minecraft.world.level.block.state.BlockBehaviour
|
| 119 | import net.minecraft.world.level.block.state.BlockState
|
| 120 | import net.minecraft.world.level.levelgen.structure.BoundingBox
|
| 121 | import net.minecraft.world.level.material.Fluids
|
| 122 | import net.minecraft.world.phys.AABB
|
| 123 | import net.minecraft.world.phys.BlockHitResult
|
| 124 | import net.minecraft.world.phys.HitResult
|
| 125 | import net.minecraft.world.phys.Vec3
|
| 126 | import net.minecraft.world.phys.shapes.CollisionContext
|
| 127 | import net.minecraft.world.phys.shapes.Shapes
|
| 128 | import net.minecraft.world.phys.shapes.VoxelShape
|
| 129 | import java.util.function.BiPredicate
|
| 130 | import java.util.function.Predicate
|
| 131 | import kotlin.math.ceil
|
| 132 | import kotlin.math.floor
|
| 133 |
|
| 134 | fun Vec3i.toBlockPos() = BlockPos(this)
|
| 135 |
|
| 136 | @AddonApi
|
| 137 | val BlockPos.state: BlockState? get() = mc.level?.getBlockState(this)
|
| 138 |
|
| 139 | @Deprecated(
|
| 140 | "Use BlockPos.state or BlockPos.stateOrEmpty instead",
|
| 141 | replaceWith = ReplaceWith("this.state", imports = ["net.ccbluex.liquidbounce.utils.block.state"]),
|
| 142 | level = DeprecationLevel.ERROR,
|
| 143 | )
|
| 144 | @JvmName("getState-deprecated")
|
| 145 | inline fun BlockPos.getState() = state
|
| 146 |
|
| 147 | @AddonApi
|
| 148 | val BlockPos.stateOrEmpty: BlockState get() = state ?: Blocks.VOID_AIR.defaultBlockState()
|
| 149 |
|
| 150 | @AddonApi
|
| 151 | fun BlockPos.getBlock(): Block? = state?.block
|
| 152 |
|
| 153 | fun BlockPos.getCenterDistanceSquared() = this.distToCenterSqr(player.position())
|
| 154 |
|
| 155 | fun BlockPos.getCenterDistanceSquaredEyes() = this.distToCenterSqr(player.eyePosition)
|
| 156 |
|
| 157 | val BlockState.isBed: Boolean
|
| 158 | get() = block is BedBlock
|
| 159 |
|
| 160 | val TypedInstance<Block>.isAnyChest: Boolean
|
| 161 | get() = this.`is`(Blocks.CHEST)
|
| 162 | || this.`is`(Blocks.TRAPPED_CHEST)
|
| 163 | || this.`is`(Blocks.ENDER_CHEST)
|
| 164 | || this.`is`(BlockTags.COPPER_CHESTS)
|
| 165 |
|
| 166 | /**
|
| 167 | * Converts this [BlockPos] to an immutable one if needed.
|
| 168 | */
|
| 169 | val BlockPos.immutable: BlockPos get() = if (this is BlockPos.MutableBlockPos) this.immutable() else this
|
| 170 |
|
| 171 | /**
|
| 172 | * Returns the block box outline of the block at the position. If the block is air, it will return an empty box.
|
| 173 | * Outline Box should be used for rendering purposes only.
|
| 174 | *
|
| 175 | * Returns [FULL_BOX] when block is air or does not exist.
|
| 176 | */
|
| 177 | @AddonApi
|
| 178 | val BlockPos.outlineBox: AABB
|
| 179 | get() {
|
| 180 | val blockState = state ?: return FULL_BOX
|
| 181 | if (blockState.isAir) {
|
| 182 | return FULL_BOX
|
| 183 | }
|
| 184 |
|
| 185 | val outlineShape = blockState.getShape(world, this)
|
| 186 | return outlineShape.boundsOrNull() ?: FULL_BOX
|
| 187 | }
|
| 188 |
|
| 189 | val BlockPos.collisionShape: VoxelShape
|
| 190 | get() = state?.getCollisionShape(world, this) ?: Shapes.empty()
|
| 191 |
|
| 192 | val BlockPos.outlineShape: VoxelShape
|
| 193 | get() = state?.getShape(world, this) ?: Shapes.empty()
|
| 194 |
|
| 195 | fun BlockState.outlineBox(blockPos: BlockPos): AABB {
|
| 196 | val outlineShape = this.getShape(world, blockPos)
|
| 197 |
|
| 198 | return outlineShape.boundsOrNull() ?: FULL_BOX
|
| 199 | }
|
| 200 |
|
| 201 | fun Vec3.searchBlocksInCuboid(radius: Float): Iterable<BlockPos> =
|
| 202 | BlockPos.betweenClosed(
|
| 203 | floor(x - radius).toInt(),
|
| 204 | floor(y - radius).toInt(),
|
| 205 | floor(z - radius).toInt(),
|
| 206 | ceil(x + radius).toInt(),
|
| 207 | ceil(y + radius).toInt(),
|
| 208 | ceil(z + radius).toInt(),
|
| 209 | )
|
| 210 |
|
| 211 | /**
|
| 212 | * Scan blocks around the position in a cuboid with filtering.
|
| 213 | */
|
| 214 | fun Vec3.searchBlocksInCuboid(
|
| 215 | radius: Float,
|
| 216 | filter: BiPredicate<BlockPos, BlockState>,
|
| 217 | ): Sequence<Pair<BlockPos, BlockState>> =
|
| 218 | searchBlocksInCuboid(radius).asSequence().mapNotNull {
|
| 219 | val state = it.state ?: return@mapNotNull null
|
| 220 |
|
| 221 | if (filter.test(it, state)) {
|
| 222 | it.immutable() to state
|
| 223 | } else {
|
| 224 | null
|
| 225 | }
|
| 226 | }
|
| 227 |
|
| 228 | /**
|
| 229 | * Scan blocks around the position in a cuboid, filtered and sorted by shape distance from this [Vec3].
|
| 230 | * Distance calculation is based on outline shape:
|
| 231 | * `shapeGetter.get(state, level, pos, collisionContext).move(pos).distanceToSqr(eyesPos)`.
|
| 232 | *
|
| 233 | * @return pairs of [BlockPos] and its [BlockState], sorted by distance to the center
|
| 234 | */
|
| 235 | fun Vec3.searchBlocksInRangeSorted(
|
| 236 | range: Float,
|
| 237 | shapeGetter: ClipContext.ShapeGetter = ClipContext.Block.OUTLINE,
|
| 238 | collisionContext: CollisionContext = CollisionContext.of(player),
|
| 239 | filter: BiPredicate<BlockPos, BlockState>,
|
| 240 | ): List<Pair<BlockPos, BlockState>> =
|
| 241 | searchBlocksInCuboid(range + 1, filter)
|
| 242 | .weightedFilterSortedByAtMost(range.sq().toDouble()) { (pos, state) ->
|
| 243 | shapeGetter.get(state, world, pos, collisionContext)
|
| 244 | .move(pos)
|
| 245 | .distanceToSqr(this)
|
| 246 | }
|
| 247 |
|
| 248 | /**
|
| 249 | * Scan blocks outwards from a bed
|
| 250 | */
|
| 251 | fun BlockPos.searchBedLayer(state: BlockState, layers: Int): Sequence<IntLongPair> {
|
| 252 | check(state.isBed) { "This function is only available for Beds" }
|
| 253 |
|
| 254 | val anotherPartDirection = state.anotherBedPartDirection()!!
|
| 255 | val bedDirection = anotherPartDirection.opposite
|
| 256 |
|
| 257 | val left: Direction
|
| 258 | val right: Direction
|
| 259 | if (bedDirection.axis == Direction.Axis.X) {
|
| 260 | left = Direction.SOUTH
|
| 261 | right = Direction.NORTH
|
| 262 | } else {
|
| 263 | left = Direction.WEST
|
| 264 | right = Direction.EAST
|
| 265 | }
|
| 266 |
|
| 267 | return searchLayer(layers, bedDirection, Direction.UP, left, right) +
|
| 268 | relative(anotherPartDirection).searchLayer(layers, anotherPartDirection, Direction.UP, left, right)
|
| 269 | }
|
| 270 |
|
| 271 | /**
|
| 272 | * Scan blocks outwards from center along given [directions], up to [layers]
|
| 273 | *
|
| 274 | * @return The layer to the BlockPos (long value)
|
| 275 | */
|
| 276 | @Suppress("detekt:CognitiveComplexMethod")
|
| 277 | fun BlockPos.searchLayer(layers: Int, vararg directions: Direction): Sequence<IntLongPair> =
|
| 278 | sequence {
|
| 279 | val longValueOfThis = this@searchLayer.asLong()
|
| 280 | val initialCapacity = layers * layers * directions.size / 2
|
| 281 |
|
| 282 | val queue = ArrayDeque<IntLongPair>(initialCapacity).apply { add(IntLongPair.of(0, longValueOfThis)) }
|
| 283 | val visited = LongOpenHashSet(initialCapacity).apply { add(longValueOfThis) }
|
| 284 |
|
| 285 | while (queue.isNotEmpty()) {
|
| 286 | val next = queue.removeFirst()
|
| 287 | val layer = next.leftInt()
|
| 288 | val pos = next.rightLong()
|
| 289 |
|
| 290 | if (layer > 0) {
|
| 291 | yield(next)
|
| 292 | }
|
| 293 |
|
| 294 | if (layer >= layers) continue
|
| 295 |
|
| 296 | // Search next layer
|
| 297 | for (direction in directions) {
|
| 298 | val newLong = BlockPos.offset(pos, direction)
|
| 299 | if (visited.add(newLong)) {
|
| 300 | queue.add(IntLongPair.of(layer + 1, newLong))
|
| 301 | }
|
| 302 | }
|
| 303 | }
|
| 304 | }
|
| 305 |
|
| 306 | fun BlockPos.getSortedSphere(radius: Float): Array<BlockPos> {
|
| 307 | val longs = CachedBlockPosSpheres.rangeLong(0, ceil(radius).toInt())
|
| 308 | val mutable = BlockPos.MutableBlockPos()
|
| 309 | return Array(longs.size) {
|
| 310 | mutable.set(longs.getLong(it))
|
| 311 | this.offset(mutable)
|
| 312 | }
|
| 313 | }
|
| 314 |
|
| 315 | /**
|
| 316 | * Basically [BlockGetter.raycast] but this method allows us to exclude blocks using [exclude].
|
| 317 | */
|
| 318 | @Suppress("SpellCheckingInspection", "CognitiveComplexMethod")
|
| 319 | fun BlockGetter.raycast(
|
| 320 | context: ClipContext,
|
| 321 | exclude: Collection<BlockPos>?,
|
| 322 | include: BlockPos?,
|
| 323 | maxBlastResistance: Float?
|
| 324 | ): BlockHitResult {
|
| 325 | return BlockGetter.traverseBlocks(
|
| 326 | context.from, context.to, context,
|
| 327 | { raycastContext, pos ->
|
| 328 | val excluded = exclude?.let { pos in it } ?: false
|
| 329 |
|
| 330 | val blockState = if (excluded) {
|
| 331 | Blocks.VOID_AIR.defaultBlockState()
|
| 332 | } else if (include != null && pos == include) {
|
| 333 | Blocks.OBSIDIAN.defaultBlockState()
|
| 334 | } else {
|
| 335 | var state = getBlockState(pos)
|
| 336 | maxBlastResistance?.let {
|
| 337 | if (state.block.explosionResistance < it) {
|
| 338 | state = Blocks.VOID_AIR.defaultBlockState()
|
| 339 | }
|
| 340 | }
|
| 341 | state
|
| 342 | }
|
| 343 |
|
| 344 | val fluidState = if (excluded) {
|
| 345 | Fluids.EMPTY.defaultFluidState()
|
| 346 | } else {
|
| 347 | var state = getFluidState(pos)
|
| 348 | maxBlastResistance?.let {
|
| 349 | if (state.explosionResistance < it) {
|
| 350 | state = Fluids.EMPTY.defaultFluidState()
|
| 351 | }
|
| 352 | }
|
| 353 | state
|
| 354 | }
|
| 355 |
|
| 356 | val vec = raycastContext.from
|
| 357 | val vec2 = raycastContext.to
|
| 358 |
|
| 359 | val blockShape = raycastContext.getBlockShape(blockState, this, pos)
|
| 360 | val blockHitResult = clipWithInteractionOverride(vec, vec2, pos, blockShape, blockState)
|
| 361 |
|
| 362 | val fluidShape = raycastContext.getFluidShape(fluidState, this, pos)
|
| 363 | val fluidHitResult = fluidShape.clip(vec, vec2, pos)
|
| 364 |
|
| 365 | val blockHitDistance = blockHitResult?.let {
|
| 366 | raycastContext.from.distanceToSqr(blockHitResult.location)
|
| 367 | } ?: Double.MAX_VALUE
|
| 368 | val fluidHitDistance = fluidHitResult?.let {
|
| 369 | raycastContext.from.distanceToSqr(fluidHitResult.location)
|
| 370 | } ?: Double.MAX_VALUE
|
| 371 |
|
| 372 | if (blockHitDistance <= fluidHitDistance) blockHitResult else fluidHitResult
|
| 373 | },
|
| 374 | { raycastContext ->
|
| 375 | val vec = raycastContext.from.subtract(raycastContext.to)
|
| 376 | BlockHitResult.miss(
|
| 377 | raycastContext.to,
|
| 378 | Direction.getApproximateNearest(vec.x, vec.y, vec.z),
|
| 379 | BlockPos.containing(raycastContext.to)
|
| 380 | )
|
| 381 | })
|
| 382 | }
|
| 383 |
|
| 384 | fun BlockPos.canStandOn(): Boolean {
|
| 385 | return this.state?.isFaceSturdy(world, this, Direction.UP, SupportType.CENTER) ?: false
|
| 386 | }
|
| 387 |
|
| 388 | fun BlockState?.anotherChestPartDirection(): Direction? {
|
| 389 | if (this?.block !is ChestBlock) return null
|
| 390 |
|
| 391 | if (ChestBlock.getBlockType(this) === DoubleBlockCombiner.BlockType.SINGLE) {
|
| 392 | return null
|
| 393 | }
|
| 394 |
|
| 395 | return ChestBlock.getConnectedDirection(this)
|
| 396 | }
|
| 397 |
|
| 398 | fun BlockState?.anotherBedPartDirection(): Direction? {
|
| 399 | if (this?.block !is BedBlock) return null
|
| 400 |
|
| 401 | // [body|head] -> (facing)
|
| 402 | val bedFacing = this.getValue(BedBlock.FACING)
|
| 403 |
|
| 404 | return if (BedBlock.getBlockType(this) == DoubleBlockCombiner.BlockType.FIRST) {
|
| 405 | bedFacing.opposite
|
| 406 | } else {
|
| 407 | bedFacing
|
| 408 | }
|
| 409 | }
|
| 410 |
|
| 411 | /**
|
| 412 | * Check if box is reaching of specified blocks
|
| 413 | */
|
| 414 | inline fun AABB.isBlockAtPosition(
|
| 415 | isCorrectBlock: (Block?) -> Boolean,
|
| 416 | ): Boolean {
|
| 417 | val blockPos = BlockPos.MutableBlockPos(0, floor(minY).toInt(), 0)
|
| 418 |
|
| 419 | for (x in floor(minX).toInt()..ceil(maxX).toInt()) {
|
| 420 | for (z in floor(minZ).toInt()..ceil(maxZ).toInt()) {
|
| 421 | blockPos.x = x
|
| 422 | blockPos.z = z
|
| 423 |
|
| 424 | if (isCorrectBlock(blockPos.getBlock())) {
|
| 425 | return true
|
| 426 | }
|
| 427 | }
|
| 428 | }
|
| 429 |
|
| 430 | return false
|
| 431 | }
|
| 432 |
|
| 433 | /**
|
| 434 | * Check if box intersects with bounding box of specified blocks
|
| 435 | */
|
| 436 | inline fun AABB.collideBlockIntersects(
|
| 437 | checkCollisionShape: Boolean = true,
|
| 438 | isCorrectBlock: (Block) -> Boolean
|
| 439 | ): Boolean {
|
| 440 | for (blockPos in collidingRegion) {
|
| 441 | val blockState = blockPos.state
|
| 442 |
|
| 443 | if (blockState == null || !isCorrectBlock(blockState.block)) {
|
| 444 | continue
|
| 445 | }
|
| 446 |
|
| 447 | if (!checkCollisionShape) {
|
| 448 | return true
|
| 449 | }
|
| 450 |
|
| 451 | val shape = blockState.getCollisionShape(mc.level!!, blockPos)
|
| 452 |
|
| 453 | if (shape.isEmpty) {
|
| 454 | continue
|
| 455 | }
|
| 456 |
|
| 457 | if (intersects(shape.bounds())) {
|
| 458 | return true
|
| 459 | }
|
| 460 | }
|
| 461 |
|
| 462 | return false
|
| 463 | }
|
| 464 |
|
| 465 | val AABB.collidingRegion: BoundingBox
|
| 466 | get() = BoundingBox(
|
| 467 | floor(this.minX).toInt(), floor(this.minY).toInt(), floor(this.minZ).toInt(),
|
| 468 | ceil(this.maxX).toInt(), ceil(this.maxY).toInt(), ceil(this.maxZ).toInt(),
|
| 469 | )
|
| 470 |
|
| 471 | fun BlockState.canBeReplacedWith(
|
| 472 | pos: BlockPos,
|
| 473 | usedStack: ItemStack,
|
| 474 | ): Boolean {
|
| 475 | val placementContext =
|
| 476 | BlockPlaceContext(
|
| 477 | mc.player!!,
|
| 478 | InteractionHand.MAIN_HAND,
|
| 479 | usedStack,
|
| 480 | BlockHitResult(Vec3.atLowerCornerOf(pos), Direction.UP, pos, false),
|
| 481 | )
|
| 482 |
|
| 483 | return canBeReplaced(
|
| 484 | placementContext,
|
| 485 | )
|
| 486 | }
|
| 487 |
|
| 488 | val BlockHitResult.targetBlockPos: BlockPos get() = this.blockPos.relative(this.direction)
|
| 489 |
|
| 490 | /**
|
| 491 | * Simulated [net.minecraft.world.phys.HitResult.Type.BLOCK] branch in vanilla
|
| 492 | *
|
| 493 | * This function does not perform the surrounding checks from [net.minecraft.client.Minecraft.startUseItem],
|
| 494 | * such as whether the game mode is destroying a block, the player's hands are busy, or the held item is enabled.
|
| 495 | * Callers should perform the applicable checks before calling this function.
|
| 496 | *
|
| 497 | * @param rotation rotation used to produce [hitResult]
|
| 498 | * @see net.minecraft.client.Minecraft.startUseItem
|
| 499 | */
|
| 500 | @AddonApi
|
| 501 | @JvmOverloads
|
| 502 | fun doPlacement(
|
| 503 | hitResult: BlockHitResult,
|
| 504 | rotation: Rotation,
|
| 505 | hand: InteractionHand = InteractionHand.MAIN_HAND,
|
| 506 | onPlacementSuccess: () -> Boolean = { true },
|
| 507 | onItemUseSuccess: () -> Boolean = { true },
|
| 508 | swingMode: SwingMode = SwingMode.DO_NOT_HIDE
|
| 509 | ) {
|
| 510 | val stack = player.getItemInHand(hand)
|
| 511 | val count = stack.count
|
| 512 |
|
| 513 | val useItemOnResult = interaction.useItemOn(player, hand, hitResult)
|
| 514 |
|
| 515 | when {
|
| 516 | useItemOnResult is InteractionResult.Fail -> {
|
| 517 | return
|
| 518 | }
|
| 519 |
|
| 520 | useItemOnResult is InteractionResult.Pass -> {
|
| 521 | // Ok, we cannot place on the block, so let's just use the item in the direction
|
| 522 | // without targeting a block (for buckets, etc.)
|
| 523 | if (!stack.isEmpty) {
|
| 524 | val useItemResult = interaction.useItem(player, hand, rotation.yRot, rotation.xRot)
|
| 525 | if (useItemResult is Success) {
|
| 526 | if (useItemResult.swingSource == SwingSource.CLIENT && onItemUseSuccess()) {
|
| 527 | swingMode.swing(hand)
|
| 528 | }
|
| 529 |
|
| 530 | mc.gameRenderer.itemInHandRenderer.itemUsed(hand) // <- no condition on this
|
| 531 | }
|
| 532 | }
|
| 533 | }
|
| 534 |
|
| 535 | useItemOnResult.consumesAction() -> {
|
| 536 | val wasStackUsed = !stack.isEmpty && (stack.count != count || player.hasInfiniteMaterials())
|
| 537 |
|
| 538 | handleActionsOnAccept(hand, useItemOnResult, wasStackUsed, onPlacementSuccess, swingMode)
|
| 539 | }
|
| 540 | }
|
| 541 | }
|
| 542 |
|
| 543 | /**
|
| 544 | * Swings item, resets equip progress and hand swing progress
|
| 545 | *
|
| 546 | * @param wasStackUsed was an item consumed in order to place the block
|
| 547 | * @param shouldSwing if result of the lambda is true, swing hand with [swingMode]
|
| 548 | */
|
| 549 | private inline fun handleActionsOnAccept(
|
| 550 | hand: InteractionHand,
|
| 551 | interactionResult: InteractionResult,
|
| 552 | wasStackUsed: Boolean,
|
| 553 | shouldSwing: () -> Boolean,
|
| 554 | swingMode: SwingMode,
|
| 555 | ) {
|
| 556 | if (interactionResult is Success && interactionResult.swingSource != SwingSource.CLIENT) {
|
| 557 | return
|
| 558 | }
|
| 559 |
|
| 560 | if (shouldSwing()) {
|
| 561 | swingMode.swing(hand)
|
| 562 | }
|
| 563 |
|
| 564 | if (wasStackUsed) {
|
| 565 | mc.gameRenderer.itemInHandRenderer.itemUsed(hand)
|
| 566 | }
|
| 567 | }
|
| 568 |
|
| 569 | /**
|
| 570 | * Places the item in [hand] at [pos] against a neighbouring block, rotating silently towards it.
|
| 571 | *
|
| 572 | * @return false when there is nothing to place against or the spot is out of reach
|
| 573 | */
|
| 574 | @AddonApi
|
| 575 | @JvmOverloads
|
| 576 | fun doPlacement(
|
| 577 | pos: BlockPos,
|
| 578 | hand: InteractionHand = InteractionHand.MAIN_HAND,
|
| 579 | swingMode: SwingMode = SwingMode.DO_NOT_HIDE,
|
| 580 | ): Boolean {
|
| 581 | val options = BlockPlacementTargetFindingOptions(
|
| 582 | BlockOffsetOptions.Default,
|
| 583 | FaceHandlingOptions(CenterTargetPositionFactory),
|
| 584 | stackToPlaceWith = player.getItemInHand(hand),
|
| 585 | PlayerLocationOnPlacement(position = player.position()),
|
| 586 | )
|
| 587 | val target = findBestBlockPlacementTarget(pos, options) ?: return false
|
| 588 | val hit = traceFromPlayer(target.rotation)
|
| 589 | if (hit.type != HitResult.Type.BLOCK) {
|
| 590 | return false
|
| 591 | }
|
| 592 | doPlacement(hit, target.rotation, hand = hand, swingMode = swingMode)
|
| 593 | return true
|
| 594 | }
|
| 595 |
|
| 596 | /**
|
| 597 | * Starts breaking [pos], rotating silently towards it. [immediate] sends start and stop at once,
|
| 598 | * which only works in creative or on blocks that break instantly.
|
| 599 | *
|
| 600 | * @return false when [pos] is not in reach
|
| 601 | */
|
| 602 | @AddonApi
|
| 603 | @JvmOverloads
|
| 604 | fun doBreak(pos: BlockPos, immediate: Boolean = false, swingMode: SwingMode = SwingMode.DO_NOT_HIDE): Boolean {
|
| 605 | val hit = traceFromPlayer(Rotation.lookingAt(Vec3.atCenterOf(pos), player.eyePosition))
|
| 606 | if (hit.type != HitResult.Type.BLOCK || hit.blockPos != pos) {
|
| 607 | return false
|
| 608 | }
|
| 609 | doBreak(hit, immediate, swingMode)
|
| 610 | return true
|
| 611 | }
|
| 612 |
|
| 613 | /**
|
| 614 | * Breaks the block
|
| 615 | */
|
| 616 | @AddonApi
|
| 617 | @JvmOverloads
|
| 618 | fun doBreak(
|
| 619 | rayTraceResult: BlockHitResult,
|
| 620 | immediate: Boolean = false,
|
| 621 | swingMode: SwingMode = SwingMode.DO_NOT_HIDE
|
| 622 | ) {
|
| 623 | val direction = rayTraceResult.direction
|
| 624 | val blockPos = rayTraceResult.blockPos
|
| 625 |
|
| 626 | if (player.isCreative) {
|
| 627 | if (interaction.startDestroyBlock(blockPos, rayTraceResult.direction)) {
|
| 628 | swingMode.swing(InteractionHand.MAIN_HAND)
|
| 629 | return
|
| 630 | }
|
| 631 | }
|
| 632 |
|
| 633 | if (immediate) {
|
| 634 | EventManager.callEvent(BlockBreakingProgressEvent(blockPos))
|
| 635 |
|
| 636 | interaction.startPrediction(world) { sequence ->
|
| 637 | ServerboundPlayerActionPacket(
|
| 638 | ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, blockPos, direction, sequence
|
| 639 | )
|
| 640 | }
|
| 641 | swingMode.swing(InteractionHand.MAIN_HAND)
|
| 642 | interaction.startPrediction(world) { sequence ->
|
| 643 | ServerboundPlayerActionPacket(
|
| 644 | ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, blockPos, direction, sequence
|
| 645 | )
|
| 646 | }
|
| 647 | return
|
| 648 | }
|
| 649 |
|
| 650 | if (interaction.continueDestroyBlock(blockPos, direction)) {
|
| 651 | swingMode.swing(InteractionHand.MAIN_HAND)
|
| 652 | world.addBreakingBlockEffect(blockPos, direction)
|
| 653 | }
|
| 654 | }
|
| 655 |
|
| 656 | fun BlockState.isNotBreakable(pos: BlockPos) = !isBreakable(pos)
|
| 657 |
|
| 658 | fun BlockState.isBreakable(pos: BlockPos): Boolean {
|
| 659 | return !isAir && (player.isCreative || getDestroySpeed(world, pos) >= 0f)
|
| 660 | }
|
| 661 |
|
| 662 | fun BlockPos?.fallDamageMultiplier(entity: Entity): Float =
|
| 663 | this?.getBlock()?.fallDamageMultiplier(entity) ?: 1f
|
| 664 |
|
| 665 | fun Block?.fallDamageMultiplier(entity: Entity): Float =
|
| 666 | when (this) {
|
| 667 | Blocks.WATER, Blocks.COBWEB, Blocks.POWDER_SNOW -> 0f
|
| 668 | Blocks.HAY_BLOCK, Blocks.HONEY_BLOCK -> 0.2f
|
| 669 | Blocks.SLIME_BLOCK -> if (entity.isSuppressingBounce && isOlderThan1_21_2) 1f else 0f
|
| 670 | is BedBlock -> 0.5f
|
| 671 | else -> 1f
|
| 672 | }
|
| 673 |
|
| 674 | fun BlockPos.isBlastResistant(): Boolean {
|
| 675 | return getBlock()!!.explosionResistance >= 600f
|
| 676 | }
|
| 677 |
|
| 678 | @Suppress("UnusedReceiverParameter")
|
| 679 | fun RespawnAnchorBlock.isCharged(state: BlockState): Boolean {
|
| 680 | return state.getValue(RespawnAnchorBlock.CHARGE) > 0
|
| 681 | }
|
| 682 |
|
| 683 | /**
|
| 684 | * Returns the second bed block position that might not exist (normally beds are two blocks long tho).
|
| 685 | */
|
| 686 | @Suppress("UnusedReceiverParameter")
|
| 687 | fun BedBlock.getPotentialSecondBedBlock(state: BlockState, pos: BlockPos): BlockPos {
|
| 688 | return pos.relative((state.getValue(HorizontalDirectionalBlock.FACING)).opposite)
|
| 689 | }
|
| 690 |
|
| 691 | // TODO replace this by an approach that automatically collects the blocks, this would create better mod compatibility
|
| 692 | /**
|
| 693 | * Checks if the block can be interacted with, null will be returned as not interactable.
|
| 694 | * The [blockState] is optional but can make the result more accurate, if not provided
|
| 695 | * it will just assume the block is interactable.
|
| 696 | *
|
| 697 | * Note: The player is required to NOT be `null`.
|
| 698 | *
|
| 699 | * This data has been collected by looking at the implementations of [BlockBehaviour.useWithoutItem].
|
| 700 | */
|
| 701 | fun Block?.isInteractable(blockState: BlockState?): Boolean {
|
| 702 | if (this == null) {
|
| 703 | return false
|
| 704 | }
|
| 705 |
|
| 706 | return this is BedBlock || this is AbstractChestBlock<*> || this is AbstractFurnaceBlock || this is AnvilBlock
|
| 707 | || this is BarrelBlock || this is BeaconBlock || this is BellBlock || this is BrewingStandBlock
|
| 708 | || this is ButtonBlock || this is CakeBlock && player.foodData.needsFood() || this is CandleCakeBlock
|
| 709 | || this is CartographyTableBlock
|
| 710 | || this is CaveVinesPlantBlock && blockState?.getValue(CaveVines.BERRIES) ?: true
|
| 711 | || this is CaveVinesBlock && blockState?.getValue(CaveVines.BERRIES) ?: true
|
| 712 | || this is ComparatorBlock || this is ComposterBlock && (blockState?.getValue(ComposterBlock.LEVEL) ?: 8) == 8
|
| 713 | || this is CrafterBlock || this is CraftingTableBlock || this is DaylightDetectorBlock
|
| 714 | || this is DecoratedPotBlock || this is DispenserBlock || this is DoorBlock || this is DragonEggBlock
|
| 715 | || this is EnchantingTableBlock || this is FenceGateBlock || this is FlowerPotBlock
|
| 716 | || this is GrindstoneBlock || this is HopperBlock || this is GameMasterBlock && player.canUseGameMasterBlocks()
|
| 717 | || this is JukeboxBlock && blockState?.getValue(JukeboxBlock.HAS_RECORD) == true || this is LecternBlock
|
| 718 | || this is LeverBlock || this is LightBlock && player.canUseGameMasterBlocks() || this is NoteBlock
|
| 719 | || this is RedStoneWireBlock || this is RepeaterBlock || this is RespawnAnchorBlock // this only works
|
| 720 | // when we hold glow stone or are not in the nether and the anchor is charged, but it'd be too error-prone when
|
| 721 | // it would be checked as the player can quickly switch to glow stone
|
| 722 | || this is ShulkerBoxBlock || this is StonecutterBlock
|
| 723 | || this is SweetBerryBushBlock && (blockState?.getValue(SweetBerryBushBlock.AGE) ?: 2) > 1
|
| 724 | || this is TrapDoorBlock
|
| 725 | }
|
| 726 |
|
| 727 | @AddonApi
|
| 728 | val BlockState?.isInteractable: Boolean get() = this?.block?.isInteractable(this) ?: false
|
| 729 |
|
| 730 | fun BlockPos.hasAnySolidPlacementNeighbor(): Boolean {
|
| 731 | val cache = BlockPos.MutableBlockPos()
|
| 732 | return Direction.entries.any {
|
| 733 | !cache.setWithOffset(this, it).stateOrEmpty.canBeReplaced()
|
| 734 | }
|
| 735 | }
|
| 736 |
|
| 737 | private val PREDICATE_UNOBSTRUCTED: Predicate<Entity> =
|
| 738 | EntitySelector.NO_SPECTATORS.and { entity ->
|
| 739 | !entity.isRemoved && entity.blocksBuilding
|
| 740 | }
|
| 741 |
|
| 742 | /**
|
| 743 | * Checks whether the position is unobstructed for placing a block.
|
| 744 | *
|
| 745 | * @see net.minecraft.world.level.EntityGetter.isUnobstructed
|
| 746 | */
|
| 747 | fun BlockPos.isUnobstructed(
|
| 748 | except: Entity? = null,
|
| 749 | box: AABB = FULL_BOX,
|
| 750 | predicate: Predicate<Entity> = Predicates.alwaysTrue(),
|
| 751 | ): Boolean {
|
| 752 | val posBox = box + this
|
| 753 | return world.getEntities(except, posBox, PREDICATE_UNOBSTRUCTED.and(predicate))
|
| 754 | .isEmpty()
|
| 755 | }
|
| 756 |
|
| 757 | fun BlockPos.getBlockingEntities(
|
| 758 | except: Entity? = null,
|
| 759 | box: AABB = FULL_BOX,
|
| 760 | predicate: Predicate<Entity> = Predicates.alwaysTrue(),
|
| 761 | ): List<Entity> {
|
| 762 | val posBox = box + this
|
| 763 | return world.getEntities(except, posBox, PREDICATE_UNOBSTRUCTED.and(predicate))
|
| 764 | }
|
| 765 |
|
| 766 | /**
|
| 767 | * Checks whether the position is blocked for placing a block and returns a blocking end crystal if present.
|
| 768 | *
|
| 769 | * @param buildingOnly when `true` (default) only entities that block building (`Entity.blocksBuilding`)
|
| 770 | * count, matching vanilla block placement; when `false` every entity counts, matching vanilla
|
| 771 | * end crystal placement.
|
| 772 | * @return `[blocked, crystal?]`
|
| 773 | */
|
| 774 | fun BlockPos.isBlockedByEntitiesReturnCrystal(
|
| 775 | except: Entity? = null,
|
| 776 | box: AABB = FULL_BOX,
|
| 777 | excludeIds: IntCollection? = null,
|
| 778 | buildingOnly: Boolean = true
|
| 779 | ): BooleanObjectPair<EndCrystal?> {
|
| 780 | var blocked = false
|
| 781 |
|
| 782 | val posBox = box + this
|
| 783 |
|
| 784 | val baseFilter = if (buildingOnly) PREDICATE_UNOBSTRUCTED else EntitySelector.NO_SPECTATORS
|
| 785 | val selector = if (excludeIds.isNullOrEmpty()) baseFilter else baseFilter.and { it.id !in excludeIds }
|
| 786 |
|
| 787 | world.getEntities(except, posBox, selector).forEach {
|
| 788 | if (it is EndCrystal) {
|
| 789 | return BooleanObjectPair.of(true, it)
|
| 790 | }
|
| 791 |
|
| 792 | blocked = true
|
| 793 | }
|
| 794 |
|
| 795 | return BooleanObjectPair.of(blocked, null)
|
| 796 | }
|
| 797 |
|