Esempio n. 1
0
 protected override SharpDX.DXGI.SwapChain2 CreateSwapChain(SharpDX.DXGI.Factory2 factory, SharpDX.Direct3D11.Device1 device, SharpDX.DXGI.SwapChainDescription1 desc)
 {
     // Creates a SwapChain from a CoreWindow pointer
     using (var comWindow = new ComObject(window))
     using (var swapChain1 = new SwapChain1(factory, device, comWindow, ref desc))
         return swapChain1.QueryInterface<SwapChain2>();
 }
Esempio n. 2
0
        public Result DrawGlyphRun(
            object clientDrawingContext, 
            float baselineOriginX, 
            float baselineOriginY, 
            MeasuringMode measuringMode, 
            GlyphRun glyphRun, 
            GlyphRunDescription glyphRunDescription, 
            ComObject clientDrawingEffect)
        {
            var wrapper = clientDrawingEffect as BrushWrapper;
            var brush = (wrapper == null) ?
                this.foreground :
                wrapper.Brush.ToDirect2D(this.renderTarget);

            this.renderTarget.DrawGlyphRun(
                new Vector2(baselineOriginX, baselineOriginY),
                glyphRun,
                brush,
                measuringMode);

            if (wrapper != null)
            {
                brush.Dispose();
            }

            return Result.Ok;
        }
Esempio n. 3
0
        private void InitRenderTarget(IntPtr surface)
        {
            IntPtr sharedHandle;

            var c = new SharpDX.ComObject(surface);
            var D3DImageResource = c.QueryInterface <SharpDX.DXGI.Resource>();


            sharedHandle = D3DImageResource.SharedHandle;

            var tempResource    = D3DDevice.OpenSharedResource <SharpDX.Direct3D11.Resource>(sharedHandle);
            var d3DImageTexture = tempResource.QueryInterface <Texture2D>();

            RenderTarget = new RenderTargetView(D3DDevice, d3DImageTexture);

            var vp = new ViewportF {
                Width    = (float)host.ActualWidth,
                Height   = (float)host.ActualHeight,
                MinDepth = 0.0f,
                MaxDepth = 1.0f
            };

            D3DContext.Rasterizer.SetViewport(vp);
            D3DContext.OutputMerger.SetRenderTargets(RenderTarget);

            ////Cleanup
            tempResource.Dispose();
            d3DImageTexture.Dispose();
        }
        public Result DrawGlyphRun(
            object clientDrawingContext,
            float baselineOriginX,
            float baselineOriginY,
            MeasuringMode measuringMode,
            GlyphRun glyphRun,
            GlyphRunDescription glyphRunDescription,
            ComObject clientDrawingEffect)
        {
            var wrapper = clientDrawingEffect as BrushWrapper;

            // TODO: Work out how to get the size below rather than passing new Size().
            var brush = (wrapper == null) ?
                _foreground :
                _context.CreateBrush(wrapper.Brush, new Size()).PlatformBrush;

            _renderTarget.DrawGlyphRun(
                new RawVector2 { X = baselineOriginX, Y = baselineOriginY },
                glyphRun,
                brush,
                measuringMode);

            if (wrapper != null)
            {
                brush.Dispose();
            }

            return Result.Ok;
        }
Esempio n. 5
0
        DXGI.SwapChain1 IDirect3DWindow.CreateSwapChain(D3D11.Device1 device, ref DXGI.SwapChainDescription1 description)
        {
            var dxgiDevice = device.QueryInterface<DXGI.Device1>();
            var dxgiAdapter = dxgiDevice.Adapter;

            var dxgiFactory = dxgiAdapter.GetParent<DXGI.Factory2>();

            var coWindow = new SharpDX.ComObject(_coreWindow);
            return dxgiFactory.CreateSwapChainForCoreWindow(dxgiDevice, coWindow, ref description, null);
        }
Esempio n. 6
0
        /// <summary>
        /// Opens the given video file and plays it directly.
        /// </summary>
        /// <param name="videoLink">The link to the video file.</param>
        public async Task OpenAndShowVideoFileAsync(ResourceLink videoLink)
        {
            // Check for correct state
            if (this.State != MediaPlayerState.NothingToDo)
            {
                throw new InvalidOperationException("Unable to open video file as long as there is another video playing!");
            }

            // Apply new state
            this.State = MediaPlayerState.Opening;

            try
            {
                // Create media session and a corresponding event listener obect for async events
                MF.MediaFactory.CreateMediaSession(null, out m_mediaSession);
                m_sessionEventHandler = MFSessionEventListener.AttachTo(m_mediaSession);
                m_sessionEventHandler.EndOfPresentation += OnSessionEventHandlerEndOfPresentationReached;

                // Create source object
                MF.SourceResolver sourceResolver = new MF.SourceResolver();
                MF.ObjectType     objType        = MF.ObjectType.Invalid;
                m_videoSourceStreamNet = videoLink.OpenInputStream();
                m_videoSourceStream    = new MF.ByteStream(m_videoSourceStreamNet);
                SharpDX.ComObject objSource = sourceResolver.CreateObjectFromStream(
                    m_videoSourceStream,
                    "Dummy." + videoLink.FileExtension,
                    MF.SourceResolverFlags.MediaSource,
                    out objType);
                using (MF.MediaSource mediaSource = objSource.QueryInterface <MF.MediaSource>())
                {
                    GraphicsHelper.SafeDispose(ref objSource);
                    GraphicsHelper.SafeDispose(ref sourceResolver);

                    await ShowVideoAsync(mediaSource);
                }

                // Video opened successfully
                m_currentVideoLink     = videoLink;
                m_currentCaptureDevice = null;
                this.State             = MediaPlayerState.Playing;
            }
            catch (Exception)
            {
                // Unload all resources in case of an exception
                DisposeResources();

                throw;
            }
        }
Esempio n. 7
0
        public void InitRenderTargetSurface(IntPtr Resource)
        {
            ZBuffer?.Dispose();
            DepthStencilViewRef?.Dispose();
            RenderTargetViewRef?.Dispose();
            RenderTarget2D?.Dispose();

            SharpDX.DXGI.Resource dxgiResource;
            using (var r = new SharpDX.ComObject(Resource)) {
                dxgiResource = r.QueryInterface <SharpDX.DXGI.Resource>();
            }

            Texture2D OutputResource = DeviceRef.OpenSharedResource <Texture2D>(dxgiResource.SharedHandle);

            using (var surface = DeviceRef.OpenSharedResource <Surface>(dxgiResource.SharedHandle)) {
                RenderTarget2D = new RenderTarget(Factory2D, surface, RenderTarget2DProperites);
            }

            //Crash everything
            //dxgiResource.Dispose();

            RenderTarget2D.AntialiasMode     = AntialiasMode.PerPrimitive;
            RenderTarget2D.TextAntialiasMode = TextAntialiasMode.Cleartype;

            RenderTargetViewRef = new RenderTargetView(DeviceRef, OutputResource);

            Texture2DDescription OutputDesc = OutputResource.Description;

            if (OutputDesc.Width != Width || OutputDesc.Height != Height)
            {
                Width  = OutputDesc.Width;
                Height = OutputDesc.Height;
                SetUpViewport();
            }

            ZBufferTextureDescription.Width  = Width;
            ZBufferTextureDescription.Height = Height;
            ZBuffer = new Texture2D(DeviceRef, ZBufferTextureDescription);

            DepthStencilViewRef = new DepthStencilView(DeviceRef, ZBuffer, new DepthStencilViewDescription {
                Format    = Format.D32_Float,
                Dimension = DepthStencilViewDimension.Texture2D,
                Flags     = DepthStencilViewFlags.None,
            });

            Context.OutputMerger.SetRenderTargets(DepthStencilViewRef, RenderTargetViewRef);
            OnInitRenderTarget?.Invoke();
            OutputResource?.Dispose();
        }
Esempio n. 8
0
 public static ObjectReference Find(ComObject comObject)
 {
     lock (ObjectTracker.ObjectReferences)
       {
     List<ObjectReference> local_0;
     if (ObjectTracker.ObjectReferences.TryGetValue(comObject.NativePointer, out local_0))
     {
       foreach (ObjectReference item_0 in local_0)
       {
     if (object.ReferenceEquals(item_0.Object.Target, (object) comObject))
       return item_0;
       }
     }
       }
       return (ObjectReference) null;
 }
Esempio n. 9
0
        public override Result DrawGlyphRun(object clientDrawingContext, float baselineOriginX, float baselineOriginY, MeasuringMode measuringMode, GlyphRun glyphRun, GlyphRunDescription glyphRunDescription, ComObject clientDrawingEffect)
        {
            SolidColorBrush sb = defaultBrush;
            if (clientDrawingEffect != null && clientDrawingEffect is SolidColorBrush)
            {
                sb = (SolidColorBrush)clientDrawingEffect;
            }

            try
            {
                this.renderTarget.DrawGlyphRun(new Vector2(baselineOriginX, baselineOriginY), glyphRun, sb, measuringMode);
                return Result.Ok;
            }
            catch
            {
                return Result.Fail;
            }
        }
Esempio n. 10
0
        public Result DrawGlyphRun(object clientDrawingContext, float baselineOriginX, float baselineOriginY, MeasuringMode measuringMode, GlyphRun glyphRun, GlyphRunDescription glyphRunDescription, ComObject clientDrawingEffect)
        {
            var pathGeometry = new PathGeometry(_d2DFactory);
            var geometrySink = pathGeometry.Open();

            var fontFace = glyphRun.FontFace;
            if (glyphRun.Indices.Length > 0)
                fontFace.GetGlyphRunOutline(glyphRun.FontSize, glyphRun.Indices, glyphRun.Advances, glyphRun.Offsets, glyphRun.IsSideways, glyphRun.BidiLevel % 2 != 0, geometrySink);
            geometrySink.Close();
            geometrySink.Dispose();
            fontFace.Dispose();

            var matrix = new Matrix3x2()
            {
                M11 = 1,
                M12 = 0,
                M21 = 0,
                M22 = 1,
                M31 = baselineOriginX,
                M32 = baselineOriginY
            };

            var transformedGeometry = new TransformedGeometry(_d2DFactory, pathGeometry, matrix);

            var  brushColor = (Color4)Color.Black;

            if (clientDrawingEffect != null && clientDrawingEffect is ColorDrawingEffect)
                brushColor = (clientDrawingEffect as ColorDrawingEffect).Color;

            var brush = new SolidColorBrush(_renderTarget, brushColor);
            
            _renderTarget.DrawGeometry(transformedGeometry, brush);
            _renderTarget.FillGeometry(transformedGeometry, brush);

            pathGeometry.Dispose();
            transformedGeometry.Dispose();
            brush.Dispose();

            return SharpDX.Result.Ok;
        }
Esempio n. 11
0
        public override Result DrawStrikethrough(object clientDrawingContext, float baselineOriginX, float baselineOriginY, ref Strikethrough strikethrough, ComObject clientDrawingEffect)
        {
            PathGeometry pg = new PathGeometry(this.factory);
            GeometrySink sink = pg.Open();

            Vector2 topLeft = new Vector2(0.0f, strikethrough.Offset);
            sink.BeginFigure(topLeft, FigureBegin.Filled);
            topLeft.X += strikethrough.Width;
            sink.AddLine(topLeft);
            topLeft.Y += strikethrough.Thickness;
            sink.AddLine(topLeft);
            topLeft.X -= strikethrough.Width;
            sink.AddLine(topLeft);
            sink.EndFigure(FigureEnd.Closed);
            sink.Close();

            TransformedGeometry tg = new TransformedGeometry(this.factory, pg, Matrix3x2.Translation(baselineOriginX, baselineOriginY) * Matrix3x2.Scaling(1.0f, -1.0f));
            pg.Dispose();

            this.AddGeometry(tg);
            return Result.Ok;
        }
 /// <summary>
 /// IDWriteTextLayout::Draw calls this function to instruct the client to draw a strikethrough.
 /// </summary>
 /// <param name="clientDrawingContext">The application-defined drawing context passed to  IDWriteTextLayout::Draw.</param>
 /// <param name="baselineOriginX">The pixel location (X-coordinate) at the baseline origin of the run where strikethrough applies.</param>
 /// <param name="baselineOriginY">The pixel location (Y-coordinate) at the baseline origin of the run where strikethrough applies.</param>
 /// <param name="strikethrough">Pointer to  a structure containing strikethrough logical information.</param>
 /// <param name="clientDrawingEffect">Application-defined effect to apply to the strikethrough.  Usually this argument represents effects such as the foreground brush filling the interior of a line.</param>
 /// <returns>
 /// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.
 /// </returns>
 /// <unmanaged>HRESULT DrawStrikethrough([None] void* clientDrawingContext,[None] FLOAT baselineOriginX,[None] FLOAT baselineOriginY,[In] const DWRITE_STRIKETHROUGH* strikethrough,[None] IUnknown* clientDrawingEffect)</unmanaged>
 /// <remarks>
 /// A single strikethrough can be broken into multiple calls, depending on how the formatting changes attributes. Strikethrough is not averaged across font sizes/styles changes. To get an appropriate starting pixel position, add strikethrough::offset to the baseline. Like underlines, the x coordinate will always be passed as the left side, regardless of text directionality.
 /// </remarks>
 public override SDX.Result DrawStrikethrough(object clientDrawingContext, float baselineOriginX, float baselineOriginY, ref Strikethrough strikethrough, SDX.ComObject clientDrawingEffect)
 {
     return(SDX.Result.Ok);
 }
Esempio n. 13
0
        public override SharpDXLib.Result DrawGlyphRun(object clientDrawingContext, float baselineOriginX, float baselineOriginY, MeasuringMode measuringMode, GlyphRun glyphRun, GlyphRunDescription glyphRunDescription, SharpDXLib.ComObject clientDrawingEffect)
        {
            var cce  = (ClientTextEffect)clientDrawingEffect;
            var args = (Object[])clientDrawingContext;
            var ofs  = (Point)args[0];
            var ut   = (UText)args[1];

            Point origin = new Point(baselineOriginX, baselineOriginY);

            var fgb = cce == null ? defaultEffect.fgBrush : cce.fgBrush;

            rt.DrawGlyphRun(D2DTr.tr(origin), glyphRun, fgb, MeasuringMode.Natural);

            return(SharpDXLib.Result.Ok);
        }
Esempio n. 14
0
 public static T QueryInterface <T>(object comObject) where T : ComObject
 {
     using (ComObject comObject1 = new ComObject(Marshal.GetIUnknownForObject(comObject)))
         return(comObject1.QueryInterface <T>());
 }
Esempio n. 15
0
 public static void Track(ComObject comObject)
 {
     if (comObject == null || comObject.NativePointer == IntPtr.Zero)
     return;
       lock (ObjectTracker.ObjectReferences)
       {
     List<ObjectReference> local_0;
     if (!ObjectTracker.ObjectReferences.TryGetValue(comObject.NativePointer, out local_0))
     {
       local_0 = new List<ObjectReference>();
       ObjectTracker.ObjectReferences.Add(comObject.NativePointer, local_0);
     }
     local_0.Add(new ObjectReference(DateTime.Now, comObject, new StackTrace(3, true)));
       }
 }
Esempio n. 16
0
 public static T As <T>(IntPtr iunknownPtr) where T : ComObject
 {
     using (ComObject comObject = new ComObject(iunknownPtr))
         return(comObject.QueryInterface <T>());
 }
        private void HandleDeviceChangeEnd(object sender, EventArgs e)
        {
            var device = _graphicsDeviceManager.GraphicsDevice;

            var swapChain = (SwapChain)device.Presenter.NativePresenter;
            var d = swapChain.Description;

            var d3DDevice = (SharpDX.Direct3D11.Device)device;
            using (var dxgiDevice = d3DDevice.QueryInterface<Device3>())
            {
                var adapter = dxgiDevice.Adapter;
                var factory = adapter.GetParent<Factory2>();

                var description = new SwapChainDescription1
                                  {
                                      Width = d.ModeDescription.Width,
                                      Height = d.ModeDescription.Height,
                                      Format = d.ModeDescription.Format,
                                      Stereo = false,
                                      SampleDescription = new SampleDescription(1, 0),
                                      Usage = Usage.RenderTargetOutput,
                                      BufferCount = 2,
                                      SwapEffect = SwapEffect.FlipSequential,
                                      Flags = SwapChainFlags.ForegroundLayer,
                                      Scaling = Scaling.None,
                                      AlphaMode = AlphaMode.Premultiplied
                                  };

                // create the foreground swap chain for the core window
                using (var comWindow = new ComObject(Window.NativeWindow))
                    _foregroundChain = new SwapChain1(factory, (SharpDX.Direct3D11.Device)device, comWindow, ref description);

                // recreate the foreground render target
                using (var backBuffer = _foregroundChain.GetBackBuffer<SharpDX.Direct3D11.Texture2D>(0))
                    _foregroundRenderTarget = RenderTarget2D.New(device, backBuffer);
            }
        }
Esempio n. 18
0
 internal unsafe void SetFromNative(int index, ComObject value)
 {
     this.values[index] = value;
       value.NativePointer = ((IntPtr*) (void*) this.nativeBuffer)[index];
 }
Esempio n. 19
0
 private void CreateSwapChain(ref SwapChainDescription1 swapChainDescription1, Factory4 factory)
 {
     using (var sc1 = new SwapChain1(factory, commandQueue, ref swapChainDescription1))
     {
         swapChain = Collect(sc1.QueryInterface<SwapChain3>());
         using (var comPtr = new ComObject(panel))
         {
             using (var native = comPtr.QueryInterface<ISwapChainPanelNative>())
             {
                 native.SwapChain = swapChain;
             }
         }
     }
 }
 /// <summary>
 /// IDWriteTextLayout::Draw calls this application callback when it needs to draw an inline object.
 /// </summary>
 /// <param name="clientDrawingContext">The application-defined drawing context passed to IDWriteTextLayout::Draw.</param>
 /// <param name="originX">X-coordinate at the top-left corner of the inline object.</param>
 /// <param name="originY">Y-coordinate at the top-left corner of the inline object.</param>
 /// <param name="inlineObject">The application-defined inline object set using IDWriteTextFormat::SetInlineObject.</param>
 /// <param name="isSideways">A Boolean flag that indicates whether the object's baseline runs alongside the baseline axis of the line.</param>
 /// <param name="isRightToLeft">A Boolean flag that indicates whether the object is in a right-to-left context, hinting that the drawing may want to mirror the normal image.</param>
 /// <param name="clientDrawingEffect">Application-defined drawing effects for the glyphs to render. Usually this argument represents effects such as the foreground brush filling the interior of a line.</param>
 /// <returns>
 /// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.
 /// </returns>
 /// <unmanaged>HRESULT DrawInlineObject([None] void* clientDrawingContext,[None] FLOAT originX,[None] FLOAT originY,[None] IDWriteInlineObject* inlineObject,[None] BOOL isSideways,[None] BOOL isRightToLeft,[None] IUnknown* clientDrawingEffect)</unmanaged>
 public override SDX.Result DrawInlineObject(object clientDrawingContext, float originX, float originY, InlineObject inlineObject, bool isSideways, bool isRightToLeft, SDX.ComObject clientDrawingEffect)
 {
     return(SDX.Result.Ok);
 }
 //public override int Width
 //{
 //    get
 //    {
 //        return 0; // use size of CoreWindow
 //    }
 //}
 //public override int Height
 //{
 //    get
 //    {
 //        return 0; // use size of CoreWindow
 //    }
 //}
 protected override SharpDX.DXGI.SwapChain1 CreateSwapChain(SharpDX.DXGI.Factory2 factory, SharpDX.Direct3D11.Device1 device, SharpDX.DXGI.SwapChainDescription1 desc)
 {
     // Creates the swap chain for the CoreWindow
     using (var coreWindow = new ComObject(_window))
         return new SwapChain1(factory, device, coreWindow, ref desc);
 }
Esempio n. 22
0
            private void SetupScreenBuffers()
            {
                width = (int) window.Bounds.Width;
                height = (int) window.Bounds.Height;

                // If the swap chain already exists, resize it.
                if (swapChain != null)
                {
                    swapChain.ResizeBuffers(2, width, height, Format.B8G8R8A8_UNorm, SwapChainFlags.None);
                }
                    // Otherwise, create a new one.
                else
                {
                    // SwapChain description
                    var desc = new SwapChainDescription1
                                   {
                                       // Automatic sizing
                                       Width = width,
                                       Height = height,
                                       Format = Format.B8G8R8A8_UNorm,
                                       Stereo = false,
                                       SampleDescription = new SampleDescription(1, 0),
                                       Usage = Usage.BackBuffer | Usage.RenderTargetOutput,
                                       // Use two buffers to enable flip effect.
                                       BufferCount = 2,
                                       Scaling = Scaling.None,
                                       SwapEffect = SwapEffect.FlipSequential,
                                   };

                    // Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device

                    // First, retrieve the underlying DXGI Device from the D3D Device.
                    // Creates the swap chain 
                    using (var dxgiDevice2 = graphicsDevice.QueryInterface<Device2>())
                    using (Adapter dxgiAdapter = dxgiDevice2.Adapter)
                    using (var dxgiFactory2 = dxgiAdapter.GetParent<Factory2>())
                    {
                        // Creates a SwapChain from a CoreWindow pointer
                        using (var comWindow = new ComObject(window))
                            swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(graphicsDevice, comWindow, ref desc, null);

                        // Ensure that DXGI does not queue more than one frame at a time. This both reduces 
                        // latency and ensures that the application will only render after each VSync, minimizing 
                        // power consumption.
                        dxgiDevice2.MaximumFrameLatency = 1;
                    }
                }

                // Obtain the backbuffer for this window which will be the final 3D rendertarget.
                backBuffer = ToDispose(Resource.FromSwapChain<Texture2D>(swapChain, 0));
                {
                    // Create a view interface on the rendertarget to use on bind.
                    renderTargetView = ToDispose(new RenderTargetView(graphicsDevice, backBuffer));
                }

                // Create a viewport descriptor of the full window size.
                var viewport = new Viewport(0, 0, width, height, 0.0f, 1.0f);

                // Set the current viewport using the descriptor.
                graphicsDevice.ImmediateContext.Rasterizer.SetViewports(viewport);
            }
Esempio n. 23
0
        public Result DrawStrikethrough(object clientDrawingContext, float baselineOriginX, float baselineOriginY, ref Strikethrough strikethrough, ComObject clientDrawingEffect)
        {
            var rect = new SharpDX.RectangleF(0, strikethrough.Offset, strikethrough.Width, strikethrough.Offset + strikethrough.Thickness);
            var rectangleGeometry = new RectangleGeometry(_d2DFactory, rect);
            var matrix = new Matrix3x2()
            {
                M11 = 1,
                M12 = 0,
                M21 = 0,
                M22 = 1,
                M31 = baselineOriginX,
                M32 = baselineOriginY
            };
            var transformedGeometry = new TransformedGeometry(_d2DFactory, rectangleGeometry, matrix);
            
            var  brushColor = (Color4)Color.Black;

            if (clientDrawingEffect != null && clientDrawingEffect is ColorDrawingEffect)
                brushColor = (Color4)(clientDrawingEffect as ColorDrawingEffect).Color;

            var brush = new SolidColorBrush(_renderTarget, brushColor);

            _renderTarget.DrawGeometry(transformedGeometry, brush);
            _renderTarget.FillGeometry(transformedGeometry, brush);

            rectangleGeometry.Dispose();
            transformedGeometry.Dispose();
            brush.Dispose();

            return Result.Ok;
        }
Esempio n. 24
0
 public Result DrawInlineObject(object clientDrawingContext, float originX, float originY, InlineObject inlineObject, bool isSideways, bool isRightToLeft, ComObject clientDrawingEffect)
 {
     return SharpDX.Result.NotImplemented;
 }
Esempio n. 25
0
        public override SharpDX.Result DrawGlyphRun(object clientDrawingContext, float baselineOriginX, float baselineOriginY, MeasuringMode measuringMode, GlyphRun glyphRun, GlyphRunDescription glyphRunDescription, SharpDX.ComObject clientDrawingEffect)
        {
            PathGeometry pg = new PathGeometry(this.factory);

            GeometrySink sink = pg.Open();

            glyphRun.FontFace.GetGlyphRunOutline(glyphRun.FontSize, glyphRun.Indices, glyphRun.Advances, glyphRun.Offsets, glyphRun.IsSideways, glyphRun.BidiLevel % 2 == 1, sink as SimplifiedGeometrySink);

            sink.Close();

            TransformedGeometry tg = new TransformedGeometry(this.factory, pg, Matrix3x2.Translation(baselineOriginX, baselineOriginY));

            pg.Dispose();

            //Transform from baseline

            this.AddGeometry(tg);

            return(SharpDX.Result.Ok);
        }
 /// <summary>
 /// IDWriteTextLayout::Draw calls this function to instruct the client to draw an underline.
 /// </summary>
 /// <param name="clientDrawingContext">The application-defined drawing context passed to  IDWriteTextLayout::Draw.</param>
 /// <param name="baselineOriginX">The pixel location (X-coordinate) at the baseline origin of the run where underline applies.</param>
 /// <param name="baselineOriginY">The pixel location (Y-coordinate) at the baseline origin of the run where underline applies.</param>
 /// <param name="underline">Pointer to  a structure containing underline logical information.</param>
 /// <param name="clientDrawingEffect">Application-defined effect to apply to the underline. Usually this argument represents effects such as the foreground brush filling the interior of a line.</param>
 /// <returns>
 /// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.
 /// </returns>
 /// <unmanaged>HRESULT DrawUnderline([None] void* clientDrawingContext,[None] FLOAT baselineOriginX,[None] FLOAT baselineOriginY,[In] const DWRITE_UNDERLINE* underline,[None] IUnknown* clientDrawingEffect)</unmanaged>
 /// <remarks>
 /// A single underline can be broken into multiple calls, depending on how the formatting changes attributes. If font sizes/styles change within an underline, the thickness and offset will be averaged weighted according to characters. To get an appropriate starting pixel position, add underline::offset to the baseline. Otherwise there will be no spacing between the text. The x coordinate will always be passed as the left side, regardless of text directionality. This simplifies drawing and reduces the problem of round-off that could potentially cause gaps or a double stamped alpha blend. To avoid alpha overlap, round the end points to the nearest device pixel.
 /// </remarks>
 public override SDX.Result DrawUnderline(object clientDrawingContext, float baselineOriginX, float baselineOriginY, ref Underline underline, SDX.ComObject clientDrawingEffect)
 {
     return(SDX.Result.Ok);
 }
Esempio n. 27
0
 public unsafe void Set(int index, ComObject value)
 {
     this.values[index] = value;
       ((IntPtr*) (void*) this.nativeBuffer)[index] = value.NativePointer;
 }
        /// <summary>
        /// IDWriteTextLayout::Draw calls this function to instruct the client to render a run of glyphs.
        /// </summary>
        /// <param name="clientDrawingContext">The application-defined drawing context passed to  <see cref="M:SharpDX.DirectWrite.TextLayout.Draw_(System.IntPtr,System.IntPtr,System.Single,System.Single)" />.</param>
        /// <param name="baselineOriginX">The pixel location (X-coordinate) at the baseline origin of the glyph run.</param>
        /// <param name="baselineOriginY">The pixel location (Y-coordinate) at the baseline origin of the glyph run.</param>
        /// <param name="measuringMode">The measuring method for glyphs in the run, used with the other properties to determine the rendering mode.</param>
        /// <param name="glyphRun">Pointer to the glyph run instance to render.</param>
        /// <param name="glyphRunDescription">A pointer to the optional glyph run description instance which contains properties of the characters  associated with this run.</param>
        /// <param name="clientDrawingEffect">Application-defined drawing effects for the glyphs to render. Usually this argument represents effects such as the foreground brush filling the interior of text.</param>
        /// <returns>
        /// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.
        /// </returns>
        /// <unmanaged>HRESULT DrawGlyphRun([None] void* clientDrawingContext,[None] FLOAT baselineOriginX,[None] FLOAT baselineOriginY,[None] DWRITE_MEASURING_MODE measuringMode,[In] const DWRITE_GLYPH_RUN* glyphRun,[In] const DWRITE_GLYPH_RUN_DESCRIPTION* glyphRunDescription,[None] IUnknown* clientDrawingEffect)</unmanaged>
        /// <remarks>
        /// The <see cref="M:SharpDX.DirectWrite.TextLayout.Draw_(System.IntPtr,System.IntPtr,System.Single,System.Single)" /> function calls this callback function with all the information about glyphs to render. The application implements this callback by mostly delegating the call to the underlying platform's graphics API such as {{Direct2D}} to draw glyphs on the drawing context. An application that uses GDI can implement this callback in terms of the <see cref="M:SharpDX.DirectWrite.BitmapRenderTarget.DrawGlyphRun(System.Single,System.Single,SharpDX.Direct2D1.MeasuringMode,SharpDX.DirectWrite.GlyphRun,SharpDX.DirectWrite.RenderingParams,SharpDX.Color4)" /> method.
        /// </remarks>
        public override SDX.Result DrawGlyphRun(
            object clientDrawingContext, float baselineOriginX, float baselineOriginY,
            MeasuringMode measuringMode, GlyphRun glyphRun, GlyphRunDescription glyphRunDescription, SDX.ComObject clientDrawingEffect)
        {
            if ((glyphRun.Indices == null) ||
                (glyphRun.Indices.Length == 0))
            {
                return(SDX.Result.Ok);;
            }

            SharpDX.DirectWrite.Factory dWriteFactory = GraphicsCore.Current.FactoryDWrite;
            SharpDX.Direct2D1.Factory   d2DFactory    = GraphicsCore.Current.FactoryD2D;

            // Extrude geometry data out of given glyph run
            SimplePolygon2DGeometrySink geometryExtruder = new SimplePolygon2DGeometrySink(new Vector2(baselineOriginX, baselineOriginY));

            using (PathGeometry pathGeometry = new PathGeometry(d2DFactory))
            {
                // Write all geometry data into a standard PathGeometry object
                using (GeometrySink geoSink = pathGeometry.Open())
                {
                    glyphRun.FontFace.GetGlyphRunOutline(
                        glyphRun.FontSize,
                        glyphRun.Indices,
                        glyphRun.Advances,
                        glyphRun.Offsets,
                        glyphRun.IsSideways,
                        glyphRun.BidiLevel % 2 == 1,
                        geoSink);
                    geoSink.Close();
                }

                // Simplify written geometry and write it into own structure
                pathGeometry.Simplify(GeometrySimplificationOption.Lines, m_geometryOptions.SimplificationFlatternTolerance, geometryExtruder);
            }

            // Structure for caching the result
            VertexStructure        tempStructure = new VertexStructure();
            VertexStructureSurface tempSurface   = tempStructure.CreateSurface();

            // Create the text surface
            if (m_geometryOptions.MakeSurface)
            {
                // Separate polygons by clock direction
                // Order polygons as needed for further hole finding algorithm
                IEnumerable <Polygon2D> fillingPolygons = geometryExtruder.GeneratedPolygons
                                                          .Where(actPolygon => actPolygon.EdgeOrder == EdgeOrder.CounterClockwise)
                                                          .OrderBy(actPolygon => actPolygon.BoundingBox.Size.X * actPolygon.BoundingBox.Size.Y);
                List <Polygon2D> holePolygons = geometryExtruder.GeneratedPolygons
                                                .Where(actPolygon => actPolygon.EdgeOrder == EdgeOrder.Clockwise)
                                                .OrderByDescending(actPolygon => actPolygon.BoundingBox.Size.X * actPolygon.BoundingBox.Size.Y)
                                                .ToList();

                // Build geometry for all polygons
                int loopPolygon = 0;
                foreach (Polygon2D actFillingPolygon in fillingPolygons)
                {
                    // Find all corresponding holes
                    BoundingBox2D           actFillingPolygonBounds = actFillingPolygon.BoundingBox;
                    IEnumerable <Polygon2D> correspondingHoles      = holePolygons
                                                                      .Where(actHolePolygon => actHolePolygon.BoundingBox.IsContainedBy(actFillingPolygonBounds))
                                                                      .ToList();

                    // Two steps here:
                    // - Merge current filling polygon and all its holes.
                    // - Remove found holes from current hole list
                    Polygon2D      polygonForRendering     = actFillingPolygon;
                    Polygon2D      polygonForTriangulation = actFillingPolygon.Clone();
                    List <Vector2> cutPoints = new List <Vector2>();
                    foreach (Polygon2D actHole in correspondingHoles)
                    {
                        holePolygons.Remove(actHole);
                        polygonForRendering     = polygonForRendering.MergeWithHole(actHole, Polygon2DMergeOptions.Default, cutPoints);
                        polygonForTriangulation = polygonForTriangulation.MergeWithHole(actHole, new Polygon2DMergeOptions()
                        {
                            MakeMergepointSpaceForTriangulation = true
                        });
                    }

                    loopPolygon++;
                    int actBaseIndex = (int)tempStructure.CountVertices;

                    EdgeOrder edgeOrder = polygonForRendering.EdgeOrder;
                    float     edgeSize  = edgeOrder == EdgeOrder.CounterClockwise ? 0.1f : 0.4f;

                    // Append all vertices to temporary VertexStructure
                    for (int loop = 0; loop < polygonForRendering.Vertices.Count; loop++)
                    {
                        // Calculate 3d location and texture coordinate
                        Vector3 actVertexLocation = new Vector3(
                            polygonForRendering.Vertices[loop].X,
                            0f,
                            polygonForRendering.Vertices[loop].Y);
                        Vector2 actTexCoord = new Vector2(
                            (polygonForRendering.Vertices[loop].X - polygonForRendering.BoundingBox.Location.X) / polygonForRendering.BoundingBox.Size.X,
                            (polygonForRendering.Vertices[loop].Y - polygonForRendering.BoundingBox.Location.Y) / polygonForRendering.BoundingBox.Size.Y);
                        if (float.IsInfinity(actTexCoord.X) || float.IsNaN(actTexCoord.X))
                        {
                            actTexCoord.X = 0f;
                        }
                        if (float.IsInfinity(actTexCoord.Y) || float.IsNaN(actTexCoord.Y))
                        {
                            actTexCoord.Y = 0f;
                        }

                        // Append the vertex to the result
                        tempStructure.AddVertex(
                            new Vertex(
                                actVertexLocation,
                                m_geometryOptions.SurfaceVertexColor,
                                actTexCoord,
                                new Vector3(0f, 1f, 0f)));
                    }

                    // Generate cubes on each vertex if requested
                    if (m_geometryOptions.GenerateCubesOnVertices)
                    {
                        for (int loop = 0; loop < polygonForRendering.Vertices.Count; loop++)
                        {
                            Color4 colorToUse      = Color4.GreenColor;
                            float  pointRenderSize = 0.1f;
                            if (cutPoints.Contains(polygonForRendering.Vertices[loop]))
                            {
                                colorToUse      = Color4.RedColor;
                                pointRenderSize = 0.15f;
                            }

                            Vector3 actVertexLocation = new Vector3(
                                polygonForRendering.Vertices[loop].X,
                                0f,
                                polygonForRendering.Vertices[loop].Y);
                            tempSurface.BuildCube24V(actVertexLocation, pointRenderSize, colorToUse);
                        }
                    }

                    // Triangulate the polygon
                    IEnumerable <int> triangleIndices = polygonForTriangulation.TriangulateUsingCuttingEars();
                    if (triangleIndices == null)
                    {
                        continue;
                    }
                    if (triangleIndices == null)
                    {
                        throw new SeeingSharpGraphicsException("Unable to triangulate given PathGeometry object!");
                    }

                    // Append all triangles to the temporary structure
                    using (IEnumerator <int> indexEnumerator = triangleIndices.GetEnumerator())
                    {
                        while (indexEnumerator.MoveNext())
                        {
                            int index1 = indexEnumerator.Current;
                            int index2 = 0;
                            int index3 = 0;

                            if (indexEnumerator.MoveNext())
                            {
                                index2 = indexEnumerator.Current;
                            }
                            else
                            {
                                break;
                            }
                            if (indexEnumerator.MoveNext())
                            {
                                index3 = indexEnumerator.Current;
                            }
                            else
                            {
                                break;
                            }

                            tempSurface.AddTriangle(
                                (int)(actBaseIndex + index3),
                                (int)(actBaseIndex + index2),
                                (int)(actBaseIndex + index1));
                        }
                    }
                }
            }

            // Make volumetric outlines
            int triangleCountWithoutSide = tempSurface.CountTriangles;

            if (m_geometryOptions.MakeVolumetricText)
            {
                float volumetricTextDepth = m_geometryOptions.VolumetricTextDepth;
                if (m_geometryOptions.VerticesScaleFactor > 0f)
                {
                    volumetricTextDepth = volumetricTextDepth / m_geometryOptions.VerticesScaleFactor;
                }

                // Add all side surfaces
                foreach (Polygon2D actPolygon in geometryExtruder.GeneratedPolygons)
                {
                    foreach (Line2D actLine in actPolygon.Lines)
                    {
                        tempSurface.BuildRect4V(
                            new Vector3(actLine.StartPosition.X, -volumetricTextDepth, actLine.StartPosition.Y),
                            new Vector3(actLine.EndPosition.X, -volumetricTextDepth, actLine.EndPosition.Y),
                            new Vector3(actLine.EndPosition.X, 0f, actLine.EndPosition.Y),
                            new Vector3(actLine.StartPosition.X, 0f, actLine.StartPosition.Y),
                            m_geometryOptions.VolumetricSideSurfaceVertexColor);
                    }
                }
            }

            // Do also make back surface?
            if (m_geometryOptions.MakeBackSurface)
            {
                for (int loop = 0; loop < triangleCountWithoutSide; loop++)
                {
                    Triangle triangle     = tempSurface.Triangles[loop];
                    Vertex   vertex0      = tempStructure.Vertices[triangle.Index1];
                    Vertex   vertex1      = tempStructure.Vertices[triangle.Index2];
                    Vertex   vertex2      = tempStructure.Vertices[triangle.Index3];
                    Vector3  changeVector = new Vector3(0f, -m_geometryOptions.VolumetricTextDepth, 0f);

                    tempSurface.AddTriangle(
                        vertex2.Copy(vertex2.Position - changeVector, Vector3.Negate(vertex2.Normal)),
                        vertex1.Copy(vertex1.Position - changeVector, Vector3.Negate(vertex1.Normal)),
                        vertex0.Copy(vertex0.Position - changeVector, Vector3.Negate(vertex0.Normal)));
                }
            }

            // TODO: Make this configurable
            tempStructure.ToggleCoordinateSystem();

            // Scale the text using given scale factor
            if (m_geometryOptions.VerticesScaleFactor > 0f)
            {
                Matrix4x4 scaleMatrix = Matrix4x4.CreateScale(
                    m_geometryOptions.VerticesScaleFactor,
                    m_geometryOptions.VerticesScaleFactor,
                    m_geometryOptions.VerticesScaleFactor);

                Matrix4Stack transformMatrix = new Matrix4Stack(scaleMatrix);
                transformMatrix.TransformLocal(m_geometryOptions.VertexTransform);

                tempStructure.UpdateVerticesUsingRelocationFunc((actVector) => Vector3.Transform(actVector, transformMatrix.Top));
            }

            // Calculate all normals before adding to target structure
            if (m_geometryOptions.CalculateNormals)
            {
                tempStructure.CalculateNormalsFlat();
            }

            // Merge temporary structure to target structure
            m_targetSurface.AddStructure(tempStructure);

            return(SDX.Result.Ok);
        }
Esempio n. 29
0
        void Initialize(ComObject coreWindow, AntiAliasingMode antiAliasingMode)
        {
            InitializeInner(antiAliasingMode);

            var swapChainDesc = device.CreateSwapChainDescription();
            DXGI.Factory2 factory = device.QueryInterface<DXGI.Device1>().Adapter.GetParent<DXGI.Factory2>();
            swapChain = new DXGI.SwapChain1(factory, device, coreWindow, ref swapChainDesc);
        }
Esempio n. 30
0
 public Result DrawStrikethrough(object clientDrawingContext, float baselineOriginX, float baselineOriginY, ref Strikethrough strikethrough, ComObject clientDrawingEffect)
 {
     throw new NotImplementedException();
 }
Esempio n. 31
0
 public ObjectReference(DateTime creationTime, ComObject comObject, StackTrace stackTrace)
 {
     this.CreationTime = creationTime;
       this.Object = new WeakReference((object) comObject, true);
       this.StackTrace = stackTrace;
 }
Esempio n. 32
0
        private SwapChain CreateSwapChainForUWP()
        {
            bufferCount = 2;
            var description = new SwapChainDescription1
            {
                // Automatic sizing
                Width             = Description.BackBufferWidth,
                Height            = Description.BackBufferHeight,
                Format            = (SharpDX.DXGI.Format)Description.BackBufferFormat.ToNonSRgb(),
                Stereo            = false,
                SampleDescription = new SharpDX.DXGI.SampleDescription((int)Description.MultisampleCount, 0),
                Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                // Use two buffers to enable flip effect.
                BufferCount = bufferCount,
                Scaling     = SharpDX.DXGI.Scaling.Stretch,
                SwapEffect  = SharpDX.DXGI.SwapEffect.FlipSequential,
            };

            SwapChain swapChain = null;

            switch (Description.DeviceWindowHandle.Context)
            {
            case Games.AppContextType.UWPXaml:
            {
                var nativePanel = ComObject.As <ISwapChainPanelNative>(Description.DeviceWindowHandle.NativeWindow);

                // Creates the swap chain for XAML composition
                swapChain = new SwapChain1(GraphicsAdapterFactory.NativeFactory, GraphicsDevice.NativeDevice, ref description);

                // Associate the SwapChainPanel with the swap chain
                nativePanel.SwapChain = swapChain;

                break;
            }

            case Games.AppContextType.UWPCoreWindow:
            {
                using (var dxgiDevice = GraphicsDevice.NativeDevice.QueryInterface <SharpDX.DXGI.Device2>())
                {
                    // Ensure that DXGI does not queue more than one frame at a time. This both reduces
                    // latency and ensures that the application will only render after each VSync, minimizing
                    // power consumption.
                    dxgiDevice.MaximumFrameLatency = 1;

                    // Next, get the parent factory from the DXGI Device.
                    using (var dxgiAdapter = dxgiDevice.Adapter)
                        using (var dxgiFactory = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>())
                            // Finally, create the swap chain.
                            using (var coreWindow = new SharpDX.ComObject(Description.DeviceWindowHandle.NativeWindow))
                            {
                                swapChain = new SharpDX.DXGI.SwapChain1(dxgiFactory
                                                                        , GraphicsDevice.NativeDevice, coreWindow, ref description);
                            }
                }

                break;
            }

            default:
                throw new NotSupportedException(string.Format("Window context [{0}] not supported while creating SwapChain", Description.DeviceWindowHandle.Context));
            }

            return(swapChain);
        }
Esempio n. 33
0
        public override SharpDX.Result DrawGlyphRun(object clientDrawingContext, float baselineOriginX, float baselineOriginY, MeasuringMode measuringMode, GlyphRun glyphRun, GlyphRunDescription glyphRunDescription, SharpDX.ComObject clientDrawingEffect)
        {
            Color4 c = Color4.White;

            if (clientDrawingEffect != null)
            {
                if (clientDrawingEffect is SharpDX.Direct2D1.SolidColorBrush)
                {
                    var sb = (SharpDX.Direct2D1.SolidColorBrush)clientDrawingEffect;
                    c = sb.Color;
                }
            }

            if (glyphRun.Indices.Length > 0)
            {
                PathGeometry pg = new PathGeometry(this.factory);

                GeometrySink sink = pg.Open();

                glyphRun.FontFace.GetGlyphRunOutline(glyphRun.FontSize, glyphRun.Indices, glyphRun.Advances, glyphRun.Offsets, glyphRun.IsSideways, glyphRun.BidiLevel % 2 == 1, sink as SimplifiedGeometrySink);
                sink.Close();

                TransformedGeometry tg = new TransformedGeometry(this.factory, pg, Matrix3x2.Translation(baselineOriginX, baselineOriginY) * Matrix3x2.Scaling(1.0f, -1.0f));

                pg.Dispose();
                sink.Dispose();
                //Transform from baseline

                this.AddGeometry(tg);

                return(SharpDX.Result.Ok);
            }
            else
            {
                return(SharpDX.Result.Ok);
            }
        }
Esempio n. 34
0
 internal static T AsUnsafe <T>(IntPtr iunknownPtr)
 {
     using (ComObject comObject = new ComObject(iunknownPtr))
         return(comObject.QueryInterfaceUnsafe <T>());
 }
Esempio n. 35
0
 public Result DrawInlineObject(object clientDrawingContext, float originX, float originY, InlineObject inlineObject, bool isSideways, bool isRightToLeft, ComObject clientDrawingEffect)
 {
     throw new NotImplementedException();
 }
        public Result DrawUnderline(object clientDrawingContext, float baselineOriginX, float baselineOriginY, ref Underline underline, ComObject clientDrawingEffect)
        {
            var rect = new SharpDX.RectangleF(0, underline.Offset, underline.Width, underline.Offset + underline.Thickness);
            var rectangleGeometry = new RectangleGeometry(_d2DFactory, rect);
            var matrix = new Matrix3x2()
            {
                M11 = 1,
                M12 = 0,
                M21 = 0,
                M22 = 1,
                M31 = baselineOriginX,
                M32 = baselineOriginY
            };
            var transformedGeometry = new TransformedGeometry(_d2DFactory, rectangleGeometry, matrix);

            var brushColor = new Color4(1, 0, 0, 0);
            if (clientDrawingEffect != null && clientDrawingEffect is ColorDrawingEffect)
                brushColor = (clientDrawingEffect as ColorDrawingEffect).Color;

            var brush = new SolidColorBrush(_renderTarget, brushColor);

            _renderTarget.DrawGeometry(transformedGeometry, brush);
            _renderTarget.FillGeometry(transformedGeometry, brush);

            rectangleGeometry.Dispose();
            transformedGeometry.Dispose();
            brush.Dispose();

            return SharpDX.Result.Ok;
        }
Esempio n. 37
0
 public Result DrawUnderline(object clientDrawingContext, float baselineOriginX, float baselineOriginY, ref Underline underline, ComObject clientDrawingEffect)
 {
     throw new NotImplementedException();
 }
Esempio n. 38
0
 protected override SharpDX.DXGI.SwapChain1 CreateSwapChain(SharpDX.DXGI.Factory2 factory, SharpDX.Direct3D11.Device1 device, SharpDX.DXGI.SwapChainDescription1 desc)
 {
     // Creates a SwapChain from a CoreWindow pointer
     using (var comWindow = new ComObject(window))
         return factory.CreateSwapChainForCoreWindow(device, comWindow, ref desc, null);
 }
Esempio n. 39
0
 public void Attach(SharpDX.ComObject hostDevice, PointD2D hostSize)
 {
     Attach((Device)hostDevice, hostSize);
 }
Esempio n. 40
0
 public static void UnTrack(ComObject comObject)
 {
     if (comObject == null || comObject.NativePointer == IntPtr.Zero)
     return;
       lock (ObjectTracker.ObjectReferences)
       {
     List<ObjectReference> local_0;
     if (!ObjectTracker.ObjectReferences.TryGetValue(comObject.NativePointer, out local_0))
       return;
     for (int local_1 = local_0.Count - 1; local_1 >= 0; --local_1)
     {
       ObjectReference local_2 = local_0[local_1];
       if (object.ReferenceEquals(local_2.Object.Target, (object) comObject))
     local_0.RemoveAt(local_1);
       else if (!local_2.IsAlive)
     local_0.RemoveAt(local_1);
     }
     if (local_0.Count != 0)
       return;
     ObjectTracker.ObjectReferences.Remove(comObject.NativePointer);
       }
 }