Here are the examples of the csharp api System.Math.Abs(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1889 Examples
19
Source : AreaForm.cs
with MIT License
from 1CM69
with MIT License
from 1CM69
private void mouse_Move(object sender, MouseEventArgs e)
{
int num = 1;
if (this.LeftButtonDown)
{
this.g.DrawRectangle(this.EraserPen, this.CurrentTopLeft.X, this.CurrentTopLeft.Y, this.CurrentBottomRight.X - this.CurrentTopLeft.X, this.CurrentBottomRight.Y - this.CurrentTopLeft.Y);
num = Math.Max(Math.Abs(Cursor.Position.X - this.ClickPoint.X), Math.Abs(Cursor.Position.Y - this.ClickPoint.Y));
this.Cursor = Cursors.Hand;
}
this.CurrentTopLeft.X = this.ClickPoint.X - num;
this.CurrentTopLeft.Y = this.ClickPoint.Y - num;
this.CurrentBottomRight.X = this.ClickPoint.X + num;
this.CurrentBottomRight.Y = this.ClickPoint.Y + num;
this.g.DrawRectangle(this.MyPen, this.CurrentTopLeft.X, this.CurrentTopLeft.Y, this.CurrentBottomRight.X - this.CurrentTopLeft.X, this.CurrentBottomRight.Y - this.CurrentTopLeft.Y);
}
19
Source : GlobalFunctions.cs
with MIT License
from 3RD-Dimension
with MIT License
from 3RD-Dimension
public static string DecimalPlaceNoRounding(double d, int decimalPlaces)
{
d = d * Math.Pow(10, decimalPlaces);
d = Math.Truncate(d);
d = d / Math.Pow(10, decimalPlaces);
return string.Format("{0:N" + Math.Abs(decimalPlaces) + "}", d);
}
19
Source : Solar.cs
with MIT License
from 6tail
with MIT License
from 6tail
public Solar next(int days, bool onlyWorkday)
{
DateTime c = ExactDate.fromYmdHms(year, month, day, hour, minute, second);
if (0 != days)
{
if (!onlyWorkday)
{
c = c.AddDays(days);
}
else
{
int rest = Math.Abs(days);
int add = days < 1 ? -1 : 1;
while (rest > 0)
{
c = c.AddDays(add);
bool work = true;
Holiday holiday = HolidayUtil.getHoliday(c.Year, c.Month, c.Day);
if (null == holiday)
{
string week = c.DayOfWeek.ToString("d");
if ("0".Equals(week)||"6".Equals(week))
{
work = false;
}
}
else
{
work = holiday.isWork();
}
if (work)
{
rest--;
}
}
}
}
return new Solar(c);
}
19
Source : LunarMonth.cs
with MIT License
from 6tail
with MIT License
from 6tail
public override string ToString()
{
return year + "年" + (isLeap() ? "闰" : "") + LunarUtil.MONTH[Math.Abs(month)] + "月(" + dayCount + "天)";
}
19
Source : Mathd.cs
with MIT License
from 734843327
with MIT License
from 734843327
public static int Abs(int value) {
return Math.Abs(value);
}
19
Source : MeshBoolean.cs
with GNU Lesser General Public License v3.0
from 9and3
with GNU Lesser General Public License v3.0
from 9and3
protected override void SolveInstance(IGH_DataAccess DA) {
Random random = new Random();
//Input
GH_Structure<GH_Mesh> B0 = new GH_Structure<GH_Mesh>();
GH_Structure<GH_Mesh> B1 = new GH_Structure<GH_Mesh>();
DA.GetDataTree(0, out B0);
DA.GetDataTree(1, out B1);
int t = 0;
DA.GetData(2, ref t);
double scale = 1.001;
DA.GetData(3, ref scale);
bool showEdges = false;
DA.GetData(5, ref showEdges);
var color = System.Drawing.Color.White;
bool f = DA.GetData(4, ref color);
if (color.R == 255 && color.G == 255 && color.B == 255) {
f = false;
}
//Match trees
var result = new DataTree<Mesh>();
for (int i = 0; i < B0.PathCount; i++) {
var path = B0.Paths[i];
result.Add(B0.get_DataItem(path, 0).Value, path);
if (!B1.PathExists(path)) continue;
HashSet<Point3d> cylindersCenters = new HashSet<Point3d>();
var nonNulls = new List<GH_Mesh>();
foreach (var v in B1[path]) {
if (v != null) {
nonNulls.Add(v);
}
}
for (int j = 0; j < nonNulls.Count; j++) {
var brep = nonNulls[j].Value.DuplicateMesh();
brep.Transform(Rhino.Geometry.Transform.Scale(brep.GetBoundingBox(true).Center, scale));
Mesh mesh = brep;
result.Add(mesh, path);
}
}
//Perform boolean
var resultBoolean = new DataTree<Mesh>();
for (int b = 0; b < result.BranchCount; b++) {
GH_Path path = result.Paths[b];
List<Mesh> m = result.Branch(path);
//Rhino.RhinoApp.WriteLine(m.Count.ToString());
if (m.Count == 1) {
Mesh mm = m[0].DuplicateMesh();
mm.Unweld(0, true);
//DA.SetDataList(0, new Mesh[] { mm });
//if (!f)
mm.VertexColors.CreateMonotoneMesh(System.Drawing.Color.FromArgb(200, 200, 200));
m_.Append(mm);
if(showEdges)
l_.AddRange(MeshEdgesByAngle(mm, 0.37));
if (bbox_.IsValid) bbox_.Union(m_.GetBoundingBox(false)); else bbox_ = m_.GetBoundingBox(false);
resultBoolean.Add(mm, path);
} else {
try {
//Mesh r = f ? PInvokeCSharp.TestLIBIGL.CreateLIBIGLMeshBoolean(m.ToArray(), t) : PInvokeCSharp.TestCGAL.CreateMeshBooleanArray(m.ToArray(), t);
Mesh r = f ? PInvokeCSharp.TestCGAL.CreateMeshBooleanArrayTrackColors(m.ToArray(), color,Math.Abs( t)) : PInvokeCSharp.TestCGAL.CreateMeshBooleanArray(m.ToArray(), Math.Abs(t));
// Mesh r = PInvokeCSharp.TestCGAL.CreateMeshBooleanArrayTrackColors(m.ToArray(), color, t) ;
//resultBoolean.Add(r, path);
if (r.IsValid) {
Mesh[] s = null;
if (t == 0 || t == 1) {
s = r.SplitDisjointPieces();
double[] a = new double[s.Length];
for (int i = 0; i < s.Length; i++)
a[i] = s[i].GetBoundingBox(false).Diagonal.Length;
Array.Sort(a, s);
} else {
s = new Mesh[] { r };
}
if (!f) s[s.Length - 1].VertexColors.CreateMonotoneMesh(System.Drawing.Color.FromArgb(200, 200, 200));
m_.Append(s[s.Length - 1]);
if (showEdges)
l_.AddRange(MeshEdgesByAngle(s[s.Length - 1], 0.37));
if (bbox_.IsValid) bbox_.Union(m_.GetBoundingBox(false)); else bbox_ = m_.GetBoundingBox(false);
resultBoolean.Add(s[s.Length - 1], path);
}
} catch (Exception e) {
Rhino.RhinoApp.WriteLine(e.ToString());
}
}
}
DA.SetDataTree(0, resultBoolean);
}
19
Source : SecondToStringConverter.cs
with MIT License
from 944095635
with MIT License
from 944095635
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is int offset)
{
var absOffset = Math.Abs(offset);
var hour = ((absOffset / 3600)).ToString();
var minute = ((absOffset - ((absOffset / 3600) * 3600)) / 60).ToString();
var second = ((absOffset - ((absOffset / 3600) * 3600)) % 60).ToString();
return $"{(offset >= 0 ? "" : "-")}{hour.PadLeft(2, '0')}:{minute.PadLeft(2, '0')}:{second.PadLeft(2, '0')}";
}
return value;
}
19
Source : AccelCalculator.cs
with MIT License
from a1xd
with MIT License
from a1xd
public static double Magnitude(int x, int y)
{
if (x == 0)
{
return Math.Abs(y);
}
if (y == 0)
{
return Math.Abs(x);
}
return Math.Sqrt(x * x + y * y);
}
19
Source : Caret.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
void RevalidateVisualColumn(VisualLine visualLine)
{
if (visualLine == null)
throw new ArgumentNullException("visualLine");
// mark column as validated
visualColumnValid = true;
int caretOffset = textView.Doreplacedent.GetOffset(position.Location);
int firstDoreplacedentLineOffset = visualLine.FirstDoreplacedentLine.Offset;
position.VisualColumn = visualLine.ValidateVisualColumn(position, textArea.Selection.EnableVirtualSpace);
// search possible caret positions
int newVisualColumnForwards = visualLine.GetNextCaretPosition(position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, textArea.Selection.EnableVirtualSpace);
// If position.VisualColumn was valid, we're done with validation.
if (newVisualColumnForwards != position.VisualColumn) {
// also search backwards so that we can pick the better match
int newVisualColumnBackwards = visualLine.GetNextCaretPosition(position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, textArea.Selection.EnableVirtualSpace);
if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0)
throw ThrowUtil.NoValidCaretPosition();
// determine offsets for new visual column positions
int newOffsetForwards;
if (newVisualColumnForwards >= 0)
newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDoreplacedentLineOffset;
else
newOffsetForwards = -1;
int newOffsetBackwards;
if (newVisualColumnBackwards >= 0)
newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDoreplacedentLineOffset;
else
newOffsetBackwards = -1;
int newVisualColumn, newOffset;
// if there's only one valid position, use it
if (newVisualColumnForwards < 0) {
newVisualColumn = newVisualColumnBackwards;
newOffset = newOffsetBackwards;
} else if (newVisualColumnBackwards < 0) {
newVisualColumn = newVisualColumnForwards;
newOffset = newOffsetForwards;
} else {
// two valid positions: find the better match
if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) {
// backwards is better
newVisualColumn = newVisualColumnBackwards;
newOffset = newOffsetBackwards;
} else {
// forwards is better
newVisualColumn = newVisualColumnForwards;
newOffset = newOffsetForwards;
}
}
this.Position = new TextViewPosition(textView.Doreplacedent.GetLocation(newOffset), newVisualColumn);
}
isInVirtualSpace = (position.VisualColumn > visualLine.VisualLength);
}
19
Source : RopeNode.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
[Conditional("DATACONSISTENCYTEST")]
internal void CheckInvariants()
{
if (height == 0) {
Debug.replacedert(left == null && right == null);
if (contents == null) {
Debug.replacedert(this is FunctionNode<T>);
Debug.replacedert(length > 0);
Debug.replacedert(isShared);
} else {
Debug.replacedert(contents != null && contents.Length == NodeSize);
Debug.replacedert(length >= 0 && length <= NodeSize);
}
} else {
Debug.replacedert(left != null && right != null);
Debug.replacedert(contents == null);
Debug.replacedert(length == left.length + right.length);
Debug.replacedert(height == 1 + Math.Max(left.height, right.height));
Debug.replacedert(Math.Abs(this.Balance) <= 1);
// this is an additional invariant that forces the tree to combine small leafs to prevent excessive memory usage:
Debug.replacedert(length > NodeSize);
// note that this invariant ensures that all nodes except for the empty rope's single node have at least length 1
if (isShared)
Debug.replacedert(left.isShared && right.isShared);
left.CheckInvariants();
right.CheckInvariants();
}
}
19
Source : RopeNode.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
internal void Rebalance()
{
// Rebalance() shouldn't be called on shared nodes - it's only called after modifications!
Debug.replacedert(!isShared);
// leaf nodes are always balanced (we don't use 'height' to detect leaf nodes here
// because Balance is supposed to recompute the height).
if (left == null)
return;
// ensure we didn't miss a MergeIfPossible step
Debug.replacedert(this.length > NodeSize);
// We need to loop until it's balanced. Rotations might cause two small leaves to combine to a larger one,
// which changes the height and might mean we need additional balancing steps.
while (Math.Abs(this.Balance) > 1) {
// AVL balancing
// note: because we don't care about the idenreplacedy of concat nodes, this works a little different than usual
// tree rotations: in our implementation, the "this" node will stay at the top, only its children are rearranged
if (this.Balance > 1) {
if (right.Balance < 0) {
right = right.CloneIfShared();
right.RotateRight();
}
this.RotateLeft();
// If 'this' was unbalanced by more than 2, we've shifted some of the inbalance to the left node; so rebalance that.
this.left.Rebalance();
} else if (this.Balance < -1) {
if (left.Balance > 0) {
left = left.CloneIfShared();
left.RotateLeft();
}
this.RotateRight();
// If 'this' was unbalanced by more than 2, we've shifted some of the inbalance to the right node; so rebalance that.
this.right.Rebalance();
}
}
Debug.replacedert(Math.Abs(this.Balance) <= 1);
this.height = (byte)(1 + Math.Max(left.height, right.height));
}
19
Source : TextRangeProvider.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
private int MoveOffset(int offset, CaretPositioningMode mode, int count)
{
var direction = count < 0 ? LogicalDirection.Backward : LogicalDirection.Forward;
count = Math.Abs(count);
for (int i = 0; i < count; i++) {
int newOffset = TextUtilities.GetNextCaretPosition(doc, offset, direction, mode);
if (newOffset == offset || newOffset < 0)
break;
offset = newOffset;
}
return offset;
}
19
Source : FdbTupleExtensions.cs
with MIT License
from abdullin
with MIT License
from abdullin
public static IFdbTuple Truncate([NotNull] this IFdbTuple tuple, int count)
{
tuple.OfSizeAtLeast(Math.Abs(count));
if (count < 0)
{
int offset = tuple.Count + count;
return Substring(tuple, offset, -count);
}
else
{
return Substring(tuple, 0, count);
}
}
19
Source : Dock.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public bool TryMoveToFreeSpace(DockPosition position)
{
if (dockPositions == null)
{
UpdatePositions();
}
if (!dockPositions.Contains(position))
{
Debug.LogError("Looking for a DockPosition in the wrong Dock.");
return false;
}
var index = dockPositions.IndexOf(position);
if (!dockPositions[index].IsOccupied)
{
// Already free
return true;
}
// Where is the closest free space? (on a tie, favor left)
int? closestFreeSpace = null;
int distanceToClosestFreeSpace = int.MaxValue;
for (int i = 0; i < dockPositions.Count; i++)
{
var distance = Math.Abs(index - i);
if (!dockPositions[i].IsOccupied && distance < distanceToClosestFreeSpace)
{
closestFreeSpace = i;
distanceToClosestFreeSpace = distance;
}
}
if (closestFreeSpace == null)
{
// No free space
return false;
}
if (closestFreeSpace < index)
{
// Move left
// Check if we can undock all of them
for (int i = closestFreeSpace.Value + 1; i <= index; i++)
{
if (!dockPositions[i].DockedObject.CanUndock)
{
return false;
}
}
for (int i = closestFreeSpace.Value + 1; i <= index; i++)
{
MoveDockedObject(i, i - 1);
}
}
else
{
// Move right
// Check if we can undock all of them
for (int i = closestFreeSpace.Value - 1; i >= index; i--)
{
if (!dockPositions[i].DockedObject.CanUndock)
{
return false;
}
}
for (int i = closestFreeSpace.Value - 1; i >= index; i--)
{
MoveDockedObject(i, i + 1);
}
}
return true;
}
19
Source : CoverFlowControl.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void CoverFlowItemSelected(object sender, EventArgs e)
{
if (sender is CoverFlowItemControl item)
{
var index = _items.IndexOf(item);
if (index >= 0)
{
if (NextPrevSelectionOnly && Math.Abs(index - SelectedIndex) > 1)
{
return;
}
if (index != SelectedIndex)
{
IndexSelected(index, true);
}
else
{
var handler = SelectedItemClick;
handler?.Invoke(this, new CoverFlowEventArgs
{
Index = index,
Item = _items[index].Content,
MouseClick = false
});
}
}
}
}
19
Source : LandblockId.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public bool IsAdjacentTo(LandblockId block)
{
return (Math.Abs(this.LandblockX - block.LandblockX) <= 1 && Math.Abs(this.LandblockY - block.LandblockY) <= 1);
}
19
Source : BishopPiece.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public override bool CanMove(int dx, int dy)
{
return Math.Abs(dx) == Math.Abs(dy);
}
19
Source : KingPiece.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public override bool CanMove(int dx, int dy)
{
return Math.Abs(dx) < 2 && Math.Abs(dy) < 2;
}
19
Source : KnightPiece.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public override bool CanMove(int dx, int dy)
{
var adx = Math.Abs(dx);
var ady = Math.Abs(dy);
return adx == 1 && ady == 2 || adx == 2 && ady == 1;
}
19
Source : QuestManager.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void SetQuestCompletions(string questFormat, int questCompletions = 0)
{
var questName = GetQuestName(questFormat);
var maxSolves = GetMaxSolves(questName);
var numTimesCompleted = maxSolves > -1 ? Math.Min(questCompletions, maxSolves) : Math.Abs(questCompletions);
var quest = GetOrCreateQuest(questName, out var questRegistryWasCreated);
if (questRegistryWasCreated)
{
quest.LastTimeCompleted = (uint) Time.GetUnixTime();
quest.NumTimesCompleted = numTimesCompleted; // initialize the quest to the given completions
quest.CharacterId = IDtoUseForQuestRegistry;
if (Debug) Console.WriteLine($"{Name}.QuestManager.SetQuestCompletions({questFormat}): initialized quest to {quest.NumTimesCompleted}");
if (Creature is Player player)
{
player.CharacterChangesDetected = true;
player.ContractManager.NotifyOfQuestUpdate(quest.QuestName);
}
}
else
{
// update existing quest
quest.LastTimeCompleted = (uint)Time.GetUnixTime();
quest.NumTimesCompleted = numTimesCompleted;
if (Debug) Console.WriteLine($"{Name}.QuestManager.SetQuestCompletions({questFormat}): initialized quest to {quest.NumTimesCompleted}");
if (Creature is Player player)
{
player.CharacterChangesDetected = true;
player.ContractManager.NotifyOfQuestUpdate(quest.QuestName);
}
}
}
19
Source : PawnPiece.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public override bool CanMove(int dx, int dy)
{
var startRank = Color == ChessColor.White ? 2 : 7;
var hasMoved = startRank != Coord.Y;
var ady = Math.Abs(dy);
return dx == 0 && (ady == 1 || ady == 2 && !hasMoved);
}
19
Source : PawnPiece.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public override bool CanAttack(int dx, int dy)
{
var y = Color == ChessColor.White ? 1 : -1;
return Math.Abs(dx) == 1 && dy == y;
}
19
Source : QueenPiece.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public override bool CanMove(int dx, int dy)
{
return dx == 0 || dy == 0 || Math.Abs(dx) == Math.Abs(dy);
}
19
Source : Creature_Vitals.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public bool VitalHeartBeat(CreatureVital vital)
{
// Current and MaxValue are properties and include overhead in getting their values. We cache them so we only hit the overhead once.
var vitalCurrent = vital.Current;
var vitalMax = vital.MaxValue;
if (vitalCurrent == vitalMax && vital.RegenRate > 0)
return false;
if (vitalCurrent > vitalMax)
{
UpdateVital(vital, vitalMax);
return true;
}
if (vital.RegenRate == 0.0) return false;
// take attributes into consideration (strength, endurance)
var attributeMod = GetAttributeMod(vital);
// take stance into consideration (combat, crouch, sitting, sleeping)
var stanceMod = GetStanceMod(vital);
// take enchantments into consideration:
// (regeneration / rejuvenation / mana renewal / etc.)
var enchantmentMod = EnchantmentManager.GetRegenerationMod(vital);
var augMod = 1.0f;
if (this is Player player && player.AugmentationFasterRegen > 0)
augMod += player.AugmentationFasterRegen;
// cap rate?
var currentTick = vital.RegenRate * attributeMod * stanceMod * enchantmentMod * augMod;
// add in partially acreplacedulated / rounded vitals from previous tick(s)
var totalTick = currentTick + vital.PartialRegen;
// acreplacedulate partial vital rates between ticks
var intTick = (int)totalTick;
vital.PartialRegen = totalTick - intTick;
if (intTick != 0)
{
//if (this is Player)
//Console.WriteLine($"VitalTick({vital.Vital.ToSentence()}): attributeMod={attributeMod}, stanceMod={stanceMod}, enchantmentMod={enchantmentMod}, regenRate={vital.RegenRate}, currentTick={currentTick}, totalTick={totalTick}, acreplacedulated={vital.PartialRegen}");
UpdateVitalDelta(vital, intTick);
if (vital.Vital == PropertyAttribute2nd.MaxHealth)
{
if (intTick > 0)
DamageHistory.OnHeal((uint)intTick);
else
{
DamageHistory.Add(this, DamageType.Health, (uint)Math.Abs(intTick));
if (Health.Current <= 0)
{
OnDeath(DamageHistory.LastDamager, DamageType.Health);
Die();
}
}
return true;
}
}
return false;
}
19
Source : Hotspot.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private void Activate(Creature creature)
{
if (!IsHot) return;
var amount = DamageNext;
var iAmount = (int)Math.Round(amount);
var player = creature as Player;
switch (DamageType)
{
default:
if (creature.Invincible) return;
amount *= creature.GetResistanceMod(DamageType, this, null);
if (player != null)
iAmount = player.TakeDamage(this, DamageType, amount, Server.Enreplacedy.BodyPart.Foot);
else
iAmount = (int)creature.TakeDamage(this, DamageType, amount);
if (creature.IsDead && Creatures.Contains(creature.Guid))
Creatures.Remove(creature.Guid);
break;
case DamageType.Mana:
iAmount = creature.UpdateVitalDelta(creature.Mana, -iAmount);
break;
case DamageType.Stamina:
iAmount = creature.UpdateVitalDelta(creature.Stamina, -iAmount);
break;
case DamageType.Health:
iAmount = creature.UpdateVitalDelta(creature.Health, -iAmount);
if (iAmount > 0)
creature.DamageHistory.OnHeal((uint)iAmount);
else
creature.DamageHistory.Add(this, DamageType.Health, (uint)-iAmount);
break;
}
if (!Visibility)
EnqueueBroadcast(new GameMessageSound(Guid, Sound.TriggerActivated, 1.0f));
if (player != null && !string.IsNullOrWhiteSpace(ActivationTalk) && iAmount != 0)
player.Session.Network.EnqueueSend(new GameMessageSystemChat(ActivationTalk.Replace("%i", Math.Abs(iAmount).ToString()), ChatMessageType.Broadcast));
// perform activation emote
if (ActivationResponse.HasFlag(ActivationResponse.Emote))
OnEmote(creature);
}
19
Source : ItemFinder.cs
with MIT License
from adainrivers
with MIT License
from adainrivers
private static int DamerauLevenshteinDistance(string source, string target, int threshold)
{
int length1 = source.Length;
int length2 = target.Length;
// Return trivial case - difference in string lengths exceeds threshhold
if (Math.Abs(length1 - length2) > threshold) { return int.MaxValue; }
// Ensure arrays [i] / length1 use shorter length
if (length1 > length2)
{
Swap(ref target, ref source);
Swap(ref length1, ref length2);
}
int maxi = length1;
int maxj = length2;
int[] dCurrent = new int[maxi + 1];
int[] dMinus1 = new int[maxi + 1];
int[] dMinus2 = new int[maxi + 1];
int[] dSwap;
for (int i = 0; i <= maxi; i++) { dCurrent[i] = i; }
int jm1 = 0, im1 = 0, im2 = -1;
for (int j = 1; j <= maxj; j++)
{
// Rotate
dSwap = dMinus2;
dMinus2 = dMinus1;
dMinus1 = dCurrent;
dCurrent = dSwap;
// Initialize
int minDistance = int.MaxValue;
dCurrent[0] = j;
im1 = 0;
im2 = -1;
for (int i = 1; i <= maxi; i++)
{
int cost = source[im1] == target[jm1] ? 0 : 1;
int del = dCurrent[im1] + 1;
int ins = dMinus1[i] + 1;
int sub = dMinus1[im1] + cost;
//Fastest execution for min value of 3 integers
int min = (del > ins) ? (ins > sub ? sub : ins) : (del > sub ? sub : del);
if (i > 1 && j > 1 && source[im2] == target[jm1] && source[im1] == target[j - 2])
min = Math.Min(min, dMinus2[im2] + cost);
dCurrent[i] = min;
if (min < minDistance) { minDistance = min; }
im1++;
im2++;
}
jm1++;
if (minDistance > threshold) { return int.MaxValue; }
}
int result = dCurrent[maxi];
return (result > threshold) ? int.MaxValue : result;
}
19
Source : VideoPlayerRenderer.cs
with MIT License
from adamfisher
with MIT License
from adamfisher
public virtual bool CanSeek(int time)
{
var control = Control;
var absoluteTime = Math.Abs(time);
return control != null &&
((time > 0 && control.CanSeek && (control.Position.Add(TimeSpan.FromSeconds(absoluteTime)) <= control.NaturalDuration))
|| (time < 0 && control.CanSeek && (control.Position.Subtract(TimeSpan.FromSeconds(absoluteTime)) >= TimeSpan.Zero)));
}
19
Source : Global.cs
with MIT License
from adamped
with MIT License
from adamped
public static string ToRadixString(this int value, int radix)
{
var digits = "0123456789abcdefghijklmnopqrstuvwxyz";
radix = Math.Abs(radix);
if (radix > digits.Length || radix < 2)
throw new ArgumentOutOfRangeException("radix", radix, string.Format("Radix has to be > 2 and < {0}", digits.Length));
string result = string.Empty;
int quotient = Math.Abs(value);
while (0 < quotient)
{
int temp = quotient % radix;
result = digits[temp] + result;
quotient /= radix;
}
return result;
}
19
Source : BigDecimal.cs
with MIT License
from AdamWhiteHat
with MIT License
from AdamWhiteHat
private static String ToString(BigInteger mantissa, int exponent, IFormatProvider provider)
{
if (provider == null) throw new ArgumentNullException();
if (mantissa == null || BigDecimalNumberFormatInfo == null) { return NullString; }
NumberFormatInfo formatProvider = NumberFormatInfo.GetInstance(provider);
bool negativeValue = (mantissa.Sign == -1);
bool negativeExponent = (Math.Sign(exponent) == -1);
string result = BigInteger.Abs(mantissa).ToString();
int absExp = Math.Abs(exponent);
if (negativeExponent)
{
if (absExp > result.Length)
{
int zerosToAdd = Math.Abs(absExp - result.Length);
string zeroString = string.Join(string.Empty, Enumerable.Repeat(formatProvider.NativeDigits[0], zerosToAdd));
result = zeroString + result;
result = result.Insert(0, formatProvider.NumberDecimalSeparator);
result = result.Insert(0, formatProvider.NativeDigits[0]);
}
else
{
int indexOfRadixPoint = Math.Abs(absExp - result.Length);
result = result.Insert(indexOfRadixPoint, formatProvider.NumberDecimalSeparator);
if (indexOfRadixPoint == 0)
{
result = result.Insert(0, formatProvider.NativeDigits[0]);
}
}
result = result.TrimEnd(new char[] { '0' });
if (result.Last().ToString() == formatProvider.NumberDecimalSeparator)
{
result = result.Substring(0, result.Length - 1);
}
}
else
{
string zeroString = string.Join(string.Empty, Enumerable.Repeat(formatProvider.NativeDigits[0], absExp));
result += zeroString;
}
if (negativeExponent) // Prefix "0."
{
}
if (negativeValue) // Prefix "-"
{
result = result.Insert(0, formatProvider.NegativeSign);
}
return result;
}
19
Source : Bin.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
public void FreeCell(int index)
{
int freeIndex = index - _header.FileOffset;
int len = EndianUtilities.ToInt32LittleEndian(_buffer, freeIndex);
if (len >= 0)
{
throw new ArgumentException("Attempt to free non-allocated cell");
return;
}
len = Math.Abs(len);
// If there's a free cell before this one, combine
int i = 0;
while (i < _freeCells.Count && _freeCells[i].Offset < freeIndex)
{
if (_freeCells[i].Offset + _freeCells[i].Count == freeIndex)
{
freeIndex = _freeCells[i].Offset;
len += _freeCells[i].Count;
_freeCells.RemoveAt(i);
}
else
{
++i;
}
}
// If there's a free cell after this one, combine
if (i < _freeCells.Count && _freeCells[i].Offset == freeIndex + len)
{
len += _freeCells[i].Count;
_freeCells.RemoveAt(i);
}
// Record the new free cell
_freeCells.Insert(i, new Range<int, int>(freeIndex, len));
// Free cells are indicated by length > 0
EndianUtilities.WriteBytesLittleEndian(len, _buffer, freeIndex);
_fileStream.Position = _streamPos + freeIndex;
_fileStream.Write(_buffer, freeIndex, 4);
}
19
Source : PadView.cs
with MIT License
from ademanuele
with MIT License
from ademanuele
partial void PreviousTestedProjectTapped(NSButton sender)
{
if (currentResults == null) return;
PresentCoverageAtIndex(Math.Abs(presentedResultIndex - 1) % currentResults.Count);
}
19
Source : CoverFlow.cs
with GNU General Public License v3.0
from aduskin
with GNU General Public License v3.0
from aduskin
private void UpdateIndex(int newIndex, int oldIndex)
{
var animate = Math.Abs(newIndex - oldIndex) < MaxShowCountHalf;
UpdateShowRange();
if (newIndex > oldIndex)
{
if (oldIndex < _firstShowIndex)
{
oldIndex = _firstShowIndex;
}
for (var i = oldIndex; i <= newIndex; i++)
{
Move(i, animate);
}
}
else
{
if (oldIndex > _lastShowIndex)
{
oldIndex = _lastShowIndex;
}
for (var i = oldIndex; i >= newIndex; i--)
{
Move(i, animate);
}
}
_camera.Position = new Point3D(CoverFlowItem.Interval * newIndex, _camera.Position.Y,
_camera.Position.Z);
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private static bool IsBelowMinFloorsApart(int level)
{
if (Config.MinFloorsBetweenMonsterFloors <= 0)
return false;
foreach(int i in monsterFloors)
{
if(Math.Abs(level-i) <= Config.MinFloorsBetweenMonsterFloors){
return true;
}
}
return false;
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void SpawnBossLoot(GameLocation location, float x, float y, float difficulty)
{
Vector2 playerPosition = new Vector2((float)Game1.player.GetBoundingBox().Center.X, (float)Game1.player.GetBoundingBox().Center.Y);
foreach (string loot in BossLootList.loot)
{
string[] loota = loot.Split('/');
if (!int.TryParse(loota[0], out int objectToAdd))
{
try
{
objectToAdd = Game1.objectInformation.First(p => p.Value.StartsWith($"{loota[0]}/")).Key;
}
catch
{
PMonitor.Log($"loot object {loota[0]} is invalid", LogLevel.Error);
continue;
}
}
Object o = new Object(objectToAdd, 1);
if (objectToAdd >= 0)
{
if (o.Name == Game1.content.LoadString("Strings\\StringsFromCSFiles:CraftingRecipe.cs.575"))
{
PMonitor.Log($"object {objectToAdd} is error item");
continue;
}
}
if (!double.TryParse(loota[1], out double chance))
{
PMonitor.Log($"loot chance {loota[1]} is invalid", LogLevel.Error);
continue;
}
while (chance > 1 || (chance > 0 && Game1.random.NextDouble() < chance))
{
if (objectToAdd < 0)
{
Game1.createDebris(Math.Abs(objectToAdd), (int)x, (int)y, (int)Math.Round(Game1.random.Next(10, 40) * difficulty), location);
}
else
{
location.debris.Add(Game1.createItemDebris(o, new Vector2(x, y), Game1.random.Next(4)));
}
chance -= 1;
}
}
}
19
Source : PhoneVisuals.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void Display_RenderedWorld(object sender, StardewModdingAPI.Events.RenderedWorldEventArgs e)
{
Point mousePos = Game1.getMousePosition();
Point lastMousePos = ModEntry.lastMousePosition;
ModEntry.lastMousePosition = mousePos;
if (!ModEntry.phoneOpen)
{
ModEntry.appRunning = false;
ModEntry.runningApp = null;
if (Config.ShowPhoneIcon && Game1.displayHUD && !Game1.eventUp && Game1.currentBillboard == 0 && Game1.gameMode == 3 && !Game1.freezeControls && !Game1.panMode && !Game1.HostPaused && !Game1.game1.takingMapScreenshot)
{
if (ModEntry.clickingPhoneIcon)
{
if(Helper.Input.IsSuppressed(SButton.MouseLeft) && lastMousePos != mousePos)
{
ModEntry.draggingPhoneIcon = true;
Config.PhoneIconOffsetX += mousePos.X - lastMousePos.X;
Config.PhoneIconOffsetY += mousePos.Y - lastMousePos.Y;
ModEntry.phoneIconPosition = PhoneUtils.GetPhoneIconPosition();
}
else if (!Helper.Input.IsSuppressed(SButton.MouseLeft))
{
if (!ModEntry.draggingPhoneIcon)
{
PhoneUtils.TogglePhone(true);
}
else
{
Helper.WriteConfig(Config);
}
ModEntry.clickingPhoneIcon = false;
ModEntry.draggingPhoneIcon = false;
}
}
float rot = 0;
int speed = 3;
if (ModEntry.callingNPC != null && Config.VibratePhoneIcon)
{
ringingTicks++;
rot = ringingTicks % (speed * 4);
if (rot < speed)
rot *= -1;
else if (rot < speed * 3)
rot -= speed * 2;
else
rot = speed * 4 - rot;
rot /= 20f;
}
else
{
ringingTicks = 0;
}
e.SpriteBatch.Draw(ModEntry.backgroundTexture, new Vector2((int)ModEntry.phoneIconPosition.X + ModEntry.phoneTexture.Width / 20, (int)ModEntry.phoneIconPosition.Y + ModEntry.phoneTexture.Height / 20), null, Color.White, rot, new Vector2(ModEntry.phoneTexture.Width / 2, ModEntry.phoneTexture.Height / 2), 0.1f, SpriteEffects.None, 0.86f);
e.SpriteBatch.Draw(ModEntry.phoneTexture, new Vector2((int)ModEntry.phoneIconPosition.X + ModEntry.phoneTexture.Width / 20, (int)ModEntry.phoneIconPosition.Y + ModEntry.phoneTexture.Height / 20), null, Color.White, rot, new Vector2(ModEntry.phoneTexture.Width / 2, ModEntry.phoneTexture.Height / 2), 0.1f, SpriteEffects.None, 0.86f);
}
return;
}
else
{
ModEntry.clickingPhoneIcon = false;
ModEntry.draggingPhoneIcon = false;
}
if (Game1.game1.takingMapScreenshot)
{
return;
}
if (ModEntry.draggingPhone)
{
if (Helper.Input.IsSuppressed(SButton.MouseLeft))
{
if (mousePos != lastMousePos)
{
int x = mousePos.X - lastMousePos.X;
int y = mousePos.Y - lastMousePos.Y;
if (ModEntry.phoneRotated)
{
Config.PhoneRotatedOffsetX += x;
Config.PhoneRotatedOffsetY += y;
}
else
{
Config.PhoneOffsetX += x;
Config.PhoneOffsetY += y;
}
PhoneUtils.RefreshPhoneLayout();
}
}
else
{
ModEntry.context.Helper.WriteConfig(Config);
ModEntry.draggingPhone = false;
Monitor.Log($"released dragging phone");
}
}
else if (Helper.Input.IsSuppressed(SButton.MouseLeft) && !ModEntry.movingAppIcon)
{
int dy = mousePos.Y - lastMousePos.Y;
if (Math.Abs(dy) > 0 && ModEntry.screenRect.Contains(mousePos))
{
ModEntry.clickingApp = -1;
ModEntry.draggingIcons = true;
}
if (ModEntry.draggingIcons)
{
ModEntry.yOffset = (int)Math.Max(Math.Min(0, ModEntry.yOffset + dy), -1 * Math.Max(0, ModEntry.listHeight - PhoneUtils.GetScreenSize().Y));
}
}
e.SpriteBatch.Draw(ModEntry.phoneRotated ? ModEntry.backgroundRotatedTexture : ModEntry.backgroundTexture, ModEntry.phoneRect, Color.White);
e.SpriteBatch.Draw(ModEntry.phoneRotated ? ModEntry.phoneRotatedTexture : ModEntry.phoneTexture, ModEntry.phoneRect, Color.White);
Vector2 screenPos = PhoneUtils.GetScreenPosition();
Vector2 screenSize = PhoneUtils.GetScreenSize();
if (ModEntry.callingNPC != null)
{
Rectangle destRect;
Rectangle portraitSource = Game1.getSourceRectForStandardTileSheet(ModEntry.callingNPC.Portrait, 0, 64, 64);
float scale;
if ((float)portraitSource.Height * screenSize.X / (float)portraitSource.Width > screenSize.Y - Config.AppHeaderHeight)
{
scale = (screenSize.Y - Config.AppHeaderHeight) / (float)portraitSource.Height;
destRect = new Rectangle((int)(screenPos.X + screenSize.X / 2f - portraitSource.Width * scale / 2f), (int)screenPos.Y, (int)(portraitSource.Width * scale), (int)screenSize.Y - Config.AppHeaderHeight);
}
else
{
scale = screenSize.X / (float)portraitSource.Width;
//Monitor.Log($"{screenSize} {portraitSource.Width},{portraitSource.Height} {scale}");
destRect = new Rectangle((int)(screenPos.X), (int)(screenPos.Y + (screenSize.Y - Config.AppHeaderHeight) / 2f - portraitSource.Height * scale / 2f), (int)screenSize.X, (int)(portraitSource.Height * scale));
}
e.SpriteBatch.Draw(ModEntry.callingNPC.Portrait, destRect, new Rectangle?(portraitSource), Color.White);
SpriteText.drawStringHorizontallyCenteredAt(e.SpriteBatch, ModEntry.callingNPC.getName(), destRect.X + destRect.Width / 2, destRect.Bottom + 16, 999999, -1, 999999, 1f, 0.88f, false, -1, 99999);
if (!ModEntry.inCall)
{
Rectangle answerRect = new Rectangle((int)(screenPos.X), ModEntry.screenRect.Bottom - Config.AppHeaderHeight, (int)(screenSize.X / 2f), Config.AppHeaderHeight);
Rectangle declineRect = new Rectangle((int)(screenPos.X + screenSize.X / 2f), ModEntry.screenRect.Bottom - Config.AppHeaderHeight, (int)(screenSize.X / 2f), Config.AppHeaderHeight);
e.SpriteBatch.Draw(ModEntry.answerTexture, answerRect, Color.White);
e.SpriteBatch.Draw(ModEntry.declineTexture, declineRect, Color.White);
float textScale = Config.CallTextScale;
string ans = Helper.Translation.Get("answer");
Vector2 ansSize = Game1.dialogueFont.MeasureString(ans) * textScale;
string dec = Helper.Translation.Get("decline");
Vector2 decSize = Game1.dialogueFont.MeasureString(dec) * textScale;
e.SpriteBatch.DrawString(Game1.dialogueFont, ans, new Vector2(answerRect.X + answerRect.Width / 2f - ansSize.X / 2f, answerRect.Top + answerRect.Height / 2f - ansSize.Y / 2f), Config.CallTextColor, 0f, Vector2.Zero, textScale, SpriteEffects.None,1f);
e.SpriteBatch.DrawString(Game1.dialogueFont, dec, new Vector2(declineRect.X + declineRect.Width / 2f - decSize.X / 2f, declineRect.Top + declineRect.Height / 2f - decSize.Y / 2f), Config.CallTextColor, 0f, Vector2.Zero, textScale, SpriteEffects.None, 1f);
if (ModEntry.clicking && !Helper.Input.IsSuppressed(SButton.MouseLeft))
{
if (answerRect.Contains(mousePos))
{
PhoneUtils.StopRingTone();
MobilePhoneApp.CallNPC(ModEntry.callingNPC);
ModEntry.currentCallRings = 0;
}
else if (declineRect.Contains(mousePos))
{
PhoneUtils.StopRingTone();
ModEntry.currentCallRings = 0;
ModEntry.callingNPC = null;
}
}
}
else if(!ModEntry.buildingInCall)
{
Rectangle endRect = new Rectangle((int)(screenPos.X + screenSize.X / 4), ModEntry.screenRect.Bottom - Config.AppHeaderHeight, (int)(screenSize.X / 2), Config.AppHeaderHeight);
e.SpriteBatch.Draw(ModEntry.declineTexture, endRect, Color.White);
float textScale = Config.CallTextScale;
string ends = Helper.Translation.Get("end-call");
Vector2 endsSize = Game1.dialogueFont.MeasureString(ends) * textScale;
e.SpriteBatch.DrawString(Game1.dialogueFont, ends, new Vector2(endRect.X + endRect.Width / 2f - endsSize.X / 2f, endRect.Top + endRect.Height / 2f - endsSize.Y / 2f), Config.CallTextColor, 0f, Vector2.Zero, textScale, SpriteEffects.None,1f);
if (ModEntry.clicking && !Helper.Input.IsSuppressed(SButton.MouseLeft))
{
if (endRect.Contains(mousePos) && !ModEntry.buildingInCall)
{
if (ModEntry.isReminiscing)
{
Game1.CurrentEvent?.skipEvent();
//ModEntry.reminisceEvent = null;
ModEntry.isReminiscing = false;
}
MobilePhoneCall.EndCall();
if (Game1.activeClickableMenu is DialogueBox)
Game1.activeClickableMenu = null;
}
}
}
if ((ModEntry.clicking || ModEntry.clickingPhoneIcon) && !Helper.Input.IsSuppressed(SButton.MouseLeft))
{
ModEntry.clickingApp = -1;
ModEntry.switchingApp = -1;
ModEntry.movingAppIconOffset = new Point(0, 0);
ModEntry.clickingTicks = 0;
ModEntry.clicking = false;
ModEntry.movingAppIcon = false;
ModEntry.clickingPhoneIcon = false;
ModEntry.draggingPhone = false;
ModEntry.draggingIcons = false;
}
return;
}
if (ModEntry.appRunning)
{
return;
}
if (ModEntry.runningApp == Helper.ModRegistry.ModID && Game1.activeClickableMenu == null)
{
MobilePhoneApp.OpenPhoneBook();
return;
}
List<string> keys = new List<string>(ModEntry.appOrder);
if ((ModEntry.clicking || ModEntry.clickingPhoneIcon) && !Helper.Input.IsSuppressed(SButton.MouseLeft))
{
Monitor.Log($"released click");
if (ModEntry.movingAppIcon && ModEntry.switchingApp != -1)
{
Monitor.Log($"switching app: {ModEntry.switchingApp} clicking app {ModEntry.clickingApp}");
Game1.playSound("stoneStep");
ModEntry.appOrder[ModEntry.clickingApp] = keys[ModEntry.switchingApp];
ModEntry.appOrder[ModEntry.switchingApp] = keys[ModEntry.clickingApp];
keys = new List<string>(ModEntry.appOrder);
Config.AppList = keys.ToArray();
Helper.WriteConfig(Config);
}
else if (ModEntry.draggingIcons)
{
ModEntry.draggingIcons = false;
}
else if(!ModEntry.movingAppIcon)
{
for (int i = 0; i < keys.Count; i++)
{
Vector2 pos = PhoneUtils.GetAppPos(i);
Rectangle r = new Rectangle((int)pos.X, (int)pos.Y, Config.IconWidth, Config.IconHeight);
if (r.Contains(mousePos))
{
if(keys[i] == Helper.ModRegistry.ModID + "_Rotate")
{
Monitor.Log($"rotating phone app");
PhoneUtils.RotatePhone();
}
else if (ModEntry.apps[keys[i]].keyPress != null)
{
Monitor.Log($"pressing key {ModEntry.apps[keys[i]].keyPress}");
PhoneInput.PressKey(ModEntry.apps[keys[i]]);
}
else
{
Monitor.Log($"starting app {ModEntry.apps[keys[i]].name}");
ModEntry.apps[keys[i]].action?.Invoke();
}
}
}
}
ModEntry.clickingApp = -1;
ModEntry.switchingApp = -1;
ModEntry.movingAppIconOffset = new Point(0, 0);
ModEntry.clickingTicks = 0;
ModEntry.clicking = false;
ModEntry.movingAppIcon = false;
ModEntry.clickingPhoneIcon = false;
ModEntry.draggingPhone = false;
ModEntry.draggingIcons = false;
}
else if (ModEntry.clicking && ModEntry.clickingApp != -1 && !ModEntry.movingAppIcon)
{
if (lastMousePos == mousePos)
{
if (ModEntry.clickingTicks > Config.TicksToMoveAppIcon)
{
Game1.playSound("pickUpItem");
ModEntry.movingAppIconOffset = new Point(5,5);
ModEntry.movingAppIcon = true;
}
else
{
ModEntry.clickingTicks++;
}
}
else
{
ModEntry.clickingTicks = 0;
ModEntry.clickingApp = -1;
}
}
else if (ModEntry.movingAppIcon)
{
ModEntry.movingAppIconOffset = new Point(ModEntry.movingAppIconOffset.X + mousePos.X - lastMousePos.X, ModEntry.movingAppIconOffset.Y + mousePos.Y - lastMousePos.Y);
Vector2 currentPos = PhoneUtils.GetAppPos(ModEntry.clickingApp);
if (ModEntry.screenRect.Contains(Utility.Vector2ToPoint(currentPos)))
{
bool alreadySwitched = false;
if(ModEntry.switchingApp != -1)
{
Vector2 pos = PhoneUtils.GetAppPos(ModEntry.switchingApp, true);
if (Vector2.Distance(currentPos, pos) < (Config.IconWidth + Config.IconHeight) / 4f)
alreadySwitched = true;
}
if (!alreadySwitched)
{
for (int i = 0; i < keys.Count; i++)
{
Vector2 pos = PhoneUtils.GetAppPos(i);
if (i != ModEntry.clickingApp && Vector2.Distance(currentPos, pos) < (Config.IconWidth + Config.IconHeight) / 4f)
{
ModEntry.switchingApp = i;
Monitor.Log($"new switching app: {ModEntry.switchingApp} clicking app {ModEntry.clickingApp}");
break;
}
else
{
ModEntry.switchingApp = -1;
}
}
}
}
}
string appHover = null;
bool hover = false;
if (mousePos == lastMousePos && !Helper.Input.IsSuppressed(SButton.MouseLeft))
{
hover = true;
}
else
{
ModEntry.ticksSinceMoved = 0;
}
int screenBottom = (int)(screenPos.Y + screenSize.Y);
for (int i = keys.Count - 1; i >= 0; i--)
{
MobileApp app = ModEntry.apps[keys[i]];
Vector2 appPos = PhoneUtils.GetAppPos(i);
Rectangle r = new Rectangle(0, 0, Config.IconWidth, Config.IconHeight);
Rectangle sourceRect = r;
if (!ModEntry.movingAppIcon || i != ModEntry.clickingApp)
{
if (appPos.Y < screenPos.Y - r.Height * 2 || appPos.Y >= screenBottom)
{
continue;
}
if (appPos.Y < screenPos.Y)
{
int cutTop = (int)screenPos.Y - (int)appPos.Y;
sourceRect = new Rectangle(r.X, r.Y + cutTop, r.Width, r.Height - cutTop);
appPos = new Vector2(appPos.X, screenPos.Y);
}
else if (appPos.Y > screenBottom - r.Height)
{
int cutBottom = screenBottom - r.Height - (int)appPos.Y;
sourceRect = new Rectangle(r.X, r.Y, r.Width, r.Height + cutBottom);
}
}
e.SpriteBatch.Draw(app.icon, new Rectangle((int)appPos.X, (int)appPos.Y, sourceRect.Width, sourceRect.Height), sourceRect, Color.White, 0, Vector2.Zero, SpriteEffects.None, i == ModEntry.clickingApp && ModEntry.movingAppIcon ? 1f : 0.5f);
Rectangle rect = new Rectangle((int)appPos.X, (int)appPos.Y, Config.IconWidth, sourceRect.Height);
if (hover && !Helper.Input.IsSuppressed(SButton.MouseLeft) && rect.Contains(mousePos))
{
ModEntry.ticksSinceMoved++;
if (ModEntry.ticksSinceMoved > Config.ToolTipDelayTicks)
appHover = app.name;
}
}
if (appHover != null)
{
e.SpriteBatch.DrawString(Game1.dialogueFont, appHover, new Vector2(mousePos.X, mousePos.Y) - Game1.dialogueFont.MeasureString(appHover) + new Vector2(-2, 2), Color.Black);
e.SpriteBatch.DrawString(Game1.dialogueFont, appHover, new Vector2(mousePos.X, mousePos.Y) - Game1.dialogueFont.MeasureString(appHover), Color.White);
}
}
19
Source : MobilePhoneApp.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private static void Display_RenderedWorld(object sender, StardewModdingAPI.Events.RenderedWorldEventArgs e)
{
if (ModEntry.callingNPC != null)
{
return;
}
if (!ModEntry.appRunning || !ModEntry.phoneOpen || ModEntry.runningApp != Helper.ModRegistry.ModID)
{
ModEntry.appRunning = false;
ModEntry.phoneAppRunning = false;
Helper.Events.Display.RenderedWorld -= Display_RenderedWorld;
Helper.Events.Input.ButtonPressed -= Input_ButtonPressed;
Helper.Events.Input.MouseWheelScrolled -= Input_MouseWheelScrolled;
return;
}
Vector2 screenPos = PhoneUtils.GetScreenPosition();
Vector2 screenSize = PhoneUtils.GetScreenSize();
Rectangle headerRect = new Rectangle((int)screenPos.X, (int)screenPos.Y, (int)screenSize.X, Config.AppHeaderHeight);
Point mousePos = Game1.getMousePosition();
if (Helper.Input.IsSuppressed(SButton.MouseLeft))
{
int dy = mousePos.Y - lastMousePositionY;
if (Math.Abs(dy) > 0 && ModEntry.screenRect.Contains(mousePos))
{
dragging = true;
}
if (dragging)
{
AddYOffset(dy);
}
}
if (clicked && !Helper.Input.IsSuppressed(SButton.MouseLeft))
{
clicked = false;
if (dragging)
{
Monitor.Log($"was dragging");
dragging = false;
}
else
{
if (headerRect.Contains(mousePos))
{
if (new Rectangle((int)screenPos.X + (int)screenSize.X - Config.AppHeaderHeight, (int)screenPos.Y, Config.AppHeaderHeight, Config.AppHeaderHeight).Contains(mousePos))
{
PhoneUtils.ToggleApp(false);
}
}
else
{
for (int i = 0; i < callableList.Count; i++)
{
Vector2 pos = GetNPCPos(i);
Rectangle r = new Rectangle((int)pos.X, (int)pos.Y, Config.ContactWidth, Config.ContactHeight);
if (r.Contains(mousePos))
{
Monitor.Log($"calling {callableList[i].npc.Name}");
//PhoneUtils.PlayRingTone();
CallNPC(callableList[i].npc);
}
}
}
}
}
lastMousePositionY = Game1.getMouseY();
int startListY = (int)screenPos.Y + Config.AppHeaderHeight;
e.SpriteBatch.Draw(ModEntry.phoneBookTexture, screenPos, Color.White);
if(yOffset < 0)
{
e.SpriteBatch.Draw(ModEntry.upArrowTexture, ModEntry.upArrowPosition, Color.White);
}
if (yOffset > PhoneUtils.GetScreenSize().Y - Config.AppHeaderHeight - listHeight)
{
e.SpriteBatch.Draw(ModEntry.downArrowTexture, ModEntry.downArrowPosition, Color.White);
}
int screenBottom = (int)(screenPos.Y + screenSize.Y);
for (int i = 0; i < callableList.Count; i++)
{
Vector2 npcPos = GetNPCPos(i);
Rectangle r = callableList[i].sourceRect;
if (npcPos.Y < startListY - r.Height * 2 || npcPos.Y >= screenBottom)
{
continue;
}
Rectangle sourceRect = r;
int cutTop = 0;
int cutBottom = 0;
if(npcPos.Y < startListY)
{
cutTop = (int)Math.Round((startListY - (int)npcPos.Y) / 2f);
sourceRect = new Rectangle(r.X, r.Y + cutTop, r.Width, r.Height - cutTop);
npcPos = new Vector2(npcPos.X, startListY);
}
else if(npcPos.Y > screenBottom - r.Height * 2)
{
cutBottom = (int)Math.Round((screenBottom - r.Height * 2 - (int)npcPos.Y) / 2f);
sourceRect = new Rectangle(r.X, r.Y, r.Width, r.Height + cutBottom);
}
int alpha = callableList[i].npc.CurrentDialogue.Any() && !callableList[i].npc.isSleeping.Value ? 255 : Config.UncallableNPCAlpha;
e.SpriteBatch.Draw(callableList[i].portrait, npcPos + new Vector2((Config.ContactWidth - 32) / 2f,0), sourceRect, new Color(255,255,255,alpha), 0, Vector2.Zero, 2, SpriteEffects.None, 0.86f);
if(Config.ShowNamesInPhoneBook && npcPos.Y < screenBottom - Config.ContactHeight - callableList[i].nameSize.Y * 0.4f + 6)
e.SpriteBatch.DrawString(Game1.dialogueFont, callableList[i].name, GetNPCPos(i) + new Vector2(Config.ContactWidth / 2f - callableList[i].nameSize.X * 0.2f, Config.ContactHeight - 6 ), Color.Black, 0, Vector2.Zero, 0.4f, SpriteEffects.None, 0.86f);
}
e.SpriteBatch.Draw(ModEntry.phoneBookHeaderTexture, headerRect, Color.White);
string headerText = Helper.Translation.Get("phone-book");
Vector2 headerTextSize = Game1.dialogueFont.MeasureString(headerText) * Config.HeaderTextScale;
e.SpriteBatch.DrawString(Game1.dialogueFont, headerText, screenPos + new Vector2(screenSize.X / 2f - headerTextSize.X / 2f, Config.AppHeaderHeight / 2f - headerTextSize.Y / 2f ), Config.PhoneBookHeaderTextColor, 0, Vector2.Zero, Config.HeaderTextScale, SpriteEffects.None, 0.86f);
e.SpriteBatch.DrawString(Game1.dialogueFont, "x", screenPos + new Vector2(screenSize.X - Config.AppHeaderHeight / 2f - Game1.dialogueFont.MeasureString("x").X * Config.HeaderTextScale / 2f, Config.AppHeaderHeight / 2f - headerTextSize.Y / 2f), Config.PhoneBookHeaderTextColor, 0, Vector2.Zero, Config.HeaderTextScale, SpriteEffects.None, 0.86f);
}
19
Source : FamiliarsUtils.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void monsterDrop(Familiar familiar, Monster monster, Farmer owner)
{
IList<int> objects = monster.objectsToDrop;
if (Game1.player.isWearingRing(526))
{
string result = "";
Game1.content.Load<Dictionary<string, string>>("Data\\Monsters").TryGetValue(monster.Name, out result);
if (result != null && result.Length > 0)
{
string[] objectsSplit = result.Split(new char[]
{
'/'
})[6].Split(new char[]
{
' '
});
for (int i = 0; i < objectsSplit.Length; i += 2)
{
if (Game1.random.NextDouble() < Convert.ToDouble(objectsSplit[i + 1]))
{
objects.Add(Convert.ToInt32(objectsSplit[i]));
}
}
}
}
if (objects == null || objects.Count == 0)
return;
int objectToAdd = objects[Game1.random.Next(objects.Count)];
if (objectToAdd < 0)
{
familiar.currentLocation.debris.Add(Game1.createItemDebris(new StardewValley.Object(Math.Abs(objectToAdd), Game1.random.Next(1, 4)), familiar.position, Game1.random.Next(4)));
}
else
{
familiar.currentLocation.debris.Add(Game1.createItemDebris(new StardewValley.Object(Math.Abs(objectToAdd), 1), familiar.position, Game1.random.Next(4)));
}
}
19
Source : ThemeApp.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private static void Display_RenderedWorld(object sender, StardewModdingAPI.Events.RenderedWorldEventArgs e)
{
if (ModEntry.callingNPC != null)
return;
if (!ModEntry.appRunning || !ModEntry.phoneOpen || ModEntry.runningApp != Helper.ModRegistry.ModID)
{
ModEntry.appRunning = false;
Helper.Events.Display.RenderedWorld -= Display_RenderedWorld;
Helper.Events.Input.ButtonPressed -= Input_ButtonPressed;
return;
}
Vector2 screenPos = PhoneUtils.GetScreenPosition();
Vector2 screenSize = PhoneUtils.GetScreenSize();
Rectangle headerRect = new Rectangle((int)screenPos.X, (int)screenPos.Y, (int)screenSize.X, Config.AppHeaderHeight);
Rectangle footerRect = new Rectangle((int)screenPos.X, (int)screenPos.Y + (int)screenSize.Y - Config.AppHeaderHeight, (int)screenSize.X, Config.AppHeaderHeight);
Point mousePos = Game1.getMousePosition();
if (Helper.Input.IsSuppressed(SButton.MouseLeft))
{
int dy = mousePos.Y - lastMousePositionY;
if (Math.Abs(dy) > 0 && ModEntry.screenRect.Contains(mousePos) && !headerRect.Contains(mousePos) && !footerRect.Contains(mousePos))
{
dragging = true;
}
if (dragging)
{
float listHeight;
if (whichTab == 0)
listHeight = skinListHeight;
else if (whichTab == 1)
listHeight = backListHeight;
else
listHeight = ringListHeight;
yOffset = (int)Math.Max(Math.Min(0, yOffset + dy), -1 * Math.Max(0, listHeight - screenSize.Y));
}
}
if (clicked && !Helper.Input.IsSuppressed(SButton.MouseLeft))
{
clicked = false;
Monitor.Log($"unclicked");
if (dragging)
{
Monitor.Log($"was dragging");
dragging = false;
}
else
{
if (headerRect.Contains(mousePos))
{
if (new Rectangle((int)screenPos.X + (int)screenSize.X - Config.AppHeaderHeight, (int)screenPos.Y, Config.AppHeaderHeight, Config.AppHeaderHeight).Contains(mousePos))
{
PhoneUtils.ToggleApp(false);
}
}
else if(footerRect.Contains(mousePos))
{
int newTab = (int)((mousePos.X - screenPos.X) / (screenSize.X / 3));
if(whichTab != newTab)
{
whichTab = newTab;
yOffset = 0;
int listcount = whichTab == 0 ? skinList.Count : (whichTab == 1 ? backgroundList.Count : ringList.Count);
Monitor.Log($"switching to tab {whichTab}: {listcount} items");
}
}
else
{
if (whichTab == 0)
{
for(int i = 0; i < skinList.Count; i++)
{
Vector2 pos = GereplacedemPos(i);
Rectangle r = new Rectangle((int)pos.X, (int)pos.Y, Config.ThemeItemWidth, Config.ThemeItemHeight);
if (r.Contains(mousePos))
{
Monitor.Log($"switching to {skinList[i]}");
SetSkin(skinList[i]);
}
}
}
else if (whichTab == 1)
{
for(int i = 0; i < backgroundList.Count; i++)
{
Vector2 pos = GereplacedemPos(i);
Rectangle r = new Rectangle((int)pos.X, (int)pos.Y, Config.ThemeItemWidth, Config.ThemeItemHeight);
if (r.Contains(mousePos))
{
Monitor.Log($"switching to {backgroundList[i]}");
SetBackground(backgroundList[i]);
}
}
}
else if (whichTab == 2)
{
for(int i = 0; i < ringList.Count; i++)
{
Vector2 pos = GereplacedemPos(i);
Rectangle r = new Rectangle((int)pos.X, (int)pos.Y, ModEntry.phoneWidth, Config.RingLisreplacedemHeight);
if (r.Contains(mousePos))
{
Monitor.Log($"switching to {ringList[i]}");
SetRing(ringList[i]);
}
}
}
}
}
}
lastMousePositionY = Game1.getMouseY();
int startListY = (int)screenPos.Y + Config.AppHeaderHeight;
if (whichTab == 2)
e.SpriteBatch.Draw(ModEntry.ringListBackgroundTexture, ModEntry.screenRect, Color.White);
else
e.SpriteBatch.Draw(ModEntry.backgroundTexture, ModEntry.phoneRect, Color.White);
if(yOffset < 0)
{
e.SpriteBatch.Draw(ModEntry.upArrowTexture, ModEntry.upArrowPosition, Color.White);
}
if (yOffset > PhoneUtils.GetScreenSize().Y - Config.AppHeaderHeight - skinListHeight)
{
e.SpriteBatch.Draw(ModEntry.downArrowTexture, ModEntry.downArrowPosition, Color.White);
}
int screenBottom = (int)(screenPos.Y + screenSize.Y);
int count = whichTab == 0 ? skinList.Count : (whichTab == 1 ? backgroundList.Count : ringList.Count );
for (int i = 0; i < count; i++)
{
Vector2 itemPos = GereplacedemPos(i);
if (whichTab < 2)
{
Rectangle r = new Rectangle(0,0,Config.PhoneWidth, Config.PhoneHeight);
Rectangle sourceRect = r;
Rectangle destRect;
destRect = new Rectangle((int)itemPos.X, (int)itemPos.Y, Config.ThemeItemWidth, Config.ThemeItemHeight);
float yScale = Config.ThemeItemHeight / (float)Config.PhoneHeight;
if (itemPos.Y < startListY - r.Height * yScale || itemPos.Y >= screenBottom)
{
continue;
}
int cutTop = 0;
int cutBottom = 0;
if (itemPos.Y < startListY)
{
cutTop = (int)Math.Ceiling((startListY - itemPos.Y) / yScale);
sourceRect = new Rectangle(r.X, (int)(r.Y + cutTop), r.Width, (int)(r.Height - cutTop));
destRect.Y = startListY;
destRect.Height -= (int)(cutTop * yScale);
itemPos = new Vector2(itemPos.X, startListY);
}
else if (itemPos.Y > screenBottom - r.Height * yScale - Config.AppHeaderHeight)
{
cutBottom = (int)Math.Ceiling((screenBottom - Config.AppHeaderHeight - r.Height * yScale - itemPos.Y) / yScale);
destRect.Height += (int)(cutBottom * yScale);
sourceRect = new Rectangle(r.X, r.Y, r.Width, r.Height + cutBottom);
}
Texture2D texture = whichTab == 0 ? skinDict[skinList[i]][0] : backgroundDict[backgroundList[i]][0];
//Monitor.Log($"drawing texture {i} {texture.Width}x{texture.Height} {destRect} {ModEntry.screenRect}");
e.SpriteBatch.Draw(texture, destRect, sourceRect, Color.White);
}
else
{
if (itemPos.Y < screenPos.Y || itemPos.Y >= screenBottom - Config.AppHeaderHeight)
{
continue;
}
if (ringList[i] == Config.PhoneRingTone)
e.SpriteBatch.Draw(ModEntry.ringListHighlightTexture, new Rectangle((int)(itemPos.X), (int)itemPos.Y, (int)(screenSize.X), Config.RingLisreplacedemHeight), Color.White);
string itemName = ringList[i];
if (itemName.Contains(":"))
itemName = itemName.Split(':')[1];
e.SpriteBatch.DrawString(Game1.dialogueFont, itemName, itemPos, Config.RingLisreplacedemColor, 0, Vector2.Zero, Config.RingLisreplacedemScale, SpriteEffects.None, 0.86f);
}
}
e.SpriteBatch.Draw(ModEntry.themesHeaderTexture, headerRect, Color.White);
e.SpriteBatch.Draw(ModEntry.themesHeaderTexture, footerRect, Color.White);
e.SpriteBatch.Draw(ModEntry.themesHighlightTexture, new Rectangle((int)(screenPos.X + (screenSize.X/3f) * whichTab),screenBottom - Config.AppHeaderHeight, (int)(screenSize.X / 3f), Config.AppHeaderHeight), Color.White);
string headerText = Helper.Translation.Get("themes");
string skinsText = Helper.Translation.Get("skins");
string backsText = Helper.Translation.Get("backs");
string ringsText = Helper.Translation.Get("rings");
Vector2 headerTextSize = Game1.dialogueFont.MeasureString(headerText) * Config.HeaderTextScale;
Vector2 skinsTextSize = Game1.dialogueFont.MeasureString(skinsText) * Config.TabTextScale;
Vector2 backsTextSize = Game1.dialogueFont.MeasureString(backsText) * Config.TabTextScale;
Vector2 ringsTextSize = Game1.dialogueFont.MeasureString(ringsText) * Config.TabTextScale;
e.SpriteBatch.DrawString(Game1.dialogueFont, headerText, screenPos + new Vector2(screenSize.X / 2f - headerTextSize.X / 2f, Config.AppHeaderHeight / 2f - headerTextSize.Y / 2f ), Config.PhoneBookHeaderTextColor, 0, Vector2.Zero, Config.HeaderTextScale, SpriteEffects.None, 0.86f);
e.SpriteBatch.DrawString(Game1.dialogueFont, "x", screenPos + new Vector2(screenSize.X - Config.AppHeaderHeight / 2f - Game1.dialogueFont.MeasureString("x").X * Config.HeaderTextScale / 2f, Config.AppHeaderHeight / 2f - headerTextSize.Y / 2f), Config.PhoneBookHeaderTextColor, 0, Vector2.Zero, Config.HeaderTextScale, SpriteEffects.None, 0.86f);
e.SpriteBatch.DrawString(Game1.dialogueFont, skinsText, screenPos + new Vector2(screenSize.X / 6f - skinsTextSize.X / 2f, screenSize.Y - Config.AppHeaderHeight / 2f - headerTextSize.Y / 2f), whichTab == 0 ? Config.ThemesHeaderHighlightedTextColor : Config.ThemesHeaderTextColor, 0, Vector2.Zero, Config.TabTextScale, SpriteEffects.None, 0.86f);
e.SpriteBatch.DrawString(Game1.dialogueFont, backsText, screenPos + new Vector2(screenSize.X / 2f - backsTextSize.X / 2f, screenSize.Y - Config.AppHeaderHeight / 2f - headerTextSize.Y / 2f), whichTab == 1 ? Config.ThemesHeaderHighlightedTextColor : Config.ThemesHeaderTextColor, 0, Vector2.Zero, Config.TabTextScale, SpriteEffects.None, 0.86f);
e.SpriteBatch.DrawString(Game1.dialogueFont, ringsText, screenPos + new Vector2(screenSize.X * 5f / 6f - ringsTextSize.X / 2f, screenSize.Y - Config.AppHeaderHeight / 2f - headerTextSize.Y / 2f), whichTab == 2 ? Config.ThemesHeaderHighlightedTextColor : Config.ThemesHeaderTextColor, 0, Vector2.Zero, Config.TabTextScale, SpriteEffects.None, 0.86f);
}
19
Source : Round.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public int GetMiningInterval()
{
if (RealTimeMinersInformation.Count == 1)
{
// Just appoint the mining interval for single miner.
return 4000;
}
var firstTwoMiners = RealTimeMinersInformation.Values.Where(m => m.Order == 1 || m.Order == 2)
.ToList();
return Math.Abs((int) (firstTwoMiners[1].ExpectedMiningTime - firstTwoMiners[0].ExpectedMiningTime)
.Milliseconds());
}
19
Source : Round.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private static int GetAbsModulus(long longValue, int intValue)
{
return Math.Abs((int) longValue % intValue);
}
19
Source : Bresenhams.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public static void Line(int x0, int y0, int x1, int y1, PlotFunction plot)
{
bool steep = Math.Abs(y1 - y0) > Math.Abs(x1 - x0);
if (steep) { Swap<int>(ref x0, ref y0); Swap<int>(ref x1, ref y1); }
int sign = 1;
if (x0 > x1) { sign = -1; x0 *= -1; x1 *= -1; }
int dX = (x1 - x0), dY = Math.Abs(y1 - y0), err = (dX / 2), ystep = (y0 < y1 ? 1 : -1), y = y0;
for (int x = x0; x <= x1; ++x)
{
if (!(steep ? plot(y, sign*x) : plot(sign*x, y))) return;
err -= dY;
if (err < 0) { y += ystep; err += dX; }
}
}
19
Source : Creature.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public void Attack(Creature defender)
{
if (defender.Alive == false)
return;
Item weapon = Body.MainHand;
ApplyActionCost(weapon.GetWeaponCost(this));
bool attackLanded = this.CheckAttackLanded(weapon, defender);
if (attackLanded)
{
// set the proper multiplier to damage
int multiplier = 1; if (weapon is Weapon w && w.TwoHanded) multiplier = 2;
// get the damage and apply the muliplier
int damage = weapon.GetWepDmg(this) * multiplier;
// get the proper damage type
DamageType dmgType = weapon.GetWepDmgType();
// get a random armor piece from the defender
Armor armorpiece = defender.GetRandomArmorPiece();
if (weapon != null && !weapon.OnHit(armorpiece)) BreakWeapon(weapon);
if (armorpiece != null && !armorpiece.OnHit(weapon)) BreakArmorPiece(armorpiece);
// dish out the damage
int dmgDealt = defender.Defend(dmgType, damage, position);
bool defenderBlocked = dmgDealt >= 0 ? true : false;
if (defenderBlocked) {
// write a message, convert to absolute value
Program.MsgConsole.WriteLine($"{defender.Name} blocked {Name}'s attack, taking {Math.Abs((int)dmgDealt)} damage.");
}
else {
// apply enchantments if opponent did not block
if (weapon != null && weapon is MeleeWeapon && ((MeleeWeapon)weapon).Enchantments.Count > 0)
foreach (WeaponEnchantment enchantment in ((MeleeWeapon)weapon).Enchantments)
enchantment.Apply(this, defender);
// also write a message about the attack
Program.MsgConsole.WriteLine($"{Name} attacked {defender} for {dmgDealt} damage!");
}
if (defender.Alive == false)
Program.MsgConsole.WriteLine($"{defender.Name} died.");
}
// deplete stamina
if (weapon != null)
ChangeResource(Resource.SP, -(int)(weapon.Weight));
else
ChangeResource(Resource.SP, -4);
}
19
Source : Creature.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public int Defend(DamageType dmgType, int dmg, Point dmgAngle)
{
Random rng = new Random();
int armorVal = GetDefenseValue(dmgType);
double finalDmg = Math.Max(dmg - armorVal, 1);
// blocking //
if (Body.OffHand is Shield && (dmgType == DamageType.Blunt || dmgType == DamageType.Shear))
{
int blockChance = 10 + (Stats.Skills[Skill.Block] / 5);
if (rng.Next(0, 101) <= blockChance)
{
finalDmg /= -((double)2 + ((Stats.Attributes[Attribute.Strength] + Stats.Attributes[Attribute.Strength]) / 400));
LvlWeaponSkill((MeleeWeapon)body.OffHand, 25);
}
}
else
{
LvlArmorSkill(25);
if (finalDmg > 0) SplatterBlood(dmgAngle);
}
ChangeResource(Resource.HP, Math.Abs((int)finalDmg) * -1);
ChangeResource(Resource.SP, Math.Abs((int)finalDmg) * -1);
if (this is Monster m)
m.TurnsSinceAttentionCaught = m.Persistence;
return (int)finalDmg;
}
19
Source : ChineseMoney.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static string NumberString(int number)
{
if (number == 0)
{
return "零";
}
var sc = new List<string>();
GetString(Math.Abs(number), sc, 0);
var sb = new StringBuilder();
if (number < 0)
{
sb.Append("负");
}
foreach (var s in sc)
{
sb.Append(s);
}
return sb.ToString();
}
19
Source : Cell.cs
with GNU General Public License v3.0
from AHeroicLlama
with GNU General Public License v3.0
from AHeroicLlama
void InitializePlotData()
{
plots = DataHelper.GetAllCellCoords(formID);
plots = plots.OrderBy(plot => plot.x).ToList();
xMin = plots.First().x;
xMax = plots.Last().x;
plots = plots.OrderBy(plot => plot.y).ToList();
yMin = plots.First().y;
yMax = plots.Last().y;
plots = plots.OrderBy(plot => plot.z).ToList();
zMin = plots.First().z;
zMax = plots.Last().z;
heightRange = Math.Abs(zMax - zMin);
}
19
Source : Map.cs
with GNU General Public License v3.0
from AHeroicLlama
with GNU General Public License v3.0
from AHeroicLlama
public static void Draw()
{
// Reset the current image to the background layer
finalImage = (Image)backgroundLayer.Clone();
Graphics imageGraphic = Graphics.FromImage(finalImage);
imageGraphic.SmoothingMode = SmoothingMode.AntiAlias;
Font font = new Font(fontCollection.Families[0], fontSize, GraphicsUnit.Pixel);
CellScaling cellScaling = null;
// Prepare the game version and watermark to be printed later
string infoText = (SettingsPlot.IsTopographic() ? "Topographic View\n" : string.Empty) + "Game version " + IOManager.GetGameVersion() + "\nMade with Mappalachia - github.com/AHeroicLlama/Mappalachia";
// Additional steps for cell mode (Add further text to watermark text, get cell height boundings)
if (SettingsMap.IsCellModeActive())
{
Cell currentCell = SettingsCell.GetCell();
// replacedign the CellScaling property
cellScaling = currentCell.GetScaling();
infoText =
currentCell.displayName + " (" + currentCell.editorID + ")\n" +
"Height distribution: " + SettingsCell.minHeightPerc + "% - " + SettingsCell.maxHeightPerc + "%\n" +
"Scale: 1:" + Math.Round(cellScaling.scale, 2) + "\n\n" +
infoText;
}
// Gather resources for drawing informational watermark text
Brush brushWhite = new SolidBrush(Color.White);
RectangleF infoTextBounds = new RectangleF(plotXMin, 0, mapDimension - plotXMin, mapDimension);
StringFormat stringFormatBottomRight = new StringFormat() { Alignment = StringAlignment.Far, LineAlignment = StringAlignment.Far }; // Align the text bottom-right
StringFormat stringFormatBottomLeft = new StringFormat() { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Far }; // Align the text bottom-left
// Draws bottom-right info text
imageGraphic.DrawString(infoText, font, brushWhite, infoTextBounds, stringFormatBottomRight);
// Draw a height-color key for Topography mode
if (SettingsPlot.IsTopographic())
{
// Identify the sizing and locations for drawing the height-color-key strings
double numHeightKeys = SettingsPlotTopograph.heightKeyIndicators;
Font topographFont = new Font(fontCollection.Families[0], 62, GraphicsUnit.Pixel);
float singleLineHeight = imageGraphic.MeasureString(SettingsPlotTopograph.heightKeyString, topographFont, new SizeF(infoTextBounds.Width, infoTextBounds.Height)).Height;
// Identify the lower limit to start printing the key so that it ends up centered
double baseHeight = (mapDimension / 2) - (singleLineHeight * (numHeightKeys / 2d));
for (int i = 0; i <= numHeightKeys - 1; i++)
{
Brush brush = new SolidBrush(GetTopographColor(i / (numHeightKeys - 1)));
imageGraphic.DrawString(SettingsPlotTopograph.heightKeyString, topographFont, brush, new RectangleF(plotXMax, 0, mapDimension - plotXMax, (float)(mapDimension - baseHeight)), stringFormatBottomRight);
baseHeight += singleLineHeight;
}
}
// Draw all legend text for every MapItem
int skippedLegends = DrawLegend(font, imageGraphic);
// Adds additional text if some items were missed from legend
if (skippedLegends > 0)
{
string extraLegendText = "+" + skippedLegends + " more item" + (skippedLegends == 1 ? string.Empty : "s") + "...";
imageGraphic.DrawString(extraLegendText, font, brushWhite, infoTextBounds, stringFormatBottomLeft);
}
// Start progress bar off at 0
progressBarMain.Value = progressBarMain.Minimum;
float progress = 0;
// Nothing else to plot - ensure we update for the background layer but then return
if (FormMaster.legendItems.Count == 0)
{
mapFrame.Image = finalImage;
return;
}
// Count how many Map Data Points are due to be mapped
int totalMapDataPoints = 0;
foreach (MapItem mapItem in FormMaster.legendItems)
{
totalMapDataPoints += mapItem.count;
}
// Loop through every MapDataPoint represented by all the MapItems to find the min/max z coord in the dataset
bool first = true;
int zMin = 0;
int zMax = 0;
double zRange = 0;
if (SettingsPlot.IsTopographic())
{
foreach (MapItem mapItem in FormMaster.legendItems)
{
foreach (MapDataPoint point in mapItem.GetPlots())
{
if (first)
{
zMin = point.z - (point.boundZ / 2);
zMax = point.z + (point.boundZ / 2);
first = false;
continue;
}
// Do not contribute outlier values to the min/max range - this ensures they have the same
// color as the min/max *legitimate* item and they do not skew the color ranges
if (point.z > SettingsPlotTopograph.zThreshUpper || point.z < SettingsPlotTopograph.zThreshLower)
{
continue;
}
if (point.z - (point.boundZ / 2) < zMin)
{
zMin = point.z - (point.boundZ / 2);
}
if (point.z + (point.boundZ / 2) > zMax)
{
zMax = point.z + (point.boundZ / 2);
}
}
}
zRange = Math.Abs(zMax - zMin);
if (zRange == 0)
{
zRange = 1;
}
}
if (SettingsPlot.IsIconOrTopographic())
{
if (SettingsPlot.IsTopographic())
{
// Somehow this line prevents a memory leak
// Without it, if drawing a large topographic map on first map draw, GC will not collect the multiple PlotIcon elements used in topographic drawing.
Application.DoEvents();
}
// Processing each MapItem in serial, draw plots for every matching valid MapDataPoint
foreach (MapItem mapItem in FormMaster.legendItems)
{
// Generate a Plot Icon and colours/brushes to be used for all instances of the MapItem
PlotIcon plotIcon = mapItem.GetIcon();
Image plotIconImg = SettingsPlot.IsIcon() ? plotIcon.GetIconImage() : null; // Icon mode has icon per MapItem, Topography needs icons per MapDataPoint and will be generated later
Color volumeColor = Color.FromArgb(volumeOpacity, plotIcon.color);
Brush volumeBrush = new SolidBrush(volumeColor);
// Iterate over every data point and draw it
foreach (MapDataPoint point in mapItem.GetPlots())
{
// Override colors in Topographic mode
if (SettingsPlot.IsTopographic())
{
// Clamp the z values to the percieved outlier threshold
double z = point.z + (point.boundZ / 2);
z = Math.Max(Math.Min(z, SettingsPlotTopograph.zThreshUpper), SettingsPlotTopograph.zThreshLower);
// Normalize the height of this item between the min/max z of the whole set
double colorValue = (z - zMin) / zRange;
// Override the plot icon color
plotIcon.color = GetTopographColor(colorValue);
plotIconImg = plotIcon.GetIconImage(); // Generate a new icon with a unique color for this height color
// Apply the color to volume plotting too
volumeColor = Color.FromArgb(volumeOpacity, plotIcon.color);
volumeBrush = new SolidBrush(volumeColor);
}
if (SettingsMap.IsCellModeActive())
{
// If this coordinate exceeds the user-selected cell mapping height bounds, skip it
// (Also accounts for the z-height of volumes)
if (point.z + (point.boundZ / 2d) < SettingsCell.GetMinHeightCoordBound() || point.z - (point.boundZ / 2d) > SettingsCell.GetMaxHeightCoordBound())
{
continue;
}
point.x += cellScaling.xOffset;
point.y += cellScaling.yOffset;
// Multiply the coordinates by the scaling, but multiply around 0,0
point.x = ((point.x - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
point.y = ((point.y - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
point.boundX *= cellScaling.scale;
point.boundY *= cellScaling.scale;
}
else // Skip the point if its origin is outside the surface world
if (point.x < plotXMin || point.x >= plotXMax || point.y < plotYMin || point.y >= plotYMax)
{
continue;
}
// If this meets all the criteria to be suitable to be drawn as a volume
if (point.primitiveShape != string.Empty && // This is a primitive shape at all
SettingsPlot.drawVolumes && // Volume drawing is enabled
point.boundX >= minVolumeDimension && point.boundY >= minVolumeDimension) // This is large enough to be visible if drawn as a volume
{
Image volumeImage = new Bitmap((int)point.boundX, (int)point.boundY);
Graphics volumeGraphic = Graphics.FromImage(volumeImage);
volumeGraphic.SmoothingMode = SmoothingMode.AntiAlias;
switch (point.primitiveShape)
{
case "Box":
case "Line":
case "Plane":
volumeGraphic.FillRectangle(volumeBrush, new Rectangle(0, 0, (int)point.boundX, (int)point.boundY));
break;
case "Sphere":
case "Ellipsoid":
volumeGraphic.FillEllipse(volumeBrush, new Rectangle(0, 0, (int)point.boundX, (int)point.boundY));
break;
default:
continue; // If we reach this, we dropped the drawing of a volume. Verify we've covered all shapes via the database summary.txt
}
volumeImage = ImageTools.RotateImage(volumeImage, point.rotationZ);
imageGraphic.DrawImage(volumeImage, (float)(point.x - (volumeImage.Width / 2)), (float)(point.y - (volumeImage.Height / 2)));
}
// This MapDataPoint is not suitable to be drawn as a volume - draw a normal plot icon, or topographic plot
else
{
imageGraphic.DrawImage(plotIconImg, (float)(point.x - (plotIconImg.Width / 2d)), (float)(point.y - (plotIconImg.Height / 2d)));
}
}
// Increment the progress bar per MapItem
progress += mapItem.count;
progressBarMain.Value = (int)((progress / totalMapDataPoints) * progressBarMain.Maximum);
Application.DoEvents();
}
}
else if (SettingsPlot.IsHeatmap())
{
int resolution = SettingsPlotHeatmap.resolution;
int blendRange = SettingsPlotHeatmap.blendDistance;
// Create a 2D Array of HeatMapGridSquare
HeatMapGridSquare[,] squares = new HeatMapGridSquare[resolution, resolution];
for (int x = 0; x < resolution; x++)
{
for (int y = 0; y < resolution; y++)
{
squares[x, y] = new HeatMapGridSquare();
}
}
int pixelsPerSquare = mapDimension / resolution;
foreach (MapItem mapItem in FormMaster.legendItems)
{
int heatmapLegendGroup = SettingsPlotHeatmap.IsDuo() ? mapItem.legendGroup % 2 : 0;
foreach (MapDataPoint point in mapItem.GetPlots())
{
if (SettingsMap.IsCellModeActive())
{
point.x += cellScaling.xOffset;
point.y += cellScaling.yOffset;
point.x = ((point.x - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
point.y = ((point.y - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
}
// Identify which grid square this MapDataPoint falls within
int squareX = (int)Math.Floor(point.x / pixelsPerSquare);
int squareY = (int)Math.Floor(point.y / pixelsPerSquare);
// Loop over every grid square within range, and increment by the weight proportional to the distance
for (int x = squareX - blendRange; x < squareX + blendRange; x++)
{
for (int y = squareY - blendRange; y < squareY + blendRange; y++)
{
// Don't try to target squares which would lay outside of the grid
if (x < 0 || x >= resolution || y < 0 || y >= resolution)
{
continue;
}
// Pythagoras on the x and y dist gives us the 'as the crow flies' distance between the squares
double distance = Pythagoras(squareX - x, squareY - y);
// Weight and hence brightness is modified by 1/x^2 + 1 where x is the distance from actual item
double additionalWeight = point.weight * (1d / ((distance * distance) + 1));
squares[x, y].weights[heatmapLegendGroup] += additionalWeight;
}
}
}
// Increment the progress bar per MapItem
progress += mapItem.count;
progressBarMain.Value = (int)((progress / totalMapDataPoints) * progressBarMain.Maximum);
Application.DoEvents();
}
// Find the largest weight value of all squares
double largestWeight = 0;
for (int x = 0; x < resolution; x++)
{
for (int y = 0; y < resolution; y++)
{
double weight = squares[x, y].GetTotalWeight();
if (weight > largestWeight)
{
largestWeight = weight;
}
}
}
// Finally now weights are calculated, draw a square for every HeatGripMapSquare in the array
for (int x = 0; x < resolution; x++)
{
int xCoord = x * pixelsPerSquare;
// Don't draw grid squares which are entirely within the legend text area
if (xCoord + pixelsPerSquare < plotXMin)
{
continue;
}
for (int y = 0; y < resolution; y++)
{
int yCoord = y * pixelsPerSquare;
Color color = squares[x, y].GetColor(largestWeight);
Brush brush = new SolidBrush(color);
Rectangle heatMapSquare = new Rectangle(xCoord, yCoord, mapDimension / SettingsPlotHeatmap.resolution, mapDimension / SettingsPlotHeatmap.resolution);
imageGraphic.FillRectangle(brush, heatMapSquare);
}
}
}
mapFrame.Image = finalImage;
}
19
Source : Extensions.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int CalculateLength(this short num)
=> num == 0 ? 1 : (int)Math.Floor(Math.Log10(Math.Abs(num == short.MinValue ? num + 1 : num))) + (num < 0 ? 2 /* include sign */ : 1);
19
Source : Extensions.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int CalculateLength(this int num)
=> num == 0 ? 1 : (int)Math.Floor(Math.Log10(Math.Abs(num == int.MinValue ? num + 1 : num))) + (num < 0 ? 2 /* include sign */ : 1);
19
Source : GenericPolicy.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
bool SnapshotOnMouseEvent(RawEventType evt, int x, int y)
{
bool snap = false;
if ((evt == RawEventType.LeftButtonDown) || (evt == RawEventType.RightButtonDown))
{
MouseState mouse = CaptureMouseState(evt);
if (mouse.ClickOption != _lastMouseState.ClickOption)
{
snap = true;
}
else
{
if (evt == RawEventType.LeftButtonDown)
{
if (DateTime.Now.Subtract(_prevLButtonDownTime).TotalMilliseconds < 1000)
{
if ((Math.Abs(mouse.X - _lastMouseState.X) < 15) && (Math.Abs(mouse.Y - _lastMouseState.Y) < 10))
{
snap = true;
}
}
_prevLButtonDownTime = DateTime.Now;
}
if ((Math.Abs((int)(mouse.X - _lastMouseState.X)) > 5) || (Math.Abs((int)(mouse.Y - _lastMouseState.Y)) > 5))
{
snap = true;
}
}
_isLastEventFromKeyboard = false;
_lastMouseTime = DateTime.Now;
}
TraceLogger.Instance.WriteLineVerbos("SnapshotOnMouseEvent: " + snap.ToString());
return snap;
}
19
Source : SecureRandom.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public int GetInt32(int min = 0, int max = int.MaxValue)
{
if (max <= min)
throw new ArgumentException("Maximum needs to be greater than minimum.", nameof(max));
var offset = min < 0 ? -min : 0;
min += offset;
max += offset;
return Math.Abs(this.Generate<int>()) % (max - min) + min - offset;
}
See More Examples