예제 #1
0
        public static Mesh CreateTree(int vertCount, float radius, float height, int subdivisions, float variance, int branchCount)
        {
            var meshGen = new MeshGenerator();

            var armature = CreateArmature(subdivisions, height, variance);
            var branches = CreateBranches(branchCount, armature);

            armature.branches = branches;
            Armature          = armature;

            // Trunk
            {
                // Create trunk edge loops
                var edgeloops = new List <List <Vector3> >(armature.trunkVertices.Count);
                for (var i = 0; i < armature.trunkVertices.Count; i++)
                {
                    var circle = CreateCircle(vertCount, radius * Mathf.Sqrt(1 - (float)i / subdivisions), armature.trunkVertices[i]);
                    edgeloops.Add(circle);
                    meshGen.AddVertices(circle);
                }

                // Bridge trunk edge loops
                for (var i = 0; i < subdivisions; i++)
                {
                    meshGen.BridgeEdgeLoops(edgeloops[i], edgeloops[i + 1]);
                }
            }

            // Branches
            {
                foreach (var branch in branches)
                {
                    var divisions = branch.branchVertices.Count - 1;

                    var edgeloops = new List <List <Vector3> >(branch.branchVertices.Count);
                    for (var i = 0; i < branch.branchVertices.Count; i++)
                    {
                        var branchPointRadius = radius * Mathf.Sqrt(1 - (float)branch.branchVertexIndex / subdivisions);
                        var circle            = CreateCircle(vertCount, branchPointRadius * .7f * Mathf.Sqrt(1 - (float)i / divisions), branch.branchVertices[i]);

                        Vector3 rotationDir;
                        if (i == 0 || i == branch.branchVertices.Count - 1)
                        {
                            rotationDir = branch.branchVertices[i];
                        }
                        else
                        {
                            rotationDir = branch.branchVertices[i - 1] + branch.branchVertices[i];
                        }

                        circle.RotateVertices(branch.branchVertices[i], Quaternion.LookRotation(rotationDir, Vector3.down));

                        edgeloops.Add(circle);
                        meshGen.AddVertices(circle);
                    }

                    // Bridge edge loops
                    for (var i = 0; i < divisions; i++)
                    {
                        meshGen.BridgeEdgeLoops(edgeloops[i], edgeloops[i + 1]);
                    }
                }
            }

            var mesh = meshGen.GetMesh("Tree");

            mesh.RecalculateNormals();

            return(mesh);
        }