forked from gnembon/fabric-carpet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHopperCounter.java
420 lines (396 loc) · 17.5 KB
/
HopperCounter.java
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
package carpet.helpers;
import carpet.CarpetServer;
import carpet.fakes.RecipeManagerInterface;
import carpet.utils.Messenger;
import it.unimi.dsi.fastutil.objects.Object2LongLinkedOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2LongMap;
import net.minecraft.ChatFormatting;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.TextColor;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.DyeColor;
import net.minecraft.world.item.DyeItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.world.level.block.AbstractBannerBlock;
import net.minecraft.world.level.block.BeaconBeamBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.material.MapColor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static java.util.Map.entry;
/**
* The actual object residing in each hopper counter which makes them count the items and saves them. There is one for each
* colour in MC.
*/
public class HopperCounter
{
/**
* A map of all the {@link HopperCounter} counters.
*/
private static final Map<DyeColor, HopperCounter> COUNTERS;
/**
* The default display colour of each item, which makes them look nicer when printing the counter contents to the chat
*/
public static final TextColor WHITE = TextColor.fromLegacyFormat(ChatFormatting.WHITE);
static
{
EnumMap<DyeColor, HopperCounter> counterMap = new EnumMap<>(DyeColor.class);
for (DyeColor color : DyeColor.values())
{
counterMap.put(color, new HopperCounter(color));
}
COUNTERS = Collections.unmodifiableMap(counterMap);
}
/**
* The counter's colour, determined by the colour of wool it's pointing into
*/
public final DyeColor color;
/**
* The string which is passed into {@link Messenger#m} which makes each counter name be displayed in the colour of
* that counter.
*/
private final String coloredName;
/**
* All the items stored within the counter, as a map of {@link Item} mapped to a {@code long} of the amount of items
* stored thus far of that item type.
*/
private final Object2LongMap<Item> counter = new Object2LongLinkedOpenHashMap<>();
/**
* The starting tick of the counter, used to calculate in-game time. Only initialised when the first item enters the
* counter
*/
private long startTick;
/**
* The starting millisecond of the counter, used to calculate IRl time. Only initialised when the first item enters
* the counter
*/
private long startMillis;
// private PubSubInfoProvider<Long> pubSubProvider;
private HopperCounter(DyeColor color)
{
startTick = -1;
this.color = color;
String hexColor = Integer.toHexString(color.getTextColor());
if (hexColor.length() < 6)
hexColor = "0".repeat(6 - hexColor.length()) + hexColor;
this.coloredName = '#' + hexColor + ' ' + color.getName();
}
/**
* Method used to add items to the counter. Note that this is when the {@link HopperCounter#startTick} and
* {@link HopperCounter#startMillis} variables are initialised, so you can place the counters and then start the farm
* after all the collection is sorted out.
*/
public void add(MinecraftServer server, ItemStack stack)
{
if (startTick < 0)
{
startTick = server.overworld().getGameTime();
startMillis = System.currentTimeMillis();
}
Item item = stack.getItem();
counter.put(item, counter.getLong(item) + stack.getCount());
// pubSubProvider.publish();
}
/**
* Resets the counter, clearing its items but keeping the clock running.
*/
public void reset(MinecraftServer server)
{
counter.clear();
startTick = server.overworld().getGameTime();
startMillis = System.currentTimeMillis();
// pubSubProvider.publish();
}
/**
* Resets all counters, clearing their items.
* @param fresh Whether or not to start the clocks going immediately or later.
*/
public static void resetAll(MinecraftServer server, boolean fresh)
{
for (HopperCounter counter : COUNTERS.values())
{
counter.reset(server);
if (fresh) counter.startTick = -1;
}
}
/**
* Prints all the counters to chat, nicely formatted, and you can choose whether to diplay in in game time or IRL time
*/
public static List<Component> formatAll(MinecraftServer server, boolean realtime)
{
List<Component> text = new ArrayList<>();
for (HopperCounter counter : COUNTERS.values())
{
List<Component> temp = counter.format(server, realtime, false);
if (temp.size() > 1)
{
if (!text.isEmpty()) text.add(Messenger.s(""));
text.addAll(temp);
}
}
if (text.isEmpty())
{
text.add(Messenger.s("No items have been counted yet."));
}
return text;
}
/**
* Prints a single counter's contents and timings to chat, with the option to keep it short (so no item breakdown,
* only rates). Again, realtime displays IRL time as opposed to in game time.
*/
public List<Component> format(MinecraftServer server, boolean realTime, boolean brief)
{
long ticks = Math.max(realTime ? (System.currentTimeMillis() - startMillis) / 50 : server.overworld().getGameTime() - startTick, 1);
if (startTick < 0)
{
if (brief)
{
return Collections.singletonList(Messenger.c("b"+coloredName,"w : ","gi -, -/h, - min "));
}
return Collections.singletonList(Messenger.c(coloredName, "w hasn't started counting yet"));
}
long total = getTotalItems();
if (total == 0)
{
if (brief)
{
return Collections.singletonList(Messenger.c("b"+coloredName,"w : ","wb 0","w , ","wb 0","w /h, ", String.format("wb %.1f ", ticks / (20.0 * 60.0)), "w min"));
}
return Collections.singletonList(Messenger.c("w No items for ", coloredName, String.format("w yet (%.2f min.%s)",
ticks / (20.0 * 60.0), (realTime ? " - real time" : "")),
"nb [X]", "^g reset", "!/counter " + color.getName() +" reset"));
}
if (brief)
{
return Collections.singletonList(Messenger.c("b"+coloredName,"w : ",
"wb "+total,"w , ",
"wb "+(total * (20 * 60 * 60) / ticks),"w /h, ",
String.format("wb %.1f ", ticks / (20.0 * 60.0)), "w min"
));
}
List<Component> items = new ArrayList<>();
items.add(Messenger.c("w Items for ", coloredName,
"w (",String.format("wb %.2f", ticks*1.0/(20*60)), "w min"+(realTime?" - real time":"")+"), ",
"w total: ", "wb "+total, "w , (",String.format("wb %.1f",total*1.0*(20*60*60)/ticks),"w /h):",
"nb [X]", "^g reset", "!/counter "+color+" reset"
));
items.addAll(counter.object2LongEntrySet().stream().sorted((e, f) -> Long.compare(f.getLongValue(), e.getLongValue())).map(e ->
{
Item item = e.getKey();
MutableComponent itemName = Component.translatable(item.getDescriptionId());
Style itemStyle = itemName.getStyle();
TextColor color = guessColor(item, server.registryAccess());
itemName.setStyle((color != null) ? itemStyle.withColor(color) : itemStyle.withItalic(true));
long count = e.getLongValue();
return Messenger.c("g - ", itemName,
"g : ","wb "+count,"g , ",
String.format("wb %.1f", count * (20.0 * 60.0 * 60.0) / ticks), "w /h"
);
}).toList());
return items;
}
/**
* Converts a colour to have a low brightness and uniform colour, so when it prints the items in different colours
* it's not too flashy and bright, but enough that it's not dull to look at.
*/
public static int appropriateColor(int color)
{
if (color == 0) return MapColor.SNOW.col;
int r = (color >> 16 & 255);
int g = (color >> 8 & 255);
int b = (color & 255);
if (r < 70) r = 70;
if (g < 70) g = 70;
if (b < 70) b = 70;
return (r << 16) + (g << 8) + b;
}
/**
* Maps items that don't get a good block to reference for colour, or those that colour is wrong to a number of blocks, so we can get their colours easily with the
* {@link Block#defaultMapColor()} method as these items have those same colours.
*/
private static final Map<Item, Block> DEFAULTS = Map.ofEntries(
entry(Items.DANDELION, Blocks.YELLOW_WOOL),
entry(Items.POPPY, Blocks.RED_WOOL),
entry(Items.BLUE_ORCHID, Blocks.LIGHT_BLUE_WOOL),
entry(Items.ALLIUM, Blocks.MAGENTA_WOOL),
entry(Items.AZURE_BLUET, Blocks.SNOW_BLOCK),
entry(Items.RED_TULIP, Blocks.RED_WOOL),
entry(Items.ORANGE_TULIP, Blocks.ORANGE_WOOL),
entry(Items.WHITE_TULIP, Blocks.SNOW_BLOCK),
entry(Items.PINK_TULIP, Blocks.PINK_WOOL),
entry(Items.OXEYE_DAISY, Blocks.SNOW_BLOCK),
entry(Items.CORNFLOWER, Blocks.BLUE_WOOL),
entry(Items.WITHER_ROSE, Blocks.BLACK_WOOL),
entry(Items.LILY_OF_THE_VALLEY, Blocks.WHITE_WOOL),
entry(Items.BROWN_MUSHROOM, Blocks.BROWN_MUSHROOM_BLOCK),
entry(Items.RED_MUSHROOM, Blocks.RED_MUSHROOM_BLOCK),
entry(Items.STICK, Blocks.OAK_PLANKS),
entry(Items.GOLD_INGOT, Blocks.GOLD_BLOCK),
entry(Items.IRON_INGOT, Blocks.IRON_BLOCK),
entry(Items.DIAMOND, Blocks.DIAMOND_BLOCK),
entry(Items.NETHERITE_INGOT, Blocks.NETHERITE_BLOCK),
entry(Items.SUNFLOWER, Blocks.YELLOW_WOOL),
entry(Items.LILAC, Blocks.MAGENTA_WOOL),
entry(Items.ROSE_BUSH, Blocks.RED_WOOL),
entry(Items.PEONY, Blocks.PINK_WOOL),
entry(Items.CARROT, Blocks.ORANGE_WOOL),
entry(Items.APPLE,Blocks.RED_WOOL),
entry(Items.WHEAT,Blocks.HAY_BLOCK),
entry(Items.PORKCHOP, Blocks.PINK_WOOL),
entry(Items.RABBIT,Blocks.PINK_WOOL),
entry(Items.CHICKEN,Blocks.WHITE_TERRACOTTA),
entry(Items.BEEF,Blocks.NETHERRACK),
entry(Items.ENCHANTED_GOLDEN_APPLE,Blocks.GOLD_BLOCK),
entry(Items.COD,Blocks.WHITE_TERRACOTTA),
entry(Items.SALMON,Blocks.ACACIA_PLANKS),
entry(Items.ROTTEN_FLESH,Blocks.BROWN_WOOL),
entry(Items.PUFFERFISH,Blocks.YELLOW_TERRACOTTA),
entry(Items.TROPICAL_FISH,Blocks.ORANGE_WOOL),
entry(Items.POTATO,Blocks.WHITE_TERRACOTTA),
entry(Items.MUTTON, Blocks.RED_WOOL),
entry(Items.BEETROOT,Blocks.NETHERRACK),
entry(Items.MELON_SLICE,Blocks.MELON),
entry(Items.POISONOUS_POTATO,Blocks.SLIME_BLOCK),
entry(Items.SPIDER_EYE,Blocks.NETHERRACK),
entry(Items.GUNPOWDER,Blocks.GRAY_WOOL),
entry(Items.TURTLE_SCUTE,Blocks.LIME_WOOL),
entry(Items.ARMADILLO_SCUTE,Blocks.ANCIENT_DEBRIS),
entry(Items.FEATHER,Blocks.WHITE_WOOL),
entry(Items.FLINT,Blocks.BLACK_WOOL),
entry(Items.LEATHER,Blocks.SPRUCE_PLANKS),
entry(Items.GLOWSTONE_DUST,Blocks.GLOWSTONE),
entry(Items.PAPER,Blocks.WHITE_WOOL),
entry(Items.BRICK,Blocks.BRICKS),
entry(Items.INK_SAC,Blocks.BLACK_WOOL),
entry(Items.SNOWBALL,Blocks.SNOW_BLOCK),
entry(Items.WATER_BUCKET,Blocks.WATER),
entry(Items.LAVA_BUCKET,Blocks.LAVA),
entry(Items.MILK_BUCKET,Blocks.WHITE_WOOL),
entry(Items.CLAY_BALL, Blocks.CLAY),
entry(Items.COCOA_BEANS,Blocks.COCOA),
entry(Items.BONE,Blocks.BONE_BLOCK),
entry(Items.COD_BUCKET,Blocks.BROWN_TERRACOTTA),
entry(Items.PUFFERFISH_BUCKET,Blocks.YELLOW_TERRACOTTA),
entry(Items.SALMON_BUCKET,Blocks.PINK_TERRACOTTA),
entry(Items.TROPICAL_FISH_BUCKET,Blocks.ORANGE_TERRACOTTA),
entry(Items.SUGAR,Blocks.WHITE_WOOL),
entry(Items.BLAZE_POWDER,Blocks.GOLD_BLOCK),
entry(Items.ENDER_PEARL,Blocks.WARPED_PLANKS),
entry(Items.NETHER_STAR,Blocks.DIAMOND_BLOCK),
entry(Items.PRISMARINE_CRYSTALS,Blocks.SEA_LANTERN),
entry(Items.PRISMARINE_SHARD,Blocks.PRISMARINE),
entry(Items.RABBIT_HIDE,Blocks.OAK_PLANKS),
entry(Items.CHORUS_FRUIT,Blocks.PURPUR_BLOCK),
entry(Items.SHULKER_SHELL,Blocks.SHULKER_BOX),
entry(Items.NAUTILUS_SHELL,Blocks.BONE_BLOCK),
entry(Items.HEART_OF_THE_SEA,Blocks.CONDUIT),
entry(Items.HONEYCOMB,Blocks.HONEYCOMB_BLOCK),
entry(Items.NAME_TAG,Blocks.BONE_BLOCK),
entry(Items.TOTEM_OF_UNDYING,Blocks.YELLOW_TERRACOTTA),
entry(Items.TRIDENT,Blocks.PRISMARINE),
entry(Items.GHAST_TEAR,Blocks.WHITE_WOOL),
entry(Items.PHANTOM_MEMBRANE,Blocks.BONE_BLOCK),
entry(Items.EGG,Blocks.BONE_BLOCK),
//entry(Items.,Blocks.),
entry(Items.COPPER_INGOT,Blocks.COPPER_BLOCK),
entry(Items.AMETHYST_SHARD, Blocks.AMETHYST_BLOCK));
/**
* Gets the colour to print an item in when printing its count in a hopper counter.
*/
public static TextColor fromItem(Item item, RegistryAccess registryAccess)
{
if (DEFAULTS.containsKey(item)) return TextColor.fromRgb(appropriateColor(DEFAULTS.get(item).defaultMapColor().col));
if (item instanceof DyeItem dye) return TextColor.fromRgb(appropriateColor(dye.getDyeColor().getMapColor().col));
Block block = null;
final Registry<Item> itemRegistry = registryAccess.registryOrThrow(Registries.ITEM);
final Registry<Block> blockRegistry = registryAccess.registryOrThrow(Registries.BLOCK);
ResourceLocation id = itemRegistry.getKey(item);
if (item instanceof BlockItem blockItem)
{
block = blockItem.getBlock();
}
else if (blockRegistry.getOptional(id).isPresent())
{
block = blockRegistry.get(id);
}
if (block != null)
{
if (block instanceof AbstractBannerBlock) return TextColor.fromRgb(appropriateColor(((AbstractBannerBlock) block).getColor().getMapColor().col));
if (block instanceof BeaconBeamBlock) return TextColor.fromRgb(appropriateColor( ((BeaconBeamBlock) block).getColor().getMapColor().col));
return TextColor.fromRgb(appropriateColor( block.defaultMapColor().col));
}
return null;
}
/**
* Guesses the item's colour from the item itself. It first calls {@link HopperCounter#fromItem} to see if it has a
* valid colour there, if not just makes a guess, and if that fails just returns null
*/
public static TextColor guessColor(Item item, RegistryAccess registryAccess)
{
TextColor direct = fromItem(item, registryAccess);
if (direct != null) return direct;
if (CarpetServer.minecraft_server == null) return WHITE;
ResourceLocation id = registryAccess.registryOrThrow(Registries.ITEM).getKey(item);
for (RecipeType<?> type: registryAccess.registryOrThrow(Registries.RECIPE_TYPE))
{
for (Recipe<?> r: ((RecipeManagerInterface) CarpetServer.minecraft_server.getRecipeManager()).getAllMatching(type, id, registryAccess))
{
for (Ingredient ingredient: r.getIngredients())
{
for (ItemStack iStak : ingredient.getItems())
{
TextColor cand = fromItem(iStak.getItem(), registryAccess);
if (cand != null)
return cand;
}
}
}
}
return null;
}
/**
* Returns the hopper counter for the given color
*/
public static HopperCounter getCounter(DyeColor color) {
return COUNTERS.get(color);
}
/**
* Returns the hopper counter from the colour name, if not null
*/
public static HopperCounter getCounter(String color)
{
try
{
DyeColor colorEnum = DyeColor.valueOf(color.toUpperCase(Locale.ROOT));
return COUNTERS.get(colorEnum);
}
catch (IllegalArgumentException e)
{
return null;
}
}
/**
* The total number of items in the counter
*/
public long getTotalItems()
{
return counter.isEmpty()?0:counter.values().longStream().sum();
}
}