diff --git a/.gitignore b/.gitignore index d9a5a13..c45cb69 100755 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,12 @@ /Ultima.dll -/Ultima.pdb -/Ultima.dll.mdb /Ultima/bin /Ultima/obj + +/Server.dll /Server/bin /Server/obj + +/Scripts.dll /Scripts/bin /Scripts/obj /Scripts/Output @@ -29,7 +31,7 @@ *.pdb *.exe -*.exe.mdb +*.mdb *.sh *.suo *.idea diff --git a/Config/Server.cfg b/Config/Server.cfg index 924fcf1..0506d14 100755 --- a/Config/Server.cfg +++ b/Config/Server.cfg @@ -1,6 +1,6 @@ # The displayed name of the shard -Name=The Forging +Name=Code Name: The Forging # The default setting for Address, a value of 'null', will use your local IP address. # If all of your local IP addresses are private network addresses and AutoDetect is 'true' @@ -25,4 +25,4 @@ AutoDetect=True # The Port to bind the Listener to. # Default: 2593 -@Port=2593 \ No newline at end of file +@Port=2593 diff --git a/Config/TestCenter.cfg b/Config/TestCenter.cfg index 4a4357b..4d19ef0 100755 --- a/Config/TestCenter.cfg +++ b/Config/TestCenter.cfg @@ -1,3 +1,3 @@ # If true, the server will start in Test Center mode -Enabled=False \ No newline at end of file +Enabled=False diff --git a/Data/Decoration/Britannia/britain.cfg b/Data/Decoration/Britannia/britain.cfg index 7abe3aa..a3afd4f 100755 --- a/Data/Decoration/Britannia/britain.cfg +++ b/Data/Decoration/Britannia/britain.cfg @@ -159,7 +159,7 @@ Drawer 0x0A2C 1493 1610 40 1579 1584 20 1579 1584 40 -1469 1704 0 +# 1469 1704 0 1493 1620 40 1386 1800 0 1426 1752 10 @@ -187,9 +187,9 @@ Drawer 0x0A34 1460 1705 0 1416 1555 30 1184 1715 0 -1454 1705 0 +# 1454 1705 0 1507 1595 10 -1448 1707 0 +# 1448 1707 0 1624 1584 -20 1537 1739 35 1537 1744 35 @@ -665,7 +665,7 @@ LampPost1 0x0B20 1500 1701 20 1472 1623 20 1471 1676 0 -1472 1696 0 +# 1472 1696 0 1472 1636 20 1501 1543 28 1432 1665 10 @@ -702,7 +702,7 @@ LampPost3 0x0B24 1439 1754 -3 1694 1556 40 1691 1578 11 -1484 1723 0 +# 1484 1723 0 1665 1608 13 1669 1557 30 1670 1626 -5 @@ -749,7 +749,7 @@ LampPost3 0x0B24 1588 1685 10 1498 1626 10 1552 1751 15 -1472 1704 0 +# 1472 1704 0 1552 1608 10 1615 1672 19 1567 1576 20 @@ -1426,7 +1426,7 @@ PottedTree1 0x11C9 1656 1606 20 1678 1590 7 1342 1657 50 -1452 1704 0 +# 1452 1704 0 1450 1678 0 1254 1696 0 1576 1594 40 @@ -1443,7 +1443,7 @@ PottedTree1 0x11C9 1158 1622 0 1390 1806 0 1480 1580 20 -1470 1704 0 +# 1470 1704 0 1486 1580 20 1544 1736 15 1542 1680 30 @@ -1531,11 +1531,11 @@ PottedPlant 0x11CA # flowerpot PottedPlant1 0x11CB -1454 1709 9 +# 1454 1709 9 1384 1804 5 1603 1715 29 1545 1709 30 -1460 1709 9 +# 1460 1709 9 1452 1682 9 1600 1524 47 1452 1614 29 @@ -1545,9 +1545,9 @@ PottedPlant2 0x11CC 1446 1649 19 1456 1725 16 1605 1716 30 -1466 1709 9 +# 1466 1709 9 1471 1580 29 -1452 1709 9 +# 1452 1709 9 1594 1655 19 1388 1816 5 1550 1767 19 @@ -1934,7 +1934,7 @@ Fork 0x09A3 1331 1604 54 1387 1817 2 1403 1817 4 -1452 1708 6 +# 1452 1708 6 1509 1599 14 1547 1715 24 1600 1515 44 @@ -1977,7 +1977,7 @@ Knife 0x09A5 1331 1604 54 1387 1817 2 1403 1817 4 -1452 1708 6 +# 1452 1708 6 1509 1599 14 1547 1715 24 1600 1515 44 @@ -2105,11 +2105,11 @@ Spoon 0x09C3 # bottle of wine BeverageBottle 0x09C7 (Content=Wine) -1452 1707 6 -1454 1707 6 +# 1452 1707 6 +# 1454 1707 6 1456 1723 12 -1460 1707 6 -1466 1707 6 +# 1460 1707 6 +# 1466 1707 6 1468 1514 24 1469 1515 24 1509 1598 14 @@ -2222,11 +2222,11 @@ Plate 0x09D7 1342 1605 54 1344 1603 54 1344 1605 54 -1452 1708 6 -1454 1708 6 +# 1452 1708 6 +# 1454 1708 6 1456 1724 12 -1460 1708 6 -1466 1708 6 +# 1460 1708 6 +# 1466 1708 6 1467 1514 24 1467 1515 24 1470 1514 24 @@ -2371,11 +2371,11 @@ Fork 0x09F5 1261 1884 4 1388 1817 2 1404 1817 4 -1453 1708 20 -1454 1708 6 +# 1453 1708 20 +# 1454 1708 6 1456 1724 12 -1460 1708 6 -1466 1708 6 +# 1460 1708 6 +# 1466 1708 6 1510 1599 14 1548 1715 24 1601 1515 44 @@ -2419,10 +2419,10 @@ Knife 0x09F7 1261 1884 4 1388 1817 2 1404 1817 4 -1454 1708 6 +# 1454 1708 6 1456 1724 12 -1460 1708 6 -1466 1708 6 +# 1460 1708 6 +# 1466 1708 6 1510 1599 14 1548 1715 24 1601 1515 44 @@ -2459,10 +2459,10 @@ Spoon 0x09F8 # spoon Spoon 0x09F9 -1454 1708 6 +# 1454 1708 6 1456 1724 12 -1460 1708 6 -1466 1708 6 +# 1460 1708 6 +# 1466 1708 6 1510 1599 14 1548 1715 24 1601 1515 44 @@ -2524,13 +2524,13 @@ CandleLarge 0x0B1A 1412 1617 34 1412 1717 24 1430 1752 16 -1448 1704 6 +# 1448 1704 6 1452 1609 26 1453 1682 6 -1454 1704 6 +# 1454 1704 6 1456 1720 12 1460 1704 6 -1466 1704 6 +# 1466 1704 6 1471 1576 26 1473 1609 26 1482 1586 26 @@ -2983,7 +2983,7 @@ BambooChair 0x0B5D 1420 1580 30 1455 1708 0 1461 1708 0 -1467 1708 0 +# 1467 1708 0 1472 1562 30 1475 1738 0 1475 1739 0 @@ -3299,20 +3299,20 @@ Barrel 0x0E77 1408 1806 5 1408 1807 0 1408 1807 5 -1472 1720 0 -1472 1721 0 -1472 1722 0 -1473 1720 0 -1473 1724 0 -1473 1725 0 -1474 1725 0 -1477 1721 0 -1477 1722 0 -1478 1721 0 -1478 1722 0 -1480 1725 0 -1481 1724 0 -1481 1725 0 +# 1472 1720 0 +# 1472 1721 0 +# 1472 1722 0 +# 1473 1720 0 +# 1473 1724 0 +# 1473 1725 0 +# 1474 1725 0 +# 1477 1721 0 +# 1477 1722 0 +# 1478 1721 0 +# 1478 1722 0 +# 1480 1725 0 +# 1481 1724 0 +# 1481 1725 0 1560 1742 15 1560 1743 15 1560 1743 20 @@ -4147,7 +4147,7 @@ PewterMug 0x0FFF 1435 1713 24 1435 1716 24 1435 1721 24 -1452 1707 6 +# 1452 1707 6 1468 1515 24 1469 1515 24 1497 1677 24 @@ -4176,10 +4176,10 @@ PewterMug 0x1000 1429 1713 26 1429 1715 26 1429 1717 26 -1454 1707 6 +# 1454 1707 6 1456 1723 12 -1460 1707 6 -1466 1707 6 +# 1460 1707 6 +# 1466 1707 6 1468 1514 24 1489 1686 26 1491 1686 26 diff --git a/Data/Mondain's Legacy/Settings.xml b/Data/Mondain's Legacy/Settings.xml index ff3e1af..2f158a6 100755 --- a/Data/Mondain's Legacy/Settings.xml +++ b/Data/Mondain's Legacy/Settings.xml @@ -1,15 +1,15 @@ - - - - - - - - - - - - - - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Data/UltimaStore.json b/Data/UltimaStore.json index 3abe763..3d0d59b 100755 --- a/Data/UltimaStore.json +++ b/Data/UltimaStore.json @@ -1,5 +1,25 @@ { "Featured": [ + { + "Type": "Server.Items.OilOfRestoration", + "NameLines": ["Oil of Restoration"], + "Tooltip": 0, + "TooltipText": "Use this item to allow your tempered equipment to be repaired again. This item will be consumed upon use.", + "ItemID": 7192, + "GumpID": 0, + "Hue": 241, + "Price": 5000 + }, + { + "Type": "Server.Items.ForgedPardon", + "NameLines": ["1116234"], + "Tooltip": 1116235, + "TooltipText": "", + "ItemID": 10289, + "GumpID": 0, + "Hue": 1177, + "Price": 2500 + }, { "Type": "Server.Items.RoyalMintBox", "NameLines": ["Royal Mint Processing Box"], @@ -8,7 +28,7 @@ "ItemID": 2472, "GumpID": 0, "Hue": 2713, - "Price": 5000 + "Price": 1500 }, { "Type": "Server.Items.VirtueShield", @@ -294,56 +314,6 @@ "Hue": 0, "Price": 1500 }, - { - "Type": "Server.Items.HoodedBritanniaRobe", - "NameLines": ["1125155"], - "Tooltip": 1158016, - "TooltipText": "", - "ItemID": 41131, - "GumpID": 0, - "Hue": 0, - "Price": 1500 - }, - { - "Type": "Server.Items.HoodedBritanniaRobe", - "NameLines": ["1125155"], - "Tooltip": 1158016, - "TooltipText": "", - "ItemID": 41132, - "GumpID": 0, - "Hue": 0, - "Price": 1500 - }, - { - "Type": "Server.Items.HoodedBritanniaRobe", - "NameLines": ["1125155"], - "Tooltip": 1158016, - "TooltipText": "", - "ItemID": 41133, - "GumpID": 0, - "Hue": 0, - "Price": 1500 - }, - { - "Type": "Server.Items.HoodedBritanniaRobe", - "NameLines": ["1125155"], - "Tooltip": 1158016, - "TooltipText": "", - "ItemID": 41134, - "GumpID": 0, - "Hue": 0, - "Price": 1500 - }, - { - "Type": "Server.Items.HoodedBritanniaRobe", - "NameLines": ["1125155"], - "Tooltip": 1158016, - "TooltipText": "", - "ItemID": 41135, - "GumpID": 0, - "Hue": 0, - "Price": 1500 - }, { "Type": "Server.Items.HaochisPigment", "NameLines": ["1071249", "1157275"], diff --git a/Data/signs.cfg b/Data/signs.cfg index 1044a7c..985f147 100755 --- a/Data/signs.cfg +++ b/Data/signs.cfg @@ -302,7 +302,6 @@ 0 4762 1552 1728 37 #1016310 0 4765 1552 1728 34 #1016310 0 4765 1532 1705 33 #1016310 -0 4765 1485 1709 15 #1016310 0 4761 1488 1731 15 #1016310 0 4764 1468 1732 15 #1016310 0 4764 1441 1732 19 #1016310 diff --git a/Desktop.lnk b/Desktop.lnk new file mode 100644 index 0000000..be78cf1 Binary files /dev/null and b/Desktop.lnk differ diff --git a/Makefile b/Makefile index 7ef4bd3..8f5dba0 100755 --- a/Makefile +++ b/Makefile @@ -1,41 +1,48 @@ -MCS=mcs +CSC=dotnet csc EXENAME=ServUO -CURPATH=`pwd` -SRVPATH=${CURPATH}/Server -SDKPATH=${CURPATH}/Ultima -REFS=System.Drawing.dll +CURPATH=$(shell pwd) +SRVPATH=$(CURPATH)/Server +SDKPATH=$(CURPATH)/Ultima +REFS=/usr/lib/mono/4.8-api/System.Drawing.dll NOWARNS=0618,0219,0414,1635 -PHONY : default build clean run +PHONY: default build clean run default: run -debug: - ${MCS} -target:library -out:${CURPATH}/Ultima.dll -r:${REFS} -nowarn:${NOWARNS} -d:DEBUG -d:MONO -d:ServUO -d:NEWTIMERS -nologo -debug -unsafe -recurse:${SDKPATH}/*.cs - ${MCS} -win32icon:${SRVPATH}/servuo.ico -r:${CURPATH}/Ultima.dll,${REFS} -nowarn:${NOWARNS} -target:exe -out:${CURPATH}/${EXENAME}.exe -d:DEBUG -d:MONO -d:ServUO -d:NEWTIMERS -nologo -debug -unsafe -recurse:${SRVPATH}/*.cs - sed -i.bak -e 's///g' ${EXENAME}.exe.config +debug: Ultima.dll ServUO.exe +sed -i.bak -e 's///g' $(EXENAME).exe.config run: build - ${CURPATH}/${EXENAME}.sh +$(CURPATH)/$(EXENAME).sh -build: ${EXENAME}.sh +build: ServUO.exe +echo "#!/bin/sh" > $(CURPATH)/$(EXENAME).sh +echo "dotnet $(CURPATH)/$(EXENAME).exe" >> $(CURPATH)/$(EXENAME).sh +chmod a+x $(CURPATH)/$(EXENAME).sh +sed -i.bak -e 's///g' $(EXENAME).exe.config clean: - rm -f ${EXENAME}.sh - rm -f ${EXENAME}.exe - rm -f ${EXENAME}.exe.mdb - rm -f Ultima.dll - rm -f Ultima.dll.mdb - rm -f *.bin +rm -f $(EXENAME).sh +rm -f $(EXENAME).exe +rm -f Ultima.dll +rm -rf obj bin +rm -f *.bin -Ultima.dll: Ultima/*.cs - ${MCS} -target:library -out:${CURPATH}/Ultima.dll -r:${REFS} -nowarn:${NOWARNS} -d:MONO -d:ServUO -d:NEWTIMERS -nologo -optimize -unsafe -recurse:${SDKPATH}/*.cs +Ultima.dll: +$(CSC) -target:library -out:$(CURPATH)/Ultima.dll \ + -r:$(REFS) -nowarn:$(NOWARNS) \ + -d:ServUO -d:NEWTIMERS \ + -nologo -optimize -unsafe \ + -langversion:latest \ + -recurse:$(SDKPATH)/*.cs -${EXENAME}.exe: Ultima.dll Server/*.cs - ${MCS} -win32icon:${SRVPATH}/servuo.ico -r:${CURPATH}/Ultima.dll,${REFS} -nowarn:${NOWARNS} -target:exe -out:${CURPATH}/${EXENAME}.exe -d:MONO -d:ServUO -d:NEWTIMERS -nologo -optimize -unsafe -recurse:${SRVPATH}/*.cs - -${EXENAME}.sh: ${EXENAME}.exe - echo "#!/bin/sh" > ${CURPATH}/${EXENAME}.sh - echo "mono ${CURPATH}/${EXENAME}.exe" >> ${CURPATH}/${EXENAME}.sh - chmod a+x ${CURPATH}/${EXENAME}.sh - sed -i.bak -e 's///g' ${EXENAME}.exe.config +ServUO.exe: Ultima.dll +$(CSC) -win32icon:$(SRVPATH)/servuo.ico \ + -r:$(CURPATH)/Ultima.dll -r:$(REFS) \ + -nowarn:$(NOWARNS) \ + -target:exe -out:$(CURPATH)/$(EXENAME).exe \ + -d:ServUO -d:NEWTIMERS \ + -nologo -optimize -unsafe \ + -langversion:latest \ + -recurse:$(SRVPATH)/*.cs diff --git a/README.md b/README.md index 69aee60..7d20faa 100755 --- a/README.md +++ b/README.md @@ -19,35 +19,26 @@ ServUO is a community driven Ultima Online Server Emulator written in C#. #### Windows -Run `Compile.WIN - Debug.bat` for development, attaching a debugger and/or extended output. +Run `_windebug.bat` for development, attaching a debugger and/or extended output. -Run `Compile.WIN - Release.bat` for production environment (-debug is still a supported parameter for script debugging). - -After this you can run the server by executing `ServUO.exe`. +Run `_winrelease.bat` for production environment. -#### OSX -``` -brew install mono -make -``` +#### Other Platforms +Run `_makedebug` for development, attaching a debugger and/or extended output. -#### Ubuntu -``` -apt-get install mono-complete -make -``` +Run `_makerelease` for production environment. ### Summary 1. Starting with the `/Config` directory, find and edit `Server.cfg` to set up the essentials. 2. Go through the remaining `*.cfg` files to ensure they suit your needs. -3. For Windows, run `Compile.WIN - Debug.bat` to produce `ServUO.exe`, Linux users may run `Makefile`. -4. Run `ServUO.exe` to make sure everything boots up, if everything went well, you should see your IP adress being listened on the port you specified. -5. Load up UO and login! - If you require instructions on setting up your particular client, visit the Discord and ask! +3. For Windows, run `_winrelease.bat` to produce `ServUO.exe`, OSX/Linux users may run `_makerelease`. +4. Run `ServUO` +5. ??? +6. Profit! - - [ServUO]: + [ServUO]: diff --git a/Scripts.dll b/Scripts.dll old mode 100755 new mode 100644 index e87aa8a..a887549 Binary files a/Scripts.dll and b/Scripts.dll differ diff --git a/Scripts/Accounting/IPLimiter.cs b/Scripts/Accounting/IPLimiter.cs index 9b94a16..643cde1 100755 --- a/Scripts/Accounting/IPLimiter.cs +++ b/Scripts/Accounting/IPLimiter.cs @@ -32,7 +32,7 @@ namespace Server.Misc if (!Enabled || IsExempt(ourAddress)) return true; - List netStates = NetState.Instances; + IList netStates = NetState.Instances; int count = 0; @@ -52,4 +52,4 @@ namespace Server.Misc return true; } } -} \ No newline at end of file +} diff --git a/Scripts/Commands/Generic/Implementors/IPAddressCommandImplementor.cs b/Scripts/Commands/Generic/Implementors/IPAddressCommandImplementor.cs index e6d44ea..3fe477e 100755 --- a/Scripts/Commands/Generic/Implementors/IPAddressCommandImplementor.cs +++ b/Scripts/Commands/Generic/Implementors/IPAddressCommandImplementor.cs @@ -1,5 +1,7 @@ using System; using System.Collections; +using System.Collections.Generic; + using Server.Network; namespace Server.Commands.Generic @@ -36,7 +38,7 @@ namespace Server.Commands.Generic ArrayList list = new ArrayList(); ArrayList addresses = new ArrayList(); - System.Collections.Generic.List states = NetState.Instances; + IList states = NetState.Instances; for (int i = 0; i < states.Count; ++i) { @@ -60,4 +62,4 @@ namespace Server.Commands.Generic } } } -} \ No newline at end of file +} diff --git a/Scripts/Commands/Generic/Implementors/OnlineCommandImplementor.cs b/Scripts/Commands/Generic/Implementors/OnlineCommandImplementor.cs index 4a9769a..ff5d805 100755 --- a/Scripts/Commands/Generic/Implementors/OnlineCommandImplementor.cs +++ b/Scripts/Commands/Generic/Implementors/OnlineCommandImplementor.cs @@ -36,7 +36,7 @@ namespace Server.Commands.Generic ArrayList list = new ArrayList(); - List states = NetState.Instances; + IList states = NetState.Instances; for (int i = 0; i < states.Count; ++i) { @@ -63,4 +63,4 @@ namespace Server.Commands.Generic } } } -} \ No newline at end of file +} diff --git a/Scripts/Commands/SignParser.cs b/Scripts/Commands/SignParser.cs index 621e401..7734cf7 100755 --- a/Scripts/Commands/SignParser.cs +++ b/Scripts/Commands/SignParser.cs @@ -164,6 +164,9 @@ namespace Server.Commands while ((line = ip.ReadLine()) != null) { + if (string.IsNullOrEmpty(line)) + continue; + string[] split = line.Split(' '); SignEntry e = new SignEntry( @@ -346,4 +349,4 @@ namespace Server.Commands } } } -} \ No newline at end of file +} diff --git a/Scripts/Commands/TimeStamp.cs b/Scripts/Commands/TimeStamp.cs index 79b397a..224e2cc 100755 --- a/Scripts/Commands/TimeStamp.cs +++ b/Scripts/Commands/TimeStamp.cs @@ -14,7 +14,7 @@ namespace Server.Commands public static void CheckTime_OnCommand(CommandEventArgs e) { Mobile m = e.Mobile; - DateTime now = DateTime.Now; + DateTime now = DateTime.UtcNow; m.SendMessage("The Current Date And Time Is " + now + "(EST)"); } } diff --git a/Scripts/Custom/DurabilityAttachment.cs b/Scripts/Custom/DurabilityAttachment.cs new file mode 100644 index 0000000..f419828 --- /dev/null +++ b/Scripts/Custom/DurabilityAttachment.cs @@ -0,0 +1,48 @@ +using System; +using Server; +using Server.Items; +using Server.Engines.XmlSpawner2; +using Server.Custom; + +namespace Server.Custom +{ + public class DurabilityAttachment : XmlAttachment + { + public bool RepairLocked { get; set; } + public int PoFUses { get; set; } + public int MaxPoFUses { get; set; } + + public DurabilityAttachment() : base() + { + } + + public DurabilityAttachment(ASerial serial) : base(serial) + { + } + + public override void Serialize(GenericWriter writer) + { + base.Serialize(writer); + + writer.Write((int)0); // version + + writer.Write(RepairLocked); + writer.Write(PoFUses); + writer.Write(MaxPoFUses); + } + + public override void Deserialize(GenericReader reader) + { + base.Deserialize(reader); + + int version = reader.ReadInt(); + + if (version >= 0) + { + RepairLocked = reader.ReadBool(); + PoFUses = reader.ReadInt(); + MaxPoFUses = reader.ReadInt(); + } + } + } +} diff --git a/Scripts/Custom/DurabilityExtension.cs b/Scripts/Custom/DurabilityExtension.cs new file mode 100644 index 0000000..a009720 --- /dev/null +++ b/Scripts/Custom/DurabilityExtension.cs @@ -0,0 +1,52 @@ +using Server; +using Server.Items; +using Server.Engines.XmlSpawner2; + +namespace Server.Custom +{ + public static class DurabilityExtensions + { + private static DurabilityAttachment GetAttach(Item item) + { + var att = XmlAttach.FindAttachment(item, typeof(DurabilityAttachment)) as DurabilityAttachment; + + if (att == null) + { + att = new DurabilityAttachment(); + XmlAttach.AttachTo(item, att); + } + + return att; + } + + public static bool GetRepairLocked(this Item item) + { + return GetAttach(item).RepairLocked; + } + + public static void SetRepairLocked(this Item item, bool value) + { + GetAttach(item).RepairLocked = value; + } + + public static int GetPoFUses(this Item item) + { + return GetAttach(item).PoFUses; + } + + public static void SetPoFUses(this Item item, int value) + { + GetAttach(item).PoFUses = value; + } + + public static int GetMaxPoFUses(this Item item) + { + return GetAttach(item).MaxPoFUses; + } + + public static void SetMaxPoFUses(this Item item, int value) + { + GetAttach(item).MaxPoFUses = value; + } + } +} diff --git a/Scripts/Custom/Fallen Dupre Armor/ArmsofApathy2.cs b/Scripts/Custom/Fallen Dupre Armor/ArmsofApathy2.cs new file mode 100644 index 0000000..575559e --- /dev/null +++ b/Scripts/Custom/Fallen Dupre Armor/ArmsofApathy2.cs @@ -0,0 +1,88 @@ +using System; +using Server.Items; + +namespace Server.Items +{ + + public class ArmsofApathy2 : PlateArms + { + public override bool IsArtifact { get { return true; } } + + [Constructable] + public ArmsofApathy2() : base() + { + Name = "Arms of Apathy"; + LootType = LootType.Blessed; + Weight = 5.0; + + this.SetHue = 1109; + this.Attributes.RegenHits = 1; + this.Attributes.AttackChance = 5; + + this.SetAttributes.ReflectPhysical = 25; + this.SetAttributes.NightSight = 1; + + this.SetSkillBonuses.SetValues(0, SkillName.Swords, 10); + + this.SetSelfRepair = 3; + + this.SetPhysicalBonus = 2; + this.SetFireBonus = 5; + this.SetColdBonus = 5; + this.SetPoisonBonus = 3; + this.SetEnergyBonus = 5; + } + + public ArmsofApathy2( Serial serial ) : base( serial ) + { + } + public override int BasePhysicalResistance + { + get + { + return 8; + } + } + public override int BaseFireResistance + { + get + { + return 5; + } + } + public override int BaseColdResistance + { + get + { + return 5; + } + } + public override int BasePoisonResistance + { + get + { + return 7; + } + } + public override int BaseEnergyResistance + { + get + { + return 5; + } + } + public override void Serialize(GenericWriter writer) + { + base.Serialize(writer); + + writer.Write((int)0); // version + } + + public override void Deserialize(GenericReader reader) + { + base.Deserialize(reader); + + int version = reader.ReadInt(); + } + } +} \ No newline at end of file diff --git a/Scripts/Custom/Fallen Dupre Armor/GlovesofInjustice2.cs b/Scripts/Custom/Fallen Dupre Armor/GlovesofInjustice2.cs new file mode 100644 index 0000000..1e7e194 --- /dev/null +++ b/Scripts/Custom/Fallen Dupre Armor/GlovesofInjustice2.cs @@ -0,0 +1,88 @@ +using System; + +namespace Server.Items +{ + [FlipableAttribute(0x1450, 0x1455)] + public class GlovesofInjustice2 : PlateGloves + { + public override bool IsArtifact { get { return true; } } + [Constructable] + public GlovesofInjustice2() + : base() + { + this.Weight = 2.0; + this.Name = "Goves of Injustice"; + LootType = LootType.Blessed; + this.SetHue = 1109; + + this.Attributes.RegenHits = 1; + this.Attributes.AttackChance = 5; + + this.SetAttributes.ReflectPhysical = 25; + this.SetAttributes.NightSight = 1; + + this.SetSkillBonuses.SetValues(0, SkillName.Swords, 10); + + this.SetSelfRepair = 3; + this.SetPhysicalBonus = 2; + this.SetFireBonus = 5; + this.SetColdBonus = 5; + this.SetPoisonBonus = 3; + this.SetEnergyBonus = 5; + } + + public GlovesofInjustice2(Serial serial) + : base(serial) + { + } + + public override int BasePhysicalResistance + { + get + { + return 8; + } + } + public override int BaseFireResistance + { + get + { + return 5; + } + } + public override int BaseColdResistance + { + get + { + return 5; + } + } + public override int BasePoisonResistance + { + get + { + return 7; + } + } + public override int BaseEnergyResistance + { + get + { + return 5; + } + } + public override void Serialize(GenericWriter writer) + { + base.Serialize(writer); + + writer.Write((int)0); // version + } + + public override void Deserialize(GenericReader reader) + { + base.Deserialize(reader); + + int version = reader.ReadInt(); + } + } +} \ No newline at end of file diff --git a/Scripts/Custom/Fallen Dupre Armor/HeartofObsidian2.cs b/Scripts/Custom/Fallen Dupre Armor/HeartofObsidian2.cs new file mode 100644 index 0000000..b385ddc --- /dev/null +++ b/Scripts/Custom/Fallen Dupre Armor/HeartofObsidian2.cs @@ -0,0 +1,86 @@ +using System; + +namespace Server.Items +{ + public class HeartofObsidian2 : PlateChest + { + public override bool IsArtifact { get { return true; } } + [Constructable] + public HeartofObsidian2() + : base() + { + this.Name = "Heart of Obsidian"; + LootType = LootType.Blessed; + this.SetHue = 1109; + this.Attributes.RegenHits = 1; + this.Attributes.AttackChance = 5; + + this.SetAttributes.ReflectPhysical = 25; + this.SetAttributes.NightSight = 1; + + this.SetSkillBonuses.SetValues(0, SkillName.Swords, 10); + + this.SetSelfRepair = 3; + this.SetPhysicalBonus = 2; + this.SetFireBonus = 5; + this.SetColdBonus = 5; + this.SetPoisonBonus = 3; + this.SetEnergyBonus = 5; + } + + public HeartofObsidian2(Serial serial) + : base(serial) + { + } + + + public override int BasePhysicalResistance + { + get + { + return 8; + } + } + public override int BaseFireResistance + { + get + { + return 5; + } + } + public override int BaseColdResistance + { + get + { + return 5; + } + } + public override int BasePoisonResistance + { + get + { + return 7; + } + } + public override int BaseEnergyResistance + { + get + { + return 5; + } + } + public override void Serialize(GenericWriter writer) + { + base.Serialize(writer); + + writer.Write((int)0); // version + } + + public override void Deserialize(GenericReader reader) + { + base.Deserialize(reader); + + int version = reader.ReadInt(); + } + } +} \ No newline at end of file diff --git a/Scripts/Custom/Fallen Dupre Armor/HelmofIgnorance2.cs b/Scripts/Custom/Fallen Dupre Armor/HelmofIgnorance2.cs new file mode 100644 index 0000000..cb2f27f --- /dev/null +++ b/Scripts/Custom/Fallen Dupre Armor/HelmofIgnorance2.cs @@ -0,0 +1,89 @@ +using System; + +namespace Server.Items +{ + public class HelmofIgnorance2 : NorseHelm + { + public override bool IsArtifact { get { return true; } } + [Constructable] + public HelmofIgnorance2() + : base() + { + + this.Name = "Helm of Ignorance"; + LootType = LootType.Blessed; + this.SetHue = 1109; + + this.Attributes.RegenHits = 1; + this.Attributes.AttackChance = 5; + + this.SetAttributes.ReflectPhysical = 25; + this.SetAttributes.NightSight = 1; + + this.SetSkillBonuses.SetValues(0, SkillName.Swords, 10); + + this.SetSelfRepair = 3; + + this.SetPhysicalBonus = 2; + this.SetFireBonus = 5; + this.SetColdBonus = 5; + this.SetPoisonBonus = 3; + this.SetEnergyBonus = 5; + } + + public HelmofIgnorance2(Serial serial) + : base(serial) + { + } + + + public override int BasePhysicalResistance + { + get + { + return 4; + } + } + public override int BaseFireResistance + { + get + { + return 9; + } + } + public override int BaseColdResistance + { + get + { + return 3; + } + } + public override int BasePoisonResistance + { + get + { + return 6; + } + } + public override int BaseEnergyResistance + { + get + { + return 8; + } + } + public override void Serialize(GenericWriter writer) + { + base.Serialize(writer); + + writer.Write((int)0); // version + } + + public override void Deserialize(GenericReader reader) + { + base.Deserialize(reader); + + int version = reader.ReadInt(); + } + } +} \ No newline at end of file diff --git a/Scripts/Custom/Fallen Dupre Armor/LegsofSloth2.cs b/Scripts/Custom/Fallen Dupre Armor/LegsofSloth2.cs new file mode 100644 index 0000000..0d9f6aa --- /dev/null +++ b/Scripts/Custom/Fallen Dupre Armor/LegsofSloth2.cs @@ -0,0 +1,87 @@ +using System; + +namespace Server.Items +{ + public class LegsofSloth2 : PlateLegs + { + public override bool IsArtifact { get { return true; } } + [Constructable] + public LegsofSloth2() + : base() + { + + this.Name = "Legs of Sloth"; + LootType = LootType.Blessed; + this.SetHue = 1109; + + this.Attributes.RegenHits = 1; + this.Attributes.AttackChance = 5; + + this.SetAttributes.ReflectPhysical = 25; + this.SetAttributes.NightSight = 1; + + this.SetSkillBonuses.SetValues(0, SkillName.Swords, 10); + + this.SetSelfRepair = 3; + + this.SetPhysicalBonus = 2; + this.SetFireBonus = 5; + this.SetColdBonus = 5; + this.SetPoisonBonus = 3; + this.SetEnergyBonus = 5; + } + + public LegsofSloth2(Serial serial) + : base(serial) + { + } + public override int BasePhysicalResistance + { + get + { + return 8; + } + } + public override int BaseFireResistance + { + get + { + return 5; + } + } + public override int BaseColdResistance + { + get + { + return 5; + } + } + public override int BasePoisonResistance + { + get + { + return 7; + } + } + public override int BaseEnergyResistance + { + get + { + return 5; + } + } + public override void Serialize(GenericWriter writer) + { + base.Serialize(writer); + + writer.Write((int)0); // version + } + + public override void Deserialize(GenericReader reader) + { + base.Deserialize(reader); + + int version = reader.ReadInt(); + } + } +} \ No newline at end of file diff --git a/Scripts/Custom/Fallen Dupre Armor/UnbendingNeck2.cs b/Scripts/Custom/Fallen Dupre Armor/UnbendingNeck2.cs new file mode 100644 index 0000000..b2760ab --- /dev/null +++ b/Scripts/Custom/Fallen Dupre Armor/UnbendingNeck2.cs @@ -0,0 +1,86 @@ +using System; + +namespace Server.Items +{ + public class UnbendingNeck2 : PlateGorget + { + public override bool IsArtifact { get { return true; } } + [Constructable] + public UnbendingNeck2() + : base() + { + this.SetHue = 1109; + this.Name = "Unbending Neck"; + LootType = LootType.Blessed; + this.Attributes.RegenHits = 1; + this.Attributes.AttackChance = 5; + + this.SetAttributes.ReflectPhysical = 25; + this.SetAttributes.NightSight = 1; + + this.SetSkillBonuses.SetValues(0, SkillName.Swords, 10); + + this.SetSelfRepair = 3; + this.SetPhysicalBonus = 2; + this.SetFireBonus = 5; + this.SetColdBonus = 5; + this.SetPoisonBonus = 3; + this.SetEnergyBonus = 5; + } + + public UnbendingNeck2(Serial serial) + : base(serial) + { + } + + + public override int BasePhysicalResistance + { + get + { + return 8; + } + } + public override int BaseFireResistance + { + get + { + return 5; + } + } + public override int BaseColdResistance + { + get + { + return 5; + } + } + public override int BasePoisonResistance + { + get + { + return 7; + } + } + public override int BaseEnergyResistance + { + get + { + return 5; + } + } + public override void Serialize(GenericWriter writer) + { + base.Serialize(writer); + + writer.Write((int)0); // version + } + + public override void Deserialize(GenericReader reader) + { + base.Deserialize(reader); + + int version = reader.ReadInt(); + } + } +} \ No newline at end of file diff --git a/Scripts/Custom/Fallen Dupre Armor/ViceInfusedShield.cs b/Scripts/Custom/Fallen Dupre Armor/ViceInfusedShield.cs new file mode 100644 index 0000000..7ffe750 --- /dev/null +++ b/Scripts/Custom/Fallen Dupre Armor/ViceInfusedShield.cs @@ -0,0 +1,47 @@ +using System; +using Server; + +namespace Server.Items +{ + public class ViceInfusedShield : BaseShield + { + public override int BasePhysicalResistance{ get{ return 0; } } + public override int BaseFireResistance{ get{ return 1; } } + public override int BaseColdResistance{ get{ return 0; } } + public override int BasePoisonResistance{ get{ return 0; } } + public override int BaseEnergyResistance{ get{ return 0; } } + + public override int InitMinHits{ get{ return 50; } } + public override int InitMaxHits{ get{ return 65; } } + + public override int AosStrReq{ get{ return 90; } } + + public override int ArmorBase{ get{ return 23; } } + + [Constructable] + public ViceInfusedShield() : base( 11009 ) + { + Weight = 8.0; + Hue = 1109; + Name = "Vice Infused Shield"; + } + + public ViceInfusedShield( Serial serial ) : base(serial) + { + } + + public override void Deserialize( GenericReader reader ) + { + base.Deserialize( reader ); + + int version = reader.ReadInt(); + } + + public override void Serialize( GenericWriter writer ) + { + base.Serialize( writer ); + + writer.Write( (int)0 );//version + } + } +} diff --git a/Scripts/Custom/FallenDupre.cs b/Scripts/Custom/FallenDupre.cs new file mode 100644 index 0000000..97057c4 --- /dev/null +++ b/Scripts/Custom/FallenDupre.cs @@ -0,0 +1,338 @@ +//// D&D style Death Knight by Pappa Smurf //// +//// Thanks to the Following //// +//// David from RunUO.com for giving me an interest in Timers //// +//// oO_Sithid_Oo from RunUO.com for proof reading and pointing out my mistakes //// +//// and helping with the timer //// +//// TMSTKSBK for putting up with me complaining about my timers not working //// +//// The RunUO Dev Team for creating RunUO without which this script would be pointless //// +//// A_Li_N from RunUO for suggesting using a DateTime Method instead of a timer //// +//// Updated on 11/16/2008 to include new Abilities and Updates for RunUO 2.0 SVN 301 //// +//// Damage and Armor Rating calcuations, Additional Loot Drops added. //// +////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////// + + +using System; +using Server.Mobiles; +using Server.Spells.Necromancy; +using Server; +using System.Collections; +using Server.Items; +using Server.Misc; +using Server.Network; +using Server.Targeting; +using Server.Spells; +using Server.Engines.CannedEvil; + + +namespace Server.Mobiles +{ + + [CorpseName("corpse of Dupre")] + public class FallenDupre : BaseChampion + { + public override ChampionSkullType SkullType { get { return ChampionSkullType.Despair; } } + + public override WeaponAbility GetWeaponAbility() + { + switch (Utility.Random(2)) + { + default: + case 1: return WeaponAbility.DoubleStrike; + case 2: return WeaponAbility.ArmorIgnore; + } + } + + private DateTime m_NextPowerWordKillTime; + [CommandProperty(AccessLevel.GameMaster)] + public DateTime NextPowerWordKillTime + { + get + { + return m_NextPowerWordKillTime; + } + set + { + m_NextPowerWordKillTime = value; + + } + + } + + public override bool ClickTitle { get { return false; } } + + [Constructable] + public FallenDupre(): base(AIType.AI_Melee) + { + Name = "Dupre"; + Title = "Fallen Champion of the Virtues"; + Body = 744; + Hue = 0x4001; + SetStr(488, 620); + SetDex(121, 170); + SetInt(498, 657); + + SetHits(12000 , 15000); + SetStam(102, 300); + + SetDamage(10, 20); + + SetDamageType(ResistanceType.Physical, 25); + SetDamageType(ResistanceType.Energy, 50); + SetResistance(ResistanceType.Physical, 35); + SetResistance(ResistanceType.Fire, 50); + SetResistance(ResistanceType.Cold, 60); + SetResistance(ResistanceType.Poison, 25); + SetResistance(ResistanceType.Energy, 40); + SetSkill( SkillName.Parry, 120.0 ); + SetSkill( SkillName.Swords, 120.0 ); + SetSkill( SkillName.Tactics, 120.0 ); + SetSkill( SkillName.Anatomy, 120.0 ); + SetSkill( SkillName.Magery, 120.0); + SetSkill( SkillName.SpiritSpeak, 120.0); + SetSkill( SkillName.Healing, 120.0); + SetSkill(SkillName.EvalInt, 120.0); + SetSkill(SkillName.MagicResist, 140.0); + SetSkill(SkillName.Chivalry, 120.0); + + + Fame = 25000; + Karma = -25000; + + + AddItem(new ArmsofApathy2()); + AddItem(new HeartofObsidian2()); + AddItem(new GlovesofInjustice2()); + AddItem(new LegsofSloth2()); + AddItem(new ThighBoots()); + AddItem(new Katana()); + AddItem(new HelmofIgnorance2()); + AddItem(new ViceInfusedShield()); + AddItem(new UnbendingNeck2()); + + PackGold( 200, 250 ); + + new Nightmare().Rider = this; + + } + public override Type[] UniqueList + { + get + { + return new Type[] { typeof(FangOfRactus) }; + } + } + public override Type[] SharedList + { + get + { + return new Type[] + { + typeof(RoyalGuardInvestigatorsCloak), + typeof(DjinnisRing), + typeof(DetectiveBoots), + typeof(GauntletsOfAnger) + }; + } + } + public override Type[] DecorativeList + { + get + { + return new Type[] { typeof(SwampTile), typeof(MonsterStatuette) }; + } + } + public override MonsterStatuetteType[] StatueTypes + { + get + { + return new MonsterStatuetteType[] { MonsterStatuetteType.Slime }; + } + } + public override bool OnBeforeDeath() + { + IMount mount = this.Mount; + + if (mount != null) + mount.Rider = null; + + if (mount is Mobile) + ((Mobile)mount).Delete(); + + return base.OnBeforeDeath(); + } + + public override void GenerateLoot() + { + AddLoot(LootPack.UltraRich, 4); + AddLoot(LootPack.FilthyRich, 2); + AddLoot(LootPack.MedScrolls, 2); + switch (Utility.Random(6)) + { + case 0: AddItem(new ArmsofApathy()); break; + case 1: AddItem(new HeartofObsidian()); break; + case 2: AddItem(new LegsofSloth()); break; + case 3: AddItem(new HelmofIgnorance()); break; + case 4: AddItem(new GlovesofInjustice()); break; + case 5: AddItem(new UnbendingNeck()); break; + } + + + } + + public override bool AlwaysMurderer { get { return true; } } + public override bool AutoDispel { get { return true; } } + public override double AutoDispelChance { get { return 1.0; } } + public override bool BardImmune { get { return !Core.SE; } } + public override bool Unprovokable { get { return Core.SE; } } + public override bool Uncalmable { get { return Core.SE; } } + public override Poison PoisonImmune{ get{ return Poison.Lethal; } } + + public override void OnDamage(int amount, Mobile from, bool willKill) + { + if (from != null && !willKill && amount > 5 && from.Player && 5 > Utility.Random(10)) + { + string[] toSay = new string[] + { + "I sacraficed myself for the virtues, this was my reward", + "{0}, Fight me with Honor, Die like a Man!", + "{0}, You should retreat your skills are no match for mine", + "In life I stood against the evils of this world. Now I serve them to bring your doom!", + "{0}, You worm, you should be honored to die by my hand!" , + "Tis' but a scratch!" + }; + this.Say(true, String.Format(toSay[Utility.Random(toSay.Length)], from.Name)); + } + + base.OnDamage(amount, from, willKill); + } + + public void PowerWordKill() + { + ArrayList list = new ArrayList(); + + foreach (Mobile m in this.GetMobilesInRange(1)) + { + if (m == this || !CanBeHarmful(m)) + continue; + + if (m.Player) + list.Add(m); + } + + foreach (Mobile m in list) + { + m.SendMessage("Dupre's corruption has given him a remarkable power over death, the ability to kill with a single word.....too bad you were listening!"); + DoHarmful(m); + m.FixedParticles(0x36CB, 1, 9, 9911, 67, 5, EffectLayer.Head); + int toPowerWordKill = Utility.RandomMinMax(50000, 60000); + m.Damage(toPowerWordKill, this); + } + NextPowerWordKillTime = DateTime.Now + TimeSpan.FromMinutes(15.0); + } + + public void SpawnUndeadArmy(Mobile target) + { + + + Map map = this.Map; + + if (map == null) + return; + + int knights = 0; + + foreach (Mobile m in this.GetMobilesInRange(10)) + { + if (m is UndeadKnight || m is WailingBanshee) + ++knights; + + + } + + if (knights < 1) + { + PlaySound(0x567); + + int newUndead = Utility.Random(13); + + for (int i = 0; i < newUndead; ++i) + { + BaseCreature skeleton; + + switch (Utility.Random(2)) + { + default: + case 0: skeleton = new WailingBanshee(); break; + case 1: skeleton = new UndeadKnight(); break; + + } + + skeleton.Team = this.Team; + + bool validLocation = false; + Point3D loc = this.Location; + + for (int j = 0; !validLocation && j < 10; ++j) + { + int x = X + Utility.Random(3) - 1; + int y = Y + Utility.Random(3) - 1; + int z = map.GetAverageZ(x, y); + + if (validLocation = map.CanFit(x, y, this.Z, 16, false, false)) + loc = new Point3D(x, y, Z); + else if (validLocation = map.CanFit(x, y, z, 16, false, false)) + loc = new Point3D(x, y, z); + } + + skeleton.MoveToWorld(loc, map); + skeleton.Combatant = target; + } + } + } + + public override void OnThink() + { + if (Hits < 250 && DateTime.Now >= m_NextPowerWordKillTime) + PowerWordKill(); + + + } + + public void DoSpecialAbility(Mobile target) + { + if (Hits < 500 ) + SpawnUndeadArmy(target); + + } + + public override void OnGotMeleeAttack(Mobile attacker) + { + base.OnGotMeleeAttack(attacker); + DoSpecialAbility(attacker); + } + + public override void OnGaveMeleeAttack(Mobile defender) + { + base.OnGaveMeleeAttack(defender); + DoSpecialAbility(defender); + } + + + public FallenDupre( Serial serial ) : base( serial ) + { + } + + public override void Serialize( GenericWriter writer ) + { + base.Serialize( writer ); + writer.Write( (int) 0 ); // version + } + + public override void Deserialize( GenericReader reader ) + { + base.Deserialize( reader ); + int version = reader.ReadInt(); + } + } +} diff --git a/Scripts/Custom/HeritageSovereign.cs b/Scripts/Custom/HeritageSovereign.cs index fba5324..4fe9f58 100755 --- a/Scripts/Custom/HeritageSovereign.cs +++ b/Scripts/Custom/HeritageSovereign.cs @@ -21,14 +21,17 @@ namespace Server.Items [Constructable] public HeritageSovereign(int amount) : base(0x14EF) // ORIGINAL ITEM ID { - LootType = LootType.Blessed; + LootType = LootType.Cursed; Hue = 2713; // ORIGINAL HUE Stackable = true; Amount = amount; UpdateName(); } - + public static bool CanSearch(Mobile m) + { + return m != null && m.Region.GetLogoutDelay(m) <= TimeSpan.Zero; + } public HeritageSovereign(Serial serial) : base(serial) { } @@ -65,13 +68,21 @@ namespace Server.Items public override void OnDoubleClick(Mobile from) { - if (!IsChildOf(from.Backpack)) + + if (from.AccessLevel < AccessLevel.Counselor && !CanSearch(from)) + { + // Before using the in game store, you must be in a safe log-out location + // such as an inn or a house which has you on its Owner, Co-owner, or Friends list. + from.SendLocalizedMessage(1156586); + return; + } + else if (!IsChildOf(from.Backpack)) { from.SendLocalizedMessage(1042001); // Must be in pack return; } - if (from is PlayerMobile pm) + else if (from is PlayerMobile pm) { pm.DepositSovereigns(Amount); Delete(); @@ -161,7 +172,7 @@ namespace Server.CustomSystems // 4. Determine Drop Chance if (!isEndgameBoss) { - if (Utility.RandomDouble() > 0.10) + if (Utility.RandomDouble() > 0.05) return; } @@ -171,7 +182,7 @@ namespace Server.CustomSystems if (isEndgameBoss) { - baseReward = 200; + baseReward = 100; } else { @@ -180,9 +191,9 @@ namespace Server.CustomSystems else if (maxHits >= 1000 && maxHits < 5000) baseReward = 10; else if (maxHits >= 5000 && maxHits < 10000) - baseReward = 50; + baseReward = 25; else if (maxHits >= 10000) - baseReward = 100; + baseReward = 50; } if (baseReward == 0) diff --git a/Scripts/Custom/InsuranceBroker.cs b/Scripts/Custom/InsuranceAgent.cs similarity index 96% rename from Scripts/Custom/InsuranceBroker.cs rename to Scripts/Custom/InsuranceAgent.cs index da615bd..54ed848 100644 --- a/Scripts/Custom/InsuranceBroker.cs +++ b/Scripts/Custom/InsuranceAgent.cs @@ -100,4 +100,4 @@ public class InsuranceAgent : BaseCreature base.Deserialize(reader); int version = reader.ReadInt(); } -} \ No newline at end of file +} diff --git a/Scripts/Custom/InsuranceAgent.cs.wip b/Scripts/Custom/InsuranceAgent.cs.wip deleted file mode 100755 index 8380c5f..0000000 --- a/Scripts/Custom/InsuranceAgent.cs.wip +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using Server; -using Server.Mobiles; -using Server.Gumps; - -public class InsuranceAgent : BaseCreature -{ - [Constructable] - public InsuranceAgent() - : base(AIType.AI_Vendor, FightMode.None, 0, 0, 0.2, 0.4) - { - Name = "an Insurance Agent"; - Body = 0x190; // male human - Hue = Utility.RandomSkinHue(); - - Blessed = true; // invulnerable - CantWalk = true; // stationary - Frozen = true; // cannot be moved - Warmode = false; // never fights - } - - public override void OnDoubleClick(Mobile from) - { - if (from is PlayerMobile pm && pm !=null) - { - this.Say("Here are your insurance options."); - - pm.OpenItemInsuranceMenu(new ItemInsuranceMenuGump(pm, pm.Items, null, 0)); - } - } - - public InsuranceAgent(Serial serial) : base(serial) { } - - public override void Serialize(GenericWriter writer) - { - base.Serialize(writer); - writer.Write(0); - } - - public override void Deserialize(GenericReader reader) - { - base.Deserialize(reader); - reader.ReadInt(); - } -} diff --git a/Scripts/Custom/OilofRestoration.cs b/Scripts/Custom/OilofRestoration.cs new file mode 100644 index 0000000..36019a0 --- /dev/null +++ b/Scripts/Custom/OilofRestoration.cs @@ -0,0 +1,121 @@ +using System; +using Server; +using Server.Items; +using Server.Targeting; +using Server.Engines.XmlSpawner2; + +namespace Server.Items +{ + public class OilOfRestoration : Item + { + [Constructable] + public OilOfRestoration() : base(0x1C18) // Bottle graphic + { + Name = "Oil of Restoration"; + Weight = 1.0; + Hue = 241; + } + + public OilOfRestoration(Serial serial) : base(serial) + { + } + + public override void OnDoubleClick(Mobile from) + { + if (!IsChildOf(from.Backpack)) + { + from.SendMessage("This must be in your pack to use."); + return; + } + + from.SendMessage("Select an oil cloth to apply the oil to."); + from.Target = new OilClothTarget(this); + } + + private class OilClothTarget : Target + { + private OilOfRestoration m_Oil; + + public OilClothTarget(OilOfRestoration oil) + : base(1, false, TargetFlags.None) + { + m_Oil = oil; + } + + protected override void OnTarget(Mobile from, object targeted) + { + if (m_Oil.Deleted) + return; + + if (!(targeted is OilCloth cloth)) + { + from.SendMessage("You must target an oil cloth."); + return; + } + + from.SendMessage("Select the item you wish to restore."); + from.Target = new RestoreItemTarget(m_Oil, cloth); + } + } + + private class RestoreItemTarget : Target + { + private OilOfRestoration m_Oil; + private OilCloth m_Cloth; + + public RestoreItemTarget(OilOfRestoration oil, OilCloth cloth) + : base(1, false, TargetFlags.None) + { + m_Oil = oil; + m_Cloth = cloth; + } + + protected override void OnTarget(Mobile from, object targeted) + { + if (m_Oil.Deleted || m_Cloth.Deleted) + return; + + if (!(targeted is Item item)) + { + from.SendMessage("That is not a valid item."); + return; + } + + // Get durability attachment + var dura = XmlAttach.FindAttachment(item, typeof(Server.Custom.DurabilityAttachment)) + as Server.Custom.DurabilityAttachment; + + if (dura == null || !dura.RepairLocked) + { + from.SendMessage("That item is not tempered and does not require restoration."); + return; + } + + // Remove repair lock + dura.RepairLocked = false; + + // Refresh tooltip + item.InvalidateProperties(); + + // Consume both items + m_Oil.Delete(); + m_Cloth.Delete(); + + from.SendMessage("The oil soaks in and restores the malleability of your item."); + from.PlaySound(0x240); + } + } + + public override void Serialize(GenericWriter writer) + { + base.Serialize(writer); + writer.Write(0); + } + + public override void Deserialize(GenericReader reader) + { + base.Deserialize(reader); + reader.ReadInt(); + } + } +} diff --git a/Scripts/Custom/minijsonparser.cs.bk b/Scripts/Custom/minijsonparser.cs.bk deleted file mode 100755 index 58502cb..0000000 --- a/Scripts/Custom/minijsonparser.cs.bk +++ /dev/null @@ -1,140 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Server -{ -public static class MiniJson -{ - public static object Parse(string json) - { - return new Parser(json).ParseValue(); - } - - private class Parser - { - private readonly string _json; - private int _index; - - public Parser(string json) - { - _json = json; - } - - public object ParseValue() - { - SkipWhitespace(); - - if (_index >= _json.Length) - return null; - - char c = _json[_index]; - - if (c == '{') return ParseObject(); - if (c == '[') return ParseArray(); - if (c == '"') return ParseString(); - if (char.IsDigit(c) || c == '-') return ParseNumber(); - - return null; - } - - private Dictionary ParseObject() - { - var dict = new Dictionary(); - _index++; // skip { - - while (true) - { - SkipWhitespace(); - if (_json[_index] == '}') - { - _index++; - return dict; - } - - string key = ParseString(); - - SkipWhitespace(); - _index++; // skip : - - object value = ParseValue(); - dict[key] = value; - - SkipWhitespace(); - if (_json[_index] == ',') - { - _index++; - continue; - } - - if (_json[_index] == '}') - { - _index++; - return dict; - } - } - } - - private List ParseArray() - { - var list = new List(); - _index++; // skip [ - - while (true) - { - SkipWhitespace(); - if (_json[_index] == ']') - { - _index++; - return list; - } - - list.Add(ParseValue()); - - SkipWhitespace(); - if (_json[_index] == ',') - { - _index++; - continue; - } - - if (_json[_index] == ']') - { - _index++; - return list; - } - } - } - - private string ParseString() - { - _index++; // skip " - int start = _index; - - while (_json[_index] != '"') - _index++; - - string s = _json.Substring(start, _index - start); - _index++; // skip closing " - return s; - } - - private object ParseNumber() - { - int start = _index; - - while (_index < _json.Length && (char.IsDigit(_json[_index]) || _json[_index] == '-')) - _index++; - - string num = _json.Substring(start, _index - start); - return int.Parse(num); - } - - private void SkipWhitespace() - { - while (_index < _json.Length && char.IsWhiteSpace(_json[_index])) - _index++; - } - } -} -} \ No newline at end of file diff --git a/Scripts/Custom/royalmintgump.cs.bk b/Scripts/Custom/royalmintgump.cs.bk deleted file mode 100755 index b6d6e26..0000000 --- a/Scripts/Custom/royalmintgump.cs.bk +++ /dev/null @@ -1,50 +0,0 @@ -using Server; -using Server.Gumps; -using Server.Network; - -namespace Server.CustomSystems -{ - public class RoyalMintGump : Gump - { - private readonly Mobile m_From; - private readonly RoyalMintOfficial m_NPC; - - public RoyalMintGump(Mobile from, RoyalMintOfficial npc) - : base(50, 50) - { - m_From = from; - m_NPC = npc; - - Closable = true; - Dragable = true; - - AddPage(0); - - AddBackground(0, 0, 350, 250, 9270); - AddLabel(110, 20, 1152, "Royal Mint Services"); - - AddButton(40, 70, 4005, 4007, 1, GumpButtonType.Reply, 0); - AddLabel(80, 70, 0x34, "Consolidate Your Notes"); - - AddButton(40, 120, 4005, 4007, 2, GumpButtonType.Reply, 0); - AddLabel(80, 120, 0x34, "Purchase Mint Box (5000)"); - - AddButton(40, 170, 4017, 4019, 0, GumpButtonType.Reply, 0); - AddLabel(80, 170, 0x34, "Close"); - } - - public override void OnResponse(NetState sender, RelayInfo info) - { - switch (info.ButtonID) - { - case 1: - m_NPC.ConsolidateNotes(m_From); - break; - - case 2: - m_NPC.PurchaseMintBox(m_From); - break; - } - } - } -} diff --git a/Scripts/Custom/royalmintofficial.cs b/Scripts/Custom/royalmintofficial.cs index 859d3d0..6759197 100755 --- a/Scripts/Custom/royalmintofficial.cs +++ b/Scripts/Custom/royalmintofficial.cs @@ -15,62 +15,15 @@ namespace Server.CustomSystems public RoyalMintOfficial() : base(AIType.AI_Vendor, FightMode.None, 10, 1, 0.2, 0.4) { - Title = "The Royal Mint Official"; - Hue = Utility.RandomSkinHue(); - - if (Female = Utility.RandomBool()) - { - Body = 0x191; - Name = NameList.RandomName("female"); - - AddItem(new PlateChest()); - AddItem(new PlateArms()); - AddItem(new PlateLegs()); - AddItem(new Cloak(113)); - - switch (Utility.Random(3)) - { - case 0: - AddItem(new Doublet(Utility.RandomNondyedHue())); - break; - case 1: - AddItem(new Tunic(Utility.RandomNondyedHue())); - break; - case 2: - AddItem(new BodySash(Utility.RandomNondyedHue())); - break; - } - } - else - { - Body = 0x190; - Name = NameList.RandomName("male"); - - AddItem(new PlateChest()); - AddItem(new PlateArms()); - AddItem(new PlateLegs()); - AddItem(new Cloak(113)); - - switch (Utility.Random(3)) - { - case 0: - AddItem(new Doublet(Utility.RandomNondyedHue())); - break; - case 1: - AddItem(new Tunic(Utility.RandomNondyedHue())); - break; - case 2: - AddItem(new BodySash(Utility.RandomNondyedHue())); - break; - } - } - Utility.AssignRandomHair(this); - - if (Utility.RandomBool()) - { - Utility.AssignRandomFacialHair(this, HairHue); - } - } + Name = "Royal Mint Official"; + Title = "the Sovereign Clerk"; + Body = 0x190; + Hue = 33770; + + AddItem(new Robe(2713)); + AddItem(new Sandals(1150)); + AddItem(new GoldBracelet()); + } public RoyalMintOfficial(Serial serial) : base(serial) { diff --git a/Scripts/Gumps/AdminGump.cs b/Scripts/Gumps/AdminGump.cs index cdaf8b4..7337867 100755 --- a/Scripts/Gumps/AdminGump.cs +++ b/Scripts/Gumps/AdminGump.cs @@ -325,41 +325,38 @@ namespace Server.Gumps sb.Append(((maxIOCP - curIOCP) * 100) / maxIOCP); sb.Append("%"); - List pools = BufferPool.Pools; + IList pools = BufferPool.Pools; - lock (pools) + for (int i = 0; i < pools.Count; ++i) { - for (int i = 0; i < pools.Count; ++i) - { - BufferPool pool = pools[i]; - string name; - int freeCount; - int initialCapacity; - int currentCapacity; - int bufferSize; - int misses; + BufferPool pool = pools[i]; + string name; + int freeCount; + int initialCapacity; + int currentCapacity; + int bufferSize; + int misses; - pool.GetInfo(out name, out freeCount, out initialCapacity, out currentCapacity, out bufferSize, out misses); + pool.GetInfo(out name, out freeCount, out initialCapacity, out currentCapacity, out bufferSize, out misses); - if (sb.Length > 0) - sb.Append("

"); + if (sb.Length > 0) + sb.Append("

"); - sb.Append(name); - sb.Append("
Size: "); - sb.Append(FormatByteAmount(bufferSize)); - sb.Append("
Capacity: "); - sb.Append(currentCapacity); - sb.Append(" ("); - sb.Append(misses); - sb.Append(" misses)
Available: "); - sb.Append(freeCount); - sb.Append("
Usage: "); - sb.Append(((currentCapacity - freeCount) * 100) / currentCapacity); - sb.Append("% : "); - sb.Append(FormatByteAmount((currentCapacity - freeCount) * bufferSize)); - sb.Append(" of "); - sb.Append(FormatByteAmount(currentCapacity * bufferSize)); - } + sb.Append(name); + sb.Append("
Size: "); + sb.Append(FormatByteAmount(bufferSize)); + sb.Append("
Capacity: "); + sb.Append(currentCapacity); + sb.Append(" ("); + sb.Append(misses); + sb.Append(" misses)
Available: "); + sb.Append(freeCount); + sb.Append("
Usage: "); + sb.Append(((currentCapacity - freeCount) * 100) / currentCapacity); + sb.Append("% : "); + sb.Append(FormatByteAmount((currentCapacity - freeCount) * bufferSize)); + sb.Append(" of "); + sb.Append(FormatByteAmount(currentCapacity * bufferSize)); } this.AddLabel(20, 200, LabelHue, "Pooling:"); @@ -2041,7 +2038,7 @@ namespace Server.Gumps if (level > AccessLevel.VIP) { - List clients = NetState.Instances; + IList clients = NetState.Instances; int count = 0; for (int i = 0; i < clients.Count; ++i) @@ -2178,7 +2175,7 @@ namespace Server.Gumps } else { - List instances = NetState.Instances; + IList instances = NetState.Instances; for (int i = 0; i < instances.Count; ++i) { diff --git a/Scripts/Gumps/RunebookGump.cs b/Scripts/Gumps/RunebookGump.cs index a2613d0..7966ce9 100755 --- a/Scripts/Gumps/RunebookGump.cs +++ b/Scripts/Gumps/RunebookGump.cs @@ -510,4 +510,4 @@ namespace Server.Gumps } } } -} \ No newline at end of file +} diff --git a/Scripts/Gumps/WhoGump.cs b/Scripts/Gumps/WhoGump.cs index 2db8b6d..e0ca1f7 100755 --- a/Scripts/Gumps/WhoGump.cs +++ b/Scripts/Gumps/WhoGump.cs @@ -81,7 +81,7 @@ namespace Server.Gumps filter = filter.ToLower(); List list = new List(); - List states = NetState.Instances; + IList states = NetState.Instances; for (int i = 0; i < states.Count; ++i) { @@ -293,4 +293,4 @@ namespace Server.Gumps } } } -} \ No newline at end of file +} diff --git a/Scripts/Items/Artifacts/Equipment/Armor/Sets/SetItem.cs b/Scripts/Items/Artifacts/Equipment/Armor/Sets/SetItem.cs index c857df6..0363b9b 100755 --- a/Scripts/Items/Artifacts/Equipment/Armor/Sets/SetItem.cs +++ b/Scripts/Items/Artifacts/Equipment/Armor/Sets/SetItem.cs @@ -30,7 +30,7 @@ namespace Server Virtuoso, Aloron, Darden, - ForsakenVirtues + ForsakenVirtues } public interface ISetItem diff --git a/Scripts/Items/Books/RunicAtlas.cs b/Scripts/Items/Books/RunicAtlas.cs index 4b0423c..f8daeb2 100755 --- a/Scripts/Items/Books/RunicAtlas.cs +++ b/Scripts/Items/Books/RunicAtlas.cs @@ -562,4 +562,4 @@ namespace Server.Items } } } -} \ No newline at end of file +} diff --git a/Scripts/Items/Consumables/PowderOfTemperament.cs b/Scripts/Items/Consumables/PowderOfTemperament.cs index a5da3d7..0eaa7a2 100755 --- a/Scripts/Items/Consumables/PowderOfTemperament.cs +++ b/Scripts/Items/Consumables/PowderOfTemperament.cs @@ -1,65 +1,53 @@ using System; using Server.Network; using Server.Targeting; +using Server.Custom; // Required for durability extension methods namespace Server.Items { public class PowderOfTemperament : Item, IUsesRemaining { - public static bool CanPOFJewelry = Config.Get("Loot.CanPOFJewelry", false); - private int m_UsesRemaining; [Constructable] - public PowderOfTemperament() - : this(10) + public PowderOfTemperament() : this(10) { } [Constructable] - public PowderOfTemperament(int charges) - : base(4102) + public PowderOfTemperament(int charges) : base(4102) { Weight = 1.0; Hue = 2419; UsesRemaining = charges; } - public PowderOfTemperament(Serial serial) - : base(serial) + public PowderOfTemperament(Serial serial) : base(serial) { } [CommandProperty(AccessLevel.GameMaster)] public int UsesRemaining { - get - { - return m_UsesRemaining; - } + get { return m_UsesRemaining; } set { m_UsesRemaining = value; InvalidateProperties(); } } + public bool ShowUsesRemaining { - get - { - return true; - } - set - { - } + get { return true; } + set { } } + public override int LabelNumber { - get - { - return 1049082; - } - }// powder of fortifying + get { return 1049082; } // powder of fortifying + } + public override void Serialize(GenericWriter writer) { base.Serialize(writer); @@ -74,31 +62,13 @@ namespace Server.Items int version = reader.ReadInt(); - switch ( version ) - { - case 0: - { - m_UsesRemaining = reader.ReadInt(); - break; - } - } + if (version == 0) + m_UsesRemaining = reader.ReadInt(); } public override void AddUsesRemainingProperties(ObjectPropertyList list) { - list.Add(1060584, m_UsesRemaining.ToString()); // uses remaining: ~1_val~ - } - - public virtual void DisplayDurabilityTo(Mobile m) - { - LabelToAffix(m, 1017323, AffixType.Append, ": " + m_UsesRemaining.ToString()); // Durability - } - - public override void OnSingleClick(Mobile from) - { - DisplayDurabilityTo(from); - - base.OnSingleClick(from); + list.Add(1060584, m_UsesRemaining.ToString()); } public override void OnDoubleClick(Mobile from) @@ -106,12 +76,13 @@ namespace Server.Items if (IsChildOf(from.Backpack)) from.Target = new InternalTarget(this); else - from.SendLocalizedMessage(1042001); // That must be in your pack for you to use it. + from.SendLocalizedMessage(1042001); // Must be in pack } private class InternalTarget : Target { - private readonly PowderOfTemperament m_Powder; + private PowderOfTemperament m_Powder; + public InternalTarget(PowderOfTemperament powder) : base(2, false, TargetFlags.None) { @@ -122,153 +93,169 @@ namespace Server.Items { if (m_Powder.Deleted || m_Powder.UsesRemaining <= 0) { - from.SendLocalizedMessage(1049086); // You have used up your powder of temperament. + from.SendLocalizedMessage(1049086); // used up return; } - if (targeted is Item) + Item item = targeted as Item; + + if (item == null) { - Item item = (Item)targeted; - bool noGo = false; - int antique = 0; - - if (!Server.Engines.Craft.Repair.AllowsRepair(item, null) || (item is BaseJewel && !CanPOFJewelry)) - { - from.SendLocalizedMessage(1049083); // You cannot use the powder on that item. - return; - } - - #region SA - if (item is BaseWeapon) - { - if (((BaseWeapon)item).Attributes.Brittle > 0 || ((BaseWeapon)item).NegativeAttributes.Brittle > 0) - noGo = true; - antique = ((BaseWeapon)item).NegativeAttributes.Antique; - } - else if (item is BaseArmor) - { - if (((BaseArmor)item).Attributes.Brittle > 0 || ((BaseArmor)item).NegativeAttributes.Brittle > 0) - noGo = true; - antique = ((BaseArmor)item).NegativeAttributes.Antique; - } - else if (item is BaseClothing) - { - if (((BaseClothing)item).Attributes.Brittle > 0 || ((BaseClothing)item).NegativeAttributes.Brittle > 0) - noGo = true; - antique = ((BaseClothing)item).NegativeAttributes.Antique; - } - else if (item is BaseJewel) - { - if (((BaseJewel)item).Attributes.Brittle > 0 || ((BaseJewel)item).NegativeAttributes.Brittle > 0) - noGo = true; - antique = ((BaseJewel)item).NegativeAttributes.Antique; - } - else if (item is BaseTalisman && ((BaseTalisman)item).Attributes.Brittle > 0) - { - noGo = true; - } - if (noGo) - { - from.SendLocalizedMessage(1149799); //That cannot be used on brittle items. - return; - } - #endregion - - if (targeted is IDurability) - { - IDurability wearable = (IDurability)targeted; - - if (!wearable.CanFortify) - { - from.SendLocalizedMessage(1049083); // You cannot use the powder on that item. - return; - } - - if ((item.IsChildOf(from.Backpack) || (Core.ML && item.Parent == from)) && m_Powder.IsChildOf(from.Backpack)) - { - int origMaxHP = wearable.MaxHitPoints; - int origCurHP = wearable.HitPoints; - - if (origMaxHP > 0) - { - int initMaxHP = antique <= 0 ? 255 : antique == 1 ? 250 : antique == 2 ? 200 : 150; - - wearable.UnscaleDurability(); - - if (wearable.MaxHitPoints < initMaxHP) - { - if (antique > 0) - { - wearable.MaxHitPoints = initMaxHP; - wearable.HitPoints += initMaxHP; - } - else - { - int bonus = initMaxHP - wearable.MaxHitPoints; - - if (bonus > 10) - bonus = 10; - - wearable.MaxHitPoints += bonus; - wearable.HitPoints += bonus; - } - - wearable.ScaleDurability(); - - if (wearable.MaxHitPoints > 255) - wearable.MaxHitPoints = 255; - if (wearable.HitPoints > 255) - wearable.HitPoints = 255; - - if (wearable.MaxHitPoints > origMaxHP) - { - from.SendLocalizedMessage(1049084); // You successfully use the powder on the item. - from.PlaySound(0x247); - - --m_Powder.UsesRemaining; - - if (m_Powder.UsesRemaining <= 0) - { - from.SendLocalizedMessage(1049086); // You have used up your powder of fortifying. - m_Powder.Delete(); - } - - if (antique > 0) - { - if (item is BaseWeapon) ((BaseWeapon)item).NegativeAttributes.Antique++; - if (item is BaseArmor) ((BaseArmor)item).NegativeAttributes.Antique++; - if (item is BaseJewel) ((BaseJewel)item).NegativeAttributes.Antique++; - if (item is BaseClothing) ((BaseClothing)item).NegativeAttributes.Antique++; - } - } - else - { - wearable.MaxHitPoints = origMaxHP; - wearable.HitPoints = origCurHP; - from.SendLocalizedMessage(1049085); // The item cannot be improved any further. - } - } - else - { - from.SendLocalizedMessage(1049085); // The item cannot be improved any further. - wearable.ScaleDurability(); - } - } - else - { - from.SendLocalizedMessage(1049083); // You cannot use the powder on that item. - } - } - else - { - from.SendLocalizedMessage(1042001); // That must be in your pack for you to use it. - } - } + from.SendLocalizedMessage(1042001); + return; } - else + + // Jewelry cannot be fortified (OSI) + if (item is BaseJewel) { - from.SendLocalizedMessage(1049083); // You cannot use the powder on that item. + from.SendLocalizedMessage(1049083); + return; } + + // Brittle or Antique items cannot be fortified (OSI) + if (IsBrittle(item) || IsAntique(item)) + { + from.SendLocalizedMessage(1049083); + return; + } + + IDurability wearable = targeted as IDurability; + + if (wearable == null || !wearable.CanFortify) + { + from.SendLocalizedMessage(1049083); + return; + } + + if (!(item.IsChildOf(from.Backpack) || (Core.ML && item.Parent == from)) || !m_Powder.IsChildOf(from.Backpack)) + { + from.SendLocalizedMessage(1049085); + return; + } + + // =============================== + // HARD CAP CHECK — OSI ACCURATE + // =============================== + int oldMax = wearable.MaxHitPoints; + + if (oldMax >= 255) + { + from.SendMessage("This item cannot be fortified any further."); + return; + } + + // =============================== + // APPLY +10 DURABILITY (CAPPED) + // =============================== + int delta = 10; + + if (oldMax + delta > 255) + delta = 255 - oldMax; + + if (delta <= 0) + { + from.SendMessage("This item cannot be fortified any further."); + return; + } + + int newMax = oldMax + delta; + + wearable.MaxHitPoints = newMax; + wearable.HitPoints += delta; + + if (wearable.HitPoints > wearable.MaxHitPoints) + wearable.HitPoints = wearable.MaxHitPoints; + + // =============================================== + // REMOVE SELF REPAIR ON FIRST PoF USE + // =============================================== + if (item is BaseWeapon bw) + { + bw.WeaponAttributes.SelfRepair = 0; + } + + if (item is BaseArmor ba) + { + ba.ArmorAttributes.SelfRepair = 0; + } + + if (item is BaseShield bs) + { + bs.ArmorAttributes.SelfRepair = 0; + } + + if (item is BaseClothing bc) + { + bc.ClothingAttributes.SelfRepair = 0; + } + + // =============================== + // TRACK POF USES + // =============================== + item.SetPoFUses(item.GetPoFUses() + 1); + // =============================== + // APPLY REPAIR LOCK + // =============================== + item.SetRepairLocked(true); + + + + from.SendMessage("You successfully fortify the item."); + from.PlaySound(0x247); + + m_Powder.UsesRemaining--; + + if (m_Powder.UsesRemaining <= 0) + { + from.SendLocalizedMessage(1049086); + m_Powder.Delete(); + } + } + + private bool IsBrittle(Item item) + { + BaseWeapon bw = item as BaseWeapon; + if (bw != null && (bw.Attributes.Brittle > 0 || bw.NegativeAttributes.Brittle > 0)) + return true; + + BaseArmor ba = item as BaseArmor; + if (ba != null && (ba.Attributes.Brittle > 0 || ba.NegativeAttributes.Brittle > 0)) + return true; + + BaseClothing bc = item as BaseClothing; + if (bc != null && (bc.Attributes.Brittle > 0 || bc.NegativeAttributes.Brittle > 0)) + return true; + + BaseJewel bj = item as BaseJewel; + if (bj != null && (bj.Attributes.Brittle > 0 || bj.NegativeAttributes.Brittle > 0)) + return true; + + BaseTalisman bt = item as BaseTalisman; + if (bt != null && bt.Attributes.Brittle > 0) + return true; + + return false; + } + + private bool IsAntique(Item item) + { + BaseWeapon bw = item as BaseWeapon; + if (bw != null && bw.NegativeAttributes.Antique > 0) + return true; + + BaseArmor ba = item as BaseArmor; + if (ba != null && ba.NegativeAttributes.Antique > 0) + return true; + + BaseClothing bc = item as BaseClothing; + if (bc != null && bc.NegativeAttributes.Antique > 0) + return true; + + BaseJewel bj = item as BaseJewel; + if (bj != null && bj.NegativeAttributes.Antique > 0) + return true; + + return false; } } } diff --git a/Scripts/Items/Equipment/Armor/BaseArmor.cs b/Scripts/Items/Equipment/Armor/BaseArmor.cs index 0c70f77..000d8d6 100755 --- a/Scripts/Items/Equipment/Armor/BaseArmor.cs +++ b/Scripts/Items/Equipment/Armor/BaseArmor.cs @@ -284,7 +284,7 @@ namespace Server.Items } } - public virtual bool CanAlter { get { return true; } } + public virtual bool CanAlter { get { return true; } } public virtual bool UseIntOrDexProperty { @@ -401,9 +401,9 @@ namespace Server.Items return m_ArmorBase; } set - { + { m_ArmorBase = value; - Invalidate(); + Invalidate(); } } @@ -424,7 +424,7 @@ namespace Server.Items if (m_Protection != ArmorProtectionLevel.Regular) ar += 10 + (5 * (int)m_Protection); - switch ( m_Resource ) + switch (m_Resource) { case CraftResource.DullCopper: ar += 2; @@ -538,7 +538,7 @@ namespace Server.Items armor.m_RefinedPoison > 0 || armor.m_RefinedEnergy > 0); } - + public override void AddResistanceProperties(ObjectPropertyList list) { if (PhysicalResistance != 0 || m_RefinedPhysical != 0) @@ -761,9 +761,9 @@ namespace Server.Items #region Runic Reforging [CommandProperty(AccessLevel.GameMaster)] - public ReforgedPrefix ReforgedPrefix - { - get { return m_ReforgedPrefix; } + public ReforgedPrefix ReforgedPrefix + { + get { return m_ReforgedPrefix; } set { m_ReforgedPrefix = value; InvalidateProperties(); } } @@ -776,9 +776,9 @@ namespace Server.Items [CommandProperty(AccessLevel.GameMaster)] public ItemPower ItemPower - { - get { return m_ItemPower; } - set { m_ItemPower = value; InvalidateProperties(); } + { + get { return m_ItemPower; } + set { m_ItemPower = value; InvalidateProperties(); } } #endregion @@ -963,11 +963,11 @@ namespace Server.Items [CommandProperty(AccessLevel.GameMaster)] public int HitPoints { - get + get { return m_HitPoints; } - set + set { if (value != m_HitPoints && MaxHitPoints > 0) { @@ -1298,7 +1298,7 @@ namespace Server.Items { get { - switch ( Layer ) + switch (Layer) { default: case Layer.Neck: @@ -1327,7 +1327,7 @@ namespace Server.Items public int GetProtOffset() { - switch ( m_Protection ) + switch (m_Protection) { case ArmorProtectionLevel.Guarding: return 1; @@ -1372,10 +1372,10 @@ namespace Server.Items { int bonus = 0; - if (m_Quality == ItemQuality.Exceptional &&!(this is GargishLeatherWingArmor)) + if (m_Quality == ItemQuality.Exceptional && !(this is GargishLeatherWingArmor)) bonus += 20; - switch ( m_Durability ) + switch (m_Durability) { case ArmorDurabilityLevel.Durable: bonus += 20; @@ -1630,10 +1630,10 @@ namespace Server.Items PlayerConstructed = 0x01000000, xAbsorptionAttributes = 0x02000000, xWeaponAttributes = 0x04000000, - NegativeAttributes = 0x08000000, - Altered = 0x10000000, + NegativeAttributes = 0x08000000, + Altered = 0x10000000, TalismanProtection = 0x20000000, - EngravedText = 0x40000000 + EngravedText = 0x40000000 } #region Mondain's Legacy Sets @@ -1720,7 +1720,7 @@ namespace Server.Items // Version 8 writer.Write((int)m_TimesImbued); - + #endregion writer.Write((Mobile)m_BlessedBy); @@ -1903,7 +1903,7 @@ namespace Server.Items int version = reader.ReadInt(); - switch ( version ) + switch (version) { case 15: case 14: @@ -1961,12 +1961,12 @@ namespace Server.Items case 8: { m_TimesImbued = reader.ReadInt(); - + #endregion m_BlessedBy = reader.ReadMobile(); - SetFlag sflags = (SetFlag)reader.ReadEncodedInt(); + SetFlag sflags = (SetFlag)reader.ReadEncodedInt(); if (GetSaveFlag(sflags, SetFlag.Attributes)) m_SetAttributes = new AosAttributes(this, reader); @@ -2198,7 +2198,8 @@ namespace Server.Items if (m_ArmorBase == RevertArmorBase) m_ArmorBase = -1; - /*m_BodyPos = (ArmorBodyType)*/reader.ReadInt(); + /*m_BodyPos = (ArmorBodyType)*/ + reader.ReadInt(); if (version < 4) { @@ -2217,7 +2218,7 @@ namespace Server.Items { OreInfo info; - switch ( reader.ReadInt() ) + switch (reader.ReadInt()) { default: case 0: @@ -2595,7 +2596,7 @@ namespace Server.Items damageTaken -= Absorbed; - if (damageTaken < 0) + if (damageTaken < 0) damageTaken = 0; if (Absorbed < 2) @@ -2682,7 +2683,7 @@ namespace Server.Items { int oreType; - switch ( m_Resource ) + switch (m_Resource) { case CraftResource.DullCopper: oreType = 1053108; break; // dull copper case CraftResource.ShadowIron: oreType = 1053107; break; // shadow iron @@ -2701,7 +2702,7 @@ namespace Server.Items case CraftResource.GreenScales: oreType = 1060819; break; // green case CraftResource.WhiteScales: oreType = 1060821; break; // white case CraftResource.BlueScales: oreType = 1060815; break; // blue - case CraftResource.OakWood: oreType = 1072533; break; // oak + case CraftResource.OakWood: oreType = 1072533; break; // oak case CraftResource.AshWood: oreType = 1072534; break; // ash case CraftResource.YewWood: oreType = 1072535; break; // yew case CraftResource.Heartwood: oreType = 1072536; break; // heartwood @@ -2794,6 +2795,17 @@ namespace Server.Items { base.AddNameProperties(list); + // =============================================== + // DURABILITY TOOLTIP: TEMPERED / REPAIR LOCKED + // =============================================== + var dura = XmlAttach.FindAttachment(this, typeof(Server.Custom.DurabilityAttachment)) + as Server.Custom.DurabilityAttachment; + + if (dura != null && dura.RepairLocked) + { + list.Add("Tempered — Cannot be repaired"); + } + #region Factions FactionEquipment.AddFactionProperties(this, list); #endregion @@ -2895,14 +2907,14 @@ namespace Server.Items if (m_TalismanProtection != null && !m_TalismanProtection.IsEmpty && m_TalismanProtection.Amount > 0) list.Add(1072387, "{0}\t{1}", m_TalismanProtection.Name != null ? m_TalismanProtection.Name.ToString() : "Unknown", m_TalismanProtection.Amount); // ~1_NAME~ Protection: +~2_val~% - - if ((prop = m_AosArmorAttributes.SoulCharge) != 0) + + if ((prop = m_AosArmorAttributes.SoulCharge) != 0) list.Add(1113630, prop.ToString()); // Soul Charge ~1_val~% - - if((prop = m_AosArmorAttributes.ReactiveParalyze) != 0) + + if ((prop = m_AosArmorAttributes.ReactiveParalyze) != 0) list.Add(1112364); // reactive paralyze - - if ((prop = m_SAAbsorptionAttributes.EaterFire) != 0) + + if ((prop = m_SAAbsorptionAttributes.EaterFire) != 0) list.Add(1113593, prop.ToString()); // Fire Eater ~1_Val~% if ((prop = m_SAAbsorptionAttributes.EaterCold) != 0) @@ -2919,8 +2931,8 @@ namespace Server.Items if ((prop = m_SAAbsorptionAttributes.EaterDamage) != 0) list.Add(1113598, prop.ToString()); // Damage Eater ~1_Val~% - - if ((prop = m_SAAbsorptionAttributes.ResonanceFire) != 0) + + if ((prop = m_SAAbsorptionAttributes.ResonanceFire) != 0) list.Add(1113691, prop.ToString()); // Fire Resonance ~1_val~% if ((prop = m_SAAbsorptionAttributes.ResonanceCold) != 0) @@ -2934,41 +2946,41 @@ namespace Server.Items if ((prop = m_SAAbsorptionAttributes.ResonanceKinetic) != 0) list.Add(1113695, prop.ToString()); // Kinetic Resonance ~1_val~% - - if ((prop = m_SAAbsorptionAttributes.CastingFocus) != 0) + + if ((prop = m_SAAbsorptionAttributes.CastingFocus) != 0) list.Add(1113696, prop.ToString()); // Casting Focus ~1_val~% - - if ((prop = m_AosAttributes.SpellChanneling) != 0) + + if ((prop = m_AosAttributes.SpellChanneling) != 0) list.Add(1060482); // spell channeling - - if ((prop = m_AosArmorAttributes.SelfRepair) != 0) + + if ((prop = m_AosArmorAttributes.SelfRepair) != 0) list.Add(1060450, prop.ToString()); // self repair ~1_val~ - - if ((prop = m_AosAttributes.NightSight) != 0) + + if ((prop = m_AosAttributes.NightSight) != 0) list.Add(1060441); // night sight - - if ((prop = m_AosAttributes.BonusStr) != 0) + + if ((prop = m_AosAttributes.BonusStr) != 0) list.Add(1060485, prop.ToString()); // strength bonus ~1_val~ - - if ((prop = m_AosAttributes.BonusDex) != 0) + + if ((prop = m_AosAttributes.BonusDex) != 0) list.Add(1060409, prop.ToString()); // dexterity bonus ~1_val~ if ((prop = m_AosAttributes.BonusInt) != 0) list.Add(1060432, prop.ToString()); // intelligence bonus ~1_val~ - - if ((prop = m_AosAttributes.BonusHits) != 0) + + if ((prop = m_AosAttributes.BonusHits) != 0) list.Add(1060431, prop.ToString()); // hit point increase ~1_val~ - - if ((prop = m_AosAttributes.BonusStam) != 0) + + if ((prop = m_AosAttributes.BonusStam) != 0) list.Add(1060484, prop.ToString()); // stamina increase ~1_val~ - - if ((prop = m_AosAttributes.BonusMana) != 0) + + if ((prop = m_AosAttributes.BonusMana) != 0) list.Add(1060439, prop.ToString()); // mana increase ~1_val~ - - if ((prop = m_AosAttributes.RegenHits) != 0) + + if ((prop = m_AosAttributes.RegenHits) != 0) list.Add(1060444, prop.ToString()); // hit point regeneration ~1_val~ - - if ((prop = m_AosAttributes.RegenStam) != 0) + + if ((prop = m_AosAttributes.RegenStam) != 0) list.Add(1060443, prop.ToString()); // stamina regeneration ~1_val~ if ((prop = m_AosAttributes.RegenMana) != 0) @@ -2976,8 +2988,8 @@ namespace Server.Items if ((prop = (GetLuckBonus() + m_AosAttributes.Luck)) != 0) list.Add(1060436, prop.ToString()); // luck ~1_val~ - - if ((prop = m_AosAttributes.EnhancePotions) != 0) + + if ((prop = m_AosAttributes.EnhancePotions) != 0) list.Add(1060411, prop.ToString()); // enhance potions ~1_val~% if ((prop = m_AosAttributes.ReflectPhysical) != 0) @@ -2985,45 +2997,45 @@ namespace Server.Items if (this is SurgeShield && ((SurgeShield)this).Surge > SurgeType.None) list.Add(1153098, ((SurgeShield)this).Charges.ToString()); - - if ((prop = m_AosAttributes.AttackChance) != 0) + + if ((prop = m_AosAttributes.AttackChance) != 0) list.Add(1060415, prop.ToString()); // hit chance increase ~1_val~% - - if ((prop = m_AosAttributes.WeaponSpeed) != 0) + + if ((prop = m_AosAttributes.WeaponSpeed) != 0) list.Add(1060486, prop.ToString()); // swing speed increase ~1_val~% - - if ((prop = m_AosAttributes.WeaponDamage) != 0) + + if ((prop = m_AosAttributes.WeaponDamage) != 0) list.Add(1060401, prop.ToString()); // damage increase ~1_val~% if ((prop = m_AosAttributes.DefendChance) != 0) list.Add(1060408, prop.ToString()); // defense chance increase ~1_val~% - - if ((prop = m_AosAttributes.CastRecovery) != 0) + + if ((prop = m_AosAttributes.CastRecovery) != 0) list.Add(1060412, prop.ToString()); // faster cast recovery ~1_val~ - - if ((prop = m_AosAttributes.CastSpeed) != 0) + + if ((prop = m_AosAttributes.CastSpeed) != 0) list.Add(1060413, prop.ToString()); // faster casting ~1_val~ - - if ((prop = m_AosAttributes.SpellDamage) != 0) + + if ((prop = m_AosAttributes.SpellDamage) != 0) list.Add(1060483, prop.ToString()); // spell damage increase ~1_val~% - - if ((prop = m_AosAttributes.LowerManaCost) != 0) + + if ((prop = m_AosAttributes.LowerManaCost) != 0) list.Add(1060433, prop.ToString()); // lower mana cost ~1_val~% if ((prop = m_AosAttributes.LowerRegCost) != 0) list.Add(1060434, prop.ToString()); // lower reagent cost ~1_val~% - - if (Core.ML && (prop = m_AosAttributes.IncreasedKarmaLoss) != 0) + + if (Core.ML && (prop = m_AosAttributes.IncreasedKarmaLoss) != 0) list.Add(1075210, prop.ToString()); // Increased Karma Loss ~1val~% AddResistanceProperties(list); - - if ((prop = m_AosArmorAttributes.MageArmor) != 0) + + if ((prop = m_AosArmorAttributes.MageArmor) != 0) list.Add(1060437); // mage armor - - if ((prop = GetLowerStatReq()) != 0) + + if ((prop = GetLowerStatReq()) != 0) list.Add(1060435, prop.ToString()); // lower requirements ~1_val~% - + if ((prop = ComputeStatReq(StatType.Str)) > 0) list.Add(1061170, prop.ToString()); // strength requirement ~1_val~ @@ -3122,15 +3134,15 @@ namespace Server.Items #region Mondain's Legacy if (!Core.ML || !craftItem.ForceNonExceptional) { - if (typeRes == null) - typeRes = craftItem.Resources.GetAt(0).ItemType; + if (typeRes == null) + typeRes = craftItem.Resources.GetAt(0).ItemType; - Resource = CraftResources.GetFromType(typeRes); + Resource = CraftResources.GetFromType(typeRes); } #endregion if (typeRes == null || craftItem.ForceNonExceptional) - typeRes = craftItem.Resources.GetAt(0).ItemType; + typeRes = craftItem.Resources.GetAt(0).ItemType; PlayerConstructed = true; @@ -3239,7 +3251,7 @@ namespace Server.Items } info = GetResourceAttrs(m_Resource); - + // add new bonus m_PhysicalBonus += info.ArmorPhysicalResist; m_FireBonus += info.ArmorFireResist; diff --git a/Scripts/Items/Equipment/Armor/BaseShield.cs b/Scripts/Items/Equipment/Armor/BaseShield.cs index dc3d6ac..04af64f 100755 --- a/Scripts/Items/Equipment/Armor/BaseShield.cs +++ b/Scripts/Items/Equipment/Armor/BaseShield.cs @@ -1,5 +1,7 @@ using System; using Server.Network; +using Server.Engines.XmlSpawner2; + namespace Server.Items { @@ -69,6 +71,16 @@ namespace Server.Items public override void AddNameProperties(ObjectPropertyList list) { base.AddNameProperties(list); + // =============================================== + // DURABILITY TOOLTIP: TEMPERED / REPAIR LOCKED + // =============================================== + var dura = XmlAttach.FindAttachment(this, typeof(Server.Custom.DurabilityAttachment)) + as Server.Custom.DurabilityAttachment; + + if (dura != null && dura.RepairLocked) + { + list.Add("Tempered — Cannot be repaired"); + } if (Core.EJ && LastParryChance > 0) { diff --git a/Scripts/Items/Equipment/Clothing/BaseClothing.cs b/Scripts/Items/Equipment/Clothing/BaseClothing.cs index 7700ab0..cd92b7a 100755 --- a/Scripts/Items/Equipment/Clothing/BaseClothing.cs +++ b/Scripts/Items/Equipment/Clothing/BaseClothing.cs @@ -5,6 +5,8 @@ using Server.Engines.Craft; using Server.Factions; using Server.Network; using Server.Mobiles; +using Server.Engines.XmlSpawner2; + namespace Server.Items { @@ -78,7 +80,7 @@ namespace Server.Items public virtual bool CanFortify { get { return !IsImbued && NegativeAttributes.Antique < 4; } } public virtual bool CanRepair { get { return m_NegativeAttributes.NoRepair == 0; } } - public virtual bool CanAlter { get { return true; } } + public virtual bool CanAlter { get { return true; } } private int m_MaxHitPoints; private int m_HitPoints; @@ -126,7 +128,7 @@ namespace Server.Items public int HitPoints { get { return m_HitPoints; } - set + set { if (value != m_HitPoints && MaxHitPoints > 0) { @@ -362,10 +364,10 @@ namespace Server.Items public AosArmorAttributes ClothingAttributes { get { return m_AosClothingAttributes; } set { } } [CommandProperty(AccessLevel.GameMaster)] - public AosSkillBonuses SkillBonuses { get { return m_AosSkillBonuses; } set { } } + public AosSkillBonuses SkillBonuses { get { return m_AosSkillBonuses; } set { } } [CommandProperty(AccessLevel.GameMaster)] - public AosElementAttributes Resistances { get { return m_AosResistances; } set { } } + public AosElementAttributes Resistances { get { return m_AosResistances; } set { } } [CommandProperty(AccessLevel.GameMaster)] public SAAbsorptionAttributes SAAbsorptionAttributes { get { return m_SAAbsorptionAttributes; } set { } } @@ -381,7 +383,7 @@ namespace Server.Items public virtual int BaseColdResistance { get { return 0; } } public virtual int BasePoisonResistance { get { return 0; } } public virtual int BaseEnergyResistance { get { return 0; } } - + #region Mondain's Legacy Sets public override int PhysicalResistance { @@ -779,7 +781,7 @@ namespace Server.Items damageTaken -= Absorbed; - if (damageTaken < 0) + if (damageTaken < 0) damageTaken = 0; double chance = NegativeAttributes.Antique > 0 ? 80 : 25; @@ -955,7 +957,7 @@ namespace Server.Items { int oreType; - switch ( m_Resource ) + switch (m_Resource) { case CraftResource.DullCopper: oreType = 1053108; @@ -1071,6 +1073,16 @@ namespace Server.Items public override void AddNameProperties(ObjectPropertyList list) { base.AddNameProperties(list); + // =============================================== + // DURABILITY TOOLTIP: TEMPERED / REPAIR LOCKED + // =============================================== + var dura = XmlAttach.FindAttachment(this, typeof(Server.Custom.DurabilityAttachment)) + as Server.Custom.DurabilityAttachment; + + if (dura != null && dura.RepairLocked) + { + list.Add("Tempered — Cannot be repaired"); + } #region Factions FactionEquipment.AddFactionProperties(this, list); @@ -1078,7 +1090,7 @@ namespace Server.Items if (m_GorgonLenseCharges > 0) list.Add(1112590, m_GorgonLenseCharges.ToString()); //Gorgon Lens Charges: ~1_val~ - + #region Mondain's Legacy Sets if (IsSetItem) { @@ -1122,8 +1134,8 @@ namespace Server.Items if ((prop = ArtifactRarity) > 0) list.Add(1061078, prop.ToString()); // artifact rarity ~1_val~ - - #region SA + + #region SA if ((prop = m_SAAbsorptionAttributes.EaterFire) != 0) list.Add(1113593, prop.ToString()); // Fire Eater ~1_Val~% @@ -1156,8 +1168,8 @@ namespace Server.Items if ((prop = m_SAAbsorptionAttributes.ResonanceKinetic) != 0) list.Add(1113695, prop.ToString()); // Kinetic Resonance ~1_val~% - - if ((prop = m_SAAbsorptionAttributes.CastingFocus) != 0) + + if ((prop = m_SAAbsorptionAttributes.CastingFocus) != 0) list.Add(1113696, prop.ToString()); // Casting Focus ~1_val~% #endregion @@ -1208,91 +1220,91 @@ namespace Server.Items if ((prop = m_AosAttributes.SpellChanneling) != 0) list.Add(1060482); // spell channeling - - if ((prop = m_AosClothingAttributes.SelfRepair) != 0) + + if ((prop = m_AosClothingAttributes.SelfRepair) != 0) list.Add(1060450, prop.ToString()); // self repair ~1_val~ - - if ((prop = m_AosAttributes.NightSight) != 0) + + if ((prop = m_AosAttributes.NightSight) != 0) list.Add(1060441); // night sight if ((prop = m_AosAttributes.BonusStr) != 0) list.Add(1060485, prop.ToString()); // strength bonus ~1_val~ - - if ((prop = m_AosAttributes.BonusDex) != 0) + + if ((prop = m_AosAttributes.BonusDex) != 0) list.Add(1060409, prop.ToString()); // dexterity bonus ~1_val~ - - if ((prop = m_AosAttributes.BonusInt) != 0) + + if ((prop = m_AosAttributes.BonusInt) != 0) list.Add(1060432, prop.ToString()); // intelligence bonus ~1_val~ - - if ((prop = m_AosAttributes.BonusHits) != 0) + + if ((prop = m_AosAttributes.BonusHits) != 0) list.Add(1060431, prop.ToString()); // hit point increase ~1_val~ - - if ((prop = m_AosAttributes.BonusStam) != 0) + + if ((prop = m_AosAttributes.BonusStam) != 0) list.Add(1060484, prop.ToString()); // stamina increase ~1_val~ - - if ((prop = m_AosAttributes.BonusMana) != 0) + + if ((prop = m_AosAttributes.BonusMana) != 0) list.Add(1060439, prop.ToString()); // mana increase ~1_val~ if ((prop = m_AosAttributes.RegenHits) != 0) list.Add(1060444, prop.ToString()); // hit point regeneration ~1_val~ - - if ((prop = m_AosAttributes.RegenStam) != 0) + + if ((prop = m_AosAttributes.RegenStam) != 0) list.Add(1060443, prop.ToString()); // stamina regeneration ~1_val~ - - if ((prop = m_AosAttributes.RegenMana) != 0) + + if ((prop = m_AosAttributes.RegenMana) != 0) list.Add(1060440, prop.ToString()); // mana regeneration ~1_val~ - - if ((prop = m_AosAttributes.Luck) != 0) + + if ((prop = m_AosAttributes.Luck) != 0) list.Add(1060436, prop.ToString()); // luck ~1_val~ - - if ((prop = m_AosAttributes.EnhancePotions) != 0) + + if ((prop = m_AosAttributes.EnhancePotions) != 0) list.Add(1060411, prop.ToString()); // enhance potions ~1_val~% - - if ((prop = m_AosAttributes.ReflectPhysical) != 0) + + if ((prop = m_AosAttributes.ReflectPhysical) != 0) list.Add(1060442, prop.ToString()); // reflect physical damage ~1_val~% - - if ((prop = m_AosAttributes.AttackChance) != 0) + + if ((prop = m_AosAttributes.AttackChance) != 0) list.Add(1060415, prop.ToString()); // hit chance increase ~1_val~% if ((prop = m_AosAttributes.WeaponSpeed) != 0) list.Add(1060486, prop.ToString()); // swing speed increase ~1_val~% - - if ((prop = m_AosAttributes.WeaponDamage) != 0) + + if ((prop = m_AosAttributes.WeaponDamage) != 0) list.Add(1060401, prop.ToString()); // damage increase ~1_val~% - - if ((prop = m_AosAttributes.DefendChance) != 0) + + if ((prop = m_AosAttributes.DefendChance) != 0) list.Add(1060408, prop.ToString()); // defense chance increase ~1_val~% - - if ((prop = m_AosAttributes.CastRecovery) != 0) + + if ((prop = m_AosAttributes.CastRecovery) != 0) list.Add(1060412, prop.ToString()); // faster cast recovery ~1_val~ - - if ((prop = m_AosAttributes.CastSpeed) != 0) + + if ((prop = m_AosAttributes.CastSpeed) != 0) list.Add(1060413, prop.ToString()); // faster casting ~1_val~ - - if ((prop = m_AosAttributes.SpellDamage) != 0) + + if ((prop = m_AosAttributes.SpellDamage) != 0) list.Add(1060483, prop.ToString()); // spell damage increase ~1_val~% - - if ((prop = m_AosAttributes.LowerManaCost) != 0) + + if ((prop = m_AosAttributes.LowerManaCost) != 0) list.Add(1060433, prop.ToString()); // lower mana cost ~1_val~% if ((prop = m_AosAttributes.LowerRegCost) != 0) list.Add(1060434, prop.ToString()); // lower reagent cost ~1_val~% - + if ((prop = m_AosAttributes.LowerAmmoCost) != 0) - list.Add(1075208, prop.ToString()); // Lower Ammo Cost ~1_Percentage~% + list.Add(1075208, prop.ToString()); // Lower Ammo Cost ~1_Percentage~% if (Core.ML && (prop = m_AosAttributes.IncreasedKarmaLoss) != 0) list.Add(1075210, prop.ToString()); // Increased Karma Loss ~1val~% base.AddResistanceProperties(list); - - if ((prop = m_AosClothingAttributes.MageArmor) != 0) + + if ((prop = m_AosClothingAttributes.MageArmor) != 0) list.Add(1060437); // mage armor - - if ((prop = m_AosClothingAttributes.LowerStatReq) != 0) + + if ((prop = m_AosClothingAttributes.LowerStatReq) != 0) list.Add(1060435, prop.ToString()); // lower requirements ~1_val~% - - if ((prop = ComputeStatReq(StatType.Str)) > 0) + + if ((prop = ComputeStatReq(StatType.Str)) > 0) list.Add(1061170, prop.ToString()); // strength requirement ~1_val~ if ((prop = m_AosClothingAttributes.DurabilityBonus) > 0) @@ -1402,7 +1414,7 @@ namespace Server.Items Crafter = 0x00000100, Quality = 0x00000200, StrReq = 0x00000400, - NegativeAttributes = 0x00000800, + NegativeAttributes = 0x00000800, #region Imbuing //TimesImbued = 0x12000000, #endregion @@ -1614,7 +1626,7 @@ namespace Server.Items int version = reader.ReadInt(); - switch ( version ) + switch (version) { case 12: case 11: @@ -1633,10 +1645,10 @@ namespace Server.Items goto case 8; } case 8: - { - m_IsImbued = reader.ReadBool(); - goto case 7; - } + { + m_IsImbued = reader.ReadBool(); + goto case 7; + } case 7: { m_SAAbsorptionAttributes = new SAAbsorptionAttributes(this, reader); @@ -1668,11 +1680,11 @@ namespace Server.Items } case 6: { - if(version == 6) + if (version == 6) m_SAAbsorptionAttributes = new SAAbsorptionAttributes(this); m_TimesImbued = reader.ReadInt(); - + #endregion m_BlessedBy = reader.ReadMobile(); @@ -1933,7 +1945,7 @@ namespace Server.Items { for (int i = 0; i < amount; ++i) { - switch ( Utility.Random(5) ) + switch (Utility.Random(5)) { case 0: ++m_AosResistances.Physical; break; case 1: ++m_AosResistances.Fire; break; diff --git a/Scripts/Items/Equipment/Weapons/BaseWeapon.cs b/Scripts/Items/Equipment/Weapons/BaseWeapon.cs index c0e9a42..5c09804 100755 --- a/Scripts/Items/Equipment/Weapons/BaseWeapon.cs +++ b/Scripts/Items/Equipment/Weapons/BaseWeapon.cs @@ -30,8 +30,8 @@ namespace Server.Items SlayerName Slayer2 { get; set; } } - public abstract class BaseWeapon : Item, IWeapon, IFactionItem, IUsesRemaining, ICraftable, ISlayer, IDurability, ISetItem, IVvVItem, IOwnerRestricted, IResource, IArtifact, ICombatEquipment, IEngravable, IQuality - { + public abstract class BaseWeapon : Item, IWeapon, IFactionItem, IUsesRemaining, ICraftable, ISlayer, IDurability, ISetItem, IVvVItem, IOwnerRestricted, IResource, IArtifact, ICombatEquipment, IEngravable, IQuality + { #region Damage Helpers public static BaseWeapon GetDamageOutput(Mobile wielder, out int min, out int max) { @@ -144,58 +144,58 @@ namespace Server.Items } #endregion - #region IUsesRemaining members - private int m_UsesRemaining; - private bool m_ShowUsesRemaining; - - [CommandProperty(AccessLevel.GameMaster)] - public int UsesRemaining { get { return m_UsesRemaining; } set { m_UsesRemaining = value; InvalidateProperties(); } } + #region IUsesRemaining members + private int m_UsesRemaining; + private bool m_ShowUsesRemaining; - public bool ShowUsesRemaining { get { return m_ShowUsesRemaining; } set { m_ShowUsesRemaining = value; InvalidateProperties(); } } - - public void ScaleUses() - { - m_UsesRemaining = (m_UsesRemaining * GetUsesScalar()) / 100; - InvalidateProperties(); - } + [CommandProperty(AccessLevel.GameMaster)] + public int UsesRemaining { get { return m_UsesRemaining; } set { m_UsesRemaining = value; InvalidateProperties(); } } - public void UnscaleUses() - { - m_UsesRemaining = (m_UsesRemaining * 100) / GetUsesScalar(); - } + public bool ShowUsesRemaining { get { return m_ShowUsesRemaining; } set { m_ShowUsesRemaining = value; InvalidateProperties(); } } - public int GetUsesScalar() - { - if (m_Quality == ItemQuality.Exceptional) - return 200; + public void ScaleUses() + { + m_UsesRemaining = (m_UsesRemaining * GetUsesScalar()) / 100; + InvalidateProperties(); + } - return 100; - } - #endregion - - private bool _VvVItem; - private Mobile _Owner; - private string _OwnerName; + public void UnscaleUses() + { + m_UsesRemaining = (m_UsesRemaining * 100) / GetUsesScalar(); + } - [CommandProperty(AccessLevel.GameMaster)] - public bool IsVvVItem - { - get { return _VvVItem; } - set { _VvVItem = value; InvalidateProperties(); } - } + public int GetUsesScalar() + { + if (m_Quality == ItemQuality.Exceptional) + return 200; - [CommandProperty(AccessLevel.GameMaster)] - public Mobile Owner - { - get { return _Owner; } - set { _Owner = value; if (_Owner != null) _OwnerName = _Owner.Name; InvalidateProperties(); } - } + return 100; + } + #endregion - public virtual string OwnerName - { - get { return _OwnerName; } - set { _OwnerName = value; InvalidateProperties(); } - } + private bool _VvVItem; + private Mobile _Owner; + private string _OwnerName; + + [CommandProperty(AccessLevel.GameMaster)] + public bool IsVvVItem + { + get { return _VvVItem; } + set { _VvVItem = value; InvalidateProperties(); } + } + + [CommandProperty(AccessLevel.GameMaster)] + public Mobile Owner + { + get { return _Owner; } + set { _Owner = value; if (_Owner != null) _OwnerName = _Owner.Name; InvalidateProperties(); } + } + + public virtual string OwnerName + { + get { return _OwnerName; } + set { _OwnerName = value; InvalidateProperties(); } + } /* Weapon internals work differently now (Mar 13 2003) * @@ -236,15 +236,15 @@ namespace Server.Items private CraftResource m_Resource; private bool m_PlayerConstructed; - private bool m_Altered; + private bool m_Altered; - private AosAttributes m_AosAttributes; + private AosAttributes m_AosAttributes; private AosWeaponAttributes m_AosWeaponAttributes; private AosSkillBonuses m_AosSkillBonuses; private AosElementAttributes m_AosElementDamages; private SAAbsorptionAttributes m_SAAbsorptionAttributes; - private NegativeAttributes m_NegativeAttributes; - private ExtendedWeaponAttributes m_ExtendedWeaponAttributes; + private NegativeAttributes m_NegativeAttributes; + private ExtendedWeaponAttributes m_ExtendedWeaponAttributes; // Overridable values. These values are provided to override the defaults which get defined in the individual weapon scripts. private int m_StrReq, m_DexReq, m_IntReq; @@ -256,21 +256,21 @@ namespace Server.Items private WeaponType m_Type; private WeaponAnimation m_Animation; - #region Stygian Abyss - private int m_TimesImbued; - private bool m_IsImbued; - private bool m_DImodded; - #endregion + #region Stygian Abyss + private int m_TimesImbued; + private bool m_IsImbued; + private bool m_DImodded; + #endregion - #region Runic Reforging - private ItemPower m_ItemPower; - private ReforgedPrefix m_ReforgedPrefix; - private ReforgedSuffix m_ReforgedSuffix; - #endregion - #endregion + #region Runic Reforging + private ItemPower m_ItemPower; + private ReforgedPrefix m_ReforgedPrefix; + private ReforgedSuffix m_ReforgedSuffix; + #endregion + #endregion - #region Virtual Properties - public virtual WeaponAbility PrimaryAbility { get { return null; } } + #region Virtual Properties + public virtual WeaponAbility PrimaryAbility { get { return null; } } public virtual WeaponAbility SecondaryAbility { get { return null; } } public virtual int DefMaxRange { get { return 1; } } @@ -310,8 +310,8 @@ namespace Server.Items public virtual int InitMinHits { get { return 0; } } public virtual int InitMaxHits { get { return 0; } } - public virtual bool CanFortify { get { return !IsImbued && NegativeAttributes.Antique < 4; } } - public virtual bool CanRepair { get { return m_NegativeAttributes.NoRepair == 0; } } + public virtual bool CanFortify { get { return !IsImbued && NegativeAttributes.Antique < 4; } } + public virtual bool CanRepair { get { return m_NegativeAttributes.NoRepair == 0; } } public virtual bool CanAlter { get { return true; } } public override int PhysicalResistance { get { return m_AosWeaponAttributes.ResistPhysicalBonus; } } @@ -322,16 +322,16 @@ namespace Server.Items public virtual SkillName AccuracySkill { get { return SkillName.Tactics; } } - public override double DefaultWeight - { - get - { - if (NegativeAttributes == null || NegativeAttributes.Unwieldly == 0) - return base.DefaultWeight; + public override double DefaultWeight + { + get + { + if (NegativeAttributes == null || NegativeAttributes.Unwieldly == 0) + return base.DefaultWeight; - return 50; - } - } + return 50; + } + } #region Personal Bless Deed private Mobile m_BlessedBy; @@ -393,14 +393,14 @@ namespace Server.Items [CommandProperty(AccessLevel.GameMaster)] public SAAbsorptionAttributes AbsorptionAttributes { get { return m_SAAbsorptionAttributes; } set { } } - [CommandProperty(AccessLevel.GameMaster)] - public NegativeAttributes NegativeAttributes { get { return m_NegativeAttributes; } set { } } + [CommandProperty(AccessLevel.GameMaster)] + public NegativeAttributes NegativeAttributes { get { return m_NegativeAttributes; } set { } } - [CommandProperty(AccessLevel.GameMaster)] - public ExtendedWeaponAttributes ExtendedWeaponAttributes { get { return m_ExtendedWeaponAttributes; } set { } } + [CommandProperty(AccessLevel.GameMaster)] + public ExtendedWeaponAttributes ExtendedWeaponAttributes { get { return m_ExtendedWeaponAttributes; } set { } } - [CommandProperty(AccessLevel.GameMaster)] - public ConsecratedWeaponContext ConsecratedContext { get; set; } + [CommandProperty(AccessLevel.GameMaster)] + public ConsecratedWeaponContext ConsecratedContext { get; set; } [CommandProperty(AccessLevel.GameMaster)] public bool Identified @@ -476,10 +476,10 @@ namespace Server.Items set { UnscaleDurability(); - UnscaleUses(); + UnscaleUses(); m_Quality = value; ScaleDurability(); - ScaleUses(); + ScaleUses(); InvalidateProperties(); } } @@ -656,15 +656,15 @@ namespace Server.Items [CommandProperty(AccessLevel.GameMaster)] public int StrRequirement { - get - { - if (m_NegativeAttributes.Massive > 0) - { - return 125; - } + get + { + if (m_NegativeAttributes.Massive > 0) + { + return 125; + } - return m_StrReq == -1 ? Core.AOS ? AosStrengthReq : OldStrengthReq : m_StrReq; - } + return m_StrReq == -1 ? Core.AOS ? AosStrengthReq : OldStrengthReq : m_StrReq; + } set { m_StrReq = value; @@ -715,108 +715,108 @@ namespace Server.Items } } - public Mobile FocusWeilder { get; set; } - public Mobile EnchantedWeilder { get; set; } + public Mobile FocusWeilder { get; set; } + public Mobile EnchantedWeilder { get; set; } - public int LastParryChance { get; set; } + public int LastParryChance { get; set; } - #region Stygian Abyss - [CommandProperty(AccessLevel.GameMaster)] - public int TimesImbued - { - get { return m_TimesImbued; } - set { m_TimesImbued = value; } - } + #region Stygian Abyss + [CommandProperty(AccessLevel.GameMaster)] + public int TimesImbued + { + get { return m_TimesImbued; } + set { m_TimesImbued = value; } + } - [CommandProperty(AccessLevel.GameMaster)] - public bool IsImbued - { - get - { - if (TimesImbued >= 1 && !m_IsImbued) - m_IsImbued = true; + [CommandProperty(AccessLevel.GameMaster)] + public bool IsImbued + { + get + { + if (TimesImbued >= 1 && !m_IsImbued) + m_IsImbued = true; - return m_IsImbued; - } - set - { - if (TimesImbued >= 1) - m_IsImbued = true; - else - m_IsImbued = value; InvalidateProperties(); - } - } + return m_IsImbued; + } + set + { + if (TimesImbued >= 1) + m_IsImbued = true; + else + m_IsImbued = value; InvalidateProperties(); + } + } - [CommandProperty(AccessLevel.GameMaster)] - public bool DImodded - { - get { return m_DImodded; } - set { m_DImodded = value; } - } + [CommandProperty(AccessLevel.GameMaster)] + public bool DImodded + { + get { return m_DImodded; } + set { m_DImodded = value; } + } - public int[] BaseResists - { - get - { - return new int[] { 0, 0, 0, 0, 0 }; - } - } + public int[] BaseResists + { + get + { + return new int[] { 0, 0, 0, 0, 0 }; + } + } - public virtual void OnAfterImbued(Mobile m, int mod, int value) - { - } - #endregion + public virtual void OnAfterImbued(Mobile m, int mod, int value) + { + } + #endregion - [CommandProperty(AccessLevel.GameMaster)] - public bool SearingWeapon - { - get { return HasSocket(); } - set - { - if (!value) - { - RemoveSocket(); - } - else if (!SearingWeapon) - { - AttachSocket(new SearingWeapon(this)); - } - } - } + [CommandProperty(AccessLevel.GameMaster)] + public bool SearingWeapon + { + get { return HasSocket(); } + set + { + if (!value) + { + RemoveSocket(); + } + else if (!SearingWeapon) + { + AttachSocket(new SearingWeapon(this)); + } + } + } - #region Runic Reforging + #region Runic Reforging - [CommandProperty(AccessLevel.GameMaster)] - public ItemPower ItemPower - { - get { return m_ItemPower; } - set { m_ItemPower = value; InvalidateProperties(); } - } + [CommandProperty(AccessLevel.GameMaster)] + public ItemPower ItemPower + { + get { return m_ItemPower; } + set { m_ItemPower = value; InvalidateProperties(); } + } - [CommandProperty(AccessLevel.GameMaster)] - public ReforgedPrefix ReforgedPrefix - { - get { return m_ReforgedPrefix; } - set { m_ReforgedPrefix = value; InvalidateProperties(); } - } + [CommandProperty(AccessLevel.GameMaster)] + public ReforgedPrefix ReforgedPrefix + { + get { return m_ReforgedPrefix; } + set { m_ReforgedPrefix = value; InvalidateProperties(); } + } - [CommandProperty(AccessLevel.GameMaster)] - public ReforgedSuffix ReforgedSuffix - { - get { return m_ReforgedSuffix; } - set { m_ReforgedSuffix = value; InvalidateProperties(); } - } - #endregion - #endregion + [CommandProperty(AccessLevel.GameMaster)] + public ReforgedSuffix ReforgedSuffix + { + get { return m_ReforgedSuffix; } + set { m_ReforgedSuffix = value; InvalidateProperties(); } + } + #endregion + #endregion - public override void GetContextMenuEntries(Mobile from, List list) + public override void GetContextMenuEntries(Mobile from, List list) { base.GetContextMenuEntries(from, list); - if (SearingWeapon && Parent == from) - { - list.Add(new SearingWeapon.ToggleExtinguishEntry(from, this)); - } + if (SearingWeapon && Parent == from) + { + list.Add(new SearingWeapon.ToggleExtinguishEntry(from, this)); + } if (BlessedFor == from && BlessedBy == from && RootParent == from) { @@ -826,7 +826,7 @@ namespace Server.Items public override void OnAfterDuped(Item newItem) { - base.OnAfterDuped(newItem); + base.OnAfterDuped(newItem); BaseWeapon weap = newItem as BaseWeapon; @@ -839,8 +839,8 @@ namespace Server.Items weap.m_AosElementDamages = new AosElementAttributes(newItem, m_AosElementDamages); weap.m_AosSkillBonuses = new AosSkillBonuses(newItem, m_AosSkillBonuses); weap.m_AosWeaponAttributes = new AosWeaponAttributes(newItem, m_AosWeaponAttributes); - weap.m_NegativeAttributes = new NegativeAttributes(newItem, m_NegativeAttributes); - weap.m_ExtendedWeaponAttributes = new ExtendedWeaponAttributes(newItem, m_ExtendedWeaponAttributes); + weap.m_NegativeAttributes = new NegativeAttributes(newItem, m_NegativeAttributes); + weap.m_ExtendedWeaponAttributes = new ExtendedWeaponAttributes(newItem, m_ExtendedWeaponAttributes); #region Mondain's Legacy weap.m_SetAttributes = new AosAttributes(newItem, m_SetAttributes); @@ -856,26 +856,26 @@ namespace Server.Items { int scale = 100 + GetDurabilityBonus(); - m_Hits = ((m_Hits * 100) + (scale - 1)) / scale; - m_MaxHits = ((m_MaxHits * 100) + (scale - 1)) / scale; + m_Hits = ((m_Hits * 100) + (scale - 1)) / scale; + m_MaxHits = ((m_MaxHits * 100) + (scale - 1)) / scale; - InvalidateProperties(); + InvalidateProperties(); } public virtual void ScaleDurability() { int scale = 100 + GetDurabilityBonus(); - m_Hits = ((m_Hits * scale) + 99) / 100; - m_MaxHits = ((m_MaxHits * scale) + 99) / 100; + m_Hits = ((m_Hits * scale) + 99) / 100; + m_MaxHits = ((m_MaxHits * scale) + 99) / 100; - if (m_MaxHits > 255) - m_MaxHits = 255; + if (m_MaxHits > 255) + m_MaxHits = 255; - if (m_Hits > 255) - m_Hits = 255; + if (m_Hits > 255) + m_Hits = 255; - InvalidateProperties(); + InvalidateProperties(); } public int GetDurabilityBonus() @@ -991,8 +991,8 @@ namespace Server.Items protected override void OnTick() { m_Mobile.EndAction(typeof(BaseWeapon)); - m_Mobile.SendLocalizedMessage(1060168); // Your confusion has passed, you may now arm a weapon! - } + m_Mobile.SendLocalizedMessage(1060168); // Your confusion has passed, you may now arm a weapon! + } } public override bool CheckConflictingLayer(Mobile m, Item item, Layer layer) @@ -1004,12 +1004,12 @@ namespace Server.Items if (Layer == Layer.TwoHanded && layer == Layer.OneHanded) { - m.LocalOverheadMessage(MessageType.Regular, 0x3B2, 500214); // You already have something in both hands. - return true; + m.LocalOverheadMessage(MessageType.Regular, 0x3B2, 500214); // You already have something in both hands. + return true; } else if (Layer == Layer.OneHanded && layer == Layer.TwoHanded && !(item is BaseShield) && !(item is BaseEquipableLight)) { - m.LocalOverheadMessage(MessageType.Regular, 0x3B2, 500215); // // You can only wield one weapon at a time. + m.LocalOverheadMessage(MessageType.Regular, 0x3B2, 500215); // // You can only wield one weapon at a time. return true; } @@ -1040,38 +1040,38 @@ namespace Server.Items return false; } - if (from.IsPlayer()) - { - if (_Owner != null && _Owner != from) - { - from.SendLocalizedMessage(501023); // You must be the owner to use this item. - return false; - } + if (from.IsPlayer()) + { + if (_Owner != null && _Owner != from) + { + from.SendLocalizedMessage(501023); // You must be the owner to use this item. + return false; + } - if (this is IAccountRestricted && ((IAccountRestricted)this).Account != null) - { - Accounting.Account acct = from.Account as Accounting.Account; + if (this is IAccountRestricted && ((IAccountRestricted)this).Account != null) + { + Accounting.Account acct = from.Account as Accounting.Account; - if (acct == null || acct.Username != ((IAccountRestricted)this).Account) - { - from.SendLocalizedMessage(1071296); // This item is Account Bound and your character is not bound to it. You cannot use this item. - return false; - } - } + if (acct == null || acct.Username != ((IAccountRestricted)this).Account) + { + from.SendLocalizedMessage(1071296); // This item is Account Bound and your character is not bound to it. You cannot use this item. + return false; + } + } - if (IsVvVItem && !Engines.VvV.ViceVsVirtueSystem.IsVvV(from)) - { - from.SendLocalizedMessage(1155496); // This item can only be used by VvV participants! - return false; - } - } + if (IsVvVItem && !Engines.VvV.ViceVsVirtueSystem.IsVvV(from)) + { + from.SendLocalizedMessage(1155496); // This item can only be used by VvV participants! + return false; + } + } - bool morph = from.FindItemOnLayer(Layer.Earrings) is MorphEarrings; + bool morph = from.FindItemOnLayer(Layer.Earrings) is MorphEarrings; if (from.Race == Race.Gargoyle && !CanBeWornByGargoyles && from.IsPlayer()) { - from.LocalOverheadMessage(MessageType.Regular, 0x3B2, 1111708); // Gargoyles can't wear this. - return false; + from.LocalOverheadMessage(MessageType.Regular, 0x3B2, 1111708); // Gargoyles can't wear this. + return false; } if (RequiredRace != null && from.Race != RequiredRace && !morph) @@ -1079,11 +1079,11 @@ namespace Server.Items if (RequiredRace == Race.Elf) { from.SendLocalizedMessage(1072203); // Only Elves may use this. - } + } else if (RequiredRace == Race.Gargoyle) { - from.LocalOverheadMessage(MessageType.Regular, 0x3B2, 1111707); // Only gargoyles can wear this. - } + from.LocalOverheadMessage(MessageType.Regular, 0x3B2, 1111707); // Only gargoyles can wear this. + } else { from.SendMessage("Only {0} may use ", RequiredRace.PluralName); @@ -1108,10 +1108,10 @@ namespace Server.Items } else if (!from.CanBeginAction(typeof(BaseWeapon))) { - from.SendLocalizedMessage(3000201); // You must wait to perform another action. - return false; + from.SendLocalizedMessage(3000201); // You must wait to perform another action. + return false; } - #region Personal Bless Deed + #region Personal Bless Deed else if (BlessedBy != null && BlessedBy != from) { from.SendLocalizedMessage(1075277); // That item is blessed by another player. @@ -1122,7 +1122,7 @@ namespace Server.Items { return false; } - #endregion + #endregion else { @@ -1180,19 +1180,19 @@ namespace Server.Items m_MageMod.Remove(); } - m_MageMod = new DefaultSkillMod(SkillName.Magery, true, -30 + m_AosWeaponAttributes.MageWeapon); + m_MageMod = new DefaultSkillMod(SkillName.Magery, true, -30 + m_AosWeaponAttributes.MageWeapon); from.AddSkillMod(m_MageMod); } - if (Core.TOL) - { - if ((m_ExtendedWeaponAttributes.MysticWeapon != 0 && m_ExtendedWeaponAttributes.MysticWeapon != 30) || Enhancement.GetValue(from, ExtendedWeaponAttribute.MysticWeapon) > 0) - AddMysticMod(from); - } + if (Core.TOL) + { + if ((m_ExtendedWeaponAttributes.MysticWeapon != 0 && m_ExtendedWeaponAttributes.MysticWeapon != 30) || Enhancement.GetValue(from, ExtendedWeaponAttribute.MysticWeapon) > 0) + AddMysticMod(from); + } XmlAttach.CheckOnEquip(this, from); - InDoubleStrike = false; + InDoubleStrike = false; return true; } @@ -1223,17 +1223,17 @@ namespace Server.Items } #endregion - if (HasSocket()) - { - Caddellite.UpdateBuff(from); - } + if (HasSocket()) + { + Caddellite.UpdateBuff(from); + } - if (ExtendedWeaponAttributes.Focus > 0) - { - Focus.UpdateBuff(from); - } + if (ExtendedWeaponAttributes.Focus > 0) + { + Focus.UpdateBuff(from); + } - from.CheckStatTimers(); + from.CheckStatTimers(); from.Delta(MobileDelta.WeaponDamage); } } @@ -1274,12 +1274,12 @@ namespace Server.Items } ImmolatingWeaponSpell.StopImmolating(this, (Mobile)parent); - Spells.Mysticism.EnchantSpell.OnWeaponRemoved(this, m); + Spells.Mysticism.EnchantSpell.OnWeaponRemoved(this, m); - if (FocusWeilder != null) - FocusWeilder = null; + if (FocusWeilder != null) + FocusWeilder = null; - SkillMasterySpell.OnWeaponRemoved(m, this); + SkillMasterySpell.OnWeaponRemoved(m, this); #region Mondain's Legacy Sets if (IsSetItem && m_SetEquipped) @@ -1288,53 +1288,53 @@ namespace Server.Items } #endregion - if (HasSocket()) - { - Caddellite.UpdateBuff(m); - } + if (HasSocket()) + { + Caddellite.UpdateBuff(m); + } - if (SearingWeapon) - { - Server.Items.SearingWeapon.OnWeaponRemoved(this); - } + if (SearingWeapon) + { + Server.Items.SearingWeapon.OnWeaponRemoved(this); + } - if (ExtendedWeaponAttributes.Focus > 0) - { - Focus.UpdateBuff(m); - } + if (ExtendedWeaponAttributes.Focus > 0) + { + Focus.UpdateBuff(m); + } - m.CheckStatTimers(); + m.CheckStatTimers(); - m.Delta(MobileDelta.WeaponDamage); + m.Delta(MobileDelta.WeaponDamage); - XmlAttach.CheckOnRemoved(this, parent); + XmlAttach.CheckOnRemoved(this, parent); } - LastParryChance = 0; - } + LastParryChance = 0; + } - public void AddMysticMod(Mobile from) - { - if (m_MysticMod != null) - m_MysticMod.Remove(); + public void AddMysticMod(Mobile from) + { + if (m_MysticMod != null) + m_MysticMod.Remove(); - int value = m_ExtendedWeaponAttributes.MysticWeapon; + int value = m_ExtendedWeaponAttributes.MysticWeapon; - if (Enhancement.GetValue(from, ExtendedWeaponAttribute.MysticWeapon) > value) - value = Enhancement.GetValue(from, ExtendedWeaponAttribute.MysticWeapon); + if (Enhancement.GetValue(from, ExtendedWeaponAttribute.MysticWeapon) > value) + value = Enhancement.GetValue(from, ExtendedWeaponAttribute.MysticWeapon); - m_MysticMod = new DefaultSkillMod(SkillName.Mysticism, true, -30 + value); - from.AddSkillMod(m_MysticMod); - } + m_MysticMod = new DefaultSkillMod(SkillName.Mysticism, true, -30 + value); + from.AddSkillMod(m_MysticMod); + } - public void RemoveMysticMod() - { - if (m_MysticMod != null) - { - m_MysticMod.Remove(); - m_MysticMod = null; - } - } + public void RemoveMysticMod() + { + if (m_MysticMod != null) + { + m_MysticMod.Remove(); + m_MysticMod = null; + } + } public virtual SkillName GetUsedSkill(Mobile m, bool checkSkillAttrs) { @@ -1372,27 +1372,27 @@ namespace Server.Items sk = Skill; } } - else if (m_ExtendedWeaponAttributes.MysticWeapon != 0 || Enhancement.GetValue(m, ExtendedWeaponAttribute.MysticWeapon) > 0) - { - if (m.Skills[SkillName.Mysticism].Value > m.Skills[Skill].Value) - { - sk = SkillName.Mysticism; - } - else - { - sk = Skill; - } - } - else - { - sk = Skill; + else if (m_ExtendedWeaponAttributes.MysticWeapon != 0 || Enhancement.GetValue(m, ExtendedWeaponAttribute.MysticWeapon) > 0) + { + if (m.Skills[SkillName.Mysticism].Value > m.Skills[Skill].Value) + { + sk = SkillName.Mysticism; + } + else + { + sk = Skill; + } + } + else + { + sk = Skill; - if (sk != SkillName.Wrestling && !m.Player && !m.Body.IsHuman && - m.Skills[SkillName.Wrestling].Value > m.Skills[sk].Value) - { - sk = SkillName.Wrestling; - } - } + if (sk != SkillName.Wrestling && !m.Player && !m.Body.IsHuman && + m.Skills[SkillName.Wrestling].Value > m.Skills[sk].Value) + { + sk = SkillName.Wrestling; + } + } return sk; } @@ -1414,15 +1414,15 @@ namespace Server.Items public virtual bool CheckHit(Mobile attacker, IDamageable damageable) { - Mobile defender = damageable as Mobile; + Mobile defender = damageable as Mobile; - if (defender == null) - { - if (damageable is IDamageableItem) - return ((IDamageableItem)damageable).CheckHit(attacker); + if (defender == null) + { + if (damageable is IDamageableItem) + return ((IDamageableItem)damageable).CheckHit(attacker); - return true; - } + return true; + } BaseWeapon atkWeapon = attacker.Weapon as BaseWeapon; BaseWeapon defWeapon = defender.Weapon as BaseWeapon; @@ -1439,35 +1439,35 @@ namespace Server.Items if (Core.AOS) { - if (atkValue <= -20.0) - atkValue = -19.9; + if (atkValue <= -20.0) + atkValue = -19.9; - if (defValue <= -20.0) - defValue = -19.9; + if (defValue <= -20.0) + defValue = -19.9; - bonus += AosAttributes.GetValue(attacker, AosAttribute.AttackChance); + bonus += AosAttributes.GetValue(attacker, AosAttribute.AttackChance); - //SA Gargoyle cap is 50, else 45 - bonus = Math.Min(attacker.Race == Race.Gargoyle ? 50 : 45, bonus); + //SA Gargoyle cap is 50, else 45 + bonus = Math.Min(attacker.Race == Race.Gargoyle ? 50 : 45, bonus); - ourValue = (atkValue + 20.0) * (100 + bonus); + ourValue = (atkValue + 20.0) * (100 + bonus); - bonus = AosAttributes.GetValue(defender, AosAttribute.DefendChance); + bonus = AosAttributes.GetValue(defender, AosAttribute.DefendChance); - ForceArrow.ForceArrowInfo info = ForceArrow.GetInfo(attacker, defender); + ForceArrow.ForceArrowInfo info = ForceArrow.GetInfo(attacker, defender); - if (info != null && info.Defender == defender) - bonus -= info.DefenseChanceMalus; + if (info != null && info.Defender == defender) + bonus -= info.DefenseChanceMalus; - int max = 45 + BaseArmor.GetRefinedDefenseChance(defender); + int max = 45 + BaseArmor.GetRefinedDefenseChance(defender); - // Defense Chance Increase = 45% - if (bonus > max) - bonus = max; + // Defense Chance Increase = 45% + if (bonus > max) + bonus = max; - theirValue = (defValue + 20.0) * (100 + bonus); + theirValue = (defValue + 20.0) * (100 + bonus); - bonus = 0; + bonus = 0; } else { @@ -1489,51 +1489,51 @@ namespace Server.Items chance *= 1.0 + ((double)bonus / 100); - if (Core.SA) - { - if (atkWeapon is BaseThrown) - { - //Distance malas - if (attacker.InRange(defender, 1)) //Close Quarters - { - chance -= (.12 - (double)Math.Min(12, (attacker.Skills[SkillName.Throwing].Value + (double)attacker.RawDex) / 20) / 10); - } - else if (attacker.GetDistanceToSqrt(defender) < ((BaseThrown)atkWeapon).MinThrowRange) //too close - { - chance -= .12; - } + if (Core.SA) + { + if (atkWeapon is BaseThrown) + { + //Distance malas + if (attacker.InRange(defender, 1)) //Close Quarters + { + chance -= (.12 - (double)Math.Min(12, (attacker.Skills[SkillName.Throwing].Value + (double)attacker.RawDex) / 20) / 10); + } + else if (attacker.GetDistanceToSqrt(defender) < ((BaseThrown)atkWeapon).MinThrowRange) //too close + { + chance -= .12; + } - //shield penalty - BaseShield shield = attacker.FindItemOnLayer(Layer.TwoHanded) as BaseShield; + //shield penalty + BaseShield shield = attacker.FindItemOnLayer(Layer.TwoHanded) as BaseShield; - if (shield != null) - { - double malus = Math.Min(90, 1200 / Math.Max(1.0, attacker.Skills[SkillName.Parry].Value)); + if (shield != null) + { + double malus = Math.Min(90, 1200 / Math.Max(1.0, attacker.Skills[SkillName.Parry].Value)); - chance = chance - (chance * (malus / 100)); - } - } + chance = chance - (chance * (malus / 100)); + } + } - if (defWeapon is BaseThrown) - { - BaseShield shield = defender.FindItemOnLayer(Layer.TwoHanded) as BaseShield; + if (defWeapon is BaseThrown) + { + BaseShield shield = defender.FindItemOnLayer(Layer.TwoHanded) as BaseShield; - if (shield != null) - { - double malus = Math.Min(90, 1200 / Math.Max(1.0, defender.Skills[SkillName.Parry].Value)); + if (shield != null) + { + double malus = Math.Min(90, 1200 / Math.Max(1.0, defender.Skills[SkillName.Parry].Value)); - chance = chance + (chance * (malus / 100)); - } - } - } + chance = chance + (chance * (malus / 100)); + } + } + } - if (Core.AOS && chance < 0.02) - { - chance = 0.02; - } + if (Core.AOS && chance < 0.02) + { + chance = 0.02; + } - if (Core.AOS && m_AosWeaponAttributes.MageWeapon > 0 && attacker.Skills[SkillName.Magery].Value > atkSkill.Value) - return attacker.CheckSkill(SkillName.Magery, chance); + if (Core.AOS && m_AosWeaponAttributes.MageWeapon > 0 && attacker.Skills[SkillName.Magery].Value > atkSkill.Value) + return attacker.CheckSkill(SkillName.Magery, chance); return attacker.CheckSkill(atkSkill.SkillName, chance); } @@ -1632,29 +1632,29 @@ namespace Server.Items public virtual void OnBeforeSwing(Mobile attacker, IDamageable damageable) { - Mobile defender = damageable as Mobile; + Mobile defender = damageable as Mobile; WeaponAbility a = WeaponAbility.GetCurrentAbility(attacker); - if (a != null && (!a.OnBeforeSwing(attacker, defender))) - { - WeaponAbility.ClearCurrentAbility(attacker); - } + if (a != null && (!a.OnBeforeSwing(attacker, defender))) + { + WeaponAbility.ClearCurrentAbility(attacker); + } SpecialMove move = SpecialMove.GetCurrentMove(attacker); - if (move != null && !move.OnBeforeSwing(attacker, defender)) - { - SpecialMove.ClearCurrentMove(attacker); - } + if (move != null && !move.OnBeforeSwing(attacker, defender)) + { + SpecialMove.ClearCurrentMove(attacker); + } } - public virtual TimeSpan OnSwing(Mobile attacker, IDamageable damageable) + public virtual TimeSpan OnSwing(Mobile attacker, IDamageable damageable) { - return OnSwing(attacker, damageable, 1.0); + return OnSwing(attacker, damageable, 1.0); } - public virtual TimeSpan OnSwing(Mobile attacker, IDamageable damageable, double damageBonus) + public virtual TimeSpan OnSwing(Mobile attacker, IDamageable damageable, double damageBonus) { bool canSwing = true; @@ -1677,13 +1677,13 @@ namespace Server.Items } } - if (canSwing && attacker.HarmfulCheck(damageable)) + if (canSwing && attacker.HarmfulCheck(damageable)) { attacker.DisruptiveAction(); if (attacker.NetState != null) { - attacker.Send(new Swing(0, attacker, damageable)); + attacker.Send(new Swing(0, attacker, damageable)); } if (attacker is BaseCreature) @@ -1704,13 +1704,13 @@ namespace Server.Items } } - if (CheckHit(attacker, damageable)) + if (CheckHit(attacker, damageable)) { - OnHit(attacker, damageable, damageBonus); + OnHit(attacker, damageable, damageBonus); } else { - OnMiss(attacker, damageable); + OnMiss(attacker, damageable); } } @@ -1769,15 +1769,15 @@ namespace Server.Items if (shield != null || !defender.Player) { double chance = (parry - bushidoNonRacial) / 400.0; - // As per OSI, no negitive effect from the Racial stuffs, ie, 120 parry and '0' bushido with humans + // As per OSI, no negitive effect from the Racial stuffs, ie, 120 parry and '0' bushido with humans if (chance < 0) // chance shouldn't go below 0 { chance = defender.Player ? 0 : .1; } - // Skill Masteries - chance += HeightenedSensesSpell.GetParryBonus(defender); + // Skill Masteries + chance += HeightenedSensesSpell.GetParryBonus(defender); // Parry/Bushido over 100 grants a 5% bonus. if (parry >= 100.0 || bushido >= 100.0) @@ -1797,24 +1797,24 @@ namespace Server.Items chance = chance * (20 + defender.Dex) / 100; } - bool success = defender.CheckSkill(SkillName.Parry, chance); + bool success = defender.CheckSkill(SkillName.Parry, chance); - if (shield != null && Core.EJ && success) - { - shield.LastParryChance = (int)(chance * 100); - shield.InvalidateProperties(); - } + if (shield != null && Core.EJ && success) + { + shield.LastParryChance = (int)(chance * 100); + shield.InvalidateProperties(); + } - return success; - } + return success; + } else if (!(defender.Weapon is Fists) && !(defender.Weapon is BaseRanged)) { BaseWeapon weapon = defender.Weapon as BaseWeapon; - if (Core.HS && weapon.Attributes.BalancedWeapon > 0) - { - return false; - } + if (Core.HS && weapon.Attributes.BalancedWeapon > 0) + { + return false; + } double divisor = (weapon.Layer == Layer.OneHanded && defender.Player) ? 48000.0 : 41140.0; @@ -1845,25 +1845,25 @@ namespace Server.Items chance = chance * (20 + defender.Dex) / 100; } - bool success; + bool success; if (chance > aosChance) { - success = defender.CheckSkill(SkillName.Parry, chance); + success = defender.CheckSkill(SkillName.Parry, chance); } else { - success = (aosChance > Utility.RandomDouble()); - // Only skillcheck if wielding a shield & there's no effect from Bushido + success = (aosChance > Utility.RandomDouble()); + // Only skillcheck if wielding a shield & there's no effect from Bushido } - if (Core.EJ && success) - { - weapon.LastParryChance = (int)(chance * 100); - weapon.InvalidateProperties(); - } + if (Core.EJ && success) + { + weapon.LastParryChance = (int)(chance * 100); + weapon.InvalidateProperties(); + } - return success; + return success; } return false; @@ -1875,22 +1875,22 @@ namespace Server.Items bool blocked = false; - if (defender.Player || defender.Body.IsHuman || (defender is BaseCreature && - ((BaseCreature)defender).Controlled && - defender.Skills[SkillName.Wrestling].Base >= 100)) + if (defender.Player || defender.Body.IsHuman || (defender is BaseCreature && + ((BaseCreature)defender).Controlled && + defender.Skills[SkillName.Wrestling].Base >= 100)) { blocked = CheckParry(defender); - BaseWeapon weapon = defender.Weapon as BaseWeapon; + BaseWeapon weapon = defender.Weapon as BaseWeapon; if (blocked) { defender.FixedEffect(0x37B9, 10, 16); damage = 0; - if (Core.SA) - { - defender.Animate(AnimationType.Parry, 0); - } + if (Core.SA) + { + defender.Animate(AnimationType.Parry, 0); + } // Successful block removes the Honorable Execution penalty. HonorableExecution.RemovePenalty(defender); @@ -1899,13 +1899,13 @@ namespace Server.Items { if (weapon != null) { - var combatant = defender.Combatant; + var combatant = defender.Combatant; defender.FixedParticles(0x3779, 1, 15, 0x158B, 0x0, 0x3, EffectLayer.Waist); weapon.OnSwing(defender, attacker); - if (combatant != null && defender.Combatant != combatant && combatant.Alive) - defender.Combatant = combatant; + if (combatant != null && defender.Combatant != combatant && combatant.Alive) + defender.Combatant = combatant; } CounterAttack.StopCountering(defender); @@ -1914,12 +1914,12 @@ namespace Server.Items if (Confidence.IsConfident(defender)) { defender.SendLocalizedMessage(1063117); - // Your confidence reassures you as you successfully block your opponent's blow. + // Your confidence reassures you as you successfully block your opponent's blow. double bushido = defender.Skills.Bushido.Value; - defender.Hits += Utility.RandomMinMax(1, (int)(bushido / 12)) + MasteryInfo.AnticipateHitBonus(defender) / 10; - defender.Stam += Utility.RandomMinMax(1, (int)(bushido / 5)) + MasteryInfo.AnticipateHitBonus(defender) / 10; + defender.Hits += Utility.RandomMinMax(1, (int)(bushido / 12)) + MasteryInfo.AnticipateHitBonus(defender) / 10; + defender.Stam += Utility.RandomMinMax(1, (int)(bushido / 5)) + MasteryInfo.AnticipateHitBonus(defender) / 10; } BaseShield shield = defender.FindItemOnLayer(Layer.TwoHanded) as BaseShield; @@ -1928,88 +1928,88 @@ namespace Server.Items { shield.OnHit(this, damage); - #region Stygian Abyss - if (shield.ArmorAttributes.ReactiveParalyze > 0 && 30 > Utility.Random(100)) - { - int secs = (int)Math.Max(1, Math.Max(8, defender.Skills[SkillName.EvalInt].Value / 10) - attacker.Skills[SkillName.MagicResist].Value / 10); + #region Stygian Abyss + if (shield.ArmorAttributes.ReactiveParalyze > 0 && 30 > Utility.Random(100)) + { + int secs = (int)Math.Max(1, Math.Max(8, defender.Skills[SkillName.EvalInt].Value / 10) - attacker.Skills[SkillName.MagicResist].Value / 10); - attacker.Paralyze(TimeSpan.FromSeconds(secs)); - attacker.PlaySound(0x204); - attacker.FixedEffect(0x376A, 6, 1); - } - #endregion + attacker.Paralyze(TimeSpan.FromSeconds(secs)); + attacker.PlaySound(0x204); + attacker.FixedEffect(0x376A, 6, 1); + } + #endregion - XmlAttach.OnArmorHit(attacker, defender, shield, this, originalDamage); - } + XmlAttach.OnArmorHit(attacker, defender, shield, this, originalDamage); + } - #region Stygian Abyss - else if (weapon != null && weapon.Layer == Layer.TwoHanded && weapon.WeaponAttributes.ReactiveParalyze > 0 && 30 > Utility.Random(100)) - { - int secs = (int)Math.Max(1, Math.Max(8, defender.Skills[SkillName.EvalInt].Value / 10) - attacker.Skills[SkillName.MagicResist].Value / 10); + #region Stygian Abyss + else if (weapon != null && weapon.Layer == Layer.TwoHanded && weapon.WeaponAttributes.ReactiveParalyze > 0 && 30 > Utility.Random(100)) + { + int secs = (int)Math.Max(1, Math.Max(8, defender.Skills[SkillName.EvalInt].Value / 10) - attacker.Skills[SkillName.MagicResist].Value / 10); - attacker.Paralyze(TimeSpan.FromSeconds(secs)); - attacker.PlaySound(0x204); - attacker.FixedEffect(0x376A, 6, 1); - } - #endregion + attacker.Paralyze(TimeSpan.FromSeconds(secs)); + attacker.PlaySound(0x204); + attacker.FixedEffect(0x376A, 6, 1); + } + #endregion - //Skill Masteries - SkillMasterySpell.OnParried(attacker, defender); - } + //Skill Masteries + SkillMasterySpell.OnParried(attacker, defender); + } } if (!blocked) { - IWearableDurability toHit = GetRandomValidItem(defender) as IWearableDurability; + IWearableDurability toHit = GetRandomValidItem(defender) as IWearableDurability; if (toHit != null) { - toHit.OnHit(this, damage); // call OnHit to lose durability + toHit.OnHit(this, damage); // call OnHit to lose durability - if (toHit is Item && !((Item)toHit).Deleted && (attacker is VeriteElemental || attacker is ValoriteElemental)) - VeriteElemental.OnHit(defender, (Item)toHit, damage); + if (toHit is Item && !((Item)toHit).Deleted && (attacker is VeriteElemental || attacker is ValoriteElemental)) + VeriteElemental.OnHit(defender, (Item)toHit, damage); - damage -= XmlAttach.OnArmorHit(attacker, defender, (Item)toHit, this, originalDamage); + damage -= XmlAttach.OnArmorHit(attacker, defender, (Item)toHit, this, originalDamage); } } return damage; } - private Item GetRandomValidItem(Mobile m) - { - Item[] items = m.Items.Where(item => _DamageLayers.Contains(item.Layer) && item is IWearableDurability).ToArray(); + private Item GetRandomValidItem(Mobile m) + { + Item[] items = m.Items.Where(item => _DamageLayers.Contains(item.Layer) && item is IWearableDurability).ToArray(); - if (items.Length == 0) - return null; + if (items.Length == 0) + return null; - return items[Utility.Random(items.Length)]; - } + return items[Utility.Random(items.Length)]; + } - private List _DamageLayers = new List() - { - Layer.FirstValid, - Layer.OneHanded, - Layer.TwoHanded, - Layer.Shoes, - Layer.Pants, - Layer.Shirt, - Layer.Helm, - Layer.Arms, - Layer.Gloves, - Layer.Ring, - Layer.Talisman, - Layer.Neck, - Layer.Waist, - Layer.InnerTorso, - Layer.Bracelet, - Layer.MiddleTorso, - Layer.Earrings, - Layer.Cloak, - Layer.OuterTorso, - Layer.OuterLegs, - Layer.InnerLegs, - }; + private List _DamageLayers = new List() + { + Layer.FirstValid, + Layer.OneHanded, + Layer.TwoHanded, + Layer.Shoes, + Layer.Pants, + Layer.Shirt, + Layer.Helm, + Layer.Arms, + Layer.Gloves, + Layer.Ring, + Layer.Talisman, + Layer.Neck, + Layer.Waist, + Layer.InnerTorso, + Layer.Bracelet, + Layer.MiddleTorso, + Layer.Earrings, + Layer.Cloak, + Layer.OuterTorso, + Layer.OuterLegs, + Layer.InnerLegs, + }; public virtual int AbsorbDamage(Mobile attacker, Mobile defender, int damage) { @@ -2127,7 +2127,7 @@ namespace Server.Items int inPack = 1; - IPooledEnumerable eable = defender.GetMobilesInRange(1); + IPooledEnumerable eable = defender.GetMobilesInRange(1); foreach (Mobile m in eable) { @@ -2154,7 +2154,7 @@ namespace Server.Items } } - eable.Free(); + eable.Free(); if (inPack >= 5) { @@ -2177,210 +2177,210 @@ namespace Server.Items } private bool m_InDoubleStrike; - private bool m_ProcessingMultipleHits; + private bool m_ProcessingMultipleHits; - public bool InDoubleStrike - { - get { return m_InDoubleStrike; } - set - { - m_InDoubleStrike = value; + public bool InDoubleStrike + { + get { return m_InDoubleStrike; } + set + { + m_InDoubleStrike = value; - if (m_InDoubleStrike) - ProcessingMultipleHits = true; - else - ProcessingMultipleHits = false; - } - } + if (m_InDoubleStrike) + ProcessingMultipleHits = true; + else + ProcessingMultipleHits = false; + } + } - public bool ProcessingMultipleHits - { - get { return m_ProcessingMultipleHits; } - set - { - m_ProcessingMultipleHits = value; + public bool ProcessingMultipleHits + { + get { return m_ProcessingMultipleHits; } + set + { + m_ProcessingMultipleHits = value; - if (!m_ProcessingMultipleHits) - BlockHitEffects = false; - } - } + if (!m_ProcessingMultipleHits) + BlockHitEffects = false; + } + } - public bool EndDualWield { get; set; } - public bool BlockHitEffects { get; set; } - public DateTime NextSelfRepair { get; set; } + public bool EndDualWield { get; set; } + public bool BlockHitEffects { get; set; } + public DateTime NextSelfRepair { get; set; } public void OnHit(Mobile attacker, IDamageable damageable) { - OnHit(attacker, damageable, 1.0); + OnHit(attacker, damageable, 1.0); } - public virtual void OnHit(Mobile attacker, IDamageable damageable, double damageBonus) + public virtual void OnHit(Mobile attacker, IDamageable damageable, double damageBonus) { - if (EndDualWield) - { - ProcessingMultipleHits = false; - EndDualWield = false; - } + if (EndDualWield) + { + ProcessingMultipleHits = false; + EndDualWield = false; + } - Mobile defender = damageable as Mobile; - Clone clone = null; + Mobile defender = damageable as Mobile; + Clone clone = null; - if (defender != null) - { - clone = MirrorImage.GetDeflect(attacker, defender); - } + if (defender != null) + { + clone = MirrorImage.GetDeflect(attacker, defender); + } - if (clone != null) - { - defender = clone; - } + if (clone != null) + { + defender = clone; + } PlaySwingAnimation(attacker); - if(defender != null) - PlayHurtAnimation(defender); + if (defender != null) + PlayHurtAnimation(defender); attacker.PlaySound(GetHitAttackSound(attacker, defender)); - if(defender != null) - defender.PlaySound(GetHitDefendSound(attacker, defender)); + if (defender != null) + defender.PlaySound(GetHitDefendSound(attacker, defender)); int damage = ComputeDamage(attacker, defender); - WeaponAbility a = WeaponAbility.GetCurrentAbility(attacker); - SpecialMove move = SpecialMove.GetCurrentMove(attacker); + WeaponAbility a = WeaponAbility.GetCurrentAbility(attacker); + SpecialMove move = SpecialMove.GetCurrentMove(attacker); - bool ranged = this is BaseRanged; - int phys, fire, cold, pois, nrgy, chaos, direct; + bool ranged = this is BaseRanged; + int phys, fire, cold, pois, nrgy, chaos, direct; - if ((Core.TOL && a is MovingShot) || SkillMasterySpell.HasSpell(attacker)) - { - phys = 100; - fire = cold = pois = nrgy = chaos = direct = 0; - } - else - { - GetDamageTypes(attacker, out phys, out fire, out cold, out pois, out nrgy, out chaos, out direct); + if ((Core.TOL && a is MovingShot) || SkillMasterySpell.HasSpell(attacker)) + { + phys = 100; + fire = cold = pois = nrgy = chaos = direct = 0; + } + else + { + GetDamageTypes(attacker, out phys, out fire, out cold, out pois, out nrgy, out chaos, out direct); - if (!OnslaughtSpell.HasOnslaught(attacker, defender) && - ConsecratedContext != null && - ConsecratedContext.Owner == attacker && - ConsecratedContext.ConsecrateProcChance >= Utility.Random(100)) - { - phys = damageable.PhysicalResistance; - fire = damageable.FireResistance; - cold = damageable.ColdResistance; - pois = damageable.PoisonResistance; - nrgy = damageable.EnergyResistance; + if (!OnslaughtSpell.HasOnslaught(attacker, defender) && + ConsecratedContext != null && + ConsecratedContext.Owner == attacker && + ConsecratedContext.ConsecrateProcChance >= Utility.Random(100)) + { + phys = damageable.PhysicalResistance; + fire = damageable.FireResistance; + cold = damageable.ColdResistance; + pois = damageable.PoisonResistance; + nrgy = damageable.EnergyResistance; - int low = phys, type = 0; + int low = phys, type = 0; - if (fire < low) { low = fire; type = 1; } - if (cold < low) { low = cold; type = 2; } - if (pois < low) { low = pois; type = 3; } - if (nrgy < low) { low = nrgy; type = 4; } + if (fire < low) { low = fire; type = 1; } + if (cold < low) { low = cold; type = 2; } + if (pois < low) { low = pois; type = 3; } + if (nrgy < low) { low = nrgy; type = 4; } - phys = fire = cold = pois = nrgy = chaos = direct = 0; + phys = fire = cold = pois = nrgy = chaos = direct = 0; - if (type == 0) phys = 100; - else if (type == 1) fire = 100; - else if (type == 2) cold = 100; - else if (type == 3) pois = 100; - else if (type == 4) nrgy = 100; - } - else if (Core.ML && ranged) - { - IRangeDamage rangeDamage = attacker.FindItemOnLayer(Layer.Cloak) as IRangeDamage; + if (type == 0) phys = 100; + else if (type == 1) fire = 100; + else if (type == 2) cold = 100; + else if (type == 3) pois = 100; + else if (type == 4) nrgy = 100; + } + else if (Core.ML && ranged) + { + IRangeDamage rangeDamage = attacker.FindItemOnLayer(Layer.Cloak) as IRangeDamage; - if (rangeDamage != null) - { - rangeDamage.AlterRangedDamage(ref phys, ref fire, ref cold, ref pois, ref nrgy, ref chaos, ref direct); - } - } - } + if (rangeDamage != null) + { + rangeDamage.AlterRangedDamage(ref phys, ref fire, ref cold, ref pois, ref nrgy, ref chaos, ref direct); + } + } + } - bool splintering = false; + bool splintering = false; - if (m_AosWeaponAttributes.SplinteringWeapon > 0 && m_AosWeaponAttributes.SplinteringWeapon > Utility.Random(100)) - { - if (SplinteringWeaponContext.CheckHit(attacker, defender, a, this)) - splintering = true; - } + if (m_AosWeaponAttributes.SplinteringWeapon > 0 && m_AosWeaponAttributes.SplinteringWeapon > Utility.Random(100)) + { + if (SplinteringWeaponContext.CheckHit(attacker, defender, a, this)) + splintering = true; + } - double chance = NegativeAttributes.Antique > 0 ? 5 : 0; - bool acidicTarget = MaxRange <= 1 && m_AosAttributes.SpellChanneling == 0 && !(this is Fists) && (defender is Slime || defender is ToxicElemental || defender is CorrosiveSlime); + double chance = NegativeAttributes.Antique > 0 ? 5 : 0; + bool acidicTarget = MaxRange <= 1 && m_AosAttributes.SpellChanneling == 0 && !(this is Fists) && (defender is Slime || defender is ToxicElemental || defender is CorrosiveSlime); - if (acidicTarget || (defender != null && splintering) || Utility.Random(40) <= chance) - { - if (MaxRange <= 1 && acidicTarget) - { - attacker.LocalOverheadMessage(MessageType.Regular, 0x3B2, 500263); // *Acid blood scars your weapon!* - } + if (acidicTarget || (defender != null && splintering) || Utility.Random(40) <= chance) + { + if (MaxRange <= 1 && acidicTarget) + { + attacker.LocalOverheadMessage(MessageType.Regular, 0x3B2, 500263); // *Acid blood scars your weapon!* + } - int selfRepair = !Core.AOS ? 0 : m_AosWeaponAttributes.SelfRepair + (IsSetItem && m_SetEquipped ? m_SetSelfRepair : 0); + int selfRepair = !Core.AOS ? 0 : m_AosWeaponAttributes.SelfRepair + (IsSetItem && m_SetEquipped ? m_SetSelfRepair : 0); - if (selfRepair > 0 && NextSelfRepair < DateTime.UtcNow) - { - HitPoints += selfRepair; + if (selfRepair > 0 && NextSelfRepair < DateTime.UtcNow) + { + HitPoints += selfRepair; - NextSelfRepair = DateTime.UtcNow + TimeSpan.FromSeconds(60); - } - else - { - if (m_MaxHits > 0) - { - if (m_Hits >= 1) - { - if (splintering) - { - HitPoints = Math.Max(0, HitPoints - 10); - } - else - { - HitPoints--; - } - } - else if (m_MaxHits > 0) - { - MaxHitPoints--; + NextSelfRepair = DateTime.UtcNow + TimeSpan.FromSeconds(60); + } + else + { + if (m_MaxHits > 0) + { + if (m_Hits >= 1) + { + if (splintering) + { + HitPoints = Math.Max(0, HitPoints - 10); + } + else + { + HitPoints--; + } + } + else if (m_MaxHits > 0) + { + MaxHitPoints--; - if (Parent is Mobile) - ((Mobile)Parent).LocalOverheadMessage(MessageType.Regular, 0x3B2, 1061121); // Your equipment is severely damaged. + if (Parent is Mobile) + ((Mobile)Parent).LocalOverheadMessage(MessageType.Regular, 0x3B2, 1061121); // Your equipment is severely damaged. - if (m_MaxHits <= 0) - Delete(); - } - } - } - } + if (m_MaxHits <= 0) + Delete(); + } + } + } + } - WeaponAbility weavabil; - bool bladeweaving = Bladeweave.BladeWeaving(attacker, out weavabil); - bool ignoreArmor = (a is ArmorIgnore || (move != null && move.IgnoreArmor(attacker)) || (bladeweaving && weavabil is ArmorIgnore)); + WeaponAbility weavabil; + bool bladeweaving = Bladeweave.BladeWeaving(attacker, out weavabil); + bool ignoreArmor = (a is ArmorIgnore || (move != null && move.IgnoreArmor(attacker)) || (bladeweaving && weavabil is ArmorIgnore)); - // object is not a mobile, so we end here - if (defender == null) - { - AOS.Damage(damageable, attacker, damage, ignoreArmor, phys, fire, cold, pois, nrgy, chaos, direct, false, ranged ? Server.DamageType.Ranged : Server.DamageType.Melee); + // object is not a mobile, so we end here + if (defender == null) + { + AOS.Damage(damageable, attacker, damage, ignoreArmor, phys, fire, cold, pois, nrgy, chaos, direct, false, ranged ? Server.DamageType.Ranged : Server.DamageType.Melee); - // TODO: WeaponAbility/SpecialMove OnHit(...) convert target to IDamageable - // Figure out which specials work on items. For now AI only. - if (ignoreArmor) - { - Effects.PlaySound(damageable.Location, damageable.Map, 0x56); - Effects.SendTargetParticles(damageable, 0x3728, 200, 25, 0, 0, 9942, EffectLayer.Waist, 0); - } + // TODO: WeaponAbility/SpecialMove OnHit(...) convert target to IDamageable + // Figure out which specials work on items. For now AI only. + if (ignoreArmor) + { + Effects.PlaySound(damageable.Location, damageable.Map, 0x56); + Effects.SendTargetParticles(damageable, 0x3728, 200, 25, 0, 0, 9942, EffectLayer.Waist, 0); + } - WeaponAbility.ClearCurrentAbility(attacker); - SpecialMove.ClearCurrentMove(attacker); + WeaponAbility.ClearCurrentAbility(attacker); + SpecialMove.ClearCurrentMove(attacker); - if (WeaponAttributes.HitLeechHits > 0) - { - attacker.SendLocalizedMessage(1152566); // You fail to leech life from your target! - } + if (WeaponAttributes.HitLeechHits > 0) + { + attacker.SendLocalizedMessage(1152566); // You fail to leech life from your target! + } - return; - } + return; + } #region Damage Multipliers /* @@ -2399,81 +2399,81 @@ namespace Server.Items percentageBonus += (int)(move.GetDamageScalar(attacker, defender) * 100) - 100; } - if (ConsecratedContext != null && ConsecratedContext.Owner == attacker) - { - percentageBonus += ConsecratedContext.ConsecrateDamageBonus; - } + if (ConsecratedContext != null && ConsecratedContext.Owner == attacker) + { + percentageBonus += ConsecratedContext.ConsecrateDamageBonus; + } - percentageBonus += (int)(damageBonus * 100) - 100; + percentageBonus += (int)(damageBonus * 100) - 100; CheckSlayerResult cs1 = CheckSlayers(attacker, defender, Slayer); - CheckSlayerResult cs2 = CheckSlayers(attacker, defender, Slayer2); - CheckSlayerResult suit = CheckSlayers(attacker, defender, SetHelper.GetSetSlayer(attacker)); - CheckSlayerResult tal = CheckTalismanSlayer(attacker, defender); + CheckSlayerResult cs2 = CheckSlayers(attacker, defender, Slayer2); + CheckSlayerResult suit = CheckSlayers(attacker, defender, SetHelper.GetSetSlayer(attacker)); + CheckSlayerResult tal = CheckTalismanSlayer(attacker, defender); - if (cs1 == CheckSlayerResult.None && cs2 == CheckSlayerResult.None) - { - cs1 = CheckSlayers(attacker, defender, SlayerSocket.GetSlayer(this)); - } + if (cs1 == CheckSlayerResult.None && cs2 == CheckSlayerResult.None) + { + cs1 = CheckSlayers(attacker, defender, SlayerSocket.GetSlayer(this)); + } if (cs1 != CheckSlayerResult.None) { - if (cs1 == CheckSlayerResult.SuperSlayer) - percentageBonus += 100; - else if (cs1 == CheckSlayerResult.Slayer) - percentageBonus += 200; - } + if (cs1 == CheckSlayerResult.SuperSlayer) + percentageBonus += 100; + else if (cs1 == CheckSlayerResult.Slayer) + percentageBonus += 200; + } - if (cs2 != CheckSlayerResult.None) - { - if (cs2 == CheckSlayerResult.SuperSlayer) - percentageBonus += 100; - else if (cs2 == CheckSlayerResult.Slayer) - percentageBonus += 200; - } + if (cs2 != CheckSlayerResult.None) + { + if (cs2 == CheckSlayerResult.SuperSlayer) + percentageBonus += 100; + else if (cs2 == CheckSlayerResult.Slayer) + percentageBonus += 200; + } - if (suit != CheckSlayerResult.None) - { - percentageBonus += 100; - } + if (suit != CheckSlayerResult.None) + { + percentageBonus += 100; + } - if (tal != CheckSlayerResult.None) - { - percentageBonus += 100; - } + if (tal != CheckSlayerResult.None) + { + percentageBonus += 100; + } - if (CheckSlayerOpposition(attacker, defender) != CheckSlayerResult.None) - { - percentageBonus += 100; - defender.FixedEffect(0x37B9, 10, 5); - } - else if (cs1 != CheckSlayerResult.None || cs2 != CheckSlayerResult.None || suit != CheckSlayerResult.None || tal != CheckSlayerResult.None) - { - defender.FixedEffect(0x37B9, 10, 5); - } + if (CheckSlayerOpposition(attacker, defender) != CheckSlayerResult.None) + { + percentageBonus += 100; + defender.FixedEffect(0x37B9, 10, 5); + } + else if (cs1 != CheckSlayerResult.None || cs2 != CheckSlayerResult.None || suit != CheckSlayerResult.None || tal != CheckSlayerResult.None) + { + defender.FixedEffect(0x37B9, 10, 5); + } #region Enemy of One var enemyOfOneContext = EnemyOfOneSpell.GetContext(defender); - if (enemyOfOneContext != null && !enemyOfOneContext.IsWaitingForEnemy && !enemyOfOneContext.IsEnemy(attacker)) - { - percentageBonus += 100; - } - else - { - enemyOfOneContext = EnemyOfOneSpell.GetContext(attacker); + if (enemyOfOneContext != null && !enemyOfOneContext.IsWaitingForEnemy && !enemyOfOneContext.IsEnemy(attacker)) + { + percentageBonus += 100; + } + else + { + enemyOfOneContext = EnemyOfOneSpell.GetContext(attacker); - if (enemyOfOneContext != null) - { - enemyOfOneContext.OnHit(defender); + if (enemyOfOneContext != null) + { + enemyOfOneContext.OnHit(defender); - if (enemyOfOneContext.IsEnemy(defender)) - { - defender.FixedEffect(0x37B9, 10, 5, 1160, 0); - percentageBonus += enemyOfOneContext.DamageScalar; - } - } - } + if (enemyOfOneContext.IsEnemy(defender)) + { + defender.FixedEffect(0x37B9, 10, 5, 1160, 0); + percentageBonus += enemyOfOneContext.DamageScalar; + } + } + } #endregion int packInstinctBonus = GetPackInstinctBonus(attacker, defender); @@ -2491,8 +2491,8 @@ namespace Server.Items TransformContext context = TransformationSpellHelper.GetContext(defender); if ((m_Slayer == SlayerName.Silver || m_Slayer2 == SlayerName.Silver || SetHelper.GetSetSlayer(attacker) == SlayerName.Silver) - && ((context != null && context.Spell is NecromancerSpell && context.Type != typeof(HorrificBeastSpell)) - || (defender is BaseCreature && (defender.Body == 747 || defender.Body == 748 || defender.Body == 749 || defender.Hue == 0x847E)))) + && ((context != null && context.Spell is NecromancerSpell && context.Type != typeof(HorrificBeastSpell)) + || (defender is BaseCreature && (defender.Body == 747 || defender.Body == 748 || defender.Body == 749 || defender.Hue == 0x847E)))) { // Every necromancer transformation other than horrific beast takes an additional 25% damage percentageBonus += 25; @@ -2513,22 +2513,22 @@ namespace Server.Items } } - percentageBonus -= Block.GetMeleeReduction(defender); + percentageBonus -= Block.GetMeleeReduction(defender); #region Stygian Abyss percentageBonus += BattleLust.GetBonus(attacker, defender); - if (this is BaseThrown) - { - double dist = attacker.GetDistanceToSqrt(defender); - int max = ((BaseThrown)this).MaxThrowRange; + if (this is BaseThrown) + { + double dist = attacker.GetDistanceToSqrt(defender); + int max = ((BaseThrown)this).MaxThrowRange; - if (dist > max) - percentageBonus -= 47; - } + if (dist > max) + percentageBonus -= 47; + } - if (RunedSashOfWarding.IsUnderEffects(defender, WardingEffect.WeaponDamage)) - percentageBonus -= 10; + if (RunedSashOfWarding.IsUnderEffects(defender, WardingEffect.WeaponDamage)) + percentageBonus -= 10; #endregion #region Mondain's Legacy @@ -2551,31 +2551,31 @@ namespace Server.Items } #endregion - percentageBonus += ForceOfNature.GetBonus(attacker, defender); + percentageBonus += ForceOfNature.GetBonus(attacker, defender); - if (m_ExtendedWeaponAttributes.AssassinHoned > 0 && GetOppositeDir(attacker.Direction) == defender.Direction) - { - if (!ranged || 0.5 > Utility.RandomDouble()) - { - percentageBonus += (int)(146.0 / MlSpeed); - } - } + if (m_ExtendedWeaponAttributes.AssassinHoned > 0 && GetOppositeDir(attacker.Direction) == defender.Direction) + { + if (!ranged || 0.5 > Utility.RandomDouble()) + { + percentageBonus += (int)(146.0 / MlSpeed); + } + } - if (m_ExtendedWeaponAttributes.Focus > 0) - { - percentageBonus += Focus.GetBonus(attacker, defender); - Focus.OnHit(attacker, defender); - } + if (m_ExtendedWeaponAttributes.Focus > 0) + { + percentageBonus += Focus.GetBonus(attacker, defender); + Focus.OnHit(attacker, defender); + } - percentageBonus = Math.Min(percentageBonus, 300); + percentageBonus = Math.Min(percentageBonus, 300); - // bonus is seprate from weapon damage, ie not capped - percentageBonus += Spells.Mysticism.StoneFormSpell.GetMaxResistBonus(attacker); + // bonus is seprate from weapon damage, ie not capped + percentageBonus += Spells.Mysticism.StoneFormSpell.GetMaxResistBonus(attacker); damage = AOS.Scale(damage, 100 + percentageBonus); #endregion - damage = AbsorbDamage(attacker, defender, damage); + damage = AbsorbDamage(attacker, defender, damage); if (!Core.AOS && damage < 1) { @@ -2584,34 +2584,34 @@ namespace Server.Items else if (Core.AOS && damage == 0) // parried { if ((a != null && a.Validate(attacker)) || (move != null && move.Validate(attacker))) - // Parried special moves have no mana cost - era specific + // Parried special moves have no mana cost - era specific { - if (Core.SE || (a != null && a.CheckMana(attacker, true))) - { - WeaponAbility.ClearCurrentAbility(attacker); - SpecialMove.ClearCurrentMove(attacker); + if (Core.SE || (a != null && a.CheckMana(attacker, true))) + { + WeaponAbility.ClearCurrentAbility(attacker); + SpecialMove.ClearCurrentMove(attacker); - attacker.SendLocalizedMessage(1061140); // Your attack was parried! - } + attacker.SendLocalizedMessage(1061140); // Your attack was parried! + } } - return; + return; } - // Skill Masteries - if (WhiteTigerFormSpell.CheckEvasion(defender)) - { - defender.Emote("*evades*"); // Is this right? - return; - } + // Skill Masteries + if (WhiteTigerFormSpell.CheckEvasion(defender)) + { + defender.Emote("*evades*"); // Is this right? + return; + } #region Mondain's Legacy - if (ImmolatingWeaponSpell.IsImmolating(attacker, this)) + if (ImmolatingWeaponSpell.IsImmolating(attacker, this)) { - int d = ImmolatingWeaponSpell.GetImmolatingDamage(attacker); + int d = ImmolatingWeaponSpell.GetImmolatingDamage(attacker); d = AOS.Damage(defender, attacker, d, 0, 100, 0, 0, 0); - ImmolatingWeaponSpell.DoDelayEffect(attacker, defender); + ImmolatingWeaponSpell.DoDelayEffect(attacker, defender); if (d > 0) { @@ -2620,43 +2620,43 @@ namespace Server.Items } #endregion - #region SA - if (defender != null && Server.Items.SearingWeapon.CanSear(this) && attacker.Mana > 0) - { - int d = SearingWeaponContext.Damage; + #region SA + if (defender != null && Server.Items.SearingWeapon.CanSear(this) && attacker.Mana > 0) + { + int d = SearingWeaponContext.Damage; - if ((ranged && 10 > Utility.Random(100)) || 20 > Utility.Random(100)) - { - AOS.Damage(defender, attacker, d, 0, 100, 0, 0, 0); - AOS.Damage(attacker, null, 4, false, 0, 0, 0, 0, 0, 0, 100, false, false, false); + if ((ranged && 10 > Utility.Random(100)) || 20 > Utility.Random(100)) + { + AOS.Damage(defender, attacker, d, 0, 100, 0, 0, 0); + AOS.Damage(attacker, null, 4, false, 0, 0, 0, 0, 0, 0, 100, false, false, false); - defender.FixedParticles(0x36F4, 1, 11, 0x13A8, 0, 0, EffectLayer.Waist); + defender.FixedParticles(0x36F4, 1, 11, 0x13A8, 0, 0, EffectLayer.Waist); - SearingWeaponContext.CheckHit(attacker, defender); - attacker.Mana--; - } - } - #endregion + SearingWeaponContext.CheckHit(attacker, defender); + attacker.Mana--; + } + } + #endregion - #region BoneBreaker/Swarm/Sparks - bool sparks = false; - if (a == null && move == null) - { - if (m_ExtendedWeaponAttributes.BoneBreaker > 0) - damage += BoneBreakerContext.CheckHit(attacker, defender); + #region BoneBreaker/Swarm/Sparks + bool sparks = false; + if (a == null && move == null) + { + if (m_ExtendedWeaponAttributes.BoneBreaker > 0) + damage += BoneBreakerContext.CheckHit(attacker, defender); - if (m_ExtendedWeaponAttributes.HitSwarm > 0 && Utility.Random(100) < m_ExtendedWeaponAttributes.HitSwarm) - SwarmContext.CheckHit(attacker, defender); + if (m_ExtendedWeaponAttributes.HitSwarm > 0 && Utility.Random(100) < m_ExtendedWeaponAttributes.HitSwarm) + SwarmContext.CheckHit(attacker, defender); - if (m_ExtendedWeaponAttributes.HitSparks > 0 && Utility.Random(100) < m_ExtendedWeaponAttributes.HitSparks) - { - SparksContext.CheckHit(attacker, defender); - sparks = true; - } - } - #endregion + if (m_ExtendedWeaponAttributes.HitSparks > 0 && Utility.Random(100) < m_ExtendedWeaponAttributes.HitSparks) + { + SparksContext.CheckHit(attacker, defender); + sparks = true; + } + } + #endregion - Timer.DelayCall(d => AddBlood(d, damage), defender); + Timer.DelayCall(d => AddBlood(d, damage), defender); int damageGiven = damage; @@ -2672,25 +2672,25 @@ namespace Server.Items move = null; } - if (Feint.Registry.ContainsKey(defender) && Feint.Registry[defender].Enemy == attacker) - damage -= (int)((double)damage * ((double)Feint.Registry[defender].DamageReduction / 100)); + if (Feint.Registry.ContainsKey(defender) && Feint.Registry[defender].Enemy == attacker) + damage -= (int)((double)damage * ((double)Feint.Registry[defender].DamageReduction / 100)); - // Skill Masteries - if (this is Fists) - damage += (int)((double)damage * ((double)MasteryInfo.GetKnockoutModifier(attacker, defender is PlayerMobile) / 100.0)); + // Skill Masteries + if (this is Fists) + damage += (int)((double)damage * ((double)MasteryInfo.GetKnockoutModifier(attacker, defender is PlayerMobile) / 100.0)); - SkillMasterySpell.OnHit(attacker, defender, ref damage); + SkillMasterySpell.OnHit(attacker, defender, ref damage); - // Bane - if (m_ExtendedWeaponAttributes.Bane > 0 && defender.Hits < defender.HitsMax / 2) - { - double inc = Math.Min(350, (double)defender.HitsMax * .3); - inc -= (double)((double)defender.Hits / (double)defender.HitsMax) * inc; + // Bane + if (m_ExtendedWeaponAttributes.Bane > 0 && defender.Hits < defender.HitsMax / 2) + { + double inc = Math.Min(350, (double)defender.HitsMax * .3); + inc -= (double)((double)defender.Hits / (double)defender.HitsMax) * inc; - Effects.SendTargetEffect(defender, 0x37BE, 1, 4, 0x30, 3); + Effects.SendTargetEffect(defender, 0x37BE, 1, 4, 0x30, 3); - damage += (int)inc; - } + damage += (int)inc; + } damageGiven = AOS.Damage( defender, @@ -2707,14 +2707,14 @@ namespace Server.Items false, ranged ? Server.DamageType.Ranged : Server.DamageType.Melee); - DualWield.DoHit(attacker, defender, damage); + DualWield.DoHit(attacker, defender, damage); - if (sparks) - { - int mana = attacker.Mana + damageGiven; - if (!defender.Player) mana *= 2; - attacker.Mana = Math.Min(attacker.ManaMax, attacker.Mana + mana); - } + if (sparks) + { + int mana = attacker.Mana + damageGiven; + if (!defender.Player) mana *= 2; + attacker.Mana = Math.Min(attacker.ManaMax, attacker.Mana + mana); + } double propertyBonus = (move == null) ? 1.0 : move.GetPropertyBonus(attacker); @@ -2732,8 +2732,8 @@ namespace Server.Items if (Core.SA) { - lifeLeech = (int)(WeaponAttributes.HitLeechHits * propertyBonus); - manaLeech = (int)(WeaponAttributes.HitLeechMana * propertyBonus); + lifeLeech = (int)(WeaponAttributes.HitLeechHits * propertyBonus); + manaLeech = (int)(WeaponAttributes.HitLeechMana * propertyBonus); } else { @@ -2750,12 +2750,12 @@ namespace Server.Items } } - int toHealCursedWeaponSpell = 0; + int toHealCursedWeaponSpell = 0; - if (CurseWeaponSpell.IsCursed(attacker, this)) + if (CurseWeaponSpell.IsCursed(attacker, this)) { - toHealCursedWeaponSpell += (int)(AOS.Scale(damageGiven, 50)); // Additional 50% life leech for cursed weapons (necro spell) - } + toHealCursedWeaponSpell += (int)(AOS.Scale(damageGiven, 50)); // Additional 50% life leech for cursed weapons (necro spell) + } context = TransformationSpellHelper.GetContext(attacker); @@ -2770,36 +2770,36 @@ namespace Server.Items { int toHeal = Utility.RandomMinMax(0, (int)(AOS.Scale(damageGiven, lifeLeech) * 0.3)); - if (defender is BaseCreature && ((BaseCreature)defender).TaintedLifeAura) - { - AOS.Damage(attacker, defender, toHeal, false, 0, 0, 0, 0, 0, 0, 100, false, false, false); - attacker.SendLocalizedMessage(1116778); //The tainted life force energy damages you as your body tries to absorb it. - } - else - { - attacker.Hits += toHeal; - } + if (defender is BaseCreature && ((BaseCreature)defender).TaintedLifeAura) + { + AOS.Damage(attacker, defender, toHeal, false, 0, 0, 0, 0, 0, 0, 100, false, false, false); + attacker.SendLocalizedMessage(1116778); //The tainted life force energy damages you as your body tries to absorb it. + } + else + { + attacker.Hits += toHeal; + } - Effects.SendPacket(defender.Location, defender.Map, new ParticleEffect(EffectType.FixedFrom, defender.Serial, Serial.Zero, 0x377A, defender.Location, defender.Location, 1, 15, false, false, 1926, 0, 0, 9502, 1, defender.Serial, 16, 0)); - Effects.SendPacket(defender.Location, defender.Map, new ParticleEffect(EffectType.FixedFrom, defender.Serial, Serial.Zero, 0x3728, defender.Location, defender.Location, 1, 12, false, false, 1963, 0, 0, 9042, 1, defender.Serial, 16, 0)); - } + Effects.SendPacket(defender.Location, defender.Map, new ParticleEffect(EffectType.FixedFrom, defender.Serial, Serial.Zero, 0x377A, defender.Location, defender.Location, 1, 15, false, false, 1926, 0, 0, 9502, 1, defender.Serial, 16, 0)); + Effects.SendPacket(defender.Location, defender.Map, new ParticleEffect(EffectType.FixedFrom, defender.Serial, Serial.Zero, 0x3728, defender.Location, defender.Location, 1, 12, false, false, 1963, 0, 0, 9042, 1, defender.Serial, 16, 0)); + } - if (toHealCursedWeaponSpell != 0 && !(defender is BaseCreature && ((BaseCreature)defender).TaintedLifeAura)) - { - attacker.Hits += toHealCursedWeaponSpell; - } - - if (manaLeech != 0) + if (toHealCursedWeaponSpell != 0 && !(defender is BaseCreature && ((BaseCreature)defender).TaintedLifeAura)) { - attacker.Mana += Utility.RandomMinMax(0, (int)(AOS.Scale(damageGiven, manaLeech) * 0.4)); + attacker.Hits += toHealCursedWeaponSpell; + } + + if (manaLeech != 0) + { + attacker.Mana += Utility.RandomMinMax(0, (int)(AOS.Scale(damageGiven, manaLeech) * 0.4)); } } else // Old formulas { - if (toHealCursedWeaponSpell != 0) - { - attacker.Hits += toHealCursedWeaponSpell; - } + if (toHealCursedWeaponSpell != 0) + { + attacker.Hits += toHealCursedWeaponSpell; + } if (lifeLeech != 0) { @@ -2812,7 +2812,7 @@ namespace Server.Items } } - if (lifeLeech != 0 || stamLeech != 0 || manaLeech != 0 || toHealCursedWeaponSpell != 0) + if (lifeLeech != 0 || stamLeech != 0 || manaLeech != 0 || toHealCursedWeaponSpell != 0) { attacker.PlaySound(0x44D); } @@ -2876,14 +2876,14 @@ namespace Server.Items int fireballChance = (int)(AosWeaponAttributes.GetValue(attacker, AosWeaponAttribute.HitFireball) * propertyBonus); int lightningChance = (int)(AosWeaponAttributes.GetValue(attacker, AosWeaponAttribute.HitLightning) * propertyBonus); int dispelChance = (int)(AosWeaponAttributes.GetValue(attacker, AosWeaponAttribute.HitDispel) * propertyBonus); - int explosChance = (int)(ExtendedWeaponAttributes.GetValue(attacker, ExtendedWeaponAttribute.HitExplosion) * propertyBonus); + int explosChance = (int)(ExtendedWeaponAttributes.GetValue(attacker, ExtendedWeaponAttribute.HitExplosion) * propertyBonus); - #region Mondains Legacy - int velocityChance = this is BaseRanged ? (int)((BaseRanged)this).Velocity : 0; - #endregion + #region Mondains Legacy + int velocityChance = this is BaseRanged ? (int)((BaseRanged)this).Velocity : 0; + #endregion - #region Stygian Abyss - int curseChance = (int)(m_AosWeaponAttributes.HitCurse * propertyBonus); + #region Stygian Abyss + int curseChance = (int)(m_AosWeaponAttributes.HitCurse * propertyBonus); int fatigueChance = (int)(m_AosWeaponAttributes.HitFatigue * propertyBonus); int manadrainChance = (int)(m_AosWeaponAttributes.HitManaDrain * propertyBonus); #endregion @@ -2911,22 +2911,22 @@ namespace Server.Items if (dispelChance != 0 && dispelChance > Utility.Random(100)) { DoDispel(attacker, defender); - } + } - if (explosChance != 0 && explosChance > Utility.Random(100)) - { - DoExplosion(attacker, defender); - } + if (explosChance != 0 && explosChance > Utility.Random(100)) + { + DoExplosion(attacker, defender); + } - #region Mondains Legacy - if (Core.ML && velocityChance != 0 && velocityChance > Utility.Random(100)) - { - DoHitVelocity(attacker, damageable); - } - #endregion + #region Mondains Legacy + if (Core.ML && velocityChance != 0 && velocityChance > Utility.Random(100)) + { + DoHitVelocity(attacker, damageable); + } + #endregion - #region Stygian Abyss - if (curseChance != 0 && curseChance > Utility.Random(100)) + #region Stygian Abyss + if (curseChance != 0 && curseChance > Utility.Random(100)) { DoCurse(attacker, defender); } @@ -2942,42 +2942,42 @@ namespace Server.Items } #endregion - int laChance = (int)(AosWeaponAttributes.GetValue(attacker, AosWeaponAttribute.HitLowerAttack) * propertyBonus); + int laChance = (int)(AosWeaponAttributes.GetValue(attacker, AosWeaponAttribute.HitLowerAttack) * propertyBonus); if (laChance != 0 && laChance > Utility.Random(100)) { DoLowerAttack(attacker, defender); } - if (!Core.HS) - { - int ldChance = (int)(AosWeaponAttributes.GetValue(attacker, AosWeaponAttribute.HitLowerDefend) * propertyBonus); + if (!Core.HS) + { + int ldChance = (int)(AosWeaponAttributes.GetValue(attacker, AosWeaponAttribute.HitLowerDefend) * propertyBonus); - if (ldChance != 0 && ldChance > Utility.Random(100)) - { - DoLowerDefense(attacker, defender); - } - } - else - { - int hldWep = m_AosWeaponAttributes.HitLowerDefend; - int hldGlasses = 0; - - var helm = attacker.FindItemOnLayer(Layer.Helm); + if (ldChance != 0 && ldChance > Utility.Random(100)) + { + DoLowerDefense(attacker, defender); + } + } + else + { + int hldWep = m_AosWeaponAttributes.HitLowerDefend; + int hldGlasses = 0; - if (helm != null) - { - var attrs = RunicReforging.GetAosWeaponAttributes(helm); + var helm = attacker.FindItemOnLayer(Layer.Helm); - if(attrs != null) - hldGlasses = attrs.HitLowerDefend; - } + if (helm != null) + { + var attrs = RunicReforging.GetAosWeaponAttributes(helm); - if ((hldWep > 0 && hldWep > Utility.Random(100)) || (hldGlasses > 0 && hldGlasses > Utility.Random(100))) - { - DoLowerDefense(attacker, defender); - } - } + if (attrs != null) + hldGlasses = attrs.HitLowerDefend; + } + + if ((hldWep > 0 && hldWep > Utility.Random(100)) || (hldGlasses > 0 && hldGlasses > Utility.Random(100))) + { + DoLowerDefense(attacker, defender); + } + } } if (attacker is BaseCreature) @@ -3018,64 +3018,64 @@ namespace Server.Items } } - BaseFamiliar.OnHit(attacker, damageable); - WhiteTigerFormSpell.OnHit(attacker, defender); + BaseFamiliar.OnHit(attacker, damageable); + WhiteTigerFormSpell.OnHit(attacker, defender); XmlAttach.OnWeaponHit(this, attacker, defender, damageGiven); } - public Direction GetOppositeDir(Direction d) - { - Direction direction = Direction.Down; - - if (d == Direction.West) - direction = Direction.East; - - if (d == Direction.East) - direction = Direction.West; - - if (d == Direction.North) - direction = Direction.South; - - if (d == Direction.South) - direction = Direction.North; - - if (d == Direction.Right) - direction = Direction.Left; - - if (d == Direction.Left) - direction = Direction.Right; - - if (d == Direction.Up) - direction = Direction.Down; - - if (d == Direction.Down) - direction = Direction.Up; - - return direction; - } - - public virtual double GetAosSpellDamage(Mobile attacker, Mobile defender, int bonus, int dice, int sides) + public Direction GetOppositeDir(Direction d) { - int damage = Utility.Dice(dice, sides, bonus) * 100; - int damageBonus = 0; + Direction direction = Direction.Down; - int inscribeSkill = attacker.Skills[SkillName.Inscribe].Fixed; - int inscribeBonus = (inscribeSkill + (1000 * (inscribeSkill / 1000))) / 200; + if (d == Direction.West) + direction = Direction.East; - damageBonus += inscribeBonus; - damageBonus += attacker.Int / 10; - damageBonus += SpellHelper.GetSpellDamageBonus(attacker, defender, SkillName.Magery, attacker is PlayerMobile && defender is PlayerMobile); - damage = AOS.Scale(damage, 100 + damageBonus); + if (d == Direction.East) + direction = Direction.West; - if (defender != null && Feint.Registry.ContainsKey(defender) && Feint.Registry[defender].Enemy == attacker) - damage -= (int)((double)damage * ((double)Feint.Registry[defender].DamageReduction / 100)); + if (d == Direction.North) + direction = Direction.South; - // All hit spells use 80 eval - int evalScale = 30 + ((9 * 800) / 100); + if (d == Direction.South) + direction = Direction.North; - damage = AOS.Scale(damage, evalScale); + if (d == Direction.Right) + direction = Direction.Left; - return damage / 100; + if (d == Direction.Left) + direction = Direction.Right; + + if (d == Direction.Up) + direction = Direction.Down; + + if (d == Direction.Down) + direction = Direction.Up; + + return direction; + } + + public virtual double GetAosSpellDamage(Mobile attacker, Mobile defender, int bonus, int dice, int sides) + { + int damage = Utility.Dice(dice, sides, bonus) * 100; + int damageBonus = 0; + + int inscribeSkill = attacker.Skills[SkillName.Inscribe].Fixed; + int inscribeBonus = (inscribeSkill + (1000 * (inscribeSkill / 1000))) / 200; + + damageBonus += inscribeBonus; + damageBonus += attacker.Int / 10; + damageBonus += SpellHelper.GetSpellDamageBonus(attacker, defender, SkillName.Magery, attacker is PlayerMobile && defender is PlayerMobile); + damage = AOS.Scale(damage, 100 + damageBonus); + + if (defender != null && Feint.Registry.ContainsKey(defender) && Feint.Registry[defender].Enemy == attacker) + damage -= (int)((double)damage * ((double)Feint.Registry[defender].DamageReduction / 100)); + + // All hit spells use 80 eval + int evalScale = 30 + ((9 * 800) / 100); + + damage = AOS.Scale(damage, evalScale); + + return damage / 100; } #region Do @@ -3095,8 +3095,8 @@ namespace Server.Items SpellHelper.Damage(TimeSpan.FromSeconds(1.0), defender, attacker, damage, 0, 100, 0, 0, 0); - if (ProcessingMultipleHits) - BlockHitEffects = true; + if (ProcessingMultipleHits) + BlockHitEffects = true; } public virtual void DoHarm(Mobile attacker, Mobile defender) @@ -3124,8 +3124,8 @@ namespace Server.Items SpellHelper.Damage(TimeSpan.Zero, defender, attacker, damage, 0, 0, 100, 0, 0); - if (ProcessingMultipleHits) - BlockHitEffects = true; + if (ProcessingMultipleHits) + BlockHitEffects = true; } public virtual void DoFireball(Mobile attacker, Mobile defender) @@ -3144,8 +3144,8 @@ namespace Server.Items SpellHelper.Damage(TimeSpan.FromSeconds(1.0), defender, attacker, damage, 0, 100, 0, 0, 0); - if (ProcessingMultipleHits) - BlockHitEffects = true; + if (ProcessingMultipleHits) + BlockHitEffects = true; } public virtual void DoLightning(Mobile attacker, Mobile defender) @@ -3163,8 +3163,8 @@ namespace Server.Items SpellHelper.Damage(TimeSpan.Zero, defender, attacker, damage, 0, 0, 0, 0, 100); - if (ProcessingMultipleHits) - BlockHitEffects = true; + if (ProcessingMultipleHits) + BlockHitEffects = true; } public virtual void DoDispel(Mobile attacker, Mobile defender) @@ -3204,48 +3204,48 @@ namespace Server.Items } } - public virtual void DoExplosion(Mobile attacker, Mobile defender) - { - if (!attacker.CanBeHarmful(defender, false)) - { - return; - } + public virtual void DoExplosion(Mobile attacker, Mobile defender) + { + if (!attacker.CanBeHarmful(defender, false)) + { + return; + } - attacker.DoHarmful(defender); + attacker.DoHarmful(defender); - double damage = GetAosSpellDamage(attacker, defender, 40, 1, 5); + double damage = GetAosSpellDamage(attacker, defender, 40, 1, 5); - defender.FixedParticles(0x36BD, 20, 10, 5044, EffectLayer.Head); - defender.PlaySound(0x307); + defender.FixedParticles(0x36BD, 20, 10, 5044, EffectLayer.Head); + defender.PlaySound(0x307); - SpellHelper.Damage(TimeSpan.FromSeconds(1.0), defender, attacker, damage, 0, 100, 0, 0, 0); + SpellHelper.Damage(TimeSpan.FromSeconds(1.0), defender, attacker, damage, 0, 100, 0, 0, 0); - if (ProcessingMultipleHits) - BlockHitEffects = true; - } + if (ProcessingMultipleHits) + BlockHitEffects = true; + } - public virtual void DoHitVelocity(Mobile attacker, IDamageable damageable) - { - int bonus = (int)attacker.GetDistanceToSqrt(damageable); + public virtual void DoHitVelocity(Mobile attacker, IDamageable damageable) + { + int bonus = (int)attacker.GetDistanceToSqrt(damageable); - if (bonus > 0) - { - AOS.Damage(damageable, attacker, bonus * 3, 100, 0, 0, 0, 0); + if (bonus > 0) + { + AOS.Damage(damageable, attacker, bonus * 3, 100, 0, 0, 0, 0); - if (attacker.Player) - { - attacker.SendLocalizedMessage(1072794); // Your arrow hits its mark with velocity! - } + if (attacker.Player) + { + attacker.SendLocalizedMessage(1072794); // Your arrow hits its mark with velocity! + } - if (damageable is Mobile && ((Mobile)damageable).Player) - { - ((Mobile)damageable).SendLocalizedMessage(1072795); // You have been hit by an arrow with velocity! - } - } + if (damageable is Mobile && ((Mobile)damageable).Player) + { + ((Mobile)damageable).SendLocalizedMessage(1072795); // You have been hit by an arrow with velocity! + } + } - if (ProcessingMultipleHits) - BlockHitEffects = true; - } + if (ProcessingMultipleHits) + BlockHitEffects = true; + } #region Stygian Abyss public virtual void DoCurse(Mobile attacker, Mobile defender) @@ -3255,23 +3255,23 @@ namespace Server.Items defender.FixedParticles(0x374A, 10, 15, 5028, EffectLayer.Waist); defender.PlaySound(0x1EA); - TimeSpan duration = TimeSpan.FromSeconds(30); + TimeSpan duration = TimeSpan.FromSeconds(30); defender.AddStatMod( - new StatMod(StatType.Str, String.Format("[Magic] {0} Curse", StatType.Str), -10, duration)); + new StatMod(StatType.Str, String.Format("[Magic] {0} Curse", StatType.Str), -10, duration)); defender.AddStatMod( - new StatMod(StatType.Dex, String.Format("[Magic] {0} Curse", StatType.Dex), -10, duration)); + new StatMod(StatType.Dex, String.Format("[Magic] {0} Curse", StatType.Dex), -10, duration)); defender.AddStatMod( - new StatMod(StatType.Int, String.Format("[Magic] {0} Curse", StatType.Int), -10, duration)); + new StatMod(StatType.Int, String.Format("[Magic] {0} Curse", StatType.Int), -10, duration)); int percentage = -10; //(int)(SpellHelper.GetOffsetScalar(Caster, m, true) * 100); string args = String.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", percentage, percentage, percentage, 10, 10, 10, 10); - Server.Spells.Fourth.CurseSpell.AddEffect(defender, duration, 10, 10, 10); - BuffInfo.AddBuff(defender, new BuffInfo(BuffIcon.Curse, 1075835, 1075836, duration, defender, args)); + Server.Spells.Fourth.CurseSpell.AddEffect(defender, duration, 10, 10, 10); + BuffInfo.AddBuff(defender, new BuffInfo(BuffIcon.Curse, 1075835, 1075836, duration, defender, args)); - if (ProcessingMultipleHits) - BlockHitEffects = true; + if (ProcessingMultipleHits) + BlockHitEffects = true; } public virtual void DoFatigue(Mobile attacker, Mobile defender, int damagegiven) @@ -3280,8 +3280,8 @@ namespace Server.Items // Effects? defender.Stam -= (damagegiven * (100 - m_AosWeaponAttributes.HitFatigue)) / 100; - if (ProcessingMultipleHits) - BlockHitEffects = true; + if (ProcessingMultipleHits) + BlockHitEffects = true; } public virtual void DoManaDrain(Mobile attacker, Mobile defender, int damagegiven) @@ -3291,8 +3291,8 @@ namespace Server.Items defender.PlaySound(0x1F8); defender.Mana -= (damagegiven * (100 - m_AosWeaponAttributes.HitManaDrain)) / 100; - if (ProcessingMultipleHits) - BlockHitEffects = true; + if (ProcessingMultipleHits) + BlockHitEffects = true; } #endregion @@ -3323,104 +3323,104 @@ namespace Server.Items return; } - var list = SpellHelper.AcquireIndirectTargets(from, from, from.Map, 5); + var list = SpellHelper.AcquireIndirectTargets(from, from, from.Map, 5); var count = 0; - foreach(var m in list) - { + foreach (var m in list) + { ++count; - from.DoHarmful(m, true); - m.FixedEffect(0x3779, 1, 15, hue, 0); - AOS.Damage(m, from, (int)(damageGiven / 2), phys, fire, cold, pois, nrgy, Server.DamageType.SpellAOE); - } + from.DoHarmful(m, true); + m.FixedEffect(0x3779, 1, 15, hue, 0); + AOS.Damage(m, from, (int)(damageGiven / 2), phys, fire, cold, pois, nrgy, Server.DamageType.SpellAOE); + } if (count > 0) { Effects.PlaySound(from.Location, map, sound); - } + } - if (ProcessingMultipleHits) - BlockHitEffects = true; + if (ProcessingMultipleHits) + BlockHitEffects = true; } #endregion - public virtual CheckSlayerResult CheckSlayers(Mobile attacker, Mobile defender, SlayerName slayer) - { - if (slayer == SlayerName.None) - return CheckSlayerResult.None; + public virtual CheckSlayerResult CheckSlayers(Mobile attacker, Mobile defender, SlayerName slayer) + { + if (slayer == SlayerName.None) + return CheckSlayerResult.None; - BaseWeapon atkWeapon = attacker.Weapon as BaseWeapon; - SlayerEntry atkSlayer = SlayerGroup.GetEntryByName(slayer); + BaseWeapon atkWeapon = attacker.Weapon as BaseWeapon; + SlayerEntry atkSlayer = SlayerGroup.GetEntryByName(slayer); - if (atkSlayer != null && atkSlayer.Slays(defender) && _SuperSlayers.Contains(atkSlayer.Name)) - { - return CheckSlayerResult.SuperSlayer; - } + if (atkSlayer != null && atkSlayer.Slays(defender) && _SuperSlayers.Contains(atkSlayer.Name)) + { + return CheckSlayerResult.SuperSlayer; + } - if (atkSlayer != null && atkSlayer.Slays(defender)) - { - return CheckSlayerResult.Slayer; - } + if (atkSlayer != null && atkSlayer.Slays(defender)) + { + return CheckSlayerResult.Slayer; + } - return CheckSlayerResult.None; - } + return CheckSlayerResult.None; + } - public CheckSlayerResult CheckSlayerOpposition(Mobile attacker, Mobile defender) - { - ISlayer defISlayer = Spellbook.FindEquippedSpellbook(defender); + public CheckSlayerResult CheckSlayerOpposition(Mobile attacker, Mobile defender) + { + ISlayer defISlayer = Spellbook.FindEquippedSpellbook(defender); - if (defISlayer == null) - { - defISlayer = defender.Weapon as ISlayer; - } + if (defISlayer == null) + { + defISlayer = defender.Weapon as ISlayer; + } - if (defISlayer != null) - { - SlayerEntry defSlayer = SlayerGroup.GetEntryByName(defISlayer.Slayer); - SlayerEntry defSlayer2 = SlayerGroup.GetEntryByName(defISlayer.Slayer2); - SlayerEntry defSetSlayer = SlayerGroup.GetEntryByName(SetHelper.GetSetSlayer(defender)); + if (defISlayer != null) + { + SlayerEntry defSlayer = SlayerGroup.GetEntryByName(defISlayer.Slayer); + SlayerEntry defSlayer2 = SlayerGroup.GetEntryByName(defISlayer.Slayer2); + SlayerEntry defSetSlayer = SlayerGroup.GetEntryByName(SetHelper.GetSetSlayer(defender)); - if (defISlayer is Item && defSlayer == null && defSlayer2 == null) - { - defSlayer = SlayerGroup.GetEntryByName(SlayerSocket.GetSlayer((Item)defISlayer)); - } + if (defISlayer is Item && defSlayer == null && defSlayer2 == null) + { + defSlayer = SlayerGroup.GetEntryByName(SlayerSocket.GetSlayer((Item)defISlayer)); + } - if (defSlayer != null && defSlayer.Group.OppositionSuperSlays(attacker) || - defSlayer2 != null && defSlayer2.Group.OppositionSuperSlays(attacker) || - defSetSlayer != null && defSetSlayer.Group.OppositionSuperSlays(attacker)) - { - return CheckSlayerResult.Opposition; - } - } + if (defSlayer != null && defSlayer.Group.OppositionSuperSlays(attacker) || + defSlayer2 != null && defSlayer2.Group.OppositionSuperSlays(attacker) || + defSetSlayer != null && defSetSlayer.Group.OppositionSuperSlays(attacker)) + { + return CheckSlayerResult.Opposition; + } + } - return CheckSlayerResult.None; - } + return CheckSlayerResult.None; + } - public CheckSlayerResult CheckTalismanSlayer(Mobile attacker, Mobile defender) - { - BaseTalisman talisman = attacker.Talisman as BaseTalisman; + public CheckSlayerResult CheckTalismanSlayer(Mobile attacker, Mobile defender) + { + BaseTalisman talisman = attacker.Talisman as BaseTalisman; - if (talisman != null && TalismanSlayer.Slays(talisman.Slayer, defender)) - { - return CheckSlayerResult.Slayer; - } - else if (Slayer3 != TalismanSlayerName.None && TalismanSlayer.Slays(Slayer3, defender)) - { - return CheckSlayerResult.Slayer; - } + if (talisman != null && TalismanSlayer.Slays(talisman.Slayer, defender)) + { + return CheckSlayerResult.Slayer; + } + else if (Slayer3 != TalismanSlayerName.None && TalismanSlayer.Slays(Slayer3, defender)) + { + return CheckSlayerResult.Slayer; + } - return CheckSlayerResult.None; - } + return CheckSlayerResult.None; + } - private List _SuperSlayers = new List() - { - SlayerName.Repond, SlayerName.Silver, SlayerName.Fey, - SlayerName.ElementalBan, SlayerName.Exorcism, SlayerName.ArachnidDoom, - SlayerName.ReptilianDeath, SlayerName.Dinosaur, SlayerName.Myrmidex, - SlayerName.Eodon - }; + private List _SuperSlayers = new List() + { + SlayerName.Repond, SlayerName.Silver, SlayerName.Fey, + SlayerName.ElementalBan, SlayerName.Exorcism, SlayerName.ArachnidDoom, + SlayerName.ReptilianDeath, SlayerName.Dinosaur, SlayerName.Myrmidex, + SlayerName.Eodon + }; #region Blood public void AddBlood(Mobile defender, int damage) @@ -3475,7 +3475,7 @@ namespace Server.Items #region Elemental Damage public static int[] GetElementDamages(Mobile m) { - var o = new[] {100, 0, 0, 0, 0, 0, 0}; + var o = new[] { 100, 0, 0, 0, 0, 0, 0 }; var w = m.Weapon as BaseWeapon ?? Fists; @@ -3568,13 +3568,13 @@ namespace Server.Items public virtual void OnMiss(Mobile attacker, IDamageable damageable) { - Mobile defender = damageable as Mobile; + Mobile defender = damageable as Mobile; PlaySwingAnimation(attacker); attacker.PlaySound(GetMissAttackSound(attacker, defender)); - if(defender != null) - defender.PlaySound(GetMissDefendSound(attacker, defender)); + if (defender != null) + defender.PlaySound(GetMissDefendSound(attacker, defender)); WeaponAbility ability = WeaponAbility.GetCurrentAbility(attacker); @@ -3595,7 +3595,7 @@ namespace Server.Items ((IHonorTarget)defender).ReceivedHonorContext.OnTargetMissed(attacker); } - SkillMasterySpell.OnMiss(attacker, defender); + SkillMasterySpell.OnMiss(attacker, defender); } public virtual void GetBaseDamageRange(Mobile attacker, out int min, out int max) @@ -3619,16 +3619,16 @@ namespace Server.Items } } - if (this is Fists && TransformationSpellHelper.UnderTransformation(attacker, typeof(HorrificBeastSpell))) - { - min = 5; - max = 15; - } - else - { - min = MinDamage; - max = MaxDamage; - } + if (this is Fists && TransformationSpellHelper.UnderTransformation(attacker, typeof(HorrificBeastSpell))) + { + min = 5; + max = 15; + } + else + { + min = MinDamage; + max = MaxDamage; + } } public virtual double GetBaseDamage(Mobile attacker) @@ -3705,10 +3705,10 @@ namespace Server.Items public virtual int GetDamageBonus() { - #region Stygian Abyss - if (m_DImodded) - return 0; - #endregion + #region Stygian Abyss + if (m_DImodded) + return 0; + #endregion int bonus = VirtualDamageBonus; @@ -3770,9 +3770,9 @@ namespace Server.Items if (checkSkills) { attacker.CheckSkill(SkillName.Tactics, 0.0, attacker.Skills[SkillName.Tactics].Cap); - // Passively check tactics for gain + // Passively check tactics for gain attacker.CheckSkill(SkillName.Anatomy, 0.0, attacker.Skills[SkillName.Anatomy].Cap); - // Passively check Anatomy for gain + // Passively check Anatomy for gain if (Type == WeaponType.Axe) { @@ -3827,9 +3827,9 @@ namespace Server.Items if (checkSkills) { attacker.CheckSkill(SkillName.Tactics, 0.0, attacker.Skills[SkillName.Tactics].Cap); - // Passively check tactics for gain + // Passively check tactics for gain attacker.CheckSkill(SkillName.Anatomy, 0.0, attacker.Skills[SkillName.Anatomy].Cap); - // Passively check Anatomy for gain + // Passively check Anatomy for gain if (Type == WeaponType.Axe) { @@ -3869,9 +3869,9 @@ namespace Server.Items if (Type == WeaponType.Axe) { double lumberValue = attacker.Skills[SkillName.Lumberjacking].Value; - lumberValue = (lumberValue/5.0)/100.0; - if (lumberValue > 0.2) - lumberValue = 0.2; + lumberValue = (lumberValue / 5.0) / 100.0; + if (lumberValue > 0.2) + lumberValue = 0.2; modifiers += lumberValue; @@ -3936,144 +3936,144 @@ namespace Server.Items return; } - if (Core.SA) - { - from.Animate(AnimationType.Impact, 0); - } - else - { - int action; - int frames; + if (Core.SA) + { + from.Animate(AnimationType.Impact, 0); + } + else + { + int action; + int frames; - switch (from.Body.Type) - { - case BodyType.Sea: - case BodyType.Animal: - { - action = 7; - frames = 5; - break; - } - case BodyType.Monster: - { - action = 10; - frames = 4; - break; - } - case BodyType.Human: - { - action = 20; - frames = 5; - break; - } - default: - return; - } + switch (from.Body.Type) + { + case BodyType.Sea: + case BodyType.Animal: + { + action = 7; + frames = 5; + break; + } + case BodyType.Monster: + { + action = 10; + frames = 4; + break; + } + case BodyType.Human: + { + action = 20; + frames = 5; + break; + } + default: + return; + } - from.Animate(action, frames, 1, true, false, 0); - } - } + from.Animate(action, frames, 1, true, false, 0); + } + } public virtual void PlaySwingAnimation(Mobile from) { int action; - if (Core.SA) - { - action = GetNewAnimationAction(from); + if (Core.SA) + { + action = GetNewAnimationAction(from); - from.Animate(AnimationType.Attack, action); - } - else - { - switch (from.Body.Type) - { - case BodyType.Sea: - case BodyType.Animal: - { - action = Utility.Random(5, 2); - break; - } - case BodyType.Monster: - { - switch (Animation) - { - default: - case WeaponAnimation.Wrestle: - case WeaponAnimation.Bash1H: - case WeaponAnimation.Pierce1H: - case WeaponAnimation.Slash1H: - case WeaponAnimation.Bash2H: - case WeaponAnimation.Pierce2H: - case WeaponAnimation.Slash2H: - action = Utility.Random(4, 3); - break; - case WeaponAnimation.ShootBow: - return; // 7 - case WeaponAnimation.ShootXBow: - return; // 8 - } + from.Animate(AnimationType.Attack, action); + } + else + { + switch (from.Body.Type) + { + case BodyType.Sea: + case BodyType.Animal: + { + action = Utility.Random(5, 2); + break; + } + case BodyType.Monster: + { + switch (Animation) + { + default: + case WeaponAnimation.Wrestle: + case WeaponAnimation.Bash1H: + case WeaponAnimation.Pierce1H: + case WeaponAnimation.Slash1H: + case WeaponAnimation.Bash2H: + case WeaponAnimation.Pierce2H: + case WeaponAnimation.Slash2H: + action = Utility.Random(4, 3); + break; + case WeaponAnimation.ShootBow: + return; // 7 + case WeaponAnimation.ShootXBow: + return; // 8 + } - break; - } - case BodyType.Human: - { - if (!from.Mounted) - { - action = (int)Animation; - } - else - { - switch (Animation) - { - default: - case WeaponAnimation.Wrestle: - case WeaponAnimation.Bash1H: - case WeaponAnimation.Pierce1H: - case WeaponAnimation.Slash1H: - action = 26; - break; - case WeaponAnimation.Bash2H: - case WeaponAnimation.Pierce2H: - case WeaponAnimation.Slash2H: - action = 29; - break; - case WeaponAnimation.ShootBow: - action = 27; - break; - case WeaponAnimation.ShootXBow: - action = 28; - break; - } - } + break; + } + case BodyType.Human: + { + if (!from.Mounted) + { + action = (int)Animation; + } + else + { + switch (Animation) + { + default: + case WeaponAnimation.Wrestle: + case WeaponAnimation.Bash1H: + case WeaponAnimation.Pierce1H: + case WeaponAnimation.Slash1H: + action = 26; + break; + case WeaponAnimation.Bash2H: + case WeaponAnimation.Pierce2H: + case WeaponAnimation.Slash2H: + action = 29; + break; + case WeaponAnimation.ShootBow: + action = 27; + break; + case WeaponAnimation.ShootXBow: + action = 28; + break; + } + } - break; - } - default: - return; - } + break; + } + default: + return; + } - from.Animate(action, 7, 1, true, false, 0); - } + from.Animate(action, 7, 1, true, false, 0); + } } - public int GetNewAnimationAction(Mobile from) - { - switch (Animation) - { - default: - case WeaponAnimation.Wrestle: return 0; - case WeaponAnimation.Bash1H: return 3; - case WeaponAnimation.Pierce1H: return 5; - case WeaponAnimation.Slash1H: return 4; - case WeaponAnimation.Bash2H: return 6; - case WeaponAnimation.Pierce2H: return 8; - case WeaponAnimation.Slash2H: return 7; - case WeaponAnimation.ShootBow: return 1; - case WeaponAnimation.ShootXBow: return 2; - case WeaponAnimation.Throwing: return 9; - } - } + public int GetNewAnimationAction(Mobile from) + { + switch (Animation) + { + default: + case WeaponAnimation.Wrestle: return 0; + case WeaponAnimation.Bash1H: return 3; + case WeaponAnimation.Pierce1H: return 5; + case WeaponAnimation.Slash1H: return 4; + case WeaponAnimation.Bash2H: return 6; + case WeaponAnimation.Pierce2H: return 8; + case WeaponAnimation.Slash2H: return 7; + case WeaponAnimation.ShootBow: return 1; + case WeaponAnimation.ShootXBow: return 2; + case WeaponAnimation.Throwing: return 9; + } + } #region Serialization/Deserialization private static void SetSaveFlag(ref SaveFlag flags, SaveFlag toSet, bool setIf) @@ -4095,34 +4095,34 @@ namespace Server.Items writer.Write(19); // version - // Version 19 - Removes m_SearingWeapon as its handled as a socket now - // Version 18 - removed VvV Item (handled in VvV System) and BlockRepair (Handled as negative attribute) + // Version 19 - Removes m_SearingWeapon as its handled as a socket now + // Version 18 - removed VvV Item (handled in VvV System) and BlockRepair (Handled as negative attribute) - writer.Write(m_UsesRemaining); - writer.Write(m_ShowUsesRemaining); + writer.Write(m_UsesRemaining); + writer.Write(m_ShowUsesRemaining); - writer.Write(_Owner); - writer.Write(_OwnerName); + writer.Write(_Owner); + writer.Write(_OwnerName); - // Version 15 converts old leech to new leech + // Version 15 converts old leech to new leech - //Version 14 - writer.Write(m_IsImbued); + //Version 14 + writer.Write(m_IsImbued); - //version 13, converted SaveFlags to long, added negative attributes + //version 13, converted SaveFlags to long, added negative attributes - //version 12 - #region Runic Reforging - writer.Write((int)m_ReforgedPrefix); - writer.Write((int)m_ReforgedSuffix); - writer.Write((int)m_ItemPower); - #endregion + //version 12 + #region Runic Reforging + writer.Write((int)m_ReforgedPrefix); + writer.Write((int)m_ReforgedSuffix); + writer.Write((int)m_ItemPower); + #endregion - writer.Write(m_DImodded); + writer.Write(m_DImodded); // Version 11 writer.Write(m_TimesImbued); - // Version 10 + // Version 10 writer.Write(m_BlessedBy); // Bless Deed #region Veteran Rewards @@ -4142,38 +4142,38 @@ namespace Server.Items SetSaveFlag(ref sflags, SetFlag.LastEquipped, m_LastEquipped); SetSaveFlag(ref sflags, SetFlag.SetEquipped, m_SetEquipped); SetSaveFlag(ref sflags, SetFlag.SetSelfRepair, m_SetSelfRepair != 0); - SetSaveFlag(ref sflags, SetFlag.PhysicalBonus, m_SetPhysicalBonus != 0); - SetSaveFlag(ref sflags, SetFlag.FireBonus, m_SetFireBonus != 0); - SetSaveFlag(ref sflags, SetFlag.ColdBonus, m_SetColdBonus != 0); - SetSaveFlag(ref sflags, SetFlag.PoisonBonus, m_SetPoisonBonus != 0); - SetSaveFlag(ref sflags, SetFlag.EnergyBonus, m_SetEnergyBonus != 0); + SetSaveFlag(ref sflags, SetFlag.PhysicalBonus, m_SetPhysicalBonus != 0); + SetSaveFlag(ref sflags, SetFlag.FireBonus, m_SetFireBonus != 0); + SetSaveFlag(ref sflags, SetFlag.ColdBonus, m_SetColdBonus != 0); + SetSaveFlag(ref sflags, SetFlag.PoisonBonus, m_SetPoisonBonus != 0); + SetSaveFlag(ref sflags, SetFlag.EnergyBonus, m_SetEnergyBonus != 0); writer.WriteEncodedInt((int)sflags); - if (GetSaveFlag(sflags, SetFlag.PhysicalBonus)) - { - writer.WriteEncodedInt((int)m_SetPhysicalBonus); - } + if (GetSaveFlag(sflags, SetFlag.PhysicalBonus)) + { + writer.WriteEncodedInt((int)m_SetPhysicalBonus); + } - if (GetSaveFlag(sflags, SetFlag.FireBonus)) - { - writer.WriteEncodedInt((int)m_SetFireBonus); - } + if (GetSaveFlag(sflags, SetFlag.FireBonus)) + { + writer.WriteEncodedInt((int)m_SetFireBonus); + } - if (GetSaveFlag(sflags, SetFlag.ColdBonus)) - { - writer.WriteEncodedInt((int)m_SetColdBonus); - } + if (GetSaveFlag(sflags, SetFlag.ColdBonus)) + { + writer.WriteEncodedInt((int)m_SetColdBonus); + } - if (GetSaveFlag(sflags, SetFlag.PoisonBonus)) - { - writer.WriteEncodedInt((int)m_SetPoisonBonus); - } + if (GetSaveFlag(sflags, SetFlag.PoisonBonus)) + { + writer.WriteEncodedInt((int)m_SetPoisonBonus); + } - if (GetSaveFlag(sflags, SetFlag.EnergyBonus)) - { - writer.WriteEncodedInt((int)m_SetEnergyBonus); - } + if (GetSaveFlag(sflags, SetFlag.EnergyBonus)) + { + writer.WriteEncodedInt((int)m_SetEnergyBonus); + } if (GetSaveFlag(sflags, SetFlag.Attributes)) { @@ -4241,11 +4241,11 @@ namespace Server.Items SetSaveFlag(ref flags, SaveFlag.ElementalDamages, !m_AosElementDamages.IsEmpty); SetSaveFlag(ref flags, SaveFlag.EngravedText, !String.IsNullOrEmpty(m_EngravedText)); SetSaveFlag(ref flags, SaveFlag.xAbsorptionAttributes, !m_SAAbsorptionAttributes.IsEmpty); - SetSaveFlag(ref flags, SaveFlag.xNegativeAttributes, !m_NegativeAttributes.IsEmpty); - SetSaveFlag(ref flags, SaveFlag.Altered, m_Altered); - SetSaveFlag(ref flags, SaveFlag.xExtendedWeaponAttributes, !m_ExtendedWeaponAttributes.IsEmpty); + SetSaveFlag(ref flags, SaveFlag.xNegativeAttributes, !m_NegativeAttributes.IsEmpty); + SetSaveFlag(ref flags, SaveFlag.Altered, m_Altered); + SetSaveFlag(ref flags, SaveFlag.xExtendedWeaponAttributes, !m_ExtendedWeaponAttributes.IsEmpty); - writer.Write((long)flags); + writer.Write((long)flags); if (GetSaveFlag(flags, SaveFlag.DamageLevel)) { @@ -4398,16 +4398,16 @@ namespace Server.Items m_SAAbsorptionAttributes.Serialize(writer); } - if (GetSaveFlag(flags, SaveFlag.xNegativeAttributes)) - { - m_NegativeAttributes.Serialize(writer); - } + if (GetSaveFlag(flags, SaveFlag.xNegativeAttributes)) + { + m_NegativeAttributes.Serialize(writer); + } #endregion - if (GetSaveFlag(flags, SaveFlag.xExtendedWeaponAttributes)) - { - m_ExtendedWeaponAttributes.Serialize(writer); - } + if (GetSaveFlag(flags, SaveFlag.xExtendedWeaponAttributes)) + { + m_ExtendedWeaponAttributes.Serialize(writer); + } } [Flags] @@ -4446,10 +4446,10 @@ namespace Server.Items ElementalDamages = 0x20000000, EngravedText = 0x40000000, xAbsorptionAttributes = 0x80000000, - xNegativeAttributes = 0x100000000, - Altered = 0x200000000, - xExtendedWeaponAttributes = 0x400000000 - } + xNegativeAttributes = 0x100000000, + Altered = 0x200000000, + xExtendedWeaponAttributes = 0x400000000 + } #region Mondain's Legacy Sets private static void SetSaveFlag(ref SetFlag flags, SetFlag toSet, bool setIf) @@ -4476,11 +4476,11 @@ namespace Server.Items LastEquipped = 0x00000010, SetEquipped = 0x00000020, SetSelfRepair = 0x00000040, - PhysicalBonus = 0x00000080, - FireBonus = 0x00000100, - ColdBonus = 0x00000200, - PoisonBonus = 0x00000400, - EnergyBonus = 0x00000800, + PhysicalBonus = 0x00000080, + FireBonus = 0x00000100, + ColdBonus = 0x00000200, + PoisonBonus = 0x00000400, + EnergyBonus = 0x00000800, } #endregion @@ -4492,68 +4492,68 @@ namespace Server.Items switch (version) { - case 19: // Removed SearingWeapon - case 18: - case 17: - { - m_UsesRemaining = reader.ReadInt(); - m_ShowUsesRemaining = reader.ReadBool(); - goto case 16; - } - case 16: - { - if(version == 17) - reader.ReadBool(); + case 19: // Removed SearingWeapon + case 18: + case 17: + { + m_UsesRemaining = reader.ReadInt(); + m_ShowUsesRemaining = reader.ReadBool(); + goto case 16; + } + case 16: + { + if (version == 17) + reader.ReadBool(); - _Owner = reader.ReadMobile(); - _OwnerName = reader.ReadString(); - goto case 15; - } - case 15: - case 14: - { - m_IsImbued = reader.ReadBool(); - goto case 13; - } - case 13: - case 12: - { - #region Runic Reforging - m_ReforgedPrefix = (ReforgedPrefix)reader.ReadInt(); - m_ReforgedSuffix = (ReforgedSuffix)reader.ReadInt(); - m_ItemPower = (ItemPower)reader.ReadInt(); + _Owner = reader.ReadMobile(); + _OwnerName = reader.ReadString(); + goto case 15; + } + case 15: + case 14: + { + m_IsImbued = reader.ReadBool(); + goto case 13; + } + case 13: + case 12: + { + #region Runic Reforging + m_ReforgedPrefix = (ReforgedPrefix)reader.ReadInt(); + m_ReforgedSuffix = (ReforgedSuffix)reader.ReadInt(); + m_ItemPower = (ItemPower)reader.ReadInt(); - if (version < 18 && reader.ReadBool()) - { - Timer.DelayCall(TimeSpan.FromSeconds(1), () => - { - m_NegativeAttributes.NoRepair = 1; - }); - } - #endregion + if (version < 18 && reader.ReadBool()) + { + Timer.DelayCall(TimeSpan.FromSeconds(1), () => + { + m_NegativeAttributes.NoRepair = 1; + }); + } + #endregion - #region Stygian Abyss - m_DImodded = reader.ReadBool(); + #region Stygian Abyss + m_DImodded = reader.ReadBool(); - if (version == 18) - { - if (reader.ReadBool()) - { - Timer.DelayCall(TimeSpan.FromSeconds(1), () => - { - AttachSocket(new SearingWeapon(this)); - }); - } - } - goto case 11; - } + if (version == 18) + { + if (reader.ReadBool()) + { + Timer.DelayCall(TimeSpan.FromSeconds(1), () => + { + AttachSocket(new SearingWeapon(this)); + }); + } + } + goto case 11; + } case 11: { m_TimesImbued = reader.ReadInt(); - #endregion + #endregion - goto case 10; + goto case 10; } case 10: { @@ -4562,30 +4562,30 @@ namespace Server.Items m_Slayer3 = (TalismanSlayerName)reader.ReadInt(); SetFlag flags = (SetFlag)reader.ReadEncodedInt(); - if (GetSaveFlag(flags, SetFlag.PhysicalBonus)) - { - m_SetPhysicalBonus = reader.ReadEncodedInt(); - } + if (GetSaveFlag(flags, SetFlag.PhysicalBonus)) + { + m_SetPhysicalBonus = reader.ReadEncodedInt(); + } - if (GetSaveFlag(flags, SetFlag.FireBonus)) - { - m_SetFireBonus = reader.ReadEncodedInt(); - } + if (GetSaveFlag(flags, SetFlag.FireBonus)) + { + m_SetFireBonus = reader.ReadEncodedInt(); + } - if (GetSaveFlag(flags, SetFlag.ColdBonus)) - { - m_SetColdBonus = reader.ReadEncodedInt(); - } + if (GetSaveFlag(flags, SetFlag.ColdBonus)) + { + m_SetColdBonus = reader.ReadEncodedInt(); + } - if (GetSaveFlag(flags, SetFlag.PoisonBonus)) - { - m_SetPoisonBonus = reader.ReadEncodedInt(); - } + if (GetSaveFlag(flags, SetFlag.PoisonBonus)) + { + m_SetPoisonBonus = reader.ReadEncodedInt(); + } - if (GetSaveFlag(flags, SetFlag.EnergyBonus)) - { - m_SetEnergyBonus = reader.ReadEncodedInt(); - } + if (GetSaveFlag(flags, SetFlag.EnergyBonus)) + { + m_SetEnergyBonus = reader.ReadEncodedInt(); + } if (GetSaveFlag(flags, SetFlag.Attributes)) { @@ -4640,10 +4640,10 @@ namespace Server.Items { SaveFlag flags; - if(version < 13) - flags = (SaveFlag)reader.ReadInt(); - else - flags = (SaveFlag)reader.ReadLong(); + if (version < 13) + flags = (SaveFlag)reader.ReadInt(); + else + flags = (SaveFlag)reader.ReadLong(); if (GetSaveFlag(flags, SaveFlag.DamageLevel)) { @@ -4922,37 +4922,37 @@ namespace Server.Items m_SAAbsorptionAttributes = new SAAbsorptionAttributes(this); } - if (version >= 13 && GetSaveFlag(flags, SaveFlag.xNegativeAttributes)) - { - m_NegativeAttributes = new NegativeAttributes(this, reader); - } - else - { - m_NegativeAttributes = new NegativeAttributes(this); - } - #endregion + if (version >= 13 && GetSaveFlag(flags, SaveFlag.xNegativeAttributes)) + { + m_NegativeAttributes = new NegativeAttributes(this, reader); + } + else + { + m_NegativeAttributes = new NegativeAttributes(this); + } + #endregion - if (GetSaveFlag(flags, SaveFlag.Altered)) - { - m_Altered = true; - } + if (GetSaveFlag(flags, SaveFlag.Altered)) + { + m_Altered = true; + } - if (GetSaveFlag(flags, SaveFlag.xExtendedWeaponAttributes)) - { - m_ExtendedWeaponAttributes = new ExtendedWeaponAttributes(this, reader); - } - else - { - m_ExtendedWeaponAttributes = new ExtendedWeaponAttributes(this); - } + if (GetSaveFlag(flags, SaveFlag.xExtendedWeaponAttributes)) + { + m_ExtendedWeaponAttributes = new ExtendedWeaponAttributes(this, reader); + } + else + { + m_ExtendedWeaponAttributes = new ExtendedWeaponAttributes(this); + } - if (Core.TOL && m_ExtendedWeaponAttributes.MysticWeapon != 0 && m_ExtendedWeaponAttributes.MysticWeapon != 30 && Parent is Mobile) - { - m_MysticMod = new DefaultSkillMod(SkillName.Mysticism, true, -30 + m_ExtendedWeaponAttributes.MysticWeapon); - ((Mobile)Parent).AddSkillMod(m_MysticMod); - } + if (Core.TOL && m_ExtendedWeaponAttributes.MysticWeapon != 0 && m_ExtendedWeaponAttributes.MysticWeapon != 30 && Parent is Mobile) + { + m_MysticMod = new DefaultSkillMod(SkillName.Mysticism, true, -30 + m_ExtendedWeaponAttributes.MysticWeapon); + ((Mobile)Parent).AddSkillMod(m_MysticMod); + } - break; + break; } case 4: { @@ -5087,13 +5087,13 @@ namespace Server.Items } } - if (version < 15) - { - if (WeaponAttributes.HitLeechHits > 0 || WeaponAttributes.HitLeechMana > 0) - { - WeaponAttributes.ScaleLeech(Attributes.WeaponSpeed); - } - } + if (version < 15) + { + if (WeaponAttributes.HitLeechHits > 0 || WeaponAttributes.HitLeechMana > 0) + { + WeaponAttributes.ScaleLeech(Attributes.WeaponSpeed); + } + } #region Mondain's Legacy Sets if (m_SetAttributes == null) @@ -5153,11 +5153,11 @@ namespace Server.Items m_PlayerConstructed = true; // we don't know, so, assume it's crafted } - if (m_Slayer == SlayerName.DaemonDismissal || m_Slayer == SlayerName.BalronDamnation) - m_Slayer = SlayerName.Exorcism; + if (m_Slayer == SlayerName.DaemonDismissal || m_Slayer == SlayerName.BalronDamnation) + m_Slayer = SlayerName.Exorcism; - if (m_Slayer2 == SlayerName.DaemonDismissal || m_Slayer2 == SlayerName.BalronDamnation) - m_Slayer2 = SlayerName.Exorcism; + if (m_Slayer2 == SlayerName.DaemonDismissal || m_Slayer2 == SlayerName.BalronDamnation) + m_Slayer2 = SlayerName.Exorcism; } #endregion @@ -5188,8 +5188,8 @@ namespace Server.Items m_AosWeaponAttributes = new AosWeaponAttributes(this); m_AosSkillBonuses = new AosSkillBonuses(this); m_AosElementDamages = new AosElementAttributes(this); - m_NegativeAttributes = new NegativeAttributes(this); - m_ExtendedWeaponAttributes = new ExtendedWeaponAttributes(this); + m_NegativeAttributes = new NegativeAttributes(this); + m_ExtendedWeaponAttributes = new ExtendedWeaponAttributes(this); #region Stygian Abyss m_SAAbsorptionAttributes = new SAAbsorptionAttributes(this); @@ -5202,14 +5202,14 @@ namespace Server.Items m_AosSkillBonuses = new AosSkillBonuses(this); - if (this is ITool) - { - m_UsesRemaining = Utility.RandomMinMax(25, 75); - } - else - { - m_UsesRemaining = 150; - } + if (this is ITool) + { + m_UsesRemaining = Utility.RandomMinMax(25, 75); + } + else + { + m_UsesRemaining = 150; + } } public BaseWeapon(Serial serial) @@ -5277,11 +5277,11 @@ namespace Server.Items public override void AddNameProperty(ObjectPropertyList list) { - if (m_ExtendedWeaponAttributes.AssassinHoned > 0) - { - list.Add(1152207); // Assassin's Edge - return; - } + if (m_ExtendedWeaponAttributes.AssassinHoned > 0) + { + list.Add(1152207); // Assassin's Edge + return; + } int oreType; @@ -5339,7 +5339,7 @@ namespace Server.Items oreType = 1060815; break; // blue - #region Mondain's Legacy + #region Mondain's Legacy case CraftResource.OakWood: oreType = 1072533; break; // oak @@ -5358,47 +5358,47 @@ namespace Server.Items case CraftResource.Frostwood: oreType = 1072539; break; // frostwood - #endregion + #endregion default: oreType = 0; break; } - if (m_ReforgedPrefix != ReforgedPrefix.None || m_ReforgedSuffix != ReforgedSuffix.None) - { - if (m_ReforgedPrefix != ReforgedPrefix.None) - { - int prefix = RunicReforging.GetPrefixName(m_ReforgedPrefix); + if (m_ReforgedPrefix != ReforgedPrefix.None || m_ReforgedSuffix != ReforgedSuffix.None) + { + if (m_ReforgedPrefix != ReforgedPrefix.None) + { + int prefix = RunicReforging.GetPrefixName(m_ReforgedPrefix); - if (m_ReforgedSuffix == ReforgedSuffix.None) - list.Add(1151757, String.Format("#{0}\t{1}", prefix, GetNameString())); // ~1_PREFIX~ ~2_ITEM~ - else - list.Add(1151756, String.Format("#{0}\t{1}\t#{2}", prefix, GetNameString(), RunicReforging.GetSuffixName(m_ReforgedSuffix))); // ~1_PREFIX~ ~2_ITEM~ of ~3_SUFFIX~ - } - else if (m_ReforgedSuffix != ReforgedSuffix.None) - { - RunicReforging.AddSuffixName(list, m_ReforgedSuffix, GetNameString()); - } - } + if (m_ReforgedSuffix == ReforgedSuffix.None) + list.Add(1151757, String.Format("#{0}\t{1}", prefix, GetNameString())); // ~1_PREFIX~ ~2_ITEM~ + else + list.Add(1151756, String.Format("#{0}\t{1}\t#{2}", prefix, GetNameString(), RunicReforging.GetSuffixName(m_ReforgedSuffix))); // ~1_PREFIX~ ~2_ITEM~ of ~3_SUFFIX~ + } + else if (m_ReforgedSuffix != ReforgedSuffix.None) + { + RunicReforging.AddSuffixName(list, m_ReforgedSuffix, GetNameString()); + } + } else if (oreType != 0) { list.Add(1053099, "#{0}\t{1}", oreType, GetNameString()); // ~1_oretype~ ~2_armortype~ - } - #region High Seas - else if (SearingWeapon) - { - list.Add(1151318, String.Format("#{0}", LabelNumber)); - } - #endregion - else if (Name == null) - { - list.Add(LabelNumber); - } - else - { - list.Add(Name); - } + } + #region High Seas + else if (SearingWeapon) + { + list.Add(1151318, String.Format("#{0}", LabelNumber)); + } + #endregion + else if (Name == null) + { + list.Add(LabelNumber); + } + else + { + list.Add(Name); + } /* * Want to move this to the engraving tool, let the non-harmful @@ -5415,7 +5415,7 @@ namespace Server.Items if (!String.IsNullOrEmpty(m_EngravedText)) { - list.Add(1062613, Utility.FixHtml(m_EngravedText)); + list.Add(1062613, Utility.FixHtml(m_EngravedText)); } } @@ -5426,21 +5426,21 @@ namespace Server.Items return true; } - return m_AosAttributes.SpellChanneling > 0 || Enhancement.GetValue(from, AosAttribute.SpellChanneling) > 0; + return m_AosAttributes.SpellChanneling > 0 || Enhancement.GetValue(from, AosAttribute.SpellChanneling) > 0; } public virtual int ArtifactRarity { get { return 0; } } - public override bool DisplayWeight - { - get - { - if (IsVvVItem) - return true; + public override bool DisplayWeight + { + get + { + if (IsVvVItem) + return true; - return base.DisplayWeight; - } - } + return base.DisplayWeight; + } + } public virtual int GetLuckBonus() { @@ -5468,56 +5468,66 @@ namespace Server.Items return attrInfo.WeaponLuck; } - public override void AddCraftedProperties(ObjectPropertyList list) - { - if (OwnerName != null) - { - list.Add(1153213, OwnerName); - } + public override void AddCraftedProperties(ObjectPropertyList list) + { + if (OwnerName != null) + { + list.Add(1153213, OwnerName); + } - if (m_Crafter != null) - { - list.Add(1050043, m_Crafter.TitleName); // crafted by ~1_NAME~ - } + if (m_Crafter != null) + { + list.Add(1050043, m_Crafter.TitleName); // crafted by ~1_NAME~ + } - if (m_Quality == ItemQuality.Exceptional) - { - list.Add(1060636); // Exceptional - } + if (m_Quality == ItemQuality.Exceptional) + { + list.Add(1060636); // Exceptional + } - if (IsImbued) - { - list.Add(1080418); // (Imbued) - } + if (IsImbued) + { + list.Add(1080418); // (Imbued) + } - if (m_Altered) - { - list.Add(1111880); // Altered - } - } + if (m_Altered) + { + list.Add(1111880); // Altered + } + } - public override void AddWeightProperty(ObjectPropertyList list) - { - base.AddWeightProperty(list); + public override void AddWeightProperty(ObjectPropertyList list) + { + base.AddWeightProperty(list); - if (IsVvVItem) - list.Add(1154937); // VvV Item - } + if (IsVvVItem) + list.Add(1154937); // VvV Item + } - public override void AddUsesRemainingProperties(ObjectPropertyList list) - { - if (ShowUsesRemaining) - { - list.Add(1060584, UsesRemaining.ToString()); // uses remaining: ~1_val~ - } - } + public override void AddUsesRemainingProperties(ObjectPropertyList list) + { + if (ShowUsesRemaining) + { + list.Add(1060584, UsesRemaining.ToString()); // uses remaining: ~1_val~ + } + } - public override void AddNameProperties(ObjectPropertyList list) - { - base.AddNameProperties(list); + public override void AddNameProperties(ObjectPropertyList list) + { + base.AddNameProperties(list); + // =============================================== + // DURABILITY TOOLTIP: TEMPERED / REPAIR LOCKED + // =============================================== + var dura = XmlAttach.FindAttachment(this, typeof(Server.Custom.DurabilityAttachment)) + as Server.Custom.DurabilityAttachment; - #region Factions - FactionEquipment.AddFactionProperties(this, list); + if (dura != null && dura.RepairLocked) + { + list.Add("Tempered — Cannot be repaired"); + } + + #region Factions + FactionEquipment.AddFactionProperties(this, list); #endregion #region Mondain's Legacy Sets @@ -5525,37 +5535,37 @@ namespace Server.Items { list.Add(1073491, Pieces.ToString()); // Part of a Weapon/Armor Set (~1_val~ pieces) - if (SetID == SetItem.Bestial) - list.Add(1151541, BestialSetHelper.GetTotalBerserk(this).ToString()); // Berserk ~1_VAL~ + if (SetID == SetItem.Bestial) + list.Add(1151541, BestialSetHelper.GetTotalBerserk(this).ToString()); // Berserk ~1_VAL~ - if (BardMasteryBonus) - list.Add(1151553); // Activate: Bard Mastery Bonus x2
(Effect: 1 min. Cooldown: 30 min.) + if (BardMasteryBonus) + list.Add(1151553); // Activate: Bard Mastery Bonus x2
(Effect: 1 min. Cooldown: 30 min.) - if (m_SetEquipped) + if (m_SetEquipped) { list.Add(1073492); // Full Weapon/Armor Set Present GetSetProperties(list); } } - #endregion + #endregion - if (m_ExtendedWeaponAttributes.Focus > 0) - { - list.Add(1150018); // Focus - } + if (m_ExtendedWeaponAttributes.Focus > 0) + { + list.Add(1150018); // Focus + } - if (m_NegativeAttributes.Brittle == 0 && m_AosAttributes.Brittle != 0) - { - list.Add(1116209); // Brittle - } + if (m_NegativeAttributes.Brittle == 0 && m_AosAttributes.Brittle != 0) + { + list.Add(1116209); // Brittle + } - if (m_NegativeAttributes != null) - m_NegativeAttributes.GetProperties(list, this); + if (m_NegativeAttributes != null) + m_NegativeAttributes.GetProperties(list, this); if (m_AosSkillBonuses != null) { m_AosSkillBonuses.GetProperties(list); - } + } if (RequiredRace == Race.Elf) { @@ -5574,7 +5584,7 @@ namespace Server.Items list.Add(1061078, ArtifactRarity.ToString()); // artifact rarity ~1_val~ } - if (m_Poison != null && m_PoisonCharges > 0 && CanShowPoisonCharges()) + if (m_Poison != null && m_PoisonCharges > 0 && CanShowPoisonCharges()) { #region Mondain's Legacy mod list.Add(m_Poison.LabelNumber, m_PoisonCharges.ToString()); @@ -5621,209 +5631,209 @@ namespace Server.Items } #endregion - if (HasSocket()) - { - list.Add(1158662); // Caddellite Infused - } + if (HasSocket()) + { + list.Add(1158662); // Caddellite Infused + } - double focusBonus = 1; - int enchantBonus = 0; - bool fcMalus = false; - int damBonus = 0; - SpecialMove move = null; - AosWeaponAttribute bonus = AosWeaponAttribute.HitColdArea; + double focusBonus = 1; + int enchantBonus = 0; + bool fcMalus = false; + int damBonus = 0; + SpecialMove move = null; + AosWeaponAttribute bonus = AosWeaponAttribute.HitColdArea; - #region Focus Attack - if (FocusWeilder != null) - { - move = SpecialMove.GetCurrentMove(FocusWeilder); + #region Focus Attack + if (FocusWeilder != null) + { + move = SpecialMove.GetCurrentMove(FocusWeilder); - if (move is FocusAttack) - { - focusBonus = move.GetPropertyBonus(FocusWeilder); - damBonus = (int)(move.GetDamageScalar(FocusWeilder, null) * 100) - 100; - } - } - #endregion + if (move is FocusAttack) + { + focusBonus = move.GetPropertyBonus(FocusWeilder); + damBonus = (int)(move.GetDamageScalar(FocusWeilder, null) * 100) - 100; + } + } + #endregion - #region Stygian Abyss - if (EnchantedWeilder != null) - { - if (Server.Spells.Mysticism.EnchantSpell.IsUnderSpellEffects(EnchantedWeilder, this)) - { - bonus = Server.Spells.Mysticism.EnchantSpell.BonusAttribute(EnchantedWeilder); - enchantBonus = Server.Spells.Mysticism.EnchantSpell.BonusValue(EnchantedWeilder); - fcMalus = Server.Spells.Mysticism.EnchantSpell.CastingMalus(EnchantedWeilder, this); - } - } - #endregion + #region Stygian Abyss + if (EnchantedWeilder != null) + { + if (Server.Spells.Mysticism.EnchantSpell.IsUnderSpellEffects(EnchantedWeilder, this)) + { + bonus = Server.Spells.Mysticism.EnchantSpell.BonusAttribute(EnchantedWeilder); + enchantBonus = Server.Spells.Mysticism.EnchantSpell.BonusValue(EnchantedWeilder); + fcMalus = Server.Spells.Mysticism.EnchantSpell.CastingMalus(EnchantedWeilder, this); + } + } + #endregion - int prop; - double fprop; + int prop; + double fprop; - if ((prop = m_AosWeaponAttributes.DurabilityBonus) != 0) - { - list.Add(1151780, prop.ToString()); // durability +~1_VAL~% - } + if ((prop = m_AosWeaponAttributes.DurabilityBonus) != 0) + { + list.Add(1151780, prop.ToString()); // durability +~1_VAL~% + } - if (Core.TOL) - { - if (m_ExtendedWeaponAttributes.Bane > 0) - { - list.Add(1154671); // Bane - } + if (Core.TOL) + { + if (m_ExtendedWeaponAttributes.Bane > 0) + { + list.Add(1154671); // Bane + } - if (m_ExtendedWeaponAttributes.BoneBreaker > 0) - { - list.Add(1157318); // Bone Breaker - } + if (m_ExtendedWeaponAttributes.BoneBreaker > 0) + { + list.Add(1157318); // Bone Breaker + } - if ((prop = m_ExtendedWeaponAttributes.HitSwarm) != 0) - { - list.Add(1157325, prop.ToString()); // Swarm ~1_val~% - } + if ((prop = m_ExtendedWeaponAttributes.HitSwarm) != 0) + { + list.Add(1157325, prop.ToString()); // Swarm ~1_val~% + } - if ((prop = m_ExtendedWeaponAttributes.HitSparks) != 0) - { - list.Add(1157326, prop.ToString()); // Sparks ~1_val~% - } + if ((prop = m_ExtendedWeaponAttributes.HitSparks) != 0) + { + list.Add(1157326, prop.ToString()); // Sparks ~1_val~% + } - if ((prop = m_ExtendedWeaponAttributes.AssassinHoned) != 0) - { - list.Add(1152206); // Assassin Honed - } - } + if ((prop = m_ExtendedWeaponAttributes.AssassinHoned) != 0) + { + list.Add(1152206); // Assassin Honed + } + } - if ((prop = m_AosWeaponAttributes.SplinteringWeapon) != 0) - { - list.Add(1112857, prop.ToString()); //splintering weapon ~1_val~% - } + if ((prop = m_AosWeaponAttributes.SplinteringWeapon) != 0) + { + list.Add(1112857, prop.ToString()); //splintering weapon ~1_val~% + } - if ((fprop = (double)m_AosWeaponAttributes.HitDispel * focusBonus) != 0) + if ((fprop = (double)m_AosWeaponAttributes.HitDispel * focusBonus) != 0) { list.Add(1060417, ((int)fprop).ToString()); // hit dispel ~1_val~% } - else if (bonus == AosWeaponAttribute.HitDispel && enchantBonus != 0) - { - list.Add(1060417, ((int)(enchantBonus * focusBonus)).ToString()); // hit dispel ~1_val~% - } + else if (bonus == AosWeaponAttribute.HitDispel && enchantBonus != 0) + { + list.Add(1060417, ((int)(enchantBonus * focusBonus)).ToString()); // hit dispel ~1_val~% + } - if ((fprop = (double)m_AosWeaponAttributes.HitFireball * focusBonus) != 0) + if ((fprop = (double)m_AosWeaponAttributes.HitFireball * focusBonus) != 0) { list.Add(1060420, ((int)fprop).ToString()); // hit fireball ~1_val~% } - else if (bonus == AosWeaponAttribute.HitFireball && enchantBonus != 0) - { - list.Add(1060420, ((int)((double)enchantBonus * focusBonus)).ToString()); // hit fireball ~1_val~% - } - + else if (bonus == AosWeaponAttribute.HitFireball && enchantBonus != 0) + { + list.Add(1060420, ((int)((double)enchantBonus * focusBonus)).ToString()); // hit fireball ~1_val~% + } + if ((fprop = (double)m_AosWeaponAttributes.HitLightning * focusBonus) != 0) { list.Add(1060423, ((int)fprop).ToString()); // hit lightning ~1_val~% } - else if (bonus == AosWeaponAttribute.HitLightning && enchantBonus != 0) - { - list.Add(1060423, ((int)(enchantBonus * focusBonus)).ToString()); // hit lightning ~1_val~% - } + else if (bonus == AosWeaponAttribute.HitLightning && enchantBonus != 0) + { + list.Add(1060423, ((int)(enchantBonus * focusBonus)).ToString()); // hit lightning ~1_val~% + } - if ((fprop = (double)m_AosWeaponAttributes.HitHarm * focusBonus) != 0) + if ((fprop = (double)m_AosWeaponAttributes.HitHarm * focusBonus) != 0) { list.Add(1060421, ((int)fprop).ToString()); // hit harm ~1_val~% } - else if (bonus == AosWeaponAttribute.HitHarm && enchantBonus != 0) - { - list.Add(1060421, ((int)(enchantBonus * focusBonus)).ToString()); // hit harm ~1_val~% - } + else if (bonus == AosWeaponAttribute.HitHarm && enchantBonus != 0) + { + list.Add(1060421, ((int)(enchantBonus * focusBonus)).ToString()); // hit harm ~1_val~% + } - if ((fprop = (double)m_ExtendedWeaponAttributes.HitExplosion * focusBonus) != 0) - { - list.Add(1158922, ((int)fprop).ToString()); // hit explosion ~1_val~% - } + if ((fprop = (double)m_ExtendedWeaponAttributes.HitExplosion * focusBonus) != 0) + { + list.Add(1158922, ((int)fprop).ToString()); // hit explosion ~1_val~% + } - if (SearingWeapon) - { - list.Add(1151183); // Searing Weapon - } + if (SearingWeapon) + { + list.Add(1151183); // Searing Weapon + } - if ((fprop = (double)m_AosWeaponAttributes.HitMagicArrow * focusBonus) != 0) + if ((fprop = (double)m_AosWeaponAttributes.HitMagicArrow * focusBonus) != 0) { list.Add(1060426, ((int)fprop).ToString()); // hit magic arrow ~1_val~% } - else if (bonus == AosWeaponAttribute.HitMagicArrow && enchantBonus != 0) - { - list.Add(1060426, ((int)(enchantBonus * focusBonus)).ToString()); // hit magic arrow ~1_val~% - } - + else if (bonus == AosWeaponAttribute.HitMagicArrow && enchantBonus != 0) + { + list.Add(1060426, ((int)(enchantBonus * focusBonus)).ToString()); // hit magic arrow ~1_val~% + } + if ((fprop = (double)m_AosWeaponAttributes.HitPhysicalArea * focusBonus) != 0) { list.Add(1060428, ((int)fprop).ToString()); // hit physical area ~1_val~% } - + if ((fprop = (double)m_AosWeaponAttributes.HitFireArea * focusBonus) != 0) { list.Add(1060419, ((int)fprop).ToString()); // hit fire area ~1_val~% } - + if ((fprop = (double)m_AosWeaponAttributes.HitColdArea * focusBonus) != 0) { list.Add(1060416, ((int)fprop).ToString()); // hit cold area ~1_val~% } - if ((fprop = (double)m_AosWeaponAttributes.HitPoisonArea * focusBonus) != 0) + if ((fprop = (double)m_AosWeaponAttributes.HitPoisonArea * focusBonus) != 0) { list.Add(1060429, ((int)fprop).ToString()); // hit poison area ~1_val~% } - + if ((fprop = (double)m_AosWeaponAttributes.HitEnergyArea * focusBonus) != 0) { list.Add(1060418, ((int)fprop).ToString()); // hit energy area ~1_val~% } - + if ((fprop = (double)m_AosWeaponAttributes.HitLeechStam * focusBonus) != 0) { - list.Add(1060430, Math.Min(100, (int)fprop).ToString()); // hit stamina leech ~1_val~% + list.Add(1060430, Math.Min(100, (int)fprop).ToString()); // hit stamina leech ~1_val~% } - if ((fprop = (double)m_AosWeaponAttributes.HitLeechMana * focusBonus) != 0) + if ((fprop = (double)m_AosWeaponAttributes.HitLeechMana * focusBonus) != 0) { list.Add(1060427, Math.Min(100, (int)fprop).ToString()); // hit mana leech ~1_val~% } - + if ((fprop = (double)m_AosWeaponAttributes.HitLeechHits * focusBonus) != 0) { - list.Add(1060422, Math.Min(100, (int)fprop).ToString()); // hit life leech ~1_val~% + list.Add(1060422, Math.Min(100, (int)fprop).ToString()); // hit life leech ~1_val~% } - + if ((fprop = (double)m_AosWeaponAttributes.HitFatigue * focusBonus) != 0) { list.Add(1113700, ((int)fprop).ToString()); // Hit Fatigue ~1_val~% } - + if ((fprop = (double)m_AosWeaponAttributes.HitManaDrain * focusBonus) != 0) { list.Add(1113699, ((int)fprop).ToString()); // Hit Mana Drain ~1_val~% } - + if ((fprop = (double)m_AosWeaponAttributes.HitCurse * focusBonus) != 0) { list.Add(1113712, ((int)fprop).ToString()); // Hit Curse ~1_val~% } - + if ((fprop = (double)m_AosWeaponAttributes.HitLowerAttack * focusBonus) != 0) { list.Add(1060424, ((int)fprop).ToString()); // hit lower attack ~1_val~% } - + if ((fprop = (double)m_AosWeaponAttributes.HitLowerDefend * focusBonus) != 0) { list.Add(1060425, ((int)fprop).ToString()); // hit lower defense ~1_val~% } - + if ((prop = m_AosWeaponAttributes.BloodDrinker) != 0) { list.Add(1113591, prop.ToString()); // Blood Drinker } - + if ((prop = m_AosWeaponAttributes.BattleLust) != 0) { list.Add(1113710, prop.ToString()); // Battle Lust @@ -5844,135 +5854,135 @@ namespace Server.Items list.Add(1075208, prop.ToString()); // Lower Ammo Cost ~1_Percentage~% } - if ((prop = m_ExtendedWeaponAttributes.MysticWeapon) != 0) - { - list.Add(1155881, (30 - prop).ToString()); // mystic weapon -~1_val~ skill - } - else if ((prop = Parent is Mobile ? Enhancement.GetValue((Mobile)Parent, ExtendedWeaponAttribute.MysticWeapon) : 0) != 0) - { - list.Add(1155881, (30 - prop).ToString()); // mystic weapon -~1_val~ skill - } + if ((prop = m_ExtendedWeaponAttributes.MysticWeapon) != 0) + { + list.Add(1155881, (30 - prop).ToString()); // mystic weapon -~1_val~ skill + } + else if ((prop = Parent is Mobile ? Enhancement.GetValue((Mobile)Parent, ExtendedWeaponAttribute.MysticWeapon) : 0) != 0) + { + list.Add(1155881, (30 - prop).ToString()); // mystic weapon -~1_val~ skill + } if ((prop = m_AosWeaponAttributes.SelfRepair) != 0) { list.Add(1060450, prop.ToString()); // self repair ~1_val~ } - + if ((prop = m_AosAttributes.NightSight) != 0) { list.Add(1060441); // night sight } - if ((prop = fcMalus ? 1 : m_AosAttributes.SpellChanneling) != 0) + if ((prop = fcMalus ? 1 : m_AosAttributes.SpellChanneling) != 0) { list.Add(1060482); // spell channeling } - + if ((prop = m_AosWeaponAttributes.MageWeapon) != 0) { list.Add(1060438, (30 - prop).ToString()); // mage weapon -~1_val~ skill } - + if (Core.ML && m_AosAttributes.BalancedWeapon > 0 && Layer == Layer.TwoHanded) { list.Add(1072792); // Balanced } - + if ((prop = (GetLuckBonus() + m_AosAttributes.Luck)) != 0) { list.Add(1060436, prop.ToString()); // luck ~1_val~ } - + if ((prop = m_AosAttributes.EnhancePotions) != 0) { list.Add(1060411, prop.ToString()); // enhance potions ~1_val~% } - + if ((prop = m_AosWeaponAttributes.ReactiveParalyze) != 0) - { - list.Add(1112364); // reactive paralyze - } - + { + list.Add(1112364); // reactive paralyze + } + if ((prop = m_AosAttributes.BonusStr) != 0) { list.Add(1060485, prop.ToString()); // strength bonus ~1_val~ } - + if ((prop = m_AosAttributes.BonusInt) != 0) { list.Add(1060432, prop.ToString()); // intelligence bonus ~1_val~ } - + if ((prop = m_AosAttributes.BonusDex) != 0) { list.Add(1060409, prop.ToString()); // dexterity bonus ~1_val~ } - + if ((prop = m_AosAttributes.BonusHits) != 0) { list.Add(1060431, prop.ToString()); // hit point increase ~1_val~ } - + if ((prop = m_AosAttributes.BonusStam) != 0) { list.Add(1060484, prop.ToString()); // stamina increase ~1_val~ } - + if ((prop = m_AosAttributes.BonusMana) != 0) { list.Add(1060439, prop.ToString()); // mana increase ~1_val~ } - + if ((prop = m_AosAttributes.RegenHits) != 0) { list.Add(1060444, prop.ToString()); // hit point regeneration ~1_val~ } - + if ((prop = m_AosAttributes.RegenStam) != 0) { list.Add(1060443, prop.ToString()); // stamina regeneration ~1_val~ } - + if ((prop = m_AosAttributes.RegenMana) != 0) { list.Add(1060440, prop.ToString()); // mana regeneration ~1_val~ } - + if ((prop = m_AosAttributes.ReflectPhysical) != 0) { list.Add(1060442, prop.ToString()); // reflect physical damage ~1_val~% } - + if ((prop = m_AosAttributes.SpellDamage) != 0) { list.Add(1060483, prop.ToString()); // spell damage increase ~1_val~% } - + if ((prop = m_AosAttributes.CastRecovery) != 0) { list.Add(1060412, prop.ToString()); // faster cast recovery ~1_val~ } - if ((prop = fcMalus ? m_AosAttributes.CastSpeed - 1 : m_AosAttributes.CastSpeed) != 0) + if ((prop = fcMalus ? m_AosAttributes.CastSpeed - 1 : m_AosAttributes.CastSpeed) != 0) { list.Add(1060413, prop.ToString()); // faster casting ~1_val~ } - + if ((prop = (GetHitChanceBonus() + m_AosAttributes.AttackChance)) != 0) { list.Add(1060415, prop.ToString()); // hit chance increase ~1_val~% } - + if ((prop = m_AosAttributes.DefendChance) != 0) { list.Add(1060408, prop.ToString()); // defense chance increase ~1_val~% } - + if ((prop = m_AosAttributes.LowerManaCost) != 0) { list.Add(1060433, prop.ToString()); // lower mana cost ~1_val~% } - + if ((prop = m_AosAttributes.LowerRegCost) != 0) { list.Add(1060434, prop.ToString()); // lower reagent cost ~1_val~% @@ -5982,7 +5992,7 @@ namespace Server.Items { list.Add(1060486, prop.ToString()); // swing speed increase ~1_val~% } - + if ((prop = (GetDamageBonus() + m_AosAttributes.WeaponDamage + damBonus)) != 0) { list.Add(1060401, prop.ToString()); // damage increase ~1_val~% @@ -6054,14 +6064,14 @@ namespace Server.Items list.Add(1113695, prop.ToString()); // Kinetic Resonance ~1_val~% } #endregion - + base.AddResistanceProperties(list); - + if ((prop = GetLowerStatReq()) != 0) { list.Add(1060435, prop.ToString()); // lower requirements ~1_val~% } - + if ((prop = m_AosWeaponAttributes.UseBestSkill) != 0) { list.Add(1060400); // use best weapon skill @@ -6116,9 +6126,9 @@ namespace Server.Items if (Core.ML && direct != 0) { list.Add(1079978, direct.ToString()); // Direct Damage: ~1_PERCENT~% - } + } - list.Add(1061168, "{0}\t{1}", MinDamage.ToString(), MaxDamage.ToString()); // weapon damage ~1_val~ - ~2_val~ + list.Add(1061168, "{0}\t{1}", MinDamage.ToString(), MaxDamage.ToString()); // weapon damage ~1_val~ - ~2_val~ if (Core.ML) { @@ -6166,10 +6176,10 @@ namespace Server.Items case SkillName.Archery: list.Add(1061175); break; // skill required: archery - case SkillName.Throwing: - list.Add(1112075); // skill required: throwing - break; - } + case SkillName.Throwing: + list.Add(1112075); // skill required: throwing + break; + } } XmlAttach.AddAttachmentProperties(this, list); @@ -6185,32 +6195,32 @@ namespace Server.Items GetSetProperties(list); } - if (Core.EJ && LastParryChance > 0) - { - list.Add(1158861, LastParryChance.ToString()); // Last Parry Chance: ~1_val~% - } - } + if (Core.EJ && LastParryChance > 0) + { + list.Add(1158861, LastParryChance.ToString()); // Last Parry Chance: ~1_val~% + } + } - public override void AddItemPowerProperties(ObjectPropertyList list) - { - if (m_ItemPower != ItemPower.None) - { - if (m_ItemPower <= ItemPower.LegendaryArtifact) - list.Add(1151488 + ((int)m_ItemPower - 1)); - else - list.Add(1152281 + ((int)m_ItemPower - 9)); - } - } + public override void AddItemPowerProperties(ObjectPropertyList list) + { + if (m_ItemPower != ItemPower.None) + { + if (m_ItemPower <= ItemPower.LegendaryArtifact) + list.Add(1151488 + ((int)m_ItemPower - 1)); + else + list.Add(1152281 + ((int)m_ItemPower - 9)); + } + } - public bool CanShowPoisonCharges() - { - if (PrimaryAbility == WeaponAbility.InfectiousStrike || SecondaryAbility == WeaponAbility.InfectiousStrike) - return true; + public bool CanShowPoisonCharges() + { + if (PrimaryAbility == WeaponAbility.InfectiousStrike || SecondaryAbility == WeaponAbility.InfectiousStrike) + return true; - return RootParent is Mobile && SkillMasterySpell.HasSpell((Mobile)RootParent, typeof(InjectedStrikeSpell)); - } + return RootParent is Mobile && SkillMasterySpell.HasSpell((Mobile)RootParent, typeof(InjectedStrikeSpell)); + } - public override void OnSingleClick(Mobile from) + public override void OnSingleClick(Mobile from) { var attrs = new List(); @@ -6307,14 +6317,14 @@ namespace Server.Items from.Send(new DisplayEquipmentInfo(this, eqInfo)); } - public override bool DropToWorld(Mobile from, Point3D p) - { - bool drop = base.DropToWorld(from, p); + public override bool DropToWorld(Mobile from, Point3D p) + { + bool drop = base.DropToWorld(from, p); - EnchantedHotItemSocket.CheckDrop(from, this); + EnchantedHotItemSocket.CheckDrop(from, this); - return drop; - } + return drop; + } public static BaseWeapon Fists { get; set; } @@ -6367,7 +6377,7 @@ namespace Server.Items if (Core.ML && Quality == ItemQuality.Exceptional) { - double div = Siege.SiegeShard ? 12.5 : 20; + double div = Siege.SiegeShard ? 12.5 : 20; Attributes.WeaponDamage += (int)(from.Skills.ArmsLore.Value / div); from.CheckSkill(SkillName.ArmsLore, 0, 100); @@ -6468,36 +6478,36 @@ namespace Server.Items return quality; } - DistributeMaterialBonus(attrInfo); + DistributeMaterialBonus(attrInfo); } - #endregion + #endregion return quality; } - public virtual void DistributeMaterialBonus(CraftAttributeInfo attrInfo) - { - if (m_Resource != CraftResource.Heartwood) - { - m_AosAttributes.WeaponDamage += attrInfo.WeaponDamage; - m_AosAttributes.WeaponSpeed += attrInfo.WeaponSwingSpeed; - m_AosAttributes.AttackChance += attrInfo.WeaponHitChance; - m_AosAttributes.RegenHits += attrInfo.WeaponRegenHits; - m_AosWeaponAttributes.HitLeechHits += attrInfo.WeaponHitLifeLeech; - } - else - { - switch (Utility.Random(6)) - { - case 0: m_AosAttributes.WeaponDamage += attrInfo.WeaponDamage; break; - case 1: m_AosAttributes.WeaponSpeed += attrInfo.WeaponSwingSpeed; break; - case 2: m_AosAttributes.AttackChance += attrInfo.WeaponHitChance; break; - case 3: m_AosAttributes.Luck += attrInfo.WeaponLuck; break; - case 4: m_AosWeaponAttributes.LowerStatReq += attrInfo.WeaponLowerRequirements; break; - case 5: m_AosWeaponAttributes.HitLeechHits += attrInfo.WeaponHitLifeLeech; break; - } - } - } + public virtual void DistributeMaterialBonus(CraftAttributeInfo attrInfo) + { + if (m_Resource != CraftResource.Heartwood) + { + m_AosAttributes.WeaponDamage += attrInfo.WeaponDamage; + m_AosAttributes.WeaponSpeed += attrInfo.WeaponSwingSpeed; + m_AosAttributes.AttackChance += attrInfo.WeaponHitChance; + m_AosAttributes.RegenHits += attrInfo.WeaponRegenHits; + m_AosWeaponAttributes.HitLeechHits += attrInfo.WeaponHitLifeLeech; + } + else + { + switch (Utility.Random(6)) + { + case 0: m_AosAttributes.WeaponDamage += attrInfo.WeaponDamage; break; + case 1: m_AosAttributes.WeaponSpeed += attrInfo.WeaponSwingSpeed; break; + case 2: m_AosAttributes.AttackChance += attrInfo.WeaponHitChance; break; + case 3: m_AosAttributes.Luck += attrInfo.WeaponLuck; break; + case 4: m_AosWeaponAttributes.LowerStatReq += attrInfo.WeaponLowerRequirements; break; + case 5: m_AosWeaponAttributes.HitLeechHits += attrInfo.WeaponHitLifeLeech; break; + } + } + } #region Mondain's Legacy Sets public override bool OnDragLift(Mobile from) @@ -6516,15 +6526,15 @@ namespace Server.Items public virtual SetItem SetID { get { return SetItem.None; } } public virtual int Pieces { get { return 0; } } - public virtual bool BardMasteryBonus - { - get - { - return (SetID == SetItem.Virtuoso); - } - } + public virtual bool BardMasteryBonus + { + get + { + return (SetID == SetItem.Virtuoso); + } + } - public bool IsSetItem { get { return SetID != SetItem.None; } } + public bool IsSetItem { get { return SetID != SetItem.None; } } private int m_SetHue; private bool m_SetEquipped; @@ -6548,7 +6558,7 @@ namespace Server.Items private AosAttributes m_SetAttributes; private AosSkillBonuses m_SetSkillBonuses; private int m_SetSelfRepair; - private int m_SetPhysicalBonus, m_SetFireBonus, m_SetColdBonus, m_SetPoisonBonus, m_SetEnergyBonus; + private int m_SetPhysicalBonus, m_SetFireBonus, m_SetColdBonus, m_SetPoisonBonus, m_SetEnergyBonus; [CommandProperty(AccessLevel.GameMaster)] public AosAttributes SetAttributes { get { return m_SetAttributes; } set { } } @@ -6567,75 +6577,75 @@ namespace Server.Items } } - [CommandProperty(AccessLevel.GameMaster)] - public int SetPhysicalBonus - { - get - { - return m_SetPhysicalBonus; - } - set - { - m_SetPhysicalBonus = value; - InvalidateProperties(); - } - } + [CommandProperty(AccessLevel.GameMaster)] + public int SetPhysicalBonus + { + get + { + return m_SetPhysicalBonus; + } + set + { + m_SetPhysicalBonus = value; + InvalidateProperties(); + } + } - [CommandProperty(AccessLevel.GameMaster)] - public int SetFireBonus - { - get - { - return m_SetFireBonus; - } - set - { - m_SetFireBonus = value; - InvalidateProperties(); - } - } + [CommandProperty(AccessLevel.GameMaster)] + public int SetFireBonus + { + get + { + return m_SetFireBonus; + } + set + { + m_SetFireBonus = value; + InvalidateProperties(); + } + } - [CommandProperty(AccessLevel.GameMaster)] - public int SetColdBonus - { - get - { - return m_SetColdBonus; - } - set - { - m_SetColdBonus = value; - InvalidateProperties(); - } - } + [CommandProperty(AccessLevel.GameMaster)] + public int SetColdBonus + { + get + { + return m_SetColdBonus; + } + set + { + m_SetColdBonus = value; + InvalidateProperties(); + } + } - [CommandProperty(AccessLevel.GameMaster)] - public int SetPoisonBonus - { - get - { - return m_SetPoisonBonus; - } - set - { - m_SetPoisonBonus = value; - InvalidateProperties(); - } - } + [CommandProperty(AccessLevel.GameMaster)] + public int SetPoisonBonus + { + get + { + return m_SetPoisonBonus; + } + set + { + m_SetPoisonBonus = value; + InvalidateProperties(); + } + } - [CommandProperty(AccessLevel.GameMaster)] - public int SetEnergyBonus - { - get - { - return m_SetEnergyBonus; - } - set - { - m_SetEnergyBonus = value; - InvalidateProperties(); - } - } + [CommandProperty(AccessLevel.GameMaster)] + public int SetEnergyBonus + { + get + { + return m_SetEnergyBonus; + } + set + { + m_SetEnergyBonus = value; + InvalidateProperties(); + } + } public virtual void GetSetProperties(ObjectPropertyList list) { @@ -6649,38 +6659,38 @@ namespace Server.Items SetHelper.GetSetProperties(list, this); } - public int SetResistBonus(ResistanceType resist) - { - switch (resist) - { - case ResistanceType.Physical: return PhysicalResistance; - case ResistanceType.Fire: return FireResistance; - case ResistanceType.Cold: return ColdResistance; - case ResistanceType.Poison: return PoisonResistance; - case ResistanceType.Energy: return EnergyResistance; - } + public int SetResistBonus(ResistanceType resist) + { + switch (resist) + { + case ResistanceType.Physical: return PhysicalResistance; + case ResistanceType.Fire: return FireResistance; + case ResistanceType.Cold: return ColdResistance; + case ResistanceType.Poison: return PoisonResistance; + case ResistanceType.Energy: return EnergyResistance; + } - return 0; - } - #endregion + return 0; + } + #endregion - [CommandProperty(AccessLevel.GameMaster)] - public bool Altered - { - get { return m_Altered; } - set - { - m_Altered = value; - InvalidateProperties(); - } - } - } + [CommandProperty(AccessLevel.GameMaster)] + public bool Altered + { + get { return m_Altered; } + set + { + m_Altered = value; + InvalidateProperties(); + } + } + } - public enum CheckSlayerResult - { - None, - Slayer, - SuperSlayer, - Opposition - } + public enum CheckSlayerResult + { + None, + Slayer, + SuperSlayer, + Opposition + } } diff --git a/Scripts/Items/Tools/BagOfSending.cs b/Scripts/Items/Tools/BagOfSending.cs old mode 100755 new mode 100644 index b43bc46..a3f834f --- a/Scripts/Items/Tools/BagOfSending.cs +++ b/Scripts/Items/Tools/BagOfSending.cs @@ -119,7 +119,7 @@ namespace Server.Items { m_BagOfSendingHue = value; - switch ( value ) + switch (value) { case BagOfSendingHue.Yellow: Hue = 0x8A5; @@ -135,7 +135,7 @@ namespace Server.Items } public static BagOfSendingHue RandomHue() { - switch ( Utility.Random(3) ) + switch (Utility.Random(3)) { case 0: return BagOfSendingHue.Yellow; @@ -206,7 +206,7 @@ namespace Server.Items int version = reader.ReadEncodedInt(); - switch ( version ) + switch (version) { case 1: { @@ -260,6 +260,13 @@ namespace Server.Items if (m_Bag.Deleted) return; + // Block usage anywhere in Felucca + if (from.Map == Map.Felucca) + { + from.SendMessage("A mysterious force prevents the bag from working in Felucca."); + return; + } + if (from.Region.IsPartOf()) { from.SendMessage("You may not do that in jail."); diff --git a/Scripts/Items/Tools/BagOfSending.cs.backup b/Scripts/Items/Tools/BagOfSending.cs.backup new file mode 100755 index 0000000..b43bc46 --- /dev/null +++ b/Scripts/Items/Tools/BagOfSending.cs.backup @@ -0,0 +1,318 @@ +using System; +using System.Collections.Generic; +using Server.ContextMenus; +using Server.Network; +using Server.Targeting; + +namespace Server.Items +{ + public enum BagOfSendingHue + { + Yellow, + Blue, + Red + } + + public class BagOfSending : Item, TranslocationItem + { + private int m_Charges; + private int m_Recharges; + private BagOfSendingHue m_BagOfSendingHue; + [Constructable] + public BagOfSending() + : this(RandomHue()) + { + } + + [Constructable] + public BagOfSending(BagOfSendingHue hue) + : base(0xE76) + { + Weight = 2.0; + + BagOfSendingHue = hue; + + m_Charges = Utility.RandomMinMax(3, 9); + } + + public BagOfSending(Serial serial) + : base(serial) + { + } + + [CommandProperty(AccessLevel.GameMaster)] + public int Charges + { + get + { + return m_Charges; + } + set + { + if (value > MaxCharges) + m_Charges = MaxCharges; + else if (value < 0) + m_Charges = 0; + else + m_Charges = value; + + InvalidateProperties(); + } + } + [CommandProperty(AccessLevel.GameMaster)] + public int Recharges + { + get + { + return m_Recharges; + } + set + { + if (value > MaxRecharges) + m_Recharges = MaxRecharges; + else if (value < 0) + m_Recharges = 0; + else + m_Recharges = value; + + InvalidateProperties(); + } + } + [CommandProperty(AccessLevel.GameMaster)] + public int MaxCharges + { + get + { + return 30; + } + } + [CommandProperty(AccessLevel.GameMaster)] + public int MaxRecharges + { + get + { + return 255; + } + } + public string TranslocationItemName + { + get + { + return "bag of sending"; + } + } + public override int LabelNumber + { + get + { + return 1054104; + } + }// a bag of sending + [CommandProperty(AccessLevel.GameMaster)] + public BagOfSendingHue BagOfSendingHue + { + get + { + return m_BagOfSendingHue; + } + set + { + m_BagOfSendingHue = value; + + switch ( value ) + { + case BagOfSendingHue.Yellow: + Hue = 0x8A5; + break; + case BagOfSendingHue.Blue: + Hue = 0x8AD; + break; + case BagOfSendingHue.Red: + Hue = 0x89B; + break; + } + } + } + public static BagOfSendingHue RandomHue() + { + switch ( Utility.Random(3) ) + { + case 0: + return BagOfSendingHue.Yellow; + case 1: + return BagOfSendingHue.Blue; + default: + return BagOfSendingHue.Red; + } + } + + public override void GetProperties(ObjectPropertyList list) + { + base.GetProperties(list); + + list.Add(1060741, m_Charges.ToString()); // charges: ~1_val~ + } + + public override void OnSingleClick(Mobile from) + { + base.OnSingleClick(from); + + LabelTo(from, 1060741, m_Charges.ToString()); // charges: ~1_val~ + } + + public override void GetContextMenuEntries(Mobile from, List list) + { + base.GetContextMenuEntries(from, list); + + if (from.Alive) + list.Add(new UseBagEntry(this, Charges > 0 && IsChildOf(from.Backpack))); + } + + public override void OnDoubleClick(Mobile from) + { + if (from.Region.IsPartOf()) + { + from.SendMessage("You may not do that in jail."); + } + else if (!IsChildOf(from.Backpack)) + { + MessageHelper.SendLocalizedMessageTo(this, from, 1062334, 0x59); // The bag of sending must be in your backpack. + } + else if (Charges == 0) + { + MessageHelper.SendLocalizedMessageTo(this, from, 1042544, 0x59); // This item is out of charges. + } + else + { + from.Target = new SendTarget(this); + } + } + + public override void Serialize(GenericWriter writer) + { + base.Serialize(writer); + + writer.WriteEncodedInt((int)1); // version + + writer.WriteEncodedInt((int)m_Recharges); + + writer.WriteEncodedInt((int)m_Charges); + writer.WriteEncodedInt((int)m_BagOfSendingHue); + } + + public override void Deserialize(GenericReader reader) + { + base.Deserialize(reader); + + int version = reader.ReadEncodedInt(); + + switch ( version ) + { + case 1: + { + m_Recharges = reader.ReadEncodedInt(); + goto case 0; + } + case 0: + { + m_Charges = Math.Min(reader.ReadEncodedInt(), MaxCharges); + m_BagOfSendingHue = (BagOfSendingHue)reader.ReadEncodedInt(); + break; + } + } + } + + private class UseBagEntry : ContextMenuEntry + { + private readonly BagOfSending m_Bag; + public UseBagEntry(BagOfSending bag, bool enabled) + : base(6189) + { + m_Bag = bag; + + if (!enabled) + Flags |= CMEFlags.Disabled; + } + + public override void OnClick() + { + if (m_Bag.Deleted) + return; + + Mobile from = Owner.From; + + if (from.CheckAlive()) + m_Bag.OnDoubleClick(from); + } + } + + private class SendTarget : Target + { + private readonly BagOfSending m_Bag; + public SendTarget(BagOfSending bag) + : base(-1, false, TargetFlags.None) + { + m_Bag = bag; + } + + protected override void OnTarget(Mobile from, object targeted) + { + if (m_Bag.Deleted) + return; + + if (from.Region.IsPartOf()) + { + from.SendMessage("You may not do that in jail."); + } + else if (!m_Bag.IsChildOf(from.Backpack)) + { + MessageHelper.SendLocalizedMessageTo(m_Bag, from, 1062334, 0x59); // The bag of sending must be in your backpack. 1054107 is gone from client, using generic response + } + else if (m_Bag.Charges == 0) + { + MessageHelper.SendLocalizedMessageTo(m_Bag, from, 1042544, 0x59); // This item is out of charges. + } + else if (targeted is Item) + { + Item item = (Item)targeted; + int reqCharges = 1; // (int)Math.Max(1, Math.Ceiling(item.TotalWeight / 10.0)); + // change was ML, however reverted during ML period so we can put it at 1 + + if (!item.IsChildOf(from.Backpack)) + { + MessageHelper.SendLocalizedMessageTo(m_Bag, from, 1054152, 0x59); // You may only send items from your backpack to your bank box. + } + else if (item is BagOfSending || item is Container) + { + from.Send(new AsciiMessage(m_Bag.Serial, m_Bag.ItemID, MessageType.Regular, 0x3B2, 3, "", "You cannot send a container through the bag of sending.")); + } + else if (item.LootType == LootType.Cursed) + { + MessageHelper.SendLocalizedMessageTo(m_Bag, from, 1054108, 0x59); // The bag of sending rejects the cursed item. + } + else if (!item.VerifyMove(from) || item is Server.Engines.Quests.QuestItem || item.QuestItem) + { + MessageHelper.SendLocalizedMessageTo(m_Bag, from, 1054109, 0x59); // The bag of sending rejects that item. + } + else if (Spells.SpellHelper.IsDoomGauntlet(from.Map, from.Location)) + { + from.SendLocalizedMessage(1062089); // You cannot use that here. + } + else if (!from.BankBox.TryDropItem(from, item, false)) + { + MessageHelper.SendLocalizedMessageTo(m_Bag, from, 1054110, 0x59); // Your bank box is full. + } + else if (Core.ML && reqCharges > m_Bag.Charges) + { + from.SendLocalizedMessage(1079932); //You don't have enough charges to send that much weight + } + else + { + m_Bag.Charges -= (Core.ML ? reqCharges : 1); + MessageHelper.SendLocalizedMessageTo(m_Bag, from, 1054150, 0x59); // The item was placed in your bank box. + } + } + } + } + } +} \ No newline at end of file diff --git a/Scripts/Misc/AOS.cs b/Scripts/Misc/AOS.cs index 49cbcf7..d6d5e81 100755 --- a/Scripts/Misc/AOS.cs +++ b/Scripts/Misc/AOS.cs @@ -192,6 +192,16 @@ namespace Server totalDamage += (int)((double)totalDamage * .1); } + if (Core.HS && type == DamageType.Spell) + { + if (from?.FindItemOnLayer(Layer.MiddleTorso) is SpellFocusingSash spellSash) + { + spellSash.ValidateTarget(from, m, out var sdiOffset); + + totalDamage += Scale(totalDamage, sdiOffset); + } + } + if (totalDamage < 1) totalDamage = 1; } diff --git a/Scripts/Misc/ConsoleCommands.cs b/Scripts/Misc/ConsoleCommands.cs index e2e4554..786441c 100755 --- a/Scripts/Misc/ConsoleCommands.cs +++ b/Scripts/Misc/ConsoleCommands.cs @@ -139,7 +139,7 @@ namespace Server.Misc return; } - var ns = states.Find(o => o.Account != null && o.Mobile != null && Insensitive.StartsWith(sub, o.Mobile.RawName)); + var ns = states.FirstOrDefault(o => o.Account != null && o.Mobile != null && Insensitive.StartsWith(sub, o.Mobile.RawName)); if (ns != null) { @@ -163,7 +163,7 @@ namespace Server.Misc return; } - var ns = states.Find(o => o.Account != null && o.Mobile != null && Insensitive.StartsWith(sub, o.Mobile.RawName)); + var ns = states.FirstOrDefault(o => o.Account != null && o.Mobile != null && Insensitive.StartsWith(sub, o.Mobile.RawName)); if (ns != null) { @@ -523,4 +523,4 @@ namespace Server.Misc World.Broadcast(hue, false, ac, message); } } -} \ No newline at end of file +} diff --git a/Scripts/Misc/CrashGuard.cs b/Scripts/Misc/CrashGuard.cs index 16692f8..b11b37a 100755 --- a/Scripts/Misc/CrashGuard.cs +++ b/Scripts/Misc/CrashGuard.cs @@ -212,7 +212,7 @@ namespace Server.Misc try { - List states = NetState.Instances; + IList states = NetState.Instances; op.WriteLine("- Count: {0}", states.Count); diff --git a/Scripts/Misc/CurrentExpansion.cs b/Scripts/Misc/CurrentExpansion.cs index 78b303e..f71836f 100755 --- a/Scripts/Misc/CurrentExpansion.cs +++ b/Scripts/Misc/CurrentExpansion.cs @@ -43,7 +43,7 @@ namespace Server PacketHandlers.SingleClickProps = true; // single click for everything is overriden to check object property list } - Mobile.ActionDelay = Core.TOL ? 500 : Core.AOS ? 750 : 500; + Mobile.ActionDelay = Core.TOL ? 500 : Core.AOS ? 1000 : 500; Mobile.AOSStatusHandler = AOS.GetStatus; } } diff --git a/Scripts/Misc/LootPack.cs b/Scripts/Misc/LootPack.cs index 0abcadf..5ee1098 100755 --- a/Scripts/Misc/LootPack.cs +++ b/Scripts/Misc/LootPack.cs @@ -125,8 +125,6 @@ namespace Server } } - public static readonly LootPackItem[] HeritageSovereign = new[] {new LootPackItem(typeof(HeritageSovereign), 1)}; - public static readonly LootPackItem[] Gold = new[] {new LootPackItem(typeof(Gold), 1)}; public static readonly LootPackItem[] Instruments = new[] {new LootPackItem(typeof(BaseInstrument), 1)}; @@ -340,7 +338,7 @@ namespace Server new[] { new LootPackEntry(true, Gold, 100.00, "1d10+10"), new LootPackEntry(false, AosMagicItemsPoor, 0.02, 1, 5, 0, 90), - new LootPackEntry(false, Instruments, 0.02, 1), new LootPackEntry(true, HeritageSovereign, 1, "1d10+1") + new LootPackEntry(false, Instruments, 0.02, 1) }); public static readonly LootPack AosMeager = @@ -350,7 +348,7 @@ namespace Server new LootPackEntry(true, Gold, 100.00, "3d10+20"), new LootPackEntry(false, AosMagicItemsMeagerType1, 1.00, 1, 2, 0, 10), new LootPackEntry(false, AosMagicItemsMeagerType2, 0.20, 1, 5, 0, 90), - new LootPackEntry(false, Instruments, 0.10, 1), new LootPackEntry(true, HeritageSovereign, 1, "1d10+5") + new LootPackEntry(false, Instruments, 0.10, 1) }); public static readonly LootPack AosAverage = @@ -361,7 +359,7 @@ namespace Server new LootPackEntry(false, AosMagicItemsAverageType1, 5.00, 1, 4, 0, 20), new LootPackEntry(false, AosMagicItemsAverageType1, 2.00, 1, 3, 0, 50), new LootPackEntry(false, AosMagicItemsAverageType2, 0.50, 1, 5, 0, 90), - new LootPackEntry(false, Instruments, 0.40, 1), new LootPackEntry(true, HeritageSovereign, 1, "1d10+10") + new LootPackEntry(false, Instruments, 0.40, 1) }); public static readonly LootPack AosRich = @@ -371,8 +369,7 @@ namespace Server new LootPackEntry(true, Gold, 100.00, "10d10+150"), new LootPackEntry(false, AosMagicItemsRichType1, 20.00, 1, 4, 0, 40), new LootPackEntry(false, AosMagicItemsRichType1, 10.00, 1, 5, 0, 60), - new LootPackEntry(false, AosMagicItemsRichType2, 1.00, 1, 5, 0, 90), new LootPackEntry(false, Instruments, 1.00, 1), - new LootPackEntry(true, HeritageSovereign, 10, "1d10+1") + new LootPackEntry(false, AosMagicItemsRichType2, 1.00, 1, 5, 0, 90), new LootPackEntry(false, Instruments, 1.00, 1) }); public static readonly LootPack AosFilthyRich = @@ -384,7 +381,7 @@ namespace Server new LootPackEntry(false, AosMagicItemsFilthyRichType1, 33.00, 1, 4, 0, 60), new LootPackEntry(false, AosMagicItemsFilthyRichType2, 20.00, 1, 5, 0, 75), new LootPackEntry(false, AosMagicItemsFilthyRichType2, 5.00, 1, 5, 0, 100), - new LootPackEntry(false, Instruments, 2.00, 1), new LootPackEntry(true, HeritageSovereign, 10, "1d10+5") + new LootPackEntry(false, Instruments, 2.00, 1) }); public static readonly LootPack AosUltraRich = @@ -398,7 +395,7 @@ namespace Server new LootPackEntry(false, AosMagicItemsUltraRich, 100.00, 1, 5, 25, 100), new LootPackEntry(false, AosMagicItemsUltraRich, 100.00, 1, 5, 25, 100), new LootPackEntry(false, AosMagicItemsUltraRich, 100.00, 1, 5, 35, 100), - new LootPackEntry(false, Instruments, 2.00, 1), new LootPackEntry(true, HeritageSovereign, 10, "1d10+10") + new LootPackEntry(false, Instruments, 2.00, 1) }); public static readonly LootPack AosSuperBoss = @@ -416,7 +413,7 @@ namespace Server new LootPackEntry(false, AosMagicItemsUltraRich, 100.00, 1, 5, 33, 100), new LootPackEntry(false, AosMagicItemsUltraRich, 100.00, 1, 5, 50, 100), new LootPackEntry(false, AosMagicItemsUltraRich, 100.00, 1, 5, 50, 100), - new LootPackEntry(false, Instruments, 2.00, 1), new LootPackEntry(true, HeritageSovereign, 20, "1d10+10") + new LootPackEntry(false, Instruments, 2.00, 1) }); #endregion diff --git a/Scripts/Misc/ServerList.cs b/Scripts/Misc/ServerList.cs index 6444d03..82bb472 100755 --- a/Scripts/Misc/ServerList.cs +++ b/Scripts/Misc/ServerList.cs @@ -7,64 +7,20 @@ using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text.RegularExpressions; using System.Threading; + +using Server.Network; #endregion namespace Server.Misc { public class ServerList - { - /* - * The default setting for Address, a value of 'null', will use your local IP address. If all of your local IP addresses - * are private network addresses and AutoDetect is 'true' then ServUO will attempt to discover your public IP address - * for you automatically. - * - * If you do not plan on allowing clients outside of your LAN to connect, you can set AutoDetect to 'false' and leave - * Address set to 'null'. - * - * If your public IP address cannot be determined, you must change the value of Address to your public IP address - * manually to allow clients outside of your LAN to connect to your server. Address can be either an IP address or - * a hostname that will be resolved when ServUO starts. - * - * If you want players outside your LAN to be able to connect to your server and you are behind a router, you must also - * forward TCP port 2593 to your private IP address. The procedure for doing this varies by manufacturer but generally - * involves configuration of the router through your web browser. - * - * ServerList will direct connecting clients depending on both the address they are connecting from and the address and - * port they are connecting to. If it is determined that both ends of a connection are private IP addresses, ServerList - * will direct the client to the local private IP address. If a client is connecting to a local public IP address, they - * will be directed to whichever address and port they initially connected to. This allows multihomed servers to function - * properly and fully supports listening on multiple ports. If a client with a public IP address is connecting to a - * locally private address, the server will direct the client to either the AutoDetected IP address or the manually entered - * IP address or hostname, whichever is applicable. Loopback clients will be directed to loopback. - * - * If you would like to listen on additional ports (i.e. 22, 23, 80, for clients behind highly restrictive egress - * firewalls) or specific IP adddresses you can do so by modifying the file SocketOptions.cs found in this directory. - */ + { + public static string ServerName = Config.Get("Server.Name", "My Shard"); - public static readonly string Address = Config.Get("Server.Address", default(string)); - - public static readonly bool AutoDetect = Config.Get("Server.AutoDetect", true); - - public static string ServerName = Config.Get("Server.Name", "My Shard"); - - private static IPAddress _PublicAddress; - - private static readonly Regex _AddressPattern = new Regex(@"([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})"); - - public static void Initialize() - { - if (Address == null) - { - if (AutoDetect) - { - AutoDetection(); - } - } - else - { - Resolve(Address, out _PublicAddress); - } + public static IPAddress Address => Config.Get("Server.Address", IPAddress.Loopback); + public static void Initialize() + { EventSink.ServerList += EventSink_ServerList; } @@ -80,15 +36,15 @@ namespace Server.Misc var localAddress = ipep.Address; var localPort = ipep.Port; - if (IsPrivateNetwork(localAddress)) - { - ipep = (IPEndPoint)s.RemoteEndPoint; + if (!IPAddress.IsLoopback(localAddress) && IsPrivateNetwork(localAddress)) + { + ipep = (IPEndPoint)s.RemoteEndPoint; - if (!IsPrivateNetwork(ipep.Address) && _PublicAddress != null) - { - localAddress = _PublicAddress; - } - } + if (!IsPrivateNetwork(ipep.Address)) + { + localAddress = Address; + } + } e.AddServer(ServerName, new IPEndPoint(localAddress, localPort)); } @@ -98,67 +54,6 @@ namespace Server.Misc } } - public static string[] IPServices = - { - "http://services.servuo.com/ip.php", "http://api.ipify.org", - "http://checkip.dyndns.org/" - }; - - private static void AutoDetection() - { - if (!HasPublicIPAddress()) - { - Utility.PushColor(ConsoleColor.Yellow); - Console.WriteLine("ServerList: Auto-detecting public IP address..."); - - _PublicAddress = FindPublicAddress(IPServices); - - if (_PublicAddress != null) - { - Console.WriteLine("ServerList: Done: '{0}'", _PublicAddress); - } - else - { - _PublicAddress = IPAddress.Any; - - Console.WriteLine("ServerList: Failed: reverting to private IP address..."); - } - - Utility.PopColor(); - } - } - - private static void Resolve(string addr, out IPAddress outValue) - { - if (IPAddress.TryParse(addr, out outValue)) - { - return; - } - - try - { - var iphe = Dns.GetHostEntry(addr); - - if (iphe.AddressList.Length > 0) - { - outValue = iphe.AddressList[iphe.AddressList.Length - 1]; - } - } - catch - { } - } - - private static bool HasPublicIPAddress() - { - var adapters = NetworkInterface.GetAllNetworkInterfaces(); - var uips = adapters.Select(a => a.GetIPProperties()) - .SelectMany(p => p.UnicastAddresses.Cast(), (p, u) => u.Address); - - return - uips.Any( - ip => !IPAddress.IsLoopback(ip) && ip.AddressFamily != AddressFamily.InterNetworkV6 && !IsPrivateNetwork(ip)); - } - private static bool IsPrivateNetwork(IPAddress ip) { // 10.0.0.0/8 @@ -199,65 +94,5 @@ namespace Server.Misc return false; } - - public static IPAddress FindPublicAddress(params string[] services) - { - if (services == null || services.Length == 0) - { - services = IPServices; - } - - if (services == null || services.Length == 0) - { - return null; - } - - IPAddress ip = null; - - Uri uri; - string data; - Match match; - - foreach (var service in services.Where(s => !String.IsNullOrWhiteSpace(s))) - { - try - { - uri = new Uri(service); - - Console.WriteLine("ServerList: >>> {0}", uri.Host); - - using (var client = new WebClient()) - { - data = client.DownloadString(uri); - } - - Console.WriteLine("ServerList: <<< {0}", data); - - match = _AddressPattern.Match(data); - - if (!match.Success || !IPAddress.TryParse(match.Value, out ip)) - { - ip = null; - } - } - catch (UriFormatException) - { - Console.WriteLine("ServerList: Invalid IP service Uri '{0}'", service); - - ip = null; - } - catch - { - ip = null; - } - - if (ip != null) - { - break; - } - } - - return ip; - } } } diff --git a/Scripts/Misc/Timestamp.cs b/Scripts/Misc/Timestamp.cs index b40381a..f11614e 100755 --- a/Scripts/Misc/Timestamp.cs +++ b/Scripts/Misc/Timestamp.cs @@ -25,7 +25,7 @@ namespace System { get { - return String.Format("{0:D2}:{1:D2}:{2:D2} ", DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); + return String.Format("{0:D2}:{1:D2}:{2:D2} ", DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Second); } } public static void Initialize() diff --git a/Scripts/Misc/Weather.cs b/Scripts/Misc/Weather.cs index a99cacf..d6e7200 100755 --- a/Scripts/Misc/Weather.cs +++ b/Scripts/Misc/Weather.cs @@ -381,7 +381,7 @@ namespace Server.Misc else type = 2; - List states = NetState.Instances; + IList states = NetState.Instances; Packet weatherPacket = null; @@ -471,4 +471,4 @@ namespace Server.Misc int version = reader.ReadInt(); } } -} \ No newline at end of file +} diff --git a/Scripts/Mobiles/Bosses/BaseChampion.cs b/Scripts/Mobiles/Bosses/BaseChampion.cs index 2015041..1e9a8e4 100755 --- a/Scripts/Mobiles/Bosses/BaseChampion.cs +++ b/Scripts/Mobiles/Bosses/BaseChampion.cs @@ -284,7 +284,7 @@ namespace Server.Mobiles int level; double random = Utility.RandomDouble(); - if (0.2 >= random) + if (0.05 >= random) level = 20; else if (0.4 >= random) level = 15; diff --git a/Scripts/Mobiles/PlayerMobile.cs b/Scripts/Mobiles/PlayerMobile.cs index 5b015b0..0dacc01 100755 --- a/Scripts/Mobiles/PlayerMobile.cs +++ b/Scripts/Mobiles/PlayerMobile.cs @@ -1282,7 +1282,7 @@ namespace Server.Mobiles { mount.Rider = from; } - }, + }, (EtherealMount)from.Mount); } @@ -2373,10 +2373,12 @@ namespace Server.Mobiles } } } - else if (Siege.SiegeShard) + /* else if (Siege.SiegeShard) { list.Add(new CallbackEntry(3006168, SiegeBlessItem)); - } + } */ + + list.Add(new CallbackEntry(3006168, SiegeBlessItem)); if (Core.ML && Alive) { @@ -2408,7 +2410,7 @@ namespace Server.Mobiles if (Core.HS) { - list.Add(new CallbackEntry(RefuseTrades ? 1154112 : 1154113, ToggleTrades)); // Allow Trades / Refuse Trades + list.Add(new CallbackEntry(RefuseTrades ? 1154112 : 1154113, ToggleTrades)); // Allow Trades / Refuse Trades } if (m_JusticeProtectors.Count > 0) @@ -3350,7 +3352,7 @@ namespace Server.Mobiles } else if (to.Backpack == null || !to.Backpack.CheckHold(to, item, false, checkItems, plusItems, plusWeight)) { - msgNum = 1004039; // The recipient of this trade would not be able to carry + msgNum = 1004039; // The recipient of this trade would not be able to carry } else { @@ -3520,7 +3522,7 @@ namespace Server.Mobiles } BaseGump.CheckCloseGumps(this); - + DesignContext context = m_DesignContext; if (context == null || m_NoRecursion) @@ -4013,7 +4015,7 @@ namespace Server.Mobiles Faction.HandleDeath(this, killer); Guilds.Guild.HandleDeath(this, killer); - + if (m_BuffTable != null) { var list = new List(); @@ -4397,7 +4399,7 @@ namespace Server.Mobiles public override int Luck { get { return AosAttributes.GetValue(this, AosAttribute.Luck) + TenthAnniversarySculpture.GetLuckBonus(this); } } public int RealLuck - { + { get { int facetBonus = !Siege.SiegeShard && this.Map == Map.Felucca ? RandomItemGenerator.FeluccaLuckBonus : 0; @@ -4977,7 +4979,7 @@ namespace Server.Mobiles writer.Write((int)m_ExtendedFlags); writer.Write(RewardStableSlots); - + if (_BlessedItem != null && _BlessedItem.RootParent != this) { _BlessedItem = null; @@ -5513,7 +5515,7 @@ namespace Server.Mobiles #region Factions public PlayerState FactionPlayerState { get; set; } #endregion - + #region Quests private QuestSystem m_Quest; private List m_DoneQuests; @@ -5632,7 +5634,7 @@ namespace Server.Mobiles { m_SelectedTitle = num; - if (!silent) + if (!silent) SendLocalizedMessage(1074010); // You elect to hide your Reward Title. } else if (num < m_RewardTitles.Count && num >= -1) @@ -5746,7 +5748,7 @@ namespace Server.Mobiles } public override void AddNameProperties(ObjectPropertyList list) - { + { string prefix = ""; if (ShowFameTitle && Fame >= 10000) @@ -6989,4 +6991,4 @@ namespace Server.Mobiles m_AutoStabled.Clear(); } } -} +} \ No newline at end of file diff --git a/Scripts/Services/ChampionSystem/ChampionSkull.cs b/Scripts/Services/ChampionSystem/ChampionSkull.cs index 6d245a3..c354087 100755 --- a/Scripts/Services/ChampionSystem/ChampionSkull.cs +++ b/Scripts/Services/ChampionSystem/ChampionSkull.cs @@ -47,6 +47,10 @@ namespace Server.Items case ChampionSkullType.Pain: Hue = 0x035; break; + //Soth Skull + case ChampionSkullType.Despair: + Hue = 0x455; + break; } } diff --git a/Scripts/Services/ChampionSystem/ChampionSkullType.cs b/Scripts/Services/ChampionSystem/ChampionSkullType.cs index ac9af46..883c60b 100755 --- a/Scripts/Services/ChampionSystem/ChampionSkullType.cs +++ b/Scripts/Services/ChampionSystem/ChampionSkullType.cs @@ -10,6 +10,8 @@ namespace Server.Engines.CannedEvil Venom, Pain, Greed, - Death + Death, + //Dupre Skull + Despair } } \ No newline at end of file diff --git a/Scripts/Services/ChampionSystem/ChampionSpawn.cs b/Scripts/Services/ChampionSystem/ChampionSpawn.cs index 9dcf523..5ddf36d 100755 --- a/Scripts/Services/ChampionSystem/ChampionSpawn.cs +++ b/Scripts/Services/ChampionSystem/ChampionSpawn.cs @@ -467,7 +467,7 @@ namespace Server.Engines.CannedEvil { if (RandomizeType) { - switch (Utility.Random(5)) + switch (Utility.Random(6)) { case 0: Type = ChampionSpawnType.Abyss; break; @@ -479,6 +479,7 @@ namespace Server.Engines.CannedEvil Type = ChampionSpawnType.VerminHorde; break; case 4: Type = ChampionSpawnType.UnholyTerror; break; + } } diff --git a/Scripts/Services/CleanUpBritannia/CleanUpBritanniaRewards.cs b/Scripts/Services/CleanUpBritannia/CleanUpBritanniaRewards.cs index e27edc2..6d46fa5 100755 --- a/Scripts/Services/CleanUpBritannia/CleanUpBritanniaRewards.cs +++ b/Scripts/Services/CleanUpBritannia/CleanUpBritanniaRewards.cs @@ -20,7 +20,7 @@ namespace Server.Engines.CleanUpBritannia Rewards.Add(new CollectionItem(typeof(WeArePiratesRobe), 0x1F03, 1151204, 0, 1000)); Rewards.Add(new CollectionItem(typeof(FollowerOfBaneRobe), 0x1F03, 1151205, 0, 1000)); Rewards.Add(new CollectionItem(typeof(QueenDawnForeverRobe), 0x1F03, 1151206, 0, 1000)); - + Rewards.Add(new CollectionItem(typeof(LillyPad), 0xDBC, 1023516, 0, 5000)); Rewards.Add(new CollectionItem(typeof(LillyPads), 0xDBE, 1023518, 0, 5000)); Rewards.Add(new CollectionItem(typeof(Mushrooms1), 0x0D0F, 1023340, 0, 5000)); @@ -96,7 +96,6 @@ namespace Server.Engines.CleanUpBritannia Rewards.Add(new CollectionItem(typeof(DragonHeadAddonDeed), 0x2234, 1028756, 0, 50000)); Rewards.Add(new CollectionItem(typeof(NestWithEggs), 0x1AD4, 1026868, 2415, 50000)); - if (Core.HS) { @@ -173,7 +172,6 @@ namespace Server.Engines.CleanUpBritannia Rewards.Add(new CollectionItem(typeof(MysticsMemento), 0x2F5B, 1154744, 1912, 300000)); Rewards.Add(new CollectionItem(typeof(VollemHeldInCrystal), 0x1f19, 1113629, 1154, 500000)); - Rewards.Add(new CollectionItem(typeof(ItemBlessDeed),0x14F0, 1006018, 0, 500000)); } } } diff --git a/Scripts/Services/Craft/Core/Repair.cs b/Scripts/Services/Craft/Core/Repair.cs index 6729bd1..9099263 100755 --- a/Scripts/Services/Craft/Core/Repair.cs +++ b/Scripts/Services/Craft/Core/Repair.cs @@ -3,6 +3,7 @@ using Server.Items; using Server.Mobiles; using Server.Targeting; using Server.Factions; +using Server.Custom; namespace Server.Engines.Craft { @@ -225,6 +226,20 @@ namespace Server.Engines.Craft return; } + // =============================== + // CUSTOM REPAIR LOCK ENFORCEMENT + // =============================== + Item it = targeted as Item; + + if (it != null && it.GetRepairLocked()) + { + from.SendMessage("This item has been fortified and cannot be repaired until it is restored."); + + if (m_Addon != null) + m_Addon.Using = false; + + return; + } if (m_CraftSystem.CanCraft(from, m_Tool, targeted.GetType()) == 1044267) { @@ -638,7 +653,7 @@ namespace Server.Engines.Craft if (toDelete) m_Deed.Delete(); - } + } } } diff --git a/Scripts/Services/Expansions/MondainsLegacy.cs b/Scripts/Services/Expansions/MondainsLegacy.cs index fa424f3..8a9b78a 100755 --- a/Scripts/Services/Expansions/MondainsLegacy.cs +++ b/Scripts/Services/Expansions/MondainsLegacy.cs @@ -25,7 +25,7 @@ namespace Server typeof(HelmOfSwiftness), typeof(PadsOfTheCuSidhe), typeof(QuiverOfRage), typeof(QuiverOfElements), typeof(RaedsGlory), typeof(RighteousAnger), typeof(RobeOfTheEclipse), typeof(RobeOfTheEquinox), typeof(SoulSeeker), typeof(TalonBite), typeof(TotemOfVoid), typeof(WildfireBow), - typeof(Windsong),typeof(UrcuchiallianRidingShoes) + typeof(Windsong) }; // true - dungeon is enabled, false - dungeon is disabled private static bool m_PalaceOfParoxysmus; diff --git a/Scripts/Services/XmlSpawner/XmlSpawner Core/XmlSpawner2.cs b/Scripts/Services/XmlSpawner/XmlSpawner Core/XmlSpawner2.cs index 9cd7074..7690e52 100755 --- a/Scripts/Services/XmlSpawner/XmlSpawner Core/XmlSpawner2.cs +++ b/Scripts/Services/XmlSpawner/XmlSpawner Core/XmlSpawner2.cs @@ -2236,9 +2236,9 @@ namespace Server.Mobiles public bool SomeOneHasGumpOpen { get - { - // go through all online mobiles and see if any have xmlspawner gumps open - List states = NetState.Instances; + { + // go through all online mobiles and see if any have xmlspawner gumps open + IList states = NetState.Instances; for (int i = 0; i < states.Count; ++i) { diff --git a/Scripts/Spells/Base/SpellHelper.cs b/Scripts/Spells/Base/SpellHelper.cs index 89218bb..b7672f1 100755 --- a/Scripts/Spells/Base/SpellHelper.cs +++ b/Scripts/Spells/Base/SpellHelper.cs @@ -159,12 +159,12 @@ namespace Server.Spells { return CheckMulti(p, map, true, 0); } - + public static bool CheckMulti(Point3D p, Map map, bool houses) { return CheckMulti(p, map, houses, 0); } - + public static bool CheckMulti(Point3D p, Map map, bool houses, int housingrange) { if (map == null || map == Map.Internal) @@ -188,7 +188,7 @@ namespace Server.Spells return true; } } - + return false; } @@ -265,7 +265,7 @@ namespace Server.Spells { Type t = item.GetType(); - if(t.IsDefined(typeof(DispellableFieldAttribute), false) || t.IsDefined(typeof(DispellableFieldAttribute), true)) + if (t.IsDefined(typeof(DispellableFieldAttribute), false) || t.IsDefined(typeof(DispellableFieldAttribute), true)) { eable.Free(); return false; @@ -297,17 +297,17 @@ namespace Server.Spells return true; } - + public static bool CanRevealCaster(Mobile m) { if (m is BaseCreature) { BaseCreature c = (BaseCreature)m; - + if (!c.Controlled) return true; } - + return false; } @@ -329,13 +329,13 @@ namespace Server.Spells } } - protected static void RemoveStatOffsetCallback(object state) - { - if (!(state is Mobile)) - return; - // This call has the side-effect of updating all stats - ((Mobile)state).CheckStatTimers(); - } + protected static void RemoveStatOffsetCallback(object state) + { + if (!(state is Mobile)) + return; + // This call has the side-effect of updating all stats + ((Mobile)state).CheckStatTimers(); + } public static bool AddStatOffset(Mobile m, StatType type, int offset, TimeSpan duration) { @@ -365,7 +365,7 @@ namespace Server.Spells } target.AddStatMod(new StatMod(type, name, offset, duration)); - Timer.DelayCall(duration, RemoveStatOffsetCallback, target); + Timer.DelayCall(duration, RemoveStatOffsetCallback, target); return true; } @@ -401,13 +401,13 @@ namespace Server.Spells StatMod mod = target.GetStatMod(name); - if (mod != null) - offset = Math.Max(mod.Offset, offset); + if (mod != null) + offset = Math.Max(mod.Offset, offset); - offset *= -1; + offset *= -1; target.AddStatMod(new StatMod(type, name, offset, TimeSpan.Zero)); - return true; + return true; } public static TimeSpan GetDuration(Mobile caster, Mobile target) @@ -469,7 +469,7 @@ namespace Server.Spells double percent = GetOffsetScalar(caster, target, curse); - switch( type ) + switch (type) { case StatType.Str: return (int)Math.Ceiling(target.RawStr * percent); @@ -636,7 +636,7 @@ namespace Server.Spells } public static IEnumerable AcquireIndirectTargets(Mobile caster, IPoint3D p, Map map, int range, bool losCheck) - { + { if (map == null) { yield break; @@ -825,13 +825,13 @@ namespace Server.Spells private static readonly bool[,] m_Rules = new bool[,] { /*T2A(Fel), Khaldun, Ilshenar, Wind(Tram), Wind(Fel), Dungeons(Fel), Solen(Tram), Solen(Fel), CrystalCave(Malas), Gauntlet(Malas), Gauntlet(Ferry), SafeZone, Stronghold, ChampionSpawn, Dungeons(Tokuno[Malas]), LampRoom(Doom), GuardianRoom(Doom), Heartwood, MLDungeons, SA Dungeons Tomb of Kings Maze of Death SA Entrance, Eodon*/ -/* Recall From */ { false, false, true, true, false, false, true, false, false, false, false, true, true, false, true, false, false, false, false, true, true, false, false, true} , -/* Recall To */ { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }, -/* Gate From */ { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }, -/* Gate To */ { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }, -/* Mark In */ { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }, -/* Tele From */ { true, true, true, true, true, true, true, true, false, true, true, true, false, true, true, true, true, false, true, true, false, false, false, true }, -/* Tele To */ { true, true, true, true, true, true, true, true, false, true, false, false, false, true, true, true, true, false, false, true, false, false, false, true }, +/* Recall From */ { false, false, true, true, false, false, true, false, false, false, false, true, true, false, true, false, false, false, false, true, true, false, false, true} , +/* Recall To */ { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }, +/* Gate From */ { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }, +/* Gate To */ { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }, +/* Mark In */ { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }, +/* Tele From */ { true, true, true, true, true, true, true, true, false, true, true, true, false, true, true, true, true, false, true, true, false, false, false, true }, +/* Tele To */ { true, true, true, true, true, true, true, true, false, true, false, false, false, true, true, true, true, false, false, true, false, false, false, true }, }; public static void SendInvalidMessage(Mobile caster, TravelCheckType type) @@ -866,7 +866,6 @@ namespace Server.Spells return false; } - if (caster != null) { if (caster.IsPlayer()) @@ -887,7 +886,7 @@ namespace Server.Spells // Always allow monsters to teleport if (caster is BaseCreature && (type == TravelCheckType.TeleportTo || type == TravelCheckType.TeleportFrom)) { - BaseCreature bc = (BaseCreature) caster; + BaseCreature bc = (BaseCreature)caster; if (!bc.Controlled && !bc.Summoned) return true; @@ -926,7 +925,7 @@ namespace Server.Spells if ((int)type <= 4 && (IsNewDungeon(caster.Map, caster.Location) || IsNewDungeon(map, loc))) isValid = false; - + #endregion #region High Seas @@ -1206,7 +1205,7 @@ namespace Server.Spells if (map == null) return false; - + GuardedRegion reg = (GuardedRegion)Region.Find(loc, map).GetRegion(typeof(GuardedRegion)); return (reg != null && !reg.IsDisabled()); @@ -1475,7 +1474,7 @@ namespace Server.Spells int damageGiven = AOS.Damage(damageable, from, iDamage, phys, fire, cold, pois, nrgy, chaos, direct, dtype); - if(target != null) + if (target != null) Spells.Mysticism.SpellPlagueSpell.OnMobileDamaged(target); if (target != null && target.DFA != DFAlgorithm.Standard) @@ -1485,7 +1484,7 @@ namespace Server.Spells NegativeAttributes.OnCombatAction(from); - if(from != target) + if (from != target) NegativeAttributes.OnCombatAction(target); } else @@ -1747,11 +1746,11 @@ namespace Server.Spells caster.SendLocalizedMessage(1061091); // You cannot cast that spell in this form. return false; } - else if (caster.Flying && !(spell is VampiricEmbraceSpell)) - { - caster.SendLocalizedMessage(1112567); // You are flying. - return false; - } + else if (caster.Flying && !(spell is VampiricEmbraceSpell)) + { + caster.SendLocalizedMessage(1112567); // You are flying. + return false; + } return true; } diff --git a/ServUO.exe.config b/ServUO.exe.config old mode 100755 new mode 100644 index ef94b7c..8e342a9 --- a/ServUO.exe.config +++ b/ServUO.exe.config @@ -1,6 +1,6 @@ - - - - - + + + + + \ No newline at end of file diff --git a/ServUO.sln b/ServUO.sln index b54c996..853f6a2 100755 --- a/ServUO.sln +++ b/ServUO.sln @@ -1,40 +1,49 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.28307.539 +# Visual Studio Version 17 +VisualStudioVersion = 17.12.35527.113 MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{EF956787-B078-4D19-B03B-4A8F2A4841AD}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + .gitignore = .gitignore + .travis.yml = .travis.yml + LICENSE = LICENSE + README.md = README.md + ServUO.exe.config = ServUO.exe.config + _makedebug = _makedebug + _makerelease = _makerelease + _windebug.bat = _windebug.bat + _winrelease.bat = _winrelease.bat + EndProjectSection +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ultima", "Ultima\Ultima.csproj", "{E08CFBE4-E013-44EE-8829-426D05BC083F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Server", "Server\Server.csproj", "{AE4A9EAA-E0EB-4DC9-9604-BE4289F9F6C3}" +EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Scripts", "Scripts\Scripts.csproj", "{308EA7C6-2873-4E47-AF3F-ABBA3F8AB63E}" ProjectSection(ProjectDependencies) = postProject {AE4A9EAA-E0EB-4DC9-9604-BE4289F9F6C3} = {AE4A9EAA-E0EB-4DC9-9604-BE4289F9F6C3} EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Server", "Server\Server.csproj", "{AE4A9EAA-E0EB-4DC9-9604-BE4289F9F6C3}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{EF956787-B078-4D19-B03B-4A8F2A4841AD}" - ProjectSection(SolutionItems) = preProject - README.md = README.md - EndProjectSection -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ultima", "Ultima\Ultima.csproj", "{E08CFBE4-E013-44EE-8829-426D05BC083F}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU + Debug|x64 = Debug|x64 + Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {308EA7C6-2873-4E47-AF3F-ABBA3F8AB63E}.Debug|Any CPU.ActiveCfg = Release|Any CPU - {308EA7C6-2873-4E47-AF3F-ABBA3F8AB63E}.Debug|Any CPU.Build.0 = Release|Any CPU - {308EA7C6-2873-4E47-AF3F-ABBA3F8AB63E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {308EA7C6-2873-4E47-AF3F-ABBA3F8AB63E}.Release|Any CPU.Build.0 = Release|Any CPU - {AE4A9EAA-E0EB-4DC9-9604-BE4289F9F6C3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AE4A9EAA-E0EB-4DC9-9604-BE4289F9F6C3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AE4A9EAA-E0EB-4DC9-9604-BE4289F9F6C3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AE4A9EAA-E0EB-4DC9-9604-BE4289F9F6C3}.Release|Any CPU.Build.0 = Release|Any CPU - {E08CFBE4-E013-44EE-8829-426D05BC083F}.Debug|Any CPU.ActiveCfg = Release|Any CPU - {E08CFBE4-E013-44EE-8829-426D05BC083F}.Debug|Any CPU.Build.0 = Release|Any CPU - {E08CFBE4-E013-44EE-8829-426D05BC083F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E08CFBE4-E013-44EE-8829-426D05BC083F}.Release|Any CPU.Build.0 = Release|Any CPU + {E08CFBE4-E013-44EE-8829-426D05BC083F}.Debug|x64.ActiveCfg = Debug|x64 + {E08CFBE4-E013-44EE-8829-426D05BC083F}.Debug|x64.Build.0 = Debug|x64 + {E08CFBE4-E013-44EE-8829-426D05BC083F}.Release|x64.ActiveCfg = Release|x64 + {E08CFBE4-E013-44EE-8829-426D05BC083F}.Release|x64.Build.0 = Release|x64 + {AE4A9EAA-E0EB-4DC9-9604-BE4289F9F6C3}.Debug|x64.ActiveCfg = Debug|x64 + {AE4A9EAA-E0EB-4DC9-9604-BE4289F9F6C3}.Debug|x64.Build.0 = Debug|x64 + {AE4A9EAA-E0EB-4DC9-9604-BE4289F9F6C3}.Release|x64.ActiveCfg = Release|x64 + {AE4A9EAA-E0EB-4DC9-9604-BE4289F9F6C3}.Release|x64.Build.0 = Release|x64 + {308EA7C6-2873-4E47-AF3F-ABBA3F8AB63E}.Debug|x64.ActiveCfg = Debug|x64 + {308EA7C6-2873-4E47-AF3F-ABBA3F8AB63E}.Debug|x64.Build.0 = Debug|x64 + {308EA7C6-2873-4E47-AF3F-ABBA3F8AB63E}.Release|x64.ActiveCfg = Release|x64 + {308EA7C6-2873-4E47-AF3F-ABBA3F8AB63E}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Server/AssemblyInfo.cs b/Server/AssemblyInfo.cs index b67b376..a142936 100755 --- a/Server/AssemblyInfo.cs +++ b/Server/AssemblyInfo.cs @@ -4,12 +4,6 @@ using System.Resources; using System.Runtime.InteropServices; #endregion -// -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -// - [assembly: AssemblyTitle("ServUO Server")] [assembly: AssemblyDescription("Ultima Online Server Emulator")] [assembly: AssemblyConfiguration("")] @@ -18,46 +12,9 @@ using System.Runtime.InteropServices; [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: - -[assembly: AssemblyVersion("0.5.*")] -// -// In order to sign your assembly you must specify a key to use. Refer to the -// Microsoft .NET Framework documentation for more information on assembly signing. -// -// Use the attributes below to control which key is used for signing. -// -// Notes: -// (*) If no key is specified, the assembly is not signed. -// (*) KeyName refers to a key that has been installed in the Crypto Service -// Provider (CSP) on your machine. KeyFile refers to a file which contains -// a key. -// (*) If the KeyFile and the KeyName values are both specified, the -// following processing occurs: -// (1) If the KeyName can be found in the CSP, that key is used. -// (2) If the KeyName does not exist and the KeyFile does exist, the key -// in the KeyFile is installed into the CSP and used. -// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. -// When specifying the KeyFile, the location of the KeyFile should be -// relative to the project output directory which is -// %Project Directory%\obj\. For example, if your KeyFile is -// located in the project directory, you would specify the AssemblyKeyFile -// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] -// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework -// documentation for more information on this. -// - +[assembly: AssemblyVersion("57.4")] [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] [assembly: ComVisible(false)] -[assembly: NeutralResourcesLanguage("en")] \ No newline at end of file +[assembly: NeutralResourcesLanguage("en")] diff --git a/Server/Config.cs b/Server/Config.cs index 52d17c9..a8a0528 100755 --- a/Server/Config.cs +++ b/Server/Config.cs @@ -1,9 +1,10 @@ -#region References +#region References using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Net; using System.Reflection; using System.Text; using System.Text.RegularExpressions; @@ -11,822 +12,1977 @@ using System.Text.RegularExpressions; namespace Server { - public static class Config - { - public sealed class Entry : IEquatable, IComparable - { - public int FileIndex { get; private set; } + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] + public class ConfigPropertyAttribute : Attribute + { + public string Scope { get; } - public string File { get; private set; } - public string Scope { get; private set; } + public ConfigPropertyAttribute(string scope) + { + Scope = scope; + } + } - public string Desc { get; set; } + public static class Config + { + public sealed class Entry : IEquatable, IComparable + { + private readonly string m_InitialValue; + private readonly bool m_InitialDefault; - public string Key { get; set; } - public string Value { get; set; } + private int? m_Hash; - public bool UseDefault { get; set; } + public int FileIndex { get; private set; } - public Entry(string file, int fileIndex, string scope, string desc, string key, string value, bool useDefault) - { - File = file; - FileIndex = fileIndex; + public string File { get; private set; } + public string Scope { get; private set; } - Scope = scope; - Desc = desc; + public string Desc { get; set; } - Key = key; - Value = value; + public string Key { get; private set; } + public string Value { get; private set; } - UseDefault = useDefault; - } + public object Object { get; private set; } - public override string ToString() - { - return String.Format("{0}.{1}{2}={3}", Scope, UseDefault ? "@" : "", Key, Value); - } + public bool UseDefault { get; set; } - public override int GetHashCode() - { - unchecked - { - var hash = -1; + public Entry(string file, int fileIndex, string scope, string desc, string key, string value, object state, bool useDefault) + { + m_InitialValue = value; + m_InitialDefault = useDefault; - hash = (hash * 397) ^ File.GetHashCode(); - hash = (hash * 397) ^ Scope.GetHashCode(); - hash = (hash * 397) ^ Key.GetHashCode(); + File = file; + FileIndex = fileIndex; - return hash; - } - } + Scope = scope; + Desc = desc; - public override bool Equals(object obj) - { - return obj is Entry && Equals((Entry)obj); - } + Key = key; + Value = value; + Object = state; - public bool Equals(Entry other) - { - if (ReferenceEquals(other, null)) - { - return false; - } + UseDefault = useDefault; + } - if (ReferenceEquals(other, this)) - { - return true; - } + public void Set(string value, object state) + { + if (m_InitialValue == value) + { + UseDefault = m_InitialDefault; + } + else if (Value != value) + { + UseDefault = state == null; + } - return Insensitive.Equals(File, other.File) && // - Insensitive.Equals(Scope, other.Scope) && // - Insensitive.Equals(Key, other.Key); - } + var oldValue = Value; + var oldObject = Object; - public int CompareTo(Entry other) - { - if (other == null) - { - return -1; - } + Value = value; + Object = state; - if (!Insensitive.Equals(File, other.File)) - { - return Insensitive.Compare(File, other.File); - } + OnEntryChanged?.Invoke(this, oldValue, oldObject); + } - return FileIndex.CompareTo(other.FileIndex); - } - } + public override string ToString() + { + if (UseDefault) + { + return $"{Scope}.@{Key}={Value}"; + } - private static bool _Initialized; + return $"{Scope}.{Key}={Value}"; + } - private static readonly string _Path = Path.Combine(Core.BaseDirectory, "Config"); + public override int GetHashCode() + { + if (m_Hash != null) + { + return m_Hash.Value; + } - private static readonly IFormatProvider _NumFormatter = CultureInfo.InvariantCulture.NumberFormat; + unchecked + { + var hash = -1; - private static readonly Dictionary _Entries = - new Dictionary(StringComparer.OrdinalIgnoreCase); + hash = (hash * 397) ^ File.GetHashCode(); + hash = (hash * 397) ^ Scope.GetHashCode(); + hash = (hash * 397) ^ Key.GetHashCode(); - public static IEnumerable Entries { get { return _Entries.Values; } } + m_Hash = hash; - public static void Load() - { - if (_Initialized) - { - return; - } + return hash; + } + } - _Initialized = true; + public override bool Equals(object obj) + { + return obj is Entry e && Equals(e); + } - if (!Directory.Exists(_Path)) - { - Directory.CreateDirectory(_Path); - } + public bool Equals(Entry other) + { + if (other is null) + { + return false; + } - IEnumerable files; + if (ReferenceEquals(other, this)) + { + return true; + } - try - { - files = Directory.EnumerateFiles(_Path, "*.cfg", SearchOption.AllDirectories); - } - catch (DirectoryNotFoundException) - { - Console.WriteLine("Warning: No configuration files found!"); - return; - } + return Insensitive.Equals(File, other.File) && Insensitive.Equals(Scope, other.Scope) && Insensitive.Equals(Key, other.Key); + } - foreach (var path in files) - { - try - { - LoadFile(path); - } - catch (Exception e) - { - Console.WriteLine("Warning: Failed to load configuration file:"); - Console.WriteLine(path); - Utility.PushColor(ConsoleColor.Red); - Console.WriteLine(e.Message); - Utility.PopColor(); + public int CompareTo(Entry other) + { + if (other == null) + { + return -1; + } - ConsoleKey key; + if (!Insensitive.Equals(File, other.File)) + { + return Insensitive.Compare(File, other.File); + } - do + return FileIndex.CompareTo(other.FileIndex); + } + } + + private static bool _Initialized; + + private static readonly string _Path = Path.Combine(Core.BaseDirectory, "Config"); + + private static readonly HashSet _Warned = new HashSet(StringComparer.InvariantCultureIgnoreCase); + + private static readonly Dictionary _Entries = new Dictionary(StringComparer.InvariantCultureIgnoreCase); + + public static IEnumerable Entries => _Entries.Values; + + public static IFormatProvider NumFormatter => CultureInfo.InvariantCulture.NumberFormat; + + public static event Action OnEntryChanged; + + public static Entry Find(string key) + { + Load(); + + _ = _Entries.TryGetValue(key, out var e); + + return e; + } + + public static void Dump(string scope) + { + Utility.PushColor(ConsoleColor.DarkYellow); + Dump(Console.Out, scope); + Utility.PopColor(); + } + + public static void Dump(TextWriter output, string scope) + { + Load(); + + if (_Entries.Count > 0) + { + var count = 0; + + foreach (var e in _Entries.Values) + { + if (string.IsNullOrWhiteSpace(scope) || Insensitive.Equals(e.Scope, scope)) { - Console.WriteLine("Ignore this warning? (y/n)"); + if (++count == 1) + { + output.WriteLine(); + } - key = Console.ReadKey(true).Key; + output.WriteLine(e); } - while (key != ConsoleKey.Y && key != ConsoleKey.N); - - if (key != ConsoleKey.Y) - { - Console.WriteLine("Press any key to exit..."); - Console.ReadKey(); - - Core.Kill(false); - - return; - } - } - } + } - if (Core.Debug) - { - Console.WriteLine(); - - foreach (var e in _Entries.Values) - { - Console.WriteLine(e); - } - - Console.WriteLine(); - } - } - - private static void LoadFile(string path) - { - var info = new FileInfo(path); - - if (!info.Exists) - { - throw new FileNotFoundException(); - } - - path = info.Directory != null ? info.Directory.FullName : String.Empty; - - var io = path.IndexOf(_Path, StringComparison.OrdinalIgnoreCase); - - if (io > -1) - { - path = path.Substring(io + _Path.Length); - } - - var parts = path.Split(Path.DirectorySeparatorChar); - - var scope = String.Join(".", parts.Where(p => !String.IsNullOrWhiteSpace(p))); - - if (scope.Length > 0) - { - scope += "."; - } - - scope += Path.GetFileNameWithoutExtension(info.Name); - - var lines = File.ReadAllLines(info.FullName); - - var desc = new List(0x10); - - for (int i = 0, idx = 0; i < lines.Length; i++) - { - var line = lines[i].Trim(); - - if (String.IsNullOrWhiteSpace(line)) - { - desc.Clear(); - continue; - } - - if (line.StartsWith("#")) - { - desc.Add(line.TrimStart('#').Trim()); - continue; - } - - var useDef = false; - - if (line.StartsWith("@")) - { - useDef = true; - line = line.TrimStart('@').Trim(); - } - - io = line.IndexOf('='); - - if (io < 0) - { - throw new FormatException(String.Format("Bad format at line {0}", i + 1)); - } - - var key = line.Substring(0, io); - var val = line.Substring(io + 1); - - if (String.IsNullOrWhiteSpace(key)) - { - throw new NullReferenceException(String.Format("Key can not be null at line {0}", i + 1)); - } - - key = key.Trim(); - - if (String.IsNullOrEmpty(val)) - { - val = null; - } - - var e = new Entry(info.FullName, idx++, scope, String.Join(String.Empty, desc), key, val, useDef); - - _Entries[String.Format("{0}.{1}", e.Scope, e.Key)] = e; - - desc.Clear(); - } - } - - public static void Save() - { - if (!_Initialized) - { - Load(); - } - - if (!Directory.Exists(_Path)) - { - Directory.CreateDirectory(_Path); - } - - foreach (var g in _Entries.Values.ToLookup(e => e.File)) - { - try - { - SaveFile(g.Key, g.OrderBy(e => e.FileIndex)); - } - catch (Exception e) - { - Console.WriteLine("Warning: Failed to save configuration file:"); - Console.WriteLine(g.Key); - Utility.PushColor(ConsoleColor.Red); - Console.WriteLine(e.Message); - Utility.PopColor(); - } - } - } - - private static void SaveFile(string path, IEnumerable entries) - { - var content = new StringBuilder(0x1000); - var line = new StringBuilder(0x80); - - foreach (var e in entries) - { - content.AppendLine(); - - if (!String.IsNullOrWhiteSpace(e.Desc)) - { - line.Clear(); - - foreach (var word in e.Desc.Split(' ')) - { - if ((line + word).Length > 100) - { - content.AppendLine(String.Format("# {0}", line)); - line.Clear(); - } - - line.AppendFormat("{0} ", word); - } - - if (line.Length > 0) - { - content.AppendLine(String.Format("# {0}", line)); - line.Clear(); - } - } - - content.AppendLine(String.Format("{0}{1}={2}", e.UseDefault ? "@" : String.Empty, e.Key, e.Value)); - } - - File.WriteAllText(path, content.ToString()); - } - - public static Entry Find(string key) - { - Entry e; - _Entries.TryGetValue(key, out e); - return e; - } - - private static void InternalSet(string key, string value) - { - var e = Find(key); - - if (e != null) - { - e.Value = value; - e.UseDefault = false; - return; - } - - var parts = key.Split('.'); - var realKey = parts.Last(); - - parts = parts.Take(parts.Length - 1).ToArray(); - - var file = new FileInfo(Path.Combine(_Path, Path.Combine(parts) + ".cfg")); - var idx = _Entries.Values.Where(o => Insensitive.Equals(o.File, file.FullName)).Select(o => o.FileIndex).DefaultIfEmpty().Max(); - - _Entries[key] = new Entry(file.FullName, idx, String.Join(".", parts), String.Empty, realKey, value, false); - } - - public static void Set(string key, string value) - { - InternalSet(key, value); - } - - public static void Set(string key, char value) - { - InternalSet(key, value.ToString(_NumFormatter)); - } - - public static void Set(string key, sbyte value) - { - InternalSet(key, value.ToString(_NumFormatter)); - } - - public static void Set(string key, byte value) - { - InternalSet(key, value.ToString(_NumFormatter)); - } - - public static void Set(string key, short value) - { - InternalSet(key, value.ToString(_NumFormatter)); - } - - public static void Set(string key, ushort value) - { - InternalSet(key, value.ToString(_NumFormatter)); - } - - public static void Set(string key, int value) - { - InternalSet(key, value.ToString(_NumFormatter)); - } - - public static void Set(string key, uint value) - { - InternalSet(key, value.ToString(_NumFormatter)); - } - - public static void Set(string key, long value) - { - InternalSet(key, value.ToString(_NumFormatter)); - } - - public static void Set(string key, ulong value) - { - InternalSet(key, value.ToString(_NumFormatter)); - } - - public static void Set(string key, float value) - { - InternalSet(key, value.ToString(_NumFormatter)); - } - - public static void Set(string key, double value) - { - InternalSet(key, value.ToString(_NumFormatter)); - } - - public static void Set(string key, decimal value) - { - InternalSet(key, value.ToString(_NumFormatter)); - } - - public static void Set(string key, bool value) - { - InternalSet(key, value ? "true" : "false"); - } - - public static void Set(string key, TimeSpan value) - { - InternalSet(key, value.ToString()); - } - - public static void Set(string key, DateTime value) - { - InternalSet(key, value.ToString(CultureInfo.InvariantCulture)); - } - - public static void SetEnum(string key, T value) where T : struct, IConvertible - { - var t = typeof(T); - - if (!t.IsEnum) - { - throw new ArgumentException("T must be an enumerated type"); - } - - var vals = Enum.GetValues(t).Cast(); - - foreach (T o in vals.Where(o => o.Equals(value))) - { - InternalSet(key, o.ToString(CultureInfo.InvariantCulture)); - return; - } - - throw new ArgumentException("Enumerated value not found"); - } - - private static void Warn(string key) - { - Utility.PushColor(ConsoleColor.Yellow); - Console.WriteLine("Config: Warning, '{0}' invalid value for '{1}'", typeof(T), key); - Utility.PopColor(); - } - - private static string InternalGet(string key) - { - if (!_Initialized) - { - Load(); - } - - Entry e; - - if (_Entries.TryGetValue(key, out e) && e != null) - { - return e.UseDefault ? null : e.Value; - } - - Utility.PushColor(ConsoleColor.Yellow); - Console.WriteLine("Config: Warning, using default value for {0}", key); - Utility.PopColor(); - - return null; - } - - public static string Get(string key, string defaultValue) - { - return InternalGet(key) ?? defaultValue; - } - - public static sbyte Get(string key, sbyte defaultValue) - { - var ret = defaultValue; - var value = InternalGet(key); - - if (value == null || sbyte.TryParse(value, NumberStyles.Any, _NumFormatter, out ret)) - { - return ret; - } - - Warn(key); - - return defaultValue; - } - - public static byte Get(string key, byte defaultValue) - { - var ret = defaultValue; - var value = InternalGet(key); + if (count > 0) + { + output.WriteLine(); + } + } + } + + public static void Unload() + { + _Initialized = false; + + _Warned.Clear(); + _Entries.Clear(); + } + + public static void Load() + { + if (_Initialized) + { + return; + } + + _Initialized = true; + + Console.WriteLine("Config: Loading..."); + + _ = Directory.CreateDirectory(_Path); + + IEnumerable files; + + try + { + files = Directory.EnumerateFiles(_Path, "*.cfg", SearchOption.AllDirectories); + } + catch (DirectoryNotFoundException) + { + Utility.PushColor(ConsoleColor.Yellow); + Console.WriteLine("Config: Files Not Found"); + Utility.PopColor(); - if (value == null || byte.TryParse(value, NumberStyles.Any & ~NumberStyles.AllowLeadingSign, _NumFormatter, out ret)) - { - return ret; - } + return; + } - Warn(key); + foreach (var path in files) + { + try + { + LoadFile(path); + } + catch (Exception e) + { + var relativePath = path.Replace(Path.GetDirectoryName(_Path), string.Empty); - return defaultValue; - } + Utility.PushColor(ConsoleColor.Red); + Console.WriteLine($"Config: Load Failed [{e.Message}]"); + Utility.PopColor(); + Utility.PushColor(ConsoleColor.Gray); + Console.WriteLine(relativePath); + Utility.PopColor(); - public static short Get(string key, short defaultValue) - { - var ret = defaultValue; - var value = InternalGet(key); + Console.WriteLine("Ignore and continue? (Y/N)"); - if (value == null || short.TryParse(value, NumberStyles.Any, _NumFormatter, out ret)) - { - return ret; - } + var answer = Console.ReadKey(true); - Warn(key); + if (answer.Key == ConsoleKey.N) + { + Console.WriteLine("Press any key to exit..."); - return defaultValue; - } + _ = Console.ReadKey(true); - public static ushort Get(string key, ushort defaultValue) - { - var ret = defaultValue; - var value = InternalGet(key); + Core.Kill(false); - if (value == null || ushort.TryParse(value, NumberStyles.Any & ~NumberStyles.AllowLeadingSign, _NumFormatter, out ret)) - { - return ret; - } + return; + } + } + } - Warn(key); + if (Core.Debug) + { + Utility.PushColor(ConsoleColor.Blue); - return defaultValue; - } + foreach (var e in _Entries.Values) + { + Console.WriteLine(e); + } - public static int Get(string key, int defaultValue) - { - var ret = defaultValue; - var value = InternalGet(key); + Utility.PopColor(); + } + } - if (value == null || int.TryParse(value, NumberStyles.Any, _NumFormatter, out ret)) - { - return ret; - } + public static bool Load(string scope) + { + _ = Directory.CreateDirectory(_Path); - Warn(key); + var success = false; - return defaultValue; - } + var path = Path.Combine(_Path, $"{scope}.cfg"); - public static uint Get(string key, uint defaultValue) - { - var ret = defaultValue; - var value = InternalGet(key); + try + { + LoadFile(path); - if (value == null || uint.TryParse(value, NumberStyles.Any & ~NumberStyles.AllowLeadingSign, _NumFormatter, out ret)) - { - return ret; - } + success = true; + } + catch (Exception e) + { + var relativePath = path.Replace(Path.GetDirectoryName(_Path), string.Empty); - Warn(key); + Utility.PushColor(ConsoleColor.Red); + Console.WriteLine($"Config: Load Failed [{e.Message}]"); + Utility.PopColor(); + Utility.PushColor(ConsoleColor.Gray); + Console.WriteLine(relativePath, ConsoleColor.Gray); + Utility.PopColor(); + } - return defaultValue; - } + return success; + } - public static long Get(string key, long defaultValue) - { - var ret = defaultValue; - var value = InternalGet(key); + private static void LoadFile(string path) + { + var info = new FileInfo(path); - if (value == null || long.TryParse(value, NumberStyles.Any, _NumFormatter, out ret)) - { - return ret; - } + if (!info.Exists) + { + throw new FileNotFoundException(); + } - Warn(key); + path = info.Directory != null ? info.Directory.FullName : string.Empty; + + var io = path.IndexOf(_Path, StringComparison.OrdinalIgnoreCase); + + if (io > -1) + { + path = path.Substring(io + _Path.Length); + } + + var parts = path.Split(Path.DirectorySeparatorChar); - return defaultValue; - } + var scope = string.Join(".", parts.Where(p => !string.IsNullOrWhiteSpace(p))); - public static ulong Get(string key, ulong defaultValue) - { - var ret = defaultValue; - var value = InternalGet(key); + if (scope.Length > 0) + { + scope += "."; + } + + scope += Path.GetFileNameWithoutExtension(info.Name); + + var lines = File.ReadAllLines(info.FullName); + + var desc = new List(0x10); - if (value == null || ulong.TryParse(value, NumberStyles.Any & ~NumberStyles.AllowLeadingSign, _NumFormatter, out ret)) - { - return ret; - } + for (int i = 0, idx = 0; i < lines.Length; i++) + { + var line = lines[i].Trim(); + + if (string.IsNullOrWhiteSpace(line)) + { + desc.Clear(); + continue; + } + + if (line.StartsWith("#")) + { + desc.Add(line.TrimStart('#').Trim()); + continue; + } + + var useDef = false; + + if (line.StartsWith("@")) + { + useDef = true; + line = line.TrimStart('@').Trim(); + } + + io = line.IndexOf('='); + + if (io < 0) + { + throw new FormatException($"Bad format at line {i + 1}"); + } + + var key = line.Substring(0, io); + var val = line.Substring(io + 1); + + if (string.IsNullOrWhiteSpace(key)) + { + throw new NullReferenceException($"Key can not be null at line {i + 1}"); + } + + key = key.Trim(); + + if (string.IsNullOrEmpty(val)) + { + val = null; + } + + var e = new Entry(info.FullName, idx++, scope, string.Join("\n", desc), key, val, null, useDef); + + _Entries[$"{e.Scope}.{e.Key}"] = e; + + desc.Clear(); + } + } + + public static void Save() + { + Load(); + + _ = Directory.CreateDirectory(_Path); + + foreach (var g in _Entries.Values.GroupBy(e => e.File)) + { + try + { + SaveFile(g.Key, g.OrderBy(e => e.FileIndex)); + } + catch (Exception e) + { + var relativePath = g.Key.Replace(Path.GetDirectoryName(_Path), string.Empty); - Warn(key); + Utility.PushColor(ConsoleColor.Red); + Console.WriteLine($"Config: Save Failed [{e.Message}]"); + Utility.PopColor(); + Utility.PushColor(ConsoleColor.Gray); + Console.WriteLine(relativePath, ConsoleColor.Gray); + Utility.PopColor(); + } + } + } - return defaultValue; - } + public static void Save(string scope) + { + if (!_Entries.Values.Any(e => Insensitive.Equals(e.Scope, scope))) + { + _ = Load(scope); + } + + _ = Directory.CreateDirectory(_Path); + + foreach (var g in _Entries.Values.Where(e => Insensitive.Equals(e.Scope, scope)).GroupBy(e => e.File)) + { + try + { + SaveFile(g.Key, g.OrderBy(e => e.FileIndex)); + } + catch (Exception e) + { + var relativePath = g.Key.Replace(Path.GetDirectoryName(_Path), string.Empty); + + Utility.PushColor(ConsoleColor.Red); + Console.WriteLine($"Config: Save Failed [{e.Message}]"); + Utility.PopColor(); + Utility.PushColor(ConsoleColor.Gray); + Console.WriteLine(relativePath); + Utility.PopColor(); + } + } + } + + private static void SaveFile(string path, IEnumerable entries) + { + var content = new StringBuilder(0x1000); + + foreach (var e in entries) + { + _ = content.AppendLine(); + + if (!string.IsNullOrWhiteSpace(e.Desc)) + { + var split = e.Desc.Split('\n'); + + if (split.Length > 0) + { + foreach (var line in split) + { + _ = content.AppendLine($"# {line}"); + } + } + else + { + _ = content.AppendLine($"# {e.Desc}"); + } + } + + _ = content.AppendLine($"{(e.UseDefault ? "@" : string.Empty)}{e.Key}={e.Value}"); + } + + var dir = Path.GetDirectoryName(path); + + _ = Directory.CreateDirectory(dir); + + File.WriteAllText(path, content.ToString()); + } + + private static string GetFilePath(ref string key, out string scope) + { + var parts = key.Split('.'); + + key = parts[parts.Length - 1]; + + Array.Resize(ref parts, parts.Length - 1); + + scope = string.Join(".", parts); + + if (_Gen) + { + return Path.Combine(_Path, "_GEN", Path.Combine(parts) + ".cfg"); + } + + return Path.Combine(_Path, Path.Combine(parts) + ".cfg"); + } + + #region Setters + + private static void InternalSet(string key, Stringifier stringify, T state) + { + _ = _Warned.Remove(key); + + var value = stringify(state); + + if (_Entries.TryGetValue(key, out var e) && e != null) + { + e.Set(value, state); + return; + } + + var path = GetFilePath(ref key, out var scope); + + var idx = _Entries.Values.Where(o => Insensitive.Equals(o.File, path)).Select(o => o.FileIndex).DefaultIfEmpty().Max(); + + _Entries[key] = new Entry(path, idx, scope, string.Empty, key, value, state, false); + } + + public static void Set(string key, T value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, string value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, char value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, sbyte value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, byte value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, short value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, ushort value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, int value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, uint value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, long value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, ulong value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, float value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, double value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, decimal value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, bool value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, TimeSpan value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, DateTime value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, IPAddress value) + { + InternalSet(key, ToString, value); + } + + public static void Set(string key, Version value) + { + InternalSet(key, ToString, value); + } + + public static void SetEnum(string key, T value) where T : Enum + { + InternalSet(key, ToEnumString, value); + } + + public static void SetDelegate(string key, T value) where T : Delegate + { + InternalSet(key, ToDelegateString, value); + } + + public static void SetArray(string key, T[] value) + { + InternalSet(key, ToArrayString, value); + } + + #endregion + + #region Getters + + private static bool InternalGet(string key, out Entry entry) + { + Load(); + + if (!_Gen && Core.Debug && _Entries.TryGetValue($"_DEBUG.{key}", out entry) && entry != null) + { + return true; + } + + if (_Entries.TryGetValue(key, out entry) && entry != null) + { + return true; + } + + return false; + } + + private static T InternalGet(string key, T def, Parser parser) + { + if (InternalGet(key, out var entry) && !entry.UseDefault) + { + if (entry.Object is T val) + { + return val; + } + + if (entry.Value != null) + { + if (parser(entry.Value, out val)) + { + entry.Set(entry.Value, val); + + return val; + } + + if (_Warned.Add(key)) + { + Utility.PushColor(ConsoleColor.Yellow); + Console.WriteLine($"Config: Invalid Value [{key}, '{entry.Value}']"); + Utility.PopColor(); + } + } + } + + return def; + } + + public static T Get(string key, T defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static string Get(string key, string defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static sbyte Get(string key, sbyte defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static byte Get(string key, byte defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static short Get(string key, short defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static ushort Get(string key, ushort defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static int Get(string key, int defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static uint Get(string key, uint defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static long Get(string key, long defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static ulong Get(string key, ulong defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static float Get(string key, float defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static double Get(string key, double defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static decimal Get(string key, decimal defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static bool Get(string key, bool defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static TimeSpan Get(string key, TimeSpan defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static DateTime Get(string key, DateTime defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static Type Get(string key, Type defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static IPAddress Get(string key, IPAddress defaultValue) + { + return Utility.Intern(InternalGet(key, defaultValue, TryParse)); + } + + public static Version Get(string key, Version defaultValue) + { + return InternalGet(key, defaultValue, TryParse); + } + + public static T GetEnum(string key, T defaultValue) where T : struct, Enum + { + return InternalGet(key, defaultValue, TryParseEnum); + } + + public static T GetDelegate(string key, T defaultValue) where T : Delegate + { + return InternalGet(key, defaultValue, TryParseDelegate); + } + + public static T[] GetArray(string key, T[] defaultValue) + { + return InternalGet(key, defaultValue, TryParseArray); + } + + public static T[] GetArray(string key, bool defaultEmpty) + { + return GetArray(key, defaultEmpty ? Array.Empty() : null); + } + + #endregion + + #region Stringifiers + + private delegate string Stringifier(T value); + + private static readonly Dictionary _DetectedStringifiers = new Dictionary(); + + public static string ToString(T value) + { + if (value == null) + { + return string.Empty; + } + + var type = typeof(T); + + if (type.IsArray) + { + try + { + if (!_DetectedStringifiers.TryGetValue(typeof(Array), out var stringify)) + { + _DetectedStringifiers[typeof(Array)] = stringify = typeof(Config).GetMethod("ToArrayString", new[] { type }); + } + + if (stringify != null) + { + return (string)stringify.Invoke(null, new object[] { value }); + } + } + catch + { } + + return string.Empty; + } + + if (type.IsEnum) + { + try + { + if (!_DetectedStringifiers.TryGetValue(typeof(Enum), out var stringify)) + { + _DetectedStringifiers[typeof(Enum)] = stringify = typeof(Config).GetMethod("ToEnumString", new[] { type }); + } + + if (stringify != null) + { + return (string)stringify.Invoke(null, new object[] { value }); + } + } + catch + { } + + return string.Empty; + } + + if (type.IsAssignableFrom(typeof(Delegate))) + { + try + { + if (!_DetectedStringifiers.TryGetValue(typeof(Delegate), out var stringify)) + { + _DetectedStringifiers[typeof(Delegate)] = stringify = typeof(Config).GetMethod("ToDelegateString", new[] { type }); + } + + if (stringify != null) + { + return (string)stringify.Invoke(null, new object[] { value }); + } + } + catch + { } + + return string.Empty; + } + + try + { + if (!_DetectedStringifiers.TryGetValue(type, out var stringify)) + { + _DetectedStringifiers[type] = stringify = typeof(Config).GetMethod("ToString", new[] { type }); + } + + if (stringify != null) + { + return (string)stringify.Invoke(null, new object[] { value }); + } + + return value.ToString(); + } + catch + { } + + return string.Empty; + } + + public static string ToString(string value) + { + return value ?? string.Empty; + } + + public static string ToString(char value) + { + return value.ToString(NumFormatter); + } + + public static string ToString(sbyte value) + { + return value.ToString(NumFormatter); + } + + public static string ToString(byte value) + { + return value.ToString(NumFormatter); + } + + public static string ToString(short value) + { + return value.ToString(NumFormatter); + } + + public static string ToString(ushort value) + { + return value.ToString(NumFormatter); + } + + public static string ToString(int value) + { + return value.ToString(NumFormatter); + } + + public static string ToString(uint value) + { + return value.ToString(NumFormatter); + } + + public static string ToString(long value) + { + return value.ToString(NumFormatter); + } + + public static string ToString(ulong value) + { + return value.ToString(NumFormatter); + } + + public static string ToString(float value) + { + return value.ToString(NumFormatter); + } + + public static string ToString(double value) + { + return value.ToString(NumFormatter); + } + + public static string ToString(decimal value) + { + return value.ToString(NumFormatter); + } + + public static string ToString(bool value) + { + return value ? bool.TrueString : bool.FalseString; + } + + public static string ToString(TimeSpan value) + { + return value.ToString(); + } + + public static string ToString(DateTime value) + { + return value.ToString(CultureInfo.InvariantCulture); + } + + public static string ToString(IPAddress value) + { + return value.ToString(); + } + + public static string ToString(Version value) + { + return value.ToString(); + } + + public static string ToEnumString(T value) where T : Enum + { + return value.ToString(); + } + + public static string ToDelegateString(T value) where T : Delegate + { + return $"{value.Method.DeclaringType.FullName}.{value.Method.Name}"; + } + + public static string ToArrayString(T[] value) + { + if (value == null) + { + return string.Empty; + } + + if (value.Length == 0) + { + return "[]"; + } + + var type = typeof(T); + + var isString = type == typeof(string); + + var encoded = new StringBuilder(); + + _ = encoded.Append('['); + + for (var i = 0; i < value.Length; i++) + { + var val = value[i]; + + if (i > 0) + { + _ = encoded.Append(", "); + } + + if (val != null) + { + var str = ToString(val); + + var isSubArray = val?.GetType()?.IsArray == true; + + if (isSubArray) + { + _ = encoded.Append('\t'); + } + + var isSubString = isString || val?.GetType() == typeof(string); + + if (isSubString) + { + _ = encoded.Append('"'); + } + + foreach (var c in str) + { + switch (c) + { + case '"': + _ = encoded.Append("\\\""); + break; + case '\\': + _ = encoded.Append("\\\\"); + break; + case '\b': + _ = encoded.Append("\\b"); + break; + case '\f': + _ = encoded.Append("\\f"); + break; + case '\n': + _ = encoded.Append("\\n"); + break; + case '\r': + _ = encoded.Append("\\r"); + break; + case '\t': + _ = encoded.Append("\\t"); + break; + default: + { + var sur = Convert.ToInt32(c); + + if (sur >= 32 && sur <= 126) + { + _ = encoded.Append(c); + } + else + { + _ = encoded.Append("\\u" + Convert.ToString(sur, 16).PadLeft(4, '0')); + } + } + + break; + } + } + + if (isSubString) + { + _ = encoded.Append('"'); + } + + if (isSubArray) + { + _ = encoded.Append(Environment.NewLine); + } + } + } + + _ = encoded.Append(']'); + + var result = encoded.ToString(); + + _ = encoded.Clear(); + + return result; + } + + #region Args + + public static string ToArgsString(params object[] args) + { + return ToArrayString(args); + } + + #endregion + + #endregion + + #region Parsers + + private delegate bool Parser(string input, out T value); + + private static readonly Dictionary _DetectedParsers = new Dictionary(); + private static readonly Dictionary _DetectedTryParsers = new Dictionary(); + + public static bool TryParse(string input, out T value) + { + value = default; + + try + { + var type = typeof(T); + + if (type == typeof(string)) + { + if (input == null) + { + value = default; + } + else if (input.Length == 0) + { + value = (T)(object)string.Empty; + } + else + { + value = (T)(object)input.Trim().Trim('"'); + } + + return true; + } + + if (string.IsNullOrEmpty(input)) + { + value = default; + return false; + } + + if (type.IsArray) + { + try + { + if (!_DetectedTryParsers.TryGetValue(typeof(Array), out var tryParse)) + { + _DetectedTryParsers[typeof(Array)] = tryParse = typeof(Config).GetMethod("TryParseArray", new[] { typeof(string), type.MakeByRefType() }); + } + + if (tryParse != null) + { + var args = new object[] { input.Trim(), default(T) }; + + if ((bool)tryParse.Invoke(null, args)) + { + value = (T)args[1]; + return true; + } + } + } + catch + { } + + return false; + } + + if (type.IsEnum) + { + try + { + if (!_DetectedTryParsers.TryGetValue(typeof(Enum), out var tryParse)) + { + _DetectedTryParsers[typeof(Enum)] = tryParse = typeof(Config).GetMethod("TryParseEnum", new[] { typeof(string), type.MakeByRefType() }); + } + + if (tryParse != null) + { + var args = new object[] { input.Trim(), default(T) }; + + if ((bool)tryParse.Invoke(null, args)) + { + value = (T)args[1]; + return true; + } + } + } + catch + { } + + return false; + } + + if (type.IsAssignableFrom(typeof(Delegate))) + { + try + { + if (!_DetectedTryParsers.TryGetValue(typeof(Delegate), out var tryParse)) + { + _DetectedTryParsers[typeof(Delegate)] = tryParse = typeof(Config).GetMethod("TryParseDelegate", new[] { typeof(string), type.MakeByRefType() }); + } + + if (tryParse != null) + { + var args = new object[] { input.Trim(), value }; + + if ((bool)tryParse.Invoke(null, args)) + { + value = (T)args[1]; + return true; + } + } + } + catch + { } + + return false; + } + + try + { + if (!_DetectedTryParsers.TryGetValue(type, out var tryParse)) + { + _DetectedTryParsers[type] = tryParse = typeof(Config).GetMethod("TryParse", new[] { typeof(string), type.MakeByRefType() }); + } + + var args = new object[] { input.Trim(), value }; + + if (tryParse != null && (bool)tryParse.Invoke(null, args)) + { + value = (T)args[1]; + return true; + } + } + catch + { } + + if (type.IsDefined(typeof(ParsableAttribute))) + { + try + { + if (!_DetectedParsers.TryGetValue(type, out var parse)) + { + _DetectedParsers[type] = parse = type.GetMethod("Parse", new[] { typeof(string) }); + } + + if (parse != null) + { + value = (T)parse.Invoke(null, new object[] { input.Trim() }); + return true; + } + } + catch + { } + } + else + { + try + { + if (!_DetectedTryParsers.TryGetValue(type, out var tryParse)) + { + _DetectedTryParsers[type] = tryParse = type.GetMethod("TryParse", new[] { typeof(string), type.MakeByRefType() }); + } + + var args = new object[] { input.Trim(), value }; + + if (tryParse != null && (bool)tryParse.Invoke(null, args)) + { + value = (T)args[1]; + return true; + } + } + catch + { } + } + } + catch + { } + + return false; + } + + public static bool TryParse(string input, out string value) + { + return (value = input) != null; + } + + public static bool TryParse(string input, out sbyte value) + { + return sbyte.TryParse(input, NumberStyles.Any, NumFormatter, out value); + } + + public static bool TryParse(string input, out byte value) + { + return byte.TryParse(input, NumberStyles.Any & ~NumberStyles.AllowLeadingSign, NumFormatter, out value); + } + + public static bool TryParse(string input, out short value) + { + return short.TryParse(input, NumberStyles.Any, NumFormatter, out value); + } + + public static bool TryParse(string input, out ushort value) + { + return ushort.TryParse(input, NumberStyles.Any & ~NumberStyles.AllowLeadingSign, NumFormatter, out value); + } + + public static bool TryParse(string input, out int value) + { + return int.TryParse(input, NumberStyles.Any, NumFormatter, out value); + } + + public static bool TryParse(string input, out uint value) + { + return uint.TryParse(input, NumberStyles.Any & ~NumberStyles.AllowLeadingSign, NumFormatter, out value); + } + + public static bool TryParse(string input, out long value) + { + return long.TryParse(input, NumberStyles.Any, NumFormatter, out value); + } + + public static bool TryParse(string input, out ulong value) + { + return ulong.TryParse(input, NumberStyles.Any & ~NumberStyles.AllowLeadingSign, NumFormatter, out value); + } + + public static bool TryParse(string input, out float value) + { + return float.TryParse(input, NumberStyles.Any, NumFormatter, out value); + } + + public static bool TryParse(string input, out double value) + { + return double.TryParse(input, NumberStyles.Any, NumFormatter, out value); + } + + public static bool TryParse(string input, out decimal value) + { + return decimal.TryParse(input, NumberStyles.Any, NumFormatter, out value); + } + + public static bool TryParse(string input, out bool value) + { + if (bool.TryParse(input, out value)) + { + return true; + } + + if (Regex.IsMatch(input, @"(true|yes|on|1|enabled)", RegexOptions.IgnoreCase)) + { + value = true; + return true; + } + + if (Regex.IsMatch(input, @"(false|no|off|0|disabled)", RegexOptions.IgnoreCase)) + { + value = false; + return true; + } + + value = false; + return false; + } + + public static bool TryParse(string input, out TimeSpan value) + { + return TimeSpan.TryParse(input, out value); + } + + public static bool TryParse(string input, out DateTime value) + { + return DateTime.TryParse(input, out value); + } + + public static bool TryParse(string input, out Type value) + { + var type = Type.GetType(input, false); + + if (type != null) + { + return (value = type) != null; + } + + if (input.IndexOf('.') < 0) + { + return (value = ScriptCompiler.FindTypeByName(input)) != null; + } + + return (value = ScriptCompiler.FindTypeByFullName(input)) != null; + } + + public static bool TryParse(string input, out IPAddress value) + { + if (IPAddress.TryParse(input, out value)) + { + Utility.Intern(ref value); + + return true; + } + + return false; + } + + public static bool TryParse(string input, out Version value) + { + return Version.TryParse(input, out value); + } + + public static bool TryParseEnum(string input, out T value) where T : struct, Enum + { + return Enum.TryParse(input, out value); + } + + public static bool TryParseDelegate(string input, out T value) where T : Delegate + { + var i = input.LastIndexOf('.'); + + if (i > 0) + { + try + { + if (TryParse(input.Remove(i), out Type target) && target != null) + { + var info = target.GetMethod(input.Substring(i + 1), (BindingFlags)0x38); + + if (info != null && Delegate.CreateDelegate(typeof(T), info) is T d) + { + value = d; + return true; + } + } + } + catch + { } + } - public static float Get(string key, float defaultValue) - { - var ret = defaultValue; - var value = InternalGet(key); + value = null; + return false; + } - if (value == null || float.TryParse(value, NumberStyles.Any, _NumFormatter, out ret)) - { - return ret; - } + #region Args - Warn(key); + public static bool TryParseArgs(string input, out (T1, T2) value) + { + value = default; - return defaultValue; - } + if (TryParse(input, out object[] values) && values.Length >= 2) + { + var index = -1; - public static double Get(string key, double defaultValue) - { - var ret = defaultValue; - var value = InternalGet(key); + value = ((T1)values[++index], (T2)values[++index]); - if (value == null || double.TryParse(value, NumberStyles.Any, _NumFormatter, out ret)) - { - return ret; - } + return true; + } - Warn(key); + return false; + } - return defaultValue; - } + public static bool TryParseArgs(string input, out (T1, T2, T3) value) + { + value = default; - public static decimal Get(string key, decimal defaultValue) - { - var ret = defaultValue; - var value = InternalGet(key); + if (TryParseArray(input, out object[] values) && values.Length >= 3) + { + var index = -1; - if (value == null || decimal.TryParse(value, NumberStyles.Any, _NumFormatter, out ret)) - { - return ret; - } + value = ((T1)values[++index], (T2)values[++index], (T3)values[++index]); - Warn(key); + return true; + } - return defaultValue; - } + return false; + } - public static bool Get(string key, bool defaultValue) - { - var value = InternalGet(key); - - if (value == null) - { - return defaultValue; - } + public static bool TryParseArgs(string input, out (T1, T2, T3, T4) value) + { + value = default; - if (Regex.IsMatch(value, @"(true|yes|on|1|enabled)", RegexOptions.IgnoreCase)) - { - return true; - } + if (TryParseArray(input, out object[] values) && values.Length >= 4) + { + var index = -1; - if (Regex.IsMatch(value, @"(false|no|off|0|disabled)", RegexOptions.IgnoreCase)) - { - return false; - } + value = ((T1)values[++index], (T2)values[++index], (T3)values[++index], (T4)values[++index]); - Warn(key); + return true; + } - return defaultValue; - } + return false; + } - public static TimeSpan Get(string key, TimeSpan defaultValue) - { - var value = InternalGet(key); + public static bool TryParseArgs(string input, out (T1, T2, T3, T4, T5) value) + { + value = default; - TimeSpan ts; + if (TryParseArray(input, out object[] values) && values.Length >= 5) + { + var index = -1; - if (TimeSpan.TryParse(value, out ts)) - { - return ts; - } + value = ((T1)values[++index], (T2)values[++index], (T3)values[++index], (T4)values[++index], (T5)values[++index]); - Warn(key); + return true; + } - return defaultValue; - } + return false; + } - public static DateTime Get(string key, DateTime defaultValue) - { - var value = InternalGet(key); + public static bool TryParseArgs(string input, out (T1, T2, T3, T4, T5, T6) value) + { + value = default; - DateTime dt; + if (TryParseArray(input, out object[] values) && values.Length >= 6) + { + var index = -1; - if (DateTime.TryParse(value, out dt)) - { - return dt; - } + value = ((T1)values[++index], (T2)values[++index], (T3)values[++index], (T4)values[++index], (T5)values[++index], (T6)values[++index]); - Warn(key); + return true; + } - return defaultValue; - } + return false; + } - public static Type Get(string key, Type defaultValue) - { - var value = InternalGet(key); + public static bool TryParseArgs(string input, out (T1, T2, T3, T4, T5, T6, T7) value) + { + value = default; - var t = FindType(value); + if (TryParseArray(input, out object[] values) && values.Length >= 7) + { + var index = -1; - if (t != null) - { - return t; - } + value = ((T1)values[++index], (T2)values[++index], (T3)values[++index], (T4)values[++index], (T5)values[++index], (T6)values[++index], (T7)values[++index]); - Warn(key); + return true; + } - return defaultValue; - } + return false; + } - public static T GetEnum(string key, T defaultValue) where T : struct, IConvertible - { - if (!typeof(T).IsEnum) - { - throw new ArgumentException("T must be an enumerated type"); - } + public static bool TryParseArgs(string input, out (T1, T2, T3, T4, T5, T6, T7, T8) value) + { + value = default; - var value = InternalGet(key); + if (TryParseArray(input, out object[] values) && values.Length >= 8) + { + var index = -1; - if (value == null) - { - return defaultValue; - } + value = ((T1)values[++index], (T2)values[++index], (T3)values[++index], (T4)values[++index], (T5)values[++index], (T6)values[++index], (T7)values[++index], (T8)values[++index]); - value = value.Trim(); + return true; + } - var vals = Enum.GetValues(typeof(T)).Cast(); + return false; + } - foreach (var o in vals.Where(o => Insensitive.Equals(value, o.ToString(CultureInfo.InvariantCulture)))) - { - return o; - } + #endregion - Warn(key); + #region Arrays - return defaultValue; - } + public static bool TryParse(string input, out object[] value) + { + return TryParseArray(input, out value); + } - public static T GetDelegate(string key, T defaultValue) - { - if (!typeof(MulticastDelegate).IsAssignableFrom(typeof(T).BaseType)) - { - throw new ArgumentException("T must be a delegate type"); - } - - var value = InternalGet(key); - - if (value == null) - { - return defaultValue; - } - - value = value.Trim(); - - var i = value.LastIndexOf('.'); - - if (i <= 0) - { - Warn(key); - - return defaultValue; - } - - try - { - var method = value.Substring(i + 1); - var target = FindType(value.Remove(i)); - - if (target != null) - { - var info = target.GetMethod(method, (BindingFlags)0x38); - - if (info != null) - { - return (T)(object)Delegate.CreateDelegate(typeof(T), info); - } - } - } - catch - { } - - Warn(key); - - return defaultValue; - } - - private static Type FindType(string value) - { - var type = Type.GetType(value, false); - - if (type != null) - { - return type; - } - - if (value.IndexOf('.') < 0) - { - return ScriptCompiler.FindTypeByName(value); - } - - return ScriptCompiler.FindTypeByFullName(value); - } - } -} \ No newline at end of file + public static bool TryParse(string input, out string[] value) + { + return TryParseArray(input, out value); + } + + private static bool TryParseArray(string input, out T[] value) + { + try + { + if (!input.StartsWith("[") || !input.EndsWith("]")) + { + value = null; + return false; + } + + input = input.Substring(1, input.Length - 2); + + var isGeneric = typeof(T) == typeof(object); + var isString = typeof(T) == typeof(string); + + if (isGeneric || isString) + { + var output = new List(); + + var build = new StringBuilder(0x20); + + var idx = 0; + + while (idx < input.Length) + { + var oidx = idx; + + idx = input.IndexOf('"', idx); + + var inString = false; + + if (idx >= 0) + { + inString = true; + } + else if (isGeneric) + { + idx = oidx; + } + else + { + break; + } + + var dump = false; + + var o = input[idx++]; + + while (idx < input.Length) + { + var c = input[idx++]; + + if (c == o) + { + dump = true; + break; + } + + if (inString && c == '\\') + { + if (idx == input.Length) + { + dump = true; + break; + } + + c = input[idx++]; + + var found = true; + + switch (c) + { + case '"': + _ = build.Append('"'); + break; + case '\\': + _ = build.Append('\\'); + break; + case '/': + _ = build.Append('/'); + break; + case 'b': + _ = build.Append('\b'); + break; + case 'f': + _ = build.Append('\f'); + break; + case 'n': + _ = build.Append('\n'); + break; + case 'r': + _ = build.Append('\r'); + break; + case 't': + _ = build.Append('\t'); + break; + default: + found = false; + break; + } + + if (!found && c == 'u') + { + var length = input.Length - idx; + + if (length < 4) + { + value = null; + return false; + } + + if (!uint.TryParse(input.Substring(idx, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var sur)) + { + value = null; + return false; + } + + _ = build.Append(char.ConvertFromUtf32((int)sur)); + + idx += 4; + } + } + else if (inString && c == '"') + { + dump = true; + } + else if (isGeneric && (char.IsWhiteSpace(c) || c == ',')) + { + dump = true; + } + else + { + _ = build.Append(c); + } + } + + if (dump) + { + output.Add(build.ToString()); + } + + _ = build.Clear(); + } + + value = new T[output.Count]; + + for (var i = 0; i < output.Count; i++) + { + if (!TryParse(output[i], out T obj)) + { + value = null; + return false; + } + + value[i] = obj; + } + + ColUtility.Free(output); + + return true; + } + + var vals = input.Split(','); + + value = new T[vals.Length]; + + for (var i = 0; i < vals.Length; i++) + { + if (!TryParse(vals[i], out T obj)) + { + value = null; + return false; + } + + value[i] = obj; + } + + return true; + } + catch + { + value = null; + return false; + } + } + + #endregion + + #endregion + + #region Generation + + private static readonly char[] _InvalidChars = Path.GetInvalidPathChars(); + + private static bool _Gen; + + public static void Generate() + { + Load(); + + var files = new HashSet(); + + var supportedTypes = new Dictionary(); + + _Gen = true; + + try + { + Console.WriteLine($"Config: Generating..."); + + foreach (var m in typeof(Config).GetMethods(BindingFlags.Public | BindingFlags.Static)) + { + if (!m.Name.StartsWith("Set")) + { + continue; + } + + var p = m.GetParameters(); + + if (p.Length != 2) + { + continue; + } + + var keyArg = p[0]; + + if (keyArg.ParameterType != typeof(string)) + { + continue; + } + + var valArg = p[1]; + + if (valArg.ParameterType.IsGenericParameter) + { + var a = valArg.ParameterType.GetGenericParameterConstraints(); + + if (a != null && a.Length > 0) + { + supportedTypes[a[0]] = m; + } + } + else + { + supportedTypes[valArg.ParameterType] = m; + } + } + + foreach (var asm in ScriptCompiler.Assemblies) + { + var cache = ScriptCompiler.GetTypeCache(asm); + + foreach (var type in cache.Types) + { + if (type == typeof(Config) || type == typeof(Entry)) + { + continue; + } + + foreach (var field in type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly)) + { + if (field.IsLiteral) + { + continue; + } + + if (!supportedTypes.TryGetValue(field.FieldType, out var setter)) + { + continue; + } + + var key = $"{type.Name}.{field.Name}"; + + if (key.IndexOfAny(_InvalidChars) >= 0) + { + continue; + } + + if (!_Entries.TryGetValue(key, out var entry) || entry == null) + { + var val = field.GetValue(null); + + if (val != null) + { + _ = setter.Invoke(null, new object[] { key, val }); + } + else + { + InternalSet(key, ToString, null); + } + + _ = files.Add(GetFilePath(ref key, out _)); + } + } + + foreach (var prop in type.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly)) + { + if (!prop.CanRead) + { + continue; + } + + if (!supportedTypes.TryGetValue(prop.PropertyType, out var setter)) + { + continue; + } + + var key = $"{type.Name}.{prop.Name}"; + + if (key.IndexOfAny(_InvalidChars) >= 0) + { + continue; + } + + if (!_Entries.TryGetValue(key, out var entry) || entry == null) + { + var val = prop.GetValue(null); + + if (val != null) + { + _ = setter.Invoke(null, new object[] { key, val }); + } + else + { + InternalSet(key, ToString, null); + } + + _ = files.Add(GetFilePath(ref key, out _)); + } + } + } + } + + var count = 0; + + foreach (var group in _Entries.Values.GroupBy(e => e.File)) + { + if (files.Contains(group.Key)) + { + foreach (var entry in group) + { + if (string.IsNullOrWhiteSpace(entry.Desc)) + { + entry.Desc = string.Empty; + } + + if (entry.Desc.Length > 0) + { + entry.Desc += "\n"; + } + + entry.Desc += $"Default: {entry.Value}"; + + if (Core.Debug) + { + Utility.PushColor(ConsoleColor.Blue); + Console.WriteLine(entry); + Utility.PopColor(); + } + } + + SaveFile(group.Key, group); + + ++count; + } + } + + Console.WriteLine($"Config: Generated {count:N0} new files."); + } + catch (Exception e) + { + Console.WriteLine($"Config: Generation Failed"); + + Console.WriteLine(e); + } + finally + { + files.Clear(); + supportedTypes.Clear(); + + _Gen = false; + } + } + + #endregion + } +} diff --git a/Server/Gumps/Gump.cs b/Server/Gumps/Gump.cs index 9dec7e7..cd13034 100755 --- a/Server/Gumps/Gump.cs +++ b/Server/Gumps/Gump.cs @@ -183,13 +183,7 @@ namespace Server.Gumps Add(new GumpTooltip(number)); } - public void AddTooltipText(string text) - { - Add(new GumpTooltip(text)); - } - - - public void AddHtml(int x, int y, int width, int height, string text, bool background, bool scrollbar) + public void AddHtml(int x, int y, int width, int height, string text, bool background, bool scrollbar) { Add(new GumpHtml(x, y, width, height, text, background, scrollbar)); } diff --git a/Server/Gumps/GumpTooltip.cs b/Server/Gumps/GumpTooltip.cs index e8bc66d..9878304 100755 --- a/Server/Gumps/GumpTooltip.cs +++ b/Server/Gumps/GumpTooltip.cs @@ -23,69 +23,37 @@ using Server.Network; namespace Server.Gumps { - public class GumpTooltip : GumpEntry - { - private int m_Number; - private string m_Text; - public GumpTooltip(int number) - { - m_Number = number; - } - - public GumpTooltip(string text) - { - m_Text = text; - } + public class GumpTooltip : GumpEntry + { + private int m_Number; + public GumpTooltip( int number ) + { + m_Number = number; + } public int Number - { - get - { - return m_Number; - } - set - { - Delta(ref m_Number, value); - } - } - - public string Text - { - get - { - return m_Text; - } - set - { - Delta(ref m_Text, value); - } - } + { + get + { + return m_Number; + } + set + { + Delta( ref m_Number, value ); + } + } public override string Compile() - { - if (m_Number == 0 && !string.IsNullOrEmpty(m_Text)) - { // if given: use custom text # TODO UNCHECKED -> AppendTo( IGumpWriter disp ) was used! - return String.Format("{{ tooltip {0} @{1}@ }}", 1042971, m_Text); - } - else - { // default use cliloc localized text - return string.Format("{{ tooltip {0} }}", m_Number); - } + { + return string.Format("{{ tooltip {0} }}", m_Number); } - private static byte[] m_LayoutName = Gump.StringToBuffer("tooltip"); + private static byte[] m_LayoutName = Gump.StringToBuffer( "tooltip" ); - public override void AppendTo(IGumpWriter disp) - { - if (m_Number == 0 && !string.IsNullOrEmpty(m_Text)) - { // if given: use custom text replacing placeholder "~1_NOTHING~" - disp.AppendLayout(Gump.StringToBuffer(String.Format("tooltip {0}@{1}@", 1042971, m_Text))); - } - else - { // default use given cliloc localized text - disp.AppendLayout(m_LayoutName); - disp.AppendLayout(m_Number); - } + public override void AppendTo( IGumpWriter disp ) + { + disp.AppendLayout( m_LayoutName ); + disp.AppendLayout( m_Number ); } } } \ No newline at end of file diff --git a/Server/Item.cs b/Server/Item.cs index 21e7d5e..4036e1d 100755 --- a/Server/Item.cs +++ b/Server/Item.cs @@ -186,7 +186,7 @@ namespace Server /// /// Unused, using this layer makes you invisible to other players. Strange. /// - /// + /// Reserved_1 = 0x1E, /// @@ -856,7 +856,7 @@ namespace Server } } } - + private byte m_GridLocation = 0; [CommandProperty(AccessLevel.GameMaster)] @@ -1261,7 +1261,7 @@ namespace Server public virtual void AddLootTypeProperty(ObjectPropertyList list) { if (DisplayLootType) - { + { if (m_LootType == LootType.Blessed) { list.Add(1038021); // blessed @@ -1610,7 +1610,7 @@ namespace Server /// { /// if ( from.Int >= 100 ) /// return true; - /// + /// /// return base.AllowEquipedCast( from ); /// } /// When placed in an Item script, the item may be cast when equiped if the has 100 or more intelligence. Otherwise, it will drop to their backpack. @@ -2137,7 +2137,7 @@ namespace Server { return false; } - else if (Sockets != null && item.Sockets != null) + else if (Sockets != null && item.Sockets != null) { if (Sockets.Any(s => !item.HasSocket(s.GetType()))) { @@ -2515,7 +2515,18 @@ namespace Server { } public virtual void OnAdded(object parent) - { } + { + // Only enforce insurance when the item is added to a Mobile (player) + if (parent is Mobile newOwner) + { + if (Insured && InsuredBy != Serial.MinusOne && newOwner.Serial != InsuredBy) + { + Insured = false; + InsuredBy = Serial.MinusOne; + newOwner.SendMessage("The insurance on this item has been removed."); + } + } + } [CommandProperty(AccessLevel.Counselor, AccessLevel.Decorator)] public Map Map @@ -2619,16 +2630,16 @@ namespace Server // 14 writer.Write(Sockets != null ? Sockets.Count : 0); - - if(Sockets != null) - { - foreach(var socket in Sockets) - { - ItemSocket.Save(socket, writer); - } - } - // 13: Merge sync + if (Sockets != null) + { + foreach (var socket in Sockets) + { + ItemSocket.Save(socket, writer); + } + } + + // 13: Merge sync // 12: Light no longer backed by Direction // 11 @@ -3031,6 +3042,7 @@ namespace Server OnLockDownChange(); } } + public Serial InsuredBy; public virtual void OnLockDownChange() { @@ -3125,13 +3137,13 @@ namespace Server case 14: var socketCount = reader.ReadInt(); - for(int i = 0; i < socketCount; i++) + for (int i = 0; i < socketCount; i++) { ItemSocket.Load(this, reader); } goto case 13; - case 13: + case 13: case 12: case 11: m_GridLocation = reader.ReadByte(); @@ -3185,7 +3197,7 @@ namespace Server { m_Light = (LightType)reader.ReadByte(); } - else if(version < 12) + else if (version < 12) { m_Light = (LightType)m_Direction; } @@ -3721,7 +3733,7 @@ namespace Server state.Send(OPLPacket); } } - + protected virtual Packet GetWorldPacketFor(NetState state) { if (state.HighSeas) @@ -4619,7 +4631,7 @@ namespace Server module.Delete(); } - if(Sockets != null) + if (Sockets != null) { Sockets.IterateReverse(socket => { @@ -4722,7 +4734,7 @@ namespace Server #region Location Location Location! public virtual void OnLocationChange(Point3D oldLocation) - { + { var items = Items; if (items == null) @@ -4746,7 +4758,7 @@ namespace Server o.OnParentLocationChange(oldLocation); } } - } + } public virtual void OnParentLocationChange(Point3D oldLocation) { } @@ -4858,7 +4870,7 @@ namespace Server int oldPileWeight = PileWeight; m_ItemID = value; - + ReleaseWorldPackets(); int newPileWeight = PileWeight; @@ -4954,6 +4966,29 @@ namespace Server root.Obtained(this); } } + // Character-bound insurance enforcement + if (!World.Loading && Parent is Mobile newOwner) + { + // Murderers cannot have insured items at all + if (newOwner.Murderer) + { + if (Insured) + { + Insured = false; + InsuredBy = Serial.MinusOne; + newOwner.SendMessage("The Insurance Agency will not cover items owned by murderers."); + } + return; + } + + // Character-bound insurance enforcement + if (Insured && InsuredBy != Serial.MinusOne && newOwner.Serial != InsuredBy) + { + Insured = false; + InsuredBy = Serial.MinusOne; + newOwner.SendMessage("The insurance on this item has been removed."); + } + } } [CommandProperty(AccessLevel.Decorator)] @@ -5432,12 +5467,12 @@ namespace Server } okay = ((m_OpenSlots >> i) & match) == match; - + if (okay) { z += i; break; - } + } } if (!okay) { @@ -6178,7 +6213,7 @@ namespace Server { m_Serial = Serial.NewItem; m_Map = Map.Internal; - + m_Light = LightType.Empty; m_Amount = 1; @@ -6255,17 +6290,17 @@ namespace Server public List Sockets { get; private set; } public void AttachSocket(ItemSocket socket) - { - if(Sockets == null) - { - Sockets = new List(); - } + { + if (Sockets == null) + { + Sockets = new List(); + } - Sockets.Add(socket); - socket.Owner = this; - - InvalidateProperties(); - } + Sockets.Add(socket); + socket.Owner = this; + + InvalidateProperties(); + } public bool RemoveSocket() { @@ -6297,26 +6332,26 @@ namespace Server InvalidateProperties(); } - - public T GetSocket() where T : ItemSocket - { + + public T GetSocket() where T : ItemSocket + { if (Sockets == null) { return null; } - return Sockets.FirstOrDefault(s => s.GetType() == typeof(T)) as T; - } - - public T GetSocket(Func predicate) where T : ItemSocket - { + return Sockets.FirstOrDefault(s => s.GetType() == typeof(T)) as T; + } + + public T GetSocket(Func predicate) where T : ItemSocket + { if (Sockets == null) { return null; } - return Sockets.FirstOrDefault(s => s.GetType() == typeof(T) && (predicate == null || predicate(s as T))) as T; - } + return Sockets.FirstOrDefault(s => s.GetType() == typeof(T) && (predicate == null || predicate(s as T))) as T; + } public ItemSocket GetSocket(Type type) { @@ -6329,14 +6364,14 @@ namespace Server } public bool HasSocket() - { + { if (Sockets == null) { return false; } return Sockets.Any(s => s.GetType() == typeof(T)); - } + } public bool HasSocket(Type t) { @@ -6351,71 +6386,71 @@ namespace Server } public class ItemSocket - { - [CommandProperty(AccessLevel.GameMaster)] - public Item Owner { get; set; } - - [CommandProperty(AccessLevel.GameMaster)] - public DateTime Expires { get; set; } - - public virtual TimeSpan TickDuration { get { return TimeSpan.FromMinutes(1); } } - - public Timer Timer { get; set; } + { + [CommandProperty(AccessLevel.GameMaster)] + public Item Owner { get; set; } + + [CommandProperty(AccessLevel.GameMaster)] + public DateTime Expires { get; set; } + + public virtual TimeSpan TickDuration { get { return TimeSpan.FromMinutes(1); } } + + public Timer Timer { get; set; } public ItemSocket() : this(TimeSpan.Zero) { } - - public ItemSocket(TimeSpan duration) - { - if(duration != TimeSpan.Zero) - { - Expires = DateTime.UtcNow + duration; - - BeginTimer(); - } - } - - protected void BeginTimer() - { - EndTimer(); - - Timer = Timer.DelayCall(TickDuration, TickDuration, OnTick); + + public ItemSocket(TimeSpan duration) + { + if (duration != TimeSpan.Zero) + { + Expires = DateTime.UtcNow + duration; + + BeginTimer(); + } + } + + protected void BeginTimer() + { + EndTimer(); + + Timer = Timer.DelayCall(TickDuration, TickDuration, OnTick); Timer.Start(); - } - - protected void EndTimer() - { - if(Timer != null) - { - Timer.Stop(); - Timer = null; - } - } - - protected virtual void OnTick() - { - if(Expires < DateTime.UtcNow || Owner.Deleted) - { - Remove(); - } - } - - public virtual void Remove() - { - EndTimer(); - - Owner.RemoveItemSocket(this); - } - - public virtual void OnRemoved() - { - } - - public virtual void GetProperties(ObjectPropertyList list) - { - } + } + + protected void EndTimer() + { + if (Timer != null) + { + Timer.Stop(); + Timer = null; + } + } + + protected virtual void OnTick() + { + if (Expires < DateTime.UtcNow || Owner.Deleted) + { + Remove(); + } + } + + public virtual void Remove() + { + EndTimer(); + + Owner.RemoveItemSocket(this); + } + + public virtual void OnRemoved() + { + } + + public virtual void GetProperties(ObjectPropertyList list) + { + } public virtual void OnOwnerDuped(Item newItem) { @@ -6451,46 +6486,46 @@ namespace Server { } - public virtual void Serialize(GenericWriter writer) - { - writer.Write(0); - - writer.Write(Expires); - } - - public virtual void Deserialize(Item owner, GenericReader reader) - { - reader.ReadInt(); // version - - Expires = reader.ReadDateTime(); - - if(Expires != DateTime.MinValue) - { - if(Expires < DateTime.UtcNow) - { - return; - } - else - { - BeginTimer(); - } - } - - owner.AttachSocket(this); - } - - public static void Save(ItemSocket socket, GenericWriter writer) - { - writer.Write(socket.GetType().Name); - socket.Serialize(writer); - } - - public static void Load(Item item, GenericReader reader) - { - var typeName = ScriptCompiler.FindTypeByName(reader.ReadString()); + public virtual void Serialize(GenericWriter writer) + { + writer.Write(0); + + writer.Write(Expires); + } + + public virtual void Deserialize(Item owner, GenericReader reader) + { + reader.ReadInt(); // version + + Expires = reader.ReadDateTime(); + + if (Expires != DateTime.MinValue) + { + if (Expires < DateTime.UtcNow) + { + return; + } + else + { + BeginTimer(); + } + } + + owner.AttachSocket(this); + } + + public static void Save(ItemSocket socket, GenericWriter writer) + { + writer.Write(socket.GetType().Name); + socket.Serialize(writer); + } + + public static void Load(Item item, GenericReader reader) + { + var typeName = ScriptCompiler.FindTypeByName(reader.ReadString()); var socket = Activator.CreateInstance(typeName) as ItemSocket; socket.Deserialize(item, reader); } } -} +} \ No newline at end of file diff --git a/Server/Main.cs b/Server/Main.cs index e791a78..4cdce1d 100755 --- a/Server/Main.cs +++ b/Server/Main.cs @@ -47,8 +47,6 @@ namespace Server private static DateTime _ProfileStart; private static TimeSpan _ProfileTime; - public static MessagePump MessagePump { get; set; } - public static Slice Slice; public static bool Profiling @@ -453,6 +451,19 @@ namespace Server Process = Process.GetCurrentProcess(); Assembly = Assembly.GetEntryAssembly(); + // Disable Windows-only process priority on Linux/Mono +if (Environment.OSVersion.Platform == PlatformID.Win32NT) +{ + try + { + Process.PriorityClass = ProcessPriorityClass.High; + } + catch + { + } +} + + if (Thread != null) { Thread.Name = "Core Thread"; @@ -641,7 +652,7 @@ namespace Server ScriptCompiler.Invoke("Initialize"); - MessagePump messagePump = MessagePump = new MessagePump(); + MessagePump.Start(); _TimerThread.Start(); @@ -671,7 +682,7 @@ namespace Server Item.ProcessDeltaQueue(); Timer.Slice(); - messagePump.Slice(); + MessagePump.Slice(); NetState.FlushAll(); NetState.ProcessDisposedQueue(); diff --git a/Server/MultiData.cs b/Server/MultiData.cs index 867ab79..df44c55 100755 --- a/Server/MultiData.cs +++ b/Server/MultiData.cs @@ -268,10 +268,10 @@ namespace Server bin.Close(); } } - else - { - Console.WriteLine("Warning: Multi data files not found!"); - } + } + else + { + Console.WriteLine("Warning: Multi data files not found!"); } } } diff --git a/Server/Network/BufferPool.cs b/Server/Network/BufferPool.cs index ad950a5..55e51f6 100755 --- a/Server/Network/BufferPool.cs +++ b/Server/Network/BufferPool.cs @@ -1,108 +1,98 @@ #region References +using System; +using System.Collections.Concurrent; using System.Collections.Generic; +using System.Collections.ObjectModel; #endregion namespace Server.Network { - public class BufferPool - { - public static List Pools { get; private set; } + public class BufferPool + { + private static readonly ConcurrentDictionary m_Pools = new ConcurrentDictionary(); - static BufferPool() - { - Pools = new List(); - } + public static ReadOnlyCollection Pools => (ReadOnlyCollection)m_Pools.Keys; - private readonly string m_Name; + private readonly string m_Name; - private readonly int m_InitialCapacity; - private readonly int m_BufferSize; + private readonly int m_InitialCapacity; + private readonly int m_BufferSize; - private int m_Misses; + private volatile int m_Misses; - private readonly Queue m_FreeBuffers; + private readonly ConcurrentQueue m_FreeBuffers = new ConcurrentQueue(); - public int Count - { - get - { - lock (this) - return m_FreeBuffers.Count; - } - } + public int Count + { + get + { + return m_FreeBuffers.Count; + } + } - public void GetInfo( - out string name, - out int freeCount, - out int initialCapacity, - out int currentCapacity, - out int bufferSize, - out int misses) - { - lock (this) - { - name = m_Name; - freeCount = m_FreeBuffers.Count; - initialCapacity = m_InitialCapacity; - currentCapacity = m_InitialCapacity * (1 + m_Misses); - bufferSize = m_BufferSize; - misses = m_Misses; - } - } + public void GetInfo( + out string name, + out int freeCount, + out int initialCapacity, + out int currentCapacity, + out int bufferSize, + out int misses) + { + name = m_Name; + freeCount = m_FreeBuffers.Count; + initialCapacity = m_InitialCapacity; + currentCapacity = m_InitialCapacity * (1 + m_Misses); + bufferSize = m_BufferSize; + misses = m_Misses; + } - public BufferPool(string name, int initialCapacity, int bufferSize) - { - m_Name = name; + public BufferPool(string name, int initialCapacity, int bufferSize) + { + m_Name = name; - m_InitialCapacity = initialCapacity; - m_BufferSize = bufferSize; + m_InitialCapacity = initialCapacity; + m_BufferSize = bufferSize; - m_FreeBuffers = new Queue(initialCapacity); + while (m_FreeBuffers.Count < initialCapacity) + { + m_FreeBuffers.Enqueue(new byte[bufferSize]); + } - for (int i = 0; i < initialCapacity; ++i) - { - m_FreeBuffers.Enqueue(new byte[bufferSize]); - } + m_Pools[this] = name; + } - lock (Pools) - Pools.Add(this); - } + public byte[] AcquireBuffer() + { + if (m_FreeBuffers.TryDequeue(out var buffer)) + { + return buffer; + } - public byte[] AcquireBuffer() - { - lock (this) - { - if (m_FreeBuffers.Count > 0) - { - return m_FreeBuffers.Dequeue(); - } + ++m_Misses; - ++m_Misses; + while (m_FreeBuffers.Count < m_InitialCapacity - 1) + { + m_FreeBuffers.Enqueue(new byte[m_BufferSize]); + } - for (int i = 0; i < m_InitialCapacity; ++i) - { - m_FreeBuffers.Enqueue(new byte[m_BufferSize]); - } + return new byte[m_BufferSize]; + } - return m_FreeBuffers.Dequeue(); - } - } + public void ReleaseBuffer(byte[] buffer) + { + if (buffer == null || buffer.Length != m_BufferSize) + { + return; + } - public void ReleaseBuffer(byte[] buffer) - { - if (buffer == null) - { - return; - } + Array.Clear(buffer, 0, buffer.Length); - lock (this) - m_FreeBuffers.Enqueue(buffer); - } + m_FreeBuffers.Enqueue(buffer); + } - public void Free() - { - lock (Pools) - Pools.Remove(this); - } - } -} \ No newline at end of file + public void Free() + { + m_Pools.TryRemove(this, out _); + } + } +} diff --git a/Server/Network/Listener.cs b/Server/Network/Listener.cs index e0b2708..261ba3e 100755 --- a/Server/Network/Listener.cs +++ b/Server/Network/Listener.cs @@ -1,280 +1,546 @@ #region References using System; -using System.Collections; +using System.Collections.Concurrent; using System.Collections.Generic; +using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; +using System.Text; using System.Threading; #endregion namespace Server.Network { - public class Listener : IDisposable - { - private Socket m_Listener; - private PingListener _PingListener; + public class Listener : IDisposable + { + private static readonly byte[][] m_HttpFilters = + { + Encoding.UTF8.GetBytes("GET"), + Encoding.UTF8.GetBytes("POST"), + Encoding.UTF8.GetBytes("PUT"), + Encoding.UTF8.GetBytes("DELETE"), + Encoding.UTF8.GetBytes("HEAD"), + Encoding.UTF8.GetBytes("OPTIONS"), + Encoding.UTF8.GetBytes("PATCH"), + Encoding.UTF8.GetBytes("CONNECT"), + Encoding.UTF8.GetBytes("TRACE"), + }; - private readonly Queue m_Accepted; - private readonly object m_AcceptedSyncRoot; + private static readonly BufferPool m_ByteBufferPool = new BufferPool("Login Byte", 1024, 1); + private static readonly BufferPool m_PeekBufferPool = new BufferPool("Login Peek", 1024, 4); + private static readonly BufferPool m_SeedBufferPool = new BufferPool("Login Seed [0xEF]", 1024, PacketHandlers.LoginSeedLength); - private readonly AsyncCallback m_OnAccept; + public static IPAddress Address => Config.Get("Server.Listen", IPAddress.Any); - private static readonly Socket[] m_EmptySockets = new Socket[0]; + public static int Port => Config.Get("Server.Port", 2593); - public static IPEndPoint[] EndPoints { get; set; } + public static IPEndPoint[] EndPoints { get; set; } = + { + new IPEndPoint(Address, Port) + }; - public Listener(IPEndPoint ipep) - { - m_Accepted = new Queue(); - m_AcceptedSyncRoot = ((ICollection)m_Accepted).SyncRoot; + private long m_SliceTime, m_SliceCounter; - m_Listener = Bind(ipep); + private long m_Counter, m_AcceptsPerSecond; - if (m_Listener == null) - { - return; - } + public long AcceptsPerSecond => m_AcceptsPerSecond; - DisplayListener(); - _PingListener = new PingListener(ipep); + private Socket m_Listener; - m_OnAccept = OnAccept; - try - { - IAsyncResult res = m_Listener.BeginAccept(m_OnAccept, m_Listener); - } - catch (SocketException ex) - { - NetState.TraceException(ex); - } - catch (ObjectDisposedException) - { } - } + private readonly ConcurrentQueue m_Accepted = new ConcurrentQueue(); - private Socket Bind(IPEndPoint ipep) - { - Socket s = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + private readonly AutoResetEvent m_AcceptLimiter = new AutoResetEvent(true); - try - { - s.LingerState.Enabled = false; - - // Default is 'false' starting Windows Vista and Server 2008. Source: https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.exclusiveaddressuse(v=vs.110).aspx?f=255&MSPPError=-2147217396 - s.ExclusiveAddressUse = false; + private readonly Thread m_AcceptThread; - s.Bind(ipep); - s.Listen(8); + private SocketAsyncEventArgs m_AcceptArgs; - return s; - } - catch (Exception e) - { - if (e is SocketException) - { - SocketException se = (SocketException)e; + public Listener(IPEndPoint ipep) + { + m_Listener = Bind(ipep); - if (se.ErrorCode == 10048) - { - // WSAEADDRINUSE - Utility.PushColor(ConsoleColor.Red); - Console.WriteLine("Listener Failed: {0}:{1} (In Use)", ipep.Address, ipep.Port); - Utility.PopColor(); - } - else if (se.ErrorCode == 10049) - { - // WSAEADDRNOTAVAIL - Utility.PushColor(ConsoleColor.Red); - Console.WriteLine("Listener Failed: {0}:{1} (Unavailable)", ipep.Address, ipep.Port); - Utility.PopColor(); - } - else - { - Utility.PushColor(ConsoleColor.Red); - Console.WriteLine("Listener Exception:"); - Console.WriteLine(e); - Utility.PopColor(); - } - } + m_SliceTime = Core.TickCount; - return null; - } - } - - private void DisplayListener() - { - IPEndPoint ipep = m_Listener.LocalEndPoint as IPEndPoint; - - if (ipep == null) - { - return; - } - - if (ipep.Address.Equals(IPAddress.Any) || ipep.Address.Equals(IPAddress.IPv6Any)) - { - var adapters = NetworkInterface.GetAllNetworkInterfaces(); - foreach (NetworkInterface adapter in adapters) - { - IPInterfaceProperties properties = adapter.GetIPProperties(); - foreach (IPAddressInformation unicast in properties.UnicastAddresses) - { - if (ipep.AddressFamily == unicast.Address.AddressFamily) - { - Utility.PushColor(ConsoleColor.Green); - Console.WriteLine("Listening: {0}:{1}", unicast.Address, ipep.Port); - Utility.PopColor(); - } - } - } - /* - try { - Console.WriteLine( "Listening: {0}:{1}", IPAddress.Loopback, ipep.Port ); - IPHostEntry iphe = Dns.GetHostEntry( Dns.GetHostName() ); - IPAddress[] ip = iphe.AddressList; - for ( int i = 0; i < ip.Length; ++i ) - Console.WriteLine( "Listening: {0}:{1}", ip[i], ipep.Port ); - } - catch { } - */ - } - else - { - Utility.PushColor(ConsoleColor.Green); - Console.WriteLine("Listening: {0}:{1}", ipep.Address, ipep.Port); - Utility.PopColor(); - } - - Utility.PushColor(ConsoleColor.DarkGreen); - Console.WriteLine(@"----------------------------------------------------------------------"); - Utility.PopColor(); - } - - private void OnAccept(IAsyncResult asyncResult) - { - Socket listener = (Socket)asyncResult.AsyncState; - - Socket accepted = null; - - try - { - accepted = listener.EndAccept(asyncResult); - } - catch (SocketException ex) - { - NetState.TraceException(ex); - } - catch (ObjectDisposedException) - { - return; - } - - if (accepted != null) - { - if (VerifySocket(accepted)) - { - Enqueue(accepted); - } - else - { - Release(accepted); - } - } - - try - { - listener.BeginAccept(m_OnAccept, listener); - } - catch (SocketException ex) - { - NetState.TraceException(ex); - } - catch (ObjectDisposedException) - { } - } - - private bool VerifySocket(Socket socket) - { - try - { - SocketConnectEventArgs args = new SocketConnectEventArgs(socket); - - EventSink.InvokeSocketConnect(args); - - return args.AllowConnection; - } - catch (Exception ex) - { - NetState.TraceException(ex); - - return false; - } - } - - private void Enqueue(Socket socket) - { - lock (m_AcceptedSyncRoot) - { - m_Accepted.Enqueue(socket); - } - - Core.Set(); - } - - private void Release(Socket socket) - { - try - { - socket.Shutdown(SocketShutdown.Both); - } - catch (SocketException ex) - { - NetState.TraceException(ex); - } - - try - { - socket.Close(); - } - catch (SocketException ex) - { - NetState.TraceException(ex); - } - } - - public Socket[] Slice() - { - Socket[] array; - - lock (m_AcceptedSyncRoot) - { - if (m_Accepted.Count == 0) - { - return m_EmptySockets; - } - - array = m_Accepted.ToArray(); - m_Accepted.Clear(); - } - - return array; - } - - public void Dispose() - { - Socket socket = Interlocked.Exchange(ref m_Listener, null); - - if (socket != null) - { - socket.Close(); - } - - if (_PingListener == null) + if (m_Listener == null) { return; } - _PingListener.Dispose(); - _PingListener = null; + DisplayListener(); + + m_AcceptThread = new Thread(AcceptLoop) + { + Name = $"Login Accept Processor", + Priority = ThreadPriority.AboveNormal, + }; + + m_AcceptThread.Start(); } - } -} \ No newline at end of file + + private Socket Bind(IPEndPoint ipep) + { + Socket s = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp) + { + SendTimeout = 1000, + ReceiveTimeout = 1000, + ExclusiveAddressUse = false, + UseOnlyOverlappedIO = false, + NoDelay = true, + LingerState = + { + Enabled = true, + LingerTime = 0, + }, + }; + + try + { + s.Bind(ipep); + s.Listen(1000); + + return s; + } + catch (Exception e) + { + if (e is SocketException se) + { + if (se.ErrorCode == 10048) + { + // WSAEADDRINUSE + Utility.PushColor(ConsoleColor.Red); + Console.WriteLine("Listener Failed: {0}:{1} (In Use)", ipep.Address, ipep.Port); + Utility.PopColor(); + } + else if (se.ErrorCode == 10049) + { + // WSAEADDRNOTAVAIL + Utility.PushColor(ConsoleColor.Red); + Console.WriteLine("Listener Failed: {0}:{1} (Unavailable)", ipep.Address, ipep.Port); + Utility.PopColor(); + } + else + { + Utility.PushColor(ConsoleColor.Red); + Console.WriteLine("Listener Exception:"); + Console.WriteLine(e); + Utility.PopColor(); + } + } + + return null; + } + } + + private void DisplayListener() + { + if (!(m_Listener.LocalEndPoint is IPEndPoint ipep)) + { + return; + } + + if (ipep.Address.Equals(IPAddress.Any) || ipep.Address.Equals(IPAddress.IPv6Any)) + { + NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); + + foreach (NetworkInterface adapter in adapters) + { + IPInterfaceProperties properties = adapter.GetIPProperties(); + + foreach (IPAddressInformation unicast in properties.UnicastAddresses) + { + if (ipep.AddressFamily == unicast.Address.AddressFamily) + { + Utility.PushColor(ConsoleColor.Green); + Console.WriteLine("Listening: {0}:{1}", unicast.Address, ipep.Port); + Utility.PopColor(); + } + } + } + } + else + { + Utility.PushColor(ConsoleColor.Green); + Console.WriteLine("Listening: {0}:{1}", ipep.Address, ipep.Port); + Utility.PopColor(); + } + + Utility.PushColor(ConsoleColor.DarkGreen); + Console.WriteLine(@"----------------------------------------------------------------------"); + Utility.PopColor(); + } + + private SocketAsyncEventArgs Reset(ref SocketAsyncEventArgs e) + { + if (e == null) + { + e = new SocketAsyncEventArgs(); + + e.Completed += OnAccept; + } + + e.UserToken = this; + e.AcceptSocket = null; + e.RemoteEndPoint = null; + + e.SocketFlags = 0; + e.SocketError = 0; + + e.DisconnectReuseSocket = true; + + return e; + } + + [STAThread] + private void AcceptLoop() + { + while (m_Listener != null) + { + Accept(); + } + } + + private void Accept() + { + if (!m_AcceptLimiter.WaitOne(10)) + { + return; + } + + if (m_Listener == null) + { + return; + } + + SocketAsyncEventArgs e = Reset(ref m_AcceptArgs); + + bool iocp; + + try + { + iocp = m_Listener.AcceptAsync(e); + } + catch + { + iocp = false; + } + + if (!iocp) + { + OnAccept(e); + } + } + + private void OnAccept(object sender, SocketAsyncEventArgs e) + { + OnAccept(e); + } + + private void OnAccept(SocketAsyncEventArgs e) + { + try + { + Socket accepted = e.AcceptSocket; + SocketError error = e.SocketError; + + m_AcceptArgs = Reset(ref e); + + if (accepted == null) + { + return; + } + + Interlocked.Increment(ref m_Counter); + + accepted.NoDelay = true; + + if (error != 0) + { + Release(false, ref accepted); + + return; + } + + try + { + accepted.SendTimeout = 1000; + accepted.ReceiveTimeout = 1000; + + _ = ThreadPool.QueueUserWorkItem(o => + { + Socket s = (Socket)o; + + if (ValidateSequence(s, out byte[] seed)) + { + Enqueue(s, seed); + } + else + { + Release(false, ref s); + } + }, accepted); + } + catch + { + Release(false, ref accepted); + } + } + finally + { + m_AcceptLimiter.Set(); + } + } + + private bool ValidateSequence(Socket socket, out byte[] buffer) + { + buffer = null; + + byte[] peek; + + try + { + peek = m_PeekBufferPool.AcquireBuffer(); + } + catch + { + return false; + } + + try + { + int recv = socket.Receive(peek, peek.Length, SocketFlags.None); + + if (recv < peek.Length) + { + return false; + } + + bool allow = false; + + int index = 0; + + byte packetID = peek[index++]; + + if (packetID == 0xEF) + { + byte[] packet = m_SeedBufferPool.AcquireBuffer(); + + try + { + var diff = packet.Length - peek.Length; + + recv = socket.Receive(packet, peek.Length, diff, SocketFlags.None); + + if (recv == diff) + { + Buffer.BlockCopy(peek, 0, packet, 0, peek.Length); + + uint seed = readU32(packet, ref index); + + if (seed != 0) + { + uint clientMaj = readU32(packet, ref index); + uint clientMin = readU32(packet, ref index); + uint clientRev = readU32(packet, ref index); + uint clientPat = readU32(packet, ref index); + + uint version = (clientMaj << 24) | (clientMin << 16) | (clientRev << 8) | clientPat; + + if (version != 0) + { + allow = true; + + buffer = packet.ToArray(); + } + } + } + } + finally + { + m_SeedBufferPool.ReleaseBuffer(packet); + } + } + else if (!Match(peek)) + { + index = packetID = 0; + + uint seed = readU32(peek, ref index); + + if (seed != 0) + { + var one = m_ByteBufferPool.AcquireBuffer(); + + try + { + recv = socket.Receive(one, 0, one.Length, SocketFlags.None); + + if (recv == one.Length) + { + packetID = one[0]; + + if (!MessagePump.CheckEncrypted(packetID)) + { + allow = true; + + buffer = new byte[peek.Length + one.Length]; + + Buffer.BlockCopy(peek, 0, buffer, 0, peek.Length); + Buffer.BlockCopy(one, 0, buffer, peek.Length, one.Length); + } + } + } + finally + { + m_ByteBufferPool.ReleaseBuffer(one); + } + } + } + + return allow; + } + catch + { + return false; + } + finally + { + m_PeekBufferPool.ReleaseBuffer(peek); + } + + uint readU32(byte[] b, ref int i) + { + return (uint)((b[i++] << 24) | (b[i++] << 16) | (b[i++] << 8) | b[i++]); + } + } + + private bool Match(byte[] buffer) + { + for (int i = 0; i < m_HttpFilters.Length; i++) + { + byte[] filter = m_HttpFilters[i]; + + if (filter?.Length > 0) + { + IEnumerable fseq = filter; + IEnumerable pseq = buffer; + + if (filter.Length > buffer.Length) + { + fseq = fseq.Take(buffer.Length); + } + else if (buffer.Length > filter.Length) + { + pseq = pseq.Take(filter.Length); + } + + if (Enumerable.SequenceEqual(fseq, pseq)) + { + return true; + } + } + } + + return false; + } + + private void Enqueue(Socket socket, byte[] seed) + { + m_Accepted.Enqueue(new SocketState(socket, seed)); + + Core.Set(); + } + + private void Release(bool graceful, ref Socket socket) + { + if (socket != null) + { + try + { + if (graceful) + { + try + { + socket.Shutdown(SocketShutdown.Both); + } + catch (SocketException ex) + { + NetState.TraceException(ex); + } + } + + if (socket.LingerState != null) + { + socket.LingerState.Enabled = true; + socket.LingerState.LingerTime = graceful ? 1 : 0; + } + else + { + socket.LingerState = new LingerOption(true, graceful ? 1 : 0); + } + } + catch + { + } + finally + { + socket.Close(); + + socket = null; + } + } + } + + public IEnumerable Slice() + { + long now = Core.TickCount; + + if (now - m_SliceTime >= 1000) + { + var count = m_Counter; + + Interlocked.Exchange(ref m_SliceTime, now); + Interlocked.Exchange(ref m_AcceptsPerSecond, count - m_SliceCounter); + Interlocked.Exchange(ref m_SliceCounter, count); + } + + int limit = Math.Min(m_Accepted.Count, 100); + + while (--limit >= 0 && m_Accepted.TryDequeue(out SocketState accepted)) + { + Socket socket = accepted.Socket; + + SocketConnectEventArgs args = new SocketConnectEventArgs(socket); + + EventSink.InvokeSocketConnect(args); + + if (args.AllowConnection) + { + yield return accepted; + } + else + { + Release(true, ref socket); + } + } + } + + public void Dispose() + { + Socket socket = Interlocked.Exchange(ref m_Listener, null); + + socket?.Close(); + } + } + + public readonly struct SocketState + { + public readonly Socket Socket; + public readonly byte[] Seed; + + public SocketState(Socket socket, byte[] seed) + { + Socket = socket; + Seed = seed; + } + } +} diff --git a/Server/Network/MessagePump.cs b/Server/Network/MessagePump.cs index befd50d..3fa2927 100755 --- a/Server/Network/MessagePump.cs +++ b/Server/Network/MessagePump.cs @@ -1,7 +1,7 @@ #region References using System; -using System.Collections.Generic; -using System.Net.Sockets; +using System.Collections.Concurrent; +using System.Linq; using System.Threading; using Server.Diagnostics; @@ -9,15 +9,17 @@ using Server.Diagnostics; namespace Server.Network { - public class MessagePump + public static class MessagePump { - private Queue m_Queue; - private Queue m_WorkingQueue; - private readonly Queue m_Throttled; + private static readonly ConcurrentQueue m_Queue = new ConcurrentQueue(); - public Listener[] Listeners { get; set; } - - public MessagePump() + private static readonly ConcurrentQueue m_Throttled = new ConcurrentQueue(); + + public static Listener[] Listeners { get; private set; } + + public static long AcceptsPerSecond => Listeners.Sum(l => l.AcceptsPerSecond); + + public static void Start() { var ipep = Listener.EndPoints; @@ -44,13 +46,9 @@ namespace Server.Network } } while (!success); - - m_Queue = new Queue(); - m_WorkingQueue = new Queue(); - m_Throttled = new Queue(); } - public void AddListener(Listener l) + public static void AddListener(Listener l) { var old = Listeners; @@ -64,15 +62,13 @@ namespace Server.Network Listeners[old.Length] = l; } - private void CheckListener() + private static void CheckListener() { foreach (Listener l in Listeners) { - var accepted = l.Slice(); - - foreach (Socket s in accepted) + foreach (SocketState state in l.Slice()) { - NetState ns = new NetState(s, this); + NetState ns = new NetState(state); ns.Start(); @@ -104,50 +100,41 @@ namespace Server.Network private static string[] _NoDisplay = { - "192.99.10.155", - "192.99.69.21", + "54.39.99.106", }; - public void OnReceive(NetState ns) + public static void OnReceive(NetState ns) { - lock (this) - m_Queue.Enqueue(ns); + m_Queue.Enqueue(ns); Core.Set(); } - public void Slice() - { - CheckListener(); + public static void Slice() + { + CheckListener(); - lock (this) - { - var temp = m_WorkingQueue; - m_WorkingQueue = m_Queue; - m_Queue = temp; - } + var limit = m_Queue.Count; - while (m_WorkingQueue.Count > 0) - { - NetState ns = m_WorkingQueue.Dequeue(); + while (--limit >= 0 && m_Queue.TryDequeue(out NetState ns)) + { + if (ns.Running) + { + HandleReceive(ns); + } + } - if (ns.Running) - { - HandleReceive(ns); - } - } - - lock (this) - { - while (m_Throttled.Count > 0) - { - m_Queue.Enqueue(m_Throttled.Dequeue()); - } - } - } + while (m_Throttled.TryDequeue(out NetState ns)) + { + if (ns.Running) + { + m_Queue.Enqueue(ns); + } + } + } private const int BufferSize = 4096; - private readonly BufferPool m_Buffers = new BufferPool("Processor", 4, BufferSize); + private static readonly BufferPool m_Buffers = new BufferPool("Processor", 4, BufferSize); public static bool HandleSeed(NetState ns, ByteQueue buffer) { @@ -187,24 +174,36 @@ namespace Server.Network return false; } - public static bool CheckEncrypted(NetState ns, int packetID) - { - if (!ns.SentFirstPacket && packetID != 0xF0 && packetID != 0xF1 && packetID != 0xCF && packetID != 0x80 && - packetID != 0x91 && packetID != 0xA4 && packetID != 0xEF && packetID != 0xE4 && packetID != 0xFF) - { - Utility.PushColor(ConsoleColor.Red); - Console.WriteLine("Client: {0}: Encrypted Client Unsupported", ns); - Utility.PopColor(); - - ns.Dispose(); + public static bool CheckEncrypted(NetState ns, int packetID) + { + if (ns.SentFirstPacket || !CheckEncrypted(packetID)) + { + return false; + } - return true; - } + Utility.PushColor(ConsoleColor.Red); + Console.WriteLine("Client: {0}: Encrypted Client Unsupported", ns); + Utility.PopColor(); - return false; + ns.Dispose(); + + return true; + } + + public static bool CheckEncrypted(int packetID) + { + return packetID != 0xF0 + && packetID != 0xF1 + && packetID != 0xCF + && packetID != 0x80 + && packetID != 0x91 + && packetID != 0xA4 + && packetID != 0xEF + && packetID != 0xE4 + && packetID != 0xFF; } - public void HandleReceive(NetState ns) + public static void HandleReceive(NetState ns) { ByteQueue buffer = ns.Buffer; diff --git a/Server/Network/NetState.cs b/Server/Network/NetState.cs index 1689ce2..2a9a361 100755 --- a/Server/Network/NetState.cs +++ b/Server/Network/NetState.cs @@ -1,11 +1,14 @@ #region References using System; +using System.Collections.Concurrent; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; +using System.Threading.Tasks; using Server.Accounting; using Server.Diagnostics; @@ -17,804 +20,823 @@ using Server.Menus; namespace Server.Network { - public interface IPacketEncoder - { - void EncodeOutgoingPacket(NetState to, ref byte[] buffer, ref int length); - void DecodeIncomingPacket(NetState from, ref byte[] buffer, ref int length); - } + public interface IPacketEncoder + { + void EncodeOutgoingPacket(NetState to, ref byte[] buffer, ref int length); + void DecodeIncomingPacket(NetState from, ref byte[] buffer, ref int length); + } - public interface IPacketEncryptor - { - void EncryptOutgoingPacket(NetState to, ref byte[] buffer, ref int length); - void DecryptIncomingPacket(NetState from, ref byte[] buffer, ref int length); - } + public interface IPacketEncryptor + { + void EncryptOutgoingPacket(NetState to, ref byte[] buffer, ref int length); + void DecryptIncomingPacket(NetState from, ref byte[] buffer, ref int length); + } - public delegate void NetStateCreatedCallback(NetState ns); + public delegate void NetStateCreatedCallback(NetState ns); - [PropertyObject] - public class NetState : IComparable - { - public static bool BufferStaticPackets = false; + [PropertyObject] + public class NetState : IComparable + { + public static bool BufferStaticPackets = false; - public static event NetStateCreatedCallback CreatedCallback; + public static event NetStateCreatedCallback CreatedCallback; - private readonly IPAddress m_Address; - private ByteQueue m_Buffer; - private byte[] m_RecvBuffer; - private readonly SendQueue m_SendQueue; - private bool m_Running; + private readonly IPAddress m_Address; + private ByteQueue m_Buffer; + private byte[] m_RecvBuffer; + private readonly SendQueue m_SendQueue; + private bool m_Running; - private AsyncCallback m_OnReceive, m_OnSend; + private List m_Gumps; + private List m_HuePickers; + private List m_Menus; + private readonly List m_Trades; + private readonly string m_ToString; + private ClientVersion m_Version; - private readonly MessagePump m_MessagePump; - private List m_Gumps; - private List m_HuePickers; - private List m_Menus; - private readonly List m_Trades; - private readonly string m_ToString; - private ClientVersion m_Version; + private readonly DateTime m_ConnectedOn; - private readonly DateTime m_ConnectedOn; - - [CommandProperty(AccessLevel.Administrator, true)] + [CommandProperty(AccessLevel.Administrator, true)] public DateTime ConnectedOn { get { return m_ConnectedOn; } } - [CommandProperty(AccessLevel.Administrator, true)] - public TimeSpan ConnectedFor { get { return (DateTime.UtcNow - m_ConnectedOn); } } + [CommandProperty(AccessLevel.Administrator, true)] + public TimeSpan ConnectedFor { get { return (DateTime.UtcNow - m_ConnectedOn); } } - [CommandProperty(AccessLevel.Administrator, true)] - public uint AuthID { get; set; } + [CommandProperty(AccessLevel.Administrator, true)] + public uint AuthID { get; set; } - [CommandProperty(AccessLevel.Administrator, true)] - public uint Seed { get; set; } + [CommandProperty(AccessLevel.Administrator, true)] + public uint Seed { get; set; } - [CommandProperty(AccessLevel.Administrator)] - public IPAddress Address { get { return m_Address; } } + [CommandProperty(AccessLevel.Administrator)] + public IPAddress Address { get { return m_Address; } } - private static bool m_Paused; + private static bool m_Paused; - [Flags] - private enum AsyncState - { - Pending = 0x01, - Paused = 0x02 - } + [Flags] + private enum AsyncState + { + Pending = 0x01, + Paused = 0x02 + } - private AsyncState m_AsyncState; + private volatile AsyncState m_AsyncState; + private readonly object m_AsyncLock = new object(); - public IPacketEncoder PacketEncoder { get; set; } - public IPacketEncryptor PacketEncryptor { get; set; } + public IPacketEncoder PacketEncoder { get; set; } + public IPacketEncryptor PacketEncryptor { get; set; } - [CommandProperty(AccessLevel.Administrator, true)] - public bool SentFirstPacket { get; set; } + [CommandProperty(AccessLevel.Administrator, true)] + public bool SentFirstPacket { get; set; } - [CommandProperty(AccessLevel.Administrator, true)] - public bool BlockAllPackets { get; set; } + [CommandProperty(AccessLevel.Administrator, true)] + public bool BlockAllPackets { get; set; } - [CommandProperty(AccessLevel.Administrator, true)] - public bool? Encrypted { get; set; } + [CommandProperty(AccessLevel.Administrator, true)] + public bool? Encrypted { get; set; } - [CommandProperty(AccessLevel.Administrator, true)] - public ClientFlags Flags { get; set; } + [CommandProperty(AccessLevel.Administrator, true)] + public ClientFlags Flags { get; set; } - [CommandProperty(AccessLevel.Administrator, true)] - public ClientVersion Version - { - get { return m_Version; } - set - { - m_Version = value; + [CommandProperty(AccessLevel.Administrator, true)] + public ClientVersion Version + { + get { return m_Version; } + set + { + m_Version = value; - if (value >= m_Version70610) - { - _ProtocolChanges = ProtocolChanges.Version70610; - } - else if (value >= m_Version70500) - { - _ProtocolChanges = ProtocolChanges.Version70500; - } - else if (value >= m_Version704565) - { - _ProtocolChanges = ProtocolChanges.Version704565; - } - else if (value >= m_Version70331) - { - _ProtocolChanges = ProtocolChanges.Version70331; - } - else if (value >= m_Version70300) - { - _ProtocolChanges = ProtocolChanges.Version70300; - } - else if (value >= m_Version70160) - { - _ProtocolChanges = ProtocolChanges.Version70160; - } - else if (value >= m_Version70130) - { - _ProtocolChanges = ProtocolChanges.Version70130; - } - else if (value >= m_Version7090) - { - _ProtocolChanges = ProtocolChanges.Version7090; - } - else if (value >= m_Version7000) - { - _ProtocolChanges = ProtocolChanges.Version7000; - } - else if (value >= m_Version60142) - { - _ProtocolChanges = ProtocolChanges.Version60142; - } - else if (value >= m_Version6017) - { - _ProtocolChanges = ProtocolChanges.Version6017; - } - else if (value >= m_Version6000) - { - _ProtocolChanges = ProtocolChanges.Version6000; - } - else if (value >= m_Version502b) - { - _ProtocolChanges = ProtocolChanges.Version502b; - } - else if (value >= m_Version500a) - { - _ProtocolChanges = ProtocolChanges.Version500a; - } - else if (value >= m_Version407a) - { - _ProtocolChanges = ProtocolChanges.Version407a; - } - else if (value >= m_Version400a) - { - _ProtocolChanges = ProtocolChanges.Version400a; - } - } - } + if (value >= m_Version70610) + { + _ProtocolChanges = ProtocolChanges.Version70610; + } + else if (value >= m_Version70500) + { + _ProtocolChanges = ProtocolChanges.Version70500; + } + else if (value >= m_Version704565) + { + _ProtocolChanges = ProtocolChanges.Version704565; + } + else if (value >= m_Version70331) + { + _ProtocolChanges = ProtocolChanges.Version70331; + } + else if (value >= m_Version70300) + { + _ProtocolChanges = ProtocolChanges.Version70300; + } + else if (value >= m_Version70160) + { + _ProtocolChanges = ProtocolChanges.Version70160; + } + else if (value >= m_Version70130) + { + _ProtocolChanges = ProtocolChanges.Version70130; + } + else if (value >= m_Version7090) + { + _ProtocolChanges = ProtocolChanges.Version7090; + } + else if (value >= m_Version7000) + { + _ProtocolChanges = ProtocolChanges.Version7000; + } + else if (value >= m_Version60142) + { + _ProtocolChanges = ProtocolChanges.Version60142; + } + else if (value >= m_Version6017) + { + _ProtocolChanges = ProtocolChanges.Version6017; + } + else if (value >= m_Version6000) + { + _ProtocolChanges = ProtocolChanges.Version6000; + } + else if (value >= m_Version502b) + { + _ProtocolChanges = ProtocolChanges.Version502b; + } + else if (value >= m_Version500a) + { + _ProtocolChanges = ProtocolChanges.Version500a; + } + else if (value >= m_Version407a) + { + _ProtocolChanges = ProtocolChanges.Version407a; + } + else if (value >= m_Version400a) + { + _ProtocolChanges = ProtocolChanges.Version400a; + } + } + } - private static readonly ClientVersion m_Version400a = new ClientVersion("4.0.0a"); - private static readonly ClientVersion m_Version407a = new ClientVersion("4.0.7a"); - private static readonly ClientVersion m_Version500a = new ClientVersion("5.0.0a"); - private static readonly ClientVersion m_Version502b = new ClientVersion("5.0.2b"); - private static readonly ClientVersion m_Version6000 = new ClientVersion("6.0.0.0"); - private static readonly ClientVersion m_Version6017 = new ClientVersion("6.0.1.7"); - private static readonly ClientVersion m_Version60142 = new ClientVersion("6.0.14.2"); - private static readonly ClientVersion m_Version7000 = new ClientVersion("7.0.0.0"); - private static readonly ClientVersion m_Version7090 = new ClientVersion("7.0.9.0"); - private static readonly ClientVersion m_Version70130 = new ClientVersion("7.0.13.0"); - private static readonly ClientVersion m_Version70160 = new ClientVersion("7.0.16.0"); - private static readonly ClientVersion m_Version70300 = new ClientVersion("7.0.30.0"); - private static readonly ClientVersion m_Version70331 = new ClientVersion("7.0.33.1"); - private static readonly ClientVersion m_Version704565 = new ClientVersion("7.0.45.65"); - private static readonly ClientVersion m_Version70500 = new ClientVersion("7.0.50.0"); - private static readonly ClientVersion m_Version70610 = new ClientVersion("7.0.61.0"); + private static readonly ClientVersion m_Version400a = new ClientVersion("4.0.0a"); + private static readonly ClientVersion m_Version407a = new ClientVersion("4.0.7a"); + private static readonly ClientVersion m_Version500a = new ClientVersion("5.0.0a"); + private static readonly ClientVersion m_Version502b = new ClientVersion("5.0.2b"); + private static readonly ClientVersion m_Version6000 = new ClientVersion("6.0.0.0"); + private static readonly ClientVersion m_Version6017 = new ClientVersion("6.0.1.7"); + private static readonly ClientVersion m_Version60142 = new ClientVersion("6.0.14.2"); + private static readonly ClientVersion m_Version7000 = new ClientVersion("7.0.0.0"); + private static readonly ClientVersion m_Version7090 = new ClientVersion("7.0.9.0"); + private static readonly ClientVersion m_Version70130 = new ClientVersion("7.0.13.0"); + private static readonly ClientVersion m_Version70160 = new ClientVersion("7.0.16.0"); + private static readonly ClientVersion m_Version70300 = new ClientVersion("7.0.30.0"); + private static readonly ClientVersion m_Version70331 = new ClientVersion("7.0.33.1"); + private static readonly ClientVersion m_Version704565 = new ClientVersion("7.0.45.65"); + private static readonly ClientVersion m_Version70500 = new ClientVersion("7.0.50.0"); + private static readonly ClientVersion m_Version70610 = new ClientVersion("7.0.61.0"); - private ProtocolChanges _ProtocolChanges; + private ProtocolChanges _ProtocolChanges; - private enum ProtocolChanges - { - NewSpellbook = 0x00000001, - DamagePacket = 0x00000002, - Unpack = 0x00000004, - BuffIcon = 0x00000008, - NewHaven = 0x00000010, - ContainerGridLines = 0x00000020, - ExtendedSupportedFeatures = 0x00000040, - StygianAbyss = 0x00000080, - HighSeas = 0x00000100, - NewCharacterList = 0x00000200, - NewCharacterCreation = 0x00000400, - ExtendedStatus = 0x00000800, - NewMobileIncoming = 0x00001000, - NewSecureTrading = 0x00002000, - UltimaStore = 0x00004000, - EndlessJourney = 0x00008000, + private enum ProtocolChanges + { + NewSpellbook = 0x00000001, + DamagePacket = 0x00000002, + Unpack = 0x00000004, + BuffIcon = 0x00000008, + NewHaven = 0x00000010, + ContainerGridLines = 0x00000020, + ExtendedSupportedFeatures = 0x00000040, + StygianAbyss = 0x00000080, + HighSeas = 0x00000100, + NewCharacterList = 0x00000200, + NewCharacterCreation = 0x00000400, + ExtendedStatus = 0x00000800, + NewMobileIncoming = 0x00001000, + NewSecureTrading = 0x00002000, + UltimaStore = 0x00004000, + EndlessJourney = 0x00008000, - Version400a = NewSpellbook, - Version407a = Version400a | DamagePacket, - Version500a = Version407a | Unpack, - Version502b = Version500a | BuffIcon, - Version6000 = Version502b | NewHaven, - Version6017 = Version6000 | ContainerGridLines, - Version60142 = Version6017 | ExtendedSupportedFeatures, - Version7000 = Version60142 | StygianAbyss, - Version7090 = Version7000 | HighSeas, - Version70130 = Version7090 | NewCharacterList, - Version70160 = Version70130 | NewCharacterCreation, - Version70300 = Version70160 | ExtendedStatus, - Version70331 = Version70300 | NewMobileIncoming, - Version704565 = Version70331 | NewSecureTrading, - Version70500 = Version704565 | UltimaStore, - Version70610 = Version70500 | EndlessJourney - } + Version400a = NewSpellbook, + Version407a = Version400a | DamagePacket, + Version500a = Version407a | Unpack, + Version502b = Version500a | BuffIcon, + Version6000 = Version502b | NewHaven, + Version6017 = Version6000 | ContainerGridLines, + Version60142 = Version6017 | ExtendedSupportedFeatures, + Version7000 = Version60142 | StygianAbyss, + Version7090 = Version7000 | HighSeas, + Version70130 = Version7090 | NewCharacterList, + Version70160 = Version70130 | NewCharacterCreation, + Version70300 = Version70160 | ExtendedStatus, + Version70331 = Version70300 | NewMobileIncoming, + Version704565 = Version70331 | NewSecureTrading, + Version70500 = Version704565 | UltimaStore, + Version70610 = Version70500 | EndlessJourney + } - [CommandProperty(AccessLevel.Administrator, true)] - public bool NewSpellbook { get { return ((_ProtocolChanges & ProtocolChanges.NewSpellbook) != 0); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool NewSpellbook { get { return ((_ProtocolChanges & ProtocolChanges.NewSpellbook) != 0); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool DamagePacket { get { return ((_ProtocolChanges & ProtocolChanges.DamagePacket) != 0); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool DamagePacket { get { return ((_ProtocolChanges & ProtocolChanges.DamagePacket) != 0); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool Unpack { get { return ((_ProtocolChanges & ProtocolChanges.Unpack) != 0); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool Unpack { get { return ((_ProtocolChanges & ProtocolChanges.Unpack) != 0); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool BuffIcon { get { return ((_ProtocolChanges & ProtocolChanges.BuffIcon) != 0); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool BuffIcon { get { return ((_ProtocolChanges & ProtocolChanges.BuffIcon) != 0); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool NewHaven { get { return ((_ProtocolChanges & ProtocolChanges.NewHaven) != 0); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool NewHaven { get { return ((_ProtocolChanges & ProtocolChanges.NewHaven) != 0); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool ContainerGridLines { get { return ((_ProtocolChanges & ProtocolChanges.ContainerGridLines) != 0); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool ContainerGridLines { get { return ((_ProtocolChanges & ProtocolChanges.ContainerGridLines) != 0); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool ExtendedSupportedFeatures { get { return ((_ProtocolChanges & ProtocolChanges.ExtendedSupportedFeatures) != 0); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool ExtendedSupportedFeatures { get { return ((_ProtocolChanges & ProtocolChanges.ExtendedSupportedFeatures) != 0); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool StygianAbyss { get { return ((_ProtocolChanges & ProtocolChanges.StygianAbyss) != 0); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool StygianAbyss { get { return ((_ProtocolChanges & ProtocolChanges.StygianAbyss) != 0); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool HighSeas { get { return ((_ProtocolChanges & ProtocolChanges.HighSeas) != 0); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool HighSeas { get { return ((_ProtocolChanges & ProtocolChanges.HighSeas) != 0); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool NewCharacterList { get { return ((_ProtocolChanges & ProtocolChanges.NewCharacterList) != 0); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool NewCharacterList { get { return ((_ProtocolChanges & ProtocolChanges.NewCharacterList) != 0); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool NewCharacterCreation { get { return ((_ProtocolChanges & ProtocolChanges.NewCharacterCreation) != 0); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool NewCharacterCreation { get { return ((_ProtocolChanges & ProtocolChanges.NewCharacterCreation) != 0); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool ExtendedStatus { get { return ((_ProtocolChanges & ProtocolChanges.ExtendedStatus) != 0); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool ExtendedStatus { get { return ((_ProtocolChanges & ProtocolChanges.ExtendedStatus) != 0); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool NewMobileIncoming { get { return ((_ProtocolChanges & ProtocolChanges.NewMobileIncoming) != 0); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool NewMobileIncoming { get { return ((_ProtocolChanges & ProtocolChanges.NewMobileIncoming) != 0); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool NewSecureTrading { get { return ((_ProtocolChanges & ProtocolChanges.NewSecureTrading) != 0); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool NewSecureTrading { get { return ((_ProtocolChanges & ProtocolChanges.NewSecureTrading) != 0); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool UltimaStore { get { return ((_ProtocolChanges & ProtocolChanges.UltimaStore) != 0); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool UltimaStore { get { return ((_ProtocolChanges & ProtocolChanges.UltimaStore) != 0); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool EndlessJourney { get { return ((_ProtocolChanges & ProtocolChanges.EndlessJourney) != 0); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool EndlessJourney { get { return ((_ProtocolChanges & ProtocolChanges.EndlessJourney) != 0); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool IsUOTDClient { get { return ((Flags & ClientFlags.UOTD) != 0 || (m_Version != null && m_Version.Type == ClientType.UOTD)); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool IsUOTDClient { get { return ((Flags & ClientFlags.UOTD) != 0 || (m_Version != null && m_Version.Type == ClientType.UOTD)); } } - [CommandProperty(AccessLevel.Administrator, true)] - public bool IsSAClient { get { return (m_Version != null && m_Version.Type == ClientType.SA); } } + [CommandProperty(AccessLevel.Administrator, true)] + public bool IsSAClient { get { return (m_Version != null && m_Version.Type == ClientType.SA); } } - [CommandProperty(AccessLevel.Administrator, true)] + [CommandProperty(AccessLevel.Administrator, true)] public bool IsEnhancedClient { get { return IsUOTDClient || (m_Version != null && m_Version.Major >= 67); } } public List Trades { get { return m_Trades; } } - public void ValidateAllTrades() - { - if (m_Trades == null) - { - return; - } + public void ValidateAllTrades() + { + if (m_Trades == null) + { + return; + } - for (int i = m_Trades.Count - 1; i >= 0; --i) - { - if (i >= m_Trades.Count) - { - continue; - } + for (int i = m_Trades.Count - 1; i >= 0; --i) + { + if (i >= m_Trades.Count) + { + continue; + } - var trade = m_Trades[i]; + var trade = m_Trades[i]; - if (trade.From.Mobile.Deleted || trade.To.Mobile.Deleted || !trade.From.Mobile.Alive || !trade.To.Mobile.Alive || - !trade.From.Mobile.InRange(trade.To.Mobile, 2) || trade.From.Mobile.Map != trade.To.Mobile.Map) - { - trade.Cancel(); - } - } - } + if (trade.From.Mobile.Deleted || trade.To.Mobile.Deleted || !trade.From.Mobile.Alive || !trade.To.Mobile.Alive || + !trade.From.Mobile.InRange(trade.To.Mobile, 2) || trade.From.Mobile.Map != trade.To.Mobile.Map) + { + trade.Cancel(); + } + } + } - public void CancelAllTrades() - { - if (m_Trades == null) - { - return; - } + public void CancelAllTrades() + { + if (m_Trades == null) + { + return; + } - for (int i = m_Trades.Count - 1; i >= 0; --i) - { - if (i < m_Trades.Count) - { - m_Trades[i].Cancel(); - } - } - } + for (int i = m_Trades.Count - 1; i >= 0; --i) + { + if (i < m_Trades.Count) + { + m_Trades[i].Cancel(); + } + } + } - public void RemoveTrade(SecureTrade trade) - { - if (m_Trades != null) - { - m_Trades.Remove(trade); - } - } + public void RemoveTrade(SecureTrade trade) + { + if (m_Trades != null) + { + m_Trades.Remove(trade); + } + } - public SecureTrade FindTrade(Mobile m) - { - if (m_Trades == null) - { - return null; - } + public SecureTrade FindTrade(Mobile m) + { + if (m_Trades == null) + { + return null; + } - foreach (var trade in m_Trades) - { - if (trade.From.Mobile == m || trade.To.Mobile == m) - { - return trade; - } - } + foreach (var trade in m_Trades) + { + if (trade.From.Mobile == m || trade.To.Mobile == m) + { + return trade; + } + } - return null; - } + return null; + } - public SecureTradeContainer FindTradeContainer(Mobile m) - { - if (m_Trades == null) - { - return null; - } + public SecureTradeContainer FindTradeContainer(Mobile m) + { + if (m_Trades == null) + { + return null; + } - foreach (var trade in m_Trades) - { - var from = trade.From; - var to = trade.To; + foreach (var trade in m_Trades) + { + var from = trade.From; + var to = trade.To; - if (from.Mobile == Mobile && to.Mobile == m) - { - return from.Container; - } + if (from.Mobile == Mobile && to.Mobile == m) + { + return from.Container; + } - if (from.Mobile == m && to.Mobile == Mobile) - { - return to.Container; - } - } + if (from.Mobile == m && to.Mobile == Mobile) + { + return to.Container; + } + } - return null; - } + return null; + } - public SecureTradeContainer AddTrade(NetState state) - { - if (m_Trades == null || state.m_Trades == null) - { - return null; - } + public SecureTradeContainer AddTrade(NetState state) + { + if (m_Trades == null || state.m_Trades == null) + { + return null; + } - var newTrade = new SecureTrade(Mobile, state.Mobile); + var newTrade = new SecureTrade(Mobile, state.Mobile); - m_Trades.Add(newTrade); - state.m_Trades.Add(newTrade); + m_Trades.Add(newTrade); + state.m_Trades.Add(newTrade); - return newTrade.From.Container; - } - - [CommandProperty(AccessLevel.Administrator, true)] - public bool CompressionEnabled { get; set; } + return newTrade.From.Container; + } - [CommandProperty(AccessLevel.Administrator, true)] - public int Sequence { get; set; } + [CommandProperty(AccessLevel.Administrator, true)] + public bool CompressionEnabled { get; set; } - public List Gumps { get { return m_Gumps; } } - public List HuePickers { get { return m_HuePickers; } } - public List Menus { get { return m_Menus; } } + [CommandProperty(AccessLevel.Administrator, true)] + public int Sequence { get; set; } - private static int m_GumpCap = 512, m_HuePickerCap = 512, m_MenuCap = 512; + public List Gumps { get { return m_Gumps; } } + public List HuePickers { get { return m_HuePickers; } } + public List Menus { get { return m_Menus; } } - public static int GumpCap { get { return m_GumpCap; } set { m_GumpCap = value; } } - public static int HuePickerCap { get { return m_HuePickerCap; } set { m_HuePickerCap = value; } } - public static int MenuCap { get { return m_MenuCap; } set { m_MenuCap = value; } } - - [CommandProperty(AccessLevel.Administrator, true)] + private static int m_GumpCap = 512, m_HuePickerCap = 512, m_MenuCap = 512; + + public static int GumpCap { get { return m_GumpCap; } set { m_GumpCap = value; } } + public static int HuePickerCap { get { return m_HuePickerCap; } set { m_HuePickerCap = value; } } + public static int MenuCap { get { return m_MenuCap; } set { m_MenuCap = value; } } + + [CommandProperty(AccessLevel.Administrator, true)] public int UpdateRange { get; set; } - public void WriteConsole(string text) - { - Console.WriteLine("Client: {0}: {1}", this, text); - } + public void WriteConsole(string text) + { + Console.WriteLine("Client: {0}: {1}", this, text); + } - public void WriteConsole(string format, params object[] args) - { - WriteConsole(String.Format(format, args)); - } + public void WriteConsole(string format, params object[] args) + { + WriteConsole(String.Format(format, args)); + } - public void AddMenu(IMenu menu) - { - if (m_Menus == null) - { - m_Menus = new List(); - } + public void AddMenu(IMenu menu) + { + if (m_Menus == null) + { + m_Menus = new List(); + } - if (m_Menus.Count < m_MenuCap) - { - m_Menus.Add(menu); - } - else - { - Utility.PushColor(ConsoleColor.Red); - WriteConsole("Exceeded menu cap, disconnecting..."); - Utility.PopColor(); - Dispose(); - } - } + if (m_Menus.Count < m_MenuCap) + { + m_Menus.Add(menu); + } + else + { + Utility.PushColor(ConsoleColor.Red); + WriteConsole("Exceeded menu cap, disconnecting..."); + Utility.PopColor(); + Dispose(); + } + } - public void RemoveMenu(IMenu menu) - { - if (m_Menus != null) - { - m_Menus.Remove(menu); - } - } + public void RemoveMenu(IMenu menu) + { + if (m_Menus != null) + { + m_Menus.Remove(menu); + } + } - public void RemoveMenu(int index) - { - if (m_Menus != null) - { - m_Menus.RemoveAt(index); - } - } + public void RemoveMenu(int index) + { + if (m_Menus != null) + { + m_Menus.RemoveAt(index); + } + } - public void ClearMenus() - { - if (m_Menus != null) - { - m_Menus.Clear(); - } - } + public void ClearMenus() + { + if (m_Menus != null) + { + m_Menus.Clear(); + } + } - public void AddHuePicker(HuePicker huePicker) - { - if (m_HuePickers == null) - { - m_HuePickers = new List(); - } + public void AddHuePicker(HuePicker huePicker) + { + if (m_HuePickers == null) + { + m_HuePickers = new List(); + } - if (m_HuePickers.Count < m_HuePickerCap) - { - m_HuePickers.Add(huePicker); - } - else - { - Utility.PushColor(ConsoleColor.Red); - WriteConsole("Exceeded hue picker cap, disconnecting..."); - Utility.PopColor(); - Dispose(); - } - } + if (m_HuePickers.Count < m_HuePickerCap) + { + m_HuePickers.Add(huePicker); + } + else + { + Utility.PushColor(ConsoleColor.Red); + WriteConsole("Exceeded hue picker cap, disconnecting..."); + Utility.PopColor(); + Dispose(); + } + } - public void RemoveHuePicker(HuePicker huePicker) - { - if (m_HuePickers != null) - { - m_HuePickers.Remove(huePicker); - } - } + public void RemoveHuePicker(HuePicker huePicker) + { + if (m_HuePickers != null) + { + m_HuePickers.Remove(huePicker); + } + } - public void RemoveHuePicker(int index) - { - if (m_HuePickers != null) - { - m_HuePickers.RemoveAt(index); - } - } + public void RemoveHuePicker(int index) + { + if (m_HuePickers != null) + { + m_HuePickers.RemoveAt(index); + } + } - public void ClearHuePickers() - { - if (m_HuePickers != null) - { - m_HuePickers.Clear(); - } - } + public void ClearHuePickers() + { + if (m_HuePickers != null) + { + m_HuePickers.Clear(); + } + } - public void AddGump(Gump gump) - { - if (m_Gumps == null) - { - m_Gumps = new List(); - } + public void AddGump(Gump gump) + { + if (m_Gumps == null) + { + m_Gumps = new List(); + } - if (m_Gumps.Count < m_GumpCap) - { - m_Gumps.Add(gump); - } - else - { - Utility.PushColor(ConsoleColor.Red); - WriteConsole("Exceeded gump cap, disconnecting..."); - Utility.PopColor(); - Dispose(); - } - } + if (m_Gumps.Count < m_GumpCap) + { + m_Gumps.Add(gump); + } + else + { + Utility.PushColor(ConsoleColor.Red); + WriteConsole("Exceeded gump cap, disconnecting..."); + Utility.PopColor(); + Dispose(); + } + } - public void RemoveGump(Gump gump) - { - if (m_Gumps != null) - { - m_Gumps.Remove(gump); - } - } + public void RemoveGump(Gump gump) + { + if (m_Gumps != null) + { + m_Gumps.Remove(gump); + } + } - public void RemoveGump(int index) - { - if (m_Gumps != null) - { - m_Gumps.RemoveAt(index); - } - } + public void RemoveGump(int index) + { + if (m_Gumps != null) + { + m_Gumps.RemoveAt(index); + } + } - public void ClearGumps() - { - if (m_Gumps != null) - { - m_Gumps.Clear(); - } - } + public void ClearGumps() + { + if (m_Gumps != null) + { + m_Gumps.Clear(); + } + } - public void LaunchBrowser(string url) - { - Send(new MessageLocalized(Serial.MinusOne, -1, MessageType.Label, 0x35, 3, 501231, "", "")); - Send(new LaunchBrowser(url)); - } + public void LaunchBrowser(string url) + { + Send(new MessageLocalized(Serial.MinusOne, -1, MessageType.Label, 0x35, 3, 501231, "", "")); + Send(new LaunchBrowser(url)); + } - public CityInfo[] CityInfo { get; set; } + public CityInfo[] CityInfo { get; set; } - [CommandProperty(AccessLevel.Administrator, true)] - public Mobile Mobile { get; set; } + [CommandProperty(AccessLevel.Administrator, true)] + public Mobile Mobile { get; set; } - public ServerInfo[] ServerInfo { get; set; } - - [CommandProperty(AccessLevel.Administrator)] - public IAccount Account { get; set; } + public ServerInfo[] ServerInfo { get; set; } - public override string ToString() - { - return m_ToString; - } + [CommandProperty(AccessLevel.Administrator)] + public IAccount Account { get; set; } - private static readonly List m_Instances = new List(); + public override string ToString() + { + return m_ToString; + } - public static List Instances { get { return m_Instances; } } + private static readonly ConcurrentDictionary m_Instances = new ConcurrentDictionary(); - public const int SendBufferCapacity = 1024, SendBufferSize = 8092; - public const int ReceiveBufferCapacity = 1024, ReceiveBufferSize = 2048; + public static ReadOnlyCollection Instances => (ReadOnlyCollection)m_Instances.Keys; + public static ReadOnlyCollection Addresses => (ReadOnlyCollection)m_Instances.Values; - private static readonly BufferPool m_SendBufferPool = new BufferPool("Send", SendBufferCapacity, SendBufferSize); - private static readonly BufferPool m_ReceiveBufferPool = new BufferPool("Receive", ReceiveBufferCapacity, ReceiveBufferSize); + public const int SendBufferCapacity = 1024, SendBufferSize = 8092; + public const int ReceiveBufferCapacity = 1024, ReceiveBufferSize = 2048; - public static BufferPool SendBuffers { get { return m_SendBufferPool; } } - public static BufferPool ReceiveBuffers { get { return m_ReceiveBufferPool; } } + private static readonly BufferPool m_SendBufferPool = new BufferPool("Send", SendBufferCapacity, SendBufferSize); + private static readonly BufferPool m_ReceiveBufferPool = new BufferPool("Receive", ReceiveBufferCapacity, ReceiveBufferSize); - public NetState(Socket socket, MessagePump messagePump) - { - Socket = socket; - m_Buffer = new ByteQueue(); + public static BufferPool SendBuffers { get { return m_SendBufferPool; } } + public static BufferPool ReceiveBuffers { get { return m_ReceiveBufferPool; } } - m_RecvBuffer = m_ReceiveBufferPool.AcquireBuffer(); - m_MessagePump = messagePump; + public NetState(SocketState state) + { + Socket = state.Socket; - m_Gumps = new List(); - m_HuePickers = new List(); - m_Menus = new List(); - m_Trades = new List(); + m_InitialData = state.Seed; - m_SendQueue = new SendQueue(); + m_Buffer = new ByteQueue(); - m_NextCheckActivity = Core.TickCount + 30000; + m_RecvBuffer = m_ReceiveBufferPool.AcquireBuffer(); - m_Instances.Add(this); + m_Gumps = new List(); + m_HuePickers = new List(); + m_Menus = new List(); + m_Trades = new List(); - try - { - m_Address = Utility.Intern(((IPEndPoint)Socket.RemoteEndPoint).Address); - m_ToString = m_Address.ToString(); - } - catch (Exception ex) - { - TraceException(ex); - m_Address = IPAddress.None; - m_ToString = "(error)"; - } + m_SendQueue = new SendQueue(); - m_ConnectedOn = DateTime.UtcNow; + m_NextCheckActivity = Core.TickCount + 30000; + + try + { + m_Address = Utility.Intern(((IPEndPoint)Socket.RemoteEndPoint).Address); + m_ToString = m_Address.ToString(); + } + catch (Exception ex) + { + TraceException(ex); + m_Address = IPAddress.None; + m_ToString = "(error)"; + } + + m_Instances[this] = m_Address; + + m_ConnectedOn = DateTime.UtcNow; UpdateRange = Core.GlobalUpdateRange; - if (CreatedCallback != null) - { - CreatedCallback(this); - } - } + if (CreatedCallback != null) + { + CreatedCallback(this); + } + } - private bool _Sending; + private volatile bool _Sending; private readonly object _SendLock = new object(); - public virtual void Send(Packet p) - { - if (Socket == null || BlockAllPackets) - { - p.OnSend(); - return; - } + public virtual void Send(Packet p) + { + if (p == null) + { + return; + } - int length; + try + { + if (Socket == null || BlockAllPackets) + { + return; + } - var buffer = p.Compile(CompressionEnabled, out length); + var buffer = p.Compile(CompressionEnabled, out int length); - if (buffer != null) - { - if (buffer.Length <= 0 || length <= 0) - { - p.OnSend(); - return; - } + if (buffer != null) + { + if (buffer.Length <= 0 || length <= 0) + { + return; + } - PacketSendProfile prof = null; + PacketSendProfile prof = null; - if (Core.Profiling) - { - prof = PacketSendProfile.Acquire(p.GetType()); - } + if (Core.Profiling) + { + prof = PacketSendProfile.Acquire(p.GetType()); + } - if (prof != null) - { - prof.Start(); - } + prof?.Start(); - var buffered = false; + try + { + var buffered = false; - if (PacketEncoder != null || PacketEncryptor != null) - { - var packetBuffer = buffer; - var packetLength = length; + if (PacketEncoder != null || PacketEncryptor != null) + { + var packetBuffer = buffer; + var packetLength = length; - if (BufferStaticPackets && p.State.HasFlag(PacketState.Acquired)) - { - if (packetLength <= SendBufferSize) - { - packetBuffer = m_SendBufferPool.AcquireBuffer(); - } - else - { - packetBuffer = new byte[packetLength]; - } + if (BufferStaticPackets && p.State.HasFlag(PacketState.Acquired)) + { + if (packetLength <= SendBufferSize) + { + packetBuffer = m_SendBufferPool.AcquireBuffer(); + } + else + { + packetBuffer = new byte[packetLength]; + } - System.Buffer.BlockCopy(buffer, 0, packetBuffer, 0, packetLength); - } + System.Buffer.BlockCopy(buffer, 0, packetBuffer, 0, packetLength); + } - if (PacketEncoder != null) - { - PacketEncoder.EncodeOutgoingPacket(this, ref packetBuffer, ref packetLength); - } + PacketEncoder?.EncodeOutgoingPacket(this, ref packetBuffer, ref packetLength); + PacketEncryptor?.EncryptOutgoingPacket(this, ref packetBuffer, ref packetLength); - if (PacketEncryptor != null) - { - PacketEncryptor.EncryptOutgoingPacket(this, ref packetBuffer, ref packetLength); - } + buffered = buffer != packetBuffer && packetBuffer.Length == SendBufferSize; - buffered = buffer != packetBuffer && packetBuffer.Length == SendBufferSize; + buffer = packetBuffer; + length = packetLength; + } - buffer = packetBuffer; - length = packetLength; - } + try + { + lock (_SendLock) + { + SendQueue.Gram gram; - try - { - SendQueue.Gram gram; + lock (m_SendQueue) + { + gram = m_SendQueue.Enqueue(buffer, length); + } - lock (_SendLock) - { - lock (m_SendQueue) - { - gram = m_SendQueue.Enqueue(buffer, length); - } + if (buffered && m_SendBufferPool.Count < SendBufferCapacity) + { + m_SendBufferPool.ReleaseBuffer(buffer); + } - if (buffered && m_SendBufferPool.Count < SendBufferCapacity) - { - m_SendBufferPool.ReleaseBuffer(buffer); - } + if (gram != null && !_Sending) + { + _Sending = true; - if (gram != null && !_Sending) - { - _Sending = true; + try + { + var segment = new ArraySegment(gram.Buffer, 0, gram.Length); - try - { - Socket.BeginSend(gram.Buffer, 0, gram.Length, SocketFlags.None, m_OnSend, Socket); - } - catch (Exception ex) - { - TraceException(ex); - Dispose(false); - } - } - } - } - catch (CapacityExceededException) - { - Utility.PushColor(ConsoleColor.Red); - Console.WriteLine("Client: {0}: Too much data pending, disconnecting...", this); - Utility.PopColor(); + _ = Socket.SendAsync(segment, SocketFlags.None).ContinueWith(OnSend); + } + catch (Exception ex) + { + TraceException(ex); + Dispose(false); + } + } + } + } + catch (CapacityExceededException) + { + Utility.PushColor(ConsoleColor.Red); + Console.WriteLine("Client: {0}: Too much data pending, disconnecting...", this); + Utility.PopColor(); - Dispose(false); - } + Dispose(false); + } + } + finally + { + prof?.Finish(length); + } + } + else + { + Utility.PushColor(ConsoleColor.Red); + Console.WriteLine("Client: {0}: null buffer send, disconnecting...", this); + Utility.PopColor(); - p.OnSend(); + using (var op = new StreamWriter("null_send.log", true)) + { + op.WriteLine("{0} Client: {1}: null buffer send, disconnecting...", DateTime.UtcNow, this); + op.WriteLine(new StackTrace()); + } - if (prof != null) - { - prof.Finish(length); - } - } - else - { - Utility.PushColor(ConsoleColor.Red); - Console.WriteLine("Client: {0}: null buffer send, disconnecting...", this); - Utility.PopColor(); + Dispose(); + } + } + finally + { + p.OnSend(); + } + } - using (var op = new StreamWriter("null_send.log", true)) - { - op.WriteLine("{0} Client: {1}: null buffer send, disconnecting...", DateTime.UtcNow, this); - op.WriteLine(new StackTrace()); - } + public void Start() + { + m_Running = true; - Dispose(); - } - } + if (Socket == null || m_Paused) + { + return; + } - public void Start() - { - m_OnReceive = OnReceive; - m_OnSend = OnSend; - - m_Running = true; - - if (Socket == null || m_Paused) - { - return; - } - - try + try { lock (m_AsyncLock) - { - if ((m_AsyncState & (AsyncState.Pending | AsyncState.Paused)) == 0) - { - InternalBeginReceive(); - } - } + { + if ((m_AsyncState & (AsyncState.Pending | AsyncState.Paused)) == 0) + { + InternalBeginReceive(); + } + } } - catch (Exception ex) - { - TraceException(ex); - Dispose(false); - } - } + catch (Exception ex) + { + TraceException(ex); + Dispose(false); + } + } - private void InternalBeginReceive() - { - m_AsyncState |= AsyncState.Pending; + private byte[] m_InitialData; - Socket.BeginReceive(m_RecvBuffer, 0, m_RecvBuffer.Length, SocketFlags.None, m_OnReceive, Socket); - } + private void InternalBeginReceive() + { + m_AsyncState |= AsyncState.Pending; - private void OnReceive(IAsyncResult asyncResult) - { - try - { - var s = (Socket)asyncResult.AsyncState; + if (m_InitialData != null) + { + _ = Task.Factory.StartNew(() => + { + var data = Interlocked.Exchange(ref m_InitialData, null); - var byteCount = s.EndReceive(asyncResult); + System.Buffer.BlockCopy(data, 0, m_RecvBuffer, 0, data.Length); - if (byteCount > 0) - { - m_NextCheckActivity = Core.TickCount + 90000; + return data.Length; + }).ContinueWith(OnReceive); + } + else + { + var segment = new ArraySegment(m_RecvBuffer, 0, m_RecvBuffer.Length); + + _ = Socket.ReceiveAsync(segment, SocketFlags.None).ContinueWith(OnReceive); + } + } + + private void OnReceive(Task task) + { + try + { + if (task.IsFaulted) + { + throw task.Exception; + } + + var byteCount = task.Result; + + if (byteCount > 0) + { + m_NextCheckActivity = Core.TickCount + 90000; byte[] buffer; @@ -823,492 +845,476 @@ namespace Server.Network buffer = m_RecvBuffer; } - if (PacketEncryptor != null) - { - PacketEncryptor.DecryptIncomingPacket(this, ref buffer, ref byteCount); - } + PacketEncryptor?.DecryptIncomingPacket(this, ref buffer, ref byteCount); + PacketEncoder?.DecodeIncomingPacket(this, ref buffer, ref byteCount); - if (PacketEncoder != null) - { - PacketEncoder.DecodeIncomingPacket(this, ref buffer, ref byteCount); - } + lock (m_Buffer) + { + m_Buffer.Enqueue(buffer, 0, byteCount); + } - lock (m_Buffer) - m_Buffer.Enqueue(buffer, 0, byteCount); - - m_MessagePump.OnReceive(this); + MessagePump.OnReceive(this); lock (m_AsyncLock) { - m_AsyncState &= ~AsyncState.Pending; + m_AsyncState &= ~AsyncState.Pending; + + if ((m_AsyncState & AsyncState.Paused) == 0) + { + try + { + InternalBeginReceive(); + } + catch (Exception ex) + { + TraceException(ex); + Dispose(false); + } + } + } + } + else + { + Dispose(false); + } + } + catch + { + Dispose(false); + } + } - if ((m_AsyncState & AsyncState.Paused) == 0) - { - try - { - InternalBeginReceive(); - } - catch (Exception ex) - { - TraceException(ex); - Dispose(false); - } - } - } - } - else - { - Dispose(false); - } - } - catch - { - Dispose(false); - } - } + private void OnSend(Task task) + { + try + { + if (task.IsFaulted) + { + throw task.Exception; + } - private void OnSend(IAsyncResult asyncResult) - { - var s = (Socket)asyncResult.AsyncState; + var bytes = task.Result; - try - { - var bytes = s.EndSend(asyncResult); + if (bytes <= 0) + { + Dispose(false); + return; + } - if (bytes <= 0) - { - Dispose(false); - return; - } + m_NextCheckActivity = Core.TickCount + 90000; - m_NextCheckActivity = Core.TickCount + 90000; + if (m_CoalesceSleep >= 0) + { + Thread.Sleep(m_CoalesceSleep); + } - if (m_CoalesceSleep >= 0) - { - Thread.Sleep(m_CoalesceSleep); - } + SendQueue.Gram gram; - SendQueue.Gram gram; + lock (m_SendQueue) + { + gram = m_SendQueue.Dequeue(); - lock (m_SendQueue) - { - gram = m_SendQueue.Dequeue(); + if (gram == null && m_SendQueue.IsFlushReady) + { + gram = m_SendQueue.CheckFlushReady(); + } + } - if (gram == null && m_SendQueue.IsFlushReady) - { - gram = m_SendQueue.CheckFlushReady(); - } - } + if (gram != null) + { + try + { + var segment = new ArraySegment(gram.Buffer, 0, gram.Length); - if (gram != null) - { - try - { - s.BeginSend(gram.Buffer, 0, gram.Length, SocketFlags.None, m_OnSend, s); - } - catch (Exception ex) - { - TraceException(ex); - Dispose(false); - } - } - else - { - lock (_SendLock) - { - _Sending = false; - } - } - } - catch (Exception) - { - Dispose(false); - } - } + _ = Socket.SendAsync(segment, SocketFlags.None).ContinueWith(OnSend); + } + catch (Exception ex) + { + TraceException(ex); + Dispose(false); + } + } + else + { + lock (_SendLock) + { + _Sending = false; + } + } + } + catch (Exception) + { + Dispose(false); + } + } - public static void Pause() - { - m_Paused = true; + public static void Pause() + { + m_Paused = true; - foreach (var ns in m_Instances) - { + foreach (var ns in m_Instances.Keys) + { lock (ns.m_AsyncLock) { ns.m_AsyncState |= AsyncState.Paused; } - } - } + } + } - public static void Resume() - { - m_Paused = false; + public static void Resume() + { + m_Paused = false; - foreach (var ns in m_Instances) - { - if (ns.Socket == null) - { - continue; - } + foreach (var ns in m_Instances.Keys) + { + if (ns.Socket == null) + { + continue; + } lock (ns.m_AsyncLock) { - ns.m_AsyncState &= ~AsyncState.Paused; - - try - { - if ((ns.m_AsyncState & AsyncState.Pending) == 0) - { - ns.InternalBeginReceive(); - } - } - catch (Exception ex) - { - TraceException(ex); - ns.Dispose(false); - } - } - } - } - - public bool Flush() - { - if (Socket == null) - { - return false; - } - - lock (_SendLock) - { - if (_Sending) - { - return false; - } - - SendQueue.Gram gram; - - lock (m_SendQueue) - { - if (!m_SendQueue.IsFlushReady) - { - return false; - } - - gram = m_SendQueue.CheckFlushReady(); - } - - if (gram != null) - { - try - { - _Sending = true; - Socket.BeginSend(gram.Buffer, 0, gram.Length, SocketFlags.None, m_OnSend, Socket); - return true; - } - catch (Exception ex) - { - TraceException(ex); - Dispose(false); - } - } - } - - return false; - } - - public PacketHandler GetHandler(int packetID) - { - if (ContainerGridLines) - { - return PacketHandlers.Get6017Handler(packetID); - } - - return PacketHandlers.GetHandler(packetID); - } - - public static void FlushAll() - { - foreach (NetState ns in m_Instances) - { - ns.Flush(); - } - } - - private static int m_CoalesceSleep = -1; - - public static int CoalesceSleep { get { return m_CoalesceSleep; } set { m_CoalesceSleep = value; } } - - private long m_NextCheckActivity; - - public void CheckAlive(long curTicks) - { - if (Socket == null) - { - return; - } - - if (m_NextCheckActivity - curTicks >= 0) - { - return; - } - - Utility.PushColor(ConsoleColor.Red); - Console.WriteLine("Client: {0}: Disconnecting due to inactivity...", this); - Utility.PopColor(); - - Dispose(); - } - - public static void TraceException(Exception ex) - { - if (!Core.Debug) - { - return; - } - - try - { - using (var op = new StreamWriter("network-errors.log", true)) - { - op.WriteLine("# {0}", DateTime.UtcNow); - - op.WriteLine(ex); - - op.WriteLine(); - op.WriteLine(); - } - } - catch - { } - - try - { - Console.WriteLine(ex); - } - catch - { } - } - - private bool m_Disposing; - - [CommandProperty(AccessLevel.Administrator, true)] - public bool IsDisposing { get { return m_Disposing; } } - - public void Dispose() - { - Dispose(true); - } - - public virtual void Dispose(bool flush) - { - if (Socket == null || m_Disposing) - { - return; - } - - m_Disposing = true; - - if (flush) - { - Flush(); - } - - try - { - Socket.Shutdown(SocketShutdown.Both); - } - catch (SocketException ex) - { - TraceException(ex); - } - - try - { - Socket.Close(); - } - catch (SocketException ex) - { - TraceException(ex); - } - - if (m_RecvBuffer != null) - { - lock (m_ReceiveBufferPool) - { - m_ReceiveBufferPool.ReleaseBuffer(m_RecvBuffer); - } - } - - Socket = null; - - PacketEncoder = null; - PacketEncryptor = null; - - m_Buffer = null; - m_RecvBuffer = null; - - m_OnReceive = null; - m_OnSend = null; - - m_Running = false; - - lock (m_Disposed) - { - m_Disposed.Enqueue(this); - } - - lock (m_SendQueue) - { - if (!m_SendQueue.IsEmpty) - { - m_SendQueue.Clear(); - } - } - } - - public static void Initialize() - { - Timer.DelayCall(TimeSpan.FromMinutes(1.0), TimeSpan.FromMinutes(1.5), CheckAllAlive); - } - - public static void CheckAllAlive() - { - try - { - var curTicks = Core.TickCount; - - var i = m_Instances.Count; - - while (--i >= 0) - { - if (m_Instances[i] != null) - { - m_Instances[i].CheckAlive(curTicks); - } - } - } - catch (Exception ex) - { - TraceException(ex); - } - } - - private static readonly Queue m_Disposed = new Queue(); - - public static void ProcessDisposedQueue() - { - lock (m_Disposed) - { - var breakout = 200; - - while (--breakout >= 0 && m_Disposed.Count > 0) - { - var ns = m_Disposed.Dequeue(); - - var m = ns.Mobile; - var a = ns.Account; - - if (m != null) - { - m.CloseAllGumps(); - - m.NetState = null; - ns.Mobile = null; - } - - ns.m_Gumps.Clear(); - ns.m_Menus.Clear(); - ns.m_HuePickers.Clear(); - ns.Account = null; - ns.ServerInfo = null; - ns.CityInfo = null; - - m_Instances.Remove(ns); - - Utility.PushColor(ConsoleColor.Red); - - if (a != null) - { - ns.WriteConsole("Disconnected. [{0} Online] [{1}]", m_Instances.Count, a); - } - else if (MessagePump.Display(ns)) - { - ns.WriteConsole("Disconnected. [{0} Online]", m_Instances.Count); - } - - Utility.PopColor(); - } - } - } - - [CommandProperty(AccessLevel.Administrator, true)] - public bool Running { get { return m_Running; } } - - [CommandProperty(AccessLevel.Administrator, true)] - public bool Seeded { get; set; } - - public Socket Socket { get; private set; } - - public ByteQueue Buffer { get { return m_Buffer; } } - - public ExpansionInfo ExpansionInfo - { - get - { - for (var i = ExpansionInfo.Table.Length - 1; i >= 0; i--) - { - var info = ExpansionInfo.Table[i]; - - if ((info.RequiredClient != null && Version >= info.RequiredClient) || ((Flags & info.ClientFlags) != 0)) - { - return info; - } - } - - return ExpansionInfo.GetInfo(Expansion.None); - } - } - - [CommandProperty(AccessLevel.Administrator, true)] - public Expansion Expansion { get { return (Expansion)ExpansionInfo.ID; } } - - public bool SupportsExpansion(ExpansionInfo info, bool checkCoreExpansion) - { - if (info == null || (checkCoreExpansion && (int)Core.Expansion < info.ID)) - { - return false; - } - - if (info.RequiredClient != null) - { - return ( IsEnhancedClient || Version >= info.RequiredClient ); - } + ns.m_AsyncState &= ~AsyncState.Paused; + try + { + if ((ns.m_AsyncState & AsyncState.Pending) == 0) + { + ns.InternalBeginReceive(); + } + } + catch (Exception ex) + { + TraceException(ex); + ns.Dispose(false); + } + } + } + } + + public bool Flush() + { + if (Socket == null) + { + return false; + } + + lock (_SendLock) + { + if (_Sending) + { + return false; + } + + SendQueue.Gram gram; + + lock (m_SendQueue) + { + if (!m_SendQueue.IsFlushReady) + { + return false; + } + + gram = m_SendQueue.CheckFlushReady(); + } + + if (gram != null) + { + try + { + _Sending = true; + + var segment = new ArraySegment(gram.Buffer, 0, gram.Length); + + _ = Socket.SendAsync(segment, SocketFlags.None).ContinueWith(OnSend); + + return true; + } + catch (Exception ex) + { + TraceException(ex); + Dispose(false); + } + } + } + + return false; + } + + public PacketHandler GetHandler(int packetID) + { + if (ContainerGridLines) + { + return PacketHandlers.Get6017Handler(packetID); + } + + return PacketHandlers.GetHandler(packetID); + } + + public static void FlushAll() + { + foreach (NetState ns in m_Instances.Keys) + { + _ = ns.Flush(); + } + } + + private static int m_CoalesceSleep = -1; + + public static int CoalesceSleep { get { return m_CoalesceSleep; } set { m_CoalesceSleep = value; } } + + private long m_NextCheckActivity; + + public void CheckAlive(long curTicks) + { + if (Socket == null) + { + return; + } + + if (m_NextCheckActivity - curTicks >= 0) + { + return; + } + + Utility.PushColor(ConsoleColor.Red); + Console.WriteLine("Client: {0}: Disconnecting due to inactivity...", this); + Utility.PopColor(); + + Dispose(); + } + + public static void TraceException(Exception ex) + { + if (!Core.Debug) + { + return; + } + + try + { + using (var op = new StreamWriter("network-errors.log", true)) + { + op.WriteLine("# {0}", DateTime.UtcNow); + + op.WriteLine(ex); + + op.WriteLine(); + op.WriteLine(); + } + } + catch + { } + + try + { + Console.WriteLine(ex); + } + catch + { } + } + + private bool m_Disposing; + + [CommandProperty(AccessLevel.Administrator, true)] + public bool IsDisposing { get { return m_Disposing; } } + + public void Dispose() + { + Dispose(true); + } + + public virtual void Dispose(bool flush) + { + if (Socket == null || m_Disposing) + { + return; + } + + m_Disposing = true; + + if (flush) + { + Flush(); + } + + try + { + Socket.Shutdown(SocketShutdown.Both); + } + catch (SocketException ex) + { + TraceException(ex); + } + + try + { + Socket.Close(); + } + catch (SocketException ex) + { + TraceException(ex); + } + + var buffer = Interlocked.Exchange(ref m_RecvBuffer, null); + + if (buffer != null) + { + m_ReceiveBufferPool.ReleaseBuffer(buffer); + } + + Socket = null; + + PacketEncoder = null; + PacketEncryptor = null; + + m_Buffer = null; + + m_Running = false; + + m_Disposed.Enqueue(this); + } + + public static void Initialize() + { + Timer.DelayCall(TimeSpan.FromMinutes(1.0), TimeSpan.FromMinutes(1.5), CheckAllAlive); + } + + public static void CheckAllAlive() + { + try + { + var curTicks = Core.TickCount; + + foreach (var ns in m_Instances.Keys) + { + ns.CheckAlive(curTicks); + } + } + catch (Exception ex) + { + TraceException(ex); + } + } + + private static readonly ConcurrentQueue m_Disposed = new ConcurrentQueue(); + + public static void ProcessDisposedQueue() + { + var breakout = m_Disposed.Count; + + while (--breakout >= 0 && m_Disposed.TryDequeue(out var ns)) + { + var m = ns.Mobile; + var a = ns.Account; + + if (m != null) + { + m.CloseAllGumps(); + + m.NetState = null; + ns.Mobile = null; + } + + m_Instances.TryRemove(ns, out _); + + ns.m_Gumps.Clear(); + ns.m_Menus.Clear(); + ns.m_HuePickers.Clear(); + + ns.Account = null; + ns.ServerInfo = null; + ns.CityInfo = null; + + if (!ns.m_SendQueue.IsEmpty) + { + ns.m_SendQueue.Clear(); + } + + Utility.PushColor(ConsoleColor.Red); + + if (a != null) + { + ns.WriteConsole("Disconnected. [{0} Online] [{1}]", m_Instances.Count, a); + } + else if (MessagePump.Display(ns)) + { + ns.WriteConsole("Disconnected. [{0} Online]", m_Instances.Count); + } + + Utility.PopColor(); + } + } + + [CommandProperty(AccessLevel.Administrator, true)] + public bool Running { get { return m_Running; } } + + [CommandProperty(AccessLevel.Administrator, true)] + public bool Seeded { get; set; } + + public Socket Socket { get; private set; } + + public ByteQueue Buffer { get { return m_Buffer; } } + + public ExpansionInfo ExpansionInfo + { + get + { + for (var i = ExpansionInfo.Table.Length - 1; i >= 0; i--) + { + var info = ExpansionInfo.Table[i]; + + if ((info.RequiredClient != null && Version >= info.RequiredClient) || ((Flags & info.ClientFlags) != 0)) + { + return info; + } + } + + return ExpansionInfo.GetInfo(Expansion.None); + } + } + + [CommandProperty(AccessLevel.Administrator, true)] + public Expansion Expansion { get { return (Expansion)ExpansionInfo.ID; } } + + public bool SupportsExpansion(ExpansionInfo info, bool checkCoreExpansion) + { + if (info == null || (checkCoreExpansion && (int)Core.Expansion < info.ID)) + { + return false; + } + + if (info.RequiredClient != null) + { + return (IsEnhancedClient || Version >= info.RequiredClient); + } + return ((Flags & info.ClientFlags) != 0); - } + } - public bool SupportsExpansion(Expansion ex, bool checkCoreExpansion) - { - return SupportsExpansion(ExpansionInfo.GetInfo(ex), checkCoreExpansion); - } + public bool SupportsExpansion(Expansion ex, bool checkCoreExpansion) + { + return SupportsExpansion(ExpansionInfo.GetInfo(ex), checkCoreExpansion); + } - public bool SupportsExpansion(Expansion ex) - { - return SupportsExpansion(ex, true); - } + public bool SupportsExpansion(Expansion ex) + { + return SupportsExpansion(ex, true); + } - public bool SupportsExpansion(ExpansionInfo info) - { - return SupportsExpansion(info, true); - } + public bool SupportsExpansion(ExpansionInfo info) + { + return SupportsExpansion(info, true); + } - public int CompareTo(NetState other) - { - if (other == null) - { - return 1; - } + public int CompareTo(NetState other) + { + if (other == null) + { + return 1; + } - return String.Compare(m_ToString, other.m_ToString, StringComparison.Ordinal); + return String.Compare(m_ToString, other.m_ToString, StringComparison.Ordinal); } #region Packet Throttling diff --git a/Server/Network/PacketHandlers.cs b/Server/Network/PacketHandlers.cs index eac131f..6de0931 100755 --- a/Server/Network/PacketHandlers.cs +++ b/Server/Network/PacketHandlers.cs @@ -48,9 +48,11 @@ namespace Server.Network private static readonly EncodedPacketHandler[] m_EncodedHandlersLow; private static readonly Dictionary m_EncodedHandlersHigh; - public static PacketHandler[] Handlers { get { return m_Handlers; } } + public static PacketHandler[] Handlers { get { return m_Handlers; } } - static PacketHandlers() + public static int LoginSeedLength => Handlers[0xEF]?.Length ?? -1; + + static PacketHandlers() { m_Handlers = new PacketHandler[0x100]; m_6017Handlers = new PacketHandler[0x100]; diff --git a/Server/Network/SendQueue.cs b/Server/Network/SendQueue.cs index 2cba9c1..496cb97 100755 --- a/Server/Network/SendQueue.cs +++ b/Server/Network/SendQueue.cs @@ -1,6 +1,7 @@ #region References using System; -using System.Collections.Generic; +using System.Collections.Concurrent; +using System.Threading; #endregion namespace Server.Network @@ -9,29 +10,20 @@ namespace Server.Network { public class Gram { - private static readonly Stack _pool = new Stack(); + private static readonly ConcurrentQueue _pool = new ConcurrentQueue(); - public static Gram Acquire() - { - lock (_pool) - { - Gram gram; + public static Gram Acquire() + { + if (!_pool.TryDequeue(out Gram gram)) + { + gram = new Gram(); + } - if (_pool.Count > 0) - { - gram = _pool.Pop(); - } - else - { - gram = new Gram(); - } + gram._buffer = AcquireBuffer(); + gram._length = 0; - gram._buffer = AcquireBuffer(); - gram._length = 0; - - return gram; - } - } + return gram; + } private byte[] _buffer; private int _length; @@ -58,14 +50,12 @@ namespace Server.Network return write; } - public void Release() - { - lock (_pool) - { - _pool.Push(this); - ReleaseBuffer(_buffer); - } - } + public void Release() + { + _pool.Enqueue(this); + + ReleaseBuffer(_buffer); + } } private static int m_CoalesceBufferSize = 512; @@ -74,77 +64,60 @@ namespace Server.Network public static int CoalesceBufferSize { get { return m_CoalesceBufferSize; } - set - { - if (m_CoalesceBufferSize == value) - { - return; - } + set + { + if (m_CoalesceBufferSize == value) + { + return; + } - BufferPool old = m_UnusedBuffers; + m_UnusedBuffers?.Free(); - lock (old) - { - if (m_UnusedBuffers != null) - { - m_UnusedBuffers.Free(); - } - - m_CoalesceBufferSize = value; - m_UnusedBuffers = new BufferPool("Coalesced", 2048, m_CoalesceBufferSize); - } - } + m_CoalesceBufferSize = value; + m_UnusedBuffers = new BufferPool("Coalesced", 2048, m_CoalesceBufferSize); + } } public static byte[] AcquireBuffer() { - lock (m_UnusedBuffers) - return m_UnusedBuffers.AcquireBuffer(); + return m_UnusedBuffers.AcquireBuffer(); } - public static void ReleaseBuffer(byte[] buffer) - { - lock (m_UnusedBuffers) - if (buffer != null && buffer.Length == m_CoalesceBufferSize) - { - m_UnusedBuffers.ReleaseBuffer(buffer); - } - } + public static void ReleaseBuffer(byte[] buffer) + { + if (buffer != null && buffer.Length == m_CoalesceBufferSize) + { + m_UnusedBuffers.ReleaseBuffer(buffer); + } + } - private readonly Queue _pending; + private readonly ConcurrentQueue _pending = new ConcurrentQueue(); - private Gram _buffered; + private volatile Gram _buffered; public bool IsFlushReady { get { return (_pending.Count == 0 && _buffered != null); } } public bool IsEmpty { get { return (_pending.Count == 0 && _buffered == null); } } - public SendQueue() - { - _pending = new Queue(); - } - public Gram CheckFlushReady() { - Gram gram = _buffered; - _pending.Enqueue(_buffered); - _buffered = null; + Gram gram = Interlocked.Exchange(ref _buffered, null); + + _pending.Enqueue(gram); + return gram; } public Gram Dequeue() { - Gram gram = null; + if (_pending.TryDequeue(out Gram gram)) + { + gram?.Release(); + gram = null; - if (_pending.Count > 0) - { - _pending.Dequeue().Release(); - - if (_pending.Count > 0) - { - gram = _pending.Peek(); - } - } + if (_pending.TryPeek(out Gram peek)) + gram = peek; + } return gram; } @@ -177,41 +150,41 @@ namespace Server.Network throw new ArgumentException("Offset and length do not point to a valid segment within the buffer."); } - int existingBytes = (_pending.Count * m_CoalesceBufferSize) + (_buffered == null ? 0 : _buffered.Length); + int existingBytes = (_pending.Count * m_CoalesceBufferSize) + (_buffered?.Length ?? 0); if ((existingBytes + length) > PendingCap) { throw new CapacityExceededException(); } - Gram gram = null; + Gram gram = null; - while (length > 0) - { - if (_buffered == null) - { - // nothing yet buffered - _buffered = Gram.Acquire(); - } + while (length > 0) + { + if (_buffered == null) + { + // nothing yet buffered + _buffered = Gram.Acquire(); + } - int bytesWritten = _buffered.Write(buffer, offset, length); + int bytesWritten = _buffered.Write(buffer, offset, length); - offset += bytesWritten; - length -= bytesWritten; + offset += bytesWritten; + length -= bytesWritten; - if (_buffered.IsFull) - { - if (_pending.Count == 0) - { - gram = _buffered; - } + if (_buffered.IsFull) + { + if (_pending.Count == 0) + { + gram = _buffered; + } - _pending.Enqueue(_buffered); - _buffered = null; - } - } + _pending.Enqueue(_buffered); + _buffered = null; + } + } - return gram; + return gram; } public void Clear() @@ -222,9 +195,9 @@ namespace Server.Network _buffered = null; } - while (_pending.Count > 0) + while (_pending.TryDequeue(out Gram gram)) { - _pending.Dequeue().Release(); + gram?.Release(); } } } @@ -236,4 +209,4 @@ namespace Server.Network : base("Too much data pending.") { } } -} \ No newline at end of file +} diff --git a/Server/ScriptCompiler.cs b/Server/ScriptCompiler.cs index 48aa99b..1c9a833 100755 --- a/Server/ScriptCompiler.cs +++ b/Server/ScriptCompiler.cs @@ -1,933 +1,657 @@ #region References using System; -using System.CodeDom.Compiler; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; -using System.Security.Cryptography; -using System.Text; - -using Microsoft.CSharp; #endregion namespace Server { - public static class ScriptCompiler - { - public static Assembly[] Assemblies { get; set; } + public static class ScriptCompiler + { + public static bool Dynamic { get => Config.Get("Compiler.Dynamic", true); set => Config.Set("Compiler.Dynamic", value); } - private static readonly List m_AdditionalReferences = new List(); + public static Assembly[] Assemblies { get; set; } - public static string[] GetReferenceAssemblies() - { - var list = new List(); - - var path = Path.Combine(Core.BaseDirectory, "Data/Assemblies.cfg"); - - if (File.Exists(path)) - { - using (var ip = new StreamReader(path)) - { - string line; - - while ((line = ip.ReadLine()) != null) - { - if (line.Length > 0 && !line.StartsWith("#")) - { - list.Add(line); - } - } - } - } - - list.Add(Core.ExePath); - - list.AddRange(m_AdditionalReferences); - - return list.ToArray(); - } - - public static string GetCompilerOptions(bool debug) - { - StringBuilder sb = null; - - AppendCompilerOption(ref sb, "/d:ServUO"); - - AppendCompilerOption(ref sb, "/unsafe"); - - if (!debug) - { - AppendCompilerOption(ref sb, "/optimize"); - } - else - { - AppendCompilerOption(ref sb, "/debug"); - AppendCompilerOption(ref sb, "/d:DEBUG"); - AppendCompilerOption(ref sb, "/d:TRACE"); - } - - AppendCompilerOption(ref sb, "/langversion:7.2"); - -#if MONO - AppendCompilerOption( ref sb, "/d:MONO" ); -#endif - - if (Core.Is64Bit) - { - AppendCompilerOption(ref sb, "/d:x64"); - } - -#if NEWTIMERS - AppendCompilerOption(ref sb, "/d:NEWTIMERS"); -#endif - -#if NEWPARENT - AppendCompilerOption(ref sb, "/d:NEWPARENT"); -#endif - - return (sb == null ? null : sb.ToString()); - } - - private static void AppendCompilerOption(ref StringBuilder sb, string define) - { - if (sb == null) - { - sb = new StringBuilder(); - } - else - { - sb.Append(' '); - } - - sb.Append(define); - } - - private static byte[] GetHashCode(string compiledFile, string[] scriptFiles, bool debug) - { - using (var ms = new MemoryStream()) - { - using (var bin = new BinaryWriter(ms)) - { - var fileInfo = new FileInfo(compiledFile); - - bin.Write(fileInfo.LastWriteTimeUtc.Ticks); - - foreach (var scriptFile in scriptFiles) - { - fileInfo = new FileInfo(scriptFile); - - bin.Write(fileInfo.LastWriteTimeUtc.Ticks); - } - - bin.Write(debug); - bin.Write(Core.Version.ToString()); - - ms.Position = 0; - - using (var sha1 = SHA1.Create()) - { - return sha1.ComputeHash(ms); - } - } - } - } - - public static bool CompileCSScripts(out Assembly assembly) - { - return CompileCSScripts(false, true, out assembly); - } - - public static bool CompileCSScripts(bool debug, out Assembly assembly) - { - return CompileCSScripts(debug, true, out assembly); - } - - public static bool CompileCSScripts(bool debug, bool cache, out Assembly assembly) - { - Utility.PushColor(ConsoleColor.Yellow); - Console.Write("Scripts: Compiling C# scripts..."); - Utility.PopColor(); - var files = GetScripts("*.cs"); - - if (files.Length == 0) - { - Utility.PushColor(ConsoleColor.Red); - Console.WriteLine("no files found."); - Utility.PopColor(); - assembly = null; - return true; - } - - if (File.Exists("Scripts/Output/Scripts.CS.dll")) - { - if (cache && File.Exists("Scripts/Output/Scripts.CS.hash")) - { - try - { - var hashCode = GetHashCode("Scripts/Output/Scripts.CS.dll", files, debug); - - using (var fs = new FileStream("Scripts/Output/Scripts.CS.hash", FileMode.Open, FileAccess.Read, FileShare.Read)) - { - using (var bin = new BinaryReader(fs)) - { - var bytes = bin.ReadBytes(hashCode.Length); - - if (bytes.Length == hashCode.Length) - { - var valid = true; - - for (var i = 0; i < bytes.Length; ++i) - { - if (bytes[i] != hashCode[i]) - { - valid = false; - break; - } - } - - if (valid) - { - assembly = Assembly.LoadFrom("Scripts/Output/Scripts.CS.dll"); - - if (!m_AdditionalReferences.Contains(assembly.Location)) - { - m_AdditionalReferences.Add(assembly.Location); - } - - Utility.PushColor(ConsoleColor.Green); - Console.WriteLine("done (cached)"); - Utility.PopColor(); - - return true; - } - } - } - } - } - catch - { } - } - } - - DeleteFiles("Scripts.CS*.dll"); - -#if !MONO - using (CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider()) -#else - using (CSharpCodeProvider provider = new CSharpCodeProvider()) -#endif + public static bool Compile(bool debug, bool cache) + { + try { - var path = GetUnusedPath("Scripts.CS"); - - var parms = new CompilerParameters(GetReferenceAssemblies(), path, debug); - - var options = GetCompilerOptions(debug); - - if (options != null) - { - parms.CompilerOptions = options; - } - - if (Core.HaltOnWarning) - { - parms.WarningLevel = 4; - } - - if (Core.Unix) + var assemblies = new HashSet { - parms.CompilerOptions = String.Format( "{0} /nowarn:169,219,414 /recurse:Scripts/*.cs", parms.CompilerOptions ); - files = new string[0]; + typeof(ScriptCompiler).Assembly + }; + + if (Dynamic) + { + Console.WriteLine("Core: Compiling scripts..."); + + var path = Path.Combine(Core.BaseDirectory, "Scripts"); + + foreach (var proj in Directory.EnumerateFiles(path, "Scripts.csproj")) + { + try + { + var info = new ProcessStartInfo + { + FileName = "dotnet", + Arguments = $"build \"{proj}\" -c {(debug ? "Debug" : "Release")}", + ErrorDialog = false, + UseShellExecute = false, + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden, + RedirectStandardOutput = true, + }; + + var proc = Process.Start(info); + + Console.WriteLine(proc.StandardOutput.ReadToEnd()); + + proc.WaitForExit(); + } + catch (Exception e) + { + Console.WriteLine(e); + } + + break; + } } - - var results = provider.CompileAssemblyFromFile(parms, files); - - m_AdditionalReferences.Add(path); - - Display(results); - - if (results.Errors.Count > 0 && !Core.Unix) - { - assembly = null; - return false; - } - - if (results.Errors.Count > 0 && Core.Unix) - { - foreach( CompilerError err in results.Errors ) { - if ( !err.IsWarning ) { - assembly = null; - return false; - } - } - } - - if (cache && Path.GetFileName(path) == "Scripts.CS.dll") - { - try - { - var hashCode = GetHashCode(path, files, debug); - - using ( - var fs = new FileStream("Scripts/Output/Scripts.CS.hash", FileMode.Create, FileAccess.Write, FileShare.None)) - { - using (var bin = new BinaryWriter(fs)) - { - bin.Write(hashCode, 0, hashCode.Length); - } - } - } - catch - { } - } - - assembly = results.CompiledAssembly; - return true; - } - } - - public static void Display(CompilerResults results) - { - if (results.Errors.Count > 0) - { - var errors = new Dictionary>(results.Errors.Count, StringComparer.OrdinalIgnoreCase); - var warnings = new Dictionary>(results.Errors.Count, StringComparer.OrdinalIgnoreCase); - - foreach (CompilerError e in results.Errors) - { - var file = e.FileName; - - // Ridiculous. FileName is null if the warning/error is internally generated in csc. - if (string.IsNullOrEmpty(file)) - { - Console.WriteLine("ScriptCompiler: {0}: {1}", e.ErrorNumber, e.ErrorText); - continue; - } - - var table = (e.IsWarning ? warnings : errors); - - List list = null; - table.TryGetValue(file, out list); - - if (list == null) - { - table[file] = list = new List(); - } - - list.Add(e); - } - - if (errors.Count > 0) - { - Utility.PushColor(ConsoleColor.Red); - Console.WriteLine("Failed with: {0} errors, {1} warnings", errors.Count, warnings.Count); - Utility.PopColor(); - } - else - { - Utility.PushColor(ConsoleColor.Green); - Console.WriteLine("Finished with: {0} errors, {1} warnings", errors.Count, warnings.Count); - Utility.PopColor(); - } - - var scriptRoot = Path.GetFullPath(Path.Combine(Core.BaseDirectory, "Scripts" + Path.DirectorySeparatorChar)); - var scriptRootUri = new Uri(scriptRoot); - - Utility.PushColor(ConsoleColor.Yellow); - - if (warnings.Count > 0) - { - Console.WriteLine("Warnings:"); - } - - foreach (var kvp in warnings) - { - var fileName = kvp.Key; - var list = kvp.Value; - - var fullPath = Path.GetFullPath(fileName); - var usedPath = Uri.UnescapeDataString(scriptRootUri.MakeRelativeUri(new Uri(fullPath)).OriginalString); - - Console.WriteLine(" + {0}:", usedPath); - - Utility.PushColor(ConsoleColor.DarkYellow); - - foreach (var e in list) - { - Console.WriteLine(" {0}: Line {1}: {2}", e.ErrorNumber, e.Line, e.ErrorText); - } - - Utility.PopColor(); - } - - Utility.PopColor(); - - Utility.PushColor(ConsoleColor.Red); - - if (errors.Count > 0) - { - Console.WriteLine("Errors:"); - } - - foreach (var kvp in errors) - { - var fileName = kvp.Key; - var list = kvp.Value; - - var fullPath = Path.GetFullPath(fileName); - var usedPath = Uri.UnescapeDataString(scriptRootUri.MakeRelativeUri(new Uri(fullPath)).OriginalString); - - Console.WriteLine(" + {0}:", usedPath); - - Utility.PushColor(ConsoleColor.Red); - - foreach (var e in list) - { - Console.WriteLine(" {0}: Line {1}: {2}", e.ErrorNumber, e.Line, e.ErrorText); - } - - Utility.PopColor(); - } - - Utility.PopColor(); - } - else - { - Utility.PushColor(ConsoleColor.Green); - Console.WriteLine("Finished with: 0 errors, 0 warnings"); - Utility.PopColor(); - } - } - - public static string GetUnusedPath(string name) - { - var path = Path.Combine(Core.BaseDirectory, String.Format("Scripts/Output/{0}.dll", name)); - - for (var i = 2; File.Exists(path) && i <= 1000; ++i) - { - path = Path.Combine(Core.BaseDirectory, String.Format("Scripts/Output/{0}.{1}.dll", name, i)); - } - - return path; - } - - public static void DeleteFiles(string mask) - { - try - { - var files = Directory.GetFiles(Path.Combine(Core.BaseDirectory, "Scripts/Output"), mask); - - foreach (var file in files) - { - try - { - File.Delete(file); - } - catch - { } - } - } - catch - { } - } - - private delegate CompilerResults Compiler(bool debug); - - public static bool Compile() - { - return Compile(false); - } - - public static bool Compile(bool debug) - { - return Compile(debug, true); - } - - public static bool Compile(bool debug, bool cache) - { - EnsureDirectory("Scripts/"); - EnsureDirectory("Scripts/Output/"); - - if (m_AdditionalReferences.Count > 0) - { - m_AdditionalReferences.Clear(); - } - - var assemblies = new List(); - - Assembly assembly; - - if (CompileCSScripts(debug, cache, out assembly)) - { - if (assembly != null) - { - assemblies.Add(assembly); - } - } - else - { - return false; - } - - if (assemblies.Count == 0) - { - return false; - } - - Assemblies = assemblies.ToArray(); - - Utility.PushColor(ConsoleColor.Yellow); - Console.WriteLine("Scripts: Verifying..."); - Utility.PopColor(); - - var watch = Stopwatch.StartNew(); - - Core.VerifySerialization(); - - watch.Stop(); - - Utility.PushColor(ConsoleColor.Green); - Console.WriteLine( - "Finished ({0} items, {1} mobiles, {2} customs) ({3:F2} seconds)", - Core.ScriptItems, - Core.ScriptMobiles, - Core.ScriptCustoms, - watch.Elapsed.TotalSeconds); - Utility.PopColor(); - - return true; - } - - public static void Invoke(string method) - { - var invoke = new List(); - - foreach (var a in Assemblies) - { - var types = a.GetTypes(); - - foreach (var t in types) - { - var m = t.GetMethod(method, BindingFlags.Static | BindingFlags.Public); - - if (m != null) - { - invoke.Add(m); - } - } - } - - invoke.Sort(new CallPriorityComparer()); - - foreach (var m in invoke) - { - m.Invoke(null, null); - } - } - - private static readonly Dictionary m_TypeCaches = new Dictionary(); - private static TypeCache m_NullCache; - - public static TypeCache GetTypeCache(Assembly asm) - { - if (asm == null) - { - return m_NullCache ?? (m_NullCache = new TypeCache(null)); - } - - TypeCache c; - - m_TypeCaches.TryGetValue(asm, out c); - - if (c == null) - { - m_TypeCaches[asm] = c = new TypeCache(asm); - } - - return c; - } - - public static Type FindTypeByFullName(string fullName) - { - return FindTypeByFullName(fullName, true); - } - - public static Type FindTypeByFullName(string fullName, bool ignoreCase) - { - if (string.IsNullOrWhiteSpace(fullName)) - { - return null; - } - - Type type = null; - - for (var i = 0; type == null && i < Assemblies.Length; ++i) - { - type = GetTypeCache(Assemblies[i]).GetTypeByFullName(fullName, ignoreCase); - } - - return type ?? GetTypeCache(Core.Assembly).GetTypeByFullName(fullName, ignoreCase); - } - - public static IEnumerable FindTypesByFullName(string name) - { - return FindTypesByFullName(name, true); - } - - public static IEnumerable FindTypesByFullName(string name, bool ignoreCase) - { - if (string.IsNullOrWhiteSpace(name)) - { - yield break; - } - - for (var i = 0; i < Assemblies.Length; ++i) - { - foreach (var t in GetTypeCache(Assemblies[i]).GetTypesByFullName(name, ignoreCase)) - { - yield return t; - } - } - - foreach (var t in GetTypeCache(Core.Assembly).GetTypesByFullName(name, ignoreCase)) - { - yield return t; - } - } + + _ = assemblies.Add(Assembly.LoadFrom("Scripts.dll")); + + Assemblies = assemblies.ToArray(); + + Console.WriteLine("Core: Verifying entity type serialization..."); + + var watch = Stopwatch.StartNew(); + + Core.VerifySerialization(); + + watch.Stop(); + + Console.WriteLine($"Core: Verified {Core.ScriptItems} item and {Core.ScriptMobiles} mobile types"); + + return true; + } + catch (Exception ex) + { + Console.WriteLine(ex); + + return false; + } + } + + public static void Invoke(string method) + { + var invoke = new List(); + + foreach (var a in Assemblies) + { + var types = a.GetTypes(); + + foreach (var t in types) + { + var m = t.GetMethod(method, BindingFlags.Static | BindingFlags.Public); + + if (m != null) + { + invoke.Add(m); + } + } + } + + invoke.Sort(new CallPriorityComparer()); + + foreach (var m in invoke) + { + _ = m.Invoke(null, null); + } + } + + private static readonly Dictionary m_TypeCaches = new Dictionary(); + private static TypeCache m_NullCache; + + public static TypeCache GetTypeCache(Assembly asm) + { + if (asm == null) + { + return m_NullCache ?? (m_NullCache = new TypeCache(null)); + } + + _ = m_TypeCaches.TryGetValue(asm, out var c); + + if (c == null) + { + m_TypeCaches[asm] = c = new TypeCache(asm); + } + + return c; + } + + public static int FindHashByName(string name) + { + if (string.IsNullOrWhiteSpace(name)) + { + return 0; + } + + var hash = 0; + + for (var i = 0; hash == 0 && i < Assemblies.Length; ++i) + { + hash = GetTypeCache(Assemblies[i]).GetTypeHashByName(name); + } + + return hash != 0 ? hash : GetTypeCache(Core.Assembly).GetTypeHashByName(name); + } + + public static int FindHashByFullName(string fullName) + { + if (string.IsNullOrWhiteSpace(fullName)) + { + return 0; + } + + var hash = 0; + + for (var i = 0; hash == 0 && i < Assemblies.Length; ++i) + { + hash = GetTypeCache(Assemblies[i]).GetTypeHashByFullName(fullName); + } + + return hash != 0 ? hash : GetTypeCache(Core.Assembly).GetTypeHashByFullName(fullName); + } + + public static Type FindTypeByFullName(string fullName) + { + return FindTypeByFullName(fullName, true); + } + + public static Type FindTypeByFullName(string fullName, bool ignoreCase) + { + if (string.IsNullOrWhiteSpace(fullName)) + { + return null; + } + + Type type = null; + + for (var i = 0; type == null && i < Assemblies.Length; ++i) + { + type = GetTypeCache(Assemblies[i]).GetTypeByFullName(fullName, ignoreCase); + } + + return type ?? GetTypeCache(Core.Assembly).GetTypeByFullName(fullName, ignoreCase); + } + + public static IEnumerable FindTypesByFullName(string name) + { + return FindTypesByFullName(name, true); + } + + public static IEnumerable FindTypesByFullName(string name, bool ignoreCase) + { + if (string.IsNullOrWhiteSpace(name)) + { + yield break; + } + + for (var i = 0; i < Assemblies.Length; ++i) + { + foreach (var t in GetTypeCache(Assemblies[i]).GetTypesByFullName(name, ignoreCase)) + { + yield return t; + } + } + + foreach (var t in GetTypeCache(Core.Assembly).GetTypesByFullName(name, ignoreCase)) + { + yield return t; + } + } public static Type FindTypeByName(string name) - { - return FindTypeByName(name, true); - } - - public static Type FindTypeByName(string name, bool ignoreCase) - { - if (string.IsNullOrWhiteSpace(name)) - { - return null; - } - - Type type = null; - - for (var i = 0; type == null && i < Assemblies.Length; ++i) - { - type = GetTypeCache(Assemblies[i]).GetTypeByName(name, ignoreCase); - } - - return type ?? GetTypeCache(Core.Assembly).GetTypeByName(name, ignoreCase); - } - - public static IEnumerable FindTypesByName(string name) - { - return FindTypesByName(name, true); - } - - public static IEnumerable FindTypesByName(string name, bool ignoreCase) - { - if (string.IsNullOrWhiteSpace(name)) - { - yield break; - } - - for (var i = 0; i < Assemblies.Length; ++i) - { - foreach (var t in GetTypeCache(Assemblies[i]).GetTypesByName(name, ignoreCase)) - { - yield return t; - } - } - - foreach (var t in GetTypeCache(Core.Assembly).GetTypesByName(name, ignoreCase)) - { - yield return t; - } + { + return FindTypeByName(name, true); } - public static void EnsureDirectory(string dir) - { - var path = Path.Combine(Core.BaseDirectory, dir); + public static Type FindTypeByName(string name, bool ignoreCase) + { + if (string.IsNullOrWhiteSpace(name)) + { + return null; + } - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - } + Type type = null; - public static string[] GetScripts(string filter) - { - var list = new List(); + for (var i = 0; type == null && i < Assemblies.Length; ++i) + { + type = GetTypeCache(Assemblies[i]).GetTypeByName(name, ignoreCase); + } - GetScripts(list, Path.Combine(Core.BaseDirectory, "Scripts"), filter); + return type ?? GetTypeCache(Core.Assembly).GetTypeByName(name, ignoreCase); + } - return list.ToArray(); - } + public static IEnumerable FindTypesByName(string name) + { + return FindTypesByName(name, true); + } - public static void GetScripts(List list, string path, string filter) - { - foreach (var dir in Directory.GetDirectories(path)) - { - GetScripts(list, dir, filter); - } + public static IEnumerable FindTypesByName(string name, bool ignoreCase) + { + if (string.IsNullOrWhiteSpace(name)) + { + yield break; + } - list.AddRange(Directory.GetFiles(path, filter)); - } - } + for (var i = 0; i < Assemblies.Length; ++i) + { + foreach (var t in GetTypeCache(Assemblies[i]).GetTypesByName(name, ignoreCase)) + { + yield return t; + } + } - public class TypeCache - { - private readonly Type[] m_Types; - private readonly TypeTable m_Names; - private readonly TypeTable m_FullNames; + foreach (var t in GetTypeCache(Core.Assembly).GetTypesByName(name, ignoreCase)) + { + yield return t; + } + } - public Type[] Types { get { return m_Types; } } - public TypeTable Names { get { return m_Names; } } - public TypeTable FullNames { get { return m_FullNames; } } + public static Type FindTypeByNameHash(int hash) + { + Type type = null; - public Type GetTypeByName(string name, bool ignoreCase) - { - return GetTypesByName(name, ignoreCase).FirstOrDefault(t => t != null); - } + for (var i = 0; type == null && i < Assemblies.Length; ++i) + { + type = GetTypeCache(Assemblies[i]).GetTypeByNameHash(hash); + } - public IEnumerable GetTypesByName(string name, bool ignoreCase) - { - return m_Names.Get(name, ignoreCase); - } + return type ?? GetTypeCache(Core.Assembly).GetTypeByNameHash(hash); + } - public Type GetTypeByFullName(string fullName, bool ignoreCase) - { - return GetTypesByFullName(fullName, ignoreCase).FirstOrDefault(t => t != null); - } + public static IEnumerable FindTypesByNameHash(int hash) + { + for (var i = 0; i < Assemblies.Length; ++i) + { + foreach (var t in GetTypeCache(Assemblies[i]).GetTypesByNameHash(hash)) + { + yield return t; + } + } - public IEnumerable GetTypesByFullName(string fullName, bool ignoreCase) - { - return m_FullNames.Get(fullName, ignoreCase); - } + foreach (var t in GetTypeCache(Core.Assembly).GetTypesByNameHash(hash)) + { + yield return t; + } + } - public TypeCache(Assembly asm) - { - if (asm == null) - { - m_Types = Type.EmptyTypes; - } - else - { - m_Types = asm.GetTypes(); - } + public static Type FindTypeByFullNameHash(int hash) + { + Type type = null; - m_Names = new TypeTable(m_Types.Length); - m_FullNames = new TypeTable(m_Types.Length); + for (var i = 0; type == null && i < Assemblies.Length; ++i) + { + type = GetTypeCache(Assemblies[i]).GetTypeByFullNameHash(hash); + } - foreach (var g in m_Types.ToLookup(t => t.Name)) - { - m_Names.Add(g.Key, g); - - foreach (var type in g) - { - m_FullNames.Add(type.FullName, type); + return type ?? GetTypeCache(Core.Assembly).GetTypeByFullNameHash(hash); + } - var attr = type.GetCustomAttribute(false); + public static IEnumerable FindTypesByFullNameHash(int hash) + { + for (var i = 0; i < Assemblies.Length; ++i) + { + foreach (var t in GetTypeCache(Assemblies[i]).GetTypesByFullNameHash(hash)) + { + yield return t; + } + } - if (attr != null) - { - foreach (var a in attr.Aliases) - { - m_FullNames.Add(a, type); - } - } - } - } + foreach (var t in GetTypeCache(Core.Assembly).GetTypesByFullNameHash(hash)) + { + yield return t; + } + } + } - m_Names.Prune(); - m_FullNames.Prune(); + public class TypeCache + { + private readonly TypeTable m_FullNames; - m_Names.Sort(); - m_FullNames.Sort(); - } - } + public Type[] Types { get; } + public TypeTable Names { get; } + public TypeTable FullNames => m_FullNames; - public class TypeTable - { - private readonly Dictionary> m_Sensitive; - private readonly Dictionary> m_Insensitive; + public Type GetTypeByNameHash(int hash) + { + return GetTypesByNameHash(hash).FirstOrDefault(t => t != null); + } - public void Prune() - { - Prune(m_Sensitive); - Prune(m_Insensitive); - } + public IEnumerable GetTypesByNameHash(int hash) + { + return Names.Get(hash); + } - private static void Prune(Dictionary> types) - { - var buffer = new List(); + public Type GetTypeByFullNameHash(int hash) + { + return GetTypesByFullNameHash(hash).FirstOrDefault(t => t != null); + } + + public IEnumerable GetTypesByFullNameHash(int hash) + { + return m_FullNames.Get(hash); + } + + public Type GetTypeByName(string name, bool ignoreCase) + { + return GetTypesByName(name, ignoreCase).FirstOrDefault(t => t != null); + } + + public IEnumerable GetTypesByName(string name, bool ignoreCase) + { + return Names.Get(name, ignoreCase); + } + + public Type GetTypeByFullName(string fullName, bool ignoreCase) + { + return GetTypesByFullName(fullName, ignoreCase).FirstOrDefault(t => t != null); + } + + public IEnumerable GetTypesByFullName(string fullName, bool ignoreCase) + { + return m_FullNames.Get(fullName, ignoreCase); + } + + public int GetTypeHashByName(string name) + { + return Names.GetHash(name); + } + + public int GetTypeHashByFullName(string fullName) + { + return m_FullNames.GetHash(fullName); + } + + public TypeCache(Assembly asm) + { + if (asm == null) + { + Types = Type.EmptyTypes; + } + else + { + Types = asm.GetTypes(); + } + + Names = new TypeTable(Types.Length); + m_FullNames = new TypeTable(Types.Length); + + foreach (var g in Types.ToLookup(t => t.Name)) + { + Names.Add(g.Key, g); + + foreach (var type in g) + { + m_FullNames.Add(type.FullName, type); + + var attr = type.GetCustomAttribute(false); + + if (attr != null) + { + foreach (var a in attr.Aliases) + { + m_FullNames.Add(a, type); + } + } + } + } + + Names.Sort(); + m_FullNames.Sort(); + } + } + + public class TypeTable + { + private readonly Dictionary m_Hashes; + private readonly Dictionary> m_Hashed; + private readonly Dictionary> m_Sensitive; + private readonly Dictionary> m_Insensitive; + + public void Sort() + { + Sort(m_Hashed); + Sort(m_Sensitive); + Sort(m_Insensitive); + } + + private static void Sort(Dictionary> types) + { + var sorter = new List(); foreach (var list in types.Values) - { - if (list.Count == 1) - { - continue; - } + { + sorter.AddRange(list); + sorter.Sort(InternalSort); - buffer.AddRange(list.Distinct()); + list.Clear(); + list.UnionWith(sorter); - list.Clear(); - list.AddRange(buffer); + sorter.Clear(); + } - buffer.Clear(); - } - - buffer.TrimExcess(); - } - - public void Sort() - { - Sort(m_Sensitive); - Sort(m_Insensitive); + sorter.TrimExcess(); } - private static void Sort(Dictionary> types) - { - foreach (var list in types.Values) - { - list.Sort(InternalSort); - } - } + private static int InternalSort(Type l, Type r) + { + if (l == r) + { + return 0; + } - private static int InternalSort(Type l, Type r) - { - if (l == r) - { - return 0; - } + if (l != null && r == null) + { + return -1; + } - if (l != null && r == null) - { - return -1; - } + if (l == null && r != null) + { + return 1; + } - if (l == null && r != null) - { - return 1; - } + var a = IsEntity(l); + var b = IsEntity(r); - var a = IsEntity(l); - var b = IsEntity(r); + if (a && b) + { + a = IsConstructable(l, out var x); + b = IsConstructable(r, out var y); - if (a && b) - { - a = IsConstructable(l, out var x); - b = IsConstructable(r, out var y); + if (a && !b) + { + return -1; + } - if (a && !b) - { - return -1; - } + if (!a && b) + { + return 1; + } - if (!a && b) - { - return 1; - } + return x > y ? -1 : x < y ? 1 : 0; + } - return x > y ? -1 : x < y ? 1 : 0; - } + return a ? -1 : b ? 1 : 0; + } - return a ? -1 : b ? 1 : 0; - } + private static bool IsEntity(Type type) + { + return type.GetInterface("IEntity") != null; + } - private static bool IsEntity(Type type) - { - return type.GetInterface("IEntity") != null; - } + private static bool IsConstructable(Type type, out AccessLevel access) + { + foreach (var ctor in type.GetConstructors().OrderBy(o => o.GetParameters().Length)) + { + var attr = ctor.GetCustomAttribute(false); - private static bool IsConstructable(Type type, out AccessLevel access) - { - foreach (var ctor in type.GetConstructors().OrderBy(o => o.GetParameters().Length)) - { - var attr = ctor.GetCustomAttribute(false); + if (attr != null) + { + access = attr.AccessLevel; + return true; + } + } - if (attr != null) - { - access = attr.AccessLevel; - return true; - } - } + access = 0; + return false; + } - access = 0; - return false; - } + public void Add(string key, IEnumerable types) + { + if (!string.IsNullOrWhiteSpace(key) && types != null) + { + Add(key, types.ToArray()); + } + } - public void Add(string key, IEnumerable types) - { - if (!string.IsNullOrWhiteSpace(key) && types != null) - { - Add(key, types.ToArray()); - } - } - - public void Add(string key, params Type[] types) - { - if (string.IsNullOrWhiteSpace(key) || types == null || types.Length == 0) - { + public void Add(string key, params Type[] types) + { + if (string.IsNullOrWhiteSpace(key) || types == null || types.Length == 0) + { return; - } - - if (!m_Sensitive.TryGetValue(key, out var sensitive) || sensitive == null) - { - m_Sensitive[key] = new List(types); - } - else if (types.Length == 1) - { - sensitive.Add(types[0]); - } - else - { - sensitive.AddRange(types); - } + } + + if (!m_Sensitive.TryGetValue(key, out var sensitive) || sensitive == null) + { + m_Sensitive[key] = new HashSet(types); + } + else if (types.Length == 1) + { + _ = sensitive.Add(types[0]); + } + else + { + sensitive.UnionWith(types); + } if (!m_Insensitive.TryGetValue(key, out var insensitive) || insensitive == null) - { - m_Insensitive[key] = new List(types); - } - else if (types.Length == 1) - { - insensitive.Add(types[0]); - } - else - { - insensitive.AddRange(types); - } - } + { + m_Insensitive[key] = new HashSet(types); + } + else if (types.Length == 1) + { + _ = insensitive.Add(types[0]); + } + else + { + insensitive.UnionWith(types); + } - public IEnumerable Get(string key, bool ignoreCase) - { - if (string.IsNullOrWhiteSpace(key)) - { - return Type.EmptyTypes; - } + var hash = GenerateHash(key); - List t; + if (!m_Hashed.TryGetValue(hash, out var hashed) || hashed == null) + { + m_Hashed[hash] = new HashSet(types); + } + else if (types.Length == 1) + { + _ = hashed.Add(types[0]); + } + else + { + hashed.UnionWith(types); + } + } - if (ignoreCase) - { - m_Insensitive.TryGetValue(key, out t); - } - else - { - m_Sensitive.TryGetValue(key, out t); - } + public IEnumerable Get(string key, bool ignoreCase) + { + if (string.IsNullOrWhiteSpace(key)) + { + return Type.EmptyTypes; + } - if (t == null) - { - return Type.EmptyTypes; - } + HashSet t; - return t.AsEnumerable(); - } + if (ignoreCase) + { + _ = m_Insensitive.TryGetValue(key, out t); + } + else + { + _ = m_Sensitive.TryGetValue(key, out t); + } - public TypeTable(int capacity) - { - m_Sensitive = new Dictionary>(capacity); - m_Insensitive = new Dictionary>(capacity, StringComparer.OrdinalIgnoreCase); - } - } + if (t == null) + { + return Type.EmptyTypes; + } + + return t.AsEnumerable(); + } + + public IEnumerable Get(int hash) + { + _ = m_Hashed.TryGetValue(hash, out var t); + + if (t == null) + { + return Type.EmptyTypes; + } + + return t.AsEnumerable(); + } + + public int GetHash(string key) + { + if (string.IsNullOrWhiteSpace(key)) + { + return 0; + } + + _ = m_Hashes.TryGetValue(key, out var hash); + + return hash; + } + + private int GenerateHash(string key) + { + if (string.IsNullOrWhiteSpace(key)) + { + return 0; + } + + var hash = GetHash(key); + + if (hash != 0) + { + return hash; + } + + hash = key.Length; + + unchecked + { + for (var i = 0; i < key.Length; i++) + { + hash = (hash * 397) ^ Convert.ToInt32(key[i]); + } + } + + m_Hashes[key] = hash; + + return hash; + } + + public TypeTable(int capacity) + { + m_Hashes = new Dictionary(); + m_Hashed = new Dictionary>(capacity); + m_Sensitive = new Dictionary>(capacity); + m_Insensitive = new Dictionary>(capacity, StringComparer.OrdinalIgnoreCase); + } + } } diff --git a/Server/Server.csproj b/Server/Server.csproj index f6485d1..c1c7991 100755 --- a/Server/Server.csproj +++ b/Server/Server.csproj @@ -1,221 +1,28 @@ - - - - Debug - AnyCPU - {AE4A9EAA-E0EB-4DC9-9604-BE4289F9F6C3} - Exe - Properties - Server - ServUO - servuo.ico - Server.Core - v4.8 - win7-x64;win7-x86;ubuntu.16.10-x64 - - - true - full - false - ..\ - TRACE;DEBUG;NEWTIMERS;ServUO - prompt - 4 - true - false - false - false - - - pdbonly - true - ..\ - prompt - 4 - true - false - false - TRACE;NEWTIMERS;ServUO - false - AnyCPU - - - ServUO.exe.manifest - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - False - ..\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll - - - - - - - - {e08cfbe4-e013-44ee-8829-426d05bc083f} - Ultima - - - - - - - + + + net48 + Exe + ServUO + servuo.ico + Server.Core + ServUO.exe.manifest + False + False + False + True + x64 + + + ..\ + TRACE;DEBUG;NEWTIMERS;ServUO + embedded + + + ..\ + TRACE;NEWTIMERS;ServUO + none + + + + \ No newline at end of file diff --git a/Server/Skills.cs b/Server/Skills.cs index 8a79f43..b462935 100755 --- a/Server/Skills.cs +++ b/Server/Skills.cs @@ -319,7 +319,7 @@ namespace Server } [CommandProperty(AccessLevel.Counselor, AccessLevel.GameMaster)] - public double Base { get { return (m_Base / 10.0); } set { BaseFixedPoint = (int)(value * 10.0); } } + public double Base { get => m_Base / 10.0; set => BaseFixedPoint = (int)Math.Round(value * 10.0); } public int CapFixedPoint { @@ -1106,4 +1106,4 @@ namespace Server return m_Skills.Where(s => s != null).GetEnumerator(); } } -} \ No newline at end of file +} diff --git a/Ultima/AssemblyInfo.cs b/Ultima/AssemblyInfo.cs index 8811433..7c5b773 100755 --- a/Ultima/AssemblyInfo.cs +++ b/Ultima/AssemblyInfo.cs @@ -4,12 +4,6 @@ using System.Resources; using System.Runtime.InteropServices; #endregion -// -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -// - [assembly: AssemblyTitle("UltimaSDK")] [assembly: AssemblyDescription("The Ultima SDK is a Software Development Kit")] [assembly: AssemblyConfiguration("")] @@ -18,43 +12,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: - -[assembly: AssemblyVersion("2.0.*")] -// -// In order to sign your assembly you must specify a key to use. Refer to the -// Microsoft .NET Framework documentation for more information on assembly signing. -// -// Use the attributes below to control which key is used for signing. -// -// Notes: -// (*) If no key is specified, the assembly is not signed. -// (*) KeyName refers to a key that has been installed in the Crypto Service -// Provider (CSP) on your machine. KeyFile refers to a file which contains -// a key. -// (*) If the KeyFile and the KeyName values are both specified, the -// following processing occurs: -// (1) If the KeyName can be found in the CSP, that key is used. -// (2) If the KeyName does not exist and the KeyFile does exist, the key -// in the KeyFile is installed into the CSP and used. -// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. -// When specifying the KeyFile, the location of the KeyFile should be -// relative to the project output directory which is -// %Project Directory%\obj\. For example, if your KeyFile is -// located in the project directory, you would specify the AssemblyKeyFile -// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] -// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework -// documentation for more information on this. -// +[assembly: AssemblyVersion("2.0")] [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] diff --git a/Ultima/Ultima.csproj b/Ultima/Ultima.csproj index 6046089..c305a1b 100755 --- a/Ultima/Ultima.csproj +++ b/Ultima/Ultima.csproj @@ -1,231 +1,21 @@ - - - - Local - 9.0.30729 - 2.0 - {E08CFBE4-E013-44EE-8829-426D05BC083F} - Debug - AnyCPU - - - - - Ultima - - - JScript - Grid - IE50 - false - Library - Ultima - OnBuildSuccess - - - - - - - 3.5 - v4.8 - win7-x64;win7-x86;ubuntu.16.10-x64 - - - ..\ - true - 285212672 - false - - - TRACE;DEBUG;NEWTIMERS;ServUO - - - true - 4096 - false - - - false - false - false - false - 4 - full - prompt - AllRules.ruleset - false - false - AnyCPU - - - ..\ - true - 285212672 - false - - - TRACE;NEWTIMERS;ServUO - - - false - 4096 - false - - - true - false - false - false - 4 - none - prompt - Auto - false - false - AnyCPU - - - true - ..\ - TRACE;DEBUG;NEWTIMERS;ServUO - 285212672 - true - full - AnyCPU - prompt - false - false - - - ..\ - 285212672 - true - true - - - AnyCPU - Off - prompt - false - TRACE;NEWTIMERS;ServUO - false - - - true - ..\ - TRACE;DEBUG;NEWTIMERS;ServUO - 285212672 - true - full - AnyCPU - prompt - false - false - - - ..\ - 285212672 - true - true - - - AnyCPU - Off - prompt - false - TRACE;NEWTIMERS;ServUO - false - - - - - System.Drawing - - - - - - Code - - - - Code - - - - - Code - - - Code - - - - Code - - - - Code - - - Code - - - - Code - - - Code - - - - Code - - - - Code - - - - - - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - - - - - - - + + + net48 + Library + False + False + False + True + x64 + + + ..\ + TRACE;DEBUG;NEWTIMERS;ServUO + embedded + + + ..\ + TRACE;NEWTIMERS;ServUO + none + \ No newline at end of file