summary refs log tree commit diff stats
path: root/src/main/java/ganarchy/chewstuff/ChewableItem.java
blob: 5e637c41ffd8de96a2f6b7fdb2ba658b60c2ed5f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package ganarchy.chewstuff;

import dev.emi.trinkets.api.SlotReference;
import dev.emi.trinkets.api.TrinketItem;
import dev.emi.trinkets.api.TrinketsApi;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.network.packet.s2c.play.EntityStatusEffectS2CPacket;
import net.minecraft.server.network.ServerPlayerEntity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * An item that can be chewed.
 */
public class ChewableItem extends TrinketItem {
    /**
     * The cooldown between activations, in ticks.
     */
    private static final int COOLDOWN = 5 * 20;
    /**
     * Number of effects to bind to.
     */
    private final int effects;

    /**
     * @param effects  Number of effects to bind to.
     * @param settings The item settings.
     */
    public ChewableItem(int effects, Settings settings) {
        super(settings);
        this.effects = effects;
    }

    @Override
    public void onEquip(ItemStack stack, SlotReference slot, LivingEntity entity) {
        if (entity.getWorld().isClient) {
            return;
        }
        var maybeInfo = ChewComponents.CHEW.maybeGet(entity);
        maybeInfo.ifPresent(info -> {
            info.sendUpdate = true;
        });
    }

    @Override
    public void onUnequip(
        ItemStack stack, SlotReference slot, LivingEntity entity
    ) {
        if (entity.getWorld().isClient) {
            return;
        }
        var maybeInfo = ChewComponents.CHEW.maybeGet(entity);
        maybeInfo.ifPresent(info -> {
            if (!info.effects.isEmpty()) {
                resetEffects(entity, info);
            }
        });
    }

    @Override
    public void tick(ItemStack stack, SlotReference slot, LivingEntity entity) {
        if (entity.getWorld().isClient) {
            return;
        }
        if (entity instanceof PlayerEntity player) {
            if (player.getItemCooldownManager().isCoolingDown(this)) {
                return;
            }
        }
        var maybeInfo = ChewComponents.CHEW.maybeGet(entity);
        maybeInfo.ifPresent(info -> {
            if (info.effects.isEmpty()) {
                var effects = entity.getStatusEffects();
                if (effects.size() >= this.effects) {
                    effects = new ArrayList<>(effects);
                    Collections.shuffle((List<?>) effects);
                    info.effects = effects.stream().filter(
                        effect -> !effect.isAmbient()
                    ).limit(this.effects).collect(
                        Collectors.toMap(
                            StatusEffectInstance::getEffectType,
                            StatusEffectInstance::getDuration,
                            (i1, i2) -> {
                                // don't crash the game in prod
                                if (
                                    FabricLoader.getInstance()
                                        .isDevelopmentEnvironment()
                                ) {
                                    throw new IllegalStateException();
                                } else {
                                    return Integer.min(i1, i2);
                                }
                            },
                            HashMap::new
                        )
                    );
                    info.sendUpdate = true;
                } else {
                    return;
                }
            }
            if (info.effects.size() != this.effects) {
                return;
            }
            if (info.sendUpdate) {
                sendEffectUpdate(entity, info);
            }
            var effects = info.effects.keySet();
            for (StatusEffect effect : effects) {
                if (info.effects.get(effect) <= 0) {
                    continue;
                }
                var effectInstance = entity.getStatusEffect(effect);
                if (effectInstance == null || effectInstance.isAmbient()) {
                    info.effects.put(effect, 0);
                    continue;
                }
                // don't wanna deal with LivingEntity internals.
                if (effectInstance.getDuration() == 1) {
                    continue;
                }
                if (!effectInstance.update(entity, () -> {})) {
                    throw new IllegalStateException();
                }
            }
            if (info.effects.values().stream().allMatch(i -> i == 0)) {
                resetEffects(entity, info);
            }
            stack.damage(1, entity, livingEntity -> {
                TrinketsApi.onTrinketBroken(stack, slot, livingEntity);
            });
        });
    }

    private void sendEffectUpdate(LivingEntity entity, ChewComponent info) {
        if (entity instanceof ServerPlayerEntity player) {
            for (StatusEffect effect : info.effects.keySet()) {
                var instance = player.getStatusEffect(effect);
                if (instance == null) {
                    continue;
                }
                NbtCompound nbt = new NbtCompound();
                instance.writeNbt(nbt);
                nbt.putInt("Duration", instance.getDuration() / 2);
                var toSend = StatusEffectInstance.fromNbt(nbt);
                if (toSend != null) {
                    player.networkHandler.sendPacket(
                        new EntityStatusEffectS2CPacket(
                            player.getId(),
                            toSend
                        )
                    );
                }
            }
        }
    }

    /**
     * Stops tracking effects, enables the cooldown, and updates the player,
     * as needed.
     *
     * @param entity The entity.
     * @param info   The tracked effects.
     */
    private void resetEffects(LivingEntity entity, ChewComponent info) {
        if (entity instanceof ServerPlayerEntity player) {
            for (StatusEffect effect : info.effects.keySet()) {
                var instance = player.getStatusEffect(effect);
                if (instance == null) {
                    continue;
                }
                player.networkHandler.sendPacket(
                    new EntityStatusEffectS2CPacket(
                        player.getId(),
                        instance
                    )
                );
            }
            player.getItemCooldownManager().set(this, COOLDOWN);
        }
        info.effects.clear();
        info.applied.clear();
    }
}