public void DrawGlyphRun(float baselineOriginX, float baselineOriginY, Graphics.Direct2D.MeasuringMode measuringMode, GlyphRun glyphRun, GlyphRunDescription glyphRunDescription, ClientDrawingEffect clientDrawingEffect)
        {
            using (PathGeometry pathGeometry = _factory.CreatePathGeometry())
            {

                using (GeometrySink sink = pathGeometry.Open())
                {
                    glyphRun.FontFace.GetGlyphRunOutline(
                        glyphRun.EmSize,
                        glyphRun.GlyphIndices,
                        glyphRun.GlyphAdvances,
                        glyphRun.GlyphOffsets,
                        glyphRun.IsSideways,
                        glyphRun.BidiLevel != 0,
                        sink);
                    sink.Close();
                }

                CustomGeometrySink customSink = new CustomGeometrySink();
                pathGeometry.Stream(customSink);
                customSink.Close();
                System.Diagnostics.Debug.WriteLine(customSink.ToString());

                Matrix3x2 matrix = new Matrix3x2(1, 0, 0, 1, baselineOriginX, baselineOriginY);
                using (TransformedGeometry transformedGeometry = _factory.CreateTransformedGeometry(pathGeometry, matrix))
                {
                    _renderTarget.DrawGeometry(_outlineBrush, 5, transformedGeometry);
                    _renderTarget.FillGeometry(_fillBrush, transformedGeometry);
                }
            }
        }
Esempio n. 2
0
        public void ConstructorValuesAreAccessibleByIndexer()
        {
            Matrix3x2 matrix3x2;

            matrix3x2 = new Matrix3x2();

            for (int x = 0; x < matrix3x2.Columns; x++)
            {
                for (int y = 0; y < matrix3x2.Rows; y++)
                {
                    Assert.Equal(0, matrix3x2[x, y], Epsilon);
                }
            }

            double value = 33.33;
            matrix3x2 = new Matrix3x2(value);

            for (int x = 0; x < matrix3x2.Columns; x++)
            {
                for (int y = 0; y < matrix3x2.Rows; y++)
                {
                    Assert.Equal(value, matrix3x2[x, y], Epsilon);
                }
            }

            GenerateFilledMatrixWithValues(out matrix3x2);

            for (int y = 0; y < matrix3x2.Rows; y++)
            {
                for (int x = 0; x < matrix3x2.Columns; x++)
                {
                    Assert.Equal(y * matrix3x2.Columns + x, matrix3x2[x, y], Epsilon);
                }
            }
        }
Esempio n. 3
0
 public static bool Equal(Matrix3x2 a, Matrix3x2 b)
 {
     return
         Equal(a.M11, b.M11) && Equal(a.M12, b.M12) &&
         Equal(a.M21, b.M21) && Equal(a.M22, b.M22) &&
         Equal(a.M31, b.M31) && Equal(a.M32, b.M32);
 }
Esempio n. 4
0
        public void Matrix3x2IdentityTest()
        {
            Matrix3x2 val = new Matrix3x2();
            val.M11 = val.M22 = 1.0f;

            Assert.True(MathHelper.Equal(val, Matrix3x2.Identity), "Matrix3x2.Indentity was not set correctly.");
        }
Esempio n. 5
0
        private static MaskF Transform(MaskF mask, Matrix3x2 transformation)
        {
            var original = mask.UnderlayingArray;
            var transformedPoints = new Vector2[original.Length];

            // Initializing the transformed bounds
            double sumX = 0;
            double sumY = 0;
            var first = Vector2.Transform(original[0], transformation);
            float left = first.X;
            float top = first.Y;
            float right = first.X;
            float bottom = first.Y;

            // Calculating the transformed coordinates
            for (int i = 0; i < original.Length; i++)
            {
                var pt = Vector2.Transform(original[i], transformation);
                sumX += pt.X;
                sumY += pt.Y;
                UpdateBoundaries(pt, ref left, ref top, ref right, ref bottom);
                transformedPoints[i] = pt;
            }

            Vector2 transformedCenter = new Vector2((float)(sumX / original.Length),
                                                  (float)(sumY / original.Length));
            MaskF transformedMask = FromArrayAndProperties(transformedPoints, transformedCenter, left, top, right, bottom);
            return transformedMask;
        }
Esempio n. 6
0
 static Matrix3x2 GenerateMatrixNumberFrom1To6()
 {
     Matrix3x2 a = new Matrix3x2();
     a.M11 = 1.0f; a.M12 = 2.0f;
     a.M21 = 3.0f; a.M22 = 4.0f;
     a.M31 = 5.0f; a.M32 = 6.0f;
     return a;
 }
Esempio n. 7
0
		private TransformSession(CanvasDrawingSession session, Matrix3x2 oldTransform, SvgMatrix multiply)
		{
			this.Session = session;
			this.OldTransform = oldTransform;

			var transform = new Matrix3x2((float)multiply.A, (float)multiply.B, (float)multiply.C, (float)multiply.D, (float)multiply.E, (float)multiply.F);
			session.Transform = transform * session.Transform;
		}
Esempio n. 8
0
        public void ConstantValuesAreCorrect()
        {
            Matrix3x2 matrix3x2 = new Matrix3x2();

            Assert.Equal(3, matrix3x2.Columns);
            Assert.Equal(2, matrix3x2.Rows);
            Assert.Equal(Matrix3x2.ColumnCount, matrix3x2.Columns);
            Assert.Equal(Matrix3x2.RowCount, matrix3x2.Rows);
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="RadialGradientStyle" /> class.
 /// </summary>
 /// <param name="unitOriginOffset">The unit origin offset.</param>
 /// <param name="transform">The transform.</param>
 /// <param name="gradientStops">The gradient stops.</param>
 public RadialGradientStyle(
     Vector2 unitOriginOffset,
     Matrix3x2 transform,
     [NotNull] IReadOnlyList<GradientStop> gradientStops)
     : base(gradientStops)
 {
     UnitOriginOffset = unitOriginOffset;
     GradientTransform = transform;
 }
Esempio n. 10
0
        public void MatrixVectorMultiplication()
        {
            var v = new Vector3(2, 2, 1);
            var m = new Matrix3x2(1, 0, 0, 1, 5, 6);

            var r = Matrix3x2.Multiply(ref m, v);

            Assert.AreEqual(r.X, 7);
            Assert.AreEqual(r.Y, 8);
        }
        /// <summary>
        ///     Returns a copy of this style with the given transform applied.
        /// </summary>
        /// <param name="matrix">The transform matrix.</param>
        /// <returns>
        ///     The transformed style.
        /// </returns>
        public override IStyle Transform(Matrix3x2 matrix)
        {
            if (matrix == Matrix3x2.Identity) return this;

            Vector2 start = Vector2.Transform(Start, matrix);
            Vector2 end = Vector2.Transform(End, matrix);

            if (start == Start && end == End) return this;
            return new LinearGradientStyle(start, end, GradientStops);
        }
Esempio n. 12
0
        /// <summary>
        /// Writes a value to the output stream.
        /// </summary>
        /// <param name="writer">The binary writer.</param>
        /// <param name="value">The value to write.</param>
        public static void Write(this BinaryWriter writer, Matrix3x2 value)
        {
            writer.Write(value.M11);
            writer.Write(value.M21);
            writer.Write(value.M31);

            writer.Write(value.M12);
            writer.Write(value.M22);
            writer.Write(value.M32);
        }
Esempio n. 13
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="Tile" /> class.
 /// </summary>
 /// <param name="label">The label.</param>
 /// <param name="shape">The shape.</param>
 /// <param name="transform">The transform.</param>
 /// <param name="partShapes">The part shapes.</param>
 /// <exception cref="System.ArgumentNullException"></exception>
 public Tile(
     [NotNull] string label,
     [NotNull] Shape shape,
     Matrix3x2 transform,
     [NotNull] IReadOnlyList<EdgePartShape> partShapes)
     : base(label, shape, transform)
 {
     if (partShapes == null) throw new ArgumentNullException(nameof(partShapes));
     PartShapes = partShapes;
 }
Esempio n. 14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LayerParameters1"/> struct.
 /// </summary>
 /// <param name="contentBounds">The content bounds.</param>
 /// <param name="geometryMask">The geometry mask.</param>
 /// <param name="maskAntialiasMode">The mask antialias mode.</param>
 /// <param name="maskTransform">The mask transform.</param>
 /// <param name="opacity">The opacity.</param>
 /// <param name="opacityBrush">The opacity brush.</param>
 /// <param name="layerOptions">The layer options.</param>
 public LayerParameters1(RectangleF contentBounds, Geometry geometryMask, AntialiasMode maskAntialiasMode, Matrix3x2 maskTransform, float opacity, Brush opacityBrush, LayerOptions1 layerOptions)
     : this()
 {
     ContentBounds = contentBounds;
     geometricMask_ = geometryMask.NativePointer;
     MaskAntialiasMode = maskAntialiasMode;
     MaskTransform = maskTransform;
     Opacity = opacity;
     opacityBrush_ = opacityBrush.NativePointer;
     LayerOptions = layerOptions;
 }
Esempio n. 15
0
        /// <summary>
        ///     Returns a copy of this style with the given transform applied.
        /// </summary>
        /// <param name="matrix">The transform matrix.</param>
        /// <returns>
        ///     The transformed style.
        /// </returns>
        public IStyle Transform(Matrix3x2 matrix)
        {
            if (matrix.IsIdentity) return this;
            Vector2 pos = Vector2.Transform(Position, matrix);

            // ReSharper disable CompareOfFloatsByEqualityOperator
            if (Math.Round(pos.X, 3) == Math.Round(Position.X, 3) &&
                Math.Round(pos.X, 3) == Math.Round(Position.X, 3))
                // ReSharper restore CompareOfFloatsByEqualityOperator
                return this;

            return new RandomColourStyle(From, To, pos);
        }
Esempio n. 16
0
        /// <summary>
        /// Get the transform matrix for the given Transform
        /// </summary>
        internal override Matrix3x2 GetTransform()
        {
            m_cachedTransform = Matrix3x2.Identity;

            /* Loop over all of our child transforms */
            for (int i = 0; i < m_transformChildren.Count; i++)
            {
                var transform = m_transformChildren[i].GetTransform();
                /* Multiple the transforms together */
                m_cachedTransform *= transform;
            }

            return m_cachedTransform;
        }
Esempio n. 17
0
        /// <summary>
        /// Get the transform matrix for the given Transform
        /// </summary>
        internal override Matrix3x2 GetTransform()
        {
            /* Avoid re-creating the transform if nothing has change
             * to help optimize for high perf scenarios */
            if (!m_isDirty)
                return m_cachedTransform;

            /* Create the translation */
            m_cachedTransform = Matrix3x2.Translation(X, Y);

            m_isDirty = false;

            return m_cachedTransform;
        }
Esempio n. 18
0
        /// <summary>
        /// Get the transform matrix for the given Transform
        /// </summary>
        internal override Matrix3x2 GetTransform()
        {
            /* Avoid re-creating the transform if nothing has change
             * to help optimize for high perf scenarios */
            if (!m_isDirty)
                return m_cachedTransform;

            /* Create the rotation */
            m_cachedTransform = Matrix3x2.Rotation(Angle, new PointF(CenterX, CenterY));
            
            /* Flag that we are not dirty */
            m_isDirty = false;

            return m_cachedTransform;
        }
Esempio n. 19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TextRenderUnit" /> class.
        /// </summary>
        /// <param name="textLayout">The text layout.</param>
        /// <param name="brush">The brush.</param>
        /// <param name="transform">The text transform.</param>
        public TextRenderUnit(TextLayout textLayout, Brush brush, Matrix3x2 transform)
        {
            this.layout = textLayout;
            this.brush = brush;
            this.transform = transform;

            var topleft = Matrix3x2.TransformPoint(transform, new Vector2(0, 0));
            var bottomRight = Matrix3x2.TransformPoint(transform, new Vector2(textLayout.Metrics.Width, textLayout.Metrics.Height));

            this.bounds = new RectangleF
            {
                Top = topleft.Y,
                Left = topleft.X,
                Right = bottomRight.X,
                Bottom = bottomRight.Y
            };
        }
Esempio n. 20
0
        /// <summary>
        ///     Creates a new <see cref="EdgePartPosition" /> from an edge part, shape and transform.
        /// </summary>
        /// <param name="edgePart">The edge part.</param>
        /// <param name="shape">The shape.</param>
        /// <param name="transform">The transform.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">
        ///     <paramref name="edgePart" /> or <paramref name="shape" /> was <see langword="null" />.
        /// </exception>
        public static EdgePartPosition Create([NotNull] EdgePart edgePart, [NotNull] Shape shape, Matrix3x2 transform)
        {
            if (edgePart == null) throw new ArgumentNullException(nameof(edgePart));
            if (shape == null) throw new ArgumentNullException(nameof(shape));

            Edge edge = shape.GetEdge(edgePart.EdgePattern.EdgeName);

            Vector2 startPoint = edge.GetPointOnEdge(edgePart.StartAmount);
            Vector2 endPoint = edge.GetPointOnEdge(edgePart.StartAmount + edgePart.Amount);

            if (!transform.IsIdentity)
            {
                startPoint = Vector2.Transform(startPoint, transform);
                endPoint = Vector2.Transform(endPoint, transform);
            }

            return new EdgePartPosition(edgePart, startPoint, endPoint);
        }
Esempio n. 21
0
        public GeometryOperations()
        {
            this.InitializeComponent();

            LeftGeometryType = GeometryType.Rectangle;
            RightGeometryType = GeometryType.Star;
            WhichCombineType = CanvasGeometryCombine.Union;

            interGeometryTransform = Matrix3x2.CreateTranslation(200, 100);

            CurrentContourTracingAnimation = ContourTracingAnimationOption.None;

            showSourceGeometry = false;
            showTessellation = false;
            enableTransform = false;

            needsToRecreateResources = true;
        }
Esempio n. 22
0
        public void IndexerGetAndSetValuesCorrectly()
        {
            Matrix3x2 matrix3x2 = new Matrix3x2();

            for (int x = 0; x < matrix3x2.Columns; x++)
            {
                for (int y = 0; y < matrix3x2.Rows; y++)
                {
                    matrix3x2[x, y] = y * matrix3x2.Columns + x;
                }
            }

            for (int y = 0; y < matrix3x2.Rows; y++)
            {
                for (int x = 0; x < matrix3x2.Columns; x++)
                {
                    Assert.Equal(y * matrix3x2.Columns + x, matrix3x2[x, y], Epsilon);
                }
            }
        }
Esempio n. 23
0
        public void Matrix3x2DeterminantTest1()
        {
            Matrix3x2 a = new Matrix3x2();
            a.M11 = 5.0f; a.M12 = 2.0f;
            a.M21 = 12.0f; a.M22 = 6.8f;
            a.M31 = 6.5f; a.M32 = 1.0f;
            Matrix3x2 i;
            Assert.IsTrue(Matrix3x2.Invert(a, out i));

            float detA = a.GetDeterminant();
            float detI = i.GetDeterminant();
            float t = 1.0f / detI;

            // only accurate to 3 precision
            Assert.IsTrue(System.Math.Abs(detA - t) < 1e-3, "Matrix3x2.GetDeterminant was not set correctly.");

            // sanity check against 4x4 version
            Assert.AreEqual(new Matrix4x4(a).GetDeterminant(), detA);
            Assert.AreEqual(new Matrix4x4(i).GetDeterminant(), detI);
        }
Esempio n. 24
0
        /// <summary>
        /// Adds the two matrices together on a per-element basis.
        /// </summary>
        /// <param name="a">First matrix to add.</param>
        /// <param name="b">Second matrix to add.</param>
        /// <param name="result">Sum of the two matrices.</param>
        public static void Add(ref Matrix3x2 a, ref Matrix3x2 b, out Matrix3x2 result)
        {
            float m11 = a.M11 + b.M11;
            float m12 = a.M12 + b.M12;

            float m21 = a.M21 + b.M21;
            float m22 = a.M22 + b.M22;

            float m31 = a.M31 + b.M31;
            float m32 = a.M32 + b.M32;

            result.M11 = m11;
            result.M12 = m12;

            result.M21 = m21;
            result.M22 = m22;

            result.M31 = m31;
            result.M32 = m32;
        }
Esempio n. 25
0
        public void Matrix3x2InvertTest()
        {
            Matrix3x2 mtx = Matrix3x2.CreateRotation(MathHelper.ToRadians(30.0f));

            Matrix3x2 expected = new Matrix3x2();
            expected.M11 = 0.8660254f;
            expected.M12 = -0.5f;

            expected.M21 = 0.5f;
            expected.M22 = 0.8660254f;

            expected.M31 = 0;
            expected.M32 = 0;

            Matrix3x2 actual;

            Assert.True(Matrix3x2.Invert(mtx, out actual));
            Assert.True(MathHelper.Equal(expected, actual), "Matrix3x2.Invert did not return the expected value.");

            Matrix3x2 i = mtx * actual;
            Assert.True(MathHelper.Equal(i, Matrix3x2.Identity), "Matrix3x2.Invert did not return the expected value.");
        }
Esempio n. 26
0
        public void AccessorThrowsWhenOutOfBounds()
        {
            Matrix3x2 matrix3x2 = new Matrix3x2();

            try
            {
                matrix3x2[-1, 0] = 0;
                Assert.Fail("Matrix3x2[-1, 0] did not throw when it should have.");
            }
            catch (ArgumentOutOfRangeException)
            { }

            try
            {
                matrix3x2[0, -1] = 0;
                Assert.Fail("Matrix3x2[0, -1] did not throw when it should have.");
            }
            catch (ArgumentOutOfRangeException)
            { }

            try
            {
                matrix3x2[3, 0] = 0;
                Assert.Fail("Matrix3x2[3, 0] did not throw when it should have.");
            }
            catch (ArgumentOutOfRangeException)
            { }

            try
            {
                matrix3x2[0, 2] = 0;
                Assert.Fail("Matrix3x2[0, 2] did not throw when it should have.");
            }
            catch (ArgumentOutOfRangeException)
            { }
        }
Esempio n. 27
0
 public CanvasGeometry CombineWith(CanvasGeometry other, Matrix3x2 matrix, CanvasGeometryCombine combineMode)
 => new Combination(this, other)
 {
     Matrix      = matrix,
     CombineMode = combineMode,
 };
Esempio n. 28
0
        protected override void OnUpdateTextureAndBillboardVertices(IDeviceResources deviceResources)
        {
            Width  = 0;
            Height = 0;
            // http://www.cyotek.com/blog/angelcode-bitmap-font-parsing-using-csharp
            var tempList = new List <BillboardVertex>(100);

            foreach (var textInfo in TextInfo)
            {
                int  tempPrevCount = tempList.Count;
                int  x             = 0;
                int  y             = 0;
                var  w             = BitmapFont.TextureSize.Width;
                var  h             = BitmapFont.TextureSize.Height;
                char previousCharacter;

                previousCharacter = ' ';
                var normalizedText = textInfo.Text;
                var rect           = new RectangleF(textInfo.Origin.X, textInfo.Origin.Y, 0, 0);
                foreach (char character in normalizedText)
                {
                    switch (character)
                    {
                    case '\n':
                        x  = 0;
                        y -= BitmapFont.LineHeight;
                        break;

                    default:
                        Character data    = BitmapFont[character];
                        int       kerning = BitmapFont.GetKerning(previousCharacter, character);
                        tempList.Add(DrawCharacter(data, new Vector3(x + data.Offset.X, y - data.Offset.Y, 0), w, h, kerning, textInfo));

                        x += data.XAdvance + kerning;
                        break;
                    }
                    previousCharacter = character;
                    if (tempList.Count > 0)
                    {
                        rect.Width  = Math.Max(rect.Width, x * textInfo.Scale * textureScale);
                        rect.Height = Math.Max(rect.Height, Math.Abs(tempList.Last().OffBR.Y));
                    }
                }
                var transform = textInfo.Angle != 0 ? Matrix3x2.Rotation(textInfo.Angle) : Matrix3x2.Identity;
                var halfW     = rect.Width / 2;
                var halfH     = rect.Height / 2;
                //Add backbround vertex first. This also used for hit test
                BillboardVertices.Add(new BillboardVertex()
                {
                    Position   = textInfo.Origin.ToVector4(),
                    Background = textInfo.Background,
                    TexTL      = Vector2.Zero,
                    TexBR      = Vector2.Zero,
                    OffTL      = Matrix3x2.TransformPoint(transform, new Vector2(-halfW, halfH)),
                    OffBR      = Matrix3x2.TransformPoint(transform, new Vector2(halfW, -halfH)),
                    OffTR      = Matrix3x2.TransformPoint(transform, new Vector2(-halfW, -halfH)),
                    OffBL      = Matrix3x2.TransformPoint(transform, new Vector2(halfW, halfH)),
                });

                textInfo.UpdateTextInfo(rect.Width, rect.Height);

                for (int k = tempPrevCount; k < tempList.Count; ++k)
                {
                    var v = tempList[k];
                    v.OffTL     = Matrix3x2.TransformPoint(transform, v.OffTL + new Vector2(-halfW, halfH));
                    v.OffBR     = Matrix3x2.TransformPoint(transform, v.OffBR + new Vector2(-halfW, halfH));
                    v.OffTR     = Matrix3x2.TransformPoint(transform, v.OffTR + new Vector2(-halfW, halfH));
                    v.OffBL     = Matrix3x2.TransformPoint(transform, v.OffBL + new Vector2(-halfW, halfH));
                    tempList[k] = v;
                }
                Width  += rect.Width;
                Height += rect.Height;
            }

            foreach (var v in tempList)
            {
                BillboardVertices.Add(v);
            }
        }
Esempio n. 29
0
 private void DrawImage(int X, int Y, int W, int H, Bitmap bitmap, float angle)
 {
     device.Transform = Matrix3x2.Rotation(angle, new Vector2(X + (H / 2), Y + (H / 2)));
     device.DrawBitmap(bitmap, new RectangleF(X, Y, W, H), 1.0f, BitmapInterpolationMode.Linear);
     device.Transform = Matrix3x2.Rotation(0);
 }
Esempio n. 30
0
        // 進行と描画


        /// <param name="全体の中央位置">
        ///		パネル(dc)の左上を原点とする座標。
        /// </param>
        public void 進行描画する(DeviceContext dc, Vector2 全体の中央位置, 成績 現在の成績)
        {
            int Combo値 = Math.Clamp(現在の成績.Combo, min: 0, max: 9999);    // 表示は9999でカンスト。

            if (Combo値 < 10)
            {
                return; // 10未満は表示しない。
            }
            if ((this._前回表示した値 % 100) > (Combo値 % 100))
            {
                // 100を超えるたびアニメ開始。
                this._百ごとのアニメ.開始(Global.Animation);
            }


            var 数字 = Combo値.ToString().PadLeft(4).Replace(' ', 'o');     // 右詰め4桁、余白は 'o'。
            var 画像矩形から表示矩形への拡大率 = new Vector2(264f / (142f * 4f), 140f / 188f);
            var 文字間隔補正          = -10f;
            var 全体の拡大率          = new Vector2((float)(this._百ごとのアニメ.拡大率?.Value ?? 1.0));

            // 全体のサイズを算出。
            var 全体のサイズ = new Vector2(0f, 0f);

            for (int i = 0; i < 数字.Length; i++)
            {
                var 矩形 = this._コンボ文字の矩形リスト[数字[i].ToString()] !;
                全体のサイズ.X += 矩形.Value.Width + 文字間隔補正;                // 合計
                全体のサイズ.Y  = Math.Max(全体のサイズ.Y, 矩形.Value.Height);    // 最大値
            }
            全体のサイズ *= 画像矩形から表示矩形への拡大率;

            // 全体の位置を修正。
            全体の中央位置.Y -= 全体のサイズ.Y / 2f;
            var 振動幅 = (float)(this._百ごとのアニメ.振動幅?.Value ?? 0.0f);

            if (0.0f < 振動幅)
            {
                全体の中央位置.X += Global.App.乱数.NextFloat(-振動幅, +振動幅);
                全体の中央位置.Y += Global.App.乱数.NextFloat(-振動幅, +振動幅);
            }


            // 1桁ずつ描画。

            var preTrans = dc.Transform;

            #region " 数字を描画。"
            //----------------
            {
                var 文字の位置 = new Vector2(-(全体のサイズ.X / 2f), 0f);

                for (int i = 0; i < 数字.Length; i++)
                {
                    if (数字[i] != this._前回表示した数字[i])
                    {
                        // 桁アニメーション開始
                        this._各桁のアニメ[i].落下開始(Global.Animation);

                        // 1の位以外は、自分より上位の桁を順番に跳ねさせる。
                        if (3 > i)
                        {
                            for (int p = (i - 1); p >= 0; p--)
                            {
                                this._各桁のアニメ[p].跳ね開始(Global.Animation, 0.05 * ((i - 1) - p + 1));
                            }
                        }
                    }

                    var 転送元矩形 = (this._コンボ文字の矩形リスト[数字[i].ToString()]) !;

                    dc.Transform =
                        Matrix3x2.Scaling(画像矩形から表示矩形への拡大率) *
                        Matrix3x2.Translation(文字の位置.X, 文字の位置.Y + (float)(this._各桁のアニメ[i].Yオフセット?.Value ?? 0.0f)) *
                        Matrix3x2.Scaling(全体の拡大率.X, 全体の拡大率.Y, center: new Vector2(0f, 全体のサイズ.Y / 2f)) *
                        Matrix3x2.Translation(全体の中央位置) *
                        preTrans;

                    dc.DrawBitmap(this._コンボ文字画像.Bitmap, (float)(this._各桁のアニメ[i].透明度?.Value ?? 1.0f), BitmapInterpolationMode.Linear, 転送元矩形.Value);

                    文字の位置.X += (転送元矩形.Value.Width + 文字間隔補正) * 画像矩形から表示矩形への拡大率.X;
                }

                dc.Transform = preTrans;
            }
            //----------------
            #endregion

            #region " Combo を描画。"
            //----------------
            {
                var 転送元矩形 = this._コンボ文字の矩形リスト["Combo"] !;
                var 文字の位置 = new Vector2(0f, 130f);

                dc.Transform =
                    Matrix3x2.Scaling(画像矩形から表示矩形への拡大率) *
                    Matrix3x2.Translation(文字の位置) *
                    Matrix3x2.Scaling(全体の拡大率) *
                    Matrix3x2.Translation(全体の中央位置) *
                    preTrans;

                dc.DrawBitmap(this._コンボ文字画像.Bitmap, 1.0f, BitmapInterpolationMode.Linear, 転送元矩形.Value);

                dc.Transform = preTrans;
            }
            //----------------
            #endregion


            // 保存

            this._前回表示した値  = 現在の成績.Combo;
            this._前回表示した数字 = 数字;
        }
Esempio n. 31
0
 public static void loadMatrix(Matrix3x2 m)
 {
     _world = new Matrix4x4(m);
 }
Esempio n. 32
0
 public static Vector2 RotateBy(float rotation, Vector2 v)
 {
     return(Matrix3x2.TransformPoint(Matrix3x2.Rotation(rotation), v));
 }
Esempio n. 33
0
 public Matrix3x2 Scale(Matrix3x2 value, float factor)
 {
     return(default(Matrix3x2));
 }
Esempio n. 34
0
 /// <summary>
 ///     Returns a copy of this style with the given transform applied.
 /// </summary>
 /// <param name="matrix">The transform matrix.</param>
 /// <returns>
 ///     The transformed style.
 /// </returns>
 public IStyle Transform(Matrix3x2 matrix) => this;
Esempio n. 35
0
        public void 進行描画する(DeviceContext1 dc)
        {
            foreach (表示レーン種別 レーン in Enum.GetValues(typeof(表示レーン種別)))
            {
                var status = this._レーンtoステータス[レーン];

                switch (status.現在の状態)
                {
                case 表示レーンステータス.状態.表示開始:
                    #region " 開始処理 "
                    //----------------
                {
                    status.アニメ用メンバを解放する();

                    var animation = グラフィックデバイス.Instance.Animation;

                    #region " (1) 光 アニメーションを構築 "
                    //----------------
                    if (status.判定種別 == 判定種別.PERFECT)            // 今のところ、光はPERFECT時のみ表示。
                    {
                        // 初期状態
                        status.光の回転角      = new Variable(animation.Manager, initialValue: 0);
                        status.光のX方向拡大率   = new Variable(animation.Manager, initialValue: 1.2);
                        status.光のY方向拡大率   = new Variable(animation.Manager, initialValue: 0.25);
                        status.光のストーリーボード = new Storyboard(animation.Manager);

                        double 期間sec;

                        // シーン1. 小さい状態からすばやく展開
                        期間sec = 0.03;
                        using (var 回転角の遷移 = animation.TrasitionLibrary.Linear(duration: 期間sec, finalValue: -100.0))                  // [degree]
                            using (var X方向拡大率の遷移 = animation.TrasitionLibrary.Linear(duration: 期間sec, finalValue: 1.0))
                                using (var Y方向拡大率の遷移 = animation.TrasitionLibrary.Linear(duration: 期間sec, finalValue: 1.0))
                                {
                                    status.光のストーリーボード.AddTransition(status.光の回転角, 回転角の遷移);
                                    status.光のストーリーボード.AddTransition(status.光のX方向拡大率, X方向拡大率の遷移);
                                    status.光のストーリーボード.AddTransition(status.光のY方向拡大率, Y方向拡大率の遷移);
                                }

                        // シーン2. 大きい状態でゆっくり消える
                        期間sec = 0.29;
                        using (var 回転角の遷移 = animation.TrasitionLibrary.Linear(duration: 期間sec, finalValue: -140.0))                  // [degree]
                            using (var X方向拡大率の遷移 = animation.TrasitionLibrary.Linear(duration: 期間sec, finalValue: 0.0))
                                using (var Y方向拡大率の遷移 = animation.TrasitionLibrary.Constant(duration: 期間sec))
                                {
                                    status.光のストーリーボード.AddTransition(status.光の回転角, 回転角の遷移);
                                    status.光のストーリーボード.AddTransition(status.光のX方向拡大率, X方向拡大率の遷移);
                                    status.光のストーリーボード.AddTransition(status.光のY方向拡大率, Y方向拡大率の遷移);
                                }

                        // 開始
                        status.光のストーリーボード.Schedule(animation.Timer.Time);
                    }
                    //----------------
                    #endregion

                    #region " (2) 判定文字(影)アニメーションを構築 "
                    //----------------
                    {
                        // 初期状態
                        status.文字列影の相対Y位置dpx = new Variable(animation.Manager, initialValue: +40.0);
                        status.文字列影の不透明度     = new Variable(animation.Manager, initialValue: 0.0);
                        status.文字列影のストーリーボード = new Storyboard(animation.Manager);

                        double 期間sec;

                        // シーン1. 完全透明のまま下から上に移動。
                        期間sec = 0.05;
                        using (var 相対Y位置の遷移 = animation.TrasitionLibrary.Linear(duration: 期間sec, finalValue: -5.0))
                            using (var 透明度の遷移 = animation.TrasitionLibrary.Constant(duration: 期間sec))
                            {
                                status.文字列影のストーリーボード.AddTransition(status.文字列影の相対Y位置dpx, 相対Y位置の遷移);
                                status.文字列影のストーリーボード.AddTransition(status.文字列影の不透明度, 透明度の遷移);
                            }

                        // シーン2. 透明になりつつ上に消える
                        期間sec = 0.15;
                        using (var 相対Y位置の遷移 = animation.TrasitionLibrary.Linear(duration: 期間sec, finalValue: -10.0))
                            using (var 透明度の遷移1 = animation.TrasitionLibrary.Linear(duration: 0.0, finalValue: 0.5))
                                using (var 透明度の遷移2 = animation.TrasitionLibrary.Linear(duration: 期間sec, finalValue: 0.0))
                                {
                                    status.文字列影のストーリーボード.AddTransition(status.文字列影の相対Y位置dpx, 相対Y位置の遷移);
                                    status.文字列影のストーリーボード.AddTransition(status.文字列影の不透明度, 透明度の遷移1);
                                    status.文字列影のストーリーボード.AddTransition(status.文字列影の不透明度, 透明度の遷移2);
                                }

                        // 開始
                        status.文字列影のストーリーボード.Schedule(animation.Timer.Time);
                    }
                    //----------------
                    #endregion

                    #region " (3) 判定文字(本体)アニメーションを構築 "
                    //----------------
                    {
                        // 初期状態
                        status.文字列本体の相対Y位置dpx = new Variable(animation.Manager, initialValue: +40.0);
                        status.文字列本体のX方向拡大率   = new Variable(animation.Manager, initialValue: 1.0);
                        status.文字列本体のY方向拡大率   = new Variable(animation.Manager, initialValue: 1.0);
                        status.文字列本体の不透明度     = new Variable(animation.Manager, initialValue: 0.0);
                        status.文字列本体のストーリーボード = new Storyboard(animation.Manager);

                        double 期間sec;

                        // シーン1. 透明から不透明になりつつ下から上に移動。
                        期間sec = 0.05;
                        using (var 相対Y位置の遷移 = animation.TrasitionLibrary.Linear(duration: 期間sec, finalValue: -5.0))
                            using (var X方向拡大率の遷移 = animation.TrasitionLibrary.Constant(duration: 期間sec))
                                using (var Y方向拡大率の遷移 = animation.TrasitionLibrary.Constant(duration: 期間sec))
                                    using (var 透明度の遷移 = animation.TrasitionLibrary.AccelerateDecelerate(duration: 期間sec, finalValue: 1.0, accelerationRatio: 0.1, decelerationRatio: 0.9))
                                    {
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体の相対Y位置dpx, 相対Y位置の遷移);
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体のX方向拡大率, X方向拡大率の遷移);
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体のY方向拡大率, Y方向拡大率の遷移);
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体の不透明度, 透明度の遷移);
                                    }

                        // シーン2. ちょっと下に跳ね返る
                        期間sec = 0.05;
                        using (var 相対Y位置の遷移 = animation.TrasitionLibrary.Linear(duration: 期間sec, finalValue: +5.0))
                            using (var X方向拡大率の遷移 = animation.TrasitionLibrary.Constant(duration: 期間sec))
                                using (var Y方向拡大率の遷移 = animation.TrasitionLibrary.Constant(duration: 期間sec))
                                    using (var 透明度の遷移 = animation.TrasitionLibrary.Constant(duration: 期間sec))
                                    {
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体の相対Y位置dpx, 相対Y位置の遷移);
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体のX方向拡大率, X方向拡大率の遷移);
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体のY方向拡大率, Y方向拡大率の遷移);
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体の不透明度, 透明度の遷移);
                                    }

                        // シーン3. また上に戻る
                        期間sec = 0.05;
                        using (var 相対Y位置の遷移 = animation.TrasitionLibrary.Linear(duration: 期間sec, finalValue: +0.0))
                            using (var X方向拡大率の遷移 = animation.TrasitionLibrary.Constant(duration: 期間sec))
                                using (var Y方向拡大率の遷移 = animation.TrasitionLibrary.Constant(duration: 期間sec))
                                    using (var 透明度の遷移 = animation.TrasitionLibrary.Constant(duration: 期間sec))
                                    {
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体の相対Y位置dpx, 相対Y位置の遷移);
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体のX方向拡大率, X方向拡大率の遷移);
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体のY方向拡大率, Y方向拡大率の遷移);
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体の不透明度, 透明度の遷移);
                                    }

                        // シーン4. 静止
                        期間sec = 0.15;
                        using (var 相対Y位置の遷移 = animation.TrasitionLibrary.Constant(duration: 期間sec))
                            using (var X方向拡大率の遷移 = animation.TrasitionLibrary.Constant(duration: 期間sec))
                                using (var Y方向拡大率の遷移 = animation.TrasitionLibrary.Constant(duration: 期間sec))
                                    using (var 透明度の遷移 = animation.TrasitionLibrary.Constant(duration: 期間sec))
                                    {
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体の相対Y位置dpx, 相対Y位置の遷移);
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体のX方向拡大率, X方向拡大率の遷移);
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体のY方向拡大率, Y方向拡大率の遷移);
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体の不透明度, 透明度の遷移);
                                    }

                        // シーン5. 横に広がり縦につぶれつつ消える
                        期間sec = 0.05;
                        using (var 相対Y位置の遷移 = animation.TrasitionLibrary.Constant(duration: 期間sec))
                            using (var X方向拡大率の遷移 = animation.TrasitionLibrary.Linear(duration: 期間sec, finalValue: 2.0))
                                using (var Y方向拡大率の遷移 = animation.TrasitionLibrary.Linear(duration: 期間sec, finalValue: 0.0))
                                    using (var 透明度の遷移 = animation.TrasitionLibrary.Linear(duration: 期間sec, finalValue: 0.0))
                                    {
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体の相対Y位置dpx, 相対Y位置の遷移);
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体のX方向拡大率, X方向拡大率の遷移);
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体のY方向拡大率, Y方向拡大率の遷移);
                                        status.文字列本体のストーリーボード.AddTransition(status.文字列本体の不透明度, 透明度の遷移);
                                    }

                        // 開始
                        status.文字列本体のストーリーボード.Schedule(animation.Timer.Time);
                    }
                    //----------------
                    #endregion

                    status.現在の状態 = 表示レーンステータス.状態.表示中;
                }
                    //----------------
                    #endregion
                    break;

                case 表示レーンステータス.状態.表示中:
                    #region " 開始完了、表示中 "
                    //----------------
                {
                    #region " (1) 光 の進行描画 "
                    //----------------
                    if (null != status.光のストーリーボード)
                    {
                        var 転送元矩形       = this._判定文字列の矩形リスト["PERFECT光"];
                        var 転送元矩形の中心dpx = new Vector2(転送元矩形.Width / 2f, 転送元矩形.Height / 2f);

                        var 換行列2D =
                            Matrix3x2.Scaling(
                                x: (float)status.光のX方向拡大率.Value,
                                y: (float)status.光のY方向拡大率.Value,
                                center: 転送元矩形の中心dpx) *
                            Matrix3x2.Rotation(
                                angle: MathUtil.DegreesToRadians((float)status.光の回転角.Value),
                                center: 転送元矩形の中心dpx) *
                            Matrix3x2.Translation(
                                status.表示中央位置dpx.X - 転送元矩形.Width / 2f,
                                status.表示中央位置dpx.Y - 転送元矩形.Height / 2f);

                        this._判定文字列画像.描画する(dc, 換行列2D, 転送元矩形: 転送元矩形);
                    }
                    //----------------
                    #endregion

                    #region " (2) 判定文字列(影)の進行描画"
                    //----------------
                    if (null != status.文字列影のストーリーボード)
                    {
                        var 転送元矩形 = this._判定文字列の矩形リスト[status.判定種別.ToString()];

                        var 換行列2D =
                            Matrix3x2.Translation(
                                status.表示中央位置dpx.X - 転送元矩形.Width / 2f,
                                status.表示中央位置dpx.Y - 転送元矩形.Height / 2f + (float)status.文字列影の相対Y位置dpx.Value);

                        this._判定文字列画像.描画する(
                            dc,
                            換行列2D,
                            転送元矩形: 転送元矩形,
                            透明度0to1: (float)status.文字列影の不透明度.Value);
                    }
                    //----------------
                    #endregion

                    #region " (3) 判定文字列(本体)の進行描画 "
                    //----------------
                    if (null != status.文字列本体のストーリーボード)
                    {
                        var 転送元矩形 = this._判定文字列の矩形リスト[status.判定種別.ToString()];

                        var sx = (float)status.文字列本体のX方向拡大率.Value;
                        var sy = (float)status.文字列本体のY方向拡大率.Value;

                        var 換行列2D =
                            Matrix3x2.Scaling(sx, sy) *
                            Matrix3x2.Translation(
                                status.表示中央位置dpx.X - sx * 転送元矩形.Width / 2f,
                                status.表示中央位置dpx.Y - sy * 転送元矩形.Height / 2f + (float)status.文字列本体の相対Y位置dpx.Value);

                        this._判定文字列画像.描画する(
                            dc,
                            換行列2D,
                            転送元矩形: 転送元矩形,
                            透明度0to1: (float)status.文字列本体の不透明度.Value);
                    }
                    //----------------
                    #endregion

                    // 全部終わったら非表示へ。
                    if (((null == status.文字列影のストーリーボード) || (status.文字列影のストーリーボード.Status == StoryboardStatus.Ready)) &&
                        ((null == status.文字列本体のストーリーボード) || (status.文字列本体のストーリーボード.Status == StoryboardStatus.Ready)) &&
                        ((null == status.光のストーリーボード) || (status.光のストーリーボード.Status == StoryboardStatus.Ready)))
                    {
                        status.現在の状態 = 表示レーンステータス.状態.非表示;
                    }
                }
                    //----------------
                    #endregion
                    break;

                default:
                    continue;       // 非表示
                }
            }
        }
Esempio n. 36
0
 /// <summary>	
 /// Determines whether the geometry's stroke contains the specified point given the specified stroke thickness, style, and transform. 	
 /// </summary>	
 /// <param name="point">The point to test for containment. </param>
 /// <param name="strokeWidth">The thickness of the stroke to apply. </param>
 /// <param name="strokeStyle">The style of stroke to apply. </param>
 /// <param name="transform">The transform to apply to the stroked geometry.  </param>
 /// <returns>When this method returns, contains a boolean value set to true if the geometry's stroke contains the specified point; otherwise, false. You must allocate storage for this parameter. </returns>
 /// <unmanaged>HRESULT ID2D1Geometry::StrokeContainsPoint([None] D2D1_POINT_2F point,[None] float strokeWidth,[In, Optional] ID2D1StrokeStyle* strokeStyle,[In, Optional] const D2D1_MATRIX_3X2_F* worldTransform,[None] float flatteningTolerance,[Out] BOOL* contains)</unmanaged>
 public bool StrokeContainsPoint(DrawingPointF point, float strokeWidth, StrokeStyle strokeStyle, Matrix3x2 transform)
 {
     return StrokeContainsPoint(point, strokeWidth, strokeStyle, transform, FlatteningTolerance);            
 }
Esempio n. 37
0
 private void SetDrawingSession(CanvasDrawingSession drawingSession)
 {
     this.drawingSession = drawingSession;
     if (drawingSession != null)
     {
         drawingSession.Transform = Matrix3x2.Multiply(drawingSession.Transform, Matrix3x2.CreateScale(ZoomFactor));
         drawingSession.Transform = Matrix3x2.Multiply(drawingSession.Transform, Matrix3x2.CreateTranslation(ActualCenter));
     }
 }
Esempio n. 38
0
        private static Image <Bgra32> CutImage(Sprite m_Sprite, Texture2D m_Texture2D, Rectf textureRect, Vector2 textureRectOffset, float downscaleMultiplier, SpriteSettings settingsRaw)
        {
            var originalImage = m_Texture2D.ConvertToImage(false);

            if (originalImage != null)
            {
                using (originalImage)
                {
                    if (downscaleMultiplier > 0f && downscaleMultiplier != 1f)
                    {
                        var width  = (int)(m_Texture2D.m_Width / downscaleMultiplier);
                        var height = (int)(m_Texture2D.m_Height / downscaleMultiplier);
                        originalImage.Mutate(x => x.Resize(width, height));
                    }
                    var rectX      = (int)Math.Floor(textureRect.x);
                    var rectY      = (int)Math.Floor(textureRect.y);
                    var rectRight  = (int)Math.Ceiling(textureRect.x + textureRect.width);
                    var rectBottom = (int)Math.Ceiling(textureRect.y + textureRect.height);
                    rectRight  = Math.Min(rectRight, originalImage.Width);
                    rectBottom = Math.Min(rectBottom, originalImage.Height);
                    var rect        = new Rectangle(rectX, rectY, rectRight - rectX, rectBottom - rectY);
                    var spriteImage = originalImage.Clone(x => x.Crop(rect));
                    if (settingsRaw.packed == 1)
                    {
                        //RotateAndFlip
                        switch (settingsRaw.packingRotation)
                        {
                        case SpritePackingRotation.kSPRFlipHorizontal:
                            spriteImage.Mutate(x => x.Flip(FlipMode.Horizontal));
                            break;

                        case SpritePackingRotation.kSPRFlipVertical:
                            spriteImage.Mutate(x => x.Flip(FlipMode.Vertical));
                            break;

                        case SpritePackingRotation.kSPRRotate180:
                            spriteImage.Mutate(x => x.Rotate(180));
                            break;

                        case SpritePackingRotation.kSPRRotate90:
                            spriteImage.Mutate(x => x.Rotate(270));
                            break;
                        }
                    }

                    //Tight
                    if (settingsRaw.packingMode == SpritePackingMode.kSPMTight)
                    {
                        try
                        {
                            var             triangles = GetTriangles(m_Sprite.m_RD);
                            var             polygons  = triangles.Select(x => new Polygon(new LinearLineSegment(x.Select(y => new PointF(y.X, y.Y)).ToArray()))).ToArray();
                            IPathCollection path      = new PathCollection(polygons);
                            var             matrix    = Matrix3x2.CreateScale(m_Sprite.m_PixelsToUnits);
                            matrix *= Matrix3x2.CreateTranslation(m_Sprite.m_Rect.width * m_Sprite.m_Pivot.X - textureRectOffset.X, m_Sprite.m_Rect.height * m_Sprite.m_Pivot.Y - textureRectOffset.Y);
                            path    = path.Transform(matrix);
                            var graphicsOptions = new GraphicsOptions
                            {
                                Antialias            = false,
                                AlphaCompositionMode = PixelAlphaCompositionMode.DestOut
                            };
                            var options = new DrawingOptions
                            {
                                GraphicsOptions = graphicsOptions
                            };
                            using (var mask = new Image <Bgra32>(rect.Width, rect.Height, SixLabors.ImageSharp.Color.Black))
                            {
                                mask.Mutate(x => x.Fill(options, SixLabors.ImageSharp.Color.Red, path));
                                var bursh = new ImageBrush(mask);
                                spriteImage.Mutate(x => x.Fill(graphicsOptions, bursh));
                                spriteImage.Mutate(x => x.Flip(FlipMode.Vertical));
                                return(spriteImage);
                            }
                        }
                        catch
                        {
                            // ignored
                        }
                    }

                    //Rectangle
                    spriteImage.Mutate(x => x.Flip(FlipMode.Vertical));
                    return(spriteImage);
                }
            }

            return(null);
        }
Esempio n. 39
0
        /// <summary>
        /// Transforms a size by the given matrix.
        /// </summary>
        /// <param name="size">The source size.</param>
        /// <param name="matrix">The transformation matrix.</param>
        /// <returns>A transformed size.</returns>
        public static SizeF Transform(Size size, Matrix3x2 matrix)
        {
            var v = Vector2.Transform(new Vector2(size.Width, size.Height), matrix);

            return(new SizeF(v.X, v.Y));
        }
Esempio n. 40
0
 /// <summary>
 /// Returns the rectangle relative to the source for the given transformation matrix.
 /// </summary>
 /// <param name="rectangle">The source rectangle.</param>
 /// <param name="matrix">The transformation matrix.</param>
 /// <returns>
 /// The <see cref="Rectangle"/>.
 /// </returns>
 public static Rectangle GetTransformedRectangle(Rectangle rectangle, Matrix3x2 matrix)
 {
     if (rectangle.Equals(default) || Matrix3x2.Identity.Equals(matrix))
Esempio n. 41
0
        private CanvasRadialGradientBrush CreateRadialGradient(CanvasDrawingSession session, Rect area, SvgRadialGradientElement element)
        {
            if (this.ResourceCache.ContainsKey(element))
            {
                return((CanvasRadialGradientBrush)this.ResourceCache[element]);
            }

            var stops = element.ChildNodes.Cast <SvgStopElement>().Select(s =>
            {
                var alpha = s.Style.StopOpacity.HasValue ? (byte)(255.0F * s.Style.StopOpacity.Value) : (byte)0xff;
                var stop  = new CanvasGradientStop()
                {
                    Position = s.Offset,
                    Color    = s.Style.StopColor.StopColorType == SvgStopColorType.CurrentColor
                                                ? s.Style.Color.ToPlatformColor(alpha)
                                                : s.Style.StopColor?.ToPlatformColor(alpha) ?? Color.FromArgb(alpha, 0, 0, 0)
                };
                return(stop);
            }).ToArray();

            var m         = element.GradientTransform.Result;
            var transform = new Matrix3x2 {
                M11 = (float)m.A, M12 = (float)m.B, M21 = (float)m.C, M22 = (float)m.D, M31 = (float)m.E, M32 = (float)m.F
            };

            float centerX, centerY, focusX, focusY, radiusX, radiusY;

            if (element.GradientUnits != SvgUnitType.UserSpaceOnUse)
            {
                centerX = this.LengthConverter.ConvertXForOBBU(element.CenterX, (float)area.X, (float)area.Width);
                centerY = this.LengthConverter.ConvertYForOBBU(element.CenterY, (float)area.Y, (float)area.Height);
                focusX  = this.LengthConverter.ConvertXForOBBU(element.FocusX, (float)area.X, (float)area.Width);
                focusY  = this.LengthConverter.ConvertYForOBBU(element.FocusY, (float)area.Y, (float)area.Height);
                radiusX = this.LengthConverter.ConvertXForOBBU(element.Radius, (float)area.X, (float)area.Width);
                radiusY = this.LengthConverter.ConvertYForOBBU(element.Radius, (float)area.Y, (float)area.Height);
            }
            else
            {
                centerX = this.LengthConverter.ConvertX(element.CenterX);
                centerY = this.LengthConverter.ConvertY(element.CenterY);
                focusX  = this.LengthConverter.ConvertX(element.FocusX);
                focusY  = this.LengthConverter.ConvertY(element.FocusY);
                radiusX = this.LengthConverter.ConvertX(element.Radius);
                radiusY = this.LengthConverter.ConvertY(element.Radius);
            }
            var spreadMethod = GetSpreadMethod(element.SpreadMethod);
            var brush        = new CanvasRadialGradientBrush(this.ResourceCreator, stops, spreadMethod, CanvasAlphaMode.Straight)
            {
                OriginOffset = new Vector2 {
                    X = focusX - centerX, Y = focusY - centerY
                },
                Center = new Vector2 {
                    X = centerX, Y = centerY
                },
                RadiusX   = radiusX,
                RadiusY   = radiusY,
                Transform = transform,
            };

            this.DisposableObjects.Add(brush);
            this.ResourceCache.Add(element, brush);
            return(brush);
        }
Esempio n. 42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LayerParameters1"/> struct.
 /// </summary>
 /// <param name="contentBounds">The content bounds.</param>
 /// <param name="geometryMask">The geometry mask.</param>
 /// <param name="maskAntialiasMode">The mask antialias mode.</param>
 /// <param name="maskTransform">The mask transform.</param>
 /// <param name="opacity">The opacity.</param>
 /// <param name="opacityBrush">The opacity brush.</param>
 /// <param name="layerOptions">The layer options.</param>
 public LayerParameters1(RectangleF contentBounds, Geometry geometryMask, AntialiasMode maskAntialiasMode, Matrix3x2 maskTransform, float opacity, Brush opacityBrush, LayerOptions1 layerOptions)
     : this()
 {
     ContentBounds     = contentBounds;
     geometricMask_    = geometryMask.NativePointer;
     MaskAntialiasMode = maskAntialiasMode;
     MaskTransform     = maskTransform;
     Opacity           = opacity;
     opacityBrush_     = opacityBrush.NativePointer;
     LayerOptions      = layerOptions;
 }
Esempio n. 43
0
 public Matrix3x2 Lerp(Matrix3x2 value1, Matrix3x2 value2, float progress)
 {
     return(default(Matrix3x2));
 }
Esempio n. 44
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="TileBase" /> class.
 /// </summary>
 /// <param name="tile">The base tile.</param>
 /// <param name="label">The tile label.</param>
 /// <param name="transform">The transform of this tile.</param>
 /// <exception cref="System.ArgumentNullException"><paramref name="label" /> or <paramref name="tile" /> was null.</exception>
 public TileInstance([NotNull] Tile tile, [NotNull] string label, Matrix3x2 transform)
     : base(label, tile.Shape, transform)
 {
     if (tile == null) throw new ArgumentNullException(nameof(tile));
     Tile = tile;
 }
Esempio n. 45
0
        public static async Task <StorageFile> DrawStrokesAsync(StorageFile file, IReadOnlyList <SmoothPathBuilder> strokes, Rect rectangle, BitmapRotation rotation, BitmapFlip flip)
        {
            var device = CanvasDevice.GetSharedDevice();
            var bitmap = await CanvasBitmap.LoadAsync(device, file.Path);

            var canvas1 = new CanvasRenderTarget(device, (float)bitmap.Size.Width, (float)bitmap.Size.Height, bitmap.Dpi);
            var canvas2 = new CanvasRenderTarget(device, (float)bitmap.Size.Width, (float)bitmap.Size.Height, bitmap.Dpi);

            var size       = canvas1.Size.ToVector2();
            var canvasSize = canvas1.Size.ToVector2();

            var scaleX = 1 / (float)rectangle.Width;
            var scaleY = 1 / (float)rectangle.Height;

            var offsetX = (float)rectangle.X * scaleX;
            var offsetY = (float)rectangle.Y * scaleY;

            if (rotation == BitmapRotation.Clockwise270Degrees ||
                rotation == BitmapRotation.Clockwise90Degrees)
            {
                size = new Vector2(size.Y, size.X);

                scaleX = scaleY;
                scaleY = 1 * 1 / (float)rectangle.Width;
            }

            using (var session = canvas1.CreateDrawingSession())
            {
                switch (rotation)
                {
                case BitmapRotation.Clockwise90Degrees:
                    var transform1 = Matrix3x2.CreateRotation(MathFEx.ToRadians(90));
                    transform1.Translation = new Vector2(size.Y, 0);
                    session.Transform      = transform1;
                    break;

                case BitmapRotation.Clockwise180Degrees:
                    var transform2 = Matrix3x2.CreateRotation(MathFEx.ToRadians(180));
                    transform2.Translation = new Vector2(size.X, size.Y);
                    session.Transform      = transform2;
                    break;

                case BitmapRotation.Clockwise270Degrees:
                    var transform3 = Matrix3x2.CreateRotation(MathFEx.ToRadians(270));
                    transform3.Translation = new Vector2(0, size.X);
                    session.Transform      = transform3;
                    break;
                }

                switch (flip)
                {
                case BitmapFlip.Horizontal:
                    switch (rotation)
                    {
                    case BitmapRotation.Clockwise90Degrees:
                    case BitmapRotation.Clockwise270Degrees:
                        session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(1, -1, canvasSize / 2));
                        break;

                    default:
                        session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(-1, 1, canvasSize / 2));
                        break;
                    }
                    break;

                case BitmapFlip.Vertical:
                    switch (rotation)
                    {
                    case BitmapRotation.None:
                    case BitmapRotation.Clockwise180Degrees:
                        session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(1, -1, canvasSize / 2));
                        break;

                    default:
                        session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(-1, 1, canvasSize / 2));
                        break;
                    }
                    break;
                }

                session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(scaleX, scaleY));
                session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateTranslation(-(offsetX * size.X), -(offsetY * size.Y)));

                foreach (var builder in strokes)
                {
                    PencilCanvas.DrawPath(session, builder, size);
                }
            }

            using (var session = canvas2.CreateDrawingSession())
            {
                session.DrawImage(bitmap);
                session.DrawImage(canvas1);
            }

            bitmap.Dispose();

            using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await canvas2.SaveAsync(stream, CanvasBitmapFileFormat.Jpeg /*, 0.77f*/);
            }

            canvas2.Dispose();
            canvas1.Dispose();

            return(file);
        }
Esempio n. 46
0
        protected override void DrawChart(CanvasDrawingSession canvas)
        {
            if (chartData != null)
            {
                float fullWidth = chartWidth / (pickerDelegate.pickerEnd - pickerDelegate.pickerStart);
                float offset    = fullWidth * pickerDelegate.pickerStart - HORIZONTAL_PADDING;

                int start = startXIndex - 1;
                if (start < 0)
                {
                    start = 0;
                }

                int end = endXIndex + 1;
                if (end > chartData.lines[0].y.Length - 1)
                {
                    end = chartData.lines[0].y.Length - 1;
                }

                //canvas.save();
                //canvas.clipRect(chartStart, 0, chartEnd, MeasuredHeight - chartBottom);
                var transform = canvas.Transform;
                var clip      = canvas.CreateLayer(1, CreateRect(chartStart, 0, chartEnd, MeasuredHeight - chartBottom));

                float transitionAlpha = 1f;
                //canvas.save();
                if (transitionMode == TRANSITION_MODE_PARENT)
                {
                    postTransition  = true;
                    selectionA      = 0f;
                    transitionAlpha = 1f - transitionParams.progress;

                    canvas.Transform = Matrix3x2.CreateScale(
                        new Vector2(1 + 2 * transitionParams.progress, 1f),
                        new Vector2(transitionParams.pX, transitionParams.pY)
                        );
                }
                else if (transitionMode == TRANSITION_MODE_CHILD)
                {
                    transitionAlpha = transitionParams.progress;

                    canvas.Transform = Matrix3x2.CreateScale(
                        new Vector2(transitionParams.progress, 1f),
                        new Vector2(transitionParams.pX, transitionParams.pY)
                        );
                }


                for (int k = 0; k < lines.Count; k++)
                {
                    BarViewData line = lines[k];
                    if (!line.enabled && line.alpha == 0)
                    {
                        continue;
                    }

                    float p;
                    if (chartData.xPercentage.Length < 2)
                    {
                        p = 1f;
                    }
                    else
                    {
                        p = chartData.xPercentage[1] * fullWidth;
                    }
                    int[] y = line.line.y;
                    int   j = 0;

                    float selectedX = 0f;
                    float selectedY = 0f;
                    bool  selected  = false;
                    float a         = line.alpha;
                    for (int i = start; i <= end; i++)
                    {
                        float xPoint      = p / 2 + chartData.xPercentage[i] * fullWidth - offset;
                        float yPercentage = y[i] / currentMaxHeight * a;

                        float yPoint = MeasuredHeight - chartBottom - yPercentage * (MeasuredHeight - chartBottom - SIGNATURE_TEXT_HEIGHT);

                        if (i == selectedIndex && legendShowing)
                        {
                            selected  = true;
                            selectedX = xPoint;
                            selectedY = yPoint;
                            continue;
                        }

                        line.linesPath[j++] = xPoint;
                        line.linesPath[j++] = yPoint;

                        line.linesPath[j++] = xPoint;
                        line.linesPath[j++] = MeasuredHeight - chartBottom;
                    }

                    Paint paint = selected || postTransition ? line.unselectedPaint : line.paint;
                    paint.StrokeWidth = p;
                    //paint.setStrokeWidth(p);


                    if (selected)
                    {
                        line.unselectedPaint.Color = Extensions.blendARGB(
                            line.line.color, line.blendColor, 1f - selectionA);
                    }

                    if (postTransition)
                    {
                        line.unselectedPaint.Color = Extensions.blendARGB(
                            line.line.color, line.blendColor, 0);
                    }

                    paint.A = (byte)(transitionAlpha * 255);
                    //canvas.drawLines(line.linesPath, 0, j, paint);
                    canvas.DrawLines(line.linesPath, 0, j, paint);

                    if (selected)
                    {
                        //line.paint.setStrokeWidth(p);
                        line.paint.StrokeWidth = p;
                        line.paint.A           = (byte)(transitionAlpha * 255);
                        //canvas.drawLine(selectedX, selectedY,
                        //        selectedX, MeasuredHeight - chartBottom,
                        //        line.paint
                        //);
                        canvas.DrawLine(selectedX, selectedY, selectedX, MeasuredHeight - chartBottom, line.paint);
                        line.paint.A = 255;
                    }
                }

                //canvas.restore();
                //canvas.restore();
                clip.Dispose();
                canvas.Transform = transform;
            }
        }
Esempio n. 47
0
        public override CanvasGeometry CreateGeometry(ICanvasResourceCreator resourceCreator, Matrix3x2 matrix)
        {
            Transformer transformer = base.Transform.Transformer;

            return(TransformerGeometry.CreateDiamond(resourceCreator, transformer, matrix, this.Mid));
        }
Esempio n. 48
0
 /// <summary>
 /// Transforms the current LineSegment using specified matrix.
 /// </summary>
 /// <param name="matrix">The matrix.</param>
 /// <returns>A line segment with the matrix applied to it.</returns>
 ILineSegment ILineSegment.Transform(Matrix3x2 matrix) => this.Transform(matrix);
Esempio n. 49
0
        public static void ComposeGlyphs(int glyphIndex, int startPoint, ref Matrix3x2 transform, List <PointF> basePoints, List <int> baseContours, BaseGlyph[] glyphTable)
        {
            var glyph  = glyphTable[glyphIndex];
            var simple = glyph as SimpleGlyph;

            if (simple != null)
            {
                foreach (var endpoint in simple.ContourEndpoints)
                {
                    baseContours.Add(endpoint + startPoint);
                }
                foreach (var point in simple.Points)
                {
                    basePoints.Add(new PointF(Vector2.TransformNormal((Vector2)point, transform), point.Type));
                }
            }
            else
            {
                // otherwise, we have a composite glyph
                var composite = (CompositeGlyph)glyph;
                foreach (var subglyph in composite.Subglyphs)
                {
                    // if we have a scale, update the local transform
                    var  local     = transform;
                    bool haveScale = (subglyph.Flags & (CompositeGlyphFlags.HaveScale | CompositeGlyphFlags.HaveXYScale | CompositeGlyphFlags.HaveTransform)) != 0;
                    if (haveScale)
                    {
                        local = transform * subglyph.Transform;
                    }

                    // recursively compose the subglyph into our lists
                    int currentPoints = basePoints.Count;
                    ComposeGlyphs(subglyph.Index, currentPoints, ref local, basePoints, baseContours, glyphTable);

                    // calculate the offset for the subglyph. we have to do offsetting after composing all subglyphs,
                    // because we might need to find the offset based on previously composed points by index
                    Vector2 offset;
                    if ((subglyph.Flags & CompositeGlyphFlags.ArgsAreXYValues) != 0)
                    {
                        offset = (Vector2) new Point((FUnit)subglyph.Arg1, (FUnit)subglyph.Arg2);
                        if (haveScale && (subglyph.Flags & CompositeGlyphFlags.ScaledComponentOffset) != 0)
                        {
                            offset = Vector2.TransformNormal(offset, local);
                        }
                        else
                        {
                            offset = Vector2.TransformNormal(offset, transform);
                        }

                        // if the RoundXYToGrid flag is set, round the offset components
                        if ((subglyph.Flags & CompositeGlyphFlags.RoundXYToGrid) != 0)
                        {
                            offset = new Vector2((float)Math.Round(offset.X), (float)Math.Round(offset.Y));
                        }
                    }
                    else
                    {
                        // if the offsets are not given in FUnits, then they are point indices
                        // in the currently composed base glyph that we should match up
                        var p1 = basePoints[(int)((uint)subglyph.Arg1 + startPoint)];
                        var p2 = basePoints[(int)((uint)subglyph.Arg2 + currentPoints)];
                        offset = p1.P - p2.P;
                    }

                    // translate all child points
                    if (offset != Vector2.Zero)
                    {
                        for (int i = currentPoints; i < basePoints.Count; i++)
                        {
                            basePoints[i] = basePoints[i].Offset(offset);
                        }
                    }
                }
            }
        }
Esempio n. 50
0
        private void OnCanvasDraw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            CanvasDrawingSession drawingSession = args.DrawingSession;

            CanvasTextFormat format =
                new CanvasTextFormat
            {
                FontSize     = Convert.ToSingle(canvas.FontSize),
                FontFamily   = canvas.FontFamily.Source,
                FontWeight   = canvas.FontWeight,
                WordWrapping = CanvasWordWrapping.NoWrap
            };

            ProcessTextFormat(drawingSession, format);

            drawingSession.FillRectangle(new Rect(0, 0, canvas.RenderSize.Width, canvas.RenderSize.Height), GetBackgroundColor(Terminal.CursorState.Attribute, false));

            lock (Terminal)
            {
                int   row            = ViewTop;
                float verticalOffset = -row * (float)CharacterHeight;

                var lines = Terminal.ViewPort.GetLines(ViewTop, Rows);

                var defaultTransform = drawingSession.Transform;
                foreach (var line in lines)
                {
                    if (line == null)
                    {
                        row++;
                        continue;
                    }

                    int column = 0;

                    drawingSession.Transform = Matrix3x2.CreateScale(
                        (float)(line.DoubleWidth ? 2.0 : 1.0),
                        (float)(line.DoubleHeightBottom | line.DoubleHeightTop ? 2.0 : 1.0)
                        );

                    foreach (var character in line)
                    {
                        bool selected = TextSelection == null ? false : TextSelection.Within(column, row);

                        var rect = new Rect(
                            column * CharacterWidth,
                            ((row - (line.DoubleHeightBottom ? 1 : 0)) * CharacterHeight + verticalOffset) * (line.DoubleHeightBottom | line.DoubleHeightTop ? 0.5 : 1.0),
                            CharacterWidth + 0.9,
                            CharacterHeight + 0.9
                            );

                        var textLayout      = new CanvasTextLayout(drawingSession, character.Char.ToString(), format, 0.0f, 0.0f);
                        var backgroundColor = GetBackgroundColor(character.Attributes, selected);
                        var foregroundColor = GetForegroundColor(character.Attributes, selected);
                        drawingSession.FillRectangle(rect, backgroundColor);

                        drawingSession.DrawTextLayout(
                            textLayout,
                            (float)rect.Left,
                            (float)rect.Top,
                            foregroundColor
                            );

                        if (character.Attributes.Underscore)
                        {
                            drawingSession.DrawLine(
                                new Vector2(
                                    (float)rect.Left,
                                    (float)rect.Bottom
                                    ),
                                new Vector2(
                                    (float)rect.Right,
                                    (float)rect.Bottom
                                    ),
                                foregroundColor
                                );
                        }

                        column++;
                    }
                    row++;
                }
                drawingSession.Transform = defaultTransform;

                if (Terminal.CursorState.ShowCursor)
                {
                    var cursorY    = Terminal.ViewPort.TopRow - ViewTop + Terminal.CursorState.CurrentRow;
                    var cursorRect = new Rect(
                        Terminal.CursorState.CurrentColumn * CharacterWidth,
                        cursorY * CharacterHeight,
                        CharacterWidth + 0.9,
                        CharacterHeight + 0.9
                        );

                    drawingSession.DrawRectangle(cursorRect, GetForegroundColor(Terminal.CursorState.Attribute, false));
                }
            }

            if (ViewDebugging)
            {
                AnnotateView(drawingSession);
            }
        }
        private static void CalculateLayout(Size size, float width, float height, out Matrix3x2 counterTransform, out Matrix3x2 graphTransform)
        {
            bool verticalLayout = true;

            if (size.Width > size.Height)
            {
                verticalLayout = false;
            }

            if (verticalLayout)
            {
                float targetWidth  = (float)size.Width;
                float targetHeight = (float)size.Height / 2;

                float scaleFactor = targetHeight / height;

                if ((width * scaleFactor) > targetWidth)
                {
                    scaleFactor = targetWidth / width;
                }

                float xoffset = (targetWidth / 2) - (height * scaleFactor) / 2;
                counterTransform = Matrix3x2.CreateScale(scaleFactor, scaleFactor) * Matrix3x2.CreateTranslation(xoffset, 0);
                graphTransform   = Matrix3x2.CreateScale(scaleFactor, scaleFactor) * Matrix3x2.CreateTranslation(xoffset, targetHeight);
            }
            else
            {
                float targetWidth  = (float)size.Width / 2;
                float targetHeight = (float)size.Height;

                float scaleFactor = targetWidth / width;

                if ((height * scaleFactor) > targetHeight)
                {
                    scaleFactor = targetHeight / height;
                }

                float yoffset = (targetHeight / 2) - (height * scaleFactor) / 2;
                counterTransform = Matrix3x2.CreateScale(scaleFactor, scaleFactor) * Matrix3x2.CreateTranslation(0, yoffset);
                graphTransform   = Matrix3x2.CreateScale(scaleFactor, scaleFactor) * Matrix3x2.CreateTranslation(targetWidth, yoffset);
            }
        }
Esempio n. 52
0
 public Vector2 Transform(Vector2 value, Matrix3x2 matrix)
 {
     return(default(Vector2));
 }
Esempio n. 53
0
 public static Point Transform(Point point, Matrix3x2 matrix) => Round(Vector2.Transform(new Vector2(point.X, point.Y), matrix));
Esempio n. 54
0
 /// <summary>
 /// Default Constructor for a <see cref = "SharpDX.Direct2D1.TransformedGeometry" />.
 /// </summary>
 /// <param name="factory">an instance of <see cref = "SharpDX.Direct2D1.Factory" /></param>
 /// <param name="geometrySource"></param>
 /// <param name="matrix3X2"></param>
 public TransformedGeometry(Factory factory, Geometry geometrySource, Matrix3x2 matrix3X2) : base(IntPtr.Zero)
 {
     factory.CreateTransformedGeometry(geometrySource, ref matrix3X2, this);
 }
Esempio n. 55
0
        /// <summary>
        /// Returns the rectangle bounds relative to the source for the given transformation matrix.
        /// </summary>
        /// <param name="rectangle">The source rectangle.</param>
        /// <param name="matrix">The transformation matrix.</param>
        /// <returns>
        /// The <see cref="Rectangle"/>.
        /// </returns>
        public static Rectangle GetTransformedBoundingRectangle(Rectangle rectangle, Matrix3x2 matrix)
        {
            Rectangle transformed = GetTransformedRectangle(rectangle, matrix);

            return(new Rectangle(0, 0, transformed.Width, transformed.Height));
        }
Esempio n. 56
0
 protected override void Scale(Vector2 scale) => TransformPoints(Matrix3x2.CreateScale(scale));
Esempio n. 57
0
 /// <summary>	
 /// Indicates whether the area filled by the geometry would contain the specified point given the specified flattening tolerance. 	
 /// </summary>	
 /// <param name="point">The point to test. </param>
 /// <param name="worldTransform">The transform to apply to the geometry prior to testing for containment, or NULL. </param>
 /// <param name="flatteningTolerance">The numeric accuracy with which the precise geometric path and path intersection is calculated. Points missing the fill by less than the tolerance are still considered inside.  Smaller values produce more accurate results but cause slower execution.  </param>
 /// <returns>When this method returns, contains a bool value that is true if the area filled by the geometry contains point; otherwise, false.You must allocate storage for this parameter. </returns>
 /// <unmanaged>HRESULT ID2D1Geometry::FillContainsPoint([None] D2D1_POINT_2F point,[In, Optional] const D2D1_MATRIX_3X2_F* worldTransform,[None] float flatteningTolerance,[Out] BOOL* contains)</unmanaged>
 public bool FillContainsPoint(DrawingPoint point, Matrix3x2 worldTransform, float flatteningTolerance)
 {
     return FillContainsPoint(new DrawingPointF(point.X, point.Y), worldTransform, flatteningTolerance);
 }
Esempio n. 58
0
        /// <summary>
        /// Gets the centered transform matrix based upon the source and destination rectangles.
        /// </summary>
        /// <param name="sourceRectangle">The source image bounds.</param>
        /// <param name="matrix">The transformation matrix.</param>
        /// <returns>The <see cref="Matrix3x2"/></returns>
        public static Matrix3x2 CreateCenteredTransformMatrix(Rectangle sourceRectangle, Matrix3x2 matrix)
        {
            Rectangle destinationRectangle = GetTransformedBoundingRectangle(sourceRectangle, matrix);

            // We invert the matrix to handle the transformation from screen to world space.
            // This ensures scaling matrices are correct.
            Matrix3x2.Invert(matrix, out Matrix3x2 inverted);

            var translationToTargetCenter = Matrix3x2.CreateTranslation(new Vector2(-destinationRectangle.Width, -destinationRectangle.Height) * .5F);
            var translateToSourceCenter   = Matrix3x2.CreateTranslation(new Vector2(sourceRectangle.Width, sourceRectangle.Height) * .5F);

            // Translate back to world space.
            Matrix3x2.Invert(translationToTargetCenter * inverted * translateToSourceCenter, out Matrix3x2 centered);

            return(centered);
        }
Esempio n. 59
0
 /// <summary>	
 /// Determines whether the geometry's stroke contains the specified point given the specified stroke thickness, style, and transform. 	
 /// </summary>	
 /// <param name="point">The point to test for containment. </param>
 /// <param name="strokeWidth">The thickness of the stroke to apply. </param>
 /// <param name="strokeStyle">The style of stroke to apply. </param>
 /// <param name="transform">The transform to apply to the stroked geometry.  </param>
 /// <param name="flatteningTolerance">The numeric accuracy with which the precise geometric path and path intersection is calculated. Points missing the stroke by less than the tolerance are still considered inside.  Smaller values produce more accurate results but cause slower execution. </param>
 /// <returns>When this method returns, contains a boolean value set to true if the geometry's stroke contains the specified point; otherwise, false. You must allocate storage for this parameter. </returns>
 /// <unmanaged>HRESULT ID2D1Geometry::StrokeContainsPoint([None] D2D1_POINT_2F point,[None] float strokeWidth,[In, Optional] ID2D1StrokeStyle* strokeStyle,[In, Optional] const D2D1_MATRIX_3X2_F* worldTransform,[None] float flatteningTolerance,[Out] BOOL* contains)</unmanaged>
 public bool StrokeContainsPoint(DrawingPoint point, float strokeWidth, StrokeStyle strokeStyle, Matrix3x2 transform, float flatteningTolerance)
 {
     return StrokeContainsPoint(new DrawingPointF(point.X, point.Y), strokeWidth, strokeStyle, transform, flatteningTolerance);
 }
Esempio n. 60
0
        static void Main(string[] args)
        {
            // Create the window and the graphics device
            VeldridInit(out var window, out var graphicsDevice);

            // See the Primitives sample for the basic concepts of OpenWheels
            var texStorage            = new VeldridTextureStorage(graphicsDevice);
            var renderer              = new VeldridRenderer(graphicsDevice, texStorage);
            var batcher               = new Batcher(NullBitmapFontRenderer.Instance);
            var checkerBoardTextureId = texStorage.LoadTexture("checkerboard.png");

            // OpenWheels defines a sprite as an image that's part of a texture.
            // To create a sprite, we pass a texture and a region of that texture that contains the image
            // We can define the region either in pixels (using Sprite) or in UV coordinates (using UvSprite).
            // Let's create a sprite that draws 3/4th of the checkerboard using UvSprite.
            // So if our original texture looks like this:
            //         |##  |
            //         |##  |
            //         |  ##|
            //         |  ##|
            // We'll create a sprite that looks like this:
            //         |## |
            //         |## |
            //         |  #|

            var cbSize                = texStorage.GetTextureSize(checkerBoardTextureId);
            var subSpriteRect         = new RectangleF(0, 0, 0.75f, 0.75f);
            var checkerBoardSubSprite = new UvSprite(checkerBoardTextureId, subSpriteRect);

            var frame = 0;

            // We run the game loop here and do our drawing inside of it.
            VeldridRunLoop(window, graphicsDevice, () =>
            {
                renderer.Clear(Color.CornflowerBlue);

                // Start a new batch
                batcher.Start();

                // we set the texture using the texture id we got back when registering the texture
                // OpenWheels internally only works with sprites
                // If you set a texture on a batcher it will convert it to a sprite with the region being the
                // entire texture bounds
                batcher.SetTexture(checkerBoardTextureId);

                // The Batcher API is stateful. Anything we render now will use the checkerboard texture.
                // By default the UV coordinates 0, 0, 1, 1 are used, so our texture is stretched
                batcher.FillRect(new RectangleF(50, 20, 100, 100), Color.White);
                batcher.FillRect(new RectangleF(200, 20, 100, 200), Color.White);

                // Let's draw our subsprite
                batcher.SetUvSprite(checkerBoardSubSprite);
                batcher.FillRect(new RectangleF(350, 20, 100, 100), Color.White);

                // We can only draw 1 texture in a single draw call, but since our subsprite actually uses the same
                // texture as our full checkerboard the batcher can still combine the calls into a single batch.

                batcher.SetTexture(checkerBoardTextureId);
                // Most of the primitives support UV coordinates one way or another.
                batcher.FillCircle(new Vector2(550, 70), 50, Color.White, .25f);
                batcher.FillRoundedRect(new RectangleF(650, 20, 100, 100), 15, Color.White);

                var v1 = new Vector2(50, 280);
                var v2 = new Vector2(150, 380);
                batcher.DrawLine(v1, v2, Color.White, 6f);
                // Note that the texture rotates with the line
                // This is different from the circle(segment) primitives where we draw a cutout of the active texture
                // There are a lot of ways to UV-map shapes, but OpenWheels currently picks just one for each shape

                // we can set a matrix to transform UV coordinates
                // let's make our texture loop in length while keeping it's aspect ratio and UV across its width.

                // The sampler should wrap to be able to loop the texture (the default sampler state is LinearClamp)
                // Render state sticks across frames, so we could set it before the render loop as well
                batcher.SamplerState = SamplerState.LinearWrap;
                var v3 = new Vector2(200, 280);
                var v4 = new Vector2(300, 380);
                const float lineWidth = 10f;

                // we want our UV aspect ratio to be 1:1, but it's lineWidth:length and we want to use
                // the coordinate system of the width, so we normalize height to get the right aspect ratio
                // (note that height is defined as the forward direction of the line)

                var uvHeight        = Vector2.Distance(v3, v4) / lineWidth;
                batcher.UvTransform = Matrix3x2.CreateScale(1f, uvHeight);
                batcher.DrawLine(v3, v4, Color.White, lineWidth);

                // Reset the uv transform
                batcher.UvTransform = Matrix3x2.Identity;

                // The color value we can pass to these methods is multiplied with our texture color at each pixel.
                batcher.FillRect(new RectangleF(350, 280, 100, 100), Color.Red);

                // Finish the batch and let the renderer draw everything to the back buffer.
                batcher.Render(renderer);

                if (frame < 2)
                {
                    // Note that the first frame renders in two batches because we change the sampler state
                    // halfway through.
                    // Every subsequent frame render in a single batch because the sampler state stays at LinearClamp
                    Console.WriteLine("Frame " + frame);
                    Console.WriteLine("Vertices: " + batcher.VerticesSubmitted);
                    Console.WriteLine("Indices: " + batcher.IndicesSubmitted);
                    Console.WriteLine("Batches: " + batcher.BatchCount);
                    Console.WriteLine();
                    frame++;
                }
            });

            renderer.Dispose();
            graphicsDevice.Dispose();
        }