Example #1
0
        internal MyTextureArray(TexId[] mergeList)
        {
            var srcDesc = MyTextures.GetView(mergeList[0]).Description;

            Size     = MyTextures.GetSize(mergeList[0]);
            ArrayLen = mergeList.Length;

            Texture2DDescription desc = new Texture2DDescription();

            desc.ArraySize                 = ArrayLen;
            desc.BindFlags                 = BindFlags.ShaderResource;
            desc.CpuAccessFlags            = CpuAccessFlags.None;
            desc.Format                    = srcDesc.Format;
            desc.Height                    = (int)Size.Y;
            desc.Width                     = (int)Size.X;
            desc.MipLevels                 = 0;
            desc.SampleDescription.Count   = 1;
            desc.SampleDescription.Quality = 0;
            desc.Usage                     = ResourceUsage.Default;
            m_resource                     = new Texture2D(MyRender11.Device, desc);

            // foreach mip
            var mipmaps = (int)Math.Log(Size.X, 2) + 1;

            for (int a = 0; a < ArrayLen; a++)
            {
                for (int m = 0; m < mipmaps; m++)
                {
                    MyRender11.Context.CopySubresourceRegion(MyTextures.Textures.Data[mergeList[a].Index].Resource, Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource,
                                                             Resource.CalculateSubResourceIndex(m, a, mipmaps));
                }
            }

            ShaderView = new ShaderResourceView(MyRender11.Device, Resource);
        }
Example #2
0
        /// <summary>
        /// Maps the data contained in a subresource to a memory pointer, and denies the GPU access to that subresource.
        /// </summary>
        /// <param name="resource">The resource.</param>
        /// <param name="mipSlice">The mip slice.</param>
        /// <param name="arraySlice">The array slice.</param>
        /// <param name="mode">The mode.</param>
        /// <param name="flags">The flags.</param>
        /// <param name="mipSize">Size of the selected miplevel.</param>
        /// <returns>
        /// The locked <see cref="SharpDX.DataBox"/>
        /// </returns>
        /// <unmanaged>HRESULT ID3D11DeviceContext::Map([In] ID3D11Resource* pResource,[In] unsigned int Subresource,[In] D3D11_MAP MapType,[In] D3D11_MAP_FLAG MapFlags,[Out] D3D11_MAPPED_SUBRESOURCE* pMappedResource)</unmanaged>
        public DataBox MapSubresource(Resource resource, int mipSlice, int arraySlice, MapMode mode, MapFlags flags, out int mipSize)
        {
            int subresource = resource.CalculateSubResourceIndex(mipSlice, arraySlice, out mipSize);
            var box         = MapSubresource(resource, subresource, mode, flags);

            return(box);
        }
Example #3
0
        private Texture2D CaptureTexture(DeviceContext deviceContext, Texture2D source, out Texture2DDescription desc)
        {
            var d3dDevice = deviceContext.Device;
            // debug: i got it!
            //D3D11.Texture2D texture = source.QueryInterface<D3D11.Texture2D>();
            Texture2D staging;

            desc = source.Description;

            if (desc.SampleDescription.Count > 1)
            {
                desc.SampleDescription.Count   = 1;
                desc.SampleDescription.Quality = 0;

                var temp = new Texture2D(d3dDevice, desc);

                var fmt = EnsureNotTypeless(desc.Format);

                var support = d3dDevice.CheckFormatSupport(fmt);

                if ((support & FormatSupport.MultisampleResolve) == 0)
                {
                    return(null);
                }

                for (var item = 0; item < desc.ArraySize; ++item)
                {
                    for (var level = 0; level < desc.MipLevels; ++level)
                    {
                        var index = Resource.CalculateSubResourceIndex(level, item, desc.MipLevels);
                        deviceContext.ResolveSubresource(temp, index, source, index, fmt);
                    }
                }

                desc.BindFlags      = 0;
                desc.OptionFlags   &= ResourceOptionFlags.TextureCube;
                desc.CpuAccessFlags = CpuAccessFlags.Read;
                desc.Usage          = ResourceUsage.Staging;

                staging = new Texture2D(d3dDevice, desc);
                deviceContext.CopyResource(temp, staging);
            }
            else if (desc.Usage == ResourceUsage.Staging &&
                     desc.CpuAccessFlags == CpuAccessFlags.Read)
            {
                staging = source;
            }
            else
            {
                desc.BindFlags      = 0;
                desc.OptionFlags   &= ResourceOptionFlags.TextureCube;
                desc.CpuAccessFlags = CpuAccessFlags.Read;
                desc.Usage          = ResourceUsage.Staging;
                staging             = new Texture2D(d3dDevice, desc);
                deviceContext.CopyResource(source, staging);
            }

            return(staging);
        }
            public void OnDeviceInit()
            {
                ISrvBindable firstTex = MyManagers.FileTextures.GetTexture(m_listSubresourceFilenames[0], m_type, true);
                var          srcDesc  = firstTex.Srv.Description;
                Vector2I     Size     = firstTex.Size;

                Texture2DDescription desc = new Texture2DDescription();

                desc.ArraySize                 = m_listSubresourceFilenames.Count;
                desc.BindFlags                 = BindFlags.ShaderResource;
                desc.CpuAccessFlags            = CpuAccessFlags.None;
                desc.Format                    = srcDesc.Format;
                desc.Height                    = (int)Size.Y;
                desc.Width                     = (int)Size.X;
                desc.MipLevels                 = srcDesc.Texture2D.MipLevels;
                desc.SampleDescription.Count   = 1;
                desc.SampleDescription.Quality = 0;
                desc.Usage                     = ResourceUsage.Default;
                m_resource                     = new Texture2D(MyRender11.Device, desc);
                m_resource.DebugName           = m_resourceName;
                TextureFormat                  = srcDesc.Format;

                // foreach mip
                var mipmaps = srcDesc.Texture2D.MipLevels;

                int i = 0;

                foreach (var path in m_listSubresourceFilenames)
                {
                    ISrvBindable tex   = MyManagers.FileTextures.GetTexture(path, m_type, true);
                    var          tex2D = tex.Resource as Texture2D;
                    MyRenderProxy.Assert(tex2D != null,
                                         "MyTextureArray supports only 2D textures. Inconsistent texture: " + tex.Name);
                    bool consistent = MyResourceUtils.CheckTexturesConsistency(desc, tex2D.Description);
                    if (!consistent)
                    {
                        string errorMsg =
                            "All MyTextureArray has to have the same pixel format, width / height and # of mipmaps. Inconsistent textures: " +
                            tex.Name + " / " + firstTex.Name;
                        MyRenderProxy.Error(errorMsg);
                        MyRender11.Log.WriteLine(errorMsg);
                    }

                    for (int m = 0; m < mipmaps; m++)
                    {
                        MyRender11.RC.CopySubresourceRegion(tex2D,
                                                            Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource,
                                                            Resource.CalculateSubResourceIndex(m, i, mipmaps));

                        int sizeX = Resource.CalculateMipSize(m, Size.X);
                        int sizeY = Resource.CalculateMipSize(m, Size.Y);
                        ByteSize += FormatHelper.ComputeScanlineCount(TextureFormat, sizeX) * 4 * FormatHelper.ComputeScanlineCount(TextureFormat, sizeY) * 4 * FormatHelper.SizeOfInBytes(TextureFormat);
                    }

                    i++;
                }

                m_srv = new ShaderResourceView(MyRender11.Device, Resource);
            }
            public void OnDeviceInit()
            {
                ISrvBindable tex0 = m_sourceTextures[0];

                Texture2DDescription texDesc = new Texture2DDescription();

                texDesc.ArraySize                 = m_sourceTextures.Count;
                texDesc.BindFlags                 = BindFlags.ShaderResource;
                texDesc.CpuAccessFlags            = CpuAccessFlags.None;
                texDesc.Format                    = tex0.Srv.Description.Format;
                texDesc.Height                    = tex0.Size.X;
                texDesc.MipLevels                 = tex0.Srv.Description.Texture2D.MipLevels;
                texDesc.OptionFlags               = ResourceOptionFlags.None;
                texDesc.SampleDescription.Count   = 1;
                texDesc.SampleDescription.Quality = 0;
                texDesc.Usage        = ResourceUsage.Default;
                texDesc.Width        = tex0.Size.Y;
                m_resource           = new Texture2D(MyRender11.Device, texDesc);
                m_resource.DebugName = m_debugName;

                ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription();

                srvDesc.Format    = tex0.Srv.Description.Format;
                srvDesc.Dimension = ShaderResourceViewDimension.Texture2DArray;
                srvDesc.Texture2DArray.ArraySize       = m_sourceTextures.Count;
                srvDesc.Texture2DArray.FirstArraySlice = 0;
                srvDesc.Texture2DArray.MipLevels       = tex0.Srv.Description.Texture2D.MipLevels;
                srvDesc.Texture2DArray.MostDetailedMip = 0;
                m_srv           = new ShaderResourceView(MyRender11.Device, m_resource, srvDesc);
                m_srv.DebugName = m_debugName;

                int i = 0;

                foreach (ISrvBindable tex in m_sourceTextures)
                {
                    Texture2D tex2 = (Texture2D)tex.Resource;
                    if (tex2 == null)
                    {
                        MyRenderProxy.Assert(false, "Array texture is created using resource that is not texture2d");
                        i++;
                        continue;
                    }
                    Texture2DDescription texDesc2 = tex2.Description;
                    MyRenderProxy.Assert(MyArrayTextureManager.CheckArrayCompatible(texDesc, texDesc2),
                                         "Incompatible texture is used to create array texture");

                    int mipmaps = tex.Srv.Description.Texture2D.MipLevels;
                    for (int m = 0; m < mipmaps; m++)
                    {
                        MyRender11.RC.CopySubresourceRegion(tex.Resource,
                                                            Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource,
                                                            Resource.CalculateSubResourceIndex(m, i, mipmaps));
                    }
                    i++;
                }
            }
Example #6
0
        /// <summary>
        /// 原始思想:http://stackoverflow.com/questions/19364012/d3d11-creating-a-cube-map-from-6-images
        /// 上面的链接页面中,OptionFlags 的参数错误,后参考 http://www.gamedev.net/topic/647237-dx11-cube-texture-creation/ 做出修正。
        /// </summary>
        /// <param name="device"></param>
        /// <param name="texture2Ds"></param>
        /// <returns></returns>
        public static ShaderResourceView CreateCubeMapFrom6Textures(Device device, Texture2D[] texture2Ds)
        {
            Debug.Assert(texture2Ds.Length == 6);
            var texElemDesc  = texture2Ds[0].Description;
            var texArrayDesc = new Texture2DDescription()
            {
                Width             = texElemDesc.Width,
                Height            = texElemDesc.Height,
                MipLevels         = texElemDesc.MipLevels,
                ArraySize         = 6,
                Format            = texElemDesc.Format,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.TextureCube
            };
            var texArray     = new Texture2D(device, texArrayDesc);
            var context      = device.ImmediateContext;
            var sourceRegion = new ResourceRegion();

            for (var i = 0; i < 6; ++i)
            {
                for (var mipLevel = 0; mipLevel < texArrayDesc.MipLevels; ++mipLevel)
                {
                    sourceRegion.Left   = 0;
                    sourceRegion.Right  = texArrayDesc.Width >> mipLevel;
                    sourceRegion.Top    = 0;
                    sourceRegion.Bottom = texArrayDesc.Height >> mipLevel;
                    sourceRegion.Front  = 0;
                    sourceRegion.Back   = 1;
                    if (sourceRegion.Bottom <= 0 || sourceRegion.Right <= 0)
                    {
                        break;
                    }
                    var n = Resource.CalculateSubResourceIndex(mipLevel, i, texArrayDesc.MipLevels);
                    context.CopySubresourceRegion(texture2Ds[i], mipLevel, sourceRegion, texArray, n);
                }
            }

            var viewDesc = new ShaderResourceViewDescription()
            {
                Format      = texArrayDesc.Format,
                Dimension   = ShaderResourceViewDimension.TextureCube,
                TextureCube = new ShaderResourceViewDescription.TextureCubeResource()
                {
                    MostDetailedMip = 0,
                    MipLevels       = texArrayDesc.MipLevels
                }
            };

            return(new ShaderResourceView(device, texArray, viewDesc));
        }
Example #7
0
        internal void Init()
        {
            var srcData = MyTextures.Textures.Data[m_mergeList[0].Index];
            var srcDesc = MyTextures.GetView(m_mergeList[0]).Description;

            Size     = MyTextures.GetSize(m_mergeList[0]);
            ArrayLen = m_mergeList.Length;

            Texture2DDescription desc = new Texture2DDescription();

            desc.ArraySize                 = ArrayLen;
            desc.BindFlags                 = BindFlags.ShaderResource;
            desc.CpuAccessFlags            = CpuAccessFlags.None;
            desc.Format                    = srcDesc.Format;
            desc.Height                    = (int)Size.Y;
            desc.Width                     = (int)Size.X;
            desc.MipLevels                 = srcDesc.Texture2D.MipLevels;
            desc.SampleDescription.Count   = 1;
            desc.SampleDescription.Quality = 0;
            desc.Usage                     = ResourceUsage.Default;
            m_resource                     = new Texture2D(MyRender11.Device, desc);
            m_resource.DebugName           = m_debugName;

            // foreach mip
            var mipmaps = srcDesc.Texture2D.MipLevels;

            for (int a = 0; a < ArrayLen; a++)
            {
                var data  = MyTextures.Textures.Data[m_mergeList[a].Index];
                var tex2D = data.Resource as Texture2D;
                MyRenderProxy.Assert(tex2D != null, "MyTextureArray supports only 2D textures. Inconsistent texture: " + data.Name);
                bool consistent = tex2D.Description.Format == desc.Format && tex2D.Description.MipLevels == desc.MipLevels &&
                                  tex2D.Description.Width == desc.Width && tex2D.Description.Height == desc.Height;
                if (!consistent)
                {
                    string errorMsg = "All MyTextureArray has to have the same pixel format, width / height and # of mipmaps. Inconsistent textures: " + data.Name + " / " + srcData.Name;
                    MyRenderProxy.Error(errorMsg);
                    MyRender11.Log.WriteLine(errorMsg);
                }

                for (int m = 0; m < mipmaps; m++)
                {
                    MyRender11.DeviceContext.CopySubresourceRegion(tex2D, Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource,
                                                                   Resource.CalculateSubResourceIndex(m, a, mipmaps));
                }
            }

            m_Srv = new ShaderResourceView(MyRender11.Device, Resource);
        }
Example #8
0
        internal MyTextureArray(TexId[] mergeList, string debugName)
        {
            var srcDesc = MyTextures.GetView(mergeList[0]).Description;

            Size     = MyTextures.GetSize(mergeList[0]);
            ArrayLen = mergeList.Length;

            Texture2DDescription desc = new Texture2DDescription();

            desc.ArraySize                 = ArrayLen;
            desc.BindFlags                 = BindFlags.ShaderResource;
            desc.CpuAccessFlags            = CpuAccessFlags.None;
            desc.Format                    = srcDesc.Format;
            desc.Height                    = (int)Size.Y;
            desc.Width                     = (int)Size.X;
            desc.MipLevels                 = srcDesc.Texture2D.MipLevels;
            desc.SampleDescription.Count   = 1;
            desc.SampleDescription.Quality = 0;
            desc.Usage                     = ResourceUsage.Default;
            m_resource                     = new Texture2D(MyRender11.Device, desc);
            m_resource.DebugName           = debugName;

            // foreach mip
            var mipmaps = desc.MipLevels;// (int)Math.Log(Size.X, 2) + 1;

            for (int a = 0; a < ArrayLen; a++)
            {
                var tex2D = MyTextures.Textures.Data[mergeList[a].Index].Resource as Texture2D;
                MyRenderProxy.Assert(tex2D != null, "MyTextureArray supports only 2D textures");
                MyRenderProxy.Assert(tex2D.Description.Format == desc.Format && tex2D.Description.MipLevels == desc.MipLevels &&
                                     tex2D.Description.Width == desc.Width && tex2D.Description.Height == desc.Height,
                                     "All MyTextureArray has to have the same pixel format, width / height and # of mipmaps.");

                for (int m = 0; m < mipmaps; m++)
                {
                    if (((Texture2D)MyTextures.Textures.Data[mergeList[a].Index].Resource).Description.Format != ((Texture2D)Resource).Description.Format)
                    {
                        MyRender11.Log.WriteLine(String.Format("Inconsistent format in textures array {0}", MyTextures.Textures.Data[mergeList[a].Index].Name));
                    }

                    MyRender11.DeviceContext.CopySubresourceRegion(MyTextures.Textures.Data[mergeList[a].Index].Resource, Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource,
                                                                   Resource.CalculateSubResourceIndex(m, a, mipmaps));
                }
            }

            ShaderView = new ShaderResourceView(MyRender11.Device, Resource);
        }
Example #9
0
        /// <summary>
        ///     Converts this object to a texture 2 d array.
        /// </summary>
        /// <param name="device">        The device. </param>
        /// <param name="bitmapSources"> The bitmap sources. </param>
        /// <returns>
        ///     The given data converted to a Texture2D.
        /// </returns>
        internal static Texture2D ToTexture2DArray(Device5 device, BitmapSource[] bitmapSources)
        {
            int width  = bitmapSources[0].Size.Width;
            int height = bitmapSources[0].Size.Height;

            Texture2D texArray = new Texture2D(
                device,
                new Texture2DDescription
            {
                Width             = width,
                Height            = height,
                ArraySize         = bitmapSources.Length,
                BindFlags         = BindFlags.ShaderResource,
                Usage             = ResourceUsage.Default,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.R8G8B8A8_UNorm,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0)
            });

            int stride = width * 4;

            for (int i = 0; i < bitmapSources.Length; i++)
            {
                using (BitmapSource bitmap = bitmapSources[i])
                {
                    using (DataStream buffer = new DataStream(height * stride, true, true))
                    {
                        bitmap.CopyPixels(stride, buffer);
                        DataBox box = new DataBox(buffer.DataPointer, stride, 1);
                        device.ImmediateContext.UpdateSubresource(
                            box, texArray, Resource.CalculateSubResourceIndex(0, i, 1));
                    }
                }
            }
            return(texArray);
        }
Example #10
0
            public void Load()
            {
                if (TextureState == FileTextureState.Loaded)
                {
                    return;
                }

                string path = Path.Combine(MyFileSystem.ContentPath, Name);

                Debug.Assert(m_resource == null);
                Debug.Assert(m_srv == null, "Texture " + Name + " in invalid state");

                Image img = null;

                if (MyFileSystem.FileExists(path))
                {
                    try
                    {
                        using (var s = MyFileSystem.OpenRead(path))
                        {
                            img = Image.Load(s);
                            m_imageFormatInFile = img.Description.Format;
                        }
                    }
                    catch (Exception e)
                    {
                        MyRender11.Log.WriteLine("Error while loading texture: " + path + ", exception: " + e);
                    }
                }

                bool loaded = false;

                if (img != null)
                {
                    int skipMipmaps = (m_type != MyFileTextureEnum.GUI && m_type != MyFileTextureEnum.GPUPARTICLES && img.Description.MipLevels > 1)
                        ? MyRender11.RenderSettings.TextureQuality.MipmapsToSkip(img.Description.Width,
                                                                                 img.Description.Height)
                        : 0;

                    if (m_skipQualityReduction)
                    {
                        skipMipmaps = 0;
                    }

                    int totalSize = 0;

                    int targetMipmaps = img.Description.MipLevels - skipMipmaps;
                    var mipmapsData   = new DataBox[(img.Description.MipLevels - skipMipmaps) * img.Description.ArraySize];

                    long delta    = 0;
                    int  lastSize = 0;

                    for (int z = 0; z < img.Description.ArraySize; z++)
                    {
                        for (int i = 0; i < targetMipmaps; i++)
                        {
                            var pixels = img.GetPixelBuffer(z, i + skipMipmaps);
                            mipmapsData[Resource.CalculateSubResourceIndex(i, z, targetMipmaps)] =
                                new DataBox {
                                DataPointer = pixels.DataPointer, RowPitch = pixels.RowStride
                            };
                            delta = pixels.DataPointer.ToInt64() - img.DataPointer.ToInt64();

                            lastSize   = pixels.BufferStride;
                            totalSize += lastSize;
                        }
                    }

                    var targetWidth  = img.Description.Width >> skipMipmaps;
                    var targetHeight = img.Description.Height >> skipMipmaps;

                    bool overwriteFormatToSrgb = (m_type != MyFileTextureEnum.NORMALMAP_GLOSS) &&
                                                 !FormatHelper.IsSRgb(img.Description.Format);

                    var desc = new Texture2DDescription
                    {
                        MipLevels         = targetMipmaps,
                        Format            = overwriteFormatToSrgb ? MyResourceUtils.MakeSrgb(img.Description.Format) : img.Description.Format,
                        Height            = targetHeight,
                        Width             = targetWidth,
                        ArraySize         = img.Description.ArraySize,
                        BindFlags         = BindFlags.ShaderResource,
                        CpuAccessFlags    = CpuAccessFlags.None,
                        Usage             = ResourceUsage.Immutable,
                        SampleDescription = new SampleDescription {
                            Count = 1, Quality = 0
                        },
                        OptionFlags =
                            img.Description.Dimension == TextureDimension.TextureCube
                                ? ResourceOptionFlags.TextureCube
                                : ResourceOptionFlags.None
                    };

                    try
                    {
                        m_resource = new Texture2D(MyRender11.Device, desc, mipmapsData);
                        m_size     = new Vector2I(targetWidth, targetHeight);
                        //m_skippedMipmaps = skipMipmaps;
                        m_fileExists = true;
                        m_byteSize   = totalSize;
                        m_ownsData   = true;

                        m_srv = new ShaderResourceView(MyRender11.Device, m_resource);
                        m_resource.DebugName = m_name;
                        m_srv.DebugName      = m_name;

                        img.Dispose();

                        loaded = true;
                    }
                    catch (SharpDXException)
                    {
                        img.Dispose();
                    }
                }
                if (!loaded)
                {
                    ISrvBindable replacingTexture = MyGeneratedTextureManager.ZeroTex;
                    switch (m_type)
                    {
                    case MyFileTextureEnum.NORMALMAP_GLOSS:
                        replacingTexture = MyGeneratedTextureManager.MissingNormalGlossTex;
                        break;

                    case MyFileTextureEnum.EXTENSIONS:
                        replacingTexture = MyGeneratedTextureManager.MissingExtensionTex;
                        break;

                    case MyFileTextureEnum.ALPHAMASK:
                        replacingTexture = MyGeneratedTextureManager.MissingAlphamaskTex;
                        break;

                    case MyFileTextureEnum.CUBEMAP:
                        replacingTexture = MyGeneratedTextureManager.MissingCubeTex;
                        break;
                    }

                    MyRender11.Log.WriteLine("Could not load texture: " + path);

                    m_srv        = replacingTexture.Srv;
                    m_resource   = replacingTexture.Resource;
                    m_size       = replacingTexture.Size;
                    m_ownsData   = false;
                    m_fileExists = false;
                    m_byteSize   = 0;
                    MyRender11.Log.WriteLine("Missing or invalid texture: " + Name);
                }

                TextureState = FileTextureState.Loaded;
            }
Example #11
0
            public void OnDeviceInit()
            {
                MyFileTextureParams fileTexParams;
                bool ret = GetCorrectedFileTextureParams(out fileTexParams);

                //MyRenderProxy.Assert(ret, "It is not implemented mechanism, what to do, when none of the textures exist");

                m_size = fileTexParams.Resolution;
                Texture2DDescription desc = new Texture2DDescription();

                desc.ArraySize      = m_listSubresourceFilenames.Count;
                desc.BindFlags      = BindFlags.ShaderResource;
                desc.CpuAccessFlags = CpuAccessFlags.None;
                desc.Format         = fileTexParams.Format;
                desc.Height         = (int)Size.Y;
                desc.Width          = (int)Size.X;
                var mipmaps = desc.MipLevels = fileTexParams.Mipmaps;

                desc.SampleDescription.Count   = 1;
                desc.SampleDescription.Quality = 0;
                desc.Usage           = ResourceUsage.Default;
                m_resource           = new Texture2D(MyRender11.Device, desc);
                m_resource.DebugName = m_resourceName;
                TextureFormat        = fileTexParams.Format;

                // foreach mip
                int i = 0;

                foreach (var path in m_listSubresourceFilenames)
                {
                    bool         isUsedCreatedGeneratedTexture = false;
                    ISrvBindable tex   = MyManagers.FileTextures.GetTexture(path, m_type, true);
                    var          tex2D = tex.Resource as Texture2D;
                    MyRenderProxy.Assert(tex2D != null,
                                         "MyFileArrayTexture supports only 2D textures. Inconsistent texture: " + tex.Name);
                    bool consistent = MyResourceUtils.CheckTexturesConsistency(desc, tex2D.Description);
                    if (!consistent)
                    {
                        if (!string.IsNullOrEmpty(path) && MyFileSystem.FileExists(path))
                        {
                            string msg =
                                string.Format(
                                    "Texture {0} cannot be loaded. If this message is displayed on reloading textures, please restart the game. If it is not, please notify developers.", path);
                            MyRenderProxy.Fail(msg);
                        }
                    }

                    if (!consistent && m_recoverySystem.UseErrorTexture) // if the texture cannot be used, error texture will be used
                    {
                        tex   = MyManagers.FileTextures.GetTexture(m_recoverySystem.TextureFilepath, m_type, true);
                        tex2D = tex.Resource as Texture2D;
                        MyRenderProxy.Assert(tex2D != null,
                                             "MyFileArrayTexture supports only 2D textures. Inconsistent texture: " + m_recoverySystem.TextureFilepath);
                        consistent = MyResourceUtils.CheckTexturesConsistency(desc, tex2D.Description);
                    }
                    if (!consistent && m_recoverySystem.UseBytePattern) // if the texture cannot be used, byte pattern will be used to generate texture
                    {
                        tex = MyManagers.GeneratedTextures.CreateFromBytePattern("MyFileArrayTexture.Tmp", desc.Width,
                                                                                 desc.Height, m_recoverySystem.FormatBytePattern, m_recoverySystem.BytePattern);
                        tex2D = tex.Resource as Texture2D;
                        MyRenderProxy.Assert(tex2D != null);
                        consistent = MyResourceUtils.CheckTexturesConsistency(desc, tex2D.Description);
                        isUsedCreatedGeneratedTexture = true;
                    }
                    if (!consistent)
                    {
                        Texture2DDescription desc1 = desc;
                        Texture2DDescription desc2 = tex2D.Description;
                        string errorMsg            = string.Format("Textures ({0}) is not compatible within array texture! Width: ({1},{2}) Height: ({3},{4}) Mipmaps: ({5},{6}) Format: ({7},{8})",
                                                                   path, desc1.Width, desc2.Width, desc1.Height, desc2.Height, desc1.MipLevels, desc2.MipLevels, desc1.Format, desc2.Format);
                        MyRenderProxy.Error(errorMsg);
                        MyRender11.Log.WriteLine(errorMsg);
                    }

                    for (int m = 0; m < mipmaps; m++)
                    {
                        MyRender11.RC.CopySubresourceRegion(tex,
                                                            Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource,
                                                            Resource.CalculateSubResourceIndex(m, i, mipmaps));

                        int sizeX = Resource.CalculateMipSize(m, Size.X);
                        int sizeY = Resource.CalculateMipSize(m, Size.Y);
                        ByteSize += FormatHelper.ComputeScanlineCount(TextureFormat, sizeX) * 4 * FormatHelper.ComputeScanlineCount(TextureFormat, sizeY) * 4 * FormatHelper.SizeOfInBytes(TextureFormat);
                    }

                    if (isUsedCreatedGeneratedTexture)
                    {
                        IGeneratedTexture generatedTex = (IGeneratedTexture)tex;
                        MyManagers.GeneratedTextures.DisposeTex(generatedTex);
                    }
                    i++;
                }

                m_srv = new ShaderResourceView(MyRender11.Device, Resource);
            }
Example #12
0
        private Result CaptureTextureFix(DeviceContext deviceContext,
                                         Texture2D source,
                                         out Texture2DDescription desc,
                                         out Texture2D staging)
        {
            desc    = new Texture2DDescription();
            staging = null;

            if (deviceContext == null || source == null)
            {
                return(Result.InvalidArg);
            }

            var resType = source.Dimension;

            if (resType != ResourceDimension.Texture2D)
            {
                //string message = SharpDX.Diagnostics.ErrorManager.GetErrorMessage(0);
                //return Result.GetResultFromWin32Error(ERROR_NOT_SUPPORTED)
            }

            desc = source.Description;

            var d3dDevice = deviceContext.Device;

            //Texture2D staging = null;

            if (desc.SampleDescription.Count > 1)
            {
                desc.SampleDescription.Count   = 1;
                desc.SampleDescription.Quality = 0;

                Texture2D temp;

                try {
                    temp = new Texture2D(d3dDevice, desc);
                } catch (SharpDXException e) {
                    return(e.ResultCode);
                }

                var fmt = EnsureNotTypeless(desc.Format);

                FormatSupport support;
                try {
                    support = d3dDevice.CheckFormatSupport(fmt);
                } catch (SharpDXException e) {
                    return(e.ResultCode);
                }

                if ((support & FormatSupport.MultisampleResolve) == 0)
                {
                    return(Result.Fail);
                }

                for (var item = 0; item < desc.ArraySize; ++item)
                {
                    for (var level = 0; level < desc.MipLevels; ++level)
                    {
                        var index = Resource.CalculateSubResourceIndex(level, item, desc.MipLevels);
                        deviceContext.ResolveSubresource(temp, index, source, index, fmt);
                    }
                }

                desc.BindFlags      = 0;
                desc.OptionFlags   &= ResourceOptionFlags.TextureCube;
                desc.CpuAccessFlags = CpuAccessFlags.Read;
                desc.Usage          = ResourceUsage.Staging;

                try {
                    staging = new Texture2D(d3dDevice, desc);
                    deviceContext.CopyResource(temp, staging);
                } catch (SharpDXException e) {
                    return(e.ResultCode);
                }
            }
            else if (desc.Usage == ResourceUsage.Staging && desc.CpuAccessFlags == CpuAccessFlags.Read)
            {
                staging = source;
            }
            else
            {
                desc.BindFlags      = 0;
                desc.OptionFlags   &= ResourceOptionFlags.TextureCube;
                desc.CpuAccessFlags = CpuAccessFlags.Read;
                desc.Usage          = ResourceUsage.Staging;

                try {
                    staging = new Texture2D(d3dDevice, desc);
                    deviceContext.CopyResource(source, staging);
                } catch (SharpDXException e) {
                    return(e.ResultCode);
                }
            }

            return(Result.Ok);
        }
Example #13
0
        public static ShaderResourceView CreateTexture2DArray(Device device, DeviceContext context, string[] filePaths, TextureLoadOptions options)
        {
            var srcTex = new Texture2D[filePaths.Length];

            for (var i = 0; i < filePaths.Length; i++)
            {
                srcTex[i] = CreateTextureFromFile(device, filePaths[i], options);
            }
            var texElementDesc = srcTex[0].Description;

            var texArrayDesc = new Texture2DDescription {
                Width             = texElementDesc.Width,
                Height            = texElementDesc.Height,
                MipLevels         = texElementDesc.MipLevels,
                ArraySize         = srcTex.Length,
                Format            = texElementDesc.Format,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            };

            var texArray = new Texture2D(device, texArrayDesc);

            texArray.DebugName = "texture array: + " + filePaths.Aggregate((i, j) => i + ", " + j);
            for (int texElement = 0; texElement < srcTex.Length; texElement++)
            {
                for (int mipLevel = 0; mipLevel < texElementDesc.MipLevels; mipLevel++)
                {
                    int     mippedSize;
                    DataBox mappedTex2D;
                    mappedTex2D = context.MapSubresource(srcTex[texElement], mipLevel, 0, MapMode.Read, MapFlags.None, out mippedSize);

                    context.UpdateSubresource(
                        mappedTex2D,
                        texArray,
                        Resource.CalculateSubResourceIndex(mipLevel, texElement, texElementDesc.MipLevels)
                        );
                    context.UnmapSubresource(srcTex[texElement], mipLevel);
                }
            }
            var viewDesc = new ShaderResourceViewDescription {
                Format         = texArrayDesc.Format,
                Dimension      = ShaderResourceViewDimension.Texture2DArray,
                Texture2DArray = new ShaderResourceViewDescription.Texture2DArrayResource()
                {
                    MostDetailedMip = 0,
                    MipLevels       = texArrayDesc.MipLevels,
                    FirstArraySlice = 0,
                    ArraySize       = srcTex.Length
                }
            };

            var texArraySRV = new ShaderResourceView(device, texArray, viewDesc);

            Utilities.Dispose(ref texArray);
            for (int i = 0; i < srcTex.Length; i++)
            {
                Utilities.Dispose(ref srcTex[i]);
            }

            return(texArraySRV);
        }