-
Notifications
You must be signed in to change notification settings - Fork 1
/
RecipeParser.java
387 lines (358 loc) · 13.4 KB
/
RecipeParser.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
package io.github.cottonmc.libcd.api.tweaker.recipe;
import com.google.common.collect.Sets;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.mojang.datafixers.Dynamic;
import io.github.cottonmc.libcd.api.CDSyntaxError;
import io.github.cottonmc.libcd.api.tag.TagHelper;
import io.github.cottonmc.libcd.api.tweaker.util.TweakerUtils;
import io.github.cottonmc.libcd.api.util.GsonOps;
import io.github.cottonmc.libcd.api.util.NbtMatchType;
import io.github.cottonmc.libcd.impl.IngredientAccessUtils;
import io.netty.buffer.Unpooled;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.datafixer.NbtOps;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.recipe.Ingredient;
import net.minecraft.tag.ItemTags;
import net.minecraft.tag.Tag;
import net.minecraft.util.DefaultedList;
import net.minecraft.util.Identifier;
import net.minecraft.util.PacketByteBuf;
import net.minecraft.util.registry.Registry;
import java.util.*;
/**
* Helper class to make public versions private recipe methods
*/
public class RecipeParser {
/**
* Get an Ingredient from a string item or tag id.
* @param input The id to use, with a # at the front if it's a tag or -> between two ids for a getter
* @return the Ingredient for the given id
*/
public static Ingredient processIngredient(Object input) throws CDSyntaxError {
if (input instanceof Ingredient) return (Ingredient)input;
else if (input instanceof ItemStack) {
ItemStack stack = (ItemStack)input;
Ingredient ing = hackStackIngredients(stack);
if (stack.hasTag()) {
((IngredientAccessUtils)(Object)ing).libcd$setMatchType(NbtMatchType.EXACT);
}
return ing;
}
else if (input instanceof ItemStack[]) {
ItemStack[] stacks = (ItemStack[])input;
boolean needsTags = false;
for (int i = 0; i < stacks.length; i++) {
ItemStack stack = stacks[i];
if (stack.hasTag()) {
needsTags = true;
}
}
Ingredient ing = hackStackIngredients(stacks);
if (needsTags) {
((IngredientAccessUtils)(Object)ing).libcd$setMatchType(NbtMatchType.EXACT);
}
return ing;
}
else if (input instanceof String) {
String in = (String)input;
int index = in.indexOf('{');
String nbt = "";
NbtMatchType type = NbtMatchType.NONE;
List<ItemStack> stacks = new ArrayList<>();
if (index != -1) {
int andIndex = in.indexOf('&');
if (andIndex != -1) {
type = NbtMatchType.forName(in.substring(andIndex+1));
in = in.substring(0, andIndex);
}
nbt = in.substring(index);
in = in.substring(0, index);
}
if (in.indexOf('#') == 0) {
String tag = in.substring(1);
Tag<Item> itemTag = ItemTags.getContainer().get(new Identifier(tag));
if (itemTag == null) throw new CDSyntaxError("Failed to get item tag for input: " + in);
for (Item item : itemTag.values()) {
stacks.add(new ItemStack(item));
}
} else if (in.contains("->")) {
ItemStack stack = TweakerUtils.INSTANCE.getSpecialStack(in);
if (stack.isEmpty())
throw new CDSyntaxError("Failed to get special stack for input: " + in);
stacks.add(stack);
type = NbtMatchType.EXACT;
} else {
Item item = TweakerUtils.INSTANCE.getItem(in);
if (item == Items.AIR) throw new CDSyntaxError("Failed to get item for input: " + in);
stacks.add(new ItemStack(item));
}
if (!nbt.equals("")) {
for (ItemStack stack : stacks) {
if (!stack.hasTag() || stack.getTag().isEmpty()) TweakerUtils.INSTANCE.addNbtToStack(stack, nbt);
}
}
Ingredient ret = hackStackIngredients(stacks.toArray(new ItemStack[]{}));
((IngredientAccessUtils)(Object)ret).libcd$setMatchType(type);
return ret;
}
else throw new CDSyntaxError("Illegal object passed to recipe parser of type " + input.getClass().getName());
}
public static ItemStack processItemStack(Object input) throws CDSyntaxError {
if (input instanceof ItemStack) return (ItemStack) input;
else if (input instanceof String) {
String in = (String) input;
int atIndex = in.lastIndexOf('@');
int nbtIndex = in.indexOf('{');
int count = 1;
if (atIndex != -1 && atIndex > in.lastIndexOf('}')) {
count = Integer.parseInt(in.substring(atIndex + 1));
in = in.substring(0, atIndex);
}
String nbt = "";
if (nbtIndex != -1) {
nbt = in.substring(nbtIndex);
in = in.substring(0, nbtIndex);
}
Item item;
if (in.indexOf('#') == 0) {
String tag = in.substring(1);
Tag<Item> itemTag = ItemTags.getContainer().get(new Identifier(tag));
if (itemTag == null) throw new CDSyntaxError("Failed to get item tag for output: " + in);
item = TagHelper.ITEM.getDefaultEntry(itemTag);
} else if (in.contains("->")) {
ItemStack stack = TweakerUtils.INSTANCE.getSpecialStack(in);
if (stack.isEmpty())
throw new CDSyntaxError("Failed to get special stack for output: " + in);
if (stack.isStackable()) {
stack.setCount(count);
}
return stack;
} else {
item = TweakerUtils.INSTANCE.getItem(in);
}
ItemStack stack = new ItemStack(item, count);
if (!nbt.equals("")) {
TweakerUtils.INSTANCE.addNbtToStack(stack, nbt);
}
return stack;
}
else throw new CDSyntaxError("Illegal object passed to recipe parser of type " + input.getClass().getName());
}
/**
* Split a factory string into the ids of the factory/id.
* @param base The base factory string to split.
* @return A two-item array of the two parts of the getter.
*/
public static String[] processStackFactory(String base) {
String[] split = new String[2];
int splitter = base.indexOf("->");
split[0] = base.substring(0, splitter);
split[1] = base.substring(splitter + 2);
return split;
}
/**
* Process a grid of inputs CraftTweaker-style. Max of 3 width and height.
* @param inputs The array of string arrays to process inputs from
* @return The inputs converted into a single string array if the grid is valid
*/
public static Object[] processGrid(Object[][] inputs) throws CDSyntaxError {
return processGrid(inputs, 3, 3);
}
/**
* Process a grid of inputs CraftTweaker-style.
* @param inputs The array of string arrays to process inputs from
* @param maxWidth The maximum number of columns allowed
* @param maxHeight The maximum number of rows allowed
* @return The inputs converted into a single string array if the grid is valid
*/
public static Object[] processGrid(Object[][] inputs, int maxWidth, int maxHeight) throws CDSyntaxError {
if (inputs.length > maxHeight) throw new CDSyntaxError("Invalid pattern: too many rows, " + maxHeight + " is maximum");
if (inputs.length == 0) throw new CDSyntaxError("Invalid pattern: empty pattern is not allowed");
int width = inputs[0].length;
List<Object> output = new ArrayList<>();
for (int i = 0; i < inputs.length; i++) {
Object[] row = inputs[i];
if (row.length > maxWidth) throw new CDSyntaxError("Invalid pattern: too many columns, " + maxWidth + " is maximum");
if (row.length != width) throw new CDSyntaxError("Invalid pattern: each row must be the same width");
for (int j = 0; j < width; j++) {
output.add(inputs[i][j]);
}
}
return output.toArray();
}
/**
* validate and parse a recipe pattern. Max of 3 width and height.
* @param pattern up to three strings of up to three characters each for the pattern
* @return processed pattern
*/
public static String[] processPattern(String... pattern) throws CDSyntaxError {
return processPattern(3, 3, pattern);
}
/**
* Validate and parse a recipe pattern.
* @param maxWidth The maximum number of columns allowed
* @param maxHeight The maximum number of rows allowed
* @param pattern Up to <height> strings of up to <width> characters each for the pattern
* @return processed pattern
*/
public static String[] processPattern(int maxWidth, int maxHeight, String... pattern) throws CDSyntaxError {
if (pattern.length > 3) {
throw new CDSyntaxError("Invalid pattern: too many rows, " + maxHeight + " is maximum");
} else if (pattern.length == 0) {
throw new CDSyntaxError("Invalid pattern: empty pattern not allowed");
} else {
for (int i = 0; i < pattern.length; i++) {
String row = pattern[i];
if (row.length() > 3) {
throw new CDSyntaxError("Invalid pattern: too many columns, " + maxWidth + " is maximum");
}
if (i > 0 && pattern[0].length() != row.length()) {
throw new CDSyntaxError("Invalid pattern: each row must be the same width");
}
pattern[i] = row;
}
int nextIndex = 2147483647;
int highIndex = 0;
int checked = 0;
int sinceLastEmpty = 0;
for (int i = 0; i < pattern.length; ++i) {
String input = pattern[i];
nextIndex = Math.min(nextIndex, findNextIngredient(input));
int lastIndex = findNextIngredientReverse(input);
highIndex = Math.max(highIndex, lastIndex);
if (lastIndex < 0) {
if (checked == i) {
++checked;
}
++sinceLastEmpty;
} else {
sinceLastEmpty = 0;
}
}
if (pattern.length == sinceLastEmpty) {
return new String[0];
} else {
String[] combined = new String[pattern.length - sinceLastEmpty - checked];
for (int i = 0; i < combined.length; ++i) {
combined[i] = pattern[i + checked].substring(nextIndex, highIndex + 1);
}
return combined;
}
}
}
/**
* Process dictionaries into a Recipe-readable form.
* @param dictionary a map of keys to values for a recipe to parse.
* @return A map of string keys to ingredient values that a Recipe can read.
*/
public static Map<String, Ingredient> processDictionary(Map<String, Object> dictionary) throws CDSyntaxError {
Map<String, Ingredient> map = new HashMap<>();
for (Map.Entry<String, Object> entry : dictionary.entrySet()) {
if (entry.getKey().length() != 1) {
throw new CDSyntaxError("Invalid key entry: '" + entry.getKey() + "' is an invalid symbol (must be 1 character only).");
}
if (" ".equals(entry.getKey())) {
throw new CDSyntaxError("Invalid key entry: ' ' is a reserved symbol.");
}
map.put(entry.getKey(), processIngredient(entry.getValue()));
}
map.put(" ", Ingredient.EMPTY);
return map;
}
/**
* Compile a pattern and dictionary into a full ingredient list.
* @param pattern A patern parsed by processPattern.
* @param dictionary A dictionary parsed by processDictionary.
* @param x How many columns there are.
* @param y How many rows there are.
* @return A defaulted list of ingredients.
*/
public static DefaultedList<Ingredient> getIngredients(String[] pattern, Map<String, Ingredient> dictionary, int x, int y) throws CDSyntaxError {
DefaultedList<Ingredient> ingredients = DefaultedList.ofSize(x * y, Ingredient.EMPTY);
Set<String> keys = Sets.newHashSet(dictionary.keySet());
keys.remove(" ");
for(int i = 0; i < pattern.length; i++) {
for(int j = 0; j < pattern[i].length(); j++) {
String key = pattern[i].substring(j, j + 1);
Ingredient ingredient = dictionary.get(key);
if (ingredient == null) {
throw new CDSyntaxError("Pattern references symbol '" + key + "' but it's not defined in the key");
}
keys.remove(key);
ingredients.set(j + x * i, ingredient);
}
}
if (!keys.isEmpty()) {
throw new CDSyntaxError("Key defines symbols that aren't used in pattern: " + keys);
} else {
return ingredients;
}
}
/**
* Skip forwards through a recipe row to find an ingredient key
* @param input a recipe row to parse
* @return index for the next ingredient character
*/
private static int findNextIngredient(String input) {
int i;
for (i = 0; i < input.length() && input.charAt(i) == ' '; i++) { }
return i;
}
/**
* Skip backwards through a recipe row to find an ingredient key
* @param input a recipe row to parse
* @return index for the next ingredient character
*/
private static int findNextIngredientReverse(String input) {
int i;
for (i = input.length() - 1; i >= 0 && input.charAt(i) == ' '; i--) { }
return i;
}
/**
* Thanks, ProGuard! The `Ingredient.ofStacks()` method is currently only in the client environment,
* so I have to write this ugly, terrible hack to make it work!
* Serializes the input stacks into a PacketByteBuf,
* then tricks the Ingredient class into deserializing them.
* However, if NBT Crafting is here, I can just do it with that!
* @param stacks The input stacks to support.
* @return The ingredient object for the input stacks.
*/
public static Ingredient hackStackIngredients(ItemStack...stacks) {
if (FabricLoader.getInstance().isModLoaded("nbtcrafting")) {
if (stacks.length > 1) {
JsonArray array = new JsonArray();
for (ItemStack stack : stacks) {
array.add(serializeStack(stack));
}
return Ingredient.fromJson(array);
} else {
return Ingredient.fromJson(serializeStack(stacks[0]));
}
// return IngredientAssembler.constructFromStacks(stacks);
} else {
PacketByteBuf buf = new PacketByteBuf(Unpooled.buffer());
buf.writeVarInt(stacks.length);
for (ItemStack stack : stacks) {
buf.writeItemStack(stack);
}
return Ingredient.fromPacket(buf);
}
}
/*
* Helpful if the NBT Crafting `constructFromStacks` doesn't work. It doesn't currently, so here it is.
*/
private static JsonObject serializeStack(ItemStack stack) {
JsonObject ret = new JsonObject();
ret.addProperty("item", Registry.ITEM.getId(stack.getItem()).toString());
ret.addProperty("count", stack.getCount());
if (stack.hasTag()) {
JsonObject data = Dynamic.convert(NbtOps.INSTANCE, GsonOps.INSTANCE, stack.getTag()).getAsJsonObject();
ret.add("data", data);
}
return ret;
}
}