public static Texture2D CreateClipMask(float[] heightMap, int size, float shoreLevel, TextureFormat format)
        {
            Texture2D mask = new Texture2D(size, size, format, false, true);
            mask.filterMode = FilterMode.Bilinear;

            int s2 = size * size;

            Color[] colors = new Color[s2];

            for (int i = 0; i < s2; i++)
            {
                float h = Mathf.Clamp(heightMap[i] - shoreLevel, 0.0f, 1.0f);

                if (h > 0.0f) h = 1.0f;

                colors[i].r = h;
                colors[i].g = h;
                colors[i].b = h;
                colors[i].a = h;
            }

            mask.SetPixels(colors);

            mask.Apply();

            return mask;
        }
        public static Texture2D LoadTextureDXT( string path, TextureFormat format, bool mipmap = true )
        {
            var a = Path.Combine( GenFilePaths.CoreModsFolderPath, LoadedModManager.LoadedMods.ToList().Find( s => s.name == "LT_RedistHeat" ).name );
            var b = Path.Combine( a, "Textures" );
            var filePath = Path.Combine( b,  path + ".dds");
            var bytes = File.ReadAllBytes( filePath );

            if (format != TextureFormat.DXT1 && format != TextureFormat.DXT5)
                throw new Exception("Invalid TextureFormat. Only DXT1 and DXT5 formats are supported by this method.");

            var ddsSizeCheck = bytes[4];
            if (ddsSizeCheck != 124)
                throw new Exception("Invalid DDS DXT texture. Unable to read");  //this header byte should be 124 for DDS image files

            var height = bytes[13] * 256 + bytes[12];
            var width = bytes[17] * 256 + bytes[16];

            var dxtBytes = new byte[bytes.Length - DDSHeaderSize];
            Buffer.BlockCopy(bytes, DDSHeaderSize, dxtBytes, 0, bytes.Length - DDSHeaderSize);

            var texture = new Texture2D(width, height, format, mipmap);
            texture.LoadRawTextureData(dxtBytes);
            texture.Apply();

            return (texture);
        }
Example #3
0
 public static uint GetPixelSize(TextureFormat textureFormat, int width, int height)
 {
     switch (textureFormat)
     {
         case TextureFormat.Rgba8:
             return (uint)(4 * width * height);
         case TextureFormat.Rgb8:
             return (uint)(3 * width * height);
         case TextureFormat.Rgb5551:
         case TextureFormat.Rgb565:
         case TextureFormat.Rgba4:
         case TextureFormat.La8:
         case TextureFormat.Hilo8:
             return (uint)(2 * width * height);
         case TextureFormat.L8:
         case TextureFormat.A8:
         case TextureFormat.La4:
             return (uint)(1 * width * height);
         case TextureFormat.L4: //TODO: Verify this is correct
         case TextureFormat.A4:
             return (uint)((1 * width * height) / 2);
         case TextureFormat.Etc1:
             return (uint)Etc.GetEtc1Length(new Size(width, height), false);
         case TextureFormat.Etc1A4:
             return (uint)Etc.GetEtc1Length(new Size(width, height), true);
         default:
             throw new Exception("Unsupported Texture Format " + (int)textureFormat);
     }
 }
        public static void GetDXT(Texture2D texture, int i, byte[] bytes, TextureFormat format)
        {
            Color32[] colors = texture.GetPixels32(i);
            uint w = (uint) texture.width>>i;
            uint h = (uint) texture.height>>i;

            ColorBlock rgba = new ColorBlock();
            BlockDXT1 block1 = new BlockDXT1();
            BlockDXT5 block5 = new BlockDXT5();

            int blocksize = format == TextureFormat.DXT1 ? 8 : 16;
            int index = 0;
            for (uint y = 0; y < h; y += 4) {
                for (uint x = 0; x < w; x += 4) {
                    rgba.init(w, h, colors, x, y);

                    if (format == TextureFormat.DXT1)
                    {
                        QuickCompress.compressDXT1(rgba, block1);
                        block1.WriteBytes(bytes, index);
                    }
                    else
                    {
                        QuickCompress.compressDXT5(rgba, block5, 0);
                        block5.WriteBytes(bytes, index);
                    }

                    index += blocksize;
                }
            }
        }
        /// <summary>
        /// Creates a bitmap from the currently bound texture
        /// </summary>
        public static unsafe Bitmap CreateBitmapFromTexture( int target, int level, TextureFormat format )
        {
            int width = GetTextureLevelParameterInt32( target, level, Gl.GL_TEXTURE_WIDTH );
            int height = GetTextureLevelParameterInt32( target, level, Gl.GL_TEXTURE_HEIGHT );

            GraphicsLog.Verbose( "Creating bitmap from level {0} in {1}x{2} {3} texture", level, width, height, format );

            if ( ( format == TextureFormat.Depth16 ) || ( format == TextureFormat.Depth24 ) || ( format == TextureFormat.Depth32 ) )
            {
                return CreateBitmapFromDepthTexture( target, level, width, height );
            }

            //	Handle colour textures

            //	Get texture memory
            int bytesPerPixel = TextureFormatInfo.GetSizeInBytes( format );
            TextureInfo info = CheckTextureFormat( format );
            byte[] textureMemory = new byte[ width * height * bytesPerPixel ];
            Gl.glGetTexImage( Gl.GL_TEXTURE_2D, level, info.GlFormat, info.GlType, textureMemory );

            //	TODO: Same problem as above...

            //	Create a Bitmap object from image memory
            fixed ( byte* textureMemoryPtr = textureMemory )
            {
                //	TODO: Add per-case check of Format - in cases with no mapping (see TextureFormatToPixelFormat()), do a manual conversion
                return new Bitmap( width, height, width * bytesPerPixel, TextureFormatInfo.ToPixelFormat( format ), ( IntPtr )textureMemoryPtr );
            }
        }
Example #6
0
        public void OpenTexture(Stream data, string fname, TextureFormat format)
        {
            Bitmap textureBitmap;
            Texture.Read(data, out textureBitmap, format);

            DisplayTexture(textureBitmap, fname, format);
        }
Example #7
0
    public static Texture3D LoadVolumeFromFile(string fileName, TextureFormat format, int elementSize ,int width, int height, int depth)
    {
        BinaryReader br = new BinaryReader(File.Open(fileName, FileMode.Open, FileAccess.Read));
        Texture3D noiseTex = new Texture3D(width, height, depth, TextureFormat.RGBA32, false);
        noiseTex.filterMode = FilterMode.Bilinear;
        noiseTex.wrapMode = TextureWrapMode.Repeat;

        int numElements = width * height * depth;
        List<Color> colors = new List<Color>(numElements);


        // Get pixels from 2d texture for each slize in z direction
        for (int z = 0; z < depth; z++)
        {
            Texture2D tex2d = LoadTexture2DRaw(br, width, height, format, elementSize);
            colors.AddRange(tex2d.GetPixels());
        }
        //colors should now be filled with all pixels
        noiseTex.SetPixels(colors.ToArray());
        noiseTex.Apply(false);

        br.Close();
        return noiseTex;
   
    }
Example #8
0
        public Corona.Image ConvertDown(Corona.Image sourceImage, TextureFormat toFormat)
        {
            int bits = -1;
            if (toFormat == TextureFormat.Format2_I2) bits = 2;
            if (toFormat == TextureFormat.Format3_I4) bits = 4;
            if (toFormat == TextureFormat.Format4_I8) bits = 8;
            if (toFormat == TextureFormat.Format7_16bpp) bits = 16;

            int colors = 1<<bits;

            Corona.Image ret = null;

            using (Util.TempFile tmpIn = new Util.TempFile("png"), tmpOut = new Util.TempFile("png"))
            {
                sourceImage.Save(tmpIn.Path, Corona.FileFormat.PNG);

                string output = Run("-treedepth", 4, "-colors", colors, tmpIn, tmpOut);

                if (toFormat == TextureFormat.Format7_16bpp)
                    ret = Corona.Image.Open(tmpOut.Path, Corona.PixelFormat.R8G8B8A8, Corona.FileFormat.PNG);
                else
                    ret = Corona.Image.Open(tmpOut.Path, Corona.PixelFormat.I8, Corona.FileFormat.PNG);

            }
            return ret;
        }
 /// <summary>
 /// Creates the texture data
 /// </summary>
 public void Create( int width, int height, TextureFormat format )
 {
     m_Width = width;
     m_Height = height;
     m_Format = format;
     m_Data = new byte[ width * height * TextureFormatInfo.GetSizeInBytes( format ) ];
 }
        /// <summary>
        /// Generates a texture containing the given graph's noise output.
        /// If this is being called very often, create a permanent render target and material and
        ///     use the other version of this method instead for much better performance.
        /// If an error occurred, outputs to the Unity debug console and returns "null".
        /// </summary>
        /// <param name="outputComponents">
        /// The texture output.
        /// For example, pass "rgb" or "xyz" to output the noise into the red, green, and blue channels
        ///     but not the alpha channel.
        /// </param>
        /// <param name="defaultColor">
        /// The color (generally 0-1) of the color components which aren't set by the noise.
        /// </param>
        public static Texture2D GenerateToTexture(Graph g, GraphParamCollection c, int width, int height,
												  string outputComponents, float defaultColor,
												  TextureFormat format = TextureFormat.RGBAFloat)
        {
            //Generate a shader from the graph and have Unity compile it.
            string shaderPath = Path.Combine(Application.dataPath, "gpuNoiseShaderTemp.shader");
            Shader shader = SaveShader(g, shaderPath, "TempGPUNoiseShader", outputComponents, defaultColor);
            if (shader == null)
            {
                return null;
            }

            //Render the shader's output into a render texture and copy the data to a Texture2D.
            RenderTexture target = new RenderTexture(width, height, 16, RenderTextureFormat.ARGBFloat);
            target.Create();
            Texture2D resultTex = new Texture2D(width, height, format, false, true);

            //Create the material and set its parameters.
            Material mat = new Material(shader);
            c.SetParams(mat);

            GraphUtils.GenerateToTexture(target, mat, resultTex);

            //Clean up.
            target.Release();
            if (!AssetDatabase.DeleteAsset(StringUtils.GetRelativePath(shaderPath, "Assets")))
            {
                Debug.LogError("Unable to delete temp file: " + shaderPath);
            }

            return resultTex;
        }
Example #11
0
 public static byte[] GetScreenBytes(TextureFormat textureFormat)
 {
     Texture2D screenTexture = new Texture2D(Screen.width, Screen.height,textureFormat,true);
     screenTexture.ReadPixels(new Rect(0f, 0f, Screen.width, Screen.height),0,0);
     screenTexture.Apply();
     byte[] byteArray = screenTexture.EncodeToPNG();
     return byteArray;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="Tango.YUVTexture"/> class.
 /// NOTE : Texture resolutions will be reset by the API. The sizes passed
 /// into the constructor are not guaranteed to persist when running on device.
 /// </summary>
 /// <param name="width">Width.</param>
 /// <param name="height">Height.</param>
 /// <param name="format">Format.</param>
 /// <param name="mipmap">If set to <c>true</c> mipmap.</param>
 public YUVTexture(int yPlaneWidth, int yPlaneHeight,
                   int uvPlaneWidth, int uvPlaneHeight,
                   TextureFormat format, bool mipmap)
 {
     m_videoOverlayTextureY = new Texture2D(yPlaneWidth, yPlaneHeight, format, mipmap);
     m_videoOverlayTextureCb = new Texture2D(uvPlaneWidth, uvPlaneHeight, format, mipmap);
     m_videoOverlayTextureCr = new Texture2D(uvPlaneWidth, uvPlaneHeight, format, mipmap);
 }
		public TileMeshSettings (IVector2 tiles, int tileResolution, float tileSize, MeshMode meshMode, TextureFormat textureFormat)
		{
			Tiles			= tiles;
			TileResolution	= tileResolution;
			TileSize		= tileSize;
			MeshMode		= meshMode;
			TextureFormat	= textureFormat;
		}
	public Texture2DInfo(int width, int height, TextureFormat format, bool hasMipmaps, byte[] rawData)
	{
		this.width = width;
		this.height = height;
		this.format = format;
		this.hasMipmaps = hasMipmaps;
		this.rawData = rawData;
	}
Example #15
0
 public TileMeshSettings(int tilesX, int tilesY, int tileResolution, float tileSize, MeshMode meshMode, TextureFormat textureFormat)
 {
     TilesX = tilesX;
     TilesY = tilesY;
     TileResolution = tileResolution;
     TileSize = tileSize;
     MeshMode = meshMode;
     TextureFormat = textureFormat;
 }
Example #16
0
 public static int GetBitsPerPixel(TextureFormat format)
 {
     switch (format)
     {
     case TextureFormat.Alpha8: //	 Alpha-only texture format.
         return 8;
     case TextureFormat.ARGB4444: //	 A 16 bits/pixel texture format. Texture stores color with an alpha channel.
         return 16;
     case TextureFormat.RGBA4444: //	 A 16 bits/pixel texture format.
         return 16;
     case TextureFormat.RGB24:	// A color texture format.
         return 24;
     case TextureFormat.RGBA32:	//Color with an alpha channel texture format.
         return 32;
     case TextureFormat.ARGB32:	//Color with an alpha channel texture format.
         return 32;
     case TextureFormat.RGB565:	//	 A 16 bit color texture format.
         return 16;
     case TextureFormat.DXT1:	// Compressed color texture format.
         return 4;
     case TextureFormat.DXT5:	// Compressed color with alpha channel texture format.
         return 8;
         /*
         case TextureFormat.WiiI4:	// Wii texture format.
         case TextureFormat.WiiI8:	// Wii texture format. Intensity 8 bit.
         case TextureFormat.WiiIA4:	// Wii texture format. Intensity + Alpha 8 bit (4 + 4).
         case TextureFormat.WiiIA8:	// Wii texture format. Intensity + Alpha 16 bit (8 + 8).
         case TextureFormat.WiiRGB565:	// Wii texture format. RGB 16 bit (565).
         case TextureFormat.WiiRGB5A3:	// Wii texture format. RGBA 16 bit (4443).
         case TextureFormat.WiiRGBA8:	// Wii texture format. RGBA 32 bit (8888).
         case TextureFormat.WiiCMPR:	//	 Compressed Wii texture format. 4 bits/texel, ~RGB8A1 (Outline alpha is not currently supported).
             return 0;  //Not supported yet
         */
     case TextureFormat.PVRTC_RGB2://	 PowerVR (iOS) 2 bits/pixel compressed color texture format.
         return 2;
     case TextureFormat.PVRTC_RGBA2://	 PowerVR (iOS) 2 bits/pixel compressed with alpha channel texture format
         return 2;
     case TextureFormat.PVRTC_RGB4://	 PowerVR (iOS) 4 bits/pixel compressed color texture format.
         return 4;
     case TextureFormat.PVRTC_RGBA4://	 PowerVR (iOS) 4 bits/pixel compressed with alpha channel texture format
         return 4;
     case TextureFormat.ETC_RGB4://	 ETC (GLES2.0) 4 bits/pixel compressed RGB texture format.
         return 4;
     case TextureFormat.ATC_RGB4://	 ATC (ATITC) 4 bits/pixel compressed RGB texture format.
         return 4;
     case TextureFormat.ATC_RGBA8://	 ATC (ATITC) 8 bits/pixel compressed RGB texture format.
         return 8;
     case TextureFormat.BGRA32://	 Format returned by iPhone camera
         return 32;
     // case TextureFormat.ATF_RGB_DXT1://	 Flash-specific RGB DXT1 compressed color texture format.
     // case TextureFormat.ATF_RGBA_JPG://	 Flash-specific RGBA JPG-compressed color texture format.
     // case TextureFormat.ATF_RGB_JPG://	 Flash-specific RGB JPG-compressed color texture format.
     // 	return 0; //Not supported yet
     }
     return 0;
 }
Example #17
0
        public void OpenTexture(Stream data, string fname, Stream paletteData, TextureFormat format)
        {
            Bitmap textureBitmap;

            TextureBase texture = Texture.GetModule(format);
            texture.PaletteStream = paletteData;
            texture.Read(data, out textureBitmap);

            DisplayTexture(textureBitmap, fname, format);
        }
 /// <summary>
 /// Returns true if the specified texture format supports an alpha channel
 /// </summary>
 public static bool HasAlphaChannel( TextureFormat texFormat )
 {
     switch ( texFormat )
     {
         case TextureFormat.R8G8B8A8:
         case TextureFormat.B8G8R8A8:
         case TextureFormat.A8R8G8B8:
         case TextureFormat.A8B8G8R8: return true;
     }
     return false;
 }
Example #19
0
 public static bool getTextureFormat(ref TextureFormat result, SerializedObject serialTex)
 {
     if(serialTex == null) return false;
     SerializedProperty prop = serialTex.FindProperty("m_TextureFormat");
     if( prop != null ) {
         result = (TextureFormat)prop.intValue;
         return true;
     }
     Debug.LogError("m_TextureFormat SerializedProperty not found!");
     return false;
 }
Example #20
0
		// Load a texture with the specified height and calculating width by respecting the aspect ratio
		public static Texture2D LoadFixedHeightFromFile(string filePath, int fixedHeight, TextureFormat textureFormat = TextureFormat.R16)
		{
			Vector2 imageSize = ImageHelper.GetDimensions(filePath);
			float width = fixedHeight;
			if (imageSize.y != 0)
			{
				width = imageSize.x * fixedHeight / imageSize.y;
			}
			
			return LoadFromFile(filePath, (int)width, fixedHeight, textureFormat);
		}
 public static IEnumerator LoadImage(this Texture2D texture2D, string url, Vector2 size, TextureFormat format = TextureFormat.RGB24, bool mipmap = false)
 {
     Texture2D tex = new Texture2D((int)size.x, (int)size.y, format, mipmap);
     WWW www = new WWW(url);
     yield return www;
     if (string.IsNullOrEmpty(www.error))
     {
         www.LoadImageIntoTexture(tex);
         texture2D = tex;
     }
 }
Example #22
0
        /// <summary>
        /// Creates a texture instance
        /// </summary>
        /// <param name="_Name"></param>
        /// <param name="_Width"></param>
        /// <param name="_Height"></param>
        /// <param name="_Format"></param>
        /// <param name="_bUseMipMaps">Create mip maps for the texture</param>
        /// <param name="_FilterMode">Filter mode to use to sample the texture</param>
        /// <param name="_WrapMode">Wrap mode to use to address the texture</param>
        /// <returns></returns>
        public NuajTexture2D( string _Name, int _Width, int _Height, TextureFormat _Format, bool _bUseMipMaps, FilterMode _FilterMode, TextureWrapMode _WrapMode )
        {
            Help.LogDebug( "Nuaj.Help.CreateTexture() \"" + _Name + "\" => " + _Width + "x" + _Height + "x" + _Format );
            if ( _Width < 1 || _Height < 1 )
                throw new Exception( "NuajTexture2D.ctor() => Invalid resolution !" );

            m_Texture = new Texture2D( _Width, _Height, _Format, _bUseMipMaps );
            m_Texture.name = _Name;
            m_Texture.filterMode = _FilterMode;
            m_Texture.wrapMode = _WrapMode;
            m_Texture.hideFlags = HideFlags.HideAndDontSave;
        }
Example #23
0
 public void create(int width, int height, TextureFormat texFormat = TextureFormat.ARGB32)
 {
     this.width = width;
     this.height = height;
     texture = new Texture2D(width, height, texFormat, false);
     if (texture == null)
     {
         PGraphics.debuglogWaring("create: new Texture2D <failed>");
         return;
     }
     clear(new Color(0, 0, 0, 0));
 }
 public static IEnumerator LoadTexture2D(this Texture2D te, string url, Vector2 size, TextureFormat format = TextureFormat.RGB24, bool mipmap = false)
 {
     Texture2D tex = new Texture2D((int)size.x, (int)size.y, format, mipmap);
     //tex.name = "Demo";
     WWW www = new WWW("file:///" + url);
     yield return www;
     Debug.Log(url);
     if (string.IsNullOrEmpty(www.error))
     {
         www.LoadImageIntoTexture(tex);
         te = tex;
     }
 }
Example #25
0
 public void CompileTextures(string name, TextureFormat format = TextureFormat.RGBA32, Color defaultColor = default(Color), bool linear = false)
 {
     if(SystemInfo.supports2DArrayTextures)
     {
         UsingArray = true;
         BuildTextureArray(format, defaultColor, linear);
     }
     else
     {
         UsingArray = false;
         BuildAtlas(name, format, defaultColor, linear);
     }
 }
    public ChannelTexture(int width, int height, TextureFormat format)
    {
        tex = new Texture2D(width, height, format, false);

        tex.wrapMode = TextureWrapMode.Clamp; //important for NPOT

        #if !((UNITY_ANDROID || UNITY_IPHONE) && !UNITY_EDITOR)
        pixels = tex.GetPixels32(0);
        handle = GCHandle.Alloc(pixels, GCHandleType.Pinned);
        #endif

        ReAlloc();
    }
    public bool Build(int width, int height, TextureFormat format = TextureFormat.RGBA32)
    {
        _width = width;
        _height = height;
        _format = format;

        if (CreateTexture())
        {
            AVProLiveCameraPlugin.SetTexturePointer(_deviceIndex, _bufferIndex, _texture.GetNativeTexturePtr());
            return true;
        }
        return false;
    }
        /// <summary>
        /// Utility function to check that the texture size is supported on the graphics platform for the provided graphics profile.
        /// </summary>
        /// <param name="textureFormat">The desired type of format for the output texture</param>
        /// <param name="platform">The graphics platform</param>
        /// <param name="graphicsProfile">The graphics profile</param>
        /// <param name="textureSizeInput">The texture size input.</param>
        /// <param name="textureSizeRequested">The texture size requested.</param>
        /// <param name="generateMipmaps">Indicate if mipmaps should be generated for the output texture</param>
        /// <param name="logger">The logger.</param>
        /// <returns>true if the texture size is supported</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">graphicsProfile</exception>
        public static Size2 FindBestTextureSize(TextureFormat textureFormat, GraphicsPlatform platform, GraphicsProfile graphicsProfile, Size2 textureSizeInput, Size2 textureSizeRequested, bool generateMipmaps, ILogger logger)
        {
            var textureSize = textureSizeRequested;

            // compressed DDS files has to have a size multiple of 4.
            if (platform == GraphicsPlatform.Direct3D11 && textureFormat == TextureFormat.Compressed
                && ((textureSizeRequested.Width % 4) != 0 || (textureSizeRequested.Height % 4) != 0))
            {
                textureSize.Width = unchecked((int)(((uint)(textureSizeRequested.Width + 3)) & ~(uint)3));
                textureSize.Height = unchecked((int)(((uint)(textureSizeRequested.Height + 3)) & ~(uint)3));
            }

            var maxTextureSize = 0;

            // determine if the desired size if valid depending on the graphics profile
            switch (graphicsProfile)
            {
                case GraphicsProfile.Level_9_1:
                case GraphicsProfile.Level_9_2:
                case GraphicsProfile.Level_9_3:
                    if (generateMipmaps && (!IsPowerOfTwo(textureSize.Width) || !IsPowerOfTwo(textureSize.Height)))
                    {
                        // TODO: TEMPORARY SETUP A MAX TEXTURE OF 1024. THIS SHOULD BE SPECIFIED DONE IN THE ASSET INSTEAD
                        textureSize.Width = Math.Min(MathUtil.NextPowerOfTwo(textureSize.Width), 1024);
                        textureSize.Height = Math.Min(MathUtil.NextPowerOfTwo(textureSize.Height), 1024);
                        logger.Warning("Graphic profiles 9.1/9.2/9.3 do not support mipmaps with textures that are not power of 2. Asset is automatically resized to " + textureSize);
                    }
                    maxTextureSize = graphicsProfile >= GraphicsProfile.Level_9_3 ? 4096 : 2048;
                    break;
                case GraphicsProfile.Level_10_0:
                case GraphicsProfile.Level_10_1:
                    maxTextureSize = 8192;
                    break;
                case GraphicsProfile.Level_11_0:
                case GraphicsProfile.Level_11_1:
                case GraphicsProfile.Level_11_2:
                    maxTextureSize = 16384;
                    break;
                default:
                    throw new ArgumentOutOfRangeException("graphicsProfile");
            }

            if (textureSize.Width > maxTextureSize || textureSize.Height > maxTextureSize)
            {
                logger.Error("Graphic profile {0} do not support texture with resolution {2} x {3} because it is larger than {1}. " +
                             "Please reduce texture size or upgrade your graphic profile.", graphicsProfile, maxTextureSize, textureSize.Width, textureSize.Height);
                return new Size2(Math.Min(textureSize.Width, maxTextureSize), Math.Min(textureSize.Height, maxTextureSize));
            }

            return textureSize;
        }
Example #29
0
		public static Texture2D LoadFromFile(string filePath, int width, int height, TextureFormat textureFormat = TextureFormat.R16)
		{
			// Load texture in memory
			byte[] fileData = File.ReadAllBytes(filePath);
			
			// Create texture for Unity and load it
			Texture2D texture = new Texture2D(2, 2, textureFormat, false);
			texture.LoadImage(fileData);
			
			// Resize the texture
			Resize(texture, width, height);
			
			return texture;
		}
Example #30
0
				/// <summary>
				/// Generic texture-building method. Creates a texture using a fuction that transforms float coordiantes (in the range [0,1]x[0,1]) into color
				/// </summary>
				///<param name="width">Texture width.</param>
				///<param name="height">Texture height</param>
				/// <param name="colorFunc">Function mapping coordinates to color</param>
				///<param name="format">Texture format to use</param>
				///<returns></returns>
				public static Texture Make (int width, int height, Func<float, float, Color> colorFunc, TextureFormat format)
				{
						Color[] cols = new Color[width * height];
						for (int ii = 0; ii < width; ii++) {
								for (int jj = 0; jj < height; jj++) {
										cols [ii + jj * width] = colorFunc ((float)ii / width, (float)jj / height);
								}
						}
						var res = new Texture2D (width, height, format, false);
						res.SetPixels (cols, 0);
						res.Apply ();

						return res;

				}
Example #31
0
        public static void Sust(EmitterContext context)
        {
            OpCodeImage op = (OpCodeImage)context.CurrOp;

            SamplerType type = ConvertSamplerType(op.Dimensions);

            if (type == SamplerType.None)
            {
                context.Config.GpuAccessor.Log("Invalid image store sampler type.");

                return;
            }

            int raIndex = op.Ra.Index;
            int rbIndex = op.Rb.Index;

            Operand Ra()
            {
                if (raIndex > RegisterConsts.RegisterZeroIndex)
                {
                    return(Const(0));
                }

                return(context.Copy(Register(raIndex++, RegisterType.Gpr)));
            }

            Operand Rb()
            {
                if (rbIndex > RegisterConsts.RegisterZeroIndex)
                {
                    return(Const(0));
                }

                return(context.Copy(Register(rbIndex++, RegisterType.Gpr)));
            }

            List <Operand> sourcesList = new List <Operand>();

            if (op.IsBindless)
            {
                sourcesList.Add(context.Copy(Register(op.Rc)));
            }

            int coordsCount = type.GetDimensions();

            for (int index = 0; index < coordsCount; index++)
            {
                sourcesList.Add(Ra());
            }

            if (Sample1DAs2D && (type & SamplerType.Mask) == SamplerType.Texture1D)
            {
                sourcesList.Add(Const(0));

                type &= ~SamplerType.Mask;
                type |= SamplerType.Texture2D;
            }

            if (type.HasFlag(SamplerType.Array))
            {
                sourcesList.Add(Ra());

                type |= SamplerType.Array;
            }

            TextureFormat format = TextureFormat.Unknown;

            if (op.UseComponents)
            {
                int componentMask = (int)op.Components;

                for (int compMask = componentMask, compIndex = 0; compMask != 0; compMask >>= 1, compIndex++)
                {
                    if ((compMask & 1) != 0)
                    {
                        sourcesList.Add(Rb());
                    }
                }

                if (!op.IsBindless)
                {
                    format = context.Config.GetTextureFormat(op.HandleOffset);
                }
            }
            else
            {
                if (op.ByteAddress)
                {
                    int xIndex = op.IsBindless ? 1 : 0;

                    sourcesList[xIndex] = context.ShiftRightS32(sourcesList[xIndex], Const(GetComponentSizeInBytesLog2(op.Size)));
                }

                int components = GetComponents(op.Size);

                for (int compIndex = 0; compIndex < components; compIndex++)
                {
                    sourcesList.Add(Rb());
                }

                format = GetTextureFormat(op.Size);
            }

            Operand[] sources = sourcesList.ToArray();

            int handle = !op.IsBindless ? op.HandleOffset : 0;

            TextureFlags flags = op.IsBindless ? TextureFlags.Bindless : TextureFlags.None;

            TextureOperation operation = context.CreateTextureOperation(
                Instruction.ImageStore,
                type,
                format,
                flags,
                handle,
                0,
                null,
                sources);

            context.Add(operation);
        }
Example #32
0
 public static extern int GetRowBytesFromWidthAndFormat(int width, TextureFormat format);
 public static extern void CompressTexture([NotNull] Texture2D texture, TextureFormat format, int quality);
 public static extern void CompressCubemapTexture([NotNull] Cubemap texture, TextureFormat format, int quality);
        private void OnGUI()
        {
            m_Scroll = GUILayout.BeginScrollView(m_Scroll);

            EditorGUILayout.LabelField("Resolution", EditorStyles.boldLabel);
            m_ResWidth      = EditorGUILayout.IntField("Width", m_ResWidth);
            m_ResHeight     = EditorGUILayout.IntField("Height", m_ResHeight);
            m_IsTransparent = EditorGUILayout.Toggle("Transparent Background", m_IsTransparent);

            m_Scale = EditorGUILayout.IntSlider("Scale", m_Scale, 1, 15);

            // Save Path control.
            float kButtonWidth  = 60;
            Rect  contentRect   = EditorGUI.PrefixLabel(EditorGUILayout.GetControlRect(), new GUIContent("Save Path"));
            Rect  textFieldRect = new Rect(contentRect.x, contentRect.y, contentRect.width - kButtonWidth, contentRect.height);
            Rect  buttonRect    = new Rect(textFieldRect.x + textFieldRect.width, textFieldRect.y, kButtonWidth, textFieldRect.height);

            EditorGUI.TextField(textFieldRect, m_Path);
            if (GUI.Button(buttonRect, "Browse"))
            {
                GetPath();
            }

            // Camera
            m_ScreenshotCamera = EditorGUILayout.ObjectField("Camera", m_ScreenshotCamera, typeof(Camera), true) as Camera;

            if (m_ScreenshotCamera == null)
            {
                m_ScreenshotCamera = FindObjectOfType <Camera>();
            }

            EditorGUILayout.LabelField("Default Options", EditorStyles.boldLabel);
            GUILayout.BeginHorizontal();

            float halfButtonWidth = EditorGUIUtility.currentViewWidth / 2 - 6;

            // Screen Size button
            if (GUILayout.Button("Set To Screen Size", GUILayout.Width(halfButtonWidth)))
            {
                Vector2 gameView = Handles.GetMainGameViewSize();
                m_ResWidth  = (int)gameView.x;
                m_ResHeight = (int)gameView.y;
            }

            // Default Size button
            if (GUILayout.Button("Default Size", GUILayout.Width(halfButtonWidth)))
            {
                m_ResWidth  = 2560;
                m_ResHeight = 1440;
                m_Scale     = 1;
            }

            GUILayout.EndHorizontal();

            // Screenshot resolution info.
            EditorGUILayout.Space();
            EditorGUILayout.LabelField($"Screenshot will be taken at {m_ResWidth*m_Scale} x {m_ResHeight*m_Scale} px", EditorStyles.boldLabel);

            // Take Screenshot button.
            if (GUILayout.Button("Take Screenshot", GUILayout.MinHeight(60)))
            {
                if (m_Path == "" || !Directory.Exists(m_Path))
                {
                    m_Path = EditorUtility.SaveFolderPanel("Path to Save Images", m_Path, Application.dataPath);
                    EditorPrefs.SetString(kPrefKey, m_Path);
                    Debug.Log("Path Set");
                }

                TakeHiResShot();
            }
            EditorGUILayout.Space();

            EditorGUILayout.BeginHorizontal();

            // Open Last Screenshot button.
            GUI.enabled = m_LastScreenshot != "";
            if (GUILayout.Button("Open Last Screenshot", GUILayout.MinHeight(40), GUILayout.Width(halfButtonWidth)))
            {
                Application.OpenURL("file://" + m_LastScreenshot);
                Debug.Log("Opening File " + m_LastScreenshot);
            }
            GUI.enabled = true;

            // Open Folder button.
            if (GUILayout.Button("Open Folder", GUILayout.MinHeight(40), GUILayout.Width(halfButtonWidth)))
            {
                Application.OpenURL("file://" + m_Path);
            }

            EditorGUILayout.EndHorizontal();

            if (m_TakeHiResShot)
            {
                int           resWidthN  = m_ResWidth * m_Scale;
                int           resHeightN = m_ResHeight * m_Scale;
                RenderTexture rt         = new RenderTexture(resWidthN, resHeightN, 24);
                m_ScreenshotCamera.targetTexture = rt;

                TextureFormat tFormat = m_IsTransparent ? TextureFormat.ARGB32 : TextureFormat.RGB24;

                Texture2D screenShot = new Texture2D(resWidthN, resHeightN, tFormat, false);
                m_ScreenshotCamera.Render();
                RenderTexture.active = rt;
                screenShot.ReadPixels(new Rect(0, 0, resWidthN, resHeightN), 0, 0);
                m_ScreenshotCamera.targetTexture = null;
                RenderTexture.active             = null;
                byte[] bytes    = screenShot.EncodeToPNG();
                string filename = ScreenShotName(resWidthN, resHeightN);

                File.WriteAllBytes(filename, bytes);
                Debug.Log($"Took screenshot to: {filename}");
                Application.OpenURL(filename);
                m_TakeHiResShot = false;
            }

            EditorGUILayout.HelpBox("Requires Unity Pro.", MessageType.Info);

            GUILayout.EndScrollView();
        }
        /// <summary>
        /// Creates and populates a duplicate skin with cloned attachments that are backed by a new packed texture atlas comprised of all the regions from the original skin.</summary>
        /// <remarks>No Spine.Atlas object is created so there is no way to find AtlasRegions except through the Attachments using them.</remarks>
        public static Skin GetRepackedSkin(this Skin o, string newName, Shader shader, out Material m, out Texture2D t, int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps)
        {
            var skinAttachments = o.Attachments;
            var newSkin         = new Skin(newName);

            // Use these to detect and use shared regions.
            var existingRegions = new Dictionary <AtlasRegion, int>();
            var regionIndexes   = new List <int>();

            // Collect all textures from the attachments of the original skin.
            var repackedAttachments = new List <Attachment>();
            var texturesToPack      = new List <Texture2D>();
            var originalRegions     = new List <AtlasRegion>();
            int newRegionIndex      = 0;

            foreach (var kvp in skinAttachments)
            {
                var newAttachment = kvp.Value.GetClone(true);
                if (IsRenderable(newAttachment))
                {
                    var region = newAttachment.GetAtlasRegion();
                    int existingIndex;
                    if (existingRegions.TryGetValue(region, out existingIndex))
                    {
                        regionIndexes.Add(existingIndex);                         // Store the region index for the eventual new attachment.
                    }
                    else
                    {
                        originalRegions.Add(region);
                        texturesToPack.Add(region.ToTexture());                    // Add the texture to the PackTextures argument
                        existingRegions.Add(region, newRegionIndex);               // Add the region to the dictionary of known regions
                        regionIndexes.Add(newRegionIndex);                         // Store the region index for the eventual new attachment.
                        newRegionIndex++;
                    }

                    repackedAttachments.Add(newAttachment);
                }
                var key = kvp.Key;
                newSkin.AddAttachment(key.slotIndex, key.name, newAttachment);
            }

            // Fill a new texture with the collected attachment textures.
            var newTexture = new Texture2D(maxAtlasSize, maxAtlasSize, textureFormat, mipmaps);

            newTexture.anisoLevel = texturesToPack[0].anisoLevel;
            newTexture.name       = newName;
            var rects = newTexture.PackTextures(texturesToPack.ToArray(), padding, maxAtlasSize);

            // Rehydrate the repacked textures as a Material, Spine atlas and Spine.AtlasAttachments
            var newMaterial = new Material(shader);

            newMaterial.name        = newName;
            newMaterial.mainTexture = newTexture;
            var page = newMaterial.ToSpineAtlasPage();

            page.name = newName;

            var repackedRegions = new List <AtlasRegion>();

            for (int i = 0, n = originalRegions.Count; i < n; i++)
            {
                var oldRegion = originalRegions[i];
                var newRegion = UVRectToAtlasRegion(rects[i], oldRegion.name, page, oldRegion.offsetX, oldRegion.offsetY, oldRegion.rotate);
                repackedRegions.Add(newRegion);
            }

            // Map the cloned attachments to the repacked atlas.
            for (int i = 0, n = repackedAttachments.Count; i < n; i++)
            {
                var a = repackedAttachments[i];
                a.SetRegion(repackedRegions[regionIndexes[i]]);
            }

            // Clean up
            foreach (var ttp in texturesToPack)
            {
                UnityEngine.Object.Destroy(ttp);
            }

            t = newTexture;
            m = newMaterial;
            return(newSkin);
        }
Example #37
0
 public static extern int GetBytesFromTextureFormat(TextureFormat inFormat);
Example #38
0
        public Texture2D(ObjectReader reader) : base(reader)
        {
            m_Width  = reader.ReadInt32();
            m_Height = reader.ReadInt32();
            var m_CompleteImageSize = reader.ReadInt32();

            if (version[0] >= 2020) //2020.1 and up
            {
                var m_MipsStripped = reader.ReadInt32();
            }
            m_TextureFormat = (TextureFormat)reader.ReadInt32();
            if (version[0] < 5 || (version[0] == 5 && version[1] < 2)) //5.2 down
            {
                m_MipMap = reader.ReadBoolean();
            }
            else
            {
                m_MipCount = reader.ReadInt32();
            }
            if (version[0] > 2 || (version[0] == 2 && version[1] >= 6)) //2.6.0 and up
            {
                var m_IsReadable = reader.ReadBoolean();
            }
            if (version[0] >= 2020) //2020.1 and up
            {
                var m_IsPreProcessed = reader.ReadBoolean();
            }
            if (version[0] > 2019 || (version[0] == 2019 && version[1] >= 3)) //2019.3 and up
            {
                var m_IgnoreMasterTextureLimit = reader.ReadBoolean();
            }
            if (version[0] >= 3) //3.0.0 - 5.4
            {
                if (version[0] < 5 || (version[0] == 5 && version[1] <= 4))
                {
                    var m_ReadAllowed = reader.ReadBoolean();
                }
            }
            if (version[0] > 2018 || (version[0] == 2018 && version[1] >= 2)) //2018.2 and up
            {
                var m_StreamingMipmaps = reader.ReadBoolean();
            }
            reader.AlignStream();
            if (version[0] > 2018 || (version[0] == 2018 && version[1] >= 2)) //2018.2 and up
            {
                var m_StreamingMipmapsPriority = reader.ReadInt32();
            }
            var m_ImageCount       = reader.ReadInt32();
            var m_TextureDimension = reader.ReadInt32();

            m_TextureSettings = new GLTextureSettings(reader);
            if (version[0] >= 3) //3.0 and up
            {
                var m_LightmapFormat = reader.ReadInt32();
            }
            if (version[0] > 3 || (version[0] == 3 && version[1] >= 5)) //3.5.0 and up
            {
                var m_ColorSpace = reader.ReadInt32();
            }
            if (version[0] > 2020 || (version[0] == 2020 && version[1] >= 2)) //2020.2 and up
            {
                var m_PlatformBlob = reader.ReadUInt8Array();
                reader.AlignStream();
            }
            var image_data_size = reader.ReadInt32();

            if (image_data_size == 0 && ((version[0] == 5 && version[1] >= 3) || version[0] > 5))//5.3.0 and up
            {
                m_StreamData = new StreamingInfo(reader);
            }

            ResourceReader resourceReader;

            if (!string.IsNullOrEmpty(m_StreamData?.path))
            {
                resourceReader = new ResourceReader(m_StreamData.path, assetsFile, m_StreamData.offset, (int)m_StreamData.size);
            }
            else
            {
                resourceReader = new ResourceReader(reader, reader.BaseStream.Position, image_data_size);
            }
            image_data = resourceReader;
        }
Example #39
0
        public static RegionAttachment ToRegionAttachmentPMAClone(this Sprite sprite, Shader shader, TextureFormat textureFormat = TextureFormat.RGBA32, bool mipmaps = false, Material materialPropertySource = null)
        {
            if (sprite == null)
            {
                throw new ArgumentNullException("sprite");
            }
            if (shader == null)
            {
                throw new ArgumentNullException("shader");
            }
            AtlasRegion region = sprite.ToAtlasRegionPMAClone(shader, textureFormat, mipmaps, materialPropertySource);
            float       scale  = 1f / sprite.pixelsPerUnit;

            return(region.ToRegionAttachment(sprite.name, scale));
        }
Example #40
0
 public static RegionAttachment ToRegionAttachmentPMAClone(this Sprite sprite, Material materialPropertySource, TextureFormat textureFormat = TextureFormat.RGBA32, bool mipmaps = false)
 {
     return(sprite.ToRegionAttachmentPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource));
 }
Example #41
0
 public virtual bool SupportsTextureFormat(TextureFormat format)
 {
     return(EditorSystemInfo.SupportsTextureFormat(format));
 }
    int GetBitsPerPixel(TextureFormat format)
    {
        switch (format)
        {
        case TextureFormat.Alpha8:         //	 Alpha-only texture format.
            return(8);

        case TextureFormat.ARGB4444:         //	 A 16 bits/pixel texture format. Texture stores color with an alpha channel.
            return(16);

        case TextureFormat.RGBA4444:         //	 A 16 bits/pixel texture format.
            return(16);

        case TextureFormat.RGB24:               // A color texture format.
            return(24);

        case TextureFormat.RGBA32:              //Color with an alpha channel texture format.
            return(32);

        case TextureFormat.ARGB32:              //Color with an alpha channel texture format.
            return(32);

        case TextureFormat.RGB565:              //	 A 16 bit color texture format.
            return(16);

        case TextureFormat.DXT1:                // Compressed color texture format.
            return(4);

        case TextureFormat.DXT5:                // Compressed color with alpha channel texture format.
            return(8);

        /*
         * case TextureFormat.WiiI4:	// Wii texture format.
         * case TextureFormat.WiiI8:	// Wii texture format. Intensity 8 bit.
         * case TextureFormat.WiiIA4:	// Wii texture format. Intensity + Alpha 8 bit (4 + 4).
         * case TextureFormat.WiiIA8:	// Wii texture format. Intensity + Alpha 16 bit (8 + 8).
         * case TextureFormat.WiiRGB565:	// Wii texture format. RGB 16 bit (565).
         * case TextureFormat.WiiRGB5A3:	// Wii texture format. RGBA 16 bit (4443).
         * case TextureFormat.WiiRGBA8:	// Wii texture format. RGBA 32 bit (8888).
         * case TextureFormat.WiiCMPR:	//	 Compressed Wii texture format. 4 bits/texel, ~RGB8A1 (Outline alpha is not currently supported).
         *      return 0;  //Not supported yet
         */
        case TextureFormat.PVRTC_RGB2:        //	 PowerVR (iOS) 2 bits/pixel compressed color texture format.
            return(2);

        case TextureFormat.PVRTC_RGBA2:        //	 PowerVR (iOS) 2 bits/pixel compressed with alpha channel texture format
            return(2);

        case TextureFormat.PVRTC_RGB4:        //	 PowerVR (iOS) 4 bits/pixel compressed color texture format.
            return(4);

        case TextureFormat.PVRTC_RGBA4:        //	 PowerVR (iOS) 4 bits/pixel compressed with alpha channel texture format
            return(4);

        case TextureFormat.ETC_RGB4:        //	 ETC (GLES2.0) 4 bits/pixel compressed RGB texture format.
            return(4);

        case TextureFormat.ATC_RGB4:        //	 ATC (ATITC) 4 bits/pixel compressed RGB texture format.
            return(4);

        case TextureFormat.ATC_RGBA8:        //	 ATC (ATITC) 8 bits/pixel compressed RGB texture format.
            return(8);

        case TextureFormat.BGRA32:        //	 Format returned by iPhone camera
            return(32);

                        #if !UNITY_5
        case TextureFormat.ATF_RGB_DXT1: //	 Flash-specific RGB DXT1 compressed color texture format.
        case TextureFormat.ATF_RGBA_JPG: //	 Flash-specific RGBA JPG-compressed color texture format.
        case TextureFormat.ATF_RGB_JPG:  //	 Flash-specific RGB JPG-compressed color texture format.
            return(0);                   //Not supported yet
                        #endif
        }
        return(0);
    }
Example #43
0
 private static void Internal_Create([Writable] Texture3D mono, int w, int h, int d, TextureFormat format, bool mipmap)
 {
     if (!Texture3D.Internal_CreateImpl(mono, w, h, d, format, mipmap))
     {
         throw new UnityException("Failed to create texture because of invalid parameters.");
     }
 }
Example #44
0
        /// <summary>
        /// Extracts a DDS file's texture format and pixel data.
        /// </summary>
        private static void ExtractDDSTextureFormatAndData(DDSHeader header, UnityBinaryReader reader, out bool hasMipmaps, out uint DDSMipmapLevelCount, out TextureFormat textureFormat, out int bytesPerPixel, out byte[] textureData)
        {
            hasMipmaps = Utils.ContainsBitFlags(header.dwCaps, (uint)DDSCaps.Mipmap);
            hasMipmaps = hasMipmaps || header.dwMipMapCount > 1;
            // Non-mipmapped textures still have one mipmap level: the texture itself.
            DDSMipmapLevelCount = hasMipmaps ? header.dwMipMapCount : 1;


            // If the DDS file contains uncompressed data.
            if (Utils.ContainsBitFlags(header.pixelFormat.flags, (uint)DDSPixelFormatFlags.RGB))
            {
                // some permutation of RGB
                if (!Utils.ContainsBitFlags(header.pixelFormat.flags, (uint)DDSPixelFormatFlags.AlphaPixels))
                {
                    throw new NotImplementedException("Unsupported DDS file pixel format.");
                }
                // some permutation of RGBA
                else
                {
                    // There should be 32 bits per pixel.
                    if (header.pixelFormat.RGBBitCount != 32)
                    {
                        throw new FileFormatException("Invalid DDS file pixel format.");
                    }

                    // BGRA32
                    if ((header.pixelFormat.BBitMask == 0x000000FF) && (header.pixelFormat.GBitMask == 0x0000FF00) && (header.pixelFormat.RBitMask == 0x00FF0000) && (header.pixelFormat.ABitMask == 0xFF000000))
                    {
                        textureFormat = TextureFormat.BGRA32;
                        bytesPerPixel = 4;
                    }
                    // ARGB32
                    else if ((header.pixelFormat.ABitMask == 0x000000FF) && (header.pixelFormat.RBitMask == 0x0000FF00) && (header.pixelFormat.GBitMask == 0x00FF0000) && (header.pixelFormat.BBitMask == 0xFF000000))
                    {
                        textureFormat = TextureFormat.ARGB32;
                        bytesPerPixel = 4;
                    }
                    else
                    {
                        throw new NotImplementedException("Unsupported DDS file pixel format.");
                    }

                    if (!hasMipmaps)
                    {
                        textureData = new byte[header.dwPitchOrLinearSize * header.dwHeight];
                    }
                    else
                    {
                        // Create a data buffer to hold all mipmap levels down to 1x1.
                        textureData = new byte[TextureUtils.CalculateMipMappedTextureDataSize((int)header.dwWidth, (int)header.dwHeight, bytesPerPixel)];
                    }

                    reader.ReadRestOfBytes(textureData, 0);
                }
            }
            else if (StringUtils.Equals(header.pixelFormat.fourCC, "DXT1"))
            {
                textureFormat = TextureFormat.ARGB32;
                bytesPerPixel = 4;

                var compressedTextureData = reader.ReadRestOfBytes();
                textureData = DecodeDXT1ToARGB(compressedTextureData, header.dwWidth, header.dwHeight, header.pixelFormat, DDSMipmapLevelCount);
            }
            else if (StringUtils.Equals(header.pixelFormat.fourCC, "DXT3"))
            {
                textureFormat = TextureFormat.ARGB32;
                bytesPerPixel = 4;

                var compressedTextureData = reader.ReadRestOfBytes();
                textureData = DecodeDXT3ToARGB(compressedTextureData, header.dwWidth, header.dwHeight, header.pixelFormat, DDSMipmapLevelCount);
            }
            else if (StringUtils.Equals(header.pixelFormat.fourCC, "DXT5"))
            {
                textureFormat = TextureFormat.ARGB32;
                bytesPerPixel = 4;

                var compressedTextureData = reader.ReadRestOfBytes();
                textureData = DecodeDXT5ToARGB(compressedTextureData, header.dwWidth, header.dwHeight, header.pixelFormat, DDSMipmapLevelCount);
            }
            else
            {
                throw new NotImplementedException("Unsupported DDS file pixel format.");
            }
        }
        /// <summary>Creates a new Texture2D object based on an AtlasRegion.
        /// If applyImmediately is true, Texture2D.Apply is called immediately after the Texture2D is filled with data.</summary>
        public static Texture2D ToTexture(this AtlasRegion ar, bool applyImmediately = true, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps)
        {
            Texture2D sourceTexture = ar.GetMainTexture();
            Rect      r             = ar.GetUnityRect(sourceTexture.height);
            int       width         = (int)r.width;
            int       height        = (int)r.height;
            Texture2D output        = new Texture2D(width, height, textureFormat, mipmaps);

            output.name = ar.name;
            Color[] pixelBuffer = sourceTexture.GetPixels((int)r.x, (int)r.y, width, height);
            output.SetPixels(pixelBuffer);

            if (applyImmediately)
            {
                output.Apply();
            }

            return(output);
        }
        /// <summary>
        /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary>
        public static AtlasRegion ToAtlasRegionPMAClone(this Texture2D t, Shader shader, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps)
        {
            var material   = new Material(shader);
            var newTexture = t.GetClone(false, textureFormat, mipmaps);

            newTexture.ApplyPMA(true);

            newTexture.name = t.name + "-pma-";
            material.name   = t.name + shader.name;

            material.mainTexture = newTexture;
            var page = material.ToSpineAtlasPage();

            var region = newTexture.ToAtlasRegion(shader);

            region.page = page;

            return(region);
        }
Example #47
0
 public static extern bool IsValidTextureFormat(TextureFormat format);
Example #48
0
 public static extern bool ReformatTexture([NotNull("NullExceptionObject")] ref Texture2D texture, int width, int height, TextureFormat textureFormat, bool useMipmap, bool linear);
        /// <summary>
        /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data.</summary>
        public static AtlasRegion ToAtlasRegionPMAClone(this Sprite s, Shader shader, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps)
        {
            var material = new Material(shader);
            var tex      = s.ToTexture(false, textureFormat, mipmaps);

            tex.ApplyPMA(true);

            tex.name      = s.name + "-pma-";
            material.name = tex.name + shader.name;

            material.mainTexture = tex;
            var page = material.ToSpineAtlasPage();

            var region = s.ToAtlasRegion(true);

            region.page = page;

            return(region);
        }
Example #50
0
 public static extern bool IsCompressedTextureFormat(TextureFormat format);
        /// <summary>
        /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate texture of the Sprite's texture data. Returns a RegionAttachment that uses it. Use this if you plan to use a premultiply alpha shader such as "Spine/Skeleton"</summary>
        public static RegionAttachment ToRegionAttachmentPMAClone(this Sprite sprite, Shader shader, TextureFormat textureFormat = SpriteAtlasRegionExtensions.SpineTextureFormat, bool mipmaps = SpriteAtlasRegionExtensions.UseMipMaps)
        {
            if (sprite == null)
            {
                throw new System.ArgumentNullException("sprite");
            }
            if (shader == null)
            {
                throw new System.ArgumentNullException("shader");
            }
            var region        = sprite.ToAtlasRegionPMAClone(shader, textureFormat, mipmaps);
            var unitsPerPixel = 1f / sprite.pixelsPerUnit;

            return(region.ToRegionAttachment(sprite.name, unitsPerPixel));
        }
        public PlanarReflectionProbeCache(HDRenderPipelineAsset hdAsset, IBLFilterGGX iblFilter, int cacheSize, int probeSize, TextureFormat probeFormat, bool isMipmaped)
        {
            m_ConvertTextureMaterial = CoreUtils.CreateEngineMaterial(hdAsset.renderPipelineResources.blitCubeTextureFace);
            m_ConvertTextureMPB      = new MaterialPropertyBlock();

            // BC6H requires CPP feature not yet available
            probeFormat = TextureFormat.RGBAHalf;

            Debug.Assert(probeFormat == TextureFormat.BC6H || probeFormat == TextureFormat.RGBAHalf, "Reflection Probe Cache format for HDRP can only be BC6H or FP16.");

            m_ProbeSize    = probeSize;
            m_CacheSize    = cacheSize;
            m_TextureCache = new TextureCache2D("PlanarReflectionProbe");
            m_TextureCache.AllocTextureArray(cacheSize, probeSize, probeSize, probeFormat, isMipmaped);
            m_IBLFilterGGX = iblFilter;

            m_PerformBC6HCompression = probeFormat == TextureFormat.BC6H;

            InitializeProbeBakingStates();
        }
Example #53
0
 public Texture3D(int width, int height, int depth, TextureFormat format, bool mipmap)
 {
     Texture3D.Internal_Create(this, width, height, depth, format, mipmap);
 }
Example #54
0
 public static extern bool ReformatCubemap([NotNull("NullExceptionObject")] Cubemap cubemap, int width, int height, TextureFormat textureFormat, bool useMipmap, bool linear);
Example #55
0
 /// <summary>
 /// Determines whether a given
 /// [`TextureFormat`](https://docs.unity3d.com/ScriptReference/TextureFormat.html) is supported for image
 /// conversion.
 /// </summary>
 /// <param name="image">The <see cref="XRCpuImage"/> to convert.</param>
 /// <param name="format">The [`TextureFormat`](https://docs.unity3d.com/ScriptReference/TextureFormat.html)
 ///     to test.</param>
 /// <returns>Returns `true` if <paramref name="image"/> can be converted to <paramref name="format"/>.
 ///     Returns `false` otherwise.</returns>
 public virtual bool FormatSupported(XRCpuImage image, TextureFormat format) => false;
Example #56
0
 private static extern bool Internal_CreateImpl([Writable] Texture3D mono, int w, int h, int d, TextureFormat format, bool mipmap);
Example #57
0
        public static Sprite Load9SliceSprite(string path, RectOffset slices, Vector2 pivot = new Vector2(), TextureFormat format = TextureFormat.BC7, float pixelsPerUnit = 100f, SpriteMeshType spriteType = SpriteMeshType.Tight)
        {
            string spriteKey = path + slices;

            if (spriteCache.TryGetValue(spriteKey, out Sprite foundSprite))
            {
                return(foundSprite);
            }

            Texture2D texture2D = SMLHelper.V2.Utility.ImageUtils.LoadTextureFromFile(path, format);

            if (!texture2D)
            {
                return(null);
            }
            var    border = new Vector4(slices.left, slices.right, slices.top, slices.bottom);
            Sprite sprite = TextureToSprite(texture2D, pivot, pixelsPerUnit, spriteType, border);

            spriteCache.Add(spriteKey, sprite);
            return(sprite);
        }
Example #58
0
 /// <summary>
 /// Method to be implemented by the provider to get the number of bytes required to store an image with the
 /// given dimensions and <c>TextureFormat</c>.
 /// </summary>
 /// <param name="nativeHandle">A unique identifier for the camera image to convert.</param>
 /// <param name="dimensions">The dimensions of the output image.</param>
 /// <param name="format">The <c>TextureFormat</c> for the image.</param>
 /// <param name="size">The number of bytes required to store the converted image.</param>
 /// <returns><c>true</c> if the output <paramref name="size"/> was set.</returns>
 /// <exception cref="System.NotSupportedException">Thrown if the implementation does not support camera image conversion.</exception>
 public virtual bool TryGetConvertedDataSize(int nativeHandle, Vector2Int dimensions, TextureFormat format, out int size)
 {
     throw new NotSupportedException("Camera image conversion is not supported by this implementation");
 }
Example #59
0
 private static extern void Internal_Create([Writable] Texture3D mono, int width, int height, int depth, TextureFormat format, bool mipmap);
Example #60
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            ctx.DependsOnCustomDependency("HLODSystemPlatform");

            var buildTargetGroup = BuildPipeline.GetBuildTargetGroup(ctx.selectedBuildTarget);

            try
            {
                UpdateProgress(ctx.assetPath, 0, 1);
                using (Stream stream = new FileStream(ctx.assetPath, FileMode.Open, FileAccess.Read))
                {
                    HLODData      data           = HLODDataSerializer.Read(stream);
                    RootData      rootData       = RootData.CreateInstance <RootData>();
                    TextureFormat compressFormat = GetCompressFormat(data, buildTargetGroup);

                    int currentProgress = 0;
                    int maxProgress     = 0;

                    if (data.GetMaterials() != null)
                    {
                        maxProgress += data.GetMaterials().Count;
                    }
                    if (data.GetObjects() != null)
                    {
                        maxProgress += data.GetObjects().Count;
                    }
                    if (data.GetColliders() != null)
                    {
                        maxProgress += data.GetColliders().Count;
                    }

                    rootData.name = "Root";

                    var serializableMaterials = data.GetMaterials();
                    var loadedMaterials       = new Dictionary <string, Material>();
                    if (serializableMaterials != null)
                    {
                        for (int mi = 0; mi < serializableMaterials.Count; ++mi)
                        {
                            UpdateProgress(ctx.assetPath, currentProgress++, maxProgress);
                            var sm = serializableMaterials[mi];

                            if (loadedMaterials.ContainsKey(sm.ID))
                            {
                                continue;
                            }

                            Material mat = sm.To();
                            loadedMaterials.Add(sm.ID, mat);

                            if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(mat)) == false)
                            {
                                continue;
                            }

                            ctx.AddObjectToAsset(mat.name, mat);

                            for (int ti = 0; ti < sm.GetTextureCount(); ++ti)
                            {
                                HLODData.SerializableTexture st = sm.GetTexture(ti);
                                Texture2D texture = st.To();
                                EditorUtility.CompressTexture(texture, compressFormat,
                                                              TextureCompressionQuality.Normal);

                                mat.SetTexture(st.Name, texture);
                                ctx.AddObjectToAsset(texture.name, texture);
                            }

                            mat.EnableKeyword("_NORMALMAP");
                        }
                    }

                    var serializableObjects   = data.GetObjects();
                    var serializableColliders = data.GetColliders();
                    Dictionary <string, List <GameObject> >
                    createdGameObjects = new Dictionary <string, List <GameObject> >();
                    Dictionary <string, GameObject> createdColliders = new Dictionary <string, GameObject>();

                    if (serializableObjects != null)
                    {
                        for (int oi = 0; oi < serializableObjects.Count; ++oi)
                        {
                            UpdateProgress(ctx.assetPath, currentProgress++, maxProgress);

                            var        so = serializableObjects[oi];
                            GameObject go = new GameObject();
                            go.name = so.Name;

                            MeshFilter      mf          = go.AddComponent <MeshFilter>();
                            MeshRenderer    mr          = go.AddComponent <MeshRenderer>();
                            List <string>   materialIds = so.GetMaterialIds();
                            List <Material> materials   = new List <Material>();

                            for (int mi = 0; mi < materialIds.Count; ++mi)
                            {
                                string id = materialIds[mi];
                                if (loadedMaterials.ContainsKey(id))
                                {
                                    materials.Add(loadedMaterials[id]);
                                }
                                else
                                {
                                    string path = AssetDatabase.GUIDToAssetPath(id);
                                    if (string.IsNullOrEmpty(path) == false)
                                    {
                                        materials.Add(AssetDatabase.LoadAssetAtPath <Material>(path));
                                    }
                                    else
                                    {
                                        materials.Add(null);
                                    }
                                }
                            }

                            Mesh mesh = so.GetMesh().To();
                            mf.sharedMesh      = mesh;
                            mr.sharedMaterials = materials.ToArray();

                            ctx.AddObjectToAsset(mesh.name, mesh);

                            if (createdGameObjects.ContainsKey(go.name) == false)
                            {
                                createdGameObjects.Add(go.name, new List <GameObject>());
                            }

                            createdGameObjects[go.name].Add(go);
                        }
                    }

                    if (serializableColliders != null)
                    {
                        for (int ci = 0; ci < serializableColliders.Count; ++ci)
                        {
                            UpdateProgress(ctx.assetPath, currentProgress++, maxProgress);

                            var        sc = serializableColliders[ci];
                            GameObject go;

                            if (createdColliders.ContainsKey(sc.Name) == false)
                            {
                                createdColliders[sc.Name] = new GameObject("Collider");
                            }

                            go = createdColliders[sc.Name];

                            var collider = sc.CreateGameObject();
                            if (collider != null)
                            {
                                collider.name = "Collider" + ci;
                                collider.transform.SetParent(go.transform, true);
                            }
                        }
                    }

                    foreach (var objects in createdGameObjects.Values)
                    {
                        GameObject root;
                        if (objects.Count > 1)
                        {
                            root      = new GameObject();
                            root.name = objects[0].name;
                            for (int i = 0; i < objects.Count; ++i)
                            {
                                objects[i].name = objects[i].name + "_" + i;
                                objects[i].transform.SetParent(root.transform, true);
                            }
                        }
                        else
                        {
                            root = objects[0];
                        }

                        if (createdColliders.ContainsKey(root.name))
                        {
                            createdColliders[root.name].transform.SetParent(root.transform, true);
                        }

                        rootData.SetRootObject(root.name, root);
                        ctx.AddObjectToAsset(root.name, root);
                    }

                    ctx.AddObjectToAsset("Root", rootData);
                    ctx.SetMainObject(rootData);
                }
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }
        }