notifier module

notifier: Minecraft 26.3 cheat module, full source for every implementation (3 clients: Meteor Client, OfflineClient, LiquidBounce (Kotlin)).

3 implementationsMiscMISC

Full module source: 3 implementations

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

Meteor ClientMiscsrc/main/java/meteordevelopment/meteorclient/systems/modules/misc/Notifier.javaJava · 425 lines · 17.2 KB

Notifies you of different events.

Settingstotem-popsdistance-checkplayer-radiusignore-ownignore-friendsignore-othersvisual-rangeevententitiesignore-fake-playerssoundpearlplayer-joins-leavesnotification-delaysimple-notifications
Notifier.javaJava · Minecraft 26.2 · 425 lines · 17.2 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Meteor Client distribution (https://github.com/MeteorDevelopment/meteor-client).
3
 * Copyright (c) Meteor Development.
4
 */
5
6
package meteordevelopment.meteorclient.systems.modules.misc;
7
8
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
9
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
10
import it.unimi.dsi.fastutil.objects.Object2IntMap;
11
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
12
import meteordevelopment.meteorclient.events.entity.EntityAddedEvent;
13
import meteordevelopment.meteorclient.events.entity.EntityRemovedEvent;
14
import meteordevelopment.meteorclient.events.game.GameJoinedEvent;
15
import meteordevelopment.meteorclient.events.game.GameLeftEvent;
16
import meteordevelopment.meteorclient.events.packets.PacketEvent;
17
import meteordevelopment.meteorclient.events.world.TickEvent;
18
import meteordevelopment.meteorclient.settings.*;
19
import meteordevelopment.meteorclient.systems.friends.Friends;
20
import meteordevelopment.meteorclient.systems.modules.Categories;
21
import meteordevelopment.meteorclient.systems.modules.Module;
22
import meteordevelopment.meteorclient.utils.entity.fakeplayer.FakePlayerEntity;
23
import meteordevelopment.meteorclient.utils.player.ChatUtils;
24
import meteordevelopment.meteorclient.utils.player.PlayerUtils;
25
import meteordevelopment.orbit.EventHandler;
26
import net.minecraft.ChatFormatting;
27
import net.minecraft.client.multiplayer.PlayerInfo;
28
import net.minecraft.network.chat.Component;
29
import net.minecraft.network.chat.MutableComponent;
30
import net.minecraft.network.protocol.game.ClientboundEntityEventPacket;
31
import net.minecraft.network.protocol.game.ClientboundPlayerInfoRemovePacket;
32
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket;
33
import net.minecraft.sounds.SoundEvents;
34
import net.minecraft.sounds.SoundSource;
35
import net.minecraft.util.ArrayListDeque;
36
import net.minecraft.world.entity.Entity;
37
import net.minecraft.world.entity.EntityEvent;
38
import net.minecraft.world.entity.EntityType;
39
import net.minecraft.world.entity.EntityTypes;
40
import net.minecraft.world.entity.player.Player;
41
import net.minecraft.world.entity.projectile.throwableitemprojectile.ThrownEnderpearl;
42
import net.minecraft.world.phys.Vec3;
43
44
import java.util.*;
45
46
import static meteordevelopment.meteorclient.utils.player.ChatUtils.formatCoords;
47
48
public class Notifier extends Module {
49
    private final SettingGroup sgTotemPops = settings.createGroup("Totem Pops");
50
    private final SettingGroup sgVisualRange = settings.createGroup("Visual Range");
51
    private final SettingGroup sgPearl = settings.createGroup("Pearl");
52
    private final SettingGroup sgJoinsLeaves = settings.createGroup("Joins/Leaves");
53
54
    // Totem Pops
55
56
    private final Setting<Boolean> totemPops = sgTotemPops.add(new BoolSetting.Builder()
57
        .name("totem-pops")
58
        .description("Notifies you when a player pops a totem.")
59
        .defaultValue(true)
60
        .build()
61
    );
62
63
    private final Setting<Boolean> totemsDistanceCheck = sgTotemPops.add(new BoolSetting.Builder()
64
        .name("distance-check")
65
        .description("Limits the distance in which the pops are recognized.")
66
        .defaultValue(false)
67
        .visible(totemPops::get)
68
        .build()
69
    );
70
71
    private final Setting<Integer> totemsDistance = sgTotemPops.add(new IntSetting.Builder()
72
        .name("player-radius")
73
        .description("The radius in which to log totem pops.")
74
        .defaultValue(30)
75
        .sliderRange(1, 50)
76
        .range(1, 100)
77
        .visible(() -> totemPops.get() && totemsDistanceCheck.get())
78
        .build()
79
    );
80
81
    private final Setting<Boolean> totemsIgnoreOwn = sgTotemPops.add(new BoolSetting.Builder()
82
        .name("ignore-own")
83
        .description("Ignores your own totem pops.")
84
        .defaultValue(false)
85
        .build()
86
    );
87
88
    private final Setting<Boolean> totemsIgnoreFriends = sgTotemPops.add(new BoolSetting.Builder()
89
        .name("ignore-friends")
90
        .description("Ignores friends totem pops.")
91
        .defaultValue(false)
92
        .build()
93
    );
94
95
    private final Setting<Boolean> totemsIgnoreOthers = sgTotemPops.add(new BoolSetting.Builder()
96
        .name("ignore-others")
97
        .description("Ignores other players totem pops.")
98
        .defaultValue(false)
99
        .build()
100
    );
101
102
    // Visual Range
103
104
    private final Setting<Boolean> visualRange = sgVisualRange.add(new BoolSetting.Builder()
105
        .name("visual-range")
106
        .description("Notifies you when an entity enters your render distance.")
107
        .defaultValue(false)
108
        .build()
109
    );
110
111
    private final Setting<Event> event = sgVisualRange.add(new EnumSetting.Builder<Event>()
112
        .name("event")
113
        .description("When to log the entities.")
114
        .defaultValue(Event.Both)
115
        .build()
116
    );
117
118
    private final Setting<Set<EntityType<?>>> entities = sgVisualRange.add(new EntityTypeListSetting.Builder()
119
        .name("entities")
120
        .description("Which entities to notify about.")
121
        .defaultValue(EntityTypes.PLAYER)
122
        .build()
123
    );
124
125
    private final Setting<Boolean> visualRangeIgnoreFriends = sgVisualRange.add(new BoolSetting.Builder()
126
        .name("ignore-friends")
127
        .description("Ignores friends.")
128
        .defaultValue(true)
129
        .build()
130
    );
131
132
    private final Setting<Boolean> visualRangeIgnoreFakes = sgVisualRange.add(new BoolSetting.Builder()
133
        .name("ignore-fake-players")
134
        .description("Ignores fake players.")
135
        .defaultValue(true)
136
        .build()
137
    );
138
139
    private final Setting<Boolean> visualMakeSound = sgVisualRange.add(new BoolSetting.Builder()
140
        .name("sound")
141
        .description("Emits a sound effect on enter / leave")
142
        .defaultValue(true)
143
        .build()
144
    );
145
146
    // Pearl
147
148
    private final Setting<Boolean> pearl = sgPearl.add(new BoolSetting.Builder()
149
        .name("pearl")
150
        .description("Notifies you when a player is teleported using an ender pearl.")
151
        .defaultValue(true)
152
        .build()
153
    );
154
155
    private final Setting<Boolean> pearlIgnoreOwn = sgPearl.add(new BoolSetting.Builder()
156
        .name("ignore-own")
157
        .description("Ignores your own pearls.")
158
        .defaultValue(false)
159
        .build()
160
    );
161
162
    private final Setting<Boolean> pearlIgnoreFriends = sgPearl.add(new BoolSetting.Builder()
163
        .name("ignore-friends")
164
        .description("Ignores friends pearls.")
165
        .defaultValue(false)
166
        .build()
167
    );
168
169
    // Joins/Leaves
170
171
    private final Setting<JoinLeaveModes> joinsLeavesMode = sgJoinsLeaves.add(new EnumSetting.Builder<JoinLeaveModes>()
172
        .name("player-joins-leaves")
173
        .description("How to handle player join/leave notifications.")
174
        .defaultValue(JoinLeaveModes.None)
175
        .build()
176
    );
177
178
    private final Setting<Integer> notificationDelay = sgJoinsLeaves.add(new IntSetting.Builder()
179
        .name("notification-delay")
180
        .description("How long to wait in ticks before posting the next join/leave notification in your chat.")
181
        .range(0, 1000)
182
        .sliderRange(0, 100)
183
        .defaultValue(0)
184
        .build()
185
    );
186
187
    private final Setting<Boolean> simpleNotifications = sgJoinsLeaves.add(new BoolSetting.Builder()
188
        .name("simple-notifications")
189
        .description("Display join/leave notifications without a prefix, to reduce chat clutter.")
190
        .defaultValue(true)
191
        .build()
192
    );
193
194
    private int timer;
195
    private boolean loginPacket = true;
196
    private final Object2IntMap<UUID> totemPopMap = new Object2IntOpenHashMap<>();
197
    private final Object2IntMap<UUID> chatIdMap = new Object2IntOpenHashMap<>();
198
    private final Int2ObjectMap<Vec3> pearlStartPosMap = new Int2ObjectOpenHashMap<>();
199
    private final ArrayListDeque<MutableComponent> messageQueue = new ArrayListDeque<>();
200
201
    private final Random random = new Random();
202
203
    public Notifier() {
204
        super(Categories.Misc, "notifier", "Notifies you of different events.");
205
    }
206
207
    // Visual Range
208
209
    @EventHandler
210
    private void onEntityAdded(EntityAddedEvent event) {
211
        if (!event.entity.getUUID().equals(mc.player.getUUID()) && entities.get().contains(event.entity.getType()) && visualRange.get() && this.event.get() != Event.Despawn) {
212
            if (event.entity instanceof Player player) {
213
                if ((!visualRangeIgnoreFriends.get() || !Friends.get().isFriend(player)) && (!visualRangeIgnoreFakes.get() || !(event.entity instanceof FakePlayerEntity))) {
214
                    ChatUtils.sendMsg(event.entity.getId() + 100, ChatFormatting.GRAY, "(highlight)%s(default) has entered your visual range!", event.entity.getName().getString());
215
216
                    if (visualMakeSound.get())
217
                        mc.level.playSound(mc.player, mc.player, SoundEvents.EXPERIENCE_ORB_PICKUP, SoundSource.AMBIENT, 3.0F, 1.0F);
218
                }
219
            } else {
220
                MutableComponent text = Component.literal(event.entity.getType().getDescription().getString()).withStyle(ChatFormatting.WHITE);
221
                text.append(Component.literal(" has spawned at ").withStyle(ChatFormatting.GRAY));
222
                text.append(formatCoords(event.entity.position()));
223
                text.append(Component.literal(".").withStyle(ChatFormatting.GRAY));
224
                info(text);
225
            }
226
        }
227
228
        if (pearl.get() && event.entity instanceof ThrownEnderpearl pearlEntity) {
229
            pearlStartPosMap.put(pearlEntity.getId(), new Vec3(pearlEntity.getX(), pearlEntity.getY(), pearlEntity.getZ()));
230
        }
231
    }
232
233
    @EventHandler
234
    private void onEntityRemoved(EntityRemovedEvent event) {
235
        if (!event.entity.getUUID().equals(mc.player.getUUID()) && entities.get().contains(event.entity.getType()) && visualRange.get() && this.event.get() != Event.Spawn) {
236
            if (event.entity instanceof Player player) {
237
                if ((!visualRangeIgnoreFriends.get() || !Friends.get().isFriend(player)) && (!visualRangeIgnoreFakes.get() || !(event.entity instanceof FakePlayerEntity))) {
238
                    ChatUtils.sendMsg(event.entity.getId() + 100, ChatFormatting.GRAY, "(highlight)%s(default) has left your visual range!", event.entity.getName().getString());
239
240
                    if (visualMakeSound.get())
241
                        mc.level.playSound(mc.player, mc.player, SoundEvents.EXPERIENCE_ORB_PICKUP, SoundSource.AMBIENT, 3.0F, 1.0F);
242
                }
243
            } else {
244
                MutableComponent text = Component.literal(event.entity.getType().getDescription().getString()).withStyle(ChatFormatting.WHITE);
245
                text.append(Component.literal(" has despawned at ").withStyle(ChatFormatting.GRAY));
246
                text.append(formatCoords(event.entity.position()));
247
                text.append(Component.literal(".").withStyle(ChatFormatting.GRAY));
248
                info(text);
249
            }
250
        }
251
252
        if (pearl.get()) {
253
            Entity e = event.entity;
254
            int i = e.getId();
255
            Vec3 thrownPos = pearlStartPosMap.remove(i);
256
            if (thrownPos != null) {
257
                ThrownEnderpearl pearl = (ThrownEnderpearl) e;
258
                if (pearl.getOwner() != null && pearl.getOwner() instanceof Player p) {
259
                    double d = thrownPos.distanceTo(e.position());
260
                    if ((!Friends.get().isFriend(p) || !pearlIgnoreFriends.get()) && (!p.equals(mc.player) || !pearlIgnoreOwn.get())) {
261
                        info("(highlight)%s's(default) pearl landed at %d, %d, %d (highlight)(%.1fm away, travelled %.1fm)(default).", pearl.getOwner().getName().getString(), pearl.blockPosition().getX(), pearl.blockPosition().getY(), pearl.blockPosition().getZ(), pearl.distanceTo(mc.player), d);
262
                    }
263
                }
264
            }
265
        }
266
    }
267
268
    // Totem Pops && Joins/Leaves
269
270
    @Override
271
    public void onActivate() {
272
        totemPopMap.clear();
273
        chatIdMap.clear();
274
        pearlStartPosMap.clear();
275
    }
276
277
    @Override
278
    public void onDeactivate() {
279
        timer = 0;
280
        messageQueue.clear();
281
    }
282
283
    @EventHandler
284
    private void onGameJoin(GameJoinedEvent event) {
285
        timer = 0;
286
        totemPopMap.clear();
287
        chatIdMap.clear();
288
        messageQueue.clear();
289
        pearlStartPosMap.clear();
290
    }
291
292
    @EventHandler
293
    private void onGameLeave(GameLeftEvent event) {
294
        loginPacket = true;
295
    }
296
297
    @EventHandler
298
    private void onReceivePacket(PacketEvent.Receive event) {
299
        switch (event.packet) {
300
            case
301
                ClientboundPlayerInfoUpdatePacket packet when joinsLeavesMode.get().equals(JoinLeaveModes.Both) || joinsLeavesMode.get().equals(JoinLeaveModes.Joins) -> {
302
                if (loginPacket) {
303
                    loginPacket = false;
304
                    return;
305
                }
306
307
                if (packet.actions().contains(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER)) {
308
                    createJoinNotifications(packet);
309
                }
310
            }
311
            case
312
                ClientboundPlayerInfoRemovePacket packet when joinsLeavesMode.get().equals(JoinLeaveModes.Both) || joinsLeavesMode.get().equals(JoinLeaveModes.Leaves) ->
313
                createLeaveNotification(packet);
314
315
            case
316
                ClientboundEntityEventPacket packet when totemPops.get() && packet.getEventId() == EntityEvent.PROTECTED_FROM_DEATH && packet.getEntity(mc.level) instanceof Player entity -> {
317
                if ((entity.equals(mc.player) && totemsIgnoreOwn.get())
318
                    || (Friends.get().isFriend(entity) && totemsIgnoreOthers.get())
319
                    || (!Friends.get().isFriend(entity) && totemsIgnoreFriends.get())
320
                ) return;
321
322
                synchronized (totemPopMap) {
323
                    int pops = totemPopMap.getOrDefault(entity.getUUID(), 0);
324
                    totemPopMap.put(entity.getUUID(), ++pops);
325
326
                    double distance = PlayerUtils.distanceTo(entity);
327
                    if (totemsDistanceCheck.get() && distance > totemsDistance.get()) return;
328
329
                    ChatUtils.sendMsg(getChatId(entity), ChatFormatting.GRAY, "(highlight)%s (default)popped (highlight)%d (default)%s.", entity.getName().getString(), pops, pops == 1 ? "totem" : "totems");
330
                }
331
            }
332
            default -> {
333
            }
334
        }
335
    }
336
337
    @EventHandler
338
    private void onTick(TickEvent.Post event) {
339
        if (joinsLeavesMode.get() != JoinLeaveModes.None) {
340
            timer++;
341
            while (timer >= notificationDelay.get() && !messageQueue.isEmpty()) {
342
                timer = 0;
343
                if (simpleNotifications.get()) {
344
                    mc.player.sendSystemMessage(messageQueue.removeFirst());
345
                } else {
346
                    ChatUtils.sendMsg(messageQueue.removeFirst());
347
                }
348
            }
349
        }
350
351
        if (!totemPops.get()) return;
352
        synchronized (totemPopMap) {
353
            for (Player player : mc.level.players()) {
354
                if (!totemPopMap.containsKey(player.getUUID())) continue;
355
356
                if (player.deathTime > 0 || player.getHealth() <= 0) {
357
                    int pops = totemPopMap.removeInt(player.getUUID());
358
359
                    ChatUtils.sendMsg(getChatId(player), ChatFormatting.GRAY, "(highlight)%s (default)died after popping (highlight)%d (default)%s.", player.getName().getString(), pops, pops == 1 ? "totem" : "totems");
360
                    chatIdMap.removeInt(player.getUUID());
361
                }
362
            }
363
        }
364
    }
365
366
    private int getChatId(Entity entity) {
367
        return chatIdMap.computeIfAbsent(entity.getUUID(), _ -> random.nextInt());
368
    }
369
370
    private void createJoinNotifications(ClientboundPlayerInfoUpdatePacket packet) {
371
        for (ClientboundPlayerInfoUpdatePacket.Entry entry : packet.newEntries()) {
372
            if (entry.profile() == null) continue;
373
374
            if (simpleNotifications.get()) {
375
                messageQueue.addLast(Component.literal(
376
                    ChatFormatting.GRAY + "["
377
                        + ChatFormatting.GREEN + "+"
378
                        + ChatFormatting.GRAY + "] "
379
                        + entry.profile().name()
380
                ));
381
            } else {
382
                messageQueue.addLast(Component.literal(
383
                    ChatFormatting.WHITE
384
                        + entry.profile().name()
385
                        + ChatFormatting.GRAY + " joined."
386
                ));
387
            }
388
        }
389
    }
390
391
    private void createLeaveNotification(ClientboundPlayerInfoRemovePacket packet) {
392
        if (mc.getConnection() == null) return;
393
394
        for (UUID id : packet.profileIds()) {
395
            PlayerInfo toRemove = mc.getConnection().getPlayerInfo(id);
396
            if (toRemove == null) continue;
397
398
            if (simpleNotifications.get()) {
399
                messageQueue.addLast(Component.literal(
400
                    ChatFormatting.GRAY + "["
401
                        + ChatFormatting.RED + "-"
402
                        + ChatFormatting.GRAY + "] "
403
                        + toRemove.getProfile().name()
404
                ));
405
            } else {
406
                messageQueue.addLast(Component.literal(
407
                    ChatFormatting.WHITE
408
                        + toRemove.getProfile().name()
409
                        + ChatFormatting.GRAY + " left."
410
                ));
411
            }
412
        }
413
    }
414
415
    public enum Event {
416
        Spawn,
417
        Despawn,
418
        Both
419
    }
420
421
    public enum JoinLeaveModes {
422
        None, Joins, Leaves, Both
423
    }
424
}
425
OfflineClientMISCsrc/main/java/com/jellypudding/offlineclient/modules/misc/Notifier.javaJava · 478 lines · 18.4 KB

Chat messages when players come and go and when totems pop.

SettingsVisual rangeReportEntitiesTotem popsOwn totemsIgnore othersDistance checkPlayer radiusPearlsOwn pearlsJoins and leavesNotification delaySimple notificationsIgnore friendsSound
Notifier.javaJava · Minecraft 26.2 · 478 lines · 18.4 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.misc;
2
3
import com.jellypudding.offlineclient.OfflineClient;
4
import com.jellypudding.offlineclient.event.Subscribe;
5
import com.jellypudding.offlineclient.event.events.EntityAddedEvent;
6
import com.jellypudding.offlineclient.event.events.PacketReceiveEvent;
7
import com.jellypudding.offlineclient.event.events.TickEvent;
8
import com.jellypudding.offlineclient.module.Category;
9
import com.jellypudding.offlineclient.module.Module;
10
import com.jellypudding.offlineclient.setting.BoolSetting;
11
import com.jellypudding.offlineclient.setting.EnumSetting;
12
import com.jellypudding.offlineclient.setting.NumberSetting;
13
import com.jellypudding.offlineclient.setting.RegistryListSetting;
14
import com.jellypudding.offlineclient.util.ChatUtil;
15
import net.minecraft.client.multiplayer.ClientLevel;
16
import net.minecraft.client.multiplayer.chat.GuiMessage;
17
import net.minecraft.client.resources.sounds.SimpleSoundInstance;
18
import net.minecraft.core.registries.BuiltInRegistries;
19
import net.minecraft.network.chat.Component;
20
import net.minecraft.network.protocol.game.ClientboundEntityEventPacket;
21
import net.minecraft.network.protocol.game.ClientboundPlayerInfoRemovePacket;
22
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket;
23
import net.minecraft.sounds.SoundEvents;
24
import net.minecraft.world.entity.Entity;
25
import net.minecraft.world.entity.EntityEvent;
26
import net.minecraft.world.entity.EntityType;
27
import net.minecraft.world.entity.EntityTypes;
28
import net.minecraft.world.entity.player.Player;
29
import net.minecraft.world.entity.projectile.throwableitemprojectile.ThrownEnderpearl;
30
import net.minecraft.world.phys.Vec3;
31
32
import java.util.ArrayDeque;
33
import java.util.Deque;
34
import java.util.Iterator;
35
import java.util.LinkedHashMap;
36
import java.util.List;
37
import java.util.Map;
38
import java.util.Queue;
39
import java.util.UUID;
40
import java.util.concurrent.LinkedBlockingQueue;
41
42
public final class Notifier extends Module {
43
44
    private enum Report {
45
        SPAWN,
46
        DESPAWN,
47
        BOTH
48
    }
49
50
    private enum JoinsLeaves {
51
        NONE,
52
        JOINS,
53
        LEAVES,
54
        BOTH
55
    }
56
57
    private enum Kind {
58
        TOTEM,
59
        JOIN,
60
        LEAVE
61
    }
62
63
    private record Pending(Kind kind, int entityId, String name) {
64
    }
65
66
    // What we last knew about one entity we are watching.
67
    private record Watched(String name, EntityType<?> type, Vec3 pos) {
68
    }
69
70
    // Where a pearl started and the last place we saw it.
71
    private record Pearl(String owner, boolean own, Vec3 start, Vec3 pos) {
72
    }
73
74
    private static final String UNKNOWN_OWNER = "Someone";
75
76
    // Ticks after joining during which entities already nearby stay quiet.
77
    private static final int JOIN_GRACE_TICKS = 40;
78
79
    // Packets held whilst the game thread is busy. Anything past this is dropped.
80
    private static final int MAX_PENDING = 4096;
81
82
    private static final int MAX_TRACKED = 512;
83
84
    // How far back a totem line is looked for when it is replaced.
85
    private static final int REPLACE_DEPTH = 64;
86
87
    private final BoolSetting visualRange = new BoolSetting("Visual range",
88
        "Say when something enters or leaves your render distance.", true);
89
    private final EnumSetting<Report> report = new EnumSetting<>("Report",
90
        "Which half of visual range is reported.", Report.BOTH)
91
        .describe(Report.SPAWN, "Only arrivals.")
92
        .describe(Report.DESPAWN, "Only departures.")
93
        .describe(Report.BOTH, "Arrivals and departures.")
94
        .under(visualRange);
95
    private final RegistryListSetting<EntityType<?>> entities = new RegistryListSetting<>("Entities",
96
        "Kinds of entity visual range watches.", BuiltInRegistries.ENTITY_TYPE,
97
        List.of(EntityTypes.PLAYER))
98
        .under(visualRange);
99
100
    private final BoolSetting totemPops = new BoolSetting("Totem pops",
101
        "Says when a player pops a totem and how many they have popped.", true);
102
    private final BoolSetting ownTotems = new BoolSetting("Own totems",
103
        "Also count your own totem pops.", false)
104
        .under(totemPops);
105
    private final BoolSetting ignoreOthers = new BoolSetting("Ignore others",
106
        "Only report totem pops from friends.", false)
107
        .under(totemPops);
108
    private final BoolSetting distanceCheck = new BoolSetting("Distance check",
109
        "Only report totem pops from players close to you.", false)
110
        .under(totemPops);
111
    private final NumberSetting playerRadius = new NumberSetting("Player radius",
112
        "How far away a totem pop can be and still be reported.", 30, 1, 50, 1, " blocks")
113
        .min(1).max(100)
114
        .under(distanceCheck);
115
116
    private final BoolSetting pearls = new BoolSetting("Pearls",
117
        "Says where every thrown ender pearl lands.", true);
118
    private final BoolSetting ownPearls = new BoolSetting("Own pearls",
119
        "Also report your own pearls.", true)
120
        .under(pearls);
121
122
    private final EnumSetting<JoinsLeaves> joinsLeaves = new EnumSetting<>("Joins and leaves",
123
        "Say when a player joins or leaves the server.", JoinsLeaves.NONE)
124
        .describe(JoinsLeaves.NONE, "Say nothing.")
125
        .describe(JoinsLeaves.JOINS, "Only joins.")
126
        .describe(JoinsLeaves.LEAVES, "Only leaves.")
127
        .describe(JoinsLeaves.BOTH, "Joins and leaves.");
128
    private final NumberSetting notificationDelay = new NumberSetting("Notification delay",
129
        "Ticks between one join or leave line and the next.", 0, 0, 100, 1, " ticks")
130
        .min(0).max(1000)
131
        .under(joinsLeaves, JoinsLeaves.JOINS, JoinsLeaves.LEAVES, JoinsLeaves.BOTH);
132
    private final BoolSetting simpleNotifications = new BoolSetting("Simple notifications",
133
        "Short join and leave lines with no client prefix.", true)
134
        .under(joinsLeaves, JoinsLeaves.JOINS, JoinsLeaves.LEAVES, JoinsLeaves.BOTH);
135
136
    private final BoolSetting ignoreFriends = new BoolSetting("Ignore friends",
137
        "Stay quiet about people on your friend list.", false);
138
    private final BoolSetting sound = new BoolSetting("Sound",
139
        "Play a soft ping with every message.", false);
140
141
    private final Queue<Pending> queue = new LinkedBlockingQueue<>(MAX_PENDING);
142
    private final Deque<String> joinLeaveQueue = new ArrayDeque<>();
143
    // Entity id to what we last knew about it.
144
    private final Map<Integer, Watched> watched = bounded(MAX_TRACKED);
145
    private final Map<Integer, Pearl> flying = bounded(MAX_TRACKED);
146
    // Totem pops per player since their last death.
147
    private final Map<UUID, Integer> pops = bounded(MAX_TRACKED);
148
    // The last totem line printed for a player. The next one replaces it.
149
    private final Map<UUID, String> popLines = bounded(MAX_TRACKED);
150
    // Names from the tab list. The netty thread must not read the real one.
151
    private final Map<UUID, String> tabNames = bounded(MAX_TRACKED);
152
    private ClientLevel lastLevel;
153
    private boolean firstTabPacket = true;
154
    private int delayTimer;
155
156
    // The client removes some entities without a packet.
157
    // None of these maps can be trusted to empty itself.
158
    private static <K, V> Map<K, V> bounded(int max) {
159
        return new LinkedHashMap<K, V>() {
160
            @Override
161
            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
162
                return size() > max;
163
            }
164
        };
165
    }
166
167
    public Notifier() {
168
        super("Notifier", "Chat messages when players come and go and when totems pop.", Category.MISC);
169
        addSettings(visualRange, report, entities, totemPops, ownTotems, ignoreOthers,
170
            distanceCheck, playerRadius, pearls, ownPearls, joinsLeaves, notificationDelay,
171
            simpleNotifications, ignoreFriends, sound);
172
        searchTags("visual range", "totem pop", "alert", "pearl", "join", "leave");
173
    }
174
175
    @Override
176
    protected void onEnable() {
177
        reset();
178
    }
179
180
    @Override
181
    protected void onDisable() {
182
        reset();
183
    }
184
185
    private void reset() {
186
        queue.clear();
187
        joinLeaveQueue.clear();
188
        watched.clear();
189
        flying.clear();
190
        pops.clear();
191
        popLines.clear();
192
        tabNames.clear();
193
        lastLevel = null;
194
        firstTabPacket = true;
195
        delayTimer = 0;
196
    }
197
198
    // Fired on the netty thread. The level must not be read here.
199
    @Subscribe
200
    private void onPacketReceive(PacketReceiveEvent event) {
201
        switch (event.getPacket()) {
202
            case ClientboundPlayerInfoUpdatePacket packet -> onTabUpdate(packet);
203
            case ClientboundPlayerInfoRemovePacket packet -> onTabRemove(packet);
204
            case ClientboundEntityEventPacket packet when packet.getEventId() == EntityEvent.PROTECTED_FROM_DEATH ->
205
                queue.offer(new Pending(Kind.TOTEM, packet.entityId, null));
206
            default -> {
207
            }
208
        }
209
    }
210
211
    // The first packet after login lists everyone already on the server.
212
    private void onTabUpdate(ClientboundPlayerInfoUpdatePacket packet) {
213
        if (!packet.actions().contains(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER)) {
214
            return;
215
        }
216
        boolean first = firstTabPacket;
217
        firstTabPacket = false;
218
        for (ClientboundPlayerInfoUpdatePacket.Entry entry : packet.newEntries()) {
219
            if (entry.profile() == null) {
220
                continue;
221
            }
222
            tabNames.put(entry.profileId(), entry.profile().name());
223
            if (!first && wants(JoinsLeaves.JOINS)) {
224
                queue.offer(new Pending(Kind.JOIN, 0, entry.profile().name()));
225
            }
226
        }
227
    }
228
229
    private void onTabRemove(ClientboundPlayerInfoRemovePacket packet) {
230
        for (UUID id : packet.profileIds()) {
231
            String name = tabNames.remove(id);
232
            if (name != null && wants(JoinsLeaves.LEAVES)) {
233
                queue.offer(new Pending(Kind.LEAVE, 0, name));
234
            }
235
        }
236
    }
237
238
    private boolean wants(JoinsLeaves half) {
239
        return joinsLeaves.is(half) || joinsLeaves.is(JoinsLeaves.BOTH);
240
    }
241
242
    @Subscribe
243
    private void onEntityAdded(EntityAddedEvent event) {
244
        Entity entity = event.getEntity();
245
        if (entity == mc.player) {
246
            return;
247
        }
248
        if (pearls.isOn() && entity instanceof ThrownEnderpearl pearl) {
249
            flying.put(pearl.getId(), new Pearl(ownerName(pearl), pearl.getOwner() == mc.player,
250
                pearl.position(), pearl.position()));
251
        }
252
        if (!entities.contains(entity.getType())) {
253
            return;
254
        }
255
        watched.put(entity.getId(), new Watched(entity.getName().getString(),
256
            entity.getType(), entity.position()));
257
        // Everything already nearby shows up in one burst right after joining.
258
        if (mc.player.tickCount < JOIN_GRACE_TICKS) {
259
            return;
260
        }
261
        if (visualRange.isOn() && !report.is(Report.DESPAWN)) {
262
            announce(entity.getName().getString(), entity.getType(), entity.position(), true);
263
        }
264
    }
265
266
    private static String ownerName(ThrownEnderpearl pearl) {
267
        Entity owner = pearl.getOwner();
268
        return owner == null ? UNKNOWN_OWNER : owner.getName().getString();
269
    }
270
271
    @Subscribe
272
    private void onTick(TickEvent event) {
273
        if (!inGame()) {
274
            return;
275
        }
276
        if (mc.level != lastLevel) {
277
            // A new dimension resends every entity. Queued ids belong to the old one.
278
            queue.clear();
279
            watched.clear();
280
            flying.clear();
281
            pops.clear();
282
            popLines.clear();
283
            lastLevel = mc.level;
284
        }
285
        Pending pending;
286
        while ((pending = queue.poll()) != null) {
287
            switch (pending.kind()) {
288
                case TOTEM -> handleTotem(pending);
289
                case JOIN -> joinLeaveQueue.addLast(joinLine(pending.name(), true));
290
                case LEAVE -> joinLeaveQueue.addLast(joinLine(pending.name(), false));
291
            }
292
        }
293
        drainJoinLeave();
294
        sweepWatched();
295
        sweepPearls();
296
        if (totemPops.isOn()) {
297
            checkDeaths();
298
        }
299
    }
300
301
    private void drainJoinLeave() {
302
        if (joinLeaveQueue.isEmpty()) {
303
            delayTimer = 0;
304
            return;
305
        }
306
        delayTimer++;
307
        while (delayTimer >= notificationDelay.getInt() && !joinLeaveQueue.isEmpty()) {
308
            delayTimer = 0;
309
            String line = joinLeaveQueue.removeFirst();
310
            if (simpleNotifications.isOn()) {
311
                mc.gui.hud.getChat().addClientSystemMessage(Component.literal(line));
312
            } else {
313
                say(line);
314
            }
315
        }
316
    }
317
318
    private String joinLine(String name, boolean joined) {
319
        if (simpleNotifications.isOn()) {
320
            return joined ? "§7[§a+§7] §f" + name : "§7[§c-§7] §f" + name;
321
        }
322
        return "§f" + name + (joined ? " §7joined." : " §7left.");
323
    }
324
325
    // The client drops entities without a packet. The level is the only truth.
326
    private void sweepWatched() {
327
        if (watched.isEmpty()) {
328
            return;
329
        }
330
        Iterator<Map.Entry<Integer, Watched>> it = watched.entrySet().iterator();
331
        while (it.hasNext()) {
332
            Map.Entry<Integer, Watched> entry = it.next();
333
            Entity entity = mc.level.getEntity(entry.getKey());
334
            if (entity != null && entity.isAlive()) {
335
                entry.setValue(new Watched(entry.getValue().name(), entry.getValue().type(),
336
                    entity.position()));
337
                continue;
338
            }
339
            it.remove();
340
            if (visualRange.isOn() && !report.is(Report.SPAWN)) {
341
                Watched gone = entry.getValue();
342
                announce(gone.name(), gone.type(), gone.pos(), false);
343
            }
344
        }
345
    }
346
347
    private void announce(String name, EntityType<?> type, Vec3 pos, boolean arrived) {
348
        if (type == EntityTypes.PLAYER) {
349
            if (skip(name)) {
350
                return;
351
            }
352
            say("§b" + name + " §7" + (arrived ? "entered" : "left")
353
                + " your render distance.");
354
            return;
355
        }
356
        say("§f" + type.getDescription().getString() + " §7has "
357
            + (arrived ? "spawned" : "despawned") + " at " + coords(pos) + "§7.");
358
    }
359
360
    private static String coords(Vec3 pos) {
361
        return "§b" + Math.round(pos.x) + " " + Math.round(pos.y) + " " + Math.round(pos.z);
362
    }
363
364
    private void sweepPearls() {
365
        if (flying.isEmpty()) {
366
            return;
367
        }
368
        Iterator<Map.Entry<Integer, Pearl>> it = flying.entrySet().iterator();
369
        while (it.hasNext()) {
370
            Map.Entry<Integer, Pearl> entry = it.next();
371
            Pearl pearl = entry.getValue();
372
            if (mc.level.getEntity(entry.getKey()) instanceof ThrownEnderpearl live) {
373
                String owner = pearl.owner().equals(UNKNOWN_OWNER) ? ownerName(live) : pearl.owner();
374
                entry.setValue(new Pearl(owner, live.getOwner() == mc.player,
375
                    pearl.start(), live.position()));
376
                continue;
377
            }
378
            it.remove();
379
            if (!pearls.isOn() || (pearl.own() && !ownPearls.isOn()) || skip(pearl.owner())) {
380
                continue;
381
            }
382
            long travelled = Math.round(pearl.start().distanceTo(pearl.pos()));
383
            long away = Math.round(mc.player.position().distanceTo(pearl.pos()));
384
            say("§b" + pearl.owner() + "§7's pearl landed at " + coords(pearl.pos())
385
                + " §7after §b" + travelled + " §7blocks and is §b"
386
                + away + " §7blocks away.");
387
        }
388
    }
389
390
    private void handleTotem(Pending pending) {
391
        if (!totemPops.isOn() || !(mc.level.getEntity(pending.entityId()) instanceof Player player)) {
392
            return;
393
        }
394
        if (player == mc.player && !ownTotems.isOn()) {
395
            return;
396
        }
397
        String name = player.getGameProfile().name();
398
        boolean friend = OfflineClient.INSTANCE.getFriendManager().isFriend(name);
399
        if (player != mc.player && ((ignoreFriends.isOn() && friend)
400
            || (ignoreOthers.isOn() && !friend))) {
401
            return;
402
        }
403
        int count = pops.merge(player.getUUID(), 1, Integer::sum);
404
        if (distanceCheck.isOn() && mc.player.distanceTo(player) > playerRadius.getValue()) {
405
            return;
406
        }
407
        replace(player.getUUID(), label(player) + "popped " + describe(count) + ".");
408
    }
409
410
    private void checkDeaths() {
411
        if (pops.isEmpty()) {
412
            return;
413
        }
414
        for (Player player : mc.level.players()) {
415
            Integer count = pops.get(player.getUUID());
416
            if (count == null || !(player.isDeadOrDying() || player.deathTime > 0)) {
417
                continue;
418
            }
419
            pops.remove(player.getUUID());
420
            replace(player.getUUID(), label(player) + "died after popping " + describe(count) + ".");
421
            popLines.remove(player.getUUID());
422
        }
423
    }
424
425
    private String label(Player player) {
426
        return player == mc.player ? "§7You " : "§b" + player.getGameProfile().name() + " §7";
427
    }
428
429
    private static String describe(int count) {
430
        return count == 1 ? "§b1 §7totem" : "§b" + count + " §7totems";
431
    }
432
433
    // One player running count updates in place rather than stacking lines.
434
    private void replace(UUID player, String message) {
435
        String previous = popLines.put(player, message);
436
        if (previous != null) {
437
            drop(previous);
438
        }
439
        say(message);
440
    }
441
442
    private static void drop(String message) {
443
        String wanted = plain(message);
444
        List<GuiMessage> all = mc.gui.hud.getChat().allMessages;
445
        int max = Math.min(REPLACE_DEPTH, all.size());
446
        for (int i = 0; i < max; i++) {
447
            if (plain(all.get(i).content().getString()).contains(wanted)) {
448
                all.remove(i);
449
                mc.gui.hud.getChat().refreshTrimmedMessages();
450
                return;
451
            }
452
        }
453
    }
454
455
    private static String plain(String text) {
456
        StringBuilder out = new StringBuilder(text.length());
457
        for (int i = 0; i < text.length(); i++) {
458
            if (text.charAt(i) == '§') {
459
                i++;
460
            } else {
461
                out.append(text.charAt(i));
462
            }
463
        }
464
        return out.toString();
465
    }
466
467
    private boolean skip(String name) {
468
        return ignoreFriends.isOn() && OfflineClient.INSTANCE.getFriendManager().isFriend(name);
469
    }
470
471
    private void say(String message) {
472
        ChatUtil.message(message);
473
        if (sound.isOn()) {
474
            mc.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.EXPERIENCE_ORB_PICKUP, 1f));
475
        }
476
    }
477
}
478
LiquidBounce (Kotlin)MISCsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/misc/ModuleNotifier.ktKotlin · 349 lines · 12.8 KB

Notifies you about all kinds of events.

SettingsJoinMessagesJoinMessageFormatLeaveMessagesLeaveMessageFormatGameModeMessagesGameModeMessageFormatItemConsumptionMessagesItemConsumptionMessageFormatHeldItemMessagesHeldItemMessageFormatHeldItemsTotemPopMessagesTotemPopMessageFormatUseNotification
ModuleNotifier.ktKotlin · Minecraft 26.2 · 349 lines · 12.8 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.misc
20
21
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
22
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap
23
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet
24
import net.ccbluex.liquidbounce.event.events.NotificationEvent
25
import net.ccbluex.liquidbounce.event.events.PacketEvent
26
import net.ccbluex.liquidbounce.event.events.PlayerTickEvent
27
import net.ccbluex.liquidbounce.event.events.WorldChangeEvent
28
import net.ccbluex.liquidbounce.event.handler
29
import net.ccbluex.liquidbounce.features.misc.FriendManager
30
import net.ccbluex.liquidbounce.features.module.ClientModule
31
import net.ccbluex.liquidbounce.features.module.ModuleCategories
32
import net.ccbluex.liquidbounce.features.module.modules.misc.antibot.ModuleAntiBot
33
import net.ccbluex.liquidbounce.utils.client.chat
34
import net.ccbluex.liquidbounce.utils.client.notification
35
import net.ccbluex.liquidbounce.utils.client.regular
36
import net.ccbluex.liquidbounce.utils.collection.itemSortedSetOf
37
import net.ccbluex.liquidbounce.utils.item.isConsumable
38
import net.ccbluex.liquidbounce.utils.network.isDeathProtection
39
import net.minecraft.client.player.RemotePlayer
40
import net.minecraft.network.protocol.common.ClientboundDisconnectPacket
41
import net.minecraft.network.protocol.game.ClientboundEntityEventPacket
42
import net.minecraft.network.protocol.game.ClientboundLoginPacket
43
import net.minecraft.network.protocol.game.ClientboundPlayerInfoRemovePacket
44
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket
45
import net.minecraft.world.InteractionHand
46
import net.minecraft.world.entity.player.Player
47
import net.minecraft.world.item.ItemStack
48
import net.minecraft.world.item.ItemUseAnimation
49
import net.minecraft.world.item.Items
50
import net.minecraft.world.level.GameType
51
import java.util.UUID
52
53
/**
54
 * Notifier module
55
 *
56
 * Notifies you about all kinds of events.
57
 */
58
object ModuleNotifier : ClientModule("Notifier", ModuleCategories.MISC) {
59
60
    init {
61
        doNotIncludeAlways()
62
    }
63
64
    private val joinMessages by boolean("JoinMessages", true)
65
    private val joinMessageFormat by text("JoinMessageFormat", "%s joined")
66
67
    private val leaveMessages by boolean("LeaveMessages", true)
68
    private val leaveMessageFormat by text("LeaveMessageFormat", "%s left")
69
70
    private val gameModeMessages by boolean("GameModeMessages", false)
71
    private val gameModeMessageFormat by text("GameModeMessageFormat", "%s changed their game mode to %s")
72
73
    private val itemConsumptionMessages by boolean("ItemConsumptionMessages", true)
74
    private val itemConsumptionMessageFormat by text("ItemConsumptionMessageFormat", $$"%1$s used %2$s")
75
76
    private val heldItemMessages by boolean("HeldItemMessages", false)
77
    private val heldItemMessageFormat by text("HeldItemMessageFormat", $$"%1$s holds %2$s x%3$s in %4$s")
78
    private val heldItems by items("HeldItems", itemSortedSetOf(Items.END_CRYSTAL, Items.ENCHANTED_GOLDEN_APPLE))
79
80
    private val totemPopMessages by boolean("TotemPopMessages", true)
81
    private val totemPopMessageFormat by text("TotemPopMessageFormat", $$"%1$s popped a totem %2$s times")
82
83
    private val useNotification by boolean("UseNotification", false)
84
85
    private val uuidNameCache = Object2ObjectOpenHashMap<UUID, String>()
86
    private val uuidGameModeCache = Object2ObjectOpenHashMap<UUID, GameType>()
87
    private val itemConsumptionCache = Object2ObjectOpenHashMap<UUID, ItemConsumptionState>()
88
    private val heldItemCache = Object2ObjectOpenHashMap<UUID, HeldItemState>()
89
    private val observedPlayers = ObjectOpenHashSet<UUID>()
90
    private val totemPopCounter = Object2IntOpenHashMap<UUID>()
91
92
    override fun onEnabled() {
93
        for (entry in network.onlinePlayers) {
94
            uuidNameCache[entry.profile.id] = entry.profile.name
95
            uuidGameModeCache[entry.profile.id] = entry.gameMode
96
        }
97
    }
98
99
    override fun onDisabled() {
100
        uuidNameCache.clear()
101
        uuidGameModeCache.clear()
102
        itemConsumptionCache.clear()
103
        heldItemCache.clear()
104
        observedPlayers.clear()
105
        totemPopCounter.clear()
106
    }
107
108
    val packetHandler = handler<PacketEvent> { event ->
109
        when (val packet = event.packet) {
110
            is ClientboundPlayerInfoUpdatePacket -> mc.execute {
111
                val actions = packet.actions()
112
                val entries = packet.entries()
113
114
                if (ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER in actions) {
115
                    for (entry in entries) {
116
                        handlePlayerAdd(entry)
117
                    }
118
                }
119
120
                if (ClientboundPlayerInfoUpdatePacket.Action.UPDATE_GAME_MODE in actions) {
121
                    val isInitializing = ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER in actions
122
123
                    for (entry in entries) {
124
                        handleGameModeUpdate(entry, isInitializing)
125
                    }
126
                }
127
            }
128
129
            is ClientboundPlayerInfoRemovePacket -> mc.execute {
130
                for (uuid in packet.profileIds) {
131
                    val profileName = uuidNameCache.remove(uuid)
132
                    uuidGameModeCache.remove(uuid)
133
134
                    if (profileName != null && profileName.length >= 2) {
135
                        if (leaveMessages) {
136
                            sendNotifierMessage(leaveMessageFormat.format(profileName))
137
                        }
138
                    }
139
                }
140
            }
141
142
            is ClientboundEntityEventPacket -> if (packet.isDeathProtection) {
143
                mc.execute {
144
                    val entity = packet.getEntity(world) as? Player ?: return@execute
145
                    if (entity === mc.player || FriendManager.isFriend(entity.name.string)) return@execute
146
147
                    totemPopCounter.addTo(entity.uuid, 1)
148
149
                    if (totemPopMessages) {
150
                        sendNotifierMessage(
151
                            totemPopMessageFormat.format(
152
                                entity.name.string,
153
                                totemPopCounter.getInt(entity.uuid)
154
                            )
155
                        )
156
                    }
157
                }
158
            }
159
160
            is ClientboundDisconnectPacket, is ClientboundLoginPacket -> mc.execute(totemPopCounter::clear)
161
        }
162
    }
163
164
    @Suppress("unused")
165
    private val tickHandler = handler<PlayerTickEvent> {
166
        observedPlayers.clear()
167
        for (player in world.players()) {
168
            if (player !is RemotePlayer || ModuleAntiBot.isBot(player)) {
169
                continue
170
            }
171
172
            observedPlayers.add(player.uuid)
173
174
            if (itemConsumptionMessages) {
175
                handleItemConsumption(player)
176
            }
177
178
            if (heldItemMessages) {
179
                handleHeldItems(player)
180
            }
181
        }
182
183
        if (itemConsumptionMessages) {
184
            itemConsumptionCache.keys.retainAll(observedPlayers)
185
        } else {
186
            itemConsumptionCache.clear()
187
        }
188
189
        if (heldItemMessages) {
190
            heldItemCache.keys.retainAll(observedPlayers)
191
        } else {
192
            heldItemCache.clear()
193
        }
194
    }
195
196
    @Suppress("unused")
197
    private val worldChangeHandler = handler<WorldChangeEvent> {
198
        itemConsumptionCache.clear()
199
        heldItemCache.clear()
200
        observedPlayers.clear()
201
    }
202
203
    private fun handlePlayerAdd(entry: ClientboundPlayerInfoUpdatePacket.Entry) {
204
        val profile = entry.profile ?: return
205
        val profileName = profile.name
206
207
        if (profileName == null || profileName.length <= 2) {
208
            return
209
        }
210
211
        uuidNameCache[profile.id] = profileName
212
213
        if (joinMessages) {
214
            sendNotifierMessage(joinMessageFormat.format(profileName))
215
        }
216
    }
217
218
    private fun handleGameModeUpdate(entry: ClientboundPlayerInfoUpdatePacket.Entry, isInitializing: Boolean) {
219
        val previousGameMode = uuidGameModeCache.put(entry.profileId, entry.gameMode)
220
221
        if (isInitializing || previousGameMode == null || previousGameMode == entry.gameMode || !gameModeMessages) {
222
            return
223
        }
224
225
        val profileName = uuidNameCache[entry.profileId] ?: return
226
        sendNotifierMessage(gameModeMessageFormat.format(profileName, entry.gameMode))
227
    }
228
229
    private fun handleItemConsumption(player: RemotePlayer) {
230
        if (!player.isUsingItem) {
231
            val state = itemConsumptionCache.remove(player.uuid)
232
233
            if (state != null && state.isComplete) {
234
                sendNotifierMessage(
235
                    itemConsumptionMessageFormat.format(
236
                        player.gameProfile.name,
237
                        state.itemStack.hoverName.string
238
                    )
239
                )
240
            }
241
242
            return
243
        }
244
245
        val state = itemConsumptionCache[player.uuid]
246
        val useItem = player.useItem
247
        if (!useItem.isTrackedConsumable()) {
248
            itemConsumptionCache.remove(player.uuid)
249
            return
250
        }
251
252
        if (state == null || !ItemStack.isSameItemSameComponents(state.itemStack, useItem)) {
253
            itemConsumptionCache[player.uuid] = ItemConsumptionState(
254
                useItem.copy(),
255
                useItem.getUseDuration(player),
256
                player.ticksUsingItem
257
            )
258
            return
259
        }
260
261
        state.lastTicksUsingItem = maxOf(state.lastTicksUsingItem, player.ticksUsingItem)
262
    }
263
264
    private fun handleHeldItems(player: RemotePlayer) {
265
        val currentMainHand = player.mainHandItem.takeIf { it.isTrackedHeldItem() }
266
        val currentOffHand = player.offhandItem.takeIf { it.isTrackedHeldItem() }
267
268
        val currentState = HeldItemState(currentMainHand, currentOffHand)
269
        val previousState = heldItemCache[player.uuid]
270
271
        if (currentState.isEmpty) {
272
            heldItemCache.remove(player.uuid)
273
            return
274
        }
275
276
        if (previousState != null) {
277
            if (currentMainHand != null && !currentMainHand.isSameHeldItem(previousState.mainHand)) {
278
                sendHeldItemMessage(player, currentMainHand, InteractionHand.MAIN_HAND)
279
            }
280
            if (currentOffHand != null && !currentOffHand.isSameHeldItem(previousState.offHand)) {
281
                sendHeldItemMessage(player, currentOffHand, InteractionHand.OFF_HAND)
282
            }
283
        } else {
284
            if (currentMainHand != null) {
285
                sendHeldItemMessage(player, currentMainHand, InteractionHand.MAIN_HAND)
286
            }
287
            if (currentOffHand != null) {
288
                sendHeldItemMessage(player, currentOffHand, InteractionHand.OFF_HAND)
289
            }
290
        }
291
292
        heldItemCache[player.uuid] = currentState
293
    }
294
295
    private fun ItemStack.isTrackedConsumable(): Boolean {
296
        if (!isConsumable) {
297
            return false
298
        }
299
300
        val animation = useAnimation
301
        return animation == ItemUseAnimation.EAT || animation == ItemUseAnimation.DRINK
302
    }
303
304
    private fun ItemStack.isTrackedHeldItem(): Boolean {
305
        return !isEmpty && item in heldItems
306
    }
307
308
    private fun ItemStack.isSameHeldItem(other: ItemStack?): Boolean {
309
        return other != null && ItemStack.isSameItemSameComponents(this, other) && count == other.count
310
    }
311
312
    private fun sendHeldItemMessage(player: RemotePlayer, itemStack: ItemStack, hand: InteractionHand) {
313
        sendNotifierMessage(
314
            heldItemMessageFormat.format(
315
                player.gameProfile.name,
316
                itemStack.hoverName.string,
317
                itemStack.count,
318
                hand
319
            )
320
        )
321
    }
322
323
    private fun sendNotifierMessage(message: String) {
324
        if (useNotification) {
325
            notification(this.name, message, NotificationEvent.Severity.INFO)
326
        } else {
327
            chat(regular(message))
328
        }
329
    }
330
331
    private data class ItemConsumptionState(
332
        val itemStack: ItemStack,
333
        val useDuration: Int,
334
        var lastTicksUsingItem: Int,
335
    ) {
336
        val isComplete: Boolean
337
            get() = useDuration > 0 && lastTicksUsingItem >= useDuration - 1
338
    }
339
340
    private data class HeldItemState(
341
        val mainHand: ItemStack?,
342
        val offHand: ItemStack?,
343
    ) {
344
        val isEmpty: Boolean
345
            get() = mainHand == null && offHand == null
346
    }
347
348
}
349