BlockESP module

BlockESP: Minecraft 26.3 cheat module, full source for every implementation (4 clients: MelaHack (ThunderHack fork), OfflineClient, Combatant, …).

4 implementationsRENDERVISUALS

Full module source: 4 implementations

Every implementation below is the complete module file, verbatim. Expand a client to read its code.

MelaHack (ThunderHack fork)RENDERsrc/main/java/thunder/hack/features/modules/render/BlockESP.javaJava · 166 lines · 6.5 KB

Highlights selected blocks.

SettingsSelectedBlocksRangeLimitLimitCountColorIllegalsTracersFillOutline
BlockESP.javaJava · Minecraft 26.2 · 166 lines · 6.5 KB · complete file, verbatimOriginal ↗
1
package thunder.hack.features.modules.render;
2
3
import com.google.common.collect.Lists;
4
import com.mojang.blaze3d.vertex.PoseStack;
5
import net.minecraft.core.BlockPos;
6
import net.minecraft.util.Util;
7
import net.minecraft.world.level.block.*;
8
import net.minecraft.world.level.block.state.BlockState;
9
import net.minecraft.world.level.levelgen.Heightmap;
10
import net.minecraft.world.phys.AABB;
11
import net.minecraft.world.phys.Vec3;
12
import org.jetbrains.annotations.NotNull;
13
import thunder.hack.features.modules.Module;
14
import thunder.hack.setting.Setting;
15
import thunder.hack.setting.impl.BooleanSettingGroup;
16
import thunder.hack.setting.impl.ColorSetting;
17
import thunder.hack.setting.impl.ItemSelectSetting;
18
import thunder.hack.utility.Timer;
19
import thunder.hack.utility.player.PlayerUtility;
20
import thunder.hack.utility.render.Render3DEngine;
21
22
import java.util.ArrayList;
23
import java.util.concurrent.CompletableFuture;
24
import java.util.concurrent.ExecutorService;
25
import java.util.concurrent.Executors;
26
27
import static thunder.hack.features.modules.client.ClientSettings.isRu;
28
29
public class BlockESP extends Module {
30
    public BlockESP() {
31
        super("BlockESP", Category.RENDER);
32
    }
33
34
    public final Setting<ItemSelectSetting> selectedBlocks = new Setting<>("SelectedBlocks", new ItemSelectSetting(new ArrayList<>()));
35
    public static ArrayList<BlockVec> blocks = new ArrayList<>();
36
    private final Setting<Integer> range = new Setting<>("Range", 100, 1, 128);
37
    private final Setting<BooleanSettingGroup> limit = new Setting<>("Limit", new BooleanSettingGroup(true));
38
    private final Setting<Integer> limitCount = new Setting<>("LimitCount", 50, 1, 2048).addToGroup(limit);
39
    private final Setting<ColorSetting> color = new Setting<>("Color", new ColorSetting(0xFF00FFFF));
40
    private final Setting<Boolean> illegals = new Setting<>("Illegals", true);
41
    private final Setting<Boolean> tracers = new Setting<>("Tracers", false);
42
    private final Setting<Boolean> fill = new Setting<>("Fill", true);
43
    private final Setting<Boolean> outline = new Setting<>("Outline", true);
44
45
    private final ExecutorService searchThread = Executors.newSingleThreadExecutor();
46
    private final Timer searchTimer = new Timer();
47
    private long lastFrameTime;
48
    private boolean canContinue;
49
50
    @Override
51
    public void onEnable() {
52
        blocks.clear();
53
        lastFrameTime = System.currentTimeMillis();
54
        canContinue = true;
55
    }
56
57
    @Override
58
    public void onUpdate() {
59
        if (searchTimer.every(1000) && canContinue) {
60
            CompletableFuture.supplyAsync(this::scan, searchThread).thenAcceptAsync(this::sync, Util.backgroundExecutor());
61
            canContinue = false;
62
        }
63
    }
64
65
    private ArrayList<BlockVec> scan() {
66
        ArrayList<BlockVec> blocks = new ArrayList<>();
67
        int startX = (int) Math.floor(mc.player.getX() - range.getValue());
68
        int endX = (int) Math.ceil(mc.player.getX() + range.getValue());
69
        int startY = mc.level.getMinY() + 1;
70
        int endY = mc.level.getHeight(Heightmap.Types.WORLD_SURFACE, (int) mc.player.getX(), (int) mc.player.getZ());
71
        int startZ = (int) Math.floor(mc.player.getZ() - range.getValue());
72
        int endZ = (int) Math.ceil(mc.player.getZ() + range.getValue());
73
74
        for (int x = startX; x <= endX; x++) {
75
            for (int y = startY; y <= endY; y++) {
76
                for (int z = startZ; z <= endZ; z++) {
77
                    BlockPos pos = new BlockPos(x, y, z);
78
                    BlockState bs = mc.level.getBlockState(pos);
79
                    if (shouldAdd(bs.getBlock(), pos)) {
80
                        blocks.add(new BlockVec(pos.getX(), pos.getY(), pos.getZ()));
81
                    }
82
                }
83
            }
84
        }
85
        return blocks;
86
    }
87
88
    private void sync(ArrayList<BlockVec> b) {
89
        blocks = b;
90
        canContinue = true;
91
    }
92
93
    public void onRender3D(PoseStack stack) {
94
        if (fullNullCheck() || blocks.isEmpty()) return;
95
        int count = 0;
96
97
        if (mc.getFps() < 8 && mc.player.tickCount > 100) {
98
            disable(isRu() ? "Спасаем твой ПК :)" : "Saving ur pc :)");
99
            return;
100
        }
101
102
        if (fill.getValue() || outline.getValue()) {
103
            for (BlockVec vec : Lists.newArrayList(blocks)) {
104
                if (count > limitCount.getValue() && limit.getValue().isEnabled())
105
                    continue;
106
107
                if (vec.getDistance(mc.player.position()) > range.getPow2Value()) {
108
                    blocks.remove(vec);
109
                    continue;
110
                }
111
112
                AABB b = new AABB(vec.x, vec.y, vec.z, vec.x + 1, vec.y + 1, vec.z + 1);
113
114
                if (fill.getValue())
115
                    Render3DEngine.FILLED_QUEUE.add(new Render3DEngine.FillAction(b, color.getValue().getColorObject()));
116
117
                if (outline.getValue())
118
                    Render3DEngine.OUTLINE_QUEUE.add(new Render3DEngine.OutlineAction(b, color.getValue().getColorObject(), 2f));
119
120
                if (tracers.getValue()) {
121
                    Vec3 vec2 = new Vec3(0, 0, 75)
122
                            .xRot(-(float) Math.toRadians(mc.gameRenderer.mainCamera().xRot()))
123
                            .yRot(-(float) Math.toRadians(mc.gameRenderer.mainCamera().yRot()))
124
                            .add(mc.getCameraEntity().getEyePosition());
125
126
                    Render3DEngine.drawLineDebug(vec2, vec.getVector(), color.getValue().getColorObject());
127
                }
128
                count++;
129
            }
130
        }
131
        lastFrameTime = System.currentTimeMillis();
132
    }
133
134
    private boolean shouldAdd(Block block, BlockPos pos) {
135
        if (block instanceof AirBlock) return false;
136
        if (selectedBlocks.getValue().contains(block)) return true;
137
        if (illegals.getValue()) return isIllegal(block, pos);
138
        return false;
139
    }
140
141
    private boolean isIllegal(Block block, BlockPos pos) {
142
        if (block instanceof CommandBlock || block instanceof BarrierBlock) return true;
143
144
        if (block == Blocks.BEDROCK) {
145
            if (!PlayerUtility.isInHell())
146
                return pos.getY() > 4;
147
            else
148
                return pos.getY() > 127 || (pos.getY() < 123 && pos.getY() > 4);
149
        }
150
        return false;
151
    }
152
153
    public record BlockVec(double x, double y, double z) {
154
        public double getDistance(@NotNull Vec3 v) {
155
            double dx = x - v.x;
156
            double dy = y - v.y;
157
            double dz = z - v.z;
158
            return dx * dx + dy * dy + dz * dz;
159
        }
160
161
        public Vec3 getVector() {
162
            return new Vec3(x + 0.5f, y + 0.5f, z + 0.5f);
163
        }
164
    }
165
}
166
OfflineClientRENDERsrc/main/java/com/jellypudding/offlineclient/modules/render/BlockEsp.javaJava · 472 lines · 17.9 KB

Highlights chosen blocks through walls.

SettingsRangeLimitBlocksAutomatic coloursDefault tracerDefault tracer colourBlock looks
BlockEsp.javaJava · Minecraft 26.2 · 472 lines · 17.9 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.render;
2
3
import com.google.gson.JsonArray;
4
import com.google.gson.JsonElement;
5
import com.google.gson.JsonObject;
6
import com.jellypudding.offlineclient.event.Subscribe;
7
import com.jellypudding.offlineclient.event.events.PacketReceiveEvent;
8
import com.jellypudding.offlineclient.event.events.Render3DEvent;
9
import com.jellypudding.offlineclient.event.events.TickEvent;
10
import com.jellypudding.offlineclient.module.Category;
11
import com.jellypudding.offlineclient.module.Module;
12
import com.jellypudding.offlineclient.render.BoxStyle;
13
import com.jellypudding.offlineclient.render.DrawBatch;
14
import com.jellypudding.offlineclient.setting.BoolSetting;
15
import com.jellypudding.offlineclient.setting.ColorSetting;
16
import com.jellypudding.offlineclient.setting.NumberSetting;
17
import com.jellypudding.offlineclient.setting.RegistryListSetting;
18
import com.jellypudding.offlineclient.setting.Setting;
19
import com.jellypudding.offlineclient.util.ChunkScanner;
20
import com.jellypudding.offlineclient.util.ColorUtil;
21
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
22
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
23
import it.unimi.dsi.fastutil.longs.LongArrayList;
24
import net.minecraft.core.BlockPos;
25
import net.minecraft.core.Direction;
26
import net.minecraft.core.registries.BuiltInRegistries;
27
import net.minecraft.resources.Identifier;
28
import net.minecraft.world.level.ChunkPos;
29
import net.minecraft.world.level.block.Block;
30
import net.minecraft.world.level.block.Blocks;
31
import net.minecraft.world.phys.AABB;
32
import net.minecraft.world.phys.Vec3;
33
34
import java.util.ArrayList;
35
import java.util.HashSet;
36
import java.util.LinkedHashMap;
37
import java.util.List;
38
import java.util.Locale;
39
import java.util.Map;
40
import java.util.Set;
41
42
// Every loaded chunk in range is scanned once on a background thread.
43
// It is scanned again only when the server sends a change for it.
44
public final class BlockEsp extends Module {
45
46
    private static final Direction[] SIDES = Direction.values();
47
48
    // The block found and where it stands. Built on the scanner thread.
49
    private record Target(int x, int y, int z, Block block) {
50
    }
51
52
    // Hand tuned colours for the usual targets.
53
    private static final Map<Block, Integer> PRESET_COLORS = Map.ofEntries(
54
        Map.entry(Blocks.DIAMOND_ORE, 0xFF40E0FF),
55
        Map.entry(Blocks.DEEPSLATE_DIAMOND_ORE, 0xFF40E0FF),
56
        Map.entry(Blocks.ANCIENT_DEBRIS, 0xFFB08060),
57
        Map.entry(Blocks.EMERALD_ORE, 0xFF40FF80),
58
        Map.entry(Blocks.DEEPSLATE_EMERALD_ORE, 0xFF40FF80),
59
        Map.entry(Blocks.GOLD_ORE, 0xFFFFD040),
60
        Map.entry(Blocks.DEEPSLATE_GOLD_ORE, 0xFFFFD040),
61
        Map.entry(Blocks.NETHER_GOLD_ORE, 0xFFFFD040),
62
        Map.entry(Blocks.IRON_ORE, 0xFFD8C0A8),
63
        Map.entry(Blocks.DEEPSLATE_IRON_ORE, 0xFFD8C0A8),
64
        Map.entry(Blocks.REDSTONE_ORE, 0xFFFF4040),
65
        Map.entry(Blocks.DEEPSLATE_REDSTONE_ORE, 0xFFFF4040),
66
        Map.entry(Blocks.LAPIS_ORE, 0xFF4060FF),
67
        Map.entry(Blocks.DEEPSLATE_LAPIS_ORE, 0xFF4060FF),
68
        Map.entry(Blocks.COAL_ORE, 0xFF909090),
69
        Map.entry(Blocks.DEEPSLATE_COAL_ORE, 0xFF909090),
70
        Map.entry(Blocks.COPPER_ORE, 0xFFFF8050),
71
        Map.entry(Blocks.DEEPSLATE_COPPER_ORE, 0xFFFF8050),
72
        Map.entry(Blocks.NETHER_QUARTZ_ORE, 0xFFF0F0E0),
73
        Map.entry(Blocks.SPAWNER, 0xFFC050FF),
74
        Map.entry(Blocks.TRIAL_SPAWNER, 0xFFC050FF),
75
        Map.entry(Blocks.END_PORTAL_FRAME, 0xFF60FFC0),
76
        Map.entry(Blocks.BEACON, 0xFF80D0FF),
77
        Map.entry(Blocks.ENCHANTING_TABLE, 0xFFE070FF));
78
79
    private final NumberSetting range = new NumberSetting("Range",
80
        "Chunk radius to scan around you.", 4, 1, 8, 1, " chunks").max(16);
81
    private final NumberSetting limit = new NumberSetting("Limit",
82
        "Most blocks drawn at once with the nearest first.", 2000, 100, 5000, 100).min(1);
83
    private final RegistryListSetting<Block> blocks = new RegistryListSetting<>("Blocks",
84
        "The blocks to find.", BuiltInRegistries.BLOCK,
85
        List.of(Blocks.DIAMOND_ORE, Blocks.DEEPSLATE_DIAMOND_ORE, Blocks.ANCIENT_DEBRIS,
86
            Blocks.EMERALD_ORE, Blocks.DEEPSLATE_EMERALD_ORE,
87
            Blocks.SPAWNER, Blocks.TRIAL_SPAWNER, Blocks.END_PORTAL_FRAME,
88
            Blocks.BEACON, Blocks.ENCHANTING_TABLE));
89
    private final BoolSetting automatic = new BoolSetting("Automatic colours",
90
        "Blocks with no look of their own take a colour worked out from the block.", true);
91
    private final BoxStyle defaultStyle = new BoxStyle("Default", BoxStyle.Shape.LINES, 167);
92
    private final BoolSetting defaultTracer = new BoolSetting("Default tracer",
93
        "Draw a line to every group of blocks with no look of its own.", false);
94
    private final ColorSetting defaultTracerColor = new ColorSetting("Default tracer colour",
95
        "Colour of those lines.", 167, 1f, 1f, false)
96
        .under(defaultTracer, () -> defaultTracer.isOn() && !automatic.isOn());
97
98
    // The look of every block that has one. Kept after a block leaves the list.
99
    private final Map<Block, BlockLook> looks = new LinkedHashMap<>();
100
101
    // One saved entry. The rows are rebuilt from it after the config has loaded.
102
    private final Setting<Void> store = new Setting<Void>("Block looks",
103
        "Where the look of each block is kept.", null) {
104
105
        @Override
106
        public JsonElement toJson() {
107
            JsonObject out = new JsonObject();
108
            for (Map.Entry<Block, BlockLook> entry : looks.entrySet()) {
109
                if (entry.getValue().isOwn()) {
110
                    out.add(BuiltInRegistries.BLOCK.getKey(entry.getKey()).toString(),
111
                        entry.getValue().toJson());
112
                }
113
            }
114
            return out;
115
        }
116
117
        @Override
118
        public void fromJson(JsonElement json) {
119
            if (!json.isJsonObject()) {
120
                return;
121
            }
122
            for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
123
                Identifier id = Identifier.tryParse(entry.getKey());
124
                if (id != null && BuiltInRegistries.BLOCK.containsKey(id)) {
125
                    lookFor(BuiltInRegistries.BLOCK.getValue(id)).fromJson(entry.getValue());
126
                }
127
            }
128
        }
129
130
        @Override
131
        public void reset() {
132
            looks.clear();
133
        }
134
    }.visibleWhen(() -> false);
135
136
    // Read from the scanner thread and replaced whole.
137
    private volatile Set<Block> wanted = Set.of();
138
139
    private final ChunkScanner<Target> scanner = new ChunkScanner<>();
140
    // Set from the settings screen and read on the next tick.
141
    private volatile boolean listChanged = true;
142
    private List<Target> drawn = List.of();
143
144
    // The scan list and the chunk the last draw list was cut for.
145
    private List<Target> cutFrom;
146
    private long cutChunk;
147
148
    // Where every drawn block stands and which run of touching blocks it belongs to.
149
    private final Long2ObjectOpenHashMap<Block> blockAt = new Long2ObjectOpenHashMap<>();
150
    private final Long2IntOpenHashMap groupOf = new Long2IntOpenHashMap();
151
    private final List<Vec3> groupCenters = new ArrayList<>();
152
153
    public BlockEsp() {
154
        super("BlockESP", "Highlights chosen blocks through walls.", Category.RENDER);
155
        addSettings(range, limit, blocks, automatic);
156
        addSettings(defaultStyle.settings());
157
        addSettings(defaultTracer, defaultTracerColor, store);
158
        searchTags("search", "block search", "ore esp");
159
        blocks.onChange(() -> listChanged = true);
160
        groupOf.defaultReturnValue(-1);
161
    }
162
163
    // The per block rows are built as blocks are picked and follow the list.
164
    @Override
165
    public List<Setting<?>> getSettings() {
166
        for (Block block : blocks.resolved()) {
167
            lookFor(block);
168
        }
169
        List<Setting<?>> all = new ArrayList<>(super.getSettings());
170
        for (BlockLook look : looks.values()) {
171
            look.addTo(all);
172
        }
173
        return all;
174
    }
175
176
    @Override
177
    public String getSuffix() {
178
        return count(drawn.size());
179
    }
180
181
    @Override
182
    protected void onEnable() {
183
        listChanged = true;
184
        reset();
185
    }
186
187
    @Override
188
    protected void onDisable() {
189
        reset();
190
    }
191
192
    private void reset() {
193
        scanner.reset();
194
        drawn = List.of();
195
        cutFrom = null;
196
        blockAt.clear();
197
        groupOf.clear();
198
        groupCenters.clear();
199
    }
200
201
    private BlockLook lookFor(Block block) {
202
        return looks.computeIfAbsent(block, BlockLook::new);
203
    }
204
205
    // True if the wanted blocks changed.
206
    private boolean snapshot() {
207
        Set<Block> next = new HashSet<>(blocks.resolved());
208
        for (Block block : next) {
209
            lookFor(block);
210
        }
211
        boolean differs = !next.equals(wanted);
212
        if (differs) {
213
            wanted = Set.copyOf(next);
214
        }
215
        return differs;
216
    }
217
218
    // A hue derived from the id stays stable between sessions.
219
    private static int autoColor(Block block) {
220
        Integer preset = PRESET_COLORS.get(block);
221
        if (preset != null) {
222
            return preset;
223
        }
224
        int hue = Math.floorMod(BuiltInRegistries.BLOCK.getKey(block).toString().hashCode(), 360);
225
        return ColorUtil.hsv(hue, 0.65f, 1f);
226
    }
227
228
    @Subscribe
229
    private void onPacketReceive(PacketReceiveEvent event) {
230
        scanner.markChanged(event.getPacket());
231
    }
232
233
    @Subscribe
234
    private void onTick(TickEvent event) {
235
        if (!inGame()) {
236
            return;
237
        }
238
        if (listChanged) {
239
            listChanged = false;
240
            if (snapshot()) {
241
                reset();
242
            }
243
        }
244
245
        Set<Block> query = wanted;
246
        scanner.update(range.getInt(), (view, out) -> view.forEachMatching(
247
            state -> query.contains(state.getBlock()),
248
            (x, y, z, state) -> out.add(new Target(x, y, z, state.getBlock()))));
249
250
        rebuildDrawList();
251
    }
252
253
    // The nearest blocks win when there are more than the limit allows.
254
    private void rebuildDrawList() {
255
        List<Target> all = scanner.results();
256
        int max = limit.getInt();
257
        long chunk = ChunkPos.pack(mc.player.blockPosition());
258
        if (all == cutFrom && chunk == cutChunk && drawn.size() == Math.min(max, all.size())) {
259
            return;
260
        }
261
        cutFrom = all;
262
        cutChunk = chunk;
263
        if (all.size() > max) {
264
            Vec3 eye = mc.player.getEyePosition();
265
            all = new ArrayList<>(all);
266
            all.sort((a, b) -> Double.compare(distanceSqr(eye, a), distanceSqr(eye, b)));
267
            all = all.subList(0, max);
268
        }
269
        drawn = all;
270
        regroup(drawn);
271
    }
272
273
    private static double distanceSqr(Vec3 eye, Target target) {
274
        double dx = target.x() + 0.5 - eye.x;
275
        double dy = target.y() + 0.5 - eye.y;
276
        double dz = target.z() + 0.5 - eye.z;
277
        return dx * dx + dy * dy + dz * dz;
278
    }
279
280
    // Blocks of one kind that touch even at a corner count as one find.
281
    private void regroup(List<Target> targets) {
282
        blockAt.clear();
283
        groupOf.clear();
284
        groupCenters.clear();
285
        for (Target target : targets) {
286
            blockAt.put(key(target.x(), target.y(), target.z()), target.block());
287
        }
288
        LongArrayList pending = new LongArrayList();
289
        for (Target target : targets) {
290
            long start = key(target.x(), target.y(), target.z());
291
            if (groupOf.get(start) != -1) {
292
                continue;
293
            }
294
            int id = groupCenters.size();
295
            groupOf.put(start, id);
296
            pending.add(start);
297
            int minX = target.x();
298
            int minY = target.y();
299
            int minZ = target.z();
300
            int maxX = minX;
301
            int maxY = minY;
302
            int maxZ = minZ;
303
            while (!pending.isEmpty()) {
304
                long pos = pending.removeLong(pending.size() - 1);
305
                int x = BlockPos.getX(pos);
306
                int y = BlockPos.getY(pos);
307
                int z = BlockPos.getZ(pos);
308
                minX = Math.min(minX, x);
309
                minY = Math.min(minY, y);
310
                minZ = Math.min(minZ, z);
311
                maxX = Math.max(maxX, x);
312
                maxY = Math.max(maxY, y);
313
                maxZ = Math.max(maxZ, z);
314
                for (int dx = -1; dx <= 1; dx++) {
315
                    for (int dy = -1; dy <= 1; dy++) {
316
                        for (int dz = -1; dz <= 1; dz++) {
317
                            long next = key(x + dx, y + dy, z + dz);
318
                            if (next != pos && blockAt.get(next) == target.block()
319
                                && groupOf.get(next) == -1) {
320
                                groupOf.put(next, id);
321
                                pending.add(next);
322
                            }
323
                        }
324
                    }
325
                }
326
            }
327
            groupCenters.add(new Vec3((minX + maxX + 1) / 2.0,
328
                (minY + maxY + 1) / 2.0, (minZ + maxZ + 1) / 2.0));
329
        }
330
    }
331
332
    private static long key(int x, int y, int z) {
333
        return BlockPos.asLong(x, y, z);
334
    }
335
336
    @Subscribe
337
    private void onRender3D(Render3DEvent event) {
338
        DrawBatch batch = event.getBatch();
339
        boolean[] traced = new boolean[groupCenters.size()];
340
        for (Target target : drawn) {
341
            BlockLook look = looks.get(target.block());
342
            boolean own = look != null && look.isOwn();
343
            BoxStyle style = own ? look.style() : defaultStyle;
344
            AABB box = new AABB(target.x(), target.y(), target.z(),
345
                target.x() + 1, target.y() + 1, target.z() + 1);
346
            int hidden = sharedSides(target);
347
            if (own || !automatic.isOn()) {
348
                style.drawJoined(batch, box, hidden, true);
349
            } else {
350
                int color = autoColor(target.block());
351
                style.drawJoined(batch, box, hidden, color, color, true);
352
            }
353
354
            boolean wantsTracer = own ? look.tracesLines() : defaultTracer.isOn();
355
            int group = groupOf.get(key(target.x(), target.y(), target.z()));
356
            if (!wantsTracer || group < 0 || group >= traced.length || traced[group]) {
357
                continue;
358
            }
359
            traced[group] = true;
360
            batch.tracer(groupCenters.get(group), tracerColor(look, own, target.block()), true);
361
        }
362
    }
363
364
    private int tracerColor(BlockLook look, boolean own, Block block) {
365
        if (own) {
366
            return look.tracerColor();
367
        }
368
        return automatic.isOn() ? autoColor(block) : defaultTracerColor.getColor();
369
    }
370
371
    // A bit for every side another block of the same kind is pressed against.
372
    private int sharedSides(Target target) {
373
        long key = key(target.x(), target.y(), target.z());
374
        int hidden = 0;
375
        for (Direction side : SIDES) {
376
            if (blockAt.get(BlockPos.offset(key, side)) == target.block()) {
377
                hidden |= DrawBatch.sideBit(side);
378
            }
379
        }
380
        return hidden;
381
    }
382
383
    // The look of one block. Its own rows show whilst the toggle is ticked.
384
    private final class BlockLook {
385
386
        private final BoolSetting own;
387
        private final BoxStyle style;
388
        private final BoolSetting tracer;
389
        private final ColorSetting tracerColor;
390
391
        private BlockLook(Block block) {
392
            String label = sentence(BuiltInRegistries.BLOCK.getKey(block).getPath());
393
            own = new BoolSetting(label, "Give " + label.toLowerCase(Locale.ROOT)
394
                + " a look of its own instead of the default.", false)
395
                .visibleWhen(() -> blocks.contains(block));
396
            style = new BoxStyle(label, BoxStyle.Shape.LINES, 167).under(own);
397
            tracer = new BoolSetting(label + " tracer",
398
                "Draw a line to every group of these.", false).under(own);
399
            tracerColor = new ColorSetting(label + " tracer colour",
400
                "Colour of those lines.", 167, 1f, 1f, false)
401
                .under(tracer, () -> own.isOn() && tracer.isOn());
402
        }
403
404
        private boolean isOwn() {
405
            return own.isOn();
406
        }
407
408
        private BoxStyle style() {
409
            return style;
410
        }
411
412
        private boolean tracesLines() {
413
            return tracer.isOn();
414
        }
415
416
        private int tracerColor() {
417
            return tracerColor.getColor();
418
        }
419
420
        private void addTo(List<Setting<?>> out) {
421
            out.add(own);
422
            for (Setting<?> setting : style.settings()) {
423
                out.add(setting);
424
            }
425
            out.add(tracer);
426
            out.add(tracerColor);
427
        }
428
429
        private JsonElement toJson() {
430
            JsonObject out = new JsonObject();
431
            JsonArray rows = new JsonArray();
432
            for (Setting<?> setting : style.settings()) {
433
                rows.add(setting.toJson());
434
            }
435
            out.add("style", rows);
436
            out.add("tracer", tracer.toJson());
437
            out.add("tracerColour", tracerColor.toJson());
438
            return out;
439
        }
440
441
        private void fromJson(JsonElement json) {
442
            if (!json.isJsonObject()) {
443
                return;
444
            }
445
            JsonObject o = json.getAsJsonObject();
446
            own.setValue(true);
447
            if (o.has("style") && o.get("style").isJsonArray()) {
448
                JsonArray rows = o.getAsJsonArray("style");
449
                Setting<?>[] settings = style.settings();
450
                for (int i = 0; i < settings.length && i < rows.size(); i++) {
451
                    settings[i].fromJson(rows.get(i));
452
                }
453
            }
454
            if (o.has("tracer")) {
455
                tracer.fromJson(o.get("tracer"));
456
            }
457
            if (o.has("tracerColour")) {
458
                tracerColor.fromJson(o.get("tracerColour"));
459
            }
460
        }
461
    }
462
463
    // A block id such as deepslate_diamond_ore reads as a sentence case name.
464
    private static String sentence(String id) {
465
        if (id.isEmpty()) {
466
            return id;
467
        }
468
        String words = id.replace('_', ' ');
469
        return Character.toUpperCase(words.charAt(0)) + words.substring(1);
470
    }
471
}
472
CombatantVISUALSsrc/main/java/combatant/client/features/module/modules/visuals/BlockESP.javaJava · 888 lines · 30.8 KB
SettingsblockEspModeblockEspDeobfuscationblockEspLimitDistanceblockEspMaxDistanceblockEspMaxTargetsblockEspDeobfuscationRadiusblockEspDeobfuscationUpblockEspDeobfuscationDownblockEspDeobfuscationFastblockEspSearchBlocksblockEspUseTracersblockEspOutlineShapeblockEspLineWidthblockEspVisibleColorblockEspChunkColorblockEspClusterTracers
BlockESP.javaJava · Minecraft 26.2 · 888 lines · 30.8 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Combatant Client distribution.
3
 * Copyright (c) 2026 pivosos2007.
4
 *
5
 * Licensed under the GNU General Public License v3.0.
6
 */
7
8
package combatant.client.features.module.modules.visuals;
9
10
import com.mojang.blaze3d.vertex.PoseStack;
11
import combatant.client.config.values.*;
12
import combatant.client.features.module.*;
13
import combatant.client.features.module.Module;
14
import combatant.client.util.block.*;
15
import net.minecraft.client.Minecraft;
16
import net.minecraft.client.multiplayer.ClientLevel;
17
import net.minecraft.client.renderer.SubmitNodeCollector;
18
import net.minecraft.core.BlockPos;
19
import net.minecraft.core.SectionPos;
20
import net.minecraft.core.registries.BuiltInRegistries;
21
import net.minecraft.world.level.block.state.BlockState;
22
import net.minecraft.world.phys.AABB;
23
import net.minecraft.world.phys.Vec3;
24
import combatant.client.config.common.CommonSettingSchemas;
25
import combatant.client.config.values.*;
26
import combatant.client.features.gui.clickgui.settings.TextListSetting;
27
import combatant.client.features.module.*;
28
import combatant.client.render.engine.RenderState;
29
import combatant.client.render.engine.renderer.Renderer3D;
30
import combatant.client.util.block.*;
31
import combatant.client.util.logging.DebugLog;
32
33
import java.util.*;
34
import java.util.concurrent.ConcurrentHashMap;
35
36
//todo Description
37
@ModuleInfo(
38
        id = "blockesp",
39
        displayName = "BlockESP",
40
        aliases = {"xray", "oreesp", "blocks"},
41
        category = ModuleCategory.VISUALS
42
)
43
public class BlockESP extends Module {
44
45
    private static final int SECTION_SCAN_BUDGET_PER_TICK = 10;
46
    private static final int SECTION_SCAN_BURST_BUDGET_PER_TICK = 64;
47
    private static final int SECTION_SCAN_BURST_TICKS = 4;
48
    private static final int SECTION_SCAN_REFRESH_TICKS = 40;
49
    private static final int SODIUM_CANDIDATE_DRAIN_BUDGET_PER_TICK = 4096;
50
    private static final int RECONCILE_BUDGET_PER_TICK = 512;
51
    private static final int FULL_RECONCILE_REFRESH_TICKS = 20;
52
    private final Minecraft mc = Minecraft.getInstance();
53
    private final BlockDeobfuscationScanner deobfuscationScanner = new BlockDeobfuscationScanner();
54
    private final WorldSectionBlockScanner sectionScanner = new WorldSectionBlockScanner();
55
56
    private final EnumValue<BlockScanMode> modeValue =
57
            enumCommon(
58
                    "blockEspMode",
59
                    "mode",
60
                    CommonSettingSchemas.ESP_SCAN_MODE,
61
                    BlockScanMode.LOS,
62
                    BlockScanMode.values()
63
            );
64
65
    private final BooleanValue deobfuscationValue =
66
            bool(
67
                    "blockEspDeobfuscation",
68
                    "deobfuscation",
69
                    false
70
            );
71
72
    private final BooleanValue limitDistanceValue =
73
            boolCommon(
74
                    "blockEspLimitDistance",
75
                    "limit_distance",
76
                    CommonSettingSchemas.ESP_LIMIT_DISTANCE,
77
                    true
78
            );
79
80
    private final NumberValue<Integer> maxDistanceValue =
81
            visibleWhen(numCommon(
82
                    "blockEspMaxDistance",
83
                    "max_distance",
84
                    CommonSettingSchemas.ESP_MAX_DISTANCE,
85
                    64,
86
                    1,
87
                    256
88
            ), limitDistanceValue::get);
89
90
    private final NumberValue<Integer> maxTargetsValue =
91
            numCommon(
92
                    "blockEspMaxTargets",
93
                    "max_targets",
94
                    CommonSettingSchemas.ESP_MAX_TARGETS,
95
                    128,
96
                    1,
97
                    4096
98
            );
99
100
    private final NumberValue<Integer> deobfuscationRadiusValue =
101
            visibleWhen(num(
102
                    "blockEspDeobfuscationRadius",
103
                    "deobfuscation_radius",
104
                    5,
105
                    1,
106
                    64
107
            ), deobfuscationValue::get);
108
109
    private final NumberValue<Integer> deobfuscationUpValue =
110
            visibleWhen(num(
111
                    "blockEspDeobfuscationUp",
112
                    "deobfuscation_up",
113
                    5,
114
                    1,
115
                    32
116
            ), deobfuscationValue::get);
117
118
    private final NumberValue<Integer> deobfuscationDownValue =
119
            visibleWhen(num(
120
                    "blockEspDeobfuscationDown",
121
                    "deobfuscation_down",
122
                    5,
123
                    1,
124
                    32
125
            ), deobfuscationValue::get);
126
127
    private final BooleanValue deobfuscationFastValue =
128
            visibleWhen(bool(
129
                    "blockEspDeobfuscationFast",
130
                    "deobfuscation_fast",
131
                    false
132
            ), deobfuscationValue::get);
133
134
    private final ItemIdSetValue searchBlocksValue =
135
            itemList(
136
                    "blockEspSearchBlocks",
137
                    "search_blocks",
138
                    TextListSetting.PickerMode.BLOCKS
139
            );
140
141
    private final BlockScanContext scanContext = new BlockScanContext(mc, searchBlocksValue);
142
143
    private final BooleanValue useTracersValue =
144
            boolCommon(
145
                    "blockEspUseTracers",
146
                    "use_tracers",
147
                    CommonSettingSchemas.ESP_USE_TRACERS,
148
                    false
149
            );
150
151
    private final EnumValue<BlockOutlineShapeMode> outlineShapeMode =
152
            enumCommon(
153
                    "blockEspOutlineShape",
154
                    "outline_shape",
155
                    CommonSettingSchemas.ESP_OUTLINE_SHAPE,
156
                    BlockOutlineShapeMode.FULL_BLOCK,
157
                    BlockOutlineShapeMode.values()
158
            );
159
160
    private final NumberValue<Float> lineWidth =
161
            numCommon(
162
                    "blockEspLineWidth",
163
                    "line_width",
164
                    CommonSettingSchemas.ESP_LINE_WIDTH,
165
                    1.5f,
166
                    0.5f,
167
                    4.0f
168
            );
169
170
    private final RGBColorValue visibleColor =
171
            colorNoAlpha(
172
                    "blockEspVisibleColor",
173
                    "visible_color",
174
                    "#FF0000"
175
            );
176
177
    private final RGBColorValue chunkColor =
178
            colorNoAlpha(
179
                    "blockEspChunkColor",
180
                    "chunk_color",
181
                    "#FFFF00"
182
            );
183
184
    private final BooleanValue clusterTracersValue =
185
            visibleWhen(bool(
186
                    "blockEspClusterTracers",
187
                    "cluster_tracers",
188
                    false
189
            ), useTracersValue::get);
190
    private final Map<BlockPos, ObservedTarget> observedTargetStates = new ConcurrentHashMap<>();
191
    private final Set<Long> loggedTargets = ConcurrentHashMap.newKeySet();
192
    private final ArrayDeque<BlockPos> reconcileQueue = new ArrayDeque<>();
193
    private final Set<Long> queuedReconcileTargets = ConcurrentHashMap.newKeySet();
194
    private volatile Map<BlockPos, Target> renderTargets = new ConcurrentHashMap<>();
195
    private ClientLevel lastWorld;
196
    private BlockScanMode lastMode;
197
    private int lastSearchBlocksHash;
198
    private int lastScanSignature = Integer.MIN_VALUE;
199
    private int sectionScanRefreshTicks;
200
    private int sectionScanBurstTicks;
201
    private int fastSnapshotGeneration;
202
    private int fullReconcileRefreshTicks;
203
204
    @Override
205
    public void onEnable() {
206
        resetRuntimeState();
207
        scanContext.refresh();
208
        lastSearchBlocksHash = currentSearchBlocksHash();
209
        publishFastScanSnapshot();
210
        BlockObservationHub.requestSodiumRebuild(mc, scanBlockRadius());
211
        requestLocalSectionScan(true);
212
    }
213
214
    @Override
215
    public void onDisable() {
216
        BlockEspSodiumCandidateCollector.disable();
217
        resetRuntimeState();
218
    }
219
220
    @Override
221
    public void onTick() {
222
        if (!isEnabled() || mc.level == null) {
223
            BlockEspSodiumCandidateCollector.disable();
224
            return;
225
        }
226
227
        if (lastWorld != mc.level) {
228
            if (lastWorld != null) {
229
                resetRuntimeState();
230
                RenderSectionBlockScanner.clear();
231
            }
232
            lastWorld = mc.level;
233
        }
234
235
        scanContext.refresh();
236
        if (mc.player == null) {
237
            BlockEspSodiumCandidateCollector.disable();
238
            return;
239
        }
240
        publishFastScanSnapshot();
241
242
        int searchBlocksHash = currentSearchBlocksHash();
243
        if (lastSearchBlocksHash != searchBlocksHash) {
244
            clearObservedTargets();
245
            deobfuscationScanner.reset();
246
            sectionScanner.reset();
247
            lastSearchBlocksHash = searchBlocksHash;
248
            fastSnapshotGeneration++;
249
            publishFastScanSnapshot();
250
            BlockObservationHub.requestSodiumRebuild(mc, scanBlockRadius());
251
            requestLocalSectionScan(true);
252
        }
253
254
        BlockScanMode mode = modeValue.get();
255
        if (lastMode != mode) {
256
            renderTargets = new ConcurrentHashMap<>();
257
            loggedTargets.clear();
258
            reconcileQueue.clear();
259
            queuedReconcileTargets.clear();
260
            lastMode = mode;
261
            requestLocalSectionScan(true);
262
        }
263
264
        drainSodiumCandidateQueue();
265
        maintainSectionScanQueue();
266
        drainSectionScanQueue();
267
268
        if (deobfuscationValue.get()) {
269
            deobfuscationScanner.tick(
270
                    mc,
271
                    1,
272
                    deobfuscationRadiusValue.get(),
273
                    deobfuscationUpValue.get(),
274
                    deobfuscationDownValue.get(),
275
                    deobfuscationFastValue.get()
276
            );
277
            mergeDeobfuscatedTargets();
278
        }
279
280
        maintainReconcileQueue();
281
        drainReconcileQueue("cached", RECONCILE_BUDGET_PER_TICK);
282
    }
283
284
    public void acceptSodiumBlockState(int x, int y, int z, BlockState state) {
285
        if (!isEnabled() || !scanContext.isConfiguredTarget(state)) {
286
            return;
287
        }
288
        acceptObservedCandidate(BlockPos.asLong(x, y, z), state, "sodium-direct", RenderStatus.HIDDEN);
289
    }
290
291
    public void acceptWorldBlockUpdate(BlockPos pos, BlockState state) {
292
        if (!isEnabled()) {
293
            return;
294
        }
295
        acceptBlockUpdate(pos, state);
296
    }
297
298
    private void acceptBlockUpdate(BlockPos pos, BlockState state) {
299
        if (pos == null || state == null) {
300
            return;
301
        }
302
303
        sectionScanner.forget(pos);
304
        scanContext.refresh();
305
        boolean target = scanContext.isConfiguredTarget(state);
306
        boolean deobfuscatedPositive = deobfuscationScanner.hasPositiveState(pos);
307
        deobfuscationScanner.acceptBlockUpdate(pos, state, scanContext::isConfiguredTarget);
308
309
        if (!target && deobfuscatedPositive) {
310
            BlockState positiveState = deobfuscationScanner.getPositiveState(pos);
311
            if (scanContext.isConfiguredTarget(positiveState)) {
312
                recordTargetCandidate(pos, positiveState);
313
                updateObservedTarget(pos, positiveState, "deobfuscation-update");
314
            }
315
            return;
316
        }
317
318
        if (!target) {
319
            removeTargetCandidate(pos);
320
            return;
321
        }
322
323
        recordTargetCandidate(pos, state);
324
        updateObservedTarget(pos, state, "world-update");
325
        if (deobfuscationValue.get()) {
326
            DebugLog.info("[BlockESP] deobfuscated %s at %s", BuiltInRegistries.BLOCK.getKey(state.getBlock()), pos.toShortString());
327
        }
328
    }
329
330
    private void resetRuntimeState() {
331
        clearObservedTargets();
332
        lastMode = null;
333
        lastWorld = mc.level;
334
        lastSearchBlocksHash = currentSearchBlocksHash();
335
        lastScanSignature = Integer.MIN_VALUE;
336
        sectionScanRefreshTicks = 0;
337
        sectionScanBurstTicks = 0;
338
        fullReconcileRefreshTicks = 0;
339
        fastSnapshotGeneration++;
340
        BlockEspSodiumCandidateCollector.clear();
341
        deobfuscationScanner.reset();
342
        sectionScanner.reset();
343
    }
344
345
    private void clearObservedTargets() {
346
        renderTargets = new ConcurrentHashMap<>();
347
        observedTargetStates.clear();
348
        loggedTargets.clear();
349
        reconcileQueue.clear();
350
        queuedReconcileTargets.clear();
351
        BlockEspSodiumCandidateCollector.clear();
352
    }
353
354
    private void recordTargetCandidate(BlockPos rawPos, BlockState state) {
355
        recordTargetCandidate(rawPos, state, RenderStatus.PRESERVE);
356
    }
357
358
    private void recordTargetCandidate(BlockPos rawPos, BlockState state, RenderStatus renderStatus) {
359
        if (rawPos == null || state == null) {
360
            return;
361
        }
362
363
        BlockPos pos = rawPos.immutable();
364
        RenderSectionBlockScanner.recordBlock(pos, state);
365
        observedTargetStates.compute(pos, (ignored, previous) -> {
366
            boolean rendered = switch (renderStatus) {
367
                case PRESERVE -> previous != null && previous.rendered();
368
                case HIDDEN -> false;
369
                case VISIBLE -> true;
370
            };
371
            return new ObservedTarget(state, rendered);
372
        });
373
        enqueueReconcile(pos);
374
    }
375
376
    private void removeTargetCandidate(BlockPos pos) {
377
        if (pos == null) {
378
            return;
379
        }
380
381
        observedTargetStates.remove(pos);
382
        renderTargets.remove(pos);
383
        loggedTargets.remove(pos.asLong());
384
        queuedReconcileTargets.remove(pos.asLong());
385
        sectionScanner.forget(pos);
386
        if (mc.level != null) {
387
            RenderSectionBlockScanner.recordBlock(pos, mc.level.getBlockState(pos));
388
        }
389
    }
390
391
    private void updateObservedTarget(BlockPos pos, BlockState state, String source) {
392
        if (mc.level == null || mc.player == null || !withinDistance(pos)) {
393
            renderTargets.remove(pos);
394
            return;
395
        }
396
397
        ObservedTarget observed = observedTargetStates.get(pos);
398
        boolean visible = observed != null && observed.rendered();
399
        if (!acceptsMode(pos, visible)) {
400
            renderTargets.remove(pos);
401
            return;
402
        }
403
        if (!renderTargets.containsKey(pos) && renderTargets.size() >= maxTargetsValue.get()) {
404
            return;
405
        }
406
407
        Target target = new Target();
408
        target.pos = pos;
409
        target.state = state;
410
        target.box = new AABB(pos);
411
        target.visible = visible;
412
        renderTargets.put(pos, target);
413
414
        if (loggedTargets.add(pos.asLong())) {
415
            DebugLog.info(
416
                    "[BlockESP] detected %s at %s visible=%s source=%s mode=%s",
417
                    BuiltInRegistries.BLOCK.getKey(state.getBlock()),
418
                    pos.toShortString(),
419
                    visible,
420
                    source,
421
                    modeValue.get().getId()
422
            );
423
        }
424
    }
425
426
    private void drainSodiumCandidateQueue() {
427
        BlockEspSodiumCandidateCollector.drain(
428
                SODIUM_CANDIDATE_DRAIN_BUDGET_PER_TICK,
429
                candidate -> {
430
                    if (candidate.generation() == fastSnapshotGeneration) {
431
                        RenderStatus renderStatus = candidate.source() == BlockEspSodiumCandidateCollector.CandidateSource.SODIUM_BUFFERED_QUAD
432
                                ? RenderStatus.VISIBLE
433
                                : RenderStatus.HIDDEN;
434
                        acceptObservedCandidate(
435
                                candidate.packedPos(),
436
                                candidate.state(),
437
                                candidate.source().name().toLowerCase(),
438
                                renderStatus
439
                        );
440
                    }
441
                }
442
        );
443
    }
444
445
    private void acceptObservedCandidate(long packedPos, BlockState hintedState, String source) {
446
        acceptObservedCandidate(packedPos, hintedState, source, RenderStatus.PRESERVE);
447
    }
448
449
    private void acceptObservedCandidate(long packedPos, BlockState hintedState, String source, RenderStatus renderStatus) {
450
        if (mc.level == null || mc.player == null) {
451
            return;
452
        }
453
454
        BlockPos pos = BlockPos.of(packedPos);
455
        if (!withinDistance(pos)) {
456
            removeTargetCandidate(pos);
457
            return;
458
        }
459
460
        BlockState currentState = mc.level.getBlockState(pos);
461
        BlockState state = scanContext.isConfiguredTarget(currentState) ? currentState : hintedState;
462
        if (!scanContext.isConfiguredTarget(state)) {
463
            removeTargetCandidate(pos);
464
            return;
465
        }
466
467
        recordTargetCandidate(pos, state, renderStatus);
468
        updateObservedTarget(pos, state, source);
469
    }
470
471
    private void enqueueReconcile(BlockPos pos) {
472
        if (pos == null) {
473
            return;
474
        }
475
476
        long key = pos.asLong();
477
        if (queuedReconcileTargets.add(key)) {
478
            reconcileQueue.addLast(pos.immutable());
479
        }
480
    }
481
482
    private void maintainReconcileQueue() {
483
        if (++fullReconcileRefreshTicks < FULL_RECONCILE_REFRESH_TICKS) {
484
            return;
485
        }
486
487
        fullReconcileRefreshTicks = 0;
488
        for (BlockPos pos : observedTargetStates.keySet()) {
489
            enqueueReconcile(pos);
490
        }
491
    }
492
493
    private void drainReconcileQueue(String source, int maxEntries) {
494
        int processed = 0;
495
        while (processed < maxEntries && !reconcileQueue.isEmpty()) {
496
            BlockPos pos = reconcileQueue.removeFirst();
497
            queuedReconcileTargets.remove(pos.asLong());
498
499
            ObservedTarget observed = observedTargetStates.get(pos);
500
            if (observed == null) {
501
                processed++;
502
                continue;
503
            }
504
            BlockState state = observed.state();
505
506
            if (mc.level != null && withinDistance(pos)) {
507
                BlockState currentState = mc.level.getBlockState(pos);
508
                if (scanContext.isConfiguredTarget(currentState)) {
509
                    if (currentState != state) {
510
                        observedTargetStates.put(pos, new ObservedTarget(currentState, observed.rendered()));
511
                        state = currentState;
512
                    }
513
                } else if (!deobfuscationScanner.hasPositiveState(pos)) {
514
                    removeTargetCandidate(pos);
515
                    processed++;
516
                    continue;
517
                }
518
            }
519
520
            updateObservedTarget(pos, state, source);
521
            processed++;
522
        }
523
    }
524
525
    private void maintainSectionScanQueue() {
526
        if (mc.level == null || mc.player == null) {
527
            return;
528
        }
529
530
        int signature = currentScanSignature();
531
        if (signature != lastScanSignature || ++sectionScanRefreshTicks >= SECTION_SCAN_REFRESH_TICKS) {
532
            lastScanSignature = signature;
533
            sectionScanRefreshTicks = 0;
534
            requestLocalSectionScan(false);
535
        }
536
    }
537
538
    private void requestLocalSectionScan(boolean burst) {
539
        if (mc.level == null || mc.player == null) {
540
            return;
541
        }
542
543
        int radius = scanBlockRadius();
544
        int minY;
545
        int maxY;
546
        if (limitDistanceValue.get()) {
547
            int eyeY = (int) Math.floor(mc.player.getEyePosition().y);
548
            minY = eyeY - radius;
549
            maxY = eyeY + radius;
550
        } else {
551
            minY = mc.level.getMinY();
552
            maxY = mc.level.getMaxY();
553
        }
554
555
        sectionScanner.enqueueAround(mc, radius, minY, maxY);
556
        if (burst) {
557
            sectionScanBurstTicks = SECTION_SCAN_BURST_TICKS;
558
        }
559
    }
560
561
    private void drainSectionScanQueue() {
562
        int budget = sectionScanBurstTicks > 0 ? SECTION_SCAN_BURST_BUDGET_PER_TICK : SECTION_SCAN_BUDGET_PER_TICK;
563
        if (sectionScanBurstTicks > 0) {
564
            sectionScanBurstTicks--;
565
        }
566
567
        sectionScanner.drain(
568
                mc,
569
                budget,
570
                scanContext::isConfiguredTarget,
571
                (pos, state) -> acceptObservedCandidate(pos.asLong(), state, "section")
572
        );
573
    }
574
575
    private void publishFastScanSnapshot() {
576
        if (!isEnabled() || mc.player == null) {
577
            BlockEspSodiumCandidateCollector.disable();
578
            return;
579
        }
580
581
        BlockEspSodiumCandidateCollector.publishSnapshot(
582
                true,
583
                scanContext.targetBlocksSnapshot(),
584
                limitDistanceValue.get(),
585
                scanBlockRadius(),
586
                mc.player.getBlockX(),
587
                mc.player.getBlockY(),
588
                mc.player.getBlockZ(),
589
                fastSnapshotGeneration
590
        );
591
    }
592
593
    private int scanBlockRadius() {
594
        return limitDistanceValue.get() ? Math.max(1, maxDistanceValue.get()) : 256;
595
    }
596
597
    private int currentSearchBlocksHash() {
598
        Set<String> targets = searchBlocksValue.get();
599
        return targets == null ? 0 : targets.hashCode();
600
    }
601
602
    private int currentScanSignature() {
603
        int centerChunkX = SectionPos.blockToSectionCoord(mc.player.getBlockX());
604
        int centerChunkZ = SectionPos.blockToSectionCoord(mc.player.getBlockZ());
605
        int centerSectionY = SectionPos.blockToSectionCoord(mc.player.getBlockY());
606
        int result = 17;
607
        result = 31 * result + centerChunkX;
608
        result = 31 * result + centerChunkZ;
609
        result = 31 * result + centerSectionY;
610
        result = 31 * result + (limitDistanceValue.get() ? 1 : 0);
611
        result = 31 * result + maxDistanceValue.get();
612
        result = 31 * result + currentSearchBlocksHash();
613
        return result;
614
    }
615
616
    private void mergeDeobfuscatedTargets() {
617
        for (RenderSectionBlockScanner.ScanResult result : deobfuscationScanner.snapshot(
618
                mc,
619
                scanContext::isConfiguredTarget,
620
                null,
621
                maxTargetsValue.get()
622
        )) {
623
            acceptObservedCandidate(result.pos().asLong(), result.state(), "deobfuscation");
624
        }
625
    }
626
627
    private boolean withinDistance(BlockPos pos) {
628
        if (!limitDistanceValue.get() || mc.player == null) {
629
            return true;
630
        }
631
632
        Vec3 eye = mc.player.getEyePosition();
633
        double dx = pos.getX() + 0.5 - eye.x;
634
        double dy = pos.getY() + 0.5 - eye.y;
635
        double dz = pos.getZ() + 0.5 - eye.z;
636
        int maxDistance = maxDistanceValue.get();
637
        return dx * dx + dy * dy + dz * dz <= (double) maxDistance * (double) maxDistance;
638
    }
639
640
    private boolean isCurrentTargetBlock(BlockPos pos) {
641
        if (mc.level == null || pos == null) {
642
            return false;
643
        }
644
        return scanContext.isConfiguredTarget(mc.level.getBlockState(pos));
645
    }
646
647
    private boolean acceptsMode(BlockPos pos, boolean visible) {
648
        return switch (modeValue.get()) {
649
            case LOS -> visible;
650
            case UNRESTRICTED -> true;
651
        };
652
    }
653
654
    @Override
655
    public WorldPhase getWorldPhase() {
656
        return WorldPhase.END_MAIN;
657
    }
658
659
    @Override
660
    public void onRenderWorld(PoseStack matrices, SubmitNodeCollector consumers) {
661
    }
662
663
    @Override
664
    public void onRenderWorldEngine(Renderer3D renderer, Renderer3D depthRenderer, float tickDelta) {
665
        if (!isEnabled() || mc.level == null || mc.player == null) {
666
            return;
667
        }
668
669
        float previousLineWidth = RenderState.lineWidth;
670
        RenderState.lineWidth = Math.max(0.5f, lineWidth.get());
671
        try {
672
            for (Target target : renderTargets.values()) {
673
                if (!withinDistance(target.pos)) {
674
                    continue;
675
                }
676
677
                BlockState state = target.state;
678
                if (mc.level != null) {
679
                    BlockState current = mc.level.getBlockState(target.pos);
680
                    if (!scanContext.isConfiguredTarget(current)) {
681
                        removeTargetCandidate(target.pos);
682
                        continue;
683
                    }
684
                    state = current;
685
                    if (!state.equals(target.state)) {
686
                        ObservedTarget observed = observedTargetStates.get(target.pos);
687
                        boolean rendered = observed != null && observed.rendered();
688
                        observedTargetStates.put(target.pos, new ObservedTarget(state, rendered));
689
                        target.state = state;
690
                    }
691
                }
692
693
                int color = 0xFF000000 | ((target.visible ? visibleColor.getArgb() : chunkColor.getArgb()) & 0x00FFFFFF);
694
                BlockOutlineRenderer.render(renderer, mc.level, target.pos, state, outlineShapeMode.get(), color);
695
            }
696
        } finally {
697
            RenderState.lineWidth = previousLineWidth;
698
        }
699
700
        renderBlockTracers(renderer, tickDelta);
701
    }
702
703
    private void drawBox(Renderer3D renderer, AABB box, int r, int g, int b, int a) {
704
        double x1 = box.minX;
705
        double y1 = box.minY;
706
        double z1 = box.minZ;
707
        double x2 = box.maxX;
708
        double y2 = box.maxY;
709
        double z2 = box.maxZ;
710
711
        line(renderer, x1, y1, z1, x2, y1, z1, r, g, b, a);
712
        line(renderer, x2, y1, z1, x2, y1, z2, r, g, b, a);
713
        line(renderer, x2, y1, z2, x1, y1, z2, r, g, b, a);
714
        line(renderer, x1, y1, z2, x1, y1, z1, r, g, b, a);
715
716
        line(renderer, x1, y2, z1, x2, y2, z1, r, g, b, a);
717
        line(renderer, x2, y2, z1, x2, y2, z2, r, g, b, a);
718
        line(renderer, x2, y2, z2, x1, y2, z2, r, g, b, a);
719
        line(renderer, x1, y2, z2, x1, y2, z1, r, g, b, a);
720
721
        line(renderer, x1, y1, z1, x1, y2, z1, r, g, b, a);
722
        line(renderer, x2, y1, z1, x2, y2, z1, r, g, b, a);
723
        line(renderer, x2, y1, z2, x2, y2, z2, r, g, b, a);
724
        line(renderer, x1, y1, z2, x1, y2, z2, r, g, b, a);
725
    }
726
727
    private void line(Renderer3D renderer,
728
                      double x1, double y1, double z1,
729
                      double x2, double y2, double z2,
730
                      int r, int g, int b, int a) {
731
        renderer.line(x1, y1, z1, x2, y2, z2, r, g, b, a);
732
    }
733
734
    private void renderBlockTracers(Renderer3D renderer, float tickDelta) {
735
        Tracers tracers = Modules.get(Tracers.class);
736
        if (!useTracersValue.get() || tracers == null) {
737
            return;
738
        }
739
740
        if (!clusterTracersValue.get()) {
741
            for (Target target : renderTargets.values()) {
742
                if (!withinDistance(target.pos) || !isCurrentTargetBlock(target.pos)) {
743
                    continue;
744
                }
745
                int color = target.visible ? visibleColor.getArgb() : chunkColor.getArgb();
746
                tracers.render3DTracersRaw(renderer, tickDelta, List.of(Vec3.atCenterOf(target.pos)), color);
747
            }
748
            return;
749
        }
750
751
        List<List<Target>> clusters = buildClusters(renderTargets.values().stream()
752
                .filter(target -> withinDistance(target.pos) && isCurrentTargetBlock(target.pos))
753
                .toList());
754
        for (List<Target> cluster : clusters) {
755
            boolean anyVisible = cluster.stream().anyMatch(target -> target.visible);
756
            int color = anyVisible ? visibleColor.getArgb() : chunkColor.getArgb();
757
            tracers.render3DTracersRaw(renderer, tickDelta, List.of(clusterCenter(cluster)), color);
758
        }
759
    }
760
761
    /**
762
     * Immutable view of the targets currently accepted by BlockESP's own scan mode and distance filters.
763
     * HUD consumers should use this instead of rescanning the world or reaching into render state.
764
     */
765
    public DetectionSnapshot detectionSnapshot() {
766
        if (!isEnabled() || renderTargets.isEmpty()) return DetectionSnapshot.EMPTY;
767
768
        Map<String, MutableBlockCount> byBlock = new LinkedHashMap<>();
769
        int visible = 0;
770
        int hidden = 0;
771
        for (Target target : renderTargets.values()) {
772
            if (target == null || target.state == null) continue;
773
            String id = BuiltInRegistries.BLOCK.getKey(target.state.getBlock()).toString();
774
            String name = target.state.getBlock().getName().getString();
775
            MutableBlockCount count = byBlock.computeIfAbsent(id, ignored -> new MutableBlockCount(id, name));
776
            count.total++;
777
            if (target.visible) {
778
                count.visible++;
779
                visible++;
780
            } else {
781
                count.hidden++;
782
                hidden++;
783
            }
784
        }
785
786
        List<BlockDetection> blocks = byBlock.values().stream()
787
                .map(count -> new BlockDetection(count.id, count.name, count.total, count.visible, count.hidden))
788
                .sorted(Comparator.comparingInt(BlockDetection::total).reversed().thenComparing(BlockDetection::id))
789
                .toList();
790
        return new DetectionSnapshot(visible + hidden, visible, hidden, List.copyOf(blocks));
791
    }
792
793
    private List<List<Target>> buildClusters(Collection<Target> targets) {
794
        Map<BlockPos, Target> map = new HashMap<>();
795
        for (Target target : targets) {
796
            map.put(target.pos, target);
797
        }
798
799
        Set<BlockPos> visited = new HashSet<>();
800
        List<List<Target>> clusters = new ArrayList<>();
801
802
        for (Target target : targets) {
803
            if (visited.contains(target.pos)) {
804
                continue;
805
            }
806
807
            List<Target> cluster = new ArrayList<>();
808
            ArrayDeque<BlockPos> queue = new ArrayDeque<>();
809
810
            queue.add(target.pos);
811
            visited.add(target.pos);
812
813
            while (!queue.isEmpty()) {
814
                BlockPos current = queue.poll();
815
                Target currentTarget = map.get(current);
816
                if (currentTarget != null) {
817
                    cluster.add(currentTarget);
818
                }
819
820
                for (BlockPos neighbor : new BlockPos[]{
821
                        current.above(), current.below(),
822
                        current.north(), current.south(),
823
                        current.east(), current.west()
824
                }) {
825
                    if (!visited.contains(neighbor) && map.containsKey(neighbor)) {
826
                        visited.add(neighbor);
827
                        queue.add(neighbor);
828
                    }
829
                }
830
            }
831
832
            clusters.add(cluster);
833
        }
834
835
        return clusters;
836
    }
837
838
    private Vec3 clusterCenter(List<Target> cluster) {
839
        double x = 0.0;
840
        double y = 0.0;
841
        double z = 0.0;
842
        for (Target target : cluster) {
843
            Vec3 center = Vec3.atCenterOf(target.pos);
844
            x += center.x;
845
            y += center.y;
846
            z += center.z;
847
        }
848
        int size = cluster.size();
849
        return new Vec3(x / size, y / size, z / size);
850
    }
851
852
    public static class Target {
853
        BlockPos pos;
854
        BlockState state;
855
        AABB box;
856
        boolean visible;
857
    }
858
859
    public record DetectionSnapshot(int total, int visible, int hidden, List<BlockDetection> blocks) {
860
        public static final DetectionSnapshot EMPTY = new DetectionSnapshot(0, 0, 0, List.of());
861
    }
862
863
    public record BlockDetection(String id, String name, int total, int visible, int hidden) {
864
    }
865
866
    private static final class MutableBlockCount {
867
        private final String id;
868
        private final String name;
869
        private int total;
870
        private int visible;
871
        private int hidden;
872
873
        private MutableBlockCount(String id, String name) {
874
            this.id = id;
875
            this.name = name;
876
        }
877
    }
878
879
    private enum RenderStatus {
880
        PRESERVE,
881
        HIDDEN,
882
        VISIBLE
883
    }
884
885
    private record ObservedTarget(BlockState state, boolean rendered) {
886
    }
887
}
888
LiquidBounce (Kotlin)RENDERsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/render/ModuleBlockESP.ktKotlin · 332 lines · 11.6 KB

Allows you to see selected blocks through walls.

SettingsTargetsMergeAdjacentOutline
ModuleBlockESP.ktKotlin · Minecraft 26.2 · 332 lines · 11.6 KB · complete file, verbatimOriginal ↗
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
package net.ccbluex.liquidbounce.features.module.modules.render
20
21
import kotlinx.atomicfu.atomic
22
import net.ccbluex.liquidbounce.event.events.DrawOutlinesEvent
23
import net.ccbluex.liquidbounce.event.events.GameTickEvent
24
import net.ccbluex.liquidbounce.event.events.WorldRenderEvent
25
import net.ccbluex.liquidbounce.event.handler
26
import net.ccbluex.liquidbounce.features.module.ClientModule
27
import net.ccbluex.liquidbounce.features.module.ModuleCategories
28
import net.ccbluex.liquidbounce.render.CachedMeshStorage
29
import net.ccbluex.liquidbounce.render.ClientRenderPipelines
30
import net.ccbluex.liquidbounce.render.GenericRainbowColorMode
31
import net.ccbluex.liquidbounce.render.GenericStaticColorMode
32
import net.ccbluex.liquidbounce.render.MapColorMode
33
import net.ccbluex.liquidbounce.render.addShapeFaces
34
import net.ccbluex.liquidbounce.render.addShapeOutlines
35
import net.ccbluex.liquidbounce.render.buildMesh
36
import net.ccbluex.liquidbounce.render.drawGenericBlockESP
37
import net.ccbluex.liquidbounce.render.engine.type.Color4b
38
import net.ccbluex.liquidbounce.render.getDynamicTransformsUniform
39
import net.ccbluex.liquidbounce.render.translate
40
import net.ccbluex.liquidbounce.render.utils.DistanceFadeUniformValueGroup
41
import net.ccbluex.liquidbounce.render.withPush
42
import net.ccbluex.liquidbounce.utils.block.AbstractBlockLocationTracker
43
import net.ccbluex.liquidbounce.utils.block.ChunkScanner
44
import net.ccbluex.liquidbounce.utils.inventory.findBlocksEndingWith
45
import net.ccbluex.liquidbounce.utils.math.PositionedVoxelShape
46
import net.ccbluex.liquidbounce.utils.math.mergeAdjacentVoxelShapes
47
import net.minecraft.core.BlockPos
48
import net.minecraft.world.level.block.Block
49
import net.minecraft.world.level.block.Blocks
50
import net.minecraft.world.level.block.state.BlockState
51
import net.minecraft.world.phys.shapes.VoxelShape
52
import org.joml.Matrix4f
53
import java.util.concurrent.ConcurrentSkipListSet
54
55
/**
56
 * BlockESP module
57
 *
58
 * Allows you to see selected blocks through walls.
59
 */
60
61
object ModuleBlockESP : ClientModule("BlockESP", ModuleCategories.RENDER) {
62
63
    private val modes = choices("Mode", 0) {
64
        arrayOf(
65
            BoxMode,
66
            GlowMode,
67
        )
68
    }
69
    private val targets by blocks(
70
        "Targets",
71
        ConcurrentSkipListSet(findBlocksEndingWith("_BED", "DRAGON_EGG"))
72
    ).onChange {
73
        if (running) {
74
            onDisabled()
75
            onEnabled()
76
        }
77
        it
78
    }
79
80
    private val colorMode = choices("ColorMode", 0) {
81
        arrayOf(
82
            MapColorMode(it),
83
            GenericStaticColorMode(it, Color4b(255, 179, 72, 50)),
84
            GenericRainbowColorMode(it)
85
        )
86
    }.apply {
87
        onChanged { markDirtyForModes() }
88
    }
89
90
    private val distanceFade = tree(DistanceFadeUniformValueGroup())
91
    private val mergeAdjacent by boolean("MergeAdjacent", false).onChanged {
92
        markDirtyForModes()
93
    }
94
95
    sealed class Mode(name: String) : net.ccbluex.liquidbounce.config.types.group.Mode(name) {
96
        final override val parent get() = modes
97
98
        protected var useColor = false
99
        protected val dirtyFlag = atomic(true)
100
101
        fun markDirty() {
102
            if (this.running) {
103
                dirtyFlag.value = true
104
            }
105
        }
106
107
        final override fun enable() {
108
            dirtyFlag.value = true
109
            super.enable()
110
        }
111
112
        protected fun getDynamicTransformsUniform(
113
            modelView: Matrix4f? = null,
114
            colorModulatorAlpha: Int = -1,
115
        ) = getDynamicTransformsUniform(
116
            modelView = modelView,
117
            colorModulator = if (useColor) {
118
                Color4b.WHITE
119
            } else {
120
                val color = colorMode.activeMode.getColor(BlockPos.ZERO to Blocks.AIR.defaultBlockState())
121
                if (colorModulatorAlpha == -1) color else color.alpha(colorModulatorAlpha)
122
            },
123
        )
124
    }
125
126
    private object BoxMode : Mode("Box") {
127
        private val outline by boolean("Outline", true).onChanged {
128
            if (!it && running) {
129
                outlinesRenderState.clearStates()
130
            }
131
        }
132
        private val facesRenderState = CachedMeshStorage("${ModuleBlockESP.name} $name Faces")
133
        private val outlinesRenderState = CachedMeshStorage("${ModuleBlockESP.name} $name Outlines")
134
135
        override fun disable() {
136
            facesRenderState.clearStates()
137
            facesRenderState.clearBuffers()
138
            outlinesRenderState.clearStates()
139
            outlinesRenderState.clearBuffers()
140
            super.disable()
141
        }
142
143
        @Suppress("unused")
144
        private val renderHandler = handler<WorldRenderEvent> { event ->
145
            if (outline) {
146
                mc.gameRenderer.mainRenderTarget().drawGenericBlockESP(
147
                    outlinesRenderState,
148
                    ClientRenderPipelines.relativeLines(useColor),
149
                    distanceFade,
150
                ) {
151
                    getDynamicTransformsUniform(
152
                        modelView = event.poseStack.last().pose(),
153
                        colorModulatorAlpha = 150,
154
                    )
155
                }
156
            }
157
158
            mc.gameRenderer.mainRenderTarget().drawGenericBlockESP(
159
                facesRenderState,
160
                ClientRenderPipelines.relativeQuads(useColor),
161
                distanceFade,
162
            ) {
163
                getDynamicTransformsUniform(
164
                    modelView = event.poseStack.last().pose(),
165
                )
166
            }
167
        }
168
169
        @Suppress("unused")
170
        private val tickHandler = handler<GameTickEvent> {
171
            if (BlockTracker.isEmpty()) {
172
                facesRenderState.clearStates()
173
                outlinesRenderState.clearStates()
174
                return@handler
175
            }
176
177
            if (!dirtyFlag.compareAndSet(expect = true, update = false)) {
178
                return@handler
179
            }
180
181
            val colorMode = colorMode.activeMode
182
            useColor = colorMode.isParamSensitive
183
            val mergedShapes = collectBlockShapes(colorMode, useColor)
184
185
            facesRenderState.buildMesh(
186
                pipeline = ClientRenderPipelines.relativeQuads(useColor),
187
                origin = player.blockPosition(),
188
            ) { pose, origin ->
189
                for (mergedShape in mergedShapes) {
190
                    pose.withPush {
191
                        translate(mergedShape.blockPos, origin)
192
                        addShapeFaces(last().pose(), mergedShape.shape, mergedShape.key.color)
193
                    }
194
                }
195
            }
196
197
            if (outline) {
198
                outlinesRenderState.buildMesh(
199
                    pipeline = ClientRenderPipelines.relativeLines(useColor),
200
                    origin = player.blockPosition(),
201
                ) { pose, meshOrigin ->
202
                    for (mergedShape in mergedShapes) {
203
                        pose.withPush {
204
                            translate(mergedShape.blockPos, meshOrigin)
205
                            addShapeOutlines(last().pose(), mergedShape.shape, mergedShape.key.color)
206
                        }
207
                    }
208
                }
209
            }
210
        }
211
212
    }
213
214
    object GlowMode : Mode("Glow") {
215
        private val renderState = CachedMeshStorage("${ModuleBlockESP.name} $name")
216
217
        override fun disable() {
218
            renderState.clearStates()
219
            renderState.clearBuffers()
220
            super.disable()
221
        }
222
223
        @Suppress("unused")
224
        private val renderHandler = handler<DrawOutlinesEvent> { event ->
225
            val dirty = event.renderTarget.drawGenericBlockESP(
226
                renderState,
227
                ClientRenderPipelines.outlineQuads(useColor),
228
                distanceFade,
229
            ) {
230
                getDynamicTransformsUniform(
231
                    colorModulatorAlpha = 255,
232
                )
233
            }
234
235
            if (dirty) {
236
                event.markDirty()
237
            }
238
        }
239
240
        @Suppress("unused")
241
        private val tickHandler = handler<GameTickEvent> {
242
            if (BlockTracker.isEmpty()) {
243
                renderState.clearStates()
244
                return@handler
245
            }
246
247
            if (!dirtyFlag.compareAndSet(expect = true, update = false)) {
248
                return@handler
249
            }
250
251
            val colorMode = colorMode.activeMode
252
            useColor = colorMode.isParamSensitive
253
            val origin = player.blockPosition()
254
255
            renderState.buildMesh(
256
                pipeline = ClientRenderPipelines.outlineQuads(useColor),
257
                origin = origin,
258
            ) { pose, meshOrigin ->
259
                for (mergedShape in collectBlockShapes(colorMode, useColor)) {
260
                    pose.withPush {
261
                        translate(mergedShape.blockPos, meshOrigin)
262
                        addShapeFaces(last().pose(), mergedShape.shape, mergedShape.key.color?.alpha(255))
263
                    }
264
                }
265
            }
266
        }
267
268
    }
269
270
    override fun onEnabled() {
271
        ChunkScanner.subscribe(BlockTracker)
272
    }
273
274
    override fun onDisabled() {
275
        ChunkScanner.unsubscribe(BlockTracker)
276
        markDirtyForModes()
277
    }
278
279
    private fun markDirtyForModes() {
280
        modes.modes.forEach { it.markDirty() }
281
    }
282
283
    private inline fun forEachTrackedBlocks(
284
        block: (blockPos: BlockPos, blockState: BlockState, outlineShape: VoxelShape) -> Unit,
285
    ) {
286
        for ((blockPos, t) in BlockTracker.iterate()) {
287
            val blockState = t.state
288
            val outlineShape = t.shape
289
            block(blockPos, blockState, outlineShape)
290
        }
291
    }
292
293
    private fun collectBlockShapes(
294
        colorMode: net.ccbluex.liquidbounce.render.GenericColorMode<Pair<BlockPos, BlockState>>,
295
        useColor: Boolean,
296
    ): List<PositionedVoxelShape<BlockMergeKey>> {
297
        val shapes = buildList {
298
            forEachTrackedBlocks { blockPos, blockState, outlineShape ->
299
                val color = if (useColor) colorMode.getColor(blockPos to blockState) else null
300
                add(
301
                    PositionedVoxelShape(
302
                        blockPos = blockPos.asLong(),
303
                        key = BlockMergeKey(blockState.block, color),
304
                        shape = outlineShape,
305
                    )
306
                )
307
            }
308
        }
309
310
        return if (mergeAdjacent) shapes.mergeAdjacentVoxelShapes() else shapes
311
    }
312
313
    private data class BlockMergeKey(val block: Block, val color: Color4b?)
314
315
    private class TrackedState(@JvmField val state: BlockState, @JvmField val shape: VoxelShape)
316
317
    private object BlockTracker : AbstractBlockLocationTracker.BlockPos2State<TrackedState>() {
318
        override fun getStateFor(pos: BlockPos, state: BlockState): TrackedState? {
319
            return if (!state.isAir && state.block in targets) {
320
                TrackedState(state, state.getShape(world, pos))
321
            } else {
322
                null
323
            }
324
        }
325
326
        override fun onUpdated() {
327
            markDirtyForModes()
328
        }
329
    }
330
331
}
332