コード例 #1
0
ファイル: MatrixTest.cs プロジェクト: RichardBradley/MMEd
 public void TestFloatHelper()
 {
     Assert.IsTrue(FloatHelper.AlmostEqual(-1.224606e-16, 0));
     Assert.IsTrue(FloatHelper.AlmostEqual(
                       33.760013846626308,
                       33.76002));
 }
コード例 #2
0
        float?GetText(IEnumerable <IElement> allTds, int skip)
        {
            var td   = allTds.Skip(skip).First();
            var span = td.QuerySelector("span");

            return(FloatHelper.ParseToNullable(span.TextContent));
        }
コード例 #3
0
 private static ulong Pack(ref Vector2 vector)
 {
     vector = Vector2.Clamp(vector, Vector2.Zero, Vector2.One);
     return((ulong)(
                (uint)FloatHelper.PackFloatToFloat32(vector.X)
                | (((uint)Math.Round(vector.Y * 255F) & 255) << 32)));
 }
コード例 #4
0
        private bool IsConditionSatisfied(ProfileCondition condition, float?currentValue)
        {
            if (!currentValue.HasValue)
            {
                // If the value is unknown, it satisfies if not marked as required
                return(!condition.IsRequired);
            }

            float expected;

            if (FloatHelper.TryParseCultureInvariant(condition.Value, out expected))
            {
                switch (condition.Condition)
                {
                case ProfileConditionType.Equals:
                    return(currentValue.Value.Equals(expected));

                case ProfileConditionType.GreaterThanEqual:
                    return(currentValue.Value >= expected);

                case ProfileConditionType.LessThanEqual:
                    return(currentValue.Value <= expected);

                case ProfileConditionType.NotEquals:
                    return(!currentValue.Value.Equals(expected));

                default:
                    throw new InvalidOperationException("Unexpected ProfileConditionType");
                }
            }

            return(false);
        }
コード例 #5
0
        float?GetToalText(IEnumerable <IElement> allTds, int skip)
        {
            var rawTotalLessText = allTds.Skip(skip).First().TextContent;

            if (rawTotalLessText.Contains("—"))
            {
                return(null);
            }

            var startIndex = rawTotalLessText.IndexOf('(');

            if (startIndex == -1)
            {
                throw new Exception("startIndex = -1; skip = " + skip);
            }
            startIndex += 1;

            var stopIndex = rawTotalLessText.IndexOf(')');

            if (stopIndex == -1)
            {
                throw new Exception("stopIndex = -1; skip = " + skip);
            }

            var totalLessText = rawTotalLessText.Substring(startIndex, stopIndex - startIndex);

            return(FloatHelper.ParseToNullable(totalLessText));
        }
コード例 #6
0
 private static uint Pack(ref Vector2 vector)
 {
     vector = Vector2.Clamp(vector, Vector2.Zero, Vector2.One);
     return((uint)(
                (uint)FloatHelper.PackFloatToFloat16(vector.X)
                | ((uint)FloatHelper.PackFloatToFloat16(vector.Y) << 16)));
 }
コード例 #7
0
 /// <summary>Asserts that two floating point values are almost equal</summary>
 /// <param name="expected">Expected value</param>
 /// <param name="actual">Actual value</param>
 private void assertAlmostEqual(float expected, float actual)
 {
     if (!FloatHelper.AreAlmostEqual(expected, actual, 1))
     {
         Assert.AreEqual(expected, actual);
     }
 }
コード例 #8
0
 private static uint Pack(ref Vector3 vector)
 {
     vector = Vector3.Clamp(vector, Vector3.Zero, Vector3.One);
     return((uint)(
                (uint)FloatHelper.PackFloatToFloat11(vector.X)
                | ((uint)FloatHelper.PackFloatToFloat11(vector.Y) << 11)
                | ((uint)FloatHelper.PackFloatToFloat10(vector.Z) << 22)));
 }
コード例 #9
0
        /// <summary>
        /// Set new range and calculate inclusive bounds.
        /// </summary>
        /// <param name="newRange">New range value</param>
        public void SetData(Vector2 newRange)
        {
            range = ClampNewRangeValues(newRange);

            isXInclusive = range.x == 0 || FloatHelper.CheckIfProvidedFloatsAreEqual(1f, range.x);

            isYInclusive = true;
        }
コード例 #10
0
 public Vector4 ToVector4()
 {
     return(new Vector4(
                FloatHelper.UnpackFloat16ToFloat((ushort)(this.PackedValue & 65535)),
                FloatHelper.UnpackFloat16ToFloat((ushort)((this.PackedValue >> 16) & 65535)),
                FloatHelper.UnpackFloat16ToFloat((ushort)((this.PackedValue >> 32) & 65535)),
                FloatHelper.UnpackFloat16ToFloat((ushort)((this.PackedValue >> 48) & 65535))));
 }
コード例 #11
0
 public Vector4 ToVector4()
 {
     return(new Vector4(
                FloatHelper.UnpackFloat32ToFloat((uint)(this.PackedValue & 4294967295)),
                ((this.PackedValue >> 32) & 255) / 255F,
                0.0f,
                1.0f));
 }
コード例 #12
0
 public Vector4 ToVector4()
 {
     return(new Vector4(
                FloatHelper.UnpackFloat11ToFloat((ushort)(this.PackedValue & 2047)),
                FloatHelper.UnpackFloat11ToFloat((ushort)((this.PackedValue >> 11) & 2047)),
                FloatHelper.UnpackFloat10ToFloat((ushort)((this.PackedValue >> 22) & 1023)),
                1.0f));
 }
コード例 #13
0
 private static ulong Pack(ref Vector4 vector)
 {
     vector = Vector4.Clamp(vector, Vector4.Zero, Vector4.One);
     return((ulong)(
                (uint)FloatHelper.PackFloatToFloat16(vector.X)
                | ((uint)FloatHelper.PackFloatToFloat16(vector.Y) << 16)
                | ((uint)FloatHelper.PackFloatToFloat16(vector.Z) << 32)
                | ((uint)FloatHelper.PackFloatToFloat16(vector.W) << 48)));
 }
コード例 #14
0
        private Color GetColorFromValue(Data15MinClass s)
        {
            // Data repeat flag is orange
            if (s.flags.dataRepeatFlag)
            {
                return(ConfigClass.colors.colorRepeat);
            }

            // Data duplicate flag is Olive, but CornflowerBlue if zero and Orchid if null
            if (s.flags.duplicateFlag)
            {
                if (s.Values.successfullyParsed)
                {
                    // This means its valid or zero

                    if (FloatHelper.CheckIfZero(s.Values)) // If zero color it with zero color
                    {
                        return(ConfigClass.colors.colorZero);
                    }
                    return(ConfigClass.colors.colorDuplicate);; // Otherwise color it with olive
                }
                else
                {
                    // This means its null
                    return(ConfigClass.colors.colorNull);
                }
            }

            // Missing flag is OrangeRed
            if (s.flags.missingFlag)
            {
                return(ConfigClass.colors.colorMissing);
            }

            // Null flag is Orchid
            if (s.flags.nullFlag)
            {
                return(ConfigClass.colors.colorNull);
            }

            // Zero flag is CornflowerBlue
            if (s.flags.zeroFlag)
            {
                return(ConfigClass.colors.colorZero);
            }

            // invalid flag is Red
            if (s.flags.invalidFlag)
            {
                return(ConfigClass.colors.colorInvalid);
            }

            // If no flags are active that means data is just valid
            return(ConfigClass.colors.colorValid);
        }
コード例 #15
0
        /// '-----------------------------------------------------------------------------------------
        /// <summary>
        /// Get specified config app setting's value as a float number.
        /// </summary>
        /// <param name="appSetting"></param>
        /// <returns></returns>
        /// '-----------------------------------------------------------------------------------------
        public static float GetAppSettingAsFloat(string appSetting)
        {
            string setting = AppSettings[appSetting];

            if (setting == null || setting.Trim().Length == 0)
            {
                throw new ConfigurationErrorsException(String.Format(MISSING_APPSETTING_ERR_MSG, appSetting));
            }

            return(FloatHelper.ConvertToFloat(setting));
        }
コード例 #16
0
        private void LatestButton_Click(object sender, EventArgs e)
        {
            var dt = WeatherSQLite.GetLatest(Convert.ToInt32(AreaIdTextBox.Text));

            if (dt.Rows.Count > 0)
            {
                DataDateLabel.Text    = dt.Rows[0]["DataDate"].ToString();
                ConditionLabel.Text   = dt.Rows[0]["Condition"].ToString();
                TemperatureLabel.Text =
                    FloatHelper.RoundString(Convert.ToSingle(dt.Rows[0]["Temperature"]), Temperature.DecimalPoint) + Temperature.UnitName;
            }
        }
コード例 #17
0
        /// <summary>
        /// Checks is value positioned in current range.
        /// </summary>
        /// <param name="value">Value to check.</param>
        /// <returns></returns>
        public bool CheckIfValueInRange(float value)
        {
            if (isXInclusive && FloatHelper.CheckIfProvidedFloatsAreEqual(value, range.x))
            {
                return(true);
            }

            if (isYInclusive && FloatHelper.CheckIfProvidedFloatsAreEqual(value, range.y))
            {
                return(true);
            }

            return(value > range.x && value < range.y);
        }
コード例 #18
0
        /// <summary>
        /// Analyze all 15min data points and rise internal flags based on values
        /// </summary>
        public void ProcessData()
        {
            lastFw = new FloatValues(); // Initialize with devil data
            foreach (var d in data)
            {
                if (d.valid == 1)
                {
                    // Data is valid
                    if (d.numberOfPoints != 0)
                    {
                        // First check if there is some data (null values)
                        if (d.Values == null)
                        {
                            d.flags.nullFlag = true;
                            continue;
                        }

                        // Check is it zero
                        d.flags.zeroFlag = FloatHelper.CheckIfZero(d.Values);

                        if (!d.flags.zeroFlag)
                        {
                            // Check if data is repeating, ignoring zero values
                            d.flags.dataRepeatFlag = FloatHelper.CompareDuplicateValues(lastFw, d.Values); // This duplicate is based on last storred value
                            lastFw = d.Values;                                                             // make sure next 15min point compares with this value
                        }

                        // Check if null
                        if (!d.Values.successfullyParsed) // Probably redundant
                        {
                            d.flags.nullFlag = true;
                        }

                        if (d.numberOfPoints > 1) // Is it duplicate (more data points arrived for this timestamp)
                        {
                            d.flags.duplicateFlag = true;
                        }
                    }
                    else
                    { // numberOfPoints = 0
                      // Data is missing
                        d.flags.missingFlag = true;
                    }
                }
                else
                { // Data is not valid
                    d.flags.invalidFlag = true;
                }
            } // foreach
        }
コード例 #19
0
 private bool arrayContains(float[] array, float toCheck)
 {
     for (int index = 0; index < array.Length; ++index)
     {
         bool almostEqual = FloatHelper.AreAlmostEqual(
             array[index], toCheck, Specifications.MaximumDeviation
             );
         if (almostEqual)
         {
             return(true);
         }
     }
     return(false);
 }
コード例 #20
0
        /// <summary>Asserts that two vectors are equal within the accepted deviation</summary>
        /// <param name="expected">Value the vector is expected to have</param>
        /// <param name="actual">Actual value that the vector has</param>
        /// <param name="message">Message to describe the assertion</param>
        public static void AssertAreEqual(Vector3 expected, Vector3 actual, string message)
        {
            // Determine whether the values are within a reasonable range to the expected results
            bool almostEqual =
                FloatHelper.AreAlmostEqual(expected.X, actual.X, 1) &&
                FloatHelper.AreAlmostEqual(expected.Y, actual.Y, 1) &&
                FloatHelper.AreAlmostEqual(expected.Z, actual.Z, 1);

            // If the values are off, let NUnit do its (zero-tolerance) own check which we
            // already know will fail, but which saves us from writing our own NUnit assertion
            if (!almostEqual)
            {
                Assert.AreEqual(expected, actual, message);
            }
        }
コード例 #21
0
    private void Start()
    {
        _waterSurfaceObj = GameObject.FindGameObjectWithTag("WaterSurface");
        if (_waterSurfaceObj == null)
        {
            print("it's null");
        }
        _floatObjRB  = GetComponent <Rigidbody>();
        _waterHeight = _waterSurfaceObj.transform.position.y;

        _modifyBoatMesh = new ModifyBoatMesh(gameObject, _waterHeight);//

        float volume = FloatHelper.MeshVolume(GetComponent <MeshFilter>());

        _floatObjRB.mass = _objectDensity * volume;
    }
コード例 #22
0
ファイル: Disc2.Test.cs プロジェクト: minskowl/MY
        public void TestRandomPointWithin()
        {
            Disc2 testDisc = new Disc2(new Vector2(123.4f, 567.8f), 9.0f);

            DefaultRandom randomNumberGenerator = new DefaultRandom();

            for (int index = 0; index < Specifications.ProbabilisticFunctionSamples; ++index)
            {
                Vector2 randomPoint = testDisc.RandomPointWithin(randomNumberGenerator);

                float randomPointDistance = (testDisc.Center - randomPoint).Length();
                if (!FloatHelper.AreAlmostEqual(randomPointDistance, testDisc.Radius, 36))
                {
                    Assert.LessOrEqual(randomPointDistance, testDisc.Radius);
                }
            }
        }
コード例 #23
0
        /// <summary>
        /// Create and return commands for deleting duplicate items from database
        /// </summary>
        /// <returns></returns>
        private List <string> CreateDBRemoveCommands()
        {
            List <string> commands = new List <string>(); // List of database commands

            foreach (Data15MinClass d15 in dataPtr.data)
            {
                if (d15.numberOfPoints < 2)
                {
                    continue; // If point have less than 2 values ignore
                }

                var uniqueValues   = new List <FloatValues>(); // Create new list which will hold unique values
                var all15minValues = d15.GetAllValues();       // Some 15min point can have multiple values, duplicates

                // First value is always unique
                uniqueValues.Add(all15minValues[0]);

                // Generate remove command for each duplicated value, leave values that are different in float values
                for (int i = 1; i < d15.GetAllValues().Count; i++) // Skip first
                {
                    bool equalFlag = false;                        // This will be set to true if any of data point is true duplicate
                    foreach (var item2 in uniqueValues)
                    {
                        if (FloatHelper.CompareDuplicateValues(item2, all15minValues[i])) // Check if they are equal
                        {
                            equalFlag = true;
                            // Generate command for row removal from database and add it to list of commands
                            commands.Add(GenerateDatabaseRemoveCommand(all15minValues[i]));
                        }
                    }

                    if (!equalFlag)
                    {
                        // This garantiues unique value
                        uniqueValues.Add(all15minValues[i]);
                    }
                    equalFlag = false;
                }
            }

            return(commands);
        }
コード例 #24
0
        /// <summary>Ensures that two vectors are equal</summary>
        /// <param name="expected">Expected vector</param>
        /// <param name="actual">Actual vector</param>
        /// <param name="deltaUlps">Allowed deviation in representable floating point values</param>
        /// <param name="message">Message to display when the vectors are not equal</param>
        public static void AreAlmostEqual(
            Vector3 expected, Vector3 actual, int deltaUlps, string message
            )
        {
            bool almostEqual =
                FloatHelper.AreAlmostEqual(expected.X, actual.X, deltaUlps) &&
                FloatHelper.AreAlmostEqual(expected.Y, actual.Y, deltaUlps) &&
                FloatHelper.AreAlmostEqual(expected.Z, actual.Z, deltaUlps);

            if (almostEqual)
            {
                return;
            }

            // Now we already know that the two vectors are not equal even within the allowed
            // deviation (delta argument). In order to force NUnit to output a good error
            // message, we now let NUnit do the job again fully well knowing that it will
            // fail. This allows for deltas and good NUnit integration at the same time.
            Assert.AreEqual(expected, actual, message);
        }
コード例 #25
0
    public void GenerateUnderwaterMesh()
    {
        //Reset
        underWaterTriangleData.Clear();

        //Find all the distances to water once because some triangles share vertices, so reuse
        for (int j = 0; j < _floatObjVertices.Length; j++)
        {
            //The coordinate should be in global position
            Vector3 globalPos = _floatObjTrans.TransformPoint(_floatObjVertices[j]);

            //Save the global position so we only need to calculate it once here
            //And if we want to debug we can convert it back to local
            globalFloatObjVertices[j] = globalPos;

            _allDistancesToWater[j] = FloatHelper.DistanceToWater(globalPos, _waterHeight);
        }

        //Add the triangles that are below the water
        AddTriangles();
    }
コード例 #26
0
    public TriangleData(Vector3 p1, Vector3 p2, Vector3 p3, float pwaterHeight)
    {
        this.p1 = p1;
        this.p2 = p2;
        this.p3 = p3;

        //Center of the triangle
        this.center = (p1 + p2 + p3) / 3f;

        //Distance to the surface from the center of the triangle
        this.distanceToSurface = Mathf.Abs(FloatHelper.DistanceToWater(this.center, pwaterHeight));

        //Normal to the triangle
        this.normal = Vector3.Cross(p2 - p1, p3 - p1).normalized;

        //Area of the triangle
        float a = Vector3.Distance(p1, p2);

        float c = Vector3.Distance(p3, p1);

        this.area = (a * c * Mathf.Sin(Vector3.Angle(p2 - p1, p3 - p1) * Mathf.Deg2Rad)) / 2f;
    }
コード例 #27
0
        float?GetForaText(IEnumerable <IElement> allTds, int skip)
        {
            var foraRawText = allTds.Skip(skip).First().TextContent;

            if (foraRawText.Contains("—")) //т.е. ставки нет
            {
                return(null);
            }

            var startIndex = foraRawText.IndexOf('(');

            if (startIndex == -1)
            {
                //log
                throw new Exception("startIndex = -1; skip = " + skip);
            }
            startIndex += 1;
            var endIndex = foraRawText.IndexOf(')');
            //не отображает минус в дебаге
            var foraText = foraRawText.Substring(startIndex, endIndex - startIndex);

            return(FloatHelper.ParseToNullable(foraText));
        }
コード例 #28
0
ファイル: StreamBuilder.cs プロジェクト: egandt/Emby
        private void ApplyTranscodingConditions(StreamInfo item, IEnumerable <ProfileCondition> conditions)
        {
            foreach (ProfileCondition condition in conditions)
            {
                string value = condition.Value;

                if (string.IsNullOrEmpty(value))
                {
                    continue;
                }

                // No way to express this
                if (condition.Condition == ProfileConditionType.GreaterThanEqual)
                {
                    continue;
                }

                switch (condition.Property)
                {
                case ProfileConditionValue.AudioBitrate:
                {
                    int num;
                    if (IntHelper.TryParseCultureInvariant(value, out num))
                    {
                        item.AudioBitrate = num;
                    }
                    break;
                }

                case ProfileConditionValue.AudioChannels:
                {
                    int num;
                    if (IntHelper.TryParseCultureInvariant(value, out num))
                    {
                        item.MaxAudioChannels = num;
                    }
                    break;
                }

                case ProfileConditionValue.IsAnamorphic:
                case ProfileConditionValue.AudioProfile:
                case ProfileConditionValue.Has64BitOffsets:
                case ProfileConditionValue.PacketLength:
                case ProfileConditionValue.NumAudioStreams:
                case ProfileConditionValue.NumVideoStreams:
                case ProfileConditionValue.IsSecondaryAudio:
                case ProfileConditionValue.VideoTimestamp:
                {
                    // Not supported yet
                    break;
                }

                case ProfileConditionValue.RefFrames:
                {
                    int num;
                    if (IntHelper.TryParseCultureInvariant(value, out num))
                    {
                        item.MaxRefFrames = num;
                    }
                    break;
                }

                case ProfileConditionValue.VideoBitDepth:
                {
                    int num;
                    if (IntHelper.TryParseCultureInvariant(value, out num))
                    {
                        item.MaxVideoBitDepth = num;
                    }
                    break;
                }

                case ProfileConditionValue.VideoProfile:
                {
                    item.VideoProfile = (value ?? string.Empty).Split('|')[0];
                    break;
                }

                case ProfileConditionValue.Height:
                {
                    int num;
                    if (IntHelper.TryParseCultureInvariant(value, out num))
                    {
                        item.MaxHeight = num;
                    }
                    break;
                }

                case ProfileConditionValue.VideoBitrate:
                {
                    int num;
                    if (IntHelper.TryParseCultureInvariant(value, out num))
                    {
                        item.VideoBitrate = num;
                    }
                    break;
                }

                case ProfileConditionValue.VideoFramerate:
                {
                    float num;
                    if (FloatHelper.TryParseCultureInvariant(value, out num))
                    {
                        item.MaxFramerate = num;
                    }
                    break;
                }

                case ProfileConditionValue.VideoLevel:
                {
                    int num;
                    if (IntHelper.TryParseCultureInvariant(value, out num))
                    {
                        item.VideoLevel = num;
                    }
                    break;
                }

                case ProfileConditionValue.Width:
                {
                    int num;
                    if (IntHelper.TryParseCultureInvariant(value, out num))
                    {
                        item.MaxWidth = num;
                    }
                    break;
                }
                }
            }
        }
コード例 #29
0
        public void AddTileVertices(Point2 position, Rectangle?sourceRectangle = null, TiledMapTileFlipFlags flags = TiledMapTileFlipFlags.None)
        {
            float texelLeft, texelTop, texelRight, texelBottom;
            var   sourceRectangle1 = sourceRectangle ?? new Rectangle(0, 0, (int)ImageSize.Width, (int)ImageSize.Height);

            if (sourceRectangle.HasValue)
            {
                var reciprocalWidth  = 1f / ImageSize.Width;
                var reciprocalHeight = 1f / ImageSize.Height;
                texelLeft   = (sourceRectangle1.X + 0.5f) * reciprocalWidth;
                texelTop    = (sourceRectangle1.Y + 0.5f) * reciprocalHeight;
                texelRight  = (sourceRectangle1.X + sourceRectangle1.Width) * reciprocalWidth;
                texelBottom = (sourceRectangle1.Y + sourceRectangle1.Height) * reciprocalHeight;
            }
            else
            {
                texelLeft   = 0;
                texelTop    = 0;
                texelBottom = 1;
                texelRight  = 1;
            }

            VertexPositionTexture vertexTopLeft, vertexTopRight, vertexBottomLeft, vertexBottomRight;

            vertexTopLeft.Position     = new Vector3(position, 0);
            vertexTopRight.Position    = new Vector3(position + new Vector2(sourceRectangle1.Width, 0), 0);
            vertexBottomLeft.Position  = new Vector3(position + new Vector2(0, sourceRectangle1.Height), 0);
            vertexBottomRight.Position =
                new Vector3(position + new Vector2(sourceRectangle1.Width, sourceRectangle1.Height), 0);

            vertexTopLeft.TextureCoordinate.Y = texelTop;
            vertexTopLeft.TextureCoordinate.X = texelLeft;

            vertexTopRight.TextureCoordinate.Y = texelTop;
            vertexTopRight.TextureCoordinate.X = texelRight;

            vertexBottomLeft.TextureCoordinate.Y = texelBottom;
            vertexBottomLeft.TextureCoordinate.X = texelLeft;

            vertexBottomRight.TextureCoordinate.Y = texelBottom;
            vertexBottomRight.TextureCoordinate.X = texelRight;

            var flipDiagonally   = (flags & TiledMapTileFlipFlags.FlipDiagonally) != 0;
            var flipHorizontally = (flags & TiledMapTileFlipFlags.FlipHorizontally) != 0;
            var flipVertically   = (flags & TiledMapTileFlipFlags.FlipVertically) != 0;

            if (flipDiagonally)
            {
                FloatHelper.Swap(ref vertexTopRight.TextureCoordinate.X, ref vertexBottomLeft.TextureCoordinate.X);
                FloatHelper.Swap(ref vertexTopRight.TextureCoordinate.Y, ref vertexBottomLeft.TextureCoordinate.Y);
            }

            if (flipHorizontally)
            {
                if (flipDiagonally)
                {
                    FloatHelper.Swap(ref vertexTopLeft.TextureCoordinate.Y, ref vertexTopRight.TextureCoordinate.Y);
                    FloatHelper.Swap(ref vertexBottomLeft.TextureCoordinate.Y, ref vertexBottomRight.TextureCoordinate.Y);
                }
                else
                {
                    FloatHelper.Swap(ref vertexTopLeft.TextureCoordinate.X, ref vertexTopRight.TextureCoordinate.X);
                    FloatHelper.Swap(ref vertexBottomLeft.TextureCoordinate.X, ref vertexBottomRight.TextureCoordinate.X);
                }
            }

            if (flipVertically)
            {
                if (flipDiagonally)
                {
                    FloatHelper.Swap(ref vertexTopLeft.TextureCoordinate.X, ref vertexBottomLeft.TextureCoordinate.X);
                    FloatHelper.Swap(ref vertexTopRight.TextureCoordinate.X, ref vertexBottomRight.TextureCoordinate.X);
                }
                else
                {
                    FloatHelper.Swap(ref vertexTopLeft.TextureCoordinate.Y, ref vertexBottomLeft.TextureCoordinate.Y);
                    FloatHelper.Swap(ref vertexTopRight.TextureCoordinate.Y, ref vertexBottomRight.TextureCoordinate.Y);
                }
            }

            _vertices.Add(vertexTopLeft);
            _vertices.Add(vertexTopRight);
            _vertices.Add(vertexBottomLeft);
            _vertices.Add(vertexBottomRight);

            Debug.Assert(Vertices.Count <= TiledMapHelper.MaximumVerticesPerModel);
        }
コード例 #30
0
        private static IEnumerable <VertexPositionTexture> CreateVertices(Texture2D texture, Vector2 position, Rectangle sourceRectangle, TiledMapTileFlipFlags flags = TiledMapTileFlipFlags.None)
        {
            var reciprocalWidth  = 1f / texture.Width;
            var reciprocalHeight = 1f / texture.Height;
            var texelLeft        = (sourceRectangle.X + 0.5f) * reciprocalWidth;
            var texelTop         = (sourceRectangle.Y + 0.5f) * reciprocalHeight;
            var texelRight       = (sourceRectangle.X + sourceRectangle.Width) * reciprocalWidth;
            var texelBottom      = (sourceRectangle.Y + sourceRectangle.Height) * reciprocalHeight;

            VertexPositionTexture vertexTopLeft, vertexTopRight, vertexBottomLeft, vertexBottomRight;

            vertexTopLeft.Position     = new Vector3(position, 0);
            vertexTopRight.Position    = new Vector3(position + new Vector2(sourceRectangle.Width, 0), 0);
            vertexBottomLeft.Position  = new Vector3(position + new Vector2(0, sourceRectangle.Height), 0);
            vertexBottomRight.Position = new Vector3(position + new Vector2(sourceRectangle.Width, sourceRectangle.Height), 0);

            vertexTopLeft.TextureCoordinate.Y = texelTop;
            vertexTopLeft.TextureCoordinate.X = texelLeft;

            vertexTopRight.TextureCoordinate.Y = texelTop;
            vertexTopRight.TextureCoordinate.X = texelRight;

            vertexBottomLeft.TextureCoordinate.Y = texelBottom;
            vertexBottomLeft.TextureCoordinate.X = texelLeft;

            vertexBottomRight.TextureCoordinate.Y = texelBottom;
            vertexBottomRight.TextureCoordinate.X = texelRight;

            var flipDiagonally   = (flags & TiledMapTileFlipFlags.FlipDiagonally) != 0;
            var flipHorizontally = (flags & TiledMapTileFlipFlags.FlipHorizontally) != 0;
            var flipVertically   = (flags & TiledMapTileFlipFlags.FlipVertically) != 0;

            if (flipDiagonally)
            {
                FloatHelper.Swap(ref vertexTopRight.TextureCoordinate.X, ref vertexBottomLeft.TextureCoordinate.X);
                FloatHelper.Swap(ref vertexTopRight.TextureCoordinate.Y, ref vertexBottomLeft.TextureCoordinate.Y);
            }

            if (flipHorizontally)
            {
                if (flipDiagonally)
                {
                    FloatHelper.Swap(ref vertexTopLeft.TextureCoordinate.Y, ref vertexTopRight.TextureCoordinate.Y);
                    FloatHelper.Swap(ref vertexBottomLeft.TextureCoordinate.Y, ref vertexBottomRight.TextureCoordinate.Y);
                }
                else
                {
                    FloatHelper.Swap(ref vertexTopLeft.TextureCoordinate.X, ref vertexTopRight.TextureCoordinate.X);
                    FloatHelper.Swap(ref vertexBottomLeft.TextureCoordinate.X, ref vertexBottomRight.TextureCoordinate.X);
                }
            }

            if (flipVertically)
            {
                if (flipDiagonally)
                {
                    FloatHelper.Swap(ref vertexTopLeft.TextureCoordinate.X, ref vertexBottomLeft.TextureCoordinate.X);
                    FloatHelper.Swap(ref vertexTopRight.TextureCoordinate.X, ref vertexBottomRight.TextureCoordinate.X);
                }
                else
                {
                    FloatHelper.Swap(ref vertexTopLeft.TextureCoordinate.Y, ref vertexBottomLeft.TextureCoordinate.Y);
                    FloatHelper.Swap(ref vertexTopRight.TextureCoordinate.Y, ref vertexBottomRight.TextureCoordinate.Y);
                }
            }

            yield return(vertexTopLeft);

            yield return(vertexTopRight);

            yield return(vertexBottomLeft);

            yield return(vertexBottomRight);
        }