Core/Refactor: Part 2

This commit is contained in:
hondacrx
2018-05-07 22:07:35 -04:00
parent 216db1c23a
commit 9b40067017
93 changed files with 321 additions and 388 deletions
+1 -1
View File
@@ -466,7 +466,7 @@ namespace BNetServer.Networking
{ {
var realmListTicketClientInformation = Json.CreateObject<RealmListTicketClientInformation>(clientInfo.BlobValue.ToStringUtf8(), true); var realmListTicketClientInformation = Json.CreateObject<RealmListTicketClientInformation>(clientInfo.BlobValue.ToStringUtf8(), true);
clientInfoOk = true; clientInfoOk = true;
_clientSecret.AddRange(realmListTicketClientInformation.Info.Secret.Select(x => Convert.ToByte(x)).ToArray()); _clientSecret.AddRange(realmListTicketClientInformation.Info.Secret.Select(Convert.ToByte).ToArray());
} }
if (!clientInfoOk) if (!clientInfoOk)
+61 -61
View File
@@ -29,13 +29,13 @@ namespace System.Collections
} }
Contract.EndContractBlock(); Contract.EndContractBlock();
m_array = new uint[GetArrayLength(length, BitsPerInt32)]; _mArray = new uint[GetArrayLength(length, BitsPerInt32)];
m_length = length; _mLength = length;
uint fillValue = defaultValue ? 0xffffffff : 0; uint fillValue = defaultValue ? 0xffffffff : 0;
for (int i = 0; i < m_array.Length; i++) for (int i = 0; i < _mArray.Length; i++)
{ {
m_array[i] = fillValue; _mArray[i] = fillValue;
} }
_version = 0; _version = 0;
@@ -54,10 +54,10 @@ namespace System.Collections
throw new ArgumentException(); throw new ArgumentException();
} }
m_array = new uint[values.Length]; _mArray = new uint[values.Length];
m_length = values.Length * BitsPerInt32; _mLength = values.Length * BitsPerInt32;
Array.Copy(values, m_array, values.Length); Array.Copy(values, _mArray, values.Length);
_version = 0; _version = 0;
} }
@@ -70,11 +70,11 @@ namespace System.Collections
} }
Contract.EndContractBlock(); Contract.EndContractBlock();
int arrayLength = GetArrayLength(bits.m_length, BitsPerInt32); int arrayLength = GetArrayLength(bits._mLength, BitsPerInt32);
m_array = new uint[arrayLength]; _mArray = new uint[arrayLength];
m_length = bits.m_length; _mLength = bits._mLength;
Array.Copy(bits.m_array, m_array, arrayLength); Array.Copy(bits._mArray, _mArray, arrayLength);
_version = bits._version; _version = bits._version;
} }
@@ -99,7 +99,7 @@ namespace System.Collections
} }
Contract.EndContractBlock(); Contract.EndContractBlock();
return (Convert.ToInt64(m_array[index / 32]) & (1 << (index % 32))) != 0; return (Convert.ToInt64(_mArray[index / 32]) & (1 << (index % 32))) != 0;
} }
public void Set(int index, bool value) public void Set(int index, bool value)
@@ -112,11 +112,11 @@ namespace System.Collections
if (value) if (value)
{ {
m_array[index / 32] |= (1u << (index % 32)); _mArray[index / 32] |= (1u << (index % 32));
} }
else else
{ {
m_array[index / 32] &= ~(1u << (index % 32)); _mArray[index / 32] &= ~(1u << (index % 32));
} }
_version++; _version++;
@@ -125,10 +125,10 @@ namespace System.Collections
public void SetAll(bool value) public void SetAll(bool value)
{ {
uint fillValue = value ? 0xffffffff : 0u; uint fillValue = value ? 0xffffffff : 0u;
int ints = GetArrayLength(m_length, BitsPerInt32); int ints = GetArrayLength(_mLength, BitsPerInt32);
for (int i = 0; i < ints; i++) for (int i = 0; i < ints; i++)
{ {
m_array[i] = fillValue; _mArray[i] = fillValue;
} }
_version++; _version++;
@@ -142,10 +142,10 @@ namespace System.Collections
throw new ArgumentException(); throw new ArgumentException();
Contract.EndContractBlock(); Contract.EndContractBlock();
int ints = GetArrayLength(m_length, BitsPerInt32); int ints = GetArrayLength(_mLength, BitsPerInt32);
for (int i = 0; i < ints; i++) for (int i = 0; i < ints; i++)
{ {
m_array[i] &= value.m_array[i]; _mArray[i] &= value._mArray[i];
} }
_version++; _version++;
@@ -160,10 +160,10 @@ namespace System.Collections
throw new ArgumentException(); throw new ArgumentException();
Contract.EndContractBlock(); Contract.EndContractBlock();
int ints = GetArrayLength(m_length, BitsPerInt32); int ints = GetArrayLength(_mLength, BitsPerInt32);
for (int i = 0; i < ints; i++) for (int i = 0; i < ints; i++)
{ {
m_array[i] |= value.m_array[i]; _mArray[i] |= value._mArray[i];
} }
_version++; _version++;
@@ -178,10 +178,10 @@ namespace System.Collections
throw new ArgumentException(); throw new ArgumentException();
Contract.EndContractBlock(); Contract.EndContractBlock();
int ints = GetArrayLength(m_length, BitsPerInt32); int ints = GetArrayLength(_mLength, BitsPerInt32);
for (int i = 0; i < ints; i++) for (int i = 0; i < ints; i++)
{ {
m_array[i] ^= value.m_array[i]; _mArray[i] ^= value._mArray[i];
} }
_version++; _version++;
@@ -190,10 +190,10 @@ namespace System.Collections
public BitSet Not() public BitSet Not()
{ {
int ints = GetArrayLength(m_length, BitsPerInt32); int ints = GetArrayLength(_mLength, BitsPerInt32);
for (int i = 0; i < ints; i++) for (int i = 0; i < ints; i++)
{ {
m_array[i] = ~m_array[i]; _mArray[i] = ~_mArray[i];
} }
_version++; _version++;
@@ -205,7 +205,7 @@ namespace System.Collections
get get
{ {
Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() >= 0);
return m_length; return _mLength;
} }
set set
{ {
@@ -216,29 +216,29 @@ namespace System.Collections
Contract.EndContractBlock(); Contract.EndContractBlock();
int newints = GetArrayLength(value, BitsPerInt32); int newints = GetArrayLength(value, BitsPerInt32);
if (newints > m_array.Length || newints + _ShrinkThreshold < m_array.Length) if (newints > _mArray.Length || newints + ShrinkThreshold < _mArray.Length)
{ {
// grow or shrink (if wasting more than _ShrinkThreshold ints) // grow or shrink (if wasting more than _ShrinkThreshold ints)
uint[] newarray = new uint[newints]; uint[] newarray = new uint[newints];
Array.Copy(m_array, newarray, newints > m_array.Length ? m_array.Length : newints); Array.Copy(_mArray, newarray, newints > _mArray.Length ? _mArray.Length : newints);
m_array = newarray; _mArray = newarray;
} }
if (value > m_length) if (value > _mLength)
{ {
// clear high bit values in the last int // clear high bit values in the last int
int last = GetArrayLength(m_length, BitsPerInt32) - 1; int last = GetArrayLength(_mLength, BitsPerInt32) - 1;
int bits = m_length % 32; int bits = _mLength % 32;
if (bits > 0) if (bits > 0)
{ {
m_array[last] &= (1u << bits) - 1; _mArray[last] &= (1u << bits) - 1;
} }
// clear remaining int values // clear remaining int values
Array.Clear(m_array, last + 1, newints - last - 1); Array.Clear(_mArray, last + 1, newints - last - 1);
} }
m_length = value; _mLength = value;
_version++; _version++;
} }
} }
@@ -259,26 +259,26 @@ namespace System.Collections
if (array is uint[]) if (array is uint[])
{ {
Array.Copy(m_array, 0, array, index, GetArrayLength(m_length, BitsPerInt32)); Array.Copy(_mArray, 0, array, index, GetArrayLength(_mLength, BitsPerInt32));
} }
else if (array is byte[]) else if (array is byte[])
{ {
int arrayLength = GetArrayLength(m_length, BitsPerByte); int arrayLength = GetArrayLength(_mLength, BitsPerByte);
if ((array.Length - index) < arrayLength) if ((array.Length - index) < arrayLength)
throw new ArgumentException(); throw new ArgumentException();
byte[] b = (byte[])array; byte[] b = (byte[])array;
for (int i = 0; i < arrayLength; i++) for (int i = 0; i < arrayLength; i++)
b[index + i] = (byte)((m_array[i / 4] >> ((i % 4) * 8)) & 0x000000FF); // Shift to bring the required byte to LSB, then mask b[index + i] = (byte)((_mArray[i / 4] >> ((i % 4) * 8)) & 0x000000FF); // Shift to bring the required byte to LSB, then mask
} }
else if (array is bool[]) else if (array is bool[])
{ {
if (array.Length - index < m_length) if (array.Length - index < _mLength)
throw new ArgumentException(); throw new ArgumentException();
bool[] b = (bool[])array; bool[] b = (bool[])array;
for (int i = 0; i < m_length; i++) for (int i = 0; i < _mLength; i++)
b[index + i] = ((m_array[i / 32] >> (i % 32)) & 0x00000001) != 0; b[index + i] = ((_mArray[i / 32] >> (i % 32)) & 0x00000001) != 0;
} }
else else
throw new ArgumentException(); throw new ArgumentException();
@@ -290,7 +290,7 @@ namespace System.Collections
{ {
Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() >= 0);
return (int)m_length; return (int)_mLength;
} }
} }
@@ -299,9 +299,9 @@ namespace System.Collections
Contract.Ensures(Contract.Result<Object>() != null); Contract.Ensures(Contract.Result<Object>() != null);
Contract.Ensures(((BitArray)Contract.Result<Object>()).Length == this.Length); Contract.Ensures(((BitArray)Contract.Result<Object>()).Length == this.Length);
BitSet bitArray = new BitSet(m_array); BitSet bitArray = new BitSet(_mArray);
bitArray._version = _version; bitArray._version = _version;
bitArray.m_length = m_length; bitArray._mLength = _mLength;
return bitArray; return bitArray;
} }
@@ -352,16 +352,16 @@ namespace System.Collections
[Serializable] [Serializable]
private class BitArrayEnumeratorSimple : IEnumerator, ICloneable private class BitArrayEnumeratorSimple : IEnumerator, ICloneable
{ {
private BitSet bitarray; private BitSet _bitarray;
private int index; private int _index;
private int version; private int _version;
private bool currentElement; private bool _currentElement;
internal BitArrayEnumeratorSimple(BitSet bitarray) internal BitArrayEnumeratorSimple(BitSet bitarray)
{ {
this.bitarray = bitarray; this._bitarray = bitarray;
this.index = -1; _index = -1;
version = bitarray._version; _version = bitarray._version;
} }
public Object Clone() public Object Clone()
@@ -372,14 +372,14 @@ namespace System.Collections
public bool MoveNext() public bool MoveNext()
{ {
//if (version != bitarray._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion)); //if (version != bitarray._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
if (index < (bitarray.Count - 1)) if (_index < (_bitarray.Count - 1))
{ {
index++; _index++;
currentElement = bitarray.Get(index); _currentElement = _bitarray.Get(_index);
return true; return true;
} }
else else
index = bitarray.Count; _index = _bitarray.Count;
return false; return false;
} }
@@ -388,27 +388,27 @@ namespace System.Collections
{ {
get get
{ {
if (index == -1) if (_index == -1)
throw new InvalidOperationException(); throw new InvalidOperationException();
if (index >= bitarray.Count) if (_index >= _bitarray.Count)
throw new InvalidOperationException(); throw new InvalidOperationException();
return currentElement; return _currentElement;
} }
} }
public void Reset() public void Reset()
{ {
//if (version != bitarray._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion)); //if (version != bitarray._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
index = -1; _index = -1;
} }
} }
private uint[] m_array; private uint[] _mArray;
private int m_length; private int _mLength;
private int _version; private int _version;
[NonSerialized] [NonSerialized]
private Object _syncRoot; private Object _syncRoot;
private const int _ShrinkThreshold = 256; private const int ShrinkThreshold = 256;
} }
} }
@@ -19,84 +19,84 @@ namespace Framework.Collections
{ {
public class LinkedListElement public class LinkedListElement
{ {
internal LinkedListElement iNext; internal LinkedListElement INext;
internal LinkedListElement iPrev; internal LinkedListElement IPrev;
public LinkedListElement() public LinkedListElement()
{ {
iNext = iPrev = null; INext = IPrev = null;
} }
~LinkedListElement() { delink(); } ~LinkedListElement() { Delink(); }
bool hasNext() { return (iNext != null && iNext.iNext != null); } bool HasNext() { return (INext != null && INext.INext != null); }
bool hasPrev() { return (iPrev != null && iPrev.iPrev != null); } bool HasPrev() { return (IPrev != null && IPrev.IPrev != null); }
public bool isInList() { return (iNext != null && iPrev != null); } public bool IsInList() { return (INext != null && IPrev != null); }
public LinkedListElement GetNextElement() { return hasNext() ? iNext : null; } public LinkedListElement GetNextElement() { return HasNext() ? INext : null; }
public LinkedListElement GetPrevElement() { return hasPrev() ? iPrev : null; } public LinkedListElement GetPrevElement() { return HasPrev() ? IPrev : null; }
public void delink() public void Delink()
{ {
if (!isInList()) if (!IsInList())
return; return;
iNext.iPrev = iPrev; INext.IPrev = IPrev;
iPrev.iNext = iNext; IPrev.INext = INext;
iNext = null; INext = null;
iPrev = null; IPrev = null;
} }
public void insertBefore(LinkedListElement pElem) public void InsertBefore(LinkedListElement pElem)
{ {
pElem.iNext = this; pElem.INext = this;
pElem.iPrev = iPrev; pElem.IPrev = IPrev;
iPrev.iNext = pElem; IPrev.INext = pElem;
iPrev = pElem; IPrev = pElem;
} }
public void insertAfter(LinkedListElement pElem) public void InsertAfter(LinkedListElement pElem)
{ {
pElem.iPrev = this; pElem.IPrev = this;
pElem.iNext = iNext; pElem.INext = INext;
iNext.iPrev = pElem; INext.IPrev = pElem;
iNext = pElem; INext = pElem;
} }
} }
public class LinkedListHead public class LinkedListHead
{ {
LinkedListElement iFirst = new LinkedListElement(); LinkedListElement _iFirst = new LinkedListElement();
LinkedListElement iLast = new LinkedListElement(); LinkedListElement _iLast = new LinkedListElement();
uint iSize; uint _iSize;
public LinkedListHead() public LinkedListHead()
{ {
iSize = 0; _iSize = 0;
// create empty list // create empty list
iFirst.iNext = iLast; _iFirst.INext = _iLast;
iLast.iPrev = iFirst; _iLast.IPrev = _iFirst;
} }
public bool isEmpty() { return (!iFirst.iNext.isInList()); } public bool IsEmpty() { return (!_iFirst.INext.IsInList()); }
public LinkedListElement GetFirstElement() { return (isEmpty() ? null : iFirst.iNext); } public LinkedListElement GetFirstElement() { return (IsEmpty() ? null : _iFirst.INext); }
public LinkedListElement GetLastElement() { return (isEmpty() ? null : iLast.iPrev); } public LinkedListElement GetLastElement() { return (IsEmpty() ? null : _iLast.IPrev); }
public void insertFirst(LinkedListElement pElem) public void InsertFirst(LinkedListElement pElem)
{ {
iFirst.insertAfter(pElem); _iFirst.InsertAfter(pElem);
} }
public void insertLast(LinkedListElement pElem) public void InsertLast(LinkedListElement pElem)
{ {
iLast.insertBefore(pElem); _iLast.InsertBefore(pElem);
} }
public uint getSize() public uint GetSize()
{ {
if (iSize == 0) if (_iSize == 0)
{ {
uint result = 0; uint result = 0;
LinkedListElement e = GetFirstElement(); LinkedListElement e = GetFirstElement();
@@ -108,10 +108,10 @@ namespace Framework.Collections
return result; return result;
} }
else else
return iSize; return _iSize;
} }
public void incSize() { ++iSize; } public void IncSize() { ++_iSize; }
public void decSize() { --iSize; } public void DecSize() { --_iSize; }
} }
} }
+15 -15
View File
@@ -29,13 +29,13 @@ namespace Framework.Cryptography
public void InitializeEncryption<T>(T p, T q, T dp, T dq, T iq, bool isBigEndian = false) public void InitializeEncryption<T>(T p, T q, T dp, T dq, T iq, bool isBigEndian = false)
{ {
this._p = p.ToBigInteger(isBigEndian); _p = p.ToBigInteger(isBigEndian);
this._q = q.ToBigInteger(isBigEndian); _q = q.ToBigInteger(isBigEndian);
this._dp = dp.ToBigInteger(isBigEndian); _dp = dp.ToBigInteger(isBigEndian);
this._dq = dq.ToBigInteger(isBigEndian); _dq = dq.ToBigInteger(isBigEndian);
this._iq = iq.ToBigInteger(isBigEndian); _iq = iq.ToBigInteger(isBigEndian);
if (this._p.IsZero && this._q.IsZero) if (_p.IsZero && _q.IsZero)
throw new InvalidOperationException("'0' isn't allowed for p or q"); throw new InvalidOperationException("'0' isn't allowed for p or q");
else else
_isEncryptionInitialized = true; _isEncryptionInitialized = true;
@@ -43,8 +43,8 @@ namespace Framework.Cryptography
public void InitializeDecryption<T>(T e, T n, bool reverseBytes = false) public void InitializeDecryption<T>(T e, T n, bool reverseBytes = false)
{ {
this._e = e.ToBigInteger(reverseBytes); _e = e.ToBigInteger(reverseBytes);
this._n = n.ToBigInteger(reverseBytes); _n = n.ToBigInteger(reverseBytes);
_isDecryptionInitialized = true; _isDecryptionInitialized = true;
} }
@@ -82,13 +82,13 @@ namespace Framework.Cryptography
public void Dispose() public void Dispose()
{ {
this._e = 0; _e = 0;
this._n = 0; _n = 0;
this._p = 0; _p = 0;
this._q = 0; _q = 0;
this._dp = 0; _dp = 0;
this._dq = 0; _dq = 0;
this._iq = 0; _iq = 0;
_isEncryptionInitialized = false; _isEncryptionInitialized = false;
_isDecryptionInitialized = false; _isDecryptionInitialized = false;
@@ -31,10 +31,7 @@ namespace Framework.Database
if (_callbacks.Empty()) if (_callbacks.Empty())
return; return;
_callbacks.RemoveAll(callback => _callbacks.RemoveAll(callback => callback.InvokeIfReady() == QueryCallbackStatus.Completed);
{
return callback.InvokeIfReady() == QueryCallbackStatus.Completed;
});
} }
List<QueryCallback> _callbacks = new List<QueryCallback>(); List<QueryCallback> _callbacks = new List<QueryCallback>();
+2 -2
View File
@@ -58,7 +58,7 @@ namespace Framework.Dynamic
public void unlink() public void unlink()
{ {
targetObjectDestroyLink(); targetObjectDestroyLink();
delink(); Delink();
_RefTo = null; _RefTo = null;
_RefFrom = null; _RefFrom = null;
} }
@@ -68,7 +68,7 @@ namespace Framework.Dynamic
public void invalidate() // the iRefFrom MUST remain!! public void invalidate() // the iRefFrom MUST remain!!
{ {
sourceObjectDestroyLink(); sourceObjectDestroyLink();
delink(); Delink();
_RefTo = null; _RefTo = null;
} }
+4 -10
View File
@@ -157,7 +157,7 @@ namespace Framework.Dynamic
public TaskScheduler CancelAll() public TaskScheduler CancelAll()
{ {
/// Clear the task holder // Clear the task holder
_task_holder.Clear(); _task_holder.Clear();
_asyncHolder.Clear(); _asyncHolder.Clear();
return this; return this;
@@ -165,10 +165,7 @@ namespace Framework.Dynamic
public TaskScheduler CancelGroup(uint group) public TaskScheduler CancelGroup(uint group)
{ {
_task_holder.RemoveIf(task => _task_holder.RemoveIf(task => task.IsInGroup(@group));
{
return task.IsInGroup(group);
});
return this; return this;
} }
@@ -689,10 +686,7 @@ namespace Framework.Dynamic
public TaskContext Schedule(TimeSpan time, Action<TaskContext> task) public TaskContext Schedule(TimeSpan time, Action<TaskContext> task)
{ {
var end = _task._end; var end = _task._end;
return Dispatch(scheduler => return Dispatch(scheduler => scheduler.ScheduleAt(end, time, task));
{
return scheduler.ScheduleAt(end, time, task);
});
} }
public TaskContext Schedule(TimeSpan time, Action task) { return Schedule(time, delegate (TaskContext task1) { task(); }); } public TaskContext Schedule(TimeSpan time, Action task) { return Schedule(time, delegate (TaskContext task1) { task(); }); }
@@ -709,7 +703,7 @@ namespace Framework.Dynamic
public TaskContext Schedule(TimeSpan time, uint group, Action<TaskContext> task) public TaskContext Schedule(TimeSpan time, uint group, Action<TaskContext> task)
{ {
var end = _task._end; var end = _task._end;
return Dispatch(scheduler => { return scheduler.ScheduleAt(end, time, group, task); }); return Dispatch(scheduler => scheduler.ScheduleAt(end, time, @group, task));
} }
public TaskContext Schedule(TimeSpan time, uint group, Action task) { return Schedule(time, group, delegate (TaskContext task1) { task(); }); } public TaskContext Schedule(TimeSpan time, uint group, Action task) { return Schedule(time, group, delegate (TaskContext task1) { task(); }); }
+1 -1
View File
@@ -174,7 +174,7 @@ namespace Framework.GameMath
/// <returns>A string representation of this object.</returns> /// <returns>A string representation of this object.</returns>
public override string ToString() public override string ToString()
{ {
return string.Format("AxisAlignedBox(Min={0}, Max={1})", _lo, _hi); return $"AxisAlignedBox(Min={_lo}, Max={_hi})";
} }
#endregion #endregion
+1 -2
View File
@@ -449,8 +449,7 @@ namespace Framework.GameMath
/// <returns>A string representation of this object.</returns> /// <returns>A string representation of this object.</returns>
public override string ToString() public override string ToString()
{ {
return string.Format("2x2[{0}, {1}, {2}, {3}]", return $"2x2[{_m11}, {_m12}, {_m21}, {_m22}]";
_m11, _m12, _m21, _m22);
} }
#endregion #endregion
+1 -2
View File
@@ -633,8 +633,7 @@ namespace Framework.GameMath
/// <returns>A string representation of this object.</returns> /// <returns>A string representation of this object.</returns>
public override string ToString() public override string ToString()
{ {
return string.Format("3x3[{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}]", return $"3x3[{_m11}, {_m12}, {_m13}, {_m21}, {_m22}, {_m23}, {_m31}, {_m32}, {_m33}]";
_m11, _m12, _m13, _m21, _m22, _m23, _m31, _m32, _m33);
} }
#endregion #endregion
+2 -2
View File
@@ -705,8 +705,8 @@ namespace Framework.GameMath
/// <returns>A string representation of this object.</returns> /// <returns>A string representation of this object.</returns>
public override string ToString() public override string ToString()
{ {
return string.Format("4x4[{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}, {14}, {15}]", return
_m11, _m12, _m13, _m14, _m21, _m22, _m23, _m24, _m31, _m32, _m33, _m34, _m41, _m42, _m43, _m44); $"4x4[{_m11}, {_m12}, {_m13}, {_m14}, {_m21}, {_m22}, {_m23}, {_m24}, {_m31}, {_m32}, {_m33}, {_m34}, {_m41}, {_m42}, {_m43}, {_m44}]";
} }
#endregion #endregion
+2 -2
View File
@@ -205,7 +205,7 @@ namespace Framework.GameMath
/// <returns>A float representing the shortest distance from the given vector to the plane.</returns> /// <returns>A float representing the shortest distance from the given vector to the plane.</returns>
public float GetDistanceToPlane(Vector3 p) public float GetDistanceToPlane(Vector3 p)
{ {
return Vector3.DotProduct(p, this.Normal) - this.Constant; return Vector3.DotProduct(p, Normal) - Constant;
} }
public void getEquation(ref Vector3 n, out float d) public void getEquation(ref Vector3 n, out float d)
@@ -253,7 +253,7 @@ namespace Framework.GameMath
/// <returns>A string representation of this object.</returns> /// <returns>A string representation of this object.</returns>
public override string ToString() public override string ToString()
{ {
return string.Format("Plane[n={0}, c={1}]", _normal.ToString(), _const.ToString()); return $"Plane[n={_normal.ToString()}, c={_const.ToString()}]";
} }
#endregion #endregion
} }
+1 -1
View File
@@ -648,7 +648,7 @@ namespace Framework.GameMath
/// <returns>A string representation of this object.</returns> /// <returns>A string representation of this object.</returns>
public override string ToString() public override string ToString()
{ {
return string.Format("({0}, {1}, {2}, {3})", _w, _x, _y, _z); return $"({_w}, {_x}, {_y}, {_z})";
} }
#endregion #endregion
+1 -1
View File
@@ -164,7 +164,7 @@ namespace Framework.GameMath
/// <returns>A string representation of this object.</returns> /// <returns>A string representation of this object.</returns>
public override string ToString() public override string ToString()
{ {
return string.Format("({0}, {1})", _origin, _direction); return $"({_origin}, {_direction})";
} }
#endregion #endregion
+1 -1
View File
@@ -569,7 +569,7 @@ namespace Framework.GameMath
/// <returns>A string representation of this object.</returns> /// <returns>A string representation of this object.</returns>
public override string ToString() public override string ToString()
{ {
return string.Format("({0}, {1})", _x, _y); return $"({_x}, {_y})";
} }
#endregion #endregion
+1 -1
View File
@@ -594,7 +594,7 @@ namespace Framework.GameMath
/// <returns>A string representation of this object.</returns> /// <returns>A string representation of this object.</returns>
public override string ToString() public override string ToString()
{ {
return string.Format("({0}, {1}, {2})", X, Y, Z); return $"({X}, {Y}, {Z})";
} }
#endregion #endregion
+1 -1
View File
@@ -617,7 +617,7 @@ namespace Framework.GameMath
/// <returns>A string representation of this object.</returns> /// <returns>A string representation of this object.</returns>
public override string ToString() public override string ToString()
{ {
return string.Format("({0}, {1}, {2}, {3})", _x, _y, _z, _w); return $"({_x}, {_y}, {_z}, {_w})";
} }
#endregion #endregion
+2 -2
View File
@@ -26,8 +26,8 @@ namespace Framework.IO
private delegate T LoadFromByteRefDelegate(ref byte source); private delegate T LoadFromByteRefDelegate(ref byte source);
private delegate void CopyMemoryDelegate(ref T dest, ref byte src, int count); private delegate void CopyMemoryDelegate(ref T dest, ref byte src, int count);
private readonly static LoadFromByteRefDelegate LoadFromByteRef = BuildLoadFromByteRefMethod(); private static readonly LoadFromByteRefDelegate LoadFromByteRef = BuildLoadFromByteRefMethod();
private readonly static CopyMemoryDelegate CopyMemory = BuildCopyMemoryMethod(); private static readonly CopyMemoryDelegate CopyMemory = BuildCopyMemoryMethod();
public static readonly int Size = Marshal.SizeOf<T>(); public static readonly int Size = Marshal.SizeOf<T>();
+1 -1
View File
@@ -180,7 +180,7 @@ abstract class Appender
StringBuilder ss = new StringBuilder(); StringBuilder ss = new StringBuilder();
if (_flags.HasAnyFlag(AppenderFlags.PrefixTimestamp)) if (_flags.HasAnyFlag(AppenderFlags.PrefixTimestamp))
ss.AppendFormat("{0} ", message.mtime.ToString("MM/dd/yyyy HH:mm:ss")); ss.AppendFormat("{0:MM/dd/yyyy HH:mm:ss} ", message.mtime);
if (_flags.HasAnyFlag(AppenderFlags.PrefixLogLevel)) if (_flags.HasAnyFlag(AppenderFlags.PrefixLogLevel))
ss.AppendFormat("{0}: ", message.level); ss.AppendFormat("{0}: ", message.level);
+2 -2
View File
@@ -130,12 +130,12 @@ public struct RealmHandle : IEquatable<RealmHandle>
} }
public string GetAddressString() public string GetAddressString()
{ {
return string.Format("{0}-{1}-{2}", Region, Site, Realm); return $"{Region}-{Site}-{Realm}";
} }
public string GetSubRegionAddress() public string GetSubRegionAddress()
{ {
return string.Format("{0}-{1}-0", Region, Site); return $"{Region}-{Site}-0";
} }
public override bool Equals(object obj) public override bool Equals(object obj)
+3 -6
View File
@@ -57,7 +57,7 @@ namespace System
public static byte[] ToByteArray(this string value, char separator) public static byte[] ToByteArray(this string value, char separator)
{ {
return Array.ConvertAll(value.Split(separator), s => byte.Parse(s)); return Array.ConvertAll(value.Split(separator), byte.Parse);
} }
static uint LeftRotate(this uint value, int shiftCount) static uint LeftRotate(this uint value, int shiftCount)
@@ -144,7 +144,7 @@ namespace System
ret = (BigInteger)Convert.ChangeType(value, typeof(BigInteger)); ret = (BigInteger)Convert.ChangeType(value, typeof(BigInteger));
break; break;
default: default:
throw new NotSupportedException(string.Format("'{0}' conversion to 'BigInteger' not supported.", typeof(T).Name)); throw new NotSupportedException($"'{typeof(T).Name}' conversion to 'BigInteger' not supported.");
} }
return ret; return ret;
@@ -268,10 +268,7 @@ namespace System
string pattern = @"(%\W*\d*[a-zA-Z]*)"; string pattern = @"(%\W*\d*[a-zA-Z]*)";
int count = 0; int count = 0;
string result = Regex.Replace(str, pattern, m => string result = Regex.Replace(str, pattern, m => string.Concat("{", count++, "}"));
{
return string.Concat("{", count++, "}");
});
return result; return result;
} }
+1 -1
View File
@@ -19,7 +19,7 @@ using System.Diagnostics.Contracts;
public class RandomHelper public class RandomHelper
{ {
private readonly static Random rand; private static readonly Random rand;
static RandomHelper() static RandomHelper()
{ {
+1 -1
View File
@@ -185,7 +185,7 @@ public static class Time
long hours = (time % Day) / Hour; long hours = (time % Day) / Hour;
long minute = (time % Hour) / Minute; long minute = (time % Hour) / Minute;
return string.Format("Days: {0} Hours: {1} Minutes: {2}", days, hours, minute); return $"Days: {days} Hours: {hours} Minutes: {minute}";
} }
public static void Profile(string description, int iterations, Action func) public static void Profile(string description, int iterations, Action func)
+2 -5
View File
@@ -440,10 +440,7 @@ namespace Game.AI
if (instance != null) if (instance != null)
SetBoundary(instance.GetBossBoundary(bossId)); SetBoundary(instance.GetBossBoundary(bossId));
_scheduler.SetValidator(() => _scheduler.SetValidator(() => !me.HasUnitState(UnitState.Casting));
{
return !me.HasUnitState(UnitState.Casting);
});
} }
public void _Reset() public void _Reset()
@@ -699,7 +696,7 @@ namespace Game.AI
while (!this.Empty()) while (!this.Empty())
{ {
Creature summon = ObjectAccessor.GetCreature(me, this.FirstOrDefault()); Creature summon = ObjectAccessor.GetCreature(me, this.FirstOrDefault());
this.RemoveAt(0); RemoveAt(0);
if (summon) if (summon)
summon.DespawnOrUnsummon(); summon.DespawnOrUnsummon();
} }
+1 -1
View File
@@ -3991,7 +3991,7 @@ namespace Game.AI
if (bounds.Empty()) if (bounds.Empty())
return null; return null;
var foundCreature = bounds.Find(creature => { return creature.IsAlive(); }); var foundCreature = bounds.Find(creature => creature.IsAlive());
return foundCreature ?? bounds[0]; return foundCreature ?? bounds[0];
} }
@@ -162,7 +162,7 @@ namespace Game.Achievements
{ {
if (criteriaTree.Criteria != null) if (criteriaTree.Criteria != null)
{ {
CriteriaProgress criteriaProgress = this.GetCriteriaProgress(criteriaTree.Criteria); CriteriaProgress criteriaProgress = GetCriteriaProgress(criteriaTree.Criteria);
if (criteriaProgress != null) if (criteriaProgress != null)
progress += (long)criteriaProgress.Counter; progress += (long)criteriaProgress.Counter;
} }
@@ -656,7 +656,7 @@ namespace Game.Achievements
public override string GetOwnerInfo() public override string GetOwnerInfo()
{ {
return string.Format("{0} {1}", _owner.GetGUID().ToString(), _owner.GetName()); return $"{_owner.GetGUID().ToString()} {_owner.GetName()}";
} }
Player _owner; Player _owner;
@@ -1017,7 +1017,7 @@ namespace Game.Achievements
public override string GetOwnerInfo() public override string GetOwnerInfo()
{ {
return string.Format("Guild ID {0} {1}", _owner.GetId(), _owner.GetName()); return $"Guild ID {_owner.GetId()} {_owner.GetName()}";
} }
Guild _owner; Guild _owner;
+3 -2
View File
@@ -1554,7 +1554,8 @@ namespace Game.Achievements
uint questObjectiveCriterias = 0; uint questObjectiveCriterias = 0;
foreach (CriteriaRecord criteriaEntry in CliDB.CriteriaStorage.Values) foreach (CriteriaRecord criteriaEntry in CliDB.CriteriaStorage.Values)
{ {
Contract.Assert(criteriaEntry.Type < CriteriaTypes.TotalTypes, string.Format("CRITERIA_TYPE_TOTAL must be greater than or equal to {0} but is currently equal to {1}", criteriaEntry.Type + 1, CriteriaTypes.TotalTypes)); Contract.Assert(criteriaEntry.Type < CriteriaTypes.TotalTypes,
$"CRITERIA_TYPE_TOTAL must be greater than or equal to {criteriaEntry.Type + 1} but is currently equal to {CriteriaTypes.TotalTypes}");
var treeList = _criteriaTreeByCriteria.LookupByKey(criteriaEntry.Id); var treeList = _criteriaTreeByCriteria.LookupByKey(criteriaEntry.Id);
if (treeList.Empty()) if (treeList.Empty())
@@ -1819,7 +1820,7 @@ namespace Game.Achievements
public CriteriaData(CriteriaDataType _dataType, uint _value1, uint _value2, uint _scriptId) public CriteriaData(CriteriaDataType _dataType, uint _value1, uint _value2, uint _scriptId)
{ {
this.DataType = _dataType; DataType = _dataType;
Raw.Value1 = _value1; Raw.Value1 = _value1;
Raw.Value2 = _value2; Raw.Value2 = _value2;
+1 -1
View File
@@ -794,7 +794,7 @@ namespace Game
public string BuildAuctionMailSubject(MailAuctionAnswers response) public string BuildAuctionMailSubject(MailAuctionAnswers response)
{ {
return string.Format("{0}:0:{1}:{2}:{3}", itemEntry, response, Id, itemCount); return $"{itemEntry}:0:{response}:{Id}:{itemCount}";
} }
public static string BuildAuctionMailBody(ulong lowGuid, ulong bid, ulong buyout, ulong deposit, ulong cut) public static string BuildAuctionMailBody(ulong lowGuid, ulong bid, ulong buyout, ulong deposit, ulong cut)
@@ -124,7 +124,7 @@ namespace Game.Collision
if (1.3f * nodeNewW < nodeBoxW) if (1.3f * nodeNewW < nodeBoxW)
{ {
stats.updateBVH2(); stats.updateBVH2();
int nextIndex1 = tempTree.Count(); int nextIndex1 = tempTree.Count;
// allocate child // allocate child
tempTree.Add(0); tempTree.Add(0);
tempTree.Add(0); tempTree.Add(0);
@@ -301,7 +301,7 @@ namespace Game.Collision
public static string getMapFileName(uint mapId) public static string getMapFileName(uint mapId)
{ {
return string.Format("{0:D4}.vmtree", mapId); return $"{mapId:D4}.vmtree";
} }
public void setEnableLineOfSightCalc(bool pVal) { _enableLineOfSightCalc = pVal; } public void setEnableLineOfSightCalc(bool pVal) { _enableLineOfSightCalc = pVal; }
+1 -1
View File
@@ -271,7 +271,7 @@ namespace Game.Collision
public static string getTileFileName(uint mapID, uint tileX, uint tileY) public static string getTileFileName(uint mapID, uint tileX, uint tileY)
{ {
return string.Format("{0:D4}_{1:D2}_{2:D2}.vmtile", mapID, tileY, tileX); return $"{mapID:D4}_{tileY:D2}_{tileX:D2}.vmtile";
} }
public bool getAreaInfo(ref Vector3 pos, out uint flags, out int adtId, out int rootId, out int groupId) public bool getAreaInfo(ref Vector3 pos, out uint flags, out int adtId, out int rootId, out int groupId)
+1 -1
View File
@@ -39,7 +39,7 @@ namespace Game.Combat
public void threatAssist(Unit victim, float baseThreat, SpellInfo threatSpell = null) public void threatAssist(Unit victim, float baseThreat, SpellInfo threatSpell = null)
{ {
float threat = ThreatManager.calcThreat(victim, Owner, baseThreat, (threatSpell != null ? threatSpell.GetSchoolMask() : SpellSchoolMask.Normal), threatSpell); float threat = ThreatManager.calcThreat(victim, Owner, baseThreat, (threatSpell != null ? threatSpell.GetSchoolMask() : SpellSchoolMask.Normal), threatSpell);
threat /= getSize(); threat /= GetSize();
HostileReference refe = getFirst(); HostileReference refe = getFirst();
while (refe != null) while (refe != null)
+1 -1
View File
@@ -467,7 +467,7 @@ namespace Game.Combat
} }
public HostileReference getMostHated() public HostileReference getMostHated()
{ {
return threatList.Count() == 0 ? null : threatList[0]; return threatList.Count == 0 ? null : threatList[0];
} }
public void remove(HostileReference hostileRef) public void remove(HostileReference hostileRef)
+1 -4
View File
@@ -2001,10 +2001,7 @@ namespace Game
{ {
if (condition.QuestKillMonster[i] != 0) if (condition.QuestKillMonster[i] != 0)
{ {
var questObjective = quest.Objectives.Find(objective => var questObjective = quest.Objectives.Find(objective => objective.Type == QuestObjectiveType.Monster && objective.ObjectID == condition.QuestKillMonster[i]);
{
return objective.Type == QuestObjectiveType.Monster && objective.ObjectID == condition.QuestKillMonster[i];
});
if (questObjective != null) if (questObjective != null)
results[i] = player.GetQuestObjectiveData(quest, questObjective.StorageIndex) >= questObjective.Amount; results[i] = player.GetQuestObjectiveData(quest, questObjective.StorageIndex) >= questObjective.Amount;
@@ -168,15 +168,16 @@ namespace Game.DataStorage
continue; continue;
} }
Func<uint, uint> ValidateAndSetCurve = value => uint ValidateAndSetCurve(uint value)
{ {
if (value != 0 && !CliDB.CurveStorage.ContainsKey(value)) if (value != 0 && !CliDB.CurveStorage.ContainsKey(value))
{ {
Log.outError(LogFilter.Sql, "Table `spell_areatrigger` has listed areatrigger (MiscId: {0}, Id: {1}) with invalid Curve ({2}), set to 0!", miscTemplate.MiscId, areatriggerId, value); Log.outError(LogFilter.Sql, "Table `spell_areatrigger` has listed areatrigger (MiscId: {0}, Id: {1}) with invalid Curve ({2}), set to 0!", miscTemplate.MiscId, areatriggerId, value);
return 0; return 0;
} }
return value; return value;
}; }
miscTemplate.MoveCurveId = ValidateAndSetCurve(areatriggerSpellMiscs.Read<uint>(2)); miscTemplate.MoveCurveId = ValidateAndSetCurve(areatriggerSpellMiscs.Read<uint>(2));
miscTemplate.ScaleCurveId = ValidateAndSetCurve(areatriggerSpellMiscs.Read<uint>(3)); miscTemplate.ScaleCurveId = ValidateAndSetCurve(areatriggerSpellMiscs.Read<uint>(3));
@@ -720,13 +720,8 @@ namespace Game.DataStorage
public FieldStructureEntry(short bits, ushort offset) public FieldStructureEntry(short bits, ushort offset)
{ {
this.Bits = bits; Bits = bits;
this.Offset = offset; Offset = offset;
}
public void SetLength(FieldStructureEntry nextField)
{
this.Length = Math.Max(1, (int)Math.Floor((nextField.Offset - this.Offset) / (double)this.ByteCount));
} }
} }
@@ -755,13 +750,13 @@ namespace Game.DataStorage
struct OffsetDuplicate struct OffsetDuplicate
{ {
public int HiddenIndex { get; set; } public int HiddenIndex { get; }
public int VisibleIndex { get; set; } public int VisibleIndex { get; }
public OffsetDuplicate(int hidden, int visible) public OffsetDuplicate(int hidden, int visible)
{ {
this.HiddenIndex = hidden; HiddenIndex = hidden;
this.VisibleIndex = visible; VisibleIndex = visible;
} }
} }
+1 -1
View File
@@ -174,7 +174,7 @@ namespace Game.DataStorage
uint oldMSTime = Time.GetMSTime(); uint oldMSTime = Time.GetMSTime();
foreach (CinematicCameraRecord cameraEntry in CliDB.CinematicCameraStorage.Values) foreach (CinematicCameraRecord cameraEntry in CliDB.CinematicCameraStorage.Values)
{ {
string filename = dataPath + "/cameras/" + string.Format("FILE{0:x8}.xxx", cameraEntry.FileDataID); string filename = dataPath + "/cameras/" + $"FILE{cameraEntry.FileDataID:x8}.xxx";
try try
{ {
+1 -1
View File
@@ -655,7 +655,7 @@ namespace Game.DungeonFinding
} }
} }
return string.Format("Queued Players: {0} (in group: {1}) Groups: {2}\n", players, playersInGroup, groups); return $"Queued Players: {players} (in group: {playersInGroup}) Groups: {groups}\n";
} }
public string DumpCompatibleInfo(bool full = false) public string DumpCompatibleInfo(bool full = false)
@@ -302,10 +302,7 @@ namespace Game.Entities
AxisAlignedBox box = new AxisAlignedBox(new Vector3(minX, minY, minZ), new Vector3(maxX, maxY, maxZ)); AxisAlignedBox box = new AxisAlignedBox(new Vector3(minX, minY, minZ), new Vector3(maxX, maxY, maxZ));
targetList.RemoveAll(unit => targetList.RemoveAll(unit => !box.contains(new Vector3(unit.GetPositionX(), unit.GetPositionY(), unit.GetPositionZ())));
{
return !box.contains(new Vector3(unit.GetPositionX(), unit.GetPositionY(), unit.GetPositionZ()));
});
} }
void SearchUnitInPolygon(List<Unit> targetList) void SearchUnitInPolygon(List<Unit> targetList)
@@ -319,11 +316,7 @@ namespace Game.Entities
float maxZ = GetPositionZ() + height; float maxZ = GetPositionZ() + height;
targetList.RemoveAll(unit => targetList.RemoveAll(unit =>
{ !CheckIsInPolygon2D(unit) || unit.GetPositionZ() < minZ || unit.GetPositionZ() > maxZ);
return !CheckIsInPolygon2D(unit)
|| unit.GetPositionZ() < minZ
|| unit.GetPositionZ() > maxZ;
});
} }
void SearchUnitInCylinder(List<Unit> targetList) void SearchUnitInCylinder(List<Unit> targetList)
@@ -336,11 +329,8 @@ namespace Game.Entities
float minZ = GetPositionZ() - height; float minZ = GetPositionZ() - height;
float maxZ = GetPositionZ() + height; float maxZ = GetPositionZ() + height;
targetList.RemoveAll(unit => targetList.RemoveAll(unit => unit.GetPositionZ() < minZ
{ || unit.GetPositionZ() > maxZ);
return unit.GetPositionZ() < minZ
|| unit.GetPositionZ() > maxZ;
});
} }
void HandleUnitEnterExit(List<Unit> newTargetList) void HandleUnitEnterExit(List<Unit> newTargetList)
+1 -1
View File
@@ -3052,7 +3052,7 @@ namespace Game.Entities
// The last taunt aura caster is alive an we are happy to attack him // The last taunt aura caster is alive an we are happy to attack him
if (caster != null && caster.IsAlive()) if (caster != null && caster.IsAlive())
return GetVictim(); return GetVictim();
else if (tauntAuras.Count() > 1) else if (tauntAuras.Count > 1)
{ {
// We do not have last taunt aura caster but we have more taunt auras, // We do not have last taunt aura caster but we have more taunt auras,
// so find first available target // so find first available target
+1 -1
View File
@@ -793,7 +793,7 @@ namespace Game.Misc
public int GetMenuItemCount() public int GetMenuItemCount()
{ {
return _questMenuItems.Count(); return _questMenuItems.Count;
} }
public bool IsEmpty() public bool IsEmpty()
+1 -1
View File
@@ -108,7 +108,7 @@ namespace Game.Entities
TrainerSpellState GetSpellState(Player player, TrainerSpell trainerSpell) TrainerSpellState GetSpellState(Player player, TrainerSpell trainerSpell)
{ {
if (player.HasSpell(trainerSpell.SpellId)) if (player.HasSpell(trainerSpell.IsCastable() ? trainerSpell.LearnedSpellId : trainerSpell.SpellId))
return TrainerSpellState.Known; return TrainerSpellState.Known;
// check race/class requirement // check race/class requirement
+3 -6
View File
@@ -265,7 +265,7 @@ namespace Game.Entities
stmt.AddValue(0, GetGUID().GetCounter()); stmt.AddValue(0, GetGUID().GetCounter());
trans.Append(stmt); trans.Append(stmt);
if (transmogMods.Any(modifier => { return GetModifier(modifier) != 0; })) if (transmogMods.Any(modifier => GetModifier(modifier) != 0))
{ {
stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_ITEM_INSTANCE_TRANSMOG); stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_ITEM_INSTANCE_TRANSMOG);
stmt.AddValue(0, GetGUID().GetCounter()); stmt.AddValue(0, GetGUID().GetCounter());
@@ -318,7 +318,7 @@ namespace Game.Entities
stmt.AddValue(0, GetGUID().GetCounter()); stmt.AddValue(0, GetGUID().GetCounter());
trans.Append(stmt); trans.Append(stmt);
if (modifiersTable.Any(modifier => { return GetModifier(modifier) != 0; })) if (modifiersTable.Any(modifier => GetModifier(modifier) != 0))
{ {
stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_ITEM_INSTANCE_MODIFIERS); stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_ITEM_INSTANCE_MODIFIERS);
stmt.AddValue(0, GetGUID().GetCounter()); stmt.AddValue(0, GetGUID().GetCounter());
@@ -1115,10 +1115,7 @@ namespace Game.Entities
public byte GetGemCountWithID(uint GemID) public byte GetGemCountWithID(uint GemID)
{ {
return (byte)GetGems().Count(gemData => return (byte)GetGems().Count(gemData => gemData.ItemId == GemID);
{
return gemData.ItemId == GemID;
});
} }
public byte GetGemCountWithLimitCategory(uint limitCategory) public byte GetGemCountWithLimitCategory(uint limitCategory)
+1 -1
View File
@@ -170,7 +170,7 @@ namespace Game.Entities
public override string ToString() public override string ToString()
{ {
string str = string.Format("GUID Full: 0x{0}, Type: {1}", _high + _low, GetHigh()); string str = $"GUID Full: 0x{_high + _low}, Type: {GetHigh()}";
if (HasEntry()) if (HasEntry())
str += (IsPet() ? " Pet number: " : " Entry: ") + GetEntry() + " "; str += (IsPet() ? " Pet number: " : " Entry: ") + GetEntry() + " ";
+2 -2
View File
@@ -311,7 +311,7 @@ namespace Game.Entities
public override string ToString() public override string ToString()
{ {
return string.Format("X: {0} Y: {1} Z: {2} O: {3}", posX, posY, posZ, Orientation); return $"X: {posX} Y: {posY} Z: {posZ} O: {Orientation}";
} }
public float posX; public float posX;
@@ -356,7 +356,7 @@ namespace Game.Entities
} }
public uint GetMapId() { return _mapId; } public uint GetMapId() { return _mapId; }
public void SetMapId(uint _mapId) { this._mapId = _mapId; } public void SetMapId(uint mapId) { _mapId = mapId; }
public Cell GetCurrentCell() public Cell GetCurrentCell()
{ {
+2 -2
View File
@@ -1526,7 +1526,7 @@ namespace Game.Entities
SetDynamicValue(index, (ushort)((offset + 1) * BlockCount - 1), 0); // reserve space SetDynamicValue(index, (ushort)((offset + 1) * BlockCount - 1), 0); // reserve space
for (ushort i = 0; i < BlockCount; ++i) for (ushort i = 0; i < BlockCount; ++i)
SetDynamicValue(index, (ushort)(offset * BlockCount + i), Extensions.SerializeObject(value)[i]); SetDynamicValue(index, (ushort)(offset * BlockCount + i), value.SerializeObject()[i]);
} }
public void AddDynamicStructuredValue<T>(object index, T value) public void AddDynamicStructuredValue<T>(object index, T value)
@@ -1535,7 +1535,7 @@ namespace Game.Entities
ushort offset = (ushort)(_dynamicValues[(int)index].Length / BlockCount); ushort offset = (ushort)(_dynamicValues[(int)index].Length / BlockCount);
SetDynamicValue(index, (ushort)((offset + 1) * BlockCount - 1), 0); // reserve space SetDynamicValue(index, (ushort)((offset + 1) * BlockCount - 1), 0); // reserve space
for (ushort i = 0; i < BlockCount; ++i) for (ushort i = 0; i < BlockCount; ++i)
SetDynamicValue(index, (ushort)(offset * BlockCount + i), Extensions.SerializeObject(value)[i]); SetDynamicValue(index, (ushort)(offset * BlockCount + i), value.SerializeObject()[i]);
} }
bool PrintIndexError(object index, bool set) bool PrintIndexError(object index, bool set)
@@ -816,7 +816,7 @@ namespace Game.Entities
if (transmogSlot < 0 || knownPieces[transmogSlot] == 1) if (transmogSlot < 0 || knownPieces[transmogSlot] == 1)
continue; continue;
(var hasAppearance, var isTemporary) = HasItemAppearance(transmogSetItem.ItemModifiedAppearanceID); (var hasAppearance, bool isTemporary) = HasItemAppearance(transmogSetItem.ItemModifiedAppearanceID);
knownPieces[transmogSlot] = (hasAppearance && !isTemporary) ? 1 : 0; knownPieces[transmogSlot] = (hasAppearance && !isTemporary) ? 1 : 0;
} }
+1 -1
View File
@@ -740,7 +740,7 @@ namespace Game.Entities
{ {
byte objectiveIndex = result.Read<byte>(1); byte objectiveIndex = result.Read<byte>(1);
var objectiveItr = quest.Objectives.FirstOrDefault(objective => { return objective.StorageIndex == objectiveIndex; }); var objectiveItr = quest.Objectives.FirstOrDefault(objective => objective.StorageIndex == objectiveIndex);
if (objectiveIndex < questStatusData.ObjectiveData.Length && objectiveItr != null) if (objectiveIndex < questStatusData.ObjectiveData.Length && objectiveItr != null)
{ {
int data = result.Read<int>(2); int data = result.Read<int>(2);
+2 -5
View File
@@ -1213,7 +1213,7 @@ namespace Game.Entities
ushort pos = itemPosCount.pos; ushort pos = itemPosCount.pos;
uint count = itemPosCount.count; uint count = itemPosCount.count;
if (i == dest.Count() - 1) if (i == dest.Count - 1)
{ {
lastItem = _StoreItem(pos, pItem, count, false, update); lastItem = _StoreItem(pos, pItem, count, false, update);
break; break;
@@ -4489,10 +4489,7 @@ namespace Game.Entities
public bool HasLootWorldObjectGUID(ObjectGuid lootWorldObjectGuid) public bool HasLootWorldObjectGUID(ObjectGuid lootWorldObjectGuid)
{ {
return m_AELootView.Any(lootView => return m_AELootView.Any(lootView => lootView.Value == lootWorldObjectGuid);
{
return lootView.Value == lootWorldObjectGuid;
});
} }
//Inventory //Inventory
+2 -8
View File
@@ -2778,15 +2778,9 @@ namespace Game.Entities
pctMod.ModifierData.Add(pctData); pctMod.ModifierData.Add(pctData);
} }
flatMod.ModifierData.RemoveAll(mod => flatMod.ModifierData.RemoveAll(mod => MathFunctions.fuzzyEq(mod.ModifierValue, 0.0f));
{
return MathFunctions.fuzzyEq(mod.ModifierValue, 0.0f);
});
pctMod.ModifierData.RemoveAll(mod => pctMod.ModifierData.RemoveAll(mod => MathFunctions.fuzzyEq(mod.ModifierValue, 1.0f));
{
return MathFunctions.fuzzyEq(mod.ModifierValue, 1.0f);
});
flatMods.Modifiers.Add(flatMod); flatMods.Modifiers.Add(flatMod);
pctMods.Modifiers.Add(pctMod); pctMods.Modifiers.Add(pctMod);
+3 -3
View File
@@ -5284,7 +5284,7 @@ namespace Game.Entities
packet.HealthDelta = 0; packet.HealthDelta = 0;
/// @todo find some better solution /// @todo find some better solution
packet.PowerDelta[0] = basemana - GetCreateMana(); packet.PowerDelta[0] = (int)basemana - (int)GetCreateMana();
packet.PowerDelta[1] = 0; packet.PowerDelta[1] = 0;
packet.PowerDelta[2] = 0; packet.PowerDelta[2] = 0;
packet.PowerDelta[3] = 0; packet.PowerDelta[3] = 0;
@@ -5292,7 +5292,7 @@ namespace Game.Entities
packet.PowerDelta[5] = 0; packet.PowerDelta[5] = 0;
for (Stats i = Stats.Strength; i < Stats.Max; ++i) for (Stats i = Stats.Strength; i < Stats.Max; ++i)
packet.StatDelta[(int)i] = info.stats[(int)i] - (uint)GetCreateStat(i); packet.StatDelta[(int)i] = info.stats[(int)i] - (int)GetCreateStat(i);
uint[] rowLevels = (GetClass() != Class.Deathknight) ? PlayerConst.DefaultTalentRowLevels : PlayerConst.DKTalentRowLevels; uint[] rowLevels = (GetClass() != Class.Deathknight) ? PlayerConst.DefaultTalentRowLevels : PlayerConst.DKTalentRowLevels;
@@ -6301,7 +6301,7 @@ namespace Game.Entities
int count = 0; int count = 0;
string result = System.Text.RegularExpressions.Regex.Replace(input, pattern, m => string result = System.Text.RegularExpressions.Regex.Replace(input, pattern, m =>
{ {
return String.Concat("{", count++, "}"); return string.Concat("{", count++, "}");
}); });
SendSysMessage(result, args); SendSysMessage(result, args);
+1 -4
View File
@@ -1514,10 +1514,7 @@ namespace Game.Entities
Item weapon = GetWeaponForAttack(attack, true); Item weapon = GetWeaponForAttack(attack, true);
expertise += GetTotalAuraModifier(AuraType.ModExpertise, aurEff => expertise += GetTotalAuraModifier(AuraType.ModExpertise, aurEff => aurEff.GetSpellInfo().IsItemFitToSpellRequirements(weapon));
{
return aurEff.GetSpellInfo().IsItemFitToSpellRequirements(weapon);
});
if (expertise < 0) if (expertise < 0)
expertise = 0; expertise = 0;
+2 -2
View File
@@ -342,7 +342,7 @@ namespace Game.Entities
/// </returns> /// </returns>
public override string ToString() public override string ToString()
{ {
return string.Format("From: {0}, To: {1}, Weight: {2}", From, To, Weight); return $"From: {From}, To: {To}, Weight: {Weight}";
} }
} }
@@ -374,7 +374,7 @@ namespace Game.Entities
{ {
if (edge.Weight < 0) if (edge.Weight < 0)
{ {
throw new ArgumentOutOfRangeException(string.Format("Edge: '{0}' has negative weight", edge)); throw new ArgumentOutOfRangeException($"Edge: '{edge}' has negative weight");
} }
} }
+1 -1
View File
@@ -290,7 +290,7 @@ namespace Game.Entities
public void addHatedBy(HostileReference pHostileReference) public void addHatedBy(HostileReference pHostileReference)
{ {
m_HostileRefManager.insertFirst(pHostileReference); m_HostileRefManager.InsertFirst(pHostileReference);
} }
public void removeHatedBy(HostileReference pHostileReference) { } //nothing to do yet public void removeHatedBy(HostileReference pHostileReference) { } //nothing to do yet
+4 -4
View File
@@ -4295,7 +4295,7 @@ namespace Game.Entities
public int GetTotalAuraModifier(AuraType auratype) public int GetTotalAuraModifier(AuraType auratype)
{ {
return GetTotalAuraModifier(auratype, aurEff => { return true; }); return GetTotalAuraModifier(auratype, aurEff => true);
} }
public int GetTotalAuraModifier(AuraType auratype, Func<AuraEffect, bool> predicate) public int GetTotalAuraModifier(AuraType auratype, Func<AuraEffect, bool> predicate)
@@ -4324,7 +4324,7 @@ namespace Game.Entities
public float GetTotalAuraMultiplier(AuraType auratype) public float GetTotalAuraMultiplier(AuraType auratype)
{ {
return GetTotalAuraMultiplier(auratype, aurEff => { return true; }); return GetTotalAuraMultiplier(auratype, aurEff => true);
} }
public float GetTotalAuraMultiplier(AuraType auratype, Func<AuraEffect, bool> predicate) public float GetTotalAuraMultiplier(AuraType auratype, Func<AuraEffect, bool> predicate)
@@ -4356,7 +4356,7 @@ namespace Game.Entities
public int GetMaxPositiveAuraModifier(AuraType auratype) public int GetMaxPositiveAuraModifier(AuraType auratype)
{ {
return GetMaxPositiveAuraModifier(auratype, aurEff => { return true; }); return GetMaxPositiveAuraModifier(auratype, aurEff => true);
} }
public int GetMaxPositiveAuraModifier(AuraType auratype, Func<AuraEffect, bool> predicate) public int GetMaxPositiveAuraModifier(AuraType auratype, Func<AuraEffect, bool> predicate)
@@ -4377,7 +4377,7 @@ namespace Game.Entities
public int GetMaxNegativeAuraModifier(AuraType auratype) public int GetMaxNegativeAuraModifier(AuraType auratype)
{ {
return GetMaxNegativeAuraModifier(auratype, aurEff => { return true; }); return GetMaxNegativeAuraModifier(auratype, aurEff => true);
} }
public int GetMaxNegativeAuraModifier(AuraType auratype, Func<AuraEffect, bool> predicate) public int GetMaxNegativeAuraModifier(AuraType auratype, Func<AuraEffect, bool> predicate)
+2 -2
View File
@@ -150,7 +150,7 @@ namespace Game.Entities
// Check UNIT_STATE_MELEE_ATTACKING or UNIT_STATE_CHASE (without UNIT_STATE_FOLLOW in this case) so pets can reach far away // Check UNIT_STATE_MELEE_ATTACKING or UNIT_STATE_CHASE (without UNIT_STATE_FOLLOW in this case) so pets can reach far away
// targets without stopping half way there and running off. // targets without stopping half way there and running off.
// These flags are reset after target dies or another command is given. // These flags are reset after target dies or another command is given.
if (m_HostileRefManager.isEmpty()) if (m_HostileRefManager.IsEmpty())
{ {
// m_CombatTimer set at aura start and it will be freeze until aura removing // m_CombatTimer set at aura start and it will be freeze until aura removing
if (m_CombatTimer <= diff) if (m_CombatTimer <= diff)
@@ -1931,7 +1931,7 @@ namespace Game.Entities
public void addFollower(FollowerReference pRef) public void addFollower(FollowerReference pRef)
{ {
m_FollowingRefManager.insertFirst(pRef); m_FollowingRefManager.InsertFirst(pRef);
} }
public void removeFollower(FollowerReference pRef) { } //nothing to do yet public void removeFollower(FollowerReference pRef) { } //nothing to do yet
+10 -13
View File
@@ -3063,7 +3063,7 @@ namespace Game
uint trainerId = trainerLocalesResult.Read<uint>(0); uint trainerId = trainerLocalesResult.Read<uint>(0);
string localeName = trainerLocalesResult.Read<string>(1); string localeName = trainerLocalesResult.Read<string>(1);
LocaleConstant locale = Extensions.ToEnum<LocaleConstant>(localeName); LocaleConstant locale = localeName.ToEnum<LocaleConstant>();
if (locale == LocaleConstant.enUS) if (locale == LocaleConstant.enUS)
continue; continue;
@@ -4804,7 +4804,7 @@ namespace Game
if (!Convert.ToBoolean(((ulong)cInfo.Npcflag | ORnpcflag) & (ulong)NPCFlags.Vendor)) if (!Convert.ToBoolean(((ulong)cInfo.Npcflag | ORnpcflag) & (ulong)NPCFlags.Vendor))
{ {
if (skipvendors == null || skipvendors.Count() == 0) if (skipvendors == null || skipvendors.Count == 0)
{ {
if (player != null) if (player != null)
player.SendSysMessage(CypherStrings.CommandVendorselection); player.SendSysMessage(CypherStrings.CommandVendorselection);
@@ -7562,12 +7562,12 @@ namespace Game
return; return;
} }
Func<uint, PhaseInfoStruct> getOrCreatePhaseIfMissing = phaseId => PhaseInfoStruct getOrCreatePhaseIfMissing(uint phaseId)
{ {
PhaseInfoStruct phaseInfo = _phaseInfoById[phaseId]; PhaseInfoStruct phaseInfo = _phaseInfoById[phaseId];
phaseInfo.Id = phaseId; phaseInfo.Id = phaseId;
return phaseInfo; return phaseInfo;
}; }
uint count = 0; uint count = 0;
do do
@@ -8935,7 +8935,7 @@ namespace Game
continue; continue;
} }
var response = choice.Responses.FirstOrDefault(playerChoiceResponse => { return playerChoiceResponse.ResponseId == responseId; }); var response = choice.Responses.FirstOrDefault(playerChoiceResponse => playerChoiceResponse.ResponseId == responseId);
if (response == null) if (response == null)
{ {
Log.outError(LogFilter.Sql, $"Table `playerchoice_response_reward_item` references non-existing ResponseId: {responseId} for ChoiceId {choiceId}, skipped"); Log.outError(LogFilter.Sql, $"Table `playerchoice_response_reward_item` references non-existing ResponseId: {responseId} for ChoiceId {choiceId}, skipped");
@@ -8977,7 +8977,7 @@ namespace Game
continue; continue;
} }
var response = choice.Responses.FirstOrDefault(playerChoiceResponse => { return playerChoiceResponse.ResponseId == responseId; }); var response = choice.Responses.FirstOrDefault(playerChoiceResponse => playerChoiceResponse.ResponseId == responseId);
if (response == null) if (response == null)
{ {
Log.outError(LogFilter.Sql, $"Table `playerchoice_response_reward_currency` references non-existing ResponseId: {responseId} for ChoiceId {choiceId}, skipped"); Log.outError(LogFilter.Sql, $"Table `playerchoice_response_reward_currency` references non-existing ResponseId: {responseId} for ChoiceId {choiceId}, skipped");
@@ -9019,7 +9019,7 @@ namespace Game
continue; continue;
} }
var response = choice.Responses.FirstOrDefault(playerChoiceResponse => { return playerChoiceResponse.ResponseId == responseId; }); var response = choice.Responses.FirstOrDefault(playerChoiceResponse => playerChoiceResponse.ResponseId == responseId);
if (response == null) if (response == null)
{ {
Log.outError(LogFilter.Sql, $"Table `playerchoice_response_reward_faction` references non-existing ResponseId: {responseId} for ChoiceId {choiceId}, skipped"); Log.outError(LogFilter.Sql, $"Table `playerchoice_response_reward_faction` references non-existing ResponseId: {responseId} for ChoiceId {choiceId}, skipped");
@@ -9853,7 +9853,7 @@ namespace Game
public string GetDebugInfo() public string GetDebugInfo()
{ {
return string.Format("{0} ('{1}' script id: {2})", command, Global.ObjectMgr.GetScriptsTableNameByType(type), id); return $"{command} ('{Global.ObjectMgr.GetScriptsTableNameByType(type)}' script id: {id})";
} }
#region Structs #region Structs
@@ -10484,10 +10484,7 @@ namespace Game
public bool IsAllowedInArea(uint areaId) public bool IsAllowedInArea(uint areaId)
{ {
return Areas.Any(areaToCheck => return Areas.Any(areaToCheck => Global.DB2Mgr.IsInArea(areaId, areaToCheck));
{
return Global.DB2Mgr.IsInArea(areaId, areaToCheck);
});
} }
public uint Id; public uint Id;
@@ -10608,7 +10605,7 @@ namespace Game
{ {
public PlayerChoiceResponse GetResponse(int responseId) public PlayerChoiceResponse GetResponse(int responseId)
{ {
return Responses.FirstOrDefault(playerChoiceResponse => { return playerChoiceResponse.ResponseId == responseId; }); return Responses.FirstOrDefault(playerChoiceResponse => playerChoiceResponse.ResponseId == responseId);
} }
public int ChoiceId; public int ChoiceId;
+3 -3
View File
@@ -608,7 +608,7 @@ namespace Game.Groups
} }
} }
if (m_memberMgr.getSize() < ((isLFGGroup() || isBGGroup()) ? 1 : 2)) if (m_memberMgr.GetSize() < ((isLFGGroup() || isBGGroup()) ? 1 : 2))
Disband(); Disband();
else if (player) else if (player)
{ {
@@ -2448,7 +2448,7 @@ namespace Game.Groups
public void LinkMember(GroupReference pRef) public void LinkMember(GroupReference pRef)
{ {
m_memberMgr.insertFirst(pRef); m_memberMgr.InsertFirst(pRef);
} }
void DelinkMember(ObjectGuid guid) void DelinkMember(ObjectGuid guid)
@@ -2616,7 +2616,7 @@ namespace Game.Groups
lootItem.Quantity = itemCount; lootItem.Quantity = itemCount;
lootItem.LootListID = (byte)(itemSlot + 1); lootItem.LootListID = (byte)(itemSlot + 1);
LootItem lootItemInSlot = this.getTarget().GetItemInSlot(itemSlot); LootItem lootItemInSlot = getTarget().GetItemInSlot(itemSlot);
if (lootItemInSlot != null) if (lootItemInSlot != null)
{ {
lootItem.CanTradeToTapList = lootItemInSlot.allowedGUIDs.Count > 1; lootItem.CanTradeToTapList = lootItemInSlot.allowedGUIDs.Count > 1;
+5 -5
View File
@@ -341,7 +341,7 @@ namespace Game
bool allowTwoSideAccounts = !Global.WorldMgr.IsPvPRealm() || HasPermission(RBACPermissions.TwoSideCharacterCreation); bool allowTwoSideAccounts = !Global.WorldMgr.IsPvPRealm() || HasPermission(RBACPermissions.TwoSideCharacterCreation);
int skipCinematics = WorldConfig.GetIntValue(WorldCfg.SkipCinematics); int skipCinematics = WorldConfig.GetIntValue(WorldCfg.SkipCinematics);
Action<SQLResult> finalizeCharacterCreation = result1 => void finalizeCharacterCreation(SQLResult result1)
{ {
bool haveSameRace = false; bool haveSameRace = false;
int demonHunterReqLevel = WorldConfig.GetIntValue(WorldCfg.CharacterCreatingMinLevelForDemonHunter); int demonHunterReqLevel = WorldConfig.GetIntValue(WorldCfg.CharacterCreatingMinLevelForDemonHunter);
@@ -479,7 +479,7 @@ namespace Game
Global.WorldMgr.AddCharacterInfo(newChar.GetGUID(), GetAccountId(), newChar.GetName(), newChar.GetByteValue(PlayerFields.Bytes3, PlayerFieldOffsets.Bytes3OffsetGender), (byte)newChar.GetRace(), (byte)newChar.GetClass(), (byte)newChar.getLevel(), false); Global.WorldMgr.AddCharacterInfo(newChar.GetGUID(), GetAccountId(), newChar.GetName(), newChar.GetByteValue(PlayerFields.Bytes3, PlayerFieldOffsets.Bytes3OffsetGender), (byte)newChar.GetRace(), (byte)newChar.GetClass(), (byte)newChar.getLevel(), false);
newChar.CleanupsBeforeDelete(); newChar.CleanupsBeforeDelete();
}; }
if (!allowTwoSideAccounts || skipCinematics == 1 || createInfo.ClassId == Class.DemonHunter) if (!allowTwoSideAccounts || skipCinematics == 1 || createInfo.ClassId == Class.DemonHunter)
{ {
@@ -2169,12 +2169,12 @@ namespace Game
uint zoneId = GetPlayer().GetZoneId(); uint zoneId = GetPlayer().GetZoneId();
uint team = (uint)GetPlayer().GetTeam(); uint team = (uint)GetPlayer().GetTeam();
List<int> graveyardIds = new List<int>(); List<uint> graveyardIds = new List<uint>();
var range = Global.ObjectMgr.GraveYardStorage.LookupByKey(zoneId); var range = Global.ObjectMgr.GraveYardStorage.LookupByKey(zoneId);
for (int i = 0; i < range.Count && graveyardIds.Count < 16; ++i) // client max for (uint i = 0; i < range.Count && graveyardIds.Count < 16; ++i) // client max
{ {
var gYard = range[i]; var gYard = range[(int)i];
if (gYard.team == 0 || gYard.team == team) if (gYard.team == 0 || gYard.team == team)
graveyardIds.Add(i); graveyardIds.Add(i);
} }
+1 -1
View File
@@ -96,7 +96,7 @@ namespace Game
} }
var items = Global.ObjectMgr.GetGameObjectQuestItemList(packet.GameObjectID); var items = Global.ObjectMgr.GetGameObjectQuestItemList(packet.GameObjectID);
foreach (int item in items) foreach (uint item in items)
stats.QuestItems.Add(item); stats.QuestItems.Add(item);
unsafe unsafe
+1 -1
View File
@@ -63,7 +63,7 @@ namespace Game
if (!_collectionMgr.HasToy(itemId)) if (!_collectionMgr.HasToy(itemId))
return; return;
var effect = item.Effects.Find(eff => { return packet.Cast.SpellID == eff.SpellID; }); var effect = item.Effects.Find(eff => packet.Cast.SpellID == eff.SpellID);
if (effect == null) if (effect == null)
return; return;
+1 -1
View File
@@ -812,7 +812,7 @@ namespace Game.Loots
public void addLootValidatorRef(LootValidatorRef pLootValidatorRef) public void addLootValidatorRef(LootValidatorRef pLootValidatorRef)
{ {
i_LootValidatorRefManager.insertFirst(pLootValidatorRef); i_LootValidatorRefManager.InsertFirst(pLootValidatorRef);
} }
public void clear() public void clear()
+1 -1
View File
@@ -84,7 +84,7 @@ namespace Game.Maps
public override string ToString() public override string ToString()
{ {
return string.Format("grid[{0}, {1}]cell[{2}, {3}]", GetGridX(), GetGridY(), GetCellX(), GetCellY()); return $"grid[{GetGridX()}, {GetGridY()}]cell[{GetCellX()}, {GetCellY()}]";
} }
public struct Data public struct Data
+3 -3
View File
@@ -88,7 +88,7 @@ namespace Game.Maps
public static bool ExistMap(uint mapid, uint gx, uint gy) public static bool ExistMap(uint mapid, uint gx, uint gy)
{ {
string fileName = string.Format("{0}/maps/{1:D4}_{2:D2}_{3:D2}.map", Global.WorldMgr.GetDataPath(), mapid, gx, gy); string fileName = $"{Global.WorldMgr.GetDataPath()}/maps/{mapid:D4}_{gx:D2}_{gy:D2}.map";
if (!File.Exists(fileName)) if (!File.Exists(fileName))
{ {
Log.outError(LogFilter.Maps, "Map file '{0}': does not exist!", fileName); Log.outError(LogFilter.Maps, "Map file '{0}': does not exist!", fileName);
@@ -183,7 +183,7 @@ namespace Game.Maps
} }
// map file name // map file name
string filename = string.Format("{0}/maps/{1:D4}_{2:D2}_{3:D2}.map", Global.WorldMgr.GetDataPath(), map.GetId(), gx, gy); string filename = $"{Global.WorldMgr.GetDataPath()}/maps/{map.GetId():D4}_{gx:D2}_{gy:D2}.map";
Log.outInfo(LogFilter.Maps, "Loading map {0}", filename); Log.outInfo(LogFilter.Maps, "Loading map {0}", filename);
// loading data // loading data
map.GridMaps[gx][gy] = new GridMap(); map.GridMaps[gx][gy] = new GridMap();
@@ -4184,7 +4184,7 @@ namespace Game.Maps
if (!creatureBounds.Empty()) if (!creatureBounds.Empty())
{ {
// Prefer alive (last respawned) creature // Prefer alive (last respawned) creature
var foundCreature = creatureBounds.Find(creature => { return creature.IsAlive(); }); var foundCreature = creatureBounds.Find(creature => creature.IsAlive());
cTarget = foundCreature ?? creatureBounds[0]; cTarget = foundCreature ?? creatureBounds[0];
} }
@@ -215,7 +215,7 @@ namespace Game.Movement
List<Vector3> pathing = new List<Vector3>(); List<Vector3> pathing = new List<Vector3>();
pathing.Add(new Vector3(creature.GetPositionX(), creature.GetPositionY(), creature.GetPositionZ())); pathing.Add(new Vector3(creature.GetPositionX(), creature.GetPositionY(), creature.GetPositionZ()));
for (int i = (int)currentNode; i < path.nodes.Count(); ++i) for (int i = (int)currentNode; i < path.nodes.Count; ++i)
{ {
WaypointNode waypoint = path.nodes.LookupByIndex(i); WaypointNode waypoint = path.nodes.LookupByIndex(i);
+7 -7
View File
@@ -37,7 +37,7 @@ namespace Game.Movement
public int first() { return index_lo; } public int first() { return index_lo; }
public int last() { return index_hi; } public int last() { return index_hi; }
public bool isCyclic() { return cyclic;} public bool isCyclic() { return _cyclic;}
#region Evaluate #region Evaluate
public void Evaluate_Percent(int Idx, float u, out Vector3 c) public void Evaluate_Percent(int Idx, float u, out Vector3 c)
@@ -76,28 +76,28 @@ namespace Game.Movement
#region Init #region Init
public void init_spline_custom(SplineRawInitializer initializer) public void init_spline_custom(SplineRawInitializer initializer)
{ {
initializer.Initialize(ref m_mode, ref cyclic, ref points, ref index_lo, ref index_hi); initializer.Initialize(ref m_mode, ref _cyclic, ref points, ref index_lo, ref index_hi);
} }
public void init_cyclic_spline(Vector3[] controls, int count, EvaluationMode m, int cyclic_point) public void init_cyclic_spline(Vector3[] controls, int count, EvaluationMode m, int cyclic_point)
{ {
m_mode = m; m_mode = m;
cyclic = true; _cyclic = true;
Init_Spline(controls, count, m); Init_Spline(controls, count, m);
} }
public void Init_Spline(Vector3[] controls, int count, EvaluationMode m) public void Init_Spline(Vector3[] controls, int count, EvaluationMode m)
{ {
m_mode = m; m_mode = m;
cyclic = false; _cyclic = false;
switch (m_mode) switch (m_mode)
{ {
case EvaluationMode.Linear: case EvaluationMode.Linear:
case EvaluationMode.Catmullrom: case EvaluationMode.Catmullrom:
InitCatmullRom(controls, count, cyclic, 0); InitCatmullRom(controls, count, _cyclic, 0);
break; break;
case EvaluationMode.Bezier3_Unused: case EvaluationMode.Bezier3_Unused:
InitBezier3(controls, count, cyclic, 0); InitBezier3(controls, count, _cyclic, 0);
break; break;
default: default:
break; break;
@@ -355,7 +355,7 @@ namespace Game.Movement
int[] lengths = new int[0]; int[] lengths = new int[0];
Vector3[] points = new Vector3[0]; Vector3[] points = new Vector3[0];
public EvaluationMode m_mode; public EvaluationMode m_mode;
bool cyclic; bool _cyclic;
int index_lo; int index_lo;
int index_hi; int index_hi;
public enum EvaluationMode public enum EvaluationMode
@@ -230,7 +230,7 @@ namespace Game.Network.Packets
public override void Write() public override void Write()
{ {
_worldPacket.WriteUInt32(Earned.Count()); _worldPacket.WriteUInt32(Earned.Count);
foreach (EarnedAchievement earned in Earned) foreach (EarnedAchievement earned in Earned)
earned.Write(_worldPacket); earned.Write(_worldPacket);
@@ -148,8 +148,9 @@ namespace Game.Network.Packets
data.WriteInt32(PrimaryTalentTree); data.WriteInt32(PrimaryTalentTree);
data.WriteInt32(PrimaryTalentTreeNameIndex); data.WriteInt32(PrimaryTalentTreeNameIndex);
data.WriteInt32(PlayerRace); data.WriteInt32(PlayerRace);
if (!Stats.Empty())
Stats.ForEach(id => data.WriteUInt32(id)); foreach (var id in Stats)
data.WriteUInt32(id);
data.WriteBit(Faction); data.WriteBit(Faction);
data.WriteBit(IsInWorld); data.WriteBit(IsInWorld);
@@ -366,8 +367,9 @@ namespace Game.Network.Packets
_worldPacket.WriteUInt8(MinLevel); _worldPacket.WriteUInt8(MinLevel);
_worldPacket.WriteUInt8(MaxLevel); _worldPacket.WriteUInt8(MaxLevel);
_worldPacket.WriteUInt32(Battlefields.Count); _worldPacket.WriteUInt32(Battlefields.Count);
if (!Battlefields.Empty())
Battlefields.ForEach(field => _worldPacket.WriteInt32(field)); foreach (var field in Battlefields)
_worldPacket.WriteInt32(field);
_worldPacket.WriteBit(PvpAnywhere); _worldPacket.WriteBit(PvpAnywhere);
_worldPacket.WriteBit(HasRandomWinToday); _worldPacket.WriteBit(HasRandomWinToday);
@@ -464,8 +466,9 @@ namespace Game.Network.Packets
public override void Write() public override void Write()
{ {
_worldPacket .WriteUInt32(FlagCarriers.Count); _worldPacket.WriteUInt32(FlagCarriers.Count);
FlagCarriers.ForEach(pos => pos.Write(_worldPacket)); foreach (var pos in FlagCarriers)
pos.Write(_worldPacket);
} }
public List<BattlegroundPlayerPosition> FlagCarriers = new List<BattlegroundPlayerPosition>(); public List<BattlegroundPlayerPosition> FlagCarriers = new List<BattlegroundPlayerPosition>();
@@ -515,8 +515,8 @@ namespace Game.Network.Packets
foreach (GarrisonTalent talent in Talents) foreach (GarrisonTalent talent in Talents)
talent.Write(data); talent.Write(data);
if (!ArchivedMissions.Empty()) foreach(var id in ArchivedMissions)
ArchivedMissions.ForEach(id => data.WriteInt32(id)); data.WriteInt32(id);
foreach (GarrisonBuildingInfo building in Buildings) foreach (GarrisonBuildingInfo building in Buildings)
building.Write(data); building.Write(data);
+2 -2
View File
@@ -680,8 +680,8 @@ namespace Game.Network.Packets
public uint Level = 0; public uint Level = 0;
public uint HealthDelta = 0; public uint HealthDelta = 0;
public uint[] PowerDelta = new uint[6]; public int[] PowerDelta = new int[6];
public uint[] StatDelta = new uint[(int)Stats.Max]; public int[] StatDelta = new int[(int)Stats.Max];
public int Cp = 0; public int Cp = 0;
} }
+3 -3
View File
@@ -283,8 +283,8 @@ namespace Game.Network.Packets
statsData.WriteFloat(Stats.Size); statsData.WriteFloat(Stats.Size);
statsData.WriteUInt8(Stats.QuestItems.Count); statsData.WriteUInt8(Stats.QuestItems.Count);
foreach (int questItem in Stats.QuestItems) foreach (uint questItem in Stats.QuestItems)
statsData.WriteInt32(questItem); statsData.WriteUInt32(questItem);
statsData.WriteUInt32(Stats.RequiredLevel); statsData.WriteUInt32(Stats.RequiredLevel);
@@ -731,7 +731,7 @@ namespace Game.Network.Packets
public uint DisplayID; public uint DisplayID;
public int[] Data = new int[33]; public int[] Data = new int[33];
public float Size; public float Size;
public List<int> QuestItems = new List<int>(); public List<uint> QuestItems = new List<uint>();
public uint RequiredLevel; public uint RequiredLevel;
} }
+2 -2
View File
@@ -422,8 +422,8 @@ namespace Game.Network.Packets
_worldPacket.WriteUInt32(Objectives.Count); _worldPacket.WriteUInt32(Objectives.Count);
_worldPacket.WriteInt32(QuestStartItemID); _worldPacket.WriteInt32(QuestStartItemID);
foreach (int spell in LearnSpells) foreach (uint spell in LearnSpells)
_worldPacket.WriteInt32(spell); _worldPacket.WriteUInt32(spell);
foreach (QuestDescEmote emote in DescEmotes) foreach (QuestDescEmote emote in DescEmotes)
{ {
+2 -2
View File
@@ -330,8 +330,8 @@ namespace Game.Network.Packets
_worldPacket.WriteUInt32(SpellID.Count); _worldPacket.WriteUInt32(SpellID.Count);
_worldPacket.WriteUInt32(FavoriteSpellID.Count); _worldPacket.WriteUInt32(FavoriteSpellID.Count);
foreach (int spell in SpellID) foreach (uint spell in SpellID)
_worldPacket.WriteInt32(spell); _worldPacket.WriteUInt32(spell);
foreach (int spell in FavoriteSpellID) foreach (int spell in FavoriteSpellID)
_worldPacket.WriteInt32(spell); _worldPacket.WriteInt32(spell);
+1 -4
View File
@@ -136,10 +136,7 @@ namespace Game
{ {
ObjectGuid ownerGuid = PersonalGuid; ObjectGuid ownerGuid = PersonalGuid;
ObjectGuid otherPersonalGuid = other.PersonalGuid; ObjectGuid otherPersonalGuid = other.PersonalGuid;
return Phases.Intersect(other.Phases, (myPhase, otherPhase) => return Phases.Intersect(other.Phases, (myPhase, otherPhase) => !myPhase.Flags.HasAnyFlag(excludePhasesWithFlag) && (!myPhase.Flags.HasFlag(PhaseFlags.Personal) || ownerGuid == otherPersonalGuid)).Any();
{
return !myPhase.Flags.HasAnyFlag(excludePhasesWithFlag) && (!myPhase.Flags.HasFlag(PhaseFlags.Personal) || ownerGuid == otherPersonalGuid);
}).Any();
} }
var checkInversePhaseShift = new Func<PhaseShift, PhaseShift, bool>((phaseShift, excludedPhaseShift) => var checkInversePhaseShift = new Func<PhaseShift, PhaseShift, bool>((phaseShift, excludedPhaseShift) =>
+1 -1
View File
@@ -163,7 +163,7 @@ namespace Game.Scenarios
public override string GetOwnerInfo() public override string GetOwnerInfo()
{ {
return string.Format("Instance ID {0}", _map.GetInstanceId()); return $"Instance ID {_map.GetInstanceId()}";
} }
public override void SendPacket(ServerPacket data) public override void SendPacket(ServerPacket data)
+2 -1
View File
@@ -705,7 +705,8 @@ namespace Game.Scripting
public SpellEffectInfo GetEffectInfo() public SpellEffectInfo GetEffectInfo()
{ {
Contract.Assert(IsInEffectHook(), string.Format("Script: `{0}` Spell: `{1}`: function SpellScript::GetEffectInfo was called, but function has no effect in current hook!", m_scriptName, m_scriptSpellId)); Contract.Assert(IsInEffectHook(),
$"Script: `{m_scriptName}` Spell: `{m_scriptSpellId}`: function SpellScript::GetEffectInfo was called, but function has no effect in current hook!");
return m_spell.effectInfo; return m_spell.effectInfo;
} }
+21 -21
View File
@@ -40,34 +40,34 @@ namespace Game
Values[WorldCfg.EnableSinfoLogin] = GetDefaultValue("Server.LoginInfo", 0); Values[WorldCfg.EnableSinfoLogin] = GetDefaultValue("Server.LoginInfo", 0);
// Read all rates from the config file // Read all rates from the config file
Action<WorldCfg, string> setRegenRate = (rate, configKey) => void SetRegenRate(WorldCfg rate, string configKey)
{ {
Values[rate] = GetDefaultValue(configKey, 1.0f); Values[rate] = GetDefaultValue(configKey, 1.0f);
if ((float)Values[rate] < 0.0f) if ((float) Values[rate] < 0.0f)
{ {
Log.outError(LogFilter.ServerLoading, "{0} ({1}) must be > 0. Using 1 instead.", configKey, Values[rate]); Log.outError(LogFilter.ServerLoading, "{0} ({1}) must be > 0. Using 1 instead.", configKey, Values[rate]);
Values[rate] = 1; Values[rate] = 1;
} }
}; }
setRegenRate(WorldCfg.RateHealth, "Rate.Health"); SetRegenRate(WorldCfg.RateHealth, "Rate.Health");
setRegenRate(WorldCfg.RatePowerMana, "Rate.Mana"); SetRegenRate(WorldCfg.RatePowerMana, "Rate.Mana");
setRegenRate(WorldCfg.RatePowerRageIncome, "Rate.Rage.Gain"); SetRegenRate(WorldCfg.RatePowerRageIncome, "Rate.Rage.Gain");
setRegenRate(WorldCfg.RatePowerRageLoss, "Rate.Rage.Loss"); SetRegenRate(WorldCfg.RatePowerRageLoss, "Rate.Rage.Loss");
setRegenRate(WorldCfg.RatePowerFocus, "Rate.Focus"); SetRegenRate(WorldCfg.RatePowerFocus, "Rate.Focus");
setRegenRate(WorldCfg.RatePowerEnergy, "Rate.Energy"); SetRegenRate(WorldCfg.RatePowerEnergy, "Rate.Energy");
setRegenRate(WorldCfg.RatePowerComboPointsLoss, "Rate.ComboPoints.Loss"); SetRegenRate(WorldCfg.RatePowerComboPointsLoss, "Rate.ComboPoints.Loss");
setRegenRate(WorldCfg.RatePowerRunicPowerIncome, "Rate.RunicPower.Gain"); SetRegenRate(WorldCfg.RatePowerRunicPowerIncome, "Rate.RunicPower.Gain");
setRegenRate(WorldCfg.RatePowerRunicPowerLoss, "Rate.RunicPower.Loss"); SetRegenRate(WorldCfg.RatePowerRunicPowerLoss, "Rate.RunicPower.Loss");
setRegenRate(WorldCfg.RatePowerSoulShards, "Rate.SoulShards.Loss"); SetRegenRate(WorldCfg.RatePowerSoulShards, "Rate.SoulShards.Loss");
setRegenRate(WorldCfg.RatePowerLunarPower, "Rate.LunarPower.Loss"); SetRegenRate(WorldCfg.RatePowerLunarPower, "Rate.LunarPower.Loss");
setRegenRate(WorldCfg.RatePowerHolyPower, "Rate.HolyPower.Loss"); SetRegenRate(WorldCfg.RatePowerHolyPower, "Rate.HolyPower.Loss");
setRegenRate(WorldCfg.RatePowerMaelstrom, "Rate.Maelstrom.Loss"); SetRegenRate(WorldCfg.RatePowerMaelstrom, "Rate.Maelstrom.Loss");
setRegenRate(WorldCfg.RatePowerChi, "Rate.Chi.Loss"); SetRegenRate(WorldCfg.RatePowerChi, "Rate.Chi.Loss");
setRegenRate(WorldCfg.RatePowerInsanity, "Rate.Insanity.Loss"); SetRegenRate(WorldCfg.RatePowerInsanity, "Rate.Insanity.Loss");
setRegenRate(WorldCfg.RatePowerArcaneCharges, "Rate.ArcaneCharges.Loss"); SetRegenRate(WorldCfg.RatePowerArcaneCharges, "Rate.ArcaneCharges.Loss");
setRegenRate(WorldCfg.RatePowerFury, "Rate.Fury.Loss"); SetRegenRate(WorldCfg.RatePowerFury, "Rate.Fury.Loss");
setRegenRate(WorldCfg.RatePowerPain, "Rate.Pain.Loss"); SetRegenRate(WorldCfg.RatePowerPain, "Rate.Pain.Loss");
Values[WorldCfg.RateSkillDiscovery] = GetDefaultValue("Rate.Skill.Discovery", 1.0f); Values[WorldCfg.RateSkillDiscovery] = GetDefaultValue("Rate.Skill.Discovery", 1.0f);
Values[WorldCfg.RateDropItemPoor] = GetDefaultValue("Rate.Drop.Item.Poor", 1.0f); Values[WorldCfg.RateDropItemPoor] = GetDefaultValue("Rate.Drop.Item.Poor", 1.0f);
+1 -4
View File
@@ -1780,10 +1780,7 @@ namespace Game
if (m_Autobroadcasts.Empty()) if (m_Autobroadcasts.Empty())
return; return;
var pair = m_Autobroadcasts.SelectRandomElementByWeight(autoPair => var pair = m_Autobroadcasts.SelectRandomElementByWeight(autoPair => autoPair.Value.Weight);
{
return autoPair.Value.Weight;
});
uint abcenter = WorldConfig.GetUIntValue(WorldCfg.AutoBroadcastCenter); uint abcenter = WorldConfig.GetUIntValue(WorldCfg.AutoBroadcastCenter);
+1 -1
View File
@@ -706,7 +706,7 @@ namespace Game.Spells
// Costs Check // Costs Check
var costs = eventInfo.GetProcSpell().GetPowerCost(); var costs = eventInfo.GetProcSpell().GetPowerCost();
var m = costs.Find(cost => { return cost.Amount > 0; }); var m = costs.Find(cost => cost.Amount > 0);
if (m == null) if (m == null)
return false; return false;
break; break;
+2 -2
View File
@@ -4396,7 +4396,7 @@ namespace Game.Spells
Log.outDebug(LogFilter.Spells, "Spell: {0} Effect : {1}", m_spellInfo.Id, eff); Log.outDebug(LogFilter.Spells, "Spell: {0} Effect : {1}", m_spellInfo.Id, eff);
damage = CalculateDamage(i, unitTarget, out variance); damage = CalculateDamage(i, unitTarget, out _variance);
bool preventDefault = CallScriptEffectHandlers(i, mode); bool preventDefault = CallScriptEffectHandlers(i, mode);
@@ -7283,7 +7283,7 @@ namespace Game.Spells
public WorldLocation destTarget; public WorldLocation destTarget;
public int damage; public int damage;
SpellMissInfo targetMissInfo; SpellMissInfo targetMissInfo;
float variance; float _variance;
SpellEffectHandleMode effectHandleMode; SpellEffectHandleMode effectHandleMode;
public SpellEffectInfo effectInfo; public SpellEffectInfo effectInfo;
// used in effects handlers // used in effects handlers
+7 -10
View File
@@ -156,10 +156,7 @@ namespace Game.Spells
// Meteor like spells (divided damage to targets) // Meteor like spells (divided damage to targets)
if (m_spellInfo.HasAttribute(SpellCustomAttributes.ShareDamage)) if (m_spellInfo.HasAttribute(SpellCustomAttributes.ShareDamage))
{ {
int count = m_UniqueTargetInfo.Count(targetInfo => int count = m_UniqueTargetInfo.Count(targetInfo => Convert.ToBoolean(targetInfo.effectMask & (1 << (int)effIndex)));
{
return Convert.ToBoolean(targetInfo.effectMask & (1 << (int)effIndex));
});
// divide to all targets // divide to all targets
if (count != 0) if (count != 0)
@@ -255,7 +252,7 @@ namespace Game.Spells
if (m_originalCaster != null && apply_direct_bonus) if (m_originalCaster != null && apply_direct_bonus)
{ {
uint bonus = m_originalCaster.SpellDamageBonusDone(unitTarget, m_spellInfo, (uint)damage, DamageEffectType.SpellDirect, effectInfo); uint bonus = m_originalCaster.SpellDamageBonusDone(unitTarget, m_spellInfo, (uint)damage, DamageEffectType.SpellDirect, effectInfo);
damage = (int)(bonus + (bonus * variance)); damage = (int)(bonus + (bonus * _variance));
damage = (int)unitTarget.SpellDamageBonusTaken(m_originalCaster, m_spellInfo, (uint)damage, DamageEffectType.SpellDirect, effectInfo); damage = (int)unitTarget.SpellDamageBonusTaken(m_originalCaster, m_spellInfo, (uint)damage, DamageEffectType.SpellDirect, effectInfo);
} }
@@ -827,7 +824,7 @@ namespace Game.Spells
// add spell damage bonus // add spell damage bonus
uint bonus = m_caster.SpellDamageBonusDone(unitTarget, m_spellInfo, (uint)damage, DamageEffectType.SpellDirect, effectInfo); uint bonus = m_caster.SpellDamageBonusDone(unitTarget, m_spellInfo, (uint)damage, DamageEffectType.SpellDirect, effectInfo);
damage = (int)(bonus + (bonus * variance)); damage = (int)(bonus + (bonus * _variance));
damage = (int)unitTarget.SpellDamageBonusTaken(m_caster, m_spellInfo, (uint)damage, DamageEffectType.SpellDirect, effectInfo); damage = (int)unitTarget.SpellDamageBonusTaken(m_caster, m_spellInfo, (uint)damage, DamageEffectType.SpellDirect, effectInfo);
int newDamage = -(unitTarget.ModifyPower(powerType, -damage)); int newDamage = -(unitTarget.ModifyPower(powerType, -damage));
@@ -963,7 +960,7 @@ namespace Game.Spells
{ {
addhealth = (int)caster.SpellHealingBonusDone(unitTarget, m_spellInfo, (uint)addhealth, DamageEffectType.Heal, effectInfo); addhealth = (int)caster.SpellHealingBonusDone(unitTarget, m_spellInfo, (uint)addhealth, DamageEffectType.Heal, effectInfo);
uint bonus = caster.SpellHealingBonusDone(unitTarget, m_spellInfo, (uint)addhealth, DamageEffectType.Heal, effectInfo); uint bonus = caster.SpellHealingBonusDone(unitTarget, m_spellInfo, (uint)addhealth, DamageEffectType.Heal, effectInfo);
damage = (int)(bonus + (bonus * variance)); damage = (int)(bonus + (bonus * _variance));
} }
addhealth = (int)unitTarget.SpellHealingBonusTaken(caster, m_spellInfo, (uint)addhealth, DamageEffectType.Heal, effectInfo); addhealth = (int)unitTarget.SpellHealingBonusTaken(caster, m_spellInfo, (uint)addhealth, DamageEffectType.Heal, effectInfo);
@@ -1009,7 +1006,7 @@ namespace Game.Spells
return; return;
uint heal = m_originalCaster.SpellHealingBonusDone(unitTarget, m_spellInfo, (uint)damage, DamageEffectType.Heal, effectInfo); uint heal = m_originalCaster.SpellHealingBonusDone(unitTarget, m_spellInfo, (uint)damage, DamageEffectType.Heal, effectInfo);
heal += (uint)(heal * variance); heal += (uint)(heal * _variance);
m_healing += (int)unitTarget.SpellHealingBonusTaken(m_originalCaster, m_spellInfo, heal, DamageEffectType.Heal, effectInfo); m_healing += (int)unitTarget.SpellHealingBonusTaken(m_originalCaster, m_spellInfo, heal, DamageEffectType.Heal, effectInfo);
} }
@@ -1024,7 +1021,7 @@ namespace Game.Spells
return; return;
uint bonus = m_caster.SpellDamageBonusDone(unitTarget, m_spellInfo, (uint)damage, DamageEffectType.SpellDirect, effectInfo); uint bonus = m_caster.SpellDamageBonusDone(unitTarget, m_spellInfo, (uint)damage, DamageEffectType.SpellDirect, effectInfo);
damage = (int)(bonus + (bonus * variance)); damage = (int)(bonus + (bonus * _variance));
damage = (int)unitTarget.SpellDamageBonusTaken(m_caster, m_spellInfo, (uint)damage, DamageEffectType.SpellDirect, effectInfo); damage = (int)unitTarget.SpellDamageBonusTaken(m_caster, m_spellInfo, (uint)damage, DamageEffectType.SpellDirect, effectInfo);
Log.outDebug(LogFilter.Spells, "HealthLeech :{0}", damage); Log.outDebug(LogFilter.Spells, "HealthLeech :{0}", damage);
@@ -1908,7 +1905,7 @@ namespace Game.Spells
if (dispelList.Empty()) if (dispelList.Empty())
return; return;
int remaining = dispelList.Count(); int remaining = dispelList.Count;
// Ok if exist some buffs for dispel try dispel it // Ok if exist some buffs for dispel try dispel it
uint failCount = 0; uint failCount = 0;
+1 -1
View File
@@ -3608,7 +3608,7 @@ namespace Game.Spells
public bool HasAttribute(SpellAttr13 attribute) { return Convert.ToBoolean(AttributesEx13 & attribute); } public bool HasAttribute(SpellAttr13 attribute) { return Convert.ToBoolean(AttributesEx13 & attribute); }
public bool HasAttribute(SpellCustomAttributes attribute) { return Convert.ToBoolean(AttributesCu & attribute); } public bool HasAttribute(SpellCustomAttributes attribute) { return Convert.ToBoolean(AttributesCu & attribute); }
public bool HasAnyAuraInterruptFlag() { return AuraInterruptFlags.Any(flag => { return flag != 0; }); } public bool HasAnyAuraInterruptFlag() { return AuraInterruptFlags.Any(flag => flag != 0); }
public bool HasAuraInterruptFlag(SpellAuraInterruptFlags flag) { return (AuraInterruptFlags[0] & (uint)flag) != 0; } public bool HasAuraInterruptFlag(SpellAuraInterruptFlags flag) { return (AuraInterruptFlags[0] & (uint)flag) != 0; }
public bool HasAuraInterruptFlag(SpellAuraInterruptFlags2 flag) { return (AuraInterruptFlags[1] & (uint)flag) != 0; } public bool HasAuraInterruptFlag(SpellAuraInterruptFlags2 flag) { return (AuraInterruptFlags[1] & (uint)flag) != 0; }
+1 -1
View File
@@ -471,7 +471,7 @@ namespace Game.Entities
return false; return false;
var costs = eventInfo.GetProcSpell().GetPowerCost(); var costs = eventInfo.GetProcSpell().GetPowerCost();
var m = costs.Find(cost => { return cost.Amount > 0; }); var m = costs.Find(cost => cost.Amount > 0);
if (m == null) if (m == null)
return false; return false;
} }
+1 -1
View File
@@ -191,7 +191,7 @@ namespace Game
tempGroup = textGroupContainer; tempGroup = textGroupContainer;
} }
var textEntry = tempGroup.SelectRandomElementByWeight(t => { return t.probability; }); var textEntry = tempGroup.SelectRandomElementByWeight(t => t.probability);
ChatMsg finalType = (msgType == ChatMsg.Addon) ? textEntry.type : msgType; ChatMsg finalType = (msgType == ChatMsg.Addon) ? textEntry.type : msgType;
Language finalLang = (language == Language.Addon) ? textEntry.lang : language; Language finalLang = (language == Language.Addon) ? textEntry.lang : language;
@@ -252,8 +252,8 @@ namespace Scripts.EasternKingdoms.Karazhan
{ {
OUT_SAVE_INST_DATA(); OUT_SAVE_INST_DATA();
strSaveData = string.Format("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11}", m_auiEncounter[0], m_auiEncounter[1], m_auiEncounter[2], m_auiEncounter[3], strSaveData =
m_auiEncounter[4], m_auiEncounter[5], m_auiEncounter[6], m_auiEncounter[7], m_auiEncounter[8], m_auiEncounter[9], m_auiEncounter[10], m_auiEncounter[11]); $"{m_auiEncounter[0]} {m_auiEncounter[1]} {m_auiEncounter[2]} {m_auiEncounter[3]} {m_auiEncounter[4]} {m_auiEncounter[5]} {m_auiEncounter[6]} {m_auiEncounter[7]} {m_auiEncounter[8]} {m_auiEncounter[9]} {m_auiEncounter[10]} {m_auiEncounter[11]}";
SaveToDB(); SaveToDB();
OUT_SAVE_INST_DATA_COMPLETE(); OUT_SAVE_INST_DATA_COMPLETE();
@@ -330,16 +330,16 @@ namespace Scripts.Northrend.CrusadersColiseum.TrialOfTheChampion
} }
} }
bool GrandChampionsOutVehicle(Creature me) bool GrandChampionsOutVehicle(Creature creature)
{ {
InstanceScript instance = me.GetInstanceScript(); InstanceScript instance = creature.GetInstanceScript();
if (instance == null) if (instance == null)
return false; return false;
Creature pGrandChampion1 = ObjectAccessor.GetCreature(me, instance.GetGuidData((uint)Data64.DATA_GRAND_CHAMPION_1)); Creature pGrandChampion1 = ObjectAccessor.GetCreature(creature, instance.GetGuidData((uint)Data64.DATA_GRAND_CHAMPION_1));
Creature pGrandChampion2 = ObjectAccessor.GetCreature(me, instance.GetGuidData((uint)Data64.DATA_GRAND_CHAMPION_2)); Creature pGrandChampion2 = ObjectAccessor.GetCreature(creature, instance.GetGuidData((uint)Data64.DATA_GRAND_CHAMPION_2));
Creature pGrandChampion3 = ObjectAccessor.GetCreature(me, instance.GetGuidData((uint)Data64.DATA_GRAND_CHAMPION_3)); Creature pGrandChampion3 = ObjectAccessor.GetCreature(creature, instance.GetGuidData((uint)Data64.DATA_GRAND_CHAMPION_3));
if (pGrandChampion1 && pGrandChampion2 && pGrandChampion3) if (pGrandChampion1 && pGrandChampion2 && pGrandChampion3)
{ {
@@ -266,7 +266,8 @@ namespace Scripts.Northrend.CrusadersColiseum.TrialOfTheChampion
{ {
OUT_SAVE_INST_DATA(); OUT_SAVE_INST_DATA();
string str_data = string.Format("T C {0} {1} {2} {3} {4} {5}", m_auiEncounter[0], m_auiEncounter[1], m_auiEncounter[2], m_auiEncounter[3], uiGrandChampionsDeaths, uiMovementDone); string str_data =
$"T C {m_auiEncounter[0]} {m_auiEncounter[1]} {m_auiEncounter[2]} {m_auiEncounter[3]} {uiGrandChampionsDeaths} {uiMovementDone}";
OUT_SAVE_INST_DATA_COMPLETE(); OUT_SAVE_INST_DATA_COMPLETE();
return str_data; return str_data;
@@ -309,10 +309,7 @@ namespace Scripts.Northrend.FrozenHalls.ForgeOfSouls.Bronjahm
void FilterTargets(List<WorldObject> targets) void FilterTargets(List<WorldObject> targets)
{ {
Unit caster = GetCaster(); Unit caster = GetCaster();
targets.RemoveAll(target => targets.RemoveAll(target => caster.GetExactDist2d(target) <= 10.0f);
{
return caster.GetExactDist2d(target) <= 10.0f;
});
} }
public override void Register() public override void Register()
+1 -1
View File
@@ -1741,7 +1741,7 @@ namespace Scripts.Northrend.Ulduar
{ {
void FilterTargets(List<WorldObject> targets) void FilterTargets(List<WorldObject> targets)
{ {
targets.RemoveAll(obj => { return obj.ToUnit() && (obj.ToUnit().GetVehicleBase() || obj.HasFlag(UnitFields.Flags, UnitFlags.NonAttackable)); }); targets.RemoveAll(obj => obj.ToUnit() && (obj.ToUnit().GetVehicleBase() || obj.HasFlag(UnitFields.Flags, UnitFlags.NonAttackable)));
} }
public override void Register() public override void Register()
+1 -1
View File
@@ -649,7 +649,7 @@ namespace Scripts.Spells.Druid
Unit caster = eventInfo.GetActor(); Unit caster = eventInfo.GetActor();
var costs = spell.GetPowerCost(); var costs = spell.GetPowerCost();
var m = costs.First(cost => { return cost.Power == PowerType.Mana; }); var m = costs.First(cost => cost.Power == PowerType.Mana);
if (m == null) if (m == null)
return; return;
+2 -5
View File
@@ -1462,7 +1462,7 @@ namespace Scripts.Spells.Items
if (spell != null) if (spell != null)
{ {
var costs = spell.GetPowerCost(); var costs = spell.GetPowerCost();
var m = costs.FirstOrDefault(cost => { return cost.Power == PowerType.Mana && cost.Amount > 0; }); var m = costs.FirstOrDefault(cost => cost.Power == PowerType.Mana && cost.Amount > 0);
if (m != null) if (m != null)
return true; return true;
} }
@@ -3040,10 +3040,7 @@ namespace Scripts.Spells.Items
void FilterTargets(List<WorldObject> targets) void FilterTargets(List<WorldObject> targets)
{ {
targets.RemoveAll(obj => targets.RemoveAll(obj => !obj.IsTypeId(TypeId.Player) && !obj.IsTypeId(TypeId.Corpse));
{
return !obj.IsTypeId(TypeId.Player) && !obj.IsTypeId(TypeId.Corpse);
});
if (targets.Empty()) if (targets.Empty())
{ {
+2 -8
View File
@@ -345,10 +345,7 @@ namespace Scripts.Spells.Shaman
{ {
void SelectTargets(List<WorldObject> targets) void SelectTargets(List<WorldObject> targets)
{ {
targets.RemoveAll(target => targets.RemoveAll(target => !target.ToUnit() || target.ToUnit().IsFullHealth());
{
return !target.ToUnit() || target.ToUnit().IsFullHealth();
});
targets.RandomResize(1); targets.RandomResize(1);
@@ -635,10 +632,7 @@ namespace Scripts.Spells.Shaman
void FilterTargets(List<WorldObject> targets) void FilterTargets(List<WorldObject> targets)
{ {
targets.Remove(GetExplTargetUnit()); targets.Remove(GetExplTargetUnit());
targets.RandomResize(target => targets.RandomResize(target => target.IsTypeId(TypeId.Unit) && !target.ToUnit().HasAura(SpellIds.FlameShockMaelstrom, GetCaster().GetGUID()), 1);
{
return target.IsTypeId(TypeId.Unit) && !target.ToUnit().HasAura(SpellIds.FlameShockMaelstrom, GetCaster().GetGUID());
}, 1);
} }
void HandleScript(uint effIndex) void HandleScript(uint effIndex)
+2 -2
View File
@@ -741,7 +741,7 @@ namespace Scripts.World.NpcSpecial
{ {
List<Creature> targets = new List<Creature>(); List<Creature> targets = new List<Creature>();
me.GetCreatureListWithEntryInGrid(targets, CreatureIds.TorchTossingTargetBunny, 60.0f); me.GetCreatureListWithEntryInGrid(targets, CreatureIds.TorchTossingTargetBunny, 60.0f);
targets.RemoveAll(creature => { return creature.GetGUID() == lastTargetGUID; }); targets.RemoveAll(creature => creature.GetGUID() == lastTargetGUID);
if (!targets.Empty()) if (!targets.Empty())
{ {
@@ -788,7 +788,7 @@ namespace Scripts.World.NpcSpecial
{ {
Initialize(); Initialize();
_scheduler.SetValidator(() => { return running; }); _scheduler.SetValidator(() => running);
_scheduler.Schedule(TimeSpan.FromMilliseconds(1), task => _scheduler.Schedule(TimeSpan.FromMilliseconds(1), task =>
{ {