예제 #1
0
        public void DrawItem(BluRayAPI.OSDTexture item)
        {
            try
            {
                lock (_syncObj)
                {
                    InitTexture(item);
                    if (_combinedOsdSurface != null)
                    {
                        Rectangle sourceRect = new Rectangle(0, 0, item.Width, item.Height);
                        Rectangle dstRect    = new Rectangle(item.X, item.Y, item.Width, item.Height);

                        using (Texture itemTexture = new Texture(item.Texture))
                            _device.StretchRectangle(itemTexture.GetSurfaceLevel(0), sourceRect, _combinedOsdSurface, dstRect, TextureFilter.None);
                    }
                }
            }
            catch (Exception ex)
            {
                BluRayPlayerBuilder.LogError(ex.ToString());
            }

            if (_onTextureInvalidated != null)
            {
                _onTextureInvalidated();
            }
        }
예제 #2
0
        /// <summary>
        /// Draw Sprite
        /// </summary>
        /// <param name="spriteTexture">The texture that will be used</param>
        /// <param name="destRect">The destination rectangle = drawing translation offset + scaling</param>
        /// <param name="color">Color Modifiers</param>
        /// <param name="textureArrayIndex"> </param>
        public void Draw(SpriteTexture spriteTexture, ref Rectangle destRect, ref ByteColor color, int textureArrayIndex = 0, int drawGroupId = 0)
        {
            Vector2 position = new Vector2(destRect.X, destRect.Y);
            Vector2 size     = new Vector2(destRect.Width, destRect.Height);

            Draw(spriteTexture, ref position, ref size, ref color, textureArrayIndex, drawGroupId);
        }
예제 #3
0
파일: Util.cs 프로젝트: qkwlqk/EloBuddy
        public static void Init(EventArgs args = null)
        {
            Core.DelayAction(() =>
            {

                float mmul =
                    new Vector3(1000, 1000, 0).WorldToMinimap().Distance(new Vector3(2000, 1000, 0).WorldToMinimap()) /
                    1000f;
                if (mmul <= 0.0000001)
                    Init();
                else
                {
                    MinimapMul = mmul;
                    Vector2 leftUpper;
                    Vector2 rightLower;
                    if (Game.MapId == GameMapId.CrystalScar)
                    {
                        leftUpper = new Vector3(0, 13800, 0).WorldToMinimap();
                        rightLower = new Vector3(13800, 0, 0).WorldToMinimap();
                    }
                    else
                    {
                        leftUpper = new Vector3(0, 14800, 0).WorldToMinimap();
                        rightLower = new Vector3(14800, 0, 0).WorldToMinimap();
                    }

                    MinimapRectangle = new Rectangle((int)leftUpper.X, (int)leftUpper.Y,
                        (int)(rightLower.X - leftUpper.X), (int)(rightLower.Y - leftUpper.Y));
                }

            }, 1000);
        }
예제 #4
0
        /// <summary>
        /// Function to perform the creation of a specific kind of view.
        /// </summary>
        /// <returns>The view that was created.</returns>
        private protected override D3D11.ResourceView OnCreateNativeView()
        {
            Graphics.Log.Print($"Render Target 3D View '{Texture.Name}': Creating D3D11 render target view.", LoggingLevel.Simple);

            var desc = new D3D11.RenderTargetViewDescription1
            {
                Format    = (Format)Format,
                Dimension = D3D11.RenderTargetViewDimension.Texture3D,
                Texture3D =
                {
                    DepthSliceCount = DepthSliceCount,
                    FirstDepthSlice = StartDepthSlice,
                    MipSlice        = MipSlice
                }
            };

            MipWidth  = (Width >> MipSlice).Max(1);
            MipHeight = (Height >> MipSlice).Max(1);

            Bounds = new DX.Rectangle(0, 0, Width, Height);

            Graphics.Log.Print($"Render Target 3D View '{Texture.Name}': {Texture.ResourceType} -> Mip slice: {MipSlice}, Starting depth slide: {StartDepthSlice}, Depth slice count: {DepthSliceCount}",
                               LoggingLevel.Verbose);

            Native = new D3D11.RenderTargetView1(Texture.Graphics.D3DDevice, Texture.D3DResource, desc)
            {
                DebugName = $"'{Texture.Name}'_D3D11RenderTargetView1_3D"
            };

            return(Native);
        }
예제 #5
0
 public static void DrawTransformedSprite(Sprite sprite, Texture texture, Rectangle spriteResize, Color color)
 {
     if (sprite != null && texture != null)
     {
         sprite.Draw(texture, color);
     }
 }
예제 #6
0
        /// <summary>
        /// Function to build builds from the font information.
        /// </summary>
        /// <param name="textures">The list of textures loaded.</param>
        /// <param name="fontInfo">The font information to retrieve glyph data from.</param>
        /// <returns>A new list of glyphs.</returns>
        private IReadOnlyList <GorgonGlyph> GetGlyphs(IReadOnlyList <GorgonTexture2D> textures, BmFontInfo fontInfo)
        {
            var glyphs = new List <GorgonGlyph>();

            foreach (char character in fontInfo.Characters)
            {
                int advance = fontInfo.CharacterAdvances[character];

                // Build a glyph that is not linked to a texture if it's whitespace.
                if (char.IsWhiteSpace(character))
                {
                    glyphs.Add(CreateGlyph(character, advance));
                    continue;
                }

                int             textureIndex = fontInfo.GlyphTextureIndices[character];
                GorgonTexture2D texture      = textures[textureIndex];

                DX.Rectangle glyphRectangle = fontInfo.GlyphRects[character];
                DX.Point     offset         = fontInfo.GlyphOffsets[character];

                GorgonGlyph glyph = CreateGlyph(character, advance);
                glyph.Offset = offset;
                glyph.UpdateTexture(texture, glyphRectangle, DX.Rectangle.Empty, 0);

                glyphs.Add(glyph);
            }

            return(glyphs);
        }
예제 #7
0
        /// <summary>
        /// Function to convert a rectangle of pixel coordinates to texel space.
        /// </summary>
        /// <param name="pixelCoordinates">The pixel coordinates to convert.</param>
        /// <param name="mipLevel">[Optional] The mip level to use.</param>
        /// <returns>A rectangle containing the texel space coordinates.</returns>
        /// <remarks>
        /// <para>
        /// If specified, the <paramref name="mipLevel"/> only applies to the <see cref="MipSlice"/> and <see cref="MipCount"/> for this view, it will be constrained if it falls outside of that range.
        /// Because of this, the coordinates returned may not be the exact size of the texture bound to the view at mip level 0. If the <paramref name="mipLevel"/> is omitted, then the first mip level
        /// for the underlying <see cref="Texture"/> is used.
        /// </para>
        /// </remarks>
        public DX.RectangleF ToTexel(DX.Rectangle pixelCoordinates, int?mipLevel = null)
        {
            float width  = Texture.Width;
            float height = Texture.Height;

            if (mipLevel == null)
            {
                return(new DX.RectangleF
                {
                    Left = pixelCoordinates.Left / width,
                    Top = pixelCoordinates.Top / height,
                    Right = pixelCoordinates.Right / width,
                    Bottom = pixelCoordinates.Bottom / height
                });
            }

            width  = GetMipWidth(mipLevel.Value);
            height = GetMipHeight(mipLevel.Value);

            return(new DX.RectangleF
            {
                Left = pixelCoordinates.Left / width,
                Top = pixelCoordinates.Top / height,
                Right = pixelCoordinates.Right / width,
                Bottom = pixelCoordinates.Bottom / height
            });
        }
예제 #8
0
        private void RetrieveFrameMetadata(DesktopFrame frame)
        {
            if (_frameInfo.TotalMetadataBufferSize > 0)
            {
                // Get moved regions
                int movedRegionsLength;
                OutputDuplicateMoveRectangle[] movedRectangles = new OutputDuplicateMoveRectangle[_frameInfo.TotalMetadataBufferSize];
                _outputDuplication.GetFrameMoveRects(movedRectangles.Length, movedRectangles, out movedRegionsLength);
                frame.MovedRegions = new MovedRegion[movedRegionsLength / Marshal.SizeOf(typeof(OutputDuplicateMoveRectangle))];
                for (int i = 0; i < frame.MovedRegions.Length; i++)
                {
                    frame.MovedRegions[i] = new MovedRegion()
                    {
                        Source      = new System.Drawing.Point(movedRectangles[i].SourcePoint.X, movedRectangles[i].SourcePoint.Y),
                        Destination = new System.Drawing.Rectangle(movedRectangles[i].DestinationRect.X, movedRectangles[i].DestinationRect.Y, movedRectangles[i].DestinationRect.Width, movedRectangles[i].DestinationRect.Height)
                    };
                }

                // Get dirty regions
                int         dirtyRegionsLength;
                Rectangle[] dirtyRectangles = new Rectangle[_frameInfo.TotalMetadataBufferSize];
                _outputDuplication.GetFrameDirtyRects(dirtyRectangles.Length, dirtyRectangles, out dirtyRegionsLength);
                frame.UpdatedRegions = new System.Drawing.Rectangle[dirtyRegionsLength / Marshal.SizeOf(typeof(Rectangle))];
                for (int i = 0; i < frame.UpdatedRegions.Length; i++)
                {
                    frame.UpdatedRegions[i] = new System.Drawing.Rectangle(dirtyRectangles[i].X, dirtyRectangles[i].Y, dirtyRectangles[i].Width, dirtyRectangles[i].Height);
                }
            }
            else
            {
                frame.MovedRegions   = new MovedRegion[0];
                frame.UpdatedRegions = new System.Drawing.Rectangle[0];
            }
        }
예제 #9
0
파일: Form.cs 프로젝트: ishkang/Gorgon
        /// <summary>
        /// Function called during idle time.
        /// </summary>
        /// <returns><b>true</b> to continue execution, <b>false</b> to stop.</returns>
        private bool Idle()
        {
            _swap.RenderTargetView.Clear(GorgonColor.White);

            var windowSize = new DX.Size2F(ClientSize.Width, ClientSize.Height);
            var imageSize  = new DX.Size2F(_texture.Width, _texture.Height);

            // Calculate the scale between the images.
            var scale = new DX.Size2F(windowSize.Width / imageSize.Width, windowSize.Height / imageSize.Height);

            // Only scale on a single axis if we don't have a 1:1 aspect ratio.
            if (scale.Height > scale.Width)
            {
                scale.Height = scale.Width;
            }
            else
            {
                scale.Width = scale.Height;
            }

            // Scale the image.
            var size = new DX.Size2((int)(scale.Width * imageSize.Width), (int)(scale.Height * imageSize.Height));

            // Find the position.
            var bounds = new DX.Rectangle((int)((windowSize.Width / 2) - (size.Width / 2)), (int)((windowSize.Height / 2) - (size.Height / 2)), size.Width, size.Height);

            _graphics.DrawTexture(_texture, bounds);

            GorgonExample.BlitLogo(_graphics);

            _swap.Present(1);

            return(true);
        }
예제 #10
0
        public static void Init(EventArgs args = null)
        {
            Core.DelayAction(() =>
            {
                float mmul =
                    new Vector3(1000, 1000, 0).WorldToMinimap().Distance(new Vector3(2000, 1000, 0).WorldToMinimap()) /
                    1000f;
                if (mmul <= 0.0000001)
                {
                    Init();
                }
                else
                {
                    MinimapMul = mmul;
                    Vector2 leftUpper;
                    Vector2 rightLower;
                    if (Game.MapId == GameMapId.CrystalScar)
                    {
                        leftUpper  = new Vector3(0, 13800, 0).WorldToMinimap();
                        rightLower = new Vector3(13800, 0, 0).WorldToMinimap();
                    }
                    else
                    {
                        leftUpper  = new Vector3(0, 14800, 0).WorldToMinimap();
                        rightLower = new Vector3(14800, 0, 0).WorldToMinimap();
                    }

                    MinimapRectangle = new Rectangle((int)leftUpper.X, (int)leftUpper.Y,
                                                     (int)(rightLower.X - leftUpper.X), (int)(rightLower.Y - leftUpper.Y));
                }
            }, 1000);
        }
예제 #11
0
        /// <summary>
        /// Function to perform the creation of a specific kind of view.
        /// </summary>
        /// <returns>The view that was created.</returns>
        private protected override D3D11.ResourceView OnCreateNativeView()
        {
            Graphics.Log.Print($"Render Target 2D View '{Texture.Name}': Creating D3D11 render target view.", LoggingLevel.Simple);

            D3D11.RenderTargetViewDescription1 desc = GetDesc2D(!Texture.MultisampleInfo.Equals(GorgonMultisampleInfo.NoMultiSampling));

            if (desc.Dimension == D3D11.RenderTargetViewDimension.Unknown)
            {
                throw new GorgonException(GorgonResult.CannotCreate, Resources.GORGFX_ERR_VIEW_CANNOT_BIND_UNKNOWN_RESOURCE);
            }

            MipWidth  = (Width >> MipSlice).Max(1);
            MipHeight = (Height >> MipSlice).Max(1);

            Bounds = new DX.Rectangle(0, 0, Width, Height);

            Graphics.Log.Print($"Render Target 2D View '{Texture.Name}': {Texture.ResourceType} -> Mip slice: {MipSlice}, Array Index: {ArrayIndex}, Array Count: {ArrayCount}",
                               LoggingLevel.Verbose);

            Native = new D3D11.RenderTargetView1(Texture.Graphics.D3DDevice, Texture.D3DResource, desc)
            {
                DebugName = $"'{Texture.Name}'_D3D11RenderTargetView1_2D"
            };

            return(Native);
        }
예제 #12
0
        /// <summary>
        /// Function to set a scissor rectangle clipping rectangle.
        /// </summary>
        /// <param name="rectangle">Rectangle to set.</param>
        /// <remarks>Scissor rectangles define a 2D area on the render target that can be used for clipping.  That is, all pixels outside of the rectangle will be discarded.
        /// <para>To use scissor rectangles, set the <see cref="GorgonLibrary.Graphics.GorgonRasterizerStates.IsScissorTestingEnabled">IsScissorTestingEnabled</see>
        /// state to TRUE. If the state is set to FALSE, this value will have no effect.</para>
        /// <para>This method will only set the first scissor test rectangle.</para>
        /// </remarks>
        public void SetScissorRectangle(Rectangle rectangle)
        {
            if ((_clipRects == null) || (_clipRects.Length != 1))
            {
                _clipRects = new[]
                {
                    rectangle
                };
                _dxRects = new[]
                {
                    DX.Rectangle.Empty
                };
            }
            else
            {
                if (_clipRects[0] == rectangle)
                {
                    return;
                }

                _clipRects[0] = rectangle;
                _dxRects[0]   = new DX.Rectangle(rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Bottom);
            }

            Graphics.Context.Rasterizer.SetScissorRectangle(rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Bottom);
        }
예제 #13
0
        /// <summary>
        /// Function to convert a rectangle of pixel coordinates to texel space.
        /// </summary>
        /// <param name="pixelCoordinates">The pixel coordinates to convert.</param>
        /// <returns>A rectangle containing the texel space coordinates.</returns>
        public DX.RectangleF ToTexel(DX.Rectangle pixelCoordinates)
        {
            float width  = Texture.Width;
            float height = Texture.Height;

            return(new DX.RectangleF(pixelCoordinates.X / width, pixelCoordinates.Y / height, pixelCoordinates.Width / width, pixelCoordinates.Height / height));
        }
예제 #14
0
        private void BuildFontSheetBitmap(Font font, Graphics charGraphics, Bitmap charBitmap, Graphics fontSheetGraphics)
        {
            var whiteBrush = Brushes.White;
            var fontSheetX = 0;
            var fontSheetY = 0;

            for (var i = 0; i < NUM_CHARS; ++i)
            {
                charGraphics.Clear(Color.FromArgb(0, Color.Black));
                charGraphics.DrawString(((char)(START_CHAR + i)).ToString(), font, whiteBrush, new PointF(0.0f, 0.0f));

                var minX      = GetCharMinX(charBitmap);
                var maxX      = GetCharMaxX(charBitmap);
                var charWidth = maxX - minX + 1;

                if (fontSheetX + charWidth >= texWidth)
                {
                    fontSheetX  = 0;
                    fontSheetY += charHeight + 1;
                }

                charRects[i] = new Rectangle(fontSheetX, fontSheetY, charWidth, charHeight);

                fontSheetGraphics.DrawImage(charBitmap, fontSheetX, fontSheetY, new System.Drawing.Rectangle(minX, 0, charWidth, charHeight), GraphicsUnit.Pixel);

                fontSheetX += charWidth + 1;
            }
        }
예제 #15
0
        public void DrawByte(byte[] bytes)
        {
            //System.Drawing.Graphics graphics = this.CreateGraphics();
            //graphics.DrawImage(bmp, 10, 10);


            /*d2dContext.Target = d2dTarget;
             * d2dContext.BeginDraw();
             * SolidColorBrush solidBrush = new SolidColorBrush(d2dContext, SharpDX.Color.Coral);
             * d2dContext.FillRectangle(new SharpDX.RectangleF(50, 50, 200, 200), solidBrush);*/

            //d2dTarget.CopyFromBitmap();
            //d2dContex

            d2dContext.Target = d2dTarget;
            d2dContext.BeginDraw();
            //d2dContext.
            //SolidColorBrush solidBrush = new SolidColorBrush(d2dContext, SharpDX.Color.Coral);
            //d2dContext.FillRectangle(new SharpDX.RectangleF(50, 50, 200, 200), solidBrush);

            //SharpDX.Rectangle rect = new SharpDX.Rectangle(0, 0, dWidth, dHeight);
            //d2dTarget.CopyFromMemory(bytes, dWidth * 4, rect);
            SharpDX.Rectangle rect = new SharpDX.Rectangle(0, 0, RenderWidth(), RenderHeight());
            d2dTarget.CopyFromMemory(bytes, RenderWidth() * 4, rect);

            //BitmapProperties bp = new BitmapProperties(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied));
            //int stride = bmp.Width * sizeof(int);
            //SharpDX.Direct2D1.Bitmap newBMP = Texture2D.FromStream<Texture2D>()

            /*using (SharpDX.DataStream tempStream = new SharpDX.DataStream(bmp.Height * stride, false, true))
             * {
             *  for (int y = 0; y < bmp.Height; y++)
             *  {
             *      for (int x = 0; x < bmp.Width; x++)
             *      {
             *          System.Drawing.Color c = bmp.GetPixel(x, y);
             *          int a = c.A;
             *          int r = (c.R * a) / 255;
             *          int g = (c.G * a) / 255;
             *          int b = (c.B * a) / 255;
             *          int bgra = b | (g << 8) | (r << 16) | (a << 24);
             *          tempStream.Write(bgra);
             *      }
             *  }
             *
             *  //d2dRenderTarget.BeginDraw();
             *  //newBMP = new SharpDX.Direct2D1.Bitmap(d2dRenderTarget, new Size2(bmp.Width, bmp.Height), tempStream, stride, bp);
             *  //d2dRenderTarget.EndDraw();
             * }*/


            //rect, 1.0f, SharpDX.Direct2D1.InterpolationMode.Linear
            //SharpDX.Mathematics.Interop.RawRectangleF rect = new SharpDX.Mathematics.Interop.RawRectangleF(50, 50, dWidth + 50, dHeight + 50);
            //d2dContext.DrawBitmap(bmp, rect, 1.0f, SharpDX.Direct2D1.InterpolationMode.Linear);
            //d2dContext.DrawBitmap(bmp, 1.0f, SharpDX.Direct2D1.InterpolationMode.Linear);
            d2dContext.EndDraw();

            //newBMP.Dispose();
        }
예제 #16
0
파일: Window.cs 프로젝트: pipe01/EloBuddy
 private void DrawRectangle(Rectangle rect, Color borderColor)
 {
     Line.DrawLine(borderColor,
                   PointToVector2(rect.Location),
                   new Vector2(rect.X, rect.Y + rect.Height),
                   new Vector2(rect.X + rect.Width, rect.Y + rect.Width),
                   new Vector2(rect.X + rect.Width, rect.Y));
 }
예제 #17
0
 /// <summary>
 ///     Calculates the center position for the given text on within a rectangle boundaries.
 /// </summary>
 /// <param name="rectangle">Rectangle boundaries</param>
 /// <param name="sprite">Sprite which is being drawn on</param>
 /// <param name="text">The Text</param>
 /// <param name="flags">Centered Flags</param>
 /// <returns>Returns the center position of the text on the rectangle.</returns>
 public static Vector2 GetCenteredText(
     this SharpDX.Rectangle rectangle,
     Sprite sprite,
     string text,
     CenteredFlags flags)
 {
     return(rectangle.GetCenter(sprite, Constants.LeagueSharpFont.MeasureText(sprite, text, 0), flags));
 }
예제 #18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GlyphInfo"/> class.
 /// </summary>
 /// <param name="glyphBitmap">The glyph bitmap.</param>
 /// <param name="region">The region.</param>
 /// <param name="offset">The offset.</param>
 /// <param name="outlineRegion">The outline region.</param>
 /// <param name="outlineOffset">The outline offset.</param>
 public GlyphInfo(Bitmap glyphBitmap, DX.Rectangle region, DX.Point offset, DX.Rectangle outlineRegion, DX.Point outlineOffset)
 {
     GlyphBitmap   = glyphBitmap;
     Region        = region;
     Offset        = offset;
     OutlineRegion = outlineRegion;
     OutlineOffset = outlineOffset;
 }
예제 #19
0
 public Sprite(Rectangle sourceRect, Rectangle destRect, Color4 color)
 {
     SrcRect  = sourceRect;
     DestRect = destRect;
     Color    = color;
     Z        = 0.0f;
     Angle    = 0.0f;
     Scale    = 1.0f;
 }
예제 #20
0
        public void Draw(SpriteTexture spriteTexture, ref Rectangle destRect, ref Rectangle srcRect, ref ByteColor color, float textureRotation, SamplerState sampler, int textureArrayIndex = 0, bool sourceRectInTextCoord = true, int drawGroupId = 0)
        {
            Vector2 position = new Vector2(destRect.Left, destRect.Top);
            Vector2 size     = new Vector2(destRect.Width, destRect.Height);

            var src = new RectangleF(srcRect.Left, srcRect.Top, srcRect.Width, srcRect.Height);

            _spriteBuffer.AddSprite(spriteTexture, sampler, ref position, ref size, ref src, sourceRectInTextCoord, textureArrayIndex, ref color, drawGroupId, textureRotation, float.NaN);
        }
예제 #21
0
        public void DrawWithWrapping(SpriteTexture spriteTexture, ref Rectangle destRect, ref Rectangle srcRect, ref ByteColor color, int textureArrayIndex = 0, bool sourceRectInTextCoord = true, int drawGroupId = 0)
        {
            Vector2 position = new Vector2(destRect.Left, destRect.Top);
            Vector2 size     = new Vector2(destRect.Width, destRect.Height);

            var src = new RectangleF(srcRect.Left, srcRect.Top, srcRect.Width, srcRect.Height);

            _spriteBuffer.AddWrappingSprite(spriteTexture, _spriteSamplerWrap, ref position, ref size, ref src, textureArrayIndex, ref color, drawGroupId);
        }
예제 #22
0
        public void DrawCustomTexture(SpriteTexture customTex, ref Rectangle textureSourceRect, ref RectangleF bounds, int groupId = 0)
        {
            var offset            = new UniRectangle(0, 0, bounds.Width, bounds.Height);
            var destinationRegion = calculateDestinationRectangle(
                ref bounds, ref offset
                );

            spriteRenderer.Draw(customTex, ref destinationRegion, ref textureSourceRect, ref _defaultColor, groupId);
        }
예제 #23
0
        public static void DrawText(Font font, String text, int posX, int posY, Color color)
        {
            Rectangle rec = font.MeasureText(null, text, FontDrawFlags.Center);

            font.DrawText(null, text, posX + 1 + rec.X, posY + 1, Color.Black);
            font.DrawText(null, text, posX + rec.X, posY + 1, Color.Black);
            font.DrawText(null, text, posX - 1 + rec.X, posY - 1, Color.Black);
            font.DrawText(null, text, posX + rec.X, posY - 1, Color.Black);
            font.DrawText(null, text, posX + rec.X, posY, color);
        }
예제 #24
0
        public void DrawBytes(byte[] bytes)
        {
            d2dContext.Target = d2dTarget;
            d2dContext.BeginDraw();

            SharpDX.Rectangle rect = new SharpDX.Rectangle(0, 0, RenderWidth, RenderHeight);
            d2dTarget.CopyFromMemory(bytes, RenderWidth * 4, rect);

            d2dContext.EndDraw();
        }
예제 #25
0
파일: Font.cs 프로젝트: loreggia/SharpDX
        /// <summary>
        /// Draw formatted text.
        /// </summary>
        /// <remarks>
        /// The parameters of this method are very similar to those of the {{GDI DrawText}} function. This method supports both ANSI and Unicode strings. Unless the DT_NOCLIP format is used, this method clips the text so that it does not appear outside the specified rectangle. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is specified. If the selected font is too large for the rectangle, this method does not attempt to substitute a smaller font. This method supports only fonts whose escapement and orientation are both zero.
        /// </remarks>
        /// <param name="sprite">Reference to an ID3DX10Sprite object that contains the string you wish to draw. Can be NULL, in which case Direct3D will render the string with its own sprite object. To improve efficiency, a sprite object should be specified if ID3DX10Font::DrawText is to be called more than once in a row. </param>
        /// <param name="text">Pointer to a string to draw. If UNICODE is defined, this parameter type resolves to an LPCWSTR, otherwise, the type resolves to an LPCSTR. If the Count parameter is -1, the string must be NULL terminated. </param>
        /// <param name="rect">Pointer to a <see cref="SharpDX.Rectangle"/> structure that contains the rectangle, in logical coordinates, in which the text is to be formatted. As with any RECT object, the coordinate value of the rectangle's right side must be greater than that of its left side. Likewise, the coordinate value of the bottom must be greater than that of the top. </param>
        /// <param name="drawFlags">Specify the method of formatting the text. It can be any combination of the following values:    ItemDescription  DT_BOTTOM  Justify the text to the bottom of the rectangle. This value must be combined with DT_SINGLELINE.   DT_CALCRECT  Tell DrawText to automatically calculate the width and height of the rectangle based on the length of the string you tell it to draw. If there are multiple lines of text, ID3DX10Font::DrawText uses the width of the rectangle pointed to by the pRect parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, ID3DX10Font::DrawText modifies the right side of the rectangle so that it bounds the last character in the line. In either case, ID3DX10Font::DrawText returns the height of the formatted text but does not draw the text.   DT_CENTER  Center text horizontally in the rectangle.   DT_EXPANDTABS  Expand tab characters. The default number of characters per tab is eight.   DT_LEFT  Align text to the left.   DT_NOCLIP  Draw without clipping. ID3DX10Font::DrawText is somewhat faster when DT_NOCLIP is used.   DT_RIGHT  Align text to the right.   DT_RTLREADING  Display text in right-to-left reading order for bidirectional text when a Hebrew or Arabic font is selected. The default reading order for all text is left-to-right.   DT_SINGLELINE  Display text on a single line only. Carriage returns and line feeds do not break the line.   DT_TOP  Top-justify text.   DT_VCENTER  Center text vertically (single line only).   DT_WORDBREAK  Break words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the pRect parameter. A carriage return/line feed sequence also breaks the line.   ? </param>
        /// <param name="color">Color of the text. See <see cref="SharpDX.Color4"/>. </param>
        /// <returns>If the function succeeds, the return value is the height of the text in logical units. If DT_VCENTER or DT_BOTTOM is specified, the return value is the offset from pRect (top to the bottom) of the drawn text. If the function fails, the return value is zero. </returns>
        /// <unmanaged>int ID3DX10Font::DrawTextW([None] LPD3DX10SPRITE pSprite,[None] const wchar_t* pString,[None] int Count,[None] RECT* pRect,[None] int Format,[None] D3DXCOLOR Color)</unmanaged>
        public unsafe int DrawText(SharpDX.Direct3D10.Sprite sprite, string text, SharpDX.Rectangle rect, FontDrawFlags drawFlags, SharpDX.Color4 color)
        {
            int value = DrawText(sprite, text, text.Length, new IntPtr(&rect), (int)drawFlags, color);

            if (value == 0)
            {
                throw new SharpDXException("Draw failed");
            }
            return(value);
        }
예제 #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GorgonRenderTarget3DView" /> class.
 /// </summary>
 /// <param name="texture">The render target texture to bind.</param>
 /// <param name="format">The format of the render target view.</param>
 /// <param name="formatInfo">The format information.</param>
 /// <param name="mipSlice">The mip slice to use in the view.</param>
 /// <param name="startDepthSlice">The first depth slice to use in the view.</param>
 /// <param name="depthSliceCount">The number of depth slices to use in the view.</param>
 internal GorgonRenderTarget3DView(GorgonTexture3D texture, BufferFormat format, GorgonFormatInfo formatInfo, int mipSlice, int startDepthSlice, int depthSliceCount)
     : base(texture, format, formatInfo)
 {
     Texture         = texture;
     MipSlice        = mipSlice;
     StartDepthSlice = startDepthSlice;
     DepthSliceCount = depthSliceCount;
     MipWidth        = (Width >> MipSlice).Max(1);
     MipHeight       = (Height >> MipSlice).Max(1);
     Bounds          = new DX.Rectangle(0, 0, Width, Height);
 }
예제 #27
0
        /// <summary>
        /// Function to crop the image to the rectangle passed to the parameters.
        /// </summary>
        /// <param name="baseImage">The image to resize.</param>
        /// <param name="cropRect">The rectangle that will be used to crop the image.</param>
        /// <param name="newDepth">The new depth for the image (for <see cref="ImageType.Image3D"/> images).</param>
        /// <returns>A <see cref="IGorgonImage"/> containing the resized image.</returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="baseImage"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown if the <paramref name="newDepth"/> parameter is less than 1.</exception>
        /// <remarks>
        /// <para>
        /// This method will crop the existing image a smaller version of itself as a new <see cref="IGorgonImage"/>. If the sizes are the same, or the <paramref name="cropRect"/> is larger than the size
        /// of the <paramref name="baseImage"/>, then no changes will be made.
        /// </para>
        /// </remarks>
        public static IGorgonImage Crop(this IGorgonImage baseImage, DX.Rectangle cropRect, int newDepth)
        {
            if (baseImage == null)
            {
                throw new ArgumentNullException(nameof(baseImage));
            }

            if ((newDepth < 1) && (baseImage.ImageType == ImageType.Image3D))
            {
                throw new ArgumentOutOfRangeException(Resources.GORIMG_ERR_IMAGE_DEPTH_TOO_SMALL, nameof(newDepth));
            }

            // Only use the appropriate dimensions.
            switch (baseImage.ImageType)
            {
            case ImageType.Image1D:
                cropRect.Height = baseImage.Height;
                break;

            case ImageType.Image2D:
            case ImageType.ImageCube:
                newDepth = baseImage.Depth;
                break;
            }

            // If the intersection of the crop rectangle and the source buffer are the same (and the depth is the same), then we don't need to crop.
            var bufferRect = new DX.Rectangle(0, 0, baseImage.Width, baseImage.Height);
            var clipRect   = DX.Rectangle.Intersect(cropRect, bufferRect);

            if ((bufferRect.Equals(ref clipRect)) && (newDepth == baseImage.Depth))
            {
                return(baseImage);
            }

            var wic = new WicUtilities();

            IGorgonImage newImage = null;

            try
            {
                int calcMipLevels = GorgonImage.CalculateMaxMipCount(cropRect.Width, cropRect.Height, newDepth).Min(baseImage.MipCount);
                newImage = wic.Resize(baseImage, cropRect.X, cropRect.Y, cropRect.Width, cropRect.Height, newDepth, calcMipLevels, ImageFilter.Point, ResizeMode.Crop);

                // Send the data over to the new image.
                newImage.CopyTo(baseImage);

                return(baseImage);
            }
            finally
            {
                newImage?.Dispose();
                wic.Dispose();
            }
        }
예제 #28
0
 /// <summary>
 ///     Calculates the center position for the given text on within a rectangle boundaries.
 /// </summary>
 /// <param name="rectangle">Rectangle boundaries</param>
 /// <param name="sprite">Sprite which is being drawn on</param>
 /// <param name="font">Text Font</param>
 /// <param name="text">The Text</param>
 /// <param name="flags">Centered Flags</param>
 /// <returns>Returns the center position of the text on the rectangle.</returns>
 public static Vector2 GetCenteredText(
     this SharpDX.Rectangle rectangle,
     Sprite sprite,
     Font font,
     string text,
     CenteredFlags flags)
 {
     return(font == null
                ? rectangle.GetCenteredText(sprite, text, flags)
                : rectangle.GetCenter(sprite, font.MeasureText(sprite, text, 0), flags));
 }
예제 #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GorgonRenderTarget2DView" /> class.
 /// </summary>
 /// <param name="texture">The render target texture to bind.</param>
 /// <param name="format">The format of the render target view.</param>
 /// <param name="formatInfo">The format information.</param>
 /// <param name="mipSlice">The mip slice to use in the view.</param>
 /// <param name="arrayIndex">The first array index to use in the view.</param>
 /// <param name="arrayCount">The number of array indices to use in the view.</param>
 internal GorgonRenderTarget2DView(GorgonTexture2D texture, BufferFormat format, GorgonFormatInfo formatInfo, int mipSlice, int arrayIndex, int arrayCount)
     : base(texture, format, formatInfo)
 {
     Texture    = texture;
     MipSlice   = mipSlice;
     ArrayIndex = arrayIndex;
     ArrayCount = arrayCount;
     MipWidth   = (Width >> MipSlice).Max(1);
     MipHeight  = (Height >> MipSlice).Max(1);
     Bounds     = new DX.Rectangle(0, 0, Width, Height);
 }
예제 #30
0
            public override bool Draw()
            {
                var rect = new SharpDX.Rectangle((int)MainMenu.Position.X + 160, (int)MainMenu.Position.Y + 95 + 50, 750, 380);

                if (MainMenu.IsVisible && IsVisible && rect.IsInside(Position))
                {
                    _colorOverlaySprite.Color = SelectedColor;
                    _colorOverlaySprite.Draw(new Vector2(Position.X + 522 + 1, Position.Y - 34 + 1));
                    return(true);
                }
                return(false);
            }
예제 #31
0
        private void GetDirtyAndMoveRects(ref FrameData data, Resource screenResource,
                                          OutputDuplicateFrameInformation duplicateFrameInformation)
        {
            //copy resource into memory that can be accessed by the CPU
            using (var screenTexture2D = screenResource.QueryInterface <Texture2D>())
                device.ImmediateContext.CopyResource(screenTexture2D, screenTexture);
            screenResource.Dispose();

            int bufSize = duplicateFrameInformation.TotalMetadataBufferSize;

            if (bufSize <= 0)
            {
                return;
            }

            var moveRectangles =
                new OutputDuplicateMoveRectangle
                [
                    (int)
                    Math.Ceiling((double)bufSize /
                                 Marshal.SizeOf(typeof(OutputDuplicateMoveRectangle)))
                ];

            Console.WriteLine("Move : {0}  {1}  {2}  {3}", moveRectangles.Length, bufSize,
                              Marshal.SizeOf(typeof(OutputDuplicateMoveRectangle)),
                              bufSize / Marshal.SizeOf(typeof(OutputDuplicateMoveRectangle)));

            //get move rects
            if (moveRectangles.Length > 0)
            {
                duplicatedOutput.GetFrameMoveRects(bufSize, moveRectangles, out bufSize);
            }

            data.MoveRectangles = moveRectangles;
            data.MoveCount      = bufSize;

            bufSize = duplicateFrameInformation.TotalMetadataBufferSize - bufSize;
            var dirtyRectangles = new Rectangle[bufSize / Marshal.SizeOf(typeof(Rectangle))];

            Console.WriteLine("Dirty : {0}  {1}  {2}  {3}", dirtyRectangles.Length, bufSize,
                              Marshal.SizeOf(typeof(Rectangle)), bufSize / Marshal.SizeOf(typeof(Rectangle)));
            //get dirty rects
            if (dirtyRectangles.Length > 0)
            {
                duplicatedOutput.GetFrameDirtyRects(bufSize, dirtyRectangles, out bufSize);
            }
            data.DirtyRectangles = dirtyRectangles;
            data.DirtyCount      = bufSize;

            data.Frame = screenTexture;

            data.FrameInfo = duplicateFrameInformation;
        }
예제 #32
0
    private void InitTexture(BluRayAPI.OSDTexture item)
    {
      if (item.Width == 0 || item.Height == 0 || item.Texture == IntPtr.Zero)
      {
        FreeResources();
        return;
      }

      if (_combinedOsdTexture == null || _combinedOsdTexture.IsDisposed)
      {
        _combinedOsdTexture = new Texture(_device, _fullOsdSize.Width, _fullOsdSize.Height, 1, Usage.RenderTarget, FORMAT, Pool.Default);
        _combinedOsdSurface = _combinedOsdTexture.GetSurfaceLevel(0);

        _sprite = new Sprite(_device);

        Rectangle dstRect = new Rectangle(0, 0, _fullOsdSize.Width, _fullOsdSize.Height);
        _device.ColorFill(_combinedOsdSurface, dstRect, _transparentColor);
      }
    }
예제 #33
0
        private void EnsureResources(Device device, Texture2DDescription description, Rectangle captureRegion,
            ScreenshotRequest request)
        {
            if (_device != null && request.Resize != null &&
                (_resizedRT == null ||
                 (_resizedRT.Device.NativePointer != _device.NativePointer ||
                  _resizedRT.Description.Width != request.Resize.Value.Width ||
                  _resizedRT.Description.Height != request.Resize.Value.Height)))
            {
                // Create/Recreate resources for resizing
                RemoveAndDispose(ref _resizedRT);
                RemoveAndDispose(ref _resizedRTV);
                RemoveAndDispose(ref _saQuad);

                _resizedRT = ToDispose(new Texture2D(_device, new Texture2DDescription
                {
                    Format = Format.R8G8B8A8_UNorm, // Supports BMP/PNG/etc
                    Height = request.Resize.Value.Height,
                    Width = request.Resize.Value.Width,
                    ArraySize = 1,
                    SampleDescription = new SampleDescription(1, 0),
                    BindFlags = BindFlags.RenderTarget,
                    MipLevels = 1,
                    Usage = ResourceUsage.Default,
                    OptionFlags = ResourceOptionFlags.None
                }));

                _resizedRTV = ToDispose(new RenderTargetView(_device, _resizedRT));

                _saQuad = ToDispose(new ScreenAlignedQuadRenderer());
                _saQuad.Initialize(new DeviceManager(_device));
            }

            // Check if _resolvedRT or _finalRT require creation
            if (_finalRT != null && _finalRT.Device.NativePointer == _device.NativePointer &&
                _finalRT.Description.Height == captureRegion.Height && _finalRT.Description.Width == captureRegion.Width &&
                _resolvedRT != null && _resolvedRT.Description.Height == description.Height &&
                _resolvedRT.Description.Width == description.Width &&
                _resolvedRT.Device.NativePointer == device.NativePointer &&
                _resolvedRT.Description.Format == description.Format
                )
            {
                return;
            }

            RemoveAndDispose(ref _query);
            RemoveAndDispose(ref _resolvedRT);
            RemoveAndDispose(ref _resolvedSharedSRV);
            RemoveAndDispose(ref _finalRT);
            RemoveAndDispose(ref _resolvedRTShared);

            _query = new Query(_device, new QueryDescription
            {
                Flags = QueryFlags.None,
                Type = QueryType.Event
            });
            _queryIssued = false;

            _resolvedRT = ToDispose(new Texture2D(device, new Texture2DDescription
            {
                CpuAccessFlags = CpuAccessFlags.None,
                Format = description.Format, // for multisampled backbuffer, this must be same format
                Height = description.Height,
                Usage = ResourceUsage.Default,
                Width = description.Width,
                ArraySize = 1,
                SampleDescription = new SampleDescription(1, 0), // Ensure single sample
                BindFlags = BindFlags.ShaderResource,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.SharedKeyedmutex
            }));

            // Retrieve reference to the keyed mutex
            _resolvedRTKeyedMutex = ToDispose(_resolvedRT.QueryInterfaceOrNull<KeyedMutex>());

            using (var resource = _resolvedRT.QueryInterface<Resource>())
            {
                _resolvedRTShared = ToDispose(_device.OpenSharedResource<Texture2D>(resource.SharedHandle));
                _resolvedRTKeyedMutex_Dev2 = ToDispose(_resolvedRTShared.QueryInterfaceOrNull<KeyedMutex>());
            }

            // SRV for use if resizing
            _resolvedSharedSRV = ToDispose(new ShaderResourceView(_device, _resolvedRTShared));

            _finalRT = ToDispose(new Texture2D(_device, new Texture2DDescription
            {
                CpuAccessFlags = CpuAccessFlags.Read,
                Format = description.Format,
                Height = captureRegion.Height,
                Usage = ResourceUsage.Staging,
                Width = captureRegion.Width,
                ArraySize = 1,
                SampleDescription = new SampleDescription(1, 0),
                BindFlags = BindFlags.None,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None
            }));
            _finalRTMapped = false;
        }
예제 #34
0
        public static string SaveScreenshot(Texture tex, string file)
        {
            MyRender.Log.WriteLine("MyScreenshot.SaveTexture2D() - START");
            MyRender.Log.IncreaseIndent();

            string filename = null;

            using (Texture systemTex = new Texture(MyRender.GraphicsDevice, tex.GetLevelDescription(0).Width, tex.GetLevelDescription(0).Height, 1, Usage.None, Format.A8R8G8B8, Pool.SystemMemory))
            {
                string extension = Path.GetExtension(file);

                using (Surface sourceSurface = tex.GetSurfaceLevel(0))
                using (Surface destSurface = systemTex.GetSurfaceLevel(0))
                {
                    MyRender.GraphicsDevice.GetRenderTargetData(sourceSurface, destSurface);
                }
                
                try
                {
                    MyRender.Log.WriteLine("File: " + file);

                    Stack<SharpDX.Rectangle> tiles = new Stack<SharpDX.Rectangle>();

                    int tileWidth = systemTex.GetLevelDescription(0).Width;
                    int tileHeight = systemTex.GetLevelDescription(0).Height;

                    while (tileWidth > 3200)
                    {
                        tileWidth /= 2;
                        tileHeight /= 2;
                    }

                    int widthOffset = 0;
                    int heightOffset = 0;

                    while (widthOffset < systemTex.GetLevelDescription(0).Width)
                    {
                        while (heightOffset < systemTex.GetLevelDescription(0).Height)
                        {
                            tiles.Push(new SharpDX.Rectangle(widthOffset, heightOffset, widthOffset + tileWidth, heightOffset + tileHeight));
                            heightOffset += tileHeight;
                        }

                        heightOffset = 0;
                        widthOffset += tileWidth;
                    }

                    bool multipleTiles = tiles.Count > 1;

                    int sc = 0;
                    while (tiles.Count > 0)
                    {
                        SharpDX.Rectangle rect = tiles.Pop();

                        byte[] data = new byte[rect.Width * rect.Height * 4];
                        SharpDX.Rectangle rect2 = new SharpDX.Rectangle(rect.X, rect.Y, rect.X + rect.Width, rect.Y + rect.Height);
                        //texture2D.GetData<byte>(0, rect2, data, 0, data.Length);
                        DataStream ds;
                        //DataRectangle dr = texture2D.LockRectangle(0, rect2, LockFlags.ReadOnly, out ds);
                        DataRectangle dr = systemTex.LockRectangle(0, LockFlags.ReadOnly, out ds);

                        //we have to go line by line..
                        ds.Seek(rect2.Y * systemTex.GetLevelDescription(0).Width * 4, SeekOrigin.Begin);
                        byte[] emptyLine = new byte[rect2.Width * 4];
                        byte[] line = new byte[rect2.Width * 4];
                        int targetOffset = 0;

                        int linesCount = rect2.Height;

                        int pixelsBefore = rect2.X;
                        int pixelsAfter = systemTex.GetLevelDescription(0).Width - rect2.Width - rect2.X;

                        while (linesCount-- > 0)
                        {
                            if (pixelsBefore > 0)
                                ds.Read(emptyLine, 0, pixelsBefore * 4);

                            ds.Read(line, 0, rect2.Width * 4);

                            if (pixelsAfter > 0)
                                ds.Read(emptyLine, 0, pixelsAfter * 4);

                            Array.Copy(line, 0, data, targetOffset, rect2.Width * 4);

                            targetOffset += rect2.Width * 4;
                        }


                        //ds.Read(data, 0, data.Length);
                        /*
                for (int i = 0; i < data.Length; i += 4)
                {
                    //Swap ARGB <-> RGBA
                    byte b = data[i + 0];
                    byte g = data[i + 1];
                    byte r = data[i + 2];
                    byte a = data[i + 3];
                    data[i + 0] = r;  //Blue
                    data[i + 1] = g; //Green
                    data[i + 2] = b; //Red
                    data[i + 3] = a; //Alpha
                }         */

                        //ds.Seek(0, SeekOrigin.Begin);
                        //ds.WriteRange(data);

                        systemTex.UnlockRectangle(0);

                        filename = file;

                        if (multipleTiles)
                        {
                            filename = file.Replace(extension, "_" + sc.ToString("##00") + extension);
                        }

                        using (var stream = MyFileSystem.OpenWrite(MyFileSystem.UserDataPath, filename))
                        {
                            using (System.Drawing.Bitmap image = new System.Drawing.Bitmap(rect.Width, rect.Height))
                            {
                                System.Drawing.Imaging.BitmapData imageData = image.LockBits(new System.Drawing.Rectangle(0, 0, rect.Width, rect.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                                System.Runtime.InteropServices.Marshal.Copy(data, 0, imageData.Scan0, data.Length);

                                if (extension == ".png")
                                    image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                                else if (extension == ".jpg" || extension == ".jpeg")
                                    image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                                else if (extension == ".bmp")
                                    image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
                                else
                                    throw new InvalidOperationException("Invalid file extension: " + extension + ", please use png, jpg or bmp");

                                image.UnlockBits(imageData);
                            }

                            //texture2D.SaveAsPng(stream, texture2D.Width, texture2D.Height);
                            //BaseTexture.ToStream(texture2D, ImageFileFormat.Png);
                        }

                        sc++;
                        GC.Collect();
                    }
                }
                catch (Exception exc)
                {
                    //  Write exception to log, but continue as if nothing wrong happened
                    MyRender.Log.WriteLine(exc);
                    filename = null;
                }
            }
            //BaseTexture.ToFile(texture2D, "c:\\test.png", ImageFileFormat.Png);

            MyRender.Log.DecreaseIndent();
            MyRender.Log.WriteLine("MyScreenshot.SaveTexture2D() - END");

            return filename;
        }
        /// <inveritdoc/>
        public override void RenderAll()
        {
            SurfaceViewData viewData = null;

            var regionToDraw = new SharpDX.Rectangle(0, 0, pixelWidth, pixelHeight);

            // Unlike other targets, we can only get the DXGI surface to render to
            // just before rendering.
            using (var surface = surfaceImageSourceNative.BeginDraw(regionToDraw, out position))
            {
                // Cache DXGI surface in order to avoid recreate all render target view, depth stencil...etc.
                // Is it the right way to do it?
                // It seems that ISurfaceImageSourceNative.BeginDraw is returning 2 different DXGI surfaces (when the application is in foreground)
                // or different DXGI surfaces (when the application is in background).
                foreach (var surfaceViewData in viewDatas)
                {
                    if (surfaceViewData.SurfacePointer == surface.NativePointer)
                    {
                        viewData = surfaceViewData;
                        break;
                    }
                }

                if (viewData == null)
                {
                    viewData = viewDatas[nextViewDataIndex];
                    nextViewDataIndex = (nextViewDataIndex + 1) % viewDatas.Length;

                    // Make sure that previous was disposed.
                    viewData.Dispose();
                    viewData.SurfacePointer = surface.NativePointer;

                    // Allocate a new renderTargetView if size is different
                    // Cache the rendertarget dimensions in our helper class for convenient use.
                    viewData.BackBuffer = surface.QueryInterface<SharpDX.Direct3D11.Texture2D>();
                    {
                        var desc = viewData.BackBuffer.Description;
                        viewData.RenderTargetSize = new Size(desc.Width, desc.Height);
                        viewData.RenderTargetView = new SharpDX.Direct3D11.RenderTargetView(DeviceManager.DeviceDirect3D, viewData.BackBuffer);
                    }

                    // Create a descriptor for the depth/stencil buffer.
                    // Allocate a 2-D surface as the depth/stencil buffer.
                    // Create a DepthStencil view on this surface to use on bind.
                    // TODO: Recreate a DepthStencilBuffer is inefficient. We should only have one depth buffer. Shared depth buffer?
                    using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(DeviceManager.DeviceDirect3D, new SharpDX.Direct3D11.Texture2DDescription()
                    {
                        Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                        ArraySize = 1,
                        MipLevels = 1,
                        Width = (int)viewData.RenderTargetSize.Width,
                        Height = (int)viewData.RenderTargetSize.Height,
                        SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                        BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
                    }))
                        viewData.DepthStencilView = new SharpDX.Direct3D11.DepthStencilView(DeviceManager.DeviceDirect3D, depthBuffer, new SharpDX.Direct3D11.DepthStencilViewDescription() { Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D });

                    // Now we set up the Direct2D render target bitmap linked to the swapchain. 
                    // Whenever we render to this bitmap, it will be directly rendered to the 
                    // swapchain associated with the window.
                    var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1(
                        new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                        DeviceManager.Dpi,
                        DeviceManager.Dpi,
                        SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

                    // Direct2D needs the dxgi version of the backbuffer surface pointer.
                    // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
                    viewData.BitmapTarget = new SharpDX.Direct2D1.Bitmap1(DeviceManager.ContextDirect2D, surface, bitmapProperties);

                    // Create a viewport descriptor of the full window size.
                    viewData.Viewport = new SharpDX.ViewportF(position.X, position.Y, (float)viewData.RenderTargetSize.Width - position.X, (float)viewData.RenderTargetSize.Height - position.Y, 0.0f, 1.0f);
                }

                backBuffer = viewData.BackBuffer;
                renderTargetView = viewData.RenderTargetView;
                depthStencilView = viewData.DepthStencilView;
                RenderTargetBounds = new Rect(viewData.Viewport.X, viewData.Viewport.Y, viewData.Viewport.Width, viewData.Viewport.Height);
                bitmapTarget = viewData.BitmapTarget;

                DeviceManager.ContextDirect2D.Target = viewData.BitmapTarget;

                // Set the current viewport using the descriptor.
                DeviceManager.ContextDirect3D.Rasterizer.SetViewports(viewData.Viewport);

                // Perform the actual rendering of this target
                base.RenderAll();
            }

            surfaceImageSourceNative.EndDraw();
        }
예제 #36
0
        private unsafe int PresentHook(IntPtr devicePtr, Rectangle* pSourceRect, Rectangle* pDestRect,
            IntPtr hDestWindowOverride, IntPtr pDirtyRegion)
        {
            _isUsingPresent = true;

            var device = (Device) devicePtr;

            DoCaptureRenderTarget(device, "PresentHook");

            return Direct3DDevice_PresentHook.Original(devicePtr, pSourceRect, pDestRect, hDestWindowOverride,
                pDirtyRegion);
        }
예제 #37
0
 private DataRectangle LockRenderTarget(Surface _renderTargetCopy, out Rectangle rect)
 {
     if (_requestCopy.RegionToCapture.Height > 0 && _requestCopy.RegionToCapture.Width > 0)
     {
         rect = new Rectangle(_requestCopy.RegionToCapture.Left, _requestCopy.RegionToCapture.Top,
             _requestCopy.RegionToCapture.Width, _requestCopy.RegionToCapture.Height);
     }
     else
     {
         rect = new Rectangle(0, 0, _renderTargetCopy.Description.Width, _renderTargetCopy.Description.Height);
     }
     return _renderTargetCopy.LockRectangle(rect, LockFlags.ReadOnly);
 }
예제 #38
0
        private void BuildFontSheetBitmap(Font font, Graphics charGraphics, Bitmap charBitmap, Graphics fontSheetGraphics)
        {
            var whiteBrush = Brushes.White;
            var fontSheetX = 0;
            var fontSheetY = 0;

            for (var i = 0; i < NumChars; ++i)
            {
                charGraphics.Clear(Color.FromArgb(0, Color.Black));
                charGraphics.DrawString(((char) (StartChar + i)).ToString(), font, whiteBrush, new PointF(0.0f, 0.0f));

                var minX = GetCharMinX(charBitmap);
                var maxX = GetCharMaxX(charBitmap);
                var charWidth = maxX - minX + 1;

                if (fontSheetX + charWidth >= _texWidth)
                {
                    fontSheetX = 0;
                    fontSheetY += (int) (_charHeight) + 1;
                }

                _charRects[i] = new Rectangle(fontSheetX, fontSheetY, fontSheetX + charWidth, fontSheetY + _charHeight);

                fontSheetGraphics.DrawImage(charBitmap, fontSheetX, fontSheetY, new System.Drawing.Rectangle(minX, 0, charWidth, _charHeight), GraphicsUnit.Pixel);

                fontSheetX += charWidth + 1;
            }
        }
        private void RetrieveFrameMetadata(DesktopFrame frame)
        {

            if (frameInfo.TotalMetadataBufferSize > 0)
            {
                // Get moved regions
                int movedRegionsLength = 0;
                OutputDuplicateMoveRectangle[] movedRectangles = new OutputDuplicateMoveRectangle[frameInfo.TotalMetadataBufferSize];
                mDeskDupl.GetFrameMoveRects(movedRectangles.Length, movedRectangles, out movedRegionsLength);
                frame.MovedRegions = new MovedRegion[movedRegionsLength / Marshal.SizeOf(typeof(OutputDuplicateMoveRectangle))];
                for (int i = 0; i < frame.MovedRegions.Length; i++)
                {
                    frame.MovedRegions[i] = new MovedRegion()
                    {
                        Source = new System.Drawing.Point(movedRectangles[i].SourcePoint.X, movedRectangles[i].SourcePoint.Y),
                        Destination = new System.Drawing.Rectangle(movedRectangles[i].DestinationRect.X, movedRectangles[i].DestinationRect.Y, movedRectangles[i].DestinationRect.Width, movedRectangles[i].DestinationRect.Height)
                    };
                }

                // Get dirty regions
                int dirtyRegionsLength = 0;
                Rectangle[] dirtyRectangles = new Rectangle[frameInfo.TotalMetadataBufferSize];
                mDeskDupl.GetFrameDirtyRects(dirtyRectangles.Length, dirtyRectangles, out dirtyRegionsLength);
                frame.UpdatedRegions = new System.Drawing.Rectangle[dirtyRegionsLength / Marshal.SizeOf(typeof(Rectangle))];
                for (int i = 0; i < frame.UpdatedRegions.Length; i++)
                {
                    frame.UpdatedRegions[i] = new System.Drawing.Rectangle(dirtyRectangles[i].X, dirtyRectangles[i].Y, dirtyRectangles[i].Width, dirtyRectangles[i].Height);
                }
            }
            else
            {
                frame.MovedRegions = new MovedRegion[0];
                frame.UpdatedRegions = new System.Drawing.Rectangle[0];
            }
        }
예제 #40
0
        public static void SaveScreenshot(Texture texture2D, string file)
        {      
            MyMwcLog.WriteLine("MyScreenshot.SaveTexture2D() - START");
            MyMwcLog.IncreaseIndent();

            Texture systemTex =  new Texture(MinerWars.AppCode.App.MyMinerGame.Static.GraphicsDevice, texture2D.GetLevelDescription(0).Width, texture2D.GetLevelDescription(0).Height, 0, Usage.None, Format.A8R8G8B8, Pool.SystemMemory);


            Surface sourceSurface = texture2D.GetSurfaceLevel(0);
            Surface destSurface = systemTex.GetSurfaceLevel(0);
            MinerWars.AppCode.App.MyMinerGame.Static.GraphicsDevice.GetRenderTargetData(sourceSurface, destSurface);
            sourceSurface.Dispose();
            destSurface.Dispose();

            texture2D = systemTex;

            try
            {
                MyMwcLog.WriteLine("File: " + file);

                MyFileSystemUtils.CreateFolderForFile(file);

                Stack<SharpDX.Rectangle> tiles = new Stack<SharpDX.Rectangle>();

                int tileWidth = texture2D.GetLevelDescription(0).Width;
                int tileHeight = texture2D.GetLevelDescription(0).Height;

                while (tileWidth > 3200)
                {
                    tileWidth /= 2;
                    tileHeight /= 2;
                }

                int widthOffset = 0;
                int heightOffset = 0;

                while (widthOffset < texture2D.GetLevelDescription(0).Width)
                {
                    while (heightOffset < texture2D.GetLevelDescription(0).Height)
                    {
                        tiles.Push(new SharpDX.Rectangle(widthOffset, heightOffset, tileWidth, tileHeight));
                        heightOffset += tileHeight;
                    }

                    heightOffset = 0;
                    widthOffset += tileWidth;
                }

                int sc = 0;
                while (tiles.Count > 0)
                {
                    SharpDX.Rectangle rect = tiles.Pop();

                    byte[] data = new byte[rect.Width * rect.Height * 4];
                    SharpDX.Rectangle rect2 = new SharpDX.Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
                    //texture2D.GetData<byte>(0, rect2, data, 0, data.Length);
                    DataStream ds;
                    texture2D.LockRectangle(0, rect2, LockFlags.None, out ds); 

                    ds.Read(data, 0, data.Length);
                            /*
                    for (int i = 0; i < data.Length; i += 4)
                    {
                        //Swap ARGB <-> RGBA
                        byte b = data[i + 0];
                        byte g = data[i + 1];
                        byte r = data[i + 2];
                        byte a = data[i + 3];
                        data[i + 0] = r;  //Blue
                        data[i + 1] = g; //Green
                        data[i + 2] = b; //Red
                        data[i + 3] = a; //Alpha
                    }         */

                    ds.Seek(0, SeekOrigin.Begin);
                    ds.WriteRange(data);

                    texture2D.UnlockRectangle(0);

                    string filename = file.Replace(".png", "_" + sc.ToString("##00") + ".png");
                    using (Stream stream = File.Create(filename))
                    {        
                        System.Drawing.Bitmap image = new System.Drawing.Bitmap(rect.Width, rect.Height);

                        System.Drawing.Imaging.BitmapData imageData = image.LockBits(new System.Drawing.Rectangle(0,0,rect.Width, rect.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                        System.Runtime.InteropServices.Marshal.Copy(data, 0, imageData.Scan0, data.Length);

                        image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);

                        image.UnlockBits(imageData);
                        image.Dispose();
                               
                        //texture2D.SaveAsPng(stream, texture2D.Width, texture2D.Height);
                        //BaseTexture.ToStream(texture2D, ImageFileFormat.Png);
                    }

                    sc++;
                    GC.Collect();
                }
            }
            catch (Exception exc)
            {
                //  Write exception to log, but continue as if nothing wrong happened
                MyMwcLog.WriteLine(exc);
            }

            texture2D.Dispose();

            //BaseTexture.ToFile(texture2D, "c:\\test.png", ImageFileFormat.Png);

            MyMwcLog.DecreaseIndent();
            MyMwcLog.WriteLine("MyScreenshot.SaveTexture2D() - END");   
        }
예제 #41
0
 public static void DrawTransformedSprite(Sprite sprite, Texture texture, Rectangle spriteResize, Color color)
 {
     if (sprite != null && texture != null)
     {
         sprite.Draw(texture, color);
     }
 }
예제 #42
0
        private void OnPreviewViewportDraw(Device device, SpriteBatch spriteBatch, Rectangle cliprectangle)
        {
            UiEncodingWindowSource source = _currentSource;
            if (source == null)
                return;

            spriteBatch.Begin(SpriteSortMode.Deferred, null, _previewViewport.DxControl.RenderContainer.GraphicsDevice.SamplerStates.PointClamp, null, null, null, SharpDX.Matrix.Scaling(_scale));

            float x = 0, maxX = 0;
            float y = source.Info.Header.LineSpacing;
            int squareSize = source.Info.Header.SquareSize;
            int lineSpacing = source.Info.Header.LineHeight + source.Info.Header.LineSpacing;

            foreach (char ch in _previewText)
            {
                if (ch == '\r')
                    continue;

                if (ch == '\n')
                {
                    x = 0;
                    y += lineSpacing;
                    continue;
                }

                short index;
                if (source.Codes.TryGetValue(ch, out index))
                {
                    int ox, oy;
                    int h, w;
                    if (index < 256)
                    {
                        byte before, width, after;
                        source.Info.GetSizes(index, out before, out width, out after);
                        w = width;
                        h = source.Info.Header.LineHeight;

                        if (before > 0x7F)
                            x = Math.Max(x - (0xFF - before), 0);
                        else
                            x += before;

                        source.Info.GetOffsets(index, out ox, out oy);
                        source.Texture.Draw(device, spriteBatch, new Vector2(x, y), new Rectangle(ox, oy, w, h), 0, cliprectangle);

                        if (after > 0x7F)
                            x = Math.Max(x - (0xFF - after), 0);
                        else
                            x += after;
                    }
                    else
                    {
                        index -= 256;
                        w = h = squareSize;
                        int value = source.Info.AdditionalTable[index];
                        ox = (value & 0xFF) * squareSize;
                        oy = (value >> 8) * squareSize;
                        source.Texture.Draw(device, spriteBatch, new Vector2(x, y), new Rectangle(ox, oy, w, h), 0, cliprectangle);
                    }

                    x += w;
                    maxX = Math.Max(x, maxX);
                }
            }

            spriteBatch.End();

            double desiredWidth, desiredHeight;
            _previewViewport.GetDesiredSize(out desiredWidth, out desiredHeight);

            double newDesiredWidth = x * _scale;
            double newDesiredHeight = (y + lineSpacing) * _scale;

            if (Math.Abs(newDesiredWidth - desiredWidth) > 1 || Math.Abs(newDesiredHeight - newDesiredHeight) > 1)
                _previewViewport.SetDesiredSize(newDesiredWidth, newDesiredHeight);
        }
예제 #43
0
        private void OnEditViewportDrawPrimitives(Device device, RenderTarget target2D, Rectangle cliprectangle)
        {
            UiEncodingWindowSource source = _currentSource;

            WflContent info = source?.Info;
            if (info?.Header.TableType != WflHeader.LargeTable)
                return;

            int viewportX = _editViewport.X;
            int viewportY = _editViewport.Y;

            RectangleF rectangle = new RectangleF {Height = info.Header.LineHeight};

            target2D.BeginDraw();

            for (int i = 0; i < 256 * 2; i++)
            {
                if (i % 256 < 0x20)
                    continue;

                int x, y;
                info.GetOffsets(i, out x, out y);
                x -= viewportX;
                y -= viewportY;

                byte before, width, after;
                info.GetSizes(i, out before, out width, out after);

                rectangle.X = x;
                rectangle.Y = y;
                rectangle.Width = width & 0x7F;

                if (_charactersControl.CurrentMainIndices.Contains(i))
                {
                    target2D.FillRectangle(rectangle, _selectedColorBrush);

                    if (before > 0x7F)
                    {
                        rectangle.Width = (0xFF - before) + 1;
                        rectangle.X = x;
                    }
                    else
                    {
                        rectangle.Width = before;
                        rectangle.X = x - before;
                    }
                    target2D.FillRectangle(rectangle, _spacingColorBrush);

                    if (after > 0x7F)
                    {
                        rectangle.Width = (0xFF - after) + 1;
                        rectangle.X = x + (width & 0x7F) - rectangle.Width;
                    }
                    else
                    {
                        rectangle.Width = after;
                        rectangle.X = x + width & 0x7F;
                    }

                    target2D.FillRectangle(rectangle, _spacingColorBrush);
                }
                else if (source.Chars[i % 256] == 0x00)
                {
                    target2D.FillRectangle(rectangle, _notMappedColorBrush);
                }
                else
                {
                    target2D.DrawRectangle(rectangle, _gridColorBrush, 1.0f);
                }
            }

            int squareSize = info.Header.LineSpacing + info.Header.SquareDiff;
            rectangle.Height = squareSize;
            rectangle.Width = squareSize;
            for (int i = 0; i < info.AdditionalTable.Length; i++)
            {
                int value = info.AdditionalTable[i];
                if (value == 0)
                    continue;

                rectangle.Y = (value >> 8) * squareSize - viewportY;
                rectangle.X = (value & 0xFF) * squareSize - viewportX;

                if (_charactersControl.CurrentAdditionalIndices.Contains(i))
                    target2D.FillRectangle(rectangle, _selectedColorBrush);
                else if (source.Chars[i + 256] == 0x00)
                    target2D.FillRectangle(rectangle, _notMappedColorBrush);
                else
                    target2D.DrawRectangle(rectangle, _gridColorBrush, 1.0f);
            }

            target2D.EndDraw();
        }
예제 #44
0
    public void DrawItem(BluRayAPI.OSDTexture item)
    {
      try
      {
        lock (_syncObj)
        {
          InitTexture(item);
          if (_combinedOsdSurface != null)
          {
            Rectangle sourceRect = new Rectangle(0, 0, item.Width, item.Height);
            Rectangle dstRect = new Rectangle(item.X, item.Y, item.Width, item.Height);

            using (Texture itemTexture = new Texture(item.Texture))
              _device.StretchRectangle(itemTexture.GetSurfaceLevel(0), sourceRect, _combinedOsdSurface, dstRect, TextureFilter.None);
          }
        }
      }
      catch (Exception ex)
      {
        BluRayPlayerBuilder.LogError(ex.ToString());
      }

      if (_onTextureInvalidated != null)
        _onTextureInvalidated();
    }
예제 #45
0
        /// <summary>
        ///     Our present hook that will grab a copy of the backbuffer when requested. Note: this supports multi-sampling
        ///     (anti-aliasing)
        /// </summary>
        /// <param name="swapChainPtr"></param>
        /// <param name="syncInterval"></param>
        /// <param name="flags"></param>
        /// <returns>The HRESULT of the original method</returns>
        private int PresentHook(IntPtr swapChainPtr, int syncInterval, PresentFlags flags)
        {
            Frame();
            var swapChain = (SwapChain) swapChainPtr;
            try
            {
                #region Screenshot Request

                if (Request != null)
                {
                    DebugMessage("PresentHook: Request Start");
                    var startTime = DateTime.Now;
                    using (var currentRT = SharpDX.Direct3D11.Resource.FromSwapChain<Texture2D>(swapChain, 0))
                    {
                        #region Determine region to capture

                        var captureRegion = new Rectangle(0, 0, currentRT.Description.Width,
                            currentRT.Description.Height);

                        if (Request.RegionToCapture.Width > 0)
                        {
                            captureRegion = new Rectangle(Request.RegionToCapture.Left, Request.RegionToCapture.Top,
                                Request.RegionToCapture.Right, Request.RegionToCapture.Bottom);
                        }
                        else if (Request.Resize.HasValue)
                        {
                            captureRegion = new Rectangle(0, 0, Request.Resize.Value.Width, Request.Resize.Value.Height);
                        }

                        #endregion

                        // Create / Recreate resources as necessary
                        EnsureResources(currentRT.Device, currentRT.Description, captureRegion, Request);

                        Texture2D sourceTexture = null;

                        // If texture is multisampled, then we can use ResolveSubresource to copy it into a non-multisampled texture
                        if (currentRT.Description.SampleDescription.Count > 1 || Request.Resize.HasValue)
                        {
                            if (Request.Resize.HasValue)
                                DebugMessage("PresentHook: resizing texture");
                            else
                                DebugMessage("PresentHook: resolving multi-sampled texture");

                            // Resolve into _resolvedRT
                            if (_resolvedRTKeyedMutex != null)
                                _resolvedRTKeyedMutex.Acquire(0, int.MaxValue);
                            currentRT.Device.ImmediateContext.ResolveSubresource(currentRT, 0, _resolvedRT, 0,
                                _resolvedRT.Description.Format);
                            if (_resolvedRTKeyedMutex != null)
                                _resolvedRTKeyedMutex.Release(1);

                            if (Request.Resize.HasValue)
                            {
                                lock (_lock)
                                {
                                    if (_resolvedRTKeyedMutex_Dev2 != null)
                                        _resolvedRTKeyedMutex_Dev2.Acquire(1, int.MaxValue);
                                    _saQuad.ShaderResource = _resolvedSharedSRV;
                                    _saQuad.RenderTargetView = _resizedRTV;
                                    _saQuad.RenderTarget = _resizedRT;
                                    _saQuad.Render();
                                    if (_resolvedRTKeyedMutex_Dev2 != null)
                                        _resolvedRTKeyedMutex_Dev2.Release(0);
                                }

                                // set sourceTexture to the resized RT
                                sourceTexture = _resizedRT;
                            }
                            else
                            {
                                // Make sourceTexture be the resolved texture
                                sourceTexture = _resolvedRTShared;
                            }
                        }
                        else
                        {
                            // Copy the resource into the shared texture
                            if (_resolvedRTKeyedMutex != null) _resolvedRTKeyedMutex.Acquire(0, int.MaxValue);
                            currentRT.Device.ImmediateContext.CopySubresourceRegion(currentRT, 0, null, _resolvedRT, 0);
                            if (_resolvedRTKeyedMutex != null) _resolvedRTKeyedMutex.Release(1);
                            sourceTexture = _resolvedRTShared;
                        }

                        // Copy to memory and send back to host process on a background thread so that we do not cause any delay in the rendering pipeline
                        _requestCopy = Request.Clone();
                            // this.Request gets set to null, so copy the Request for use in the thread

                        // Prevent the request from being processed a second time
                        Request = null;

                        var acquireLock = sourceTexture == _resolvedRTShared;

                        ThreadPool.QueueUserWorkItem(o =>
                        {
                            // Acquire lock on second device
                            if (acquireLock && _resolvedRTKeyedMutex_Dev2 != null)
                                _resolvedRTKeyedMutex_Dev2.Acquire(1, int.MaxValue);

                            lock (_lock)
                            {
                                // Copy the subresource region, we are dealing with a flat 2D texture with no MipMapping, so 0 is the subresource index
                                sourceTexture.Device.ImmediateContext.CopySubresourceRegion(sourceTexture, 0,
                                    new ResourceRegion
                                    {
                                        Top = captureRegion.Top,
                                        Bottom = captureRegion.Bottom,
                                        Left = captureRegion.Left,
                                        Right = captureRegion.Right,
                                        Front = 0,
                                        Back = 1 // Must be 1 or only black will be copied
                                    }, _finalRT, 0, 0, 0, 0);

                                // Release lock upon shared surface on second device
                                if (acquireLock && _resolvedRTKeyedMutex_Dev2 != null)
                                    _resolvedRTKeyedMutex_Dev2.Release(0);

                                _finalRT.Device.ImmediateContext.End(_query);
                                _queryIssued = true;
                                while (!_finalRT.Device.ImmediateContext.GetData(_query).ReadBoolean())
                                {
                                    // Spin (usually no spin takes place)
                                }

                                var startCopyToSystemMemory = DateTime.Now;
                                try
                                {
                                    var db = default(DataBox);
                                    if (_requestCopy.Format == ImageFormat.PixelData)
                                    {
                                        db = _finalRT.Device.ImmediateContext.MapSubresource(_finalRT, 0, MapMode.Read,
                                            MapFlags.DoNotWait);
                                        _finalRTMapped = true;
                                    }
                                    _queryIssued = false;

                                    try
                                    {
                                        using (var ms = new MemoryStream())
                                        {
                                            switch (_requestCopy.Format)
                                            {
                                                case ImageFormat.Bitmap:
                                                    SharpDX.Direct3D11.Resource.ToStream(
                                                        _finalRT.Device.ImmediateContext, _finalRT, ImageFileFormat.Bmp,
                                                        ms);
                                                    break;
                                                case ImageFormat.Jpeg:
                                                    SharpDX.Direct3D11.Resource.ToStream(
                                                        _finalRT.Device.ImmediateContext, _finalRT, ImageFileFormat.Jpg,
                                                        ms);
                                                    break;
                                                case ImageFormat.Png:
                                                    SharpDX.Direct3D11.Resource.ToStream(
                                                        _finalRT.Device.ImmediateContext, _finalRT, ImageFileFormat.Png,
                                                        ms);
                                                    break;
                                                case ImageFormat.PixelData:
                                                    if (db.DataPointer != IntPtr.Zero)
                                                    {
                                                        ProcessCapture(_finalRT.Description.Width,
                                                            _finalRT.Description.Height, db.RowPitch,
                                                            PixelFormat.Format32bppArgb, db.DataPointer, _requestCopy);
                                                    }
                                                    return;
                                            }
                                            ms.Position = 0;
                                            ProcessCapture(ms, _requestCopy);
                                        }
                                    }
                                    finally
                                    {
                                        DebugMessage("PresentHook: Copy to System Memory time: " +
                                                     (DateTime.Now - startCopyToSystemMemory).ToString());
                                    }

                                    if (_finalRTMapped)
                                    {
                                        lock (_lock)
                                        {
                                            _finalRT.Device.ImmediateContext.UnmapSubresource(_finalRT, 0);
                                            _finalRTMapped = false;
                                        }
                                    }
                                }
                                catch (SharpDXException exc)
                                {
                                    // Catch DXGI_ERROR_WAS_STILL_DRAWING and ignore - the data isn't available yet
                                }
                            }
                        });


                        // Note: it would be possible to capture multiple frames and process them in a background thread
                    }
                    DebugMessage("PresentHook: Copy BackBuffer time: " + (DateTime.Now - startTime));
                    DebugMessage("PresentHook: Request End");
                }

                #endregion

                #region Draw overlay (after screenshot so we don't capture overlay as well)

                if (Config.ShowOverlay)
                {
                    // Initialise Overlay Engine
                    if (_swapChainPointer != swapChain.NativePointer 
                        || _overlayEngine == null
                        || IsOverlayUpdatePending)
                    {
                        if (_overlayEngine != null)
                            _overlayEngine.Dispose();

                        _overlayEngine = new DXOverlayEngine();
                        _overlayEngine.Overlays.Add(new Overlay
                        {
                            Elements = OverlayElements
                        });
                        _overlayEngine.Initialise(swapChain);

                        _swapChainPointer = swapChain.NativePointer;
                    }
                    // Draw Overlay(s)
                    else if (_overlayEngine != null)
                    {
                        foreach (var overlay in _overlayEngine.Overlays)
                            overlay.Frame();
                        _overlayEngine.Draw();
                    }
                }

                #endregion
            }
            catch (Exception e)
            {
                // If there is an error we do not want to crash the hooked application, so swallow the exception
                DebugMessage("PresentHook: Exeception: " + e.GetType().FullName + ": " + e);
                //return unchecked((int)0x8000FFFF); //E_UNEXPECTED
            }

            // As always we need to call the original method, note that EasyHook will automatically skip the hook and call the original method
            // i.e. calling it here will not cause a stack overflow into this function
            return DXGISwapChain_PresentHook.Original(swapChainPtr, syncInterval, flags);
        }
 private Result Present(IntPtr devicePointer, Rectangle sourceRect, Rectangle destRect, IntPtr destWindowOverride, ref Region dirtyRegion)
 {
     throw new NotImplementedException();
 }
예제 #47
0
 public static void DrawSprite(Sprite sprite, Texture texture, Size size, Color color, Rectangle? spriteResize)
 {
     if (sprite != null && texture != null)
     {
         sprite.Draw(texture, color, spriteResize, new Vector3(size.Width, size.Height, 0));
     }
 }
예제 #48
0
        private void OnEditViewportDrawSprites(Device device, SpriteBatch spriteBatch, Rectangle cliprectangle)
        {
            UiEncodingWindowSource current = _currentSource;
            if (current == null)
                return;

            try
            {
                spriteBatch.Begin();
                current.Texture.Draw(device, spriteBatch, Vector2.Zero, new Rectangle(0, 0, current.Texture.Descriptor2D.Width, current.Texture.Descriptor2D.Height), 0, cliprectangle);
                spriteBatch.End();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }
예제 #49
0
        private Glyph ImportGlyph(Factory factory, FontFace fontFace, char character, FontMetrics fontMetrics, float fontSize, FontAntiAliasMode antiAliasMode)
        {
            var indices = fontFace.GetGlyphIndices(new int[] { character });

            var metrics = fontFace.GetDesignGlyphMetrics(indices, false);
            var metric = metrics[0];

            var width = (float)(metric.AdvanceWidth - metric.LeftSideBearing - metric.RightSideBearing) / fontMetrics.DesignUnitsPerEm * fontSize;
            var height = (float)(metric.AdvanceHeight - metric.TopSideBearing - metric.BottomSideBearing) / fontMetrics.DesignUnitsPerEm * fontSize;

            var xOffset = (float)metric.LeftSideBearing / fontMetrics.DesignUnitsPerEm * fontSize;
            var yOffset = (float)(metric.TopSideBearing - metric.VerticalOriginY) / fontMetrics.DesignUnitsPerEm * fontSize;

            var advanceWidth = (float)metric.AdvanceWidth / fontMetrics.DesignUnitsPerEm * fontSize;
            //var advanceHeight = (float)metric.AdvanceHeight / fontMetrics.DesignUnitsPerEm * fontSize;

            var pixelWidth = (int)Math.Ceiling(width + 4);
            var pixelHeight = (int)Math.Ceiling(height + 4);

            var matrix = Matrix.Identity;
            matrix.M41 = -(float)Math.Floor(xOffset) + 1;
            matrix.M42 = -(float)Math.Floor(yOffset) + 1;

            Bitmap bitmap;
            if (char.IsWhiteSpace(character))
            {
                bitmap = new Bitmap(1, 1, PixelFormat.Format32bppArgb);
            }
            else
            {
                var glyphRun = new GlyphRun
                {
                    FontFace = fontFace,
                    Advances = new[] { (float)Math.Ceiling(advanceWidth) },
                    FontSize = fontSize,
                    BidiLevel = 0,
                    Indices = indices,
                    IsSideways = false,
                    Offsets = new[] { new GlyphOffset() }
                };


                RenderingMode renderingMode;
                if (antiAliasMode != FontAntiAliasMode.Aliased)
                {
                    var rtParams = new RenderingParams(factory);
                    renderingMode = fontFace.GetRecommendedRenderingMode(fontSize, 1.0f, MeasuringMode.Natural, rtParams);
                    rtParams.Dispose();
                }
                else
                {
                    renderingMode = RenderingMode.Aliased;
                }

                using (var runAnalysis = new GlyphRunAnalysis(factory,
                    glyphRun,
                    1.0f,
                    matrix,
                    renderingMode,
                    MeasuringMode.Natural,
                    0.0f,
                    0.0f))
                {

                    var bounds = new SharpDX.Rectangle(0, 0, pixelWidth, pixelHeight);
                    bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);

                    if (renderingMode == RenderingMode.Aliased)
                    {

                        var texture = new byte[bounds.Width * bounds.Height];
                        runAnalysis.CreateAlphaTexture(TextureType.Aliased1x1, bounds, texture, texture.Length);
                        for (int y = 0; y < bounds.Height; y++)
                        {
                            for (int x = 0; x < bounds.Width; x++)
                            {
                                int pixelX = y * bounds.Width + x;
                                var grey = texture[pixelX];
                                var color = Color.FromArgb(grey, grey, grey);

                                bitmap.SetPixel(x, y, color);
                            }
                        }
                    }
                    else
                    {
                        var texture = new byte[bounds.Width * bounds.Height * 3];
                        runAnalysis.CreateAlphaTexture(TextureType.Cleartype3x1, bounds, texture, texture.Length);
                        for (int y = 0; y < bounds.Height; y++)
                        {
                            for (int x = 0; x < bounds.Width; x++)
                            {
                                int pixelX = (y * bounds.Width + x) * 3;
                                var red = LinearToGamma(texture[pixelX]);
                                var green = LinearToGamma(texture[pixelX + 1]);
                                var blue = LinearToGamma(texture[pixelX + 2]);
                                var color = Color.FromArgb(red, green, blue);

                                bitmap.SetPixel(x, y, color);
                            }
                        }
                    }
                }
            }

            var glyph = new Glyph(character, bitmap)
            {
                XOffset = -matrix.M41,
                XAdvance = advanceWidth,
                YOffset = -matrix.M42,
            };
            return glyph;
        }
        /// <summary>
        /// Create size dependent resources, in this case the swap chain and render targets
        /// </summary>
        /// <param name="app"></param>
        protected virtual void CreateSizeDependentResources(D3DApplicationBase app)
        {
            // Retrieve references to device and context
            var device = DeviceManager.Direct3DDevice;
            var context = DeviceManager.Direct3DContext;
            // Retrieve Direct2D context (for use with text rendering etc)
            var d2dContext = DeviceManager.Direct2DContext;

            // Before the swapchain can resize all the buffers must be released
            RemoveAndDispose(ref _backBuffer);
            RemoveAndDispose(ref _renderTargetView);
            RemoveAndDispose(ref _depthStencilView);
            RemoveAndDispose(ref _depthBuffer);
            RemoveAndDispose(ref _bitmapTarget);
            d2dContext.Target = null;

            #region Initialize Direct3D swap chain and render target

            // If the swap chain already exists, resize it.
            if (_swapChain != null)
            {
                _swapChain.ResizeBuffers(
                    _swapChain.Description1.BufferCount,
                    Width,
                    Height,
                    _swapChain.Description.ModeDescription.Format,
                    _swapChain.Description.Flags);
            }
            // Otherwise, create a new one.
            else
            {
                // SwapChain description
                var desc = CreateSwapChainDescription();

                // Rather than create a new DXGI Factory we should reuse
                // the one that has been used internally to create the device

                // First, retrieve the underlying DXGI Device from the D3D Device.
                // access the adapter used for that device and then create the swap chain
                using (var dxgiDevice2 = device.QueryInterface<SharpDX.DXGI.Device2>())
                using (var dxgiAdapter = dxgiDevice2.Adapter)
                using (var dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>())
                using (var output = dxgiAdapter.Outputs.First())
                {
                    // The CreateSwapChain method is used so we can descend
                    // from this class and implement a swapchain for a desktop
                    // or a Windows 8 AppStore app
                    _swapChain = ToDispose(CreateSwapChain(dxgiFactory2, device, desc));

            #if !NETFX_CORE
                    // Retrieve the list of supported display modes
                    DisplayModeList = output.GetDisplayModeList(desc.Format, DisplayModeEnumerationFlags.Scaling);
            #endif
                }
            }

            // Obtain the backbuffer for this window which will be the final 3D rendertarget.
            BackBuffer = ToDispose(Texture2D.FromSwapChain<Texture2D>(_swapChain, 0));
            // Create a view interface on the rendertarget to use on bind.
            RenderTargetView = ToDispose(new RenderTargetView(device, BackBuffer));

            // Cache the rendertarget dimensions in our helper class for convenient use.
            var backBufferDesc = BackBuffer.Description;
            RenderTargetBounds = new SharpDX.Rectangle(0, 0, backBufferDesc.Width, backBufferDesc.Height);

            // Create a viewport descriptor of the render size.
            this.Viewport = new SharpDX.ViewportF(
                (float)RenderTargetBounds.X,
                (float)RenderTargetBounds.Y,
                (float)RenderTargetBounds.Width,
                (float)RenderTargetBounds.Height,
                0.0f,   // min depth
                1.0f);  // max depth

            // Set the current viewport for the rasterizer.
            context.Rasterizer.SetViewport(Viewport);

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D texture as the depth/stencil buffer.
            // Create a DSV to use on bind.
            this.DepthBuffer = ToDispose(new Texture2D(device, new Texture2DDescription()
                {
                    Format = SharpDX.DXGI.Format.D32_Float_S8X24_UInt,
                    ArraySize = 1,
                    MipLevels = 1,
                    Width = RenderTargetSize.Width,
                    Height = RenderTargetSize.Height,
                    SampleDescription = SwapChain.Description.SampleDescription,
                    BindFlags = BindFlags.DepthStencil,
                }));
            this.DepthStencilView = ToDispose(
                new DepthStencilView(
                    device,
                    DepthBuffer,
                    new DepthStencilViewDescription()
                    {
                        Dimension = (SwapChain.Description.SampleDescription.Count > 1 || SwapChain.Description.SampleDescription.Quality > 0) ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D
                    }));

            // Set the OutputMerger targets
            context.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);

            #endregion

            #region Initialize Direct2D render target

            // Now we set up the Direct2D render target bitmap linked to the swapchain.
            // Whenever we render to this bitmap, it will be directly rendered to the
            // swapchain associated with the window.
            var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1(
                new SharpDX.Direct2D1.PixelFormat(_swapChain.Description.ModeDescription.Format, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                DeviceManager.Dpi,
                DeviceManager.Dpi,
                SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

            // Direct2D needs the dxgi version of the backbuffer surface pointer.
            // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
            using (var dxgiBackBuffer = _swapChain.GetBackBuffer<SharpDX.DXGI.Surface>(0))
                BitmapTarget2D = ToDispose(new SharpDX.Direct2D1.Bitmap1(d2dContext, dxgiBackBuffer, bitmapProperties));

            // So now we can set the Direct2D render target.
            d2dContext.Target = BitmapTarget2D;

            // Set D2D text anti-alias mode to Grayscale to ensure proper rendering of text on intermediate surfaces.
            d2dContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;

            #endregion
        }
예제 #51
0
 public void Crop(SharpDX.Rectangle rect)
 {
     _crop = rect;
 }
예제 #52
0
 public static void DrawTransformSprite(Sprite sprite, Texture texture, Color color, Size size, float[] scale,
     float rotation, Rectangle? spriteResize)
 {
     if (sprite != null && texture != null)
     {
         Matrix matrix = sprite.Transform;
         Matrix nMatrix = Matrix.Scaling(scale[0], scale[1], 0) * Matrix.RotationZ(rotation) *
                          Matrix.Translation(size.Width, size.Height, 0);
         sprite.Transform = nMatrix;
         sprite.Draw(texture, color);
         sprite.Transform = matrix;
     }
 }
예제 #53
0
        /// <summary>
        ///     Creates and sets a corp towards the texture.
        /// </summary>
        /// <param name="rectangle">
        ///     The rectangle
        /// </param>
        /// <param name="scale">
        ///     The scale
        /// </param>
        public void Crop(Rectangle rectangle, bool scale = false)
        {
            this.CorpRectangle = rectangle;

            if (scale)
            {
                this.CorpRectangle = new Rectangle(
                    (int)(this.Scale.X * rectangle.X), 
                    (int)(this.Scale.Y * rectangle.Y), 
                    (int)(this.Scale.X * rectangle.Width), 
                    (int)(this.Scale.Y * rectangle.Height));
            }
        }