Ejemplo n.º 1
0
        /// <summary>
        /// Converts rendered image to bitmap
        /// </summary>
        /// <returns></returns>
        private D2D1.BitmapRenderTarget RenderBitmap()
        {
            using (var textureToBitmap = Texture2D.FromSwapChain <Texture2D>(_swapChain, 0)) {
                using (var surface = textureToBitmap.QueryInterface <Surface>()) {
                    using (D2D1.Factory factory = new D2D1.Factory1()) {
                        var target = new D2D1.RenderTarget(
                            factory,
                            surface,
                            new D2D1.RenderTargetProperties(
                                new D2D1.PixelFormat(Format.B8G8R8A8_UNorm, D2D1.AlphaMode.Ignore)
                                )
                            );

                        D2D1.BitmapRenderTarget tes = null;

                        tes = new D2D1.BitmapRenderTarget(
                            target,
                            D2D1.CompatibleRenderTargetOptions.None,
                            new D2D1.PixelFormat(
                                Format.B8G8R8A8_UNorm,
                                D2D1.AlphaMode.Ignore));

                        target.Dispose();

                        return(tes);
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public VisualBrushImpl(
            VisualBrush brush,
            SharpDX.Direct2D1.RenderTarget target,
            Size targetSize)
        {
            var visual = brush.Visual;

            if (visual == null)
            {
                return;
            }

            var layoutable = visual as ILayoutable;

            if (layoutable?.IsArrangeValid == false)
            {
                layoutable.Measure(Size.Infinity);
                layoutable.Arrange(new Rect(layoutable.DesiredSize));
            }

            var tileMode = brush.TileMode;
            var sourceRect = brush.SourceRect.ToPixels(layoutable.Bounds.Size);
            var destinationRect = brush.DestinationRect.ToPixels(targetSize);
            var scale = brush.Stretch.CalculateScaling(destinationRect.Size, sourceRect.Size);
            var translate = CalculateTranslate(brush, sourceRect, destinationRect, scale);
            var intermediateSize = CalculateIntermediateSize(tileMode, targetSize, destinationRect.Size);
            var brtOpts = CompatibleRenderTargetOptions.None;

            // TODO: There are times where we don't need to draw an intermediate bitmap. Identify
            // them and directly use 'image' in those cases.
            using (var intermediate = new BitmapRenderTarget(target, brtOpts, intermediateSize))
            {
                Rect drawRect;
                var transform = CalculateIntermediateTransform(
                    tileMode,
                    sourceRect,
                    destinationRect,
                    scale,
                    translate,
                    out drawRect);
                var renderer = new RenderTarget(intermediate);

                using (var ctx = renderer.CreateDrawingContext())
                using (ctx.PushClip(drawRect))
                using (ctx.PushPostTransform(transform))
                {
                    intermediate.Clear(new Color4(0));
                    ctx.Render(visual);
                }

                this.PlatformBrush = new BitmapBrush(
                    target,
                    intermediate.Bitmap,
                    GetBitmapBrushProperties(brush),
                    GetBrushProperties(brush, destinationRect));
            }
        }
Ejemplo n.º 3
0
        public VisualBrushImpl(
            VisualBrush brush,
            RenderTarget target,
            Size targetSize)
        {
            var visual = brush.Visual;
            var layoutable = visual as ILayoutable;

            if (layoutable?.IsArrangeValid == false)
            {
                layoutable.Measure(Size.Infinity);
                layoutable.Arrange(new Rect(layoutable.DesiredSize));
            }

            var sourceRect = brush.SourceRect.ToPixels(layoutable.Bounds.Size);
            var destinationRect = brush.DestinationRect.ToPixels(targetSize);
            var bitmapSize = brush.TileMode == TileMode.None ? targetSize : destinationRect.Size;
            var scale = brush.Stretch.CalculateScaling(destinationRect.Size, sourceRect.Size);
            var translate = CalculateTranslate(brush, sourceRect, destinationRect, scale);
            var options = CompatibleRenderTargetOptions.None;

            using (var brt = new BitmapRenderTarget(target, options, bitmapSize.ToSharpDX()))
            {
                var renderer = new Renderer(brt);
                var transform = Matrix.CreateTranslation(-sourceRect.Position) *
                                Matrix.CreateScale(scale) *
                                Matrix.CreateTranslation(translate);

                Rect drawRect;

                if (brush.TileMode == TileMode.None)
                {
                    drawRect = destinationRect;
                    transform *= Matrix.CreateTranslation(destinationRect.Position);
                }
                else
                {
                    drawRect = new Rect(0, 0, destinationRect.Width, destinationRect.Height);
                }

                renderer.Render(visual, null, transform, drawRect);

                var result = new BitmapBrush(brt, brt.Bitmap);
                result.ExtendModeX = (brush.TileMode & TileMode.FlipX) != 0 ? ExtendMode.Mirror : ExtendMode.Wrap;
                result.ExtendModeY = (brush.TileMode & TileMode.FlipY) != 0 ? ExtendMode.Mirror : ExtendMode.Wrap;

                if (brush.TileMode != TileMode.None)
                {
                    result.Transform = SharpDX.Matrix3x2.Translation(
                        (float)destinationRect.X,
                        (float)destinationRect.Y);
                }

                PlatformBrush = result;
            }
        }
Ejemplo n.º 4
0
        public ImageBrushImpl(
            ImageBrush brush,
            SharpDX.Direct2D1.RenderTarget target,
            Size targetSize)
        {
            if (brush.Source == null)
            {
                return;
            }

            var image = ((BitmapImpl)brush.Source.PlatformImpl).GetDirect2DBitmap(target);
            var imageSize = new Size(brush.Source.PixelWidth, brush.Source.PixelHeight);
            var tileMode = brush.TileMode;
            var sourceRect = brush.SourceRect.ToPixels(imageSize);
            var destinationRect = brush.DestinationRect.ToPixels(targetSize);
            var scale = brush.Stretch.CalculateScaling(destinationRect.Size, sourceRect.Size);
            var translate = CalculateTranslate(brush, sourceRect, destinationRect, scale);
            var intermediateSize = CalculateIntermediateSize(tileMode, targetSize, destinationRect.Size);
            var brtOpts = CompatibleRenderTargetOptions.None;

            // TODO: There are times where we don't need to draw an intermediate bitmap. Identify
            // them and directly use 'image' in those cases.
            using (var intermediate = new BitmapRenderTarget(target, brtOpts, intermediateSize))
            {
                Rect drawRect;
                var transform = CalculateIntermediateTransform(
                    tileMode,
                    sourceRect,
                    destinationRect,
                    scale,
                    translate,
                    out drawRect);

                intermediate.BeginDraw();
                intermediate.PushAxisAlignedClip(drawRect.ToDirect2D(), AntialiasMode.Aliased);
                intermediate.Transform = transform.ToDirect2D();
                intermediate.DrawBitmap(image, 1, BitmapInterpolationMode.Linear);
                intermediate.PopAxisAlignedClip();
                intermediate.EndDraw();

                this.PlatformBrush = new BitmapBrush(
                    target, 
                    intermediate.Bitmap,
                    GetBitmapBrushProperties(brush),
                    GetBrushProperties(brush, destinationRect));
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Unload content and cleanup unmanaged resources.
        /// </summary>
        public override void UnloadContent()
        {
            base.UnloadContent();

            if (_state != null && !_state.IsDisposed)
            {
                _state.Dispose();
                _state = null;
            }
            if (_font != null)
            {
                _font.Dispose();
            }
            _font = null;
            if (_target != null)
            {
                _target.Dispose();
            }
            _target = null;
        }
Ejemplo n.º 6
0
        public TileBrushImpl(
            TileBrush brush,
            SharpDX.Direct2D1.RenderTarget target,
            Size targetSize)
        {
            var helper = new TileBrushImplHelper(brush, targetSize);
            if (!helper.IsValid)
                return;

            using (var intermediate = new BitmapRenderTarget(target, CompatibleRenderTargetOptions.None, helper.IntermediateSize.ToSharpDX()))
            {
                using (var ctx = new RenderTarget(intermediate).CreateDrawingContext())
                    helper.DrawIntermediate(ctx);

                PlatformBrush = new BitmapBrush(
                    target,
                    intermediate.Bitmap,
                    GetBitmapBrushProperties(brush),
                    GetBrushProperties(brush, helper.DestinationRect));
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Load Content and initialize unmanaged resources.
        /// </summary>
        public override void LoadContent()
        {
            int width  = 256;
            int height = 256;

            var size  = Surface.RenderTarget2D.PixelSize;
            var sizeV = new Vector2(size.Width, size.Height);

            _start        = sizeV - new Vector2(width, height) - new Vector2(10, 10);
            _end          = sizeV - new Vector2(10, 10);
            _viewLocation = new SharpDX.RectangleF(_start.X, _start.Y, _end.X - _start.X, _end.Y - _start.Y);

            base.LoadContent();

            if (_font == null || _font.IsDisposed)
            {
                _font = Surface.Fonts.GetTextFormat(MM_Repository.OverallDisplay.NetworkMapFont, 5);
            }

            if (_target == null || _target.IsDisposed)
            {
                _target = Surface.CreateRenderTarget(width, height);
            }

            MM_Boundary State;

            if (MM_Repository.Counties.TryGetValue("STATE", out State))
            {
                RawRectangleF bounds;
                var           geometry = Surface.CreateRegionPathGeometry(MM_Coordinates.ConvertPoints(State.Coordinates, 4).ToList(), out bounds, filled: true, simplify: true);
                geometry.Dispose();

                _scale = new Vector2(width / (bounds.Right - bounds.Left), height / (bounds.Bottom - bounds.Top));

                var geometryScaled = Surface.CreateRegionPathGeometry(MM_Coordinates.ConvertPoints(State.Coordinates, 4).ToList(), out bounds, filled: true, compression: 0.001f, simplify: true, scaleX: _scale.X, scaleY: _scale.Y);
                _location = new Vector2(bounds.Left, bounds.Top);

                _state = new RegionProxy(geometryScaled, State.DisplayParameter.ForeColor, State.DisplayParameter.Width, bounds);
            }
        }
Ejemplo n.º 8
0
        public SharpDX.Direct2D1.BitmapRenderTarget CreateRenderTarget(int height, int width)
        {
            var desc = new Texture2DDescription
            {
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format            = Format.R8G8B8A8_UNorm,
                Height            = height,
                Width             = width,
                MipLevels         = 1,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                OptionFlags       = ResourceOptionFlags.None,
                CpuAccessFlags    = CpuAccessFlags.None,
                ArraySize         = 1
            };

            var texture    = new Texture2D(Device, desc);
            var d3DSurface = texture.QueryInterface <Surface>();
            var rt2d       = new RenderTarget(Factory2D, d3DSurface, new RenderTargetProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)));
            var rt         = new SharpDX.Direct2D1.BitmapRenderTarget(rt2d, CompatibleRenderTargetOptions.None);

            rt.AntialiasMode = AntialiasMode;
            return(rt);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Sends bitmap to ViewModel through manager
        /// </summary>
        /// <param name="bitmapTarget"></param>
        /// <param name="data"></param>
        /// <param name="screenPoints"></param>
        /// <param name="manager"></param>
        private void DisplayBitmap(D2D1.BitmapRenderTarget bitmapTarget, byte[] data, List <List <windows.Point> > screenPoints, GraphView_StateManager manager)
        {
            if (bitmapTarget != null && data != null)
            {
                int   height    = 0;
                int   width     = 0;
                float dpiHeight = 0;
                float dpiWidth  = 0;

                using (var bitmap = bitmapTarget.Bitmap) {
                    height = bitmap.PixelSize.Height;
                    width  = bitmap.PixelSize.Width;

                    dpiHeight = bitmap.DotsPerInch.Height;
                    dpiWidth  = bitmap.DotsPerInch.Width;
                }

                bitmapTarget.Dispose();

                displayThread = new Thread(() => manager.SetupView(height, width, dpiHeight, dpiWidth, data, screenPoints));
                displayThread.SetApartmentState(ApartmentState.STA);
                displayThread.Start();
            }
        }
Ejemplo n.º 10
0
        public void Start()
        {
            if (ProcessStarted != null)
                ProcessStarted();

            int index           = 0;
            var rendererUtil    = new RendererUtil();

            // obtain file list
            var regionList      = Directory.GetFiles(Path.Combine(worldLocation, "region"), "*.mca").ToList();
            var regionEntries   = new List<RegionEntry>();

            foreach (string region in regionList)
            {
                try
                {
                    // load the region
                    using (RegionFile regionFile = RegionFile.OpenRegion(File.OpenRead(region)))
                    {
                        var renderedChunks = new List<ChunkEntry>();

                        if (RegionLoaded != null)
                            RegionLoaded(regionFile);

                        Debug.WriteLine("Rendering region");

                        DateTime sTime = DateTime.Now;

                        #region Chunk render

                        using (var renderTarget = new BitmapRenderTarget(rendererUtil.D2DDeviceContext, CompatibleRenderTargetOptions.None, new DrawingSizeF(16, 16), new DrawingSize(16, 16), new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)))
                        {
                            foreach (var anvilChunk in regionFile.Content.Select(chunk => new Anvil(chunk)))
                            {
                                ChunkEntry entry;
                                RenderSegment(anvilChunk, renderTarget, out entry);

                                renderedChunks.Add(entry);
                            }
                        }

                        #endregion

                        #region Region compositor

                        using (var renderTarget = new BitmapRenderTarget(rendererUtil.D2DDeviceContext, CompatibleRenderTargetOptions.None, new DrawingSizeF(512, 512), new DrawingSize(512, 512), new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)))
                        {
                            renderTarget.BeginDraw();

                            renderTarget.Clear(Color.Transparent);

                            // compose the images
                            foreach (ChunkEntry chunk in renderedChunks)
                            {
                                int cxPos = chunk.XPos % 32;
                                int czPos = chunk.ZPos % 32;

                                if (cxPos < 0)
                                    cxPos = 32 + cxPos;

                                if (czPos < 0)
                                    czPos = 32 + czPos;

                                int xPos = cxPos * 16;
                                int zPos = czPos * 16;

                                renderTarget.Transform = Matrix3x2.Translation(xPos, zPos);
                                renderTarget.DrawBitmap(chunk.RenderedChunk, 1, BitmapInterpolationMode.Linear);
                            }

                            // ReSharper disable PossibleNullReferenceException
                            string[] info = Path.GetFileNameWithoutExtension(region).Split('.');
                            // ReSharper restore PossibleNullReferenceException

                            regionEntries.Add(new RegionEntry
                            {
                                RenderedRegion  = renderTarget.Bitmap,
                                XPos            = Convert.ToInt32(info[1]),
                                ZPos            = Convert.ToInt32(info[2])
                            });

                            renderTarget.EndDraw();
                        }

                        #endregion

                        Debug.WriteLine("Render time is: " + (DateTime.Now - sTime).Seconds + " seconds.");

                        if (RegionRendered != null)
                            RegionRendered();

                        #region Cleanup

                        foreach (ChunkEntry chunk in renderedChunks)
                            chunk.RenderedChunk.Dispose();

                        renderedChunks.Clear();

                        #endregion
                    }
                }
                catch (Exception exception)
                {
                    if (ProcessFailed != null)
                        ProcessFailed(exception.Message + "\nAt:\n" + exception);
                }

                if (ProgressChanged != null)
                    ProgressChanged(++index / (float)regionList.Count);
            }

            #region Extrema processor

            int xMin = 0;
            int zMin = 0;

            int xMax = 0;
            int zMax = 0;

            foreach (RegionEntry entry in regionEntries)
            {
                if (xMin > entry.XPos)
                    xMin = entry.XPos;

                if (xMax < entry.XPos)
                    xMax = entry.XPos;

                if (zMin > entry.ZPos)
                    zMin = entry.ZPos;

                if (zMax < entry.ZPos)
                    zMax = entry.ZPos;
            }

            int wSizeX = (xMax - xMin) * 512 + 512;
            int wSizeZ = (zMax - zMin) * 512 + 512;

            xMin = Math.Abs(xMin);
            zMin = Math.Abs(zMin);

            #endregion

            #region World compositor

            var ResultingBitmap = new Bitmap1(rendererUtil.D2DDeviceContext,
                                              new DrawingSize(wSizeX, wSizeZ),
                                              new BitmapProperties1
                                              {
                                                  BitmapOptions = BitmapOptions.Target,
                                                  PixelFormat   = new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)
                                              });

            rendererUtil.D2DDeviceContext.Target = ResultingBitmap;

            rendererUtil.D2DDeviceContext.BeginDraw();

            rendererUtil.D2DDeviceContext.Clear(Color.Transparent);

            foreach (RegionEntry entry in regionEntries)
            {
                int xPos = ((xMin + entry.XPos) * 512);
                int zPos = ((zMin + entry.ZPos) * 512);

                rendererUtil.D2DDeviceContext.Transform = Matrix3x2.Translation(xPos, zPos);
                rendererUtil.D2DDeviceContext.DrawBitmap(entry.RenderedRegion, 1, BitmapInterpolationMode.Linear);
            }

            rendererUtil.D2DDeviceContext.EndDraw();

            #endregion

            #region File save

            FileStream file = File.OpenWrite(Path.GetFileName(worldLocation) + ".png");

            var encoder = new PngBitmapEncoder(rendererUtil.ImagingFactory);
            encoder.Initialize(file);

            var frameEncode = new BitmapFrameEncode(encoder);
            frameEncode.Initialize();

            var imageEncoder = new ImageEncoder(rendererUtil.ImagingFactory, rendererUtil.D2DDevice);
            imageEncoder.WriteFrame(ResultingBitmap,
                                    frameEncode,
                                    new ImageParameters(
                                        new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied),
                                        96,
                                        96,
                                        0,
                                        0,
                                        wSizeX,
                                        wSizeZ));

            frameEncode.Commit();
            encoder.Commit();

            #endregion

            #region Cleanup

            file.Close();
            file.Dispose();

            foreach (RegionEntry bitmap in regionEntries)
            {
                bitmap.RenderedRegion.Dispose();
            }

            regionEntries.Clear();

            rendererUtil.Dispose();
            theBlocks.Dispose();

            ResultingBitmap.Dispose();

            #endregion

            if (ProcessComplete != null)
                ProcessComplete();
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Creates a new D2dBitmapGraphics with specified pixel size for use during intermediate offscreen drawing
 /// that is compatible with the current D2dGraphics and has the same DPI, and pixel format
 /// as the current D2dGraphics and with the specified options</summary>        
 /// <param name="pixelSize">The desired size of the new D2dGraphics in pixels</param>
 /// <param name="options">Whether the new D2dBitmapGraphics must be compatible with GDI</param>   
 /// <returns>D2dBitmapGraphics with specified pixel size for use during intermediate offscreen drawing</returns>
 public D2dBitmapGraphics CreateCompatibleGraphics(Size pixelSize, D2dCompatibleGraphicsOptions options)
 {
     var dsize = new Size2(pixelSize.Width, pixelSize.Height);
     var rt = new BitmapRenderTarget(m_renderTarget, (CompatibleRenderTargetOptions)options, null, dsize, null);
     return new D2dBitmapGraphics(this, rt);
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Creates a new D2dBitmapGraphics with specified DIP size for use during intermediate offscreen drawing
 /// that is compatible with the current D2dGraphics and has the same DPI, and pixel format
 /// as the current D2dGraphics and with the specified options</summary>        
 /// <param name="size">The desired size of the new D2dGraphics in pixels</param>
 /// <param name="options">Whether the new D2dBitmapGraphics must be compatible with GDI</param> 
 /// <returns>D2dBitmapGraphics with specified DIP size for use during intermediate offscreen drawing</returns>
 public D2dBitmapGraphics CreateCompatibleGraphics(SizeF size, D2dCompatibleGraphicsOptions options)
 {
     var rt = new BitmapRenderTarget(m_renderTarget, (CompatibleRenderTargetOptions)options, size.ToSharpDX(), null, null);
     return new D2dBitmapGraphics(this, rt);
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Creates a new D2dBitmapGraphics for use during intermediate offscreen drawing 
 /// that is compatible with the current D2dGraphics and has the same size, DPI, and pixel format
 /// as the current D2dGraphics</summary>
 /// <returns>D2dBitmapGraphics for use during intermediate offscreen drawing</returns>
 public D2dBitmapGraphics CreateCompatibleGraphics()
 {
     var rt = new BitmapRenderTarget(m_renderTarget, CompatibleRenderTargetOptions.None);
     return new D2dBitmapGraphics(this, rt);
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Creates a new D2dBitmapGraphics for use during intermediate offscreen drawing 
        /// that is compatible with the current D2dGraphics and has the same size, DPI, and pixel format
        /// as the current D2dGraphics and with the specified options</summary>        
        /// <param name="options">Whether the new D2dBitmapGraphics must be compatible with GDI</param>    
        /// <returns>D2dBitmapGraphics for use during intermediate offscreen drawing</returns>
        public D2dBitmapGraphics CreateCompatibleGraphics(D2dCompatibleGraphicsOptions options)
        {
            var rt = new BitmapRenderTarget(m_renderTarget, (CompatibleRenderTargetOptions)options);
            return new D2dBitmapGraphics(this, rt);

        }
Ejemplo n.º 15
0
 public RenderBitmap1(d2d.RenderTarget parentRenderTarget)
 {
     renderTarget = new d2d.BitmapRenderTarget(parentRenderTarget, d2d.CompatibleRenderTargetOptions.None);
 }
Ejemplo n.º 16
0
 internal D2dBitmapGraphics(BitmapRenderTarget renderTarget)
     : base(renderTarget)
 {            
 }
Ejemplo n.º 17
0
 internal D2dBitmapGraphics(D2dGraphics owner,BitmapRenderTarget renderTarget)
     : base(renderTarget)
 {
     m_owner = owner;
 }
Ejemplo n.º 18
0
        public override void Draw(DrawData dd)
        {
            //	draw wave data
            byte[] wavedata = dd.Song.WaveformData;

            if (wavedata != null)
            {
#if (MARKERS)
                Markers.WriteFlag("Wave");
#endif

                int fnd = -1;
                for (int ndx = dd.LFT / Global.pxpersec; ndx < (dd.RIT + Global.pxpersec - 1) / Global.pxpersec; ndx++)
                {
                    if (resources.Wave_Bmps[ndx] == null)
                    {
                        fnd = ndx;
                        break;
                    }
                }

                if (fnd == -1)
                {
                    for (int ndx = 0; ndx < resources.Wave_Bmps.Length; ndx++)
                    {
                        if (resources.Wave_Bmps[ndx] == null)
                        {
                            fnd = ndx;
                            break;
                        }
                    }
                }

                if (fnd != -1)
                {
                    var ht   = Global.Wave_Height;
                    var half = ht >> 1;

                    using (var renderT = new SharpDX.Direct2D1.BitmapRenderTarget(dd.target, CompatibleRenderTargetOptions.None, new Size2F(Global.pxpersec, ht),
                                                                                  null, new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied)))
                    {
                        renderT.BeginDraw();
                        renderT.Clear(SharpDX.Color.Black);

                        using (var path = new PathGeometry(Global.Instance.factory2D1))
                        {
                            var sink = path.Open();
                            sink.BeginFigure(new Vector2(Global.pxpersec, half + 1), FigureBegin.Hollow);
                            sink.AddLine(new Vector2(0, half + 1));
                            for (int ndx = 0, src = fnd * 2 * Global.pxpersec; ndx < Global.pxpersec && src < wavedata.Length; ndx++, src += 2)
                            {
                                sink.AddLine(new Vector2(ndx, half + 1 + wavedata[src]));
                            }
                            sink.EndFigure(FigureEnd.Open);
                            sink.Close();

                            renderT.DrawGeometry(path, resources.Wave_RedBrush);
                        }

                        using (var path = new PathGeometry(Global.Instance.factory2D1))
                        {
                            var sink = path.Open();
                            sink.BeginFigure(new Vector2(Global.pxpersec, half - 1), FigureBegin.Hollow);
                            sink.AddLine(new Vector2(0, half - 1));
                            for (int ndx = 0, src = fnd * 2 * Global.pxpersec + 1; ndx < Global.pxpersec && src < wavedata.Length; ndx++, src += 2)
                            {
                                sink.AddLine(new Vector2(ndx, half - 1 - wavedata[src]));
                            }
                            sink.EndFigure(FigureEnd.Open);
                            sink.Close();

                            renderT.DrawGeometry(path, resources.Wave_GreenBrush);
                        }

                        renderT.EndDraw();

                        resources.Wave_Bmps[fnd] = renderT.Bitmap;
                    }
                }


                for (int ndx = dd.LFT / Global.pxpersec, bgn = ndx * Global.pxpersec; ndx < resources.Wave_Bmps.Length && bgn <= dd.RIT; ndx++, bgn += Global.pxpersec)
                {
                    var bmp = resources.Wave_Bmps[ndx];
                    if (bmp == null)
                    {
                        break;
                    }

                    dd.target.DrawBitmap(bmp, new RectangleF(bgn, Global.Wave_Channels, Global.pxpersec, Global.Wave_Height), 1.0f, BitmapInterpolationMode.NearestNeighbor,
                                         new RectangleF(0, 0, Global.pxpersec, Global.Wave_Height));
                }

#if (MARKERS)
                Markers.WriteFlag("WaveEnd");
#endif
            }
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Creates a new D2dBitmapGraphics with specified DIP size for use during intermediate offscreen drawing
 /// that is compatible with the current D2dGraphics and has the same DPI, and pixel format
 /// as the current D2dGraphics and with the specified options</summary>        
 /// <param name="size">The desired size of the new D2dGraphics in pixels</param>
 /// <param name="options">Whether the new D2dBitmapGraphics must be compatible with GDI</param>        
 public D2dBitmapGraphics CreateCompatibleGraphics(SizeF size, D2dCompatibleGraphicsOptions options)
 {
     var dsize = new DrawingSizeF(size.Width, size.Height);
     var rt = new BitmapRenderTarget(m_renderTarget, (CompatibleRenderTargetOptions)options, dsize, null, null);
     return new D2dBitmapGraphics(rt);
 }
Ejemplo n.º 20
0
        public VisualBrushImpl(
            VisualBrush brush,
            RenderTarget target,
            Size targetSize)
        {
            var visual = brush.Visual;

            if (visual == null)
            {
                return;
            }

            var layoutable = visual as ILayoutable;

            if (layoutable?.IsArrangeValid == false)
            {
                layoutable.Measure(Size.Infinity);
                layoutable.Arrange(new Rect(layoutable.DesiredSize));
            }

            var tileMode = brush.TileMode;
            var sourceRect = brush.SourceRect.ToPixels(layoutable.Bounds.Size);
            var destinationRect = brush.DestinationRect.ToPixels(targetSize);
            var scale = brush.Stretch.CalculateScaling(destinationRect.Size, sourceRect.Size);
            var translate = CalculateTranslate(brush, sourceRect, destinationRect, scale);
            var intermediateSize = CalculateIntermediateSize(tileMode, targetSize, destinationRect.Size);
            var brtOpts = CompatibleRenderTargetOptions.None;

            // TODO: There are times where we don't need to draw an intermediate bitmap. Identify
            // them and directly use 'image' in those cases.
            using (var intermediate = new BitmapRenderTarget(target, brtOpts, intermediateSize))
            {
                Rect drawRect;
                var transform = CalculateIntermediateTransform(
                    tileMode,
                    sourceRect,
                    destinationRect,
                    scale,
                    translate,
                    out drawRect);
                var renderer = new Renderer(intermediate);

                renderer.Render(visual, null, transform, drawRect);

                this.PlatformBrush = new BitmapBrush(
                    target,
                    intermediate.Bitmap,
                    GetBitmapBrushProperties(brush),
                    GetBrushProperties(brush, destinationRect));
            }

            //var sourceRect = brush.SourceRect.ToPixels(layoutable.Bounds.Size);
            //var destinationRect = brush.DestinationRect.ToPixels(targetSize);
            //var bitmapSize = brush.TileMode == TileMode.None ? targetSize : destinationRect.Size;
            //var scale = brush.Stretch.CalculateScaling(destinationRect.Size, sourceRect.Size);
            //var translate = CalculateTranslate(brush, sourceRect, destinationRect, scale);
            //var options = CompatibleRenderTargetOptions.None;

            //using (var brt = new BitmapRenderTarget(target, options, bitmapSize.ToSharpDX()))
            //{
            //    var renderer = new Renderer(brt);
            //    var transform = Matrix.CreateTranslation(-sourceRect.Position) *
            //                    Matrix.CreateScale(scale) *
            //                    Matrix.CreateTranslation(translate);

            //    Rect drawRect;

            //    if (brush.TileMode == TileMode.None)
            //    {
            //        drawRect = destinationRect;
            //        transform *= Matrix.CreateTranslation(destinationRect.Position);
            //    }
            //    else
            //    {
            //        drawRect = new Rect(0, 0, destinationRect.Width, destinationRect.Height);
            //    }

            //    renderer.Render(visual, null, transform, drawRect);

            //    var result = new BitmapBrush(brt, brt.Bitmap);
            //    result.ExtendModeX = GetExtendModeX(brush.TileMode);
            //    result.ExtendModeY = GetExtendModeY(brush.TileMode);

            //    if (brush.TileMode != TileMode.None)
            //    {
            //        result.Transform = SharpDX.Matrix3x2.Translation(
            //            (float)destinationRect.X,
            //            (float)destinationRect.Y);
            //    }

            //    PlatformBrush = result;
            //}
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Starts render loop
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="View"></param>
        public void Render(GraphView_StateManager manager, View.GraphView_CurveView View)
        {
            var signature = CreateShaders("Smooth.fx");
            //var signature = CreateShaders();
            var layout = new InputLayout(_device, signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32B32A32_Float, 32, 0)
            });

            SetSamplerState();

            // Instantiate buffers
            CreateVertexBuffer();
            CreateConstantBuffer();

            // Prepare Context
            SetUpContext(layout);

            // Prepare matrices
            var    view = Matrix.OrthoLH(_RenderForm.ClientSize.Width, _RenderForm.ClientSize.Width, 0.00f, 10000.0f);
            Matrix proj = Matrix.Identity;

            // Declare texture for rendering
            bool             userResized = true;
            Texture2D        backBuffer  = null;
            RenderTargetView renderView  = null;
            Texture2D        depthBuffer = null;
            DepthStencilView depthView   = null;

            var camera = ((ViewModel.CurveGraphViewModel)manager.ViewModel).Camera;

            var rastDesc = new RasterizerStateDescription {
                FillMode = FillMode.Solid,
                CullMode = CullMode.None,
                IsAntialiasedLineEnabled = true,
                IsMultisampleEnabled     = true
            };

            var viewPort = new Viewport(0, 0, _RenderForm.ClientSize.Width, _RenderForm.ClientSize.Height);

            _RenderForm.UserResized += (sender, args) => userResized = true;


            // Main loop
            RenderLoop.Run(_RenderForm, () => {
                //TODO: Check for if collectionchanged event has been raised and trigger vertex recalculation

                if (IsViewModelChanged || !MessageQueue.IsEmpty || true)
                {
                    CreateSwapChain();

                    IsViewModelChanged = false;

                    if (true)
                    {
                        if (WindowResized())
                        {
                            userResized = true;
                        }

                        SetSamplerState();
                    }

                    // If Form resized
                    if (userResized)
                    {
                        Console.WriteLine("resizing");
                        // Dispose all previous allocated resources
                        Utilities.Dispose(ref backBuffer);
                        Utilities.Dispose(ref renderView);
                        Utilities.Dispose(ref depthBuffer);
                        Utilities.Dispose(ref depthView);

                        // Resizing buffers
                        _swapChain.ResizeBuffers(
                            _SwapDesc.BufferCount,
                            //2048,
                            //1280,
                            _RenderForm.Width,
                            _RenderForm.Height,
                            Format.B8G8R8A8_UNorm,
                            SwapChainFlags.None
                            );

                        backBuffer = Texture2D.FromSwapChain <Texture2D>(_swapChain, 0);
                        renderView = new RenderTargetView(_device, backBuffer);

                        // Create the depth buffer
                        depthBuffer = new Texture2D(_device, new Texture2DDescription()
                        {
                            Format    = Format.D32_Float_S8X24_UInt,
                            ArraySize = 1,
                            MipLevels = 1,
                            //Width = 2048,
                            //Height = 1280,
                            Width             = _RenderForm.Width,
                            Height            = _RenderForm.Height,
                            SampleDescription = new SampleDescription(1, 0),
                            Usage             = ResourceUsage.Default,
                            BindFlags         = BindFlags.DepthStencil,
                            CpuAccessFlags    = CpuAccessFlags.None,
                            OptionFlags       = ResourceOptionFlags.None
                        });

                        // Create the depth buffer view
                        depthView       = new DepthStencilView(_device, depthBuffer);
                        viewPort.Width  = _RenderForm.ClientSize.Width;
                        viewPort.Height = _RenderForm.ClientSize.Height;

                        // Setup targets and viewport for rendering
                        _context.Rasterizer.SetViewport(viewPort);
                        _context.OutputMerger.SetTargets(depthView, renderView);
                        _context.Rasterizer.State = new RasterizerState(_device, rastDesc);

                        userResized = false;
                    }

                    Thread vertexThread = new Thread(() => CalculateQuads(manager));
                    vertexThread.Start();

                    // World Matrix
                    // The World Matrix translates the position of your vertices from model space to World space.
                    // That means it applies its position in the world and its rotation
                    var world = CalculateWorldTransform(camera);

                    // A view matrix tells the GPU the position of the camera, the point the camera is facing,
                    // and the up vector for the camera
                    view = Matrix.LookAtLH(new Vector3(0, 0, -100), new Vector3(0, 0, 0), Vector3.Up);

                    // A projection matrix tells the GPU the FOV, aspect ratio, and near and far clipping planes for the camera
                    //proj = Matrix.OrthoLH(1280, 720, 0.00f, 1000.0f);
                    proj         = Matrix.OrthoLH(screenWidth, screenHeight, 0.00f, 1000.0f);
                    var viewProj = Matrix.Multiply(view, proj);

                    //var worldViewProj = Matrix.Multiply(world, proj);
                    var worldViewProj = Matrix.Multiply(world, viewProj);

                    // Clear views and set background as transparent
                    _context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
                    _context.ClearRenderTargetView(renderView, new SharpDX.Mathematics.Interop.RawColor4(0, 0, 0, 0.0f));

                    var screenPoints = PointToScreenSpace(manager, viewPort, worldViewProj);

                    worldViewProj.Transpose();

                    _context.UpdateSubresource(ref worldViewProj, _ConstantBuffer);

                    // Instantiate Vertex buffer from vertex data
                    vertexThread.Join();
                    CreateVertexBuffer();
                    SetUpContext(layout);

                    // Draw
                    _context.Draw(vertices.Length, 0);

                    // Convert backbuffer to texture, then to bitmap for display
                    D2D1.BitmapRenderTarget target = RenderBitmap();

                    // Get byte array for bitmap
                    byte[] data = CalculateBitmapBytes(backBuffer);

                    DisplayBitmap(target, data, screenPoints, manager);

                    // Dispose all previous allocated resources
                    _context.Flush();
                    screenPoints = null;
                    GC.Collect();

                    if (displayThread != null)
                    {
                        displayThread.Join();
                    }

                    mre.Reset();
                    mre.WaitOne();
                }
                // End of renderloop
            });

            // Release all resources
            _context.ClearState();
            _context.Flush();
            DisposeResources();

            signature.Dispose();
            layout.Dispose();

            depthBuffer.Dispose();
            backBuffer.Dispose();

            depthView.Dispose();
            renderView.Dispose();
        }