| 1 | package net.minecraft.world.item;
|
| 2 |
|
| 3 | import com.mojang.serialization.Codec;
|
| 4 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 5 | import java.util.Optional;
|
| 6 | import net.minecraft.core.Holder;
|
| 7 | import net.minecraft.core.component.DataComponents;
|
| 8 | import net.minecraft.core.registries.Registries;
|
| 9 | import net.minecraft.core.registries.codec.RegistryCodecs;
|
| 10 | import net.minecraft.network.RegistryFriendlyByteBuf;
|
| 11 | import net.minecraft.network.chat.Component;
|
| 12 | import net.minecraft.network.chat.ComponentSerialization;
|
| 13 | import net.minecraft.network.codec.ByteBufCodecs;
|
| 14 | import net.minecraft.network.codec.StreamCodec;
|
| 15 | import net.minecraft.sounds.SoundEvent;
|
| 16 | import net.minecraft.util.ExtraCodecs;
|
| 17 | import net.minecraft.util.Mth;
|
| 18 |
|
| 19 | public record JukeboxSong(Holder<SoundEvent> soundEvent, Component description, float lengthInSeconds, int comparatorOutput) {
|
| 20 | public static final Codec<JukeboxSong> DIRECT_CODEC = RecordCodecBuilder.create(
|
| 21 | i -> i.group(
|
| 22 | SoundEvent.CODEC.fieldOf("sound_event").forGetter(JukeboxSong::soundEvent),
|
| 23 | ComponentSerialization.CODEC.fieldOf("description").forGetter(JukeboxSong::description),
|
| 24 | ExtraCodecs.POSITIVE_FLOAT.fieldOf("length_in_seconds").forGetter(JukeboxSong::lengthInSeconds),
|
| 25 | ExtraCodecs.intRange(0, 15).fieldOf("comparator_output").forGetter(JukeboxSong::comparatorOutput)
|
| 26 | )
|
| 27 | .apply(i, JukeboxSong::new)
|
| 28 | );
|
| 29 | public static final StreamCodec<RegistryFriendlyByteBuf, JukeboxSong> DIRECT_STREAM_CODEC = StreamCodec.composite(
|
| 30 | SoundEvent.STREAM_CODEC,
|
| 31 | JukeboxSong::soundEvent,
|
| 32 | ComponentSerialization.STREAM_CODEC,
|
| 33 | JukeboxSong::description,
|
| 34 | ByteBufCodecs.FLOAT,
|
| 35 | JukeboxSong::lengthInSeconds,
|
| 36 | ByteBufCodecs.VAR_INT,
|
| 37 | JukeboxSong::comparatorOutput,
|
| 38 | JukeboxSong::new
|
| 39 | );
|
| 40 | public static final Codec<Holder<JukeboxSong>> CODEC = RegistryCodecs.holder(Registries.JUKEBOX_SONG);
|
| 41 | public static final StreamCodec<RegistryFriendlyByteBuf, Holder<JukeboxSong>> STREAM_CODEC = ByteBufCodecs.holder(Registries.JUKEBOX_SONG, DIRECT_STREAM_CODEC);
|
| 42 | private static final int SONG_END_PADDING_TICKS = 20;
|
| 43 |
|
| 44 | public int lengthInTicks() {
|
| 45 | return Mth.ceil(this.lengthInSeconds * 20.0F);
|
| 46 | }
|
| 47 |
|
| 48 | public boolean hasFinished(final long ticksElapsed) {
|
| 49 | return ticksElapsed >= this.lengthInTicks() + 20;
|
| 50 | }
|
| 51 |
|
| 52 | public static Optional<Holder<JukeboxSong>> fromStack(final ItemStack stack) {
|
| 53 | JukeboxPlayable jukeboxPlayable = stack.get(DataComponents.JUKEBOX_PLAYABLE);
|
| 54 | return jukeboxPlayable != null ? Optional.of(jukeboxPlayable.song()) : Optional.empty();
|
| 55 | }
|
| 56 | }
|
| 57 |
|