Exemplo n.º 1
0
    // Start is called before the first frame update
    void Start()
    {
        Texture2D t = terrain.ToTexture2D(true);

        byte[] bytes = ImageConversion.EncodeToEXR(t, Texture2D.EXRFlags.OutputAsFloat);
        System.IO.File.WriteAllBytes(path, bytes);
    }
        static void ExportToEXR(string path, Texture2D tex, Texture2D.EXRFlags flags)
        {
#if UNITY_2018_1_OR_NEWER
            System.IO.File.WriteAllBytes(path, ImageConversion.EncodeToEXR(tex, flags));
#else
            System.IO.File.WriteAllBytes(path, tex.EncodeToEXR(flags));
#endif
        }
Exemplo n.º 3
0
        public void Render()
        {
            Lock();

            if (!Directory.Exists(Utils.designFilesDirectory.ToAbsolute()))
            {
                Directory.CreateDirectory(Utils.designFilesDirectory.ToAbsolute());
            }
            if (!Directory.Exists(designFilesDirectory.ToAbsolute()))
            {
                Directory.CreateDirectory(designFilesDirectory.ToAbsolute());
            }

            var     rectTransform = GetComponent <RectTransform>();
            Vector2 size          = rectTransform.sizeDelta * cubemapSize;
            var     renderTexture = new RenderTexture(
                Mathf.RoundToInt(size.x),
                Mathf.RoundToInt(size.y), 24, GraphicsFormat.R32G32B32A32_SFloat, 0);
            var camera = GetComponentInChildren <Camera>();

            camera.targetTexture = renderTexture;
            camera.allowHDR      = true;
            //TierSettings.hdr = true;
            camera.Render();
            camera.targetTexture = null;
            RenderTexture.active = renderTexture;
            Texture2D texture = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGBAFloat, false);

            texture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
            RenderTexture.active = null;

            /*PhotoshopFile.PsdFile output = new PhotoshopFile.PsdFile(PhotoshopFile.PsdFileVersion.Psd);
             * output.RowCount = renderTexture.height;
             * output.ColumnCount = renderTexture.width;
             * output.ChannelCount = 4;
             * output.ColorMode = PhotoshopFile.PsdColorMode.RGB;
             * output.BitDepth = 32;
             * output.ImageCompression = PhotoshopFile.ImageCompression.Raw;
             *
             *
             * output.Resolution = new PhotoshopFile.ResolutionInfo();
             * var layer = new PhotoshopFile.Layer(output);
             * layer.CreateMissingChannels();
             * output.Layers.Add(layer);
             *
             * output.PrepareSave();
             * output.Save(Path.Combine(resourceDirectory.ToAbsolute(), $"{name}.psd"),System.Text.Encoding.UTF8);*/

            var bytes      = ImageConversion.EncodeToEXR(texture, Texture2D.EXRFlags.OutputAsFloat);
            var outputPath = exrFilePath.ToAbsolute();

            File.WriteAllBytes(outputPath, bytes);

            AssetDatabase.Refresh();
            //Debug.Log(rectTransform.sizeDelta * cubemapSize);
        }
Exemplo n.º 4
0
        ///// <summary>
        ///// Outputs a Render texture as a .png file
        ///// </summary>
        ///// <param name="path">The path to write to, including filename ending in .exr</param>
        ///// <param name="sourceRenderTexture">The render texture to export</param>
        //public static void WriteRenderTexturePNG(string path, RenderTexture sourceRenderTexture, TextureFormat textureFormat = TextureFormat.RGBA32)
        //{
        //    RenderTexture origTex = RenderTexture.active;
        //    RenderTexture.active = sourceRenderTexture;
        //    Texture2D exportTexture = new Texture2D(RenderTexture.active.width, RenderTexture.active.height, textureFormat, false);
        //    exportTexture.ReadPixels(new Rect(0, 0, RenderTexture.active.width, RenderTexture.active.height), 0, 0);
        //    exportTexture.Apply();
        //    byte[] exrBytes = ImageConversion.EncodeToPNG(exportTexture);
        //    PWCommon4.Utils.WriteAllBytes(path, exrBytes);
        //    RenderTexture.active = origTex;
        //}


        /// <summary>
        /// Outputs a Render texture to different file formats (default: .exr file)
        /// </summary>
        /// <param name="path">The path to write to, without the extension. The correct extension will be added according to the chosen imageFileType.</param>
        /// <param name="sourceRenderTexture">The render texture to export</param>
        /// <param name="imageFileType">Image File Type: EXR, PNG, TGA or JPG</param>
        /// <param name="textureFormat">Texture color format for the temporary Texture 2D to read the render texture into for exporting.</param>
        /// <returns>The full path to the exported file.</returns>
        public static string WriteRenderTexture(string path, RenderTexture sourceRenderTexture, GaiaConstants.ImageFileType imageFileType = GaiaConstants.ImageFileType.Exr, TextureFormat textureFormat = TextureFormat.RGBAFloat, int jpgQuality = 75)
        {
            RenderTexture origTex = RenderTexture.active;

            RenderTexture.active = sourceRenderTexture;
            Texture2D exportTexture = new Texture2D(RenderTexture.active.width, RenderTexture.active.height, textureFormat, false);

            exportTexture.ReadPixels(new Rect(0, 0, RenderTexture.active.width, RenderTexture.active.height), 0, 0);
            exportTexture.Apply();
            byte[] fileBytes = new byte[0];
            string extension = ".file";

            switch (imageFileType)
            {
            case GaiaConstants.ImageFileType.Exr:
                fileBytes = ImageConversion.EncodeToEXR(exportTexture, Texture2D.EXRFlags.CompressZIP);
                extension = ".exr";
                break;

            case GaiaConstants.ImageFileType.Png:
                fileBytes = ImageConversion.EncodeToPNG(exportTexture);
                extension = ".png";
                break;

            case GaiaConstants.ImageFileType.Tga:
                fileBytes = ImageConversion.EncodeToTGA(exportTexture);
                extension = ".tga";
                break;

            case GaiaConstants.ImageFileType.Jpg:
                fileBytes = ImageConversion.EncodeToJPG(exportTexture, jpgQuality);
                extension = ".jpg";
                break;
            }
            path += extension;
            PWCommon4.Utils.WriteAllBytes(path, fileBytes);
            RenderTexture.active = origTex;
            return(path);
        }
        private static void CreateAnimationTexture(SkinnedMeshRenderer smr, BoneColorLookup bcl, AnimationClip ac, int texSize, float refScale, string outputPath)
        {
            Debug.Log($"Creating animation texture for mesh-renderer: {smr.name}");

            Texture2D texture = new Texture2D(texSize, texSize, TextureFormat.RGBAFloat, mipChain: false, linear: true);

            for (int boneIndex = 0; boneIndex < smr.bones.Length; boneIndex++)
            {
                int startY = boneIndex * 2; //because 2 elements per bone: color and (position, scale)
                for (int x = 0; x < texSize; x++)
                {
                    float prog = x == 0 ? 0 : ((float)x / (texSize - 1));

                    //Get color
                    Color color = bcl == null ? Color.white : bcl.GetColor(smr.bones[boneIndex].name, prog);

                    //Get position
                    ac.SampleAnimation(smr.transform.root.gameObject, prog * ac.length);
                    Vector3 position = smr.bones[boneIndex].localPosition;

                    //Get scale
                    float boneScale     = GetUniformLocalScale(smr.bones[boneIndex]) / refScale;
                    float bindposeScale = GetUniformScale(smr.sharedMesh.bindposes[boneIndex].lossyScale);
                    float scale         = boneScale * bindposeScale;

                    //Save the data in the texture
                    texture.SetPixel(x, startY, color);
                    texture.SetPixel(x, startY + 1, new Color(position.x, position.y, position.z, scale));
                }
            }
            texture.Apply(updateMipmaps: false, makeNoLongerReadable: false);

            byte[] exrData = ImageConversion.EncodeToEXR(texture, Texture2D.EXRFlags.OutputAsFloat);
            File.WriteAllBytes($"{Application.dataPath}/{outputPath}", exrData);
            AssetDatabase.Refresh();
        }
 public static byte[] ByteArray(Texture2D texture, PictureExtension extension)
 {
     if (extension == PictureExtension.EXR)
     {
         return(ImageConversion.EncodeToEXR(texture));
     }
     else if (extension == PictureExtension.JPG)
     {
         return(ImageConversion.EncodeToJPG(texture));
     }
     else if (extension == PictureExtension.PNG)
     {
         return(ImageConversion.EncodeToPNG(texture));
     }
     else if (extension == PictureExtension.TGA)
     {
         return(ImageConversion.EncodeToTGA(texture));
     }
     else
     {
         Debug.LogError("Not possible to encode 'Texture2D' to byte array ... ");
         return(null);
     }
 }
Exemplo n.º 7
0
    public Texture2D Combine(string savePath)
    {
        int xMin = int.MaxValue;
        int yMin = int.MaxValue;

        if (m_rSource.width > 4 && m_rSource.width < xMin)
        {
            xMin = m_rSource.width;
        }
        if (m_gSource.width > 4 && m_gSource.width < xMin)
        {
            xMin = m_gSource.width;
        }
        if (m_bSource.width > 4 && m_bSource.width < xMin)
        {
            xMin = m_bSource.width;
        }
        if (m_aSource.width > 4 && m_aSource.width < xMin)
        {
            xMin = m_aSource.width;
        }
        if (xMin == int.MaxValue)
        {
            xMin = 4;
        }

        if (m_rSource.height > 4 && m_rSource.height < yMin)
        {
            yMin = m_rSource.height;
        }
        if (m_gSource.height > 4 && m_gSource.height < yMin)
        {
            yMin = m_gSource.height;
        }
        if (m_bSource.height > 4 && m_bSource.height < yMin)
        {
            yMin = m_bSource.height;
        }
        if (m_aSource.height > 4 && m_aSource.height < yMin)
        {
            yMin = m_aSource.height;
        }
        if (yMin == int.MaxValue)
        {
            yMin = 4;
        }

        Texture2D combined = new Texture2D(xMin, yMin, TextureFormat.RGBAFloat, true, true);

        combined.hideFlags = HideFlags.DontUnloadUnusedAsset;

        Material combinerMaterial = new Material(Shader.Find("Hidden/SRP_Core/TextureCombiner"));

        combinerMaterial.hideFlags = HideFlags.DontUnloadUnusedAsset;

        combinerMaterial.SetTexture("_RSource", GetRawTexture(m_rSource));
        combinerMaterial.SetTexture("_GSource", GetRawTexture(m_gSource));
        combinerMaterial.SetTexture("_BSource", GetRawTexture(m_bSource));
        combinerMaterial.SetTexture("_ASource", GetRawTexture(m_aSource));

        combinerMaterial.SetFloat("_RChannel", m_rChanel);
        combinerMaterial.SetFloat("_GChannel", m_gChanel);
        combinerMaterial.SetFloat("_BChannel", m_bChanel);
        combinerMaterial.SetFloat("_AChannel", m_aChanel);

        combinerMaterial.SetVector("_RRemap", m_remapings[0]);
        combinerMaterial.SetVector("_GRemap", m_remapings[1]);
        combinerMaterial.SetVector("_BRemap", m_remapings[2]);
        combinerMaterial.SetVector("_ARemap", m_remapings[3]);

        RenderTexture combinedRT = new RenderTexture(xMin, yMin, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.sRGB);

        Graphics.Blit(Texture2D.whiteTexture, combinedRT, combinerMaterial);

        // Readback the render texture
        RenderTexture previousActive = RenderTexture.active;

        RenderTexture.active = combinedRT;
        combined.ReadPixels(new Rect(0, 0, xMin, yMin), 0, 0, false);
        combined.Apply();
        RenderTexture.active = previousActive;

        byte[] bytes = new byte[0];

        if (savePath.EndsWith("png"))
        {
            bytes = ImageConversion.EncodeToPNG(combined);
        }
        if (savePath.EndsWith("exr"))
        {
            bytes = ImageConversion.EncodeToEXR(combined);
        }
        if (savePath.EndsWith("jpg"))
        {
            bytes = ImageConversion.EncodeToJPG(combined);
        }

        string systemPath = Path.Combine(Application.dataPath.Remove(Application.dataPath.Length - 6), savePath);

        File.WriteAllBytes(systemPath, bytes);

        Object.DestroyImmediate(combined);

        AssetDatabase.ImportAsset(savePath);

        TextureImporter combinedImporter = (TextureImporter)AssetImporter.GetAtPath(savePath);

        combinedImporter.sRGBTexture = false;
        combinedImporter.SaveAndReimport();

        if (savePath.EndsWith("exr"))
        {
            // The options for the platform string are: "Standalone", "iPhone", "Android", "WebGL", "Windows Store Apps", "PSP2", "PS4", "XboxOne", "Nintendo 3DS", "WiiU", "tvOS".
            combinedImporter.SetPlatformTextureSettings(new TextureImporterPlatformSettings()
            {
                name = "Standalone", format = TextureImporterFormat.DXT5, overridden = true
            });
        }

        combined = AssetDatabase.LoadAssetAtPath <Texture2D>(savePath);

        //cleanup "raw" textures
        foreach (KeyValuePair <Texture, Texture> prop in m_RawTextures)
        {
            if (AssetDatabase.Contains(prop.Value))
            {
                AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(prop.Value));
            }
        }
        Object.DestroyImmediate(combinerMaterial);

        m_RawTextures.Clear();

        return(combined);
    }
Exemplo n.º 8
0
    /// <summary>
    /// Writes the given texture asynchronously to the disk at the given path. If a file already exists at the given path it will be overwritten
    /// </summary>
    /// <param name="texture"> The texture to write</param>
    /// <param name="format"> The image format to save the texture in. Note that EXR format requires an uncompressed HDR texture</param>
    /// <param name="fileName"> The file name without the extension.</param>
    /// <param name="path"> The absolute path where the file will be saved</param>
    /// <param name="callback"> The method to call when the operation ends. The method will be passed an error if any error occurred</param>

    public static async Task WriteTextureAsync(Texture2D texture, ImageFormat format, string fileName, string path, Action <string> callback)
    {
        try
        {
            byte[] data = null;

            switch (format)
            {
            case ImageFormat.PNG:
                data = ImageConversion.EncodeToPNG(texture);
                if (!fileName.ToLower().Contains(".png"))
                {
                    fileName += ".png";
                }
                break;

            case ImageFormat.JPG:
                data = ImageConversion.EncodeToJPG(texture);
                if (!fileName.ToLower().Contains(".jpg"))
                {
                    fileName += ".jpg";
                }
                break;

            case ImageFormat.EXR:
                data = ImageConversion.EncodeToEXR(texture);
                if (!fileName.ToLower().Contains(".exr"))
                {
                    fileName += ".exr";
                }
                break;
            }

            if (data == null)
            {
                Debug.Log("Failed encoding");
            }
            if (path.EndsWith("/") || path.EndsWith("\\"))
            {
                path += fileName;
            }
            else
            {
                path += "/" + fileName;
            }

            using (FileStream fileStream = File.Create(path))
            {
                await fileStream.WriteAsync(data, 0, data.Length);
            }

            callback("");
            Debug.Log(data.Length / 1024 + "Kb was saved as: " + path);
        }


        catch (Exception ex)
        {
            callback(ex.ToString());
        }
    }
        public void Convert()
        {
#if UNITY_EDITOR
            int       width      = lightmapTexture.width;
            int       height     = lightmapTexture.height;
            Texture2D newTexture = new Texture2D(width, height, DefaultFormat.HDR, TextureCreationFlags.None);

            Color[] lmColorsRaw = lightmapTexture.GetPixels(0, 0, width, height);
            Color[] colors      = new Color[width * height];
            for (int i = 0; i < lmColorsRaw.Length; i++)
            {
                //colors[i] = lmColorsRaw[i].linear;
                //colors[i] *= 0.45f;
                //colors[i].r = GammaToLinearSpaceExact(lmColorsRaw[i].r);
                //colors[i].g = GammaToLinearSpaceExact(lmColorsRaw[i].g);
                //colors[i].b = GammaToLinearSpaceExact(lmColorsRaw[i].b);

                //colors[i] = (2.0f * lmColorsRaw[i].a) * sqrt(lmColorsRaw[i]);
                //colors[i] = (decodeInstructionsX * Mathf.Pow(lmColorsRaw[i].a, decodeInstructionsY)) * lmColorsRaw[i];
                //colors[i] = GammaToLinearSpaceExact(lmColorsRaw[i]);
                colors[i] = lmColorsRaw[i].linear;
            }

            Debug.Log("Difference: " + GetMaxDifference(lmColorsRaw, colors).ToString());

            //may be we need some color conversation

            newTexture.SetPixels(0, 0, width, height, colors);
            newTexture.Apply();

            string filePath = Application.dataPath + "/" + outputPath;

            if (saveExr)
            {
                byte[] _bytes = ImageConversion.EncodeToEXR(newTexture, Texture2D.EXRFlags.CompressZIP);
                File.WriteAllBytes(filePath, _bytes);
            }
            else
            {
                byte[] _bytes = ImageConversion.EncodeToPNG(newTexture);
                File.WriteAllBytes(filePath, _bytes);
            }

            AssetDatabase.ImportAsset("Assets/" + outputPath, ImportAssetOptions.ForceUpdate);

            TextureImporter importer = AssetImporter.GetAtPath("Assets/" + outputPath) as TextureImporter;
            if (importer != null)
            {
                if (saveExr)
                {
                    importer.textureType = TextureImporterType.Default;
                }
                else
                {
                    importer.textureType = TextureImporterType.Default;
                    importer.sRGBTexture = false;
                }

                importer.wrapMode = TextureWrapMode.Clamp;

                importer.npotScale = TextureImporterNPOTScale.ToNearest;
                //importer.textureCompression = TextureImporterCompression.Uncompressed;
                importer.textureCompression = TextureImporterCompression.CompressedLQ;
                importer.isReadable         = true;

                EditorUtility.SetDirty(importer);
                importer.SaveAndReimport();

                AssetDatabase.ImportAsset("Assets/" + outputPath);
                AssetDatabase.Refresh();
            }

            //next read asset again
            Texture2D t       = AssetDatabase.LoadAssetAtPath <Texture2D>("Assets/" + outputPath);
            Color[]   tColors = t.GetPixels();
            for (int i = 0; i < tColors.Length; i++)
            {
                tColors[i] = tColors[i].linear;
            }
            Debug.Log(GetMaxDifference(tColors, lmColorsRaw));
#endif
        }
Exemplo n.º 10
0
        /// <summary>
        /// Compress / encode a multi layer map file to an image
        /// </summary>
        /// <param name="input">Multi layer map in format x,y,layer</param>
        /// <param name="imageName">Output image name - image image index and extension will be added</param>
        /// <param name="exportPNG">True if a png is wanted</param>
        /// <param name="exportJPG">True if a jpg is wanted</param>
        public static void CompressToMultiChannelFileImage(string imageName, HeightMap r, HeightMap g, HeightMap b, HeightMap a, TextureFormat imageStorageFormat, GaiaConstants.ImageFileType imageFileType)
        {
            int width  = 0;
            int height = 0;

            if (r != null)
            {
                width  = r.Width();
                height = r.Depth();
            }
            else if (g != null)
            {
                width  = g.Width();
                height = g.Depth();
            }
            else if (b != null)
            {
                width  = b.Width();
                height = b.Depth();
            }
            else if (a != null)
            {
                width  = a.Width();
                height = a.Depth();
            }

            if (string.IsNullOrEmpty(imageName))
            {
                Debug.LogError("Cannot write image - no name supplied!");
                return;
            }

            if (width == 0 || height == 0)
            {
                Debug.LogError("Cannot write image - invalid dimensions : " + width + ", " + height);
                return;
            }

            Texture2D exportTexture = new Texture2D(width, height, imageStorageFormat, true, false);
            Color     pixelColor    = new Color();

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    pixelColor.r = r != null ? r[x, y] : 0f;
                    pixelColor.g = g != null ? g[x, y] : 0f;
                    pixelColor.b = b != null ? b[x, y] : 0f;
                    pixelColor.a = a != null ? a[x, y] : 1f;
                    exportTexture.SetPixel(x, y, pixelColor);
                }
            }
            exportTexture.Apply();

            #if UNITY_2017_1_OR_NEWER
            switch (imageFileType)
            {
            case GaiaConstants.ImageFileType.Jpg:
                byte[] jpgBytes = ImageConversion.EncodeToJPG(exportTexture, 100);
                GaiaCommon1.Utils.WriteAllBytes(imageName + ".jpg", jpgBytes);
                break;

            case GaiaConstants.ImageFileType.Png:
                byte[] pngBytes = ImageConversion.EncodeToPNG(exportTexture);
                GaiaCommon1.Utils.WriteAllBytes(imageName + ".png", pngBytes);
                break;

            case GaiaConstants.ImageFileType.Exr:
                byte[] exrBytes = ImageConversion.EncodeToEXR(exportTexture, Texture2D.EXRFlags.CompressZIP);
                GaiaCommon1.Utils.WriteAllBytes(imageName + ".exr", exrBytes);
                break;
            }
            #else
            switch (imageFileType)
            {
            case GaiaConstants.ImageFileType.Jpg:
                byte[] jpgBytes = exportTexture.EncodeToJPG();
                GaiaCommon1.Utils.WriteAllBytes(imageName + ".jpg", jpgBytes);
                break;

            case GaiaConstants.ImageFileType.Png:
                byte[] pngBytes = exportTexture.EncodeToPNG();
                GaiaCommon1.Utils.WriteAllBytes(imageName + ".png", pngBytes);
                break;

            case GaiaConstants.ImageFileType.Exr:
                byte[] exrBytes = exportTexture.EncodeToEXR(Texture2D.EXRFlags.CompressZIP);
                GaiaCommon1.Utils.WriteAllBytes(imageName + ".exr", exrBytes);
                break;
            }
            #endif

            #if UNITY_EDITOR
            AssetDatabase.Refresh();
            #endif

            //Lose the texture
            DestroyImmediate(exportTexture);
        }
Exemplo n.º 11
0
 static byte[] EncodeToEXR(Texture2D texture, Texture2D.EXRFlags exrFlags)
 {
     return(ImageConversion.EncodeToEXR(texture, exrFlags));
 }
Exemplo n.º 12
0
        void Export(ExportFormat exportFormat, System.Func <string, string> callback)
        {
            string extension = string.Empty;

            switch (exportFormat)
            {
            case ExportFormat.kExr16:
            case ExportFormat.kExr16ZIP:
            case ExportFormat.kExr16RLE:
            case ExportFormat.kExr32:
            case ExportFormat.kExr32ZIP:
            case ExportFormat.kExr32RLE:
            {
                extension = "exr";
                break;
            }

            default:                     /* case ExportFormat.kPng: */
            {
                extension = "png";
                break;
            }
            }

            string path = callback?.Invoke(extension) ?? string.Empty;

            if (string.IsNullOrEmpty(path) == false)
            {
                Texture2D texture = null;

                switch (exportFormat)
                {
                case ExportFormat.kExr16:
                case ExportFormat.kExr16ZIP:
                case ExportFormat.kExr16RLE:
                {
                    texture = new Texture2D(previewTexture.width, previewTexture.height, TextureFormat.RGBAHalf, false, false);
                    break;
                }

                case ExportFormat.kExr32:
                case ExportFormat.kExr32ZIP:
                case ExportFormat.kExr32RLE:
                {
                    texture = new Texture2D(previewTexture.width, previewTexture.height, TextureFormat.RGBAFloat, false, false);
                    break;
                }

                default:                         /* case ExportFormat.kPng: */
                {
                    texture = new Texture2D(previewTexture.width, previewTexture.height, TextureFormat.RGBA32, false, false);
                    break;
                }
                }
                if (texture != null)
                {
                    var current = RenderTexture.active;
                    RenderTexture.active = previewTexture;
                    texture.ReadPixels(new Rect(0, 0, previewTexture.width, previewTexture.height), 0, 0);
                    texture.Apply();
                    RenderTexture.active = current;
                    byte[] bytes = null;

                    if (exportFormat == ExportFormat.kPng)
                    {
                        bytes = texture.EncodeToPNG();
                    }
                    else
                    {
                        Texture2D.EXRFlags exrFlags = Texture2D.EXRFlags.None;

                        switch (exportFormat)
                        {
                        case ExportFormat.kExr16ZIP:
                        {
                            exrFlags |= Texture2D.EXRFlags.CompressZIP;
                            break;
                        }

                        case ExportFormat.kExr16RLE:
                        {
                            exrFlags |= Texture2D.EXRFlags.CompressRLE;
                            break;
                        }

                        case ExportFormat.kExr32:
                        {
                            exrFlags |= Texture2D.EXRFlags.OutputAsFloat;
                            break;
                        }

                        case ExportFormat.kExr32ZIP:
                        {
                            exrFlags |= Texture2D.EXRFlags.OutputAsFloat;
                            exrFlags |= Texture2D.EXRFlags.CompressZIP;
                            break;
                        }

                        case ExportFormat.kExr32RLE:
                        {
                            exrFlags |= Texture2D.EXRFlags.OutputAsFloat;
                            exrFlags |= Texture2D.EXRFlags.CompressRLE;
                            break;
                        }
                        }
                        bytes = ImageConversion.EncodeToEXR(texture, exrFlags);
                    }
                    Texture.DestroyImmediate(texture);

                    if (bytes != null)
                    {
                        System.IO.File.WriteAllBytes(path, bytes);
                    }
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Takes the actual screen shot when the key is pressed or takeshot is true
        /// </summary>
        private void LateUpdate()
        {
            if (Input.GetKeyDown(m_screenShotKey) || m_takeShot)
            {
                if (m_mainCamera == null)
                {
                    m_mainCamera = GaiaUtils.GetCamera(true);
                }

                //Pick up and use the actual screen dimensions
                if (m_useScreenSize)
                {
                    m_targetWidth  = Screen.width;
                    m_targetHeight = Screen.height;
                }

                m_refreshAssetDB = true;
                RenderTexture rt;
                if (m_imageFormat == GaiaConstants.ImageFileType.Exr)
                {
                    rt = new RenderTexture(m_targetWidth, m_targetHeight, 24, DefaultFormat.HDR);
                }
                else
                {
                    rt = new RenderTexture(m_targetWidth, m_targetHeight, 24, DefaultFormat.LDR);
                }
                m_mainCamera.targetTexture = rt;
                Texture2D screenShot;
                if (m_imageFormat == GaiaConstants.ImageFileType.Exr)
                {
                    screenShot = new Texture2D(m_targetWidth, m_targetHeight, TextureFormat.RGBAFloat, false);
                }
                else
                {
                    screenShot = new Texture2D(m_targetWidth, m_targetHeight, TextureFormat.RGB24, false);
                }

                bool allowHDR = m_mainCamera.allowHDR;
                if (m_imageFormat == GaiaConstants.ImageFileType.Exr)
                {
                    m_mainCamera.allowHDR = true;
                }
                m_mainCamera.Render();
                m_mainCamera.allowHDR = allowHDR;
                RenderTexture.active  = rt;
                screenShot.ReadPixels(new Rect(0, 0, m_targetWidth, m_targetHeight), 0, 0);
                m_mainCamera.targetTexture = null;
                RenderTexture.active       = null; // JC: added to avoid errors
                Destroy(rt);

                if (m_watermark != null)
                {
                    Gaia.GaiaUtils.MakeTextureReadable(m_watermark);
                    screenShot = AddWatermark(screenShot, m_watermark);
                }

                byte[] bytes = null;
                switch (m_imageFormat)
                {
                case GaiaConstants.ImageFileType.Exr:
                    bytes = ImageConversion.EncodeToEXR(screenShot, Texture2D.EXRFlags.CompressZIP);
                    break;

                case GaiaConstants.ImageFileType.Png:
                    bytes = ImageConversion.EncodeToPNG(screenShot);
                    break;

                case GaiaConstants.ImageFileType.Tga:
                    bytes = ImageConversion.EncodeToTGA(screenShot);
                    break;

                case GaiaConstants.ImageFileType.Jpg:
                    bytes = ImageConversion.EncodeToJPG(screenShot, 100);
                    break;
                }

                string filename = ScreenShotName(m_targetWidth, m_targetHeight);
                PWCommon4.Utils.WriteAllBytes(filename, bytes);
                m_takeShot = false;
                Debug.Log(string.Format("Took screenshot to: {0}", filename));
            }
        }