Beispiel #1
0
    /// <summary>
    /// Creates a mesh with the given amount of detail (vertices)
    /// </summary>
    /// <param name="detail">
    /// A <see cref="System.Int32"/>
    /// </param>
    public void GenerateMesh(int detail)
    {
        if (planet.Terrain.module == null)
        {
            planet.LoadModule();
        }

        // mesh data
        Vector3[] vertices     = null;
        Color[]   vertexColors = null;
        Vector2[] uvs          = null;
        Vector3[] normals      = null;
        int[]     indexbuffer  = null;

        // Action to be called when generation has finished, applies mesh data
        Action ApplyMesh = () => {
            if (mesh != null)
            {
                // create mesh
                mesh.vertices  = vertices;
                mesh.colors    = vertexColors;
                mesh.triangles = indexbuffer;
                mesh.uv        = uvs;
                mesh.normals   = normals;
                //mesh.RecalculateNormals();
                mesh.RecalculateBounds();
            }

            if (this != null)
            {
                transform.localPosition = Vector3.zero;
                transform.localRotation = Quaternion.identity;
                transform.position      = transform.parent.position;
                transform.rotation      = transform.parent.rotation;
            }

            // set mesh to collider
            if (planet.generateColliders[lodLevel])
            {
                MeshCollider collider = (MeshCollider)gameObject.GetComponent(typeof(MeshCollider));
                if (collider == null)
                {
                    collider = (MeshCollider)gameObject.AddComponent(typeof(MeshCollider));
                }
                collider.sharedMesh = mesh;
            }

            // report to planet
            planet.ReportGeneration(this);

            // event to parent surface
            if (GenerationComplete != null)
            {
                GenerationComplete(this);
            }
        };

        if (planet.useLod && Application.isPlaying)
        {
            // calculate on another thread
            ThreadScheduler.RunOnThread(() => {
                CalculateGeometry(detail, out vertices, out vertexColors, out uvs, out normals, out indexbuffer);
                ThreadScheduler.RunOnMainThread(ApplyMesh);
            });
        }
        else
        {
            // no LOD or in editor, generate in main thread
            CalculateGeometry(detail, out vertices, out vertexColors, out uvs, out normals, out indexbuffer);
            ApplyMesh();
        }
    }