notebot module

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

3 implementationsMiscMISCFUN

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/Notebot.javaJava · 983 lines · 33.7 KB

Plays noteblock nicely

Settingstick-delayconcurrent-tune-blocksmodeinstrument-detect-modepolyphonicauto-rotateauto-playround-out-of-rangeswing-armcheck-noteblocks-again-delayrender-textrender-boxesshape-modeuntuned-side-coloruntuned-line-colortuned-side-colortuned-line-colorhit-side-colorhit-line-colorscanned-noteblock-side-colorscanned-noteblock-line-colornote-text-scaleshow-scanned-noteblocks
Notebot.javaJava · Minecraft 26.2 · 983 lines · 33.7 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 com.google.common.collect.Multimap;
9
import com.google.common.collect.MultimapBuilder;
10
import meteordevelopment.meteorclient.MeteorClient;
11
import meteordevelopment.meteorclient.events.render.Render2DEvent;
12
import meteordevelopment.meteorclient.events.render.Render3DEvent;
13
import meteordevelopment.meteorclient.events.world.TickEvent;
14
import meteordevelopment.meteorclient.gui.GuiTheme;
15
import meteordevelopment.meteorclient.gui.widgets.WLabel;
16
import meteordevelopment.meteorclient.gui.widgets.WWidget;
17
import meteordevelopment.meteorclient.gui.widgets.containers.WTable;
18
import meteordevelopment.meteorclient.gui.widgets.pressable.WButton;
19
import meteordevelopment.meteorclient.renderer.ShapeMode;
20
import meteordevelopment.meteorclient.renderer.text.TextRenderer;
21
import meteordevelopment.meteorclient.settings.*;
22
import meteordevelopment.meteorclient.systems.modules.Categories;
23
import meteordevelopment.meteorclient.systems.modules.Module;
24
import meteordevelopment.meteorclient.utils.notebot.NotebotUtils;
25
import meteordevelopment.meteorclient.utils.notebot.decoder.SongDecoder;
26
import meteordevelopment.meteorclient.utils.notebot.decoder.SongDecoders;
27
import meteordevelopment.meteorclient.utils.notebot.instrumentdetect.InstrumentDetectMode;
28
import meteordevelopment.meteorclient.utils.notebot.song.Note;
29
import meteordevelopment.meteorclient.utils.notebot.song.Song;
30
import meteordevelopment.meteorclient.utils.player.Rotations;
31
import meteordevelopment.meteorclient.utils.render.NametagUtils;
32
import meteordevelopment.meteorclient.utils.render.color.Color;
33
import meteordevelopment.meteorclient.utils.render.color.SettingColor;
34
import meteordevelopment.orbit.EventHandler;
35
import net.minecraft.core.BlockPos;
36
import net.minecraft.core.Direction;
37
import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket;
38
import net.minecraft.network.protocol.game.ServerboundUseItemOnPacket;
39
import net.minecraft.sounds.SoundEvents;
40
import net.minecraft.world.InteractionHand;
41
import net.minecraft.world.level.block.Blocks;
42
import net.minecraft.world.level.block.NoteBlock;
43
import net.minecraft.world.level.block.state.BlockState;
44
import net.minecraft.world.level.block.state.properties.NoteBlockInstrument;
45
import net.minecraft.world.phys.BlockHitResult;
46
import net.minecraft.world.phys.Vec3;
47
import org.apache.commons.io.FilenameUtils;
48
import org.joml.Vector3d;
49
import org.jspecify.annotations.NonNull;
50
import org.jspecify.annotations.Nullable;
51
52
import java.io.File;
53
import java.util.*;
54
import java.util.concurrent.CancellationException;
55
import java.util.concurrent.CompletableFuture;
56
import java.util.concurrent.ThreadLocalRandom;
57
import java.util.concurrent.TimeUnit;
58
import java.util.stream.Collectors;
59
60
61
public class Notebot extends Module {
62
63
    private final SettingGroup sgGeneral = settings.getDefaultGroup();
64
    private final SettingGroup sgNoteMap = settings.createGroup("Note Map", false);
65
    private final SettingGroup sgRender = settings.createGroup("Render", true);
66
67
    public final Setting<Integer> tickDelay = sgGeneral.add(new IntSetting.Builder()
68
        .name("tick-delay")
69
        .description("The delay when loading a song.")
70
        .defaultValue(1)
71
        .sliderRange(1, 20)
72
        .min(1)
73
        .build()
74
    );
75
76
    public final Setting<Integer> concurrentTuneBlocks = sgGeneral.add(new IntSetting.Builder()
77
        .name("concurrent-tune-blocks")
78
        .description("How many noteblocks can be tuned at the same time. On Paper it is recommended to set it to 1 to avoid bugs.")
79
        .defaultValue(1)
80
        .min(1)
81
        .sliderRange(1, 20)
82
        .build()
83
    );
84
85
    public final Setting<NotebotUtils.NotebotMode> mode = sgGeneral.add(new EnumSetting.Builder<NotebotUtils.NotebotMode>()
86
        .name("mode")
87
        .description("Select mode of notebot")
88
        .defaultValue(NotebotUtils.NotebotMode.ExactInstruments)
89
        .build()
90
    );
91
92
    public final Setting<InstrumentDetectMode> instrumentDetectMode = sgGeneral.add(new EnumSetting.Builder<InstrumentDetectMode>()
93
        .name("instrument-detect-mode")
94
        .description("Select an instrument detect mode. Can be useful when server has a plugin that modifies noteblock state (e.g ItemsAdder) but noteblock can still play the right note")
95
        .defaultValue(InstrumentDetectMode.BlockState)
96
        .build()
97
    );
98
99
    public final Setting<Boolean> polyphonic = sgGeneral.add(new BoolSetting.Builder()
100
        .name("polyphonic")
101
        .description("Whether or not to allow multiple notes to be played at the same time")
102
        .defaultValue(true)
103
        .build()
104
    );
105
106
    public final Setting<Boolean> autoRotate = sgGeneral.add(new BoolSetting.Builder()
107
        .name("auto-rotate")
108
        .description("Should client look at note block when it wants to hit it")
109
        .defaultValue(true)
110
        .build()
111
    );
112
113
    public final Setting<Boolean> autoPlay = sgGeneral.add(new BoolSetting.Builder()
114
        .name("auto-play")
115
        .description("Auto plays random songs")
116
        .defaultValue(false)
117
        .build()
118
    );
119
120
    public final Setting<Boolean> roundOutOfRange = sgGeneral.add(new BoolSetting.Builder()
121
        .name("round-out-of-range")
122
        .description("Rounds out of range notes")
123
        .defaultValue(false)
124
        .build()
125
    );
126
127
    public final Setting<Boolean> swingArm = sgGeneral.add(new BoolSetting.Builder()
128
        .name("swing-arm")
129
        .description("Should swing arm on hit")
130
        .defaultValue(true)
131
        .build()
132
    );
133
134
    public final Setting<Integer> checkNoteblocksAgainDelay = sgGeneral.add(new IntSetting.Builder()
135
        .name("check-noteblocks-again-delay")
136
        .description("How much delay should be between end of tuning and checking again")
137
        .defaultValue(10)
138
        .min(1)
139
        .sliderRange(1, 20)
140
        .build()
141
    );
142
143
    public final Setting<Boolean> renderText = sgRender.add(new BoolSetting.Builder()
144
        .name("render-text")
145
        .description("Whether or not to render the text above noteblocks.")
146
        .defaultValue(true)
147
        .build()
148
    );
149
150
    public final Setting<Boolean> renderBoxes = sgRender.add(new BoolSetting.Builder()
151
        .name("render-boxes")
152
        .description("Whether or not to render the outline around the noteblocks.")
153
        .defaultValue(true)
154
        .build()
155
    );
156
157
    public final Setting<ShapeMode> shapeMode = sgRender.add(new EnumSetting.Builder<ShapeMode>()
158
        .name("shape-mode")
159
        .description("How the shapes are rendered.")
160
        .defaultValue(ShapeMode.Both)
161
        .build()
162
    );
163
164
    public final Setting<SettingColor> untunedSideColor = sgRender.add(new ColorSetting.Builder()
165
        .name("untuned-side-color")
166
        .description("The color of the sides of the untuned blocks being rendered.")
167
        .defaultValue(new SettingColor(204, 0, 0, 10))
168
        .build()
169
    );
170
171
    public final Setting<SettingColor> untunedLineColor = sgRender.add(new ColorSetting.Builder()
172
        .name("untuned-line-color")
173
        .description("The color of the lines of the untuned blocks being rendered.")
174
        .defaultValue(new SettingColor(204, 0, 0, 255))
175
        .build()
176
    );
177
178
    public final Setting<SettingColor> tunedSideColor = sgRender.add(new ColorSetting.Builder()
179
        .name("tuned-side-color")
180
        .description("The color of the sides of the tuned blocks being rendered.")
181
        .defaultValue(new SettingColor(0, 204, 0, 10))
182
        .build()
183
    );
184
185
    public final Setting<SettingColor> tunedLineColor = sgRender.add(new ColorSetting.Builder()
186
        .name("tuned-line-color")
187
        .description("The color of the lines of the tuned blocks being rendered.")
188
        .defaultValue(new SettingColor(0, 204, 0, 255))
189
        .build()
190
    );
191
192
    public final Setting<SettingColor> tuneHitSideColor = sgRender.add(new ColorSetting.Builder()
193
        .name("hit-side-color")
194
        .description("The color of the sides being rendered on noteblock tune hit.")
195
        .defaultValue(new SettingColor(255, 153, 0, 10))
196
        .build()
197
    );
198
199
    private final Setting<SettingColor> tuneHitLineColor = sgRender.add(new ColorSetting.Builder()
200
        .name("hit-line-color")
201
        .description("The color of the lines being rendered on noteblock tune hit.")
202
        .defaultValue(new SettingColor(255, 153, 0, 255))
203
        .build()
204
    );
205
206
    public final Setting<SettingColor> scannedNoteblockSideColor = sgRender.add(new ColorSetting.Builder()
207
        .name("scanned-noteblock-side-color")
208
        .description("The color of the sides of the scanned noteblocks being rendered.")
209
        .defaultValue(new SettingColor(255, 255, 0, 30))
210
        .build()
211
    );
212
213
    private final Setting<SettingColor> scannedNoteblockLineColor = sgRender.add(new ColorSetting.Builder()
214
        .name("scanned-noteblock-line-color")
215
        .description("The color of the lines of the scanned noteblocks being rendered.")
216
        .defaultValue(new SettingColor(255, 255, 0, 255))
217
        .build()
218
    );
219
220
    public final Setting<Double> noteTextScale = sgRender.add(new DoubleSetting.Builder()
221
        .name("note-text-scale")
222
        .description("The scale.")
223
        .defaultValue(1.5)
224
        .min(0)
225
        .build()
226
    );
227
228
    public final Setting<Boolean> showScannedNoteblocks = sgRender.add(new BoolSetting.Builder()
229
        .name("show-scanned-noteblocks")
230
        .description("Show scanned Noteblocks")
231
        .defaultValue(false)
232
        .build()
233
    );
234
235
    private CompletableFuture<Song> loadingSongFuture = null;
236
237
    private Song song; // Loaded song
238
    private final Map<Note, BlockPos> noteBlockPositions = new HashMap<>(); // Currently used noteblocks by the song
239
    private final Multimap<Note, BlockPos> scannedNoteblocks = MultimapBuilder.linkedHashKeys().arrayListValues().build(); // Found noteblocks
240
    private final Set<BlockPos> clickedBlocks = new HashSet<>();
241
    private Stage stage = Stage.None;
242
    private PlayingMode playingMode = PlayingMode.None;
243
    private boolean isPlaying = false;
244
    private int currentTick = 0;
245
    private int ticks = 0;
246
    private WLabel status;
247
248
    private boolean anyNoteblockTuned = false;
249
    private final Map<BlockPos, Integer> tuneHits = new HashMap<>(); // noteblock -> target hits number
250
251
    private int waitTicks = -1;
252
253
254
    public Notebot() {
255
        super(Categories.Misc, "notebot", "Plays noteblock nicely");
256
257
        for (NoteBlockInstrument inst : NoteBlockInstrument.values()) {
258
            NotebotUtils.OptionalInstrument optionalInstrument = NotebotUtils.OptionalInstrument.fromMinecraftInstrument(inst);
259
            if (optionalInstrument != null) {
260
                sgNoteMap.add(new EnumSetting.Builder<NotebotUtils.OptionalInstrument>()
261
                    .name(beautifyText(inst.name()))
262
                    .defaultValue(optionalInstrument)
263
                    .visible(() -> mode.get() == NotebotUtils.NotebotMode.ExactInstruments)
264
                    .build()
265
                );
266
            }
267
        }
268
    }
269
270
    @Override
271
    public String getInfoString() {
272
        if (stage == Stage.None) {
273
            return "None";
274
        } else {
275
            return playingMode.toString() + " | " + stage.toString();
276
        }
277
    }
278
279
    @Override
280
    public void onActivate() {
281
        ticks = 0;
282
        resetVariables();
283
    }
284
285
    private void resetVariables() {
286
        if (loadingSongFuture != null) {
287
            loadingSongFuture.cancel(true);
288
            loadingSongFuture = null;
289
        }
290
        clickedBlocks.clear();
291
        tuneHits.clear();
292
        anyNoteblockTuned = false;
293
        currentTick = 0;
294
        playingMode = PlayingMode.None;
295
        isPlaying = false;
296
        stage = Stage.None;
297
        song = null;
298
        noteBlockPositions.clear();
299
    }
300
301
    @EventHandler
302
    private void onRender3D(Render3DEvent event) {
303
        if (!renderBoxes.get()) return;
304
305
        if (stage != Stage.SetUp && stage != Stage.Tune && stage != Stage.WaitingToCheckNoteblocks && !isPlaying)
306
            return;
307
308
        if (showScannedNoteblocks.get()) {
309
            for (BlockPos blockPos : scannedNoteblocks.values()) {
310
                double x1 = blockPos.getX();
311
                double y1 = blockPos.getY();
312
                double z1 = blockPos.getZ();
313
                double x2 = blockPos.getX() + 1;
314
                double y2 = blockPos.getY() + 1;
315
                double z2 = blockPos.getZ() + 1;
316
317
                event.renderer.box(x1, y1, z1, x2, y2, z2, scannedNoteblockSideColor.get(), scannedNoteblockLineColor.get(), shapeMode.get(), 0);
318
            }
319
        } else {
320
            for (var entry : noteBlockPositions.entrySet()) {
321
                Note note = entry.getKey();
322
                BlockPos blockPos = entry.getValue();
323
324
                BlockState state = mc.level.getBlockState(blockPos);
325
                if (state.getBlock() != Blocks.NOTE_BLOCK) continue;
326
327
                int level = state.getValue(NoteBlock.NOTE);
328
329
                double x1 = blockPos.getX();
330
                double y1 = blockPos.getY();
331
                double z1 = blockPos.getZ();
332
                double x2 = blockPos.getX() + 1;
333
                double y2 = blockPos.getY() + 1;
334
                double z2 = blockPos.getZ() + 1;
335
336
                // Render boxes around noteblocks in use
337
338
                Color sideColor;
339
                Color lineColor;
340
                if (clickedBlocks.contains(blockPos)) {
341
                    sideColor = tuneHitSideColor.get();
342
                    lineColor = tuneHitLineColor.get();
343
                } else {
344
                    if (note.getNoteLevel() == level) {
345
                        sideColor = tunedSideColor.get();
346
                        lineColor = tunedLineColor.get();
347
                    } else {
348
                        sideColor = untunedSideColor.get();
349
                        lineColor = untunedLineColor.get();
350
                    }
351
                }
352
353
                event.renderer.box(x1, y1, z1, x2, y2, z2, sideColor, lineColor, shapeMode.get(), 0);
354
            }
355
        }
356
    }
357
358
    @EventHandler
359
    private void onRender2D(Render2DEvent event) {
360
        if (!renderText.get()) return;
361
362
        if (stage != Stage.SetUp && stage != Stage.Tune && stage != Stage.WaitingToCheckNoteblocks && !isPlaying)
363
            return;
364
365
        Vector3d pos = new Vector3d();
366
367
        for (BlockPos blockPos : noteBlockPositions.values()) {
368
            BlockState state = mc.level.getBlockState(blockPos);
369
            if (state.getBlock() != Blocks.NOTE_BLOCK) continue;
370
371
            double x = blockPos.getX() + 0.5;
372
            double y = blockPos.getY() + 1;
373
            double z = blockPos.getZ() + 0.5;
374
375
            pos.set(x, y, z);
376
377
            // Render level text logic
378
379
            String levelText = String.valueOf(state.getValue(NoteBlock.NOTE));
380
            String tuneHitsText = null;
381
            if (tuneHits.containsKey(blockPos)) {
382
                tuneHitsText = " -" + tuneHits.get(blockPos);
383
            }
384
385
            if (!NametagUtils.to2D(pos, noteTextScale.get(), true)) {
386
                continue;
387
            }
388
389
            TextRenderer text = TextRenderer.get();
390
391
            NametagUtils.begin(pos, event.graphics);
392
            text.beginBig(event.graphics);
393
394
            double xScreen = text.getWidth(levelText) / 2.0;
395
            if (tuneHitsText != null) {
396
                xScreen += text.getWidth(tuneHitsText) / 2.0;
397
            }
398
399
            double hX = text.render(levelText, -xScreen, 0, Color.GREEN);
400
            if (tuneHitsText != null) {
401
                text.render(tuneHitsText, hX, 0, Color.RED);
402
            }
403
            text.end();
404
405
            NametagUtils.end(event.graphics);
406
        }
407
    }
408
409
    @EventHandler
410
    private void onTick(TickEvent.Pre event) {
411
        ticks++;
412
        clickedBlocks.clear();
413
414
        if (stage == Stage.WaitingToCheckNoteblocks) {
415
            waitTicks--;
416
            if (waitTicks == 0) {
417
                waitTicks = -1;
418
                info("Checking noteblocks again...");
419
420
                setupTuneHitsMap();
421
                stage = Stage.Tune;
422
            }
423
        } else if (stage == Stage.SetUp) {
424
            scanForNoteblocks();
425
            if (scannedNoteblocks.isEmpty()) {
426
                error("Can't find any nearby noteblock!");
427
                stop();
428
                return;
429
            }
430
431
            setupNoteblocksMap();
432
            if (noteBlockPositions.isEmpty()) {
433
                error("Can't find any valid noteblock to play song.");
434
                stop();
435
                return;
436
            }
437
            setupTuneHitsMap();
438
            stage = Stage.Tune;
439
        } else if (stage == Stage.Tune) {
440
            tune();
441
        } else if (stage == Stage.Playing) {
442
            if (!isPlaying) return;
443
444
            if (mc.player == null || currentTick > song.getLastTick()) {
445
                // Stop the song after it is finished
446
                onSongEnd();
447
                return;
448
            }
449
450
            if (song.getNotesMap().containsKey(currentTick)) {
451
                if (playingMode == PlayingMode.Preview) onTickPreview();
452
                else if (mc.player.getAbilities().instabuild) {
453
                    error("You need to be in survival mode.");
454
                    stop();
455
                    return;
456
                } else onTickPlay();
457
            }
458
459
            currentTick++;
460
461
            updateStatus();
462
        }
463
    }
464
465
    /**
466
     * Set up a map of noteblocks positions
467
     */
468
    private void setupNoteblocksMap() {
469
        noteBlockPositions.clear();
470
471
        // Modifiable list of unique notes
472
        List<Note> uniqueNotesToUse = new ArrayList<>(song.getRequirements());
473
        // A map with noteblocks that have incorrect note level
474
        Map<NoteBlockInstrument, List<BlockPos>> incorrectNoteBlocks = new HashMap<>();
475
476
        // Check if there are already tuned noteblocks
477
        for (var entry : scannedNoteblocks.asMap().entrySet()) {
478
            Note note = entry.getKey();
479
            List<BlockPos> noteblocks = new ArrayList<>(entry.getValue());
480
481
            if (uniqueNotesToUse.contains(note)) {
482
                // Add correct noteblock position to a noteBlockPositions
483
                noteBlockPositions.put(note, noteblocks.removeFirst());
484
                uniqueNotesToUse.remove(note);
485
            }
486
487
            if (!noteblocks.isEmpty()) {
488
                // Add excess noteblocks for mapping process [note -> block pos]
489
490
                if (!incorrectNoteBlocks.containsKey(note.getInstrument())) {
491
                    incorrectNoteBlocks.put(note.getInstrument(), new ArrayList<>());
492
                }
493
494
                incorrectNoteBlocks.get(note.getInstrument()).addAll(noteblocks);
495
            }
496
        }
497
498
        // Map [note -> block pos]
499
        for (var entry : incorrectNoteBlocks.entrySet()) {
500
            List<BlockPos> positions = entry.getValue();
501
502
            if (mode.get() == NotebotUtils.NotebotMode.ExactInstruments) {
503
                NoteBlockInstrument inst = entry.getKey();
504
505
                List<Note> foundNotes = uniqueNotesToUse.stream()
506
                    .filter(note -> note.getInstrument() == inst)
507
                    .collect(Collectors.toList());
508
509
                if (foundNotes.isEmpty()) continue;
510
511
                for (BlockPos pos : positions) {
512
                    if (foundNotes.isEmpty()) break;
513
514
                    Note note = foundNotes.removeFirst();
515
                    noteBlockPositions.put(note, pos);
516
517
                    uniqueNotesToUse.remove(note);
518
                }
519
            } else {
520
                for (BlockPos pos : positions) {
521
                    if (uniqueNotesToUse.isEmpty()) break;
522
523
                    Note note = uniqueNotesToUse.removeFirst();
524
                    noteBlockPositions.put(note, pos);
525
                }
526
            }
527
        }
528
529
        if (!uniqueNotesToUse.isEmpty()) {
530
            for (Note note : uniqueNotesToUse) {
531
                warning("Missing note: " + note.getInstrument() + ", " + note.getNoteLevel());
532
            }
533
            warning(uniqueNotesToUse.size() + " missing notes!");
534
        }
535
    }
536
537
    /**
538
     * Set up a tune hits map which tells how many times player needs to
539
     * hit noteblock to obtain desired note level
540
     */
541
    private void setupTuneHitsMap() {
542
        tuneHits.clear();
543
544
        for (var entry : noteBlockPositions.entrySet()) {
545
            int targetLevel = entry.getKey().getNoteLevel();
546
            BlockPos blockPos = entry.getValue();
547
548
            BlockState blockState = mc.level.getBlockState(blockPos);
549
            if (blockState.getBlock() != Blocks.NOTE_BLOCK) continue;
550
551
            int currentLevel = blockState.getValue(NoteBlock.NOTE);
552
553
            if (targetLevel != currentLevel) {
554
                tuneHits.put(blockPos, calcNumberOfHits(currentLevel, targetLevel));
555
            }
556
        }
557
    }
558
559
    @Override
560
    public WWidget getWidget(GuiTheme theme) {
561
        WTable table = theme.table();
562
563
        // Open Song GUI
564
        WButton openSongGUI = table.add(theme.button("Open Song GUI")).expandX().minWidth(100).widget();
565
        openSongGUI.action = () -> mc.gui.setScreen(theme.notebotSongs());
566
567
        table.row();
568
569
        // Align Center
570
        WButton alignCenter = table.add(theme.button("Align Center")).expandX().minWidth(100).widget();
571
        alignCenter.action = () -> {
572
            if (mc.player == null) return;
573
            Vec3 pos = Vec3.atBottomCenterOf(mc.player.blockPosition());
574
            mc.player.setPos(pos.x, mc.player.getY(), pos.z);
575
        };
576
577
        table.row();
578
579
        // Label
580
        status = table.add(theme.label(getStatus())).expandCellX().widget();
581
582
        // Pause
583
        WButton pause = table.add(theme.button(isPlaying ? "Pause" : "Resume")).right().widget();
584
        pause.action = () -> {
585
            pause();
586
            pause.set(isPlaying ? "Pause" : "Resume");
587
            updateStatus();
588
        };
589
590
        // Stop
591
        WButton stop = table.add(theme.button("Stop")).right().widget();
592
        stop.action = this::stop;
593
594
        return table;
595
    }
596
597
    /**
598
     * Gets status for GUI
599
     *
600
     * @return A status
601
     */
602
    public String getStatus() {
603
        if (!this.isActive()) return "Module disabled.";
604
        if (song == null) return "No song loaded.";
605
        if (isPlaying) return String.format("Playing song. %d/%d", currentTick, song.getLastTick());
606
        if (stage == Stage.Playing) return "Ready to play.";
607
        if (stage == Stage.SetUp || stage == Stage.Tune || stage == Stage.WaitingToCheckNoteblocks)
608
            return "Setting up the noteblocks.";
609
        else return String.format("Stage: %s.", stage.toString());
610
    }
611
612
    /**
613
     * Plays a song after loading and tuning
614
     */
615
    public void play() {
616
        if (mc.player == null) return;
617
        if (mc.player.getAbilities().instabuild && playingMode != PlayingMode.Preview) {
618
            error("You need to be in survival mode.");
619
        } else if (stage == Stage.Playing) {
620
            isPlaying = true;
621
            info("Playing.");
622
        } else {
623
            error("No song loaded.");
624
        }
625
    }
626
627
    public void pause() {
628
        enable();
629
        if (isPlaying) {
630
            info("Pausing.");
631
            isPlaying = false;
632
        } else {
633
            info("Resuming.");
634
            isPlaying = true;
635
        }
636
    }
637
638
    public void stop() {
639
        info("Stopping.");
640
        disableNotebot();
641
        updateStatus();
642
    }
643
644
    public void onSongEnd() {
645
        if (autoPlay.get() && playingMode != PlayingMode.Preview) {
646
            playRandomSong();
647
        } else {
648
            stop();
649
        }
650
    }
651
652
    public void playRandomSong() {
653
        File[] files = MeteorClient.FOLDER.toPath().resolve("notebot").toFile().listFiles();
654
        if (files == null) return;
655
656
        File randomSong = files[ThreadLocalRandom.current().nextInt(files.length)];
657
        if (SongDecoders.hasDecoder(randomSong)) {
658
            loadSong(randomSong);
659
        } else {
660
            playRandomSong();
661
        }
662
    }
663
664
    public void disableNotebot() {
665
        resetVariables();
666
        enable();
667
    }
668
669
    /**
670
     * Loads and plays song
671
     *
672
     * @param file Song supported by one of {@link SongDecoder}
673
     */
674
    public void loadSong(File file) {
675
        enable();
676
        resetVariables();
677
678
        this.playingMode = PlayingMode.Noteblocks;
679
        if (!loadFileToMap(file, () -> stage = Stage.SetUp)) {
680
            onSongEnd();
681
            return;
682
        }
683
        updateStatus();
684
    }
685
686
    /**
687
     * Loads and previews the song
688
     *
689
     * @param file Song supported by one of {@link SongDecoder}
690
     */
691
    public void previewSong(File file) {
692
        enable();
693
        resetVariables();
694
695
        this.playingMode = PlayingMode.Preview;
696
        loadFileToMap(file, () -> {
697
            stage = Stage.Playing;
698
            play();
699
        });
700
        updateStatus();
701
    }
702
703
    /**
704
     * Loads and plays song directly
705
     *
706
     * @param file     Song supported by one of {@link SongDecoder}
707
     * @param callback Callback that is run when song has been loaded
708
     * @return Success
709
     */
710
    public boolean loadFileToMap(File file, Runnable callback) {
711
        if (!file.exists() || !file.isFile()) {
712
            error("File not found");
713
            return false;
714
        }
715
716
        if (!SongDecoders.hasDecoder(file)) {
717
            error("File is in wrong format. Decoder not found.");
718
            return false;
719
        }
720
721
        info("Loading song \"%s\".", FilenameUtils.getBaseName(file.getName()));
722
723
        // Start loading song
724
        loadingSongFuture = CompletableFuture.supplyAsync(() -> {
725
            try {
726
                return SongDecoders.parse(file);
727
            } catch (Exception e) {
728
                throw new RuntimeException(e);
729
            }
730
        });
731
        loadingSongFuture.completeOnTimeout(null, 60, TimeUnit.SECONDS);
732
733
        stage = Stage.LoadingSong;
734
        long time1 = System.currentTimeMillis();
735
        loadingSongFuture.whenComplete((song, ex) -> {
736
            if (ex == null) {
737
                // Song is null only when it times out
738
                if (song == null) {
739
                    error("Loading song '" + FilenameUtils.getBaseName(file.getName()) + "' timed out.");
740
                    onSongEnd();
741
                    return;
742
                }
743
744
                this.song = song;
745
                long time2 = System.currentTimeMillis();
746
                long diff = time2 - time1;
747
748
                info("Song '" + FilenameUtils.getBaseName(file.getName()) + "' has been loaded to the memory! Took " + diff + "ms");
749
                callback.run();
750
            } else {
751
                if (ex instanceof CancellationException) {
752
                    error("Loading song '" + FilenameUtils.getBaseName(file.getName()) + "' was cancelled.");
753
                } else {
754
                    error("An error occurred while loading song '" + FilenameUtils.getBaseName(file.getName()) + "'. See the logs for more details");
755
                    MeteorClient.LOG.error("An error occurred while loading song '{}'", FilenameUtils.getBaseName(file.getName()), ex);
756
                    onSongEnd();
757
                }
758
            }
759
        });
760
        return true;
761
    }
762
763
    /**
764
     * Scans noteblocks nearby and adds them to the map
765
     */
766
    private void scanForNoteblocks() {
767
        if (mc.gameMode == null || mc.level == null || mc.player == null) return;
768
        scannedNoteblocks.clear();
769
        int min = (int) (-mc.player.blockInteractionRange()) - 2;
770
        int max = (int) mc.player.blockInteractionRange() + 2;
771
772
        // Scan for noteblocks horizontally
773
        // 6^3 kek
774
        for (int y = min; y < max; y++) {
775
            for (int x = min; x < max; x++) {
776
                for (int z = min; z < max; z++) {
777
                    BlockPos pos = mc.player.blockPosition().offset(x, y + 1, z);
778
779
                    BlockState blockState = mc.level.getBlockState(pos);
780
                    if (blockState.getBlock() != Blocks.NOTE_BLOCK) continue;
781
782
                    // Copied from ServerPlayNetworkHandler#onPlayerInteractBlock
783
                    if (!mc.player.isWithinBlockInteractionRange(pos, 1)) continue;
784
785
                    if (!isValidScanSpot(pos)) continue;
786
787
                    Note note = NotebotUtils.getNoteFromNoteBlock(blockState, pos, mode.get(), instrumentDetectMode.get().getInstrumentDetectFunction());
788
                    scannedNoteblocks.put(note, pos);
789
                }
790
            }
791
        }
792
    }
793
794
    private void onTickPreview() {
795
        for (Note note : song.getNotesMap().get(currentTick)) {
796
            if (mode.get() == NotebotUtils.NotebotMode.ExactInstruments) {
797
                mc.player.playSound(note.getInstrument().getSoundEvent().value(), 2f, (float) Math.pow(2.0D, (note.getNoteLevel() - 12) / 12.0D));
798
            } else {
799
                mc.player.playSound(SoundEvents.NOTE_BLOCK_HARP.value(), 2f, (float) Math.pow(2.0D, (note.getNoteLevel() - 12) / 12.0D));
800
            }
801
        }
802
    }
803
804
    /**
805
     * Tunes noteblocks. This method is called per tick.
806
     */
807
    private void tune() {
808
        if (tuneHits.isEmpty()) {
809
            if (anyNoteblockTuned) {
810
                anyNoteblockTuned = false;
811
                waitTicks = checkNoteblocksAgainDelay.get();
812
                stage = Stage.WaitingToCheckNoteblocks;
813
814
                info("Delaying check for noteblocks");
815
            } else {
816
                stage = Stage.Playing;
817
                info("Loading done.");
818
                play();
819
            }
820
            return;
821
        }
822
823
        if (ticks < tickDelay.get()) {
824
            return;
825
        }
826
827
        tuneBlocks();
828
        ticks = 0;
829
    }
830
831
    private void tuneBlocks() {
832
        if (mc.level == null || mc.player == null) {
833
            disableNotebot();
834
        }
835
836
        if (swingArm.get()) {
837
            mc.player.swing(InteractionHand.MAIN_HAND);
838
        }
839
840
        int iterations = 0;
841
        var iterator = tuneHits.entrySet().iterator();
842
843
        // Concurrent tuning :o
844
        while (iterator.hasNext()) {
845
            var entry = iterator.next();
846
            BlockPos pos = entry.getKey();
847
            int hitsNumber = entry.getValue();
848
849
            if (autoRotate.get()) {
850
                Rotations.rotate(Rotations.getYaw(pos), Rotations.getPitch(pos), 100, () -> tuneNoteblockWithPackets(pos));
851
            } else {
852
                this.tuneNoteblockWithPackets(pos);
853
            }
854
855
            clickedBlocks.add(pos);
856
857
            hitsNumber--;
858
            entry.setValue(hitsNumber);
859
860
            if (hitsNumber == 0) {
861
                iterator.remove();
862
            }
863
864
            iterations++;
865
866
            if (iterations == concurrentTuneBlocks.get()) return;
867
        }
868
    }
869
870
    private void tuneNoteblockWithPackets(BlockPos pos) {
871
        // We don't need to raycast here. Server handles this packet fine
872
        mc.gameMode.startPrediction(mc.level, sequence -> new ServerboundUseItemOnPacket(InteractionHand.MAIN_HAND, new BlockHitResult(Vec3.atCenterOf(pos), Direction.DOWN, pos, false), sequence));
873
874
        anyNoteblockTuned = true;
875
    }
876
877
    public void updateStatus() {
878
        if (status != null) status.set(getStatus());
879
    }
880
881
    private static int calcNumberOfHits(int from, int to) {
882
        if (from > to) {
883
            return (25 - from) + to;
884
        } else {
885
            return to - from;
886
        }
887
    }
888
889
    private void onTickPlay() {
890
        Collection<Note> notes = song.getNotesMap().get(this.currentTick);
891
        if (!notes.isEmpty()) {
892
893
            // Rotate player's head
894
            if (autoRotate.get()) {
895
                Optional<Note> firstNote = notes.stream().findFirst();
896
                if (firstNote.isPresent()) {
897
                    BlockPos firstPos = noteBlockPositions.get(firstNote.get());
898
899
                    if (firstPos != null) {
900
                        Rotations.rotate(Rotations.getYaw(firstPos), Rotations.getPitch(firstPos));
901
                    }
902
                }
903
            }
904
905
            // Swing arm
906
            if (swingArm.get()) {
907
                mc.player.swing(InteractionHand.MAIN_HAND);
908
            }
909
910
            // Play notes
911
            for (Note note : notes) {
912
                BlockPos pos = noteBlockPositions.get(note);
913
                if (pos == null) {
914
                    return;
915
                }
916
917
                if (polyphonic.get()) {
918
                    playRotate(pos);
919
                } else {
920
                    this.playRotate(pos);
921
                }
922
            }
923
        }
924
    }
925
926
    private void playRotate(BlockPos pos) {
927
        if (mc.gameMode == null) return;
928
        try {
929
            mc.gameMode.startPrediction(mc.level, sequence -> new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, pos, Direction.DOWN, sequence));
930
        } catch (NullPointerException _) {
931
        }
932
    }
933
934
    private boolean isValidScanSpot(BlockPos pos) {
935
        if (mc.level.getBlockState(pos).getBlock() != Blocks.NOTE_BLOCK) return false;
936
        return mc.level.getBlockState(pos.above()).isAir();
937
    }
938
939
    /**
940
     * Gets an NoteBlockInstrument from Note Map
941
     *
942
     * @param inst An instrument
943
     * @return A new instrument mapped by instrument given in parameters
944
     */
945
    @Nullable
946
    public NoteBlockInstrument getMappedInstrument(@NonNull NoteBlockInstrument inst) {
947
        if (mode.get() == NotebotUtils.NotebotMode.ExactInstruments) {
948
            NotebotUtils.OptionalInstrument optionalInstrument = (NotebotUtils.OptionalInstrument) sgNoteMap.getByIndex(inst.ordinal()).get();
949
            return optionalInstrument.toMinecraftInstrument();
950
        } else {
951
            return inst;
952
        }
953
    }
954
955
    private String beautifyText(String text) {
956
        text = text.toLowerCase(Locale.ROOT);
957
958
        String[] arr = text.split("_");
959
        StringBuilder sb = new StringBuilder();
960
961
        for (String s : arr) {
962
            sb.append(Character.toUpperCase(s.charAt(0)))
963
                .append(s.substring(1));
964
        }
965
        return sb.toString().trim();
966
    }
967
968
    public enum Stage {
969
        None,
970
        LoadingSong,
971
        SetUp,
972
        Tune,
973
        WaitingToCheckNoteblocks,
974
        Playing
975
    }
976
977
    public enum PlayingMode {
978
        None,
979
        Preview,
980
        Noteblocks
981
    }
982
}
983
OfflineClientMISCsrc/main/java/com/jellypudding/offlineclient/modules/misc/Notebot.javaJava · 639 lines · 24.4 KB

Plays songs on the note blocks around you.

SettingsSongsInstrumentsDetect instrumentRemap instrumentsTune per tickTune delayRecheck delayFold notesRotateSwingPlay nextPreviewShow blocksShow notesNote scaleShow scanned
Notebot.javaJava · Minecraft 26.2 · 639 lines · 24.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.Render2DEvent;
6
import com.jellypudding.offlineclient.event.events.Render3DEvent;
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.render.BoxStyle;
11
import com.jellypudding.offlineclient.render.WorldToScreen;
12
import com.jellypudding.offlineclient.setting.BoolSetting;
13
import com.jellypudding.offlineclient.setting.ChoiceListSetting;
14
import com.jellypudding.offlineclient.setting.EnumSetting;
15
import com.jellypudding.offlineclient.setting.NumberSetting;
16
import com.jellypudding.offlineclient.setting.Setting;
17
import com.jellypudding.offlineclient.util.BlockUtil;
18
import com.jellypudding.offlineclient.util.ChatUtil;
19
import com.jellypudding.offlineclient.util.InventoryUtil;
20
import com.jellypudding.offlineclient.util.InventoryUtil.SlotSwap;
21
import com.jellypudding.offlineclient.util.ItemUtil;
22
import com.jellypudding.offlineclient.util.NoteSong;
23
import com.jellypudding.offlineclient.util.NoteSong.Note;
24
import com.jellypudding.offlineclient.util.RenderUtil;
25
import net.minecraft.core.BlockPos;
26
import net.minecraft.core.Direction;
27
import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket;
28
import net.minecraft.world.InteractionHand;
29
import net.minecraft.world.level.block.Blocks;
30
import net.minecraft.world.level.block.NoteBlock;
31
import net.minecraft.world.level.block.state.BlockState;
32
import net.minecraft.world.level.block.state.properties.NoteBlockInstrument;
33
import net.minecraft.world.phys.BlockHitResult;
34
import net.minecraft.world.phys.Vec3;
35
36
import java.io.IOException;
37
import java.nio.file.Files;
38
import java.nio.file.Path;
39
import java.util.ArrayList;
40
import java.util.Collection;
41
import java.util.EnumMap;
42
import java.util.HashMap;
43
import java.util.HashSet;
44
import java.util.Iterator;
45
import java.util.LinkedHashMap;
46
import java.util.List;
47
import java.util.Locale;
48
import java.util.Map;
49
import java.util.Random;
50
import java.util.Set;
51
import java.util.stream.Stream;
52
53
// Plays Note Block Studio songs on the note blocks around you.
54
// Blocks are tuned with clicks then struck on the beat. The bind pauses and resumes.
55
public final class Notebot extends Module {
56
57
    public enum Instruments { EXACT, ANY }
58
59
    public enum Detect { BLOCK_STATE, BELOW_BLOCK }
60
61
    // Where the notes of one instrument are sent. Same leaves them alone.
62
    public enum Remap {
63
        SAME, NONE, HARP, BASEDRUM, SNARE, HAT, BASS, FLUTE, BELL, GUITAR, CHIME,
64
        XYLOPHONE, IRON_XYLOPHONE, COW_BELL, DIDGERIDOO, BIT, BANJO, PLING
65
    }
66
67
    private enum Stage { SCAN, TUNE, RECHECK, PLAY, PREVIEW }
68
69
    // The instruments a note block can be tuned to.
70
    private static final NoteBlockInstrument[] PLAYABLE = {
71
        NoteBlockInstrument.HARP, NoteBlockInstrument.BASEDRUM, NoteBlockInstrument.SNARE,
72
        NoteBlockInstrument.HAT, NoteBlockInstrument.BASS, NoteBlockInstrument.FLUTE,
73
        NoteBlockInstrument.BELL, NoteBlockInstrument.GUITAR, NoteBlockInstrument.CHIME,
74
        NoteBlockInstrument.XYLOPHONE, NoteBlockInstrument.IRON_XYLOPHONE,
75
        NoteBlockInstrument.COW_BELL, NoteBlockInstrument.DIDGERIDOO, NoteBlockInstrument.BIT,
76
        NoteBlockInstrument.BANJO, NoteBlockInstrument.PLING
77
    };
78
79
    // Note block pitches wrap after this many clicks.
80
    private static final int PITCHES = 25;
81
82
    private static final int TEXT_COLOR = 0xFF30E030;
83
    private static final int OWED_COLOR = 0xFFE03030;
84
85
    private final ChoiceListSetting songs = new ChoiceListSetting("Songs",
86
        "Which files in the songs folder to play. Click to pick them. An empty list plays any.",
87
        Notebot::songNames);
88
    private final EnumSetting<Instruments> instruments = new EnumSetting<>("Instruments",
89
        "How strictly the block under a note block must match.", Instruments.EXACT)
90
        .describe(Instruments.EXACT, "Each note needs a block with the right instrument.")
91
        .describe(Instruments.ANY, "Any note block will do. Every note plays on whatever is there.");
92
    private final EnumSetting<Detect> detect = new EnumSetting<>("Detect instrument",
93
        "Where the instrument of a note block is read from.", Detect.BLOCK_STATE)
94
        .describe(Detect.BLOCK_STATE, "From the note block itself.")
95
        .describe(Detect.BELOW_BLOCK, "From the block underneath for servers that alter the state.")
96
        .under(instruments, Instruments.EXACT);
97
    private final BoolSetting remap = new BoolSetting("Remap instruments",
98
        "Sends the notes of one instrument to another or drops them.", false)
99
        .under(instruments, Instruments.EXACT);
100
    private final Map<NoteBlockInstrument, EnumSetting<Remap>> remaps =
101
        new EnumMap<>(NoteBlockInstrument.class);
102
    private final NumberSetting tunePerTick = new NumberSetting("Tune per tick",
103
        "How many note blocks to click in one tick whilst tuning. Paper servers want one.",
104
        1, 1, 20, 1).min(1);
105
    private final NumberSetting tuneDelay = new NumberSetting("Tune delay",
106
        "Ticks between one round of tuning clicks and the next.", 1, 1, 20, 1, " ticks").min(1);
107
    private final NumberSetting recheckDelay = new NumberSetting("Recheck delay",
108
        "Ticks to wait after tuning before the blocks are read back.", 10, 1, 40, 1, " ticks").min(1);
109
    private final BoolSetting foldNotes = new BoolSetting("Fold notes",
110
        "Moves notes outside the two octave range by an octave instead of dropping them.", true);
111
    private final BoolSetting rotate = new BoolSetting("Rotate",
112
        "Turn towards the note block on the server side.", true);
113
    private final BoolSetting swing = new BoolSetting("Swing",
114
        "Swings the arm on every hit.", true);
115
    private final BoolSetting playNext = new BoolSetting("Play next",
116
        "Starts another song from the folder when one ends.", false);
117
    private final BoolSetting preview = new BoolSetting("Preview",
118
        "Plays the song through your own speakers instead of note blocks.", false);
119
    private final BoolSetting render = new BoolSetting("Show blocks",
120
        "Outlines the note blocks the song uses.", true);
121
    private final BoxStyle untunedStyle = new BoxStyle("Untuned", BoxStyle.Shape.LINES, 0f)
122
        .under(render);
123
    private final BoxStyle tunedStyle = new BoxStyle("Tuned", BoxStyle.Shape.LINES, 0.33f)
124
        .under(render);
125
    private final BoxStyle hitStyle = new BoxStyle("Hit", BoxStyle.Shape.BOTH, 0.1f)
126
        .under(render);
127
    private final BoolSetting renderText = new BoolSetting("Show notes",
128
        "Draws the pitch of each note block above it.", true)
129
        .under(render);
130
    private final NumberSetting textScale = new NumberSetting("Note scale",
131
        "How big that text is drawn.", 1.5, 0.5, 4, 0.1).min(0.1).max(10)
132
        .under(renderText);
133
    private final BoolSetting showScanned = new BoolSetting("Show scanned",
134
        "Also outlines every note block found in the scan.", false);
135
    private final BoxStyle scannedStyle = new BoxStyle("Scanned", BoxStyle.Shape.LINES, 0.16f)
136
        .under(showScanned);
137
138
    private NoteSong loaded;
139
    private Stage stage;
140
    // Holds a slot that cannot finish a note block whilst the song plays.
141
    private final SlotSwap slots = new SlotSwap();
142
143
    private boolean paused;
144
    private int tick;
145
    private int waitTicks;
146
147
    // Which note block plays each note.
148
    private final Map<Note, BlockPos> assigned = new LinkedHashMap<>();
149
150
    // Clicks still owed to each block whilst tuning.
151
    private final Map<BlockPos, Integer> tuning = new HashMap<>();
152
153
    // Blocks struck this tick for the renderer.
154
    private final Set<BlockPos> struck = new HashSet<>();
155
156
    // Every note block the scan saw whether the song uses it or not.
157
    private final Set<BlockPos> scanned = new HashSet<>();
158
159
    // Ticks left before the next round of tuning clicks.
160
    private int tuneWait;
161
162
    private final Random random = new Random();
163
164
    public Notebot() {
165
        super("Notebot", "Plays songs on the note blocks around you.", Category.MISC);
166
        addSettings(songs, instruments, detect, remap);
167
        addSettings(buildRemaps());
168
        addSettings(tunePerTick, tuneDelay, recheckDelay, foldNotes, rotate, swing,
169
            playNext, preview, render);
170
        addSettings(untunedStyle.settings());
171
        addSettings(tunedStyle.settings());
172
        addSettings(hitStyle.settings());
173
        addSettings(renderText, textScale, showScanned);
174
        addSettings(scannedStyle.settings());
175
        searchTags("note block", "music", "nbs");
176
    }
177
178
    // One row per instrument a note block can play.
179
    private Setting<?>[] buildRemaps() {
180
        List<Setting<?>> rows = new ArrayList<>();
181
        for (NoteBlockInstrument instrument : PLAYABLE) {
182
            EnumSetting<Remap> row = new EnumSetting<>(rowName(instrument),
183
                "Which instrument these notes are sent to.", Remap.SAME)
184
                .describe(Remap.SAME, "Leaves these notes alone.")
185
                .describe(Remap.NONE, "Drops these notes.")
186
                .under(remap, () -> remap.isOn() && instruments.is(Instruments.EXACT));
187
            remaps.put(instrument, row);
188
            rows.add(row);
189
        }
190
        return rows.toArray(new Setting<?>[0]);
191
    }
192
193
    private static String rowName(NoteBlockInstrument instrument) {
194
        String words = instrument.name().toLowerCase(Locale.ROOT).replace('_', ' ');
195
        return Character.toUpperCase(words.charAt(0)) + words.substring(1) + " notes";
196
    }
197
198
    // The names the song picker offers.
199
    private static Collection<String> songNames() {
200
        List<String> names = new ArrayList<>();
201
        try (Stream<Path> stream = Files.list(songsFolder())) {
202
            stream.map(file -> file.getFileName().toString())
203
                .filter(Notebot::isSong)
204
                .forEach(names::add);
205
        } catch (IOException ignored) {
206
        }
207
        return names;
208
    }
209
210
    private static boolean isSong(String name) {
211
        String lower = name.toLowerCase(Locale.ROOT);
212
        return lower.endsWith(".nbs") || lower.endsWith(".txt");
213
    }
214
215
    @Override
216
    public boolean savesEnabledState() {
217
        return false;
218
    }
219
220
    @Override
221
    public String getSuffix() {
222
        if (loaded == null || stage == null) {
223
            return null;
224
        }
225
        return switch (stage) {
226
            case SCAN, TUNE, RECHECK -> "tuning";
227
            case PLAY, PREVIEW -> (paused ? "paused " : "") + tick + "/" + loaded.lastTick();
228
        };
229
    }
230
231
    // The bind pauses a running song. Off the module it switches on as usual.
232
    @Override
233
    public void onKeybind() {
234
        if (!isEnabled() || (stage != Stage.PLAY && stage != Stage.PREVIEW)) {
235
            toggle();
236
            return;
237
        }
238
        paused = !paused;
239
        ChatUtil.message("§bNotebot §7" + (paused ? "paused." : "resumed."));
240
    }
241
242
    @Override
243
    protected void onEnable() {
244
        loaded = null;
245
        stage = null;
246
        paused = false;
247
        assigned.clear();
248
        tuning.clear();
249
        scanned.clear();
250
        if (inGame()) {
251
            loadSong();
252
        }
253
    }
254
255
    @Override
256
    protected void onDisable() {
257
        loaded = null;
258
        stage = null;
259
        assigned.clear();
260
        tuning.clear();
261
        struck.clear();
262
        scanned.clear();
263
        slots.restore();
264
    }
265
266
    private static Path songsFolder() {
267
        return OfflineClient.MC.gameDirectory.toPath().resolve("offlineclient").resolve("songs");
268
    }
269
270
    private void loadSong() {
271
        Path folder = songsFolder();
272
        try {
273
            Files.createDirectories(folder);
274
        } catch (IOException ignored) {
275
        }
276
        Path file = pickFile(folder);
277
        if (file == null) {
278
            return;
279
        }
280
        try {
281
            loaded = NoteSong.read(file).remapped(remapTable()).foldedIntoRange(foldNotes.isOn());
282
        } catch (IOException e) {
283
            ChatUtil.error("Could not read " + file.getFileName() + ".");
284
            setEnabled(false);
285
            return;
286
        }
287
        tick = 0;
288
        paused = false;
289
        stage = preview.isOn() ? Stage.PREVIEW : Stage.SCAN;
290
        ChatUtil.message("§bNotebot §7loaded §f" + loaded.title()
291
            + (loaded.author().isBlank() ? "" : " §7by §f" + loaded.author()) + "§7.");
292
    }
293
294
    // A picked file or a random one. Null when nothing fits and the module is off.
295
    private Path pickFile(Path folder) {
296
        List<Path> files = new ArrayList<>();
297
        try (Stream<Path> stream = Files.list(folder)) {
298
            stream.filter(file -> isSong(file.getFileName().toString()))
299
                .filter(file -> songs.size() == 0 || songs.contains(file.getFileName().toString()))
300
                .forEach(files::add);
301
        } catch (IOException ignored) {
302
        }
303
        if (files.isEmpty()) {
304
            ChatUtil.error("No songs to play in " + folder + ".");
305
            setEnabled(false);
306
            return null;
307
        }
308
        return files.get(random.nextInt(files.size()));
309
    }
310
311
    // What each instrument in the file is turned into. Empty when nothing is remapped.
312
    private Map<NoteBlockInstrument, NoteBlockInstrument> remapTable() {
313
        Map<NoteBlockInstrument, NoteBlockInstrument> table = new EnumMap<>(NoteBlockInstrument.class);
314
        if (!remap.isOn() || !instruments.is(Instruments.EXACT)) {
315
            return table;
316
        }
317
        for (Map.Entry<NoteBlockInstrument, EnumSetting<Remap>> entry : remaps.entrySet()) {
318
            Remap choice = entry.getValue().getValue();
319
            if (choice == Remap.SAME) {
320
                continue;
321
            }
322
            table.put(entry.getKey(), choice == Remap.NONE
323
                ? null : NoteBlockInstrument.valueOf(choice.name()));
324
        }
325
        return table;
326
    }
327
328
    @Subscribe
329
    private void onTick(TickEvent event) {
330
        struck.clear();
331
        if (loaded == null) {
332
            if (inGame()) {
333
                loadSong();
334
            }
335
            return;
336
        }
337
        if (!inGame()) {
338
            return;
339
        }
340
        switch (stage) {
341
            case SCAN -> scan();
342
            case TUNE -> tune();
343
            case RECHECK -> recheck();
344
            case PLAY -> play();
345
            case PREVIEW -> previewTick();
346
        }
347
    }
348
349
    private void scan() {
350
        Map<Note, List<BlockPos>> found = findNoteBlocks();
351
        if (found.isEmpty()) {
352
            ChatUtil.error("No note blocks in reach with air above them.");
353
            setEnabled(false);
354
            return;
355
        }
356
        assign(found);
357
        if (assigned.isEmpty()) {
358
            ChatUtil.error("None of the note blocks in reach can play this song.");
359
            setEnabled(false);
360
            return;
361
        }
362
        int missing = loaded.needed().size() - assigned.size();
363
        if (missing > 0) {
364
            ChatUtil.message("§bNotebot §7is short of §f" + missing + "§7 note blocks. Those notes are skipped.");
365
        }
366
        planTuning();
367
        stage = Stage.TUNE;
368
    }
369
370
    // Every note block in reach keyed by what it plays right now.
371
    private Map<Note, List<BlockPos>> findNoteBlocks() {
372
        Map<Note, List<BlockPos>> found = new LinkedHashMap<>();
373
        scanned.clear();
374
        double reach = mc.player.blockInteractionRange();
375
        for (BlockPos pos : BlockUtil.positionsWithin(reach + 1)) {
376
            BlockState state = BlockUtil.state(pos);
377
            if (!state.is(Blocks.NOTE_BLOCK) || !BlockUtil.state(pos.above()).isAir()) {
378
                continue;
379
            }
380
            if (!mc.player.isWithinBlockInteractionRange(pos, 1)) {
381
                continue;
382
            }
383
            scanned.add(pos.immutable());
384
            found.computeIfAbsent(noteOf(state, pos), k -> new ArrayList<>()).add(pos.immutable());
385
        }
386
        return found;
387
    }
388
389
    private Note noteOf(BlockState state, BlockPos pos) {
390
        NoteBlockInstrument instrument = instruments.is(Instruments.EXACT)
391
            ? instrumentAt(state, pos) : null;
392
        return new Note(instrument, state.getValue(NoteBlock.NOTE));
393
    }
394
395
    // Some servers alter the block state. The block underneath is the truth.
396
    private NoteBlockInstrument instrumentAt(BlockState state, BlockPos pos) {
397
        return detect.is(Detect.BELOW_BLOCK)
398
            ? BlockUtil.state(pos.below()).instrument() : state.getValue(NoteBlock.INSTRUMENT);
399
    }
400
401
    // A note the song needs but the file stored with an instrument the scan ignores.
402
    private Note wanted(Note note) {
403
        return instruments.is(Instruments.EXACT) ? note : new Note(null, note.pitch());
404
    }
405
406
    // Blocks already on the right pitch are kept as they are.
407
    // The rest are handed out by instrument to the notes still missing.
408
    private void assign(Map<Note, List<BlockPos>> found) {
409
        assigned.clear();
410
        List<Note> missing = new ArrayList<>();
411
        for (Note note : loaded.needed()) {
412
            Note key = wanted(note);
413
            List<BlockPos> ready = found.get(key);
414
            if (ready != null && !ready.isEmpty()) {
415
                assigned.put(note, ready.removeFirst());
416
            } else {
417
                missing.add(note);
418
            }
419
        }
420
        Map<NoteBlockInstrument, List<BlockPos>> spare = new HashMap<>();
421
        for (Map.Entry<Note, List<BlockPos>> entry : found.entrySet()) {
422
            spare.computeIfAbsent(entry.getKey().instrument(), k -> new ArrayList<>()).addAll(entry.getValue());
423
        }
424
        Iterator<Note> it = missing.iterator();
425
        while (it.hasNext()) {
426
            Note note = it.next();
427
            List<BlockPos> blocks = spare.get(wanted(note).instrument());
428
            if (blocks != null && !blocks.isEmpty()) {
429
                assigned.put(note, blocks.removeFirst());
430
                it.remove();
431
            }
432
        }
433
    }
434
435
    private void planTuning() {
436
        tuning.clear();
437
        for (Map.Entry<Note, BlockPos> entry : assigned.entrySet()) {
438
            BlockState state = BlockUtil.state(entry.getValue());
439
            if (!state.is(Blocks.NOTE_BLOCK)) {
440
                continue;
441
            }
442
            int now = state.getValue(NoteBlock.NOTE);
443
            int target = entry.getKey().pitch();
444
            if (now != target) {
445
                tuning.put(entry.getValue(), Math.floorMod(target - now, PITCHES));
446
            }
447
        }
448
    }
449
450
    private void tune() {
451
        if (tuning.isEmpty()) {
452
            waitTicks = recheckDelay.getInt();
453
            stage = Stage.RECHECK;
454
            return;
455
        }
456
        if (--tuneWait > 0) {
457
            return;
458
        }
459
        tuneWait = tuneDelay.getInt();
460
        if (swing.isOn()) {
461
            mc.player.swing(InteractionHand.MAIN_HAND);
462
        }
463
        int clicked = 0;
464
        Iterator<Map.Entry<BlockPos, Integer>> it = tuning.entrySet().iterator();
465
        while (it.hasNext() && clicked < tunePerTick.getInt()) {
466
            Map.Entry<BlockPos, Integer> entry = it.next();
467
            BlockPos pos = entry.getKey();
468
            if (rotate.isOn()) {
469
                BlockUtil.faceVector(Vec3.atCenterOf(pos));
470
            }
471
            mc.gameMode.useItemOn(mc.player, InteractionHand.MAIN_HAND,
472
                new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false));
473
            struck.add(pos);
474
            entry.setValue(entry.getValue() - 1);
475
            if (entry.getValue() <= 0) {
476
                it.remove();
477
            }
478
            clicked++;
479
        }
480
    }
481
482
    // The server may have refused some clicks. The blocks are read back once more.
483
    private void recheck() {
484
        if (--waitTicks > 0) {
485
            return;
486
        }
487
        planTuning();
488
        if (!tuning.isEmpty()) {
489
            stage = Stage.TUNE;
490
            return;
491
        }
492
        if (mc.player.getAbilities().instabuild) {
493
            ChatUtil.error("Notebot cannot strike note blocks in creative. They break instead.");
494
            setEnabled(false);
495
            return;
496
        }
497
        holdSafeItem();
498
        ChatUtil.message("§bNotebot §7tuned. Playing.");
499
        tick = 0;
500
        stage = Stage.PLAY;
501
    }
502
503
    // A strike becomes a break if the held item would finish the block in one go.
504
    // The gentlest thing in the hotbar is held instead.
505
    private void holdSafeItem() {
506
        BlockState note = Blocks.NOTE_BLOCK.defaultBlockState();
507
        int best = -1;
508
        float slowest = ItemUtil.miningSpeed(mc.player.getInventory().getSelectedItem(), note);
509
        for (int i = 0; i < InventoryUtil.HOTBAR_SIZE; i++) {
510
            float speed = ItemUtil.miningSpeed(mc.player.getInventory().getItem(i), note);
511
            if (speed < slowest) {
512
                slowest = speed;
513
                best = i;
514
            }
515
        }
516
        if (best != -1) {
517
            slots.select(best);
518
        }
519
    }
520
521
    private void play() {
522
        if (paused) {
523
            return;
524
        }
525
        if (tick > loaded.lastTick()) {
526
            finish();
527
            return;
528
        }
529
        List<Note> notes = loaded.notesAt(tick++);
530
        if (notes.isEmpty()) {
531
            return;
532
        }
533
        boolean turned = false;
534
        for (Note note : notes) {
535
            BlockPos pos = assigned.get(note);
536
            if (pos == null) {
537
                continue;
538
            }
539
            if (rotate.isOn() && !turned) {
540
                BlockUtil.faceVector(Vec3.atCenterOf(pos));
541
                turned = true;
542
            }
543
            // A left click plays the block without harming it.
544
            mc.player.connection.send(new ServerboundPlayerActionPacket(
545
                ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, pos, Direction.UP));
546
            mc.player.connection.send(new ServerboundPlayerActionPacket(
547
                ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, pos, Direction.UP));
548
            struck.add(pos);
549
        }
550
        if (swing.isOn() && !struck.isEmpty()) {
551
            mc.player.swing(InteractionHand.MAIN_HAND);
552
        }
553
    }
554
555
    private void previewTick() {
556
        if (paused) {
557
            return;
558
        }
559
        if (tick > loaded.lastTick()) {
560
            finish();
561
            return;
562
        }
563
        for (Note note : loaded.notesAt(tick++)) {
564
            NoteBlockInstrument instrument = note.instrument() == null
565
                ? NoteBlockInstrument.HARP : note.instrument();
566
            mc.player.playSound(instrument.getSoundEvent().value(), 2f,
567
                NoteBlock.getPitchFromNote(note.pitch()));
568
        }
569
    }
570
571
    private void finish() {
572
        if (playNext.isOn()) {
573
            loaded = null;
574
            assigned.clear();
575
            loadSong();
576
            return;
577
        }
578
        ChatUtil.message("§bNotebot §7finished §f" + loaded.title() + "§7.");
579
        setEnabled(false);
580
    }
581
582
    @Subscribe
583
    private void onRender3D(Render3DEvent event) {
584
        if (loaded == null) {
585
            return;
586
        }
587
        if (showScanned.isOn()) {
588
            for (BlockPos pos : scanned) {
589
                if (!assigned.containsValue(pos)) {
590
                    scannedStyle.draw(event.getBatch(), pos, false);
591
                }
592
            }
593
        }
594
        if (!render.isOn()) {
595
            return;
596
        }
597
        for (BlockPos pos : assigned.values()) {
598
            style(pos).draw(event.getBatch(), pos, false);
599
        }
600
    }
601
602
    private BoxStyle style(BlockPos pos) {
603
        if (struck.contains(pos)) {
604
            return hitStyle;
605
        }
606
        return tuning.containsKey(pos) ? untunedStyle : tunedStyle;
607
    }
608
609
    // The pitch each block sits on with the clicks it still owes after it.
610
    @Subscribe
611
    private void onRender2D(Render2DEvent event) {
612
        if (loaded == null || !render.isOn() || !renderText.isOn() || !inGame()) {
613
            return;
614
        }
615
        for (BlockPos pos : assigned.values()) {
616
            BlockState state = BlockUtil.state(pos);
617
            if (!state.is(Blocks.NOTE_BLOCK)) {
618
                continue;
619
            }
620
            Vec3 screen = WorldToScreen.project(new Vec3(pos.getX() + 0.5, pos.getY() + 1.2,
621
                pos.getZ() + 0.5));
622
            if (screen == null) {
623
                continue;
624
            }
625
            Integer owed = tuning.get(pos);
626
            List<String> parts = new ArrayList<>();
627
            List<Integer> colors = new ArrayList<>();
628
            parts.add(String.valueOf(state.getValue(NoteBlock.NOTE)));
629
            colors.add(TEXT_COLOR);
630
            if (owed != null) {
631
                parts.add(" -" + owed);
632
                colors.add(OWED_COLOR);
633
            }
634
            RenderUtil.label(event.getContext(), mc.font, screen.x, screen.y,
635
                textScale.getFloat(), parts, colors);
636
        }
637
    }
638
}
639
LiquidBounce (Kotlin)FUNsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/fun/notebot/ModuleNotebot.ktKotlin · 254 lines · 8.4 KB

Automatically plays note block songs from NBS (Note Block Song) file.

SettingsPianoOnlyReuseBlocksRangeIgnoreOpenInventoryTestTunePlay
ModuleNotebot.ktKotlin · Minecraft 26.2 · 254 lines · 8.4 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.`fun`.notebot
20
21
import kotlinx.coroutines.Dispatchers
22
import kotlinx.coroutines.withContext
23
import net.ccbluex.fastutil.enumSetOf
24
import net.ccbluex.liquidbounce.config.types.group.ValueGroup
25
import net.ccbluex.liquidbounce.event.events.PacketEvent
26
import net.ccbluex.liquidbounce.event.handler
27
import net.ccbluex.liquidbounce.event.tickHandler
28
import net.ccbluex.liquidbounce.features.module.ClientModule
29
import net.ccbluex.liquidbounce.features.module.ModuleCategories
30
import net.ccbluex.liquidbounce.features.module.modules.`fun`.notebot.nbs.InstrumentNote
31
import net.ccbluex.liquidbounce.features.module.modules.`fun`.notebot.nbs.NbsLoader
32
import net.ccbluex.liquidbounce.features.module.modules.`fun`.notebot.nbs.NbsNoteBlock
33
import net.ccbluex.liquidbounce.features.module.modules.`fun`.notebot.nbs.SongData
34
import net.ccbluex.liquidbounce.features.module.modules.world.packetmine.ModulePacketMine
35
import net.ccbluex.liquidbounce.render.engine.type.Color4b
36
import net.ccbluex.liquidbounce.utils.aiming.RotationsValueGroup
37
import net.ccbluex.liquidbounce.utils.client.MessageMetadata
38
import net.ccbluex.liquidbounce.utils.client.chat
39
import net.ccbluex.liquidbounce.utils.client.inGame
40
import net.ccbluex.liquidbounce.utils.client.markAsError
41
import net.ccbluex.liquidbounce.utils.client.regular
42
import net.ccbluex.liquidbounce.utils.client.removeMessage
43
import net.ccbluex.liquidbounce.utils.text.textLoadingBar
44
import net.ccbluex.liquidbounce.utils.client.variable
45
import net.minecraft.ChatFormatting
46
import net.minecraft.network.chat.MutableComponent
47
import net.minecraft.network.protocol.game.ClientboundSoundPacket
48
import net.minecraft.util.Mth
49
import net.minecraft.world.level.block.state.properties.NoteBlockInstrument
50
51
/**
52
 * Notebot Module
53
 *
54
 * Automatically plays note block songs from NBS files.
55
 *
56
 * @author ccetl
57
 */
58
object ModuleNotebot : ClientModule("Notebot", ModuleCategories.FUN, disableOnQuit = true) {
59
60
    private val song = file("Song", supportedExtensions = setOf("nbs"))
61
    private val pianoOnly by boolean("PianoOnly", false)
62
    val reuseBlocks by boolean("ReuseBlocks", true).onChanged { enabled = false }
63
    val range by float("Range", 6f, 1f..6f)
64
    val rotations = RotationsValueGroup(this)
65
    val ignoreOpenInventory by boolean("IgnoreOpenInventory", true)
66
67
    private object StartDelay : ValueGroup("StartDelay") {
68
        val test by int("Test", 0, 0..20, "ticks")
69
        val tune by int("Tune", 0, 0..20, "ticks")
70
        val play by int("Play", 2, 0..20, "ticks")
71
    }
72
73
    init {
74
        tree(StartDelay)
75
    }
76
77
    val renderer = tree(NotebotRenderer)
78
79
    var engine: NotebotEngine? = null
80
        private set
81
82
    @Suppress("unused")
83
    private val tickHandler = tickHandler {
84
        engine?.onTick()
85
    }
86
87
    @Suppress("unused")
88
    private val packetHandler = handler<PacketEvent> { event ->
89
        if (event.packet is ClientboundSoundPacket) {
90
            this.engine?.handleSoundPacket(event.packet)
91
        }
92
    }
93
94
    override suspend fun enabledEffect() {
95
        val messageMetadata = MessageMetadata(id = "M${this.name}#loaded", remove = false)
96
        mc.gui.hud.chat.removeMessage(messageMetadata.id)
97
98
        if (!checkRequirements()) {
99
            this.enabled = false
100
            return
101
        }
102
103
        val songData = loadSongData()
104
105
        if (songData == null) {
106
            this.enabled = false
107
            return
108
        }
109
110
        val blocksAndRequirements = NotebotScanner.scanBlocksAndCheckRequirements(songData)
111
112
        if (!blocksAndRequirements.validateRequirements()) {
113
            blocksAndRequirements.printRequirements()
114
            this.enabled = false
115
            return
116
        }
117
118
        this.setRenderedBlocks(blocksAndRequirements.availableBlocks.flatMap { it.value })
119
120
        showSongInfo(songData, messageMetadata)
121
122
        this.engine = NotebotEngine(songData, blocksAndRequirements)
123
        chat(message("startTesting").withStyle(ChatFormatting.GREEN), this)
124
    }
125
126
    fun setRenderedBlocks(blocks: List<NoteBlockTracker>) {
127
        renderer.clearSilently()
128
129
        blocks.forEach {
130
            renderer.addBlock(it.pos, false)
131
        }
132
133
        renderer.updateAll()
134
    }
135
136
    private suspend fun loadSongData(): SongData? {
137
        chat(message("startLoading").withStyle(ChatFormatting.GREEN), this)
138
139
        val songData = withContext(Dispatchers.IO) {
140
            NbsLoader.load(song.absoluteFile)
141
        }
142
143
        return songData
144
    }
145
146
    private fun checkRequirements(): Boolean {
147
        return when {
148
            !inGame -> {
149
                chat(markAsError(message("notInGame")), this)
150
                false
151
            }
152
153
            player.isCreative -> {
154
                chat(markAsError(message("inCreative")), this)
155
                false
156
            }
157
158
            ModulePacketMine.enabled -> {
159
                chat(markAsError(message("packetMineEnabled")), this)
160
                false
161
            }
162
163
            else -> true
164
        }
165
    }
166
167
    private fun showSongInfo(
168
        songData: SongData,
169
        messageMetadata: MessageMetadata
170
    ) {
171
        chat(
172
            regular(message("songInfoName", variable(songData.name))),
173
            messageMetadata
174
        )
175
        chat(
176
            regular(message("songInfoTicksPerGameTick", variable(songData.songTicksPerGameTick.toString()))),
177
            messageMetadata
178
        )
179
        chat(
180
            regular(message("songInfoTickLength", variable(songData.songTickLength.toString()))),
181
            messageMetadata
182
        )
183
        chat(
184
            regular(message("songInfoTotalNotes", variable(songData.nbs.noteBlocks.size.toString()))),
185
            messageMetadata
186
        )
187
    }
188
189
    override fun onDisabled() {
190
        removeProgressMessage()
191
192
        renderer.reset()
193
    }
194
195
    private val progressMessageMetadata = MessageMetadata(id = "M$name#progress", remove = false)
196
197
    private fun removeProgressMessage() {
198
        mc.gui.hud.chat.removeMessage(progressMessageMetadata.id)
199
    }
200
201
    fun sendNewProgressMessage(name: MutableComponent, progress: Int, total: Int) {
202
        removeProgressMessage()
203
204
        val percent = (progress.toDouble() / total.toDouble() * 100.0).toInt()
205
        chat(
206
            variable(name.copy())
207
                .append(regular(" ["))
208
                .append(textLoadingBar(percent))
209
                .append(regular("] "))
210
                .append(variable(percent.toString()))
211
                .append(regular("%")),
212
            metadata = progressMessageMetadata
213
        )
214
    }
215
216
    fun getPlayedNote(note: NbsNoteBlock): InstrumentNote {
217
        val noteValue = Mth.clamp(note.key - 33, 0, 24)
218
        val instrument = if (!this.pianoOnly) {
219
            note.instrument.toInt()
220
        } else {
221
            0
222
        }
223
224
        return InstrumentNote(instrument, noteValue)
225
    }
226
227
    fun getRequiredInstruments(songData: SongData): Set<NoteBlockInstrument> {
228
        if (pianoOnly) {
229
            return setOf(NoteBlockInstrument.HARP)
230
        }
231
232
        return songData.nbs.noteBlocks
233
            .mapTo(enumSetOf()) {
234
                InstrumentNote.getInstrumentEnumFromId(it.instrument.toInt())
235
            }
236
    }
237
238
    enum class NotebotStage(
239
        val stageStartDelay: () -> Int,
240
        val blockColor: () -> Color4b,
241
        val blockOutlineColor: () -> Color4b
242
    ) {
243
        TEST(StartDelay::test, NotebotRenderer::testColor, NotebotRenderer::outlineTestColor),
244
        TUNE(StartDelay::tune, NotebotRenderer::tuneColor, NotebotRenderer::outlineTuneColor),
245
        PLAY(StartDelay::play, NotebotRenderer::colorSetting, NotebotRenderer::outlineColorSetting)
246
    }
247
248
    interface NotebotStageHandler {
249
        val handledStage: NotebotStage
250
251
        fun onTick(engine: NotebotEngine)
252
    }
253
}
254