StashFinder module

StashFinder: Minecraft 26.3 cheat module, full source for every implementation (1 client: OfflineClient).

1 implementationMISC

Clients with this module

Full module source: 1 implementation

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

OfflineClientMISCsrc/main/java/com/jellypudding/offlineclient/modules/misc/StashFinder.javaJava · 420 lines · 16.8 KB

Points out chunks packed with containers as you travel.

SettingsMinimumContainersIgnored supportsMinimum distanceNotifyNotify modeTracersTracer colourHide withinTracer rangeChunk columnsColumn colourClear key
StashFinder.javaJava · Minecraft 26.2 · 420 lines · 16.8 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.misc;
2
3
import com.google.gson.JsonArray;
4
import com.google.gson.JsonElement;
5
import com.google.gson.JsonObject;
6
import com.google.gson.JsonParser;
7
import com.jellypudding.offlineclient.OfflineClient;
8
import com.jellypudding.offlineclient.event.Subscribe;
9
import com.jellypudding.offlineclient.event.events.KeyPressEvent;
10
import com.jellypudding.offlineclient.event.events.Render3DEvent;
11
import com.jellypudding.offlineclient.event.events.TickEvent;
12
import com.jellypudding.offlineclient.module.Category;
13
import com.jellypudding.offlineclient.module.Module;
14
import com.jellypudding.offlineclient.setting.BoolSetting;
15
import com.jellypudding.offlineclient.setting.ColorSetting;
16
import com.jellypudding.offlineclient.setting.EnumSetting;
17
import com.jellypudding.offlineclient.setting.KeybindSetting;
18
import com.jellypudding.offlineclient.setting.NumberSetting;
19
import com.jellypudding.offlineclient.setting.RegistryListSetting;
20
import com.jellypudding.offlineclient.util.ChatUtil;
21
import net.minecraft.client.gui.components.toasts.SystemToast;
22
import net.minecraft.client.multiplayer.ClientLevel;
23
import net.minecraft.client.multiplayer.ServerData;
24
import net.minecraft.core.BlockPos;
25
import net.minecraft.core.registries.BuiltInRegistries;
26
import net.minecraft.network.chat.Component;
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.level.block.entity.BlockEntity;
32
import net.minecraft.world.level.block.entity.BlockEntityType;
33
import net.minecraft.world.level.block.entity.BlockEntityTypes;
34
import net.minecraft.world.level.chunk.LevelChunk;
35
import net.minecraft.world.level.chunk.status.ChunkStatus;
36
import net.minecraft.world.phys.Vec3;
37
import org.lwjgl.glfw.GLFW;
38
39
import java.io.IOException;
40
import java.nio.file.Files;
41
import java.nio.file.Path;
42
import java.util.ArrayList;
43
import java.util.Iterator;
44
import java.util.LinkedHashMap;
45
import java.util.List;
46
import java.util.Map;
47
48
public final class StashFinder extends Module {
49
50
    public enum Notify { CHAT, TOAST, BOTH }
51
52
    // The server is part of the identity. Two servers share their dimension keys.
53
    private record Stash(String server, String dimension, int x, int z,
54
                         Map<String, Integer> counts, boolean tracer) {
55
56
        int total() {
57
            int sum = 0;
58
            for (int count : counts.values()) {
59
                sum += count;
60
            }
61
            return sum;
62
        }
63
64
        boolean sameChunk(String server, String dimension, int x, int z) {
65
            return this.server.equals(server) && this.dimension.equals(dimension)
66
                && this.x == x && this.z == z;
67
        }
68
    }
69
70
    private static final int SCANS_PER_TICK = 4;
71
72
    // Ticks before a chunk is looked at again. Chests placed after the first
73
    // look are picked up on the next.
74
    private static final int RESCAN_TICKS = 200;
75
76
    private static final int MAX_SCANNED = 20_000;
77
78
    private static final int DROP_PER_TRIM = 4_000;
79
80
    private static final int MAX_STASHES = 1024;
81
82
    private final NumberSetting minimum = new NumberSetting("Minimum",
83
        "How many containers a chunk needs before it counts as a stash.", 6, 2, 64, 1)
84
        .min(1);
85
    private final RegistryListSetting<BlockEntityType<?>> containers = new RegistryListSetting<>(
86
        "Containers", "Which container blocks are counted. Click to pick them.",
87
        BuiltInRegistries.BLOCK_ENTITY_TYPE,
88
        List.of(BlockEntityTypes.BARREL, BlockEntityTypes.BLAST_FURNACE,
89
            BlockEntityTypes.BREWING_STAND, BlockEntityTypes.CAMPFIRE, BlockEntityTypes.CHEST,
90
            BlockEntityTypes.CHISELED_BOOKSHELF, BlockEntityTypes.CRAFTER,
91
            BlockEntityTypes.DISPENSER, BlockEntityTypes.DECORATED_POT, BlockEntityTypes.DROPPER,
92
            BlockEntityTypes.ENDER_CHEST, BlockEntityTypes.FURNACE, BlockEntityTypes.HOPPER,
93
            BlockEntityTypes.SHULKER_BOX, BlockEntityTypes.SMOKER,
94
            BlockEntityTypes.TRAPPED_CHEST));
95
    private final RegistryListSetting<Block> ignoredSupports = new RegistryListSetting<>(
96
        "Ignored supports", "A container standing on one of these is not counted. Click to pick them.",
97
        BuiltInRegistries.BLOCK, List.of(Blocks.TUFF_BRICKS, Blocks.BARREL));
98
    private final NumberSetting minimumDistance = new NumberSetting("Minimum distance",
99
        "Chunks closer than this to the world origin are never recorded.",
100
        0, 0, 10000, 100, " blocks").min(0).max(100000);
101
    private final BoolSetting notify = new BoolSetting("Notify",
102
        "Say something when a stash is found.", true);
103
    private final EnumSetting<Notify> notifyMode = new EnumSetting<>("Notify mode",
104
        "Where the message goes.", Notify.BOTH)
105
        .describe(Notify.CHAT, "A chat line only.")
106
        .describe(Notify.TOAST, "A toast in the corner only.")
107
        .describe(Notify.BOTH, "Both a chat line and a toast.")
108
        .under(notify);
109
    private final BoolSetting tracers = new BoolSetting("Tracers",
110
        "Draws a line to every recorded chunk.", true);
111
    private final ColorSetting tracerColor = new ColorSetting("Tracer colour",
112
        "Colour of those lines.", 48, 1f, 1f, false)
113
        .under(tracers);
114
    private final NumberSetting tracerHide = new NumberSetting("Hide within",
115
        "A tracer is dropped once you are this close to the chunk.", 16, 1, 50, 1, " blocks")
116
        .min(1).max(200)
117
        .under(tracers);
118
    private final NumberSetting tracerRange = new NumberSetting("Tracer range",
119
        "Chunks further away than this get no tracer.", 2000, 50, 10000, 50, " blocks")
120
        .min(10).max(1000000)
121
        .under(tracers);
122
    private final BoolSetting columns = new BoolSetting("Chunk columns",
123
        "Draws four tall lines at the centre of every recorded chunk.", false);
124
    private final ColorSetting columnColor = new ColorSetting("Column colour",
125
        "Colour of those lines.", 48, 1f, 1f, false)
126
        .under(columns);
127
    private final KeybindSetting clearKey = new KeybindSetting("Clear key",
128
        "Press to drop every tracer.", KeybindSetting.UNBOUND);
129
130
    // Kept for the whole session even whilst turned off and saved to disk.
131
    private final List<Stash> stashes = new ArrayList<>();
132
133
    // When each chunk in the current dimension was last counted. Oldest first.
134
    private final Map<Long, Integer> scanned = new LinkedHashMap<>();
135
    private int tick;
136
137
    private String dimension = "";
138
    private boolean loaded;
139
    private boolean dirty;
140
141
    // A new world object means a new server or a new dimension.
142
    private ClientLevel lastLevel;
143
144
    public StashFinder() {
145
        super("StashFinder", "Points out chunks packed with containers as you travel.", Category.MISC);
146
        addSettings(minimum, containers, ignoredSupports, minimumDistance, notify, notifyMode,
147
            tracers, tracerColor, tracerHide, tracerRange, columns, columnColor, clearKey);
148
        searchTags("stash", "base finder", "chests", "loot");
149
    }
150
151
    @Override
152
    public String getSuffix() {
153
        return count(stashes.size());
154
    }
155
156
    @Subscribe
157
    private void onKeyPress(KeyPressEvent event) {
158
        if (event.getAction() != GLFW.GLFW_PRESS || mc.gui.screen() != null
159
            || !clearKey.isBound() || event.getKey() != clearKey.getValue()) {
160
            return;
161
        }
162
        for (int i = 0; i < stashes.size(); i++) {
163
            Stash stash = stashes.get(i);
164
            stashes.set(i, new Stash(stash.server(), stash.dimension(), stash.x(), stash.z(),
165
                stash.counts(), false));
166
        }
167
        dirty = true;
168
        ChatUtil.message("§bStashFinder §7dropped every tracer.");
169
    }
170
171
    @Subscribe
172
    private void onTick(TickEvent event) {
173
        if (!inGame()) {
174
            return;
175
        }
176
        if (!loaded) {
177
            loaded = true;
178
            load();
179
        }
180
        if (mc.level != lastLevel) {
181
            // Chunk coordinates mean something different in every world.
182
            lastLevel = mc.level;
183
            dimension = mc.level.dimension().identifier().toString();
184
            scanned.clear();
185
        }
186
187
        tick++;
188
        int radius = mc.options.getEffectiveRenderDistance();
189
        int centerX = mc.player.chunkPosition().x();
190
        int centerZ = mc.player.chunkPosition().z();
191
        int budget = SCANS_PER_TICK;
192
193
        for (int dx = -radius; dx <= radius && budget > 0; dx++) {
194
            for (int dz = -radius; dz <= radius && budget > 0; dz++) {
195
                int x = centerX + dx;
196
                int z = centerZ + dz;
197
                long key = ChunkPos.pack(x, z);
198
                Integer last = scanned.get(key);
199
                if (last != null && tick - last < RESCAN_TICKS) {
200
                    continue;
201
                }
202
                LevelChunk chunk = mc.level.getChunkSource()
203
                    .getChunk(x, z, ChunkStatus.FULL, false);
204
                if (chunk == null) {
205
                    continue;
206
                }
207
                // Back to the end of the queue. The trim drops the stalest first.
208
                scanned.remove(key);
209
                scanned.put(key, tick);
210
                budget--;
211
                check(new ChunkPos(x, z), chunk);
212
            }
213
        }
214
        trim();
215
        if (dirty) {
216
            dirty = false;
217
            save();
218
        }
219
    }
220
221
    private void trim() {
222
        if (scanned.size() <= MAX_SCANNED) {
223
            return;
224
        }
225
        Iterator<Long> iterator = scanned.keySet().iterator();
226
        for (int i = 0; i < DROP_PER_TRIM && iterator.hasNext(); i++) {
227
            iterator.next();
228
            iterator.remove();
229
        }
230
    }
231
232
    private void check(ChunkPos pos, LevelChunk chunk) {
233
        int middleX = pos.getMiddleBlockX();
234
        int middleZ = pos.getMiddleBlockZ();
235
        if (Math.sqrt(middleX * (double) middleX + middleZ * (double) middleZ)
236
            < minimumDistance.getValue()) {
237
            return;
238
        }
239
        Map<String, Integer> counts = new LinkedHashMap<>();
240
        for (BlockEntity blockEntity : chunk.getBlockEntities().values()) {
241
            if (!counts(blockEntity)) {
242
                continue;
243
            }
244
            Identifier id = BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(blockEntity.getType());
245
            counts.merge(id == null ? "unknown" : id.getPath(), 1, Integer::sum);
246
        }
247
        int total = 0;
248
        for (int each : counts.values()) {
249
            total += each;
250
        }
251
        if (total < minimum.getInt()) {
252
            return;
253
        }
254
255
        String server = serverName();
256
        Stash fresh = new Stash(server, dimension, middleX, middleZ, counts, true);
257
        for (int i = 0; i < stashes.size(); i++) {
258
            Stash old = stashes.get(i);
259
            if (!old.sameChunk(server, dimension, middleX, middleZ)) {
260
                continue;
261
            }
262
            // Only a changed haul is worth saying again.
263
            if (old.counts().equals(counts)) {
264
                return;
265
            }
266
            stashes.set(i, new Stash(server, dimension, middleX, middleZ, counts, old.tracer()));
267
            dirty = true;
268
            report(fresh);
269
            return;
270
        }
271
        stashes.add(fresh);
272
        if (stashes.size() > MAX_STASHES) {
273
            stashes.removeFirst();
274
        }
275
        dirty = true;
276
        report(fresh);
277
    }
278
279
    // A container resting on a listed block belongs to a generated structure.
280
    private boolean counts(BlockEntity blockEntity) {
281
        if (!containers.contains(blockEntity.getType())) {
282
            return false;
283
        }
284
        BlockPos below = blockEntity.getBlockPos().below();
285
        return !ignoredSupports.contains(mc.level.getBlockState(below).getBlock());
286
    }
287
288
    private String serverName() {
289
        ServerData server = mc.getCurrentServer();
290
        return server == null ? "" : server.ip;
291
    }
292
293
    private void report(Stash stash) {
294
        if (!notify.isOn()) {
295
            return;
296
        }
297
        int distance = (int) Math.sqrt(mc.player.distanceToSqr(stash.x(), mc.player.getY(), stash.z()));
298
        String where = stash.x() + " " + stash.z();
299
        if (!notifyMode.is(Notify.TOAST)) {
300
            ChatUtil.message("§bStashFinder §7found §f" + describe(stash) + "§7 at §f" + where
301
                + "§7 in " + shortName(stash.dimension()) + " and that is §f" + distance
302
                + "§7 blocks away.");
303
        }
304
        if (!notifyMode.is(Notify.CHAT)) {
305
            mc.gui.toastManager().addToast(new SystemToast(
306
                SystemToast.SystemToastId.PERIODIC_NOTIFICATION,
307
                Component.literal("Found stash"),
308
                Component.literal(stash.total() + " containers at " + where)));
309
        }
310
    }
311
312
    // The types found with a count each such as "12 chest 3 barrel".
313
    private static String describe(Stash stash) {
314
        StringBuilder text = new StringBuilder();
315
        for (Map.Entry<String, Integer> entry : stash.counts().entrySet()) {
316
            text.append(text.isEmpty() ? "" : " ").append(entry.getValue()).append(" ")
317
                .append(entry.getKey().replace('_', ' '));
318
        }
319
        return text.toString();
320
    }
321
322
    private static String shortName(String dimension) {
323
        int colon = dimension.indexOf(':');
324
        return colon == -1 ? dimension : dimension.substring(colon + 1);
325
    }
326
327
    @Subscribe
328
    private void onRender3D(Render3DEvent event) {
329
        if (!inGame() || (!tracers.isOn() && !columns.isOn())) {
330
            return;
331
        }
332
        String server = serverName();
333
        double eye = mc.player.getEyeY();
334
        for (Stash stash : stashes) {
335
            if (!stash.tracer() || !stash.server().equals(server)
336
                || !stash.dimension().equals(dimension)) {
337
                continue;
338
            }
339
            double away = Math.sqrt(mc.player.distanceToSqr(stash.x(), mc.player.getY(), stash.z()));
340
            if (away < tracerHide.getValue() || away > tracerRange.getValue()) {
341
                continue;
342
            }
343
            if (tracers.isOn()) {
344
                event.getBatch().tracer(new Vec3(stash.x() + 0.5, eye, stash.z() + 0.5),
345
                    tracerColor.getColor(), true);
346
            }
347
            if (columns.isOn()) {
348
                drawColumn(event, stash);
349
            }
350
        }
351
    }
352
353
    private void drawColumn(Render3DEvent event, Stash stash) {
354
        double bottom = mc.level.getMinY();
355
        double top = mc.level.getMaxY();
356
        int colour = columnColor.getColor();
357
        for (int corner = 0; corner < 4; corner++) {
358
            double x = stash.x() + (corner < 2 ? 0 : 1);
359
            double z = stash.z() + (corner % 2 == 0 ? 0 : 1);
360
            event.getBatch().line(new Vec3(x, bottom, z), new Vec3(x, top, z), colour, true);
361
        }
362
    }
363
364
    private static Path file() {
365
        return OfflineClient.MC.gameDirectory.toPath().resolve("offlineclient")
366
            .resolve("stashes.json");
367
    }
368
369
    private void load() {
370
        Path path = file();
371
        if (!Files.exists(path)) {
372
            return;
373
        }
374
        try {
375
            JsonElement root = JsonParser.parseString(Files.readString(path));
376
            if (!root.isJsonArray()) {
377
                return;
378
            }
379
            for (JsonElement element : root.getAsJsonArray()) {
380
                JsonObject object = element.getAsJsonObject();
381
                Map<String, Integer> counts = new LinkedHashMap<>();
382
                for (Map.Entry<String, JsonElement> entry
383
                    : object.getAsJsonObject("counts").entrySet()) {
384
                    counts.put(entry.getKey(), entry.getValue().getAsInt());
385
                }
386
                stashes.add(new Stash(object.get("server").getAsString(),
387
                    object.get("dimension").getAsString(), object.get("x").getAsInt(),
388
                    object.get("z").getAsInt(), counts, object.get("tracer").getAsBoolean()));
389
            }
390
        } catch (Exception error) {
391
            OfflineClient.LOG.error("Failed to read the stash list", error);
392
        }
393
    }
394
395
    private void save() {
396
        JsonArray array = new JsonArray();
397
        for (Stash stash : stashes) {
398
            JsonObject object = new JsonObject();
399
            object.addProperty("server", stash.server());
400
            object.addProperty("dimension", stash.dimension());
401
            object.addProperty("x", stash.x());
402
            object.addProperty("z", stash.z());
403
            object.addProperty("tracer", stash.tracer());
404
            JsonObject counts = new JsonObject();
405
            for (Map.Entry<String, Integer> entry : stash.counts().entrySet()) {
406
                counts.addProperty(entry.getKey(), entry.getValue());
407
            }
408
            object.add("counts", counts);
409
            array.add(object);
410
        }
411
        try {
412
            Path path = file();
413
            Files.createDirectories(path.getParent());
414
            Files.writeString(path, array.toString());
415
        } catch (IOException error) {
416
            OfflineClient.LOG.error("Failed to write the stash list", error);
417
        }
418
    }
419
}
420