Apply() private méthode

private Apply ( ) : void
Résultat void
 /// <summary>
 /// Initializes a new instance of the <see cref="UnityGwenRenderer"/> class.
 /// </summary>
 /// <param name="target">Unity render target.</param>
 public UnityGwenRenderer()
 {
     whiteTex = new Texture2D(1, 1);
     whiteTex.SetPixel(0, 0, UnityEngine.Color.white);
     whiteTex.Apply();
     m_ViewScale = Vector2.one;
 }
        public static void DrawRectWithOutline( Rect rect, Color color, Color colorOutline )
        {
            #if UNITY_EDITOR
            Vector3[] rectVerts = { new Vector3(rect.x, rect.y, 0),
                new Vector3(rect.x + rect.width, rect.y, 0),
                new Vector3(rect.x + rect.width, rect.y + rect.height, 0),
                new Vector3(rect.x, rect.y + rect.height, 0) };
            Handles.DrawSolidRectangleWithOutline(rectVerts, color, colorOutline);
            #else
            Texture2D texture = new Texture2D(1, 1);
            texture.SetPixel(0,0,colorOutline);
            texture.Apply();

            Rect rLine = new Rect( rect.x, rect.y, rect.width, 1 );
            GUI.DrawTexture(rLine, texture);
            rLine.y = rect.y + rect.height - 1;
            GUI.DrawTexture(rLine, texture);
            rLine = new Rect( rect.x, rect.y+1, 1, rect.height-2 );
            GUI.DrawTexture(rLine, texture);
            rLine.x = rect.x + rect.width - 1;
            GUI.DrawTexture(rLine, texture);

            rect.x += 1;
            rect.y += 1;
            rect.width -= 2;
            rect.height -= 2;
            texture.SetPixel(0,0,color);
            texture.Apply();
            GUI.DrawTexture(rect, texture);
            #endif
        }
Exemple #3
0
    Texture2D AltGenTex(Vector3[] verts, ModuleBase module)
    {
        Texture2D tex = new Texture2D((int) Mathf.Sqrt(verts.Length), (int) Mathf.Sqrt(verts.Length));

        int reso = (int) Mathf.Sqrt(verts.Length);
        int pixelx = 0;
        int pixely = 0;

        for (int i = 0; i < verts.Length; i++)
        {
            verts[i] = transform.TransformPoint(verts[i]);
            if (pixelx == reso)
                {
                    pixelx = 0;
                    pixely += 1;
                }
            float noiseval = (float) module.GetValue(verts[i]);
            noiseval = Mathf.Clamp(noiseval + 0.5f, 0f, 1f);
            Color pixelColor = new Color(noiseval, noiseval, noiseval, 0);
            tex.SetPixel(pixelx, pixely, pixelColor);
            tex.Apply();
            pixelx += 1;
        }

        tex.Apply();
        return tex;
    }
	public void StartProcess () {

//		TextureScale.Bilinear (screenshot, 90, 160);
		copy = Instantiate(screenshot);
		pixels = copy.GetPixels();
		
		for(int i=0; i<pixels.Length; i++){
			r_color_map[(i/screenshot.width), i%screenshot.width,0] = (int)(pixels[i].r*255);
			r_color_map[(i/screenshot.width), i%screenshot.width,1] =(int)(pixels[i].g*255);
			r_color_map[i/screenshot.width, i%screenshot.width,2] =(int)(pixels[i].b*255);

			float gray = pixels[i].grayscale;
			pixels[i] = new Color(1f-gray, 1f-gray, 1f-gray, pixels[i].a);
		}
		copy.SetPixels(pixels);
		copy.Apply();
		copy = ChangeTextureContrast(copy, 0.999f);
		copy.Apply();

		AnalyTexture(copy.GetPixels());

		try{
			SaveLoad.SaveColorMap(r_color_map);
			SaveLoad.SaveEdgeMap(r_edge_map);
			SaveLoad.SaveEdgeGroup(r_edge_group);
		}catch{};


		Finished = true;

		MFS = GetComponent<MapFromScreenshot>();
		if(MFS!=null && MFS!=null){ //try to move map infront camera(in map creating page)
			
			transform.position =  new Vector3(-113f, -190f, -354f);
			transform.eulerAngles = new Vector3(-59f/360f, -26f/360f, -90f/360f);
			transform.localScale = new Vector3(0.01f, 0.01f, 0.01f);
		}
		// -------------------------------------for debug GUI ---------------------------------------------------------
		for(int i =0;i<pixels.Length; i++){
			pixels[i] = Color.black;
			if(r_edge_map[i/copy.width, i%copy.width]==1)
				pixels[i] = Color.white;
		}
		
		foreach(List<int[]> group in r_edge_group){
			float r_color = Random.Range(0f,1f);
			float r_color_g = Random.Range(0f,1f);
			float r_color_b = Random.Range(0f,1f);

			foreach(int[] point in group){
				pixels[point[1]*copy.width + point[0]] = new Color(r_color, r_color_g, r_color_b);
			}
		}
		copy.SetPixels(pixels);
		copy.Apply();
		show = false;

		//-------------------------------------------------------------------------------------------------------------
	}
    IEnumerator ConvertToImage()
    {
        //grab the main camera and mess with it for rendering the object - make sure orthographic
            Camera cam = Camera.main;
            cam.orthographic = true;

            //render to screen rect area equal to out image size
            float rw  = imageWidth;
            rw /= Screen.width;
            float rh = imageHeight;
            rh /= Screen.height;
            cam.rect = new Rect(0,0,rw,rh);

            //grab size of object to render - place/size camera to fit
            Bounds bb = objectToRender.GetComponent<Renderer>().bounds;

            //place camera looking at centre of object - and backwards down the z-axis from it
            cam.transform.position = bb.center;
            cam.transform.position.Set(cam.transform.position.x, cam.transform.position.y, -1.0f + (bb.min.z * 2.0f));
            //make clip planes fairly optimal and enclose whole mesh
            cam.nearClipPlane = 0.5f;
            cam.farClipPlane = -cam.transform.position.z + 10.0f + bb.max.z;
            //set camera size to just cover entire mesh
            cam.orthographicSize = 1.01f * Mathf.Max( (bb.max.y - bb.min.y)/2.0f, (bb.max.x - bb.min.x)/2.0f);
            cam.transform.position.Set(cam.transform.position.x, cam.orthographicSize * 0.05f, cam.transform.position.y);

            //render
            yield return new WaitForEndOfFrame();

            var tex = new Texture2D( imageWidth, imageHeight, TextureFormat.ARGB32, false );
            // Read screen contents into the texture
            tex.ReadPixels(new Rect(0, 0, imageWidth, imageHeight), 0, 0 );
            tex.Apply();

            //turn all pixels == background-color to transparent
            Color bCol = cam.backgroundColor;
            Color alpha = bCol;
            alpha.a = 0.0f;
            for(int y = 0; y < imageHeight; y++)
            {
                for(int x = 0; x < imageWidth; x++)
                {
                    Color c = tex.GetPixel(x,y);
                    if (c.r == bCol.r)
                        tex.SetPixel(x,y,alpha);
                }
            }
            tex.Apply();

            // Encode texture into PNG
            byte[] bytes = tex.EncodeToPNG();
            Destroy( tex );
            System.IO.File.WriteAllBytes(Application.dataPath + "/../billboard.png", bytes);
    }
Exemple #6
0
        void Update()
        {
            TimerManager.Instance.UpdateFunc(Time.deltaTime);

            calTime += Time.deltaTime;
            if (calTime > perTime)
            {
                calTime = 0;

                UnityEngine.Color color = UnityEngine.Color.white;
                pipeline.Render();

                for (int h = 0; h < Global.screenHeight; h++)
                {
                    for (int w = 0; w < Global.screenWidth; w++)
                    {
                        Color colorData = pipeline.backBuffer.GetColor(w, h);
                        color.r = colorData.r;
                        color.g = colorData.g;
                        color.b = colorData.b;
                        color.a = colorData.a;

                        texture.SetPixel(w, h, color);
                    }
                }
                texture.Apply();
            }
        }
    public void Generate2DTexture()
    {
        texture2D = new Texture2D(n,n,TextureFormat.ARGB32,true);
        int size = n*n;
        Color[] cols = new Color[size];
        float u,v;
        int idx = 0;
        Color c = Color.white;
        for(int i = 0; i < n; i++) {
            u = i/(float)n;
            for(int j = 0; j < n; j++, ++idx) {
              	v = j/(float)n;
                float noise = Mathf.PerlinNoise(u,v);
                c.r = c.g = c.b = noise;
                cols[idx] = c;

            }
        }

        texture2D.SetPixels(cols);
        texture2D.Apply();
        renderer.material.SetTexture("g_tex", texture2D);

        //Color[] cs = texture3D.GetPixels();
        //for(int i = 0; i < 10; i++)
        //	Debug.Log (cs[i]);
    }
Exemple #8
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);
 }
        private Texture2D DownSample(Texture2D src)
        {
            int width = 1024, height = 512;
            Texture2D dst = new Texture2D(width, height, TextureFormat.ARGB32, false);
            Color[] cs = new Color[width * height];
            for (int x = 0; x < width; ++x)
            for (int y = 0; y < height; ++y) {
                int dstIndex = x + y * width;
                Color dstColor = Color.black;

                for (int subX = 0; subX < 4; ++subX)
                    for (int subY = 0; subY < 4; ++subY) {
                        Color srcColor = src.GetPixel(x * 4 + subX, y * 4 + subY);
                        dstColor += srcColor;
                    }

                dstColor /= 16.0f;
                dstColor.a = 1.0f;

                cs[dstIndex] = dstColor;
            }
            dst.SetPixels(cs);
            dst.Apply();

            return dst;
        }
        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);
        }
Exemple #11
0
 public static UnityEngine.Texture2D CreateTemporaryDuplicate(UnityEngine.Texture2D original, int width, int height)
 {
     UnityEngine.Texture2D result;
     if (!ShaderUtil.hardwareSupportsRectRenderTexture || !original)
     {
         result = null;
     }
     else
     {
         RenderTexture active          = RenderTexture.active;
         Rect          rawViewportRect = ShaderUtil.rawViewportRect;
         RenderTexture temporary       = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.sRGB);
         Graphics.Blit(original, temporary, EditorGUIUtility.GUITextureBlit2SRGBMaterial);
         RenderTexture.active = temporary;
         bool flag = width >= SystemInfo.maxTextureSize || height >= SystemInfo.maxTextureSize;
         UnityEngine.Texture2D texture2D = new UnityEngine.Texture2D(width, height, TextureFormat.RGBA32, original.mipmapCount > 1 || flag);
         texture2D.ReadPixels(new Rect(0f, 0f, (float)width, (float)height), 0, 0);
         texture2D.Apply();
         RenderTexture.ReleaseTemporary(temporary);
         EditorGUIUtility.SetRenderTextureNoViewport(active);
         ShaderUtil.rawViewportRect    = rawViewportRect;
         texture2D.alphaIsTransparency = original.alphaIsTransparency;
         result = texture2D;
     }
     return(result);
 }
Exemple #12
0
 private Texture2D loadIcon(string path)
 {
     Texture2D result = new Texture2D(1, 1);
         result.LoadImage(System.IO.File.ReadAllBytes(PATH+path));
     result.Apply();
     return result;
 }
    public IEnumerator GetAd(int id)
    {
		BusinessCard = null;
        adReady = false;
        hasAd = false;
        BusinessID = id;
        string adURL = serverURL + "getAd?b=" + id;
        string bcURL = serverURL + "bizcard?id=" + id;

        WWW card = new WWW(bcURL);
        yield return card;
        BusinessCard = new Texture2D(Convert.ToInt32(card.texture.width),
                              Convert.ToInt32(card.texture.height),
                              TextureFormat.ARGB32, false);
        BusinessCard.SetPixels(card.texture.GetPixels());
        BusinessCard.Apply();

        WWW page = new WWW(adURL);
        yield return page;
        if (page.error == null && page.text[0] == '{')
        {
            Debug.Log(page.text);
            // Get the ad as a Dictionary object.
            hasAd = true;
            Dictionary<string, object> ad = Json.Deserialize(page.text) as Dictionary<string, object>;
            AdImages(ad);
            AdInfo = new AdData(ad);
        }

        adReady = true;
    }
    IEnumerator ScreenshotEncode()
    {
        // wait for graphics to render
        yield return new WaitForEndOfFrame();

        // create a texture to pass to encoding
        Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);

        // put buffer into texture
        texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        texture.Apply();

        // split the process up--ReadPixels() and the GetPixels() call inside of the encoder are both pretty heavy
        yield return 0;

        byte[] bytes = texture.EncodeToPNG();

        count = PlayerPrefs.GetInt("count");

        // save our test image (could also upload to WWW)
        File.WriteAllBytes(Application.dataPath + "/../testscreen-" + count + ".png", bytes);
        count++;

        PlayerPrefs.SetInt("count", count);

        // Added by Karl. - Tell unity to delete the texture, by default it seems to keep hold of it and memory crashes will occur after too many screenshots.
        DestroyObject(texture);

        Debug.Log( Application.dataPath + "/../testscreen-" + count + ".png" );
    }
Exemple #15
0
        private void ConstructForceTexture()
        {
            float w = WIDTH;
            float h = HEIGHT;

            //float top = Screen.height / 2;
            //float left = Screen.width / 2;

            _barTexture = new Texture2D((int)w, (int)h);

            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    _barTexture.SetPixel(i, j, new Color(((float)j) / h, 1.0f - ((float)j) / h, 0.2f, 1.0f));
                }
            }

            _barTexture.Apply();

            _backgroundTexture = new Texture2D((int)w, (int)h);

            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    _backgroundTexture.SetPixel(i, j, new Color(0.14f, 0.15f, 0.16f, 0.7f));
                }
            }

            _backgroundTexture.Apply();
        }
 static public int Apply(IntPtr l)
 {
     try{
         if (matchType(l, 2, typeof(bool), typeof(bool)))
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Boolean        a1;
             checkType(l, 2, out a1);
             System.Boolean a2;
             checkType(l, 3, out a2);
             self.Apply(a1, a2);
             return(0);
         }
         else if (matchType(l, 2, typeof(bool)))
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Boolean        a1;
             checkType(l, 2, out a1);
             self.Apply(a1);
             return(0);
         }
         else if (matchType(l, 2))
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             self.Apply();
             return(0);
         }
         LuaDLL.luaL_error(l, "No matched override function to call");
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
 static public int Apply(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 1)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             self.Apply();
             return(0);
         }
         else if (argc == 2)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Boolean        a1;
             checkType(l, 2, out a1);
             self.Apply(a1);
             return(0);
         }
         else if (argc == 3)
         {
             UnityEngine.Texture2D self = (UnityEngine.Texture2D)checkSelf(l);
             System.Boolean        a1;
             checkType(l, 2, out a1);
             System.Boolean a2;
             checkType(l, 3, out a2);
             self.Apply(a1, a2);
             return(0);
         }
         return(error(l, "No matched override function to call"));
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
 public static UnityEngine.Texture2D CreateTemporaryDuplicate(UnityEngine.Texture2D original, int width, int height)
 {
     UnityEngine.Texture2D result;
     if (!ShaderUtil.hardwareSupportsRectRenderTexture || !original)
     {
         result = null;
     }
     else
     {
         RenderTexture active    = RenderTexture.active;
         bool          flag      = !TextureUtil.GetLinearSampled(original);
         RenderTexture temporary = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, (!flag) ? RenderTextureReadWrite.Linear : RenderTextureReadWrite.sRGB);
         GL.sRGBWrite = (flag && QualitySettings.activeColorSpace == ColorSpace.Linear);
         Graphics.Blit(original, temporary);
         GL.sRGBWrite         = false;
         RenderTexture.active = temporary;
         bool flag2 = width >= SystemInfo.maxTextureSize || height >= SystemInfo.maxTextureSize;
         UnityEngine.Texture2D texture2D = new UnityEngine.Texture2D(width, height, TextureFormat.RGBA32, original.mipmapCount > 1 || flag2);
         texture2D.ReadPixels(new Rect(0f, 0f, (float)width, (float)height), 0, 0);
         texture2D.Apply();
         RenderTexture.ReleaseTemporary(temporary);
         EditorGUIUtility.SetRenderTextureNoViewport(active);
         texture2D.alphaIsTransparency = original.alphaIsTransparency;
         result = texture2D;
     }
     return(result);
 }
    /// <summary>
    /// Converts vector data stored within a texture using the specified basis.  Assume all calculations are performed in tangent space.
    /// </summary>
    /// <param name='basis'>
    /// Basis to multiply the vector values against.
    /// </param>
    /// <param name='vectorData'>
    /// Texture2D containing vector data.  Textures are passed by reference, so make sure to copy beforehand if you don't want to overwrite your data!
    /// </param>
    public static void ConvertTangentBasis(Matrix4x4 basis, ref Texture2D vectorData, bool recomputeZ = false)
    {
        Color[] colorData = vectorData.GetPixels();
        Texture2D tmpTexture = new Texture2D(vectorData.width, vectorData.height, TextureFormat.ARGB32, false);

        for (int i = 0; i < colorData.Length; i++)
        {
            Color vecData = new Color(colorData[i].r, colorData[i].g, colorData[i].b, 1);
            vecData.r = Vector3.Dot(new Vector3(basis.m00, basis.m01, basis.m02), UnpackUnitVector(new Vector3(colorData[i].r, colorData[i].g, colorData[i].b))) * 0.5f + 0.5f;
            vecData.g = Vector3.Dot(new Vector3(basis.m10, basis.m11, basis.m12), UnpackUnitVector(new Vector3(colorData[i].r, colorData[i].g, colorData[i].b))) * 0.5f + 0.5f;
            if (recomputeZ)
            {
                vecData.r = vecData.r * 2 - 1;
                vecData.g = vecData.g * 2 - 1;
                vecData.b = Mathf.Sqrt(1 - vecData.r * vecData.r - vecData.g * vecData.g) * 0.5f + 0.5f;
                vecData.r = vecData.r * 0.5f + 0.5f;
                vecData.g = vecData.g * 0.5f + 0.5f;
            } else {
                vecData.b = Vector3.Dot(new Vector3(basis.m20, basis.m21, basis.m22), UnpackUnitVector(new Vector3(colorData[i].r, colorData[i].g, colorData[i].b))) * 0.5f + 0.5f;
            }
            colorData[i] = vecData;
        }
        tmpTexture.SetPixels(colorData);
        tmpTexture.Apply();
        vectorData = tmpTexture;
    }
        public static UnityTexture2D RenderStaticPreview(Sprite sprite, Color color, int width, int height, Matrix4x4 transform)
        {
            if (sprite == null)
            {
                return(null);
            }

            PreviewHelpers.AdjustWidthAndHeightForStaticPreview((int)sprite.rect.width, (int)sprite.rect.height, ref width, ref height);

            SavedRenderTargetState savedRTState = new SavedRenderTargetState();

            RenderTexture tmp = RenderTexture.GetTemporary(width, height, 0, SystemInfo.GetGraphicsFormat(DefaultFormat.LDR));

            RenderTexture.active = tmp;
            GL.Clear(true, true, new Color(0f, 0f, 0f, 0.1f));

            previewSpriteDefaultMaterial.mainTexture = sprite.texture;
            previewSpriteDefaultMaterial.SetPass(0);

            RenderSpriteImmediate(sprite, color, transform);

            UnityTexture2D copy = new UnityTexture2D(width, height, TextureFormat.ARGB32, false);

            copy.hideFlags = HideFlags.HideAndDontSave;
            copy.ReadPixels(new Rect(0, 0, width, height), 0, 0);
            copy.Apply();
            RenderTexture.ReleaseTemporary(tmp);

            savedRTState.Restore();
            return(copy);
        }
Exemple #21
0
	void Start ()
	{
		mTrans = transform;
		mUITex = GetComponent<UITexture>();
		mCam = UICamera.FindCameraForLayer(gameObject.layer);

		mWidth = mUITex.width;
		mHeight = mUITex.height;
		Color[] cols = new Color[mWidth * mHeight];

		for (int y = 0; y < mHeight; ++y)
		{
			float fy = (y - 1f) / mHeight;

			for (int x = 0; x < mWidth; ++x)
			{
				float fx = (x - 1f) / mWidth;
				int index = x + y * mWidth;
				cols[index] = Sample(fx, fy);
			}
		}

		mTex = new Texture2D(mWidth, mHeight, TextureFormat.RGB24, false);
		mTex.SetPixels(cols);
		mTex.filterMode = FilterMode.Trilinear;
		mTex.wrapMode = TextureWrapMode.Clamp;
		mTex.Apply();
		mUITex.mainTexture = mTex;

		Select(value);
	}
Exemple #22
0
 public static UnityEngine.Texture2D RenderStaticPreview(Sprite sprite, Color color, int width, int height, Matrix4x4 transform)
 {
     UnityEngine.Texture2D result;
     if (sprite == null)
     {
         result = null;
     }
     else
     {
         PreviewHelpers.AdjustWidthAndHeightForStaticPreview((int)sprite.rect.width, (int)sprite.rect.height, ref width, ref height);
         SavedRenderTargetState savedRenderTargetState = new SavedRenderTargetState();
         RenderTexture          temporary = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Default);
         RenderTexture.active = temporary;
         GL.Clear(true, true, new Color(0f, 0f, 0f, 0.1f));
         SpriteUtility.previewSpriteDefaultMaterial.mainTexture = sprite.texture;
         SpriteUtility.previewSpriteDefaultMaterial.SetPass(0);
         SpriteUtility.RenderSpriteImmediate(sprite, color, transform);
         UnityEngine.Texture2D texture2D = new UnityEngine.Texture2D(width, height, TextureFormat.ARGB32, false);
         texture2D.hideFlags = HideFlags.HideAndDontSave;
         texture2D.ReadPixels(new Rect(0f, 0f, (float)width, (float)height), 0, 0);
         texture2D.Apply();
         RenderTexture.ReleaseTemporary(temporary);
         savedRenderTargetState.Restore();
         result = texture2D;
     }
     return(result);
 }
        public void DoDrawTextureCircle(Texture2D tex, int cx, int cy, int r, Color col)
        {
            //Color32 _col = (Color32)col;

               int x, y, px, nx, py, ny, d;

              // Color32[] tempArray = tex.GetPixels32();

               for (x = 0; x <= r; x++)
               {
             d = (int)Mathf.Ceil(Mathf.Sqrt(r * r - x * x));
             for (y = 0; y <= d; y++)
             {
              px = cx + x;
              nx = cx - x;
              py = cy + y;
              ny = cy - y;

             tex.SetPixel(px, py, col);
              	tex.SetPixel(nx, py, col);

             	 tex.SetPixel(px, ny, col);
             	 tex.SetPixel(nx, ny, col);

             // tempArray[py*1024 + px] = _col;
             // tempArray[py*1024 + nx] = _col;
             // tempArray[ny*1024 + px] = _col;
               //   tempArray[ny*1024 + nx] = _col;
             }
               }
             //  tex.SetPixels32(tempArray);
               tex.Apply ();
        }
Exemple #24
0
 public UnityEngine.Texture2D ToUnityType()
 {
     UnityEngine.Texture2D texture2D = new UnityEngine.Texture2D(1, 1);
     texture2D.LoadImage(pixels);
     texture2D.Apply();
     return(texture2D);
 }
    void OnGUI()
    {
        if (gameOver) {
            string gameOverText = "";
            int textSize = Screen.width / 40;
            textSize = textSize < 12 ? 12 : textSize;
            Texture2D texture = new Texture2D(1, 1);
            texture.SetPixel(0, 0, new Color(0.0f, 0.0f, 0.0f, 0.5f));
            texture.Apply();
            GUI.skin.box.normal.background = texture;
            if (EnemyInterScript.numEnemies != 0)
            {
                gameOverText = "<size=" + textSize + ">Those sneaky cyber people kicked your butt..\n Monday could not get any worse than this.\n"
                    + "Initiating time relapse...\n Press Enter to restart or press Escape to exit.</size>";
            }
            else
            {
                gameOverText = "<size=" + textSize + ">Ritual!!! You win!!!\n"
                    + "Initiating time relapse...\n Press Enter to restart or press Escape to exit.</size>";
            }
            GUI.Box(new Rect(Screen.width * 0.25f, Screen.height * 0.25f, Screen.width * 0.5f, Screen.height * 0.5f), GUIContent.none);
            GUI.Label(new Rect(Screen.width * 0.25f, Screen.height * 0.25f, Screen.width * 0.5f, Screen.height * 0.5f), gameOverText);
        }

    }
Exemple #26
0
        public Monitor(Int32[] arr, UInt16 ptr, UInt16 chars, UInt16 colPtr, UInt16 modePointer)
        {
            mem = arr;
            pointer = ptr;
            charSetPtr = chars;
            colors = new Color[16];
            modePtr = modePointer;
            for (int i = 0; i < 16; ++i) {
                colors[i] = new Color();
                colors[i].a = 1.0f;
            }
            colorPointer = colPtr;

            image = new Texture2D(256, 256, TextureFormat.ARGB32, false);
            windowPos = new Rect();
            if ((windowPos.x == 0) && (windowPos.y == 0))//windowPos is used to position the GUI window, lets set it in the center of the screen
            {
                windowPos = new Rect(Screen.width / 2, Screen.height / 2, 100, 100);
            }
            //Set all the pixels to black. If you don't do this the image contains random junk.
            for (int y = 0; y < image.height; y++) {
                for (int x = 0; x < image.width; x++) {
                    image.SetPixel(x, y, Color.black);
                }
            }
            image.Apply();
        }
Exemple #27
0
 private void CreateGrassTexture()
 {
     grassTexture = new Texture2D(2,2);
     grassTexture.SetPixels(new Color[]{Color.green,Color.green,Color.green,Color.green});
     grassTexture.filterMode = FilterMode.Point;
     grassTexture.Apply();
 }
        public static bool LoadTexture2DLutFromImage( Texture2D texture, ToolSettings settings, out Texture2D lutTexture )
        {
            var width = settings.Resolution.TargetWidth;
            var height = settings.Resolution.TargetHeight;

            var size = settings.LUT.Size;
            var cols = settings.LUT.Columns;
            var rows = settings.LUT.Rows;

            var imageData = texture.GetPixels();

            var lutText = new Texture2D( size * size, size, TextureFormat.ARGB32, false );
            var lutData = new Color[ size * size * size ];

            for ( int h = 0, i = 0; h < size; h++ )
            {
                for ( int r = 0; r < rows; r++ )
                {
                    for ( int w = 0; w < size * cols; w++ )
                    {
                        var x = w;
                        var y = h + r * size;
                        y = height - 1 - y;
                        lutData[ i++ ] = imageData[ x + y * width ];
                    }
                }
            }

            lutText.SetPixels( lutData );
            lutText.Apply();
            lutTexture = lutText;

            return true;
        }
Exemple #29
0
	public override Texture2D CreateSprite (Texture2D texture)
	{
		Color[] pixels = texture.GetPixels ();
		Color[,] pixels2D = new Color[texture.width, texture.height];
		for (int i = 0; i < pixels.Length; i++) {
			
			int x = i % texture.width;
			int y = i / texture.height;

			pixels2D [x, y] = pixels [i];
		}

		int amountOfEyes = (int)(sightAngle / 45);
		for (int i = 0; i < amountOfEyes; i++) {
			
			int radius = (texture.width - eyeSize) / 2;
			float xPos = Mathf.Sin (Mathf.Deg2Rad * (i * 45));
			float yPos = Mathf.Cos (Mathf.Deg2Rad * (i * 45));
			Vector2 pos = new Vector2 (xPos, yPos) * radius + new Vector2 (texture.width - eyeSize, texture.height - eyeSize) / 2;

			ApplyKernel (ref pixels2D, texture.width, texture.height, pos);
		}

		for (int x = 0; x < pixels2D.GetLength (0); x++) {
			for (int y = 0; y < pixels2D.GetLength (1); y++) {
				
				pixels [x + y * texture.width] = pixels2D [x, y];
			}
		}

		texture.SetPixels (pixels);
		texture.Apply ();

		return texture;
	}
    public IEnumerator TakeScreenShot()
    {
        yield return new WaitForEndOfFrame();

        Camera camOV = OVcamera.GetComponent<Camera>();

        RenderTexture currentRT = RenderTexture.active;

        RenderTexture.active = camOV.targetTexture;
        camOV.Render();
        Texture2D imageOverview = new Texture2D(camOV.targetTexture.width, camOV.targetTexture.height, TextureFormat.RGB24, false);
        imageOverview.ReadPixels(new Rect(0, 0, camOV.targetTexture.width, camOV.targetTexture.height), 0, 0);
        imageOverview.Apply();
        RenderTexture.active = currentRT;

        // Encode texture into PNG
        byte[] bytes = imageOverview.EncodeToPNG();

        // save in memory
        //string filename = fileName(Convert.ToInt32(imageOverview.width), Convert.ToInt32(imageOverview.height));
        string filename = fileName(resWidth, resHeight);
        //path = Application.persistentDataPath + "/Snapshots/" + filename;
        path = filename;

        System.IO.File.WriteAllBytes(path, bytes);
    }
Exemple #31
0
        IEnumerator PostScreenshot()
        {
            yield return new WaitForEndOfFrame();

            var cam = Camera.current;
            var renderTexture = new RenderTexture(Screen.width, Screen.height, 24);
            cam.targetTexture = renderTexture;
            cam.Render();
            cam.targetTexture = null;

            Texture2D screenshot = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGB24, false);
            screenshot.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
            screenshot.Apply();
            Debug.Log("Screenshot taken...");

            Imvu.Login().Then(
                userModel => userModel.GetPersonalFeed()
            ).Then(
                feedCollection => {
                    return feedCollection.PostImage(screenshot);
                }
            ).Then(
                _ => Debug.Log("Screenshot posted!")
            ).Catch(
                error => Debug.Log(error.message)
            );
        }
Exemple #32
0
        public MiniMapSector(int x, int y, int z)
        {
            SectorX = x;
            SectorY = y;
            SectorZ = z;

            Texture2D = new Texture2D(Constants.MiniMapSectorSize, Constants.MiniMapSectorSize, TextureFormat.ARGB32, true)
            {
                filterMode = FilterMode.Point
            };

            Texture2D.SetPixels(Enumerable.Repeat(Color.black, Constants.MiniMapSectorSize * Constants.MiniMapSectorSize).ToArray());
            Texture2D.Apply();

            m_WaypointsTexture2D = new Texture2D(Constants.MiniMapSectorSize, Constants.MiniMapSectorSize, TextureFormat.ARGB32, true)
            {
                filterMode = FilterMode.Point
            };

            m_WaypointsTexture2D.SetPixels(Enumerable.Repeat(Colors.ColorFrom8Bit(Constants.PathCostUndefined), Constants.MiniMapSectorSize * Constants.MiniMapSectorSize).ToArray());
            m_WaypointsTexture2D.Apply();

            for (int i = 0; i < m_Cost.Length; i++)
            {
                m_Cost[i] = Constants.PathCostUndefined;
            }
        }
	private Texture2D getTexture(float alph){

		float alpha = Mathf.Clamp01 (alph);

		if (textureForMaterial == null || lastAlpha  != alpha) {

			lastAlpha = alpha;

			textureForMaterial = new Texture2D (400,400);
		
			int borderWidth = 5;
			Color bordercolor = new Color(103f/255f, 230f/255f, 236f/255f, alpha);


			for (int x = 0; x < textureForMaterial.width; x++) {

				for (int y = 0; y < textureForMaterial.height; y++) {

					if ((x < borderWidth || x > textureForMaterial.width - borderWidth) || (y < borderWidth || y > textureForMaterial.height - borderWidth)) {
						textureForMaterial.SetPixel (x, y, bordercolor);
					} else {
						textureForMaterial.SetPixel (x, y, Color.clear);
					}

				}

			}

			textureForMaterial.Apply ();

		}

		return textureForMaterial;

	}
Exemple #34
0
        void InitModules()
        {
            m_AllRegisteredModules = new List <SpriteEditorModuleBase>();
            m_ModuleRequireSpriteDataProvider.Clear();

            if (m_OutlineTexture == null)
            {
                m_OutlineTexture = new UnityTexture2D(1, 16, TextureFormat.RGBA32, false);
                m_OutlineTexture.SetPixels(new Color[]
                {
                    new Color(0.5f, 0.5f, 0.5f, 0.5f), new Color(0.5f, 0.5f, 0.5f, 0.5f), new Color(0.8f, 0.8f, 0.8f, 0.8f), new Color(0.8f, 0.8f, 0.8f, 0.8f),
                    Color.white, Color.white, Color.white, Color.white,
                    new Color(.8f, .8f, .8f, 1f), new Color(.5f, .5f, .5f, .8f), new Color(0.3f, 0.3f, 0.3f, 0.5f), new Color(0.3f, .3f, 0.3f, 0.5f),
                    new Color(0.3f, .3f, 0.3f, 0.3f), new Color(0.3f, .3f, 0.3f, 0.3f), new Color(0.1f, 0.1f, 0.1f, 0.1f), new Color(0.1f, .1f, 0.1f, 0.1f)
                });
                m_OutlineTexture.Apply();
                m_OutlineTexture.hideFlags = HideFlags.HideAndDontSave;
            }
            var outlineTexture = new Texture2DWrapper(m_OutlineTexture);

            // Add your modules here
            RegisterModule(new SpriteFrameModule(this, m_EventSystem, m_UndoSystem, m_AssetDatabase));
            RegisterModule(new SpritePolygonModeModule(this, m_EventSystem, m_UndoSystem, m_AssetDatabase));
            RegisterModule(new SpriteOutlineModule(this, m_EventSystem, m_UndoSystem, m_AssetDatabase, m_GUIUtility, new ShapeEditorFactory(), outlineTexture));
            RegisterModule(new SpritePhysicsShapeModule(this, m_EventSystem, m_UndoSystem, m_AssetDatabase, m_GUIUtility, new ShapeEditorFactory(), outlineTexture));
            RegisterCustomModules();
            UpdateAvailableModules();
        }
Exemple #35
0
    void Awake()
    {
        //set the dimensions for the bar relative to the screen height
        rect.x = (float)Screen.height * barWidthRatio * barMultiplyer;
        rect.y = (float)Screen.height * barHeightRatio * barMultiplyer;

        //rect.x =  barWidthRatio;
        //rect.y =  barHeightRatio;

        //Debug.Log("X: " + rect.x + " Y: " + rect.y);
        //Debug.Log("ScreenX: " + Screen.width + " ScreenY: " + Screen.height);
        //healthBarGUIStyle = new GUIStyle();

        healthWaterTexture = new Texture2D(1, 1);
        healthWaterTexture.SetPixel(0,0, healthWaterColor);
        healthWaterTexture.wrapMode = TextureWrapMode.Clamp;
        healthWaterTexture.Apply();

        healthLightTexture = new Texture2D(1, 1);
        healthLightTexture.SetPixel(0,0, healthLightColor);
        healthLightTexture.wrapMode = TextureWrapMode.Clamp;
        healthLightTexture.Apply();

        barTexture = new Texture2D(1, 1);
        barTexture.SetPixel(0,0, baseBarColor);
        barTexture.wrapMode = TextureWrapMode.Clamp;
        barTexture.Apply();

        //setLightPrecentage(0.8F);
    }
 /// <summary>
 /// Creates a 1x1 texture
 /// </summary>
 /// <param name="Background">Color of the texture</param>
 /// <returns></returns>
 internal static Texture2D CreateColorPixel(Color32 Background)
 {
     Texture2D retTex = new Texture2D(1, 1);
     retTex.SetPixel(0, 0, Background);
     retTex.Apply();
     return retTex;
 }
Exemple #37
0
        public void ShowElevation(GameObject plane, Map2 map)
        {
            var textureWidth = (int)Map1.Width * _textureScale;
            var textureHeight = (int)Map1.Height * _textureScale;

            var texture = new Texture2D(textureWidth, textureHeight, TextureFormat.RGB565, true);
            texture.SetPixels(Enumerable.Repeat(BiomeProperties.Colors[Biome.Ocean], textureWidth * textureHeight).ToArray());

            //绘制陆地
            var lands = map.Graph.centers.Where(p => !p.ocean);
            foreach (var land in lands)
                texture.FillPolygon(
                    land.corners.Select(p => p.point * _textureScale).ToArray(),
					BiomeProperties.Colors[Biome.Beach] * land.elevation);

            //绘制边缘
            var lines = map.Graph.edges.Where(p => p.v0 != null).Select(p => new[]
            {
                p.v0.point.x, p.v0.point.y,
                p.v1.point.x, p.v1.point.y
            }).ToArray();

            foreach (var line in lines)
                DrawLine(texture, line[0], line[1], line[2], line[3], Color.black);
            //绘制中心点
            var points = map.Graph.centers.Select(p => p.point).ToList();
            foreach (var p in points)
                texture.SetPixel((int)(p.x * _textureScale), (int)(p.y * _textureScale), Color.red);

            texture.Apply();

            plane.GetComponent<Renderer>().material.mainTexture = texture;
        }
Exemple #38
0
    Texture2D Capture(Camera camera, Rect rect)
    {
        // 创建一个RenderTexture对象
        RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
        camera.targetTexture = rt;
        camera.Render();
        //ps: --- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。
        //ps: camera2.targetTexture = rt;
        //ps: camera2.Render();
        //ps: -------------------------------------------------------------------

        // 激活这个rt, 并从中中读取像素。
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.ARGB32, false);
        screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示
        camera.targetTexture = null;
        //ps: camera2.targetTexture = null;
        RenderTexture.active = null; // JC: added to avoid errors
        GameObject.Destroy(rt);
        // 最后将这些纹理数据,成一个png图片文件  
        byte[] bytes = screenShot.EncodeToPNG();
        string filename = Application.dataPath + "/Screenshot.png";
        System.IO.File.WriteAllBytes(filename, bytes);
        Debug.Log(string.Format("截屏了一张照片: {0}", filename));

        return screenShot;
    }
        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;
        }
Exemple #40
0
    public static UnityTexture2D CreateTemporaryDuplicate(UnityTexture2D original, int width, int height)
    {
        if (!ShaderUtil.hardwareSupportsRectRenderTexture || !original)
        {
            return(null);
        }

        RenderTexture save = RenderTexture.active;

        RenderTexture tmp = RenderTexture.GetTemporary(
            width,
            height,
            0,
            RenderTextureFormat.Default,
            RenderTextureReadWrite.sRGB);

        Graphics.Blit(original, tmp);

        RenderTexture.active = tmp;

        // If the user system doesn't support this texture size, force it to use mipmap
        bool forceUseMipMap = width >= SystemInfo.maxTextureSize || height >= SystemInfo.maxTextureSize;

        UnityTexture2D copy = new UnityTexture2D(width, height, TextureFormat.RGBA32, original.mipmapCount > 1 || forceUseMipMap);

        copy.ReadPixels(new Rect(0, 0, width, height), 0, 0);
        copy.Apply();
        RenderTexture.ReleaseTemporary(tmp);

        copy.alphaIsTransparency = original.alphaIsTransparency;
        return(copy);
    }
Exemple #41
0
	// Use this for initialization
	void Awake () {
		OptionalParameters.DoSomething();
		current = this;
		_1pixel = new Texture2D(1,1);
		_1pixel.SetPixel(0,0,Color.white);
		_1pixel.Apply();
	}
		/// <summary>
		/// Adds the button to the KSP toolbar.
		/// </summary>
		public void Add () {
//			_logger.Trace("Add");
			if (_button != null) {
				_logger.Debug("Button already added");
				return;
			}

			var texture = new Texture2D(38, 38, TextureFormat.ARGB32, false);
			
			var iconStream = Assembly.GetExecutingAssembly ().GetManifestResourceStream ("ScienceChecklist.icons.icon.png").ReadToEnd ();
			
			texture.LoadImage(iconStream);
			texture.Apply();
			
//			_logger.Info("Adding button");
			_button = ApplicationLauncher.Instance.AddModApplication(
				OnToggleOn,
				OnToggleOff,
				null,
				null,
				null,
				null,
				ApplicationLauncher.AppScenes.SPACECENTER |
				ApplicationLauncher.AppScenes.FLIGHT |
				ApplicationLauncher.AppScenes.MAPVIEW |
				ApplicationLauncher.AppScenes.VAB |
				ApplicationLauncher.AppScenes.SPH |
				ApplicationLauncher.AppScenes.TRACKSTATION,
				texture);
		}
Exemple #43
0
    /// <summary>
    /// 对相机截图。 
    /// </summary>
    /// <returns>The screenshot2.</returns>
    /// <param name="camera">Camera.要被截屏的相机</param>
    /// <param name="rect">Rect.截屏的区域</param>
    public static Texture2D CaptureCamera(string _fileParentPath, string _fileName)
    {
        // 创建一个RenderTexture对象
        RenderTexture rt = new RenderTexture((int)Screen.width, (int)Screen.height, 24);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
        Camera.main.targetTexture = rt;
        Camera.main.Render();
        //ps: --- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。
        //ps: camera2.targetTexture = rt;
        //ps: camera2.Render();
        //ps: -------------------------------------------------------------------

        // 激活这个rt, 并从中中读取像素。
        RenderTexture.active = rt;
        screenShot = new Texture2D((int)Screen.width * 3 / 4, (int)Screen.height, TextureFormat.RGB24, false);
        screenShot.ReadPixels(new Rect(Screen.width * 1 / 8, 0, Screen.width * 3 / 4, Screen.height), 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
        screenShot.Apply();

        // 重置相关参数,以使用camera继续在屏幕上显示
        Camera.main.targetTexture = null;
        //ps: camera2.targetTexture = null;
        RenderTexture.active = null; // JC: added to avoid errors
        GameObject.Destroy(rt);
        // 最后将这些纹理数据,成一个png图片文件
        //byte[] bytes = screenShot.EncodeToPNG();
        byte[] bytes = screenShot.EncodeToJPG();
        string filename = _fileParentPath + _fileName;
        System.IO.File.WriteAllBytes(filename, bytes);

        return screenShot;
    }
    // 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);
            }
        }
    }
Exemple #45
0
 public void ApplyPixelChanges()
 {
     if (UncommittedPixelChanges)
     {
         UncommittedPixelChanges = false;
         Texture2D.Apply();
         m_WaypointsTexture2D.Apply();
     }
 }
    /// <summary>
    /// Call this to capture a custom, screenshot
    /// </summary>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    public static Texture2D CaptureCustomScreenshot(int width, int height)
    {
        UnityEngine.Texture2D textured = new UnityEngine.Texture2D(width, height, UnityEngine.TextureFormat.RGB24, true, false);
        textured.ReadPixels(new UnityEngine.Rect(0f, 0f, (float)width, (float)height), 0, 0);
        int miplevel = UnityEngine.Screen.width / 800;

        UnityEngine.Texture2D textured2 = new UnityEngine.Texture2D(width >> miplevel, height >> miplevel, UnityEngine.TextureFormat.RGB24, false, false);
        textured2.SetPixels32(textured.GetPixels32(miplevel));
        textured2.Apply();
        return(textured2);
    }
Exemple #47
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);
        }
        ////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Re sample and crop a texture
        /// </summary>
        /// <param name="p_Source">Source texture</param>
        /// <param name="p_TargetWidth">Target width</param>
        /// <param name="p_TargetHeight">Target height</param>
        /// <returns></returns>
        public static UnityEngine.Texture2D ResampleAndCrop(UnityEngine.Texture2D p_Source, int p_TargetWidth, int p_TargetHeight, float p_YOffsetRel = 0.5f)
        {
            int l_SourceWidth  = p_Source.width;
            int l_SourceHeight = p_Source.height;

            float l_SourceAspect = (float)l_SourceWidth / l_SourceHeight;
            float l_TargetAspect = (float)p_TargetWidth / p_TargetHeight;

            int l_XOffset = 0;
            int l_YOffset = 0;

            float l_Factor;

            /// Crop width
            if (l_SourceAspect > l_TargetAspect)
            {
                l_Factor  = (float)p_TargetHeight / l_SourceHeight;
                l_XOffset = (int)((l_SourceWidth - l_SourceHeight * l_TargetAspect) * 0.5f);
            }
            /// Crop height
            else
            {
                l_Factor  = (float)p_TargetWidth / l_SourceWidth;
                l_YOffset = (int)((l_SourceHeight - l_SourceWidth / l_TargetAspect) * (1f - p_YOffsetRel));
            }

            Color32[] l_Source = p_Source.GetPixels32();
            Color32[] l_Result = new Color32[p_TargetWidth * p_TargetHeight];

            for (int l_Y = 0; l_Y < p_TargetHeight; l_Y++)
            {
                for (int l_X = 0; l_X < p_TargetWidth; l_X++)
                {
                    var l_Pixel = new Vector2(Mathf.Clamp(l_XOffset + l_X / l_Factor, 0, l_SourceWidth - 1), Mathf.Clamp(l_YOffset + l_Y / l_Factor, 0, l_SourceHeight - 1));

                    /// Bilinear filtering
                    var l_C11 = l_Source[Mathf.FloorToInt(l_Pixel.x) + l_SourceWidth * (Mathf.FloorToInt(l_Pixel.y))];
                    var l_C12 = l_Source[Mathf.FloorToInt(l_Pixel.x) + l_SourceWidth * (Mathf.CeilToInt(l_Pixel.y))];
                    var l_C21 = l_Source[Mathf.CeilToInt(l_Pixel.x) + l_SourceWidth * (Mathf.FloorToInt(l_Pixel.y))];
                    var l_C22 = l_Source[Mathf.CeilToInt(l_Pixel.x) + l_SourceWidth * (Mathf.CeilToInt(l_Pixel.y))];

                    l_Result[l_X + l_Y * p_TargetWidth] = Color.Lerp(Color.Lerp(l_C11, l_C12, l_Pixel.y), Color.Lerp(l_C21, l_C22, l_Pixel.y), l_Pixel.x);
                }
            }

            var l_ResultTexture = new UnityEngine.Texture2D(p_TargetWidth, p_TargetHeight);

            l_ResultTexture.SetPixels32(l_Result);
            l_ResultTexture.Apply(true);

            return(l_ResultTexture);
        }
    /// <summary>
    /// 实际存储方法,存储jpg
    /// </summary>
    /// <param name="captureSucceed">存储完执行</param>
    /// <returns></returns>
    private IEnumerator Capture()
    {
        RectTransform rt = trans_b_grayMask.GetComponent <RectTransform>();

        yield return(new WaitForEndOfFrame());

        Texture2D te = new Texture2D((int)rt.sizeDelta.x, (int)rt.sizeDelta.y, TextureFormat.ARGB32, false);

        te.ReadPixels(new Rect(240, 0, te.width, te.height), 0, 0);
        te.Apply();
        //yield return new WaitForSeconds(0.1f);
        JpgShotEnd(te);
    }
    /// <summary>
    /// 实际存储方法,存gif
    /// </summary>
    /// <param name="index">gif编号</param>
    /// <param name="captureSucceed">存储完执行</param>
    /// <returns></returns>
    private IEnumerator Capture(int index)
    {
        RectTransform rt = trans_b_grayMask.GetComponent <RectTransform>();

        yield return(new WaitForEndOfFrame());

        Texture2D te = new Texture2D((int)rt.sizeDelta.x, (int)rt.sizeDelta.y, TextureFormat.ARGB32, false);

        te.ReadPixels(new Rect(240, 0, te.width, te.height), 0, 0);
        te.Apply();
        //yield return new WaitForSeconds(0.1f);
        UserModel.Ins.StoreFXJPGTex(te, index);
        CameraManager.Instan().CameraResume();
    }
 public static int Apply2_wrap(long L)
 {
     try
     {
         long nThisPtr             = FCLibHelper.fc_get_inport_obj_ptr(L);
         UnityEngine.Texture2D obj = get_obj(nThisPtr);
         obj.Apply();
     }
     catch (Exception e)
     {
         Debug.LogException(e);
     }
     return(0);
 }
Exemple #52
0
 public UnityEngine.Texture2D CreateTexture2D()
 {
     UnityEngine.Texture2D tex = new UnityEngine.Texture2D(this.width, this.height);
     UnityEngine.Color[]   c   = new UnityEngine.Color[colors.Length];
     for (int i = 0; i < colors.Length; i++)
     {
         c[i].r = colors[i];
         c[i].g = colors[i];
         c[i].b = colors[i];
         c[i].a = 1;
     }
     tex.SetPixels(c);
     tex.Apply();
     return(tex);
 }
        ////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Blur a Texture2D
        /// </summary>
        /// <param name="p_Image">Source</param>
        /// <param name="p_BlurSize">Blur size</param>
        /// <returns></returns>
        public static UnityEngine.Texture2D Blur(UnityEngine.Texture2D p_Image, int p_BlurSize)
        {
            UnityEngine.Texture2D l_Blurred = new UnityEngine.Texture2D(p_Image.width, p_Image.height);

            /// Look at every pixel in the blur rectangle
            for (int l_XX = 0; l_XX < p_Image.width; l_XX++)
            {
                for (int l_YY = 0; l_YY < p_Image.height; l_YY++)
                {
                    float l_AvgR = 0, l_AvgG = 0, l_AvgB = 0, l_AvgA = 0;
                    int   l_BlurPixelCount = 0;

                    /// Average the color of the red, green and blue for each pixel in the
                    /// blur size while making sure you don't go outside the image bounds
                    for (int l_X = l_XX; (l_X < l_XX + p_BlurSize && l_X < p_Image.width); l_X++)
                    {
                        for (int l_Y = l_YY; (l_Y < l_YY + p_BlurSize && l_Y < p_Image.height); l_Y++)
                        {
                            Color l_Pixel = p_Image.GetPixel(l_X, l_Y);

                            l_AvgR += l_Pixel.r;
                            l_AvgG += l_Pixel.g;
                            l_AvgB += l_Pixel.b;
                            l_AvgA += l_Pixel.a;

                            l_BlurPixelCount++;
                        }
                    }

                    l_AvgR /= l_BlurPixelCount;
                    l_AvgG /= l_BlurPixelCount;
                    l_AvgB /= l_BlurPixelCount;
                    l_AvgA /= l_BlurPixelCount;

                    /// Now that we know the average for the blur size, set each pixel to that color
                    for (int l_X = l_XX; l_X < l_XX + p_BlurSize && l_X < p_Image.width; l_X++)
                    {
                        for (int l_Y = l_YY; l_Y < l_YY + p_BlurSize && l_Y < p_Image.height; l_Y++)
                        {
                            l_Blurred.SetPixel(l_X, l_Y, new Color(l_AvgR, l_AvgG, l_AvgB, l_AvgA));
                        }
                    }
                }
            }

            l_Blurred.Apply();
            return(l_Blurred);
        }
 public static int Apply_wrap(long L)
 {
     try
     {
         long VM                   = FCLibHelper.fc_get_vm_ptr(L);
         long nThisPtr             = FCLibHelper.fc_get_inport_obj_ptr(L);
         UnityEngine.Texture2D obj = get_obj(nThisPtr);
         bool arg0                 = FCLibHelper.fc_get_bool(L, 0);
         bool arg1                 = FCLibHelper.fc_get_bool(L, 1);
         obj.Apply(arg0, arg1);
     }
     catch (Exception e)
     {
         Debug.LogException(e);
     }
     return(0);
 }
Exemple #55
0
        public static void GenerateRandom(this UnityEngine.Texture2D tex)
        {
            var pixels = tex.GetPixels32();

            for (int y = 0; y < tex.height; ++y)
            {
                for (int x = 0; x < tex.width; ++x)
                {
                    pixels[y * tex.width + x] = new Color(UnityEngine.Random.Range(0f, 1f),
                                                          UnityEngine.Random.Range(0f, 1f),
                                                          UnityEngine.Random.Range(0f, 1f),
                                                          UnityEngine.Random.Range(0f, 1f));
                }
            }

            tex.SetPixels32(pixels);
            tex.Apply();
        }
Exemple #56
0
        public ue.Sprite GetImage(SharpNeat.Network.INetworkDefinition net)
        {
            Graphics g = Graphics.FromImage(_image);

            g.FillRectangle(_brushBackground, 0, 0, _image.Width, _image.Height);

            _viewportPainter.IOGraph = _factory.CreateGraph(net);

            _viewportPainter.Paint(g, _viewportArea, _zoomFactor);

            texture = new ue.Texture2D(_width, _height, ue.TextureFormat.RGBA32, false);
            ImgToTexture(_image, texture);

            texture.Apply();

            var sprt = ue.Sprite.Create(texture, new ue.Rect(0, 0, _width, _height), ue.Vector2.zero);

            g.Dispose();

            return(sprt);
        }
Exemple #57
0
        private UnityEngine.Texture2D ConstructBarTexture(float x, int width, UnityEngine.Color main, UnityEngine.Color background)
        {
            UnityEngine.Texture2D t = new UnityEngine.Texture2D(width, 16);
            int i = 0;

            for (; i < width * x; i++)
            {
                for (int j = 0; j < 16; j++)
                {
                    t.SetPixel(i, j, main);
                }
            }
            for (; i < width; i++)
            {
                for (int j = 0; j < 16; j++)
                {
                    t.SetPixel(i, j, background);
                }
            }
            t.Apply();
            return(t);
        }
Exemple #58
0
    static int Apply(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 1 && TypeChecker.CheckTypes <UnityEngine.Texture2D>(L, 1))
            {
                UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.ToObject(L, 1);
                obj.Apply();
                return(0);
            }
            else if (count == 2 && TypeChecker.CheckTypes <UnityEngine.Texture2D, bool>(L, 1))
            {
                UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.ToObject(L, 1);
                bool arg0 = LuaDLL.lua_toboolean(L, 2);
                obj.Apply(arg0);
                return(0);
            }
            else if (count == 3 && TypeChecker.CheckTypes <UnityEngine.Texture2D, bool, bool>(L, 1))
            {
                UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.ToObject(L, 1);
                bool arg0 = LuaDLL.lua_toboolean(L, 2);
                bool arg1 = LuaDLL.lua_toboolean(L, 3);
                obj.Apply(arg0, arg1);
                return(0);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Texture2D.Apply"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Exemple #59
0
    static int Apply(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 1)
            {
                UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.CheckObject(L, 1, typeof(UnityEngine.Texture2D));
                obj.Apply();
                return(0);
            }
            else if (count == 2)
            {
                UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.CheckObject(L, 1, typeof(UnityEngine.Texture2D));
                bool arg0 = LuaDLL.luaL_checkboolean(L, 2);
                obj.Apply(arg0);
                return(0);
            }
            else if (count == 3)
            {
                UnityEngine.Texture2D obj = (UnityEngine.Texture2D)ToLua.CheckObject(L, 1, typeof(UnityEngine.Texture2D));
                bool arg0 = LuaDLL.luaL_checkboolean(L, 2);
                bool arg1 = LuaDLL.luaL_checkboolean(L, 3);
                obj.Apply(arg0, arg1);
                return(0);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Texture2D.Apply"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Exemple #60
0
 /// <summary>
 /// 获取某个索引的图片
 /// </summary>
 /// <param name="index">图片索引,从0开始</param>
 /// <returns>对应图片数据</returns>
 internal U3d.Texture2D this[uint index]
 {
     get
     {
         M2ImageInfo   ii     = ImageInfos[index];
         U3d.Texture2D result = new U3d.Texture2D(ii.Width, ii.Height);
         if (ii.Width == 0 && ii.Height == 0)
         {
             return(result);
         }
         byte[] pixels = null;
         lock (wzl_locker)
         {
             FS_wzl.Position = OffsetList[index] + 16;
             using (BinaryReader rwzl = new BinaryReader(FS_wzl))
             {
                 pixels = unzip(rwzl.ReadBytes(LengthList[index]));
             }
         }
         int p_index = 0;
         for (int h = 0; h < ii.Height; ++h)
         {
             for (int w = 0; w < ii.Width; ++w)
             {
                 // 跳过填充字节
                 if (w == 0)
                 {
                     p_index += Delphi.SkipBytes(8, ii.Width);
                 }
                 float[] pallete = Delphi.PALLETE[pixels[p_index++] & 0xff];
                 result.SetPixel(w, ii.Height - h, new U3d.Color(pallete[1], pallete[2], pallete[3], pallete[0]));
             }
         }
         result.Apply();
         return(result);
     }
 }