-
-
Notifications
You must be signed in to change notification settings - Fork 104
/
InventoryCommand.java
453 lines (440 loc) · 22.3 KB
/
InventoryCommand.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
package com.denizenscript.denizen.scripts.commands.item;
import com.denizenscript.denizen.nms.NMSHandler;
import com.denizenscript.denizen.objects.*;
import com.denizenscript.denizen.objects.notable.NotableManager;
import com.denizenscript.denizen.scripts.containers.core.InventoryScriptHelper;
import com.denizenscript.denizen.utilities.Conversion;
import com.denizenscript.denizen.utilities.Utilities;
import com.denizenscript.denizen.utilities.debugging.Debug;
import com.denizenscript.denizen.utilities.inventory.SlotHelper;
import com.denizenscript.denizencore.exceptions.InvalidArgumentsException;
import com.denizenscript.denizencore.objects.*;
import com.denizenscript.denizencore.objects.core.*;
import com.denizenscript.denizencore.objects.properties.PropertyParser;
import com.denizenscript.denizencore.scripts.ScriptEntry;
import com.denizenscript.denizencore.scripts.commands.AbstractCommand;
import com.denizenscript.denizencore.scripts.commands.core.FlagCommand;
import com.denizenscript.denizencore.utilities.Deprecations;
import com.denizenscript.denizencore.utilities.data.DataAction;
import com.denizenscript.denizencore.utilities.data.DataActionHelper;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.AbstractMap;
import java.util.HashSet;
import java.util.List;
import java.util.function.Consumer;
public class InventoryCommand extends AbstractCommand {
public InventoryCommand() {
setName("inventory");
setSyntax("inventory [open/close/copy/move/swap/set/keep/exclude/fill/clear/update/adjust <mechanism>:<value>/flag <name>(:<action>)[:<value>] (duration:<duration>)] (destination:<inventory>) (origin:<inventory>/<item>|...) (slot:<slot>)");
setRequiredArguments(1, 6);
isProcedural = false;
}
// <--[language]
// @name Virtual Inventories
// @group Inventory System
// @description
// Virtual inventories are inventories that have no attachment to anything within the world of Minecraft.
// They can be used for a wide range of purposes - from looting fallen enemies to serving as interactive menus with item 'buttons'.
//
// In Denizen, all noted inventories (saved by the Note command) are automatically converted into a virtual copy of the saved inventory.
// This enables you to open and edit the items inside freely, with automatic saving, as if it were a normal inventory.
//
// Noting is not the only way to create virtual inventories, however.
// Using 'generic' along with inventory properties will allow you to create temporary custom inventories to do with as you please.
// The properties that can be used like this are:
//
// size=<size>
// contents=<item>|...
// title=<title>
// holder=<inventory type>
//
// For example, the following task script opens a virtual inventory with 18 slots,
// where the second slot is a snowball, all the rest are empty, and the title is "My Awesome Inventory" with some colors in it.
// <code>
// open random inventory:
// type: task
// script:
// - inventory open "d:generic[size=18;title=<red>My <green>Awesome <blue>Inventory;contents=air|snow_ball]"
// </code>
//
// -->
// <--[command]
// @Name Inventory
// @Syntax inventory [open/close/copy/move/swap/set/keep/exclude/fill/clear/update/adjust <mechanism>:<value>/flag <name>(:<action>)[:<value>] (duration:<duration>)] (destination:<inventory>) (origin:<inventory>/<item>|...) (slot:<slot>)
// @Required 1
// @Maximum 6
// @Short Edits the inventory of a player, NPC, or chest.
// @Group item
//
// @Description
// Use this command to edit the state of inventories.
// By default, the destination inventory is the current attached player's inventory.
//
// If you are copying, swapping, removing from (including via "keep" and "exclude"), adding to, moving, or filling inventories,
// you'll need both destination and origin inventories.
//
// Origin inventories may be specified as a list of ItemTags, but destinations must be actual InventoryTags.
//
// Using "open", "clear", or "update" only require a destination.
// "Update" also requires the destination to be a valid player inventory.
//
// Using "close" closes any inventory that the currently attached player has opened.
//
// The "adjust" option adjusts mechanisms on an item within a specific slot of an inventory (the "slot" parameter is required).
// Note that this is only for items, it does NOT adjust the inventory itself. Use <@link command adjust> to adjust an inventory mechanism.
//
// The "flag" option sets a flag on items, similar to <@link command flag>.
// See also <@link language flag system>.
//
// The "update" option will refresh the client's view of an inventory to match the server's view, which is useful to workaround some sync bugs.
//
// Note that to add items to an inventory, you should usually use <@link command give>,
// and to remove items from an inventory, you should usually use <@link command take>.
//
// The slot argument can be any valid slot, see <@link language Slot Inputs>.
//
// @Tags
// <PlayerTag.inventory>
// <PlayerTag.enderchest>
// <PlayerTag.open_inventory>
// <NPCTag.inventory>
// <LocationTag.inventory>
//
// @Usage
// Use to open a chest inventory, at a location.
// - inventory open d:<context.location>
//
// @Usage
// Use to open a virtual inventory with a title and some items.
// - inventory open d:generic[size=27;title=BestInventory;contents=snow_ball|stick]
//
// @Usage
// Use to open another player's inventory.
// - inventory open d:<[player].inventory>
//
// @Usage
// Use to remove all items from a chest, except any items in the specified list.
// - inventory keep d:<context.location.inventory> o:snow_ball|ItemScript
//
// @Usage
// Use to remove all sticks and stones from the player's inventory.
// - inventory exclude origin:stick|stone
//
// @Usage
// Use to clear the player's inventory entirely.
// - inventory clear
//
// @Usage
// Use to swap two players' inventories.
// - inventory swap d:<[playerOne].inventory> o:<[playerTwo].inventory>
//
// @Usage
// Use to adjust a specific item in the player's inventory.
// - inventory adjust slot:5 "lore:Item modified!"
//
// @Usage
// Use to set a single stick into slot 10 of the player's inventory.
// - inventory set o:stick slot:10
//
// @Usage
// Use to set a temporary flag on the player's held item.
// - inventory flag slot:hand my_target:<player.cursor_on> duration:1d
// -->
private enum Action {OPEN, CLOSE, COPY, MOVE, SWAP, ADD, REMOVE, SET, KEEP, EXCLUDE, FILL, CLEAR, UPDATE, ADJUST, FLAG}
@Override
public void addCustomTabCompletions(String arg, Consumer<String> addOne) {
for (String mech : PropertyParser.propertiesByClass.get(ItemTag.class).propertiesByMechanism.keySet()) {
addOne.accept(mech);
}
if (arg.contains(":")) {
Consumer<String> addAll = (s) -> {
addOne.accept("o:" + s);
addOne.accept("origin:" + s);
addOne.accept("d:" + s);
addOne.accept("dest:" + s);
addOne.accept("destination:" + s);
};
for (InventoryTag inventory : (HashSet<InventoryTag>) ((HashSet) NotableManager.notesByType.get(InventoryTag.class))) {
addAll.accept(inventory.noteName);
}
for (String script : InventoryScriptHelper.inventoryScripts.keySet()) {
addAll.accept(script);
}
}
}
@Override
public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException {
boolean isAdjust = false, isFlag = false;
for (Argument arg : scriptEntry.getProcessedArgs()) {
if (!scriptEntry.hasObject("origin")
&& arg.matchesPrefix("origin", "o", "source", "items", "item", "i", "from", "f")
&& (arg.matchesArgumentTypes(InventoryTag.class, EntityTag.class, LocationTag.class, MapTag.class)
|| arg.matchesArgumentList(ItemTag.class))) {
scriptEntry.addObject("origin", Conversion.getInventory(arg, scriptEntry));
}
else if (!scriptEntry.hasObject("destination")
&& arg.matchesPrefix("destination", "dest", "d", "target", "to", "t")
&& arg.matchesArgumentTypes(InventoryTag.class, EntityTag.class, LocationTag.class)) {
scriptEntry.addObject("destination", Conversion.getInventory(arg, scriptEntry));
}
else if (!scriptEntry.hasObject("slot")
&& arg.matchesPrefix("slot", "s")) {
scriptEntry.addObject("slot", arg.asElement());
}
else if (!scriptEntry.hasObject("actions")
&& arg.matchesEnumList(Action.values())) {
scriptEntry.addObject("actions", arg.asType(ListTag.class).filter(Action.values()));
isAdjust = arg.toString().equalsIgnoreCase("adjust");
isFlag = arg.toString().equalsIgnoreCase("flag");
}
else if (!scriptEntry.hasObject("mechanism")
&& isAdjust) {
if (arg.hasPrefix()) {
scriptEntry.addObject("mechanism", new ElementTag(arg.getPrefix().getValue()));
scriptEntry.addObject("mechanism_value", arg.object);
}
else {
scriptEntry.addObject("mechanism", arg.asElement());
}
}
else if (!scriptEntry.hasObject("duration")
&& arg.matchesPrefix("duration")
&& arg.matchesArgumentType(DurationTag.class)
&& isFlag) {
scriptEntry.addObject("duration", arg.asType(DurationTag.class));
}
else if (!scriptEntry.hasObject("flag_action")
&& isFlag) {
scriptEntry.addObject("flag_action", DataActionHelper.parse(new FlagCommand.FlagActionProvider(), arg, scriptEntry.context));
}
else {
arg.reportUnhandled();
}
}
// Check to make sure required arguments have been filled
if (!scriptEntry.hasObject("actions")) {
throw new InvalidArgumentsException("Must specify an Inventory action!");
}
if (isAdjust && !scriptEntry.hasObject("mechanism")) {
throw new InvalidArgumentsException("Inventory adjust must have a mechanism!");
}
if (isAdjust && !scriptEntry.hasObject("slot")) {
throw new InvalidArgumentsException("Inventory adjust must have an explicit slot!");
}
if (isFlag && !scriptEntry.hasObject("flag_action")) {
throw new InvalidArgumentsException("Inventory flag must have a flag action!");
}
scriptEntry.defaultObject("slot", new ElementTag(1));
scriptEntry.defaultObject("destination",
Utilities.entryHasPlayer(scriptEntry) ?
new AbstractMap.SimpleEntry<>(0, Utilities.getEntryPlayer(scriptEntry).getInventory()) : null);
if (!scriptEntry.hasObject("destination")) {
throw new InvalidArgumentsException("Must specify a Destination Inventory!");
}
}
@Override
public void execute(final ScriptEntry scriptEntry) {
List<String> actions = (List<String>) scriptEntry.getObject("actions");
AbstractMap.SimpleEntry<Integer, InventoryTag> originentry = (AbstractMap.SimpleEntry<Integer, InventoryTag>) scriptEntry.getObject("origin");
InventoryTag origin = originentry != null ? originentry.getValue() : null;
AbstractMap.SimpleEntry<Integer, InventoryTag> destinationentry = (AbstractMap.SimpleEntry<Integer, InventoryTag>) scriptEntry.getObject("destination");
InventoryTag destination = destinationentry.getValue();
ElementTag slot = scriptEntry.getElement("slot");
ElementTag mechanism = scriptEntry.getElement("mechanism");
ObjectTag mechanismValue = scriptEntry.getObjectTag("mechanism_value");
DataAction flagAction = (DataAction) scriptEntry.getObject("flag_action");
DurationTag duration = scriptEntry.getObjectTag("duration");
if (scriptEntry.dbCallShouldDebug()) {
Debug.report(scriptEntry, getName(), ArgumentHelper.debugObj("actions", actions.toString()), destination, origin, mechanism, mechanismValue, flagAction, duration, slot);
}
int slotId = SlotHelper.nameToIndexFor(slot.asString(), destination.getInventory().getHolder());
if (slotId < 0) {
if (slotId == -1) {
Debug.echoError(scriptEntry.getResidingQueue(), "The input '" + slot.asString() + "' is not a valid slot (unrecognized)!");
}
else {
Debug.echoError(scriptEntry.getResidingQueue(), "The input '" + slot.asString() + "' is not a valid slot (negative values are invalid)!");
}
return;
}
InventoryTag.trackTemporaryInventory(destination);
if (origin != null) {
InventoryTag.trackTemporaryInventory(origin);
}
for (String action : actions) {
switch (Action.valueOf(action.toUpperCase())) {
// Make the attached player open the destination inventory
case OPEN:
// Use special method to make opening workbenches work properly
if (destination.getIdType().equals("workbench")
|| destination.getIdHolder().equals(new ElementTag("workbench"))) {
Utilities.getEntryPlayer(scriptEntry).getPlayerEntity().openWorkbench(null, true);
}
// Otherwise, open inventory as usual
else {
Utilities.getEntryPlayer(scriptEntry).getPlayerEntity().openInventory(destination.getInventory());
}
break;
// Make the attached player close any open inventory
case CLOSE:
Utilities.getEntryPlayer(scriptEntry).getPlayerEntity().closeInventory();
break;
// Turn destination's contents into a copy of origin's
case COPY:
if (origin == null) {
Debug.echoError(scriptEntry.getResidingQueue(), "Missing origin argument!");
return;
}
replace(origin, destination);
break;
// Copy origin's contents to destination, then empty origin
case MOVE:
if (origin == null) {
Debug.echoError(scriptEntry.getResidingQueue(), "Missing origin argument!");
return;
}
replace(origin, destination);
origin.clear();
break;
// Swap the contents of the two inventories
case SWAP:
if (origin == null) {
Debug.echoError(scriptEntry.getResidingQueue(), "Missing origin argument!");
return;
}
InventoryTag temp = new InventoryTag(destination.getInventory().getContents());
replace(origin, destination);
replace(temp, origin);
break;
// Add origin's contents to destination
case ADD:
Deprecations.oldInventoryCommands.warn(scriptEntry);
if (origin == null) {
Debug.echoError(scriptEntry.getResidingQueue(), "Missing origin argument!");
return;
}
destination.add(slotId, origin.getContents());
break;
// Remove origin's contents from destination
case REMOVE:
Deprecations.oldInventoryCommands.warn(scriptEntry);
if (origin == null) {
Debug.echoError(scriptEntry.getResidingQueue(), "Missing origin argument!");
return;
}
remove(destination.getInventory(), origin.getContents());
break;
// Set items by slot
case SET:
if (origin == null) {
Debug.echoError(scriptEntry.getResidingQueue(), "Missing origin argument!");
return;
}
destination.setSlots(slotId, origin.getContents(), originentry.getKey());
break;
// Keep only items from the origin's contents in the destination
case KEEP: {
if (origin == null) {
Debug.echoError(scriptEntry.getResidingQueue(), "Missing origin argument!");
return;
}
ItemStack[] items = origin.getContents();
for (ItemStack invStack : destination.getInventory()) {
if (invStack != null) {
boolean keep = false;
// See if the item array contains
// this inventory item
for (ItemStack item : items) {
if (invStack.isSimilar(item)) {
keep = true;
break;
}
}
// If the item array did not contain
// this inventory item, remove it
// from the inventory
if (!keep) {
destination.getInventory().remove(invStack);
}
}
}
break;
}
// Exclude all items from the origin's contents in the destination
case EXCLUDE: {
if (origin == null) {
Debug.echoError(scriptEntry.getResidingQueue(), "Missing origin argument!");
return;
}
int oldCount = destination.count(null, false);
int newCount = -1;
while (oldCount != newCount) {
oldCount = newCount;
remove(destination.getInventory(), origin.getContents());
newCount = destination.count(null, false);
}
break;
}
// Add origin's contents over and over to destination until it is full
case FILL: {
if (origin == null) {
Debug.echoError(scriptEntry.getResidingQueue(), "Missing origin argument!");
return;
}
int oldCount = destination.count(null, false);
int newCount = -1;
while (oldCount != newCount) {
oldCount = newCount;
newCount = destination.add(0, origin.getContents()).count(null, false);
}
break;
}
// Clear the content of the destination inventory
case CLEAR:
destination.clear();
break;
// If this is a player inventory, update it
case UPDATE:
if (destination.idHolder instanceof PlayerTag) {
((PlayerTag) destination.idHolder).getPlayerEntity().updateInventory();
}
else {
Debug.echoError("Only player inventories can be force-updated!");
}
break;
case ADJUST:
ItemTag toAdjust = new ItemTag(destination.getInventory().getItem(slotId));
toAdjust.safeAdjust(new Mechanism(mechanism.asString(), mechanismValue, scriptEntry.getContext()));
NMSHandler.getItemHelper().setInventoryItem(destination.getInventory(), toAdjust.getItemStack(), slotId);
break;
case FLAG:
ItemTag toFlag = new ItemTag(destination.getInventory().getItem(slotId));
FlagCommand.FlagActionProvider provider = (FlagCommand.FlagActionProvider) flagAction.provider;
provider.expiration = duration == null ? null : new TimeTag(TimeTag.now().millis() + duration.getMillis());
provider.tracker = toFlag.getFlagTracker();
flagAction.execute(scriptEntry.context);
toFlag.reapplyTracker(provider.tracker);
NMSHandler.getItemHelper().setInventoryItem(destination.getInventory(), toFlag.getItemStack(), slotId);
break;
}
}
}
public void replace(InventoryTag origin, InventoryTag destination) {
// If the destination is smaller than our current inventory, add as many items as possible
if (destination.getSize() < origin.getSize()) {
destination.clear();
destination.add(0, origin.getContents());
}
else {
destination.setContents(origin.getContents());
}
}
public void remove(Inventory inventory, ItemStack[] items) {
for (ItemStack item : items) {
if (item != null) {
inventory.removeItem(item.clone());
}
}
}
}