Esempio n. 1
0
        /// <summary>
        /// Compute the max size of a power of two atlas for a given size in byte (weight).
        /// </summary>
        /// <param name="weight">Atlas size in bytes.</param>
        /// <param name="hasMipmap">Atlas uses mip maps.</param>
        /// <param name="format">Atlas format.</param>
        /// <returns></returns>
        public static int GetMaxCacheSizeForWeightInByte(int weight, bool hasMipmap, GraphicsFormat format)
        {
            float bytePerPixel       = (float)GraphicsFormatUtility.GetBlockSize(format) * (hasMipmap ? k_MipmapFactorApprox : 1.0f);
            var   maxAtlasSquareSize = Mathf.Sqrt((float)weight / bytePerPixel);

            return(CoreUtils.PreviousPowerOfTwo((int)maxAtlasSquareSize));
        }
Esempio n. 2
0
 public CustomRenderTexture(int width, int height, GraphicsFormat format)
 {
     Internal_CreateCustomRenderTexture(this, GraphicsFormatUtility.IsSRGBFormat(format) ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear);
     this.width  = width;
     this.height = height;
     this.format = GraphicsFormatUtility.GetRenderTextureFormat(format);
 }
        private void SetupReflectionTexture(Camera camera)
        {
            if (!camera)
            {
                return;
            }

            float scaleRatio = UnityEngine.Rendering.Universal.UniversalRenderPipeline.asset.renderScale * GetScaleValue();

            int width  = (int)(camera.pixelWidth * scaleRatio);
            int height = (int)(camera.pixelHeight * scaleRatio);

            if (m_reflectionRT)
            {
                if ((m_reflectionRT.width == width) && (m_reflectionRT.height == height))
                {
                    return;
                }
                else
                {
                    RenderTexture.ReleaseTemporary(m_reflectionRT);
                    m_reflectionRT = null;
                }
            }
            const bool useHdr10 = true;
            const RenderTextureFormat hdrFormat = useHdr10 ? RenderTextureFormat.RGB111110Float : RenderTextureFormat.DefaultHDR;

            //m_reflectionRT = RenderTexture.GetTemporary(width, height, 16, RenderTextureFormat.ARGB32);
            m_reflectionRT = RenderTexture.GetTemporary(width, height, 16, GraphicsFormatUtility.GetGraphicsFormat(hdrFormat, true));
        }
Esempio n. 4
0
        internal bool ValidateFormat(TextureFormat format)
        {
            bool flag = SystemInfo.SupportsTextureFormat(format);
            bool result;

            if (flag)
            {
                result = true;
            }
            else
            {
                bool flag2 = GraphicsFormatUtility.IsCompressedTextureFormat(format);
                if (flag2)
                {
                    Debug.LogWarning(string.Format("'{0}' is not supported on this platform. Decompressing texture. Use 'SystemInfo.SupportsTextureFormat' C# API to check format support.", format.ToString()), this);
                    result = true;
                }
                else
                {
                    Debug.LogError(string.Format("Texture creation failed. '{0}' is not supported on this platform. Use 'SystemInfo.SupportsTextureFormat' C# API to check format support.", format.ToString()), this);
                    result = false;
                }
            }
            return(result);
        }
Esempio n. 5
0
        /// <summary>
        /// Perform async read back from the provided source texture.
        /// </summary>
        /// <param name="src">Texture source to be used for the read back.</param>
        /// <param name="mipIndex">Index of the mipmap to be fetched.</param>
        /// <param name="dstFormat">Target TextureFormat of the data. If the target format is different from the format stored on the GPU, the conversion is automatic.</param>
        /// <param name="functor">Functor that will be invoked after the async read back request is complete.</param>
        /// <typeparam name="T">Type for the destination data buffer.</typeparam>
        /// <returns>Returns an AsynRequest</returns>
        public static AsyncRequest <object> Capture <T>(Texture src, int mipIndex, GraphicsFormat dstFormat, Func <AsyncRequest <object>, AsyncRequest <object> .Result> functor = null) where T : struct
        {
            var req = Manager.Instance.CreateRequest <AsyncRequest <object> >();

            if (GraphicsUtilities.SupportsAsyncReadback())
            {
                AsyncGPUReadback.Request(src, mipIndex, GraphicsFormatUtility.GetTextureFormat(dstFormat), (AsyncGPUReadbackRequest request) =>
                {
                    req.error = request.hasError;
                    if (!request.hasError)
                    {
                        req.data = request.GetData <T>().ToArray();
                        req.Enqueue(functor);
                        req.Execute();
                    }
                });
            }
            else
            {
                req.data = GraphicsUtilities.GetPixelsSlow(src as RenderTexture);
                req.Enqueue(functor);
                req.Execute();
            }

            return(req);
        }
Esempio n. 6
0
 public SparseTexture(int width, int height, GraphicsFormat format, int mipCount)
 {
     if (ValidateFormat(format, FormatUsage.Sample))
     {
         Internal_Create(this, width, height, GraphicsFormatUtility.GetTextureFormat(format), GraphicsFormatUtility.IsSRGBFormat(format), mipCount);
     }
 }
Esempio n. 7
0
        public override void OnPreviewSettings()
        {
            // Do not allow changing of pages when multiple atlases is selected.
            if (targets.Length == 1 && m_OptionDisplays != null && m_OptionValues != null && m_TotalPages > 1)
            {
                m_PreviewPage = EditorGUILayout.IntPopup(m_PreviewPage, m_OptionDisplays, m_OptionValues, styles.preDropDown, GUILayout.MaxWidth(50));
            }
            else
            {
                m_PreviewPage = 0;
            }

            if (m_PreviewTextures != null)
            {
                m_PreviewPage = Mathf.Min(m_PreviewPage, m_PreviewTextures.Length - 1);

                Texture2D t = m_PreviewTextures[m_PreviewPage];

                if (GraphicsFormatUtility.HasAlphaChannel(t.format) || (m_PreviewAlphaTextures != null && m_PreviewAlphaTextures.Length > 0))
                {
                    m_ShowAlpha = GUILayout.Toggle(m_ShowAlpha, m_ShowAlpha ? styles.alphaIcon : styles.RGBIcon, styles.previewButton);
                }

                int mipCount = Mathf.Max(1, TextureUtil.GetMipmapCount(t));
                if (mipCount > 1)
                {
                    GUILayout.Box(styles.smallZoom, styles.previewLabel);
                    m_MipLevel = Mathf.Round(GUILayout.HorizontalSlider(m_MipLevel, mipCount - 1, 0, styles.previewSlider, styles.previewSliderThumb, GUILayout.MaxWidth(64)));
                    GUILayout.Box(styles.largeZoom, styles.previewLabel);
                }
            }
        }
Esempio n. 8
0
        override public string GetInfoString()
        {
            RenderTexture t = target as RenderTexture;

            string info = t.width + "x" + t.height;

            if (t.dimension == UnityEngine.Rendering.TextureDimension.Tex3D)
            {
                info += "x" + t.volumeDepth;
            }

            if (!t.isPowerOfTwo)
            {
                info += "(NPOT)";
            }

            if (QualitySettings.desiredColorSpace == ColorSpace.Linear)
            {
                bool formatIsHDR = GraphicsFormatUtility.IsIEEE754Format(t.graphicsFormat);
                bool sRGB        = t.sRGB && !formatIsHDR;
                info += " " + (sRGB ? "sRGB" : "Linear");
            }

            info += "  " + t.graphicsFormat;
            info += "  " + EditorUtility.FormatBytes(TextureUtil.GetRuntimeMemorySizeLong(t));

            return(info);
        }
Esempio n. 9
0
        internal void SaveCurrentViewToImage()
        {
            // Temp texture for the readback (before compression)
            Texture2D tmp = new Texture2D(savedTexture.width, savedTexture.height, GraphicsFormat.R32G32B32A32_SFloat, TextureCreationFlags.None);

            // Radback color & depth:
            RenderTexture.active = tmpRenderTexture;
            tmp.filterMode       = settings.GetResolvedFilterMode(graph);
            tmp.wrapMode         = settings.GetResolvedWrapMode(graph);
            tmp.ReadPixels(new Rect(0, 0, savedTexture.width, savedTexture.height), 0, 0);
            RenderTexture.active = null;
            tmp.Apply();

#if UNITY_EDITOR
            if (GraphicsFormatUtility.IsCompressedFormat(savedTexture.graphicsFormat))
            {
                EditorUtility.CompressTexture(tmp, compressionFormat, TextureCompressionQuality.Best);
                EditorUtility.CopySerialized(tmp, savedTexture);
                Object.DestroyImmediate(tmp);
            }
            else
            {
                savedTexture.SetPixels(tmp.GetPixels());
                savedTexture.Apply();
            }
#endif

            graph.NotifyNodeChanged(this);

            if (!graph.IsObjectInGraph(savedTexture))
            {
                graph.AddObjectToGraph(savedTexture);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Validates the lookup texture assigned to the volume component.
        /// </summary>
        /// <returns>True if the texture is valid, false otherwise.</returns>
        public bool ValidateLUT()
        {
            var asset = UniversalRenderPipeline.asset;

            if (asset == null || texture.value == null)
            {
                return(false);
            }

            int lutSize = asset.colorGradingLutSize;

            if (texture.value.height != lutSize)
            {
                return(false);
            }

            bool valid = false;

            switch (texture.value)
            {
            case Texture2D t:
                valid |= t.width == lutSize * lutSize &&
                         !GraphicsFormatUtility.IsSRGBFormat(t.graphicsFormat);
                break;

            case RenderTexture rt:
                valid |= rt.dimension == TextureDimension.Tex2D &&
                         rt.width == lutSize * lutSize &&
                         !rt.sRGB;
                break;
            }

            return(valid);
        }
                public void CopyPixelDataToLayer <T>(NativeArray <T> colorData, int layerIdx, GraphicsFormat format) where T : struct
                {
                    var layer = GetLayer(layerIdx);

                    NativeArray <T>    dstDataAsColor;
                    AtomicSafetyHandle safety = AtomicSafetyHandle.Create();

                    unsafe
                    {
                        dstDataAsColor = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray <T>(layer.data, layer.dataSize, Allocator.None);
                        NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref dstDataAsColor, safety);
                    }

                    var dstWidth  = layer.scanlineSize / UnsafeUtility.SizeOf <T>();
                    int scanLines = height / (int)GraphicsFormatUtility.GetBlockHeight(format);
                    int pitch     = (width * (int)GraphicsFormatUtility.GetBlockSize(format)) / ((int)GraphicsFormatUtility.GetBlockWidth(format) * UnsafeUtility.SizeOf <T>());

                    if (scanLines * pitch > colorData.Length)
                    {
                        throw new ArgumentException($"Could not copy from ColorData in layer {layer}, {format}. The Provided source array is smaller than the tile content.");
                    }

                    if ((scanLines - 1) * dstWidth + pitch > dstDataAsColor.Length)
                    {
                        throw new ArgumentException($"Trying to write outside of the layer {layer} data buffer bounds. Is the provided format {format} correct?");
                    }

                    for (int i = 0; i < scanLines; ++i)
                    {
                        NativeArray <T> .Copy(colorData, i *pitch, dstDataAsColor, i *dstWidth, pitch);
                    }
                    dstDataAsColor.Dispose();
                    AtomicSafetyHandle.Release(safety);
                }
    void OnCompleteReadback(AsyncGPUReadbackRequest request)
    {
        if (request.hasError)
        {
            Debug.LogError("GPU readback error detected");
            return;
        }

        // This happens when the delayed async readback happens as we're exiting play mode
        if (instance == null || visibilityMaskTexture == null)
        {
            return;
        }

        // Read the color of the visibility mask texture to determine which visibility masks are active on cursor
        Texture2D visibilityMaskTex = new Texture2D(
            1,
            1,
            GraphicsFormatUtility.GetTextureFormat(visibilityMaskTexture.graphicsFormat),
            false
            );

        visibilityMaskTex.LoadRawTextureData(request.GetData <Color32>());
        visibilityMaskTex.Apply();

        // Only one pixel so we can sample at 0, 0
        Color sample = visibilityMaskTex.GetPixel(0, 0);

        visibilityMaskValue = DimensionShaderUtils.MaskValueFromSample(sample.linear);
    }
Esempio n. 13
0
        internal static int PrepareVolumePreview(Material material, Texture texture, Vector3 scale, float opacity,
                                                 FilterMode filterMode, bool colorRamp, Gradient customColorRamp, Camera camera, Matrix4x4 trs, float qualityModifier = 2)
        {
            float   inverseResolution;
            Vector3 inverseScale;

            PrepareGeneralPreview(material, texture, out inverseScale, out inverseResolution, customColorRamp);
            uint colorChannelCount = GraphicsFormatUtility.GetColorComponentCount(texture.graphicsFormat);

            material.SetVector(MaterialProps.globalScale, scale);
            material.SetFloat(MaterialProps.ramp, Convert.ToSingle(colorRamp));
            material.SetFloat(MaterialProps.invResolution, inverseResolution);
            material.SetVector(MaterialProps.invChannels, new Vector3(1.0f / colorChannelCount, 1.0f / colorChannelCount, 1.0f / colorChannelCount));
            material.SetFloat(MaterialProps.alpha, Mathf.Pow(Mathf.Clamp01(opacity), 3));
            material.SetFloat(MaterialProps.filterMode, Convert.ToSingle(filterMode));

            float quality = inverseResolution / qualityModifier / 2;

            material.SetFloat(MaterialProps.quality, quality);

            material.SetMatrix("_CamToW", camera.cameraToWorldMatrix);
            material.SetMatrix("_WToCam", camera.worldToCameraMatrix);
            material.SetMatrix("_ObjToW", trs);
            material.SetMatrix("_WToObj", trs.inverse);

            return(Convert.ToInt32(1 / inverseResolution * qualityModifier * 2));
        }
        public static bool CompareFormat(this RenderTexture rt, GraphicsFormat format)
        {
#if UNITY_2019_3_OR_NEWER
            return(rt.graphicsFormat == format);
#else
            return(rt.format == GraphicsFormatUtility.GetRenderTextureFormat(format));
#endif
        }
Esempio n. 15
0
 static public bool TextureHasAlpha(Texture2D inTex)
 {
     if (inTex != null)
     {
         return(GraphicsFormatUtility.HasAlphaChannel(GraphicsFormatUtility.GetGraphicsFormat(inTex.format, true)));
     }
     return(false);
 }
        private bool RenderTextureHasDepth()
        {
            if (GraphicsFormatUtility.IsDepthFormat((GraphicsFormat)m_ColorFormat.enumValueIndex))
            {
                return(true);
            }

            return(m_DepthFormat.enumValueIndex != 0);
        }
Esempio n. 17
0
 internal bool ValidateSize(int width, int height, GraphicsFormat format)
 {
     if (GraphicsFormatUtility.GetBlockSize(format) * (width / GraphicsFormatUtility.GetBlockWidth(format)) * (height / GraphicsFormatUtility.GetBlockHeight(format)) < 65536)
     {
         Debug.LogError(String.Format("SparseTexture creation failed. The minimum size in bytes of a SparseTexture is 64KB."), this);
         return(false);
     }
     return(true);
 }
Esempio n. 18
0
        private static void ValidateIsNotCrunched(TextureFormat textureFormat)
        {
            bool flag = GraphicsFormatUtility.IsCrunchFormat(textureFormat);

            if (flag)
            {
                throw new ArgumentException("Crunched SparseTexture is not supported.");
            }
        }
 static void SetupAlternateGetBlockSize()
 {
     _blockSizeMap = new Dictionary <GraphicsFormat, int>();
     foreach (GraphicsFormat format in Enum.GetValues(typeof(GraphicsFormat)))
     {
         _blockSizeMap[format]      = (int)GraphicsFormatUtility.GetBlockSize(format);
         _componentCountMap[format] = (int)GraphicsFormatUtility.GetComponentCount(format);
     }
 }
Esempio n. 20
0
        public override string GetInfoString()
        {
            Texture        t      = target as Texture;
            string         info   = t.width + "x" + t.height;
            GraphicsFormat format = GraphicsFormatUtility.GetFormat(t);

            info += "  " + GraphicsFormatUtility.GetFormatString(format);
            return(info);
        }
 static bool IsRenderTextureFormatSupportedForLinearFiltering(RenderTextureFormat format)
 {
         #if UNITY_2019_1_OR_NEWER
     GraphicsFormat graphicFormat = GraphicsFormatUtility.GetGraphicsFormat(format, RenderTextureReadWrite.Linear);
     return(SystemInfo.IsFormatSupported(graphicFormat, FormatUsage.Linear));
         #else
     return(format.IsSupported());
         #endif
 }
        internal static void ValidateFormat(Texture src, GraphicsFormat dstformat)
        {
            GraphicsFormat srcformat = GraphicsFormatUtility.GetFormat(src);

            if (!SystemInfo.IsFormatSupported(srcformat, FormatUsage.ReadPixels))
            {
                Debug.LogError(String.Format("'{0}' doesn't support ReadPixels usage on this platform. Async GPU readback failed.", srcformat));
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Specifies whether the Texture has an alpha channel or not. Returns true if it does and false otherwise.
        /// </summary>
        /// <param name="tex">The Texture for this function to check.</param>
        /// <returns></returns>
        public static bool TextureHasAlpha(Texture2D tex)
        {
            if (tex == null)
            {
                return(false);
            }

            return(GraphicsFormatUtility.HasAlphaChannel(tex.graphicsFormat));
        }
Esempio n. 24
0
        static bool IsRenderTextureFormatSupportedForLinearFiltering(RenderTextureFormat format)
        {
#if UNITY_2019_1_OR_NEWER
            var gFormat = GraphicsFormatUtility.GetGraphicsFormat(format, RenderTextureReadWrite.Linear);
            return(SystemInfo.IsFormatSupported(gFormat, FormatUsage.Linear));
#else
            // No good/fast way to test it on pre-2019.1
            return(format.IsSupported());
#endif
        }
Esempio n. 25
0
 private static string[] BuildTextureStrings(int[] texFormatValues)
 {
     string[] retval = new string[texFormatValues.Length];
     for (int i = 0; i < texFormatValues.Length; i++)
     {
         int val = texFormatValues[i];
         retval[i] = (val < 0 ? "Automatic" : GraphicsFormatUtility.GetFormatString((TextureFormat)val));
     }
     return(retval);
 }
Esempio n. 26
0
        private bool RenderTextureHasDepth()
        {
            if (((GraphicsFormat)m_ColorFormat.enumValueIndex == GraphicsFormat.None) ||
                GraphicsFormatUtility.IsDepthFormat((GraphicsFormat)m_ColorFormat.enumValueIndex)) /* This should be removed if ShadowAuto and DepthAuto formats are finally removed (they are currently deprecated already)*/
            {
                return(true);
            }

            return(m_DepthStencilFormat.enumValueIndex != 0);
        }
Esempio n. 27
0
        public static Rect[] PackTexture(out Texture2D atlas_, Texture2D[] texture_, int size_, int padding_)
        {
            //TODO test on device
            var format = texture_[0].graphicsFormat;

            if (!SystemInfo.IsFormatSupported(format, FormatUsage.Sample))
            {
                Log.Warning($"unsupported format {format}");
                atlas_ = new Texture2D(1, 1);
                return(atlas_.PackTextures(texture_, padding_, size_));
            }
            var rect     = new System.Collections.Generic.List <Rect>(texture_.Length);
            var texArray = texture_.Select(t => new Vector2(t.width, t.height)).ToArray();

            if (!Texture2D.GenerateAtlas(texArray, padding_, size_, rect))
            {
                Log.Error("failed to pack textures");
                atlas_ = null;
                return(null);
            }
            atlas_ = new Texture2D(size_, size_, format, TextureCreationFlags.None);
            //etc2+eac 8bpp 4x4 = 128bits
            //dxt5/bc3 8bpp 4x4 = 128bits
            //pvrtc 4bpp: 4x4 = 64bits 2bpp: 8x4=64bits
            //astc fixed 128bits
            var blockSize   = GraphicsFormatUtility.GetBlockSize(format);
            var blockWidth  = (int)GraphicsFormatUtility.GetBlockWidth(format);
            var blockHeight = (int)GraphicsFormatUtility.GetBlockHeight(format);

            if (blockSize == 16)
            {
                CopyTextureRawData <Block128Bit>(atlas_, texture_, rect, blockWidth, blockHeight);
            }
            else if (blockSize == 8)
            {
                CopyTextureRawData <UInt64>(atlas_, texture_, rect, blockWidth, blockHeight);
            }
            else if (blockSize == 4)
            {
                CopyTextureRawData <UInt32>(atlas_, texture_, rect, blockWidth, blockHeight);
            }
            else
            {
                Log.Warning($"unsupported block size {blockSize} byte");
            }
            atlas_.Apply(false, true);
            float sizeInv = 1f / size_;

            for (int k = 0; k < rect.Count; ++k)
            {
                var r = rect[k];
                rect[k] = new Rect(r.x * sizeInv, r.y * sizeInv, r.width * sizeInv, r.height * sizeInv);
            }
            return(rect.ToArray());
        }
Esempio n. 28
0
        public override string GetInfoString()
        {
            if (m_PreviewTextures != null && m_PreviewPage < m_PreviewTextures.Length)
            {
                Texture2D      t      = m_PreviewTextures[m_PreviewPage];
                GraphicsFormat format = GraphicsFormatUtility.GetFormat(t);

                return(string.Format("{0}x{1} {2}\n{3}", t.width, t.height, GraphicsFormatUtility.GetFormatString(format), EditorUtility.FormatBytes(TextureUtil.GetStorageMemorySizeLong(t))));
            }
            return("");
        }
Esempio n. 29
0
        public RenderTexture(int width, int height, int depth, GraphicsFormat format)
        {
            if (!ValidateFormat(format, FormatUsage.Render))
            {
                return;
            }

            Internal_Create(this);
            this.width = width; this.height = height; this.depth = depth; this.graphicsFormat = format;

            SetSRGBReadWrite(GraphicsFormatUtility.IsSRGBFormat(format));
        }
Esempio n. 30
0
 private void PlanarReflectionTexture(Camera cam)
 {
     if (_reflectionTexture == null)
     {
         var        res      = ReflectionResolution(cam, UniversalRenderPipeline.asset.renderScale);
         const bool useHdr10 = true;
         const RenderTextureFormat hdrFormat = useHdr10 ? RenderTextureFormat.RGB111110Float : RenderTextureFormat.DefaultHDR;
         _reflectionTexture = RenderTexture.GetTemporary(res.x, res.y, 16,
                                                         GraphicsFormatUtility.GetGraphicsFormat(hdrFormat, true));
     }
     _reflectionCamera.targetTexture = _reflectionTexture;
 }