Ejemplo n.º 1
0
    public override RectangleF GetZoomRect(float animationProgress, Size imageSize, Size outputSize)
    {
      bool isLandscape = IsLandscape(imageSize.ToSize2F(), outputSize.ToSize2F());
      Point startEndPanPoints = isLandscape ? KenBurnsEffects.LANDSCAPE_PAN_SPOTS[_panPointsIndex] : KenBurnsEffects.PORTRAIT_PAN_SPOTS[_panPointsIndex];
      PointF panStartPoint = KenBurnsEffects.SPOT_POINTS[startEndPanPoints.X];
      PointF panEndPoint = KenBurnsEffects.SPOT_POINTS[startEndPanPoints.Y];

      return KenBurnsEffects.GetKenBurnsPanRectangle(_zoomFactor,
          panStartPoint.X + (panEndPoint.X - panStartPoint.X) * animationProgress,
          panStartPoint.Y + (panEndPoint.Y - panStartPoint.Y) * animationProgress, imageSize.ToSize2F(), outputSize.ToSize2F());
    }
Ejemplo n.º 2
0
    public RectangleF GetZoomRect(Size imageSize, Size outputSize, DateTime displayTime)
    {
      TimeSpan timeProgress = displayTime - _startTime;
      float animationProgress = (float) timeProgress.TotalMilliseconds / (float) _animationDuration.TotalMilliseconds;
      // Flatten progress function to be in the range 0-1
      if (animationProgress < 0)
        animationProgress = 0;
      animationProgress = 1 - 1 / (5 * animationProgress * animationProgress + 1);

      return _currentEffect == null ? RectangleF.Empty : _currentEffect.GetZoomRect(animationProgress, imageSize, outputSize);
    }
Ejemplo n.º 3
0
        /// <summary>
        /// Function to build our render targets and textures.
        /// </summary>
        /// <param name="size">The size of the render targets.</param>
        private static void BuildRenderTargets(DX.Size2 size)
        {
            _layer1Target = GorgonRenderTarget2DView.CreateRenderTarget(_graphics,
                                                                        new GorgonTexture2DInfo("Layer 1")
            {
                Width   = size.Width,
                Height  = size.Height,
                Format  = BufferFormat.R8G8B8A8_UNorm,
                Binding = TextureBinding.ShaderResource,
                Usage   = ResourceUsage.Default
            });
            _blurTarget = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo(_layer1Target, "Blurred Image"));

            _layer1Texture = _layer1Target.GetShaderResourceView();
            _blurTexture   = _blurTarget.GetShaderResourceView();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Function to render the data to the panel assigned in the <see cref="SetPanel"/> method.
        /// </summary>
        /// <param name="texture">The texture to render.</param>
        /// <param name="outputTexture">The output texture to render.</param>
        public void Render(GorgonTexture2DView texture, GorgonTexture2DView outputTexture)
        {
            if (_swapChain == null)
            {
                return;
            }

            if (_graphics.RenderTargets[0] != _swapChain.RenderTargetView)
            {
                _graphics.SetRenderTarget(_swapChain.RenderTargetView);
            }

            _swapChain.RenderTargetView.Clear(Color.CornflowerBlue);

            if ((texture == null) ||
                (outputTexture == null))
            {
                _swapChain.Present(1);
                return;
            }

            // Get aspect ratio.
            var scale = new DX.Size2F((_swapChain.Width * 0.5f) / texture.Width, (float)_swapChain.Height / texture.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 * texture.Width), (int)(scale.Height * texture.Height));

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

            _graphics.DrawTexture(texture, bounds, blendState: GorgonBlendState.Default, samplerState: GorgonSamplerState.PointFiltering);

            bounds = new DX.Rectangle((_swapChain.Width - (_swapChain.Width / 4)) - (size.Width / 2), ((_swapChain.Height / 2) - (size.Height / 2)), size.Width, size.Height);
            _graphics.DrawTexture(outputTexture, bounds, blendState: GorgonBlendState.Default, samplerState: GorgonSamplerState.PointFiltering);

            _swapChain.Present(1);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Function to add a node as a child to this node.
        /// </summary>
        /// <param name="dimensions">Dimensions that the node will occupy.</param>
        public SpriteNode AddNode(DX.Size2 dimensions)
        {
            if (!IsLeaf)
            {
                return(Left.IsLeaf ? Left.AddNode(dimensions) ?? Right.AddNode(dimensions)
                                   : Right.AddNode(dimensions) ?? Left.AddNode(dimensions));
            }

            // Do nothing if there's no more room.
            if (_noMoreRoom)
            {
                return(null);
            }

            // Ensure we can fit this node.
            if ((dimensions.Width > Region.Width) || (dimensions.Height > Region.Height))
            {
                return(null);
            }

            // We have an exact fit, so there will be no more room for other nodes.
            if ((dimensions.Width == Region.Width) && (dimensions.Height == Region.Height))
            {
                _noMoreRoom = true;
                return(this);
            }

            // The region occupied by the requested dimensions.
            Left  = new SpriteNode(this);
            Right = new SpriteNode(this);

            // Subdivide.
            var delta = new DX.Size2(Region.Width - dimensions.Width, Region.Height - dimensions.Height);

            if (delta.Height <= 0) //(delta.Width > delta.Height)
            {
                Left.Region  = new DX.Rectangle(Region.Left, Region.Top, dimensions.Width, Region.Height);
                Right.Region = new DX.Rectangle(Region.Left + dimensions.Width, Region.Top, delta.Width, Region.Height);
            }
            else
            {
                Left.Region  = new DX.Rectangle(Region.Left, Region.Top, Region.Width, dimensions.Height);
                Right.Region = new DX.Rectangle(Region.Left, Region.Top + dimensions.Height, Region.Width, delta.Height);
            }

            return(Left.AddNode(dimensions) ?? Right.AddNode(dimensions));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Loads a Direct2D Bitmap from a file using <see cref="System.Drawing.Image.FromFile(string)"/>
        /// </summary>
        /// <param name="renderTarget">The render target.</param>
        /// <param name="file">The file.</param>
        /// <returns>A D2D1 Bitmap</returns>
        public static SharpDX.Direct2D1.Bitmap LoadBitmapFromFile(this RenderTarget renderTarget, string file)
        {
            try
            {
                // Loads from file using System.Drawing.Image
                using (var bitmap = (System.Drawing.Bitmap)System.Drawing.Image.FromFile(file))
                {
                    var sourceArea       = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
                    var bitmapProperties = new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));
                    var size             = new SharpDX.Size2(bitmap.Width, bitmap.Height);

                    // Transform pixels from BGRA to RGBA
                    int stride = bitmap.Width * sizeof(int);
                    using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
                    {
                        // Lock System.Drawing.Bitmap
                        var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                        // Convert all pixels
                        for (int y = 0; y < bitmap.Height; y++)
                        {
                            int offset = bitmapData.Stride * y;
                            for (int x = 0; x < bitmap.Width; x++)
                            {
                                // Not optimized
                                byte B    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                byte G    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                byte R    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                byte A    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                int  rgba = R | (G << 8) | (B << 16) | (A << 24);
                                tempStream.Write(rgba);
                            }
                        }
                        bitmap.UnlockBits(bitmapData);
                        tempStream.Position = 0;

                        return(new SharpDX.Direct2D1.Bitmap(renderTarget, size, tempStream, stride, bitmapProperties));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("DX Bitmap Conversion Error: {0}", ex.Message);
                return(null);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Function to add a node to the
        /// </summary>
        /// <param name="dimensions">The sprite dimensions.</param>
        /// <returns>A rectangle for the area on the image that the sprite will be located at, or <b>null</b> if there's no room.</returns>
        public static DX.Rectangle?Add(DX.Size2 dimensions)
        {
            if ((dimensions.Width > Root.Region.Width) || (dimensions.Height > Root.Region.Height))
            {
                return(null);
            }

            // Do nothing here.
            if ((dimensions.Width == 0) || (dimensions.Height == 0))
            {
                return(DX.Rectangle.Empty);
            }

            SpriteNode newNode = Root.AddNode(dimensions);

            return(newNode?.Region);
        }
Ejemplo n.º 8
0
        private void ChangeRenderSizeButton_OnClick(object sender, RoutedEventArgs e)
        {
            var currentSize = BigPlane.Material.GetDXAttributeOrDefault <SharpDX.Size2>(DXAttributeType.CachedBitmapSize);

            SharpDX.Size2 newSize;

            if (currentSize.Width == 512)
            {
                newSize = new SharpDX.Size2(64, 32);
            }
            else
            {
                newSize = new SharpDX.Size2(512, 256);
            }

            _currentBigPlaneBitmapSize = newSize;
            BigPlane.Material.SetDXAttribute(DXAttributeType.CachedBitmapSize, newSize);
        }
Ejemplo n.º 9
0
        public static SharpDX.Size2 GetPositionsSizeOnScreen(Point3DCollection positions, Transform3D transform, Ab3d.Cameras.BaseCamera camera)
        {
            double minX = double.MaxValue;
            double maxX = double.MinValue;
            double minY = double.MaxValue;
            double maxY = double.MinValue;

            var positionsCount = positions.Count;

            bool useTransform = transform != null && !transform.Value.IsIdentity;

            for (int i = 0; i < positionsCount; i++)
            {
                var onePoint = positions[i];
                if (useTransform)
                {
                    onePoint = transform.Transform(onePoint);
                }

                var pointOnScreen = camera.Point3DTo2D(onePoint);

                if (pointOnScreen.X < minX)
                {
                    minX = pointOnScreen.X;
                }
                if (pointOnScreen.X > maxX)
                {
                    maxX = pointOnScreen.X;
                }

                if (pointOnScreen.Y < minY)
                {
                    minY = pointOnScreen.Y;
                }
                if (pointOnScreen.Y > maxY)
                {
                    maxY = pointOnScreen.Y;
                }
            }

            var sizeOnScreen = new SharpDX.Size2((int)(maxX - minX), (int)(maxY - minY));

            return(sizeOnScreen);
        }
Ejemplo n.º 10
0
 public override RectangleF GetZoomRect(float animationProgress, Size imageSize, Size outputSize)
 {
   bool isLandscape = IsLandscape(imageSize.ToSize2F(), outputSize.ToSize2F());
   int zoomCenterPoint = 0;
   switch (_zoomCenterClass)
   {
     case ZoomCenterClass.TopLeft:
       zoomCenterPoint = isLandscape ? 8 : 2;
       break;
     case ZoomCenterClass.Middle:
       zoomCenterPoint = 0;
       break;
     case ZoomCenterClass.BottomRight:
       zoomCenterPoint = isLandscape ? 4 : 6;
       break;
   }
   return KenBurnsEffects.GetKenBurnsZoomRectangle(_startZoomFactor + (_endZoomFactor - _startZoomFactor) * animationProgress,
       zoomCenterPoint, imageSize.ToSize2F(), outputSize.ToSize2F());
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Function to retrieve the starting point for an operaiton based on an alignment.
        /// </summary>
        /// <param name="srcSize">The size of the image being cropped/resized.</param>
        /// <param name="destSize">The new size for the image.</param>
        /// <param name="alignment">The alignment of the image for the operation.</param>
        /// <returns></returns>
        private DX.Point GetAnchorStart(DX.Size2 srcSize, ref DX.Size2 destSize, Alignment alignment)
        {
            // Limit the extents if the destination is larger in one direction than the source.
            if (srcSize.Height < destSize.Height)
            {
                destSize.Height = srcSize.Height;
            }

            if (srcSize.Width < destSize.Width)
            {
                destSize.Width = srcSize.Width;
            }

            switch (alignment)
            {
            case Alignment.UpperCenter:
                return(new DX.Point(srcSize.Width / 2 - destSize.Width / 2, 0));

            case Alignment.UpperRight:
                return(new DX.Point(srcSize.Width - destSize.Width, 0));

            case Alignment.CenterLeft:
                return(new DX.Point(0, srcSize.Height / 2 - destSize.Height / 2));

            case Alignment.Center:
                return(new DX.Point(srcSize.Width / 2 - destSize.Width / 2, srcSize.Height / 2 - destSize.Height / 2));

            case Alignment.CenterRight:
                return(new DX.Point(srcSize.Width - destSize.Width, srcSize.Height / 2 - destSize.Height / 2));

            case Alignment.LowerLeft:
                return(new DX.Point(0, srcSize.Height - destSize.Height));

            case Alignment.LowerCenter:
                return(new DX.Point(srcSize.Width / 2 - destSize.Width / 2, srcSize.Height - destSize.Height));

            case Alignment.LowerRight:
                return(new DX.Point(srcSize.Width - destSize.Width, srcSize.Height - destSize.Height));

            default:
                return(DX.Point.Zero);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Function to render a texture to the current render target using the current effect.
        /// </summary>
        /// <param name="texture">The texture to render.</param>
        /// <param name="outputSize">The size of the output render target that the blit will render into.</param>
        /// <param name="destinationRegion">[Optional] The region that the texture will be drawn into.</param>
        /// <param name="textureCoordinates">[Optional] The texture coordinates to use with the texture.</param>
        /// <param name="samplerStateOverride">[Optional] An override for the current texture sampler.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="texture"/> parameter is <b>null</b>.</exception>
        /// <remarks>
        /// <para>
        /// This method is a convenience method that will render a texture to the current set render target in slot 0.
        /// </para>
        /// <para>
        /// If the <paramref name="destinationRegion"/> parameter is omitted, then the texture will be rendered to the full size of the current render target.  If it is provided, then texture will be rendered to the
        /// location specified, and with the width and height specified.
        /// </para>
        /// <para>
        /// If the <paramref name="textureCoordinates"/> parameter is omitted, then the full size of the texture is rendered.
        /// </para>
        /// <para>
        /// If the <paramref name="samplerStateOverride"/> parameter is omitted, then the <see cref="GorgonSamplerState.Default"/> is used.  When provided, this will alter how the pixel shader samples our
        /// texture in slot 0.
        /// </para>
        /// <para>
        /// <note type="important">
        /// <para>
        /// For performance reasons, any exceptions thrown by this method will only be thrown when Gorgon is compiled as DEBUG.
        /// </para>
        /// </note>
        /// </para>
        /// </remarks>
        /// <seealso cref="GorgonBlendState"/>
        /// <seealso cref="GorgonDepthStencilState"/>
        /// <seealso cref="GorgonRasterState"/>
        /// <seealso cref="Gorgon2DOrthoCamera"/>
        /// <seealso cref="Gorgon2DPerspectiveCamera"/>
        protected void BlitTexture(GorgonTexture2DView texture,
                                   DX.Size2 outputSize,
                                   DX.RectangleF?destinationRegion         = null,
                                   DX.RectangleF?textureCoordinates        = null,
                                   GorgonSamplerState samplerStateOverride = null)
        {
            texture.ValidateObject(nameof(texture));

            if (destinationRegion == null)
            {
                destinationRegion = new DX.RectangleF(0, 0, outputSize.Width, outputSize.Height);
            }

            if (textureCoordinates == null)
            {
                textureCoordinates = new DX.RectangleF(0, 0, 1, 1);
            }

            Renderer.DrawFilledRectangle(destinationRegion.Value, GorgonColor.White, texture, textureCoordinates, textureSampler: samplerStateOverride);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        /// <param name="resolution">The client side resolution to use.</param>
        /// <param name="appTitle">The title for the application.</param>
        /// <param name="formLoad">The method to execute when the form load event is triggered.</param>
        /// <returns>The newly created form.</returns>
        public static FormMain Initialize(DX.Size2 resolution, string appTitle, EventHandler formLoad = null)
        {
            _mainForm = new FormMain
            {
                Text       = appTitle,
                ClientSize = new Drawing.Size(resolution.Width, resolution.Height)
            };

            if (formLoad != null)
            {
                _mainForm.Load += formLoad;
            }

            _mainForm.Show();

            Application.DoEvents();

            Cursor.Current = Cursors.WaitCursor;

            return(_mainForm);
        }
Ejemplo n.º 14
0
        public MediaFoundationVideoWriter(string filePath, Size2 videoPixelSize, Guid videoInputFormat, bool supportAudio = false)
        {
            bitrate   = 1500000;
            framerate = 15;

            if (!MFInitialized)
            {
                // Initialize MF library. MUST be called before any MF related operations.
                MF.MediaFactory.Startup(MF.MediaFactory.Version, 0);
            }

            sinkWriter = MF.MediaFactory.CreateSinkWriterFromURL(filePath, IntPtr.Zero, null);

            this.videoPixelSize = videoPixelSize;
            CreateMediaTarget(sinkWriter, videoPixelSize, out streamIndex);

            // Configure input
            using (MF.MediaType mediaTypeIn = new MF.MediaType())
            {
                mediaTypeIn.Set <Guid>(MF.MediaTypeAttributeKeys.MajorType, MF.MediaTypeGuids.Video);
                mediaTypeIn.Set <Guid>(MF.MediaTypeAttributeKeys.Subtype, videoInputFormat);
                mediaTypeIn.Set <int>(MF.MediaTypeAttributeKeys.InterlaceMode, (int)MF.VideoInterlaceMode.Progressive);
                mediaTypeIn.Set <long>(MF.MediaTypeAttributeKeys.FrameSize, MFHelper.GetMFEncodedIntsByValues(videoPixelSize.Width, videoPixelSize.Height));
                mediaTypeIn.Set <long>(MF.MediaTypeAttributeKeys.FrameRate, MFHelper.GetMFEncodedIntsByValues(framerate, 1));
                sinkWriter.SetInputMediaType(streamIndex, mediaTypeIn, null);
            }

            if (supportAudio)
            {
                // initialize audio writer
                var waveFormat = WAVEFORMATEX.DefaultPCM;
                audioWriter = new MP3AudioWriter(sinkWriter, ref waveFormat);
            }

            // Start writing the video file. MUST be called before write operations.
            sinkWriter.BeginWriting();

            // Set initial frame index
            frameIndex = -1;
        }
        public override RectangleF GetZoomRect(float animationProgress, Size imageSize, Size outputSize)
        {
            bool isLandscape     = IsLandscape(imageSize.ToSize2F(), outputSize.ToSize2F());
            int  zoomCenterPoint = 0;

            switch (_zoomCenterClass)
            {
            case ZoomCenterClass.TopLeft:
                zoomCenterPoint = isLandscape ? 8 : 2;
                break;

            case ZoomCenterClass.Middle:
                zoomCenterPoint = 0;
                break;

            case ZoomCenterClass.BottomRight:
                zoomCenterPoint = isLandscape ? 4 : 6;
                break;
            }
            return(KenBurnsEffects.GetKenBurnsZoomRectangle(_startZoomFactor + (_endZoomFactor - _startZoomFactor) * animationProgress,
                                                            zoomCenterPoint, imageSize.ToSize2F(), outputSize.ToSize2F()));
        }
Ejemplo n.º 16
0
        private Bitmap LoadFromResource(RenderTarget renderTarget, Stream resourceStream)
        {
            // Loads from resource via stream
            using (resourceStream)
                using (var bitmap = new System.Drawing.Bitmap(resourceStream))
                {
                    var sourceArea       = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
                    var bitmapProperties = new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));
                    var size             = new SharpDX.Size2(bitmap.Width, bitmap.Height);

                    // Transform pixels from BGRA to RGBA
                    int stride = bitmap.Width * sizeof(int);
                    using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
                    {
                        // Lock System.Drawing.Bitmap
                        var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                        // Convert all pixels
                        for (int y = 0; y < bitmap.Height; y++)
                        {
                            int offset = bitmapData.Stride * y;
                            for (int x = 0; x < bitmap.Width; x++)
                            {
                                // Not optimized
                                byte B    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                byte G    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                byte R    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                byte A    = Marshal.ReadByte(bitmapData.Scan0, offset++);
                                int  rgba = R | (G << 8) | (B << 16) | (A << 24);
                                tempStream.Write(rgba);
                            }
                        }
                        bitmap.UnlockBits(bitmapData);
                        tempStream.Position = 0;

                        return(new Bitmap(renderTarget, size, tempStream, stride, bitmapProperties));
                    }
                }
        }
Ejemplo n.º 17
0
        public Vector4 GetTextureClip()
        {
            IImageAnimator animator = Animation;

            // TODO: Execute animation in own timer
            if (animator == null || !AnimationEnabled)
            {
                return(_brushTransform);
            }

            Size       size        = new Size((int)BrushDimensions.X, (int)BrushDimensions.Y);
            Size       outputSize  = new Size((int)_vertsBounds.Width, (int)_vertsBounds.Height);
            RectangleF textureClip = animator.GetZoomRect(size, outputSize, DateTime.Now);

            var vector4 = new Vector4(
                -textureClip.X * TextureMaxUV.X,
                -textureClip.Y * TextureMaxUV.Y,
                textureClip.Width * TextureMaxUV.X,
                textureClip.Height * TextureMaxUV.Y
                );

            return(vector4);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Function to set up state prior to rendering.
        /// </summary>
        /// <param name="blendStateOverride">An override for the current blending state.</param>
        /// <param name="depthStencilStateOverride">An override for the current depth/stencil state.</param>
        /// <param name="rasterStateOverride">An override for the current raster state.</param>
        /// <param name="output">The target used as the output.</param>
        /// <param name="camera">The active camera.</param>
        /// <returns><b>true</b> if state was overridden, <b>false</b> if not or <b>null</b> if rendering is canceled.</returns>
        private bool SetupStates(GorgonBlendState blendStateOverride, GorgonDepthStencilState depthStencilStateOverride, GorgonRasterState rasterStateOverride, GorgonRenderTargetView output, IGorgon2DCamera camera)
        {
            if (!_isInitialized)
            {
                OnInitialize();
                _isInitialized = true;
            }

            bool outputSizeChanged = false;

            if ((_prevOutputSize.Width != output.Width) ||
                (_prevOutputSize.Height != output.Height))
            {
                _prevOutputSize   = new DX.Size2(output.Width, output.Height);
                outputSizeChanged = true;
            }

            OnBeforeRender(output, camera, outputSizeChanged);

            if ((blendStateOverride == BlendStateOverride) &&
                (depthStencilStateOverride == DepthStencilStateOverride) &&
                (rasterStateOverride == RasterStateOverride))
            {
                return(false);
            }

            BatchStateBuilder.BlendState(blendStateOverride ?? GorgonBlendState.Default)
            .DepthStencilState(depthStencilStateOverride ?? GorgonDepthStencilState.Default)
            .RasterState(rasterStateOverride ?? GorgonRasterState.Default);

            BlendStateOverride        = blendStateOverride;
            DepthStencilStateOverride = depthStencilStateOverride;
            RasterStateOverride       = rasterStateOverride;

            return(true);
        }
Ejemplo n.º 19
0
 /// <summary>
 ///		SharpDX.Size2 を System.Drawing.Size へ変換する。
 /// </summary>
 public static System.Drawing.Size ToDrawingSize(this SharpDX.Size2 size)
 => new System.Drawing.Size(size.Width, size.Height);
Ejemplo n.º 20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BeforeSwapChainResizedEventArgs"/> class.
 /// </summary>
 /// <param name="oldSize">The old size.</param>
 /// <param name="newSize">The new size.</param>
 public BeforeSwapChainResizedEventArgs(DX.Size2 oldSize, DX.Size2 newSize)
 {
     OldSize = oldSize;
     NewSize = newSize;
 }
Ejemplo n.º 21
0
 /// <summary>Function called when the render window changes size.</summary>
 /// <param name="size">The size of the window.</param>
 protected override void OnWindowResize(DX.Size2 size) => _volRenderer.ResizeRenderRegion();
Ejemplo n.º 22
0
 /// <summary>
 /// Function to convert a size into an floating point size.
 /// </summary>
 /// <param name="size">The size to convert.</param>
 /// <returns>The equivalent size value.</returns>
 public static DX.Size2F ToSize2F(this DX.Size2 size) => new DX.Size2F(size.Width, size.Height);
Ejemplo n.º 23
0
        public override RectangleF GetZoomRect(float animationProgress, Size imageSize, Size outputSize)
        {
            bool   isLandscape       = IsLandscape(imageSize.ToSize2F(), outputSize.ToSize2F());
            Point  startEndPanPoints = isLandscape ? KenBurnsEffects.LANDSCAPE_PAN_SPOTS[_panPointsIndex] : KenBurnsEffects.PORTRAIT_PAN_SPOTS[_panPointsIndex];
            PointF panStartPoint     = KenBurnsEffects.SPOT_POINTS[startEndPanPoints.X];
            PointF panEndPoint       = KenBurnsEffects.SPOT_POINTS[startEndPanPoints.Y];

            return(KenBurnsEffects.GetKenBurnsPanRectangle(_zoomFactor,
                                                           panStartPoint.X + (panEndPoint.X - panStartPoint.X) * animationProgress,
                                                           panStartPoint.Y + (panEndPoint.Y - panStartPoint.Y) * animationProgress, imageSize.ToSize2F(), outputSize.ToSize2F()));
        }
Ejemplo n.º 24
0
    public Vector4 GetTextureClip()
    {
      IImageAnimator animator = Animation;
      // TODO: Execute animation in own timer
      if (animator == null || !AnimationEnabled)
        return _brushTransform;

      Size size = new Size((int) BrushDimensions.X, (int) BrushDimensions.Y);
      Size outputSize = new Size((int) _vertsBounds.Width, (int) _vertsBounds.Height);
      RectangleF textureClip = animator.GetZoomRect(size, outputSize, DateTime.Now);

      var vector4 = new Vector4(
        -textureClip.X * TextureMaxUV.X, 
        -textureClip.Y * TextureMaxUV.Y,
        textureClip.Width * TextureMaxUV.X, 
        textureClip.Height * TextureMaxUV.Y
        );
      return vector4;
    }
Ejemplo n.º 25
0
 /// <summary>
 /// Function to convert a size into a vector.
 /// </summary>
 /// <param name="size">The size to convert.</param>
 /// <returns>The equivalent vector value.</returns>
 public static DX.Vector2 ToVector2(this DX.Size2 size) => new DX.Vector2(size.Width, size.Height);
Ejemplo n.º 26
0
        protected bool RefreshEffectParameters(IVideoPlayer player)
        {
            ISharpDXVideoPlayer sdvPlayer = player as ISharpDXVideoPlayer;

            if (sdvPlayer == null)
            {
                return(false);
            }
            SizeF      aspectRatio   = sdvPlayer.VideoAspectRatio.ToSize2F();
            Size       playerSize    = sdvPlayer.VideoSize.ToSize2();
            Rectangle  cropVideoRect = sdvPlayer.CropVideoRect;
            IGeometry  geometry      = ChooseVideoGeometry(player);
            string     effectName    = player.EffectOverride;
            int        deviceWidth   = GraphicsDevice.Width; // To avoid threading issues if the device size changes
            int        deviceHeight  = GraphicsDevice.Height;
            RectangleF vertsBounds   = _vertsBounds;

            // Do we need a refresh?
            if (!_refresh &&
                _lastVideoSize == playerSize &&
                _lastAspectRatio == aspectRatio &&
                _lastCropVideoRect == cropVideoRect &&
                _lastGeometry == geometry &&
                _lastEffect == effectName &&
                _lastDeviceWidth == deviceWidth &&
                _lastDeviceHeight == deviceHeight &&
                _lastVertsBounds == vertsBounds)
            {
                return(true);
            }

            SizeF targetSize = vertsBounds.Size;

            lock (sdvPlayer.SurfaceLock)
            {
                Surface surface = sdvPlayer.Surface;
                if (surface == null)
                {
                    _refresh = true;
                    return(false);
                }
                SurfaceDescription desc = surface.Description;
                _videoTextureClip = new RectangleF(cropVideoRect.X / desc.Width, cropVideoRect.Y / desc.Height,
                                                   cropVideoRect.Width / desc.Width, cropVideoRect.Height / desc.Height);
            }
            _scaledVideoSize = cropVideoRect.Size.ToSize2F();

            // Correct aspect ratio for anamorphic video
            if (!aspectRatio.IsEmpty() && geometry.RequiresCorrectAspectRatio)
            {
                float pixelRatio = aspectRatio.Width / aspectRatio.Height;
                _scaledVideoSize.Width = _scaledVideoSize.Height * pixelRatio;
            }
            // Adjust target size to match final Skin scaling
            targetSize = ImageContext.AdjustForSkinAR(targetSize);

            // Adjust video size to fit desired geometry
            _scaledVideoSize = geometry.Transform(_scaledVideoSize.ToDrawingSizeF(), targetSize.ToDrawingSizeF()).ToSize2F();

            // Cache inverse RelativeTransform
            Transform relativeTransform = RelativeTransform;

            _inverseRelativeTransformCache = (relativeTransform == null) ? Matrix.Identity : Matrix.Invert(relativeTransform.GetTransform());

            // Prepare our ImageContext
            _imageContext.FrameSize       = targetSize;
            _imageContext.ShaderBase      = EFFECT_BASE_VIDEO;
            _imageContext.ShaderTransform = geometry.Shader;
            _imageContext.ShaderEffect    = player.EffectOverride;

            // Store state
            _lastFrameData     = new Vector4(playerSize.Width, playerSize.Height, 0.0f, 0.0f);
            _lastVideoSize     = playerSize;
            _lastAspectRatio   = aspectRatio;
            _lastGeometry      = geometry;
            _lastCropVideoRect = cropVideoRect;
            _lastEffect        = effectName;
            _lastDeviceWidth   = deviceWidth;
            _lastDeviceHeight  = deviceHeight;

            _refresh = false;
            return(true);
        }
 /// <summary>
 /// Returns the zoom view rectangle for the current animation state for the given <see cref="outputSize"/>.
 /// </summary>
 /// <param name="animationProgress">Progress of the animation, value between 0 (= start) and 1 (=end).</param>
 /// <param name="imageSize">Size of the image to animate.</param>
 /// <param name="outputSize">Size of the output region.</param>
 /// <returns>Rectangle which contains fractions of the image size; X and Y coords go from 0 to 1.</returns>
 public abstract RectangleF GetZoomRect(float animationProgress, Size imageSize, Size outputSize);
        public MediaFoundationVideoWriter(string filePath, Size2 videoPixelSize, Guid videoInputFormat, bool supportAudio = false)
        {
            bitrate = 1500000;
            framerate = 15;

            if (!MFInitialized)
            {
                // Initialize MF library. MUST be called before any MF related operations.
                MF.MediaFactory.Startup(MF.MediaFactory.Version, 0);
            }

            sinkWriter = MF.MediaFactory.CreateSinkWriterFromURL(filePath, IntPtr.Zero, null);

            this.videoPixelSize = videoPixelSize;
            CreateMediaTarget(sinkWriter, videoPixelSize, out streamIndex);

            // Configure input
            using (MF.MediaType mediaTypeIn = new MF.MediaType())
            {
                mediaTypeIn.Set<Guid>(MF.MediaTypeAttributeKeys.MajorType, MF.MediaTypeGuids.Video);
                mediaTypeIn.Set<Guid>(MF.MediaTypeAttributeKeys.Subtype, videoInputFormat);
                mediaTypeIn.Set<int>(MF.MediaTypeAttributeKeys.InterlaceMode, (int)MF.VideoInterlaceMode.Progressive);
                mediaTypeIn.Set<long>(MF.MediaTypeAttributeKeys.FrameSize, MFHelper.GetMFEncodedIntsByValues(videoPixelSize.Width, videoPixelSize.Height));
                mediaTypeIn.Set<long>(MF.MediaTypeAttributeKeys.FrameRate, MFHelper.GetMFEncodedIntsByValues(framerate, 1));
                sinkWriter.SetInputMediaType(streamIndex, mediaTypeIn, null);
            }

            if (supportAudio)
            {
                // initialize audio writer
                var waveFormat = WAVEFORMATEX.DefaultPCM;
                audioWriter = new MP3AudioWriter(sinkWriter, ref waveFormat);
            }

            // Start writing the video file. MUST be called before write operations.
            sinkWriter.BeginWriting();

            // Set initial frame index
            frameIndex = -1;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="BeforeSwapChainResizedEventArgs"/> class.
 /// </summary>
 /// <param name="newSize">The new size.</param>
 /// <param name="oldSize">The old size.</param>
 public AfterSwapChainResizedEventArgs(DX.Size2 newSize, DX.Size2 oldSize)
 {
     Size    = newSize;
     OldSize = oldSize;
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Function to draw the scene that needs lighting.
 /// </summary>
 /// <param name="pass">Not used.</param>
 /// <param name="passCount">Not used.</param>
 /// <param name="outputSize">The size of the output render target.</param>
 private static void DrawLitScene(int pass, int passCount, DX.Size2 outputSize)
 {
     _logoSprite.Position = new DX.Vector2(outputSize.Width / 2.0f, outputSize.Height / 2.0f);
     _renderer.DrawSprite(_logoSprite);
 }
Ejemplo n.º 31
0
 /// <summary>
 /// Creates a media target.
 /// </summary>
 /// <param name="sinkWriter">The previously created SinkWriter.</param>
 /// <param name="videoPixelSize">The pixel size of the video.</param>
 /// <param name="streamIndex">The stream index for the new target.</param>
 protected abstract void CreateMediaTarget(MF.SinkWriter sinkWriter, SharpDX.Size2 videoPixelSize, out int streamIndex);
Ejemplo n.º 32
0
 /// <summary>
 /// Function called when our layer needs resizing.
 /// </summary>
 /// <param name="newSize">The new size.</param>
 public void OnResize(DX.Size2 newSize)
 {
     OutputSize = newSize;
     OnResized();
 }
Ejemplo n.º 33
0
 public RectangleF GetZoomRect(Size imageSize, Size outputSize, DateTime displayTime)
 {
     return(_zoomRect);
 }
Ejemplo n.º 34
0
        /// <summary>
        /// Function to extract the rectangle that defines the sprite on the texture, in pixels.
        /// </summary>
        /// <param name="texture">The texture to evaluate.</param>
        /// <param name="column">The current column.</param>
        /// <param name="row">The current row.</param>
        /// <param name="offset">The offset of the grid from the upper left corner of the texture.</param>
        /// <param name="cellSize">The size of the cell, in pixels.</param>
        /// <returns>The pixel coordinates for the sprite.</returns>
        private DX.Rectangle GetSpriteRect(int column, int row, DX.Point offset, DX.Size2 cellSize)
        {
            var upperLeft = new DX.Point(column * cellSize.Width + offset.X, row * cellSize.Height + offset.Y);

            return(new DX.Rectangle(upperLeft.X, upperLeft.Y, cellSize.Width, cellSize.Height));
        }
Ejemplo n.º 35
0
    protected bool RefreshEffectParameters(IVideoPlayer player)
    {
      ISharpDXVideoPlayer sdvPlayer = player as ISharpDXVideoPlayer;
      if (sdvPlayer == null)
        return false;
      SizeF aspectRatio = sdvPlayer.VideoAspectRatio.ToSize2F();
      Size playerSize = sdvPlayer.VideoSize.ToSize2();
      Rectangle cropVideoRect = sdvPlayer.CropVideoRect;
      IGeometry geometry = ChooseVideoGeometry(player);
      string effectName = player.EffectOverride;
      int deviceWidth = GraphicsDevice.Width; // To avoid threading issues if the device size changes
      int deviceHeight = GraphicsDevice.Height;
      RectangleF vertsBounds = _vertsBounds;

      // Do we need a refresh?
      if (!_refresh &&
          _lastVideoSize == playerSize &&
          _lastAspectRatio == aspectRatio &&
          _lastCropVideoRect == cropVideoRect &&
          _lastGeometry == geometry &&
          _lastEffect == effectName &&
          _lastDeviceWidth == deviceWidth &&
          _lastDeviceHeight == deviceHeight &&
          _lastVertsBounds == vertsBounds)
        return true;

      SizeF targetSize = vertsBounds.Size;

      lock (sdvPlayer.SurfaceLock)
      {
        Surface surface = sdvPlayer.Surface;
        if (surface == null)
        {
          _refresh = true;
          return false;
        }
        SurfaceDescription desc = surface.Description;
        _videoTextureClip = new RectangleF(cropVideoRect.X / desc.Width, cropVideoRect.Y / desc.Height,
            cropVideoRect.Width / desc.Width, cropVideoRect.Height / desc.Height);
      }
      _scaledVideoSize = cropVideoRect.Size.ToSize2F();

      // Correct aspect ratio for anamorphic video
      if (!aspectRatio.IsEmpty() && geometry.RequiresCorrectAspectRatio)
      {
        float pixelRatio = aspectRatio.Width / aspectRatio.Height;
        _scaledVideoSize.Width = _scaledVideoSize.Height * pixelRatio;
      }
      // Adjust target size to match final Skin scaling
      targetSize = ImageContext.AdjustForSkinAR(targetSize);

      // Adjust video size to fit desired geometry
      _scaledVideoSize = geometry.Transform(_scaledVideoSize.ToDrawingSizeF(), targetSize.ToDrawingSizeF()).ToSize2F();

      // Cache inverse RelativeTransform
      Transform relativeTransform = RelativeTransform;
      _inverseRelativeTransformCache = (relativeTransform == null) ? Matrix.Identity : Matrix.Invert(relativeTransform.GetTransform());

      // Prepare our ImageContext
      _imageContext.FrameSize = targetSize;
      _imageContext.ShaderBase = EFFECT_BASE_VIDEO;
      _imageContext.ShaderTransform = geometry.Shader;
      _imageContext.ShaderEffect = player.EffectOverride;

      // Store state
      _lastFrameData = new Vector4(playerSize.Width, playerSize.Height, 0.0f, 0.0f);
      _lastVideoSize = playerSize;
      _lastAspectRatio = aspectRatio;
      _lastGeometry = geometry;
      _lastCropVideoRect = cropVideoRect;
      _lastEffect = effectName;
      _lastDeviceWidth = deviceWidth;
      _lastDeviceHeight = deviceHeight;

      _refresh = false;
      return true;
    }
Ejemplo n.º 36
0
 public RectangleF GetTextureClip(Size outputSize)
 {
   // TODO: Execute animation in own timer
   lock (_syncObj)
   {
     DateTime displayTime = _pauseTime.HasValue ? _pauseTime.Value : DateTime.Now;
     RectangleF textureClip = _animator.GetZoomRect(ImageSize.ToSize2(), outputSize, displayTime);
     return new RectangleF(textureClip.X * _textureMaxUV.Width, textureClip.Y * _textureMaxUV.Height, textureClip.Width * _textureMaxUV.Width, textureClip.Height * _textureMaxUV.Height);
   }
 }
Ejemplo n.º 37
0
 public RectangleF GetZoomRect(Size imageSize, Size outputSize, DateTime displayTime)
 {
   return _zoomRect;
 }
Ejemplo n.º 38
0
 /// <summary>
 /// Converts a <see cref="RectangleF"/> into a <see cref="Rectangle"/> with checking for proper surface coordinates in range from
 /// <see cref="new Point()"/> to <paramref name="clip"/>.
 /// </summary>
 /// <param name="rect">Source rect</param>
 /// <param name="clip">Maximum size</param>
 /// <returns>Converted rect</returns>
 protected Rectangle ToRect(RectangleF rect, Size clip)
 {
   int x = Math.Min(Math.Max(0, (int) Math.Floor(rect.X)), clip.Width); // Limit to 0 .. Width
   int y = Math.Min(Math.Max(0, (int) Math.Floor(rect.Y)), clip.Height); // Limit to 0 .. Height
   int width = Math.Min(Math.Max(0, (int) Math.Ceiling(rect.Width)), clip.Width - x); // Limit to 0 .. Width - x
   int height = Math.Min(Math.Max(0, (int) Math.Ceiling(rect.Height)), clip.Height - y); // Limit to 0 .. Height - y
   return new Rectangle(x, y, width, height);
 }
Ejemplo n.º 39
0
 public static Size ToEto(this s.Size2 value)
 {
     return(new Size(value.Width, value.Height));
 }
 /// <summary>
 /// Returns the zoom view rectangle for the current animation state for the given <see cref="outputSize"/>.
 /// </summary>
 /// <param name="animationProgress">Progress of the animation, value between 0 (= start) and 1 (=end).</param>
 /// <param name="imageSize">Size of the image to animate.</param>
 /// <param name="outputSize">Size of the output region.</param>
 /// <returns>Rectangle which contains fractions of the image size; X and Y coords go from 0 to 1.</returns>
 public abstract RectangleF GetZoomRect(float animationProgress, Size imageSize, Size outputSize);