-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathccs.cs
5676 lines (4888 loc) · 256 KB
/
ccs.cs
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
//pluginref __item.dll
//pluginref _extralevelprops.dll
//pluginref _na2lib.dll
//reference System.Core.dll
//reference System.dll
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Linq;
using System.Text;
using MCGalaxy;
using MCGalaxy.Maths;
using MCGalaxy.Events.PlayerEvents;
using MCGalaxy.Events.LevelEvents;
using MCGalaxy.Events.PlayerDBEvents;
using MCGalaxy.Commands;
using MCGalaxy.Network;
using BlockID = System.UInt16;
using ExtraLevelProps;
using NA2;
using System.Globalization;
using MCGalaxy.Tasks;
using System.Diagnostics;
//COLLAPSE EVERYTHING IN VS WITH CTRL M A
namespace PluginCCS {
public class CmdDefineHotkey : Command2 {
public override string name { get { return "DefineHotkey"; } }
public override string shortcut { get { return ""; } }
public override bool MessageBlockRestricted { get { return true; } }
public override string type { get { return "other"; } }
public override bool museumUsable { get { return false; } }
public override LevelPermission defaultRank { get { return LevelPermission.Guest; } }
public override bool LogUsage { get { return true; } }
public override CommandPerm[] ExtraPerms {
get { return new[] { new CommandPerm(LevelPermission.Operator, "can run DefineHotkey without message blocks") }; }
}
public override void Use(Player p, string message, CommandData data) {
if (!(data.Context == CommandContext.MessageBlock || CheckExtraPerm(p, data, 1))) { return; }
string[] args = message.SplitSpaces(3);
if (args.Length != 3) { p.Message("&WNot enough args to define hotkey."); Help(p); return; }
int keycode = Hotkeys.GetKeyCode(p, args[1]);
if (keycode == 0) { return; }
string fullAction = args[2] + "◙";
if (fullAction.Length > NetUtils.StringSize) {
p.Message("Hotkey text is too long ({0}), must be {1} at most.", fullAction.Length, NetUtils.StringSize);
return;
}
Hotkeys.DefineFor(p, args[0], fullAction, keycode, 0);
}
public override void Help(Player p) {
p.Message("%T/DefineHotkey [user-facing name] [key] [hotkey text]");
p.Message("%HDefines a hotkey for this level.");
p.Message("%H[user-facing name] must not have spaces.");
p.Message("%H[hotkey text] is sent to the server unchanged.");
p.Message("%HMake sure to use a / if it is a command.");
}
}
/// <summary>
/// Base class for commands that need to throw script errors when there are invalid user args.
/// </summary>
public abstract class CmdThrowableForScript : Command2 {
public override void Use(Player p, string message, CommandData data) {
//Don't throw errors if ran manually
if (data.Context != CommandContext.MessageBlock) {
try {
UseThrowable(p, message, data);
} catch (ArgumentException e) {
p.Message("&W{0}", e.Message);
}
return;
}
//Throw errors if ran from MB (script) so it can be caught as script errors
UseThrowable(p, message, data);
}
/// <summary>
/// Override this method to implement command functionality. Throw ArgumentExceptions if user input is incorrect.
/// </summary>
protected abstract void UseThrowable(Player p, string message, CommandData data);
}
public class CmdTempBlock : CmdThrowableForScript {
public override string name { get { return "TempBlock"; } }
public override string shortcut { get { return ""; } }
public override string type { get { return CommandTypes.Building; } }
public override bool museumUsable { get { return true; } }
public override LevelPermission defaultRank { get { return LevelPermission.Guest; } }
public override bool LogUsage { get { return false; } }
protected override void UseThrowable(Player p, string message, CommandData data) {
if (!(p.group.Permission >= LevelPermission.Operator)) {
if (!Hacks.CanUseHacks(p)) {
if (data.Context != CommandContext.MessageBlock) {
p.Message("%cYou cannot use this command manually when hacks are disabled.");
return;
}
}
}
BlockID block = p.GetHeldBlock();
int x = p.Pos.BlockX, y = (p.Pos.Y - 32) / 32, z = p.Pos.BlockZ;
string blockWord = null;
int coordOffset = -1;
string[] words = message.SplitSpaces();
bool Public = false;
if (message.Length > 0) {
blockWord = words[0];
if (words.Length == 2) {
throw new ArgumentException(String.Format("Arg \"{0}\" has too few parts for coords, too many for only block.", message));
} else if (words.Length == 3) {
coordOffset = 0; blockWord = null;
} else if (words.Length == 4) {
coordOffset = 1;
} else if (words.Length > 4) {
coordOffset = 1;
if (!CommandParser.GetBool(p, words[4], ref Public)) {
throw new ArgumentException(String.Format("Could not parse arg \"{0}\" as true or false for public tempblock", words[4]));
}
if (data.Context != CommandContext.MessageBlock && Public) {
p.Message("%cYou can't send the tempblock to all players unless the command comes from a message block.");
return;
}
}
}
if (coordOffset >= 0) {
try {
x = int.Parse(words[0 + coordOffset]);
y = int.Parse(words[1 + coordOffset]);
z = int.Parse(words[2 + coordOffset]);
} catch {
throw new ArgumentException("Could not parse coordinates from \"" + message + "\".");
}
}
if (blockWord != null) {
if (!CommandParser.GetBlock(p, blockWord, out block)) {
throw new ArgumentException("There is no block \"" + blockWord + "\".");
}
}
if (!CommandParser.IsBlockAllowed(p, "place ", block)) return;
x = Clamp(x, p.level.Width);
y = Clamp(y, p.level.Height);
z = Clamp(z, p.level.Length);
Player[] players = Public ? PlayerInfo.Online.Items : new[] { p };
foreach (Player pl in players) {
if (pl.level != p.level) { continue; }
pl.SendBlockchange((ushort)x, (ushort)y, (ushort)z, block);
}
}
static int Clamp(int value, int axisLen) {
if (value < 0) return 0;
if (value >= axisLen) return axisLen - 1;
return value;
}
public override void Help(Player p) {
p.Message("%T/TempBlock [block] <x> <y> <z> <public>");
p.Message("%HPlaces a client-side block at your feet or <x> <y> <z>");
p.Message("%HIf <public> is true, the tempblock is shown to all players in the level.");
}
}
public class CmdTempChunk : CmdThrowableForScript {
public override string name { get { return "tempchunk"; } }
public override string shortcut { get { return "tempc"; } }
public override string type { get { return CommandTypes.Building; } }
public override bool museumUsable { get { return true; } }
public override LevelPermission defaultRank { get { return LevelPermission.Guest; } }
public override bool LogUsage { get { return false; } }
protected override void UseThrowable(Player p, string message, CommandData data) {
if (p.group.Permission < LevelPermission.Operator && !Hacks.CanUseHacks(p)) {
if (data.Context != CommandContext.MessageBlock) {
p.Message("%cYou cannot use this command manually when hacks are disabled.");
return;
}
}
Level startingLevel = p.level;
if (message == "") { Help(p); return; }
string[] words = message.Split(' ');
if (words.Length < 9) {
throw new ArgumentException("%cYou need to provide all 3 sets of coordinates, which means 9 numbers total.");
}
int x1 = 0, y1 = 0, z1 = 0, x2 = 0, y2 = 0, z2 = 0, x3 = 0, y3 = 0, z3 = 0;
bool mistake = false;
if (!CommandParser.GetInt(p, words[0], "x1", ref x1, 0, p.Level.Width - 1)) { mistake = true; }
if (!CommandParser.GetInt(p, words[1], "y1", ref y1, 0, p.Level.Height - 1)) { mistake = true; }
if (!CommandParser.GetInt(p, words[2], "z1", ref z1, 0, p.Level.Length - 1)) { mistake = true; }
if (!CommandParser.GetInt(p, words[3], "x2", ref x2, 0, p.Level.Width - 1)) { mistake = true; }
if (!CommandParser.GetInt(p, words[4], "y2", ref y2, 0, p.Level.Height - 1)) { mistake = true; }
if (!CommandParser.GetInt(p, words[5], "z2", ref z2, 0, p.Level.Length - 1)) { mistake = true; }
if (!CommandParser.GetInt(p, words[6], "x3", ref x3, 0, p.Level.Width - 1)) { mistake = true; }
if (!CommandParser.GetInt(p, words[7], "y3", ref y3, 0, p.Level.Height - 1)) { mistake = true; }
if (!CommandParser.GetInt(p, words[8], "z3", ref z3, 0, p.Level.Length - 1)) { mistake = true; }
if (mistake) {
throw new ArgumentException("Could not parse one or more tempchunk coordinate numbers.");
}
string errorMsg = "";
if (x1 > x2) { errorMsg += "%cx1 cannot be greater than x2! "; mistake = true; }
if (y1 > y2) { errorMsg += "%cy1 cannot be greater than y2! "; mistake = true; }
if (z1 > z2) { errorMsg += "%cz1 cannot be greater than z2! "; mistake = true; }
if (mistake) {
errorMsg += " %HMake sure the first set of coords is on the minimum corner (press f7)";
throw new ArgumentException(errorMsg);
}
bool allPlayers = false;
if (words.Length > 9) {
CommandParser.GetBool(p, words[9], ref allPlayers);
if (data.Context != CommandContext.MessageBlock && allPlayers) {
p.Message("%cYou can't send the tempchunk to all players unless the command comes from a message block.");
return;
}
}
bool pasteAir = true;
if (words.Length > 10) {
if (!CommandParser.GetBool(p, words[10], ref pasteAir)) { return; }
}
// 95, 33, 73, 99, 36, 75, 97, 37, 79
BlockID[] blocks = GetBlocks(p, x1, y1, z1, x2, y2, z2);
PlaceBlocks(p, blocks, x1, y1, z1, x2, y2, z2, x3, y3, z3, allPlayers, pasteAir, startingLevel);
}
public BlockID[] GetBlocks(Player p, int x1, int y1, int z1, int x2, int y2, int z2) {
int xLen = (x2 - x1) + 1;
int yLen = (y2 - y1) + 1;
int zLen = (z2 - z1) + 1;
BlockID[] blocks = new BlockID[xLen * yLen * zLen];
int index = 0;
for (int xi = x1; xi < x1 + xLen; ++xi) {
for (int yi = y1; yi < y1 + yLen; ++yi) {
for (int zi = z1; zi < z1 + zLen; ++zi) {
blocks[index] = p.level.GetBlock((ushort)xi, (ushort)yi, (ushort)zi);
index++;
}
}
}
return blocks;
}
public void PlaceBlocks(Player p, BlockID[] blocks, int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3, bool allPlayers, bool pasteAir, Level startingLevel) {
int xLen = (x2 - x1) + 1;
int yLen = (y2 - y1) + 1;
int zLen = (z2 - z1) + 1;
Player[] players = allPlayers ? PlayerInfo.Online.Items : new[] { p };
foreach (Player pl in players) {
if (pl.level != p.level) { continue; }
BufferedBlockSender buffer = new BufferedBlockSender(pl);
int index = 0;
for (int xi = x3; xi < x3 + xLen; ++xi) {
for (int yi = y3; yi < y3 + yLen; ++yi) {
for (int zi = z3; zi < z3 + zLen; ++zi) {
if (p.level != startingLevel) { return; }
if (!pasteAir && blocks[index] == Block.Air) { index++; continue; }
int pos = pl.level.PosToInt((ushort)xi, (ushort)yi, (ushort)zi);
if (pos >= 0) { buffer.Add(pos, blocks[index]); }
index++;
}
}
}
// last few blocks
buffer.Flush();
}
}
public override void Help(Player p) {
p.Message("%T/TempChunk %f[x1 y1 z1] %7[x2 y2 z2] %r[x3 y3 z3] <allPlayers?true/false> <pasteAir?true/false>");
p.Message("%HCopies a chunk of the world defined by %ffirst %Hand %7second%H coords then pastes it into the spot defined by the %rthird %Hset of coords.");
p.Message("%H<allPlayers?true/false> is optional, and defaults to false. If true, the tempchunk changes are sent to all players in the map.");
p.Message("%H<pasteAir?true/false> is optional, and defaults to true. If false, the tempchunk will not paste air blocks. You need to specify the first optional arg to specify this one.");
}
}
public class CmdStuff : Command2 {
public override string name { get { return "Stuff"; } }
public override string shortcut { get { return ""; } }
public override string type { get { return "other"; } }
public override bool MessageBlockRestricted { get { return true; } }
public override bool museumUsable { get { return false; } }
public override LevelPermission defaultRank { get { return LevelPermission.Operator; } }
public override CommandPerm[] ExtraPerms {
get { return new[] { new CommandPerm(LevelPermission.Operator, "can get/take stuff without message blocks") }; }
}
public override void Use(Player p, string message, CommandData data) {
p.lastCMD = "nothing2";
if (message.Length == 0) {
DisplayItems(p, false);
_Help(p);
return;
}
string[] args = message.SplitSpaces(2);
string function = args[0].ToUpper();
string functionArgs = args.Length > 1 ? args[1] : "";
if (function == "DROP") {
p.Message("%cTo delete stuff, use %b/drop [name]");
return;
}
if (function == "LOOK" || function == "EXAMINE") {
UseExamine(p, functionArgs);
return;
}
Action unknownMsg = () => { p.Message("&WUnknown &T/stuff &Warg \"{0}\"", function); };
if (functionArgs != "") {
if (!(data.Context == CommandContext.MessageBlock || HasExtraPerm(p, p.Rank, 1))) {
unknownMsg();
return;
}
UseGiveTake(p, functionArgs, data);
return;
}
unknownMsg();
Help(p);
}
static void UseExamine(Player p, string itemName) {
if (itemName == "") {
p.Message("Please specify something to examine.");
return;
}
Item item = Item.MakeInstance(p, itemName);
if (item == null) { return; }
if (!item.OwnedBy(p.name) || item.isVar) {
p.Message("&cYou dont have any stuff called \"{0}\".", item.displayName);
return;
}
string[] desc = item.ItemDesc; //cache
if (desc.Length == 0) {
p.Message("You don't notice anything particular about the {0}%S.", item.ColoredName); return;
}
p.Message("You examine the {0}%S...", item.ColoredName);
Thread.Sleep(1000);
p.MessageLines(desc.Select(line => "&e" + line));
}
void UseGiveTake(Player p, string message, CommandData data) {
if (message == "") { p.Message("Expected arg LIST, GET/GIVE [ITEM_NAME], or TAKE/REMOVE [ITEM_NAME]"); return; }
string[] args = message.ToUpper().SplitSpaces(2);
string function = args[0];
if (function == "LIST") { DisplayItems(p, true); return; }
string itemName = args.Length > 1 ? args[1] : "";
Item item = Item.MakeInstance(p, itemName);
if (item == null) { return; }
if (function == "GET" || function == "GIVE") { item.GiveTo(p); return; }
if (function == "TAKE" || function == "REMOVE") { item.TakeFrom(p); return; }
p.Message("Function &c" + function + "%S was unrecognized."); return;
}
static void DisplayItems(Player p, bool showVars) {
p.Message("%eYour stuff:");
Item[] items = Item.GetItemsOwnedBy(p.name);
List<string> coloredItems = new List<string>(items.Length);
int amountDisplayed = 0;
for (int i = 0; i < items.Length; i++) {
if (items[i].isVar && !showVars) { continue; }
amountDisplayed++;
coloredItems.Add(items[i].ColoredName);
}
if (amountDisplayed == 0) {
p.Message("You have no stuff!"); return;
}
p.Message(String.Join(" &8• ", coloredItems));
}
public override void Help(Player p) {
p.Message("%T/Stuff");
p.Message("%HLists your stuff.");
_Help(p);
if (!HasExtraPerm(p, p.Rank, 1)) { return; }
p.Message("%T/Stuff [anyword] GET [item]");
p.Message("%T/Stuff [anyword] TAKE [item]");
p.Message("%HStaff only -- get/take any item.");
p.Message("%H[anyword] is required for backwards compatibility with the obsolete password system.");
}
static void _Help(Player p) {
p.Message("%eUse %b/stuff look [item name] %eto examine items.");
p.Message("%HTo delete stuff, use %b/drop [item name]");
}
}
public class CmdDrop : Command2 {
public override string name { get { return "drop"; } }
public override bool MessageBlockRestricted { get { return true; } }
public override string type { get { return "other"; } }
public override bool museumUsable { get { return true; } }
public override LevelPermission defaultRank { get { return LevelPermission.Guest; } }
public override void Use(Player p, string message, CommandData data) {
if (message == "") { Help(p); return; }
Item item = Item.MakeInstance(p, message);
if (item == null) { return; }
if (!item.OwnedBy(p.name) || item.isVar) {
p.Message("&cYou dont have any stuff called \"{0}\".", item.displayName);
return;
}
item.TakeFrom(p);
}
public override void Help(Player p) {
p.Message("%T/Drop [stuff]");
p.Message("%HDrops the /stuff you specify.");
}
}
public class CmdReplyTwo : Command2 {
public override string name { get { return "ReplyTwo"; } }
public override string shortcut { get { return ""; } }
public override bool MessageBlockRestricted { get { return false; } }
public override string type { get { return "other"; } }
public override bool museumUsable { get { return false; } }
public override LevelPermission defaultRank { get { return LevelPermission.Guest; } }
public override bool LogUsage { get { return false; } }
public const int maxReplyCount = 6;
const CpeMessageType line1 = CpeMessageType.BottomRight3;
const CpeMessageType line2 = CpeMessageType.BottomRight2;
const CpeMessageType line3 = CpeMessageType.BottomRight1;
const CpeMessageType line4 = CpeMessageType.Status1;
const CpeMessageType line5 = CpeMessageType.Status2;
const CpeMessageType line6 = CpeMessageType.Status3;
public const PersistentMessagePriority replyPriority = PersistentMessagePriority.Highest;
public override void Use(Player p, string message, CommandData data) {
if (message == "") { Help(p); return; }
int replyNum = -1;
if (!CommandParser.GetInt(p, message, "Reply number", ref replyNum, 1, maxReplyCount)) { return; }
ScriptData scriptData = Core.GetScriptData(p);
ReplyData replyData = scriptData.replies[replyNum - 1]; //reply number is from 1-6 but the array is indexed 0-5, hence -1
if (replyData == null) { p.Message("There's no reply option &f[{0}] &Sat the moment.", replyNum); return; }
//reset the replies once you choose one
scriptData.ResetReplies();
//the script has to be ran as if from a message block
CommandData cmdData = default(CommandData); cmdData.Context = CommandContext.MessageBlock;
ScriptRunner.PerformScript(p, p.level, replyData.scriptName, replyData.labelName, replyData.perms, false, cmdData);
}
public static void SetUpDone(Player p) {
p.Message("&e(say a number to choose a response from the right →→)");
}
public static CpeMessageType GetReplyMessageType(int i) {
if (i == 1) { return line1; }
if (i == 2) { return line2; }
if (i == 3) { return line3; }
if (i == 4) { return line4; }
if (i == 5) { return line5; }
if (i == 6) { return line6; }
return CpeMessageType.Normal;
}
public override void Help(Player p) {
p.Message("&T/Reply [num]");
p.Message("&HReplies with the option you specify.");
p.Message("&HYou'll be prompted to use it during adventure maps.");
}
public static bool HandlePlayerChat(Player p, string message) {
ScriptData scriptData = Core.GetScriptData(p);
bool replyActive = false;
bool notifyPlayer = false;
for (int i = 0; i < maxReplyCount; i++) {
if (scriptData.replies[i] != null) {
if (scriptData.replies[i].notifyPlayer) { notifyPlayer = true; }
replyActive = true;
}
}
if (!replyActive) { return false; }
string msgStripped = message.Replace("[", "");
msgStripped = msgStripped.Replace("]", "");
int reply = -1;
if (NumberParser.TryParseInt(msgStripped, out reply)) {
CommandData data2 = default(CommandData); data2.Context = CommandContext.MessageBlock;
p.HandleCommand("replytwo", msgStripped, data2);
p.cancelchat = true;
return true;
}
//notify player how to reply if they don't choose one and one is available
if (notifyPlayer) { SetUpDone(p); }
return true;
}
}
public class CmdItems : Command2 {
public override string name { get { return "Items"; } }
public override string type { get { return "other"; } }
public override bool museumUsable { get { return false; } }
public override LevelPermission defaultRank { get { return LevelPermission.Operator; } }
public override void Use(Player p, string message, CommandData data) {
Core.GetScriptData(p).DisplayItems();
}
public override void Help(Player p) {
p.Message("%T/Items");
p.Message("%HLists your items.");
p.Message("Notably, items are different from &T/stuff&S because they will disappear if you leave this map.");
}
}
public class CmdUpdateOsScript : Command2 {
public override string name { get { return "OsUploadScript"; } }
public override string shortcut { get { return "osus"; } }
public override bool MessageBlockRestricted { get { return false; } }
public override string type { get { return "other"; } }
public override bool museumUsable { get { return false; } }
public override LevelPermission defaultRank { get { return LevelPermission.Admin; } }
public override bool UpdatesLastCmd { get { return false; } }
public override void Use(Player p, string message, CommandData data) {
if (!Script.OsAllowed(p)) { return; }
string levelName = p.level.name; //cache the level so that it won't change if the user switches map while the command is running
if (!LevelInfo.IsRealmOwner(p.name, levelName)) { p.Message("You can only upload scripts to maps that you own."); return; }
if (message.Length == 0) { p.Message("%cYou need to provide a url of the file that will be used as your map's script."); return; }
HttpUtil.FilterURL(ref message);
byte[] webData = HttpUtil.DownloadData(message, p);
if (webData == null) { return; }
Script.Update(p, Script.OS_PREFIX + levelName.ToLower(), webData);
}
public override void Help(Player p) {
p.Message("&T/OsUploadScript [url]");
p.Message("&HUploads [url] as the script for your map.");
}
}
public sealed class Core : Plugin {
public static bool IsNA2 {
get {
return Server.Config.Name.StartsWith("Not Awesome 2");
}
}
public static string NA2WebFileDirectory = "/home/na2/Website-Files/";
public static string NA2WebURL = "https://notawesome.cc/";
public static void MsgDev(string message, params object[] args) {
Player debugger = PlayerInfo.FindExact(DEBUG_MESSAGE_TARGET); if (debugger == null) { return; }
debugger.Message(message, args);
}
public static void MsgIfDev(Player p, string message, params object[] args) {
if (p.name != DEBUG_MESSAGE_TARGET) return;
p.Message(message, args);
}
public override string creator { get { return "Goodly"; } }
const string DEBUG_MESSAGE_TARGET = "goodlyay+";
public override string name { get { return "ccs"; } }
public override string MCGalaxy_Version { get { return "1.9.5.0"; } }
static readonly object scriptDataLocker = new object();
private static Dictionary<string, ScriptData> scriptDataAtPlayer = new Dictionary<string, ScriptData>();
public static ScriptData GetScriptData(Player p) {
lock (scriptDataLocker) { //only one thread should access this at a time
ScriptData sd;
if (scriptDataAtPlayer.TryGetValue(p.name, out sd)) { return sd; } else {
//throw new System.Exception("Tried to get script data for "+p.name+" but there was NOTHING there");
Logger.Log(LogType.SystemActivity, "ccs: This shouldn't happen, but; FAILED to GetScriptData for " + p.name + ", returning a new one.");
scriptDataAtPlayer[p.name] = new ScriptData(p);
return scriptDataAtPlayer[p.name];
}
}
}
public static Command tempBlockCmd;
public static Command tempChunkCmd;
public static Command stuffCmd;
public static Command dropCmd;
public static Command runscriptCmd;
public static Command osRunscriptCmd;
public static Command debugScriptCmd;
public static Command replyCmd;
public static Command itemsCmd;
public static Command updateOsScriptCmd;
public static Command downloadScriptCmd;
static Command[] cmds = new Command[] { new KeybindCommand(), new CmdDefineHotkey(), new CmdScriptAction(), new CmdOsScriptAction(), };
static Command _boostCmd = null;
public static Command boostCmd {
get { if (_boostCmd == null) { _boostCmd = Command.Find("boost"); } return _boostCmd; }
}
static Command _effectCmd = null;
public static Command effectCmd {
get { if (_effectCmd == null) { _effectCmd = Command.Find("effect"); } return _effectCmd; }
}
public const string inputProp = "input";
static string[] inputPropDesc = new string[] {
"[scriptname] &H- which script /input runs (non OS)",
};
public const string savePlayerScriptDataProp = "save_player_script_data";
static string[] savePlayerScriptDataPropDesc = new string[] {
"[true/false]",
"Allows OS scripts read and write permanently saved data."
};
public override void Load(bool startup) {
ExtraLevelProps.ExtraLevelProps.Register(name, inputProp, LevelPermission.Operator, inputPropDesc, null);
ExtraLevelProps.ExtraLevelProps.Register(name, savePlayerScriptDataProp, LevelPermission.Operator, savePlayerScriptDataPropDesc, ExtraLevelProps.ExtraLevelProps.OnPropChangingBool);
Script.PluginLoad();
ScriptActions.PluginLoad();
ReadOnlyPackages.PluginLoad();
Docs.PluginLoad();
Keybinds.PluginLoad();
PersistentAnnouncements.PluginLoad();
tempBlockCmd = new CmdTempBlock();
tempChunkCmd = new CmdTempChunk();
stuffCmd = new CmdStuff();
dropCmd = new CmdDrop();
runscriptCmd = new CmdScript();
osRunscriptCmd = new CmdOsScript();
debugScriptCmd = new CmdDebugScript();
replyCmd = new CmdReplyTwo();
itemsCmd = new CmdItems();
updateOsScriptCmd = new CmdUpdateOsScript();
downloadScriptCmd = new CmdDownloadScript();
Command.Register(tempBlockCmd);
Command.Register(tempChunkCmd);
Command.Register(stuffCmd);
Command.Register(dropCmd);
Command.Register(runscriptCmd);
Command.Register(osRunscriptCmd);
Command.Register(debugScriptCmd);
Command.Register(replyCmd);
Command.Register(itemsCmd);
Command.Register(updateOsScriptCmd);
Command.Register(downloadScriptCmd);
foreach (Command cmd in cmds) { Command.Register(cmd); }
OnPlayerFinishConnectingEvent.Register(OnPlayerFinishConnecting, Priority.High);
OnInfoSwapEvent.Register(OnInfoSwap, Priority.Low);
OnJoinedLevelEvent.Register(OnJoinedLevel, Priority.High);
OnJoiningLevelEvent.Register(OnJoiningLevel, Priority.High);
OnPlayerSpawningEvent.Register(OnPlayerSpawning, Priority.High);
OnLevelRenamedEvent.Register(OnLevelRenamed, Priority.Low);
OnLevelUnloadEvent.Register(OnLevelUnload, Priority.Low);
OnPlayerChatEvent.Register(OnPlayerChat, Priority.High);
OnPlayerCommandEvent.Register(OnPlayerCommand, Priority.High);
OnPlayerDisconnectEvent.Register(OnPlayerDisconnect, Priority.Low);
OnPlayerMoveEvent.Register(OnPlayerMove, Priority.Low);
OnPlayerClickEvent.Register(OnPlayerClick, Priority.Low);
foreach (Player pl in PlayerInfo.Online.Items) {
OnPlayerFinishConnecting(pl);
}
Chat.MessageGlobal("Script plugin reloaded. If you're in an adventure map, you may need to rejoin it.");
}
public override void Unload(bool shutdown) {
ExtraLevelProps.ExtraLevelProps.Unregister(inputProp);
ExtraLevelProps.ExtraLevelProps.Unregister(savePlayerScriptDataProp);
PersistentAnnouncements.PluginUnload();
Command.Unregister(tempBlockCmd);
Command.Unregister(tempChunkCmd);
Command.Unregister(stuffCmd);
Command.Unregister(dropCmd);
Command.Unregister(runscriptCmd);
Command.Unregister(osRunscriptCmd);
Command.Unregister(debugScriptCmd);
Command.Unregister(replyCmd);
Command.Unregister(itemsCmd);
Command.Unregister(updateOsScriptCmd);
Command.Unregister(downloadScriptCmd);
foreach (Command cmd in cmds) { Command.Unregister(cmd); }
OnPlayerFinishConnectingEvent.Unregister(OnPlayerFinishConnecting);
OnInfoSwapEvent.Unregister(OnInfoSwap);
OnJoinedLevelEvent.Unregister(OnJoinedLevel);
OnJoiningLevelEvent.Unregister(OnJoiningLevel);
OnPlayerSpawningEvent.Unregister(OnPlayerSpawning);
OnLevelRenamedEvent.Unregister(OnLevelRenamed);
OnPlayerChatEvent.Unregister(OnPlayerChat);
OnPlayerCommandEvent.Unregister(OnPlayerCommand);
OnPlayerDisconnectEvent.Unregister(OnPlayerDisconnect);
OnPlayerMoveEvent.Unregister(OnPlayerMove);
OnPlayerClickEvent.Unregister(OnPlayerClick);
SaveAllPlayerData();
scriptDataAtPlayer.Clear();
}
static void SaveAllPlayerData() {
Player[] players = PlayerInfo.Online.Items;
foreach (Player p in players) {
SavePlayerData(p);
}
}
static void OnPlayerFinishConnecting(Player p) {
//Logger.Log(LogType.SystemActivity, "ccs CONECTING " + p.name + " : " + Environment.StackTrace);
lock (scriptDataLocker) { //only one thread should access this at a time
if (scriptDataAtPlayer.ContainsKey(p.name)) {
//this happens when they Reconnect.
scriptDataAtPlayer[p.name].UpdatePlayerReference(p);
Logger.Log(LogType.SystemActivity, "ccs ScriptData already exists for player: " + p.name);
return;
}
scriptDataAtPlayer[p.name] = new ScriptData(p);
}
}
static void OnPlayerDisconnect(Player p, string reason) {
if (reason.StartsWith("(Reconnecting")) {
Logger.Log(LogType.SystemActivity, "ccs is not clearing scriptdata due to player reconnecting: " + p.name);
return;
}
ScriptRunner.PerformOnExit(p, p.level);
SavePlayerData(p);
scriptDataAtPlayer.Remove(p.name);
}
static void SavePlayerData(Player p) {
ScriptData data;
if (!scriptDataAtPlayer.TryGetValue(p.name, out data)) { return; }
data.WriteSavedStringsToDisk();
data.hotkeys.keybinds.SaveBinds();
}
/// <summary>
/// Runs after OnPlayerSpawning which resets script variables
/// </summary>
public static void OnJoinedLevel(Player p, Level prevLevel, Level lvl, ref bool announce) {
if (prevLevel == null) { return; }
ScriptRunner.PerformOnExit(p, prevLevel);
}
public static void OnJoiningLevel(Player p, Level lvl, ref bool canJoin) {
if (ScriptRunner.PerformAccessControl(p, lvl.name)) {
canJoin = false;
lvl.AutoUnload();
}
}
static void OnPlayerSpawning(Player p, ref Position pos, ref byte yaw, ref byte pitch, bool respawning) {
if (respawning) { return; } //Only call when spawning in a new level
//Reset cinematic gui when changing levels
ScriptActions.Gui.ResetFor(p);
//clear all persistent chat lines at the priority used by cpemessage in script
for (int i = 1; i < CmdReplyTwo.maxReplyCount + 1; i++) {
CpeMessageType type = CmdReplyTwo.GetReplyMessageType(i);
if (type != CpeMessageType.Normal) { p.SendCpeMessage(type, "", ScriptRunner.CpeMessagePriority); }
}
ScriptData data;
if (scriptDataAtPlayer.TryGetValue(p.name, out data)) {
data.OnPlayerSpawning(); //Reset script variables, cancel running scripts, etc
}
//Perform the #onJoin label for this level if it exists
ScriptRunner.PerformOnJoin(p, p.level);
}
static void OnInfoSwap(string source, string dest) {
string sourcePath = ScriptData.savePath + source;
string destPath = ScriptData.savePath + dest;
string backupPath = ScriptData.savePath + "temporary-info-swap";
//Chat.MessageOps("info swap event: "+sourcePath+" and "+destPath+"");
if (Directory.Exists(sourcePath)) {
Directory.Move(sourcePath, backupPath);
}
if (Directory.Exists(destPath)) {
Directory.Move(destPath, sourcePath);
}
if (Directory.Exists(backupPath)) {
Directory.Move(backupPath, destPath);
}
}
static void OnLevelRenamed(string srcMap, string dstMap) {
Script.OnLevelRenamed(srcMap, dstMap);
}
static void OnLevelUnload(Level lvl, ref bool cancel) {
Script.OnLevelUnload(lvl, ref cancel);
}
static void OnPlayerChat(Player p, string message) {
//If reply is used,don't run the rest of this junk
if (CmdReplyTwo.HandlePlayerChat(p, message)) { return; }
ScriptData scriptData = GetScriptData(p);
if (!scriptData.chatEvents.active) { return; }
Sevent sevent = scriptData.chatEvents.sync;
if (sevent == null) { return; }
ScriptActions.ChatEvent.ChatEventArgs args = (ScriptActions.ChatEvent.ChatEventArgs)sevent.arg;
string chatEventLabel = args.onChatLabel;
string[] phrases = args.phrases;
double[] similarities = new double[phrases.Length];
for (int i = 0; i < phrases.Length; i++) {
similarities[i] = StringUtils.CalculateSimilarity(message.StripPunctuation(), phrases[i].StripPunctuation());
}
StringBuilder sb = new StringBuilder();
sb.Append(message.Replace(' ', '_')); //runArg1, message
foreach (double sim in similarities) {
sb.Append(ScriptRunner.pipeChar);
sb.Append(sim); //runArg2, 3, etc, similarity to 1st, 2nd, etc target phrase
}
string runArgs = sb.ToString();
string cancelLogicLabelAndArgs = sevent.scriptLabel + '|' + runArgs;
string onChatLabelAndArgs = chatEventLabel + '|' + runArgs;
scriptData.SetString("cancelchat", "", sevent.perms, sevent.scriptName);
CommandData data = sevent.GetCommandData(p.Pos.FeetBlockCoords);
Level level = p.level; //Cache level so it doesn't change between labels
ScriptRunner.PerformScript(p, level, sevent.scriptName, cancelLogicLabelAndArgs, sevent.perms, false, data);
if (scriptData.GetString("cancelchat", sevent.perms, sevent.scriptName).ToLower() == "true") {
p.cancelchat = true;
}
ScriptRunner.PerformScriptOnNewThread(p, level, sevent.scriptName, onChatLabelAndArgs, sevent.perms, false, data);
}
static void OnPlayerCommand(Player p, string cmd, string message, CommandData data) {
Script.OnPlayerCommand(p, cmd, message, data);
}
static void OnPlayerMove(Player p, Position next, byte yaw, byte pitch, ref bool cancel) {
ScriptData scriptData = GetScriptData(p); if (scriptData == null) { return; }
if (scriptData.stareCoords != null) {
ScriptRunner.LookAtCoords(p, (Vec3S32)scriptData.stareCoords);
}
}
static void OnPlayerClick
(Player p,
MouseButton button, MouseAction action,
ushort yaw, ushort pitch,
byte entity, ushort x, ushort y, ushort z,
TargetBlockFace face) {
if (action != MouseAction.Pressed) { return; }
if (p.level.Config.Deletable || p.level.Config.Buildable) { return; }
ScriptData data = GetScriptData(p);
if (!data.clickEvents.active) { return; }
Vec3S32 coords = new Vec3S32(x, y, z);
ClickInfo clickInfo = new ClickInfo(button, action, yaw, pitch, entity, x, y, z, face);
DoClick(p, data.clickEvents.sync, coords, clickInfo);
DoClick(p, data.clickEvents.async, coords, clickInfo);
}
static void DoClick(Player p, Sevent sevent, Vec3S32 coords, ClickInfo clickInfo) {
if (sevent == null) { return; }
ScriptRunner.PerformScriptOnNewThread(p, p.level, sevent.scriptName, sevent.scriptLabel, sevent.perms, sevent.async,
sevent.GetCommandData(coords),
clickInfo);
}
}
public static class StringUtils {
public static string StripPunctuation(this string message) {
StringBuilder sb = new StringBuilder(message.Length);
foreach (char c in message) {
if (AlphabetOrNumeral(c)) sb.Append(c);
}
return sb.ToString().Trim();
}
static bool AlphabetOrNumeral(char c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
/// <summary>
/// Calculates the similarity, from 0 to 1, between two caselessly compared strings.
/// </summary>
public static double CalculateSimilarity(string source, string target) {
source = source.ToLower(); target = target.ToLower();
if ((source == null) || (target == null)) return 0.0;
if ((source.Length == 0) || (target.Length == 0)) return 0.0;
if (source == target) return 1.0;
int stepsToSame = ComputeLevenshteinDistance(source, target);
return (1.0 - ((double)stepsToSame / (double)Math.Max(source.Length, target.Length)));
}
//https://social.technet.microsoft.com/wiki/contents/articles/26805.c-calculating-percentage-similarity-of-2-strings.aspx
static int ComputeLevenshteinDistance(string source, string target) {
if ((source == null) || (target == null)) return 0;
if ((source.Length == 0) || (target.Length == 0)) return 0;
if (source == target) return source.Length;
int sourceWordCount = source.Length;
int targetWordCount = target.Length;
// Step 1
if (sourceWordCount == 0)
return targetWordCount;
if (targetWordCount == 0)
return sourceWordCount;
int[,] distance = new int[sourceWordCount + 1, targetWordCount + 1];
// Step 2
for (int i = 0; i <= sourceWordCount; distance[i, 0] = i++) ;
for (int j = 0; j <= targetWordCount; distance[0, j] = j++) ;
for (int i = 1; i <= sourceWordCount; i++) {
for (int j = 1; j <= targetWordCount; j++) {
// Step 3
int cost = (target[j - 1] == source[i - 1]) ? 0 : 1;
// Step 4
distance[i, j] = Math.Min(Math.Min(distance[i - 1, j] + 1, distance[i, j - 1] + 1), distance[i - 1, j - 1] + cost);
}
}
return distance[sourceWordCount, targetWordCount];
}
}
public class CmdScript : Command2 {
public override string name { get { return "Script"; } }
public override string shortcut { get { return ""; } }
public override bool MessageBlockRestricted { get { return true; } }
public override string type { get { return "other"; } }
public override bool museumUsable { get { return false; } }