コード例 #1
0
        /// <summary>
        /// Tries to find an existing texture, or create a new one if not found.
        /// </summary>
        /// <param name="memoryManager">GPU memory manager where the texture is mapped</param>
        /// <param name="flags">The texture search flags, defines texture comparison rules</param>
        /// <param name="info">Texture information of the texture to be found or created</param>
        /// <param name="layerSize">Size in bytes of a single texture layer</param>
        /// <param name="sizeHint">A hint indicating the minimum used size for the texture</param>
        /// <param name="range">Optional ranges of physical memory where the texture data is located</param>
        /// <returns>The texture</returns>
        public Texture FindOrCreateTexture(
            MemoryManager memoryManager,
            TextureSearchFlags flags,
            TextureInfo info,
            int layerSize    = 0,
            Size?sizeHint    = null,
            MultiRange?range = null)
        {
            bool isSamplerTexture = (flags & TextureSearchFlags.ForSampler) != 0;

            TextureScaleMode scaleMode = IsUpscaleCompatible(info, (flags & TextureSearchFlags.WithUpscale) != 0);

            ulong address;

            if (range != null)
            {
                address = range.Value.GetSubRange(0).Address;
            }
            else
            {
                address = memoryManager.Translate(info.GpuAddress);

                if (address == MemoryManager.PteUnmapped)
                {
                    return(null);
                }
            }

            int sameAddressOverlapsCount;

            lock (_textures)
            {
                // Try to find a perfect texture match, with the same address and parameters.
                sameAddressOverlapsCount = _textures.FindOverlaps(address, ref _textureOverlaps);
            }

            Texture texture = null;

            TextureMatchQuality bestQuality = TextureMatchQuality.NoMatch;

            for (int index = 0; index < sameAddressOverlapsCount; index++)
            {
                Texture overlap = _textureOverlaps[index];

                TextureMatchQuality matchQuality = overlap.IsExactMatch(info, flags);

                if (matchQuality != TextureMatchQuality.NoMatch)
                {
                    // If the parameters match, we need to make sure the texture is mapped to the same memory regions.
                    if (range != null)
                    {
                        // If a range of memory was supplied, just check if the ranges match.
                        if (!overlap.Range.Equals(range.Value))
                        {
                            continue;
                        }
                    }
                    else
                    {
                        // If no range was supplied, we can check if the GPU virtual address match. If they do,
                        // we know the textures are located at the same memory region.
                        // If they don't, it may still be mapped to the same physical region, so we
                        // do a more expensive check to tell if they are mapped into the same physical regions.
                        // If the GPU VA for the texture has ever been unmapped, then the range must be checked regardless.
                        if ((overlap.Info.GpuAddress != info.GpuAddress || overlap.ChangedMapping) &&
                            !memoryManager.CompareRange(overlap.Range, info.GpuAddress))
                        {
                            continue;
                        }
                    }
                }

                if (matchQuality == TextureMatchQuality.Perfect)
                {
                    texture = overlap;
                    break;
                }
                else if (matchQuality > bestQuality)
                {
                    texture     = overlap;
                    bestQuality = matchQuality;
                }
            }

            if (texture != null)
            {
                ChangeSizeIfNeeded(info, texture, isSamplerTexture, sizeHint);

                texture.SynchronizeMemory();

                return(texture);
            }
            else if (flags.HasFlag(TextureSearchFlags.NoCreate))
            {
                return(null);
            }

            // Calculate texture sizes, used to find all overlapping textures.
            SizeInfo sizeInfo = info.CalculateSizeInfo(layerSize);

            ulong size            = (ulong)sizeInfo.TotalSize;
            bool  partiallyMapped = false;

            if (range == null)
            {
                range = memoryManager.GetPhysicalRegions(info.GpuAddress, size);

                for (int i = 0; i < range.Value.Count; i++)
                {
                    if (range.Value.GetSubRange(i).Address == MemoryManager.PteUnmapped)
                    {
                        partiallyMapped = true;
                        break;
                    }
                }
            }

            // Find view compatible matches.
            int overlapsCount;

            lock (_textures)
            {
                overlapsCount = _textures.FindOverlaps(range.Value, ref _textureOverlaps);
            }

            if (_overlapInfo.Length != _textureOverlaps.Length)
            {
                Array.Resize(ref _overlapInfo, _textureOverlaps.Length);
            }

            // =============== Find Texture View of Existing Texture ===============

            int fullyCompatible = 0;

            // Evaluate compatibility of overlaps, add temporary references

            for (int index = 0; index < overlapsCount; index++)
            {
                Texture overlap = _textureOverlaps[index];
                TextureViewCompatibility overlapCompatibility = overlap.IsViewCompatible(info, range.Value, sizeInfo.LayerSize, _context.Capabilities, out int firstLayer, out int firstLevel);

                if (overlapCompatibility == TextureViewCompatibility.Full)
                {
                    if (overlap.IsView)
                    {
                        overlapCompatibility = TextureViewCompatibility.CopyOnly;
                    }
                    else
                    {
                        fullyCompatible++;
                    }
                }

                _overlapInfo[index] = new OverlapInfo(overlapCompatibility, firstLayer, firstLevel);
                overlap.IncrementReferenceCount();
            }

            // Search through the overlaps to find a compatible view and establish any copy dependencies.

            for (int index = 0; index < overlapsCount; index++)
            {
                Texture     overlap = _textureOverlaps[index];
                OverlapInfo oInfo   = _overlapInfo[index];

                if (oInfo.Compatibility == TextureViewCompatibility.Full)
                {
                    TextureInfo adjInfo = AdjustSizes(overlap, info, oInfo.FirstLevel);

                    if (!isSamplerTexture)
                    {
                        info = adjInfo;
                    }

                    texture = overlap.CreateView(adjInfo, sizeInfo, range.Value, oInfo.FirstLayer, oInfo.FirstLevel);

                    ChangeSizeIfNeeded(info, texture, isSamplerTexture, sizeHint);

                    texture.SynchronizeMemory();
                    break;
                }
                else if (oInfo.Compatibility == TextureViewCompatibility.CopyOnly && fullyCompatible == 0)
                {
                    // Only copy compatible. If there's another choice for a FULLY compatible texture, choose that instead.

                    texture = new Texture(_context, _physicalMemory, info, sizeInfo, range.Value, scaleMode);

                    texture.InitializeGroup(true, true, new List <TextureIncompatibleOverlap>());
                    texture.InitializeData(false, false);

                    overlap.SynchronizeMemory();
                    overlap.CreateCopyDependency(texture, oInfo.FirstLayer, oInfo.FirstLevel, true);
                    break;
                }
            }

            if (texture != null)
            {
                // This texture could be a view of multiple parent textures with different storages, even if it is a view.
                // When a texture is created, make sure all possible dependencies to other textures are created as copies.
                // (even if it could be fulfilled without a copy)

                for (int index = 0; index < overlapsCount; index++)
                {
                    Texture     overlap = _textureOverlaps[index];
                    OverlapInfo oInfo   = _overlapInfo[index];

                    if (oInfo.Compatibility <= TextureViewCompatibility.LayoutIncompatible)
                    {
                        if (!overlap.IsView && texture.DataOverlaps(overlap, oInfo.Compatibility))
                        {
                            texture.Group.RegisterIncompatibleOverlap(new TextureIncompatibleOverlap(overlap.Group, oInfo.Compatibility), true);
                        }
                    }
                    else if (overlap.Group != texture.Group)
                    {
                        overlap.SynchronizeMemory();
                        overlap.CreateCopyDependency(texture, oInfo.FirstLayer, oInfo.FirstLevel, true);
                    }
                }

                texture.SynchronizeMemory();
            }

            // =============== Create a New Texture ===============

            // No match, create a new texture.
            if (texture == null)
            {
                texture = new Texture(_context, _physicalMemory, info, sizeInfo, range.Value, scaleMode);

                // Step 1: Find textures that are view compatible with the new texture.
                // Any textures that are incompatible will contain garbage data, so they should be removed where possible.

                int viewCompatible = 0;
                fullyCompatible = 0;
                bool setData = isSamplerTexture || overlapsCount == 0 || flags.HasFlag(TextureSearchFlags.ForCopy);

                bool hasLayerViews = false;
                bool hasMipViews   = false;

                var incompatibleOverlaps = new List <TextureIncompatibleOverlap>();

                for (int index = 0; index < overlapsCount; index++)
                {
                    Texture overlap        = _textureOverlaps[index];
                    bool    overlapInCache = overlap.CacheNode != null;

                    TextureViewCompatibility compatibility = texture.IsViewCompatible(overlap.Info, overlap.Range, overlap.LayerSize, _context.Capabilities, out int firstLayer, out int firstLevel);

                    if (overlap.IsView && compatibility == TextureViewCompatibility.Full)
                    {
                        compatibility = TextureViewCompatibility.CopyOnly;
                    }

                    if (compatibility > TextureViewCompatibility.LayoutIncompatible)
                    {
                        _overlapInfo[viewCompatible]     = new OverlapInfo(compatibility, firstLayer, firstLevel);
                        _textureOverlaps[index]          = _textureOverlaps[viewCompatible];
                        _textureOverlaps[viewCompatible] = overlap;

                        if (compatibility == TextureViewCompatibility.Full)
                        {
                            if (viewCompatible != fullyCompatible)
                            {
                                // Swap overlaps so that the fully compatible views have priority.

                                _overlapInfo[viewCompatible]     = _overlapInfo[fullyCompatible];
                                _textureOverlaps[viewCompatible] = _textureOverlaps[fullyCompatible];

                                _overlapInfo[fullyCompatible]     = new OverlapInfo(compatibility, firstLayer, firstLevel);
                                _textureOverlaps[fullyCompatible] = overlap;
                            }

                            fullyCompatible++;
                        }

                        viewCompatible++;

                        hasLayerViews |= overlap.Info.GetSlices() < texture.Info.GetSlices();
                        hasMipViews   |= overlap.Info.Levels < texture.Info.Levels;
                    }
                    else
                    {
                        bool dataOverlaps = texture.DataOverlaps(overlap, compatibility);

                        if (!overlap.IsView && dataOverlaps && !incompatibleOverlaps.Exists(incompatible => incompatible.Group == overlap.Group))
                        {
                            incompatibleOverlaps.Add(new TextureIncompatibleOverlap(overlap.Group, compatibility));
                        }

                        bool removeOverlap;
                        bool modified = overlap.CheckModified(false);

                        if (overlapInCache || !setData)
                        {
                            if (!dataOverlaps)
                            {
                                // Allow textures to overlap if their data does not actually overlap.
                                // This typically happens when mip level subranges of a layered texture are used. (each texture fills the gaps of the others)
                                continue;
                            }

                            // The overlap texture is going to contain garbage data after we draw, or is generally incompatible.
                            // The texture group will obtain copy dependencies for any subresources that are compatible between the two textures,
                            // but sometimes its data must be flushed regardless.

                            // If the texture was modified since its last use, then that data is probably meant to go into this texture.
                            // If the data has been modified by the CPU, then it also shouldn't be flushed.

                            bool flush = overlapInCache && !modified && overlap.AlwaysFlushOnOverlap;

                            setData |= modified || flush;

                            if (overlapInCache)
                            {
                                _cache.Remove(overlap, flush);
                            }

                            removeOverlap = modified;
                        }
                        else
                        {
                            // If an incompatible overlapping texture has been modified, then it's data is likely destined for this texture,
                            // and the overlapped texture will contain garbage. In this case, it should be removed to save memory.
                            removeOverlap = modified;
                        }

                        if (removeOverlap && overlap.Info.Target != Target.TextureBuffer)
                        {
                            overlap.RemoveFromPools(false);
                        }
                    }
                }

                texture.InitializeGroup(hasLayerViews, hasMipViews, incompatibleOverlaps);

                // We need to synchronize before copying the old view data to the texture,
                // otherwise the copied data would be overwritten by a future synchronization.
                texture.InitializeData(false, setData);

                texture.Group.InitializeOverlaps();

                for (int index = 0; index < viewCompatible; index++)
                {
                    Texture overlap = _textureOverlaps[index];

                    OverlapInfo oInfo = _overlapInfo[index];

                    if (overlap.Group == texture.Group)
                    {
                        // If the texture group is equal, then this texture (or its parent) is already a view.
                        continue;
                    }

                    TextureInfo overlapInfo = AdjustSizes(texture, overlap.Info, oInfo.FirstLevel);

                    if (texture.ScaleFactor != overlap.ScaleFactor)
                    {
                        // A bit tricky, our new texture may need to contain an existing texture that is upscaled, but isn't itself.
                        // In that case, we prefer the higher scale only if our format is render-target-like, otherwise we scale the view down before copy.

                        texture.PropagateScale(overlap);
                    }

                    if (oInfo.Compatibility != TextureViewCompatibility.Full)
                    {
                        // Copy only compatibility, or target texture is already a view.

                        overlap.SynchronizeMemory();
                        texture.CreateCopyDependency(overlap, oInfo.FirstLayer, oInfo.FirstLevel, false);
                    }
                    else
                    {
                        TextureCreateInfo createInfo = GetCreateInfo(overlapInfo, _context.Capabilities, overlap.ScaleFactor);

                        ITexture newView = texture.HostTexture.CreateView(createInfo, oInfo.FirstLayer, oInfo.FirstLevel);

                        overlap.SynchronizeMemory();

                        overlap.HostTexture.CopyTo(newView, 0, 0);

                        overlap.ReplaceView(texture, overlapInfo, newView, oInfo.FirstLayer, oInfo.FirstLevel);
                    }
                }

                texture.SynchronizeMemory();
            }

            // Sampler textures are managed by the texture pool, all other textures
            // are managed by the auto delete cache.
            if (!isSamplerTexture)
            {
                _cache.Add(texture);
            }

            lock (_textures)
            {
                _textures.Add(texture);
            }

            if (partiallyMapped)
            {
                lock (_partiallyMappedTextures)
                {
                    _partiallyMappedTextures.Add(texture);
                }
            }

            ShrinkOverlapsBufferIfNeeded();

            for (int i = 0; i < overlapsCount; i++)
            {
                _textureOverlaps[i].DecrementReferenceCount();
            }

            return(texture);
        }
コード例 #2
0
        /// <summary>
        /// Tries to find an existing texture, or create a new one if not found.
        /// </summary>
        /// <param name="flags">The texture search flags, defines texture comparison rules</param>
        /// <param name="info">Texture information of the texture to be found or created</param>
        /// <param name="layerSize">Size in bytes of a single texture layer</param>
        /// <param name="sizeHint">A hint indicating the minimum used size for the texture</param>
        /// <param name="range">Optional ranges of physical memory where the texture data is located</param>
        /// <returns>The texture</returns>
        public Texture FindOrCreateTexture(TextureSearchFlags flags, TextureInfo info, int layerSize = 0, Size?sizeHint = null, MultiRange?range = null)
        {
            bool isSamplerTexture = (flags & TextureSearchFlags.ForSampler) != 0;

            bool isScalable = IsUpscaleCompatible(info);

            TextureScaleMode scaleMode = TextureScaleMode.Blacklisted;

            if (isScalable)
            {
                scaleMode = (flags & TextureSearchFlags.WithUpscale) != 0 ? TextureScaleMode.Scaled : TextureScaleMode.Eligible;
            }

            ulong address;

            if (range != null)
            {
                address = range.Value.GetSubRange(0).Address;
            }
            else
            {
                address = _context.MemoryManager.Translate(info.GpuAddress);

                if (address == MemoryManager.PteUnmapped)
                {
                    return(null);
                }
            }

            int sameAddressOverlapsCount;

            lock (_textures)
            {
                // Try to find a perfect texture match, with the same address and parameters.
                sameAddressOverlapsCount = _textures.FindOverlaps(address, ref _textureOverlaps);
            }

            Texture texture = null;

            TextureMatchQuality bestQuality = TextureMatchQuality.NoMatch;

            for (int index = 0; index < sameAddressOverlapsCount; index++)
            {
                Texture overlap = _textureOverlaps[index];

                bool rangeMatches = range != null?overlap.Range.Equals(range.Value) : overlap.Info.GpuAddress == info.GpuAddress;

                if (!rangeMatches)
                {
                    continue;
                }

                TextureMatchQuality matchQuality = overlap.IsExactMatch(info, flags);

                if (matchQuality == TextureMatchQuality.Perfect)
                {
                    texture = overlap;
                    break;
                }
                else if (matchQuality > bestQuality)
                {
                    texture     = overlap;
                    bestQuality = matchQuality;
                }
            }

            if (texture != null)
            {
                if (!isSamplerTexture)
                {
                    // If not a sampler texture, it is managed by the auto delete
                    // cache, ensure that it is on the "top" of the list to avoid
                    // deletion.
                    _cache.Lift(texture);
                }

                ChangeSizeIfNeeded(info, texture, isSamplerTexture, sizeHint);

                texture.SynchronizeMemory();

                return(texture);
            }

            // Calculate texture sizes, used to find all overlapping textures.
            SizeInfo sizeInfo = info.CalculateSizeInfo(layerSize);

            ulong size = (ulong)sizeInfo.TotalSize;

            if (range == null)
            {
                range = _context.MemoryManager.GetPhysicalRegions(info.GpuAddress, size);
            }

            // Find view compatible matches.
            int overlapsCount;

            lock (_textures)
            {
                overlapsCount = _textures.FindOverlaps(range.Value, ref _textureOverlaps);
            }

            for (int index = 0; index < overlapsCount; index++)
            {
                Texture overlap = _textureOverlaps[index];
                TextureViewCompatibility overlapCompatibility = overlap.IsViewCompatible(info, range.Value, out int firstLayer, out int firstLevel);

                if (overlapCompatibility == TextureViewCompatibility.Full)
                {
                    TextureInfo oInfo = AdjustSizes(overlap, info, firstLevel);

                    if (!isSamplerTexture)
                    {
                        info = oInfo;
                    }

                    texture = overlap.CreateView(oInfo, sizeInfo, range.Value, firstLayer, firstLevel);

                    if (overlap.IsModified)
                    {
                        texture.SignalModified();
                    }

                    ChangeSizeIfNeeded(info, texture, isSamplerTexture, sizeHint);

                    break;
                }
                else if (overlapCompatibility == TextureViewCompatibility.CopyOnly)
                {
                    // TODO: Copy rules for targets created after the container texture. See below.
                    overlap.DisableMemoryTracking();
                }
            }

            // No match, create a new texture.
            if (texture == null)
            {
                texture = new Texture(_context, info, sizeInfo, range.Value, scaleMode);

                // Step 1: Find textures that are view compatible with the new texture.
                // Any textures that are incompatible will contain garbage data, so they should be removed where possible.

                int  viewCompatible = 0;
                bool setData        = isSamplerTexture || overlapsCount == 0 || flags.HasFlag(TextureSearchFlags.ForCopy);

                for (int index = 0; index < overlapsCount; index++)
                {
                    Texture overlap        = _textureOverlaps[index];
                    bool    overlapInCache = overlap.CacheNode != null;

                    TextureViewCompatibility compatibility = texture.IsViewCompatible(overlap.Info, overlap.Range, out int firstLayer, out int firstLevel);

                    if (compatibility != TextureViewCompatibility.Incompatible)
                    {
                        if (_overlapInfo.Length != _textureOverlaps.Length)
                        {
                            Array.Resize(ref _overlapInfo, _textureOverlaps.Length);
                        }

                        _overlapInfo[viewCompatible]       = new OverlapInfo(compatibility, firstLayer, firstLevel);
                        _textureOverlaps[viewCompatible++] = overlap;
                    }
                    else if (overlapInCache || !setData)
                    {
                        if (info.GobBlocksInZ > 1 && info.GobBlocksInZ == overlap.Info.GobBlocksInZ)
                        {
                            // Allow overlapping slices of 3D textures. Could be improved in future by making sure the textures don't overlap.
                            continue;
                        }

                        // The overlap texture is going to contain garbage data after we draw, or is generally incompatible.
                        // If the texture cannot be entirely contained in the new address space, and one of its view children is compatible with us,
                        // it must be flushed before removal, so that the data is not lost.

                        // If the texture was modified since its last use, then that data is probably meant to go into this texture.
                        // If the data has been modified by the CPU, then it also shouldn't be flushed.
                        bool modified = overlap.ConsumeModified();

                        bool flush = overlapInCache && !modified && !texture.Range.Contains(overlap.Range) && overlap.HasViewCompatibleChild(texture);

                        setData |= modified || flush;

                        if (overlapInCache)
                        {
                            _cache.Remove(overlap, flush);
                        }
                    }
                }

                // We need to synchronize before copying the old view data to the texture,
                // otherwise the copied data would be overwritten by a future synchronization.
                texture.InitializeData(false, setData);

                for (int index = 0; index < viewCompatible; index++)
                {
                    Texture     overlap = _textureOverlaps[index];
                    OverlapInfo oInfo   = _overlapInfo[index];

                    if (oInfo.Compatibility != TextureViewCompatibility.Full)
                    {
                        continue; // Copy only compatibilty.
                    }

                    TextureInfo overlapInfo = AdjustSizes(texture, overlap.Info, oInfo.FirstLevel);

                    TextureCreateInfo createInfo = GetCreateInfo(overlapInfo, _context.Capabilities, overlap.ScaleFactor);

                    if (texture.ScaleFactor != overlap.ScaleFactor)
                    {
                        // A bit tricky, our new texture may need to contain an existing texture that is upscaled, but isn't itself.
                        // In that case, we prefer the higher scale only if our format is render-target-like, otherwise we scale the view down before copy.

                        texture.PropagateScale(overlap);
                    }

                    ITexture newView = texture.HostTexture.CreateView(createInfo, oInfo.FirstLayer, oInfo.FirstLevel);

                    overlap.HostTexture.CopyTo(newView, 0, 0);

                    // Inherit modification from overlapping texture, do that before replacing
                    // the view since the replacement operation removes it from the list.
                    if (overlap.IsModified)
                    {
                        texture.SignalModified();
                    }

                    overlap.ReplaceView(texture, overlapInfo, newView, oInfo.FirstLayer, oInfo.FirstLevel);
                }

                // If the texture is a 3D texture, we need to additionally copy any slice
                // of the 3D texture to the newly created 3D texture.
                if (info.Target == Target.Texture3D && viewCompatible > 0)
                {
                    // TODO: This copy can currently only happen when the 3D texture is created.
                    // If a game clears and redraws the slices, we won't be able to copy the new data to the 3D texture.
                    // Disable tracking to try keep at least the original data in there for as long as possible.
                    texture.DisableMemoryTracking();

                    for (int index = 0; index < viewCompatible; index++)
                    {
                        Texture     overlap = _textureOverlaps[index];
                        OverlapInfo oInfo   = _overlapInfo[index];

                        if (oInfo.Compatibility != TextureViewCompatibility.Incompatible)
                        {
                            overlap.BlacklistScale();

                            overlap.HostTexture.CopyTo(texture.HostTexture, oInfo.FirstLayer, oInfo.FirstLevel);

                            if (overlap.IsModified)
                            {
                                texture.SignalModified();
                            }
                        }
                    }
                }
            }

            // Sampler textures are managed by the texture pool, all other textures
            // are managed by the auto delete cache.
            if (!isSamplerTexture)
            {
                _cache.Add(texture);
            }

            lock (_textures)
            {
                _textures.Add(texture);
            }

            ShrinkOverlapsBufferIfNeeded();

            return(texture);
        }