Example #1
0
    public ShaderResourceView Load(string filename, out Rectangle contentRectOut, out Size sizeOut)
    {
        Debug.Assert(filename != null);

        var textureData = _fs.ReadBinaryFile(filename);

        try
        {
            DecodedImage image;

            if (filename.ToLowerInvariant().EndsWith(".img") && textureData.Length == 4)
            {
                image = ImageIO.DecodeCombinedImage(_fs, filename, textureData);
            }
            else
            {
                image = ImageIO.DecodeImage(textureData);
            }

            var texWidth  = image.info.width;
            var texHeight = image.info.height;

            contentRectOut = new Rectangle(0, 0, image.info.width, image.info.height);

            sizeOut = new Size(texWidth, texHeight);

            // Load the D3D11 one
            var textureDesc = new Texture2DDescription();
            textureDesc.Format    = Format.B8G8R8A8_UNorm;
            textureDesc.Width     = texWidth;
            textureDesc.Height    = texHeight;
            textureDesc.ArraySize = 1;
            textureDesc.MipLevels = 1;
            textureDesc.BindFlags = BindFlags.ShaderResource;
            textureDesc.Usage     = ResourceUsage.Immutable;
            textureDesc.SampleDescription.Count = 1;

            Texture2D texture;
            var       initialData = new DataBox();
            unsafe
            {
                fixed(byte *imageDataPtr = image.data)
                {
                    initialData.DataPointer = (IntPtr)imageDataPtr;
                    initialData.RowPitch    = image.info.width * 4;

                    texture = new Texture2D(Device.Device, textureDesc, new[] { initialData });
                }
            }

            if (Device.IsDebugDevice())
            {
                texture.DebugName = filename;
            }

            // Make a shader resource view for the texture since that's the only thing we're interested in here
            var resourceViewDesc = new ShaderResourceViewDescription();
            resourceViewDesc.Texture2D.MipLevels = 1;
            resourceViewDesc.Dimension           = ShaderResourceViewDimension.Texture2D;

            mLoaded++;
            mEstimatedUsage += (uint)(texWidth * texHeight * 4);

            return(new ShaderResourceView(Device.Device, texture, resourceViewDesc));
        }
        catch (Exception e)
        {
            Logger.Error("Unable to load texture {0}: {1}", filename, e.Message);
            contentRectOut = new Rectangle(0, 0, 0, 0);
            sizeOut        = new Size(0, 0);
            return(null);
        }
    }