/
WorldEdit.java
1662 lines (1444 loc) · 58.1 KB
/
WorldEdit.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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// $Id$
/*
* WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import javax.script.ScriptException;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.minecraft.util.commands.CommandUsageException;
import com.sk89q.minecraft.util.commands.CommandsManager;
import com.sk89q.minecraft.util.commands.Console;
import com.sk89q.minecraft.util.commands.Logging;
import com.sk89q.minecraft.util.commands.MissingNestedCommandException;
import com.sk89q.minecraft.util.commands.SimpleInjector;
import com.sk89q.minecraft.util.commands.UnhandledCommandException;
import com.sk89q.minecraft.util.commands.WrappedCommandException;
import com.sk89q.util.StringUtil;
import com.sk89q.worldedit.CuboidClipboard.FlipDirection;
import com.sk89q.worldedit.bags.BlockBag;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockType;
import com.sk89q.worldedit.blocks.ClothColor;
import com.sk89q.worldedit.blocks.ItemType;
import com.sk89q.worldedit.blocks.MobSpawnerBlock;
import com.sk89q.worldedit.blocks.NoteBlock;
import com.sk89q.worldedit.blocks.SignBlock;
import com.sk89q.worldedit.blocks.SkullBlock;
import com.sk89q.worldedit.commands.BiomeCommands;
import com.sk89q.worldedit.commands.ChunkCommands;
import com.sk89q.worldedit.commands.ClipboardCommands;
import com.sk89q.worldedit.commands.GeneralCommands;
import com.sk89q.worldedit.commands.GenerationCommands;
import com.sk89q.worldedit.commands.HistoryCommands;
import com.sk89q.worldedit.commands.InsufficientArgumentsException;
import com.sk89q.worldedit.commands.NavigationCommands;
import com.sk89q.worldedit.commands.RegionCommands;
import com.sk89q.worldedit.commands.ScriptingCommands;
import com.sk89q.worldedit.commands.SelectionCommands;
import com.sk89q.worldedit.commands.SnapshotUtilCommands;
import com.sk89q.worldedit.commands.ToolCommands;
import com.sk89q.worldedit.commands.ToolUtilCommands;
import com.sk89q.worldedit.commands.UtilityCommands;
import com.sk89q.worldedit.masks.BiomeTypeMask;
import com.sk89q.worldedit.masks.BlockMask;
import com.sk89q.worldedit.masks.CombinedMask;
import com.sk89q.worldedit.masks.DynamicRegionMask;
import com.sk89q.worldedit.masks.ExistingBlockMask;
import com.sk89q.worldedit.masks.InvertedMask;
import com.sk89q.worldedit.masks.Mask;
import com.sk89q.worldedit.masks.RandomMask;
import com.sk89q.worldedit.masks.RegionMask;
import com.sk89q.worldedit.masks.UnderOverlayMask;
import com.sk89q.worldedit.patterns.BlockChance;
import com.sk89q.worldedit.patterns.ClipboardPattern;
import com.sk89q.worldedit.patterns.Pattern;
import com.sk89q.worldedit.patterns.RandomFillPattern;
import com.sk89q.worldedit.patterns.SingleBlockPattern;
import com.sk89q.worldedit.regions.RegionSelector;
import com.sk89q.worldedit.scripting.CraftScriptContext;
import com.sk89q.worldedit.scripting.CraftScriptEngine;
import com.sk89q.worldedit.scripting.RhinoCraftScriptEngine;
import com.sk89q.worldedit.tools.BlockTool;
import com.sk89q.worldedit.tools.DoubleActionBlockTool;
import com.sk89q.worldedit.tools.DoubleActionTraceTool;
import com.sk89q.worldedit.tools.Tool;
import com.sk89q.worldedit.tools.TraceTool;
/**
* This class is the main entry point for WorldEdit. All events are routed
* to an instance of this controller for processing by WorldEdit. For
* integrating WorldEdit in other platforms, an instance of this class
* should be created and events should be redirected to it.
*
* @author sk89q
*/
public class WorldEdit {
/**
* Logger for debugging.
*/
public static final Logger logger = Logger.getLogger("Minecraft.WorldEdit");
public final Logger commandLogger = Logger.getLogger("Minecraft.WorldEdit.CommandLogger");
/**
* Holds the current instance of this class, for static access
*/
private static WorldEdit instance;
/**
* Holds WorldEdit's version.
*/
private static String version;
/**
* Interface to the server.
*/
private final ServerInterface server;
/**
* Configuration. This is a subclass.
*/
private final LocalConfiguration config;
/**
* List of commands.
*/
private final CommandsManager<LocalPlayer> commands;
/**
* Holds the factory responsible for the creation of edit sessions
*/
private EditSessionFactory editSessionFactory = new EditSessionFactory();
/**
* Stores a list of WorldEdit sessions, keyed by players' names. Sessions
* persist only for the user's session. On disconnect, the session will be
* removed. Sessions are created only when they are needed and those
* without any WorldEdit abilities or never use WorldEdit in a session will
* not have a session object generated for them.
*/
private final HashMap<String, LocalSession> sessions = new HashMap<String, LocalSession>();
/**
* Initialize statically.
*/
static {
getVersion();
}
/**
* Construct an instance of the plugin
*
* @param server
* @param config
*/
public WorldEdit(ServerInterface server, final LocalConfiguration config) {
instance = this;
this.server = server;
this.config = config;
if (!config.logFile.equals("")) {
try {
FileHandler logFileHandler;
logFileHandler = new FileHandler(new File(config.getWorkingDirectory(),
config.logFile).getAbsolutePath(), true);
logFileHandler.setFormatter(new LogFormat());
commandLogger.addHandler(logFileHandler);
} catch (IOException e) {
logger.log(Level.WARNING, "Could not use command log file " + config.logFile + ": "
+ e.getMessage());
}
}
commands = new CommandsManager<LocalPlayer>() {
@Override
protected void checkPermission(LocalPlayer player, Method method) throws CommandException {
if (!player.isPlayer() && !method.isAnnotationPresent(Console.class)) {
throw new UnhandledCommandException();
}
super.checkPermission(player, method);
}
@Override
public boolean hasPermission(LocalPlayer player, String perm) {
return player.hasPermission(perm);
}
@Override
public void invokeMethod(Method parent, String[] args,
LocalPlayer player, Method method, Object instance,
Object[] methodArgs, int level) throws CommandException {
if (config.logCommands) {
final Logging loggingAnnotation = method.getAnnotation(Logging.class);
final Logging.LogMode logMode;
if (loggingAnnotation == null) {
logMode = null;
} else {
logMode = loggingAnnotation.value();
}
String msg = "WorldEdit: " + player.getName();
if (player.isPlayer()) {
msg += " (in \"" + player.getWorld().getName() + "\")";
}
msg += ": " + StringUtil.joinString(args, " ");
if (logMode != null && player.isPlayer()) {
Vector position = player.getPosition();
final LocalSession session = getSession(player);
switch (logMode) {
case PLACEMENT:
try {
position = session.getPlacementPosition(player);
} catch (IncompleteRegionException e) {
break;
}
/* FALL-THROUGH */
case POSITION:
msg += " - Position: " + position;
break;
case ALL:
msg += " - Position: " + position;
/* FALL-THROUGH */
case ORIENTATION_REGION:
msg += " - Orientation: " + player.getCardinalDirection().name();
/* FALL-THROUGH */
case REGION:
try {
msg += " - Region: " + session.getSelection(player.getWorld());
} catch (IncompleteRegionException e) {
break;
}
break;
}
}
commandLogger.info(msg);
}
super.invokeMethod(parent, args, player, method, instance, methodArgs, level);
}
};
commands.setInjector(new SimpleInjector(this));
reg(BiomeCommands.class);
reg(ChunkCommands.class);
reg(ClipboardCommands.class);
reg(GeneralCommands.class);
reg(GenerationCommands.class);
reg(HistoryCommands.class);
reg(NavigationCommands.class);
reg(RegionCommands.class);
reg(ScriptingCommands.class);
reg(SelectionCommands.class);
reg(SnapshotUtilCommands.class);
reg(ToolUtilCommands.class);
reg(ToolCommands.class);
reg(UtilityCommands.class);
}
private void reg(Class<?> clazz) {
server.onCommandRegistration(commands.registerAndReturn(clazz), commands);
}
/**
* Gets the current instance of this class
*
* @return
*/
public static WorldEdit getInstance() {
return instance;
}
/**
* Gets the LocalSession for a player name if it exists
*
* @param player
* @return The session for the player, if it exists
*/
public LocalSession getSession(String player) {
return sessions.get(player);
}
/**
* Gets the WorldEdit session for a player.
*
* @param player
* @return
*/
public LocalSession getSession(LocalPlayer player) {
LocalSession session;
synchronized (sessions) {
if (sessions.containsKey(player.getName())) {
session = sessions.get(player.getName());
} else {
session = new LocalSession(config);
session.setBlockChangeLimit(config.defaultChangeLimit);
// Remember the session
sessions.put(player.getName(), session);
}
// Set the limit on the number of blocks that an operation can
// change at once, or don't if the player has an override or there
// is no limit. There is also a default limit
int currentChangeLimit = session.getBlockChangeLimit();
if (!player.hasPermission("worldedit.limit.unrestricted")
&& config.maxChangeLimit > -1) {
// If the default limit is infinite but there is a maximum
// limit, make sure to not have it be overridden
if (config.defaultChangeLimit < 0) {
if (currentChangeLimit < 0 || currentChangeLimit > config.maxChangeLimit) {
session.setBlockChangeLimit(config.maxChangeLimit);
}
} else {
// Bound the change limit
int maxChangeLimit = config.maxChangeLimit;
if (currentChangeLimit == -1 || currentChangeLimit > maxChangeLimit) {
session.setBlockChangeLimit(maxChangeLimit);
}
}
}
// Have the session use inventory if it's enabled and the player
// doesn't have an override
session.setUseInventory(config.useInventory
&& !((config.useInventoryOverride ||
(config.useInventoryCreativeOverride && player.hasCreativeMode()))
&& player.hasPermission("worldedit.inventory.unrestricted")));
}
return session;
}
/**
* Returns true if the player has a session.
*
* @param player
* @return
*/
public boolean hasSession(LocalPlayer player) {
// TODO: If this is indeed used in multiple threads, we should use Collections.synchronizedMap here to simplify things and exclude sources of error.
synchronized (sessions) {
return sessions.containsKey(player.getName());
}
}
public BaseBlock getBlock(LocalPlayer player, String arg, boolean allAllowed)
throws UnknownItemException, DisallowedItemException {
return getBlock(player, arg, allAllowed, false);
}
/**
* Get an item ID from an item name or an item ID number.
*
* @param player
* @param arg
* @param allAllowed true to ignore blacklists
* @return
* @throws UnknownItemException
* @throws DisallowedItemException
*/
public BaseBlock getBlock(LocalPlayer player, String arg,
boolean allAllowed, boolean allowNoData)
throws UnknownItemException, DisallowedItemException {
BlockType blockType;
arg = arg.replace("_", " ");
arg = arg.replace(";", "|");
String[] blockAndExtraData = arg.split("\\|");
String[] typeAndData = blockAndExtraData[0].split(":", 2);
String testID = typeAndData[0];
int blockId = -1;
int data = -1;
// Attempt to parse the item ID or otherwise resolve an item/block
// name to its numeric ID
try {
blockId = Integer.parseInt(testID);
blockType = BlockType.fromID(blockId);
} catch (NumberFormatException e) {
blockType = BlockType.lookup(testID);
if (blockType == null) {
int t = server.resolveItem(testID);
if (t > 0) {
blockType = BlockType.fromID(t); // Could be null
blockId = t;
}
}
}
if (blockId == -1 && blockType == null) {
// Maybe it's a cloth
ClothColor col = ClothColor.lookup(testID);
if (col != null) {
blockType = BlockType.CLOTH;
data = col.getID();
} else {
throw new UnknownItemException(arg);
}
}
// Read block ID
if (blockId == -1) {
blockId = blockType.getID();
}
if (!player.getWorld().isValidBlockType(blockId)) {
throw new UnknownItemException(arg);
}
if (data == -1) { // Block data not yet detected
// Parse the block data (optional)
try {
data = (typeAndData.length > 1 && typeAndData[1].length() > 0) ? Integer.parseInt(typeAndData[1]) : (allowNoData ? -1 : 0);
if ((data > 15 && !config.allowExtraDataValues) || (data < 0 && !(allAllowed && data == -1))) {
data = 0;
}
} catch (NumberFormatException e) {
if (blockType != null) {
switch (blockType) {
case CLOTH:
ClothColor col = ClothColor.lookup(typeAndData[1]);
if (col != null) {
data = col.getID();
} else {
throw new InvalidItemException(arg, "Unknown cloth color '" + typeAndData[1] + "'");
}
break;
case STEP:
case DOUBLE_STEP:
BlockType dataType = BlockType.lookup(typeAndData[1]);
if (dataType != null) {
switch (dataType) {
case STONE:
data = 0;
break;
case SANDSTONE:
data = 1;
break;
case WOOD:
data = 2;
break;
case COBBLESTONE:
data = 3;
break;
case BRICK:
data = 4;
break;
case STONE_BRICK:
data = 5;
break;
case NETHER_BRICK:
data = 6;
break;
default:
throw new InvalidItemException(arg, "Invalid step type '" + typeAndData[1] + "'");
}
} else {
throw new InvalidItemException(arg, "Unknown step type '" + typeAndData[1] + "'");
}
break;
default:
throw new InvalidItemException(arg, "Unknown data value '" + typeAndData[1] + "'");
}
} else {
throw new InvalidItemException(arg, "Unknown data value '" + typeAndData[1] + "'");
}
}
}
// Check if the item is allowed
if (allAllowed || player.hasPermission("worldedit.anyblock") || !config.disallowedBlocks.contains(blockId)) {
if (blockType != null) {
switch (blockType) {
case SIGN_POST:
case WALL_SIGN:
// Allow special sign text syntax
String[] text = new String[4];
text[0] = blockAndExtraData.length > 1 ? blockAndExtraData[1] : "";
text[1] = blockAndExtraData.length > 2 ? blockAndExtraData[2] : "";
text[2] = blockAndExtraData.length > 3 ? blockAndExtraData[3] : "";
text[3] = blockAndExtraData.length > 4 ? blockAndExtraData[4] : "";
return new SignBlock(blockType.getID(), data, text);
case MOB_SPAWNER:
// Allow setting mob spawn type
if (blockAndExtraData.length > 1) {
String mobName = blockAndExtraData[1];
for (MobType mobType : MobType.values()) {
if (mobType.getName().toLowerCase().equals(mobName.toLowerCase())) {
mobName = mobType.getName();
break;
}
}
if (!server.isValidMobType(mobName)) {
throw new InvalidItemException(arg, "Unknown mob type '" + mobName + "'");
}
return new MobSpawnerBlock(data, mobName);
} else {
return new MobSpawnerBlock(data, MobType.PIG.getName());
}
case NOTE_BLOCK:
// Allow setting note
if (blockAndExtraData.length > 1) {
byte note = Byte.parseByte(blockAndExtraData[1]);
if (note < 0 || note > 24) {
throw new InvalidItemException(arg, "Out of range note value: '" + blockAndExtraData[1] + "'");
} else {
return new NoteBlock(data, note);
}
} else {
return new NoteBlock(data, (byte) 0);
}
case HEAD:
// allow setting type/player/rotation
if (blockAndExtraData.length > 1) {
// and thus, the format shall be "|type|rotation" or "|type" or "|rotation"
byte rot = 0;
String type = "";
try {
rot = Byte.parseByte(blockAndExtraData[1]);
} catch (NumberFormatException e) {
type = blockAndExtraData[1];
if (blockAndExtraData.length > 2) {
try {
rot = Byte.parseByte(blockAndExtraData[2]);
} catch (NumberFormatException e2) {
throw new InvalidItemException(arg, "Second part of skull metadata should be a number.");
}
}
}
byte skullType = 0;
// type is either the mob type or the player name
// sorry for the four minecraft accounts named "skeleton", "wither", "zombie", or "creeper"
if (!type.isEmpty()) {
if (type.equalsIgnoreCase("skeleton")) skullType = 0;
else if (type.equalsIgnoreCase("wither")) skullType = 1;
else if (type.equalsIgnoreCase("zombie")) skullType = 2;
else if (type.equalsIgnoreCase("creeper")) skullType = 4;
else skullType = 3;
}
if (skullType == 3) {
return new SkullBlock(data, rot, type.replace(" ", "_")); // valid MC usernames
} else {
return new SkullBlock(data, skullType, rot);
}
} else {
return new SkullBlock(data);
}
default:
return new BaseBlock(blockId, data);
}
} else {
return new BaseBlock(blockId, data);
}
}
throw new DisallowedItemException(arg);
}
/**
* Get a block.
*
* @param player
* @param id
* @return
* @throws UnknownItemException
* @throws DisallowedItemException
*/
public BaseBlock getBlock(LocalPlayer player, String id)
throws UnknownItemException, DisallowedItemException {
return getBlock(player, id, false);
}
public Set<BaseBlock> getBlocks(LocalPlayer player, String list, boolean allAllowed, boolean allowNoData)
throws DisallowedItemException, UnknownItemException {
String[] items = list.split(",");
Set<BaseBlock> blocks = new HashSet<BaseBlock>();
for (String id : items) {
blocks.add(getBlock(player, id, allAllowed, allowNoData));
}
return blocks;
}
public Set<BaseBlock> getBlocks(LocalPlayer player, String list, boolean allAllowed)
throws DisallowedItemException, UnknownItemException {
return getBlocks(player, list, allAllowed, false);
}
public Set<BaseBlock> getBlocks(LocalPlayer player, String list)
throws DisallowedItemException, UnknownItemException {
return getBlocks(player, list, false);
}
/**
* Returns a Pattern corresponding to the specified pattern string,
* as given by the player on the command line.
*
* @param player
* @param patternString
* @return pattern
* @throws UnknownItemException
* @throws DisallowedItemException
*/
public Pattern getBlockPattern(LocalPlayer player, String patternString)
throws UnknownItemException, DisallowedItemException {
String[] items = patternString.split(",");
// Handle special block pattern types
if (patternString.charAt(0) == '#') {
if (patternString.equals("#clipboard") || patternString.equals("#copy")) {
LocalSession session = getSession(player);
CuboidClipboard clipboard;
try {
clipboard = session.getClipboard();
} catch (EmptyClipboardException e) {
player.printError("Copy a selection first with //copy.");
throw new UnknownItemException("#clipboard");
}
return new ClipboardPattern(clipboard);
} else {
throw new UnknownItemException(patternString);
}
}
// If it's only one block, then just return that single one
if (items.length == 1) {
return new SingleBlockPattern(getBlock(player, items[0]));
}
List<BlockChance> blockChances = new ArrayList<BlockChance>();
for (String s : items) {
BaseBlock block;
double chance;
// Parse special percentage syntax
if (s.matches("[0-9]+(\\.[0-9]*)?%.*")) {
String[] p = s.split("%");
chance = Double.parseDouble(p[0]);
block = getBlock(player, p[1]);
} else {
chance = 1;
block = getBlock(player, s);
}
blockChances.add(new BlockChance(block, chance));
}
return new RandomFillPattern(blockChances);
}
/**
* Get a block mask. Block masks are used to determine which
* blocks to include when replacing.
*
* @param player
* @param session
* @param maskString
* @return
* @throws WorldEditException
*/
public Mask getBlockMask(LocalPlayer player, LocalSession session,
String maskString) throws WorldEditException {
List<Mask> masks = new ArrayList<Mask>();
for (String component : maskString.split(" ")) {
if (component.length() == 0) {
continue;
}
Mask current = getBlockMaskComponent(player, session, masks, component);
masks.add(current);
}
switch (masks.size()) {
case 0:
return null;
case 1:
return masks.get(0);
default:
return new CombinedMask(masks);
}
}
private Mask getBlockMaskComponent(LocalPlayer player, LocalSession session, List<Mask> masks, String component) throws WorldEditException {
final char firstChar = component.charAt(0);
switch (firstChar) {
case '#':
if (component.equalsIgnoreCase("#existing")) {
return new ExistingBlockMask();
} else if (component.equalsIgnoreCase("#dregion")
|| component.equalsIgnoreCase("#dselection")
|| component.equalsIgnoreCase("#dsel")) {
return new DynamicRegionMask();
} else if (component.equalsIgnoreCase("#selection")
|| component.equalsIgnoreCase("#region")
|| component.equalsIgnoreCase("#sel")) {
return new RegionMask(session.getSelection(player.getWorld()));
} else {
throw new UnknownItemException(component);
}
case '>':
case '<':
Mask submask;
if (component.length() > 1) {
submask = getBlockMaskComponent(player, session, masks, component.substring(1));
} else {
submask = new ExistingBlockMask();
}
return new UnderOverlayMask(submask, firstChar == '>');
case '$':
Set<BiomeType> biomes = new HashSet<BiomeType>();
String[] biomesList = component.substring(1).split(",");
for (String biomeName : biomesList) {
BiomeType biome = server.getBiomes().get(biomeName);
biomes.add(biome);
}
return new BiomeTypeMask(biomes);
case '%':
int i = Integer.parseInt(component.substring(1));
return new RandomMask(((double) i) / 100);
case '!':
if (component.length() > 1) {
return new InvertedMask(getBlockMaskComponent(player, session, masks, component.substring(1)));
}
default:
return new BlockMask(getBlocks(player, component, true, true));
}
}
/**
* Get a list of blocks as a set.
*
* @param player
* @param list
* @param allBlocksAllowed
* @return set
* @throws UnknownItemException
* @throws DisallowedItemException
*/
public Set<Integer> getBlockIDs(LocalPlayer player,
String list, boolean allBlocksAllowed)
throws UnknownItemException, DisallowedItemException {
String[] items = list.split(",");
Set<Integer> blocks = new HashSet<Integer>();
for (String s : items) {
blocks.add(getBlock(player, s, allBlocksAllowed).getType());
}
return blocks;
}
/**
* Gets the path to a file. This method will check to see if the filename
* has valid characters and has an extension. It also prevents directory
* traversal exploits by checking the root directory and the file directory.
* On success, a <code>java.io.File</code> object will be returned.
*
* @param player
* @param dir sub-directory to look in
* @param filename filename (user-submitted)
* @param defaultExt append an extension if missing one, null to not use
* @param extensions list of extensions, null for any
* @return
* @throws FilenameException
*/
public File getSafeSaveFile(LocalPlayer player, File dir, String filename,
String defaultExt, String... extensions)
throws FilenameException {
return getSafeFile(player, dir, filename, defaultExt, extensions, true);
}
/**
* Gets the path to a file. This method will check to see if the filename
* has valid characters and has an extension. It also prevents directory
* traversal exploits by checking the root directory and the file directory.
* On success, a <code>java.io.File</code> object will be returned.
*
* @param player
* @param dir sub-directory to look in
* @param filename filename (user-submitted)
* @param defaultExt append an extension if missing one, null to not use
* @param extensions list of extensions, null for any
* @return
* @throws FilenameException
*/
public File getSafeOpenFile(LocalPlayer player, File dir, String filename,
String defaultExt, String... extensions)
throws FilenameException {
return getSafeFile(player, dir, filename, defaultExt, extensions, false);
}
/**
* Get a safe path to a file.
*
* @param player
* @param dir
* @param filename
* @param defaultExt
* @param extensions
* @param isSave
* @return
* @throws FilenameException
*/
private File getSafeFile(LocalPlayer player, File dir, String filename,
String defaultExt, String[] extensions, boolean isSave)
throws FilenameException {
if (extensions != null && (extensions.length == 1 && extensions[0] == null)) extensions = null;
File f;
if (filename.equals("#")) {
if (isSave) {
f = player.openFileSaveDialog(extensions);
} else {
f = player.openFileOpenDialog(extensions);
}
if (f == null) {
throw new FileSelectionAbortedException("No file selected");
}
} else {
if (defaultExt != null && filename.lastIndexOf('.') == -1) {
filename += "." + defaultExt;
}
if (!filename.matches("^[A-Za-z0-9_\\- \\./\\\\'\\$@~!%\\^\\*\\(\\)\\[\\]\\+\\{\\},\\?]+\\.[A-Za-z0-9]+$")) {
throw new InvalidFilenameException(filename, "Invalid characters or extension missing");
}
f = new File(dir, filename);
}
try {
String filePath = f.getCanonicalPath();
String dirPath = dir.getCanonicalPath();
if (!filePath.substring(0, dirPath.length()).equals(dirPath) && !config.allowSymlinks) {
throw new FilenameResolutionException(filename,
"Path is outside allowable root");
}
return f;
} catch (IOException e) {
throw new FilenameResolutionException(filename,
"Failed to resolve path");
}
}
public int getMaximumPolygonalPoints(LocalPlayer player) {
if (player.hasPermission("worldedit.limit.unrestricted") || config.maxPolygonalPoints < 0) {
return config.defaultMaxPolygonalPoints;
} else {
if (config.defaultMaxPolygonalPoints < 0) {
return config.maxPolygonalPoints;
}
return Math.min(config.defaultMaxPolygonalPoints,
config.maxPolygonalPoints);
}
}
/**
* Checks to see if the specified radius is within bounds.
*
* @param radius
* @throws MaxRadiusException
*/
public void checkMaxRadius(double radius) throws MaxRadiusException {
if (config.maxRadius > 0 && radius > config.maxRadius) {
throw new MaxRadiusException();
}
}
/**
* Get a file relative to the defined working directory. If the specified
* path is absolute, then the working directory is not used.
*
* @param path
* @return
*/
public File getWorkingDirectoryFile(String path) {
File f = new File(path);
if (f.isAbsolute()) {
return f;
} else {
return new File(config.getWorkingDirectory(), path);
}
}
/**
* Modulus, divisor-style.
*
* @param a
* @param n
* @return
*/
public static int divisorMod(int a, int n) {
return (int) (a - n * Math.floor(Math.floor(a) / n));
}
/**
* Get the direction vector for a player's direction. May return
* null if a direction could not be found.
*
* @param player
* @param dirStr
* @return
* @throws UnknownDirectionException
*/
public Vector getDirection(LocalPlayer player, String dirStr)
throws UnknownDirectionException {
dirStr = dirStr.toLowerCase();
final PlayerDirection dir = getPlayerDirection(player, dirStr);
switch (dir) {
case WEST:
case EAST:
case SOUTH:
case NORTH:
case UP:
case DOWN:
return dir.vector();
default:
throw new UnknownDirectionException(dir.name());
}
}
private PlayerDirection getPlayerDirection(LocalPlayer player, String dirStr) throws UnknownDirectionException {
final PlayerDirection dir;
switch (dirStr.charAt(0)) {
case 'w':
dir = PlayerDirection.WEST;
break;
case 'e':
dir = PlayerDirection.EAST;
break;
case 's':
if (dirStr.indexOf('w') > 0) {
return PlayerDirection.SOUTH_WEST;
}
if (dirStr.indexOf('e') > 0) {
return PlayerDirection.SOUTH_EAST;
}
dir = PlayerDirection.SOUTH;
break;
case 'n':
if (dirStr.indexOf('w') > 0) {
return PlayerDirection.NORTH_WEST;