Beispiel #1
0
    public static ArrayMesh AddNoiseToMesh(PlaneMesh plane, float[,] noiseMap, int chunkSize, int heightMultiplier, Curve heightCurve)
    {
        SurfaceTool st = new SurfaceTool();

        st.CreateFrom(plane, 0);
        ArrayMesh    mesh = new ArrayMesh();
        MeshDataTool dt   = new MeshDataTool();

        mesh = st.Commit();
        dt.CreateFromSurface(mesh, 0);
        for (int y = 0; y < chunkSize; y++)
        {
            for (int x = 0; x < chunkSize; x++)
            {
                int     z           = y;
                int     vertexIndex = z * chunkSize + x;
                Vector3 vertex      = dt.GetVertex(vertexIndex);
                vertex.y = heightCurve.Interpolate(noiseMap[chunkSize - x - 1, chunkSize - z - 1]) * heightMultiplier;
                dt.SetVertex(vertexIndex, vertex);
            }
        }
        for (int surface = 0; surface < mesh.GetSurfaceCount(); surface++)
        {
            mesh.SurfaceRemove(surface);
        }
        dt.CommitToSurface(mesh);
        st.Begin(Mesh.PrimitiveType.Triangles);
        st.CreateFrom(mesh, 0);
        st.Index();
        st.GenerateNormals();
        return(st.Commit());
    }
Beispiel #2
0
    public void Generate()
    {
        planeMesh                = new PlaneMesh();
        planeMesh.Size           = new Vector2(chunkSize, chunkSize);
        planeMesh.SubdivideDepth = Mathf.RoundToInt(chunkSize * 0.5f);
        planeMesh.SubdivideWidth = Mathf.RoundToInt(chunkSize * 0.5f);

        surfaceTool  = new SurfaceTool();
        meshDataTool = new MeshDataTool();
        surfaceTool.CreateFrom(planeMesh, 0);
        arrayPlane = surfaceTool.Commit();
        meshDataTool.CreateFromSurface(arrayPlane, 0);

        for (int i = 0; i < meshDataTool.GetVertexCount(); i++)
        {
            Vector3 vertex = meshDataTool.GetVertex(i);
            vertex.y = noise.GetNoise3d(
                vertex.x + position.x,
                vertex.y,
                vertex.z + position.z) * References.steepness;

            meshDataTool.SetVertex(i, vertex);
            avgHeight += vertex.y;
        }
        avgHeight /= meshDataTool.GetVertexCount();

        for (int i = 0; i < arrayPlane.GetSurfaceCount(); i++)
        {
            arrayPlane.SurfaceRemove(i);
        }

        for (int i = 0; i < meshDataTool.GetFaceCount(); i++)
        {
            Vector3 A      = meshDataTool.GetVertex(meshDataTool.GetFaceVertex(i, 0));
            Vector3 B      = meshDataTool.GetVertex(meshDataTool.GetFaceVertex(i, 1));
            Vector3 C      = meshDataTool.GetVertex(meshDataTool.GetFaceVertex(i, 2));
            Vector3 face   = (A + B + C) / 3 + position;
            Vector3 normal = meshDataTool.GetFaceNormal(i);
            slope += Maths.Angle(Vector3.Up, normal);
        }
        slope /= meshDataTool.GetFaceCount();

        meshDataTool.CommitToSurface(arrayPlane);
        surfaceTool.Begin(Mesh.PrimitiveType.Triangles);
        surfaceTool.CreateFrom(arrayPlane, 0);
        surfaceTool.GenerateNormals();

        meshInstance      = new MeshInstance();
        meshInstance.Mesh = surfaceTool.Commit();
        meshInstance.SetSurfaceMaterial(0, (Material)ResourceLoader.Load("res://Assets/Shader/Terrain.material"));
        meshInstance.CreateTrimeshCollision();
        meshInstance.CastShadow = GeometryInstance.ShadowCastingSetting.On;
        AddChild(meshInstance);
    }
    private void Deform()
    {
        var sn = new OpenSimplexNoise();

        sn.Period      = Period;
        sn.Octaves     = Octaves;
        sn.Seed        = Seed;
        sn.Persistence = Persistence;
        sn.Lacunarity  = Lacunarity;

        var mesh = sphere.Mesh;
        var st   = new SurfaceTool();

        st.CreateFrom(mesh, 0);

        var array = st.Commit();

        var dt = new MeshDataTool();

        dt.CreateFromSurface(array, 0);

        var count  = dt.GetVertexCount();
        var origin = Vector3.Zero;

        for (int i = 0; i < count; i++)
        {
            var vertex = dt.GetVertex(i);
            var n      = -vertex.DirectionTo(origin);
            var noise  = sn.GetNoise3d(vertex.x, vertex.y, vertex.z);
            noise   = Mathf.Clamp(noise, -1f, 1f);
            vertex += n * noise * MoveFactor;
            dt.SetVertex(i, vertex);
        }
        var surfCount = array.GetSurfaceCount();

        for (int i = 0; i < surfCount; i++)
        {
            array.SurfaceRemove(i);
        }

        dt.CommitToSurface(array);
        st.Begin(Mesh.PrimitiveType.Triangles);
        st.CreateFrom(array, 0);
        st.GenerateNormals();

        sphere.Mesh = st.Commit();

        UpdateMaterial();
    }
Beispiel #4
0
    // Called when the node enters the scene tree for the first time.
    public override void _Ready()
    {
        global = GetNode <Global>("/root/Global");
        OnStartTimerTimeout();

        CharacterContainer = GetNode <Spatial>("/root/Spatial/CharacterContainer");

        SurfaceTool surfaceTool = new SurfaceTool();

        planeMesh                = new PlaneMesh();
        planeMesh.Material       = (Material)ResourceLoader.Load("mesh_material.tres");
        planeMesh.SubdivideWidth = width - 2;               //Subtract two bc there's already two vertices before we start subdividing
        planeMesh.SubdivideDepth = height - 2;
        planeMesh.Size           = new Vector2(42.4f, 24f); //42.47f (42.4f, 24f)

        surfaceTool.CreateFrom(planeMesh, 0);

        arrayPlane = surfaceTool.Commit();


        meshInstance      = new MeshInstance();
        meshInstance.Mesh = arrayPlane;


        NewDetectedBody();
        AddChild(meshInstance);
        AddChild(detectBody);


        UpdateShapes();
    }
Beispiel #5
0
        /// <summary>
        /// Finalizes mesh drawing and adds the built mesh to
        /// the world environment.
        /// </summary>
        public void CommitSurface()
        {
            GD.Print("COMMITING DRAWING");

            ArrayMesh finalSurface = Surface.Commit();

            adder.AddMesh(finalSurface);
        }
        //Creates a mesh from a surface tool
        public static ArrayMesh CreateMeshFromSurfaceTool(SurfaceTool surfTool)
        {
            var mesh = new ArrayMesh();

            surfTool.GenerateNormals();
            surfTool.Index();
            surfTool.Commit(mesh);
            return(mesh);
        }
Beispiel #7
0
    public Mesh CreateMesh()
    {
        SurfaceTool.Begin(Mesh.PrimitiveType.Triangles);
        SurfaceTool.SetMaterial(DefaultMaterial);

        foreach (var voxel in Voxels.Keys)
        {
            CreateVoxel(Voxels[voxel], voxel);
        }

        SurfaceTool.Index();
        return(SurfaceTool.Commit());
    }
Beispiel #8
0
    private static MeshInstance DebugMesh()
    {
        SurfaceTool tool = new SurfaceTool();

        tool.Begin(PrimitiveMesh.PrimitiveType.Lines);

        //Front
        tool.AddVertex(new Vector3(0, 0, 0));
        tool.AddVertex(new Vector3(1, 0, 0));
        tool.AddVertex(new Vector3(1, 0, 0));
        tool.AddVertex(new Vector3(1, 1, 0));
        tool.AddVertex(new Vector3(1, 1, 0));
        tool.AddVertex(new Vector3(0, 1, 0));
        tool.AddVertex(new Vector3(0, 1, 0));
        tool.AddVertex(new Vector3(0, 0, 0));

        //Back
        tool.AddVertex(new Vector3(0, 0, 1));
        tool.AddVertex(new Vector3(1, 0, 1));
        tool.AddVertex(new Vector3(1, 0, 1));
        tool.AddVertex(new Vector3(1, 1, 1));
        tool.AddVertex(new Vector3(1, 1, 1));
        tool.AddVertex(new Vector3(0, 1, 1));
        tool.AddVertex(new Vector3(0, 1, 1));
        tool.AddVertex(new Vector3(0, 0, 1));

        //BOTTOM
        tool.AddVertex(new Vector3(0, 0, 0));
        tool.AddVertex(new Vector3(0, 0, 1));
        tool.AddVertex(new Vector3(0, 0, 1));
        tool.AddVertex(new Vector3(1, 0, 1));
        tool.AddVertex(new Vector3(1, 0, 1));
        tool.AddVertex(new Vector3(1, 0, 0));
        tool.AddVertex(new Vector3(1, 0, 0));
        tool.AddVertex(new Vector3(0, 0, 0));

        //TOP
        tool.AddVertex(new Vector3(0, 1, 0));
        tool.AddVertex(new Vector3(0, 1, 1));
        tool.AddVertex(new Vector3(0, 1, 1));
        tool.AddVertex(new Vector3(1, 1, 1));
        tool.AddVertex(new Vector3(1, 1, 1));
        tool.AddVertex(new Vector3(1, 1, 0));
        tool.AddVertex(new Vector3(1, 1, 0));
        tool.AddVertex(new Vector3(0, 1, 0));

        MeshInstance instance = new MeshInstance();

        instance.Mesh = tool.Commit();
        return(instance);
    }
Beispiel #9
0
    private void Generate()
    {
        if (!_initialized)
        {
            return;
        }

        _surfaceTool.Clear();
        _meshDataTool.Clear();
        _surfaceTool.CreateFrom(_meshInstance.Mesh, 0);
        _meshDataTool.CreateFromSurface(_surfaceTool.Commit(), 0);

        int numVertices = _meshDataTool.GetVertexCount();

        _data = new float[numVertices];

        for (int i = 0; i < numVertices; i++)
        {
            Vector3 vertex = _meshDataTool.GetVertex(i);
            _data[i] = Amplitude * _noise.GetNoise2d(vertex.x, vertex.z);
            _meshDataTool.SetVertex(i, new Vector3(vertex.x, _data[i], vertex.z));
            _meshDataTool.SetVertexNormal(i, Vector3.Up);
        }

        for (int i = 0; i < numVertices - _resX; i++)
        {
            Vector3 a = _meshDataTool.GetVertex(i);
            Vector3 b = _meshDataTool.GetVertex(i + 1);
            Vector3 c = _meshDataTool.GetVertex(i + _resX);

            Vector3 normal = (c - a).Cross(b - a);

            for (int j = i; j < i + 3; j++)
            {
                _meshDataTool.SetVertexNormal(j, _meshDataTool.GetVertexNormal(j) + normal);
            }
        }

        for (int i = 0; i < numVertices; i++)
        {
            _meshDataTool.SetVertexNormal(i, _meshDataTool.GetVertexNormal(i).Normalized());
        }

        ArrayMesh newMesh = new ArrayMesh();

        _meshDataTool.CommitToSurface(newMesh);
        _meshInstance.Mesh = newMesh;
        _meshInstance.RemoveChild(_meshInstance.GetChild(0));
        _meshInstance.CreateTrimeshCollision();
    }
Beispiel #10
0
        public void BuildVoxelMesh()
        {
            Builder.Begin(Mesh.PrimitiveType.Triangles);
            // GD.Print("Builder has begun!");
            Builder.SetMaterial(voxelMaterial);

            foreach (VoxelPos pos in Voxels.Keys)
            {
                var voxel = GetVoxel(pos, false);

                if (voxel.HasFront())
                {
                    BuildFace(pos.ToVector3(), Vector3.Right, Vector3.Up, UVFromName(voxel.frontTexture), Vector3.Forward);
                }
                if (voxel.HasBack())
                {
                    BuildFace(pos.Backwards().ToVector3(), Vector3.Up, Vector3.Right, UVFromName(voxel.backTexture), Vector3.Back);
                }
                if (voxel.HasLeft())
                {
                    BuildFace(pos.ToVector3(), Vector3.Up, Vector3.Back, UVFromName(voxel.leftTexture), Vector3.Left);
                }
                if (voxel.HasRight())
                {
                    BuildFace(pos.Right().ToVector3(), Vector3.Back, Vector3.Up, UVFromName(voxel.rightTexture), Vector3.Right);
                }
                if (voxel.HasTop())
                {
                    BuildFace(pos.Up().ToVector3(), Vector3.Right, Vector3.Back, UVFromName(voxel.topTexture), Vector3.Up);
                }
                if (voxel.HasBottom())
                {
                    BuildFace(pos.ToVector3(), Vector3.Back, Vector3.Right, UVFromName(voxel.bottomTexture), Vector3.Down);
                }
            }

            Builder.Index();
            var voxelMesh = GetNode <MeshInstance>("VoxelMesh");

            voxelMesh.Mesh = Builder.Commit();
            Builder.Clear();

            /*
             * foreach (KeyValuePair<VoxelPos, Voxel> pair in Voxels)
             * {
             *  GD.Print($"{pair.Key}: {pair.Value}");
             * }
             */
        }
Beispiel #11
0
    public override void _Process(float delta)
    {
        if (generationFinished)
        {
            generationFinished = false;

            ArrayMesh mesh = new ArrayMesh();

            mesh = surfaceTool.Commit();

            collider.Shape = mesh.CreateTrimeshShape();

            meshInstance.SetMesh(mesh);
        }
    }
    public void Generate()
    {
        verts   = new List <Vector3>();
        indices = new List <int>();
        index   = 0;
        faces   = new List <TriangleIndices>();
        middlePointIndexCache = new System.Collections.Generic.Dictionary <long, int>();
        CreateIcosphere();
        SurfaceTool st = new SurfaceTool();
        var         am = CreateTheMesh();

        st.CreateFrom(am, 0);
        st.GenerateNormals();
        Mesh = st.Commit();
    }
Beispiel #13
0
    public override void _Ready()
    {
        MarchCube(new Vector3(1, 0, 0));
        SurfaceTool st = new SurfaceTool();

        st.Begin(Mesh.PrimitiveType.Triangles);

        foreach (Vector3 vert in vertices)
        {
            st.AddVertex(vert);
        }

        Mesh = st.Commit();

        GD.Print(vertices);
    }
Beispiel #14
0
    private Mesh GenerateMesh(Vector3 pos, Vector2 size, int subdivision = 0)
    {
        SurfaceTool st = new SurfaceTool();

        st.Begin(Mesh.PrimitiveType.Triangles);

        int verts = 2 + subdivision;

        Vector3[,] vertices = new Vector3[verts, verts];

        for (int i = 0; i < verts; i++)
        {
            for (int j = 0; j < verts; j++)
            {
                Vector3 p = new Vector3(
                    ((float)i / (verts - 1)),
                    0f,
                    ((float)j / (verts - 1))
                    );

                p.x *= size.x;
                p.z *= size.y;
                p.y  = GetHeight(p + pos);

                vertices[i, j] = p;
            }
        }

        for (int i = 0; i < verts - 1; i++)
        {
            for (int j = 0; j < verts - 1; j++)
            {
                st.AddVertex(vertices[i + 1, j + 0]);
                st.AddVertex(vertices[i + 1, j + 1]);
                st.AddVertex(vertices[i + 0, j + 0]);

                st.AddVertex(vertices[i + 0, j + 0]);
                st.AddVertex(vertices[i + 1, j + 1]);
                st.AddVertex(vertices[i + 0, j + 1]);
            }
        }

        st.GenerateNormals();
        //st.GenerateTangents();
        st.Index();
        return(st.Commit());
    }
    void _generate_chunk_mesh(int _this_argument_exists_due_to_bug_9924)
    {
        if (0 < data.Count)
        {
            return;
        }

        var surface_tool = new SurfaceTool();

        surface_tool.Begin(Mesh.PrimitiveType.Triangles);

        // For each block, add data to the SurfaceTool and generate a collider.
        foreach (var block_position in data.Keys)
        {
            var block_id = data[block_position];
            _draw_block_mesh(surface_tool, block_position, block_id);
        }
        // Create the chunk's mesh from the SurfaceTool data.
        surface_tool.GenerateNormals();
        // surface_tool.GenerateTangents(); // XXX add back

        surface_tool.Index();
        var array_mesh = surface_tool.Commit();

        var mi = new MeshInstance();

        mi.Mesh = array_mesh;
        var resource = ResourceLoader.Load("res://world/textures/material.tres");

        GD.Print($"====== resource should be material: {resource}");
        var materialOrNull = resource as Material;

        if (materialOrNull == null)
        {
            GD.Print("materialOrNull == null");
        }
        else
        {
            mi.MaterialOverride = materialOrNull;
        }

        AddChild(mi);
    }
Beispiel #16
0
    public void generateMeshAndColors(float[,] dataTerrain)
    {
        //init tool
        SurfaceTool st = new SurfaceTool();

        st.Begin(Mesh.PrimitiveType.Triangles);
        st.SetMaterial(mat);

        //get HeightsQuats and create triangles
        int maxI      = dataTerrain.GetLength(0);
        int maxJ      = dataTerrain.GetLength(1);
        int quadCount = 0;

        //1º rows, 2º columns
        for (int i = 0; i < maxI - 1; i++)
        {
            for (int j = 0; j < maxJ - 1; j++)
            {
                Quat q = new Quat();//heights to Quat

                q.x = dataTerrain[i, j];       q.y = dataTerrain[i, j + 1];

                q.z = dataTerrain[i + 1, j];     q.w = dataTerrain[i + 1, j + 1];

                //to mesh
                Vector3 offset = new Vector3(j, 0, i);
                createQuad(st, offset, q);

                /*//debug algoritm
                 * GD.Print(string.Format("•quad{0}:({1},{2}): points: \n{3} {4} {5}   {6} {7} {8}\n{9} {10} {11}   {12} {13} {14}",
                 * quadCount,i,j,
                 * offset.x, q.x, offset.z - 1,       offset.x + 1, q.y, offset.z-1,
                 * offset.x, q.z, offset.z,         offset.x + 1, q.w, offset.z));
                 */
                quadCount++;
            }
        }

        //finally
        st.GenerateNormals();
        st.Commit(tmpMesh);
        this.SetMesh(tmpMesh);
    }
Beispiel #17
0
        public void Render()
        {
            SurfaceTool tool = new SurfaceTool();

            tool.Begin(Mesh.PrimitiveType.Triangles);

            for (int x = 1; x < Size.x - 1; x++)
            {
                for (int z = 1; z < Size.z - 1; z++)
                {
                    for (int y = 1; y < Size.y - 1; y++)
                    {
                        BuildFaces(GetSideFree(x, y, z), tool, x, y, z);
                    }
                }
            }

            tool.GenerateNormals();

            Model.Mesh = tool.Commit();
        }
Beispiel #18
0
        private void CreateMesh()
        {
            surfaceTool.Begin(Mesh.PrimitiveType.Triangles);

            for (int i = 0; i < CHUNK_SIZE; i++)
            {
                for (int j = 0; j < CHUNK_SIZE; j++)
                {
                    for (int k = 0; k < CHUNK_SIZE; k++)
                    {
                        if (chunkData[i][j][k] == VoxelTypes.Air)
                        {
                            continue;
                        }
                        CreateFaces(i, j, k);
                    }
                }
            }
            surfaceTool.Index();
            this.SetMesh(surfaceTool.Commit());
        }
Beispiel #19
0
    private void generate_ui_mesh(Vector2[] positions)
    {
        GD.Print("Generate new UI mesh", positions);

        var st = new SurfaceTool();

        st.Begin(Mesh.PrimitiveType.Triangles);

        foreach (var p in positions)
        {
            GD.Print(p);
            _plane(st, p.x, p.y);
        }

        st.Index();
        st.GenerateNormals();
        st.GenerateTangents();

        var mesh = st.Commit();

        mesh.SurfaceSetMaterial(0, mouse_preview.GetSurfaceMaterial(0));
        GetNode <MeshInstance>("MeshInstance3").Mesh = mesh;
    }
Beispiel #20
0
    private void generate_mesh()
    {
        GD.Print("Update info mesh");
        var tmpPoints = new List <Vector2>();

        var st = new SurfaceTool();

        st.Begin(Mesh.PrimitiveType.Triangles);

        Vector2 _test = (Vector2)start_pos - (Vector2)end_pos;

        if (Mathf.Abs(_test.x) > Mathf.Abs(_test.y))
        {
            _test.y = 0;
        }
        else
        {
            _test.x = 0;
        }

        int size = (int)_test.Length();

        if (_test.x != 0 && _test.y == 0)
        {
            GD.Print("X");
            for (int i = 0; i < size + 1; i++)
            {
                if (_test.x < 0)
                {
                    _plane(st, ((Vector2)start_pos).x + i, ((Vector2)start_pos).y);
                    tmpPoints.Add(((Vector2)start_pos) + new Vector2(i, 0));
                }
                else
                {
                    _plane(st, ((Vector2)start_pos).x - i, ((Vector2)start_pos).y);
                    tmpPoints.Add(((Vector2)start_pos) + new Vector2(-i, 0));
                }
            }
        }
        else if (_test.y != 0 && _test.x == 0)
        {
            GD.Print("Y");
            for (int i = 0; i < size + 1; i++)
            {
                if (_test.y < 0)
                {
                    _plane(st, ((Vector2)start_pos).x, ((Vector2)start_pos).y + i);
                    tmpPoints.Add(((Vector2)start_pos) + new Vector2(0, i));
                }
                else
                {
                    _plane(st, ((Vector2)start_pos).x, ((Vector2)start_pos).y - i);
                    tmpPoints.Add(((Vector2)start_pos) + new Vector2(0, -i));
                }
            }
        }

        st.Index();
        st.GenerateNormals();
        st.GenerateTangents();

        var mesh = st.Commit();

        mesh.SurfaceSetMaterial(0, mouse_preview.GetSurfaceMaterial(0));
        GetNode <MeshInstance>("mouse_draw_preview").Mesh = mesh;

        curPoints = tmpPoints.ToArray();
        GD.Print(_test, size);
    }
        public override void _Ready()
        {
            var surfTool = new SurfaceTool();

            surfTool.Begin(Mesh.PrimitiveType.Triangles);
            Vector3[] vertices = new Vector3[] { new Vector3(0, 0, 0),
                                                 new Vector3(length, 0, 0),
                                                 new Vector3(length, 0, width),
                                                 new Vector3(0, 0, width),

                                                 new Vector3(0, height, 0),
                                                 new Vector3(length, height, 0),
                                                 new Vector3(length, height, width),
                                                 new Vector3(0, height, width) };

            // surfTool.AddNormal(new Vector3(0.0f,0.0f,-1.0f));
            // surfTool.AddVertex(new Vector3(length, -height, -width));
            // surfTool.AddVertex(new Vector3(-length, -height, -width));
            // surfTool.AddVertex(new Vector3(-length, height, -width));
            // surfTool.AddVertex(new Vector3(length, height, -width));

            // // surfTool.AddNormal(new Vector3(0.0f, 0.0f, 1.0f));
            // surfTool.AddVertex(new Vector3(-length, -height, width));
            // surfTool.AddVertex(new Vector3(length, -height, width));
            // surfTool.AddVertex(new Vector3(length, height, width));
            // surfTool.AddVertex(new Vector3(-length, height, width));

            // // surfTool.AddNormal(new Vector3(1.0f, 0.0f, 0.0f));
            // surfTool.AddVertex(new Vector3(length, -height, width));
            // surfTool.AddVertex(new Vector3(length, -height, -width));
            // surfTool.AddVertex(new Vector3(length, height, -width));
            // surfTool.AddVertex(new Vector3(length, height, width));

            // surfTool.AddNormal(new Vector3(-1.0f, 0.0f, 0.0f));
            // surfTool.AddVertex(new Vector3(-length, -height, -width));
            // surfTool.AddVertex(new Vector3(-length, -height, width));
            // surfTool.AddVertex(new Vector3(-length, height, width));
            // surfTool.AddVertex(new Vector3(-length, height, -width));

            //Bottom Face
            surfTool.AddNormal(new Vector3(0.0f, -1.0f, 0.0f));
            surfTool.AddVertex(vertices[1]);
            surfTool.AddVertex(vertices[3]);
            surfTool.AddVertex(vertices[2]);

            surfTool.AddVertex(vertices[1]);
            surfTool.AddVertex(vertices[0]);
            surfTool.AddVertex(vertices[3]);

            surfTool.AddNormal(new Vector3(0.0f, 1.0f, 0.0f));
            surfTool.AddVertex(vertices[4]);
            surfTool.AddVertex(vertices[5]);
            surfTool.AddVertex(vertices[7]);

            surfTool.AddVertex(vertices[5]);
            surfTool.AddVertex(vertices[6]);
            surfTool.AddVertex(vertices[7]);

            surfTool.AddNormal(new Vector3(0.0f, 0.0f, 1.0f));
            surfTool.AddVertex(vertices[0]);
            surfTool.AddVertex(vertices[1]);
            surfTool.AddVertex(vertices[5]);

            surfTool.AddVertex(vertices[5]);
            surfTool.AddVertex(vertices[4]);
            surfTool.AddVertex(vertices[0]);

            surfTool.AddNormal(new Vector3(0.0f, 0.0f, -1.0f));
            surfTool.AddVertex(vertices[3]);
            surfTool.AddVertex(vertices[6]);
            surfTool.AddVertex(vertices[2]);

            surfTool.AddVertex(vertices[3]);
            surfTool.AddVertex(vertices[7]);
            surfTool.AddVertex(vertices[6]);


            surfTool.AddNormal(new Vector3(-1.0f, 0.0f, 0.0f));
            surfTool.AddVertex(vertices[0]);
            surfTool.AddVertex(vertices[7]);
            surfTool.AddVertex(vertices[3]);

            surfTool.AddVertex(vertices[0]);
            surfTool.AddVertex(vertices[4]);
            surfTool.AddVertex(vertices[7]);

            surfTool.AddNormal(new Vector3(1.0f, 0.0f, 0.0f));
            surfTool.AddVertex(vertices[2]);
            surfTool.AddVertex(vertices[5]);
            surfTool.AddVertex(vertices[1]);

            surfTool.AddVertex(vertices[2]);
            surfTool.AddVertex(vertices[6]);
            surfTool.AddVertex(vertices[5]);


            // // surfTool.AddNormal(new Vector3(0.0f, 1.0f, 0.0f));
            // surfTool.AddVertex(new Vector3(length, height, -width));
            // surfTool.AddVertex(new Vector3(-length, height, -width));
            // surfTool.AddVertex(new Vector3(-length, height, width));
            // surfTool.AddVertex(new Vector3(length, height, width));

            surfTool.Index();
            // surfTool.GenerateNormals();

            var mesh = surfTool.Commit();

            this.SetMesh(mesh);
        }
        private void Reset()
        {
            Mesh usedMesh = mesh;

            if (usedMesh == null)
            {
                SurfaceTool st = new SurfaceTool();

                st.Begin(Mesh.PrimitiveType.Triangles);

                switch (drawMode)
                {
                case DrawMode.SingleTriangle:
                {
                    st.AddUv(new Vector2(0, 0));
                    st.AddVertex(new Vector3(-.5f, -.5f, 0));

                    st.AddUv(new Vector2(0, 2));
                    st.AddVertex(new Vector3(-.5f, 1.5f, 0));

                    st.AddUv(new Vector2(2, 0));
                    st.AddVertex(new Vector3(1.5f, -.5f, 0));
                    break;
                }

                case DrawMode.Quad:
                {
                    st.AddUv(new Vector2(0, 0));
                    st.AddVertex(new Vector3(-.5f, -.5f, 0));

                    st.AddUv(new Vector2(0, 1));
                    st.AddVertex(new Vector3(-.5f, .5f, 0));

                    st.AddUv(new Vector2(1, 0));
                    st.AddVertex(new Vector3(.5f, .51f, 0));

                    st.AddUv(new Vector2(1, 0));
                    st.AddVertex(new Vector3(.5f, -.5f, 0));

                    st.AddUv(new Vector2(0, 1));
                    st.AddVertex(new Vector3(-.5f, .5f, 0));

                    st.AddUv(new Vector2(1, 1));
                    st.AddVertex(new Vector3(.5f, .5f, 0));
                    break;
                }
                }

                //st.SetMaterial(particleSystem.testMaterial);
                st.Index();

                usedMesh = st.Commit();
            }

            multimesh = new MultiMesh();
            multimesh.TransformFormat = MultiMesh.TransformFormatEnum.Transform2d;
            multimesh.ColorFormat     = MultiMesh.ColorFormatEnum.Float;
            //multimesh.CustomDataFormat = MultiMesh.CustomDataFormatEnum.Float;
            multimesh.Mesh          = usedMesh;
            multimesh.InstanceCount = particleSystem.maxParticles;
        }
    private void CreatePerceptionPyramidMesh()
    {
        var material = new SpatialMaterial();

        material.FlagsTransparent = true;
        material.AlbedoColor      = new Color(0.0f, 1.0f, 0.0f, 0.02f);
        material.SetCullMode(SpatialMaterial.CullMode.Disabled);

        // Pyramid
        var surfaceTool = new SurfaceTool();

        surfaceTool.Begin(Mesh.PrimitiveType.Triangles);

        // Top face
        surfaceTool.AddNormal(new Vector3(0.0f, 0.5f, 0.5f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(-perceptionRadius / 2, perceptionRadius / 2, -perceptionRadius)); // top left

        surfaceTool.AddNormal(new Vector3(0.0f, 0.5f, 0.5f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(perceptionRadius / 2, perceptionRadius / 2, -perceptionRadius)); // top right

        surfaceTool.AddNormal(new Vector3(0.0f, 0.5f, 0.5f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(0, 0, 2.0f)); // home

        // Right face
        surfaceTool.AddNormal(new Vector3(0.5f, 0.0f, 0.5f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(perceptionRadius / 2, perceptionRadius / 2, -perceptionRadius)); // top right

        surfaceTool.AddNormal(new Vector3(0.5f, 0.0f, 0.5f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(perceptionRadius / 2, -perceptionRadius / 2, -perceptionRadius)); // bottom right

        surfaceTool.AddNormal(new Vector3(0.5f, 0.0f, 0.5f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(0, 0, 2.0f)); // home

        // Bottom face
        surfaceTool.AddNormal(new Vector3(0.0f, -0.5f, 0.5f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(perceptionRadius / 2, -perceptionRadius / 2, -perceptionRadius)); // bottom right

        surfaceTool.AddNormal(new Vector3(0.0f, -0.5f, 0.5f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(-perceptionRadius / 2, -perceptionRadius / 2, -perceptionRadius)); // bottom left

        surfaceTool.AddNormal(new Vector3(0.0f, -0.5f, 0.5f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(0, 0, 2.0f)); // home

        // Left face
        surfaceTool.AddNormal(new Vector3(-0.5f, 0.0f, 0.5f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(-perceptionRadius / 2, -perceptionRadius / 2, -perceptionRadius)); // bottom left

        surfaceTool.AddNormal(new Vector3(-0.5f, 0.0f, 0.5f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(-perceptionRadius / 2, perceptionRadius / 2, -perceptionRadius)); // top left

        surfaceTool.AddNormal(new Vector3(-0.5f, 0.0f, 0.5f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(0, 0, 2.0f)); // home

        // Base face1
        surfaceTool.AddNormal(new Vector3(0.0f, 0.0f, -1.0f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(perceptionRadius / 2, perceptionRadius / 2, -perceptionRadius)); // top right

        surfaceTool.AddNormal(new Vector3(0.0f, 0.0f, -1.0f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(-perceptionRadius / 2, perceptionRadius / 2, -perceptionRadius)); // top left

        surfaceTool.AddNormal(new Vector3(0.0f, 0.0f, -1.0f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(-perceptionRadius / 2, -perceptionRadius / 2, -perceptionRadius)); // bottom left

        // Base face2
        surfaceTool.AddNormal(new Vector3(0.0f, 0.0f, -1.0f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(-perceptionRadius / 2, -perceptionRadius / 2, -perceptionRadius)); // bottom left

        surfaceTool.AddNormal(new Vector3(0.0f, 0.0f, -1.0f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(perceptionRadius / 2, -perceptionRadius / 2, -perceptionRadius)); // bottom right

        surfaceTool.AddNormal(new Vector3(0.0f, 0.0f, -1.0f));
        surfaceTool.AddColor(new Color(0.0f, 1.0f, 0.0f, 0.02f));
        surfaceTool.AddVertex(new Vector3(perceptionRadius / 2, perceptionRadius / 2, -perceptionRadius)); // top right

        surfaceTool.Index();

        var mesh = surfaceTool.Commit();

        mesh.SurfaceSetMaterial(0, material);

        var meshInstance = new MeshInstance();

        meshInstance.Mesh = mesh;
        meshInstance.SetName("perceptionMesh");
        meshInstance.SetVisible(false);

        this.AddChild(meshInstance);
    }
Beispiel #24
0
    // Generates sphere with radius 1
    public void GenerateSphere(int iterations)
    {
        float radius = 10f;

        System.Diagnostics.Debug.WriteLine("Generating sphere!");
        Stopwatch totalTimer = new Stopwatch();

        totalTimer.Start();

        SurfaceTool surfaceTool = new SurfaceTool();

        this.planetMesh = new ArrayMesh();

        material.VertexColorUseAsAlbedo = true;
        surfaceTool.SetMaterial(material);
        surfaceTool.Begin(PrimitiveType.Triangles);

        // GENERATE SPHERE:
        Stopwatch planetGeneratorTimer = new Stopwatch();

        planetGeneratorTimer.Start();

        // 9 gives ~30s generate time, which is acceptable
        this.currentStatus = "Generating base topology (this step can take long!)";
        PlanetTopologyData[] planetData = pg.GenerateBaseTopology(iterations, radius);

        planetGeneratorTimer.Stop();
        TimeSpan ts = planetGeneratorTimer.Elapsed;

        System.Diagnostics.Debug.WriteLine("Sphere generated. Number of faces: " + (planetData[0].faces.Count * 20) + "; time needed: " + ts.Minutes + "m " + ts.Seconds + "." + ts.Milliseconds);

        // todo: create biomes

        // Add perlino
        Stopwatch perlinTimer = new Stopwatch();

        perlinTimer.Start();

        this.currentStatus = "Adding perlin noise ...";

        Parallel.For(0, planetData.Length, new ParallelOptions {
            MaxDegreeOfParallelism = System.Environment.ProcessorCount
        }, i => {
            PlanetTopologyData data = planetData[i];
            data.vertices           = pg.AddPerlinDisplacement(data.vertices, radius, 16, 0.42f);

            // float maxDispalcement = 0;
            // float maxNegDisplacement = 0;
            // foreach (PlanetVertex pv in data.vertices) {
            //   if (pv.h > maxDispalcement) {
            //     maxDispalcement = pv.h;
            //   }
            //   if (pv.h < maxNegDisplacement) {
            //     maxNegDisplacement = pv.h;
            //   }
            // }
            // Debug.WriteLine("Max displacement for this face (from-to) " + maxNegDisplacement +" -> " + maxDispalcement);
        });

        perlinTimer.Stop();
        ts = perlinTimer.Elapsed;
        System.Diagnostics.Debug.WriteLine("Perlin applied. Time needed: " + ts.Minutes + "m " + ts.Seconds + "." + ts.Milliseconds);

        Stopwatch surfaceToolTimer = new Stopwatch();

        surfaceToolTimer.Start();

        this.currentStatus = "Building planet mesh ...";

        // // Possible future for multithreading ahead. Might happen some day.
        //
        // SurfaceTool[] surfaceTool = new SurfaceTool[planetData.Length];
        // this.planetMeshes = new ArrayMesh[planetData.Length];

        // material.VertexColorUseAsAlbedo = true;

        // Parallel.For(0, planetData.Length, new ParallelOptions {MaxDegreeOfParallelism = System.Environment.ProcessorCount}, i => {
        //   surfaceTool[i] = new SurfaceTool();
        //   this.planetMeshes[i] = new ArrayMesh();

        //   surfaceTool[i].SetMaterial(material);
        //   surfaceTool[i].Begin(PrimitiveType.Triangles);

        //   for (int j = 0; j < planetData[i].faces.Count; j++) {
        //     planetData[i].faces[j].AddToSurfaceTool(surfaceTool[i]);
        //   }

        //   surfaceTool[i].GenerateNormals();
        //   surfaceTool[i].Commit(this.planetMeshes[i]);
        // });

        int faceCount;

        for (int i = 0; i < planetData.Length; i++)
        {
            faceCount = planetData[i].faces.Count;
            for (int j = 0; j < faceCount; j++)
            {
                planetData[i].faces[j].AddToSurfaceTool(surfaceTool);
            }
        }

        // foreach (PlanetTopologyData data in planetData) {
        //   foreach (PlanetCell c in data.faces) {
        //     c.AddToSurfaceTool(surfaceTool);
        //   }
        // }

        surfaceTool.GenerateNormals();
        surfaceTool.Commit(this.planetMesh);

        surfaceToolTimer.Stop();
        ts = surfaceToolTimer.Elapsed;
        System.Diagnostics.Debug.WriteLine("SurfaceTool generated our mesh. Time needed: " + ts.Minutes + "m " + ts.Seconds + "." + ts.Milliseconds);
        totalTimer.Stop();
        ts = totalTimer.Elapsed;
        System.Diagnostics.Debug.WriteLine("————————————————— total time needed: " + ts.Minutes + "m " + ts.Seconds + "." + ts.Milliseconds + "—————————————————");

        this.Mesh          = planetMesh;
        this.currentStatus = "";
    }
    public void CreateMesh(Tile tile, PackedScene sphereMeshScene, PackedScene greenSphereMeshScene, int numberOfTiles, float radius)
    {
        var surfTool = new SurfaceTool();
        var mesh     = new ArrayMesh();
        var material = new SpatialMaterial();

        material.SetEmission(new Color(1.0f, 0.0f, 0.0f));
        material.SetAlbedo(new Color(1.0f, 0.0f, 0.0f));
        surfTool.SetMaterial(material);
        surfTool.Begin(Mesh.PrimitiveType.LineLoop);
        decimal tileCenterX   = 0;
        decimal tileCenterY   = 0;
        decimal tileCenterZ   = 0;
        decimal polygonRadius = 0;

        List <Point> points            = tile.boundary;
        var          lastPoint         = points[points.Count - 1];
        Vector3      lastPointVector   = new Vector3((float)lastPoint.x, (float)lastPoint.y, (float)lastPoint.z);
        decimal      polygonSideLength = 0;

        foreach (Point point in points)
        {
            surfTool.AddUv(new Vector2(0, 0));
            surfTool.AddVertex(new Vector3((float)point.x, (float)point.y, (float)point.z));

            tileCenterX += point.x / points.Count;
            tileCenterY += point.y / points.Count;
            tileCenterZ += point.z / points.Count;
            Vector3 currentVector = new Vector3((float)point.x, (float)point.y, (float)point.z);
            polygonSideLength += (decimal)currentVector.DistanceTo(lastPointVector);
            lastPointVector    = currentVector;
        }
        polygonSideLength = polygonSideLength / points.Count;

        var tileCenterPoint = new Vector3((float)tileCenterX, (float)tileCenterY, (float)tileCenterZ);
        var firstPoint      = new Vector3((float)points[0].x, (float)points[0].y, (float)points[0].z);

        foreach (Point point in points)
        {
            var vector = new Vector3((float)point.x, (float)point.y, (float)point.z);
            polygonRadius += (decimal)vector.DistanceTo(tileCenterPoint);
        }
        polygonRadius = polygonRadius / points.Count;

        var polygonRotation = firstPoint.AngleTo(tileCenterPoint);


        var sphereCenterPoint = new Vector3(0f, 0f, 0f);

        var          sphereScale = radius / numberOfTiles;
        MeshInstance sphere      = (MeshInstance)sphereMeshScene.Instance();

        sphere.SetTranslation(tileCenterPoint);
        sphere.SetScale(new Vector3(sphereScale, sphereScale, sphereScale));
        this.AddChild(sphere);

        MeshInstance sphere2 = (MeshInstance)greenSphereMeshScene.Instance();

        sphere2.SetTranslation(firstPoint);
        sphere2.SetScale(new Vector3(sphereScale, sphereScale, sphereScale));
        this.AddChild(sphere2);

        MeshInstance sphere3 = (MeshInstance)greenSphereMeshScene.Instance();

        sphere3.SetTranslation((firstPoint - tileCenterPoint) / 2 + tileCenterPoint);
        sphere3.SetScale(new Vector3(sphereScale, sphereScale, sphereScale));
        this.AddChild(sphere3);

        surfTool.GenerateNormals();
        surfTool.Index();
        surfTool.Commit(mesh);
        var meshInstance = new MeshInstance();

        meshInstance.SetMesh(mesh);
        this.AddChild(meshInstance);
    }
Beispiel #26
0
    private void Render(Chunk pChunk)
    {
        // If chunk is already loaded.
        if (LoadedChunks.ContainsKey(pChunk.Offset))
        {
            return;
        }

        SurfaceTool = new SurfaceTool();
        SurfaceTool.Begin(Mesh.PrimitiveType.Triangles);

        // Adding material
        Material mat = VoxMaterial.Duplicate() as Material;

        SurfaceTool.SetMaterial(mat);

        // Creating the mesh. Voxel by voxel
        for (int y = 0; y < Chunk.ChunkSize.y; y++)
        {
            for (int x = 0; x < Chunk.ChunkSize.x; x++)
            {
                for (int z = 0; z < Chunk.ChunkSize.z; z++)
                {
                    if (!pChunk.Voxels[x, y, z].Active)
                    {
                        continue;
                    }

                    CreateVoxel(SurfaceTool, x, y, z, pChunk);
                }
            }
        }

        // Reduces vertex size
        SurfaceTool.Index();

        // Creating instance
        MeshInstance chunk = new MeshInstance
        {
            Mesh        = SurfaceTool.Commit(),
            Name        = pChunk.Offset.ToString(),
            Translation = new Vector3(pChunk.Offset.x * Chunk.ChunkSize.x, 0, pChunk.Offset.y * Chunk.ChunkSize.z)
        };

        // Creating collisions
        //chunk.CreateTrimeshCollision();


        // Tagging the chunk
        chunk.AddToGroup("Chunk");

        // Chunk is now loaded. Adding to the scene.
        LoadedChunks.TryAdd(pChunk.Offset, pChunk);
        this.CallDeferred("add_child", chunk);

        if (pChunk.VoxelSprite.Count < 64)
        {
            // Adding voxelsprite
            foreach (VoxelSprite voxSprite in pChunk.VoxelSprite)
            {
                var meshInstance = new MeshInstance();
                meshInstance.SetDeferred("mesh", voxSprite.Mesh);

                // Adding next frame to avoid locking problems.
                chunk.CallDeferred("add_child", meshInstance);

                // Moving next frame because not in tree yet
                meshInstance.SetDeferred("translation", voxSprite.Position);

                // Applying wind shader.
                meshInstance.SetDeferred("material_override", GrassMaterial);

                // Scaling down because its a decoration
                meshInstance.Scale = meshInstance.Scale /= 8;
            }
        }



        // Fade in animation.
        //var t2 = new Tween();
        //chunk.AddChild(t2);
        //t2.InterpolateProperty(mat, "albedo_color", new Color(1, 1, 1, 0f), new Color(1, 1, 1, 1f), 1f, Tween.TransitionType.Linear, Tween.EaseType.InOut);
        //t2.Start();

        SurfaceTool.Clear();
    }
Beispiel #27
0
    private Mesh GenerateMesh()
    {
        st = new SurfaceTool();
        st.Begin(Mesh.PrimitiveType.Triangles);

        for (int i = 0; i < numPoints - 1; i++)
        {
            Vector3 thisP = points[i + 0];
            Vector3 nxtP  = points[i + 1];

            Vector3 thisR = rightVecs[i + 0];
            Vector3 nxtR  = rightVecs[i + 1];

            float thisL = lengths[i + 0];
            float nxtL  = lengths[i + 1];

            Vector3 vec1 = thisP + thisR * roadWidth * .5f;
            Vector3 vec2 = thisP - thisR * roadWidth * .5f;
            Vector3 vec3 = nxtP - nxtR * roadWidth * .5f;
            Vector3 vec4 = nxtP + nxtR * roadWidth * .5f;

            Vector2 uv1 = Vector2.Zero;
            Vector2 uv2 = Vector2.Zero;
            Vector2 uv3 = Vector2.Zero;
            Vector2 uv4 = Vector2.Zero;

            if (tileUV)
            {
                uv1 = new Vector2(thisL / roadWidth, 0f);
                uv2 = new Vector2(thisL / roadWidth, 1f);
                uv3 = new Vector2(nxtL / roadWidth, 1f);
                uv4 = new Vector2(nxtL / roadWidth, 0f);
            }
            else
            {
                uv1 = new Vector2(thisL / totalLength, 0f);
                uv2 = new Vector2(thisL / totalLength, 1f);
                uv3 = new Vector2(nxtL / totalLength, 1f);
                uv4 = new Vector2(nxtL / totalLength, 0f);
            }

            uv1 *= UVScale;
            uv2 *= UVScale;
            uv3 *= UVScale;
            uv4 *= UVScale;

            CreateTRI(
                vec1, vec2, vec4,
                uv1, uv2, uv4
                );
            CreateTRI(
                vec4, vec2, vec3,
                uv4, uv2, uv3
                );
        }

        AddCaps();

        st.Index();
        st.GenerateNormals();
        return(st.Commit());
    }
Beispiel #28
0
    public MeshInstance CreateChunkMesh(Chunk chunk)
    {
        MeshInstance instance    = new MeshInstance();
        SurfaceTool  surfacetool = new SurfaceTool();

        surfacetool.Begin(Mesh.PrimitiveType.Points);
        surfacetool.SetMaterial(chunkMaterial);
        int count = 0;

        for (int i = 0; i < Constants.CHUNK_SIZE3D / chunk.Materials; i++)
        {
            Run         run         = chunk.Voxels[i];
            int         objectID    = run.value;
            TerraObject terraObject = registry.SelectByID((int)objectID);
            var         x           = i % CHUNK_SIZE;
            var         y           = (i / CHUNK_SIZE) % CHUNK_SIZE;
            var         z           = i / (CHUNK_SIZE * CHUNK_SIZE);
            if (chunk.Voxels[i].value != 0)
            {
                int face = 0b000000;
                //Left
                if (x == 0 || chunk.Voxels[i - 1].value != objectID)
                {
                    face = 0b000001;
                }

                //Right
                else if (x == 63 || chunk.Voxels[i + 1].value != objectID)
                {
                    face = 0b000010;
                }
                //Top
                else if (y == 63 || chunk.Voxels[i + 64].value != objectID)
                {
                    face = 0b000100;
                }
                //Bottom
                else if (y == 0 || chunk.Voxels[i - 64].value != objectID)
                {
                    face = 0b001000;
                }
                //Back
                else if (z == 63 || chunk.Voxels[i + 4096].value != objectID)
                {
                    face = 0b010000;
                }
                //Front
                else if (z == 0 || chunk.Voxels[i - 4096].value != objectID)
                {
                    face = 0b100000;
                }

                if (face != 0b000000)
                {
                    int     counter   = 0;
                    Vector3 normalAvg = Vector3.Zero;
                    for (int j = 0; j < 6; j++)
                    {
                        int bitFlagN = (face >> j) & 1;
                        if (bitFlagN == 1)
                        {
                            normalAvg = normalAvg + Normals[j];
                            counter  += 1;
                        }
                    }

                    count += 1;
                    surfacetool.AddColor(new Color(1f, 1f, 1f, 1f));
                    Vector3 voxPosition = new Vector3((x) * VOX_SIZE, (y) * VOX_SIZE, (z) * VOX_SIZE);
                    voxPosition.x = voxPosition.x + (chunk.x * CHUNK_SIZE * VOX_SIZE);
                    voxPosition.y = voxPosition.y + (chunk.y * CHUNK_SIZE * VOX_SIZE);
                    voxPosition.z = voxPosition.z + (chunk.z * CHUNK_SIZE * VOX_SIZE);
                    if (counter > 0)
                    {
                        normalAvg = normalAvg / counter;
                        surfacetool.AddNormal(normalAvg);
                    }

                    surfacetool.AddVertex(voxPosition);
                }
            }
        }

        surfacetool.Index();
        instance.Mesh = surfacetool.Commit();
        surfacetool.Clear();
        instance.MaterialOverride = chunkMaterial.Duplicate() as ShaderMaterial;

        // Console.WriteLine("Mesh AABB Pos: {0} , Size: {1}, End: {2}",bb.Position,bb.Size,bb.End);
        return(instance);
    }
Beispiel #29
0
        private static void BuildDoorMesh()
        {
            if (_doorMesh == null)
            {
                Color white = new Color(1f, 1f, 1f, 1f);

                using (SurfaceTool st = new SurfaceTool())
                {
                    Vector3[] cellVerts = Level.GetVerticesForCell();

                    Vector3[] verts = new Vector3[] {
                        Lerp(cellVerts[(int)Level.CellVertexIndex.Top_SW], cellVerts[(int)Level.CellVertexIndex.Top_NW], 0.5f),
                        Lerp(cellVerts[(int)Level.CellVertexIndex.Top_SE], cellVerts[(int)Level.CellVertexIndex.Top_NE], 0.5f),
                        Lerp(cellVerts[(int)Level.CellVertexIndex.Bot_SW], cellVerts[(int)Level.CellVertexIndex.Bot_NW], 0.5f),
                        Lerp(cellVerts[(int)Level.CellVertexIndex.Bot_SE], cellVerts[(int)Level.CellVertexIndex.Bot_NE], 0.5f)
                    };

                    st.Begin(Godot.Mesh.PrimitiveType.Triangles);

                    st.AddUv(new Vector2(0f, 1f));
                    st.AddColor(white);
                    st.AddNormal(Level.South);
                    st.AddVertex(verts[3]);
                    st.AddUv(new Vector2(0f, 0f));
                    st.AddColor(white);
                    st.AddNormal(Level.South);
                    st.AddVertex(verts[1]);
                    st.AddUv(new Vector2(1f, 0f));
                    st.AddColor(white);
                    st.AddNormal(Level.South);
                    st.AddVertex(verts[0]);

                    st.AddUv(new Vector2(1f, 1f));
                    st.AddColor(white);
                    st.AddNormal(Level.South);
                    st.AddVertex(verts[2]);
                    st.AddUv(new Vector2(0f, 1f));
                    st.AddColor(white);
                    st.AddNormal(Level.South);
                    st.AddVertex(verts[3]);
                    st.AddUv(new Vector2(1f, 0f));
                    st.AddColor(white);
                    st.AddNormal(Level.South);
                    st.AddVertex(verts[0]);


                    st.AddUv(new Vector2(1f, 0f));
                    st.AddColor(white);
                    st.AddNormal(Level.North);
                    st.AddVertex(verts[0]);
                    st.AddUv(new Vector2(0f, 0f));
                    st.AddColor(white);
                    st.AddNormal(Level.North);
                    st.AddVertex(verts[1]);
                    st.AddUv(new Vector2(0f, 1f));
                    st.AddColor(white);
                    st.AddNormal(Level.North);
                    st.AddVertex(verts[3]);

                    st.AddUv(new Vector2(1f, 0f));
                    st.AddColor(white);
                    st.AddNormal(Level.North);
                    st.AddVertex(verts[0]);
                    st.AddUv(new Vector2(0f, 1f));
                    st.AddColor(white);
                    st.AddNormal(Level.North);
                    st.AddVertex(verts[3]);
                    st.AddUv(new Vector2(1f, 1f));
                    st.AddColor(white);
                    st.AddNormal(Level.North);
                    st.AddVertex(verts[2]);

                    _doorMesh = st.Commit();
                }
            }
        }
Beispiel #30
0
    // Declare member variables here. Examples:
    // private int a = 2;
    // private string b = "text";

    // Called when the node enters the scene tree for the first time.
    public override void _Ready()
    {
        var orig   = GetNode <MeshInstance>("orig");
        var tights = GetNode <MeshInstance>("tights");
        var result = GetNode <MeshInstance>("result");

        var tmpMesh     = new ArrayMesh();
        var surfaceTool = new SurfaceTool();

        surfaceTool.Begin(Mesh.PrimitiveType.Triangles);

        var tool = new MeshDataTool();

        tool.CreateFromSurface((ArrayMesh)tights.Mesh, 0);

        var tool2 = new MeshDataTool();

        tool2.CreateFromSurface((ArrayMesh)orig.Mesh, 0);

        List <Vector3> vertices = new List <Vector3>();

        for (int v = 0; v < tool2.GetVertexCount(); v++)
        {
            vertices.Add(tool2.GetVertex(v));
        }

        for (int v = 0; v < tool.GetVertexCount(); v++)
        {
            //  surfaceTool.AddNormal(tool.GetVertexNormal(v));
            //  surfaceTool.AddColor(tool.GetVertexColor(v));
            // surfaceTool.AddUv(tool.GetVertexUv(v));
            //  surfaceTool.AddUv2(tool.GetVertexUv2(v));
            //  surfaceTool.AddTangent(tool.GetVertexTangent(v));

            var newVer  = tool.GetVertex(v);
            var replace = vertices.OrderBy(df => newVer.DistanceTo(df)).FirstOrDefault();

            if (replace != null && replace != Vector3.Zero && replace.DistanceTo(newVer) > 0.03f)
            {
                GD.Print("replace" + newVer + " by dist " + replace.DistanceTo(newVer));
                surfaceTool.AddVertex(replace);
            }
            else
            {
                surfaceTool.AddVertex(newVer);
            }
        }

        for (int fc = 0; fc < tool.GetFaceCount(); fc++)
        {
            for (var i = 0; i <= 2; i++)
            {
                var ind = tool.GetFaceVertex(fc, i);
                surfaceTool.AddIndex(ind);
            }
        }


        surfaceTool.Commit(tmpMesh);
        result.Mesh = tmpMesh;
    }