1 package me.shedaniel.lightoverlay.common;
3 import com.google.common.base.Suppliers;
4 import com.google.common.collect.Maps;
5 import dev.architectury.injectables.annotations.ExpectPlatform;
6 import it.unimi.dsi.fastutil.longs.Long2ByteMap;
7 import it.unimi.dsi.fastutil.longs.Long2ByteOpenHashMap;
8 import net.minecraft.client.Minecraft;
9 import net.minecraft.client.multiplayer.ClientLevel;
10 import net.minecraft.client.player.LocalPlayer;
11 import net.minecraft.core.BlockPos;
12 import net.minecraft.core.Direction;
13 import net.minecraft.core.Holder;
14 import net.minecraft.tags.BlockTags;
15 import net.minecraft.util.Mth;
16 import net.minecraft.world.entity.Entity;
17 import net.minecraft.world.entity.EntityType;
18 import net.minecraft.world.level.BlockGetter;
19 import net.minecraft.world.level.Level;
20 import net.minecraft.world.level.LightLayer;
21 import net.minecraft.world.level.biome.Biome;
22 import net.minecraft.world.level.block.Block;
23 import net.minecraft.world.level.block.state.BlockState;
24 import net.minecraft.world.level.chunk.ChunkStatus;
25 import net.minecraft.world.level.chunk.LevelChunk;
26 import net.minecraft.world.level.lighting.LayerLightEventListener;
27 import net.minecraft.world.phys.shapes.CollisionContext;
28 import net.minecraft.world.phys.shapes.VoxelShape;
29 import org.apache.logging.log4j.LogManager;
30 import sun.misc.Unsafe;
32 import java.lang.reflect.Field;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.ThreadPoolExecutor;
36 import java.util.function.Supplier;
38 public class LightOverlayTicker {
39 private final Minecraft minecraft = Minecraft.getInstance();
40 private long ticks = 0;
41 private static int threadNumber = 0;
42 private static final ThreadPoolExecutor EXECUTOR = (ThreadPoolExecutor) Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), r -> {
43 Thread thread = new Thread(r, "light-overlay-" + threadNumber++);
44 thread.setDaemon(true);
47 public final Set<CubicChunkPos> POS = Collections.synchronizedSet(new HashSet<>());
48 public final Set<CubicChunkPos> CALCULATING_POS = Collections.synchronizedSet(new HashSet<>());
49 public final Map<CubicChunkPos, Long2ByteMap> CHUNK_MAP = Maps.newConcurrentMap();
50 private static final Supplier<EntityType<Entity>> TESTING_ENTITY_TYPE = Suppliers.memoize(() -> {
53 Field f = Unsafe.class.getDeclaredField("theUnsafe");
54 f.setAccessible(true);
55 Unsafe unsafe = (Unsafe) f.get(null);
57 // instantiate entity type
58 EntityType<Entity> type = (EntityType<Entity>) unsafe.allocateInstance(EntityType.class);
60 } catch (Exception e) {
61 throw new RuntimeException(e);
66 public static void populateEntityType(EntityType<Entity> type) {
67 throw new AssertionError();
70 public void queueChunk(CubicChunkPos pos) {
71 if (LightOverlay.enabled && LightOverlay.caching && !CALCULATING_POS.contains(pos)) {
76 public void tick(Minecraft minecraft) {
77 while (LightOverlay.enableOverlay.consumeClick())
78 LightOverlay.enabled = !LightOverlay.enabled;
82 if (minecraft.player == null || !LightOverlay.enabled) {
84 CALCULATING_POS.clear();
85 EXECUTOR.getQueue().clear();
88 LocalPlayer player = minecraft.player;
89 ClientLevel world = minecraft.level;
90 CollisionContext collisionContext = CollisionContext.of(player);
92 if (!LightOverlay.caching) {
93 CALCULATING_POS.clear();
96 BlockPos playerPos = player.blockPosition();
97 LayerLightEventListener block = world.getLightEngine().getLayerListener(LightLayer.BLOCK);
98 LayerLightEventListener sky = LightOverlay.showNumber ? null : world.getLightEngine().getLayerListener(LightLayer.SKY);
99 BlockPos.MutableBlockPos downPos = new BlockPos.MutableBlockPos();
100 Iterable<BlockPos> iterate = BlockPos.betweenClosed(playerPos.getX() - LightOverlay.reach, playerPos.getY() - LightOverlay.reach, playerPos.getZ() - LightOverlay.reach,
101 playerPos.getX() + LightOverlay.reach, playerPos.getY() + LightOverlay.reach, playerPos.getZ() + LightOverlay.reach);
102 Long2ByteMap chunkData = new Long2ByteOpenHashMap();
103 CHUNK_MAP.put(new CubicChunkPos(0, 0, 0), chunkData);
104 for (BlockPos blockPos : iterate) {
105 downPos.set(blockPos.getX(), blockPos.getY() - 1, blockPos.getZ());
106 if (LightOverlay.showNumber) {
107 int level = getCrossLevel(blockPos, downPos, world, block, collisionContext);
109 chunkData.put(blockPos.asLong(), (byte) level);
112 Holder<Biome> biome = !LightOverlay.mushroom ? world.getBiome(blockPos) : null;
113 byte type = getCrossType(blockPos, biome, downPos, world, block, sky, collisionContext);
114 if (type != LightOverlay.CROSS_NONE) {
115 chunkData.put(blockPos.asLong(), type);
120 var height = Mth.ceil(Minecraft.getInstance().level.getHeight() / 32.0);
121 var start = Math.floorDiv(Minecraft.getInstance().level.getMinBuildHeight(), 32);
122 int playerPosX = ((int) player.getX()) >> 4;
123 int playerPosY = ((int) player.getY()) >> 5;
124 int playerPosZ = ((int) player.getZ()) >> 4;
125 var chunkRange = LightOverlay.getChunkRange();
126 for (int chunkX = playerPosX - chunkRange; chunkX <= playerPosX + chunkRange; chunkX++) {
127 for (int chunkY = Math.max(playerPosY - Math.max(1, chunkRange >> 1), start); chunkY <= playerPosY + Math.max(1, chunkRange >> 1) && chunkY <= start + height; chunkY++) {
128 for (int chunkZ = playerPosZ - chunkRange; chunkZ <= playerPosZ + chunkRange; chunkZ++) {
129 if (Mth.abs(chunkX - playerPosX) > chunkRange || Mth.abs(chunkY - playerPosY) > chunkRange || Mth.abs(chunkZ - playerPosZ) > chunkRange)
131 CubicChunkPos chunkPos = new CubicChunkPos(chunkX, chunkY, chunkZ);
132 if (!CHUNK_MAP.containsKey(chunkPos))
133 queueChunk(chunkPos);
137 for (int p = 0; p < 3; p++) {
138 if (EXECUTOR.getQueue().size() >= Runtime.getRuntime().availableProcessors()) break;
139 double d1 = Double.MAX_VALUE, d2 = Double.MAX_VALUE, d3 = Double.MAX_VALUE;
140 CubicChunkPos c1 = null, c2 = null, c3 = null;
142 Iterator<CubicChunkPos> iterator = POS.iterator();
143 while (iterator.hasNext()) {
144 CubicChunkPos pos = iterator.next();
145 if (Mth.abs(pos.x - playerPosX) > chunkRange || Mth.abs(pos.y - playerPosY) > Math.max(1, chunkRange >> 1) || Mth.abs(pos.z - playerPosZ) > chunkRange || CALCULATING_POS.contains(pos)) {
148 if (LightOverlay.renderer.isFrustumVisible(pos.getMinBlockX(), pos.getMinBlockY(), pos.getMinBlockZ(), pos.getMaxBlockX(), pos.getMaxBlockY(), pos.getMaxBlockZ())) {
149 int dx = Math.abs(pos.x - playerPosX);
150 int dy = Math.abs(pos.y - playerPosY) << 1;
151 int dz = Math.abs(pos.z - playerPosZ);
152 double distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
160 } else if (distance < d2) {
165 } else if (distance < d3) {
173 CubicChunkPos finalC1 = c1;
174 CubicChunkPos finalC2 = c2;
175 CubicChunkPos finalC3 = c3;
176 if (finalC1 != null) {
177 CALCULATING_POS.add(finalC1);
179 if (finalC2 != null) {
180 CALCULATING_POS.add(finalC2);
182 if (finalC3 != null) {
183 CALCULATING_POS.add(finalC3);
187 EXECUTOR.submit(() -> {
188 int playerPosX1 = ((int) minecraft.player.getX()) >> 4;
189 int playerPosY1 = ((int) minecraft.player.getY()) >> 5;
190 int playerPosZ1 = ((int) minecraft.player.getZ()) >> 4;
191 if (finalC1 != null) processChunk(finalC1, playerPosX1, playerPosY1, playerPosZ1, collisionContext);
192 if (finalC2 != null) processChunk(finalC2, playerPosX1, playerPosY1, playerPosZ1, collisionContext);
193 if (finalC3 != null) processChunk(finalC3, playerPosX1, playerPosY1, playerPosZ1, collisionContext);
197 if (ticks % 50 == 0) {
198 CHUNK_MAP.entrySet().removeIf(entry -> Mth.abs(entry.getKey().x - playerPosX) > chunkRange * 2 || Mth.abs(entry.getKey().y - playerPosY) > chunkRange * 2 || Mth.abs(entry.getKey().z - playerPosZ) > chunkRange * 2);
202 } catch (Throwable throwable) {
203 LogManager.getLogger().throwing(throwable);
207 private void processChunk(CubicChunkPos pos, int playerPosX, int playerPosY, int playerPosZ, CollisionContext context) {
208 CALCULATING_POS.remove(pos);
209 int chunkRange = LightOverlay.getChunkRange();
210 if (Mth.abs(pos.x - playerPosX) > chunkRange || Mth.abs(pos.y - playerPosY) > Math.max(1, chunkRange >> 1) || Mth.abs(pos.z - playerPosZ) > chunkRange || POS.contains(pos)) {
214 calculateChunk(minecraft.level.getChunkSource().getChunk(pos.x, pos.z, ChunkStatus.FULL, false), minecraft.level, pos, context);
215 } catch (Throwable throwable) {
216 LogManager.getLogger().throwing(throwable);
220 private void calculateChunk(LevelChunk chunk, Level world, CubicChunkPos chunkPos, CollisionContext collisionContext) {
221 if (world != null && chunk != null) {
222 Long2ByteMap chunkData = new Long2ByteOpenHashMap();
223 LayerLightEventListener block = world.getLightEngine().getLayerListener(LightLayer.BLOCK);
224 LayerLightEventListener sky = LightOverlay.showNumber ? null : world.getLightEngine().getLayerListener(LightLayer.SKY);
225 for (BlockPos pos : BlockPos.betweenClosed(chunkPos.getMinBlockX(), chunkPos.getMinBlockY(), chunkPos.getMinBlockZ(), chunkPos.getMaxBlockX(), chunkPos.getMaxBlockY(), chunkPos.getMaxBlockZ())) {
226 BlockPos down = pos.below();
227 if (LightOverlay.showNumber) {
228 int level = getCrossLevel(pos, down, chunk, block, collisionContext);
230 chunkData.put(pos.asLong(), (byte) level);
233 Holder<Biome> biome = !LightOverlay.mushroom ? world.getBiome(pos) : null;
234 byte type = getCrossType(pos, biome, down, chunk, block, sky, collisionContext);
235 if (type != LightOverlay.CROSS_NONE) {
236 chunkData.put(pos.asLong(), type);
240 CHUNK_MAP.put(chunkPos, chunkData);
242 CHUNK_MAP.remove(chunkPos);
246 public byte getCrossType(BlockPos pos, Holder<Biome> biome, BlockPos down, BlockGetter world, LayerLightEventListener block, LayerLightEventListener sky, CollisionContext entityContext) {
247 BlockState blockBelowState = world.getBlockState(down);
248 BlockState blockUpperState = world.getBlockState(pos);
249 VoxelShape upperCollisionShape = blockUpperState.getCollisionShape(world, pos, entityContext);
250 if (!LightOverlay.underwater && !blockUpperState.getFluidState().isEmpty())
251 return LightOverlay.CROSS_NONE;
252 // Check if the outline is full
253 if (Block.isFaceFull(upperCollisionShape, Direction.UP))
254 return LightOverlay.CROSS_NONE;
255 // TODO: Not to hard code no redstone
256 if (blockUpperState.isSignalSource())
257 return LightOverlay.CROSS_NONE;
258 // Check if the collision has a bump
259 if (upperCollisionShape.max(Direction.Axis.Y) > 0)
260 return LightOverlay.CROSS_NONE;
261 if (blockUpperState.is(BlockTags.RAILS))
262 return LightOverlay.CROSS_NONE;
263 // Check block state allow spawning (excludes bedrock and barriers automatically)
264 if (!blockBelowState.isValidSpawn(world, down, TESTING_ENTITY_TYPE.get()))
265 return LightOverlay.CROSS_NONE;
266 if (!LightOverlay.mushroom && Biome.BiomeCategory.MUSHROOM == Biome.getBiomeCategory(biome))
267 return LightOverlay.CROSS_NONE;
268 int blockLightLevel = block.getLightValue(pos);
269 int skyLightLevel = sky.getLightValue(pos);
270 if (blockLightLevel > LightOverlay.higherCrossLevel)
271 return LightOverlay.CROSS_NONE;
272 if (skyLightLevel > LightOverlay.higherCrossLevel)
273 return LightOverlay.higherCross;
274 return LightOverlay.lowerCrossLevel >= 0 && blockLightLevel > LightOverlay.lowerCrossLevel ?
275 LightOverlay.lowerCross : LightOverlay.CROSS_RED;
278 public static int getCrossLevel(BlockPos pos, BlockPos down, BlockGetter world, LayerLightEventListener view, CollisionContext collisionContext) {
279 BlockState blockBelowState = world.getBlockState(down);
280 BlockState blockUpperState = world.getBlockState(pos);
281 VoxelShape collisionShape = blockBelowState.getCollisionShape(world, down, collisionContext);
282 VoxelShape upperCollisionShape = blockUpperState.getCollisionShape(world, pos, collisionContext);
283 if (!LightOverlay.underwater && !blockUpperState.getFluidState().isEmpty())
285 if (!blockBelowState.getFluidState().isEmpty())
287 if (blockBelowState.isAir())
289 if (Block.isFaceFull(upperCollisionShape, Direction.DOWN))
291 return view.getLightValue(pos);