| 1 | package net.minecraft.world.level.chunk;
|
| 2 |
|
| 3 | import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
|
| 4 | import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
|
| 5 | import net.minecraft.core.BlockPos;
|
| 6 | import net.minecraft.core.SectionPos;
|
| 7 | import net.minecraft.world.level.LevelAccessor;
|
| 8 | import net.minecraft.world.level.block.Blocks;
|
| 9 | import net.minecraft.world.level.block.state.BlockState;
|
| 10 | import org.jspecify.annotations.Nullable;
|
| 11 |
|
| 12 | public class BulkSectionAccess implements AutoCloseable {
|
| 13 | private final LevelAccessor level;
|
| 14 | private final Long2ObjectMap<LevelChunkSection> acquiredSections = new Long2ObjectOpenHashMap<>();
|
| 15 | private @Nullable LevelChunkSection lastSection;
|
| 16 | private long lastSectionKey;
|
| 17 |
|
| 18 | public BulkSectionAccess(final LevelAccessor level) {
|
| 19 | this.level = level;
|
| 20 | }
|
| 21 |
|
| 22 | public @Nullable LevelChunkSection getSection(final BlockPos pos) {
|
| 23 | int sectionIndex = this.level.getSectionIndex(pos.getY());
|
| 24 | if (sectionIndex >= 0 && sectionIndex < this.level.getSectionsCount()) {
|
| 25 | long sectionKey = SectionPos.asLong(pos);
|
| 26 | if (this.lastSection == null || this.lastSectionKey != sectionKey) {
|
| 27 | this.lastSection = this.acquiredSections.computeIfAbsent(sectionKey, key -> {
|
| 28 | ChunkAccess chunk = this.level.getChunk(SectionPos.blockToSectionCoord(pos.getX()), SectionPos.blockToSectionCoord(pos.getZ()));
|
| 29 | LevelChunkSection result = chunk.getSection(sectionIndex);
|
| 30 | result.acquire();
|
| 31 | return result;
|
| 32 | });
|
| 33 | this.lastSectionKey = sectionKey;
|
| 34 | }
|
| 35 |
|
| 36 | return this.lastSection;
|
| 37 | } else {
|
| 38 | return null;
|
| 39 | }
|
| 40 | }
|
| 41 |
|
| 42 | public BlockState getBlockState(final BlockPos pos) {
|
| 43 | LevelChunkSection section = this.getSection(pos);
|
| 44 | if (section == null) {
|
| 45 | return Blocks.AIR.defaultBlockState();
|
| 46 | }
|
| 47 |
|
| 48 | int sectionRelativeX = SectionPos.sectionRelative(pos.getX());
|
| 49 | int sectionRelativeY = SectionPos.sectionRelative(pos.getY());
|
| 50 | int sectionRelativeZ = SectionPos.sectionRelative(pos.getZ());
|
| 51 | return section.getBlockState(sectionRelativeX, sectionRelativeY, sectionRelativeZ);
|
| 52 | }
|
| 53 |
|
| 54 | @Override
|
| 55 | public void close() {
|
| 56 | for (LevelChunkSection section : this.acquiredSections.values()) {
|
| 57 | section.release();
|
| 58 | }
|
| 59 | }
|
| 60 | }
|
| 61 |
|