Exemple #1
0
        public static bool Paint(IBrush brush, Texture2D texture, MeshCollider meshCollider)
        {
            int[] triangles = brush.GetAffectedTriangles(meshCollider);

            Mesh      mesh          = meshCollider.sharedMesh;
            Transform meshTransform = meshCollider.transform;

            if (mesh != prevMesh)
            {
                prevMesh      = mesh;
                meshTriangles = mesh.triangles;
                meshVertices  = mesh.vertices;
                meshUVs       = mesh.uv;
            }

            Rect bigUVRect = new Rect(-1, -1, 0, 0);

            for (int t = 0; t < triangles.Length; t++)
            {
                int triangleIndex = triangles[t];

                int[] triangle = new int[3];
                triangle[0] = meshTriangles[triangleIndex * 3];
                triangle[1] = meshTriangles[triangleIndex * 3 + 1];
                triangle[2] = meshTriangles[triangleIndex * 3 + 2];

                Vector2[] triangleUVs = new Vector2[3];
                triangleUVs[0] = meshUVs[triangle[0]];
                triangleUVs[1] = meshUVs[triangle[1]];
                triangleUVs[2] = meshUVs[triangle[2]];

                Rect uvRect = GetUVRect(triangleUVs);
                bigUVRect = MergeRects(bigUVRect, uvRect);
            }

            int x      = Mathf.FloorToInt(bigUVRect.x * texture.width);
            int y      = Mathf.FloorToInt(bigUVRect.y * texture.height);
            int width  = Mathf.FloorToInt(bigUVRect.width * texture.width);
            int height = Mathf.FloorToInt(bigUVRect.height * texture.height);

            Color[] cols = texture.GetPixels(x, y, width, height);
            //Debug.Log("colouring a " + width + "x" + height + " patch");

            for (int t = 0; t < triangles.Length; t++)
            {
                int triangleIndex = triangles[t];

                int[] triangle = new int[3];
                triangle[0] = meshTriangles[triangleIndex * 3];
                triangle[1] = meshTriangles[triangleIndex * 3 + 1];
                triangle[2] = meshTriangles[triangleIndex * 3 + 2];

                Vector3[] triangleVerts = new Vector3[3];
                triangleVerts[0] = meshVertices[triangle[0]];
                triangleVerts[1] = meshVertices[triangle[1]];
                triangleVerts[2] = meshVertices[triangle[2]];

                Vector2[] triangleUVs = new Vector2[3];
                triangleUVs[0] = meshUVs[triangle[0]];
                triangleUVs[1] = meshUVs[triangle[1]];
                triangleUVs[2] = meshUVs[triangle[2]];

                Rect uvRect = GetUVRect(triangleUVs);
                ColourPixels(ref cols, brush, triangleUVs, triangleVerts, meshTransform, uvRect, bigUVRect, texture.width, texture.height);
            }

            texture.SetPixels(x, y, width, height, cols);
            texture.Apply();

            return(triangles.Length > 0);
        }