LoadRawTextureData() public method

Fills texture pixels with raw preformatted data.

public LoadRawTextureData ( IntPtr data, int size ) : void
data IntPtr Byte array to initialize texture pixels with.
size int Size of data in bytes.
return void
コード例 #1
1
            // Ripped from Kopernicus.Utility.cs
            public static Texture2D LoadTexture(string path, bool compress, bool upload, bool unreadable)
            {
                Texture2D map = null;
                path = KSPUtil.ApplicationRootPath + "GameData/" + path;
                if (System.IO.File.Exists(path))
                {
                    bool uncaught = true;
                    try
                    {
                        if (path.ToLower().EndsWith(".dds"))
                        {
                            // Borrowed from stock KSP 1.0 DDS loader (hi Mike!)
                            // Also borrowed the extra bits from Sarbian.
                            byte[] buffer = System.IO.File.ReadAllBytes(path);
                            System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(new System.IO.MemoryStream(buffer));
                            uint num = binaryReader.ReadUInt32();
                            if (num == DDSHeaders.DDSValues.uintMagic)
                            {

                                DDSHeaders.DDSHeader dDSHeader = new DDSHeaders.DDSHeader(binaryReader);

                                if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDX10)
                                {
                                    new DDSHeaders.DDSHeaderDX10(binaryReader);
                                }

                                bool alpha = (dDSHeader.dwFlags & 0x00000002) != 0;
                                bool fourcc = (dDSHeader.dwFlags & 0x00000004) != 0;
                                bool rgb = (dDSHeader.dwFlags & 0x00000040) != 0;
                                bool alphapixel = (dDSHeader.dwFlags & 0x00000001) != 0;
                                bool luminance = (dDSHeader.dwFlags & 0x00020000) != 0;
                                bool rgb888 = dDSHeader.ddspf.dwRBitMask == 0x000000ff && dDSHeader.ddspf.dwGBitMask == 0x0000ff00 && dDSHeader.ddspf.dwBBitMask == 0x00ff0000;
                                //bool bgr888 = dDSHeader.ddspf.dwRBitMask == 0x00ff0000 && dDSHeader.ddspf.dwGBitMask == 0x0000ff00 && dDSHeader.ddspf.dwBBitMask == 0x000000ff;
                                bool rgb565 = dDSHeader.ddspf.dwRBitMask == 0x0000F800 && dDSHeader.ddspf.dwGBitMask == 0x000007E0 && dDSHeader.ddspf.dwBBitMask == 0x0000001F;
                                bool argb4444 = dDSHeader.ddspf.dwABitMask == 0x0000f000 && dDSHeader.ddspf.dwRBitMask == 0x00000f00 && dDSHeader.ddspf.dwGBitMask == 0x000000f0 && dDSHeader.ddspf.dwBBitMask == 0x0000000f;
                                bool rbga4444 = dDSHeader.ddspf.dwABitMask == 0x0000000f && dDSHeader.ddspf.dwRBitMask == 0x0000f000 && dDSHeader.ddspf.dwGBitMask == 0x000000f0 && dDSHeader.ddspf.dwBBitMask == 0x00000f00;

                                bool mipmap = (dDSHeader.dwCaps & DDSHeaders.DDSPixelFormatCaps.MIPMAP) != (DDSHeaders.DDSPixelFormatCaps)0u;
                                bool isNormalMap = ((dDSHeader.ddspf.dwFlags & 524288u) != 0u || (dDSHeader.ddspf.dwFlags & 2147483648u) != 0u);
                                if (fourcc)
                                {
                                    if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT1)
                                    {
                                        map = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT1, mipmap);
                                        map.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                                    }
                                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT3)
                                    {
                                        map = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, (TextureFormat)11, mipmap);
                                        map.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                                    }
                                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT5)
                                    {
                                        map = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT5, mipmap);
                                        map.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                                    }
                                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT2)
                                    {
                                        Debug.Log("[Kopernicus]: DXT2 not supported" + path);
                                    }
                                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT4)
                                    {
                                        Debug.Log("[Kopernicus]: DXT4 not supported: " + path);
                                    }
                                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDX10)
                                    {
                                        Debug.Log("[Kopernicus]: DX10 dds not supported: " + path);
                                    }
                                    else
                                        fourcc = false;
                                }
                                if (!fourcc)
                                {
                                    TextureFormat textureFormat = TextureFormat.ARGB32;
                                    bool ok = true;
                                    if (rgb && (rgb888 /*|| bgr888*/))
                                    {
                                        // RGB or RGBA format
                                        textureFormat = alphapixel
                                        ? TextureFormat.RGBA32
                                        : TextureFormat.RGB24;
                                    }
                                    else if (rgb && rgb565)
                                    {
                                        // Nvidia texconv B5G6R5_UNORM
                                        textureFormat = TextureFormat.RGB565;
                                    }
                                    else if (rgb && alphapixel && argb4444)
                                    {
                                        // Nvidia texconv B4G4R4A4_UNORM
                                        textureFormat = TextureFormat.ARGB4444;
                                    }
                                    else if (rgb && alphapixel && rbga4444)
                                    {
                                        textureFormat = TextureFormat.RGBA4444;
                                    }
                                    else if (!rgb && alpha != luminance)
                                    {
                                        // A8 format or Luminance 8
                                        textureFormat = TextureFormat.Alpha8;
                                    }
                                    else
                                    {
                                        ok = false;
                                        Debug.Log("[Kopernicus]: Only DXT1, DXT5, A8, RGB24, RGBA32, RGB565, ARGB4444 and RGBA4444 are supported");
                                    }
                                    if (ok)
                                    {
                                        map = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, textureFormat, mipmap);
                                        map.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                                    }

                                }
                                if (map != null)
                                    if (upload)
                                        map.Apply(false, unreadable);
                            }
                            else
                                Debug.Log("[Kopernicus]: Bad DDS header.");
                        }
                        else
                        {
                            map = new Texture2D(2, 2);
                            map.LoadImage(System.IO.File.ReadAllBytes(path));
                            if (compress)
                                map.Compress(true);
                            if (upload)
                                map.Apply(false, unreadable);
                        }
                    }
                    catch (Exception e)
                    {
                        uncaught = false;
                        Debug.Log("[Kopernicus]: failed to load " + path + " with exception " + e.Message);
                    }
                    if (map == null && uncaught)
                    {
                        Debug.Log("[Kopernicus]: failed to load " + path);
                    }
                    map.name = path.Remove(0, (KSPUtil.ApplicationRootPath + "GameData/").Length);
                }
                else
                    Debug.Log("[Kopernicus]: texture does not exist! " + path);

                return map;
            }
コード例 #2
1
ファイル: Main.cs プロジェクト: Lindet/DiabloClickerWiP
    void ReadDDS(string path, bool alpha)
    {
        /*
         * Метод для чтения изначально "выдранных" из Diablo 3 dds файлов, которые Unity отказывается считывать правильно - появляется сдвиг на 32 пикселя вправо, а сама картинка перевернута.
         * Кроме того, файлы, в которых объедененны несколько спрайтов, имеют при себе txt файл с набором "Имя" - "Координаты", благодаря которым можно порезать файл на отдельные спрайты.
         */
        int height, width;
        using (var br = new BinaryReader(File.Open(path, FileMode.Open)))
        {
            br.ReadBytes(12);
            height = BitConverter.ToInt32(br.ReadBytes(4), 0);
            width = BitConverter.ToInt32(br.ReadBytes(4), 0);
            br.ReadBytes(64);

            var type = Encoding.UTF8.GetString(br.ReadBytes(4));

            if (type != "DXT5" && type != "DXT3") return;
        }

        var bytes = File.ReadAllBytes(path);
        var texture = new Texture2D((int) width, (int) height, TextureFormat.DXT5, false);
        var nonflippedtexture = new Texture2D(texture.width, texture.height);
        texture.LoadRawTextureData(bytes.ToArray());
        for (int i = 0; i < texture.width; i++)
        {
            for (int j = 0; j < texture.height; j++)
            {
                var pixel = texture.GetPixel(i, j);
                nonflippedtexture.SetPixel(i, j, pixel);
            }
        }
        nonflippedtexture.Apply();
        var flippedtexture = new Texture2D(texture.width, texture.height);
        for (int i = 0; i < texture.width; i++)
        {
            for (int j = 0; j < texture.height; j++)
            {
                var pixel = texture.GetPixel(i, j);
                if (alpha)
                    pixel.a = 1;
                if (i >= 31)
                    flippedtexture.SetPixel(i - 31, texture.height - 1 - j, pixel);
                else
                {
                    flippedtexture.SetPixel(width - 1 - (31 - i), texture.height - j, pixel);
                }
            }
        }

        for (int i = flippedtexture.width - 31; i < flippedtexture.width; i++)
        {
            var arr = flippedtexture.GetPixels(i, 0, 1, flippedtexture.height);
            var flippedArray = new Texture2D(1, flippedtexture.height).GetPixels();
            Array.Copy(arr, 0, flippedArray, 3, arr.Length - 3);
            Array.Copy(arr, arr.Length - 3, flippedArray, 0, 3);
            flippedtexture.SetPixels(i, 0, 1, flippedtexture.height, flippedArray);
        }

        flippedtexture.Apply();

        using (var br = new BinaryWriter(new FileStream(path.Replace(".dds", "_flipped.png"), FileMode.OpenOrCreate)))
        {
            br.Write(flippedtexture.EncodeToPNG());
        }

        if (File.Exists(path.Replace(".dds", "_atlas.txt")))
        {
            using (var sr = new StreamReader(path.Replace(".dds", "_atlas.txt")))
            {
                sr.ReadLine();
                while (!sr.EndOfStream)
                {
                    var FirstLine = sr.ReadLine().Split('\t');
                    var tex = new Texture2D(int.Parse(FirstLine[7]) - (int.Parse(FirstLine[5]) + 1), int.Parse(FirstLine[8]) - (int.Parse(FirstLine[6]) + 2));
                    int x = 0;
                    for (int i = int.Parse(FirstLine[5]) + 1; i <= int.Parse(FirstLine[7]); i++)
                    {
                        int y = 0;
                        for (int j = int.Parse(FirstLine[6]) + 1; j < int.Parse(FirstLine[8]); j++)
                        {
                            var color = flippedtexture.GetPixel(i, flippedtexture.height - j);
                            tex.SetPixel(x, tex.height - y, color);
                            y++;
                        }
                        x++;
                    }
                    tex.Apply();
                    using (var br = new BinaryWriter(new FileStream(FirstLine[0] + ".png", FileMode.OpenOrCreate)))
                    {
                        br.Write(tex.EncodeToPNG());
                    }
                }
            }
        }
    }
コード例 #3
0
    static int LoadRawTextureData(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Texture2D), typeof(byte[])))
            {
                UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.ToObject(L, 1);
                byte[] arg0 = ToLua.CheckByteBuffer(L, 2);
                obj.LoadRawTextureData(arg0);
                return(0);
            }
            else if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Texture2D), typeof(System.IntPtr), typeof(int)))
            {
                UnityEngine.Texture2D obj  = (UnityEngine.Texture2D)ToLua.ToObject(L, 1);
                System.IntPtr         arg0 = (System.IntPtr)LuaDLL.lua_touserdata(L, 2);
                int arg1 = (int)LuaDLL.lua_tonumber(L, 3);
                obj.LoadRawTextureData(arg0, arg1);
                return(0);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Texture2D.LoadRawTextureData"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
コード例 #4
0
 public static Texture2D createTextureFromArray(byte[] imgArray, int width, int height)
 {
     UnityEngine.Texture2D tex = new UnityEngine.Texture2D(width, height, UnityEngine.TextureFormat.RGBA32, false);
     tex.LoadRawTextureData(imgArray);
     tex.Apply();
     return(tex);
 }
コード例 #5
0
        public static TextureInfoWrapper DDSToTexture(UrlDir.UrlFile file, TexInfo Texture, bool mipmaps, bool isCompressed, bool hasAlpha)
        {
            TextureConverter.InitImageBuffer();
            FileStream imgStream = new FileStream(Texture.filename, FileMode.Open, FileAccess.Read);
            imgStream.Position = 0;
            imgStream.Read(imageBuffer, 0, MAX_IMAGE_SIZE);
            imgStream.Close();

            TextureFormat format = TextureFormat.DXT1;
            if(hasAlpha && isCompressed)
            {
                format = TextureFormat.DXT5;
            }
            else if(hasAlpha)
            {
                format = TextureFormat.RGBA32;
            }
            else if(!isCompressed)
            {
                format = TextureFormat.RGB24;
            }

            Texture2D newTex = new Texture2D(Texture.width, Texture.height, format, mipmaps);

            newTex.LoadRawTextureData(imageBuffer);
            newTex.Apply(false, Texture.makeNotReadable);
            newTex.name = Texture.name;

            TextureInfoWrapper newTexInfo = new TextureInfoWrapper(file, newTex, Texture.isNormalMap, !Texture.makeNotReadable, isCompressed);
            newTexInfo.name = Texture.name;
            return newTexInfo;
        }
コード例 #6
0
    void loadImage(string name)
    {
        using (BinaryReader b = new BinaryReader(File.Open(name, FileMode.Open,FileAccess.Read,FileShare.Read)))
        {
            // 2.
            // Position and length variables.
            int i = 0;
            // Use BaseStream.
            int length = (int)b.BaseStream.Length;
            int w= b.ReadInt32(),h= b.ReadInt32(),format =  b.ReadInt32();

            texture = new Texture2D (w,h,TextureFormat.RFloat,false);

            byte[] data = b.ReadBytes(w*h*format*4);

            Debug.Log("Read Ima "+data.Length);
            texture.LoadRawTextureData(data);
            texture.Apply();
            Debug.Log ("Channels "+texture.format);
            ccc.callbackLoadImage(w,h);
        }

        GetComponent<Renderer> ().material.mainTexture = texture;
        // GetComponent<Renderer> ().material.SetTexture (2, texture);
        Debug.Log ("Channels "+texture.format);
    }
コード例 #7
0
 static public int LoadRawTextureData(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 2)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Byte[]         a1;
             checkArray(l, 2, out a1);
             self.LoadRawTextureData(a1);
             pushValue(l, true);
             return(1);
         }
         else if (argc == 3)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.IntPtr         a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             self.LoadRawTextureData(a1, a2);
             pushValue(l, true);
             return(1);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
コード例 #8
0
        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);
        }
コード例 #9
0
    // Update is called once per frame
    void Update()
    {
        MetaCoreInterop.meta_get_point_cloud(ref _metaPointCloud, _translation, _rotation);
        //Added by Yuqi Ding

        MetaCoreInterop.meta_get_rgb_frame(RawPixelBuffer, _translation, _new_rotation);  // The buffer is pre-allocated by constructor.

        // Check for a difference
        bool isEqual = true;

        // Check for a difference in pose (should change with each new RGB frame).
        for (int i = 0; i < _new_rotation.Length; ++i)
        {
            isEqual = _rotation[i] == _new_rotation[i];

            if (!isEqual)
            {
                break;
            }
        }

        // If the two rotations are not equal, we have a new rgb frame.
        if (!isEqual)
        {
            // Copy new rotation if it's different.
            for (int i = 0; i < _new_rotation.Length; ++i)
            {
                _rotation[i] = _new_rotation[i];
            }

            _rgbTexture.LoadRawTextureData(RawPixelBuffer, _totalBufferSize);
            _rgbTexture.Apply();
            if (Time.frameCount % 48 == 0)
            {
                byte[] bytes   = _rgbTexture.EncodeToPNG();
                string rgbname = string.Format("{0}/{1:D04} shot.png", folder, Time.frameCount);
                File.WriteAllBytes(rgbname, bytes);
            }
        }
        // Added end

        SetDepthToWorldTransform();

        if (SavePointCloud && (Time.frameCount % 48 == 0))
        {
            MarshalMetaPointCloud();
            //UpdateMesh();
            int num = _metaPointCloud.num_points;
            Debug.Log(_translation[0].ToString());
            Debug.Log(_translation[1].ToString());
            Debug.Log(_translation[2].ToString());
            if (num != 0)
            {
                string Name1 = string.Format("{0}/{1:D04} shot.ply", folder, Time.frameCount);
                SavePointCloudToPly(Name1, _pointCloud);
            }
        }
    }
コード例 #10
0
 Texture2D createTexture(vectorx.ColorStorage storage)
 {
     var texture = new Texture2D(storage.width, storage.height, TextureFormat.RGBA32, false);
     storage.data.memory.Seek (0, System.IO.SeekOrigin.Begin);
     var bytes = storage.data.memory.ToArray ();
     texture.LoadRawTextureData (bytes);
     texture.Apply ();
     return texture;
 }
コード例 #11
0
ファイル: UIManager.cs プロジェクト: rickbarraza/01_DXNR
    void CreateTextureLocally()
    {
        FillTextureDataLocally();
        processedTexture = new Texture2D(512, 424, TextureFormat.BGRA32, false);
        processedTexture.filterMode = FilterMode.Point;
        processedTexture.LoadRawTextureData(textureData);

        processedTexture.Apply();
        riOutput.texture = processedTexture;
    }
コード例 #12
0
    public static void Create(Texture2D texture)
    {
        var map = texture.GetRawTextureData();
        if (texture.name == "hoge")
        {
            var alpha = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
            var j = 0;
            var png = new byte[map.Length];
            for(var i = 0; i < map.Length; i += 4)
            {
                png[i]   = 0;
                png[i+1] = 0;
                png[i+2] = 0;
                png[i+3] = map[i];

                if (j == texture.width)
                {
                    j = -1;
                }
                j ++;
            }
            Debug.Log(alpha.width + ", " + alpha.height);
            Debug.Log(map.Length + " - " + png.Length);
            alpha.LoadRawTextureData(png);
            alpha.Apply();
            var pngData = alpha.EncodeToPNG();
            string filePath = EditorUtility.SaveFilePanel("Save Texture", "", "alphaMap.png", "png");
            if (filePath.Length > 0) {
                // pngファイル保存.
                File.WriteAllBytes(filePath, pngData);
            }
        }

        using (Stream stream = File.OpenWrite("Assets/Resources/AlphaMap/" + texture.name + ".bytes")) {
            using (var writer = new BinaryWriter(stream)) {
                writer.Write((uint)texture.width);
                writer.Write((uint)texture.height);
                for (var i = 0; i < map.Length; i += 4 * 8)
                {
                    int j = i + 4, k = i + 8, l = i + 12, m = i + 16, n = i + 20, o = i + 24, p = i + 28;
                    byte b = (byte)(
                        128 * Bit(map, p)+
                        64  * Bit(map, o)+
                        32  * Bit(map, n)+
                        16  * Bit(map, m)+
                        8   * Bit(map, l)+
                        4   * Bit(map, k)+
                        2   * Bit(map, j)+
                        1   * Bit(map, i));
                    writer.Write(b);
                }
            }
        }
    }
コード例 #13
0
        public static Texture2D createTexture(string path, int width, int height, int pixres)
        {
            UnityEngine.Texture2D tex = new UnityEngine.Texture2D(width, height, UnityEngine.TextureFormat.RGBA32, false);

            byte[] imgArray = File.ReadAllBytes(path);


            tex.LoadRawTextureData(imgArray);
            tex.Apply();
            return(tex);
        }
コード例 #14
0
	/// <summary>
	/// Creates a Unity Texture2D from this Texture2DInfo. Can only be called from the main thread.
	/// </summary>
	public Texture2D ToTexture2D()
	{
		var texture = new Texture2D(width, height, format, hasMipmaps);

		if(rawData != null)
		{
			texture.LoadRawTextureData(rawData);
			texture.Apply();
		}
		
		return texture;
	}
コード例 #15
0
 static public int LoadRawTextureData(IntPtr l)
 {
     try {
         UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
         System.Byte[]         a1;
         checkArray(l, 2, out a1);
         self.LoadRawTextureData(a1);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
コード例 #16
0
 static public int LoadRawTextureData(IntPtr l)
 {
     try{
         UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
         System.Byte[]         a1;
         checkType(l, 2, out a1);
         self.LoadRawTextureData(a1);
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
コード例 #17
0
 static public int LoadRawTextureData(IntPtr l)
 {
     try {
                     #if DEBUG
         var    method     = System.Reflection.MethodBase.GetCurrentMethod();
         string methodName = GetMethodName(method);
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.BeginSample(methodName);
                     #else
         Profiler.BeginSample(methodName);
                     #endif
                     #endif
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 2)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Byte[]         a1;
             checkArray(l, 2, out a1);
             self.LoadRawTextureData(a1);
             pushValue(l, true);
             return(1);
         }
         else if (argc == 3)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.IntPtr         a1;
             checkType(l, 2, out a1);
             System.Int32 a2;
             checkType(l, 3, out a2);
             self.LoadRawTextureData(a1, a2);
             pushValue(l, true);
             return(1);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function LoadRawTextureData to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
             #if DEBUG
     finally {
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.EndSample();
                     #else
         Profiler.EndSample();
                     #endif
     }
             #endif
 }
コード例 #18
0
 static int LoadRawTextureData(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.CheckObject(L, 1, typeof(UnityEngine.Texture2D));
         byte[] arg0 = ToLua.CheckByteBuffer(L, 2);
         obj.LoadRawTextureData(arg0);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
コード例 #19
0
 public static int LoadRawTextureData_wrap(long L)
 {
     try
     {
         long nThisPtr             = FCLibHelper.fc_get_inport_obj_ptr(L);
         UnityEngine.Texture2D obj = get_obj(nThisPtr);
         byte[] arg0 = null;
         arg0 = FCCustomParam.GetArray(ref arg0, L, 0);
         obj.LoadRawTextureData(arg0);
     }
     catch (Exception e)
     {
         Debug.LogException(e);
     }
     return(0);
 }
コード例 #20
0
    // Start is called before the first frame update
    public static void ImportDefaultTextures()
    {
        var assetManager = new AssetStudio.AssetsManager();

        assetManager.LoadFiles(PhysicalFileSystem.Instance, Path.Combine(ConfigManager.AssetBundleSourcePath, "texture.ab"));

        var textures = assetManager.assetsFileList[0].Objects.OfType <AssetStudio.Texture2D>().ToArray();

        if (textures.Length <= 0)
        {
            throw new Exception("Couldn't read default textures.");
        }

        try
        {
            for (int i = 0; i < textures.Length; i++)
            {
                var texture = textures[i];
                EditorUtility.DisplayProgressBar("Texture import", "Importing default textures",
                                                 (float)i / textures.Length);

                var textureData       = texture.image_data.GetData();
                var compressedTexture = new UnityEngine.Texture2D(texture.m_Width, texture.m_Height,
                                                                  (UnityEngine.TextureFormat)texture.m_TextureFormat, false);
                compressedTexture.LoadRawTextureData(textureData);
                compressedTexture.Apply(true);
                var pixels = compressedTexture.GetPixels32();

                // We need to create an uncompressed texture to use ImageConversion.EncodeToPNG()
                var uncompressedTexture = new UnityEngine.Texture2D(texture.m_Width, texture.m_Height,
                                                                    UnityEngine.TextureFormat.RGBA32, false);
                uncompressedTexture.SetPixels32(pixels);

                var pngData = UnityEngine.ImageConversion.EncodeToPNG(uncompressedTexture);

                string path = $"Assets/Resources/DefaultTextures/{texture.m_Name}.png";
                File.WriteAllBytes(path, pngData);
                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
                UnityEngine.Object.DestroyImmediate(compressedTexture);
                UnityEngine.Object.DestroyImmediate(uncompressedTexture);
            }
        }
        finally
        {
            EditorUtility.ClearProgressBar();
        }
    }
コード例 #21
0
 public static int LoadRawTextureData1_wrap(long L)
 {
     try
     {
         long nThisPtr             = FCLibHelper.fc_get_inport_obj_ptr(L);
         UnityEngine.Texture2D obj = get_obj(nThisPtr);
         IntPtr arg0 = new IntPtr();
         FCLibHelper.fc_get_void_ptr(L, 0, ref arg0);
         int arg1 = FCLibHelper.fc_get_int(L, 1);
         obj.LoadRawTextureData(arg0, arg1);
     }
     catch (Exception e)
     {
         Debug.LogException(e);
     }
     return(0);
 }
コード例 #22
0
    public static Texture2D LoadDDSManual(string ddsPath)
    {
        try
        {

            byte[] ddsBytes = File.ReadAllBytes(ddsPath);

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

            int height = ddsBytes[13] * 256 + ddsBytes[12];
            int width = ddsBytes[17] * 256 + ddsBytes[16];

            byte DXTType = ddsBytes[87];
            TextureFormat textureFormat = TextureFormat.DXT5;
            if (DXTType == 49)
            {
                textureFormat = TextureFormat.DXT1;
                //	Debug.Log ("DXT1");
            }

            if (DXTType == 53)
            {
                textureFormat = TextureFormat.DXT5;
                //	Debug.Log ("DXT5");
            }
            int DDS_HEADER_SIZE = 128;
            byte[] dxtBytes = new byte[ddsBytes.Length - DDS_HEADER_SIZE];
            Buffer.BlockCopy(ddsBytes, DDS_HEADER_SIZE, dxtBytes, 0, ddsBytes.Length - DDS_HEADER_SIZE);

            System.IO.FileInfo finf = new System.IO.FileInfo(ddsPath);
            Texture2D texture = new Texture2D(width, height, textureFormat, false);
            texture.LoadRawTextureData(dxtBytes);
            texture.Apply();
            texture.name = finf.Name;

            return (texture);
        }
        catch (System.Exception ex)
        {
            Debug.LogError("Error: Could not load DDS");
            return new Texture2D(8, 8);
        }
    }
コード例 #23
0
ファイル: TestSquish.cs プロジェクト: nobnak/LibsquishNet
    // Use this for initialization
    void Start()
    {
        int width = srcTex.width;
        int height = srcTex.height;
        int blockSize = Squish.Squish.GetStorageRequirements(width, height, (int)Squish.Squish.Flags.kDxt1);

        byte[] block = new byte[blockSize];
        byte[] rgba = new byte[width * height * 4];
        var srcColors = srcTex.GetPixels32();
        for (var y = 0; y < height; y++) {
            for (var x = 0; x < width; x++) {
                var index = 4 * (x + y * width);
                var c = srcColors[x + y * width];
                rgba[index]		= c.r;
                rgba[index + 1] = c.g;
                rgba[index + 2] = c.b;
                rgba[index + 3] = c.a;
            }
        }

        var startTime = Time.realtimeSinceStartup;
        var ptrRgba = Marshal.AllocHGlobal(rgba.Length);
        var ptrBlock = Marshal.AllocHGlobal(block.Length);
        try {
            Marshal.Copy(rgba, 0, ptrRgba, rgba.Length);
            for (var i = 0; i < 10; i++)
                Squish.Squish.CompressImage(ptrRgba, width, height, ptrBlock, (int)Squish.Squish.Flags.kDxt1);
            Marshal.Copy(ptrBlock, block, 0, block.Length);
        } finally {
            Marshal.FreeHGlobal(ptrRgba);
            Marshal.FreeHGlobal(ptrBlock);
        }
        var endTime = Time.realtimeSinceStartup;
        Debug.Log("Elapsed : " + (endTime - startTime));

        _dstTex = new Texture2D(width, height, TextureFormat.DXT1, false);
        _dstTex.LoadRawTextureData(block);
        //_dstTex.filterMode = FilterMode.Point;
        _dstTex.Apply(false);

        target.mainTexture = _dstTex;

        Debug.Log(string.Format("Texture format={0} size={1} original={2}", _dstTex.format, blockSize, rgba.Length));
    }
コード例 #24
0
ファイル: Texture2DExt.cs プロジェクト: sonygod/webp-unity3d
        /// <summary>
        /// 
        /// </summary>
        /// <param name="lData"></param>
        /// <param name="lError"></param>
        /// <returns></returns>
        public static unsafe Texture2D CreateTexture2DFromWebP(byte[] lData, bool lMipmaps, bool lLinear, out Error lError, ScalingFunction scalingFunction = null )
        {
            lError = 0;
            Texture2D lTexture2D = null;
            int lWidth = 0, lHeight = 0;

            GetWebPDimensions(lData, out lWidth, out lHeight);

            byte[] lRawData = LoadRGBAFromWebP(lData, ref lWidth, ref lHeight, lMipmaps, out lError, scalingFunction);

            if (lError == Error.Success)
            {
                lTexture2D = new Texture2D(lWidth, lHeight, TextureFormat.RGBA32, lMipmaps, lLinear);
                lTexture2D.LoadRawTextureData(lRawData);
                lTexture2D.Apply(lMipmaps, true);
            }

            return lTexture2D;
        }
コード例 #25
0
ファイル: BlankTexture.cs プロジェクト: Ragzouken/smooltool
    public static Texture2D New(int width, int height, Color32 color)
    {
        var texture = new Texture2D(width, height, TextureFormat.ARGB32, false);
        texture.filterMode = FilterMode.Point;

        var pixels = new byte[width * height * 4];

        for (int i = 0; i < pixels.Length; i += 4)
        {
            pixels[i + 0] = color.a;
            pixels[i + 1] = color.r;
            pixels[i + 2] = color.g;
            pixels[i + 3] = color.b;
        }
        
        texture.LoadRawTextureData(pixels);
        texture.Apply();

        return texture;
    }
コード例 #26
0
        public static Texture2D LoadTextureDXT(byte[] ddsBytes, TextureFormat textureFormat)
        {
            if (textureFormat != TextureFormat.DXT1 && textureFormat != TextureFormat.DXT5)
                throw new Exception("Invalid TextureFormat. Only DXT1 and DXT5 formats are supported by this method.");

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

            int height = ddsBytes[13] * 256 + ddsBytes[12];
            int width = ddsBytes[17] * 256 + ddsBytes[16];

            int DDS_HEADER_SIZE = 128;
            byte[] dxtBytes = new byte[ddsBytes.Length - DDS_HEADER_SIZE];
            Buffer.BlockCopy(ddsBytes, DDS_HEADER_SIZE, dxtBytes, 0, ddsBytes.Length - DDS_HEADER_SIZE);

            Texture2D texture = new Texture2D(width, height, textureFormat, false);
            texture.LoadRawTextureData(dxtBytes);
            texture.Apply();

            return (texture);
        }
コード例 #27
0
	public void LoadTextureFromGamedata(string scd, string LocalPath, int Id, bool NormalMap = false){
		SetPath();

		if(!Directory.Exists(GameDataPath)){
			Debug.LogError("Gamedata path not exist!");
			return;
		}

		if(!Directory.Exists("temfiles")) Directory.CreateDirectory("temfiles");

		ZipFile zf = null;
		try {
			FileStream fs = File.OpenRead(GameDataPath + scd);
			zf = new ZipFile(fs);



			char[] sep = ("/").ToCharArray();
			string[] LocalSepPath = LocalPath.Split(sep);
			string FileName = LocalSepPath[LocalSepPath.Length - 1];


			foreach (ZipEntry zipEntry in zf) {
				if (!zipEntry.IsFile) {
					continue;
				}
				if(zipEntry.Name.ToLower() == LocalPath.ToLower() || zipEntry.Name == LocalPath.ToLower()){
					//Debug.LogWarning("File found!");

					byte[] buffer = new byte[4096]; // 4K is optimum
					Stream zipStream = zf.GetInputStream(zipEntry);
					int size = 4096;
					using (FileStream streamWriter = File.Create("temfiles/" + FileName))
					{
						while (true)
							{
							size = zipStream.Read(buffer, 0, buffer.Length);
							if (size > 0)
							{
								streamWriter.Write(buffer, 0, size);
							}
							else
							{
								break;
							}
						}
					}



					byte[] FinalTextureData = System.IO.File.ReadAllBytes("temfiles/" + FileName);

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

					int height = FinalTextureData[13] * 256 + FinalTextureData[12];
					int width = FinalTextureData[17] * 256 + FinalTextureData[16];

					TextureFormat format;;
					// Now this is made realy bad. I don't know how to check DDS texture format, so i check texture size and its all bytes length to check if there are 3 or 4 channels
					float FormatFileSize = (float)FinalTextureData.Length / ((float)(width * height));
					//Debug.LogWarning("Size: " +  FormatFileSize);
					if(FormatFileSize < 1){
						format = TextureFormat.DXT1;
						Debug.LogWarning(FileName + " is DXT1"); 
					}
					else if(FormatFileSize > 4){
						format = TextureFormat.RGB24;
						Debug.LogWarning(FileName + " is RGB24"); 
					}
					else{
						format = TextureFormat.DXT5;
						Debug.LogWarning(FileName + " is DXT5"); 
					}

					format = GetFormatOfDds("temfiles/" + FileName);

					Texture2D texture = new Texture2D(width, height, format, true);
					int DDS_HEADER_SIZE = 128;

					byte[] dxtBytes = new byte[FinalTextureData.Length - DDS_HEADER_SIZE];
					Buffer.BlockCopy(FinalTextureData, DDS_HEADER_SIZE, dxtBytes, 0, FinalTextureData.Length - DDS_HEADER_SIZE);
					//texture.LoadImage(FinalTextureData);
					texture.LoadRawTextureData(dxtBytes);
					texture.Apply();

					if(NormalMap){
						Texture2D normalTexture = new Texture2D(height, width, TextureFormat.ARGB32, true);

						Color theColour = new Color();
						for (int x=0; x<texture.width; x++){
							for (int y=0; y<texture.height; y++){
								theColour.r = texture.GetPixel(x,y).r;
								theColour.g = texture.GetPixel(x,y).g;
								theColour.b = 1;
								theColour.a = texture.GetPixel(x,y).g;
								normalTexture.SetPixel(x,y, theColour);
							}
						}

						normalTexture.Apply();

						Scmap.Textures[Id].Normal = normalTexture;
						Scmap.Textures[Id].Normal.mipMapBias = -0.0f;
						Scmap.Textures[Id].Normal.filterMode = FilterMode.Trilinear;
						Scmap.Textures[Id].Normal.anisoLevel = 6;
					}
					else{
						Scmap.Textures[Id].Albedo = texture;
						Scmap.Textures[Id].Albedo.mipMapBias = -0.0f;
						Scmap.Textures[Id].Albedo.filterMode = FilterMode.Trilinear;
						Scmap.Textures[Id].Albedo.anisoLevel = 6;
					}

				}
			}
		} finally {
			if (zf != null) {
				zf.IsStreamOwner = true; // Makes close also shut the underlying stream
				zf.Close(); // Ensure we release resources
			}
		}
	}
コード例 #28
0
ファイル: Helper.cs プロジェクト: Mymicky/MarchingCubesUnity
    private static Texture2D LoadTexture2DRaw(BinaryReader br, int w, int h)
    {

        Texture2D tex = new Texture2D(w, h, TextureFormat.RGBAHalf, false);
        tex.wrapMode = TextureWrapMode.Repeat;
        tex.filterMode = FilterMode.Bilinear;
        int elementSize = sizeof(UInt16) * 4;
        int dataSize = w * h * elementSize;
        byte[] data = new byte[dataSize];
        br.Read(data, 0, dataSize);

        tex.LoadRawTextureData(data);
        tex.Apply(false);

        return tex;
    }
コード例 #29
0
        /// <summary>
        /// Gets the contract icon for the given id and seed (color).
        /// </summary>
        /// <param name="url">URL of the icon</param>
        /// <param name="seed">Seed to use for generating the color</param>
        /// <returns>The texture</returns>
        public static Texture2D GetContractIcon(string url, int seed)
        {
            // Check cache for texture
            Texture2D texture;
            Color color = SystemUtilities.RandomColor(seed, 1.0f, 1.0f, 1.0f);
            if (!contractIcons.ContainsKey(url))
            {
                contractIcons[url] = new Dictionary<Color, Texture2D>();
            }
            if (!contractIcons[url].ContainsKey(color))
            {
                Texture2D baseTexture = ContractDefs.sprites[url].texture;

                try
                {
                    Texture2D loadedTexture = null;
                    string path = (url.Contains('/') ? "GameData/" : "GameData/Squad/Contracts/Icons/") + url;
                    // PNG loading
                    if (File.Exists(path + ".png"))
                    {
                        path += ".png";
                        loadedTexture = new Texture2D(baseTexture.width, baseTexture.height, TextureFormat.RGBA32, false);
                        loadedTexture.LoadImage(File.ReadAllBytes(path.Replace('/', Path.DirectorySeparatorChar)));
                    }
                    // DDS loading
                    else if (File.Exists(path + ".dds"))
                    {
                        path += ".dds";
                        BinaryReader br = new BinaryReader(new MemoryStream(File.ReadAllBytes(path)));

                        if (br.ReadUInt32() != DDSValues.uintMagic)
                        {
                            throw new Exception("Format issue with DDS texture '" + path + "'!");
                        }
                        DDSHeader ddsHeader = new DDSHeader(br);
                        if (ddsHeader.ddspf.dwFourCC == DDSValues.uintDX10)
                        {
                            DDSHeaderDX10 ddsHeaderDx10 = new DDSHeaderDX10(br);
                        }

                        TextureFormat texFormat;
                        if (ddsHeader.ddspf.dwFourCC == DDSValues.uintDXT1)
                        {
                            texFormat = UnityEngine.TextureFormat.DXT1;
                        }
                        else if (ddsHeader.ddspf.dwFourCC == DDSValues.uintDXT3)
                        {
                            texFormat = UnityEngine.TextureFormat.DXT1 | UnityEngine.TextureFormat.Alpha8;
                        }
                        else if (ddsHeader.ddspf.dwFourCC == DDSValues.uintDXT5)
                        {
                            texFormat = UnityEngine.TextureFormat.DXT5;
                        }
                        else
                        {
                            throw new Exception("Unhandled DDS format!");
                        }

                        loadedTexture = new Texture2D((int)ddsHeader.dwWidth, (int)ddsHeader.dwHeight, texFormat, false);
                        loadedTexture.LoadRawTextureData(br.ReadBytes((int)(br.BaseStream.Length - br.BaseStream.Position)));
                    }
                    else
                    {
                        throw new Exception("Couldn't find file for icon  '" + url + "'");
                    }

                    Color[] pixels = loadedTexture.GetPixels();
                    for (int i = 0; i < pixels.Length; i++)
                    {
                        pixels[i] *= color;
                    }
                    texture = new Texture2D(baseTexture.width, baseTexture.height, TextureFormat.RGBA32, false);
                    texture.SetPixels(pixels);
                    texture.Apply(false, false);
                    contractIcons[url][color] = texture;
                    UnityEngine.Object.Destroy(loadedTexture);
                }
                catch (Exception e)
                {
                    Debug.LogError("WaypointManager: Couldn't create texture for '" + url + "'!");
                    Debug.LogException(e);
                    texture = contractIcons[url][color] = baseTexture;
                }
            }
            else
            {
                texture = contractIcons[url][color];
            }

            return texture;
        }
コード例 #30
0
	private void RenderPageOne() {
		if (GUILayout.Button("RequestCurrentStats()")) {
			bool ret = SteamUserStats.RequestCurrentStats();
			print("RequestCurrentStats() - " + ret);
		}

		{
			bool ret = SteamUserStats.GetStat("NumGames", out m_NumGamesStat);
			GUILayout.Label("GetStat(\"NumGames\", out m_NumGamesStat) - " + ret + " -- " + m_NumGamesStat);
		}

		{
			bool ret = SteamUserStats.GetStat("FeetTraveled", out m_FeetTraveledStat);
			GUILayout.Label("GetStat(\"FeetTraveled\", out m_FeetTraveledStat) - " + ret + " -- " + m_FeetTraveledStat);
		}

		if (GUILayout.Button("SetStat(\"NumGames\", m_NumGamesStat + 1)")) {
			bool ret = SteamUserStats.SetStat("NumGames", m_NumGamesStat + 1);
			print("SetStat(\"NumGames\", " + (m_NumGamesStat + 1) + ") - " + ret);
		}

		if (GUILayout.Button("SetStat(\"FeetTraveled\", m_FeetTraveledStat + 1)")) {
			bool ret = SteamUserStats.SetStat("FeetTraveled", m_FeetTraveledStat + 1);
			print("SetStat(\"FeetTraveled\", " + (m_FeetTraveledStat + 1) + ") - " + ret);
		}

		if (GUILayout.Button("UpdateAvgRateStat(\"AverageSpeed\", 100, 60.0)")) {
			bool ret = SteamUserStats.UpdateAvgRateStat("AverageSpeed", 100, 60.0);
			print("UpdateAvgRateStat(\"AverageSpeed\", 100, 60.0) - " + ret);
		}

		{
			bool ret = SteamUserStats.GetAchievement("ACH_WIN_ONE_GAME", out m_AchievedWinOneGame);
			GUILayout.Label("GetAchievement(\"ACH_WIN_ONE_GAME\", out m_AchievedWinOneGame) - " + ret + " -- " + m_AchievedWinOneGame);
		}

		if (GUILayout.Button("SetAchievement(\"ACH_WIN_ONE_GAME\")")) {
			bool ret = SteamUserStats.SetAchievement("ACH_WIN_ONE_GAME");
			print("SetAchievement(\"ACH_WIN_ONE_GAME\") - " + ret);
		}

		if (GUILayout.Button("ClearAchievement(\"ACH_WIN_ONE_GAME\")")) {
			bool ret = SteamUserStats.ClearAchievement("ACH_WIN_ONE_GAME");
			print("ClearAchievement(\"ACH_WIN_ONE_GAME\") - " + ret);
		}

		{
			bool Achieved;
			uint UnlockTime;
			bool ret = SteamUserStats.GetAchievementAndUnlockTime("ACH_WIN_ONE_GAME", out Achieved, out UnlockTime);
			GUILayout.Label("GetAchievementAndUnlockTime(\"ACH_WIN_ONE_GAME\", out Achieved, out UnlockTime) - " + ret + " -- " + Achieved + " -- " + UnlockTime);
		}

		if (GUILayout.Button("StoreStats()")) {
			bool ret = SteamUserStats.StoreStats();
			print("StoreStats() - " + ret);
		}

		if (GUILayout.Button("GetAchievementIcon(\"ACH_WIN_ONE_GAME\")")) {
			int icon = SteamUserStats.GetAchievementIcon("ACH_WIN_ONE_GAME");
			print("SteamUserStats.GetAchievementIcon(\"ACH_WIN_ONE_GAME\") - " + icon);

			if (icon != 0) {
				uint Width = 0;
				uint Height = 0;
				bool ret = SteamUtils.GetImageSize(icon, out Width, out Height);

				if (ret && Width > 0 && Height > 0) {
					byte[] RGBA = new byte[Width * Height * 4];
					ret = SteamUtils.GetImageRGBA(icon, RGBA, RGBA.Length);
					if (ret) {
						m_Icon = new Texture2D((int)Width, (int)Height, TextureFormat.RGBA32, false, true);
						m_Icon.LoadRawTextureData(RGBA);
						m_Icon.Apply();
					}
				}
			}
		}

		GUILayout.Label("GetAchievementDisplayAttribute(\"ACH_WIN_ONE_GAME\", \"name\") : " + SteamUserStats.GetAchievementDisplayAttribute("ACH_WIN_ONE_GAME", "name"));

		if (GUILayout.Button("IndicateAchievementProgress(\"ACH_WIN_100_GAMES\", 10, 100)")) {
			bool ret = SteamUserStats.IndicateAchievementProgress("ACH_WIN_100_GAMES", 10, 100);
			print("IndicateAchievementProgress(\"ACH_WIN_100_GAMES\", 10, 100) - " + ret);
		}

		GUILayout.Label("GetNumAchievements() : " + SteamUserStats.GetNumAchievements());
		GUILayout.Label("GetAchievementName(0) : " + SteamUserStats.GetAchievementName(0));

		if (GUILayout.Button("RequestUserStats(SteamUser.GetSteamID())")) {
			SteamAPICall_t handle = SteamUserStats.RequestUserStats(new CSteamID(76561197991230424)); //rlabrecque
			UserStatsReceived.Set(handle);
			print("RequestUserStats(" + SteamUser.GetSteamID() + ") - " + handle);
		}

		{
			int Data;
			bool ret = SteamUserStats.GetUserStat(new CSteamID(76561197991230424), "NumWins", out Data); //rlabrecque
			GUILayout.Label("GetUserStat(SteamUser.GetSteamID(), \"NumWins\", out Data) : " + ret + " -- " + Data);
		}

		{
			float Data;
			bool ret = SteamUserStats.GetUserStat(new CSteamID(76561197991230424), "MaxFeetTraveled", out Data); //rlabrecque
			GUILayout.Label("GetUserStat(SteamUser.GetSteamID(), \"NumWins\", out Data) : " + ret + " -- " + Data);
		}

		{
			bool Achieved;
			bool ret = SteamUserStats.GetUserAchievement(new CSteamID(76561197991230424), "ACH_TRAVEL_FAR_ACCUM", out Achieved); //rlabrecque
			GUILayout.Label("GetUserAchievement(SteamUser.GetSteamID(), \"ACH_TRAVEL_FAR_ACCUM\", out Achieved) : " + ret + " -- " + Achieved);
		}

		{
			bool Achieved;
			uint UnlockTime;
			bool ret = SteamUserStats.GetUserAchievementAndUnlockTime(new CSteamID(76561197991230424), "ACH_WIN_ONE_GAME", out Achieved, out UnlockTime); //rlabrecque
			GUILayout.Label("GetUserAchievementAndUnlockTime(SteamUser.GetSteamID(), ACH_TRAVEL_FAR_SINGLE\", out Achieved, out UnlockTime) : " + ret + " -- " + Achieved + " -- " + UnlockTime);
		}

		if (GUILayout.Button("ResetAllStats(true)")) {
			bool ret = SteamUserStats.ResetAllStats(true);
			print("ResetAllStats(true) - " + ret);
		}
	}
コード例 #31
0
ファイル: TextureUtils.cs プロジェクト: JokieW/ShiningHill
        public static Texture2D[] ReadDDS(string baseName, BinaryReader reader)
        {
            reader.SkipInt32(2);
            int texturesSize = reader.ReadInt32();
            reader.SkipInt32(0);
            reader.SkipInt32(0);

            reader.SkipInt32(0x19990901); //magic
            reader.SkipInt32(0);
            reader.SkipInt32(0);
            reader.SkipInt32(1);

            List<Texture2D> textures = new List<Texture2D>();

            int i = 0;
            while (reader.BaseStream.Position < texturesSize)
            {
                short textureID = reader.ReadInt16();
                reader.SkipInt16(0);
                short width = reader.ReadInt16();
                short height = reader.ReadInt16();
                reader.SkipInt16(512);
                reader.SkipInt16(512);
                int subgroupsCount = reader.ReadInt32(); //1 more?

                reader.SkipInt16();
                reader.SkipInt16();
                reader.SkipBytes(12); //Skips 0 0 0

                int texLength = 0;
                for (int j = 0; j != subgroupsCount; j++)
                {
                    //Subgroup thingie
                    /*short subgroupID = */
                    reader.SkipInt16();
                    reader.SkipInt16();
                    reader.SkipInt16(0);
                    reader.SkipInt16(0);
                    reader.SkipInt16(512);
                    reader.SkipInt16(512);
                    reader.SkipInt16(256);
                    reader.SkipInt16(0);

                    texLength = reader.ReadInt32();
                    /*int texAndHeaderLength = */
                    reader.SkipInt32();
                    reader.SkipInt32(0);
                    reader.SkipUInt32(0x99000000);
                }

                Texture2D text = new Texture2D(width, height, TextureFormat.DXT1, false);
                text.LoadRawTextureData(reader.ReadBytes(texLength));
                text.Apply();

                text.alphaIsTransparency = true;
                text.name = baseName + textureID.ToString("0000");

                textures.Add(text);
                i++;
            }
            reader.SkipBytes(0x10);

            return textures.ToArray();
        }
コード例 #32
0
    public static Texture2D Load(string TextureName)
    {
        if (!File.Exists(Configuration.GameFld + Configuration.Mod + "/materials/" + TextureName + ".vtf"))
            return new Texture2D(1, 1);

        CRead = new CustomReader(File.OpenRead(Configuration.GameFld + Configuration.Mod + "/materials/" + TextureName + ".vtf"));
        VTF_Header = CRead.ReadType<tagVTFHEADER>();

        Texture2D VTF_Texture = default(Texture2D); TextureFormat ImageFormat;
        long OffsetInFile = VTF_Header.Width * VTF_Header.Height * uiBytesPerPixels[(int)VTF_Header.HighResImageFormat];

        switch (VTF_Header.HighResImageFormat)
        {
            case VTFImageFormat.IMAGE_FORMAT_DXT1:
                OffsetInFile = ((VTF_Header.Width + 3) / 4) * ((VTF_Header.Height + 3) / 4) * 8;
                ImageFormat = TextureFormat.DXT1; break;

            case VTFImageFormat.IMAGE_FORMAT_DXT3:
            case VTFImageFormat.IMAGE_FORMAT_DXT5:
                OffsetInFile = ((VTF_Header.Width + 3) / 4) * ((VTF_Header.Height + 3) / 4) * 16;
                ImageFormat = TextureFormat.DXT5; break;

            case VTFImageFormat.IMAGE_FORMAT_RGB888:
            case VTFImageFormat.IMAGE_FORMAT_BGR888:
                ImageFormat = TextureFormat.RGB24; break;

            case VTFImageFormat.IMAGE_FORMAT_RGBA8888:
                ImageFormat = TextureFormat.RGBA32; break;

            case VTFImageFormat.IMAGE_FORMAT_ARGB8888:
                ImageFormat = TextureFormat.ARGB32; break;

            case VTFImageFormat.IMAGE_FORMAT_BGRA8888:
                ImageFormat = TextureFormat.BGRA32; break;

            default: return new Texture2D(1, 1);
        }

        VTF_Texture = new Texture2D(VTF_Header.Width, VTF_Header.Height, ImageFormat, false);
        byte[] VTF_File = CRead.GetBytes((int)OffsetInFile, CRead.InputStream.Length - OffsetInFile);

        if (VTF_Header.HighResImageFormat == VTFImageFormat.IMAGE_FORMAT_BGR888)
        {
            for (int i = 0; i < VTF_File.Length - 1; i += 3)
            {
                byte Temp = VTF_File[i];
                VTF_File[i] = VTF_File[i + 2];
                VTF_File[i + 2] = Temp;
            }
        }

        VTF_Texture.LoadRawTextureData(VTF_File);

        Texture2D Mip_Texture = new Texture2D(VTF_Header.Width, VTF_Header.Height, TextureFormat.RGBA32, true);
        Mip_Texture.SetPixels32(VTF_Texture.GetPixels32());

        Mip_Texture.Apply(); Mip_Texture.Compress(false);
        Object.DestroyImmediate(VTF_Texture);

        CRead.Dispose();
        return Mip_Texture;
    }
コード例 #33
0
	public void LoadPreview(){
		string MapPath = PlayerPrefs.GetString("MapsPath", "maps/");
		string path = Application.dataPath + "/" + MapPath + Scenario.FolderName;
		#if UNITY_EDITOR
		path = path.Replace("Assets/", "");
		#endif
		byte[] FinalTextureData;
		Vector2	ImageSize = Vector2.one;
		string	FinalImagePath = "";

		if(File.Exists(path + "/preview.jpg")){
			FinalImagePath = path + "/preview.jpg";
			ImageSize *= 256;
		}
		else if(File.Exists(path + "/" + Scenario.FolderName + ".dds")){
			FinalImagePath = path + "/" + Scenario.FolderName + ".dds";
			byte[] FinalTextureData2 = System.IO.File.ReadAllBytes(FinalImagePath);


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

			// Load DDS Header
			/*System.IO.FileStream fs = new System.IO.FileStream(FinalImagePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
			BinaryReader Stream = new BinaryReader(fs);
			LoadDDsHeader = new HeaderClass();

			byte[] signature = Stream.ReadBytes(4);
			LoadDDsHeader.size = Stream.ReadUInt32();
			LoadDDsHeader.flags = Stream.ReadUInt32();
			LoadDDsHeader.height = Stream.ReadUInt32();
			LoadDDsHeader.width = Stream.ReadUInt32();
			LoadDDsHeader.sizeorpitch = Stream.ReadUInt32();
			LoadDDsHeader.depth = Stream.ReadUInt32();
			LoadDDsHeader.mipmapcount = Stream.ReadUInt32();
			LoadDDsHeader.alphabitdepth = Stream.ReadUInt32();


			LoadDDsHeader.reserved = new uint[10];
			for (int i = 0; i < 10; i++)
			{
				LoadDDsHeader.reserved[i] = Stream.ReadUInt32();
			}

			LoadDDsHeader.pixelformatSize = Stream.ReadUInt32();
			LoadDDsHeader.pixelformatflags = Stream.ReadUInt32();
			LoadDDsHeader.pixelformatFourcc = Stream.ReadUInt32();
			LoadDDsHeader.pixelformatRgbBitCount = Stream.ReadUInt32();
			LoadDDsHeader.pixelformatRbitMask = Stream.ReadUInt32();
			LoadDDsHeader.pixelformatGbitMask = Stream.ReadUInt32();
			LoadDDsHeader.pixelformatBbitMask = Stream.ReadUInt32();
			LoadDDsHeader.pixelformatAbitMask = Stream.ReadUInt32();*/


			int height = FinalTextureData2[13] * 256 + FinalTextureData2[12];
			int width = FinalTextureData2[17] * 256 + FinalTextureData2[16];

			TextureFormat format = GamedataFiles.GetFormatOfDds(FinalImagePath);


			Texture2D textureDds = new Texture2D(width, height, format, false);
			int DDS_HEADER_SIZE = 128;
			byte[] dxtBytes = new byte[FinalTextureData2.Length - DDS_HEADER_SIZE];
			Buffer.BlockCopy(FinalTextureData2, DDS_HEADER_SIZE, dxtBytes, 0, FinalTextureData2.Length - DDS_HEADER_SIZE);
			textureDds.LoadRawTextureData(dxtBytes);
			textureDds.Apply();

			Img.texture = textureDds;
			return;
		}
		else if(File.Exists(path + "/" + Scenario.FolderName + ".png")){
			FinalImagePath = path + "/" + Scenario.FolderName + ".png";
			ImageSize *= 256;
		}
		else if(File.Exists(path + "/" + Scenario.FolderName + ".small" + ".png")){
			FinalImagePath = path + "/" + Scenario.FolderName + ".small" + ".png";
			ImageSize *= 100;
		}
		else{
			// No image
			Debug.LogWarning("no image");
			Img.texture = EmptyMapTexture;
			return;
		}
		Debug.Log(FinalImagePath);

		FinalTextureData = System.IO.File.ReadAllBytes(FinalImagePath);
		Texture2D texture = new Texture2D((int)ImageSize.x, (int)ImageSize.y);
		texture.LoadImage(FinalTextureData);
		
		Img.texture = texture;
	}
コード例 #34
0
        public static void SetTextureData(UnityEngine.Texture2D texture, Alt.Sketch.Bitmap src, Alt.Sketch.RectI srcRect, bool flip)
        {
            if (texture == null ||
                src == null ||
                !src.IsValid)
            {
                return;
            }


            Alt.Sketch.BitmapData srcData = src.LockBits(Sketch.ImageLockMode.ReadOnly);
            if (srcData == null)
            {
                return;
            }


            int src_x = srcRect.X;
            int src_y = srcRect.Y;
            //int src_w, src_h;
            int src_width =             //src_w =
                            srcRect.Width;
            int src_height =            //src_h =
                             srcRect.Height;

            int dest_x = 0;
            int dest_y = 0;

            int dest_w = texture.width;
            int dest_h = texture.height;

            if (dest_x > (dest_w - 1) ||
                dest_y > (dest_h - 1))
            {
                src.UnlockBits(srcData);

                return;
            }

            if ((dest_x + src_width) > dest_w)
            {
                src_width = dest_w - dest_x;
            }

            if ((dest_y + src_height) > dest_h)
            {
                src_height = dest_h - dest_y;
            }


            byte[] src_Buffer    = srcData.Scan0;
            int    src_stride    = srcData.Stride;
            int    src_ByteDepth = srcData.ByteDepth;


            try
            {
                bool fProcessed = false;

                switch (srcData.PixelFormat)
                {
                case Sketch.PixelFormat.Format24bppRgb:
                {
                    switch (texture.format)
                    {
                    case TextureFormat.RGB24:
                    {
                        if (src_width == dest_w &&
                            src_height == dest_h)
                        {
                            //texture.LoadRawTextureData(src_Buffer);

                            byte[] colors = src.TextureTempBuffer;
                            if (colors == null)
                            {
                                colors = new byte[src_height * src_width * 3];
                            }
                            int colors_index = 0;

                            if (flip)
                            {
                                for (int y = src_height - 1; y >= 0; y--)
                                {
                                    int src_Index = src_x * src_ByteDepth + (src_y + y) * src_stride;

                                    for (int x = 0; x < src_width; x++)
                                    {
                                        colors[colors_index++] = src_Buffer[src_Index + 2];
                                        colors[colors_index++] = src_Buffer[src_Index + 1];
                                        colors[colors_index++] = src_Buffer[src_Index];
                                        src_Index += 3;
                                    }
                                }
                            }
                            else
                            {
                                for (int y = 0; y < src_height; y++)
                                {
                                    int src_Index = src_x * src_ByteDepth + (src_y + y) * src_stride;

                                    for (int x = 0; x < src_width; x++)
                                    {
                                        colors[colors_index++] = src_Buffer[src_Index + 2];
                                        colors[colors_index++] = src_Buffer[src_Index + 1];
                                        colors[colors_index++] = src_Buffer[src_Index];
                                        src_Index += 3;
                                    }
                                }
                            }

                            texture.LoadRawTextureData(colors);
                        }
                        else
                        {
                            UnityEngine.Color[] colors = new UnityEngine.Color[src_height * src_width];
                            int colors_index           = 0;

                            if (flip)
                            {
                                for (int y = src_height - 1; y >= 0; y--)
                                {
                                    int src_Index = src_x * src_ByteDepth + (src_y + y) * src_stride;

                                    for (int x = 0; x < src_width; x++)
                                    {
                                        colors[colors_index++] = new Color32(
                                            src_Buffer[src_Index + 2],
                                            src_Buffer[src_Index + 1],
                                            src_Buffer[src_Index],
                                            255);
                                        src_Index += 3;
                                    }
                                }
                            }
                            else
                            {
                                for (int y = 0; y < src_height; y++)
                                {
                                    int src_Index = src_x * src_ByteDepth + (src_y + y) * src_stride;

                                    for (int x = 0; x < src_width; x++)
                                    {
                                        colors[colors_index++] = new Color32(
                                            src_Buffer[src_Index + 2],
                                            src_Buffer[src_Index + 1],
                                            src_Buffer[src_Index],
                                            255);
                                        src_Index += 3;
                                    }
                                }
                            }

                            texture.SetPixels(src_x, src_y, src_width, src_height, colors);
                        }

                        fProcessed = true;

                        break;
                    }

                    case TextureFormat.RGBA32:
                    {
                        if (src_width == dest_w &&
                            src_height == dest_h)
                        {
                            byte[] colors       = new byte[src_height * src_width * 4];
                            int    colors_index = 0;

                            if (flip)
                            {
                                for (int y = src_height - 1; y >= 0; y--)
                                {
                                    int src_Index = src_x * src_ByteDepth + (src_y + y) * src_stride;

                                    for (int x = 0; x < src_width; x++)
                                    {
                                        colors[colors_index++] = src_Buffer[src_Index + 2];
                                        colors[colors_index++] = src_Buffer[src_Index + 1];
                                        colors[colors_index++] = src_Buffer[src_Index];
                                        colors[colors_index++] = 255;
                                        src_Index += 3;
                                    }
                                }
                            }
                            else
                            {
                                for (int y = 0; y < src_height; y++)
                                {
                                    int src_Index = src_x * src_ByteDepth + (src_y + y) * src_stride;

                                    for (int x = 0; x < src_width; x++)
                                    {
                                        colors[colors_index++] = src_Buffer[src_Index + 2];
                                        colors[colors_index++] = src_Buffer[src_Index + 1];
                                        colors[colors_index++] = src_Buffer[src_Index];
                                        colors[colors_index++] = 255;
                                        src_Index += 3;
                                    }
                                }
                            }

                            texture.LoadRawTextureData(colors);
                        }
                        else
                        {
                            UnityEngine.Color[] colors = new UnityEngine.Color[src_height * src_width];
                            int colors_index           = 0;

                            if (flip)
                            {
                                for (int y = src_height - 1; y >= 0; y--)
                                {
                                    int src_Index = src_x * src_ByteDepth + (src_y + y) * src_stride;

                                    for (int x = 0; x < src_width; x++)
                                    {
                                        colors[colors_index++] = new Color32(
                                            src_Buffer[src_Index + 2],
                                            src_Buffer[src_Index + 1],
                                            src_Buffer[src_Index],
                                            255);
                                        src_Index += 3;
                                    }
                                }
                            }
                            else
                            {
                                for (int y = 0; y < src_height; y++)
                                {
                                    int src_Index = src_x * src_ByteDepth + (src_y + y) * src_stride;

                                    for (int x = 0; x < src_width; x++)
                                    {
                                        colors[colors_index++] = new Color32(
                                            src_Buffer[src_Index + 2],
                                            src_Buffer[src_Index + 1],
                                            src_Buffer[src_Index],
                                            255);
                                        src_Index += 3;
                                    }
                                }
                            }

                            texture.SetPixels(src_x, src_y, src_width, src_height, colors);
                        }

                        fProcessed = true;

                        break;
                    }
                    }

                    break;
                }

                case Sketch.PixelFormat.Format32bppArgb:
                {
                    switch (texture.format)
                    {
                    case TextureFormat.RGB24:
                    {
                        //  We can't be here

                        //int dest_ByteDepth = 3;

                        break;
                    }

                    case TextureFormat.RGBA32:
                    {
                        if (src_width == dest_w &&
                            src_height == dest_h)
                        {
                            //texture.LoadRawTextureData(src_Buffer);

                            byte[] colors = src.TextureTempBuffer;
                            if (colors == null)
                            {
                                colors = new byte[src_height * src_width * 4];
                            }
                            int colors_index = 0;

                            if (flip)
                            {
                                for (int y = src_height - 1; y >= 0; y--)
                                {
                                    int src_Index = src_x * src_ByteDepth + (src_y + y) * src_stride;

                                    for (int x = 0; x < src_width; x++)
                                    {
                                        colors[colors_index++] = src_Buffer[src_Index + 2];
                                        colors[colors_index++] = src_Buffer[src_Index + 1];
                                        colors[colors_index++] = src_Buffer[src_Index];
                                        colors[colors_index++] = src_Buffer[src_Index + 3];
                                        src_Index += 4;
                                    }
                                }
                            }
                            else
                            {
                                for (int y = 0; y < src_height; y++)
                                {
                                    int src_Index = src_x * src_ByteDepth + (src_y + y) * src_stride;

                                    for (int x = 0; x < src_width; x++)
                                    {
                                        colors[colors_index++] = src_Buffer[src_Index + 2];
                                        colors[colors_index++] = src_Buffer[src_Index + 1];
                                        colors[colors_index++] = src_Buffer[src_Index];
                                        colors[colors_index++] = src_Buffer[src_Index + 3];
                                        src_Index += 4;
                                    }
                                }
                            }

                            texture.LoadRawTextureData(colors);
                        }
                        else
                        {
                            UnityEngine.Color[] colors = new UnityEngine.Color[src_height * src_width];
                            int colors_index           = 0;

                            if (flip)
                            {
                                for (int y = src_height - 1; y >= 0; y--)
                                {
                                    int src_Index = src_x * src_ByteDepth + (src_y + y) * src_stride;

                                    for (int x = 0; x < src_width; x++)
                                    {
                                        colors[colors_index++] = new Color32(
                                            src_Buffer[src_Index + 2],
                                            src_Buffer[src_Index + 1],
                                            src_Buffer[src_Index],
                                            src_Buffer[src_Index + 3]);
                                        src_Index += 4;
                                    }
                                }
                            }
                            else
                            {
                                for (int y = 0; y < src_height; y++)
                                {
                                    int src_Index = src_x * src_ByteDepth + (src_y + y) * src_stride;

                                    for (int x = 0; x < src_width; x++)
                                    {
                                        colors[colors_index++] = new Color32(
                                            src_Buffer[src_Index + 2],
                                            src_Buffer[src_Index + 1],
                                            src_Buffer[src_Index],
                                            src_Buffer[src_Index + 3]);
                                        src_Index += 4;
                                    }
                                }
                            }

                            texture.SetPixels(src_x, src_y, src_width, src_height, colors);
                        }

                        fProcessed = true;

                        break;
                    }
                    }

                    break;
                }

                case Sketch.PixelFormat.Format8bppAlpha:
                {
                    //  not used yet

                    break;
                }
                }


                //  universal method
                if (!fProcessed)
                {
                    UnityEngine.Color[] colors = new UnityEngine.Color[src_height * src_width];
                    int colors_index           = 0;

                    for (int y = 0; y < src_height; y++)
                    {
                        for (int x = 0; x < src_width; x++)
                        {
                            Alt.Sketch.Color color = src.GetPixel(x, y);

                            colors[colors_index++] = new Color32(
                                color.R,
                                color.G,
                                color.B,
                                color.A);
                        }
                    }

                    texture.SetPixels(src_x, src_y, src_width, src_height, colors);

                    fProcessed = true;
                }

                if (fProcessed)
                {
                    texture.Apply(false);
                }
            }
            catch             //(System.Exception ex)
            {
                //Console.WriteLine(ex.ToString());
            }
            finally
            {
                src.UnlockBits(srcData);
            }
        }
コード例 #35
0
	private void RenderPageOne() {
		GUILayout.Label("SteamFriends.GetPersonaName() : " + SteamFriends.GetPersonaName());

		if (GUILayout.Button("SteamFriends.SetPersonaName(SteamFriends.GetPersonaName())")) {
			SteamAPICall_t handle = SteamFriends.SetPersonaName(SteamFriends.GetPersonaName());
			OnSetPersonaNameResponseCallResult.Set(handle);
			print("SteamFriends.SetPersonaName(" + SteamFriends.GetPersonaName() + ") : " + handle);
		}

		GUILayout.Label("SteamFriends.GetPersonaState() : " + SteamFriends.GetPersonaState());
		GUILayout.Label("SteamFriends.GetFriendCount(k_EFriendFlagImmediate) : " + SteamFriends.GetFriendCount(EFriendFlags.k_EFriendFlagImmediate));
		if (SteamFriends.GetFriendCount(EFriendFlags.k_EFriendFlagImmediate) == 0) {
			Debug.LogError("You must have atleast one friend to use this Test");
			return;
		}

		m_Friend = SteamFriends.GetFriendByIndex(0, EFriendFlags.k_EFriendFlagImmediate);
		GUILayout.Label("SteamFriends.GetFriendByIndex(0, k_EFriendFlagImmediate) : " + m_Friend);
		GUILayout.Label("SteamFriends.GetFriendRelationship(m_Friend) : " + SteamFriends.GetFriendRelationship(m_Friend));
		GUILayout.Label("SteamFriends.GetFriendPersonaState(m_Friend) : " + SteamFriends.GetFriendPersonaState(m_Friend));
		GUILayout.Label("SteamFriends.GetFriendPersonaName(m_Friend) : " + SteamFriends.GetFriendPersonaName(m_Friend));

		{
			var fgi = new FriendGameInfo_t();
			bool ret = SteamFriends.GetFriendGamePlayed(m_Friend, out fgi);
			GUILayout.Label("SteamFriends.GetFriendGamePlayed(m_Friend, out fgi) : " + ret + " -- " + fgi.m_gameID + " -- " + fgi.m_unGameIP + " -- " + fgi.m_usGamePort + " -- " + fgi.m_usQueryPort + " -- " + fgi.m_steamIDLobby);
		}


		GUILayout.Label("SteamFriends.GetFriendPersonaNameHistory(m_Friend, 1) : " + SteamFriends.GetFriendPersonaNameHistory(m_Friend, 1));
		GUILayout.Label("SteamFriends.GetFriendSteamLevel(m_Friend) : " + SteamFriends.GetFriendSteamLevel(m_Friend));
		GUILayout.Label("SteamFriends.GetPlayerNickname(m_Friend) : " + SteamFriends.GetPlayerNickname(m_Friend));

		{
			int FriendsGroupCount = SteamFriends.GetFriendsGroupCount();
			GUILayout.Label("SteamFriends.GetFriendsGroupCount() : " + FriendsGroupCount);

			if (FriendsGroupCount > 0) {
				FriendsGroupID_t FriendsGroupID = SteamFriends.GetFriendsGroupIDByIndex(0);
				GUILayout.Label("SteamFriends.GetFriendsGroupIDByIndex(0) : " + FriendsGroupID);
				GUILayout.Label("SteamFriends.GetFriendsGroupName(FriendsGroupID) : " + SteamFriends.GetFriendsGroupName(FriendsGroupID));

				int FriendsGroupMembersCount = SteamFriends.GetFriendsGroupMembersCount(FriendsGroupID);
				GUILayout.Label("SteamFriends.GetFriendsGroupMembersCount(FriendsGroupID) : " + FriendsGroupMembersCount);

				if (FriendsGroupMembersCount > 0) {
					CSteamID[] FriendsGroupMembersList = new CSteamID[FriendsGroupMembersCount];
					SteamFriends.GetFriendsGroupMembersList(FriendsGroupID, FriendsGroupMembersList, FriendsGroupMembersCount);
					GUILayout.Label("SteamFriends.GetFriendsGroupMembersList(FriendsGroupID, FriendsGroupMembersList, FriendsGroupMembersCount) : " + FriendsGroupMembersList[0]);
				}
			}
		}

		GUILayout.Label("SteamFriends.HasFriend(m_Friend, k_EFriendFlagImmediate) : " + SteamFriends.HasFriend(m_Friend, EFriendFlags.k_EFriendFlagImmediate));

		GUILayout.Label("SteamFriends.GetClanCount() : " + SteamFriends.GetClanCount());
		if (SteamFriends.GetClanCount() == 0) {
			Debug.LogError("You must have atleast one clan to use this Test");
			return;
		}

		m_Clan = SteamFriends.GetClanByIndex(0);
		GUILayout.Label("SteamFriends.GetClanByIndex(0) : " + m_Clan);
		GUILayout.Label("SteamFriends.GetClanName(m_Clan) : " + SteamFriends.GetClanName(m_Clan));
		GUILayout.Label("SteamFriends.GetClanTag(m_Clan) : " + SteamFriends.GetClanTag(m_Clan));

		{
			int Online;
			int InGame;
			int Chatting;
			bool ret = SteamFriends.GetClanActivityCounts(m_Clan, out Online, out InGame, out Chatting);
			GUILayout.Label("SteamFriends.GetClanActivityCounts(m_Clan, out Online, out InGame, out Chatting) : " + ret + " -- " + Online + " -- " + InGame + " -- " + Chatting);
		}

		if (GUILayout.Button("SteamFriends.DownloadClanActivityCounts(m_Clans, 2)")) {
			CSteamID[] Clans = { m_Clan, new CSteamID(103582791434672565) }; // m_Clan, Steam Universe
			SteamAPICall_t handle = SteamFriends.DownloadClanActivityCounts(Clans, 2);
			OnDownloadClanActivityCountsResultCallResult.Set(handle); // This call never seems to produce a callback.
			print("SteamFriends.DownloadClanActivityCounts(" + Clans + ", 2) : " + handle);
		}

		{
			int FriendCount = SteamFriends.GetFriendCountFromSource(m_Clan);
			GUILayout.Label("SteamFriends.GetFriendCountFromSource(m_Clan) : " + FriendCount);

			if (FriendCount > 0) {
				GUILayout.Label("SteamFriends.GetFriendFromSourceByIndex(m_Clan, 0) : " + SteamFriends.GetFriendFromSourceByIndex(m_Clan, 0));
			}
		}

		GUILayout.Label("SteamFriends.IsUserInSource(m_Friend, m_Clan) : " + SteamFriends.IsUserInSource(m_Friend, m_Clan));

		if (GUILayout.Button("SteamFriends.SetInGameVoiceSpeaking(SteamUser.GetSteamID(), false)")) {
			SteamFriends.SetInGameVoiceSpeaking(SteamUser.GetSteamID(), false);
			print("SteamClient.SetInGameVoiceSpeaking(" + SteamUser.GetSteamID() + ", false);");
		}

		if (GUILayout.Button("SteamFriends.ActivateGameOverlay(\"Friends\")")) {
			SteamFriends.ActivateGameOverlay("Friends");
			print("SteamClient.ActivateGameOverlay(\"Friends\")");
		}

		if (GUILayout.Button("SteamFriends.ActivateGameOverlayToUser(\"friendadd\", 76561197991230424)")) {
			SteamFriends.ActivateGameOverlayToUser("friendadd", new CSteamID(76561197991230424)); // rlabrecque
			print("SteamClient.ActivateGameOverlay(\"friendadd\", 76561197991230424)");
		}

		if (GUILayout.Button("SteamFriends.ActivateGameOverlayToWebPage(\"http://google.com\")")) {
			SteamFriends.ActivateGameOverlayToWebPage("http://google.com");
			print("SteamClient.ActivateGameOverlay(\"http://google.com\")");
		}

		if (GUILayout.Button("SteamFriends.ActivateGameOverlayToStore(440, k_EOverlayToStoreFlag_None)")) {
			SteamFriends.ActivateGameOverlayToStore((AppId_t)440, EOverlayToStoreFlag.k_EOverlayToStoreFlag_None); // 440 = TF2
			print("SteamClient.ActivateGameOverlay(440, k_EOverlayToStoreFlag_None)");
		}

		if (GUILayout.Button("SteamFriends.SetPlayedWith(76561197991230424)")) {
			SteamFriends.SetPlayedWith(new CSteamID(76561197991230424)); //rlabrecque
			print("SteamClient.SetPlayedWith(76561197991230424)");
		}

		if (GUILayout.Button("SteamFriends.ActivateGameOverlayInviteDialog(76561197991230424)")) {
			SteamFriends.ActivateGameOverlayInviteDialog(new CSteamID(76561197991230424)); //rlabrecque
			print("SteamClient.ActivateGameOverlayInviteDialog(76561197991230424)");
		}

		if (GUILayout.Button("SteamFriends.GetSmallFriendAvatar(m_Friend)")) {
			int FriendAvatar = SteamFriends.GetSmallFriendAvatar(m_Friend);
			print("SteamFriends.GetSmallFriendAvatar(" + m_Friend + ") - " + FriendAvatar);

			uint ImageWidth;
			uint ImageHeight;
			bool ret = SteamUtils.GetImageSize(FriendAvatar, out ImageWidth, out ImageHeight);

			if (ret && ImageWidth > 0 && ImageHeight > 0) {
				byte[] Image = new byte[ImageWidth * ImageHeight * 4];

				ret = SteamUtils.GetImageRGBA(FriendAvatar, Image, (int)(ImageWidth * ImageHeight * 4));

				m_SmallAvatar = new Texture2D((int)ImageWidth, (int)ImageHeight, TextureFormat.RGBA32, false, true);
				m_SmallAvatar.LoadRawTextureData(Image); // The image is upside down! "@ares_p: in Unity all texture data starts from "bottom" (OpenGL convention)"
				m_SmallAvatar.Apply();
			}
		}

		if (GUILayout.Button("SteamFriends.GetMediumFriendAvatar(m_Friend)")) {
			int FriendAvatar = SteamFriends.GetMediumFriendAvatar(m_Friend);
			print("SteamFriends.GetMediumFriendAvatar(" + m_Friend + ") - " + FriendAvatar);

			uint ImageWidth;
			uint ImageHeight;
			bool ret = SteamUtils.GetImageSize(FriendAvatar, out ImageWidth, out ImageHeight);

			if (ret && ImageWidth > 0 && ImageHeight > 0) {
				byte[] Image = new byte[ImageWidth * ImageHeight * 4];

				ret = SteamUtils.GetImageRGBA(FriendAvatar, Image, (int)(ImageWidth * ImageHeight * 4));
				m_MediumAvatar = new Texture2D((int)ImageWidth, (int)ImageHeight, TextureFormat.RGBA32, false, true);
				m_MediumAvatar.LoadRawTextureData(Image);
				m_MediumAvatar.Apply();
			}
		}

		if (GUILayout.Button("SteamFriends.GetLargeFriendAvatar(m_Friend)")) {
			int FriendAvatar = SteamFriends.GetLargeFriendAvatar(m_Friend);
			print("SteamFriends.GetLargeFriendAvatar(" + m_Friend + ") - " + FriendAvatar);

			uint ImageWidth;
			uint ImageHeight;
			bool ret = SteamUtils.GetImageSize(FriendAvatar, out ImageWidth, out ImageHeight);

			if (ret && ImageWidth > 0 && ImageHeight > 0) {
				byte[] Image = new byte[ImageWidth * ImageHeight * 4];

				ret = SteamUtils.GetImageRGBA(FriendAvatar, Image, (int)(ImageWidth * ImageHeight * 4));
				if (ret) {
					m_LargeAvatar = new Texture2D((int)ImageWidth, (int)ImageHeight, TextureFormat.RGBA32, false, true);
					m_LargeAvatar.LoadRawTextureData(Image);
					m_LargeAvatar.Apply();
				}
			}
		}
	}
コード例 #36
0
        private static LoadedTexture Convert(TextureNative src)
        {
            TextureFormat format;

            var loadMips = (src.Format & RasterFormat.ExtMipMap) == RasterFormat.ExtMipMap;
            var autoMips = (src.Format & RasterFormat.ExtAutoMipMap) == RasterFormat.ExtAutoMipMap;

            switch (src.Format & RasterFormat.NoExt) {
                case RasterFormat.BGRA8:
                case RasterFormat.BGR8:
                    format = TextureFormat.RGBA32;
                    break;
                case RasterFormat.LUM8:
                    format = TextureFormat.Alpha8;
                    break;
                case RasterFormat.R4G4B4A4:
                    format = TextureFormat.RGBA4444;
                    break;
                case RasterFormat.A1R5G5B5:
                    format = TextureFormat.ARGB32;
                    break;
                case RasterFormat.R5G6B5:
                    format = TextureFormat.RGB565;
                    break;
                default:
                    throw new NotImplementedException(string.Format("RasterFormat.{0}", src.Format & RasterFormat.NoExt));
            }

            switch (src.Compression) {
                case CompressionMode.None:
                    break;
                case CompressionMode.DXT1:
                    format = TextureFormat.DXT1;
                    break;
                case CompressionMode.DXT3:
                    format = TextureFormat.DXT5;
                    break;
                default:
                    throw new NotImplementedException(string.Format("CompressionMode.{0}", src.Compression));
            }

            var tex = new Texture2D(src.Width, src.Height, format, false /*loadMips*/);

            switch (src.FilterFlags) {
                case Filter.None:
                case Filter.Nearest:
                case Filter.MipNearest:
                    tex.filterMode = FilterMode.Point;
                    break;
                case Filter.Linear:
                case Filter.MipLinear:
                case Filter.LinearMipNearest:
                    tex.filterMode = FilterMode.Bilinear;
                    break;
                case Filter.LinearMipLinear:
                case Filter.Unknown:
                    tex.filterMode = FilterMode.Trilinear;
                    break;
            }

            var data = src.ImageData;

            switch (src.Format & RasterFormat.NoExt) {
                case RasterFormat.BGR8:
                case RasterFormat.BGRA8:
                    data = ConvertBGRToRGB(data);
                    break;
            }

            switch (src.Compression) {
                case CompressionMode.DXT3:
                    data = ConvertDXT3ToDXT5(data);
                    break;
            }

            tex.LoadRawTextureData(data);
            tex.Apply(loadMips || autoMips, true);

            return new LoadedTexture(tex, src.Alpha);
        }
コード例 #37
0
    public static Texture2D Load(string TextureName)
    {
        string TextureDestinationPath = Configuration.GameFld + Configuration.Mod + "/materials/" + TextureName + ".vtf";

        if (!File.Exists(TextureDestinationPath))
        {
            if (File.Exists(Configuration.GameFld + Configuration._Mod + "/materials/" + TextureName + ".vtf"))
                TextureDestinationPath = Configuration.GameFld + Configuration._Mod + "/materials/" + TextureName + ".vtf";
            else
                return new Texture2D(1, 1);
        }

        CRead = new CustomReader(File.OpenRead(TextureDestinationPath));
        VTF_Header = CRead.ReadType<tagVTFHEADER>();

        Texture2D VTF_Texture;
        TextureFormat ImageFormat;

        long OffsetInFile = VTF_Header.Width * VTF_Header.Height * uiBytesPerPixels[(int)VTF_Header.HighResImageFormat];

        switch (VTF_Header.HighResImageFormat)
        {
            case VTFImageFormat.IMAGE_FORMAT_DXT1:
                OffsetInFile = ((VTF_Header.Width + 3) / 4) * ((VTF_Header.Height + 3) / 4) * 8;
                ImageFormat = TextureFormat.DXT1;
                break;

            case VTFImageFormat.IMAGE_FORMAT_DXT3:
            case VTFImageFormat.IMAGE_FORMAT_DXT5:
                OffsetInFile = ((VTF_Header.Width + 3) / 4) * ((VTF_Header.Height + 3) / 4) * 16;
                ImageFormat = TextureFormat.DXT5;
                break;

            case VTFImageFormat.IMAGE_FORMAT_RGB888:
            case VTFImageFormat.IMAGE_FORMAT_BGR888:
                ImageFormat = TextureFormat.RGB24;
                break;

            case VTFImageFormat.IMAGE_FORMAT_RGBA8888:
                ImageFormat = TextureFormat.RGBA32;
                break;

            case VTFImageFormat.IMAGE_FORMAT_ARGB8888:
                ImageFormat = TextureFormat.ARGB32;
                break;

            case VTFImageFormat.IMAGE_FORMAT_BGRA8888:
                ImageFormat = TextureFormat.BGRA32;
                break;

            default:
                return new Texture2D(1, 1);
        }

        VTF_Texture = new Texture2D(VTF_Header.Width, VTF_Header.Height, ImageFormat, false);
        byte[] VTF_File = CRead.GetBytes((int)OffsetInFile, CRead.InputStream.Length - OffsetInFile);

        if (VTF_Header.HighResImageFormat == VTFImageFormat.IMAGE_FORMAT_BGR888)
        {
            for (int i = 0; i < VTF_File.Length - 1; i += 3)
            {
                byte Temp = VTF_File[i];
                VTF_File[i] = VTF_File[i + 2];
                VTF_File[i + 2] = Temp;
            }
        }

        VTF_Texture.LoadRawTextureData(VTF_File);
        CRead.Dispose();

        // MIPMAP NOT WORK!!! VERY SLOWLY!!!
        if (Configuration.AndroidCompression)
        {
            Texture2D Mip_Texture = new Texture2D(VTF_Header.Width, VTF_Header.Height);
            Mip_Texture.SetPixels32(VTF_Texture.GetPixels32());

            EditorUtility.CompressTexture(Mip_Texture, TextureFormat.ETC_RGB4, TextureCompressionQuality.Fast);
            Mip_Texture.Apply();

            return Mip_Texture;
        }

        VTF_Texture.Apply();
        return VTF_Texture;
    }
コード例 #38
0
        public static Texture2D LoadTexture(string url)
        {
            // Check cache for texture
            Texture2D texture;
            try
            {
                string path = "GameData/" + url;
                // PNG loading
                if (File.Exists(path) && path.Contains(".png"))
                {
                    texture = new Texture2D(2, 2, TextureFormat.RGBA32, false);
                    texture.LoadImage(File.ReadAllBytes(path.Replace('/', Path.DirectorySeparatorChar)));
                }
                // DDS loading
                else if (File.Exists(path) && path.Contains(".dds"))
                {
                    BinaryReader br = new BinaryReader(new MemoryStream(File.ReadAllBytes(path)));

                    if (br.ReadUInt32() != DDSValues.uintMagic)
                    {
                        throw new Exception("Format issue with DDS texture '" + path + "'!");
                    }
                    DDSHeader ddsHeader = new DDSHeader(br);
                    if (ddsHeader.ddspf.dwFourCC == DDSValues.uintDX10)
                    {
                        DDSHeaderDX10 ddsHeaderDx10 = new DDSHeaderDX10(br);
                    }

                    TextureFormat texFormat;
                    if (ddsHeader.ddspf.dwFourCC == DDSValues.uintDXT1)
                    {
                        texFormat = UnityEngine.TextureFormat.DXT1;
                    }
                    else if (ddsHeader.ddspf.dwFourCC == DDSValues.uintDXT3)
                    {
                        texFormat = UnityEngine.TextureFormat.DXT1 | UnityEngine.TextureFormat.Alpha8;
                    }
                    else if (ddsHeader.ddspf.dwFourCC == DDSValues.uintDXT5)
                    {
                        texFormat = UnityEngine.TextureFormat.DXT5;
                    }
                    else
                    {
                        throw new Exception("Unhandled DDS format!");
                    }

                    texture = new Texture2D((int)ddsHeader.dwWidth, (int)ddsHeader.dwHeight, texFormat, false);
                    texture.LoadRawTextureData(br.ReadBytes((int)(br.BaseStream.Length - br.BaseStream.Position)));
                    texture.Apply(false, true);
                }
                else
                {
                    throw new Exception("Couldn't find file for image  '" + url + "'");
                }
            }
            catch (Exception e)
            {
                LoggingUtil.LogError(typeof(TextureUtil), "Couldn't create texture for '" + url + "'!");
                Debug.LogException(e);
                texture = null;
            }

            return texture;
        }
コード例 #39
0
        public static Texture2D LoadTexture(string path)
        {
            var s_Data = File.ReadAllBytes(path);
            using (var s_Reader = new BinaryReader (new MemoryStream (s_Data))) {
                stream = s_Reader;
                u1 = Long ();
                u2 = Long ();
                format = Long ();
                u4 = Long ();
                sizex = Long ();
                sizey = Long ();
                u5 = Long ();
                mipmaps = Long ();

                int i = 0;
                while(i < mipmaps) {
                    int size = Long ();
                    mipmapsize += size;
                    i++;
                }
                int endPos = FTell ();
                int i2 = 0;
                Bytes (92 - endPos);
                byte[] mipmapdata = Bytes (mipmapsize);
                data = mipmapdata;

            }

            TextureFormat texFormat = TextureFormat.Alpha8;
            if (format == 0 || format == 18) {
                texFormat = TextureFormat.DXT1;
            } else if (format == 1) {
                texFormat = TextureFormat.DXT1; // should be dxt3
            } else if (format == 2 || format == 19 || format == 20) {
                texFormat = TextureFormat.DXT5;
            } else if (format == 9) {
                texFormat = TextureFormat.RGBA32;
            } else if (format == 10) {
                texFormat = TextureFormat.RGBA32;
            }
            Texture2D texture = null;
            bool useMipmaps = false;
            if(mipmaps > 1) {
                useMipmaps = true;
            }

            texture = new Texture2D (sizex, sizey, texFormat, useMipmaps);

            texture.LoadRawTextureData (data);
            texture.Apply ();
            return texture;
        }
コード例 #40
0
        // Method called to deserialize a Color object
        public System.Object SetObjectData(System.Object obj,
		                                   SerializationInfo info, StreamingContext context,
		                                   ISurrogateSelector selector)
        {
            int w = (int)info.GetValue("width", typeof(int));
            int h = (int)info.GetValue("height", typeof(int));
            TextureFormat format = (TextureFormat)info.GetValue("format", typeof(int));

            Texture2D texture = new Texture2D(w,h,format,false);

            Debug.Log("SetObjectData:\n" +
                      "Width:" + w + "\n" +
                      "Height:" + h + "\n" +
                      "Format:" + format + "\n" +
                      "");

            switch((int)StaticSerializer.Texture2DCompressionType){
            case 1:
            case 2:
                texture.LoadImage((byte[])info.GetValue("values", typeof(byte[])));
                break;
            case 0:
            default:
                texture.LoadRawTextureData((byte[])info.GetValue("values", typeof(byte[])));
                break;
            }

            texture.Apply();
            obj = texture;
            return obj;
        }
コード例 #41
0
ファイル: PaintingController.cs プロジェクト: Saelyria/Quip
	// returns current image (later: including all layers) as Texture2D
	public Texture2D GetCanvasAsTexture()
	{
		var image = new Texture2D((int)(texWidth/resolutionScaler), (int)(texHeight/resolutionScaler), TextureFormat.RGBA32, false);

		/*
		Mesh go_Mesh = GetComponent<MeshFilter>().mesh;
		var topLeft = cam.WorldToScreenPoint(go_Mesh.vertices[0]);
		var topRight= cam.WorldToScreenPoint(go_Mesh.vertices[3]);
		var bottomRight = cam.WorldToScreenPoint(go_Mesh.vertices[2]);
		*/
		//var image = new Texture2D((int)(bottomRight.x-topLeft.x),(int)(bottomRight.y-topRight.y), TextureFormat.ARGB32, false);

		// TODO: combine layers to single texture
		image.LoadRawTextureData(pixels);
		image.Apply(false);
		return image;
	}
コード例 #42
0
    // Update is called once per frame
    void Update()
    {
        //Added by Yuqi Ding
        MetaCoreInterop.meta_get_point_cloud(ref _metaPointCloud, _translation, _rotation);

        // obtain the rgb data
        MetaCoreInterop.meta_get_rgb_frame(RawPixelBuffer, _translation_rgb, _new_rotation_rgb);  // The buffer is pre-allocated by constructor.

        // obtain the rgb data parameter
        MetaCoreInterop.meta_get_rgb_intrinsics(ref _camera_params);

        // Check for a difference
        bool isEqual = true;

        // Check for a difference in pose (should change with each new RGB frame).
        for (int i = 0; i < _new_rotation_rgb.Length; ++i)
        {
            isEqual = _rotation_rgb[i] == _new_rotation_rgb[i];

            if (!isEqual)
            {
                break;
            }
        }

        // If the two rotations are not equal, we have a new rgb frame.
        if (!isEqual)
        {
            // Copy new rotation if it's different.
            for (int i = 0; i < _new_rotation_rgb.Length; ++i)
            {
                _rotation_rgb[i] = _new_rotation_rgb[i];
            }

            _rgbTexture.LoadRawTextureData(RawPixelBuffer, _totalBufferSize);
            _rgbTexture.Apply();
        }

        SetDepthToWorldTransform();

        if (SavePointCloud && (Time.frameCount % 48 == 0))
        {
            MarshalMetaPointCloud();

            int num = _metaPointCloud.num_points;
            if (num != 0)
            {
                //save the point cloud
                string PointCloudName = string.Format("{0}/{1:D04} shot.ply", folder, Time.frameCount);
                SavePointCloudToPly(PointCloudName, _pointCloud);
                string PointCloudIntrName = string.Format("{0}/{1:D04} pointcloud_Intr.txt", folder, Time.frameCount);
                SavePointCloudPara(PointCloudIntrName, _translation, _rotation);

                //save the rgb frame
                Color[] color2dtemp = _rgbTexture.GetPixels();
                for (int i = 0; i < color2dtemp.Length; i++)
                {
                    float temp = 0.0f;
                    temp             = color2dtemp[i].r;
                    color2dtemp[i].r = color2dtemp[i].b;
                    color2dtemp[i].b = temp;
                }
                _rgbTexture.SetPixels(color2dtemp);
                //Debug.Log("Swap r and b");

                byte[] bytes   = _rgbTexture.EncodeToJPG();
                string rgbName = string.Format("{0}/{1:D04} shot.jpg", folder, Time.frameCount);
                File.WriteAllBytes(rgbName, bytes);
                string rgbIntrName = string.Format("{0}/{1:D04} shot_Intr.txt", folder, Time.frameCount);
                SaveRGBIntrinsics(rgbIntrName, _camera_params);
                string rgbParaName = string.Format("{0}/{1:D04} shot_Para.txt", folder, Time.frameCount);
                SaveRGBPara(rgbParaName, _translation_rgb, _rotation_rgb);
            }
            // Added end
        }
    }
コード例 #43
0
	public void RenderOnGUI() {
		GUILayout.BeginArea(new Rect(Screen.width - 200, 0, 200, Screen.height));
		GUILayout.Label("Variables:");
		GUILayout.Label("m_Image:");
		GUILayout.Label(m_Image);
		GUILayout.EndArea();

		GUILayout.Label("SteamUtils.GetSecondsSinceAppActive() : " + SteamUtils.GetSecondsSinceAppActive());
		GUILayout.Label("SteamUtils.GetSecondsSinceComputerActive() : " + SteamUtils.GetSecondsSinceComputerActive());
		GUILayout.Label("SteamUtils.GetConnectedUniverse() : " + SteamUtils.GetConnectedUniverse());
		GUILayout.Label("SteamUtils.GetServerRealTime() : " + SteamUtils.GetServerRealTime());
		GUILayout.Label("SteamUtils.GetIPCountry() : " + SteamUtils.GetIPCountry());

		{
			uint ImageWidth = 0;
			uint ImageHeight = 0;
			bool ret = SteamUtils.GetImageSize(1, out ImageWidth, out ImageHeight);
			GUILayout.Label("SteamUtils.GetImageSize(1, out ImageWidth, out ImageHeight) : " + ret + " -- " + ImageWidth + " -- " + ImageHeight);

			if (GUILayout.Button("SteamUtils.GetImageRGBA(1, Image, (int)(ImageWidth * ImageHeight * 4)")) {
				if (ImageWidth > 0 && ImageHeight > 0) {
					byte[] Image = new byte[ImageWidth * ImageHeight * 4];
					ret = SteamUtils.GetImageRGBA(1, Image, (int)(ImageWidth * ImageHeight * 4));
					print("SteamUtils.GetImageRGBA(1, " + Image + ", " + (int)(ImageWidth * ImageHeight * 4) + ") - " + ret + " -- " + ImageWidth + " -- " + ImageHeight);
					if (ret) {
						m_Image = new Texture2D((int)ImageWidth, (int)ImageHeight, TextureFormat.RGBA32, false, true);
						m_Image.LoadRawTextureData(Image);
						m_Image.Apply();
					}
				}
			}
		}

		{
			uint IP;
			ushort Port;
			bool ret = SteamUtils.GetCSERIPPort(out IP, out Port);
			GUILayout.Label("SteamUtils.GetCSERIPPort(out IP, out Port) : " + ret + " -- " + IP + " -- " + Port);
		}

		GUILayout.Label("SteamUtils.GetCurrentBatteryPower() : " + SteamUtils.GetCurrentBatteryPower());
		GUILayout.Label("SteamUtils.GetAppID() : " + SteamUtils.GetAppID());

		if (GUILayout.Button("SteamUtils.SetOverlayNotificationPosition(k_EPositionTopRight)")) {
			SteamUtils.SetOverlayNotificationPosition(ENotificationPosition.k_EPositionTopRight);
			print("SteamUtils.SetOverlayNotificationPosition(k_EPositionTopRight)");
		}

		//GUILayout.Label("SteamUtils.IsAPICallCompleted() : " + SteamUtils.IsAPICallCompleted()); // N/A - These 3 functions are used to dispatch CallResults.
		//GUILayout.Label("SteamUtils.GetAPICallFailureReason() : " + SteamUtils.GetAPICallFailureReason()); // N/A
		//GUILayout.Label("SteamUtils.GetAPICallResult() : " + SteamUtils.GetAPICallResult()); // N/A

		if (GUILayout.Button("SteamUtils.RunFrame()")) {
			SteamUtils.RunFrame();
			print("SteamUtils.RunFrame()");
		}

		GUILayout.Label("SteamUtils.GetIPCCallCount() : " + SteamUtils.GetIPCCallCount());

		//GUILayout.Label("SteamUtils.SetWarningMessageHook() : " + SteamUtils.SetWarningMessageHook()); // N/A - Check out SteamTest.cs for example usage.

		GUILayout.Label("SteamUtils.IsOverlayEnabled() : " + SteamUtils.IsOverlayEnabled());
		GUILayout.Label("SteamUtils.BOverlayNeedsPresent() : " + SteamUtils.BOverlayNeedsPresent());

		if (GUILayout.Button("SteamUtils.CheckFileSignature(\"FileNotFound.txt\")")) {
			SteamAPICall_t handle = SteamUtils.CheckFileSignature("FileNotFound.txt");
			OnCheckFileSignatureCallResult.Set(handle);
			print("SteamUtils.CheckFileSignature(\"FileNotFound.txt\") - " + handle);
		}

		if(GUILayout.Button("SteamUtils.ShowGamepadTextInput(k_EGamepadTextInputModeNormal, k_EGamepadTextInputLineModeSingleLine, \"Description Test!\", 32)")) {
			bool ret = SteamUtils.ShowGamepadTextInput(EGamepadTextInputMode.k_EGamepadTextInputModeNormal, EGamepadTextInputLineMode.k_EGamepadTextInputLineModeSingleLine, "Description Test!", 32, "test");
			print("SteamUtils.ShowGamepadTextInput(k_EGamepadTextInputModeNormal, k_EGamepadTextInputLineModeSingleLine, \"Description Test!\", 32) - " + ret);
		}

		// Only called from within GamepadTextInputDismissed_t Callback!
		/*GUILayout.Label("SteamUtils.GetEnteredGamepadTextLength() : " + SteamUtils.GetEnteredGamepadTextLength());

		{
			string Text;
			bool ret = SteamUtils.GetEnteredGamepadTextInput(out Text, 32);
			GUILayout.Label("SteamUtils.GetEnteredGamepadTextInput(out Text, 32) - " + ret + " -- " + Text);
		}*/

		GUILayout.Label("SteamUtils.GetSteamUILanguage() : " + SteamUtils.GetSteamUILanguage());

		GUILayout.Label("SteamUtils.IsSteamRunningInVR() : " + SteamUtils.IsSteamRunningInVR());

		if (GUILayout.Button("SteamUtils.SetOverlayNotificationInset(400, 400)")) {
			SteamUtils.SetOverlayNotificationInset(400, 400);
			print("SteamUtils.SetOverlayNotificationInset(400, 400)");
		}
	}
コード例 #44
0
	public static Texture2D LoadTexture2DFromGamedata(string scd, string LocalPath, bool NormalMap = false){
		if(string.IsNullOrEmpty(LocalPath)) return null;

		if(!Directory.Exists(EnvPaths.GetGamedataPath())){
			Debug.LogError("Gamedata path not exist!");
			return null;
		}
		ZipFile zf = null;
		Texture2D texture = null;


		bool Mipmaps = false;
		try{
			FileStream fs = File.OpenRead(EnvPaths.GetGamedataPath() + scd);
			zf = new ZipFile(fs);


			ZipEntry zipEntry2 =  zf.GetEntry(LocalPath);
			if(zipEntry2 == null){
				Debug.LogError("Zip Entry is empty for: " + LocalPath);
				return null;
			}

			byte[] FinalTextureData2 = new byte[4096]; // 4K is optimum

			if (zipEntry2 != null)
			{
				Stream s = zf.GetInputStream(zipEntry2);
				FinalTextureData2 = new byte[zipEntry2.Size];
				s.Read(FinalTextureData2, 0, FinalTextureData2.Length);
			}

			TextureFormat format = GetFormatOfDdsBytes(FinalTextureData2);
			Mipmaps = LoadDDsHeader.mipmapcount > 0;
			texture = new Texture2D((int)LoadDDsHeader.width, (int)LoadDDsHeader.height, format, Mipmaps, true);

			int DDS_HEADER_SIZE = 128;
			byte[] dxtBytes = new byte[FinalTextureData2.Length - DDS_HEADER_SIZE];
			Buffer.BlockCopy(FinalTextureData2, DDS_HEADER_SIZE, dxtBytes, 0, FinalTextureData2.Length - DDS_HEADER_SIZE);

			if(IsDxt3){
				texture = DDS.DDSReader.LoadDDSTexture( new MemoryStream(FinalTextureData2), false).ToTexture2D();
				texture.Apply(false);
			}
			else{
				texture.LoadRawTextureData(dxtBytes);
				texture.Apply(false);
			}
		} finally {
			if (zf != null) {
				zf.IsStreamOwner = true; // Makes close also shut the underlying stream
				zf.Close(); // Ensure we release resources
			}
		}

		if(NormalMap){
			texture.Compress(true);

			Texture2D normalTexture = new Texture2D((int)LoadDDsHeader.width, (int)LoadDDsHeader.height, TextureFormat.RGBA32, Mipmaps, true);

			Color theColour = new Color();
			Color[] Pixels;

			for(int m = 0; m < LoadDDsHeader.mipmapcount + 1; m++){
				int Texwidth = texture.width;
				int Texheight = texture.height;

				if(m > 0){
					Texwidth /= (int)Mathf.Pow(2, m);
					Texheight /= (int)Mathf.Pow(2, m);
				}
				Pixels = texture.GetPixels(0, 0, Texwidth, Texheight, m);

				for(int i = 0; i < Pixels.Length; i++){
					theColour.r = Pixels[i].r;
					theColour.g = Pixels[i].g;
					theColour.b = 1;
					theColour.a = Pixels[i].g;
					Pixels[i] = theColour;
				}
				normalTexture.SetPixels(0, 0, Texwidth, Texheight, Pixels, m);
			}

			normalTexture.Apply(false);

			normalTexture.mipMapBias = MipmapBias;
			normalTexture.filterMode = FilterMode.Bilinear;
			normalTexture.anisoLevel = AnisoLevel;
			return normalTexture;
		}
		else{
			texture.mipMapBias = MipmapBias;
			texture.filterMode = FilterMode.Bilinear;
			texture.anisoLevel = AnisoLevel;
		}

		return texture;
	}