System.Math.Floor(double)

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

2783 Examples 7

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

public static string IncrementLast(string val, string search, string replace)
        {
            var match = Regex.Match(val, search);
            if (match.Success) {
                var matchLength = match.Groups[2].Value.Length;
                if (int.TryParse(match.Groups[2].Value, out int n) && int.TryParse(replace, out int incVal)) {
                    var i = n + incVal;
                    string pad = string.Empty;
                    if (i > 0) {
                        for (int j = (int)Math.Floor(Math.Log10(i)); j < (matchLength - 1); j++) {
                            pad += "0";
                        }
                    }

                    return Regex.Replace(val, search, m => m.Groups[1].Value + pad + i);
                }
            }
            return val;
        }

19 View Source File : Reshape2DKernel.cs
License : MIT License
Project Creator : adamtiger

public void Execute()
        {
            Dimension dimI = input.GetDimension();
            Dimension dimO = output.GetDimension();

            int B1 = dimI.h * dimI.w * dimI.c;
            int B2 = dimO.h * dimO.w * dimO.c;

            int H1 = dimI.w * dimI.c;
            int H2 = dimO.w * dimO.c;

            int W1 = dimI.c;
            int W2 = dimO.c;

            int virtualIdx = 0;
            int cc, bb, hh, ww;

            for (int b = 0; b < dimI.b; ++b)
            {
                for (int h = 0; h < dimI.h; ++h)
                {
                    for (int w = 0; w < dimI.w; ++w)
                    {
                        for (int c = 0; c < dimI.c; ++c)
                        {
                            virtualIdx = b * B1 + h * H1 + w * W1 + c;

                            bb = (int)Math.Floor((double)virtualIdx / B2);
                            virtualIdx = virtualIdx % B2;

                            hh = (int)Math.Floor((double)virtualIdx / H2);
                            virtualIdx = virtualIdx % H2;

                            ww = (int)Math.Floor((double)virtualIdx / W2);
                            cc = virtualIdx % W2;

                            output[hh, ww, cc, bb] = input[h, w, c, b];
                        }
                    }
                }
            }
        }

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

public void update_internal(float timeElapsed, ref LinkedListNode<AnimSequenceNode> animNode, ref float frameNum, ref AFrame frame)
        {
            var currAnim = animNode.Value;

            var framerate = currAnim.Framerate;
            var frametime = framerate * timeElapsed;

            var lastFrame = (int)Math.Floor(frameNum);

            frameNum += frametime;
            var frameTimeElapsed = 0.0f;
            var animDone = false;

            if (frametime > 0.0f)
            {
                if (currAnim.get_high_frame() < Math.Floor(frameNum))
                {
                    var frameOffset = frameNum - currAnim.get_high_frame() - 1.0f;
                    if (frameOffset < 0.0f)
                        frameOffset = 0.0f;

                    if (Math.Abs(framerate) > PhysicsGlobals.EPSILON)
                        frameTimeElapsed = frameOffset / framerate;

                    frameNum = currAnim.get_high_frame();
                    animDone = true;
                }
                while (Math.Floor(frameNum) > lastFrame)
                {
                    if (frame != null)
                    {
                        if (currAnim.Anim.PosFrames != null)
                            frame = AFrame.Combine(frame, currAnim.get_pos_frame(lastFrame));

                        if (Math.Abs(framerate) > PhysicsGlobals.EPSILON)
                            apply_physics(frame, 1.0f / framerate, timeElapsed);
                    }

                    execute_hooks(currAnim.get_part_frame(lastFrame), AnimationHookDir.Forward);
                    lastFrame++;
                }
            }
            else if (frametime < 0.0f)
            {
                if (currAnim.get_low_frame() > Math.Floor(frameNum))
                {
                    var frameOffset = frameNum - currAnim.get_low_frame();
                    if (frameOffset > 0.0f)
                        frameOffset = 0.0f;

                    if (Math.Abs(framerate) > PhysicsGlobals.EPSILON)
                        frameTimeElapsed = frameOffset / framerate;

                    frameNum = currAnim.get_low_frame();
                    animDone = true;
                }
                while (Math.Floor(frameNum) < lastFrame)
                {
                    if (frame != null)
                    {
                        if (currAnim.Anim.PosFrames != null)
                            frame.Subtract(currAnim.get_pos_frame(lastFrame));

                        if (Math.Abs(framerate) > PhysicsGlobals.EPSILON)
                            apply_physics(frame, 1.0f / framerate, timeElapsed);
                    }

                    execute_hooks(currAnim.get_part_frame(lastFrame), AnimationHookDir.Backward);
                    lastFrame--;
                }
            }
            else
            {
                if (frame != null && Math.Abs(timeElapsed) > PhysicsGlobals.EPSILON)
                    apply_physics(frame, timeElapsed, timeElapsed);
            }

            if (!animDone)
                return;

            if (HookObj != null)
            {
                var node = AnimList.First;
                if (!node.Equals(FirstCyclic))
                    HookObj.add_anim_hook(AnimationHook.AnimDoneHook);
            }

            advance_to_next_animation(timeElapsed, ref animNode, ref frameNum, ref frame);
            timeElapsed = frameTimeElapsed;

            // loop to next anim
            update_internal(timeElapsed, ref animNode, ref frameNum, ref frame);    
        }

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

public void ManaConsumersTick()
        {
            if (!EquippedObjectsLoaded) return;

            foreach (var item in EquippedObjects.Values)
            {
                if (!item.IsAffecting)
                    continue;

                if (item.ItemCurMana == null || item.ItemMaxMana == null || item.ManaRate == null)
                    continue;

                var burnRate = -item.ManaRate.Value;

                if (LumAugItemManaUsage != 0)
                    burnRate *= GetNegativeRatingMod(LumAugItemManaUsage * 5);

                item.ItemManaRateAcreplacedulator += (float)(burnRate * CachedHeartbeatInterval);

                if (item.ItemManaRateAcreplacedulator < 1)
                    continue;

                var manaToBurn = (int)Math.Floor(item.ItemManaRateAcreplacedulator);

                if (manaToBurn > item.ItemCurMana)
                    manaToBurn = item.ItemCurMana.Value;

                item.ItemCurMana -= manaToBurn;

                item.ItemManaRateAcreplacedulator -= manaToBurn;

                if (item.ItemCurMana > 0)
                    CheckLowMana(item, burnRate);
                else
                    HandleManaDepleted(item);
            }
        }

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

private static int CalculateArcaneLore(WorldObject wo, TreasureRoll roll)
        {
            // spellcraft - (itemSkillLevelLimit / 2.0f) + creatureLifeEnchantments + cantrips

            var spellcraft = wo.ItemSpellcraft.Value;

            // - mutates 100% of the time for melee / missile weapons
            // - mutates 55% of the time for armor
            // - mutates 0% of the time for all other item types
            var itemSkillLevelFactor = 0.0f;

            if (wo.ItemSkillLevelLimit > 0)
                itemSkillLevelFactor = wo.ItemSkillLevelLimit.Value / 2.0f;

            var fArcane = spellcraft - itemSkillLevelFactor;

            if (fArcane < 0)
                fArcane = 0;

            return (int)Math.Floor(fArcane + roll.ItemDifficulty);
        }

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

public static bool OnRoad(ObjectDesc obj, CellLandblock landblock, float x, float y)
        {
            var cellX = (int)Math.Floor(x / LandblockMesh.CellSize);
            var cellY = (int)Math.Floor(y / LandblockMesh.CellSize);
            var terrain = landblock.Terrain[cellX * LandblockMesh.CellDim + cellY];     // ensure within bounds?
            return (terrain & 0x3) != 0;    // TODO: more complicated check for within road range
        }

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

private void UpdateAxisMinAndMax() {
			decimal min = SelectedStock.StockPrices.Min(priceData => priceData.Price);
			decimal max = SelectedStock.StockPrices.Max(priceData => priceData.Price);
			YAxisMinimum = (decimal?)Math.Floor((double)(min - UpdateThreshold));
			YAxisMaximum = max + UpdateThreshold;
		}

19 View Source File : ElasticWrapPanel.cs
License : MIT License
Project Creator : 944095635

protected override Size ArrangeOverride(Size finalSize)
        {
            if (_columns == 0) return base.ArrangeOverride(finalSize);
            var columnWidth = Math.Floor(finalSize.Width/_columns);
            var totalHeight = 0d;
            var top = 0d;
            var rowHeight = 0d;
            var overflow = 0d;
            var column = 0;
            var index = 0;
            var overflowAlreadyCount = false;

            foreach (UIElement child in Children)
            {
                // Compute the tile size and position
                child.Arrange(new Rect(columnWidth*column, top, columnWidth, child.DesiredSize.Height));
                column++;
                rowHeight = Children.Count >= _columns
                    ? Math.Max(rowHeight, child.DesiredSize.Height)
                    : Math.Min(rowHeight, child.DesiredSize.Height);
                index++;

                // Check if the current element is at the end of a row and add an height overflow to get enough space for the next elements of the second row
                if (column == _columns && Children.Count != index && (Children.Count - index + 1) <= _columns &&
                    !overflowAlreadyCount)
                {
                    overflow = rowHeight;
                    totalHeight += rowHeight;
                    overflowAlreadyCount = true;
                }
                else
                {
                    if (!overflowAlreadyCount)
                        totalHeight += rowHeight;
                }

                if (column != _columns) continue;
                column = 0;
                top += rowHeight;
                rowHeight = 0;
            }

            if (Children.Count >= _columns)
                totalHeight = totalHeight/_columns + overflow;

            Height = totalHeight;
            finalSize.Height = totalHeight;
            return base.ArrangeOverride(finalSize);
        }

19 View Source File : FileSize.cs
License : MIT License
Project Creator : Adoxio

public string ToString(int precision, IFormatProvider formatProvider = null)
		{
			var pow = Math.Floor((_value > 0 ? Math.Log(_value) : 0) / Math.Log(1024));

			pow = Math.Min(pow, _units.Length - 1);

			var value = _value / Math.Pow(1024, pow);

			var precisionString = formatProvider == null
				? precision.ToString(CultureInfo.CurrentCulture)
				: precision.ToString(formatProvider);

			return value.ToString(Math.Abs(pow - 0) < double.Epsilon ? "F0" : "F" + precisionString) + " " + _units[(int)pow];
		}

19 View Source File : VirtualizingWrapPanel .cs
License : MIT License
Project Creator : 944095635

private ExtentInfo GetExtentInfo(Size viewPortSize)
        {
            if (_itemsControl == null)
            {
                return new ExtentInfo();
            }

            var itemsPerLine = Math.Max((int)Math.Floor(viewPortSize.Width / ItemWidth), 1);
            var totalLines = (int)Math.Ceiling((double)_itemsControl.Items.Count / itemsPerLine);
            var extentHeight = Math.Max(totalLines * ItemHeight, viewPortSize.Height);

            return new ExtentInfo
            {
                ItemsPerLine = itemsPerLine,
                TotalLines = totalLines,
                ExtentHeight = extentHeight,
                MaxVerticalOffset = extentHeight - viewPortSize.Height,
            };
        }

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

public void CalcNumSteps(ref Vector3 offset, ref Vector3 offsetPerStep, ref int numSteps)
        {
            if (SpherePath.BeginPos == null)
            {
                offset = Vector3.Zero;
                offsetPerStep = Vector3.Zero;
                numSteps = 1;
                return;
            }
            offset = SpherePath.BeginPos.GetOffset(SpherePath.EndPos);
            var dist = offset.Length();
            var step = dist / SpherePath.LocalSphere[0].Radius;

            if (!ObjectInfo.State.HasFlag(ObjectInfoState.IsViewer))
            {
                if (step > 1.0f)
                {
                    numSteps = (int)Math.Ceiling(step);
                    offsetPerStep = offset * (1.0f / numSteps);
                }
                else if (!offset.Equals(Vector3.Zero))
                {
                    offsetPerStep = offset;
                    numSteps = 1;
                }
                else
                {
                    offsetPerStep = Vector3.Zero;
                    numSteps = 0;
                }
                return;
            }

            if (dist <= PhysicsGlobals.EPSILON)
            {
                offsetPerStep = Vector3.Zero;
                numSteps = 0;
            }
            else
            {
                offsetPerStep = offset * (1.0f / step);
                numSteps = (int)Math.Floor(step) + 1;
            }
        }

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

public static bool AdjustToOutside(ref uint blockCellID, ref Vector3 loc)
        {
            var cellID = (uint)(blockCellID & CellID_Mask);

            if (cell_in_range(cellID))
            {
                if (Math.Abs(loc.X) < PhysicsGlobals.EPSILON)
                    loc.X = 0;
                if (Math.Abs(loc.Y) < PhysicsGlobals.EPSILON)
                    loc.Y = 0;

                var lcoord = get_outside_lcoord(blockCellID, loc.X, loc.Y);
                if (lcoord.HasValue)
                {
                    blockCellID = (uint)lcoord_to_gid(lcoord.Value.X, lcoord.Value.Y);
                    loc.X -= (float)Math.Floor(loc.X / BlockLength) * BlockLength;
                    loc.Y -= (float)Math.Floor(loc.Y / BlockLength) * BlockLength;
                    return true;
                }
            }
            blockCellID = 0;
            return false;
        }

19 View Source File : Utils.cs
License : Apache License 2.0
Project Creator : acblog

public static string ToFriendlyString(this DateTimeOffset value)
        {
            TimeSpan tspan = DateTimeOffset.Now - value;
            StringBuilder sb = new StringBuilder();
            if (tspan.TotalDays > 60)
            {
                sb.Append(value.ToString("F"));
            }
            else if (tspan.TotalDays > 30)
            {
                sb.Append("1 month ago");
            }
            else if (tspan.TotalDays > 14)
            {
                sb.Append("2 weeks ago");
            }
            else if (tspan.TotalDays > 7)
            {
                sb.Append("1 week ago");
            }
            else if (tspan.TotalDays > 1)
            {
                sb.Append($"{(int)Math.Floor(tspan.TotalDays)} days ago");
            }
            else if (tspan.TotalHours > 1)
            {
                sb.Append($"{(int)Math.Floor(tspan.TotalHours)} hours ago");
            }
            else if (tspan.TotalMinutes > 1)
            {
                sb.Append($"{(int)Math.Floor(tspan.TotalMinutes)} minutes ago");
            }
            else if (tspan.TotalSeconds > 1)
            {
                sb.Append($"{(int)Math.Floor(tspan.TotalSeconds)} seconds ago");
            }
            else
            {
                sb.Append("just");
            }
            return sb.ToString();
        }

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

private static string IncrementString(string startNumber, int incVal, bool keepLeadingZeros)
        {
            var matchLength = startNumber.Length;
            if (!string.IsNullOrEmpty(startNumber) && int.TryParse(startNumber, out int n)) {
                var i = n + incVal;
                var pad = string.Empty;
                if (i > 0) {
                    for (var j = (int)Math.Floor(Math.Log10(i)); j < (matchLength - 1); j++) {
                        pad += "0";
                    }
                }
                return keepLeadingZeros ? pad + i : i.ToString();
            }
            return startNumber;
        }

19 View Source File : Mathd.cs
License : MIT License
Project Creator : 734843327

public static double Floor(double d) {
            return Math.Floor(d);
        }

19 View Source File : NumberContextData.cs
License : MIT License
Project Creator : actions

public override JToken ToJToken()
        {
            if (Double.IsNaN(m_value) || m_value == Double.PositiveInfinity || m_value == Double.NegativeInfinity)
            {
                return (JToken)m_value;
            }

            var floored = Math.Floor(m_value);
            if (m_value == floored && m_value <= (Double)Int32.MaxValue && m_value >= (Double)Int32.MinValue)
            {
                var flooredInt = (Int32)floored;
                return (JToken)flooredInt;
            }
            else if (m_value == floored && m_value <= (Double)Int64.MaxValue && m_value >= (Double)Int64.MinValue)
            {
                var flooredInt = (Int64)floored;
                return (JToken)flooredInt;
            }
            else
            {
                return (JToken)m_value;
            }
        }

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

public AFrame get_pos_frame(float frameIdx)
        {
            return get_pos_frame((int)Math.Floor(frameIdx));
        }

19 View Source File : Interval.cs
License : GNU Affero General Public License v3.0
Project Creator : active-logic

static internal float EvalInc(float p, float o, float s, float t)
    => (float)(Floor((t - s - o) / p) + 1) * p;

19 View Source File : ZColorPicker.cs
License : MIT License
Project Creator : 0xLaileb

private Color HSVtoRGB(double H, double S, double V)
        {
            double R, G, B;
            if (S == 0)
            {
                R = V * 255;
                G = V * 255;
                B = V * 255;
            }
            else
            {
                double H1 = H * 6;
                if (H1 == 6) H1 = 0;

                int i = (int)Math.Floor(H1);

                double i1 = V * (1 - S);
                double i2 = V * (1 - S * (H1 - i));
                double i3 = V * (1 - S * (1 - (H1 - i)));

                switch (i)
                {
                    case 0:
                        R = V;
                        G = i3;
                        B = i1;
                        break;
                    case 1:
                        R = i2;
                        G = V;
                        B = i1;
                        break;
                    case 2:
                        R = i1;
                        G = V;
                        B = i3;
                        break;
                    case 3:
                        R = i1;
                        G = i2;
                        B = V;
                        break;
                    case 4:
                        R = i3;
                        G = i1;
                        B = V;
                        break;
                    default:
                        R = V;
                        G = i1;
                        B = i2;
                        break;
                }

                R *= 255;
                G *= 255;
                B *= 255;
            }
            return Color.FromArgb((int)R, (int)G, (int)B);
        }

19 View Source File : BufferedPageReaderWriter.cs
License : MIT License
Project Creator : Adoxio

protected void Seek(long position)
		{
			this.Flush();

			var pageNumber = (int)Math.Floor((double)position / this.PageSize);

			this.filePointer = position;
			this.bufferPointer = (int)(position - (pageNumber * this.PageSize));

			if (pageNumber == this.pageNumber)
			{
				return;
			}

			this.pageNumber = pageNumber;

			this.ReadCurrentPage();
		}

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

public static void add_all_outside_cells(int numParts, List<PhysicsPart> parts, CellArray cellArray, uint id)
        {
            if (cellArray.AddedOutside)
                return;

            cellArray.AddedOutside = true;

            if (numParts == 0)
                return;

            var min_x = 0;
            var min_y = 0;
            var max_x = 0;
            var max_y = 0;

            for (var i = 0; i < numParts; i++)
            {
                var curPart = parts[i];

                var loc = new Position(curPart.Pos);

                if (!LandDefs.AdjustToOutside(loc))
                    continue;

                var _lcoord = LandDefs.gid_to_lcoord(loc.ObjCellID);

                if (_lcoord == null)
                    continue;

                var lcoord = _lcoord.Value;

                var lx = (int)(((loc.ObjCellID & 0xFFFF) - 1) / 8);
                var ly = (int)(((loc.ObjCellID & 0xFFFF) - 1) % 8);

                for (var j = 0; j < numParts; j++)
                {
                    var otherPart = parts[j];

                    if (otherPart == null)
                        continue;

                    // add if missing: otherPart.Always2D, checks degrades.degradeMode != 1

                    var bbox = new BBox();
                    bbox.LocalToGlobal(otherPart.GetBoundingBox(), otherPart.Pos, loc);

                    var min_cx = (int)Math.Floor(bbox.Min.X / 24.0f);
                    var min_cy = (int)Math.Floor(bbox.Min.Y / 24.0f);

                    var max_cx = (int)Math.Floor(bbox.Max.X / 24.0f);
                    var max_cy = (int)Math.Floor(bbox.Max.Y / 24.0f);

                    min_x = Math.Min(min_cx - lx, min_x);
                    min_y = Math.Min(min_cy - ly, min_y);

                    max_x = Math.Max(max_cx - lx, max_x);
                    max_y = Math.Max(max_cy - ly, max_y);
                }

                add_cell_block(min_x + (int)lcoord.X, min_y + (int)lcoord.Y, max_x + (int)lcoord.X, max_y + (int)lcoord.Y, cellArray, id);
            }
        }

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

public static int ItemTotalXPToLevel(ulong gainedXP, ulong baseXP, int maxLevel, ItemXpStyle xpScheme)
        {
            var level = 0;

            switch (xpScheme)
            {
                case ItemXpStyle.Fixed:
                    level = (int)Math.Floor((double)gainedXP / baseXP);
                    break;

                case ItemXpStyle.ScalesWithLevel:

                    var levelXP = baseXP;
                    var remainXP = gainedXP;

                    while (remainXP >= levelXP)
                    {
                        level++;

                        remainXP -= levelXP;
                        levelXP *= 2;
                    }
                    break;

                case ItemXpStyle.FixedPlusBase:

                    if (gainedXP >= baseXP && gainedXP < baseXP * 3)
                        level = 1;
                    else
                        level = (int)Math.Floor((double)(gainedXP - baseXP) / baseXP);

                    break;
            }

            if (level > maxLevel)
                level = maxLevel;

            return level;
        }

19 View Source File : DrawEngine.cs
License : MIT License
Project Creator : 0xLaileb

public static Color HSV_To_RGB(float hue, float saturation, float value)
        {
            if (saturation < float.Epsilon)
            {
                int c = (int)(value * 255);
                return Color.FromArgb(c, c, c);
            }
            if (timer_global_rgb.Enabled) hue = h_temp;

            float r, g, b, f, p, q, t;
            int i;

            hue /= 60;
            i = (int)Math.Floor(hue);

            f = hue - i;
            p = value * (1 - saturation);
            q = value * (1 - saturation * f);
            t = value * (1 - saturation * (1 - f));

            switch (i)
            {
                case 0: r = value; g = t; b = p; break;
                case 1: r = q; g = value; b = p; break;
                case 2: r = p; g = value; b = t; break;
                case 3: r = p; g = q; b = value; break;
                case 4: r = t; g = p; b = value; break;
                default: r = value; g = p; b = q; break;
            }
            return Color.FromArgb(255, (int)(r * 255), (int)(g * 255), (int)(b * 255));
        }

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

public bool IsRoad(DatLoader.Enreplacedy.ObjectDesc obj, float x, float y)
        {
            var cellX = (int)Math.Floor(x / LandDefs.CellLength);
            var cellY = (int)Math.Floor(y / LandDefs.CellLength);
            var terrain = Terrain[cellX * LandDefs.BlockSide + cellY];     // ensure within bounds?
            return (terrain & 0x3) != 0;    // TODO: more complicated check for within road range
        }

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

private SimulatedMouseInput SimulateAngledInput(double angle, double magnitude)
        {
            SimulatedMouseInput mouseInputData;

            var moveX = Math.Round(magnitude * Math.Cos(angle), 4);
            var moveY = Math.Round(magnitude * Math.Sin(angle), 4);

            if (moveX == 0)
            {
                mouseInputData.x = 0;
                mouseInputData.y = (int)Math.Ceiling(moveY);
                mouseInputData.time = mouseInputData.y / moveY;
            }
            else if (moveY == 0)
            {
                mouseInputData.x = (int)Math.Ceiling(moveX);
                mouseInputData.y = 0;
                mouseInputData.time = mouseInputData.x / moveX;
            }
            else
            {
                var ratio =  moveY / moveX;
                int ceilX = 0;
                int ceilY = 0;
                double biggerX = 0;
                double biggerY = 0;
                double roundedBiggerX = 0;
                double roundedBiggerY = 0;
                double roundedRatio = -1;
                double factor = 10;

                while (Math.Abs(roundedRatio - ratio) > 0.01 &&
                    biggerX < 25000 &&
                    biggerY < 25000)
                {
                    roundedBiggerX = Math.Floor(biggerX);
                    roundedBiggerY = Math.Floor(biggerY);
                    ceilX = Convert.ToInt32(roundedBiggerX);
                    ceilY = Convert.ToInt32(roundedBiggerY);
                    roundedRatio =  ceilX > 0 ? ceilY / ceilX : -1;
                    biggerX = moveX * factor;
                    biggerY = moveY * factor;
                    factor *= 10;
                }

                var ceilMagnitude = Magnitude(ceilX, ceilY);
                var timeFactor = ceilMagnitude / magnitude;

                mouseInputData.x = ceilX;
                mouseInputData.y = ceilY;
                mouseInputData.time = timeFactor;

                if (mouseInputData.x == 1 && mouseInputData.time == 1)
                {
                    Console.WriteLine("Oops");
                }

            }

            mouseInputData.velocity = DecimalCheck(Velocity(mouseInputData.x, mouseInputData.y, mouseInputData.time));

            if (double.IsNaN(mouseInputData.velocity))
            {
                Console.WriteLine("oopsie");
            }

            mouseInputData.angle = angle;
            return mouseInputData;
        }

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

public RoadAlphaMap FindRoadAlpha(uint pcode, uint rcode, out LandDefs.Rotation rot, out int alphaIdx)
        {
            rot = LandDefs.Rotation.Rot0;
            alphaIdx = -1;

            var numRoadMaps = RoadMaps.Count;
            if (numRoadMaps == 0)
                return null;

            var prng = (int)Math.Floor((1379576222 * pcode - 1372186442) * 2.3283064e-10 * numRoadMaps);

            for (var i = 0; i < numRoadMaps; i++)
            {
                var idx = (i + prng) % numRoadMaps;
                var alpha = RoadMaps[idx];
                rot = LandDefs.Rotation.Rot0;
                var alphaCode = alpha.RCode;
                alphaIdx = 5 + idx;

                for (var j = 0; j < 4; j++)
                {
                    if (alphaCode == rcode)
                    {
                        rot = (LandDefs.Rotation)j;
                        if (alpha.Texture == null && alpha.RoadTexGID != 0)
                            alpha.Texture = new ImgTex(DBObj.GetSurfaceTexture(alpha.RoadTexGID));

                        return alpha;
                    }
                    alphaCode *= 2;
                    if (alphaCode >= 16)
                        alphaCode -= 15;
                }
            }
            alphaIdx = -1;
            return null;
        }

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

public static Vector2? get_outside_lcoord(uint blockCellID, float _x, float _y)
        {
            var cellID = (uint)(blockCellID & CellID_Mask);
             
            if (cell_in_range(cellID))
            {
                var offset = blockid_to_lcoord(blockCellID);
                if (!offset.HasValue) return null;

                var x = offset.Value.X + (float)Math.Floor(_x / CellLength);
                var y = offset.Value.Y + (float)Math.Floor(_y / CellLength);

                if (x < 0 || y < 0 || x >= LandLength || y >= LandLength)
                    return null;
                else
                    return new Vector2(x, y);
            }
            return null;
        }

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

private void ComputeXAxisRange(double time)
        {
            if (time >= XVisibleRange.Max)
            {
                // Calculates a visible range. When the trace touches the right edge of the chart
                // (governed by WindowSize), shift the entire range 50% so that the trace is in the 
                // middle of the chart 
                double fractionSize = WindowSize * 0.5;
                double newMin = fractionSize * Math.Floor((time - fractionSize) / fractionSize);
                double newMax = newMin + WindowSize;

                XVisibleRange = new DoubleRange(newMin, newMax);
            }
        }

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

public static int CalcNumUnits(int skill, float workmanship, int numAugs)
        {
            // https://web.archive.org/web/20170130213649/http://www.thejackcat.com/AC/Shopping/Crafts/Salvage_old.htm
            // https://web.archive.org/web/20170130194012/http://www.thejackcat.com/AC/Shopping/Crafts/Salvage.htm

            return 1 + (int)Math.Floor(skill / 194.0f * workmanship * (1.0f + 0.25f * numAugs));
        }

19 View Source File : WebTicketManager.cs
License : MIT License
Project Creator : 42skillz

public async Task<string> Reserve(string trainId, int seatsRequestedCount)
        {
            List<Seat> availableSeats = new List<Seat>();
            int count = 0;

            // get the train
            var jsonTrain = await _trainDataService.GetTrain(trainId);

            var trainInst = new Train(jsonTrain);
            if (trainInst.ReservedSeats + seatsRequestedCount <= Math.Floor(ThreasholdManager.GetMaxRes() * trainInst.GetMaxSeat()))
            {
                var numberOfReserv = 0;
                // find seats to reserve
                for (int index = 0, i = 0; index < trainInst.Seats.Count; index++)
                {
                    var each = trainInst.Seats[index];
                    if (each.BookingRef == "")
                    {
                        i++;
                        if (i <= seatsRequestedCount)
                        {
                            availableSeats.Add(each);
                        }
                    }
                }

                foreach (var unused in availableSeats)
                {
                    count++;
                }

                var reservedSets = 0;

                string bookingRef;
                if (count != seatsRequestedCount)
                {
                    return $"{{\"train_id\": \"{trainId}\", \"booking_reference\": \"\", \"seats\": []}}";
                }
                else
                {
                    bookingRef = await _bookingReferenceService.GetBookingReference();

                    foreach (var availableSeat in availableSeats)
                    {
                        availableSeat.BookingRef = bookingRef;
                        numberOfReserv++;
                        reservedSets++;
                    }
                }

                if (numberOfReserv == seatsRequestedCount)
                {
                    await _trainCaching.Save(trainId, trainInst, bookingRef);

                    await _trainDataService.BookSeats(trainId, bookingRef, availableSeats);
                    return
                            $"{{\"train_id\": \"{trainId}\", \"booking_reference\": \"{bookingRef}\", \"seats\": {dumpSeats(availableSeats)}}}";
                    
                }
            }
            return $"{{\"train_id\": \"{trainId}\", \"booking_reference\": \"\", \"seats\": []}}";
        }

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

private int GetBuyCost(int? value, ItemType? itemType)
        {
            var buyRate = BuyPrice ?? 1;
            if (itemType == ItemType.PromissoryNote)
                buyRate = 1.0;

            var cost = Math.Max(1, (int)Math.Floor(((float)buyRate * (value ?? 0)) + 0.1));
            return cost;
        }

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

public static Vector2 GetCell(Vector2 point)
        {
            var cellX = (float)Math.Floor(point.X / CellSize);
            var cellY = (float)Math.Floor(point.Y / CellSize);

            if (cellX < 0) cellX = 0;
            if (cellY < 0) cellY = 0;

            if (cellX >= CellDim) cellX = CellDim - 1;
            if (cellY >= CellDim) cellY = CellDim - 1;

            return new Vector2(cellX, cellY);
        }

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

public static string Increment(string val, string search, string replace)
        {
            if (string.IsNullOrEmpty(val) || string.IsNullOrEmpty(search)) {
                return val;
            }
            var match = Regex.Match(val, search);
            if (match.Success) {
                var matchLength = match.Groups[1].Value.Length;
                if (int.TryParse(match.Groups[1].Value, out int n) && int.TryParse(replace, out int incVal)) {
                    var i = n + incVal;
                    var firstPart = val.Substring(0, match.Groups[1].Index);
                    var secondPart = val.Substring(match.Groups[1].Index + match.Groups[1].Length);
                    var pad = string.Empty;
                    if (i > 0) {
                        for (var j = (int)Math.Floor(Math.Log10(i)); j < (matchLength - 1); j++) {
                            pad += "0";
                        }
                    }
                    return firstPart + pad + i + secondPart;
                }
            }
            return val;
        }

19 View Source File : GmicPipeServer.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

private unsafe string PrepareCroppedLayers(InputMode inputMode, RectangleF cropRect)
        {
            if (inputMode == InputMode.NoInput)
            {
                return string.Empty;
            }

            IReadOnlyList<GmicLayer> layers = GetRequestedLayers(inputMode);

            if (layers.Count == 0)
            {
                return string.Empty;
            }

            if (memoryMappedFiles.Capacity < layers.Count)
            {
                memoryMappedFiles.Capacity = layers.Count;
            }

            StringBuilder reply = new StringBuilder();

            foreach (GmicLayer layer in layers)
            {
                Surface surface = layer.Surface;
                bool disposeSurface = false;
                int destinationImageStride = surface.Stride;

                if (cropRect != WholeImageCropRect)
                {
                    int cropX = (int)Math.Floor(cropRect.X * layer.Width);
                    int cropY = (int)Math.Floor(cropRect.Y * layer.Height);
                    int cropWidth = (int)Math.Min(layer.Width - cropX, 1 + Math.Ceiling(cropRect.Width * layer.Width));
                    int cropHeight = (int)Math.Min(layer.Height - cropY, 1 + Math.Ceiling(cropRect.Height * layer.Height));

                    try
                    {
                        surface = layer.Surface.CreateWindow(cropX, cropY, cropWidth, cropHeight);
                    }
                    catch (ArgumentOutOfRangeException ex)
                    {
                        throw new InvalidOperationException(string.Format("Surface.CreateWindow bounds invalid, cropRect={0}", cropRect.ToString()), ex);
                    }
                    disposeSurface = true;
                    destinationImageStride = cropWidth * ColorBgra.SizeOf;
                }

                string mapName = "pdn_" + Guid.NewGuid().ToString();

                try
                {
                    MemoryMappedFile file = MemoryMappedFile.CreateNew(mapName, surface.Scan0.Length);
                    memoryMappedFiles.Add(file);

                    using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor())
                    {
                        byte* destination = null;
                        RuntimeHelpers.PrepareConstrainedRegions();
                        try
                        {
                            accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref destination);

                            for (int y = 0; y < surface.Height; y++)
                            {
                                ColorBgra* src = surface.GetRowAddressUnchecked(y);
                                byte* dst = destination + (y * destinationImageStride);

                                Buffer.MemoryCopy(src, dst, destinationImageStride, destinationImageStride);
                            }
                        }
                        finally
                        {
                            if (destination != null)
                            {
                                accessor.SafeMemoryMappedViewHandle.ReleasePointer();
                            }
                        }
                    }
                }
                finally
                {
                    if (disposeSurface)
                    {
                        surface.Dispose();
                    }
                }

                reply.AppendFormat(
                    CultureInfo.InvariantCulture,
                    "{0},{1},{2},{3}\n",
                    mapName,
                    surface.Width.ToString(CultureInfo.InvariantCulture),
                    surface.Height.ToString(CultureInfo.InvariantCulture),
                    destinationImageStride.ToString(CultureInfo.InvariantCulture));
            }

            return reply.ToString();
        }

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

private DrawingVisual CreateDrawingVisualHatch(Hatch hatch)
        {
            DrawingVisual drawingVisual = new DrawingVisual();
            if (hatch == null) {
                return drawingVisual;
            }

            DrawingContext drawingContext = drawingVisual.RenderOpen();

            double dx = 0;
            double dy = 0;

            var scale = hatch.IsDrafting ? 10 : 1;

            drawingContext.PushClip(new RectangleGeometry(new Rect(0, 0, width, height)));
            drawingContext.DrawRectangle(Brushes.White, null, new Rect(0, 0, width, height));
            drawingContext.PushTransform(new TranslateTransform(width / 2, height / 2));
            drawingContext.DrawEllipse(null, new Pen(Brushes.LightBlue, 1), new Point(0, 0), 10, 10);
            drawingContext.DrawLine(new Pen(Brushes.LightBlue, 1), new Point(-20, 0), new Point(20, 0));
            drawingContext.DrawLine(new Pen(Brushes.LightBlue, 1), new Point(0, -20), new Point(0, 20));
            drawingContext.PushTransform(new ScaleTransform(canvreplacedcale, canvreplacedcale));

            double maxLength = width > height ? width / canvreplacedcale * 2 : height / canvreplacedcale * 2;

            foreach (var fillGrid in hatch.HatchPattern.GetFillGrids()) {
                double scaledSequenceLength = GetDashedLineLength(fillGrid, 1, scale);
                double initialShiftOffset = scaledSequenceLength > 0 ? (int)Math.Floor(maxLength / scaledSequenceLength) * scaledSequenceLength : maxLength;
                if (scaledSequenceLength > maxLength / 4) {
                    initialShiftOffset = scaledSequenceLength * 16;
                }

                var segsInMM = new List<double>();
                foreach (var s in fillGrid.GetSegments()) {
                    segsInMM.Add(s.ToMM(scale));
                }

                if (Math.Abs(fillGrid.Offset) < 0.001) {
                    continue;
                }

                int b = 0;

                var pen = new Pen(Brushes.Black, 1);
                pen.DashStyle = new DashStyle(segsInMM, initialShiftOffset);

                double a = fillGrid.Angle.ToDeg();
                drawingContext.PushTransform(new RotateTransform(-a, fillGrid.Origin.U.ToMM(scale), -fillGrid.Origin.V.ToMM(scale)));

                double replacedulativeShift = 0;

                while (Math.Abs(dy) < maxLength * 2) {
                    b++;
                    if (b > 100) {
                        break;
                    }
                    double x = fillGrid.Origin.U.ToMM(scale) - initialShiftOffset;
                    double y = -fillGrid.Origin.V.ToMM(scale);
                    drawingContext.PushTransform(new TranslateTransform(x + dx, y - dy));
                    drawingContext.DrawLine(pen, new Point(0, 0), new Point(initialShiftOffset * 2, 0));
                    drawingContext.Pop();
                    drawingContext.PushTransform(new TranslateTransform(x - dx, y + dy));
                    drawingContext.DrawLine(pen, new Point(0, 0), new Point(initialShiftOffset * 2, 0));
                    drawingContext.Pop();
                    dx += fillGrid.Shift.ToMM(scale);
                    replacedulativeShift += fillGrid.Shift.ToMM(scale);
                    if (Math.Abs(replacedulativeShift) > scaledSequenceLength) {
                        dx -= scaledSequenceLength;
                        replacedulativeShift = 0;
                    }
                    dy += fillGrid.Offset.ToMM(scale);
                }
                drawingContext.Pop();
                dx = 0;
                dy = 0;
            }
            drawingContext.Pop();
            drawingContext.Pop();
            drawingContext.Pop();

            drawingContext.DrawText(
                new FormattedText(
                    string.Format(System.Globalization.CultureInfo.InvariantCulture, "Scale: {0}", scale * canvreplacedcale),
                    System.Globalization.CultureInfo.InvariantCulture,
                    FlowDirection.LeftToRight,
                    new Typeface("arial"),
                    10,
                    Brushes.LightBlue,
                    1),
                new Point(10, 10));

            drawingContext.Close();
            return drawingVisual;
        }

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

private static int RollItemDifficulty(WorldObject wo, int numEpics, int numLegendaries)
        {
            // - # of spells on item
            var num_spells = wo.Biota.PropertiesSpellBook.Count();

            var spellAddonChance = num_spells * (20.0f / (num_spells + 2.0f));
            var spellAddon = (float)ThreadSafeRandom.Next(1.0f, spellAddonChance) * num_spells;

            // - # of epics / legendaries on item
            var epicAddon = numEpics > 0 ? ThreadSafeRandom.Next(1, 5) * numEpics : 0;
            var legAddon = numLegendaries > 0 ? ThreadSafeRandom.Next(5, 10) * numLegendaries : 0;

            // wield difficulty - skill requirement
            var wieldFactor = 0.0f;

            if (wo.WieldDifficulty != null && wo.WieldRequirements == WieldRequirement.RawSkill)
                wieldFactor = wo.WieldDifficulty.Value / 3.0f;

            var itemDifficulty = wo.ItemSpellcraft.Value - wieldFactor;

            if (itemDifficulty < 0)
                itemDifficulty = 0;

            return (int)Math.Floor(itemDifficulty + spellAddon + epicAddon + legAddon);
        }

19 View Source File : IExpressionNodeExtensions.cs
License : MIT License
Project Creator : actions

private static void Match(
            IExpressionNode node,
            Stack<IExpressionNode>[] patterns,
            Boolean[] result)
        {
            var nodeSegments = GetMatchSegments(node);

            if (nodeSegments.Count == 0)
            {
                return;
            }

            var nodeNamedValue = nodeSegments.Peek() as NamedValue;
            var originalNodeSegments = nodeSegments;

            for (var i = 0; i < patterns.Length; i++)
            {
                var patternSegments = patterns[i];
                var patternNamedValue = patternSegments.Peek() as NamedValue;

                // Compare the named-value
                if (String.Equals(nodeNamedValue.Name, patternNamedValue.Name, StringComparison.OrdinalIgnoreCase))
                {
                    // Clone the stacks before mutating
                    nodeSegments = new Stack<IExpressionNode>(originalNodeSegments.Reverse());
                    nodeSegments.Pop();
                    patternSegments = new Stack<IExpressionNode>(patternSegments.Reverse());
                    patternSegments.Pop();

                    // Walk the stacks
                    while (true)
                    {
                        // Every pattern segment was matched
                        if (patternSegments.Count == 0)
                        {
                            result[i] = true;
                            break;
                        }
                        // Every node segment was matched. Treat the pattern as matched. There is not
                        // enough information to determine whether the property is required; replacedume it is.
                        // For example, consider the pattern "github.event" and the expression "toJson(github)".
                        // In this example the function requires the full structure of the named-value.
                        else if (nodeSegments.Count == 0)
                        {
                            result[i] = true;
                            break;
                        }

                        var nodeSegment = nodeSegments.Pop();
                        var patternSegment = patternSegments.Pop();

                        // The behavior of a wildcard varies depending on whether the left operand
                        // is an array or an object. For simplicity, treat the pattern as matched.
                        if (nodeSegment is Wildcard)
                        {
                            result[i] = true;
                            break;
                        }
                        // Treat a wildcard pattern segment as matching any literal segment
                        else if (patternSegment is Wildcard)
                        {
                            continue;
                        }

                        // Convert literals to string and compare
                        var nodeLiteral = nodeSegment as Literal;
                        var nodeEvaluationResult = EvaluationResult.CreateIntermediateResult(null, nodeLiteral.Value);
                        var nodeString = nodeEvaluationResult.ConvertToString();
                        var patternLiteral = patternSegment as Literal;
                        var patternEvaluationResult = EvaluationResult.CreateIntermediateResult(null, patternLiteral.Value);
                        var patternString = patternEvaluationResult.ConvertToString();
                        if (String.Equals(nodeString, patternString, StringComparison.OrdinalIgnoreCase))
                        {
                            continue;
                        }

                        // Convert to number and compare
                        var nodeNumber = nodeEvaluationResult.ConvertToNumber();
                        if (!Double.IsNaN(nodeNumber) && nodeNumber >= 0d && nodeNumber <= (Double)Int32.MaxValue)
                        {
                            var patternNumber = patternEvaluationResult.ConvertToNumber();
                            if (!Double.IsNaN(patternNumber) && patternNumber >= 0 && patternNumber <= (Double)Int32.MaxValue)
                            {
                                nodeNumber = Math.Floor(nodeNumber);
                                patternNumber = Math.Floor(patternNumber);
                                if (nodeNumber == patternNumber)
                                {
                                    continue;
                                }
                            }
                        }

                        // Not matched
                        break;
                    }
                }
            }
        }

19 View Source File : Mathd.cs
License : MIT License
Project Creator : 734843327

public static int FloorToInt(double d) {
            return (int)Math.Floor(d);
        }

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

private Control CreateRandomChildControl(int seed) {
			string[] commonLabels = new string[] { "Blank Page", "Bookmark", "Chart", "Cover Page", "Cross Reference", "Drop-Cap", "Equation", "Footer", "Header" };
			int randomIndex = Math.Min(commonLabels.Length - 1, (int)Math.Floor(new Random(seed * DateTime.Now.Millisecond).NextDouble() * commonLabels.Length));

			string label = commonLabels[randomIndex];
			string imageSourceBase = "/Images/Icons/" + commonLabels[randomIndex].Replace(" ", String.Empty).Replace("-", String.Empty);

			RibbonControls.Button button = new RibbonControls.Button();
			button.Label = label; 
			button.ImageSourceSmall = new BitmapImage(new Uri(imageSourceBase + "16.png", UriKind.Relative));
			button.ImageSourceLarge = new BitmapImage(new Uri(imageSourceBase + "32.png", UriKind.Relative));

			return button;
		}

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

public int get_curr_frame_number()
        {
            return (int)Math.Floor(FrameNumber);
        }

19 View Source File : RasterCache.cs
License : MIT License
Project Creator : adamped

public static SKMatrix GetIntegralTransCTM(SKMatrix ctm)
        {
            //C++ TO C# CONVERTER TODO TASK: The following line was determined to contain a copy constructor call - this should be verified and a copy constructor should be created:
            //ORIGINAL LINE: SKMatrix result = ctm;
            SKMatrix result = ctm;
            result.TransX = (float)Math.Floor((ctm.TransX) + 0.5f);
            result.TransY = (float)Math.Floor((ctm.TransY) + 0.5f);
            return result;
        }

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

protected override void TickTracker() {
            ChargesActive.Clear();
            var barreplacedigned = false;
            var currentChargesValue = 0;

            foreach (var part in Config.Parts) {
                var diamondFound = false;
                foreach (var trigger in part.Triggers) {
                    if (trigger.Type == ItemType.Buff) {
                        var buffExists = UIHelper.PlayerStatus.TryGetValue(trigger, out var buff);
                        var buffValue = buffExists ? buff.StackCount : 0;

                        if (part.Bar && !barreplacedigned && buffExists) {
                            barreplacedigned = true;
                            BarPercentValue = buff.RemainingTime / part.Duration;
                            BarTextValue = buff.RemainingTime;
                        }
                        if (part.Diamond) {
                            currentChargesValue += buffValue;
                            AddToActive(buffValue, part.MaxCharges);
                        }
                        if (buffExists || buffValue > 0) {
                            diamondFound = true;
                            break;
                        }
                    }
                    else {
                        var recastActive = UIHelper.GetRecastActive(trigger.Id, out var timeElapsed);
                        var actionValue = recastActive ? (int)Math.Floor(timeElapsed / part.CD) : part.MaxCharges;

                        if (part.Bar && !barreplacedigned && recastActive) {
                            barreplacedigned = true;
                            var currentTime = timeElapsed % part.CD;
                            var timeLeft = part.CD - currentTime;

                            BarPercentValue = currentTime / part.CD;
                            BarTextValue = timeLeft;
                        }
                        if (part.Diamond) {
                            currentChargesValue += actionValue;
                            AddToActive(actionValue, part.MaxCharges);
                        }
                        if (recastActive || actionValue > 0) {
                            diamondFound = true;
                            break;
                        }
                    }
                }
                if (!diamondFound) AddToActive(0, part.MaxCharges); // part is empty
            }
            if (!barreplacedigned) BarTextValue = BarPercentValue = 0;

            if (currentChargesValue != ChargesActiveTotal) {
                if (currentChargesValue == 0) {
                    if (Config.CompletionSound == GaugeCompleteSoundType.When_Empty || Config.CompletionSound == GaugeCompleteSoundType.When_Empty_or_Full)
                        UIHelper.PlaySeComplete();
                }
                else if (currentChargesValue == TotalCharges) {
                    if (Config.CompletionSound == GaugeCompleteSoundType.When_Full || Config.CompletionSound == GaugeCompleteSoundType.When_Empty_or_Full)
                        UIHelper.PlaySeComplete();
                }
                else if (Config.ProgressSound) UIHelper.PlaySeProgress();
            }
            ChargesActiveTotal = currentChargesValue;
        }

19 View Source File : LineBreaker.h.cs
License : MIT License
Project Creator : adamped

public float nextTab(float widthSoFar)
  {
	for (int i = 0; i < mStops.Count; i++)
	{
	  if (mStops[i] > widthSoFar)
	  {
		return mStops[i];
	  }
	}
	return Math.Floor(widthSoFar / mTabWidth + 1) * mTabWidth;
  }

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

public static void add_all_outside_cells(Position position, int numSphere, List<Sphere> spheres, CellArray cellArray)
        {
            if (cellArray.AddedOutside) return;

            if (numSphere != 0)
            {
                foreach (var sphere in spheres)
                {
                    var cellPoint = position.ObjCellID;
                    var center = sphere.Center;

                    if (!LandDefs.AdjustToOutside(ref cellPoint, ref center))
                        break;

                    var point = new Vector2();
                    point.X = center.X - (float)Math.Floor(center.X / 24.0f) * 24.0f;
                    point.Y = center.Y - (float)Math.Floor(center.Y / 24.0f) * 24.0f;
                    var minRad = sphere.Radius;
                    var maxRad = 24.0f - minRad;

                    var lcoord = LandDefs.gid_to_lcoord(cellPoint);
                    if (lcoord != null)
                    {
                        add_outside_cell(cellArray, lcoord.Value);
                        check_add_cell_boundary(cellArray, point, lcoord.Value, minRad, maxRad);
                    }
                }
            }
            else
            {
                if (!LandDefs.AdjustToOutside(position)) return;

                var lcoord = LandDefs.gid_to_lcoord(position.ObjCellID);
                if (lcoord != null)
                    add_outside_cell(cellArray, lcoord.Value);
            }
        }

19 View Source File : VirtualizingWrapPanel .cs
License : MIT License
Project Creator : 944095635

private ItemLayoutInfo GetLayoutInfo(Size availableSize, double itemHeight, ExtentInfo extentInfo)
        {
            if (_itemsControl == null)
            {
                return new ItemLayoutInfo();
            }

            // we need to ensure that there is one realized item prior to the first visible item, and one after the last visible item,
            // so that keyboard navigation works properly. For example, when focus is on the first visible item, and the user
            // navigates up, the ListBox selects the previous item, and the scrolls that into view - and this triggers the loading of the rest of the items 
            // in that row

            var firstVisibleLine = (int)Math.Floor(VerticalOffset / itemHeight);

            var firstRealizedIndex = Math.Max(extentInfo.ItemsPerLine * firstVisibleLine - 1, 0);
            var firstRealizedItemLeft = firstRealizedIndex % extentInfo.ItemsPerLine * ItemWidth - HorizontalOffset;
            // ReSharper disable once PossibleLossOfFraction
            var firstRealizedItemTop = firstRealizedIndex / extentInfo.ItemsPerLine * itemHeight - VerticalOffset;

            var firstCompleteLineTop = (firstVisibleLine == 0 ? firstRealizedItemTop : firstRealizedItemTop + ItemHeight);
            var completeRealizedLines = (int)Math.Ceiling((availableSize.Height - firstCompleteLineTop) / itemHeight);

            var lastRealizedIndex = Math.Min(firstRealizedIndex + completeRealizedLines * extentInfo.ItemsPerLine + 2, _itemsControl.Items.Count - 1);

            return new ItemLayoutInfo
            {
                FirstRealizedItemIndex = firstRealizedIndex,
                FirstRealizedItemLeft = firstRealizedItemLeft,
                FirstRealizedLineTop = firstRealizedItemTop,
                LastRealizedItemIndex = lastRealizedIndex,
            };
        }

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

public static MTexture GetIcon(string emote, float time) {
            Atlas atlas;
            if ((atlas = GetIconAtlas(ref emote)) == null)
                return null;

            List<string> iconPaths = new(emote.Split(' '));
            if (iconPaths.Count > 1 && int.TryParse(iconPaths[0], out int fps)) {
                iconPaths.RemoveAt(0);
            } else {
                fps = 7; // Default FPS.
            }

            List<MTexture> icons = iconPaths.SelectMany(iconPath => {
                iconPath = iconPath.Trim();
                List<MTexture> subs = atlas.orig_GetAtlreplacedubtextures(iconPath);
                if (subs.Count != 0)
                    return subs;
                if (atlas.Has(iconPath))
                    return new List<MTexture>() { atlas[iconPath] };
                if (iconPath.ToLowerInvariant() == "end")
                    return new List<MTexture>() { null };
                return new List<MTexture>();
            }).ToList();

            if (icons.Count == 0)
                return null;

            if (icons.Count == 1)
                return icons[0];

            int index = (int) Math.Floor(time * fps);

            if (index >= icons.Count - 1 && icons[icons.Count - 1] == null)
                return icons[icons.Count - 2];

            return icons[index % icons.Count];
        }

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

public void Rect(float x, float y, float width, float height, Color color) {
            int xi = (int) Math.Floor(x);
            int yi = (int) Math.Floor(y);
            int wi = (int) Math.Ceiling(x + width) - xi;
            int hi = (int) Math.Ceiling(y + height) - yi;

            Rectangle rect = new(xi, yi, wi, hi);

            MDraw.SpriteBatch.Draw(
                BlurRT,
                rect, rect,
                Color.White * Math.Min(1f, color.A / 255f * 2f)
            );

            MDraw.Rect(xi, yi, wi, hi, color);
        }

19 View Source File : IdleBus`1.ThreadScan.cs
License : MIT License
Project Creator : 2881099

bool ThreadJoin(TimeSpan interval)
        {
            if (interval <= TimeSpan.Zero) return true;
            var milliseconds = interval.TotalMilliseconds;
            var seconds = Math.Floor(milliseconds / 1000);
            milliseconds = milliseconds - seconds * 1000;

            for (var a = 0; a < seconds; a++)
            {
                Thread.CurrentThread.Join(TimeSpan.FromSeconds(1));
                if (isdisposed) return false;
            }
            for (var a = 0; a < milliseconds; a += 200)
            {
                Thread.CurrentThread.Join(TimeSpan.FromMilliseconds(200));
                if (isdisposed) return false;
            }
            return true;
        }

19 View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1

private static string ImportCellFormula(string cellFormula)
        {
            if (cellFormula.Length == 0) return cellFormula;

            string newCellFormula = cellFormula;

            //Unescape the "s if we are looking at a CellFormula that has been escaped
            if (newCellFormula.StartsWith('"'))
            {
                //Strip the outer quotes
                newCellFormula = new string(newCellFormula.Skip(1).Take(newCellFormula.Length - 2).ToArray());

                //Escape the inside content
                newCellFormula = ExcelHelperClreplaced.UnescapeFormulaString(newCellFormula);
            }

            //Replace any uses of SELECT and ACTIVE.CELL with variable usage to better enable the sheet being hidden
            //Mainly for use with importing EXCELntDonut macros
            newCellFormula = ReplaceSelectActiveCellFormula(newCellFormula);

            //FORMULA requires R1C1 strings
            newCellFormula = ConvertA1StringToR1C1String(newCellFormula);

            int charReplacements = 0;
            //Remap CHAR() to actual bytes
            for (int i = 1; i <= 255; i += 1)
            {
                int oldLength = newCellFormula.Length;
                newCellFormula = newCellFormula.Replace(string.Format("CHAR({0})&", i), "" + (char) i);
                newCellFormula = newCellFormula.Replace(string.Format("CHAR({0})", i), "" + (char)i);

                //Update our poor heuristic for when we're getting a cell that is just CHAR()&CHAR()&CHAR()&CHAR()...
                if (oldLength != newCellFormula.Length)
                {
                    double lengthDelta = oldLength - newCellFormula.Length;
                    charReplacements += (int)Math.Floor(lengthDelta / 6.0);
                }
            }
            
            //Arbitrary metric to determine if we should convert this to a string cell vs. formula cell
            if (charReplacements > 3 && newCellFormula[0] == '=')
            {
                newCellFormula = new string(newCellFormula.Skip(1).ToArray());

                //Excel cells will also check to see if we are a variable replacedignment cell:
                //if we have valid variable letters before an =, it will process the replacedignment value
                bool looksLikeVariablereplacedignment = LooksLikeVariablereplacedignment(newCellFormula);

                //If we have a raw string content that starts with = or @, we can wrap this with ="" and it will work
                //If the string content is already 255 bytes though, this won't work (FORMULA will fail trying to write the 258 byte string)
                //If we're close to the limit then populate the cell with =CHAR(w/e)&Ref to cell with remainder of the content
                if (newCellFormula.StartsWith('=') || newCellFormula.StartsWith('@') || looksLikeVariablereplacedignment)
                {
                    //Need to make sure there's room for inserting 3 more characters =""
                    if (newCellFormula.Length >= 255 - 3)
                    {
                        //If this is a max length cell (common with 255 byte increments of shellcode)
                        //then mark the macro with a marker and we'll break it into two cells when we're building the sheet
                        return FormulaHelper.TOOLONGMARKER + newCellFormula;
                    }
                    else
                    {
                        newCellFormula = string.Format("=\"{0}\"", newCellFormula);
                    }
                    
                }
            }
            else
            {
                //TODO Use a proper logging package and log this as DEBUG info
                // Console.WriteLine(newCellFormula);
            }

            if (newCellFormula.Length > 255)
            {
                throw new ArgumentException(string.Format("Imported Cell Formula is too long - length must be 255 or less:\n{0}", newCellFormula));
            }


            return newCellFormula;
        }

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

public TerrainAlphaMap FindTerrainAlpha(uint pcode, uint tcode, out LandDefs.Rotation rot, out int alphaIdx)
        {
            List<TerrainAlphaMap> terrainMaps = null;
            var baseIdx = 0;

            // corner tcodes - sw / se / ne / nw
            if (tcode != 1 && tcode != 2 && tcode != 4 && tcode != 8)
            {
                baseIdx = 4;
                terrainMaps = SideTerrainMaps;   // common tcode: 9
            }
            else
                terrainMaps = CornerTerrainMaps; // common tcode: 8

            var numTerrains = terrainMaps.Count;

            var prng = (int)Math.Floor((1379576222 * pcode - 1372186442) * 2.3283064e-10 * numTerrains);
            if (prng >= numTerrains)
                prng = 0;

            var alpha = terrainMaps[prng];
            alphaIdx = baseIdx + prng;

            rot = LandDefs.Rotation.Rot0;

            var i = 0;
            var alphaCode = alpha.TCode;
            while (alphaCode != tcode)
            {
                // corners: 8 -> 1 -> 2 -> 4
                // sides: 9 -> 3 -> 6 -> 12
                // west / south / east / north?
                alphaCode *= 2;
                if (alphaCode >= 16)
                    alphaCode -= 15;
                if (++i >= 4)
                    return null;
            }
            rot = (LandDefs.Rotation)i;

            if (alpha.Texture == null && alpha.TexGID != 0)
            {
                var qdid = new QualifiedDataID(11, alpha.TexGID);
                alpha.Texture = new ImgTex(DBObj.GetSurfaceTexture(alpha.TexGID));
            }
            return alpha;
        }

See More Examples