Ejemplo n.º 1
0
        /// <summary>
        /// Configures resources that don't depend on the Direct3D device.
        /// </summary>
        private void CreateDeviceIndependentResources()
        {
            // Dispose previous references and set to null
            this.RemoveAndDispose(ref d2dFactory);
            this.RemoveAndDispose(ref dwriteFactory);
            this.RemoveAndDispose(ref wicFactory);

            // Initialize Direct2D resources.
            var debugLevel = SharpDX.Direct2D1.DebugLevel.None;

#if DEBUG
            if (DirectXHelper.SdkLayersAvailable())
            {
                debugLevel = SharpDX.Direct2D1.DebugLevel.Information;
            }
#endif

            // Initialize the Direct2D Factory.
            d2dFactory = this.ToDispose(
                new SharpDX.Direct2D1.Factory2(
                    SharpDX.Direct2D1.FactoryType.SingleThreaded,
                    debugLevel
                    )
                );

            // Initialize the DirectWrite Factory.
            dwriteFactory = this.ToDispose(
                new SharpDX.DirectWrite.Factory1(SharpDX.DirectWrite.FactoryType.Shared)
                );

            // Initialize the Windows Imaging Component (WIC) Factory.
            wicFactory = this.ToDispose(
                new SharpDX.WIC.ImagingFactory2()
                );
        }
Ejemplo n.º 2
0
 public void AddTexture(string assetUri, SharpDX.WIC.ImagingFactory2 wicfactory)
 {
     using (var bitmap = LoadBitmap(wicfactory, assetUri))
         using (var texture2D = TextureLoader.CreateTexture2DFromBitmap(m_d3dDevice, bitmap))
         {
             AddTexture(texture2D);
         }
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Create device manager objects
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateInstance()
        {
            // Dispose previous references and set to null
            RemoveAndDispose(ref d3dDevice);
            RemoveAndDispose(ref d3dContext);
            RemoveAndDispose(ref d2dDevice);
            RemoveAndDispose(ref d2dContext);
            RemoveAndDispose(ref d2dFactory);
            RemoveAndDispose(ref dwriteFactory);
            RemoveAndDispose(ref wicFactory);


            #region Create Direct3D 11.1 device and retrieve device context

            // BGRA performs better especially with Direct2D software render targets
            var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;
#if DEBUG
            // Enble D3D device debug layer
            creationFlags |= SharpDX.Direct3D11.DeviceCreationFlags.Debug;
#endif
            // Retrieve the Direct3D 11.1 device and device context
            using (var device = new SharpDX.Direct3D11.Device(DriverType.Hardware,
                                                              creationFlags,
                                                              D3DFeatureLevel))
            {
                d3dDevice = ToDispose(device.QueryInterface <Device1>());
            }

            // Get Direct3D 11.1 immediate context
            d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface <DeviceContext1>());
            #endregion

            #region Create Direct2D device and context

#if DEBUG
            var debugLevel = SharpDX.Direct2D1.DebugLevel.Information;
#endif
            // Allocate new references
            d2dFactory    = ToDispose(new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debugLevel));
            dwriteFactory = ToDispose(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared));
            wicFactory    = ToDispose(new SharpDX.WIC.ImagingFactory2());

            // Create Direct2D device
            using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>())
            {
                d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice));
            }

            // Create Direct2D context
            d2dContext = ToDispose(new SharpDX.Direct2D1.DeviceContext(d2dDevice,
                                                                       SharpDX.Direct2D1.DeviceContextOptions.None));

            #endregion
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Loads a bitmap using WIC.
        /// </summary>
        /// <param name="deviceManager"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static SharpDX.WIC.BitmapSource LoadBitmap(SharpDX.WIC.ImagingFactory2 factory, string filename)
        {
            using (var bitmapDecoder = new SharpDX.WIC.BitmapDecoder(factory, filename, SharpDX.WIC.DecodeOptions.CacheOnDemand)) {
                var formatConverter = new SharpDX.WIC.FormatConverter(factory);

                formatConverter.Initialize(
                    bitmapDecoder.GetFrame(0),
                    SharpDX.WIC.PixelFormat.Format32bppPRGBA,
                    SharpDX.WIC.BitmapDitherType.None,
                    null,
                    0.0,
                    SharpDX.WIC.BitmapPaletteType.Custom);

                return(formatConverter);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates device independent resources.
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateDeviceIndependentResources()
        {
#if DEBUG
            var debugLevel = SharpDX.Direct2D1.DebugLevel.Information;
#else
            var debugLevel = SharpDX.Direct2D1.DebugLevel.None;
#endif
            // Dispose previous references and set to null
            Utilities.Dispose(ref d2dFactory);
            Utilities.Dispose(ref dwriteFactory);
            Utilities.Dispose(ref wicFactory);

            // Allocate new references
            d2dFactory    = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debugLevel);
            dwriteFactory = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared);
            wicFactory    = new SharpDX.WIC.ImagingFactory2();
        }
Ejemplo n.º 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="assetUri"></param>
        /// <param name="backgroundImageFormatConverter"></param>
        /// <param name="backgroundImageSize"></param>
        public void LoadAsset(string assetUri, out SharpDX.WIC.FormatConverter backgroundImageFormatConverter, out Size2 backgroundImageSize)
        {
            SharpDX.WIC.ImagingFactory2 wicFactory = null;
            if (_deviceManager == null)
            {
                wicFactory = new SharpDX.WIC.ImagingFactory2();
            }
            else if (_deviceManager.WICFactory == null)
            {
                wicFactory = new SharpDX.WIC.ImagingFactory2();
            }
            else
            {
                wicFactory = _deviceManager.WICFactory;
            }

            var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;

            SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder(
                wicFactory,
                assetUri,
                SharpDX.IO.NativeFileAccess.Read,
                SharpDX.WIC.DecodeOptions.CacheOnDemand
                );

            SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0);

            SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer);

            SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(wicFactory);
            //formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA);
            formatConverter.Initialize(
                bitmapSource,
                SharpDX.WIC.PixelFormat.Format32bppBGRA,
                SharpDX.WIC.BitmapDitherType.None,
                null,
                0.0f,
                SharpDX.WIC.BitmapPaletteType.Custom
                );

            backgroundImageSize = formatConverter.Size;

            backgroundImageFormatConverter = formatConverter;
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Loads a bitmap using WIC.
        /// </summary>
        /// <param name="deviceManager"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static SharpDX.WIC.BitmapSource LoadBitmap(SharpDX.WIC.ImagingFactory2 factory, string filename)
        {
            //filename = Windows.ApplicationModel.Package.Current.InstalledLocation.Path + filename;
            var bitmapDecoder = new SharpDX.WIC.BitmapDecoder(
                factory,
                filename,
                SharpDX.WIC.DecodeOptions.CacheOnDemand
                );

            var formatConverter = new SharpDX.WIC.FormatConverter(factory);

            formatConverter.Initialize(
                bitmapDecoder.GetFrame(0),
                SharpDX.WIC.PixelFormat.Format32bppPRGBA,
                SharpDX.WIC.BitmapDitherType.None,
                null,
                0.0,
                SharpDX.WIC.BitmapPaletteType.Custom);

            return(formatConverter);
        }
Ejemplo n.º 8
0
 public static void LoadFromFile(D3D11.Device device, string fileName, out D3D11.ShaderResourceView srv, out D3D11.Resource rsrc)
 {
     if (!File.Exists(fileName))
     {
         srv  = null;
         rsrc = null;
     }
     if (Path.GetExtension(fileName).ToLower() == ".dds")
     {
         rsrc = LoadDDSFromBuffer(device, SharpDX.IO.NativeFile.ReadAllBytes(fileName), out srv);
     }
     else
     {
         SharpDX.WIC.ImagingFactory2 fac = new SharpDX.WIC.ImagingFactory2();
         var bs      = LoadBitmap(fac, fileName);
         var texture = CreateTexture2DFromBitmap(device, bs);
         srv = new D3D11.ShaderResourceView(device, texture);
         fac.Dispose();
         rsrc = texture;
     }
 }
Ejemplo n.º 9
0
        public Direct2DGraphics(int width, int height)
            : this()
        {
            var wicFactory = new SharpDX.WIC.ImagingFactory2();

            bitmap = DisposeLater(new SharpDX.WIC.Bitmap(
                                      wicFactory,
                                      width, height,
                                      SharpDX.WIC.PixelFormat.Format32bppPBGRA,
                                      SharpDX.WIC.BitmapCreateCacheOption.CacheOnDemand));
            dc = DisposeLater(new WicRenderTarget(
                                  d2dFactory,
                                  bitmap,
                                  new RenderTargetProperties(
                                      RenderTargetType.Default,
                                      new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied),
                                      d2dFactory.DesktopDpi.Width, d2dFactory.DesktopDpi.Height,
                                      RenderTargetUsage.None,
                                      FeatureLevel.Level_DEFAULT)));

            Initialize();
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Copies to a stream using WIC. The format is converted if necessary.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="texture"></param>
        /// <param name="outputFormat"></param>
        /// <param name="stream"></param>
        public void ToStream(SharpDX.Direct3D11.DeviceContext context, Texture2D texture, ImageFormat outputFormat, Stream stream)
        {
            if (wicFactory == null)
            {
                wicFactory = ToDispose(new SharpDX.WIC.ImagingFactory2());
            }

            DataStream dataStream;
            var        dataBox = context.MapSubresource(
                texture,
                0,
                0,
                MapMode.Read,
                SharpDX.Direct3D11.MapFlags.None,
                out dataStream);

            try
            {
                var dataRectangle = new DataRectangle
                {
                    DataPointer = dataStream.DataPointer,
                    Pitch       = dataBox.RowPitch
                };

                var format = PixelFormatFromFormat(texture.Description.Format);

                if (format == Guid.Empty)
                {
                    return;
                }

                using (var bitmap = new SharpDX.WIC.Bitmap(
                           wicFactory,
                           texture.Description.Width,
                           texture.Description.Height,
                           format,
                           dataRectangle))
                {
                    stream.Position = 0;

                    SharpDX.WIC.BitmapEncoder bitmapEncoder = null;
                    switch (outputFormat)
                    {
                    case ImageFormat.Bitmap:
                        bitmapEncoder = new SharpDX.WIC.BmpBitmapEncoder(wicFactory, stream);
                        break;

                    case ImageFormat.Jpeg:
                        bitmapEncoder = new SharpDX.WIC.JpegBitmapEncoder(wicFactory, stream);
                        break;

                    case ImageFormat.Png:
                        bitmapEncoder = new SharpDX.WIC.PngBitmapEncoder(wicFactory, stream);
                        break;

                    default:
                        return;
                    }

                    try
                    {
                        using (var bitmapFrameEncode = new SharpDX.WIC.BitmapFrameEncode(bitmapEncoder))
                        {
                            bitmapFrameEncode.Initialize();
                            bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height);
                            var pixelFormat = format;
                            bitmapFrameEncode.SetPixelFormat(ref pixelFormat);

                            if (pixelFormat != format)
                            {
                                // IWICFormatConverter
                                var converter = new SharpDX.WIC.FormatConverter(wicFactory);
                                if (converter.CanConvert(format, pixelFormat))
                                {
                                    converter.Initialize(bitmap, SharpDX.WIC.PixelFormat.Format24bppBGR, SharpDX.WIC.BitmapDitherType.None, null, 0, SharpDX.WIC.BitmapPaletteType.MedianCut);
                                    bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
                                    bitmapFrameEncode.WriteSource(converter);
                                }
                                else
                                {
                                    this.DebugMessage(string.Format("Unable to convert Direct3D texture format {0} to a suitable WIC format", texture.Description.Format.ToString()));
                                    return;
                                }
                            }
                            else
                            {
                                bitmapFrameEncode.WriteSource(bitmap);
                            }
                            bitmapFrameEncode.Commit();
                            bitmapEncoder.Commit();
                        }
                    }
                    finally
                    {
                        bitmapEncoder.Dispose();
                    }
                }
            }
            finally
            {
                context.UnmapSubresource(texture, 0);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="assetUri"></param>
        /// <param name="backgroundImageFormatConverter"></param>
        /// <param name="backgroundImageSize"></param>
        public void LoadAsset(string assetUri, out SharpDX.WIC.FormatConverter backgroundImageFormatConverter, out Size2 backgroundImageSize)
        {
            SharpDX.WIC.ImagingFactory2 wicFactory = null;
            if (_deviceManager == null) wicFactory = new SharpDX.WIC.ImagingFactory2();
            else if (_deviceManager.WICFactory == null) wicFactory = new SharpDX.WIC.ImagingFactory2();
            else wicFactory = _deviceManager.WICFactory;

            var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;

            SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder(
                                                                                        wicFactory,
                                                                                        assetUri,
                                                                                        SharpDX.IO.NativeFileAccess.Read,
                                                                                        SharpDX.WIC.DecodeOptions.CacheOnDemand
                                                                                    );

            SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0);

            SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer);

            SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(wicFactory);
            //formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA);
            formatConverter.Initialize(
                bitmapSource,
                SharpDX.WIC.PixelFormat.Format32bppBGRA,
                SharpDX.WIC.BitmapDitherType.None,
                null,
                0.0f,
                SharpDX.WIC.BitmapPaletteType.Custom
                );

            backgroundImageSize = formatConverter.Size;

            backgroundImageFormatConverter = formatConverter;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 制作背景图片
        /// </summary>
        /// <param name="pictureFileFullPath"></param>
        /// <param name="fileDirectory"></param>
        /// <param name="textContent"></param>
        /// <returns></returns>
        static string GenerateWallPaper(string pictureFileFullPath, string fileDirectory, string textContent)
        {
            var   wic  = new SharpDX.WIC.ImagingFactory2();
            var   d2d  = new SharpDX.Direct2D1.Factory();
            float dpi  = d2d.DesktopDpi.Width;
            Size2 size = new Size2(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

            SharpDX.WIC.FormatConverter image = CreateWicImage(wic, pictureFileFullPath);
            using var wicBitmap     = new SharpDX.WIC.Bitmap(wic, size.Width, size.Height, SharpDX.WIC.PixelFormat.Format32bppPBGRA, SharpDX.WIC.BitmapCreateCacheOption.CacheOnDemand);
            using var target        = new SharpDX.Direct2D1.WicRenderTarget(d2d, wicBitmap, new SharpDX.Direct2D1.RenderTargetProperties());
            using var dc            = target.QueryInterface <SharpDX.Direct2D1.DeviceContext>();
            using var bmpPicture    = SharpDX.Direct2D1.Bitmap.FromWicBitmap(target, image);
            using var dwriteFactory = new SharpDX.DirectWrite.Factory();
            using var brush         = new SolidColorBrush(target, SharpDX.Color.LightGoldenrodYellow);
            using var bmpLayer      = new SharpDX.Direct2D1.Bitmap1(dc, target.PixelSize,
                                                                    new SharpDX.Direct2D1.BitmapProperties1(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), dpi, dpi, SharpDX.Direct2D1.BitmapOptions.Target));
            var oldTarget = dc.Target;

            dc.Target = bmpLayer;
            target.BeginDraw();
            {
                var textFormat = new SharpDX.DirectWrite.TextFormat(dwriteFactory, "Tahoma", size.Height / 27);

                // draw textContent
                {
                    var textLayout = new SharpDX.DirectWrite.TextLayout(dwriteFactory, textContent, textFormat, target.Size.Width * 0.75f, float.MaxValue);
                    var center     = new Vector2((target.Size.Width - textLayout.Metrics.Width) / 2, (target.Size.Height - textLayout.Metrics.Height) / 2);
                    target.DrawTextLayout(new Vector2(center.X, center.Y), textLayout, brush);
                }
                //{
                //    // draw otherContent
                //    var textLayout = new SharpDX.DirectWrite.TextLayout(dwriteFactory, chinese, textFormat, target.Size.Width * 0.75f, float.MaxValue);
                //    var center = new Vector2((target.Size.Width - textLayout.Metrics.Width) / 2, target.Size.Height - textLayout.Metrics.Height - size.Height / 18);
                //    target.DrawTextLayout(new Vector2(center.X, center.Y), textLayout, brush);
                //}
            }
            target.EndDraw();

            // shadow
            var shadow = new SharpDX.Direct2D1.Effects.Shadow(dc);

            shadow.SetInput(0, bmpLayer, new RawBool(false));

            dc.Target = oldTarget;
            target.BeginDraw();
            {
                target.DrawBitmap(bmpPicture, new SharpDX.RectangleF(0, 0, target.Size.Width, target.Size.Height), 1.0f, BitmapInterpolationMode.Linear);
                dc.DrawImage(shadow, new Vector2(size.Height / 150.0f, size.Height / 150.0f));
                dc.UnitMode = UnitMode.Pixels;
                target.DrawBitmap(bmpLayer, 1.0f, BitmapInterpolationMode.Linear);
            }
            target.EndDraw();
            if (!Directory.Exists(fileDirectory))
            {
                Directory.CreateDirectory(fileDirectory);
            }
            string wallpaperFileName = fileDirectory + DateTime.Now.ToString("yyyyMMdd") + "_" + "wallpaper.png";

            using var wallpaperStream = File.OpenWrite(wallpaperFileName);
            SaveD2DBitmap(wic, wicBitmap, wallpaperStream);
            wallpaperStream.Close();
            return(wallpaperFileName);
        }
Ejemplo n.º 13
0
        ///// <summary>
        /////
        ///// </summary>
        ///// <param name="assetUri"></param>
        ///// <param name="backgroundImageFormatConverter"></param>
        ///// <param name="backgroundImageSize"></param>
        //public void LoadAsset(
        //    SharpDX.WIC.ImagingFactory2 wicFactory,
        //    string assetUri,
        //    out SharpDX.WIC.FormatConverter backgroundImageFormatConverter,
        //    out DrawingSize backgroundImageSize)
        //{

        //    //var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;

        //    SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder(
        //                                                                                wicFactory,
        //                                                                                assetUri,
        //                                                                                SharpDX.IO.NativeFileAccess.Read,
        //                                                                                SharpDX.WIC.DecodeOptions.CacheOnDemand
        //                                                                            );

        //    SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0);

        //    SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer);

        //    SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(wicFactory);
        //    //formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA);
        //    formatConverter.Initialize(
        //        bitmapSource,
        //        SharpDX.WIC.PixelFormat.Format32bppBGRA,
        //        SharpDX.WIC.BitmapDitherType.None,
        //        null,
        //        0.0f,
        //        SharpDX.WIC.BitmapPaletteType.Custom
        //        );

        //    backgroundImageSize = formatConverter.Size;

        //    backgroundImageFormatConverter = formatConverter;
        //}


        /// <summary>
        /// Loads bitmap asynchronously and injects into global variables. I need to work out how to NOT make them global
        /// </summary>
        /// <param name="assetNativeUri"></param>
        /// <returns></returns>
        public async Task <Tuple <SharpDX.WIC.FormatConverter, Size2, Stream> > LoadAssetAsync(
            SharpDX.WIC.ImagingFactory2 wicFactory,
            string assetNativeUri,
            string cacheId,
            string path = ""
            )
        {
            if (_listOfAssets.ContainsKey(cacheId))
            {
                return(_listOfAssets[cacheId]);
            }


            SharpDX.WIC.FormatConverter _backgroundImageFormatConverter = null;
            Size2 _backgroundImageSize = new Size2(0, 0);

            Windows.Storage.StorageFile storageFile = null;

            if (path == string.Empty)
            {
                path        = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
                storageFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(path + assetNativeUri);
            }
            else if (path == "PicturesLibrary")
            {
                var assetNativeUriParts = assetNativeUri.Split("\\".ToCharArray());

                var foundFolder = await Windows.Storage.KnownFolders.PicturesLibrary.GetFolderAsync(assetNativeUriParts[0]);

                storageFile = await foundFolder.GetFileAsync(assetNativeUriParts[1]);
            }
            else if (path == "PublicPicturesLibrary")
            {
                var assetNativeUriParts = assetNativeUri.Split("\\".ToCharArray());

                var foundFolder = await Windows.Storage.KnownFolders.PicturesLibrary.GetFolderAsync(assetNativeUriParts[0]);

                storageFile = await foundFolder.GetFileAsync(assetNativeUriParts[1]);
            }

            if (storageFile == null)
            {
                return(null);
            }

            Stream ms = await storageFile.OpenStreamForReadAsync();  //ras.GetResults().AsStreamForRead())

            //var data = SharpDX.IO.NativeFile.ReadAllBytes(assetNativeUri);
            //using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
            {
                if (ms != null)
                {
                    SharpDX.WIC.BitmapDecoder bitmapDecoder = new SharpDX.WIC.BitmapDecoder(
                        wicFactory,
                        ms,
                        SharpDX.WIC.DecodeOptions.CacheOnDemand
                        );
                    {
                        using (SharpDX.WIC.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0))
                        {
                            using (SharpDX.WIC.BitmapSource bitmapSource = new SharpDX.WIC.BitmapSource(bitmapFrameDecode.NativePointer))
                            {
                                SharpDX.WIC.FormatConverter formatConverter = new SharpDX.WIC.FormatConverter(wicFactory);
                                //formatConverter.Initialize( bitmapSource, SharpDX.WIC.PixelFormat.Format32bppBGRA);
                                formatConverter.Initialize(
                                    bitmapSource,
                                    SharpDX.WIC.PixelFormat.Format32bppBGRA,
                                    SharpDX.WIC.BitmapDitherType.None,
                                    null,
                                    0.0f,
                                    SharpDX.WIC.BitmapPaletteType.Custom
                                    );

                                _backgroundImageSize            = formatConverter.Size;
                                _backgroundImageFormatConverter = formatConverter;


                                //return Tuple.Create<SharpDX.WIC.FormatConverter, Size2>(_backgroundImageFormatConverter, _backgroundImageSize);
                            }
                        }
                    }
                }
            }

            //ras.Close();


            var ret = Tuple.Create <SharpDX.WIC.FormatConverter, Size2, Stream>(_backgroundImageFormatConverter, _backgroundImageSize, ms);

            _listOfAssets.Add(cacheId, ret);

            return(ret);
        }
Ejemplo n.º 14
0
 public TextureLoader(string root_path)
 {
     this.factory   = new SharpDX.WIC.ImagingFactory2();
     this.root_path = root_path;
 }
Ejemplo n.º 15
0
        /* DEVICE MANAGER METHODS */
        /// <summary>
        /// Initialize resources and trigger an initialization event for all registered listeners
        /// </summary>
        public void Initialize(Tesseract gameEngine)
        {
            // Release any pre-exisitng references
            ReleaseResources();

            // Retrieve the Direct3D 11.1 device
            using (var device = new Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport, FeatureLevel))
            {
                Device3D = ToDispose(device.QueryInterface<Device1>());
            }

            // Get the Direct3D 11.1 context
            Context3D = ToDispose(Device3D.ImmediateContext.QueryInterface<DeviceContext1>());

            // Create the remaining references
            Factory2D = ToDispose(new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded));
            FactoryDW = ToDispose(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared));
            FactoryWIC = ToDispose(new SharpDX.WIC.ImagingFactory2());

            // Create the Direct2D device
            using (var device = Device3D.QueryInterface<SharpDX.DXGI.Device>())
            {
                Device2D = ToDispose(new SharpDX.Direct2D1.Device(Factory2D, device));
            }

            // Create the Direct2D context
            Context2D = ToDispose(new SharpDX.Direct2D1.DeviceContext(Device2D, SharpDX.Direct2D1.DeviceContextOptions.None));
        }
Ejemplo n.º 16
0
        public void CreateDeviceDependentResourcesAsync(DeviceResources deviceResources)
        {
            byte[] bytes         = Convert.FromBase64String(spriteImg);
            Stream stream        = new MemoryStream(bytes);
            var    factory       = new SharpDX.WIC.ImagingFactory2();
            var    bitmapDecoder = new SharpDX.WIC.BitmapDecoder(
                factory,
                stream,
                SharpDX.WIC.DecodeOptions.CacheOnDemand
                );

            var formatConverter = new SharpDX.WIC.FormatConverter(factory);

            formatConverter.Initialize(
                bitmapDecoder.GetFrame(0),
                SharpDX.WIC.PixelFormat.Format32bppPRGBA,
                SharpDX.WIC.BitmapDitherType.None,
                null,
                0.0,
                SharpDX.WIC.BitmapPaletteType.Custom);

            SharpDX.WIC.BitmapSource bitmapSource = formatConverter;

            imageWidth  = bitmapSource.Size.Width;
            imageHeight = bitmapSource.Size.Height;

            var height = bitmapSource.Size.Height * Spritesheet.textureScaleFactor;
            var width  = bitmapSource.Size.Width * Spritesheet.textureScaleFactor;

            BlendStateDescription blendSdesc = new BlendStateDescription();

            blendSdesc.IndependentBlendEnable                = false;
            blendSdesc.AlphaToCoverageEnable                 = false;
            blendSdesc.RenderTarget[0].IsBlendEnabled        = true;
            blendSdesc.RenderTarget[0].SourceBlend           = BlendOption.SourceAlpha;
            blendSdesc.RenderTarget[0].DestinationBlend      = BlendOption.InverseSourceAlpha;
            blendSdesc.RenderTarget[0].BlendOperation        = BlendOperation.Add;
            blendSdesc.RenderTarget[0].SourceAlphaBlend      = BlendOption.One;
            blendSdesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            blendSdesc.RenderTarget[0].AlphaBlendOperation   = BlendOperation.Add;
            blendSdesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

            BlendState blendS = new BlendState(deviceResources.D3DDevice, blendSdesc);

            deviceResources.D3DDeviceContext.OutputMerger.SetBlendState(blendS);

            // Load mesh vertices. Each vertex has a position and a color.
            // Note that the cube size has changed from the default DirectX app
            // template. Windows Holographic is scaled in meters, so to draw the
            // cube at a comfortable size we made the cube width 0.2 m (20 cm).
            VertexPositionTexture[] cubeVertices =
            {
                new VertexPositionTexture(new System.Numerics.Vector3(-1f * width, -1f * height, 0f), new System.Numerics.Vector2(0.0f, 1.0f)),
                new VertexPositionTexture(new System.Numerics.Vector3(1f * width,  -1f * height, 0f), new System.Numerics.Vector2(1.0f, 1.0f)),
                new VertexPositionTexture(new System.Numerics.Vector3(-1f * width,  1f * height, 0f), new System.Numerics.Vector2(0.0f, 0.0f)),
                new VertexPositionTexture(new System.Numerics.Vector3(1f * width,   1f * height, 0f), new System.Numerics.Vector2(1.0f, 0.0f))
            };

            BufferDescription mdescription = new BufferDescription(sizeof(float) * 5 * cubeVertices.Length, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);

            vertexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
                                              deviceResources.D3DDevice,
                                              cubeVertices,
                                              mdescription));
            //vertexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
            //    deviceResources.D3DDevice,
            //    SharpDX.Direct3D11.BindFlags.VertexBuffer,
            //    cubeVertices,
            //    0,
            //    ResourceUsage.Dynamic, CpuAccessFlags.Write));



            // Load mesh indices. Each trio of indices represents
            // a triangle to be rendered on the screen.
            // For example: 0,2,1 means that the vertices with indexes
            // 0, 2 and 1 from the vertex buffer compose the
            // first triangle of this mesh.
            ushort[] cubeIndices =
            {
                2, 1, 0, // -x
                2, 3, 1,
                //back face
                2, 0, 1, // -x
                2, 1, 3,
            };

            indexCount  = cubeIndices.Length;
            indexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
                                             deviceResources.D3DDevice,
                                             SharpDX.Direct3D11.BindFlags.IndexBuffer,
                                             cubeIndices));
            // Create a constant buffer to store the model matrix.
            modelConstantBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
                                                     deviceResources.D3DDevice,
                                                     SharpDX.Direct3D11.BindFlags.ConstantBuffer,
                                                     ref modelConstantBufferData));

            //Load the image

            Texture2D texture = TextureLoader.CreateTexture2DFromBitmap(deviceResources.D3DDevice, bitmapSource);

            textureView = new ShaderResourceView(deviceResources.D3DDevice, texture);
            deviceResources.D3DDeviceContext.PixelShader.SetShaderResource(0, textureView);
            //Load the sampler
            SamplerStateDescription samplerDesc = new SamplerStateDescription();

            samplerDesc.AddressU           = TextureAddressMode.Wrap;
            samplerDesc.AddressV           = TextureAddressMode.Wrap;
            samplerDesc.AddressW           = TextureAddressMode.Wrap;
            samplerDesc.ComparisonFunction = Comparison.Never;
            samplerDesc.Filter             = Filter.MinMagMipLinear;
            samplerDesc.MaximumLod         = float.MaxValue;
            SamplerState sampler = new SamplerState(deviceResources.D3DDevice, samplerDesc);

            deviceResources.D3DDeviceContext.PixelShader.SetSampler(0, sampler);

            hasLoaded = true;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Creates device independent resources.
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateDeviceIndependentResources()
        {
            #if DEBUG
            var debugLevel = SharpDX.Direct2D1.DebugLevel.Information;
            #else
            var debugLevel = SharpDX.Direct2D1.DebugLevel.None;
            #endif
            // Dispose previous references and set to null
            RemoveAndDispose(ref d2dFactory);
            RemoveAndDispose(ref dwriteFactory);
            RemoveAndDispose(ref wicFactory);

            // Allocate new references
            d2dFactory = ToDispose(new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debugLevel));
            dwriteFactory = ToDispose(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared));
            wicFactory = ToDispose(new SharpDX.WIC.ImagingFactory2());
        }
        /// <summary>
        /// Creates device manager objects
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateInstances()
        {
            // Dispose previous references and set to null
            RemoveAndDispose(ref d3dDevice);
            RemoveAndDispose(ref d3dContext);
            RemoveAndDispose(ref d2dDevice);
            RemoveAndDispose(ref d2dContext);
            RemoveAndDispose(ref d2dFactory);
            RemoveAndDispose(ref dwriteFactory);
            RemoveAndDispose(ref wicFactory);

            #region Create Direct3D 11.1 device and retrieve device context

            // Bgra performs better especially with Direct2D software
            // render targets
            var creationFlags = DeviceCreationFlags.BgraSupport;
            #if DEBUG
            // Enable D3D device debug layer
            creationFlags |= DeviceCreationFlags.Debug;
            #endif

            // Retrieve the Direct3D 11.1 device and device context
            using (var device = new Device(DriverType.Hardware, creationFlags, Direct3DFeatureLevels))
            {
                d3dDevice = ToDispose(device.QueryInterface<Device1>());
            }

            // Get Direct3D 11.1 context
            d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface<DeviceContext1>());
            #endregion

            #region Create Direct2D device and context

            #if DEBUG
            var debugLevel = SharpDX.Direct2D1.DebugLevel.Information;
            #else
            var debugLevel = SharpDX.Direct2D1.DebugLevel.None;
            #endif

            // Allocate new references
            d2dFactory = ToDispose(new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debugLevel));
            dwriteFactory = ToDispose(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared));
            wicFactory = ToDispose(new SharpDX.WIC.ImagingFactory2());

            // Create Direct2D device
            using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device>())
            {
                d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice));
            }

            // Create Direct2D context
            d2dContext = ToDispose(new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None));
            #endregion
        }