Clean up: Bugs, LINQ, constructors, default values, and null checks (#18)

This commit is contained in:
Kamron Batman 2019-03-11 14:29:59 -07:00 • committed by GitHub
parent e748af4430
commit 513e54f70e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
1094 changed files with 15913 additions and 21892 deletions

View file

@ -80,15 +80,7 @@ namespace Server
BodyID = bodyID;
}
public BodyType Type
{
get
{
if (BodyID >= 0 && BodyID < m_Types.Length)
return m_Types[BodyID];
return BodyType.Empty;
}
}
public BodyType Type => BodyID >= 0 && BodyID < m_Types.Length ? m_Types[BodyID] : BodyType.Empty;
public bool IsHuman => BodyID >= 0
&& BodyID < m_Types.Length
@ -173,14 +165,12 @@ namespace Server
public override int GetHashCode()
{
return BodyID;
return BodyID.GetHashCode();
}
public override bool Equals(object o)
{
if (!(o is Body)) return false;
return ((Body)o).BodyID == BodyID;
return o is Body b && b.BodyID == BodyID;
}
public static bool operator ==(Body l, Body r)
@ -213,4 +203,4 @@ namespace Server
return l.BodyID <= r.BodyID;
}
}
}
}

View file

@ -19,7 +19,7 @@
***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Server
@ -32,13 +32,9 @@ namespace Server
SA
}
public class ClientVersion : IComparable, IComparer
public class ClientVersion : IComparable<ClientVersion>, IComparer<ClientVersion>
{
public ClientVersion(int maj, int min, int rev, int pat) : this(maj, min, rev, pat, ClientType.Regular)
{
}
public ClientVersion(int maj, int min, int rev, int pat, ClientType type)
public ClientVersion(int maj, int min, int rev, int pat, ClientType type = ClientType.Regular)
{
Major = maj;
Minor = min;
@ -111,15 +107,10 @@ namespace Server
public string SourceString{ get; }
public int CompareTo(object obj)
public int CompareTo(ClientVersion o)
{
if (obj == null)
return 1;
ClientVersion o = obj as ClientVersion;
if (o == null)
throw new ArgumentException();
return 1;
if (Major > o.Major)
return 1;
@ -140,24 +131,6 @@ namespace Server
return 0;
}
public int Compare(object x, object y)
{
if (IsNull(x) && IsNull(y))
return 0;
if (IsNull(x))
return -1;
if (IsNull(y))
return 1;
ClientVersion a = x as ClientVersion;
ClientVersion b = y as ClientVersion;
if (IsNull(a) || IsNull(b))
throw new ArgumentException();
return a.CompareTo(b);
}
public static bool operator ==(ClientVersion l, ClientVersion r)
{
return Compare(l, r) == 0;
@ -188,9 +161,14 @@ namespace Server
return Compare(l, r) < 0;
}
public override int GetHashCode()
// public override int GetHashCode()
// {
// return Major ^ Minor ^ Revision ^ Patch ^ (int)Type;
// }
int IComparer<ClientVersion>.Compare(ClientVersion x, ClientVersion y)
{
return Major ^ Minor ^ Revision ^ Patch ^ (int)Type;
return Compare(x, y);
}
public override bool Equals(object obj)
@ -262,4 +240,4 @@ namespace Server
return a.CompareTo(b);
}
}
}
}

View file

@ -49,13 +49,15 @@ namespace Server.ContextMenus
if (target is Mobile mobile)
mobile.GetContextMenuEntries(from, list);
else if (target is Item item) item.GetContextMenuEntries(from, list);
else if (target is Item item)
item.GetContextMenuEntries(from, list);
//m_Entries = (ContextMenuEntry[])list.ToArray( typeof( ContextMenuEntry ) );
Entries = list.ToArray();
for (int i = 0; i < Entries.Length; ++i) Entries[i].Owner = this;
for (int i = 0; i < Entries.Length; ++i)
Entries[i].Owner = this;
}
/// <summary>
@ -88,4 +90,4 @@ namespace Server.ContextMenus
}
}
}
}
}

View file

@ -28,18 +28,6 @@ namespace Server.ContextMenus
/// </summary>
public class ContextMenuEntry
{
/// <summary>
/// Instantiates a new ContextMenuEntry with a given <see cref="Number">localization number</see> (<paramref name="number" />
/// ). No <see cref="Range">maximum range</see> is used.
/// </summary>
/// <param name="number">
/// The localization number containing the name of this entry.
/// <seealso cref="Number" />
/// </param>
public ContextMenuEntry(int number) : this(number, -1)
{
}
/// <summary>
/// Instantiates a new ContextMenuEntry with a given <see cref="Number">localization number</see> (<paramref name="number" />)
/// and <see cref="Range">maximum range</see> (<paramref name="range" />).
@ -52,7 +40,7 @@ namespace Server.ContextMenus
/// The maximum range at which this entry can be used.
/// <seealso cref="Range" />
/// </param>
public ContextMenuEntry(int number, int range)
public ContextMenuEntry(int number, int range = -1)
{
if (number <= 0x7FFF) // Legacy code support
Number = 3000000 + number;

View file

@ -23,7 +23,7 @@ using System;
namespace Server
{
[Parsable]
public struct Point2D : IPoint2D, IComparable, IComparable<Point2D>
public struct Point2D : IPoint2D, IComparable<Point2D>
{
internal int m_X;
internal int m_Y;
@ -96,11 +96,7 @@ namespace Server
public override bool Equals(object o)
{
if (!(o is IPoint2D)) return false;
IPoint2D p = (IPoint2D)o;
return m_X == p.X && m_Y == p.Y;
return o is IPoint2D p && m_X == p.X && m_Y == p.Y;
}
public override int GetHashCode()
@ -120,18 +116,12 @@ namespace Server
public static bool operator ==(Point2D l, IPoint2D r)
{
if (ReferenceEquals(r, null))
return false;
return l.m_X == r.X && l.m_Y == r.Y;
return !ReferenceEquals(r, null) && l.m_X == r.X && l.m_Y == r.Y;
}
public static bool operator !=(Point2D l, IPoint2D r)
{
if (ReferenceEquals(r, null))
return false;
return l.m_X != r.X || l.m_Y != r.Y;
return !ReferenceEquals(r, null) && (l.m_X != r.X || l.m_Y != r.Y);
}
public static bool operator >(Point2D l, Point2D r)
@ -146,10 +136,7 @@ namespace Server
public static bool operator >(Point2D l, IPoint2D r)
{
if (ReferenceEquals(r, null))
return false;
return l.m_X > r.X && l.m_Y > r.Y;
return !ReferenceEquals(r, null) && l.m_X > r.X && l.m_Y > r.Y;
}
public static bool operator <(Point2D l, Point2D r)
@ -164,10 +151,7 @@ namespace Server
public static bool operator <(Point2D l, IPoint2D r)
{
if (ReferenceEquals(r, null))
return false;
return l.m_X < r.X && l.m_Y < r.Y;
return !ReferenceEquals(r, null) && l.m_X < r.X && l.m_Y < r.Y;
}
public static bool operator >=(Point2D l, Point2D r)
@ -182,10 +166,7 @@ namespace Server
public static bool operator >=(Point2D l, IPoint2D r)
{
if (ReferenceEquals(r, null))
return false;
return l.m_X >= r.X && l.m_Y >= r.Y;
return !ReferenceEquals(r, null) && l.m_X >= r.X && l.m_Y >= r.Y;
}
public static bool operator <=(Point2D l, Point2D r)
@ -200,15 +181,12 @@ namespace Server
public static bool operator <=(Point2D l, IPoint2D r)
{
if (ReferenceEquals(r, null))
return false;
return l.m_X <= r.X && l.m_Y <= r.Y;
return !ReferenceEquals(r, null) && l.m_X <= r.X && l.m_Y <= r.Y;
}
}
[Parsable]
public struct Point3D : IPoint3D, IComparable, IComparable<Point3D>
public struct Point3D : IPoint3D, IComparable<Point3D>
{
internal int m_X;
internal int m_Y;
@ -261,12 +239,7 @@ namespace Server
public override bool Equals(object o)
{
if (!(o is IPoint3D))
return false;
IPoint3D p = (IPoint3D)o;
return m_X == p.X && m_Y == p.Y && m_Z == p.Z;
return o is IPoint3D p && m_X == p.X && m_Y == p.Y && m_Z == p.Z;
}
public override int GetHashCode()
@ -306,18 +279,12 @@ namespace Server
public static bool operator ==(Point3D l, IPoint3D r)
{
if (ReferenceEquals(r, null))
return false;
return l.m_X == r.X && l.m_Y == r.Y && l.m_Z == r.Z;
return !ReferenceEquals(r, null) && l.m_X == r.X && l.m_Y == r.Y && l.m_Z == r.Z;
}
public static bool operator !=(Point3D l, IPoint3D r)
{
if (ReferenceEquals(r, null))
return false;
return l.m_X != r.X || l.m_Y != r.Y || l.m_Z != r.Z;
return !ReferenceEquals(r, null) && (l.m_X != r.X || l.m_Y != r.Y || l.m_Z != r.Z);
}
public int CompareTo(Point3D other)
@ -529,4 +496,4 @@ namespace Server
&& p.Z < End.m_Z;
}
}
}
}

View file

@ -185,7 +185,8 @@ namespace Server.Gumps
Add(new GumpBackground(x, y, width, height, gumpID));
}
public void AddButton(int x, int y, int normalID, int pressedID, int buttonID, GumpButtonType type, int param)
public void AddButton(int x, int y, int normalID, int pressedID, int buttonID,
GumpButtonType type = GumpButtonType.Reply, int param = 0)
{
Add(new GumpButton(x, y, normalID, pressedID, buttonID, type, param));
}
@ -205,34 +206,29 @@ namespace Server.Gumps
Add(new GumpTooltip(number));
}
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 = false, bool scrollbar = false)
{
Add(new GumpHtml(x, y, width, height, text, background, scrollbar));
}
public void AddHtmlLocalized(int x, int y, int width, int height, int number, bool background, bool scrollbar)
public void AddHtmlLocalized(int x, int y, int width, int height, int number, bool background = false, bool scrollbar = false)
{
Add(new GumpHtmlLocalized(x, y, width, height, number, background, scrollbar));
}
public void AddHtmlLocalized(int x, int y, int width, int height, int number, int color, bool background,
bool scrollbar)
public void AddHtmlLocalized(int x, int y, int width, int height, int number, int color, bool background = false,
bool scrollbar = false)
{
Add(new GumpHtmlLocalized(x, y, width, height, number, color, background, scrollbar));
}
public void AddHtmlLocalized(int x, int y, int width, int height, int number, string args, int color,
bool background, bool scrollbar)
bool background = false, bool scrollbar = false)
{
Add(new GumpHtmlLocalized(x, y, width, height, number, args, color, background, scrollbar));
}
public void AddImage(int x, int y, int gumpID)
{
Add(new GumpImage(x, y, gumpID));
}
public void AddImage(int x, int y, int gumpID, int hue)
public void AddImage(int x, int y, int gumpID, int hue = 0)
{
Add(new GumpImage(x, y, gumpID, hue));
}
@ -243,24 +239,13 @@ namespace Server.Gumps
}
public void AddImageTiledButton(int x, int y, int normalID, int pressedID, int buttonID, GumpButtonType type,
int param, int itemID, int hue, int width, int height)
{
Add(new GumpImageTileButton(x, y, normalID, pressedID, buttonID, type, param, itemID, hue, width, height));
}
public void AddImageTiledButton(int x, int y, int normalID, int pressedID, int buttonID, GumpButtonType type,
int param, int itemID, int hue, int width, int height, int localizedTooltip)
int param, int itemID, int hue, int width, int height, int localizedTooltip = -1)
{
Add(new GumpImageTileButton(x, y, normalID, pressedID, buttonID, type, param, itemID, hue, width, height,
localizedTooltip));
}
public void AddItem(int x, int y, int itemID)
{
Add(new GumpItem(x, y, itemID));
}
public void AddItem(int x, int y, int itemID, int hue)
public void AddItem(int x, int y, int itemID, int hue = 0)
{
Add(new GumpItem(x, y, itemID, hue));
}
@ -280,12 +265,7 @@ namespace Server.Gumps
Add(new GumpRadio(x, y, inactiveID, activeID, initialState, switchID));
}
public void AddTextEntry(int x, int y, int width, int height, int hue, int entryID, string initialText)
{
Add(new GumpTextEntry(x, y, width, height, hue, entryID, initialText));
}
public void AddTextEntry(int x, int y, int width, int height, int hue, int entryID, string initialText, int size)
public void AddTextEntry(int x, int y, int width, int height, int hue, int entryID, string initialText, int size = 0)
{
Add(new GumpTextEntryLimited(x, y, width, height, hue, entryID, initialText, size));
}
@ -390,4 +370,4 @@ namespace Server.Gumps
{
}
}
}
}

View file

@ -37,7 +37,8 @@ namespace Server.Gumps
private GumpButtonType m_Type;
private int m_X, m_Y;
public GumpButton(int x, int y, int normalID, int pressedID, int buttonID, GumpButtonType type, int param)
public GumpButton(int x, int y, int normalID, int pressedID, int buttonID,
GumpButtonType type = GumpButtonType.Reply, int param = 0)
{
m_X = x;
m_Y = y;
@ -117,4 +118,4 @@ namespace Server.Gumps
disp.AppendLayout(m_ButtonID);
}
}
}
}

View file

@ -41,33 +41,38 @@ namespace Server.Gumps
}
}
}
protected void Delta(ref uint var, uint val)
{
if (var != val) var = val;
if (var != val)
var = val;
}
protected void Delta(ref int var, int val)
{
if (var != val) var = val;
if (var != val)
var = val;
}
protected void Delta(ref bool var, bool val)
{
if (var != val) var = val;
if (var != val)
var = val;
}
protected void Delta(ref string var, string val)
{
if (var != val) var = val;
if (var != val)
var = val;
}
protected void Delta(ref object[] var, object[] val)
{
if (var != val) var = val;
if (var != val)
var = val;
}
public abstract string Compile(NetState ns);
public abstract void AppendTo(NetState ns, IGumpWriter disp);
}
}
}

View file

@ -43,7 +43,8 @@ namespace Server.Gumps
private int m_Width, m_Height;
private int m_X, m_Y;
public GumpHtmlLocalized(int x, int y, int width, int height, int number, bool background, bool scrollbar)
public GumpHtmlLocalized(int x, int y, int width, int height, int number,
bool background = false, bool scrollbar = false)
{
m_X = x;
m_Y = y;
@ -56,7 +57,8 @@ namespace Server.Gumps
m_Type = GumpHtmlLocalizedType.Plain;
}
public GumpHtmlLocalized(int x, int y, int width, int height, int number, int color, bool background, bool scrollbar)
public GumpHtmlLocalized(int x, int y, int width, int height, int number, int color,
bool background = false, bool scrollbar = false)
{
m_X = x;
m_Y = y;
@ -70,8 +72,8 @@ namespace Server.Gumps
m_Type = GumpHtmlLocalizedType.Color;
}
public GumpHtmlLocalized(int x, int y, int width, int height, int number, string args, int color, bool background,
bool scrollbar)
public GumpHtmlLocalized(int x, int y, int width, int height, int number, string args, int color,
bool background = false, bool scrollbar = false)
{
// Are multiple arguments unsupported? And what about non ASCII arguments?
@ -228,4 +230,4 @@ namespace Server.Gumps
}
}
}
}
}

View file

@ -30,11 +30,7 @@ namespace Server.Gumps
private int m_Hue;
private int m_X, m_Y;
public GumpImage(int x, int y, int gumpID) : this(x, y, gumpID, 0)
{
}
public GumpImage(int x, int y, int gumpID, int hue)
public GumpImage(int x, int y, int gumpID, int hue = 0)
{
m_X = x;
m_Y = y;
@ -68,9 +64,8 @@ namespace Server.Gumps
public override string Compile(NetState ns)
{
if (m_Hue == 0)
return $"{{ gumppic {m_X} {m_Y} {m_GumpID} }}";
return $"{{ gumppic {m_X} {m_Y} {m_GumpID} hue={m_Hue} }}";
return m_Hue == 0 ? $"{{ gumppic {m_X} {m_Y} {m_GumpID} }}" :
$"{{ gumppic {m_X} {m_Y} {m_GumpID} hue={m_Hue} }}";
}
public override void AppendTo(NetState ns, IGumpWriter disp)
@ -87,4 +82,4 @@ namespace Server.Gumps
}
}
}
}
}

View file

@ -41,13 +41,7 @@ namespace Server.Gumps
private int m_X, m_Y;
public GumpImageTileButton(int x, int y, int normalID, int pressedID, int buttonID, GumpButtonType type, int param,
int itemID, int hue, int width, int height) : this(x, y, normalID, pressedID, buttonID, type, param, itemID, hue,
width, height, -1)
{
}
public GumpImageTileButton(int x, int y, int normalID, int pressedID, int buttonID, GumpButtonType type, int param,
int itemID, int hue, int width, int height, int localizedTooltip)
int itemID, int hue, int width, int height, int localizedTooltip = -1)
{
m_X = x;
m_Y = y;
@ -175,4 +169,4 @@ namespace Server.Gumps
}
}
}
}
}

View file

@ -30,11 +30,7 @@ namespace Server.Gumps
private int m_ItemID;
private int m_X, m_Y;
public GumpItem(int x, int y, int itemID) : this(x, y, itemID, 0)
{
}
public GumpItem(int x, int y, int itemID, int hue)
public GumpItem(int x, int y, int itemID, int hue = 0)
{
m_X = x;
m_Y = y;
@ -68,9 +64,8 @@ namespace Server.Gumps
public override string Compile(NetState ns)
{
if (m_Hue == 0)
return $"{{ tilepic {m_X} {m_Y} {m_ItemID} }}";
return $"{{ tilepichue {m_X} {m_Y} {m_ItemID} {m_Hue} }}";
return m_Hue == 0 ? $"{{ tilepic {m_X} {m_Y} {m_ItemID} }}" :
$"{{ tilepichue {m_X} {m_Y} {m_ItemID} {m_Hue} }}";
}
public override void AppendTo(NetState ns, IGumpWriter disp)
@ -84,4 +79,4 @@ namespace Server.Gumps
disp.AppendLayout(m_Hue);
}
}
}
}

View file

@ -32,7 +32,7 @@ namespace Server.Gumps
private int m_Width, m_Height;
private int m_X, m_Y;
public GumpTextEntryLimited(int x, int y, int width, int height, int hue, int entryID, string initialText, int size)
public GumpTextEntryLimited(int x, int y, int width, int height, int hue, int entryID, string initialText, int size = 0)
{
m_X = x;
m_Y = y;
@ -113,4 +113,4 @@ namespace Server.Gumps
disp.TextEntries++;
}
}
}
}

View file

@ -22,6 +22,7 @@ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Server.ContextMenus;
using Server.Items;
@ -965,7 +966,8 @@ namespace Server
{
Mobile m = state.Mobile;
if (!m.CanSee(this) && m.InRange(worldLoc, GetUpdateRange(m))) state.Send(RemovePacket);
if (!m.CanSee(this) && m.InRange(worldLoc, GetUpdateRange(m)))
state.Send(RemovePacket);
}
eable.Free();
@ -1864,15 +1866,15 @@ namespace Server
if (info != null)
{
if (info.m_BlessedFor != null && !info.m_BlessedFor.Deleted)
if (info.m_BlessedFor?.Deleted == false)
flags |= SaveFlag.BlessedFor;
if (info.m_HeldBy != null && !info.m_HeldBy.Deleted)
if (info.m_HeldBy?.Deleted == false)
flags |= SaveFlag.HeldBy;
if (info.m_SavedFlags != 0)
flags |= SaveFlag.SavedFlags;
}
if (info == null || info.m_Weight == -1)
if (info == null || info.m_Weight == -1.0)
{
flags |= SaveFlag.NullWeight;
}
@ -1974,7 +1976,7 @@ namespace Server
if (GetSaveFlag(flags, SaveFlag.Parent))
{
if (m_Parent != null && !m_Parent.Deleted)
if (m_Parent?.Deleted == false)
writer.Write(m_Parent.Serial);
else
writer.Write(Serial.MinusOne);
@ -2323,7 +2325,7 @@ namespace Server
Mobile blessedFor = BlessedFor;
if (blessedFor != null && !blessedFor.Deleted)
if (blessedFor?.Deleted == false)
AddBlessedForProperty(list, blessedFor);
if (DisplayLootType)
@ -2428,7 +2430,7 @@ namespace Server
{
IEntity parent = bounce.m_Parent;
if (parent == null || parent.Deleted)
if (parent?.Deleted != false)
{
MoveToWorld(bounce.m_WorldLoc, bounce.m_Map);
}
@ -3362,7 +3364,7 @@ namespace Server
public virtual void AddItem(Item item)
{
if (item == null || item.Deleted || item.m_Parent == this) return;
if (item?.Deleted != false || item.m_Parent == this) return;
if (item == this)
{
@ -3430,6 +3432,7 @@ namespace Server
}
catch
{
// ignored
}
else
m_DeltaQueue.Add(this);
@ -3759,29 +3762,24 @@ namespace Server
z = top;
}
List<Item> items = new List<Item>();
IPooledEnumerable<Item> eable = map.GetItemsInRange(p, 0);
foreach (Item item in eable)
List<Item> items = eable.Where(item =>
{
if (item is BaseMulti || item.ItemID > TileData.MaxItemValue)
continue;
items.Add(item);
return false;
ItemData id = item.ItemData;
if (!id.Surface)
continue;
if (id.Surface)
{
int top = item.Z + id.CalcHeight;
if (top <= maxZ && top >= z)
z = top;
}
int top = item.Z + id.CalcHeight;
if (top > maxZ || top < z)
continue;
z = top;
}
return true;
}).ToList();
eable.Free();

View file

@ -22,9 +22,8 @@ using System;
namespace Server.Items
{
public class BaseMulti : Item
public abstract class BaseMulti : Item
{
[Constructible]
public BaseMulti(int itemID) : base(itemID)
{
Movable = false;
@ -162,4 +161,4 @@ namespace Server.Items
ItemID -= 0x4000;
}
}
}
}

View file

@ -203,7 +203,7 @@ namespace Server.Items
public virtual bool CheckHold(Mobile m, Item item, bool message, bool checkItems, int plusItems, int plusWeight)
{
if (m != null && m.AccessLevel < AccessLevel.GameMaster)
if (m?.AccessLevel < AccessLevel.GameMaster)
{
if (IsDecoContainer)
{
@ -607,15 +607,13 @@ namespace Server.Items
{
DisplayTo(from);
SecureTradeContainer cont = GetSecureTradeCont();
SecureTrade trade = GetSecureTradeCont()?.Trade;
if (cont != null)
if (trade != null)
{
SecureTrade trade = cont.Trade;
if (trade != null && trade.From.Mobile == from)
if (trade.From.Mobile == from)
DisplayTo(trade.To.Mobile);
else if (trade != null && trade.To.Mobile == from)
else if (trade.To.Mobile == from)
DisplayTo(trade.From.Mobile);
}
}
@ -675,50 +673,50 @@ namespace Server.Items
public void ProcessOpeners(Mobile opener)
{
if (!IsPublicContainer)
if (IsPublicContainer)
return;
bool contains = false;
if (Openers != null)
{
bool contains = false;
Point3D worldLoc = GetWorldLocation();
Map map = Map;
if (Openers != null)
for (int i = 0; i < Openers.Count; ++i)
{
Point3D worldLoc = GetWorldLocation();
Map map = Map;
Mobile mob = Openers[i];
for (int i = 0; i < Openers.Count; ++i)
if (mob == opener)
{
Mobile mob = Openers[i];
contains = true;
}
else
{
int range = GetUpdateRange(mob);
if (mob == opener)
{
contains = true;
}
else
{
int range = GetUpdateRange(mob);
if (mob.Map != map || !mob.InRange(worldLoc, range))
Openers.RemoveAt(i--);
}
if (mob.Map != map || !mob.InRange(worldLoc, range))
Openers.RemoveAt(i--);
}
}
}
if (!contains)
{
if (Openers == null)
Openers = new List<Mobile>();
if (!contains)
{
if (Openers == null)
Openers = new List<Mobile>();
Openers.Add(opener);
}
else if (Openers != null && Openers.Count == 0)
{
Openers = null;
}
Openers.Add(opener);
}
else if (Openers?.Count == 0)
{
Openers = null;
}
}
public virtual void SendContentTo(NetState state)
{
if (state != null && state.ContainerGridLines)
if (state?.ContainerGridLines == true)
state.Send(new ContainerContent6017(state.Mobile, this));
else
state.Send(new ContainerContent(state.Mobile, this));
@ -1122,17 +1120,7 @@ namespace Server.Items
return -1;
}
public int ConsumeTotal(Type[] types, int[] amounts)
{
return ConsumeTotal(types, amounts, true, null);
}
public int ConsumeTotal(Type[] types, int[] amounts, bool recurse)
{
return ConsumeTotal(types, amounts, recurse, null);
}
public int ConsumeTotal(Type[] types, int[] amounts, bool recurse, OnItemConsumed callback)
public int ConsumeTotal(Type[] types, int[] amounts, bool recurse = true, OnItemConsumed callback = null)
{
if (types.Length != amounts.Length)
throw new ArgumentException();
@ -1181,17 +1169,7 @@ namespace Server.Items
return -1;
}
public bool ConsumeTotal(Type type, int amount)
{
return ConsumeTotal(type, amount, true, null);
}
public bool ConsumeTotal(Type type, int amount, bool recurse)
{
return ConsumeTotal(type, amount, recurse, null);
}
public bool ConsumeTotal(Type type, int amount, bool recurse, OnItemConsumed callback)
public bool ConsumeTotal(Type type, int amount = 1, bool recurse = true, OnItemConsumed callback = null)
{
Item[] items = FindItemsByType(type, recurse);
@ -1234,12 +1212,7 @@ namespace Server.Items
return false;
}
public int ConsumeUpTo(Type type, int amount)
{
return ConsumeUpTo(type, amount, true);
}
public int ConsumeUpTo(Type type, int amount, bool recurse)
public int ConsumeUpTo(Type type, int amount, bool recurse = true)
{
int consumed = 0;
@ -1256,37 +1229,37 @@ namespace Server.Items
private static void RecurseConsumeUpTo(Item current, Type type, int amount, bool recurse, ref int consumed,
Queue<Item> toDelete)
{
if (current != null && current.Items.Count > 0)
if (current == null || current.Items.Count == 0)
return;
List<Item> list = current.Items;
for (int i = 0; i < list.Count; ++i)
{
List<Item> list = current.Items;
Item item = list[i];
for (int i = 0; i < list.Count; ++i)
if (type.IsInstanceOfType(item))
{
Item item = list[i];
int need = amount - consumed;
int theirAmount = item.Amount;
if (type.IsInstanceOfType(item))
if (theirAmount <= need)
{
int need = amount - consumed;
int theirAmount = item.Amount;
if (theirAmount <= need)
{
toDelete.Enqueue(item);
consumed += theirAmount;
}
else
{
item.Amount -= need;
consumed += need;
return;
}
toDelete.Enqueue(item);
consumed += theirAmount;
}
else if (recurse && item is Container)
else
{
RecurseConsumeUpTo(item, type, amount, true, ref consumed, toDelete);
item.Amount -= need;
consumed += need;
return;
}
}
else if (recurse && item is Container)
{
RecurseConsumeUpTo(item, type, amount, true, ref consumed, toDelete);
}
}
}
@ -1572,7 +1545,7 @@ namespace Server.Items
private static Item RecurseFindItemByType(Item current, Type[] types, bool recurse)
{
if (current == null || current.Items.Count <= 0)
if (current == null || current.Items.Count == 0)
return null;
List<Item> list = current.Items;
@ -1635,12 +1608,12 @@ namespace Server.Items
}
}
public T FindItemByType<T>(bool recurse = true, Predicate<T> predicate = null) where T : Item
public T FindItemByType<T>(bool recurse = true) where T : Item
{
return RecurseFindItemByType(this, recurse, predicate);
return RecurseFindItemByType<T>(this, recurse);
}
private static T RecurseFindItemByType<T>(Item current, bool recurse, Predicate<T> predicate) where T : Item
private static T RecurseFindItemByType<T>(Item current, bool recurse = true, Predicate<T> predicate = null) where T : Item
{
if (current == null || current.Items.Count == 0)
return null;

View file

@ -97,8 +97,8 @@ namespace Server.Items
{
Opened = false;
if (Owner != null && SendDeleteOnClose)
Owner.Send(RemovePacket);
if (SendDeleteOnClose)
Owner?.Send(RemovePacket);
}
public override void OnSingleClick(Mobile from)
@ -116,30 +116,26 @@ namespace Server.Items
public override bool IsAccessibleTo(Mobile check)
{
if (check == Owner && Opened || check.AccessLevel >= AccessLevel.GameMaster)
return base.IsAccessibleTo(check);
return false;
return (check == Owner && Opened || check.AccessLevel >= AccessLevel.GameMaster) && base.IsAccessibleTo(check);
}
public override bool OnDragDrop(Mobile from, Item dropped)
{
if (from == Owner && Opened || from.AccessLevel >= AccessLevel.GameMaster)
return base.OnDragDrop(from, dropped);
return false;
return (from == Owner && Opened || from.AccessLevel >= AccessLevel.GameMaster) && base.OnDragDrop(from, dropped);
}
public override bool OnDragDropInto(Mobile from, Item item, Point3D p)
{
if (from == Owner && Opened || from.AccessLevel >= AccessLevel.GameMaster)
return base.OnDragDropInto(from, item, p);
return false;
return (from == Owner && Opened || from.AccessLevel >= AccessLevel.GameMaster) &&
base.OnDragDropInto(from, item, p);
}
public override int GetTotal(TotalType type)
{
if (AccountGold.Enabled && Owner?.Account != null && type == TotalType.Gold) return Owner.Account.TotalGold;
if (AccountGold.Enabled && Owner?.Account != null && type == TotalType.Gold)
return Owner.Account.TotalGold;
return base.GetTotal(type);
}
}
}
}

View file

@ -42,12 +42,7 @@ namespace Server.Items
{
if (item == Trade.From.VirtualCheck || item == Trade.To.VirtualCheck) return true;
Mobile to;
if (Trade.From.Container != this)
to = Trade.From.Mobile;
else
to = Trade.To.Mobile;
Mobile to = Trade.From.Container != this ? Trade.From.Mobile : Trade.To.Mobile;
return m.CheckTrade(to, item, this, message, checkItems, plusItems, plusWeight);
}
@ -60,49 +55,52 @@ namespace Server.Items
public override bool IsAccessibleTo(Mobile check)
{
if (!IsChildOf(check) || Trade == null || !Trade.Valid)
return false;
return base.IsAccessibleTo(check);
return IsChildOf(check) && Trade?.Valid == true && base.IsAccessibleTo(check);
}
public override void OnItemAdded(Item item)
{
if (!(item is VirtualCheck)) ClearChecks();
if (!(item is VirtualCheck))
ClearChecks();
}
public override void OnItemRemoved(Item item)
{
if (!(item is VirtualCheck)) ClearChecks();
if (!(item is VirtualCheck))
ClearChecks();
}
public override void OnSubItemAdded(Item item)
{
if (!(item is VirtualCheck)) ClearChecks();
if (!(item is VirtualCheck))
ClearChecks();
}
public override void OnSubItemRemoved(Item item)
{
if (!(item is VirtualCheck)) ClearChecks();
if (!(item is VirtualCheck))
ClearChecks();
}
public void ClearChecks()
{
if (Trade != null)
{
if (Trade.From != null && !Trade.From.IsDisposed) Trade.From.Accepted = false;
if (Trade == null)
return;
if (Trade.To != null && !Trade.To.IsDisposed) Trade.To.Accepted = false;
if (Trade.From?.IsDisposed == false)
Trade.From.Accepted = false;
Trade.Update();
}
if (Trade.To?.IsDisposed == false)
Trade.To.Accepted = false;
Trade.Update();
}
public override bool IsChildVisibleTo(Mobile m, Item child)
{
if (child is VirtualCheck) return AccountGold.Enabled && (m.NetState == null || !m.NetState.NewSecureTrading);
return base.IsChildVisibleTo(m, child);
return child is VirtualCheck
? AccountGold.Enabled && m.NetState?.NewSecureTrading != true
: base.IsChildVisibleTo(m, child);
}
public override void Serialize(GenericWriter writer)
@ -119,4 +117,4 @@ namespace Server.Items
int version = reader.ReadInt();
}
}
}
}

View file

@ -1,20 +1,7 @@
#region Header
// **********
// ServUO - VirtualCheck.cs
// **********
#endregion
#region References
using System.Drawing;
using Server.Gumps;
using Server.Items;
using Server.Network;
#endregion
namespace Server
{
public sealed class VirtualCheck : Item
@ -25,12 +12,7 @@ namespace Server
private int _Plat;
public VirtualCheck()
: this(0, 0)
{
}
public VirtualCheck(int plat, int gold)
public VirtualCheck(int plat = 0, int gold = 0)
: base(0x14F0)
{
Plat = plat;
@ -90,7 +72,7 @@ namespace Server
{
if (UseEditGump && IsAccessibleTo(from))
{
if (Editor?.Check == null || Editor.Check.Deleted)
if (Editor?.Check?.Deleted != false)
{
Editor = new EditGump(from, this);
Editor.Send();
@ -196,14 +178,15 @@ namespace Server
{
base.OnServerClose(owner);
if (Check != null && !Check.Deleted) Check.UpdateTrade(User);
if (Check?.Deleted == false)
Check.UpdateTrade(User);
}
public void Close()
{
User.CloseGump<EditGump>();
if (Check != null && !Check.Deleted)
if (Check?.Deleted == false)
Check.UpdateTrade(User);
else
Check = null;
@ -211,7 +194,7 @@ namespace Server
public void Send()
{
if (Check != null && !Check.Deleted)
if (Check?.Deleted == false)
User.SendGump(this);
else
Close();
@ -219,13 +202,14 @@ namespace Server
public void Refresh(bool recompile)
{
if (Check == null || Check.Deleted)
if (Check?.Deleted != false)
{
Close();
return;
}
if (recompile) CompileLayout();
if (recompile)
CompileLayout();
Close();
Send();
@ -233,7 +217,8 @@ namespace Server
private void CompileLayout()
{
if (Check == null || Check.Deleted) return;
if (Check?.Deleted != false)
return;
Entries.ForEach(e => e.Parent = null);
Entries.Clear();
@ -248,9 +233,9 @@ namespace Server
AddImage(360, 8, 113);
string title =
$"<BASEFONT COLOR=#{Color.DarkSlateGray.ToArgb():X}><CENTER>BANK OF {User.RawName.ToUpper()}</CENTER>";
$"<BASEFONT COLOR=#FF2F4F4F><CENTER>BANK OF {User.RawName.ToUpper()}</CENTER>";
AddHtml(40, 15, 320, 20, title, false, false);
AddHtml(40, 15, 320, 20, title);
// Platinum Row
AddBackground(15, 60, 175, 20, 9300);
@ -258,7 +243,7 @@ namespace Server
AddItem(20, 45, 3826); // Plat
AddLabel(60, 50, 0, User.Account.TotalPlat.ToString("#,0"));
AddButton(195, 50, 95, 95, (int)Buttons.AllPlat, GumpButtonType.Reply, 0); // ->
AddButton(195, 50, 95, 95, (int)Buttons.AllPlat); // ->
AddBackground(210, 60, 175, 20, 9300);
AddBackground(215, 45, 165, 30, 9350);
@ -270,21 +255,21 @@ namespace Server
AddItem(20, 85, 3823); // Gold
AddLabel(60, 90, 0, User.Account.TotalGold.ToString("#,0"));
AddButton(195, 90, 95, 95, (int)Buttons.AllGold, GumpButtonType.Reply, 0); // ->
AddButton(195, 90, 95, 95, (int)Buttons.AllGold); // ->
AddBackground(210, 100, 175, 20, 9300);
AddBackground(215, 85, 165, 30, 9350);
AddTextEntry(225, 90, 145, 20, 0, 1, _Gold.ToString(), User.Account.TotalGold.ToString().Length);
// Buttons
AddButton(20, 128, 12006, 12007, (int)Buttons.Close, GumpButtonType.Reply, 0);
AddButton(215, 128, 12003, 12004, (int)Buttons.Clear, GumpButtonType.Reply, 0);
AddButton(305, 128, 12000, 12002, (int)Buttons.Accept, GumpButtonType.Reply, 0);
AddButton(20, 128, 12006, 12007, (int)Buttons.Close);
AddButton(215, 128, 12003, 12004, (int)Buttons.Clear);
AddButton(305, 128, 12000, 12002, (int)Buttons.Accept);
}
public override void OnResponse(NetState sender, RelayInfo info)
{
if (Check == null || Check.Deleted || sender.Mobile != User)
if (Check?.Deleted != false || sender.Mobile != User)
{
Close();
return;
@ -352,9 +337,10 @@ namespace Server
break;
}
if (updated) User.SendMessage("Your offer has been updated.");
if (updated)
User.SendMessage("Your offer has been updated.");
if (refresh && Check != null && !Check.Deleted)
if (refresh && Check?.Deleted == false)
{
Refresh(true);
return;
@ -364,4 +350,4 @@ namespace Server
}
}
}
}
}

View file

@ -263,6 +263,7 @@ namespace Server
}
catch
{
// ignored
}
if (!close && !Service)
@ -273,6 +274,7 @@ namespace Server
}
catch
{
// ignored
}
Console.WriteLine("This exception is fatal, press return to exit");
@ -374,6 +376,7 @@ namespace Server
}
catch
{
// ignored
}
Thread = Thread.CurrentThread;
@ -563,7 +566,7 @@ namespace Server
warningSb.AppendLine(" - No Deserialize() method");
}
if (warningSb != null && warningSb.Length > 0) Console.WriteLine("Warning: {0}\n{1}", t, warningSb);
if (warningSb?.Length > 0) Console.WriteLine("Warning: {0}\n{1}", t, warningSb);
}
catch
{
@ -626,12 +629,7 @@ namespace Server
private bool _NewLine;
public FileLogger(string file)
: this(file, false)
{
}
public FileLogger(string file, bool append)
public FileLogger(string file, bool append = false)
{
FileName = file;
@ -733,4 +731,4 @@ namespace Server
WriteLine(string.Format(line, args));
}
}
}
}

View file

@ -72,7 +72,7 @@ namespace Server
public static IEnumerable<NetState> SelectClients(Sector s, Rectangle2D bounds)
{
return s.Clients.Where(o => o?.Mobile != null && !o.Mobile.Deleted && bounds.Contains(o.Mobile));
return s.Clients.Where(o => o?.Mobile?.Deleted == false && bounds.Contains(o.Mobile));
}
public static IEnumerable<IEntity> SelectEntities(Sector s, Rectangle2D bounds)
@ -84,9 +84,9 @@ namespace Server
{
IEnumerable<IEntity> eable = Enumerable.Empty<IEntity>();
if (mobiles)
eable = eable.Union(s.Mobiles.Where(o => o != null && !o.Deleted));
eable = eable.Union(s.Mobiles.Where(o => o?.Deleted == false));
if (items)
eable = eable.Union(s.Items.Where(o => o != null && !o.Deleted && o.Parent == null));
eable = eable.Union(s.Items.Where(o => o?.Deleted == false && o.Parent == null));
return eable.Where(bounds.Contains);
}
@ -99,17 +99,17 @@ namespace Server
public static IEnumerable<T> SelectItems<T>(Sector s, Rectangle2D bounds) where T : Item
{
return s.Items.OfType<T>()
.Where(o => !o.Deleted && o.Parent == null && bounds.Contains(o));
.Where(o => o.Deleted == false && o.Parent == null && bounds.Contains(o));
}
public static IEnumerable<BaseMulti> SelectMultis(Sector s, Rectangle2D bounds)
{
return s.Multis.Where(o => o != null && !o.Deleted && bounds.Contains(o.Location));
return s.Multis.Where(o => o?.Deleted == false && bounds.Contains(o.Location));
}
public static IEnumerable<StaticTile[]> SelectMultiTiles(Sector s, Rectangle2D bounds)
{
foreach (BaseMulti o in s.Multis.Where(o => o != null && !o.Deleted))
foreach (BaseMulti o in s.Multis.Where(o => o?.Deleted == false))
{
MultiComponentList c = o.Components;
@ -354,13 +354,8 @@ namespace Server
public Region DefaultRegion
{
get
{
if (m_DefaultRegion == null)
m_DefaultRegion = new Region(null, this, 0, new Rectangle3D[0]);
return m_DefaultRegion;
}
get => m_DefaultRegion ??
(m_DefaultRegion = new Region(null, this, 0, new Rectangle3D[0]));
set => m_DefaultRegion = value;
}
@ -424,16 +419,16 @@ namespace Server
public static Map Parse(string value)
{
if (string.IsNullOrWhiteSpace(value)) return null;
if (string.IsNullOrWhiteSpace(value))
return null;
if (Insensitive.Equals(value, "Internal")) return Internal;
if (Insensitive.Equals(value, "Internal"))
return Internal;
if (!int.TryParse(value, out int index))
return Maps.FirstOrDefault(m => m != null && Insensitive.Equals(m.Name, value));
if (index == 127) return Internal;
return Maps.FirstOrDefault(m => m != null && m.MapIndex == index);
return index == 127 ? Internal : Maps.FirstOrDefault(m => m != null && m.MapIndex == index);
}
public override string ToString()
@ -473,10 +468,8 @@ namespace Server
if (zBottom > top)
top = zBottom;
if (Math.Abs(zTop - zBottom) > Math.Abs(zLeft - zRight))
avg = FloorAverage(zLeft, zRight);
else
avg = FloorAverage(zTop, zBottom);
avg = Math.Abs(zTop - zBottom) > Math.Abs(zLeft - zRight) ?
FloorAverage(zLeft, zRight) : FloorAverage(zTop, zBottom);
}
private static int FloorAverage(int a, int b)
@ -496,16 +489,19 @@ namespace Server
private static List<Item> AcquireFixItems(Map map, int x, int y)
{
if (map == null || map == Internal || x < 0 || x > map.Width || y < 0 || y > map.Height) return _EmptyFixItems;
if (map == null || map == Internal || x < 0 || x > map.Width || y < 0 || y > map.Height)
return _EmptyFixItems;
List<Item> pool = null;
lock (_FixPool)
{
if (_FixPool.Count > 0) pool = _FixPool.Dequeue();
if (_FixPool.Count > 0)
pool = _FixPool.Dequeue();
}
if (pool == null) pool = new List<Item>(128); // Arbitrary limit
if (pool == null)
pool = new List<Item>(128); // Arbitrary limit
IPooledEnumerable<Item> eable = map.GetItemsInRange(new Point3D(x, y, 0), 0);
@ -528,7 +524,8 @@ namespace Server
lock (_FixPool)
{
if (_FixPool.Count < 128) _FixPool.Enqueue(pool);
if (_FixPool.Count < 128)
_FixPool.Enqueue(pool);
}
}
@ -1064,13 +1061,12 @@ namespace Server
IEnumerable<T> pool = PooledEnumeration.EnumerateSectors(map, bounds).SelectMany(s => selector(s, bounds));
if (e != null)
{
e._Pool.AddRange(pool);
return e;
}
if (e == null)
return new PooledEnumerable<T>(pool);
e._Pool.AddRange(pool);
return e;
return new PooledEnumerable<T>(pool);
}
}
@ -1436,14 +1432,7 @@ namespace Server
{
IPooledEnumerable<Item> eable = GetItemsInRange(point, 0);
foreach (Item item in eable)
{
if (item.Visible)
contains = false;
if (!contains)
break;
}
contains = !eable.Any(item => item.Visible);
eable.Free();

View file

@ -24,11 +24,7 @@ namespace Server.Menus.ItemLists
{
public class ItemListEntry
{
public ItemListEntry(string name, int itemID) : this(name, itemID, 0)
{
}
public ItemListEntry(string name, int itemID, int hue)
public ItemListEntry(string name, int itemID, int hue = 0)
{
Name = name;
ItemID = itemID;
@ -83,4 +79,4 @@ namespace Server.Menus.ItemLists
state.Send(new DisplayItemListMenu(this));
}
}
}
}

View file

@ -614,21 +614,12 @@ namespace Server
[CommandProperty(AccessLevel.GameMaster)]
public Race Race
{
get
{
if (m_Race == null)
m_Race = Race.DefaultRace;
return m_Race;
}
get => m_Race ?? (m_Race = Race.DefaultRace);
set
{
Race oldRace = Race;
m_Race = value;
if (m_Race == null)
m_Race = Race.DefaultRace;
m_Race = value ?? Race.DefaultRace;
Body = m_Race.Body(this);
UpdateResistances();
@ -1465,7 +1456,8 @@ namespace Server
{
get
{
if (m_NetState != null && m_NetState.Socket == null && !m_NetState.IsDisposing) NetState = null;
if (m_NetState != null && m_NetState.Socket == null && !m_NetState.IsDisposing)
NetState = null;
return m_NetState;
}
@ -1489,7 +1481,7 @@ namespace Server
BankBox box = FindBankNoCreate();
if (box != null && box.Opened)
if (box?.Opened == true)
box.Close();
// REMOVED:
@ -1591,7 +1583,7 @@ namespace Server
{
m_GuildTitle = value;
if (m_Guild != null && !m_Guild.Disbanded && m_GuildTitle != null)
if (m_Guild?.Disbanded == false && m_GuildTitle != null)
SendLocalizedMessage(1018026, true, m_GuildTitle); // Your guild title has changed :
InvalidateProperties();
@ -1881,7 +1873,7 @@ namespace Server
{
get
{
if (m_BankBox != null && !m_BankBox.Deleted && m_BankBox.Parent == this)
if (m_BankBox?.Deleted == false && m_BankBox.Parent == this)
return m_BankBox;
m_BankBox = FindItemOnLayer(Layer.Bank) as BankBox;
@ -1898,10 +1890,10 @@ namespace Server
{
get
{
if (m_Backpack != null && !m_Backpack.Deleted && m_Backpack.Parent == this)
return m_Backpack;
if (m_Backpack?.Deleted != false || m_Backpack.Parent != this)
m_Backpack = FindItemOnLayer(Layer.Backpack) as Container;
return m_Backpack = FindItemOnLayer(Layer.Backpack) as Container;
return m_Backpack;
}
}
@ -3076,10 +3068,7 @@ namespace Server
public virtual void AddNameProperties(ObjectPropertyList list)
{
string name = Name;
if (name == null)
name = string.Empty;
string name = Name ?? string.Empty;
string prefix = "";
@ -3095,10 +3084,8 @@ namespace Server
if (guild != null && (m_Player || m_DisplayGuildTitle))
{
if (suffix.Length > 0)
suffix = string.Format("{0} [{1}]", suffix, Utility.FixHtml(guild.Abbreviation));
else
suffix = string.Format("[{0}]", Utility.FixHtml(guild.Abbreviation));
suffix = suffix.Length > 0 ? $"{suffix} [{Utility.FixHtml(guild.Abbreviation)}]"
: $"[{Utility.FixHtml(guild.Abbreviation)}]";
}
suffix = ApplyNameSuffix(suffix);
@ -3114,12 +3101,7 @@ namespace Server
else
type = "";
string title = GuildTitle;
if (title == null)
title = "";
else
title = title.Trim();
string title = GuildTitle?.Trim() ?? "";
if (NewGuildDisplay && title.Length > 0)
{
@ -3349,12 +3331,7 @@ namespace Server
public bool InLOS(Point3D target)
{
if (Deleted || m_Map == null)
return false;
if (m_AccessLevel > AccessLevel.Player)
return true;
return m_Map.LineOfSight(this, target);
return !Deleted && m_Map != null && (m_AccessLevel > AccessLevel.Player || m_Map.LineOfSight(this, target));
}
public bool BeginAction<T>()
@ -3433,7 +3410,7 @@ namespace Server
public override string ToString()
{
return string.Format("0x{0:X} \"{1}\"", Serial.Value, Name);
return $"0x{Serial.Value:X} \"{Name}\"";
}
public virtual void SendSkillMessage()
@ -3849,7 +3826,7 @@ namespace Server
BankBox box = FindBankNoCreate();
if (box != null && box.Opened)
if (box?.Opened == true)
box.Close();
Point3D newLocation = m_Location;
@ -3859,7 +3836,7 @@ namespace Server
{
// We are actually moving (not just a direction change)
if (m_Spell != null && !m_Spell.OnCasterMoving(d))
if (m_Spell?.OnCasterMoving(d) == false)
return false;
if (m_Paralyzed || m_Frozen)
@ -4090,9 +4067,8 @@ namespace Server
{
if (ns.StygianAbyss)
{
Packet p;
int noto = Notoriety.Compute(m, this);
p = cache[0][noto];
Packet p = cache[0][noto];
if (p == null)
cache[0][noto] = p = Packet.Acquire(new MobileMoving(this, noto));
@ -4101,9 +4077,8 @@ namespace Server
}
else
{
Packet p;
int noto = Notoriety.Compute(m, this);
p = cache[1][noto];
Packet p = cache[1][noto];
if (p == null)
cache[1][noto] = p = Packet.Acquire(new MobileMovingOld(this, noto));
@ -4114,8 +4089,8 @@ namespace Server
}
for (int i = 0; i < cache.Length; ++i)
for (int j = 0; j < cache[i].Length; ++j)
Packet.Release(ref cache[i][j]);
for (int j = 0; j < cache[i].Length; ++j)
Packet.Release(ref cache[i][j]);
for (int i = 0; i < m_MoveList.Count; ++i)
{
@ -4286,7 +4261,7 @@ namespace Server
BankBox box = FindBankNoCreate();
if (box != null && box.Opened)
if (box?.Opened == true)
box.Close();
Poison = null;
@ -4447,7 +4422,7 @@ namespace Server
BankBox box = FindBankNoCreate();
if (box != null && box.Opened)
if (box?.Opened == true)
box.Close();
m_NetState?.CancelAllTrades();
@ -4659,12 +4634,12 @@ namespace Server
public virtual void Use(Item item)
{
if (item == null || item.Deleted || item.QuestItem || Deleted)
if (item?.Deleted != false || item.QuestItem || Deleted)
return;
DisruptiveAction();
if (m_Spell != null && !m_Spell.OnCasterUsingObject(item))
if (m_Spell?.OnCasterUsingObject(item) == false)
return;
IEntity root = item.RootParent;
@ -4722,12 +4697,12 @@ namespace Server
public virtual void Use(Mobile m)
{
if (m == null || m.Deleted || Deleted)
if (m?.Deleted != false || Deleted)
return;
DisruptiveAction();
if (m_Spell != null && !m_Spell.OnCasterUsingObject(m))
if (m_Spell?.OnCasterUsingObject(m) == false)
return;
if (!Utility.InUpdateRange(this, m))
@ -5202,24 +5177,24 @@ namespace Server
foreach (IEntity o in eable)
if (o is Mobile heard)
{
if (heard.CanSee(this) && (NoSpeechLOS || !heard.Player || heard.InLOS(this)))
if (!heard.CanSee(this) || !NoSpeechLOS && heard.Player && !heard.InLOS(this))
continue;
if (heard.m_NetState != null)
hears.Add(heard);
if (heard.HandlesOnSpeech(this))
onSpeech.Add(heard);
for (int i = 0; i < heard.Items.Count; ++i)
{
if (heard.m_NetState != null)
hears.Add(heard);
Item item = heard.Items[i];
if (heard.HandlesOnSpeech(this))
onSpeech.Add(heard);
if (item.HandlesOnSpeech)
onSpeech.Add(item);
for (int i = 0; i < heard.Items.Count; ++i)
{
Item item = heard.Items[i];
if (item.HandlesOnSpeech)
onSpeech.Add(item);
if (item is Container container)
AddSpeechItemsFrom(onSpeech, container);
}
if (item is Container container)
AddSpeechItemsFrom(onSpeech, container);
}
}
else if (o is Item item)
@ -6244,7 +6219,7 @@ namespace Server
public void AddItem(Item item)
{
if (item == null || item.Deleted)
if (item?.Deleted != false)
return;
if (item.Parent == this)
@ -6840,7 +6815,7 @@ namespace Server
BankBox box = FindBankNoCreate();
if (box != null && box.Opened)
if (box?.Opened == true)
box.Close();
m_NetState?.ValidateAllTrades();
@ -6919,24 +6894,24 @@ namespace Server
if (ObjectPropertyList.Enabled) m.m_NetState.Send(OPLPacket);
}
if (!inOldRange && CanSee(m))
if (inOldRange || !CanSee(m))
continue;
ourState.Send(MobileIncoming.Create(ourState, this, m));
if (ourState.StygianAbyss)
{
ourState.Send(MobileIncoming.Create(ourState, this, m));
//if ( m.Poisoned )
ourState.Send(new HealthbarPoison(m));
if (ourState.StygianAbyss)
{
//if ( m.Poisoned )
ourState.Send(new HealthbarPoison(m));
//if ( m.Blessed || m.YellowHealthbar )
ourState.Send(new HealthbarYellow(m));
}
if (m.IsDeadBondedPet)
ourState.Send(new BondedStatus(0, m.Serial, 1));
if (ObjectPropertyList.Enabled) ourState.Send(m.OPLPacket);
//if ( m.Blessed || m.YellowHealthbar )
ourState.Send(new HealthbarYellow(m));
}
if (m.IsDeadBondedPet)
ourState.Send(new BondedStatus(0, m.Serial, 1));
if (ObjectPropertyList.Enabled) ourState.Send(m.OPLPacket);
}
eeable.Free();
@ -6996,10 +6971,8 @@ namespace Server
public BankBox FindBankNoCreate()
{
if (m_BankBox != null && !m_BankBox.Deleted && m_BankBox.Parent == this)
return m_BankBox;
m_BankBox = FindItemOnLayer(Layer.Bank) as BankBox;
if (m_BankBox?.Deleted != false || m_BankBox.Parent != this)
m_BankBox = FindItemOnLayer(Layer.Bank) as BankBox;
return m_BankBox;
}
@ -7021,32 +6994,32 @@ namespace Server
public void SendIncomingPacket()
{
if (m_Map != null)
{
IPooledEnumerable<NetState> eable = m_Map.GetClientsInRange(m_Location);
if (m_Map == null)
return;
foreach (NetState state in eable)
if (state.Mobile.CanSee(this))
IPooledEnumerable<NetState> eable = m_Map.GetClientsInRange(m_Location);
foreach (NetState state in eable)
if (state.Mobile.CanSee(this))
{
state.Send(MobileIncoming.Create(state, state.Mobile, this));
if (state.StygianAbyss)
{
state.Send(MobileIncoming.Create(state, state.Mobile, this));
if (m_Poison != null)
state.Send(new HealthbarPoison(this));
if (state.StygianAbyss)
{
if (m_Poison != null)
state.Send(new HealthbarPoison(this));
if (m_Blessed || m_YellowHealthbar)
state.Send(new HealthbarYellow(this));
}
if (IsDeadBondedPet)
state.Send(new BondedStatus(0, Serial, 1));
if (ObjectPropertyList.Enabled) state.Send(OPLPacket);
if (m_Blessed || m_YellowHealthbar)
state.Send(new HealthbarYellow(this));
}
eable.Free();
}
if (IsDeadBondedPet)
state.Send(new BondedStatus(0, Serial, 1));
if (ObjectPropertyList.Enabled) state.Send(OPLPacket);
}
eable.Free();
}
public bool PlaceInBackpack(Item item)
@ -7054,9 +7027,7 @@ namespace Server
if (item.Deleted)
return false;
Container pack = Backpack;
return pack != null && pack.TryDropItem(this, item, false);
return Backpack?.TryDropItem(this, item, false) == true;
}
public bool AddToBackpack(Item item)
@ -7089,10 +7060,7 @@ namespace Server
public virtual bool CheckNonlocalLift(Mobile from, Item item)
{
if (from == this || from.AccessLevel > AccessLevel && from.AccessLevel >= AccessLevel.GameMaster)
return true;
return false;
return from == this || from.AccessLevel > AccessLevel && from.AccessLevel >= AccessLevel.GameMaster;
}
public virtual bool CheckTrade(Mobile to, Item item, SecureTradeContainer cont, bool message, bool checkItems,
@ -7101,12 +7069,7 @@ namespace Server
return true;
}
public bool OpenTrade(Mobile from)
{
return OpenTrade(from, null);
}
public virtual bool OpenTrade(Mobile from, Item offer)
public virtual bool OpenTrade(Mobile from, Item offer = null)
{
if (!from.Player || !Player || !from.Alive || !Alive) return false;
@ -7138,15 +7101,10 @@ namespace Server
if (from == this)
{
Container pack = Backpack;
if (pack != null)
return dropped.DropToItem(from, pack, new Point3D(-1, -1, 0));
return false;
return pack != null && dropped.DropToItem(from, pack, new Point3D(-1, -1, 0));
}
if (from.InRange(Location, 2)) return OpenTrade(from, dropped);
return false;
return from.InRange(Location, 2) && OpenTrade(from, dropped);
}
public virtual bool CheckEquip(Item item)
@ -7267,10 +7225,7 @@ namespace Server
public virtual bool CheckNonlocalDrop(Mobile from, Item item, Item target)
{
if (from == this || from.AccessLevel > AccessLevel && from.AccessLevel >= AccessLevel.GameMaster)
return true;
return false;
return from == this || from.AccessLevel > AccessLevel && from.AccessLevel >= AccessLevel.GameMaster;
}
public virtual bool CheckItemUse(Mobile from, Item item)
@ -7299,12 +7254,12 @@ namespace Server
public virtual bool EquipItem(Item item)
{
if (item == null || item.Deleted || !item.CanEquip(this))
if (item?.Deleted != false || !item.CanEquip(this))
return false;
if (CheckEquip(item) && OnEquip(item) && item.OnEquip(this))
{
if (m_Spell != null && !m_Spell.OnCasterEquipping(item))
if (m_Spell?.OnCasterEquipping(item) == false)
return false;
//if ( m_Spell != null && m_Spell.State == SpellState.Casting )
@ -7364,6 +7319,7 @@ namespace Server
}
catch
{
// ignored
}
}
else
@ -7396,22 +7352,15 @@ namespace Server
{
}
public bool CheckAlive()
public bool CheckAlive(bool message = true)
{
return CheckAlive(true);
}
if (Alive)
return true;
public bool CheckAlive(bool message)
{
if (!Alive)
{
if (message)
LocalOverheadMessage(MessageType.Regular, 0x3B2, 1019048); // I am dead and cannot do that.
if (message)
LocalOverheadMessage(MessageType.Regular, 0x3B2, 1019048); // I am dead and cannot do that.
return false;
}
return true;
return false;
}
public void LaunchBrowser(string url)
@ -7483,9 +7432,8 @@ namespace Server
/// </summary>
public virtual void OnSingleClick(Mobile from)
{
if (Deleted)
return;
if (AccessLevel == AccessLevel.Player && DisableHiddenSelfClick && Hidden && from == this)
if (Deleted ||
AccessLevel == AccessLevel.Player && DisableHiddenSelfClick && Hidden && from == this)
return;
if (GuildClickMessage)
@ -7523,10 +7471,7 @@ namespace Server
else
hue = Notoriety.GetHue(Notoriety.Compute(from, this));
string name = Name;
if (name == null)
name = string.Empty;
string name = Name ?? string.Empty;
string prefix = "";
@ -7535,7 +7480,7 @@ namespace Server
string suffix = "";
if (ClickTitle && Title != null && Title.Length > 0)
if (ClickTitle && !string.IsNullOrEmpty(Title))
suffix = Title;
suffix = ApplyNameSuffix(suffix);
@ -7556,32 +7501,22 @@ namespace Server
public bool CheckSkill(SkillName skill, double minSkill, double maxSkill)
{
if (SkillCheckLocationHandler == null)
return false;
return SkillCheckLocationHandler(this, skill, minSkill, maxSkill);
return SkillCheckLocationHandler?.Invoke(this, skill, minSkill, maxSkill) == true;
}
public bool CheckSkill(SkillName skill, double chance)
{
if (SkillCheckDirectLocationHandler == null)
return false;
return SkillCheckDirectLocationHandler(this, skill, chance);
return SkillCheckDirectLocationHandler?.Invoke(this, skill, chance) == true;
}
public bool CheckTargetSkill(SkillName skill, object target, double minSkill, double maxSkill)
{
if (SkillCheckTargetHandler == null)
return false;
return SkillCheckTargetHandler(this, skill, target, minSkill, maxSkill);
return SkillCheckTargetHandler?.Invoke(this, skill, target, minSkill, maxSkill) == true;
}
public bool CheckTargetSkill(SkillName skill, object target, double chance)
{
if (SkillCheckDirectTargetHandler == null)
return false;
return SkillCheckDirectTargetHandler(this, skill, target, chance);
return SkillCheckDirectTargetHandler?.Invoke(this, skill, target, chance) == true;
}
public virtual void DisruptiveAction()
@ -8022,8 +7957,7 @@ namespace Server
{
private Mobile m_Mobile;
public CombatTimer(Mobile m)
: base(TimeSpan.FromSeconds(0.0), TimeSpan.FromSeconds(0.01), 0)
public CombatTimer(Mobile m) : base(TimeSpan.FromSeconds(0.0), TimeSpan.FromSeconds(0.01))
{
m_Mobile = m;
@ -8033,32 +7967,32 @@ namespace Server
protected override void OnTick()
{
if (Core.TickCount - m_Mobile.NextCombatTime >= 0)
if (Core.TickCount - m_Mobile.NextCombatTime < 0)
return;
Mobile combatant = m_Mobile.Combatant;
// If no combatant, wrong map, one of us is a ghost, or cannot see, or deleted, then stop combat
if (combatant?.Deleted != false || m_Mobile.Deleted || combatant.m_Map != m_Mobile.m_Map ||
!combatant.Alive || !m_Mobile.Alive || !m_Mobile.CanSee(combatant) || combatant.IsDeadBondedPet ||
m_Mobile.IsDeadBondedPet)
{
Mobile combatant = m_Mobile.Combatant;
m_Mobile.Combatant = null;
return;
}
// If no combatant, wrong map, one of us is a ghost, or cannot see, or deleted, then stop combat
if (combatant == null || combatant.Deleted || m_Mobile.Deleted || combatant.m_Map != m_Mobile.m_Map ||
!combatant.Alive || !m_Mobile.Alive || !m_Mobile.CanSee(combatant) || combatant.IsDeadBondedPet ||
m_Mobile.IsDeadBondedPet)
{
m_Mobile.Combatant = null;
return;
}
IWeapon weapon = m_Mobile.Weapon;
IWeapon weapon = m_Mobile.Weapon;
if (!m_Mobile.InRange(combatant, weapon.MaxRange))
return;
if (!m_Mobile.InRange(combatant, weapon.MaxRange))
return;
if (m_Mobile.InLOS(combatant))
{
weapon.OnBeforeSwing(m_Mobile,
combatant); //OnBeforeSwing for checking in regards to being hidden and whatnot
m_Mobile.RevealingAction();
m_Mobile.NextCombatTime =
Core.TickCount + (int)weapon.OnSwing(m_Mobile, combatant).TotalMilliseconds;
}
if (m_Mobile.InLOS(combatant))
{
weapon.OnBeforeSwing(m_Mobile,
combatant); //OnBeforeSwing for checking in regards to being hidden and whatnot
m_Mobile.RevealingAction();
m_Mobile.NextCombatTime =
Core.TickCount + (int)weapon.OnSwing(m_Mobile, combatant).TotalMilliseconds;
}
}
}
@ -8393,12 +8327,7 @@ namespace Server
PublicOverheadMessage(MessageType.Regular, SpeechHue, number, type, affix, args);
}
public void Say(int number)
{
Say(number, "");
}
public void Say(int number, string args)
public void Say(int number, string args = "")
{
PublicOverheadMessage(MessageType.Regular, SpeechHue, number, args);
}
@ -8413,12 +8342,7 @@ namespace Server
Emote(string.Format(format, args));
}
public void Emote(int number)
{
Emote(number, "");
}
public void Emote(int number, string args)
public void Emote(int number, string args = "")
{
PublicOverheadMessage(MessageType.Emote, EmoteHue, number, args);
}
@ -8433,12 +8357,7 @@ namespace Server
Whisper(string.Format(format, args));
}
public void Whisper(int number)
{
Whisper(number, "");
}
public void Whisper(int number, string args)
public void Whisper(int number, string args = "")
{
PublicOverheadMessage(MessageType.Whisper, WhisperHue, number, args);
}
@ -8453,12 +8372,7 @@ namespace Server
Yell(string.Format(format, args));
}
public void Yell(int number)
{
Yell(number, "");
}
public void Yell(int number, string args)
public void Yell(int number, string args = "")
{
PublicOverheadMessage(MessageType.Yell, YellHue, number, args);
}
@ -8467,12 +8381,7 @@ namespace Server
#region Gumps/Menus
public bool SendHuePicker(HuePicker p)
{
return SendHuePicker(p, false);
}
public bool SendHuePicker(HuePicker p, bool throwOnOffline)
public bool SendHuePicker(HuePicker p, bool throwOnOffline = false)
{
if (m_NetState != null)
{
@ -9739,88 +9648,64 @@ namespace Server
#region Overhead messages
public void PublicOverheadMessage(MessageType type, int hue, bool ascii, string text)
public void PublicOverheadMessage(MessageType type, int hue, bool ascii, string text, bool noLineOfSight = true)
{
PublicOverheadMessage(type, hue, ascii, text, true);
if (m_Map == null)
return;
Packet p = ascii
? (Packet)new AsciiMessage(Serial, Body, type, hue, 3, Name, text)
: new UnicodeMessage(Serial, Body, type, hue, 3, m_Language, Name, text);
p.Acquire();
IPooledEnumerable<NetState> eable = m_Map.GetClientsInRange(m_Location);
foreach (NetState state in eable)
if (state.Mobile.CanSee(this) && (noLineOfSight || state.Mobile.InLOS(this)))
state.Send(p);
Packet.Release(p);
eable.Free();
}
public void PublicOverheadMessage(MessageType type, int hue, bool ascii, string text, bool noLineOfSight)
public void PublicOverheadMessage(MessageType type, int hue, int number, string args = "", bool noLineOfSight = true)
{
if (m_Map != null)
{
Packet p = null;
if (m_Map == null)
return;
if (ascii)
p = new AsciiMessage(Serial, Body, type, hue, 3, Name, text);
else
p = new UnicodeMessage(Serial, Body, type, hue, 3, m_Language, Name, text);
Packet p = Packet.Acquire(new MessageLocalized(Serial, Body, type, hue, 3, number, Name, args));
p.Acquire();
IPooledEnumerable<NetState> eable = m_Map.GetClientsInRange(m_Location);
IPooledEnumerable<NetState> eable = m_Map.GetClientsInRange(m_Location);
foreach (NetState state in eable)
if (state.Mobile.CanSee(this) && (noLineOfSight || state.Mobile.InLOS(this)))
state.Send(p);
foreach (NetState state in eable)
if (state.Mobile.CanSee(this) && (noLineOfSight || state.Mobile.InLOS(this)))
state.Send(p);
Packet.Release(p);
Packet.Release(p);
eable.Free();
}
}
public void PublicOverheadMessage(MessageType type, int hue, int number)
{
PublicOverheadMessage(type, hue, number, "", true);
}
public void PublicOverheadMessage(MessageType type, int hue, int number, string args)
{
PublicOverheadMessage(type, hue, number, args, true);
}
public void PublicOverheadMessage(MessageType type, int hue, int number, string args, bool noLineOfSight)
{
if (m_Map != null)
{
Packet p = Packet.Acquire(new MessageLocalized(Serial, Body, type, hue, 3, number, Name, args));
IPooledEnumerable<NetState> eable = m_Map.GetClientsInRange(m_Location);
foreach (NetState state in eable)
if (state.Mobile.CanSee(this) && (noLineOfSight || state.Mobile.InLOS(this)))
state.Send(p);
Packet.Release(p);
eable.Free();
}
eable.Free();
}
public void PublicOverheadMessage(MessageType type, int hue, int number, AffixType affixType, string affix,
string args)
string args = "", bool noLineOfSight = false)
{
PublicOverheadMessage(type, hue, number, affixType, affix, args, true);
}
if (m_Map == null)
return;
public void PublicOverheadMessage(MessageType type, int hue, int number, AffixType affixType, string affix,
string args, bool noLineOfSight)
{
if (m_Map != null)
{
Packet p = Packet.Acquire(new MessageLocalizedAffix(Serial, Body, type, hue, 3, number, Name, affixType,
affix, args));
Packet p = Packet.Acquire(new MessageLocalizedAffix(Serial, Body, type, hue, 3, number, Name, affixType,
affix, args));
IPooledEnumerable<NetState> eable = m_Map.GetClientsInRange(m_Location);
IPooledEnumerable<NetState> eable = m_Map.GetClientsInRange(m_Location);
foreach (NetState state in eable)
if (state.Mobile.CanSee(this) && (noLineOfSight || state.Mobile.InLOS(this)))
state.Send(p);
foreach (NetState state in eable)
if (state.Mobile.CanSee(this) && (noLineOfSight || state.Mobile.InLOS(this)))
state.Send(p);
Packet.Release(p);
Packet.Release(p);
eable.Free();
}
eable.Free();
}
public void PrivateOverheadMessage(MessageType type, int hue, bool ascii, string text, NetState state)
@ -9848,73 +9733,58 @@ namespace Server
{
NetState ns = m_NetState;
if (ns != null)
{
if (ascii)
ns.Send(new AsciiMessage(Serial, Body, type, hue, 3, Name, text));
else
ns.Send(new UnicodeMessage(Serial, Body, type, hue, 3, m_Language, Name, text));
}
if (ns == null)
return;
if (ascii)
ns.Send(new AsciiMessage(Serial, Body, type, hue, 3, Name, text));
else
ns.Send(new UnicodeMessage(Serial, Body, type, hue, 3, m_Language, Name, text));
}
public void LocalOverheadMessage(MessageType type, int hue, int number)
public void LocalOverheadMessage(MessageType type, int hue, int number, string args = "")
{
LocalOverheadMessage(type, hue, number, "");
m_NetState?.Send(new MessageLocalized(Serial, Body, type, hue, 3, number, Name, args));
}
public void LocalOverheadMessage(MessageType type, int hue, int number, string args)
public void NonlocalOverheadMessage(MessageType type, int hue, int number, string args = "")
{
NetState ns = m_NetState;
if (m_Map == null)
return;
ns?.Send(new MessageLocalized(Serial, Body, type, hue, 3, number, Name, args));
}
Packet p = Packet.Acquire(new MessageLocalized(Serial, Body, type, hue, 3, number, Name, args));
public void NonlocalOverheadMessage(MessageType type, int hue, int number)
{
NonlocalOverheadMessage(type, hue, number, "");
}
IPooledEnumerable<NetState> eable = m_Map.GetClientsInRange(m_Location);
public void NonlocalOverheadMessage(MessageType type, int hue, int number, string args)
{
if (m_Map != null)
{
Packet p = Packet.Acquire(new MessageLocalized(Serial, Body, type, hue, 3, number, Name, args));
foreach (NetState state in eable)
if (state != m_NetState && state.Mobile.CanSee(this))
state.Send(p);
IPooledEnumerable<NetState> eable = m_Map.GetClientsInRange(m_Location);
Packet.Release(p);
foreach (NetState state in eable)
if (state != m_NetState && state.Mobile.CanSee(this))
state.Send(p);
Packet.Release(p);
eable.Free();
}
eable.Free();
}
public void NonlocalOverheadMessage(MessageType type, int hue, bool ascii, string text)
{
if (m_Map != null)
{
Packet p = null;
if (m_Map == null)
return;
if (ascii)
p = new AsciiMessage(Serial, Body, type, hue, 3, Name, text);
else
p = new UnicodeMessage(Serial, Body, type, hue, 3, Language, Name, text);
Packet p = ascii
? (Packet)new AsciiMessage(Serial, Body, type, hue, 3, Name, text)
: new UnicodeMessage(Serial, Body, type, hue, 3, Language, Name, text);
p.Acquire();
p.Acquire();
IPooledEnumerable<NetState> eable = m_Map.GetClientsInRange(m_Location);
IPooledEnumerable<NetState> eable = m_Map.GetClientsInRange(m_Location);
foreach (NetState state in eable)
if (state != m_NetState && state.Mobile.CanSee(this))
state.Send(p);
foreach (NetState state in eable)
if (state != m_NetState && state.Mobile.CanSee(this))
state.Send(p);
Packet.Release(p);
Packet.Release(p);
eable.Free();
}
eable.Free();
}
#endregion
@ -9923,47 +9793,20 @@ namespace Server
public void SendLocalizedMessage(int number)
{
NetState ns = m_NetState;
ns?.Send(MessageLocalized.InstantiateGeneric(number));
m_NetState?.Send(MessageLocalized.InstantiateGeneric(number));
}
public void SendLocalizedMessage(int number, string args)
public void SendLocalizedMessage(int number, string args, int hue = 0x3B2)
{
SendLocalizedMessage(number, args, 0x3B2);
}
public void SendLocalizedMessage(int number, string args, int hue)
{
if (hue == 0x3B2 && (args == null || args.Length == 0))
{
NetState ns = m_NetState;
ns?.Send(MessageLocalized.InstantiateGeneric(number));
}
if (hue == 0x3B2 && string.IsNullOrEmpty(args))
m_NetState?.Send(MessageLocalized.InstantiateGeneric(number));
else
{
NetState ns = m_NetState;
ns?.Send(new MessageLocalized(Serial.MinusOne, -1, MessageType.Regular, hue, 3, number, "System", args));
}
m_NetState?.Send(new MessageLocalized(Serial.MinusOne, -1, MessageType.Regular, hue, 3, number, "System", args));
}
public void SendLocalizedMessage(int number, bool append, string affix)
public void SendLocalizedMessage(int number, bool append, string affix, string args = "", int hue = 0x3B2)
{
SendLocalizedMessage(number, append, affix, "", 0x3B2);
}
public void SendLocalizedMessage(int number, bool append, string affix, string args)
{
SendLocalizedMessage(number, append, affix, args, 0x3B2);
}
public void SendLocalizedMessage(int number, bool append, string affix, string args, int hue)
{
NetState ns = m_NetState;
ns?.Send(new MessageLocalizedAffix(Serial.MinusOne, -1, MessageType.Regular, hue, 3, number, "System",
m_NetState?.Send(new MessageLocalizedAffix(Serial.MinusOne, -1, MessageType.Regular, hue, 3, number, "System",
(append ? AffixType.Append : AffixType.Prepend) | AffixType.System, affix, args));
}
@ -9983,9 +9826,7 @@ namespace Server
public void SendMessage(int hue, string text)
{
NetState ns = m_NetState;
ns?.Send(new UnicodeMessage(Serial.MinusOne, -1, MessageType.Regular, hue, 3, "ENU", "System", text));
m_NetState?.Send(new UnicodeMessage(Serial.MinusOne, -1, MessageType.Regular, hue, 3, "ENU", "System", text));
}
public void SendMessage(int hue, string format, params object[] args)
@ -10005,9 +9846,7 @@ namespace Server
public void SendAsciiMessage(int hue, string text)
{
NetState ns = m_NetState;
ns?.Send(new AsciiMessage(Serial.MinusOne, -1, MessageType.Regular, hue, 3, "System", text));
m_NetState?.Send(new AsciiMessage(Serial.MinusOne, -1, MessageType.Regular, hue, 3, "System", text));
}
public void SendAsciiMessage(int hue, string format, params object[] args)

View file

@ -35,11 +35,7 @@ namespace Server.Network
private Queue<Socket> m_Accepted;
private object m_AcceptedSyncRoot;
#if NewAsyncSockets
private SocketAsyncEventArgs m_EventArgs;
#else
private AsyncCallback m_OnAccept;
#endif
private static Socket[] m_EmptySockets = new Socket[0];
@ -57,19 +53,9 @@ namespace Server.Network
DisplayListener();
#if NewAsyncSockets
m_EventArgs = new SocketAsyncEventArgs();
m_EventArgs.Completed += Accept_Completion;
Accept_Start();
#else
m_OnAccept = new AsyncCallback( OnAccept );
try {
IAsyncResult res = m_Listener.BeginAccept( m_OnAccept, m_Listener );
} catch ( SocketException ex ) {
NetState.TraceException( ex );
} catch ( ObjectDisposedException ) {
}
#endif
}
private Socket Bind(IPEndPoint ipep)
@ -144,10 +130,9 @@ namespace Server.Network
}
}
#if NewAsyncSockets
private void Accept_Start()
{
bool result = false;
bool result;
do
{
@ -187,36 +172,6 @@ namespace Server.Network
e.AcceptSocket = null;
}
#else
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 ) {
}
}
#endif
private bool VerifySocket(Socket socket)
{
@ -299,4 +254,4 @@ namespace Server.Network
GC.SuppressFinalize(this);
}
}
}
}

View file

@ -252,7 +252,7 @@ namespace Server.Network
ThrottlePacketCallback throttler = handler.ThrottleCallback;
if (throttler != null && !throttler(ns))
if (throttler?.Invoke(ns) == false)
{
m_Throttled.Enqueue(ns);
return;
@ -260,7 +260,8 @@ namespace Server.Network
PacketReceiveProfile prof = null;
if (Core.Profiling) prof = PacketReceiveProfile.Acquire(packetID);
if (Core.Profiling)
prof = PacketReceiveProfile.Acquire(packetID);
prof?.Start();
@ -286,4 +287,4 @@ namespace Server.Network
}
}
}
}
}

View file

@ -48,11 +48,8 @@ namespace Server.Network
private byte[] m_RecvBuffer;
private SendQueue m_SendQueue;
#if NewAsyncSockets
private SocketAsyncEventArgs m_ReceiveEventArgs, m_SendEventArgs;
#else
private AsyncCallback m_OnReceive, m_OnSend;
#endif
private SocketAsyncEventArgs m_ReceiveEventArgs;
private SocketAsyncEventArgs m_SendEventArgs;
private MessagePump m_MessagePump;
private string m_ToString;
@ -451,62 +448,7 @@ namespace Server.Network
byte[] buffer = p.Compile(CompressionEnabled, out int length);
if (buffer != null)
{
if (buffer.Length <= 0 || length <= 0)
{
p.OnSend();
return;
}
PacketSendProfile prof = null;
if (Core.Profiling) prof = PacketSendProfile.Acquire(p.GetType());
prof?.Start();
PacketEncoder?.EncodeOutgoingPacket(this, ref buffer, ref length);
try
{
SendQueue.Gram gram;
lock (_sendL)
{
lock (m_SendQueue)
{
gram = m_SendQueue.Enqueue(buffer, length);
}
if (gram != null && !_sending)
{
_sending = true;
#if NewAsyncSockets
m_SendEventArgs.SetBuffer(gram.Buffer, 0, gram.Length);
Send_Start();
#else
try {
m_Socket.BeginSend(gram.Buffer, 0, gram.Length, SocketFlags.None, m_OnSend, m_Socket);
}
catch (Exception ex) {
TraceException(ex);
Dispose(false);
}
#endif
}
}
}
catch (CapacityExceededException)
{
Console.WriteLine("Client: {0}: Too much data pending, disconnecting...", this);
Dispose(false);
}
p.OnSend();
prof?.Finish(length);
}
else
if (buffer == null)
{
Console.WriteLine("Client: {0}: null buffer send, disconnecting...", this);
using (StreamWriter op = new StreamWriter("null_send.log", true))
@ -516,10 +458,53 @@ namespace Server.Network
}
Dispose();
return;
}
if (buffer.Length <= 0 || length <= 0)
{
p.OnSend();
return;
}
PacketSendProfile prof = null;
if (Core.Profiling)
prof = PacketSendProfile.Acquire(p.GetType());
prof?.Start();
PacketEncoder?.EncodeOutgoingPacket(this, ref buffer, ref length);
try
{
lock (_sendL)
{
SendQueue.Gram gram;
lock (m_SendQueue)
{
gram = m_SendQueue.Enqueue(buffer, length);
}
if (gram != null && !_sending)
{
_sending = true;
m_SendEventArgs.SetBuffer(gram.Buffer, 0, gram.Length);
Send_Start();
}
}
}
catch (CapacityExceededException)
{
Console.WriteLine("Client: {0}: Too much data pending, disconnecting...", this);
Dispose(false);
}
p.OnSend();
prof?.Finish(length);
}
#if NewAsyncSockets
public void Start()
{
m_ReceiveEventArgs = new SocketAsyncEventArgs();
@ -582,7 +567,8 @@ namespace Server.Network
return;
}
if (IsDisposing) return;
if (IsDisposing)
return;
m_NextCheckActivity = Core.TickCount + 90000;
@ -607,7 +593,7 @@ namespace Server.Network
{
try
{
bool result = false;
bool result;
do
{
@ -736,190 +722,10 @@ namespace Server.Network
return false;
}
#else
public void Start() {
m_OnReceive = new AsyncCallback( OnReceive );
m_OnSend = new AsyncCallback( OnSend );
m_Running = true;
if ( m_Socket == null || m_Paused ) {
return;
}
try {
lock ( m_AsyncLock ) {
if ( ( m_AsyncState & ( AsyncState.Pending | AsyncState.Paused ) ) == 0 ) {
InternalBeginReceive();
}
}
} catch ( Exception ex ) {
TraceException( ex );
Dispose( false );
}
}
private void InternalBeginReceive() {
m_AsyncState |= AsyncState.Pending;
m_Socket.BeginReceive( m_RecvBuffer, 0, m_RecvBuffer.Length, SocketFlags.None, m_OnReceive, m_Socket );
}
private void OnReceive( IAsyncResult asyncResult ) {
Socket s = (Socket)asyncResult.AsyncState;
try {
int byteCount = s.EndReceive( asyncResult );
if ( byteCount > 0 ) {
m_NextCheckActivity = Core.TickCount + 90000;
byte[] buffer = m_RecvBuffer;
if ( m_Encoder != null )
m_Encoder.DecodeIncomingPacket( this, ref buffer, ref byteCount );
lock ( m_Buffer )
m_Buffer.Enqueue( buffer, 0, byteCount );
m_MessagePump.OnReceive( this );
lock ( m_AsyncLock ) {
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 );
}
}
private void OnSend( IAsyncResult asyncResult ) {
Socket s = (Socket)asyncResult.AsyncState;
try {
int bytes = s.EndSend( asyncResult );
if ( bytes <= 0 ) {
Dispose( false );
return;
}
m_NextCheckActivity = Core.TickCount + 90000;
if (m_CoalesceSleep >= 0) {
Thread.Sleep(m_CoalesceSleep);
}
SendQueue.Gram gram;
lock (m_SendQueue) {
gram = m_SendQueue.Dequeue();
if (gram == null && m_SendQueue.IsFlushReady)
gram = m_SendQueue.CheckFlushReady();
}
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 (_sendL)
_sending = false;
}
} catch ( Exception ){
Dispose( false );
}
}
public static void Pause() {
m_Paused = true;
for ( int i = 0; i < m_Instances.Count; ++i ) {
NetState ns = m_Instances[i];
lock ( ns.m_AsyncLock ) {
ns.m_AsyncState |= AsyncState.Paused;
}
}
}
public static void Resume() {
m_Paused = false;
for ( int i = 0; i < m_Instances.Count; ++i ) {
NetState ns = m_Instances[i];
if ( ns.m_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 (m_Socket == null)
return false;
lock (_sendL) {
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;
m_Socket.BeginSend(gram.Buffer, 0, gram.Length, SocketFlags.None, m_OnSend, m_Socket);
return true;
} catch (Exception ex) {
TraceException(ex);
Dispose(false);
}
}
}
return false;
}
#endif
public PacketHandler GetHandler(int packetID)
{
if (ContainerGridLines)
return PacketHandlers.Get6017Handler(packetID);
return PacketHandlers.GetHandler(packetID);
return ContainerGridLines ? PacketHandlers.Get6017Handler(packetID) :
PacketHandlers.GetHandler(packetID);
}
public static void FlushAll()
@ -937,13 +743,10 @@ namespace Server.Network
public void CheckAlive(long curTicks)
{
if (Socket == null)
if (Socket == null || m_NextCheckActivity - curTicks >= 0)
return;
if (m_NextCheckActivity - curTicks >= 0) return;
Console.WriteLine("Client: {0}: Disconnecting due to inactivity...", this);
Dispose();
}
@ -966,6 +769,7 @@ namespace Server.Network
}
catch
{
// ignored
}
try
@ -974,19 +778,16 @@ namespace Server.Network
}
catch
{
// ignored
}
}
public bool IsDisposing{ get; private set; }
public void Dispose()
public virtual void Dispose(bool flush = true)
{
Dispose(true);
}
public virtual void Dispose(bool flush)
{
if (Socket == null || IsDisposing) return;
if (Socket == null || IsDisposing)
return;
IsDisposing = true;
@ -1022,13 +823,8 @@ namespace Server.Network
Buffer = null;
m_RecvBuffer = null;
#if NewAsyncSockets
m_ReceiveEventArgs = null;
m_SendEventArgs = null;
#else
m_OnReceive = null;
m_OnSend = null;
#endif
Running = false;
@ -1132,38 +928,22 @@ namespace Server.Network
public Expansion Expansion => (Expansion)ExpansionInfo.ID;
public bool SupportsExpansion(ExpansionInfo info, bool checkCoreExpansion)
public bool SupportsExpansion(ExpansionInfo info, bool checkCoreExpansion = true)
{
if (info == null || checkCoreExpansion && (int)Core.Expansion < info.ID)
return false;
if (info.RequiredClient != null)
return Version >= info.RequiredClient;
return (Flags & info.ClientFlags) != 0;
return info.RequiredClient != null ? Version >= info.RequiredClient : (Flags & info.ClientFlags) != 0;
}
public bool SupportsExpansion(Expansion ex, bool checkCoreExpansion)
public bool SupportsExpansion(Expansion ex, bool checkCoreExpansion = true)
{
return SupportsExpansion(ExpansionInfo.GetInfo(ex), checkCoreExpansion);
}
public bool SupportsExpansion(Expansion ex)
{
return SupportsExpansion(ex, true);
}
public bool SupportsExpansion(ExpansionInfo info)
{
return SupportsExpansion(info, true);
}
public int CompareTo(NetState other)
{
if (other == null)
return 1;
return m_ToString.CompareTo(other.m_ToString);
return other == null ? 1 : m_ToString.CompareTo(other.m_ToString);
}
}
}
}

View file

@ -801,6 +801,7 @@ namespace Server.Network
}
catch
{
// ignored
}
break;
@ -1025,10 +1026,7 @@ namespace Server.Network
if (!valid) return;
pvSrc.Seek(5, SeekOrigin.Current);
Mobile to = World.FindMobile(pvSrc.ReadUInt32());
if (to == null)
to = from;
Mobile to = World.FindMobile(pvSrc.ReadUInt32()) ?? from;
if (!to.AllowEquipFrom(from) || !to.EquipItem(item))
item.Bounce(from);
@ -1478,14 +1476,14 @@ namespace Server.Network
{
Mobile m = World.FindMobile(s);
if (m != null && !m.Deleted)
if (m?.Deleted == false)
from.Use(m);
}
else if (s.IsItem)
{
Item item = World.FindItem(s);
if (item != null && !item.Deleted)
if (item?.Deleted == false)
from.Use(item);
}
}
@ -1525,7 +1523,7 @@ namespace Server.Network
{
Item item = World.FindItem(s);
if (item != null && !item.Deleted && from.CanSee(item) &&
if (item?.Deleted == false && from.CanSee(item) &&
Utility.InUpdateRange(from.Location, item.GetWorldLocation()))
{
if (SingleClickProps)
@ -1705,7 +1703,7 @@ namespace Server.Network
{
Item item = World.FindItem(s);
if (item != null && !item.Deleted && from.CanSee(item) &&
if (item?.Deleted == false && from.CanSee(item) &&
Utility.InUpdateRange(from.Location, item.GetWorldLocation()))
item.SendPropertiesTo(from);
}
@ -1732,7 +1730,7 @@ namespace Server.Network
{
Item item = World.FindItem(s);
if (item != null && !item.Deleted && from.CanSee(item) &&
if (item?.Deleted == false && from.CanSee(item) &&
Utility.InUpdateRange(from.Location, item.GetWorldLocation()))
item.SendPropertiesTo(from);
}
@ -2374,13 +2372,10 @@ namespace Server.Network
bool female = genderRace % 2 != 0;
Race race = null;
Race race;
byte raceID = (byte)(genderRace < 4 ? 0 : genderRace / 2 - 1);
race = Race.Races[raceID];
if (race == null)
race = Race.DefaultRace;
race = Race.Races[raceID] ?? Race.DefaultRace;
CityInfo[] info = state.CityInfo;
IAccount a = state.Account;

View file

@ -44,18 +44,11 @@ namespace Server.Network
/// </summary>
private MemoryStream m_Stream;
/// <summary>
/// Instantiates a new PacketWriter instance with the default capacity of 4 bytes.
/// </summary>
public PacketWriter() : this(32)
{
}
/// <summary>
/// Instantiates a new PacketWriter instance with a given capacity.
/// </summary>
/// <param name="capacity">Initial capacity for the internal stream.</param>
public PacketWriter(int capacity)
public PacketWriter(int capacity = 32)
{
m_Stream = new MemoryStream(capacity);
m_Capacity = capacity;
@ -103,10 +96,7 @@ namespace Server.Network
}
}
if (pw == null)
pw = new PacketWriter(capacity);
return pw;
return pw ?? new PacketWriter(capacity);
}
public static void ReleaseInstance(PacketWriter pw)
@ -456,4 +446,4 @@ namespace Server.Network
return m_Stream.ToArray();
}
}
}
}

View file

@ -382,10 +382,7 @@ namespace Server.Network
m_Stream.Write(bis.Price);
string desc = bis.Description;
if (desc == null)
desc = "";
string desc = bis.Description ?? "";
m_Stream.Write((byte)(desc.Length + 1));
m_Stream.WriteAsciiNull(desc);
@ -466,11 +463,7 @@ namespace Server.Network
m_Stream.Write(m.Serial);
m_Stream.Write((byte)0);
int lockBits = 0;
lockBits |= (int)m.StrLock << 4;
lockBits |= (int)m.DexLock << 2;
lockBits |= (int)m.IntLock;
int lockBits = (int)m.StrLock << 4 | (int)m.DexLock << 2 | (int)m.IntLock;
m_Stream.Write((byte)lockBits);
}
@ -478,11 +471,7 @@ namespace Server.Network
public class EquipInfoAttribute
{
public EquipInfoAttribute(int number) : this(number, -1)
{
}
public EquipInfoAttribute(int number, int charges)
public EquipInfoAttribute(int number, int charges = -1)
{
Number = number;
Charges = charges;
@ -1070,7 +1059,7 @@ namespace Server.Network
// +2 - Hue
// +1 - Flags
uint serial = (uint)item.Serial.Value;
uint serial = item.Serial.Value;
int itemID = item.ItemID & 0x3FFF;
int amount = item.Amount;
Point3D loc = item.Location;
@ -2441,10 +2430,7 @@ namespace Server.Network
for (int i = 0; i < strings.Count; ++i)
{
string v = strings[i];
if (v == null)
v = string.Empty;
string v = strings[i] ?? "";
m_Strings.Write((ushort)v.Length);
m_Strings.WriteBigUniFixed(v, v.Length);
@ -2603,10 +2589,7 @@ namespace Server.Network
for (int i = 0; i < text.Count; ++i)
{
string v = text[i];
if (v == null)
v = string.Empty;
string v = text[i] ?? "";
int length = (ushort)v.Length;
@ -2639,13 +2622,11 @@ namespace Server.Network
for (int i = 0; i < text.Length; ++i)
{
string v = text[i];
string v = text[i] ?? "";
if (v == null) v = "";
ushort length = (ushort)v.Length;
int length = (ushort)v.Length;
m_Stream.Write((ushort)length);
m_Stream.Write(length);
m_Stream.WriteBigUniFixed(v, length);
}
}
@ -2774,11 +2755,7 @@ namespace Server.Network
new SeasonChange[2]
};
public SeasonChange(int season) : this(season, true)
{
}
public SeasonChange(int season, bool playSound) : base(0xBC, 3)
public SeasonChange(int season, bool playSound = true) : base(0xBC, 3)
{
m_Stream.Write((byte)season);
m_Stream.Write(playSound);
@ -2979,14 +2956,10 @@ namespace Server.Network
{
public MobileName(Mobile m) : base(0x98)
{
string name = m.Name;
if (name == null) name = "";
EnsureCapacity(37);
m_Stream.Write(m.Serial);
m_Stream.WriteAsciiFixed(name, 30);
m_Stream.WriteAsciiFixed(m.Name ?? "", 30);
}
}
@ -3020,13 +2993,10 @@ namespace Server.Network
{
public MobileStatusCompact(bool canBeRenamed, Mobile m) : base(0x11)
{
string name = m.Name;
if (name == null) name = "";
EnsureCapacity(43);
m_Stream.Write(m.Serial);
m_Stream.WriteAsciiFixed(name, 30);
m_Stream.WriteAsciiFixed(m.Name ?? "", 30);
AttributeNormalizer.WriteReverse(m_Stream, m.Hits, m.HitsMax);
@ -3044,17 +3014,16 @@ namespace Server.Network
public MobileStatusExtended(Mobile m, NetState ns) : base(0x11)
{
string name = m.Name;
if (name == null) name = "";
string name = m.Name ?? "";
int type;
if (Core.HS && ns != null && ns.ExtendedStatus)
if (Core.HS && ns?.ExtendedStatus == true)
{
type = 6;
EnsureCapacity(121);
}
else if (Core.ML && ns != null && ns.SupportsExpansion(Expansion.ML))
else if (Core.ML && ns?.SupportsExpansion(Expansion.ML) == true)
{
type = 5;
EnsureCapacity(91);
@ -3141,8 +3110,7 @@ namespace Server.Network
public MobileStatus(Mobile beholder, Mobile beheld, NetState ns) : base(0x11)
{
string name = beheld.Name;
if (name == null) name = "";
string name = beheld.Name ?? "";
int type;
@ -3151,12 +3119,12 @@ namespace Server.Network
type = 0;
EnsureCapacity(43);
}
else if (Core.HS && ns != null && ns.ExtendedStatus)
else if (Core.HS && ns?.ExtendedStatus == true)
{
type = 6;
EnsureCapacity(121);
}
else if (Core.ML && ns != null && ns.SupportsExpansion(Expansion.ML))
else if (Core.ML && ns?.SupportsExpansion(Expansion.ML) == true)
{
type = 5;
EnsureCapacity(91);
@ -3180,61 +3148,61 @@ namespace Server.Network
m_Stream.Write((byte)type);
if (type > 0)
if (type <= 0)
return;
m_Stream.Write(beheld.Female);
m_Stream.Write((short)beheld.Str);
m_Stream.Write((short)beheld.Dex);
m_Stream.Write((short)beheld.Int);
WriteAttr(beheld.Stam, beheld.StamMax);
WriteAttr(beheld.Mana, beheld.ManaMax);
m_Stream.Write(beheld.TotalGold);
m_Stream.Write((short)(Core.AOS ? beheld.PhysicalResistance : (int)(beheld.ArmorRating + 0.5)));
m_Stream.Write((short)(Mobile.BodyWeight + beheld.TotalWeight));
if (type >= 5)
{
m_Stream.Write(beheld.Female);
m_Stream.Write((short)beheld.Str);
m_Stream.Write((short)beheld.Dex);
m_Stream.Write((short)beheld.Int);
WriteAttr(beheld.Stam, beheld.StamMax);
WriteAttr(beheld.Mana, beheld.ManaMax);
m_Stream.Write(beheld.TotalGold);
m_Stream.Write((short)(Core.AOS ? beheld.PhysicalResistance : (int)(beheld.ArmorRating + 0.5)));
m_Stream.Write((short)(Mobile.BodyWeight + beheld.TotalWeight));
if (type >= 5)
{
m_Stream.Write((short)beheld.MaxWeight);
m_Stream.Write((byte)(beheld.Race.RaceID + 1)); // Would be 0x00 if it's a non-ML enabled account but...
}
m_Stream.Write((short)beheld.StatCap);
m_Stream.Write((byte)beheld.Followers);
m_Stream.Write((byte)beheld.FollowersMax);
if (type >= 4)
{
m_Stream.Write((short)beheld.FireResistance); // Fire
m_Stream.Write((short)beheld.ColdResistance); // Cold
m_Stream.Write((short)beheld.PoisonResistance); // Poison
m_Stream.Write((short)beheld.EnergyResistance); // Energy
m_Stream.Write((short)beheld.Luck); // Luck
IWeapon weapon = beheld.Weapon;
if (weapon != null)
{
weapon.GetStatusDamage(beheld, out int min, out int max);
m_Stream.Write((short)min); // Damage min
m_Stream.Write((short)max); // Damage max
}
else
{
m_Stream.Write((short)0); // Damage min
m_Stream.Write((short)0); // Damage max
}
m_Stream.Write(beheld.TithingPoints);
}
if (type >= 6)
for (int i = 0; i < 15; ++i)
m_Stream.Write((short)beheld.GetAOSStatus(i));
m_Stream.Write((short)beheld.MaxWeight);
m_Stream.Write((byte)(beheld.Race.RaceID + 1)); // Would be 0x00 if it's a non-ML enabled account but...
}
m_Stream.Write((short)beheld.StatCap);
m_Stream.Write((byte)beheld.Followers);
m_Stream.Write((byte)beheld.FollowersMax);
if (type >= 4)
{
m_Stream.Write((short)beheld.FireResistance); // Fire
m_Stream.Write((short)beheld.ColdResistance); // Cold
m_Stream.Write((short)beheld.PoisonResistance); // Poison
m_Stream.Write((short)beheld.EnergyResistance); // Energy
m_Stream.Write((short)beheld.Luck); // Luck
IWeapon weapon = beheld.Weapon;
if (weapon != null)
{
weapon.GetStatusDamage(beheld, out int min, out int max);
m_Stream.Write((short)min); // Damage min
m_Stream.Write((short)max); // Damage max
}
else
{
m_Stream.Write((short)0); // Damage min
m_Stream.Write((short)0); // Damage max
}
m_Stream.Write(beheld.TithingPoints);
}
if (type >= 6)
for (int i = 0; i < 15; ++i)
m_Stream.Write((short)beheld.GetAOSStatus(i));
}
private void WriteAttr(int current, int maximum)
@ -4501,6 +4469,7 @@ namespace Server.Network
}
catch
{
// ignored
}
}

View file

@ -219,9 +219,7 @@ namespace Server
public override void ProcessDecay()
{
Item item;
while (_decayBag.TryTake(out item))
while (_decayBag.TryTake(out Item item))
if (item.OnDecay())
item.Delete();
}

View file

@ -1,105 +1,107 @@
#region References
using System;
using System.IO;
#endregion
namespace Server
{
public static class Persistence
{
public static void Serialize(string path, Action<GenericWriter> serializer)
{
Serialize(new FileInfo(path), serializer);
}
public static void Serialize(FileInfo file, Action<GenericWriter> serializer)
{
file.Refresh();
if (file.Directory != null && !file.Directory.Exists) file.Directory.Create();
if (!file.Exists) file.Create().Close();
file.Refresh();
using (FileStream fs = file.OpenWrite())
{
BinaryFileWriter writer = new BinaryFileWriter(fs, true);
try
{
serializer(writer);
}
finally
{
writer.Flush();
writer.Close();
}
}
}
public static void Deserialize(string path, Action<GenericReader> deserializer)
{
Deserialize(path, deserializer, true);
}
public static void Deserialize(FileInfo file, Action<GenericReader> deserializer)
{
Deserialize(file, deserializer, true);
}
public static void Deserialize(string path, Action<GenericReader> deserializer, bool ensure)
{
Deserialize(new FileInfo(path), deserializer, ensure);
}
public static void Deserialize(FileInfo file, Action<GenericReader> deserializer, bool ensure)
{
file.Refresh();
if (file.Directory != null && !file.Directory.Exists)
{
if (!ensure) throw new DirectoryNotFoundException();
file.Directory.Create();
}
if (!file.Exists)
{
if (!ensure)
throw new FileNotFoundException
{
Source = file.FullName
};
file.Create().Close();
}
file.Refresh();
using (FileStream fs = file.OpenRead())
{
BinaryFileReader reader = new BinaryFileReader(new BinaryReader(fs));
try
{
deserializer(reader);
}
catch (EndOfStreamException eos)
{
if (file.Length > 0) Console.WriteLine("[Persistence]: {0}", eos);
}
catch (Exception e)
{
Console.WriteLine("[Persistence]: {0}", e);
}
finally
{
reader.Close();
}
}
}
}
}
#region References
using System;
using System.IO;
#endregion
namespace Server
{
public static class Persistence
{
public static void Serialize(string path, Action<GenericWriter> serializer)
{
Serialize(new FileInfo(path), serializer);
}
public static void Serialize(FileInfo file, Action<GenericWriter> serializer)
{
file.Refresh();
if (file.Directory?.Exists == false)
file.Directory.Create();
if (!file.Exists) file.Create().Close();
file.Refresh();
using (FileStream fs = file.OpenWrite())
{
BinaryFileWriter writer = new BinaryFileWriter(fs, true);
try
{
serializer(writer);
}
finally
{
writer.Flush();
writer.Close();
}
}
}
public static void Deserialize(string path, Action<GenericReader> deserializer)
{
Deserialize(path, deserializer, true);
}
public static void Deserialize(FileInfo file, Action<GenericReader> deserializer)
{
Deserialize(file, deserializer, true);
}
public static void Deserialize(string path, Action<GenericReader> deserializer, bool ensure)
{
Deserialize(new FileInfo(path), deserializer, ensure);
}
public static void Deserialize(FileInfo file, Action<GenericReader> deserializer, bool ensure)
{
file.Refresh();
if (file.Directory?.Exists == false)
{
if (!ensure)
throw new DirectoryNotFoundException();
file.Directory.Create();
}
if (!file.Exists)
{
if (!ensure)
throw new FileNotFoundException
{
Source = file.FullName
};
file.Create().Close();
}
file.Refresh();
using (FileStream fs = file.OpenRead())
{
BinaryFileReader reader = new BinaryFileReader(new BinaryReader(fs));
try
{
deserializer(reader);
}
catch (EndOfStreamException eos)
{
if (file.Length > 0) Console.WriteLine("[Persistence]: {0}", eos);
}
catch (Exception e)
{
Console.WriteLine("[Persistence]: {0}", e);
}
finally
{
reader.Close();
}
}
}
}
}

View file

@ -94,16 +94,16 @@ namespace Server
if (Insensitive.Equals(m_RaceNames[i], value))
return m_RaceValues[i];
if (int.TryParse(value, out int index))
if (index >= 0 && index < Races.Length && Races[index] != null)
return Races[index];
if (int.TryParse(value, out int index) && index >= 0 && index < Races.Length &&
Races[index] != null)
return Races[index];
throw new ArgumentException("Invalid race name");
}
private static void CheckNamesAndValues()
{
if (m_RaceNames != null && m_RaceNames.Length == AllRaces.Count)
if (m_RaceNames?.Length == AllRaces.Count)
return;
m_RaceNames = new string[AllRaces.Count];
@ -182,4 +182,4 @@ namespace Server
return female ? FemaleGhostBody : MaleGhostBody;
}
}
}
}

View file

@ -99,7 +99,7 @@ namespace Server
ValoriaShips
}
public class Region : IComparable
public class Region : IComparable<Region>
{
public static readonly int DefaultPriority = 50;
@ -249,14 +249,11 @@ namespace Server
public bool IsDefault => Map.DefaultRegion == this;
public virtual MusicName DefaultMusic => Parent?.Music ?? MusicName.Invalid;
int IComparable.CompareTo(object obj)
public int CompareTo(Region reg)
{
if (obj == null)
if (reg == null)
return 1;
if (!(obj is Region reg))
throw new ArgumentException("obj is not a Region", nameof(obj));
// Dynamic regions go first
if (Dynamic)
{
@ -493,15 +490,14 @@ namespace Server
{
List<Mobile> list = new List<Mobile>();
if (Sectors != null)
for (int i = 0; i < Sectors.Length; i++)
{
Sector sector = Sectors[i];
for (int i = 0; i < Sectors?.Length; i++)
{
Sector sector = Sectors[i];
foreach (Mobile player in sector.Players)
if (player.Region.IsPartOf(this))
list.Add(player);
}
foreach (Mobile player in sector.Players)
if (player.Region.IsPartOf(this))
list.Add(player);
}
return list;
}
@ -510,16 +506,14 @@ namespace Server
{
int count = 0;
if (Sectors != null)
for (int i = 0; i < Sectors.Length; i++)
{
Sector sector = Sectors[i];
foreach (Mobile player in sector.Players)
if (player.Region.IsPartOf(this))
count++;
}
for (int i = 0; i < Sectors?.Length; i++)
{
Sector sector = Sectors[i];
foreach (Mobile player in sector.Players)
if (player.Region.IsPartOf(this))
count++;
}
return count;
}
@ -527,16 +521,14 @@ namespace Server
{
List<Mobile> list = new List<Mobile>();
if (Sectors != null)
for (int i = 0; i < Sectors.Length; i++)
{
Sector sector = Sectors[i];
foreach (Mobile mobile in sector.Mobiles)
if (mobile.Region.IsPartOf(this))
list.Add(mobile);
}
for (int i = 0; i < Sectors?.Length; i++)
{
Sector sector = Sectors[i];
foreach (Mobile mobile in sector.Mobiles)
if (mobile.Region.IsPartOf(this))
list.Add(mobile);
}
return list;
}
@ -544,15 +536,14 @@ namespace Server
{
int count = 0;
if (Sectors != null)
for (int i = 0; i < Sectors.Length; i++)
{
Sector sector = Sectors[i];
for (int i = 0; i < Sectors?.Length; i++)
{
Sector sector = Sectors[i];
foreach (Mobile mobile in sector.Mobiles)
if (mobile.Region.IsPartOf(this))
count++;
}
foreach (Mobile mobile in sector.Mobiles)
if (mobile.Region.IsPartOf(this))
count++;
}
return count;
}
@ -599,12 +590,12 @@ namespace Server
public virtual Type GetResource(Type type)
{
return Parent != null ? Parent.GetResource(type) : type;
return Parent?.GetResource(type) ?? type;
}
public virtual bool CanUseStuckMenu(Mobile m)
{
return Parent == null || Parent.CanUseStuckMenu(m);
return Parent?.CanUseStuckMenu(m) != false;
}
public virtual void OnAggressed(Mobile aggressor, Mobile aggressed, bool criminal)
@ -629,39 +620,37 @@ namespace Server
public virtual bool OnTarget(Mobile m, Target t, object o)
{
return Parent == null || Parent.OnTarget(m, t, o);
return Parent?.OnTarget(m, t, o) != false;
}
public virtual bool OnCombatantChange(Mobile m, Mobile Old, Mobile New)
{
return Parent == null || Parent.OnCombatantChange(m, Old, New);
return Parent?.OnCombatantChange(m, Old, New) != false;
}
public virtual bool AllowHousing(Mobile from, Point3D p)
{
return Parent == null || Parent.AllowHousing(from, p);
return Parent?.AllowHousing(from, p) != false;
}
public virtual bool SendInaccessibleMessage(Item item, Mobile from)
{
return Parent != null && Parent.SendInaccessibleMessage(item, from);
return Parent?.SendInaccessibleMessage(item, from) == true;
}
public virtual bool CheckAccessibility(Item item, Mobile from)
{
return Parent == null || Parent.CheckAccessibility(item, from);
return Parent?.CheckAccessibility(item, from) != false;
}
public virtual bool OnDecay(Item item)
{
return Parent == null || Parent.OnDecay(item);
return Parent?.OnDecay(item) != false;
}
public virtual bool AllowHarmful(Mobile from, Mobile target)
{
return Parent?.AllowHarmful(from, target) == true ||
Mobile.AllowHarmfulHandler == null ||
Mobile.AllowHarmfulHandler(from, target);
return Parent?.AllowHarmful(from, target) ?? Mobile.AllowHarmfulHandler?.Invoke(from, target) ?? true;
}
public virtual void OnCriminalAction(Mobile m, bool message)
@ -674,9 +663,8 @@ namespace Server
public virtual bool AllowBeneficial(Mobile from, Mobile target)
{
return Parent?.AllowBeneficial(from, target) == true ||
Mobile.AllowBeneficialHandler == null ||
Mobile.AllowBeneficialHandler(from, target);
return Parent?.AllowBeneficial(from, target) ??
Mobile.AllowBeneficialHandler?.Invoke(from, target) ?? true;
}
public virtual void OnBeneficialAction(Mobile helper, Mobile target)
@ -701,12 +689,12 @@ namespace Server
public virtual bool OnSkillUse(Mobile m, int Skill)
{
return Parent == null || Parent.OnSkillUse(m, Skill);
return Parent?.OnSkillUse(m, Skill) != false;
}
public virtual bool OnBeginSpellCast(Mobile m, ISpell s)
{
return Parent == null || Parent.OnBeginSpellCast(m, s);
return Parent?.OnBeginSpellCast(m, s) != false;
}
public virtual void OnSpellCast(Mobile m, ISpell s)
@ -716,12 +704,12 @@ namespace Server
public virtual bool OnResurrect(Mobile m)
{
return Parent == null || Parent.OnResurrect(m);
return Parent?.OnResurrect(m) != false;
}
public virtual bool OnBeforeDeath(Mobile m)
{
return Parent == null || Parent.OnBeforeDeath(m);
return Parent?.OnBeforeDeath(m) != false;
}
public virtual void OnDeath(Mobile m)
@ -731,27 +719,27 @@ namespace Server
public virtual bool OnDamage(Mobile m, ref int Damage)
{
return Parent == null || Parent.OnDamage(m, ref Damage);
return Parent?.OnDamage(m, ref Damage) != false;
}
public virtual bool OnHeal(Mobile m, ref int Heal)
{
return Parent == null || Parent.OnHeal(m, ref Heal);
return Parent?.OnHeal(m, ref Heal) != false;
}
public virtual bool OnDoubleClick(Mobile m, object o)
{
return Parent == null || Parent.OnDoubleClick(m, o);
return Parent?.OnDoubleClick(m, o) != false;
}
public virtual bool OnSingleClick(Mobile m, object o)
{
return Parent == null || Parent.OnSingleClick(m, o);
return Parent?.OnSingleClick(m, o) != false;
}
public virtual bool AllowSpawn()
{
return Parent == null || Parent.AllowSpawn();
return Parent?.AllowSpawn() != false;
}
public virtual void AlterLightLevel(Mobile m, ref int global, ref int personal)
@ -763,9 +751,8 @@ namespace Server
{
if (Parent != null)
return Parent.GetLogoutDelay(m);
if (m.AccessLevel > AccessLevel.Player)
return StaffLogoutDelay;
return DefaultLogoutDelay;
return m.AccessLevel > AccessLevel.Player ? StaffLogoutDelay : DefaultLogoutDelay;
}

View file

@ -364,6 +364,7 @@ namespace Server
}
catch
{
// ignored
}
assembly = results.CompiledAssembly;

View file

@ -25,7 +25,7 @@ using Server.Network;
namespace Server
{
public class RegionRect : IComparable
public class RegionRect : IComparable<RegionRect>
{
private Rectangle3D m_Rect;
@ -39,15 +39,9 @@ namespace Server
public Rectangle3D Rect => m_Rect;
int IComparable.CompareTo(object obj)
public int CompareTo(RegionRect regRect)
{
if (obj == null)
return 1;
if (!(obj is RegionRect regRect))
throw new ArgumentException("obj is not a RegionRect", nameof(obj));
return ((IComparable)Region).CompareTo(regRect.Region);
return regRect == null ? 1 : Region.CompareTo(regRect.Region);
}
public bool Contains(Point3D loc)
@ -81,71 +75,17 @@ namespace Server
m_Active = false;
}
public List<RegionRect> RegionRects
{
get
{
if (m_RegionRects == null)
return m_DefaultRectList;
public List<RegionRect> RegionRects => m_RegionRects ?? m_DefaultRectList;
return m_RegionRects;
}
}
public List<BaseMulti> Multis => m_Multis ?? m_DefaultMultiList;
public List<BaseMulti> Multis
{
get
{
if (m_Multis == null)
return m_DefaultMultiList;
public List<Mobile> Mobiles => m_Mobiles ?? m_DefaultMobileList;
return m_Multis;
}
}
public List<Item> Items => m_Items ?? m_DefaultItemList;
public List<Mobile> Mobiles
{
get
{
if (m_Mobiles == null)
return m_DefaultMobileList;
public List<NetState> Clients => m_Clients ?? m_DefaultClientList;
return m_Mobiles;
}
}
public List<Item> Items
{
get
{
if (m_Items == null)
return m_DefaultItemList;
return m_Items;
}
}
public List<NetState> Clients
{
get
{
if (m_Clients == null)
return m_DefaultClientList;
return m_Clients;
}
}
public List<Mobile> Players
{
get
{
if (m_Players == null)
return m_DefaultMobileList;
return m_Players;
}
}
public List<Mobile> Players => m_Players ?? m_DefaultMobileList;
public bool Active => m_Active && Owner != Map.Internal;
@ -314,4 +254,4 @@ namespace Server
}
}
}
}
}

View file

@ -39,11 +39,11 @@ namespace Server
From = new SecureTradeInfo(this, from, new SecureTradeContainer(this));
To = new SecureTradeInfo(this, to, new SecureTradeContainer(this));
bool from6017 = from.NetState != null && from.NetState.ContainerGridLines;
bool to6017 = to.NetState != null && to.NetState.ContainerGridLines;
bool from6017 = from.NetState?.ContainerGridLines == true;
bool to6017 = to.NetState?.ContainerGridLines == true;
bool from704565 = from.NetState != null && from.NetState.NewSecureTrading;
bool to704565 = to.NetState != null && to.NetState.NewSecureTrading;
bool from704565 = from.NetState?.NewSecureTrading == true;
bool to704565 = to.NetState?.NewSecureTrading == true;
from.Send(new MobileStatus(from, to));
from.Send(new UpdateSecureTrade(From.Container, false, false));
@ -364,7 +364,7 @@ namespace Server
Mobile.AddItem(Container);
VirtualCheck = new VirtualCheck(0, 0);
VirtualCheck = new VirtualCheck();
Container.DropItem(VirtualCheck);
}
@ -403,4 +403,4 @@ namespace Server
IsDisposed = true;
}
}
}
}

View file

@ -19,7 +19,6 @@
***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
@ -561,7 +560,7 @@ namespace Server
public override void WriteEntity(IEntity value)
{
if (value == null || value.Deleted)
if (value?.Deleted != false)
Write(Serial.MinusOne);
else
Write(value.Serial);
@ -569,7 +568,7 @@ namespace Server
public override void Write(Item value)
{
if (value == null || value.Deleted)
if (value?.Deleted != false)
Write(Serial.MinusOne);
else
Write(value.Serial);
@ -577,7 +576,7 @@ namespace Server
public override void Write(Mobile value)
{
if (value == null || value.Deleted)
if (value?.Deleted != false)
Write(Serial.MinusOne);
else
Write(value.Serial);
@ -1461,7 +1460,7 @@ namespace Server
public override void WriteEntity(IEntity value)
{
if (value == null || value.Deleted)
if (value?.Deleted != false)
Write(Serial.MinusOne);
else
Write(value.Serial);
@ -1469,7 +1468,7 @@ namespace Server
public override void Write(Item value)
{
if (value == null || value.Deleted)
if (value?.Deleted != false)
Write(Serial.MinusOne);
else
Write(value.Serial);
@ -1477,7 +1476,7 @@ namespace Server
public override void Write(Mobile value)
{
if (value == null || value.Deleted)
if (value?.Deleted != false)
Write(Serial.MinusOne);
else
Write(value.Serial);
@ -1735,7 +1734,7 @@ namespace Server
mem = m_Owner.m_WriteQueue.Dequeue();
}
if (mem != null && mem.Length > 0)
if (mem?.Length > 0)
mem.WriteTo(m_Owner.m_File);
} while (lastCount > 1);

View file

@ -42,7 +42,7 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>..\</OutputPath>
<DefineConstants>TRACE;DEBUG;NEWTIMERS;NEWPARENT;NewAsyncSockets</DefineConstants>
<DefineConstants>TRACE;DEBUG;NEWTIMERS</DefineConstants>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
@ -53,7 +53,7 @@
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<OutputPath>..\</OutputPath>
<DefineConstants>TRACE;NEWTIMERS;NEWPARENT;NewAsyncSockets</DefineConstants>
<DefineConstants>TRACE;NEWTIMERS</DefineConstants>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
@ -66,7 +66,7 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>..\</OutputPath>
<DefineConstants>TRACE;DEBUG;NEWTIMERS,NEWPARENT;NewAsyncSockets</DefineConstants>
<DefineConstants>TRACE;DEBUG;NEWTIMERS</DefineConstants>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
@ -77,7 +77,7 @@
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>..\</OutputPath>
<DefineConstants>TRACE;NEWTIMERS,NEWPARENT;NewAsyncSockets</DefineConstants>
<DefineConstants>TRACE;NEWTIMERS</DefineConstants>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
@ -260,4 +260,4 @@
</PropertyGroup>
<Error Condition="!Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
</Target>
</Project>
</Project>

View file

@ -24,12 +24,7 @@ namespace Server.Targeting
{
public abstract class MultiTarget : Target
{
protected MultiTarget(int multiID, Point3D offset)
: this(multiID, offset, 10, true, TargetFlags.None)
{
}
protected MultiTarget(int multiID, Point3D offset, int range, bool allowGround, TargetFlags flags)
protected MultiTarget(int multiID, Point3D offset, int range = 10, bool allowGround = true, TargetFlags flags = TargetFlags.None)
: base(range, allowGround, flags)
{
MultiID = multiID;
@ -47,4 +42,4 @@ namespace Server.Targeting
return new MultiTargetReq(this);
}
}
}
}

View file

@ -21,6 +21,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
@ -52,7 +53,7 @@ namespace Server
private StaticTile[] m_TileBuffer = new StaticTile[128];
private TileList m_TilesList = new TileList();
private int m_Width, m_Height;
// private int m_Width, m_Height;
public TileMatrix(Map owner, int fileIndex, int mapID, int width, int height)
{
@ -77,8 +78,8 @@ namespace Server
}
m_FileIndex = fileIndex;
m_Width = width;
m_Height = height;
// m_Width = width;
// m_Height = height;
BlockWidth = width >> 3;
BlockHeight = height >> 3;
@ -212,42 +213,37 @@ namespace Server
StaticTile[][][] tiles = m_StaticTiles[x][y];
if (tiles == null)
if (tiles != null)
return tiles;
lock (m_FileShare)
{
lock (m_FileShare)
for (int i = 0; tiles == null && i < m_FileShare.Count; ++i)
{
for (int i = 0; tiles == null && i < m_FileShare.Count; ++i)
TileMatrix shared = m_FileShare[i];
lock (shared)
{
TileMatrix shared = m_FileShare[i];
lock (shared)
if (x >= 0 && x < shared.BlockWidth && y >= 0 && y < shared.BlockHeight)
{
if (x >= 0 && x < shared.BlockWidth && y >= 0 && y < shared.BlockHeight)
StaticTile[][][][] theirTiles = shared.m_StaticTiles[x];
if (theirTiles != null)
tiles = theirTiles[y];
if (tiles != null)
{
StaticTile[][][][] theirTiles = shared.m_StaticTiles[x];
int[] theirBits = shared.m_StaticPatches[x];
if (theirTiles != null)
tiles = theirTiles[y];
if (tiles != null)
{
int[] theirBits = shared.m_StaticPatches[x];
if (theirBits != null && (theirBits[y >> 5] & (1 << (y & 0x1F))) != 0)
tiles = null;
}
if (theirBits != null && (theirBits[y >> 5] & (1 << (y & 0x1F))) != 0)
tiles = null;
}
}
}
}
if (tiles == null)
tiles = ReadStaticBlock(x, y);
m_StaticTiles[x][y] = tiles;
}
return tiles;
return m_StaticTiles[x][y] = tiles ?? ReadStaticBlock(x, y);
}
public StaticTile[] GetStaticTiles(int x, int y)
@ -262,34 +258,27 @@ namespace Server
{
StaticTile[][][] tiles = GetStaticBlock(x >> 3, y >> 3);
if (multis)
{
IPooledEnumerable<StaticTile[]> eable = m_Owner.GetMultiTilesAt(x, y);
if (!multis)
return tiles[x & 0x7][y & 0x7];
if (eable == Map.NullEnumerable<StaticTile[]>.Instance)
return tiles[x & 0x7][y & 0x7];
IPooledEnumerable<StaticTile[]> eable = m_Owner.GetMultiTilesAt(x, y);
bool any = false;
if (eable == Map.NullEnumerable<StaticTile[]>.Instance)
return tiles[x & 0x7][y & 0x7];
foreach (StaticTile[] multiTiles in eable)
{
if (!any)
any = true;
bool any = false;
m_TilesList.AddRange(multiTiles);
}
m_TilesList.AddRange(eable.SelectMany(t => { any = true; return t; }).ToArray());
eable.Free();
eable.Free();
if (!any)
return tiles[x & 0x7][y & 0x7];
if (!any)
return tiles[x & 0x7][y & 0x7];
m_TilesList.AddRange(tiles[x & 0x7][y & 0x7]);
m_TilesList.AddRange(tiles[x & 0x7][y & 0x7]);
return m_TilesList.ToArray();
}
return m_TilesList.ToArray();
return tiles[x & 0x7][y & 0x7];
}
[MethodImpl(MethodImplOptions.Synchronized)]
@ -320,49 +309,42 @@ namespace Server
LandTile[] tiles = m_LandTiles[x][y];
if (tiles == null)
if (tiles != null)
return tiles;
lock (m_FileShare)
{
lock (m_FileShare)
for (int i = 0; tiles == null && i < m_FileShare.Count; ++i)
{
for (int i = 0; tiles == null && i < m_FileShare.Count; ++i)
TileMatrix shared = m_FileShare[i];
lock (shared)
{
TileMatrix shared = m_FileShare[i];
lock (shared)
if (x >= 0 && x < shared.BlockWidth && y >= 0 && y < shared.BlockHeight)
{
if (x >= 0 && x < shared.BlockWidth && y >= 0 && y < shared.BlockHeight)
LandTile[][] theirTiles = shared.m_LandTiles[x];
if (theirTiles != null)
tiles = theirTiles[y];
if (tiles != null)
{
LandTile[][] theirTiles = shared.m_LandTiles[x];
int[] theirBits = shared.m_LandPatches[x];
if (theirTiles != null)
tiles = theirTiles[y];
if (tiles != null)
{
int[] theirBits = shared.m_LandPatches[x];
if (theirBits != null && (theirBits[y >> 5] & (1 << (y & 0x1F))) != 0)
tiles = null;
}
if (theirBits != null && (theirBits[y >> 5] & (1 << (y & 0x1F))) != 0)
tiles = null;
}
}
}
}
if (tiles == null)
tiles = ReadLandBlock(x, y);
m_LandTiles[x][y] = tiles;
}
return tiles;
return m_LandTiles[x][y] = tiles ?? ReadLandBlock(x, y);
}
public LandTile GetLandTile(int x, int y)
{
LandTile[] tiles = GetLandBlock(x >> 3, y >> 3);
return tiles[((y & 0x7) << 3) + (x & 0x7)];
return GetLandBlock(x >> 3, y >> 3)[((y & 0x7) << 3) + (x & 0x7)];
}
[MethodImpl(MethodImplOptions.Synchronized)]
@ -375,7 +357,8 @@ namespace Server
int lookup = IndexReader.ReadInt32();
int length = IndexReader.ReadInt32();
if (lookup < 0 || length <= 0) return EmptyStaticBlock;
if (lookup < 0 || length <= 0)
return EmptyStaticBlock;
int count = length / 7;

View file

@ -62,11 +62,7 @@ namespace Server
{
}
public Timer(TimeSpan delay, TimeSpan interval) : this(delay, interval, 0)
{
}
public Timer(TimeSpan delay, TimeSpan interval, int count)
public Timer(TimeSpan delay, TimeSpan interval, int count = 0)
{
m_Delay = (long)delay.TotalMilliseconds;
m_Interval = (long)interval.TotalMilliseconds;
@ -378,10 +374,6 @@ namespace Server
public void TimerMain()
{
long now;
int i, j;
bool loaded;
while (!Core.Closing)
{
if (World.Loading || World.Saving)
@ -392,17 +384,17 @@ namespace Server
ProcessChanged();
loaded = false;
bool loaded = false;
for (i = 0; i < m_Timers.Length; i++)
for (int i = 0; i < m_Timers.Length; i++)
{
now = Core.TickCount;
long now = Core.TickCount;
if (now < m_NextPriorities[i])
break;
m_NextPriorities[i] = now + m_PriorityDelays[i];
for (j = 0; j < m_Timers[i].Count; j++)
for (int j = 0; j < m_Timers[i].Count; j++)
{
Timer t = m_Timers[i][j];
@ -501,11 +493,7 @@ namespace Server
{
Timer t = new DelayCallTimer(delay, interval, count, callback);
if (count == 1)
t.Priority = ComputePriority(delay);
else
t.Priority = ComputePriority(interval);
t.Priority = ComputePriority(count == 1 ? delay : interval);
t.Start();
return t;

View file

@ -19,7 +19,6 @@
***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
@ -132,10 +131,7 @@ namespace Server
public static string Intern(string str)
{
if (str == null)
return null;
return str.Length == 0 ? string.Empty : string.Intern(str);
return str == null ? null : str.Length == 0 ? string.Empty : string.Intern(str);
}
public static void Intern(ref string str)
@ -501,7 +497,7 @@ namespace Server
}
else
{
valid = false; //high & lowpart would be 0 if it got to here.
valid = false; //high & lowp art would be 0 if it got to here.
}
}
}
@ -560,9 +556,7 @@ namespace Server
return Direction.Right;
}
if (dy > 0)
return Direction.Left;
return Direction.Up;
return dy > 0 ? Direction.Left : Direction.Up;
}
/* Should probably be rewritten to use an ITile interface
@ -614,12 +608,7 @@ namespace Server
}
*/
public static object GetArrayCap(Array array, int index)
{
return GetArrayCap(array, index, null);
}
public static object GetArrayCap(Array array, int index, object emptyValue)
public static object GetArrayCap(Array array, int index, object emptyValue = null)
{
if (array.Length > 0)
{
@ -791,18 +780,13 @@ namespace Server
return num < bound2 + allowance && num > bound1 - allowance;
}
public static void AssignRandomHair(Mobile m)
{
AssignRandomHair(m, true);
}
public static void AssignRandomHair(Mobile m, int hue)
{
m.HairItemID = m.Race.RandomHair(m);
m.HairHue = hue;
}
public static void AssignRandomHair(Mobile m, bool randomHue)
public static void AssignRandomHair(Mobile m, bool randomHue = true)
{
m.HairItemID = m.Race.RandomHair(m);
@ -810,18 +794,13 @@ namespace Server
m.HairHue = m.Race.RandomHairHue();
}
public static void AssignRandomFacialHair(Mobile m)
{
AssignRandomFacialHair(m, true);
}
public static void AssignRandomFacialHair(Mobile m, int hue)
{
m.FacialHairItemID = m.Race.RandomFacialHair(m);
m.FacialHairHue = hue;
}
public static void AssignRandomFacialHair(Mobile m, bool randomHue)
public static void AssignRandomFacialHair(Mobile m, bool randomHue = true)
{
m.FacialHairItemID = m.Race.RandomFacialHair(m);
@ -979,12 +958,7 @@ namespace Server
public static string GetAttribute(XmlElement node, string attributeName, string defaultValue = null)
{
if (node == null)
return defaultValue;
XmlAttribute attr = node.Attributes[attributeName];
return attr == null ? defaultValue : attr.Value;
return node?.Attributes[attributeName]?.Value ?? defaultValue;
}
public static string GetText(XmlElement node, string defaultValue)
@ -1237,9 +1211,8 @@ namespace Server
{
if (hue < 2)
return 2;
if (hue > 1001)
return 1001;
return hue;
return hue > 1001 ? 1001 : hue;
}
/// <summary>
@ -1255,10 +1228,8 @@ namespace Server
/// </summary>
public static int RandomBrightHue()
{
if (RandomDouble() < 0.1)
return RandomList(0x62, 0x71);
return RandomList(0x03, 0x0D, 0x13, 0x1C, 0x21, 0x30, 0x37, 0x3A, 0x44, 0x59);
return RandomDouble() < 0.1 ? RandomList(0x62, 0x71) :
RandomList(0x03, 0x0D, 0x13, 0x1C, 0x21, 0x30, 0x37, 0x3A, 0x44, 0x59);
}
#endregion

View file

@ -46,7 +46,7 @@ namespace Server
public static readonly string GuildIndexPath = Path.Combine("Saves/Guilds/", "Guilds.idx");
public static readonly string GuildDataPath = Path.Combine("Saves/Guilds/", "Guilds.bin");
private static readonly Type[] m_SerialTypeArray = new Type[] { typeof(Serial) };
private static readonly Type[] m_SerialTypeArray = { typeof(Serial) };
internal static int m_Saves;
@ -558,12 +558,9 @@ namespace Server
private static void AppendSafetyLog(string action, IEntity entity)
{
string message = string.Format("Warning: Attempted to {1} {2} during world save." +
"{0}This action could cause inconsistent state." +
"{0}It is strongly advised that the offending scripts be corrected.",
Environment.NewLine,
action, entity
);
string message = $"Warning: Attempted to {action} {entity} during world save." +
$"{Environment.NewLine}This action could cause inconsistent state." +
$"{Environment.NewLine}It is strongly advised that the offending scripts be corrected.";
Console.WriteLine(message);