| 1 | package net.minecraft.world.level.block;
|
| 2 |
|
| 3 | import java.util.Optional;
|
| 4 | import java.util.OptionalInt;
|
| 5 | import net.minecraft.core.BlockPos;
|
| 6 | import net.minecraft.core.Direction;
|
| 7 | import net.minecraft.util.Mth;
|
| 8 | import net.minecraft.world.phys.BlockHitResult;
|
| 9 | import net.minecraft.world.phys.Vec2;
|
| 10 | import net.minecraft.world.phys.Vec3;
|
| 11 |
|
| 12 | public interface SelectableSlotContainer {
|
| 13 | int getRows();
|
| 14 |
|
| 15 | int getColumns();
|
| 16 |
|
| 17 | default OptionalInt getHitSlot(final BlockHitResult hitResult, final Direction blockFacing) {
|
| 18 | return getRelativeHitCoordinatesForBlockFace(hitResult, blockFacing).map(hitCoords -> {
|
| 19 | int row = getSection(1.0F - hitCoords.y, this.getRows());
|
| 20 | int column = getSection(hitCoords.x, this.getColumns());
|
| 21 | return OptionalInt.of(column + row * this.getColumns());
|
| 22 | }).orElseGet(OptionalInt::empty);
|
| 23 | }
|
| 24 |
|
| 25 | private static Optional<Vec2> getRelativeHitCoordinatesForBlockFace(final BlockHitResult hitResult, final Direction blockFacing) {
|
| 26 | Direction hitDirection = hitResult.getDirection();
|
| 27 | if (blockFacing != hitDirection) {
|
| 28 | return Optional.empty();
|
| 29 | }
|
| 30 |
|
| 31 | BlockPos hitBlockPos = hitResult.getBlockPos().relative(hitDirection);
|
| 32 | Vec3 relativeHit = hitResult.getLocation().subtract(hitBlockPos.getX(), hitBlockPos.getY(), hitBlockPos.getZ());
|
| 33 | double relativeX = relativeHit.x();
|
| 34 | double relativeY = relativeHit.y();
|
| 35 | double relativeZ = relativeHit.z();
|
| 36 |
|
| 37 | return switch (hitDirection) {
|
| 38 | case NORTH -> Optional.of(new Vec2((float)(1.0 - relativeX), (float)relativeY));
|
| 39 | case SOUTH -> Optional.of(new Vec2((float)relativeX, (float)relativeY));
|
| 40 | case WEST -> Optional.of(new Vec2((float)relativeZ, (float)relativeY));
|
| 41 | case EAST -> Optional.of(new Vec2((float)(1.0 - relativeZ), (float)relativeY));
|
| 42 | case DOWN, UP -> Optional.empty();
|
| 43 | };
|
| 44 | }
|
| 45 |
|
| 46 | private static int getSection(final float relativeCoordinate, final int maxSections) {
|
| 47 | float targetedPixel = relativeCoordinate * 16.0F;
|
| 48 | float sectionSize = 16.0F / maxSections;
|
| 49 | return Mth.clamp(Mth.floor(targetedPixel / sectionSize), 0, maxSections - 1);
|
| 50 | }
|
| 51 | }
|
| 52 |
|