Beispiel #1
0
 public SharpDX.DXGI.SwapChain CreateSwapChain(SharpDX.DXGI.SwapChainDescription desc)
 {
     using (var factory = new SharpDX.DXGI.Factory1())
     {
         return(new SharpDX.DXGI.SwapChain(factory, _dx11Device, desc));
     }
 }
        private static void PlatformInitializeAdapters(out ReadOnlyCollection <GraphicsAdapter> adapters)
        {
            var factory = new SharpDX.DXGI.Factory1();

            var adapterCount = factory.GetAdapterCount();
            var adapterList  = new List <GraphicsAdapter>(adapterCount);

            for (var i = 0; i < adapterCount; i++)
            {
                var device = factory.GetAdapter1(i);

                var monitorCount = device.GetOutputCount();
                for (var j = 0; j < monitorCount; j++)
                {
                    var monitor = device.GetOutput(j);

                    var adapter = CreateAdapter(device, monitor);
                    adapterList.Add(adapter);

                    monitor.Dispose();
                }
            }

            factory.Dispose();

            adapters = new ReadOnlyCollection <GraphicsAdapter>(adapterList);
        }
Beispiel #3
0
        private void Form1_Load(object sender, EventArgs e)
        {
            device   = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.None, SharpDX.Direct3D.FeatureLevel.Level_11_0);
            c_device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.None, SharpDX.Direct3D.FeatureLevel.Level_11_1);
            factory  = new SharpDX.DXGI.Factory1();

            int width  = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Width;
            int height = factory.Adapters1[numAdapter].Outputs[numOutput].Description.DesktopBounds.Height;

            target = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            // creating CPU-accessible texture resource
            SharpDX.Direct3D11.Texture2DDescription texdes = new SharpDX.Direct3D11.Texture2DDescription();
            texdes.CpuAccessFlags            = SharpDX.Direct3D11.CpuAccessFlags.Read;
            texdes.BindFlags                 = SharpDX.Direct3D11.BindFlags.None;
            texdes.Format                    = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
            texdes.Height                    = height;
            texdes.Width                     = width;
            texdes.OptionFlags               = SharpDX.Direct3D11.ResourceOptionFlags.Shared;
            texdes.MipLevels                 = 1;
            texdes.ArraySize                 = 1;
            texdes.SampleDescription.Count   = 1;
            texdes.SampleDescription.Quality = 0;
            texdes.Usage                     = SharpDX.Direct3D11.ResourceUsage.Staging;

            screenTexture        = new SharpDX.Direct3D11.Texture2D(c_device, texdes);
            sharedResourceHandle = screenTexture.QueryInterface <SharpDX.DXGI.Resource>().SharedHandle;
            sharedTexture        = device.OpenSharedResource <SharpDX.Direct3D11.Texture2D>(sharedResourceHandle);


            output           = new SharpDX.DXGI.Output1(factory.Adapters1[numAdapter].Outputs[numOutput].NativePointer);
            duplicatedOutput = output.DuplicateOutput(c_device);
        }
Beispiel #4
0
 static void Main(string[] args)
 {
     if (args.Length == 1)
     {
         if (string.Equals(args[0], "--listadapters", StringComparison.InvariantCultureIgnoreCase))
         {
             var factory  = new SharpDX.DXGI.Factory1();
             var adapters = factory.Adapters;
             Console.WriteLine(adapters.Length + " adapters available.");
             for (int i = 0; i < adapters.Length; i++)
             {
                 Console.WriteLine(i + ": " + adapters[i].Description.Description);
             }
         }
         else
         {
             Console.WriteLine("Invalid parameters.");
         }
     }
     else if (args.Length == 2)
     {
         if (string.Equals(args[0], "--useadapter", StringComparison.InvariantCultureIgnoreCase))
         {
             if (!int.TryParse(args[1], out int adapterIndex))
             {
                 Console.WriteLine("Adapter ID must be an integer.");
             }
             else
             {
                 StartSim(adapterIndex);
             }
         }
         else if (string.Equals(args[0], "--headless", StringComparison.InvariantCultureIgnoreCase))
         {
             if (!int.TryParse(args[1], out int simID))
             {
                 Console.WriteLine("SimID must be an integer.");
             }
             else
             {
                 while (true)
                 {
                     var h = new HeadlessSim(simID);
                     h.UpdateLoop(60 * 60 * 60);
                 }
                 Console.WriteLine("Finished.");
                 Console.ReadKey(true);
             }
         }
         else
         {
             Console.WriteLine("Invalid parameters.");
         }
     }
     else
     {
         StartSim(-1);
     }
 }
Beispiel #5
0
        private ScratchImage convertBC7(ScratchImage image)
        {
            SharpDX.DXGI.Factory1 factory = new SharpDX.DXGI.Factory1();
            SharpDX.DXGI.Adapter  adapter = factory.GetAdapter(0);
            Device device = new Device(adapter);

            return(image.Compress(device.NativePointer, DXGI_FORMAT.BC7_UNORM, TEX_COMPRESS_FLAGS.DEFAULT, 0.5f));
        }
Beispiel #6
0
        private void Initialize(IntPtr devicePointer)
        {
            FeatureLevel[] levels = new FeatureLevel[]
            {
                #if DIRECTX11_1
                FeatureLevel.Level_11_1,
                #endif
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_10_1,
                FeatureLevel.Level_10_0,
                FeatureLevel.Level_9_3
            };

            Device dev;
            if (devicePointer != IntPtr.Zero)
            {
                dev = new SharpDX.Direct3D11.Device(devicePointer);
            }
            else if (adapterindex > 0)
            {
                SharpDX.DXGI.Factory f = new SharpDX.DXGI.Factory1();
                SharpDX.DXGI.Adapter a = f.GetAdapter(adapterindex);

                dev = new Device(a, this.creationflags, levels);

                f.Dispose();
                a.Dispose();
            }
            else
            {
                dev = new Device(DriverType.Hardware, this.creationflags, levels);
            }

            #if DIRECTX11_1
            this.Device = dev.QueryInterface <DirectXDevice>();
            Marshal.Release(this.Device.NativePointer);
            #else
            this.Device = dev;
            #endif

            DXGIDevice dxgidevice = this.Device.QueryInterface <DXGIDevice>();
            Marshal.Release(this.Device.NativePointer);

            this.Adapter = dxgidevice.Adapter.QueryInterface <DXGIAdapter>();
            Marshal.Release(dxgidevice.Adapter.NativePointer);

            this.Factory = this.Adapter.GetParent <DXGIFactory>();
            Marshal.Release(this.Adapter.NativePointer);

            this.OnLoad();
        }
Beispiel #7
0
        public static List <GpuAdapter> EnumerateGraphicsAdapter()
        {
            List <GpuAdapter> graphicsAdapters = new List <GpuAdapter>();

            LogEmitter.Apply(LogLevel.Information, "[Start Enumerate GraphicsAdapter]");

            using (var factory = new SharpDX.DXGI.Factory1())
            {
                foreach (var adapter in factory.Adapters)
                {
                    graphicsAdapters.Add(new GpuAdapter(adapter.Description.Description, adapter));

                    LogEmitter.Apply(LogLevel.Information, "[Enumerate GraphicsAdapter] [{0}]", adapter.Description.Description);
                }
            }

            LogEmitter.Apply(LogLevel.Information, "[End Enumerate GraphicsAdapter]");

            return(graphicsAdapters);
        }
        private static void Main()
        {
            RenderForm renderForm = new RenderForm("SharpFontWrapper - Transformed Text");

            renderForm.Width  = 1024;
            renderForm.Height = 768;

            viewPort = new ViewportF(0, 0, renderForm.Width, renderForm.Height, 0.0f, 1.0f);

            device        = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug);
            deviceContext = device.ImmediateContext;

            using (SharpDX.DXGI.Factory dxgiFactory = new SharpDX.DXGI.Factory1())
            {
                SharpDX.DXGI.SwapChainDescription swapChainDesc = new SharpDX.DXGI.SwapChainDescription()
                {
                    BufferCount       = 2,
                    Flags             = SharpDX.DXGI.SwapChainFlags.None,
                    IsWindowed        = true,
                    ModeDescription   = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm),
                    OutputHandle      = renderForm.Handle,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(4, 0),
                    SwapEffect        = SharpDX.DXGI.SwapEffect.Discard,
                    Usage             = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput
                };

                swapChain = new SwapChain(dxgiFactory, device, swapChainDesc);

                using (Texture2D backBuffer = swapChain.GetBackBuffer <Texture2D>(0))
                {
                    renderView = new RenderTargetView(device, backBuffer);
                }
            }


            fontFactory = new SharpFontWrapper.Factory();

            fontWrapper = fontFactory.CreateFontWrapper(device, "Arial");

            Matrix view       = Matrix.Translation(0.0f, 0.0f, 2.0f);
            Matrix projection = Matrix.PerspectiveFovLH(1.57f, 1024.0f / 768.0f, 0.01f, 100.0f);


            int objectCount = 128;

            Matrix[] mats = new Matrix[objectCount];

            Random r = new Random();

            for (int i = 0; i < objectCount; i++)
            {
                mats[i] = Matrix.Translation(r.NextVector3(new Vector3(-5.0f), new Vector3(5.0f)));
            }

            RenderLoop.Run(renderForm, () =>
            {
                float t = (float)watch.Elapsed.TotalMilliseconds;

                deviceContext.ClearRenderTargetView(renderView, Color.Black);
                deviceContext.OutputMerger.SetRenderTargets(renderView);
                deviceContext.Rasterizer.SetViewport(viewPort);

                SharpFontWrapper.TextFlags flags = SharpFontWrapper.TextFlags.NoWordWrapping
                                                   | SharpFontWrapper.TextFlags.VerticalCenter
                                                   | SharpFontWrapper.TextFlags.Center;

                Matrix rotation = Matrix.RotationY(t * 0.0001f);

                for (int i = 0; i < objectCount; i++)
                {
                    //Please note that font wrapper defaults to inverted Y
                    Matrix world = Matrix.Scaling(0.002f, -0.002f, 0.002f);
                    world        = world * mats[i] * rotation;

                    Matrix twvp = world * view * projection;

                    fontWrapper.DrawString(deviceContext, "SharpFontWrapper", "Arial", 64.0f, twvp, null, Color.White, flags);
                }



                swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);
            });


            fontWrapper.Dispose();
            fontFactory.Dispose();

            deviceContext.ClearState();
            deviceContext.Flush();

            renderView.Dispose();
            swapChain.Dispose();
            deviceContext.Dispose();
            device.Dispose();
        }
Beispiel #9
0
        public void Setup(object pars)
        {
            logger.Debug("VideoCaptureSource::Setup()");

            if (State != CaptureState.Closed)
            {
                throw new InvalidOperationException("Invalid capture state " + State);
            }

            UvcDevice captureParams = pars as UvcDevice;

            var deviceId = captureParams.DeviceId;

            try
            {
                int adapterIndex = 0;
                using (var dxgiFactory = new SharpDX.DXGI.Factory1())
                {
                    using (var adapter = dxgiFactory.GetAdapter1(adapterIndex))
                    {
                        var deviceCreationFlags = //DeviceCreationFlags.Debug |
                                                  DeviceCreationFlags.VideoSupport |
                                                  DeviceCreationFlags.BgraSupport;

                        device = new Device(adapter, deviceCreationFlags);

                        using (var multiThread = device.QueryInterface <SharpDX.Direct3D11.Multithread>())
                        {
                            multiThread.SetMultithreadProtected(true);
                        }
                    }
                }

                sourceReader = CreateSourceReaderByDeviceId(deviceId);

                if (sourceReader == null)
                {
                    throw new Exception("Unable to create media source reader " + deviceId);
                }

                var mediaType = sourceReader.GetCurrentMediaType(SourceReaderIndex.FirstVideoStream);

                logger.Debug("------------------CurrentMediaType-------------------");
                logger.Debug(MfTool.LogMediaType(mediaType));

                srcSize = MfTool.GetFrameSize(mediaType);

                var destSize = captureParams.Resolution;

                if (destSize.IsEmpty)
                {
                    destSize = srcSize;
                }

                var subtype = mediaType.Get(MediaTypeAttributeKeys.Subtype);


                mediaType?.Dispose();


                SharedTexture = new Texture2D(device,
                                              new Texture2DDescription
                {
                    CpuAccessFlags    = CpuAccessFlags.None,
                    BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    Width             = destSize.Width,
                    Height            = destSize.Height,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Default,
                    OptionFlags       = ResourceOptionFlags.Shared,
                });

                stagingTexture = new Texture2D(device,
                                               new Texture2DDescription
                {
                    CpuAccessFlags = CpuAccessFlags.Read,
                    //BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    BindFlags         = BindFlags.None,
                    Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    Width             = destSize.Width,
                    Height            = destSize.Height,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Staging,
                    OptionFlags       = ResourceOptionFlags.None,
                });


                processor = new MfVideoProcessor(null);
                var intupArgs = new MfVideoArgs
                {
                    Width  = srcSize.Width,
                    Height = srcSize.Height,
                    Format = subtype,//VideoFormatGuids.NV12,
                };


                var outputArgs = new MfVideoArgs
                {
                    Width  = destSize.Width,
                    Height = destSize.Height,
                    Format = VideoFormatGuids.Argb32,
                };

                processor.Setup(intupArgs, outputArgs);
                processor.SetMirror(VideoProcessorMirror.MirrorVertical);

                state = CaptureState.Initialized;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                LastError = ex;
                errorCode = (int)SharedTypes.ErrorCode.NotInitialized;

                CleanUp();

                throw;
            }
        }
Beispiel #10
0
        private void LoadPipeline()
        {
            viewport.Width    = this.width;
            viewport.Height   = this.height;
            viewport.MaxDepth = 1.0f;

            scissorRect.Right  = this.width;
            scissorRect.Bottom = this.height;

#if DEBUG
            // Enable the D3D12 debug layer.
            {
                DebugInterface.Get().EnableDebugLayer();
            }
#endif
            var fact = new SharpDX.DXGI.Factory1();
            SharpDX.DXGI.Adapter adapter = fact.GetAdapter(1);

            // create device
            using (var defaultDevice = new Device(adapter, SharpDX.Direct3D.FeatureLevel.Level_12_1))
                device = defaultDevice.QueryInterface <SharpDX.Direct3D12.Device2>();

            using (var factory = new SharpDX.DXGI.Factory4())
            {
                // Describe and create the command queue.
                var queueDesc = new CommandQueueDescription(CommandListType.Direct);
                commandQueue = device.CreateCommandQueue(queueDesc);


                // Describe and create the swap chain.
                var swapChainDesc = new SharpDX.DXGI.SwapChainDescription1()
                {
                    BufferCount       = FrameCount,
                    Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                    Height            = height,
                    Width             = width,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                    Scaling           = SharpDX.DXGI.Scaling.Stretch,
                    Stereo            = false,
                    SwapEffect        = SharpDX.DXGI.SwapEffect.FlipDiscard,
                    Usage             = SharpDX.DXGI.Usage.RenderTargetOutput,
                };

                var tempSwapChain = new SharpDX.DXGI.SwapChain1(factory, commandQueue, ref swapChainDesc);
                swapChain = tempSwapChain.QueryInterface <SharpDX.DXGI.SwapChain3>();
                tempSwapChain.Dispose();
                frameIndex = swapChain.CurrentBackBufferIndex;

                using (SharpDX.DXGI.ISwapChainPanelNative nativeObject = ComObject.As <SharpDX.DXGI.ISwapChainPanelNative>(swapChainPanel))
                    nativeObject.SwapChain = swapChain;
            }

            // Create descriptor heaps.
            // Describe and create a render target view (RTV) descriptor heap.
            var rtvHeapDesc = new DescriptorHeapDescription()
            {
                DescriptorCount = FrameCount,
                Flags           = DescriptorHeapFlags.None,
                Type            = DescriptorHeapType.RenderTargetView
            };

            renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc);

            rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);

            // Create frame resources.
            var rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            for (int n = 0; n < FrameCount; n++)
            {
                renderTargets[n] = swapChain.GetBackBuffer <Resource>(n);
                device.CreateRenderTargetView(renderTargets[n], null, rtvHandle);
                rtvHandle += rtvDescriptorSize;
            }

            commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);
        }
Beispiel #11
0
        //--------------------------------------------------------------
        public MyGame()
        {
            Lock = new object();

              // ----- Service Container
              // MyGame uses a ServiceContainer, which is a simple service locator and
              // Inversion of Control (IoC) container. (The ServiceContainer can be
              // replaced by any other container that implements System.IServiceProvider.)
              _serviceContainer = new ServiceContainer();
              ServiceLocator.SetLocatorProvider(() => _serviceContainer);

              _serviceContainer.Register(typeof(MyGame), null, this);

              // ----- Storage
              // Create a "virtual file system" for reading game assets.
              _titleStorage = new TitleStorage("Content");
              _assetsStorage = new ZipStorage(_titleStorage, "Content.zip");
              _digitalRuneStorage = new ZipStorage(_titleStorage, "DigitalRune.zip");
              _vfsStorage = new VfsStorage();
              _vfsStorage.MountInfos.Add(new VfsMountInfo(_assetsStorage, null));
              _vfsStorage.MountInfos.Add(new VfsMountInfo(_digitalRuneStorage, null));

              // ----- Content
              _contentManager = new StorageContentManager(ServiceLocator.Current, _vfsStorage);
              _serviceContainer.Register(typeof(ContentManager), null, _contentManager);

              // ----- Graphics
              // Create Direct3D 11 device.
              var presentationParameters = new PresentationParameters
              {
            BackBufferWidth = 1,
            BackBufferHeight = 1,
            // Do not associate graphics device with any window.
            DeviceWindowHandle = IntPtr.Zero,
              };
              var graphicsDevice = new GraphicsDevice(GraphicsAdapter.DefaultAdapter, GraphicsProfile.HiDef, presentationParameters);

              // An IGraphicsDeviceService is required by the MonoGame/XNA content manager.
              _serviceContainer.Register(typeof(IGraphicsDeviceService), null, new DummyGraphicsDeviceManager(graphicsDevice));

              // Get DXGIOutput to call WaitForVerticalBlank() in the game loop.
              using (var dxgiFactory = new SharpDX.DXGI.Factory1())
              using (var dxgiAdapter = dxgiFactory.GetAdapter1(0))
            _dxgiOutput = dxgiAdapter.GetOutput(0);

              // Create and register the graphics manager.
              _graphicsManager = new GraphicsManager(graphicsDevice, _contentManager);
              _serviceContainer.Register(typeof(IGraphicsService), null, _graphicsManager);

              // ----- Timing
              // The game loop runs in a parallel thread to keep the UI thread responsive.
              // To measure the time that has passed, we use a HighPrecisionClock.
              _clock = new HighPrecisionClock();
              _clock.Start();
              _gameLoopTask = ThreadPool.RunAsync(GameLoopTaskAction, WorkItemPriority.High, WorkItemOptions.TimeSliced)
                                .AsTask();

              // The FixedStepTimer reads the clock and triggers the game loop at 60 Hz.
              //_timer = new FixedStepTimer(_clock)
              //{
              //  StepSize = new TimeSpan(166667), // ~60 Hz
              //  AccumulateTimeSteps = false,
              //};

              // The VariableStepTimer reads the clock and triggers the game loop as often as possible.
              _timer = new VariableStepTimer(_clock);

              _timer.TimeChanged += (s, e) => GameLoop(e.DeltaTime);
              _timer.Start();

              CoreApplication.Suspending += OnCoreApplicationSuspending;

              // DirectX buffers only a limit amount of Present calls per frame which is controlled by
              // the MaximumFrameLatency property. The default value is usually 3. If the application
              // uses more SwapChainPresentationTargets we must increase this property.
              //var d3dDevice = (SharpDX.Direct3D11.Device)_graphicsManager.GraphicsDevice.Handle;
              //using (var dxgiDevice2 = d3dDevice.QueryInterface<SharpDX.DXGI.Device2>())
              //  dxgiDevice2.MaximumFrameLatency = numberOfSwapChainPanels;
        }
        private static void Main()
        {
            RenderForm renderForm = new RenderForm("SharpFontWrapper - Simple Text");

            renderForm.Width  = 1024;
            renderForm.Height = 768;

            viewPort = new ViewportF(0, 0, renderForm.Width, renderForm.Height, 0.0f, 1.0f);

            device        = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug);
            deviceContext = device.ImmediateContext;

            using (SharpDX.DXGI.Factory dxgiFactory = new SharpDX.DXGI.Factory1())
            {
                SharpDX.DXGI.SwapChainDescription swapChainDesc = new SharpDX.DXGI.SwapChainDescription()
                {
                    BufferCount       = 2,
                    Flags             = SharpDX.DXGI.SwapChainFlags.None,
                    IsWindowed        = true,
                    ModeDescription   = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm),
                    OutputHandle      = renderForm.Handle,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(4, 0),
                    SwapEffect        = SharpDX.DXGI.SwapEffect.Discard,
                    Usage             = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput
                };

                swapChain = new SwapChain(dxgiFactory, device, swapChainDesc);

                using (Texture2D backBuffer = swapChain.GetBackBuffer <Texture2D>(0))
                {
                    renderView = new RenderTargetView(device, backBuffer);
                }
            }


            fontFactory = new SharpFontWrapper.Factory();

            fontWrapper = fontFactory.CreateFontWrapper(device, "Arial");

            colorStyle = fontFactory.CreateColor(SharpDX.Color.Green);

            textFormat = new SharpDX.DirectWrite.TextFormat(fontWrapper.DWriteFactory, "Consolas", 32.0f);
            textFormat.TextAlignment      = SharpDX.DirectWrite.TextAlignment.Center;
            textFormat.ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Near;



            textLayout = new SharpDX.DirectWrite.TextLayout(fontWrapper.DWriteFactory,
                                                            "DirectWrite Text Layout with formatting and color", textFormat, 1000.0f, 1000.0f);

            textLayout.SetFontStyle(SharpDX.DirectWrite.FontStyle.Italic, new SharpDX.DirectWrite.TextRange(0, 11));

            textLayout.SetFontFamilyName("Arial", new SharpDX.DirectWrite.TextRange(24, 4));
            textLayout.SetFontSize(72.0f, new SharpDX.DirectWrite.TextRange(29, 10));

            //Stylistic typeography
            SharpDX.DirectWrite.Typography typoGraphy = new SharpDX.DirectWrite.Typography(fontWrapper.DWriteFactory);
            typoGraphy.AddFontFeature(new SharpDX.DirectWrite.FontFeature(SharpDX.DirectWrite.FontFeatureTag.StylisticSet7, 1));
            textLayout.SetFontFamilyName("Gabriola", new SharpDX.DirectWrite.TextRange(12, 4));
            textLayout.SetTypography(typoGraphy, new SharpDX.DirectWrite.TextRange(12, 4));

            //Note : to pass color, make sure to use native pointer, as in that case we do not need sharpdx/.net to build com wrapper, colorStyle is already one
            textLayout.SetDrawingEffect(colorStyle.NativePointer, new SharpDX.DirectWrite.TextRange(44, 5));

            RenderLoop.Run(renderForm, () =>
            {
                float t = (float)watch.Elapsed.TotalMilliseconds;
                float x = ((float)Math.Sin(t * 0.002f) * 100.0f) + (renderForm.Width * 0.5f);

                deviceContext.OutputMerger.SetRenderTargets(renderView);
                deviceContext.Rasterizer.SetViewport(viewPort);
                deviceContext.ClearRenderTargetView(renderView, Color.Black);

                SharpFontWrapper.TextFlags flags = SharpFontWrapper.TextFlags.NoWordWrapping
                                                   | SharpFontWrapper.TextFlags.VerticalCenter
                                                   | SharpFontWrapper.TextFlags.Center;

                fontWrapper.DrawString(deviceContext, "Hello SharpFontWrapper", 64.0f, new Vector2(x, renderForm.Height * 0.25f), Color.Yellow, flags);

                fontWrapper.DrawString(deviceContext, "This is another text", 64.0f, new Vector2(renderForm.Width * 0.5f, renderForm.Height * 0.25f + 100.0f), Color.White, flags);

                fontWrapper.DrawTextLayout(deviceContext, textLayout, new Vector2(0, renderForm.Height * 0.25f + 200.0f), Color.White, flags);

                swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);
            });

            typoGraphy.Dispose();

            colorStyle.Dispose();
            textLayout.Dispose();
            textFormat.Dispose();

            fontWrapper.Dispose();
            fontFactory.Dispose();

            deviceContext.ClearState();
            deviceContext.Flush();

            renderView.Dispose();
            swapChain.Dispose();
            deviceContext.Dispose();
            device.Dispose();
        }
        private static void Main()
        {
            RenderForm renderForm = new RenderForm("SharpFontWrapper - Simple Text");

            renderForm.Width  = 1024;
            renderForm.Height = 768;

            viewPort = new ViewportF(0, 0, renderForm.Width, renderForm.Height, 0.0f, 1.0f);

            device        = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug);
            deviceContext = new DeviceContext2(device.ImmediateContext.NativePointer);

            using (SharpDX.DXGI.Factory dxgiFactory = new SharpDX.DXGI.Factory1())
            {
                SharpDX.DXGI.SwapChainDescription swapChainDesc = new SharpDX.DXGI.SwapChainDescription()
                {
                    BufferCount       = 2,
                    Flags             = SharpDX.DXGI.SwapChainFlags.None,
                    IsWindowed        = true,
                    ModeDescription   = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm),
                    OutputHandle      = renderForm.Handle,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(4, 0),
                    SwapEffect        = SharpDX.DXGI.SwapEffect.Discard,
                    Usage             = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput
                };

                swapChain = new SwapChain(dxgiFactory, device, swapChainDesc);

                using (Texture2D backBuffer = swapChain.GetBackBuffer <Texture2D>(0))
                {
                    renderView = new RenderTargetView(device, backBuffer);
                }
            }

            //Pixel shader and custom cbuffer
            using (ShaderBytecode byteCode = ShaderBytecode.CompileFromFile("PixelShader.hlsl", "PS", "ps_5_0", ShaderFlags.OptimizationLevel3))
            {
                customPixelShader = new PixelShader(device, byteCode);
            }

            BufferDescription cbufferDesc = new BufferDescription()
            {
                BindFlags           = BindFlags.ConstantBuffer,
                CpuAccessFlags      = CpuAccessFlags.Write,
                OptionFlags         = ResourceOptionFlags.None,
                SizeInBytes         = 16, //Need to be 16 aligned
                StructureByteStride = 0,
                Usage = ResourceUsage.Dynamic
            };

            cBuffer = new Buffer(device, cbufferDesc);


            fontFactory = new SharpFontWrapper.Factory();
            fontWrapper = fontFactory.CreateFontWrapper(device, "Arial");

            renderStates = fontWrapper.RenderStates;

            RenderLoop.Run(renderForm, () =>
            {
                float t = (float)watch.Elapsed.TotalSeconds;

                deviceContext.ClearRenderTargetView(renderView, Color.Black);
                deviceContext.OutputMerger.SetRenderTargets(renderView);
                deviceContext.Rasterizer.SetViewport(viewPort);

                SharpFontWrapper.TextFlags flags = SharpFontWrapper.TextFlags.NoWordWrapping
                                                   | SharpFontWrapper.TextFlags.VerticalCenter
                                                   | SharpFontWrapper.TextFlags.Center
                                                   | SharpFontWrapper.TextFlags.StatePrepared; //Make sure this is on,otherwise pixelshader will be reverted to default

                //Custom cbuffer is not overriden, we can set it anywhere
                DataStream ds;
                deviceContext.MapSubresource(cBuffer, MapMode.WriteDiscard, MapFlags.None, out ds);
                ds.Write <float>(-t * 5.0f);
                deviceContext.UnmapSubresource(cBuffer, 0);


                deviceContext.PixelShader.SetConstantBuffer(1, cBuffer);

                //Set default render states
                renderStates.SetStates(deviceContext, 0);

                deviceContext.PixelShader.Set(customPixelShader);

                fontWrapper.DrawString(deviceContext, "SharpFontWrapper", 96.0f, new Vector2(renderForm.Width * 0.5f, renderForm.Height * 0.5f), Color.White, flags);

                swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);
            });



            renderStates.Dispose();
            fontWrapper.Dispose();
            fontFactory.Dispose();

            cBuffer.Dispose();
            customPixelShader.Dispose();
            deviceContext.ClearState();
            deviceContext.Flush();

            renderView.Dispose();
            swapChain.Dispose();
            deviceContext.Dispose();
            device.Dispose();
        }
        private static void Main()
        {
            RenderForm renderForm = new RenderForm("SharpFontWrapper - Simple Text");

            renderForm.Width  = 1024;
            renderForm.Height = 768;

            viewPort = new ViewportF(0, 0, renderForm.Width, renderForm.Height, 0.0f, 1.0f);

            device        = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug);
            deviceContext = new DeviceContext2(device.ImmediateContext.NativePointer);

            using (SharpDX.DXGI.Factory dxgiFactory = new SharpDX.DXGI.Factory1())
            {
                SharpDX.DXGI.SwapChainDescription swapChainDesc = new SharpDX.DXGI.SwapChainDescription()
                {
                    BufferCount       = 2,
                    Flags             = SharpDX.DXGI.SwapChainFlags.None,
                    IsWindowed        = true,
                    ModeDescription   = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm),
                    OutputHandle      = renderForm.Handle,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(4, 0),
                    SwapEffect        = SharpDX.DXGI.SwapEffect.Discard,
                    Usage             = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput
                };

                swapChain = new SwapChain(dxgiFactory, device, swapChainDesc);

                using (Texture2D backBuffer = swapChain.GetBackBuffer <Texture2D>(0))
                {
                    renderView = new RenderTargetView(device, backBuffer);
                }
            }


            fontFactory = new SharpFontWrapper.Factory();
            fontWrapper = fontFactory.CreateFontWrapper(device, "Arial");

            RenderLoop.Run(renderForm, () =>
            {
                float t = (float)watch.Elapsed.TotalMilliseconds;

                deviceContext.ClearRenderTargetView(renderView, Color.Black);
                deviceContext.OutputMerger.SetRenderTargets(renderView);
                deviceContext.Rasterizer.SetViewport(viewPort);


                SharpFontWrapper.TextFlags flags = SharpFontWrapper.TextFlags.NoWordWrapping
                                                   | SharpFontWrapper.TextFlags.VerticalCenter
                                                   | SharpFontWrapper.TextFlags.Center;

                RectangleF layoutRect = new RectangleF(renderForm.Width * 0.5f, renderForm.Height * 0.5f, 0, 0);

                var rect = fontWrapper.MeasureString("Hello SharpFontWrapper", "Arial", 64.0f, layoutRect, flags);

                SharpDX.Rectangle r = new Rectangle((int)rect.Left, (int)rect.Top, (int)rect.Right - (int)rect.Left, (int)rect.Bottom - (int)rect.Top);

                deviceContext.ClearView(renderView, Color.Blue, new SharpDX.Mathematics.Interop.RawRectangle[] { r }, 1);


                fontWrapper.DrawString(deviceContext, "Hello SharpFontWrapper", 64.0f, new Vector2(renderForm.Width * 0.5f, renderForm.Height * 0.5f), Color.White, flags);

                swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);
            });



            fontWrapper.Dispose();
            fontFactory.Dispose();

            deviceContext.ClearState();
            deviceContext.Flush();

            renderView.Dispose();
            swapChain.Dispose();
            deviceContext.Dispose();
            device.Dispose();
        }
Beispiel #15
0
        private void InitDx()
        {
            logger.Debug("GDICapture::InitDx()");

            SharpDX.DXGI.Factory1 dxgiFactory = null;
            SharpDX.DXGI.Adapter1 adapter     = null;
            SharpDX.DXGI.Output   output      = null;
            try
            {
                dxgiFactory = new SharpDX.DXGI.Factory1();

                logger.Info(MediaFoundation.DxTool.LogDxAdapters(dxgiFactory.Adapters1));

                //var hMonitor = NativeAPIs.User32.GetMonitorFromRect(this.srcRect);
                //if (hMonitor != IntPtr.Zero)
                //{
                //    foreach (var _adapter in dxgiFactory.Adapters1)
                //    {
                //        foreach (var _output in _adapter.Outputs)
                //        {
                //            var descr = _output.Description;
                //            if (descr.MonitorHandle == hMonitor)
                //            {
                //                adapter = _adapter;
                //                output = _output;

                //                break;
                //            }
                //        }
                //    }
                //}

                if (adapter == null)
                {// первым идет адаптер с которому подключен primary монитор
                    adapter = dxgiFactory.GetAdapter1(0);
                }

                AdapterId = adapter.Description.Luid;

                //logger.Info("Screen source info: " + adapter.Description.Description + " " + output.Description.DeviceName);

                var deviceCreationFlags =
                    //DeviceCreationFlags.Debug |
                    // DeviceCreationFlags.VideoSupport |
                    DeviceCreationFlags.BgraSupport;

                //var feature = FeatureLevel.Level_11_0;

                device = new Device(adapter, deviceCreationFlags);
                using (var multiThread = device.QueryInterface <SharpDX.Direct3D11.Multithread>())
                {
                    multiThread.SetMultithreadProtected(true);
                }

                SharedTexture = new Texture2D(device,
                                              new Texture2DDescription
                {
                    CpuAccessFlags = CpuAccessFlags.None,
                    BindFlags      = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    Format         = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    Width          = DestSize.Width,
                    Height         = DestSize.Height,

                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Default,
                    OptionFlags       = ResourceOptionFlags.Shared,
                });

                gdiTexture = new Texture2D(device,
                                           new Texture2DDescription
                {
                    CpuAccessFlags = CpuAccessFlags.None,
                    BindFlags      = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    Format         = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    Width          = SrcRect.Width,  //DestSize.Width,
                    Height         = SrcRect.Height, //DestSize.Height,

                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Default,
                    OptionFlags       = ResourceOptionFlags.GdiCompatible,
                });


                renderTexture = new Texture2D(device,
                                              new Texture2DDescription
                {
                    CpuAccessFlags = CpuAccessFlags.None,
                    BindFlags      = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    Format         = SharpDX.DXGI.Format.B8G8R8A8_UNorm,

                    Width             = DestSize.Width,
                    Height            = DestSize.Height,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Default,
                    //OptionFlags = ResourceOptionFlags.GdiCompatible//ResourceOptionFlags.None,
                    OptionFlags = ResourceOptionFlags.Shared,
                });

                if (DestSize.Width != SrcRect.Width || DestSize.Height != SrcRect.Height)
                {
                    using (SharpDX.Direct2D1.Factory1 factory2D1 = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.MultiThreaded))
                    {
                        using (var surf = renderTexture.QueryInterface <SharpDX.DXGI.Surface>())
                        {
                            //var pixelFormat = new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Ignore);

                            var pixelFormat       = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied);
                            var renderTargetProps = new SharpDX.Direct2D1.RenderTargetProperties(pixelFormat);

                            renderTarget = new SharpDX.Direct2D1.RenderTarget(factory2D1, surf, renderTargetProps);

                            //var d2dContext = new SharpDX.Direct2D1.DeviceContext(surface);
                        }
                    }
                }
            }
            finally
            {
                if (adapter != null)
                {
                    adapter.Dispose();
                    adapter = null;
                }

                if (output != null)
                {
                    output.Dispose();
                    output = null;
                }

                if (dxgiFactory != null)
                {
                    dxgiFactory.Dispose();
                    dxgiFactory = null;
                }
            }
        }
        private static void Main()
        {
            RenderForm renderForm = new RenderForm("SharpFontWrapper - View glyph sheets");

            renderForm.Width  = 1024;
            renderForm.Height = 768;

            viewPort = new ViewportF(0, 0, renderForm.Width, renderForm.Height, 0.0f, 1.0f);

            device        = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug);
            deviceContext = new DeviceContext2(device.ImmediateContext.NativePointer);

            using (SharpDX.DXGI.Factory dxgiFactory = new SharpDX.DXGI.Factory1())
            {
                SharpDX.DXGI.SwapChainDescription swapChainDesc = new SharpDX.DXGI.SwapChainDescription()
                {
                    BufferCount       = 2,
                    Flags             = SharpDX.DXGI.SwapChainFlags.None,
                    IsWindowed        = true,
                    ModeDescription   = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm),
                    OutputHandle      = renderForm.Handle,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(4, 0),
                    SwapEffect        = SharpDX.DXGI.SwapEffect.Discard,
                    Usage             = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput
                };

                swapChain = new SwapChain(dxgiFactory, device, swapChainDesc);

                using (Texture2D backBuffer = swapChain.GetBackBuffer <Texture2D>(0))
                {
                    renderView = new RenderTargetView(device, backBuffer);
                }
            }

            //Vertex/Pixel shaders
            using (ShaderBytecode byteCode = ShaderBytecode.CompileFromFile("GlyphSheetView.hlsl", "VS", "vs_5_0", ShaderFlags.OptimizationLevel3))
            {
                vsGlyphView = new VertexShader(device, byteCode);
            }
            using (ShaderBytecode byteCode = ShaderBytecode.CompileFromFile("GlyphSheetView.hlsl", "PS", "ps_5_0", ShaderFlags.OptimizationLevel3))
            {
                psGlyphView = new PixelShader(device, byteCode);
            }

            fontFactory = new SharpFontWrapper.Factory();
            fontWrapper = fontFactory.CreateFontWrapper(device, "Arial");

            renderStates = fontWrapper.RenderStates;

            bool showGlyphMode = false;

            renderForm.KeyDown += (sender, args) =>
            {
                if (args.KeyCode == System.Windows.Forms.Keys.Space)
                {
                    showGlyphMode = !showGlyphMode;
                }
            };

            RenderLoop.Run(renderForm, () =>
            {
                renderForm.Text = string.Format("SharpFontWrapper - Glyph Sheets view - {0} sheets built", fontWrapper.GlyphAtlas.SheetCount);

                float t = (float)watch.Elapsed.TotalSeconds;

                deviceContext.ClearRenderTargetView(renderView, Color.Black);
                deviceContext.OutputMerger.SetRenderTargets(renderView);
                deviceContext.Rasterizer.SetViewport(viewPort);

                SharpFontWrapper.TextFlags flags = SharpFontWrapper.TextFlags.NoWordWrapping
                                                   | SharpFontWrapper.TextFlags.VerticalCenter
                                                   | SharpFontWrapper.TextFlags.Center;


                if (showGlyphMode)
                {
                    deviceContext.VertexShader.Set(vsGlyphView);
                    deviceContext.GeometryShader.Set(null); //Text uses GS, so it might still be bound, ensure to remove it
                    deviceContext.PixelShader.Set(psGlyphView);

                    deviceContext.PixelShader.SetShaderResource(0, fontWrapper.GlyphAtlas.GetSheet(0).SheetTexture);


                    deviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
                    deviceContext.Draw(3, 0);
                }
                else
                {
                    fontWrapper.DrawString(deviceContext, "SharpFontWrapper, space to toggle glyph view", 32.0f, new Vector2(renderForm.Width * 0.5f, renderForm.Height * 0.5f), Color.White, flags);
                }
                swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);
            });



            renderStates.Dispose();
            fontWrapper.Dispose();
            fontFactory.Dispose();

            vsGlyphView.Dispose();
            psGlyphView.Dispose();
            deviceContext.ClearState();
            deviceContext.Flush();

            renderView.Dispose();
            swapChain.Dispose();
            deviceContext.Dispose();
            device.Dispose();
        }
        public void Setup(int deviceIndex = 0)
        {
            logger.Debug("VideoCaptureSource::Setup()");

            Activate[] activates = null;
            using (var attributes = new MediaAttributes())
            {
                MediaFactory.CreateAttributes(attributes, 1);
                attributes.Set(CaptureDeviceAttributeKeys.SourceType, CaptureDeviceAttributeKeys.SourceTypeVideoCapture.Guid);

                activates = MediaFactory.EnumDeviceSources(attributes);
            }

            if (activates == null || activates.Length == 0)
            {
                logger.Error("SourceTypeVideoCapture not found");
                Console.ReadKey();
            }

            foreach (var activate in activates)
            {
                Console.WriteLine("---------------------------------------------");
                var friendlyName = activate.Get(CaptureDeviceAttributeKeys.FriendlyName);
                var isHwSource   = activate.Get(CaptureDeviceAttributeKeys.SourceTypeVidcapHwSource);
                //var maxBuffers = activate.Get(CaptureDeviceAttributeKeys.SourceTypeVidcapMaxBuffers);
                var symbolicLink = activate.Get(CaptureDeviceAttributeKeys.SourceTypeVidcapSymbolicLink);

                logger.Info("FriendlyName " + friendlyName + "\r\n" +
                            "isHwSource " + isHwSource + "\r\n" +
                            //"maxBuffers " + maxBuffers +
                            "symbolicLink " + symbolicLink);
            }


            var currentActivator = activates[deviceIndex];

            mediaSource = currentActivator.ActivateObject <MediaSource>();

            foreach (var a in activates)
            {
                a.Dispose();
            }

            using (var mediaAttributes = new MediaAttributes(IntPtr.Zero))
            {
                MediaFactory.CreateAttributes(mediaAttributes, 2);
                mediaAttributes.Set(SourceReaderAttributeKeys.EnableVideoProcessing, 1);


                //var devMan = new DXGIDeviceManager();
                //devMan.ResetDevice(device);

                //mediaAttributes.Set(SourceReaderAttributeKeys.D3DManager, devMan);


                //MediaFactory.CreateSourceReaderFromMediaSource(mediaSource, mediaAttributes, sourceReader);

                sourceReader = new SourceReader(mediaSource, mediaAttributes);
            }

            Console.WriteLine("------------------CurrentMediaType-------------------");
            var mediaType = sourceReader.GetCurrentMediaType(SourceReaderIndex.FirstVideoStream);

            Console.WriteLine(MfTool.LogMediaType(mediaType));

            var frameSize = MfTool.GetFrameSize(mediaType);
            var subtype   = mediaType.Get(MediaTypeAttributeKeys.Subtype);


            mediaType?.Dispose();

            //Device device = null;
            int adapterIndex = 0;

            using (var dxgiFactory = new SharpDX.DXGI.Factory1())
            {
                var adapter = dxgiFactory.Adapters1[adapterIndex];

                device = new Device(adapter,
                                    //DeviceCreationFlags.Debug |
                                    DeviceCreationFlags.VideoSupport |
                                    DeviceCreationFlags.BgraSupport);

                using (var multiThread = device.QueryInterface <SharpDX.Direct3D11.Multithread>())
                {
                    multiThread.SetMultithreadProtected(true);
                }
            }


            SharedTexture = new Texture2D(device,
                                          new Texture2DDescription
            {
                CpuAccessFlags = CpuAccessFlags.None,
                BindFlags      = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format         = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                Width          = frameSize.Width,
                Height         = frameSize.Height,

                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Default,
                //OptionFlags = ResourceOptionFlags.GdiCompatible//ResourceOptionFlags.None,
                OptionFlags = ResourceOptionFlags.Shared,
            });

            texture = new Texture2D(device,
                                    new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                Width             = frameSize.Width,
                Height            = frameSize.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging,
                OptionFlags       = ResourceOptionFlags.None,
            });


            processor = new MfVideoProcessor(null);
            var inProcArgs = new MfVideoArgs
            {
                Width  = frameSize.Width,
                Height = frameSize.Height,
                // Format = VideoFormatGuids.Rgb24,
                Format = subtype,//VideoFormatGuids.NV12,
            };


            var outProcArgs = new MfVideoArgs
            {
                Width  = frameSize.Width,
                Height = frameSize.Height,
                Format = VideoFormatGuids.Argb32,
                //Format = VideoFormatGuids.Rgb32,//VideoFormatGuids.Argb32,
            };

            processor.Setup(inProcArgs, outProcArgs);


            //processor.SetMirror(VideoProcessorMirror.MirrorHorizontal);
            processor.SetMirror(VideoProcessorMirror.MirrorVertical);
        }
Beispiel #18
0
        //--------------------------------------------------------------
        #region Creation & Cleanup
        //--------------------------------------------------------------

        public MyGame()
        {
            Lock = new object();

            // ----- Service Container
            // MyGame uses a ServiceContainer, which is a simple service locator and
            // Inversion of Control (IoC) container. (The ServiceContainer can be
            // replaced by any other container that implements System.IServiceProvider.)
            _serviceContainer = new ServiceContainer();
            ServiceLocator.SetLocatorProvider(() => _serviceContainer);

            _serviceContainer.Register(typeof(MyGame), null, this);

            // ----- Storage
            // Create a "virtual file system" for reading game assets.
            _titleStorage       = new TitleStorage("Content");
            _assetsStorage      = new ZipStorage(_titleStorage, "Content.zip");
            _digitalRuneStorage = new ZipStorage(_titleStorage, "DigitalRune.zip");
            _vfsStorage         = new VfsStorage();
            _vfsStorage.MountInfos.Add(new VfsMountInfo(_assetsStorage, null));
            _vfsStorage.MountInfos.Add(new VfsMountInfo(_digitalRuneStorage, null));

            // ----- Content
            _contentManager = new StorageContentManager(ServiceLocator.Current, _vfsStorage);
            _serviceContainer.Register(typeof(ContentManager), null, _contentManager);

            // ----- Graphics
            // Create Direct3D 11 device.
            var presentationParameters = new PresentationParameters
            {
                BackBufferWidth  = 1,
                BackBufferHeight = 1,
                // Do not associate graphics device with any window.
                DeviceWindowHandle = IntPtr.Zero,
            };
            var graphicsDevice = new GraphicsDevice(GraphicsAdapter.DefaultAdapter, GraphicsProfile.HiDef, presentationParameters);

            // An IGraphicsDeviceService is required by the MonoGame/XNA content manager.
            _serviceContainer.Register(typeof(IGraphicsDeviceService), null, new DummyGraphicsDeviceManager(graphicsDevice));

            // Get DXGIOutput to call WaitForVerticalBlank() in the game loop.
            using (var dxgiFactory = new SharpDX.DXGI.Factory1())
                using (var dxgiAdapter = dxgiFactory.GetAdapter1(0))
                    _dxgiOutput = dxgiAdapter.GetOutput(0);

            // Create and register the graphics manager.
            _graphicsManager = new GraphicsManager(graphicsDevice, _contentManager);
            _serviceContainer.Register(typeof(IGraphicsService), null, _graphicsManager);

            // ----- Timing
            // The game loop runs in a parallel thread to keep the UI thread responsive.
            // To measure the time that has passed, we use a HighPrecisionClock.
            _clock = new HighPrecisionClock();
            _clock.Start();
            _gameLoopTask = ThreadPool.RunAsync(GameLoopTaskAction, WorkItemPriority.High, WorkItemOptions.TimeSliced)
                            .AsTask();

            // The FixedStepTimer reads the clock and triggers the game loop at 60 Hz.
            //_timer = new FixedStepTimer(_clock)
            //{
            //  StepSize = new TimeSpan(166667), // ~60 Hz
            //  AccumulateTimeSteps = false,
            //};

            // The VariableStepTimer reads the clock and triggers the game loop as often as possible.
            _timer = new VariableStepTimer(_clock);

            _timer.TimeChanged += (s, e) => GameLoop(e.DeltaTime);
            _timer.Start();

            CoreApplication.Suspending += OnCoreApplicationSuspending;

            // DirectX buffers only a limit amount of Present calls per frame which is controlled by
            // the MaximumFrameLatency property. The default value is usually 3. If the application
            // uses more SwapChainPresentationTargets we must increase this property.
            //var d3dDevice = (SharpDX.Direct3D11.Device)_graphicsManager.GraphicsDevice.Handle;
            //using (var dxgiDevice2 = d3dDevice.QueryInterface<SharpDX.DXGI.Device2>())
            //  dxgiDevice2.MaximumFrameLatency = numberOfSwapChainPanels;
        }
Beispiel #19
0
        //public IntPtr hWnd = IntPtr.Zero;

        public void Setup(VideoEncoderSettings inputPars, VideoEncoderSettings outputPars, NetworkSettings networkPars)
        {
            logger.Debug("ScreenReceiver::Setup(...)");
            var inputArgs = new MfVideoArgs
            {
                Width     = inputPars.Resolution.Width,
                Height    = inputPars.Resolution.Height,
                FrameRate = MfTool.PackToLong(inputPars.FrameRate),
            };

            var outputArgs = new MfVideoArgs
            {
                Width  = outputPars.Resolution.Width,
                Height = outputPars.Resolution.Height,

                FrameRate = MfTool.PackToLong(outputPars.FrameRate),
            };


            int adapterIndex = 0;

            using (var dxgiFactory = new SharpDX.DXGI.Factory1())
            {
                using (var adapter = dxgiFactory.GetAdapter1(adapterIndex))
                {
                    device = new Device(adapter,
                                        //DeviceCreationFlags.Debug |
                                        DeviceCreationFlags.VideoSupport |
                                        DeviceCreationFlags.BgraSupport);

                    using (var multiThread = device.QueryInterface <SharpDX.Direct3D11.Multithread>())
                    {
                        multiThread.SetMultithreadProtected(true);
                    }
                }
            }

            sharedTexture = new Texture2D(device,
                                          new Texture2DDescription
            {
                CpuAccessFlags = CpuAccessFlags.None,
                BindFlags      = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format         = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                Width          = outputArgs.Width,  //640,//texture.Description.Width,
                Height         = outputArgs.Height, //480,//texture.Description.Height,

                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Default,
                //OptionFlags = ResourceOptionFlags.GdiCompatible//ResourceOptionFlags.None,
                OptionFlags = ResourceOptionFlags.Shared,
            });

            //ImageProvider = new D3DImageProvider(dispatcher);

            //decoder = new DXVADecoder(IntPtr.Zero);

            decoder = new MfH264Decoder(device);

            decoder.Setup(inputArgs);


            var decoderType  = decoder.OutputMediaType;
            var decFormat    = decoderType.Get(MediaTypeAttributeKeys.Subtype);
            var decFrameSize = MfTool.GetFrameSize(decoderType);


            processor = new MfVideoProcessor(device);
            var inProcArgs = new MfVideoArgs
            {
                Width  = decFrameSize.Width,
                Height = decFrameSize.Height,
                Format = decFormat,
            };



            var outProcArgs = new MfVideoArgs
            {
                Width  = outputArgs.Width,
                Height = outputArgs.Height,
                Format = VideoFormatGuids.Argb32,
            };

            processor.Setup(inProcArgs, outProcArgs);


            h264Session = new H264Session();

            if (networkPars.TransportMode == TransportMode.Tcp)
            {
                rtpReceiver = new RtpTcpReceiver(h264Session);
            }
            else if (networkPars.TransportMode == TransportMode.Udp)
            {
                rtpReceiver = new RtpUdpReceiver(h264Session);
            }
            else
            {
                throw new Exception("networkPars.TransportMode");
            }

            h264Session.SSRC = networkPars.SSRC;

            rtpReceiver.Open(networkPars);
            rtpReceiver.RtpPacketReceived += RtpReceiver_RtpPacketReceived;
        }