System.Math.Round(decimal, int, System.MidpointRounding)

Here are the examples of the csharp api System.Math.Round(decimal, int, System.MidpointRounding) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2774 Examples 7

19 View Source File : MapViewer.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

public Vector2 GetLandblock(Vector2 imagePos)
        {
            return new Vector2((int)Math.Min(254, Math.Round(imagePos.X) / 8) * 8, (int)Math.Min(254, Math.Round(imagePos.Y) / 8) * 8);
        }

19 View Source File : CollapsedRegionAdornmentManager.cs
License : MIT License
Project Creator : Actipro

protected override void AddAdornment(AdornmentChangeReason reason, ITextViewLine viewLine, TagSnapshotRange<CollapsedRegionTag> tagRange, TextBounds bounds) {
			// Create a border
			Border outerBorder = new Border();
			outerBorder.Background = Brushes.Transparent;
			outerBorder.BorderBrush = Brushes.Gray;
			outerBorder.BorderThickness = new Thickness(1.0);
			outerBorder.CornerRadius = new CornerRadius(2.0);
			outerBorder.Cursor = Cursors.Arrow;
			outerBorder.SnapsToDevicePixels = true;
			outerBorder.Width = bounds.Width;
			outerBorder.Height = bounds.Height;
			this.AdornmentLayer.AddAdornment(reason, outerBorder, new Point(Math.Round(bounds.Left), Math.Round(bounds.Top)), tagRange.Tag.Key, null);

			// Create the text adornment
			TextBlock element = new TextBlock();
			element.IreplacedTestVisible = false;
			element.Text = tagRange.Tag.Text;
			element.FontFamily = this.View.SyntaxEditor.FontFamily;
			element.FontSize = this.View.SyntaxEditor.FontSize;
			element.Foreground = Brushes.Gray;
			element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

			// Get the location
			Point location = new Point(Math.Round(bounds.Left), Math.Round(bounds.Top + (bounds.Height - element.DesiredSize.Height) / 2));

			// Add the text adornment to the layer
			this.AdornmentLayer.AddAdornment(reason, element, location, tagRange.Tag.Key, null);
		}

19 View Source File : Healer.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public bool DoSkillCheck(Player healer, Player target, CreatureVital vital, ref int difficulty)
        {
            // skill check:
            // (healing skill + healing kit boost) * trainedMod
            // vs. damage * 2 * combatMod
            var healingSkill = healer.GetCreatureSkill(Skill.Healing);
            var trainedMod = healingSkill.AdvancementClreplaced == SkillAdvancementClreplaced.Specialized ? 1.5f : 1.1f;

            var combatMod = healer.CombatMode == CombatMode.NonCombat ? 1.0f : 1.1f;

            var effectiveSkill = (int)Math.Round((healingSkill.Current + BoostValue) * trainedMod);
            difficulty = (int)Math.Round((vital.MaxValue - vital.Current) * 2 * combatMod);

            var skillCheck = SkillCheck.GetSkillChance(effectiveSkill, difficulty);
            return skillCheck > ThreadSafeRandom.Next(0.0f, 1.0f);
        }

19 View Source File : Player_Luminance.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void EarnLuminance(long amount, XpType xpType, ShareType shareType = ShareType.All)
        {
            if (IsOlthoiPlayer)
                return;

            // following the same model as Player_Xp

            var modifier = PropertyManager.GetDouble("luminance_modifier").Item;

            // should this be preplaceded upstream to fellowship?
            var enchantment = GetXPAndLuminanceModifier(xpType);

            var m_amount = (long)Math.Round(amount * enchantment * modifier);

            GrantLuminance(m_amount, xpType, shareType);
        }

19 View Source File : ManaStone.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public override void HandleActionUseOnTarget(Player player, WorldObject target)
        {
            WorldObject invTarget;

            var useResult = WeenieError.None;

            if (player.IsOlthoiPlayer)
            {
                player.SendUseDoneEvent(WeenieError.OlthoiCannotInteractWithThat);
                return;
            }

            if (player != target)
            {
                invTarget = player.FindObject(target.Guid.Full, Player.SearchLocations.MyInventory | Player.SearchLocations.MyEquippedItems);
                if (invTarget == null)
                {
                    // Haven't looked to see if an error was sent for this case; however, this one fits
                    player.Session.Network.EnqueueSend(new GameEventUseDone(player.Session, WeenieError.YouDoNotOwnThareplacedem));
                    return;
                }

                target = invTarget;
            }

            if (!ItemCurMana.HasValue)
            {
                if (target == player)
                    useResult = WeenieError.ActionCancelled;
                else if (target.ItemCurMana.HasValue && target.ItemCurMana.Value > 0 && target.ItemMaxMana.HasValue && target.ItemMaxMana.Value > 0)
                {
                    // absorb mana from the item
                    if (target.Retained)
                        useResult = WeenieError.ActionCancelled;
                    else
                    {
                        if (!player.TryConsumeFromInventoryWithNetworking(target, 1) && !player.TryDequipObjectWithNetworking(target.Guid, out _, Player.DequipObjectAction.ConsumeItem))
                        {
                            log.Error($"Failed to remove {target.Name} from player inventory.");
                            player.Session.Network.EnqueueSend(new GameEventUseDone(player.Session, WeenieError.ActionCancelled));
                            return;
                        }

                        //The Mana Stone drains 5,253 points of mana from the Wand.
                        //The Wand is destroyed.

                        //The Mana Stone drains 4,482 points of mana from the Pantaloons.
                        //The Pantaloons is destroyed.

                        var manaDrained = (int)Math.Round(Efficiency.Value * target.ItemCurMana.Value);
                        ItemCurMana = manaDrained;
                        player.Session.Network.EnqueueSend(new GameMessageSystemChat($"The Mana Stone drains {ItemCurMana:N0} points of mana from the {target.Name}.\nThe {target.Name} is destroyed.", ChatMessageType.Broadcast));
                        SetUiEffect(player, ACE.Enreplacedy.Enum.UiEffects.Magical);
                    }
                }
                else
                {
                    useResult = WeenieError.ItemDoesntHaveEnoughMana;
                }
            }
            else if (ItemCurMana.Value > 0)
            {
                if (target == player)
                {
                    // dump mana into equipped items
                    var origItemsNeedingMana = player.EquippedObjects.Values.Where(k => k.ItemCurMana.HasValue && k.ItemMaxMana.HasValue && k.ItemCurMana < k.ItemMaxMana).ToList();
                    var itemsGivenMana = new Dictionary<WorldObject, int>();

                    while (ItemCurMana > 0)
                    {
                        var itemsNeedingMana = origItemsNeedingMana.Where(k => k.ItemCurMana < k.ItemMaxMana).ToList();
                        if (itemsNeedingMana.Count < 1)
                            break;

                        var ration = Math.Max(ItemCurMana.Value / itemsNeedingMana.Count, 1);

                        foreach (var item in itemsNeedingMana)
                        {
                            var manaNeededForTopoff = (int)(item.ItemMaxMana - item.ItemCurMana);
                            var adjustedRation = Math.Min(ration, manaNeededForTopoff);

                            ItemCurMana -= adjustedRation;

                            if (player.LumAugItemManaGain != 0)
                            {
                                adjustedRation = (int)Math.Round(adjustedRation * Creature.GetPositiveRatingMod(player.LumAugItemManaGain * 5));
                                if (adjustedRation > manaNeededForTopoff)
                                {
                                    var diff = adjustedRation - manaNeededForTopoff;
                                    adjustedRation = manaNeededForTopoff;
                                    ItemCurMana += diff;
                                }
                            }

                            item.ItemCurMana += adjustedRation;
                            if (!itemsGivenMana.ContainsKey(item))
                                itemsGivenMana[item] = adjustedRation;
                            else
                                itemsGivenMana[item] += adjustedRation;

                            if (ItemCurMana <= 0)
                                break;
                        }
                    }

                    if (itemsGivenMana.Count < 1)
                    {
                        player.Session.Network.EnqueueSend(new GameMessageSystemChat("You have no items equipped that need mana.", ChatMessageType.Broadcast));
                        useResult = WeenieError.ActionCancelled;
                    }
                    else
                    {
                        //The Mana Stone gives 4,496 points of mana to the following items: Fire Compound Crossbow, Qafiya, Celdon Sleeves, Amuli Leggings, Messenger's Collar, Heavy Bracelet, Scalemail Bracers, Olthoi Alduressa Gauntlets, Studded Leather Girth, Shoes, Chainmail Greaves, Loose Pants, Mechanical Scarab, Ring, Ring, Heavy Bracelet
                        //Your items are fully charged.

                        //The Mana Stone gives 1,921 points of mana to the following items: Haebrean Girth, Chiran Helm, Ring, Baggy Breeches, Scalemail Greaves, Alduressa Boots, Heavy Bracelet, Heavy Bracelet, Lorica Breastplate, Pocket Watch, Heavy Necklace
                        //You need 2,232 more mana to fully charge your items.

                        var additionalManaNeeded = origItemsNeedingMana.Sum(k => k.ItemMaxMana.Value - k.ItemCurMana.Value);
                        var additionalManaText = (additionalManaNeeded > 0) ? $"\nYou need {additionalManaNeeded:N0} more mana to fully charge your items." : "\nYour items are fully charged.";
                        var msg = $"The Mana Stone gives {itemsGivenMana.Values.Sum():N0} points of mana to the following items: {itemsGivenMana.Select(c => c.Key.Name).Aggregate((a, b) => a + ", " + b)}.{additionalManaText}";
                        player.Session.Network.EnqueueSend(new GameMessageSystemChat(msg, ChatMessageType.Broadcast));

                        if (!DoDestroyDiceRoll(player) && !UnlimitedUse)
                        {
                            ItemCurMana = null;
                            SetUiEffect(player, ACE.Enreplacedy.Enum.UiEffects.Undef);
                        }

                        if (UnlimitedUse && ItemMaxMana.HasValue)
                            ItemCurMana = ItemMaxMana;
                    }
                }
                else if (target.ItemMaxMana.HasValue && target.ItemMaxMana.Value > 0)
                {
                    var targereplacedemCurMana = target.ItemCurMana ?? 0;

                    if (targereplacedemCurMana >= target.ItemMaxMana)
                    {
                        player.Session.Network.EnqueueSend(new GameMessageSystemChat($"The {target.Name} is already full of mana.", ChatMessageType.Broadcast));
                    }
                    else
                    {
                        // The Mana Stone gives 3,502 points of mana to the Focusing Stone.

                        // The Mana Stone gives 3,267 points of mana to the Protective Drudge Charm.

                        var targetManaNeeded = target.ItemMaxMana.Value - targereplacedemCurMana;
                        var manaToPour = Math.Min(targetManaNeeded, ItemCurMana.Value);

                        if (player.LumAugItemManaGain != 0)
                        {
                            manaToPour = (int)Math.Round(manaToPour * Creature.GetPositiveRatingMod(player.LumAugItemManaGain * 5));
                            manaToPour = Math.Min(targetManaNeeded, manaToPour);
                        }

                        target.ItemCurMana = targereplacedemCurMana + manaToPour;
                        var msg = $"The Mana Stone gives {manaToPour:N0} points of mana to the {target.Name}.";
                        player.Session.Network.EnqueueSend(new GameMessageSystemChat(msg, ChatMessageType.Broadcast));

                        if (!DoDestroyDiceRoll(player) && !UnlimitedUse)
                        {
                            ItemCurMana = null;
                            SetUiEffect(player, ACE.Enreplacedy.Enum.UiEffects.Undef);
                        }
                    }
                }
                else
                {
                    useResult = WeenieError.ActionCancelled;
                }
            }

            player.Session.Network.EnqueueSend(new GameEventUseDone(player.Session, useResult));
        }

19 View Source File : Creature_Magic.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public uint CalculateManaUsage(Creature caster, Spell spell, WorldObject target = null)
        {
            var baseCost = spell.BaseMana;

            // for casting spells built into a casting implement, use the ItemManaCost
            var casreplacedem = caster.GetEquippedWand();
            if (casreplacedem != null && (casreplacedem.SpellDID ?? 0) == spell.Id)
                baseCost = (uint)(casreplacedem.ItemManaCost ?? 0);

            if ((spell.School == MagicSchool.ItemEnchantment) && (spell.MetaSpellType == SpellType.Enchantment) &&
                (spell.Category >= SpellCategory.ArmorValueRaising) && (spell.Category <= SpellCategory.AcidicResistanceLowering) && target is Player targetPlayer)
            {
                var numTargereplacedems = 1;
                if (targetPlayer != null)
                    numTargereplacedems = targetPlayer.EquippedObjects.Values.Count(i => (i is Clothing || i.IsShield) && i.IsEnchantable);

                baseCost += spell.ManaMod * (uint)numTargereplacedems;
            }
            else if ((spell.Flags & SpellFlags.FellowshipSpell) != 0)
            {
                var numFellows = 1;
                if (this is Player player && player.Fellowship != null)
                    numFellows = player.Fellowship.FellowshipMembers.Count;

                baseCost += spell.ManaMod * (uint)numFellows;
            }

            var manaConversion = caster.GetCreatureSkill(Skill.ManaConversion);

            if (manaConversion.AdvancementClreplaced < SkillAdvancementClreplaced.Trained || spell.Flags.HasFlag(SpellFlags.IgnoresManaConversion))
                return baseCost;

            var difficulty = spell.PowerMod;   // modified power difficulty

            var mana_conversion_skill = (uint)Math.Round(manaConversion.Current * GetWeaponManaConversionModifier(caster));

            var manaCost = GetManaCost(difficulty, baseCost, mana_conversion_skill);

            return manaCost;
        }

19 View Source File : PrintSettings.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

public static string GetSheetSizereplacedtring(ExportSheet sheet)
        {
            if (sheet == null) {
                return string.Empty;
            }

            double[] p = { 1189, 841, 594, 420, 297, 210, 297, 420, 594, 841, 1189 };
            string[] s = { "A0", "A1", "A2", "A3", "A4", "A4P", "A3P", "A2P", "A1P", "A0P" };

            for (int i = 0; i < s.Length; i++) {
                if (CheckSheetSize(sheet.Width, sheet.Height, p[i], p[i + 1])) {
                    return s[i];
                }
            }

            if (CheckSheetSize(sheet.Width, sheet.Height, 1000, 707)) {
                return "B1";
            }

            return Math.Round(sheet.Width).ToString(CultureInfo.InvariantCulture) + "x" +
                Math.Round(sheet.Height).ToString(CultureInfo.InvariantCulture);
        }

19 View Source File : HololensLaserPointerDetection.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private Mat getROI(Mat img)
        {
            int w = img.width();
            int h = img.height();
            int ROIwidth = Math.Max(0, Math.Min(w, ((int) Math.Round(w * detectionArea.x * 0.5 )) * 2));
            int ROIheight = Math.Max(0, Math.Min(h, ((int)Math.Round(h * detectionArea.y * 0.5)) * 2));
            Rect ROI = new Rect((w - ROIwidth) / 2, (h - ROIheight) / 2, ROIwidth, ROIheight);

            return new Mat(img, ROI);
        }

19 View Source File : CustomAdornmentManager.cs
License : MIT License
Project Creator : Actipro

protected override void AddAdornment(AdornmentChangeReason reason, ITextViewLine viewLine, TagSnapshotRange<CustomTag> tagRange, TextBounds bounds) {
			// Create the adornment
			UIElement element = CustomAdornmentManager.CreateDecorator(bounds.Width);
			Point location = new Point(Math.Round(bounds.Left), bounds.Bottom - 2);

			// Add the adornment to the layer
			this.AdornmentLayer.AddAdornment(reason, element, location, null, viewLine, tagRange.SnapshotRange, TextRangeTrackingModes.ExpandBothEdges, null);
		}

19 View Source File : RadarChartCustomizationLabelProviders.cs
License : MIT License
Project Creator : ABTSoftware

public override string FormatLabel(IComparable dataValue)
        {
            return string.Format("{0}%", Math.Round(dataValue.ToDouble(), 1));
        }

19 View Source File : Player_Death.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void ThreadSafeTeleportOnDeath()
        {
            // teleport to sanctuary or best location
            var newPosition = Sanctuary ?? Instantiation ?? Location;

            WorldManager.ThreadSafeTeleport(this, newPosition, new ActionEventDelegate(() =>
            {
                // Stand back up
                SetCombatMode(CombatMode.NonCombat);

                SetLifestoneProtection();

                var teleportChain = new ActionChain();
                if (!IsLoggingOut) // If we're in the process of logging out, we skip the delay
                    teleportChain.AddDelaySeconds(3.0f);
                teleportChain.AddAction(this, () =>
                {
                    // currently happens while in portal space
                    var newHealth = (uint)Math.Round(Health.MaxValue * 0.75f);
                    var newStamina = (uint)Math.Round(Stamina.MaxValue * 0.75f);
                    var newMana = (uint)Math.Round(Mana.MaxValue * 0.75f);

                    var msgHealthUpdate = new GameMessagePrivateUpdateAttribute2ndLevel(this, Vital.Health, newHealth);
                    var msgStaminaUpdate = new GameMessagePrivateUpdateAttribute2ndLevel(this, Vital.Stamina, newStamina);
                    var msgManaUpdate = new GameMessagePrivateUpdateAttribute2ndLevel(this, Vital.Mana, newMana);

                    UpdateVital(Health, newHealth);
                    UpdateVital(Stamina, newStamina);
                    UpdateVital(Mana, newMana);

                    Session.Network.EnqueueSend(msgHealthUpdate, msgStaminaUpdate, msgManaUpdate);

                    // reset damage history for this player
                    DamageHistory.Reset();

                    OnHealthUpdate();

                    IsInDeathProcess = false;

                    if (IsLoggingOut)
                        LogOut_Final(true);
                });

                teleportChain.EnqueueChain();
            }));
        }

19 View Source File : Monster_Melee.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public int IgnoreMagicResistScaled(int enchantments)
        {
            if (!(this is Player))
                return 0;

            var scalar = PropertyManager.GetDouble("ignore_magic_resist_pvp_scalar").Item;

            if (scalar != 1.0)
                return (int)Math.Round(enchantments * (1.0 - scalar));
            else
                return 0;
        }

19 View Source File : Corpse.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void TryGenerateRare(DamageHistoryInfo killer)
        {
            var killerPlayer = killer.TryGetAttacker() as Player;
            var timestamp = (int)Time.GetUnixTime();
            var luck = 0;
            var secondChanceGranted = false;

            var realTimeRares = PropertyManager.GetBool("rares_real_time").Item;
            var realTimeRaresAlt = PropertyManager.GetBool("rares_real_time_v2").Item;
            if (realTimeRares && killerPlayer != null)
            {
                if (killerPlayer.RaresLoginTimestamp.HasValue)
                {
                    // http://acpedia.org/wiki/Announcements_-_2010/04_-_Shedding_Skin#Rares_Update

                    // Real Time Rares work the same as they always have. It rolls a number between 1 second and 2 months worth of seconds. When that number is up you get an additional chance of finding a rare on any valid rare kill.
                    // That additional chance is very high. You can still only find one rare on any given kill but it's possible to find a normal rare when your Real Time Rare timer is up but you haven't found one yet.

                    var now = Time.GetDateTimeFromTimestamp(timestamp);
                    var playerLastRareFound = Time.GetDateTimeFromTimestamp(killerPlayer.RaresLoginTimestamp.Value);

                    if (now >= playerLastRareFound)
                        secondChanceGranted = true;
                }
                else
                    killerPlayer.RaresLoginTimestamp = (int)Time.GetFutureUnixTime(ThreadSafeRandom.Next(1, (int)PropertyManager.GetLong("rares_max_seconds_between").Item));
            }
            else if (realTimeRaresAlt && killerPlayer != null)
            {
                if (killerPlayer.RaresLoginTimestamp.HasValue)
                {
                    // This version of the system is based on interpretation of the following way the system was originally described. The one above is how it was stated to *really* works as detailed in a dev chat from 2010.

                    // http://acpedia.org/wiki/Rare#Real_Time_Rares

                    // Also there is a real time rare timer for each character, this timer starts the first time you kill a rare eligible creature. A character such as a mule that has never killed anything will not have an active timer.
                    // It works by looking at the real time that has elapsed since the last rare was found, it increases as the time gets closer to two months (real life time) at which point it is a 100% chance.
                    // People have found that for characters that don't normally hunt, it's best to take them out at at the 30 day mark and a rare will drop after a few kills (although it sometimes can take longer since it's still a % chance at the 30 day mark).

                    var now = Time.GetDateTimeFromTimestamp(timestamp);
                    var playerLastRareFound = Time.GetDateTimeFromTimestamp(killerPlayer.RaresLoginTimestamp.Value);
                    var timeBetweenRareSighting = now - playerLastRareFound;
                    var daysSinceRareSighting = timeBetweenRareSighting.TotalDays;

                    var maxDaysSinceLastRareFound = (int)PropertyManager.GetLong("rares_max_days_between").Item; // 30? 45? 60?
                    var chancesModifier = Math.Round(daysSinceRareSighting / maxDaysSinceLastRareFound, 2, MidpointRounding.ToZero);
                    var chancesModifierAdjusted = Math.Min(chancesModifier, 1.0f);

                    var t1_chance = 2500;
                    luck = (int)Math.Round(t1_chance * chancesModifierAdjusted, 0, MidpointRounding.ToZero);
                }
                else
                    killerPlayer.RaresLoginTimestamp = timestamp;
            }

            var wo = LootGenerationFactory.TryCreateRare(luck);

            if (secondChanceGranted && wo == null)
            {
                luck = 2490;
                wo = LootGenerationFactory.TryCreateRare(luck);
            }

            if (wo == null)
                return;

            if (!wo.IconUnderlayId.HasValue || wo.IconUnderlayId.Value != 0x6005B0C) // ensure icon underlay exists for rare (loot profiles use this)
                wo.IconUnderlayId = 0x6005B0C;

            var tier = LootGenerationFactory.GetRareTier(wo.WeenieClreplacedId);
            LootGenerationFactory.RareChances.TryGetValue(tier, out var chance);

            log.Debug($"[LOOT][RARE] {Name} ({Guid}) generated rare {wo.Name} ({wo.Guid}) for {killer.Name} ({killer.Guid})");
            log.Debug($"[LOOT][RARE] Tier {tier} -- 1 / {chance:N0} chance -- {luck:N0} luck");

            if (TryAddToInventory(wo))
            {
                rareGenerated = wo;
                killerName = killer.Name.TrimStart('+');
                CorpseGeneratedRare = true;
                LongDesc += " This corpse generated a rare item!";
                TimeToRot = 900;  // guesstimated 15 mins from hells

                if (killerPlayer != null)
                {
                    if (realTimeRares)
                        killerPlayer.RaresLoginTimestamp = (int)Time.GetFutureUnixTime(ThreadSafeRandom.Next(1, (int)PropertyManager.GetLong("rares_max_seconds_between").Item));
                    else
                        killerPlayer.RaresLoginTimestamp = timestamp;
                    switch (tier)
                    {
                        case 1:
                            killerPlayer.RaresTierOne++;
                            killerPlayer.RaresTierOneLogin = timestamp;
                            break;
                        case 2:
                            killerPlayer.RaresTierTwo++;
                            killerPlayer.RaresTierTwoLogin = timestamp;
                            break;
                        case 3:
                            killerPlayer.RaresTierThree++;
                            killerPlayer.RaresTierThreeLogin = timestamp;
                            break;
                        case 4:
                            killerPlayer.RaresTierFour++;
                            killerPlayer.RaresTierFourLogin = timestamp;
                            break;
                        case 5:
                            killerPlayer.RaresTierFive++;
                            killerPlayer.RaresTierFiveLogin = timestamp;
                            break;
                        case 6:
                            killerPlayer.RaresTierSix++;
                            killerPlayer.RaresTierSixLogin = timestamp;
                            break;
                        //case 7:
                        //    killerPlayer.RaresTierSeven++;
                        //    killerPlayer.RaresTierSevenLogin = timestamp;
                        //    break;
                    }
                }
            }
            else
                log.Error($"[RARE] failed to add to corpse inventory");
        }

19 View Source File : TextureViewer.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

public Vector2? GetCurrentPos(Vector2 curPos)
        {
            // get image pixel currently hovering over
            var imagePos = Vector2.Transform(curPos, Matrix.Invert(Scale * Translate));
            var curPixel = new Vector2((float)Math.Round(imagePos.X), (float)Math.Round(imagePos.Y));

            if (curPixel.X < 0 || curPixel.Y < 0 || curPixel.X >= Texture.Width || curPixel.Y >= Texture.Height)
                return null;

            return ImagePos = imagePos;
        }

public override IReadOnlyDictionary<string, int> ReadTemperatures()
        {
            Dictionary<string, int> temperatures = new();

            // OpenHardwareMonitor values
            foreach (IHardware hardware in _computer.Hardware)
            {
                hardware.Update();

                foreach (ISensor sensor in hardware.Sensors)
                {
                    if (sensor.SensorType == SensorType.Temperature && sensor.Value.HasValue)
                    {
                        if (!sensor.Name.Contains("Average") && !sensor.Name.Contains("Max"))
                        {
                            int temperature = sensor.Value != null ? (int)Math.Round(sensor.Value.Value) : 0;
                            temperatures.Add(sensor.Name, temperature);
                        }
                    }
                }
            }

            return temperatures;
        }

19 View Source File : WorldViewer.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

public async void LoadLandblocks(Vector2 startBlock, Vector2 endBlock)
        {
            Buffer.ClearBuffer();
            TextureCache.Init();
            
            LScape.unload_landblocks_all();

            DungeonMode = false;

            var dx = (int)(endBlock.X - startBlock.X) + 1;
            var dy = (int)(startBlock.Y - endBlock.Y) + 1;
            var numBlocks = dx * dy;

            var size = endBlock - startBlock;
            var center = startBlock + size / 2;
            var centerX = (uint)Math.Round(center.X);
            var centerY = (uint)Math.Round(center.Y);
            var landblockID = centerX << 24 | centerY << 16 | 0xFFFF;

            MainWindow.Status.WriteLine($"Loading {numBlocks} landblocks");
            await Task.Run(() => Thread.Sleep(50));

            //Landblocks = new Dictionary<uint, R_Landblock>();
            R_Landblock r_landblock = null;
            R_Landblock centerBlock = null;

            for (var lbx = (uint)startBlock.X; lbx <= endBlock.X; lbx++)
            {
                if (lbx < 0 || lbx > 254) continue;

                for (var lby = (uint)endBlock.Y; lby <= startBlock.Y; lby++)
                {
                    if (lby < 0 || lby > 254) continue;

                    var lbid = lbx << 24 | lby << 16 | 0xFFFF;

                    var timer = Stopwatch.StartNew();
                    var landblock = LScape.get_landblock(lbid);
                    timer.Stop();

                    r_landblock = new R_Landblock(landblock);
                    //LScape.unload_landblock(lbid);

                    if (lbid == landblockID)
                        centerBlock = r_landblock;

                    MainWindow.Status.WriteLine($"Loaded {lbid:X8} in {timer.Elapsed.TotalMilliseconds}ms");

                    //Landblocks.Add(lbid, new R_Landblock(landblock));
                }
            }

            Buffer.BuildBuffers();

            Camera.InitLandblock(centerBlock);
            GameView.ViewMode = ViewMode.World;

            FreeResources();
        }

19 View Source File : Creature_Magic.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public uint GetEffectiveMagicDefense()
        {
            var current = GetCreatureSkill(Skill.MagicDefense).Current;
            var weaponDefenseMod = GetWeaponMagicDefenseModifier(this);
            var defenseImbues = (uint)GetDefenseImbues(ImbuedEffectType.MagicDefense);

            var effectiveMagicDefense = (uint)Math.Round((current * weaponDefenseMod) + defenseImbues);

            //Console.WriteLine($"EffectiveMagicDefense: {effectiveMagicDefense}");

            return effectiveMagicDefense;
        }

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private void OnWindowLocationChanged(object sender, RoutedEventArgs e) {
			if (this.IsLocationSizeEventOutputEnabled)
				this.AppendMessage(String.Format("LocationChanged: {0},{1}", Math.Round(window.Left), Math.Round(window.Top)));
		}

19 View Source File : MainWindow.xaml.MachineStatus.cs
License : MIT License
Project Creator : 3RD-Dimension

private void Machine_PositionUpdateReceived()
		{
			ModelTool.Point1 = (machine.WorkPosition + new Vector3(0, 0, 10)).ToPoint3D();
			ModelTool.Point2 = machine.WorkPosition.ToPoint3D();

			var nfi = Constants.DecimalOutputFormat;

			LabelPosX.Text = machine.WorkPosition.X.ToString("N", nfi);
			LabelPosY.Text = machine.WorkPosition.Y.ToString("N", nfi);
			LabelPosZ.Text = machine.WorkPosition.Z.ToString("N", nfi);

			LabelPosMX.Text = machine.MachinePosition.X.ToString("N", nfi);
			LabelPosMY.Text = machine.MachinePosition.Y.ToString("N", nfi);
			LabelPosMZ.Text = machine.MachinePosition.Z.ToString("N", nfi);

			LabelFeedRateRealtime.Text = ((int)Math.Round(machine.FeedRateRealtime)).ToString();

			TextBoxCurrentTLO.Text = machine.CurrentTLO.ToString("N", nfi);

		}

19 View Source File : ColorPreviewAdornmentManager.cs
License : MIT License
Project Creator : Actipro

protected override void AddAdornment(AdornmentChangeReason reason, ITextViewLine viewLine, TagSnapshotRange<ColorPreviewTag> tagRange, TextBounds bounds) {
			// Round off the bounds to integers to help ensure crispness
			var adornmentBounds = new Rect(Math.Round(bounds.Left, MidpointRounding.AwayFromZero), Math.Round(bounds.Top, MidpointRounding.AwayFromZero),
				Math.Round(bounds.Width, MidpointRounding.AwayFromZero), Math.Round(bounds.Height, MidpointRounding.AwayFromZero));

			// Add the adornment to the layer
			this.AdornmentLayer.AddAdornment(reason, OnDrawHighlightAdornment, adornmentBounds, tagRange.Tag, viewLine, tagRange.SnapshotRange, TextRangeTrackingModes.ExpandBothEdges, null);
		}

19 View Source File : Lifestone.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public override void ActOnUse(WorldObject worldObject)
        {
            if (!(worldObject is Player player))
                return;

            var actionChain = new ActionChain();
            if (player.CombatMode != CombatMode.NonCombat)
            {
                var stanceTime = player.SetCombatMode(CombatMode.NonCombat);
                actionChain.AddDelaySeconds(stanceTime);

                player.LastUseTime += stanceTime;
            }

            actionChain.AddAction(this, () => player.EnqueueBroadcast(new GameMessageSound(player.Guid, Sound.LifestoneOn, 1.0f)));

            player.LastUseTime += player.EnqueueMotion(actionChain, MotionCommand.Sanctuary);

            actionChain.AddAction(this, () =>
            {
                if (player.IsWithinUseRadiusOf(this))
                {
                    player.Sanctuary = new Position(player.Location);
                    player.Session.Network.EnqueueSend(new GameMessageSystemChat(GetProperty(PropertyString.UseMessage), ChatMessageType.Magic));
                    var newStamina = (uint)Math.Round(player.Stamina.Current / 2f);
                    player.UpdateVital(player.Stamina, newStamina);
                }
                else
                    player.Session.Network.EnqueueSend(new GameEventWeenieError(player.Session, WeenieError.YouHaveMovedTooFar));
            });

            actionChain.EnqueueChain();
        }

19 View Source File : Lock.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static uint GetEffectiveLockpickSkill(Player player, WorldObject unlocker)
        {
            var lockpickSkill = player.GetCreatureSkill(Skill.Lockpick).Current;

            var additiveBonus = unlocker.GetProperty(PropertyInt.LockpickMod) ?? 0;
            var multiplicativeBonus = unlocker.GetProperty(PropertyFloat.LockpickMod) ?? 1.0f;

            // is this really 10x bonus, or +10% bonus?
            if (multiplicativeBonus > 1.0f)
                multiplicativeBonus = 1.0f + multiplicativeBonus * 0.01f;

            var effectiveSkill = (int)Math.Round(lockpickSkill * multiplicativeBonus + additiveBonus);

            effectiveSkill = Math.Max(0, effectiveSkill);

            //Console.WriteLine($"Base skill: {lockpickSkill}");
            //Console.WriteLine($"Effective skill: {effectiveSkill}");

            return (uint)effectiveSkill;
        }

19 View Source File : AccelCalculator.cs
License : MIT License
Project Creator : a1xd

public static int NearestAngleDivision(double angle)
        {
            var angleTransformed = angle * 2 / Math.PI * (Constants.AngleDivisions-1);
            return (int)Math.Round(angleTransformed);
        }

19 View Source File : Monster_Inventory.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void DebugTreasure()
        {
            if (WieldedTreasure == null) return;

            Console.WriteLine($"{Name} possible wielded treasure:");
            foreach (var item in WieldedTreasure)
            {
                var weenie = DatabaseManager.World.GetCachedWeenie(item.WeenieClreplacedId);
                var probability = Math.Round(item.Probability * 100, 2);
                Console.WriteLine($"{weenie.ClreplacedName} - {probability}%");
            }

            var totalProbability = Math.Round(GetTotalProbability(WieldedTreasure) * 100, 2);
            Console.WriteLine($"Probability of spawning any items: {totalProbability}%");
        }

19 View Source File : AnnotationGetXCoordinateConverter.cs
License : MIT License
Project Creator : ABTSoftware

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var annotation = value as AnnotationBase;

            var xAxis = annotation.XAxis;
            var result = annotation.X1;

            if (xAxis != null && result != null)
            {
                var xCoordCalculator = xAxis.GetCurrentCoordinateCalculator();

                var position = xCoordCalculator == null ? (double)result : xCoordCalculator.GetCoordinate((double)result);
                position = Math.Round(position);

                result = position.ToString(culture) + " px";
            }

            return result;
        }

19 View Source File : Player_Crafting.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public int GetStructure(WorldObject salvageItem, SalvageResults salvageResults, ref SalvageMessage message)
        {
            // By default, salvaging uses either a tinkering skill, or your salvaging skill that would yield the greatest amount of material.
            // Tinkering skills can only yield at most the workmanship number in units of salvage.
            // The salvaging skill can produce more units than workmanship.

            // You can also significantly increase the amount of material returned by training the Ciandra's Fortune augmentation.
            // This augmentation can be trained 4 times, each time providing an additional 25% bonus to the amount of material returned.

            // is this a bag of salvage?
            // if so, return its existing structure
            if (salvageItem.ItemType == ItemType.TinkeringMaterial)
                return salvageItem.Structure.Value;

            var workmanship = salvageItem.Workmanship ?? 1.0f;
            var stackSize = salvageItem.StackSize ?? 1;

            // should this be getting the highest tinkering skill,
            // or the tinkering skill for the material?
            var salvageSkill = GetCreatureSkill(Skill.Salvaging).Current;
            var highestTinkeringSkill = GetMaxSkill(TinkeringSkills);
            var highestTrainedTinkeringSkill = highestTinkeringSkill.AdvancementClreplaced >= SkillAdvancementClreplaced.Trained ? highestTinkeringSkill.Current : 0;

            // take augs into account for salvaging only
            var salvageAmount = CalcNumUnits((int)salvageSkill, workmanship, AugmentationBonusSalvage) * stackSize;
            var tinkeringAmount = CalcNumUnits((int)highestTrainedTinkeringSkill, workmanship, 0);

            // cap tinkeringAmount to item workmanship
            tinkeringAmount = Math.Min(tinkeringAmount, (int)Math.Round(salvageItem.Workmanship ?? 1.0f)) * stackSize;

            // choose the best one
            var addStructure = Math.Max(salvageAmount, tinkeringAmount);

            var skill = salvageAmount > tinkeringAmount ? Skill.Salvaging : GetMaxSkill(TinkeringSkills).Skill;

            message = salvageResults.GetMessage(salvageItem.MaterialType ?? ACE.Enreplacedy.Enum.MaterialType.Unknown, skill);
            message.Amount += (uint)addStructure;

            return addStructure;
        }

19 View Source File : Player_Crafting.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void AddSalvage(List<WorldObject> salvageBags, WorldObject item, SalvageResults salvageResults)
        {
            var materialType = (MaterialType)item.MaterialType;

            // determine the amount of salvage produced (structure)
            SalvageMessage message = null;
            var amountProduced = GetStructure(item, salvageResults, ref message);

            var remaining = amountProduced;

            while (remaining > 0)
            {
                // get the destination salvage bag

                // if there are no existing salvage bags for this material type,
                // or all of the salvage bags for this material type are full,
                // this will create a new salvage bag, and adds it to salvageBags

                var salvageBag = GetSalvageBag(materialType, salvageBags);

                var added = TryAddSalvage(salvageBag, item, remaining);
                remaining -= added;

                // https://asheron.fandom.com/wiki/Salvaging/Value_Pre2013

                // increase value of salvage bag - salvage skill is a factor,
                // if bags aren't being combined here
                var valueFactor = (float)added / amountProduced;
                if (item.ItemType != ItemType.TinkeringMaterial)
                    valueFactor *= GetCreatureSkill(Skill.Salvaging).Current / 387.0f * (1.0f + 0.25f * AugmentationBonusSalvage);

                var addedValue = (int)Math.Round((item.Value ?? 0) * valueFactor);

                salvageBag.Value = Math.Min((salvageBag.Value ?? 0) + addedValue, 75000);

                // a bit different here, since ACE handles overages
                if (message != null)
                {
                    message.Workmanship += item.ItemWorkmanship ?? 0.0f;
                    message.NumItemsInMaterial++;
                }
            }
        }

19 View Source File : Armor.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public int GetArmorVsType(DamageType damageType, int armorVsType)
        {
            var resistance = (float)armorVsType / Biota.BaseArmor;
            var mod = EnchantmentManager.GetResistanceMod(damageType);

            var baseArmorMod = BaseArmorMod;

            var resistanceMod = resistance / mod;
            if (baseArmorMod < 0)
                resistanceMod = 1.0f + (1.0f - resistanceMod);

            /*Console.WriteLine("BaseArmor: " + Biota.BaseArmor);
            Console.WriteLine("BaseArmorMod: " + baseArmorMod);
            Console.WriteLine("Resistance: " + resistance);
            Console.WriteLine("ResistanceMod: " + resistanceMod);*/

            return (int)Math.Round(baseArmorMod * resistanceMod);
        }

19 View Source File : WorldObject_Equipment.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public WorldObject CreateWieldedTreasure(TreasureWielded item)
        {
            var wo = WorldObjectFactory.CreateNewWorldObject(item.WeenieClreplacedId);
            if (wo == null) return null;

            if (item.PaletteId > 0)
                wo.PaletteTemplate = (int)item.PaletteId;

            if (item.Shade > 0)
                wo.Shade = item.Shade;

            if (item.StackSize > 0)
            {
                var stackSize = item.StackSize;

                var hasVariance = item.StackSizeVariance > 0;
                if (hasVariance)
                {
                    var minStack = (int)Math.Max(Math.Round(item.StackSize * item.StackSizeVariance), 1);
                    var maxStack = item.StackSize;
                    stackSize = ThreadSafeRandom.Next(minStack, maxStack);
                }
                wo.SetStackSize(stackSize);
            }
            return wo;
        }

19 View Source File : Dialog_BaseOnlineButton.cs
License : Apache License 2.0
Project Creator : AantCoder

public void DoTab0Contents(Rect inRect)
        {
            Text.Font = GameFont.Small;
            var rect = new Rect(inRect.x, inRect.y + 10f, inRect.width, 80f);
            Widgets.Label(rect, "OC_Incidents_Hire_text".Translate());
            rect.height = 30f;
            rect.y += 80f;

            Text.Font = GameFont.Medium;
            Widgets.Label(rect, "OC_What_To_DO".Translate());
            Text.Font = GameFont.Small;
            rect.y += rect.height;

            if (Widgets.RadioButtonLabeled(rect, "OC_Raid".Translate(), SelectTab0Type == "raid"))
            {
                StatusNeedUpdate = true;
                SelectTab0Type = "raid";
            }
            rect.y += rect.height;

            if (Widgets.RadioButtonLabeled(rect, "OC_Bugs".Translate(), SelectTab0Type == "inf"))
            {
                StatusNeedUpdate = true;
                SelectTab0Type = "inf";
            }
            rect.y += rect.height;

            if (SelectTab0Type == "raid")
            {
                rect.y += rect.height; //пробел
                Text.Font = GameFont.Medium;
                Widgets.Label(rect, "OC_Who_Hire".Translate());
                Text.Font = GameFont.Small;
                rect.y += rect.height;

                if (Widgets.RadioButtonLabeled(rect, "OC_Tribe".Translate(), SelectTab0Faction == "tribe"))
                {
                    StatusNeedUpdate = true;
                    SelectTab0Faction = "tribe";
                }
                rect.y += rect.height;

                if (Widgets.RadioButtonLabeled(rect, "OC_Pirate".Translate(), SelectTab0Faction == "pirate"))
                {
                    StatusNeedUpdate = true;
                    SelectTab0Faction = "pirate";
                }
                rect.y += rect.height;

                if (Widgets.RadioButtonLabeled(rect, "OC_Mech".Translate(), SelectTab0Faction == "mech"))
                {
                    StatusNeedUpdate = true;
                    SelectTab0Faction = "mech";
                }
                rect.y += rect.height;
            }

            if (SelectTab0Type == "raid")
            {
                rect.y += rect.height; //пробел
                Text.Font = GameFont.Medium;
                Widgets.Label(rect, "OC_Arrive".Translate());
                Text.Font = GameFont.Small;
                rect.y += rect.height;

                if (Widgets.RadioButtonLabeled(rect, "OC_Arrive_EdgeWalk".Translate(), SelectTab0ArrivalModes == "walk"))
                {
                    StatusNeedUpdate = true;
                    SelectTab0ArrivalModes = "walk";
                }
                rect.y += rect.height;

                if (Widgets.RadioButtonLabeled(rect, "OC_Arrive_DropCenter".Translate(), SelectTab0ArrivalModes == "air"))
                {
                    StatusNeedUpdate = true;
                    SelectTab0ArrivalModes = "air";
                }
                rect.y += rect.height;

                if (Widgets.RadioButtonLabeled(rect, "OC_Arrive_RandomDrop".Translate(), SelectTab0ArrivalModes == "random"))
                {
                    StatusNeedUpdate = true;
                    SelectTab0ArrivalModes = "random";
                }
                rect.y += rect.height;
            }

            rect.y += rect.height; //пробел
            Text.Font = GameFont.Medium;
            Widgets.Label(rect, "OC_Raid_Power".Translate((int)SelectTab0Mult));
            Text.Font = GameFont.Small;
            rect.y += rect.height;

            rect.height = 22f;
            if (SelectTab0Mult > SelectTab0MultMax) SelectTab0Mult = SelectTab0MultMax;
            if (SelectTab0Mult < 1) SelectTab0Mult = 1;
            SelectTab0Mult = (float)Math.Round(SelectTab0Mult + 0.001f);
            var newVal = Widgets.HorizontalSlider(rect, SelectTab0Mult, 1, SelectTab0MultMax);
            newVal = (float)Math.Round(newVal + 0.001f);
            if (newVal != SelectTab0Mult)
            {
                StatusNeedUpdate = true;
                SelectTab0Mult = newVal;
            }
            rect.y += rect.height;
            rect.height = 30f;

            DoTab1And2ContentsDown(rect);
        }

19 View Source File : Player_Move.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void TakeDamage_Falling(float amount)
        {
            if (IsDead || Invincible) return;

            // handle lifestone protection?
            if (UnderLifestoneProtection)
            {
                HandleLifestoneProtection();
                return;
            }

            // scale by bludgeon protection
            var resistance = GetResistanceMod(DamageType.Bludgeon, null, null);
            var damage = (uint)Math.Round(amount * resistance);

            // update health
            var damageTaken = (uint)-UpdateVitalDelta(Health, (int)-damage);
            DamageHistory.Add(this, DamageType.Bludgeon, damageTaken);

            var msg = Strings.GetFallMessage(damageTaken, Health.MaxValue);

            SendMessage(msg, ChatMessageType.Combat);

            if (Health.Current <= 0)
            {
                OnDeath(new DamageHistoryInfo(this), DamageType.Bludgeon, false);
                Die();
            }
            else
                EnqueueBroadcast(new GameMessageSound(Guid, Sound.Wound3, 1.0f));
        }

19 View Source File : Creature_Death.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void OnDeath_GrantXP()
        {
            if (this is Player && PlayerKillerStatus == PlayerKillerStatus.PKLite)
                return;

            var totalHealth = DamageHistory.TotalHealth;

            if (totalHealth == 0)
                return;

            foreach (var kvp in DamageHistory.TotalDamage)
            {
                var damager = kvp.Value.TryGetAttacker();

                var playerDamager = damager as Player;

                if (playerDamager == null && kvp.Value.PetOwner != null)
                    playerDamager = kvp.Value.TryGetPetOwner();

                if (playerDamager == null)
                    continue;

                var totalDamage = kvp.Value.TotalDamage;

                var damagePercent = totalDamage / totalHealth;

                var totalXP = (XpOverride ?? 0) * damagePercent;

                playerDamager.EarnXP((long)Math.Round(totalXP), XpType.Kill);

                // handle luminance
                if (LuminanceAward != null)
                {
                    var totalLuminance = (long)Math.Round(LuminanceAward.Value * damagePercent);
                    playerDamager.EarnLuminance(totalLuminance, XpType.Kill);
                }
            }
        }

19 View Source File : MapViewer.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

public Vector2 GetCurrentPos(Vector2 curPos)
        {
            // get image pixel currently hovering over
            var imagePos = Vector2.Transform(curPos, Matrix.Invert(Scale * Translate));
            var curPixel = new Vector2((float)Math.Round(imagePos.X), (float)Math.Round(imagePos.Y));

            if (curPixel.X < 0 || curPixel.Y < 0 || curPixel.X > WorldMap.Width || curPixel.Y > WorldMap.Height)
                return imagePos;

            ImagePos = imagePos;

            var curLandblock = GetLandblock(ImagePos);
            BlockTranslate = Matrix.CreateTranslation(curLandblock.X, curLandblock.Y, 0);

            //Console.WriteLine($"Window pos: {curPos}, Image pos: {ImagePos}");
            return imagePos;
        }

19 View Source File : Entry.cs
License : GNU General Public License v3.0
Project Creator : 1330-Studios

[HarmonyPostfix]
            public static void Postfix() {
                var cursorPosition = InGame.instance.inputManager.cursorPositionWorld;
                if (Input.GetKeyDown(KeyCode.LeftBracket)) {
                    run = !run;
                    if (lastX != cursorPosition.x || lastY != cursorPosition.y) {
                        Console.WriteLine("initArea.Add(new(" + Math.Round(cursorPosition.x) + ", " + Math.Round(cursorPosition.y) + "));");
                        lastX = cursorPosition.x;
                        lastY = cursorPosition.y;
                    }
                }
                if (Input.GetKeyDown(KeyCode.RightBracket)) {
                    run = !run;
                    if (lastX != cursorPosition.x || lastY != cursorPosition.y) {
                        Console.WriteLine("initPath.Add(new(){ point = new(" + Math.Round(cursorPosition.x) + ", " + Math.Round(cursorPosition.y) + "), bloonScale = 1, moabScale = 1 });");
                        lastX = cursorPosition.x;
                        lastY = cursorPosition.y;
                    }
                }

                if (Input.GetKeyDown(KeyCode.KeypadDivide)) {
                    run = !run;
                    if (lastX != cursorPosition.x || lastY != cursorPosition.y) Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
                }
            }

19 View Source File : Player_Xp.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void EarnXP(long amount, XpType xpType, ShareType shareType = ShareType.All)
        {
            //Console.WriteLine($"{Name}.EarnXP({amount}, {sharable}, {fixedAmount})");

            // apply xp modifier
            var modifier = PropertyManager.GetDouble("xp_modifier").Item;

            // should this be preplaceded upstream to fellowship / allegiance?
            var enchantment = GetXPAndLuminanceModifier(xpType);

            var m_amount = (long)Math.Round(amount * enchantment * modifier);

            if (m_amount < 0)
            {
                log.Warn($"{Name}.EarnXP({amount}, {shareType})");
                log.Warn($"modifier: {modifier}, enchantment: {enchantment}, m_amount: {m_amount}");
                return;
            }

            GrantXP(m_amount, xpType, shareType);
        }

19 View Source File : Creature_Magic.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static uint GetManaCost(uint difficulty, uint manaCost, uint manaConv)
        {
            // thanks to GDLE for this function!
            if (manaConv == 0)
                return manaCost;

            // Dropping diff by half as Specced ManaC is only 48 with starter Aug so 50 at level 1 means no bonus
            //   easiest change without having to create two different formulas to try to emulate retail
            var successChance = SkillCheck.GetSkillChance(manaConv, difficulty / 2);
            var roll = ThreadSafeRandom.Next(0.0f, 1.0f);

            // Luck lowers the roll value to give better outcome
            // e.g. successChance = 0.83 & roll = 0.71 would still provide some savings.
            //   but a luck roll of 0.19 will lower that 0.71 to 0.13 so the caster would
            //   receive a 60% reduction in mana cost.  without the luck roll, 12%
            //   so players will always have a level of "luck" in manacost if they make skill checks
            var luck = ThreadSafeRandom.Next(0.0f, 1.0f);

            if (roll < successChance)
            {
                manaCost = (uint)Math.Round(manaCost * (1.0f - (successChance - (roll * luck))));
            }

            // above seems to give a good middle of the range
            // seen in pcaps for mana usage for low level chars
            // bug still need a way to give a better reduction for the "lucky"

            // save some calc time if already at 1 mana cost
            if (manaCost > 1)
            {
                successChance = SkillCheck.GetSkillChance(manaConv, difficulty);
                roll = ThreadSafeRandom.Next(0.0f, 1.0f);

                if (roll < successChance)
                    manaCost = (uint)Math.Round(manaCost * (1.0f - (successChance - (roll * luck))));
            }

            return Math.Max(manaCost, 1);
        }

19 View Source File : StaduimSeatingTier.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

private void UpdateInfoString()
        {
            int i;

            var s = string.Empty;
            s += "row:\triser:\tdist:\telev:\tc-value:\r\n";

            for (i = 0; i < NumberOfRows; i++)
            {
                string c = i > 0 ? Math.Round(rows[i - 1].CValue, 2).ToString(CultureInfo.InvariantCulture) : "NA";
                string r = i > 0 ? Math.Round(rows[i].RiserHeight, 2).ToString(CultureInfo.InvariantCulture) : "NA";
                s += i + 1 + "\t" + r + "\t"
                + Math.Round(rows[i].EyeToFocusX, 2) + "\t"
                + Math.Round(rows[i].HeightToFocus - EyeHeight, 2) + "\t"
                + c + "\r\n";
            }

            InfoString = s;
        }

19 View Source File : VisualLine.cs
License : MIT License
Project Creator : Abdesol

public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
		{
			if (xPos > textLine.WidthIncludingTrailingWhitespace) {
				if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) {
					int virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
					return VisualLengthWithEndOfLineMarker + virtualX;
				}
			}
			CharacterHit ch = textLine.GetCharacterHitFromDistance(xPos);
			return ch.FirstCharacterIndex + ch.TrailingLength;
		}

19 View Source File : StaduimSeatingTier.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

[SuppressMessage("ReSharper", "BitwiseOperatorOnEnumWithoutFlags", Justification = "Revit API...")]
        public void Draw()
        {
            using (var t = new Transaction(doc, "Create sight line view"))
            {
                t.Start();

                string times = DateTime.Now.Ticks.ToString(CultureInfo.CurrentCulture);

                view = CreateLineOfSightDraftingView(
                    "LOS-X" + distanceToFirstRowX + "-Y" + distanceToFirstRowY + "-T" +
                    TreadSize + "-MinN" + MinimumRiserHeight + "-Inc" + RiserIncrement +
                    "-Eye" + EyeHeight + "-MinC" + MinimumCValue + "_" + times);

                view.Scale = 50;
                int i;

                for (i = 0; i < NumberOfRows; i++)
                {
                    if (i == 0)
                    {
                        DrawLine(0, 0, distanceToFirstRowX, 0, "Thin Lines");
                        DrawText(
                            distanceToFirstRowX / 2,
                            0,
                            distanceToFirstRowX.ToString(CultureInfo.InvariantCulture),
                            TextAlignFlags.TEF_ALIGN_CENTER | TextAlignFlags.TEF_ALIGN_TOP);
                        DrawText(
                            distanceToFirstRowX,
                            distanceToFirstRowY / 2,
                            distanceToFirstRowY.ToString(CultureInfo.InvariantCulture),
                            TextAlignFlags.TEF_ALIGN_CENTER | TextAlignFlags.TEF_ALIGN_BOTTOM);
                    }

                    // Draw the sight line
                    DrawLine(0, 0, rows[i].EyeToFocusX, rows[i].HeightToFocus, "Dash - 0.1 pen");

                    // Draw the head
                    DrawCircle(rows[i].EyeToFocusX, rows[i].HeightToFocus, "Medium Lines");

                    // Draw the body
                    DrawLine(
                        rows[i].EyeToFocusX,
                        rows[i].HeightToFocus,
                        rows[i].EyeToFocusX,
                        rows[i].HeightToFocus - rows[i].EyeHeight,
                        "Thin Lines");

                    // Draw the riser
                    DrawRiser(i);

                    // Draw the going
                    DrawGoing(i);

                    // Draw the c-value text
                    DrawText(
                        rows[i].EyeToFocusX + 125,
                        rows[i].HeightToFocus,
                        "c:" + Math.Round(rows[i].CValue, 2).ToString(CultureInfo.InvariantCulture),
                        TextAlignFlags.TEF_ALIGN_LEFT);

                    //// Draw the going text (treadSize)
                    DrawText(
                        rows[i].EyeToFocusX - (rows[i].Going / 2),
                        rows[i].HeightToFocus - rows[i].EyeHeight,
                        "R" + (i + 1).ToString(CultureInfo.InvariantCulture) + " : " + TreadSize.ToString(CultureInfo.InvariantCulture),
                        TextAlignFlags.TEF_ALIGN_CENTER | TextAlignFlags.TEF_ALIGN_TOP);

                    //// Draw the riser text)
                    if (i > 0)
                    {
                        DrawText(
                            rows[i].EyeToFocusX - TreadSize,
                            rows[i].HeightToFocus - rows[i].EyeHeight - (rows[i].RiserHeight / 2),
                            rows[i].RiserHeight.ToString(CultureInfo.InvariantCulture),
                            TextAlignFlags.TEF_ALIGN_CENTER | TextAlignFlags.TEF_ALIGN_BOTTOM);
                    }
                }
                t.Commit();

                Autodesk.Revit.UI.UIDoreplacedent uidoc = new Autodesk.Revit.UI.UIDoreplacedent(doc);
                uidoc.ActiveView = view;
            }
        }

19 View Source File : Food.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void BoostVital(Player player)
        {
            var vital = player.GetCreatureVital(BoosterEnum);

            if (vital == null)
            {
                player.Session.Network.EnqueueSend(new GameMessageSystemChat($"{Name} ({Guid}) contains invalid vital {BoosterEnum}", ChatMessageType.Broadcast));
                return;
            }

            // only apply to restoration food?
            var ratingMod = BoostValue > 0 ? player.GetHealingRatingMod() : 1.0f;

            var boostValue = (int)Math.Round(BoostValue * ratingMod);

            var vitalChange = (uint)Math.Abs(player.UpdateVitalDelta(vital, boostValue));

            if (BoosterEnum == PropertyAttribute2nd.Health)
            {
                if (BoostValue >= 0)
                    player.DamageHistory.OnHeal(vitalChange);
                else
                    player.DamageHistory.Add(this, DamageType.Health, vitalChange);
            }

            var verb = BoostValue >= 0 ? "restores" : "takes";

            player.Session.Network.EnqueueSend(new GameMessageSystemChat($"The {Name} {verb} {vitalChange} points of your {BoosterEnum}.", ChatMessageType.Broadcast));
        }

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private void OnWindowSizeChanged(object sender, RoutedEventArgs e) {
			if (this.IsLocationSizeEventOutputEnabled)
				this.AppendMessage(String.Format("SizeChanged: {0},{1}", Math.Round(window.ActualWidth), Math.Round(window.ActualHeight)));
		}

19 View Source File : GaugeChargesTracker.cs
License : GNU Affero General Public License v3.0
Project Creator : 0ceal0t

public string GetBarText() => $"{(int)Math.Round(BarTextValue)}";

19 View Source File : IntegerDataGenerator.cs
License : MIT License
Project Creator : Actipro

protected override ICollection<IntegerData> Generate() {
			// Create the results
			List<IntegerData> results = new List<IntegerData>();

			if (this.Options != null) {
				// Initialize the date
				DateTime date = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddMonths(-this.Options.Count);

				// Initialize the results with the first data item
				results.Add(new IntegerData(date, this.Options.StartValue));
				date.AddMonths(1);

				double delta = this.Options.TrendPercentage * this.Options.StepRange;
				for (int index = 1; index < this.Options.Count; index++) {
					double step = this.Random.NextDouble() * this.Options.StepRange;
					int count = (int)Math.Round(results[index - 1].Value + step - delta);

					if (!this.AllowNegativeNumbers)
						count = Math.Max(0, count);

					results.Add(new IntegerData(date, count));
					date = date.AddMonths(1);
				}
			}

			return results;
		}

19 View Source File : Healer.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public uint GetHealAmount(Player healer, Player target, CreatureVital vital, out bool criticalHeal, out uint staminaCost)
        {
            // factors: healing skill, healing kit bonus, stamina, critical chance
            var healingSkill = healer.GetCreatureSkill(Skill.Healing).Current;
            var healBase = healingSkill * (float)HealkitMod.Value;

            // todo: determine applicable range from pcaps
            var healMin = healBase * 0.2f;      // ??
            var healMax = healBase * 0.5f;
            var healAmount = ThreadSafeRandom.Next(healMin, healMax);

            // verify healing boost comes from target instead of healer?
            // sounds like target in LumAugHealingRating...
            var ratingMod = target.GetHealingRatingMod();

            healAmount *= ratingMod;

            // chance for critical healing
            criticalHeal = ThreadSafeRandom.Next(0.0f, 1.0f) < 0.1f;
            if (criticalHeal) healAmount *= 2;

            // cap to missing vital
            var missingVital = vital.MaxValue - vital.Current;
            if (healAmount > missingVital)
                healAmount = missingVital;

            // stamina check? On the Q&A board a dev posted that stamina directly effects the amount of damage you can heal
            // low stam = less vital healed. I don't have exact numbers for it. Working through forum archive.

            // stamina cost: 1 stamina per 5 vital healed 
            staminaCost = (uint)Math.Round(healAmount / 5.0f);
            if (staminaCost > healer.Stamina.Current)
            {
                staminaCost = healer.Stamina.Current;
                healAmount = staminaCost * 5;
            }
            return (uint)Math.Round(healAmount);
        }

19 View Source File : RadarChartCustomizationLabelProviders.cs
License : MIT License
Project Creator : ABTSoftware

public override string FormatLabel(IComparable dataValue)
        {
            return string.Format("${0} B", Math.Round(dataValue.ToDouble(), 1));
        }

19 View Source File : GaugeProcsTracker.cs
License : GNU Affero General Public License v3.0
Project Creator : 0ceal0t

public string GetDiamondText(int idx) {
            var proc = Procs[idx];
            return proc.RemainingTime >= 0 ? ((int)Math.Round(proc.RemainingTime)).ToString() : "";
        }

19 View Source File : CelesteNetDebugMapComponent.cs
License : MIT License
Project Creator : 0x0ade

private void OnMapEditorRender(On.Celeste.Editor.MapEditor.orig_Render orig, MapEditor self) {
            orig(self);

            AreaKey? area = LastArea;
            string sid = area?.SID;
            AreaMode mode = area?.Mode ?? (AreaMode) (-1);

            Camera camera = (Camera) f_MapEditor_Camera.GetValue(null);

            // Adapted from Everest key rendering code.

            lock (Ghosts) {
                MDraw.SpriteBatch.Begin(
                    SpriteSortMode.Deferred,
                    BlendState.AlphaBlend,
                    SamplerState.PointClamp,
                    DepthStencilState.None,
                    RasterizerState.CullNone,
                    null,
                    camera.Matrix * Engine.ScreenMatrix
                );

                foreach (DebugMapGhost ghost in Ghosts.Values)
                    if (ghost.SID == sid && ghost.Mode == mode)
                        MDraw.Rect(ghost.Position.X / 8f, ghost.Position.Y / 8f - 1f, 1f, 1f, Color.HotPink);

                MDraw.SpriteBatch.End();

                MDraw.SpriteBatch.Begin(
                    SpriteSortMode.Deferred,
                    BlendState.AlphaBlend,
                    SamplerState.LinearClamp,
                    DepthStencilState.None,
                    RasterizerState.CullNone,
                    null,
                    Engine.ScreenMatrix
                );

                foreach (DebugMapGhost ghost in Ghosts.Values) {
                    if (ghost.SID != sid || ghost.Mode != mode)
                        continue;
                    Vector2 pos = new(ghost.Position.X / 8f + 0.5f, ghost.Position.Y / 8f - 1.5f);
                    pos -= camera.Position;
                    pos = new((float) Math.Round(pos.X), (float) Math.Round(pos.Y));
                    pos *= camera.Zoom;
                    pos += new Vector2(960f, 540f);
                    CelesteNetClientFont.DrawOutline(
                        ghost.Name,
                        pos,
                        new(0.5f, 1f),
                        Vector2.One * 0.5f,
                        Color.White * 0.8f,
                        2f, Color.Black * 0.5f
                    );
                }

                MDraw.SpriteBatch.End();
            }
        }

19 View Source File : IncidentStorm.cs
License : Apache License 2.0
Project Creator : AantCoder

public override void GameConditionTick()
        {
            if (Find.TickManager.TicksGame > nextLightningTicks)
            {
                Vector2 vector = Rand.UnitVector2 * Rand.Range(0f, areaRadius);
                IntVec3 intVec = new IntVec3((int)Math.Round(vector.x) + centerLocation.x, 0, (int)Math.Round(vector.y) + centerLocation.z);
                if (IsGoodLocationForStrike(intVec))
                {
                    base.SingleMap.weatherManager.eventHandler.AddEvent(new WeatherEvent_LightningStrike(base.SingleMap, intVec));
                    nextLightningTicks = Find.TickManager.TicksGame + cooldown;
                }
            }
            if (ambientSound)
            {
                if (soundSustainer == null || soundSustainer.Ended)
                {
                    soundSustainer = SoundDefOf.FlashstormAmbience.TrySpawnSustainer(SoundInfo.InMap(new TargetInfo(centerLocation.ToIntVec3, base.SingleMap), MaintenanceType.PerTick));
                }
                else
                {
                    soundSustainer.Maintain();
                }
            }
        }

19 View Source File : Fellowship.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void SplitXp(ulong amount, XpType xpType, ShareType shareType, Player player)
        {
            // https://asheron.fandom.com/wiki/Announcements_-_2002/02_-_Fever_Dreams#Letter_to_the_Players_1

            var fellowshipMembers = GetFellowshipMembers();

            shareType &= ~ShareType.Fellowship;

            // quest turn-ins: flat share (retail default)
            if (xpType == XpType.Quest && !PropertyManager.GetBool("fellow_quest_bonus").Item)
            {
                var perAmount = (long)amount / fellowshipMembers.Count;

                foreach (var member in fellowshipMembers.Values)
                {
                    var fellowXpType = player == member ? XpType.Quest : XpType.Fellowship;

                    member.GrantXP(perAmount, fellowXpType, shareType);
                }
            }

            // divides XP evenly to all the sharable fellows within level range,
            // but with a significant boost to the amount of xp, based on # of fellowship members
            else if (EvenShare)
            {
                var totalAmount = (ulong)Math.Round(amount * GetMemberSharePercent());

                foreach (var member in fellowshipMembers.Values)
                {
                    var shareAmount = (ulong)Math.Round(totalAmount * GetDistanceScalar(player, member, xpType));

                    var fellowXpType = player == member ? xpType : XpType.Fellowship;

                    member.GrantXP((long)shareAmount, fellowXpType, shareType);
                }

                return;
            }

            // divides XP to all sharable fellows within level range
            // based on each fellowship member's level
            else
            {
                var levelXPSum = fellowshipMembers.Values.Select(p => p.GetXPToNextLevel(p.Level.Value)).Sum();

                foreach (var member in fellowshipMembers.Values)
                {
                    var levelXPScale = (double)member.GetXPToNextLevel(member.Level.Value) / levelXPSum;

                    var playerTotal = (ulong)Math.Round(amount * levelXPScale * GetDistanceScalar(player, member, xpType));

                    var fellowXpType = player == member ? xpType : XpType.Fellowship;

                    member.GrantXP((long)playerTotal, fellowXpType, shareType);
                }
            }
        }

19 View Source File : Player_Crafting.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public int TryAddSalvage(WorldObject salvageBag, WorldObject item, int tryAmount)
        {
            var maxStructure = salvageBag.MaxStructure ?? 100;
            var structure = salvageBag.Structure ?? 0;

            var space = maxStructure - structure;

            var amount = Math.Min(tryAmount, space);

            salvageBag.Structure = (ushort)(structure + amount);

            // add workmanship
            var item_numItems = item.StackSize ?? 1;
            var workmanship_bag = salvageBag.ItemWorkmanship ?? 0;
            var workmanship_item = item.ItemWorkmanship ?? 0;

            salvageBag.ItemWorkmanship = workmanship_bag + workmanship_item * item_numItems;

            // increment # of items that went into this salvage bag
            if (item.ItemType == ItemType.TinkeringMaterial)
            {
                item_numItems = item.NumItemsInMaterial ?? 1;

                // handle overflows when combining bags
                if (tryAmount > space)
                {
                    var scalar = (float)space / tryAmount;
                    var newItems = (int)Math.Ceiling(item_numItems * scalar);
                    scalar = (float)newItems / item_numItems;
                    var prevNumItems = item_numItems;
                    item_numItems = newItems;

                    salvageBag.ItemWorkmanship -= (int)Math.Round(workmanship_item * (1.0 - scalar));

                    // and for the next bag...
                    if (prevNumItems == newItems)
                        newItems--;

                    var itemWorkmanship = item.Workmanship;
                    item.NumItemsInMaterial -= newItems;
                    //item.ItemWorkmanship -= (int)Math.Round(workmanship_item * scalar);
                    item.ItemWorkmanship = (int)Math.Round(item.NumItemsInMaterial.Value * (float)itemWorkmanship);
                }
            }
            salvageBag.NumItemsInMaterial = (salvageBag.NumItemsInMaterial ?? 0) + item_numItems;

            salvageBag.Name = $"Salvage ({salvageBag.Structure})";

            if (item.ItemType == ItemType.TinkeringMaterial)
            {
                if (!PropertyManager.GetBool("salvage_handle_overages").Item)
                    return tryAmount;
                else
                    return amount;
            }
            else
                return amount;
        }

See More Examples