コード例 #1
0
        private void Initialize(int capacity)
        {
            int size = Math2.GetPrime(capacity);

            _buckets = new int[size];

            for (int i = 0; i < _buckets.Length; i++)
            {
                _buckets[i] = -1;
            }

            _entries  = new Entry[size];
            _freeList = -1;
        }
コード例 #2
0
    protected double changeDir2()
    {
        //一点一点转向。
        if (this.joystickAngle.isZero)
        {
            //this.angle2 = this._angle;
            return(0);
        }
        double max    = this.getProperty(ConfigConstant.PROPERTY_ASP);
        double angle2 = this.joystickAngle.angle;

        angle2       = Math2.range(Math2.deltaAngle(this.angle2, angle2) * this.getProperty(ConfigConstant.PROPERTY_ASP_RATE), max, -max);
        this.angle2 += angle2;
        return(angle2);
    }
コード例 #3
0
        public void GetNcrs()
        {
            var ncr = Math2.GetNcrs();

            Assert.AreEqual(1, ncr[0, 0]);
            Assert.AreEqual(1, ncr[1, 0]);
            Assert.AreEqual(1, ncr[1, 1]);
            Assert.AreEqual(0, ncr[1, 2]);
            Assert.AreEqual(1, ncr[3, 0]);
            Assert.AreEqual(3, ncr[3, 1]);
            Assert.AreEqual(3, ncr[3, 2]);
            Assert.AreEqual(1, ncr[3, 3]);
            Assert.AreEqual(210, ncr[10, 6]);
            Assert.AreEqual(7219428434016265740, ncr[66, 33]);
        }
コード例 #4
0
        public void GetNprs()
        {
            var npr = Math2.GetNprs();

            Assert.AreEqual(1, npr[0, 0]);
            Assert.AreEqual(1, npr[1, 0]);
            Assert.AreEqual(1, npr[1, 1]);
            Assert.AreEqual(0, npr[1, 2]);
            Assert.AreEqual(1, npr[3, 0]);
            Assert.AreEqual(3, npr[3, 1]);
            Assert.AreEqual(6, npr[3, 2]);
            Assert.AreEqual(6, npr[3, 3]);
            Assert.AreEqual(151200, npr[10, 6]);
            Assert.AreEqual(2432902008176640000, npr[20, 20]);
        }
コード例 #5
0
 /// <summary>
 ///     Creates a new <see cref="ConstantBuffer" /> with the specified size in bytes.
 /// </summary>
 /// <param name="graphicsDevice"> The graphics device. </param>
 /// <param name="sizeInBytes">    The size in bytes. </param>
 /// <param name="resourceUsage">  (Optional) The resource usage. </param>
 /// <param name="cpuAccessFlags"> (Optional) The CPU access flags. </param>
 /// <returns>
 ///     A <see cref="ConstantBuffer" />.
 /// </returns>
 /// <remarks>
 ///     The <paramref name="sizeInBytes" /> must be a multiple of 16,
 ///     if not it will be calculated to the minimum multiple of 16 fitting it in.
 ///     e.g.
 ///     - a size in bytes of 11 will be 16.
 ///     - a size in bytes of 23 will be 32.
 ///     - a size in bytes of 80 will be 80.
 ///     > see https://docs.microsoft.com/de-de/windows/win32/api/d3d11/ns-d3d11-d3d11_buffer_desc#remarks
 /// </remarks>
 public static ConstantBuffer Create(IGraphicsDevice graphicsDevice,
                                     int sizeInBytes,
                                     ResourceUsage resourceUsage   = ResourceUsage.Default,
                                     CpuAccessFlags cpuAccessFlags = CpuAccessFlags.None)
 {
     return(new ConstantBuffer(
                new Buffer(
                    graphicsDevice.Device,
                    Math2.Ceiling(sizeInBytes / 16.0f) * 16,
                    resourceUsage,
                    BindFlags.ConstantBuffer,
                    cpuAccessFlags,
                    ResourceOptionFlags.None,
                    0)));
 }
コード例 #6
0
    protected override void changeDir(float rate)
    {
        //TODO:先临时这么写一下吧。
        Vector3 v = new Vector3(this.scene.transform.position.x, this._transform.position.y + ViewConstant.MAP_CAMERA_OBJECT_OFFSET_Y, this.scene.transform.position.z);

        this._transform.LookAt(v);
        this.rotation = Convert.ToSingle(Math2.radianToAngle(this._fightEntity.viewData.getAngle(rate)));

        //this.warship.transform.localPosition = new Vector3();
        //this.warship.transform.position = new Vector3();

        //平滑的转上个角速度
        //_lastAngleSpeed = _lastAngleSpeed * 0.8f + angle2 * 0.2f;
        //warshipBody.transform.localRotation = Quaternion.Euler(_lastAngleSpeed * 3f, 0, 0);
    }
コード例 #7
0
        // Not supporting complex yet, but left here for future reference

        public static void AreNear(Complex expected, Complex actual, int maxUlps)
        {
            double ulpsRe = Math2.FloatDistance(expected.Real, actual.Real);
            double ulpsIm = Math2.FloatDistance(expected.Imaginary, expected.Imaginary);

            bool nearRe = (expected.Real == actual.Real || Math.Abs(ulpsRe) <= maxUlps);
            bool nearIm = (expected.Imaginary == actual.Imaginary || Math.Abs(ulpsIm) <= maxUlps);

            if (nearRe && nearIm)
            {
                return;
            }

            throw new AssertFailedException($"Failed: actual = {actual}; expected = {expected}; ulps = ({ulpsRe}, {ulpsIm}); MaxUlps = {maxUlps}");
        }
コード例 #8
0
        private static void E2S(uint *checksum, byte[] buffer, int o1, byte[] data, int o2, int size)
        {
            byte b = ONE;

            for (int i = 0; i < size; ++i)
            {
                uint d = data[o2 + i];
                byte s = (byte)(d >> 7);
                b = (byte)(b | (s << (6 - i)));
                buffer[o1 + i] = (byte)(ONE | d);
                *checksum ^= d + C0;
            }
            buffer[o1 + size] = b;
            *checksum += Math2.R1(b, 23) + C1;
        }
コード例 #9
0
ファイル: PayloadEncoding.cs プロジェクト: hnjm/network
        private static void Encode(uint *checksum, byte *buffer, byte *data, int size)
        {
            byte b = ONE;

            for (int i = 0; i < size; ++i)
            {
                uint d = *(data + i);
                byte s = (byte)(d >> 7);
                b             = (byte)(b | (s << (6 - i)));
                *(buffer + i) = (byte)(ONE | d);
                *checksum ^= d + C0;
            }
            *(buffer + size) = b;
            *checksum += Math2.R1(b, 23) + C1;
        }
コード例 #10
0
ファイル: Cooking.cs プロジェクト: xKamuna/aura-1
        /// <summary>
        /// Calculates quality based on recipe and ingredients.
        /// </summary>
        /// <remarks>
        /// The formula used in this method is unofficial. While it does feel
        /// very similar in some test cases, it could potentially create
        /// very different results. Officials also RNG the results,
        /// which this method currently does not.
        ///
        /// The Help fields in the return value specify a tip on what went
        /// wrong with the cooking attempt, if certain requirements are
        /// fulfilled. In that case it will set the item to the item in
        /// question, and the amount to the amount the ingredient differed
        /// from the recipe. If the value is lower than 0, it was less,
        /// if it's greater, it was more. If no helpful tip could be found,
        /// item is null.
        /// </remarks>
        /// <param name="recipe"></param>
        /// <param name="ingredients"></param>
        /// <returns></returns>
        private Judgement JudgeQuality(RecipeData recipe, List <Ingredient> ingredients)
        {
            Judgement result;

            result.Quality    = 0;
            result.HelpItem   = null;
            result.HelpAmount = 0;

            var total = (float)recipe.MainIngredients.Sum(a => a.Amount);

            foreach (var ingredient in ingredients)
            {
                // Every item *should* only appear once in main or other.
                var ingredientData = recipe.MainIngredients.FirstOrDefault(a => a.ItemId == ingredient.Item.Info.Id);
                if (ingredientData == null)
                {
                    ingredientData = recipe.OtherIngredients.FirstOrDefault(a => a.ItemId == ingredient.Item.Info.Id);
                    if (ingredientData == null)
                    {
                        Log.Error("Cooking.JudgeQuality: Failed to get ingredient data for item '{0}' in recipe '{1},{2}'.", ingredient.Item.Info.Id, recipe.Method, recipe.ItemId);
                        break;
                    }
                }

                // Calculate the amount difference between the provided
                // ingredient and the recipe.
                var amount        = ingredient.Amount;
                var ideal         = (1f / total * ingredientData.Amount);
                var difference    = ideal - amount;
                var differenceAbs = Math.Abs(difference);

                // Calculate quality
                var rate       = 1f - (1f / ideal * (differenceAbs * 2f));
                var qualityAdd = ingredientData.QualityMin + rate * (ingredientData.QualityMax - ingredientData.QualityMin);

                result.Quality = Math2.Clamp(-100, 100, result.Quality + qualityAdd);

                // Save the ingredient with the biggest difference,
                // for the help message.
                if (differenceAbs > 0.05f && Math.Abs(result.HelpAmount) < differenceAbs)
                {
                    result.HelpAmount = -difference;
                    result.HelpItem   = ingredient.Item;
                }
            }

            return(result);
        }
コード例 #11
0
ファイル: World.cs プロジェクト: anjhony6778/aura
        public void Load()
        {
            this.Require("system/conf/world.conf");

            this.ExpRate      = this.GetFloat("exp_rate", 100) / 100.0f;
            this.QuestExpRate = this.GetFloat("quest_exp_rate", 100) / 100.0f;
            this.SkillExpRate = this.GetFloat("skill_exp_rate", 100) / 100.0f;

            this.DropRate              = this.GetFloat("drop_rate", 100) / 100.0f;
            this.GoldDropChance        = this.GetFloat("gold_drop_chance", 30) / 100.0f;
            this.GoldDropRate          = this.GetFloat("gold_drop_rate", 100) / 100.0f;
            this.LuckyFinishChance     = this.GetFloat("lucky_finish_chance", 0.015f) / 100.0f;
            this.BigLuckyFinishChance  = this.GetFloat("big_lucky_finish_chance", 0.005f) / 100.0f;
            this.HugeLuckyFinishChance = this.GetFloat("huge_lucky_finish_chance", 0.001f) / 100.0f;
            this.PropDropChance        = this.GetFloat("prop_drop_chance", 30) / 100.0f;

            this.DeadlyNpcs       = this.GetBool("deadly_npcs", true);
            this.EnableHunger     = this.GetBool("enable_hunger", true);
            this.YouAreWhatYouEat = this.GetBool("you_are_what_you_eat", true);

            var gmcpCommand = ChannelServer.Instance.CommandProcessor.GetCommand("gmcp");

            this.GmcpMinAuth = gmcpCommand != null ? gmcpCommand.Auth : this.GetInt("gmcp_min_auth", 50);

            this.PerfectPlay       = this.GetBool("perfect_play", false);
            this.InfiniteResources = this.GetBool("infinite_resources", false);
            this.PerfectFishing    = this.GetBool("perfect_fishing", false);
            this.InfiniteBait      = this.GetBool("infinite_bait", false);
            this.InfiniteArrows    = this.GetBool("infinite_arrows", false);

            this.Bagception        = this.GetBool("bagception", false);
            this.NoDurabilityLoss  = this.GetBool("no_durability_loss", false);
            this.UnlimitedUpgrades = this.GetBool("unlimited_upgrades", false);
            this.UncapProficiency  = this.GetBool("uncap_proficiency", false);
            this.UnlimitedDyes     = this.GetBool("unlimited_dyes", false);

            this.RebirthTime = TimeSpan.FromDays(this.GetInt("rebirth_time", 6));

            this.BankGoldPerCharacter = this.GetInt("gold_per_character", 5000000);

            this.PtjInfiniteMemory = this.GetBool("ptj_infinite_memory", false);

            this.PrivateDungeons = this.GetBool("private_dungeons", false);
            this.EasySwitch      = this.GetBool("easy_switch", false);

            this.PartyExpBonus = this.GetFloat("party_exp_bonus", 0);
            this.PartyMaxSize  = Math2.Clamp(1, 99, this.GetInt("party_max_size", 8));
        }
コード例 #12
0
        public void MultiplyCheckedLong()
        {
            // Positive
            Assert.Equal(100000L, Math2.MultiplyChecked(50000L, 2));
            Assert.Equal(2000000000L, Math2.MultiplyChecked(1000000000L, 2));
            Assert.Equal(4000000000L, Math2.MultiplyChecked(2000000000L, 2));
            Assert.Equal(long.MaxValue, Math2.MultiplyChecked(5000000000000000000, 2));
            Assert.Equal(long.MaxValue, Math2.MultiplyChecked(4500000000000000000, 3));

            // Negative
            Assert.Equal(-100000L, Math2.MultiplyChecked(-50000, 2));
            Assert.Equal(-2000000000L, Math2.MultiplyChecked(-1000000000L, 2));
            Assert.Equal(-4000000000L, Math2.MultiplyChecked(-2000000000L, 2));
            Assert.Equal(long.MinValue, Math2.MultiplyChecked(-5000000000000000000, 2));
            Assert.Equal(long.MinValue, Math2.MultiplyChecked(-4500000000000000000, 3));
        }
コード例 #13
0
        public List <KeyValuePair <int, gvec2> > AllIntersectionsBySegment(gvec2 p0, gvec2 p1)
        {
            List <KeyValuePair <int, gvec2> > res = new List <KeyValuePair <int, gvec2> >();

            for (int i = 0; i < Count; i++)
            {
                gvec2 this0        = this[i];
                gvec2 this1        = this[(i + 1) % Count];
                gvec2 intersection = new gvec2();
                if (Math2.SegmentsIntersecting(p0, p1, this0, this1, ref intersection))
                {
                    res.Add(new KeyValuePair <int, gvec2>(i, intersection));
                }
            }
            return(res);
        }
コード例 #14
0
        public static NeuralNetwork Generate(int inputLength, int outputLength)
        {
            var hiddenLayers = Math2.RoundToInt(inputLength * (2f / 3) + outputLength);

            hiddenLayers = Math2.Clamp(hiddenLayers, inputLength, outputLength);
            hiddenLayers = Math2.Clamp(hiddenLayers, 0, inputLength * 2 - 1);

            var network = new NeuralNetwork();

            network.AddLayerInput(inputLength);
            network.AddLayerHidden(hiddenLayers);
            network.AddLayerHidden(hiddenLayers);
            network.AddLayerOutput(outputLength);
            network.ConnectLayers();
            return(network);
        }
コード例 #15
0
        private static ushort E2S(byte[] data, int offset, int length, byte[] buffer, int bufferOffset,
                                  out int bufferLength)
        {
            bufferLength = length + Math2.Ceiling(length / 7.0f);
            uint checksum = s_h0;

            while (offset + 7 < length)
            {
                E2S(&checksum, buffer, bufferOffset, data, offset, 7);
                bufferOffset += 8;
                offset       += 7;
            }
            E2S(&checksum, buffer, bufferOffset, data, offset, length - offset);

            return((ushort)(CONE | ((ushort)checksum ^ (checksum >> 16))));
        }
コード例 #16
0
        public static bool TryFindRollCircleInFullFrame(IndicatorData data, out CircleF ret)
        {
            ret = default(CircleF);

            if (Timeline.Data[data.Id].Roll.ForIndicatorUse != null)
            {
                // We found our own hint, return it.
                ret = (CircleF)Timeline.Data[data.Id].Roll.ForIndicatorUse;
                return(true);
            }

            var localRect = MovementRect;

            if (data.Id > 0 &&
                Timeline.Data[data.Id - 1] != null &&
                Timeline.Data[data.Id - 1].Roll != null &&
                Timeline.Data[data.Id - 1].Roll.ForIndicatorUse != null)
            {
                // Our hint from last time.
                localRect = Math2.CropCircle((CircleF)Timeline.Data[data.Id - 1].Roll.ForIndicatorUse, 10);
            }

            // Crop and blur
            var cropped_frame = data.Frame.SafeCopy(localRect).PyrUp().PyrDown();

            var MovementFrameGray = new Mat();

            CvInvoke.CvtColor(cropped_frame, MovementFrameGray, ColorConversion.Bgr2Gray);

            // Locate the attitude and possibly vertical speed indicators.
            var circles = CvInvoke.HoughCircles(MovementFrameGray, HoughType.Gradient, 2.0, 20, 10, 180, 60, 80);

            if (circles.Length == 0)
            {
                // Couldn't find initial circle
                return(false);
            }

            // Pick the topmost circle and crop.
            var rollIndicatorCicle = circles.OrderBy(c => c.Center.Y).First();

            rollIndicatorCicle.Radius = 64;
            rollIndicatorCicle.Center = rollIndicatorCicle.Center.Add(localRect.Location);
            ret = rollIndicatorCicle;
            Timeline.Data[data.Id].Roll.ForIndicatorUse = ret;
            return(true);
        }
コード例 #17
0
        private void Circle_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            Point currentLocation = e.GetCurrentPoint(RingGrid).Position;

            RingGrid.CapturePointer(e.Pointer);

            PointerEventHandler moved = null;

            moved = (s, args) =>
            {
                currentLocation = e.GetCurrentPoint(RingGrid).Position;
                double dx = currentLocation.X - colorRingCenter.X;
                double dy = currentLocation.Y - colorRingCenter.Y;
                //---
                double hue = Math2.ComputeH(dx, dy);
                //---
                Hue          = Math2.ComputeH(dx, dy);
                CurrentColor = Math2.HSVToRGB(Hue, Saturation, Value);

                CompositeTransform ct = SeletcedColorEllipseCompositeTransform;
                Point targetPoint     = new Point(ct.TranslateX, ct.TranslateY);
                ColorPickerStoryboardStart(Hue, targetPoint);
                SelectedColorShowArea.Fill = new SolidColorBrush(CurrentColor);
            };
            PointerEventHandler released = null;

            released = (s, args) =>
            {
                double dx = currentLocation.X - colorRingCenter.X;
                double dy = currentLocation.Y - colorRingCenter.Y;
                //---
                double hue = Math2.ComputeH(dx, dy);
                //---
                Hue          = Math2.ComputeH(dx, dy);
                CurrentColor = Math2.HSVToRGB(Hue, Saturation, Value);

                CompositeTransform ct = SeletcedColorEllipseCompositeTransform;
                Point targetPoint     = new Point(ct.TranslateX, ct.TranslateY);
                ColorPickerStoryboardStart(Hue, targetPoint);
                SelectedColorShowArea.Fill = new SolidColorBrush(CurrentColor);
                RingGrid.PointerMoved     -= moved;
                RingGrid.PointerReleased  -= released;
            };

            RingGrid.PointerMoved    += moved;
            RingGrid.PointerReleased += released;
        }
コード例 #18
0
ファイル: Day12.cs プロジェクト: thijsk/AdventOfCode
        public long Part2()
        {
            var moons        = ParseInput();
            var permutations = moons.GetPermutations(2);

            int periodx = -1;
            int periody = -1;
            int periodz = -1;

            int step = 0;

            while (periodx == -1 || periody == -1 || periodz == -1)
            {
                step++;

                foreach (var permutation in permutations)
                {
                    var moon1 = permutation.First();
                    var moon2 = permutation.Last();
                    moon1.UpdateVelocity(moon2);
                }
                foreach (var moon in moons)
                {
                    moon.UpdatePosition();
                }

                if (moons.All(m => m.AtStartX()) && periodx == -1)
                {
                    periodx = step;
                }


                if (moons.All(m => m.AtStartY()) && periody == -1)
                {
                    periody = step;
                }

                if (moons.All(m => m.AtStartZ()) && periodz == -1)
                {
                    periodz = step;
                }
            }
            Console.WriteLine($"{periodx} {periody} {periodz}");
            Math2.LeastCommonMultiple(4, 4, 5);

            return(Math2.LeastCommonMultiple(periodx, periody, periodz));
        }
コード例 #19
0
        private double ReadKnotsFromNeedleLine(LineSegment2D line)
        {
            var polarAngleOfNeedle = Math2.ClampAngle(Math2.GetPolarHeadingFromLine(line) - 4); // Skew angle.

            // 0-360 deg -> 0-180 kt
            var knots = (polarAngleOfNeedle / 2);

            if (knots > 175)
            {
                knots = 0;
            }
            if (knots < 0)
            {
                knots = 0;
            }
            return(knots);
        }
コード例 #20
0
        public void Expm1Test()
        {
            //
            // C99 Appendix F special cases:
            Assert.AreEqual(0, Math2.Expm1(0));
            Assert.AreEqual(-1.0, Math2.Expm1(double.NegativeInfinity));
            Assert.AreEqual(double.PositiveInfinity, Math2.Expm1(double.PositiveInfinity));
            Assert2.AreEqual <Exceptions.DomainException>(double.NaN, () => Math2.Expm1(double.NaN));


            TestCaseSet <double>[] testCases =
            {
                new TestCaseSet <double>(GetExpData(_Exp), "Expm1: Random Data", 3, 1),
            };

            NumericFunctionTest.RunSet(Math2.Expm1, "Expm1", testCases);
        }
コード例 #21
0
    ///判断和子弹的碰撞
    public void checkBullet()
    {
        if (this._checkBulletType == 0)
        {
            return;
        }
        //TODO:这里检测了两次碰撞。 只用一次其实就够了。 filter传true。
        //Biggo修改
        List <FightEntity> bullets = this._map.getFightEntitysByRange(this._shape, new List <int> {
            ConfigConstant.ENTITY_BULLET
        }, (FightEntity entity1, FightEntity entity2) => {
            return(((BulletEntity)entity2).checkBarrier);
        }, -1);

        bullets = new List <FightEntity>(bullets);//这个要副本的!因为在bomb的时候 会改变这个通用的数组的长度。
        for (int i = 0, len = bullets.Count; i < len; i++)
        {
            BulletEntity bullet   = (BulletEntity)bullets[i];
            Vector2D     deltaV2d = bullet.findDelta.clone();
            double       dist     = bullet.findDist;
            double       radius   = bullet.shape.radius + this._shape.radius;
            //障碍物到命中点的向量
            Vector2D hitDelta          = bullet.getHitPos(this);
            double   angleHitDelta     = hitDelta.angle;
            double   angleBulletBounce = bullet.velocity.angle + Math.PI;
            //子弹回弹方向如果与命中向量夹角大于90,则说明子弹本身就是向外的,不用处理
            double angleDelta = Math2.deltaAngle(angleHitDelta, angleBulletBounce);
            if (Math.Abs(angleDelta) < Math.PI / 2)
            {
                if (this._checkBulletType == 1)
                {
                    //新子弹的速度方向改变
                    bullet.velocity.angle = bullet.angle = angleHitDelta - angleDelta * 0.5f;
                }
                else if (this._checkBulletType == 2)
                {
                    //引爆消亡逻辑
                    bullet.bomb();
                }

                deltaV2d.length = bullet.backForce * this._bounceSelfRate * 0.6f;
                addForce(deltaV2d);
                this.dispatchEventWith(EventConstant.HIT);
            }
        }
    }
コード例 #22
0
ファイル: YawIndicator.cs プロジェクト: davuxcom/GTA-Pilot
        public double ReadValue(IndicatorData data, DebugState debugState)
        {
            if (TryFindCircleInFullFrame(data, out var circ))
            {
                var focusRect            = Math2.CropCircle(circ, 15);
                var focus                = data.Frame.SafeCopy(focusRect);
                var focusHsv             = focus.Convert <Hsv, byte>();
                var focusHsvText         = focusHsv.DynLowInRange(dyn_lower, new Hsv(180, 255, 255));
                var focusHsvTriangleMask = focusHsv.InRange(new Hsv(0, 0, 0), new Hsv(180, 140, 255));
                var focusHsvTextOnly     = focusHsvText.Copy(focusHsvTriangleMask);

                debugState.Add(focus);

                var blobs = Utils.DetectAndFilterBlobs(focusHsvTextOnly, 25, 250).
                            Where(b => b.Centroid.Y >= 5).OrderByDescending(b => b.Area).Take(4);

                var focusHsvOnlyBlobs = Utils.RemoveAllButBlobs(focusHsvTextOnly, blobs);
                debugState.Add(focusHsvOnlyBlobs);

                var parts = GetPacksFromImage(focusHsvOnlyBlobs, blobs, debugState);
                var ret   = ComputeHeadingFromPacks(data.Id, parts, focus, debugState);

                if (!double.IsNaN(ret))
                {
                    // Adjust now that N and S are near-vertical and the blobs are more regular.
                    ret = RefineAngle(ret, focusHsvOnlyBlobs);
                    // Adjust based on the dots on the glareshield.
                    ret += GetGlareShieldSkewAngle(focusRect, data, debugState);
                    // Add a fixed cab skew to account for the vertical perspective.
                    ret -= 1;

                    ret = Math2.ClampAngle(ret);

                    // Proof for the debug info.
                    debugState.Add(focus.Rotate(ret, new Bgr(0, 0, 0)));

                    return(CheckResultValidity(ret, data.Id));
                }
            }
            else
            {
                debugState.SetError("Couldn't find initial circle.");
            }
            return(double.NaN);
        }
コード例 #23
0
        void test_values(double val)
        {
            const double a   = 1.3456724e22;
            const double b   = 1.3456724e-22;
            const double z   = 0;
            const double one = 1;
            const double two = 2;


            TestValue(a);
            TestValue(-a);
            TestValue(b);
            TestValue(-b);
            TestValue(MachineEpsilon);
            TestValue(-MachineEpsilon);
            // TestValue(double.MinValue);
            // TestValue(-double.MinValue);
            TestValue(z);
            TestValue(-z);
            TestValue(one);
            TestValue(-one);
            TestValue(two);
            TestValue(-two);
            TestValue(double.Epsilon);
            TestValue(-double.Epsilon);
            TestValue(2 * double.Epsilon);
            TestValue(-2 * double.Epsilon);



            for (int i = 0; i < _Primes.Length; ++i)
            {
                double v1 = val;
                double v2 = val;
                for (int j = 0; j < _Primes[i]; ++j)
                {
                    v1 = Math2.FloatNext(v1);
                    v2 = Math2.FloatPrior(v2);
                }
                Assert.AreEqual(_Primes[i], Math2.FloatDistance(v1, val));
                Assert.AreEqual(-_Primes[i], Math2.FloatDistance(v2, val));
                Assert.AreEqual(v1, Math2.FloatAdvance(val, _Primes[i]));
                Assert.AreEqual(v2, Math2.FloatAdvance(val, -_Primes[i]));
            }
        }
コード例 #24
0
        public bool IntersectsAny(gvec2 p0, int thisIndex)
        {
            gvec2 p1 = this[thisIndex];

            for (int i0 = 0; i0 < Count; i0++)
            {
                int i1 = (i0 + 1) % Count;
                if (i0 != thisIndex && i1 != thisIndex)
                {
                    gvec2 res = new gvec2();
                    if (Math2.SegmentsIntersecting(p0, p1, this[i0], this[i1], ref res))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
コード例 #25
0
 public unsafe NativeFont_(int dpi, bool bold, bool italic, int height = 0)
 {
     Api.LOGFONT m = default;
     Dpi.SystemParametersInfo(Api.SPI_GETICONTITLELOGFONT, sizeof(Api.LOGFONT), &m, dpi);
     if (bold)
     {
         m.lfWeight = 700;
     }
     if (italic)
     {
         m.lfItalic = 1;
     }
     if (height != 0)
     {
         m.lfHeight = -Math2.MulDiv(height, dpi, 72);
     }
     _h = Api.CreateFontIndirect(m);
 }
コード例 #26
0
ファイル: YawIndicator.cs プロジェクト: davuxcom/GTA-Pilot
        private double RefineAngle(double resultAngle, Image <Gray, byte> focus)
        {
            var rotatedNorthUp = focus.Rotate(resultAngle, new Gray(0));

            // Re-rotate the frame now that N and S are vertical, so the centroids are in predictable
            // locations no matter what the inital angle was.
            var list = Utils.DetectAndFilterBlobs(rotatedNorthUp, 25, 250).OrderBy(b => b.Centroid.Y);

            if (list.Count() >= 2)
            {
                var verticalLine         = new LineSegment2DF(new PointF(focus.Size.Width / 2, 0), new PointF(focus.Size.Width / 2, focus.Size.Height));
                var lineFromNorthToSouth = new LineSegment2DF(list.First().Centroid, list.Last().Centroid);
                var skewAngle            = Math2.angleBetween2Lines(lineFromNorthToSouth, verticalLine) * (180 / Math.PI);
                // Divide by two since this is relative to the center of the line.
                resultAngle -= skewAngle / 2;
            }
            return(resultAngle);
        }
コード例 #27
0
        /// <inheritdoc />
        protected override float Single(int seed, double x, double y)
        {
            int x0 = Math2.Floor(x);
            int y0 = Math2.Floor(y);
            int x1 = x0 + 1;
            int y1 = y0 + 1;

            double xd0 = x - x0;
            double yd0 = y - y0;
            double xs, ys;

            switch (_noiseInterpolationType)
            {
            default:
            case NoiseInterpolationType.Linear:
                xs = xd0;
                ys = yd0;
                break;

            case NoiseInterpolationType.Hermite:
                xs = Math2.CurveHermite(xd0);
                ys = Math2.CurveHermite(yd0);
                break;

            case NoiseInterpolationType.Quintic:
                xs = Math2.CurveQuintic(xd0);
                ys = Math2.CurveQuintic(yd0);
                break;
            }

            double xd1 = xd0 - 1.0f;
            double yd1 = yd0 - 1.0f;

            return(Math2.Lerp(
                       Math2.Lerp(
                           GradCoord2D(seed, x0, y0, xd0, yd0),
                           GradCoord2D(seed, x1, y0, xd1, yd0),
                           xs),
                       Math2.Lerp(
                           GradCoord2D(seed, x0, y1, xd0, yd1),
                           GradCoord2D(seed, x1, y1, xd1, yd1),
                           xs),
                       ys));
        }
コード例 #28
0
        /// <inheritdoc />
        void IUpdateableCameraComponent.Update(GameTime gameTime, ICamera camera)
        {
            float x = Interlocked.Exchange(ref _x, 0);
            float y = Interlocked.Exchange(ref _y, 0);

            // ReSharper disable CompareOfFloatsByEqualityOperator
            if (x == 0 && y == 0)
            {
                return;
            }

            // ReSharper enable CompareOfFloatsByEqualityOperator

            float invSqrt = Math2.FastInverseSqrt((x * x) + (y * y));

            _yaw -= x * invSqrt * MOUSE_SPEED_X * gameTime.DeltaTimeS;
            _yaw  = (float)((-MathUtil.Pi + (_yaw + MathUtil.Pi)) -
                            (MathUtil.TwoPi * Math.Floor((_yaw + MathUtil.Pi) / MathUtil.TwoPi)));

            _pitch -= y * invSqrt * MOUSE_SPEED_Y * gameTime.DeltaTimeS;
            if (_pitch < -PITCH_LIMIT)
            {
                _pitch = -PITCH_LIMIT;
            }
            else if (_pitch > PITCH_LIMIT)
            {
                _pitch = PITCH_LIMIT;
            }

            Math2.SinCos(_pitch, out float height, out float distance);

            Math2.SinCos(_yaw, out float lookZ, out float lookX);
            lookX *= distance;
            lookZ *= distance;

            Math2.SinCos(_yaw + MathUtil.PiOverTwo, out float strafeZ, out float strafeX);

            camera.Up = Vector3.Cross(
                new Vector3(strafeX * distance, 0, strafeZ * distance), new Vector3(lookX, height, lookZ));
            camera.Target = new Vector3(
                camera.Position.X + lookX,
                camera.Position.Y + height,
                camera.Position.Z + lookZ);
        }
コード例 #29
0
        public void Log1pTest()
        {
            //
            // C99 Appendix F special cases:
            Assert.AreEqual(0, Math2.Log1p(0));
            Assert.AreEqual(0, Math2.Log1p(-0));
            Assert.AreEqual(double.NegativeInfinity, Math2.Log1p(-1));
            Assert.AreEqual(double.PositiveInfinity, Math2.Log1p(double.PositiveInfinity));
            Assert2.AreEqual <Exceptions.DomainException>(double.NaN, () => Math2.Log1p(double.NaN));

            //BOOST_CHECK_THROW(Math2.Log1p(m_one));

            TestCaseSet <double>[] testCases =
            {
                new TestCaseSet <double>(GetLogData(_Exp), "Log1p: Random Data", 2, 1),
            };

            NumericFunctionTest.RunSet(Math2.Log1p, "Log1p", testCases);
        }
コード例 #30
0
        public void FloatAdvanceTest()
        {
            // test non-symettrical behaviors - NaN, -0.0, Infinity

            for (int i = 1; i < 255; i++)
            {
                Assert2.AreEqual <Exceptions.DomainException>(double.NaN, () => Math2.FloatAdvance(double.NaN, i));
                Assert2.AreEqual <Exceptions.DomainException>(double.NaN, () => Math2.FloatAdvance(double.NaN, -i));
                Assert2.AreEqual <Exceptions.DomainException>(double.NaN, () => Math2.FloatAdvance(double.PositiveInfinity, i));
                Assert2.AreEqual <Exceptions.DomainException>(double.NaN, () => Math2.FloatAdvance(double.PositiveInfinity, -i));
                Assert2.AreEqual <Exceptions.DomainException>(double.NaN, () => Math2.FloatAdvance(double.NegativeInfinity, i));
                Assert2.AreEqual <Exceptions.DomainException>(double.NaN, () => Math2.FloatAdvance(double.NegativeInfinity, -i));

                Assert.AreEqual(double.PositiveInfinity, Math2.FloatAdvance(double.MaxValue, i));
                Assert.AreEqual(double.NegativeInfinity, Math2.FloatAdvance(double.MinValue, -i));

                Assert.AreEqual(double.Epsilon * (double)i, Math2.FloatAdvance(-0.0, i));   // -0.0, double.Epsilon
                Assert.AreEqual(-double.Epsilon * (double)i, Math2.FloatAdvance(-0.0, -i)); // -0.0, -double.Epsilon
            }



            foreach (var item in _FloatData)
            {
                double x        = item.X;
                int    distance = item.Distance;
                double expected = item.Result;
                double actual   = Math2.FloatAdvance(x, distance);

                Assert2.AreNear(expected, actual, 0,
                                () => { return(string.Format("FloatAdvance({0:E16},{1}) = {2:E16}; got = {3:E16}; ulps = {4}", x, distance, expected, actual, 0)); });

                // check to see that the reverse is true

                x        = item.Result;
                distance = -item.Distance;
                expected = item.X;
                actual   = Math2.FloatAdvance(x, distance);

                Assert2.AreNear(expected, actual, 0,
                                () => { return(string.Format("FloatAdvance({0:E16},{1}) = {2:E16}; got = {3:E16}; ulps = {4}", x, distance, expected, actual, 0)); });
            }
        }