Example #1
0
        void buildVertexBuffer()
        {
            Console.Write("Building vertex buffers... ");
            Stopwatch stopwatch = Stopwatch.StartNew();

            if (vertexArray == null || vertexArray.Length != vertices.Count)
            {
                vertexArray = new VertexPositionNormalColor[vertices.Count];
            }

            //for (int i = 0; i < vertexArray.Length; i++)
            Parallel.For(0, vertexArray.Length, (i) =>
            {
                Vector3 position = vertices[i].Position;
                Vector3 normal   = vertices[i].Position;
                Color color      = vertices[i].Color;
                vertexArray[i]   = new VertexPositionNormalColor(position, normal, color);
            });

            if (vertexBuffer == null || vertexBuffer.VertexCount != vertexArray.Length)
            {
                vertexBuffer = new VertexBuffer(graphicsDevice, typeof(VertexPositionNormalColor), vertexArray.Length, BufferUsage.WriteOnly);
            }
            vertexBuffer.SetData(vertexArray);

            stopwatch.Stop();
            Console.WriteLine("" + stopwatch.ElapsedMilliseconds + " ms");
        }
Example #2
0
            private void CreateTileMeshData(Point point, int width, int height, Vector3 offset, out VertexPositionNormalColor[] vertices, out ushort[] indices)
            {
                vertices = new VertexPositionNormalColor[(width + 1) * (height + 1)];

                ushort GetIndex(int x, int y) => (ushort)(y * (width + 1) + x);

                for (int j = 0; j <= height; ++j)
                {
                    for (int i = 0; i <= width; ++i)
                    {
                        GetHeightStickHeightAndColor(point.X + i, point.Y + j, out var heightStickHeight, out var color);
                        vertices[GetIndex(i, j)] = new VertexPositionNormalColor(
                            offset + new Vector3(i, heightStickHeight, j),
                            Vector3.UnitY,
                            color);
                    }
                }

                indices = new ushort[width * height * 6];
                var count = 0;

                for (int j = 0; j < height; ++j)
                {
                    for (int i = 0; i < width; ++i)
                    {
                        indices[count++] = GetIndex(i, j);
                        indices[count++] = GetIndex(i + 1, j);
                        indices[count++] = GetIndex(i, j + 1);

                        indices[count++] = GetIndex(i + 1, j);
                        indices[count++] = GetIndex(i + 1, j + 1);
                        indices[count++] = GetIndex(i, j + 1);
                    }
                }
            }
 void ConvertPartsToPrimitive(Color DefaultColor)
 {
     //Convert Vertex to VertexPositionNormalColor, with no Normal
     AsteroidVertices = new VertexPositionNormalColor[Vertices.Count];
     for (int i = 0; i < Vertices.Count; i++)
     {
         AsteroidVertices[i] = new VertexPositionNormalColor(Vertices[i].Position, Vector3.Zero, DefaultColor);
     }
     //Convert Triangles into Indices
     AsteroidIndices = new int[Triangles.Count * 3];
     for (int i = 0; i < Triangles.Count; i++)
     {
         AsteroidIndices[i * 3]     = Triangles[i].Vertices[0].Index;
         AsteroidIndices[i * 3 + 1] = Triangles[i].Vertices[1].Index;
         AsteroidIndices[i * 3 + 2] = Triangles[i].Vertices[2].Index;
     }
     //Determine Normals by summing the Normals of all Triangles
     for (int i = 0; i < Triangles.Count; i++)
     {
         AsteroidVertices[Triangles[i].Vertices[0].Index].Normal += Triangles[i].Normal;
         AsteroidVertices[Triangles[i].Vertices[1].Index].Normal += Triangles[i].Normal;
         AsteroidVertices[Triangles[i].Vertices[2].Index].Normal += Triangles[i].Normal;
     }
     //Then normalize the Normals again
     for (int i = 0; i < AsteroidVertices.Length; i++)
     {
         AsteroidVertices[i].Normal.Normalize();
     }
 }
Example #4
0
        /// <summary>
        /// Loads model from vertices and indices list.
        /// </summary>
        /// <param name="vertices">The list of vertices.</param>
        /// <param name="indices">The list of indices.</param>
        public void LoadModel(ref List <Mesh.Vertex> vertices, ref List <int> indices)
        {
            VertexPositionNormalColor[] vvertices = new VertexPositionNormalColor[vertices.Count];

            int i = 0;

            foreach (var vertex in vertices)
            {
                vvertices[i].Position = vertex.Position;
                vvertices[i].Color    = Color.DarkBlue;
                vvertices[i++].Normal = vertex.Normal;
            }

            int[] vindices = new int[indices.Count];
            i = 0;
            foreach (var index in indices)
            {
                vindices[i++] = index;
            }

            m_IndexBuffer = new IndexBuffer(GraphicsDevice, typeof(int), indices.Count, BufferUsage.WriteOnly);
            m_IndexBuffer.SetData(vindices);

            m_VertexBuffer = new VertexBuffer(GraphicsDevice, VertexPositionNormalColor.VertexDeclaration, vvertices.Length, BufferUsage.WriteOnly);
            m_VertexBuffer.SetData(vvertices);
        }
Example #5
0
        public VertexPositionNormalColor[] GenerateScaledPolygon(VertexPositionNormalColor[] unitCube, float scale)
        {
            for (int i = 0; i < unitCube.Length; i++)
            {
                unitCube[i].Position = unitCube[i].Position * scale;
            }

            return unitCube;
        }
Example #6
0
 /// <summary>
 /// Create a new model.
 /// </summary>
 /// <param name="game"></param>
 /// <param name="shapeArray"></param>
 /// <param name="collisionRadius"></param>
 //Create a coloured model with normals
 public MyModel(LabGame game, VertexPositionNormalColor[] shapeArray, float collisionRadius)
 {
     this.vertices = Buffer.Vertex.New(game.GraphicsDevice, shapeArray);
     this.inputLayout = VertexInputLayout.New<VertexPositionNormalColor>(0);
     vertexStride = Utilities.SizeOf<VertexPositionNormalColor>();
     modelType = ModelType.Colored;
     this.collisionRadius = collisionRadius;
     wasLoaded = false;
 }
Example #7
0
        /// <summary>
        /// Set colors on points on the plane
        /// </summary>
        private void SetColors()
        {
            fUpdateColors = false;

            int max = fPlane.Segments;

            Color color1 = Color.White;
            Color color2 = Color.White;

            switch (fColorMode)
            {
            case ColorMode.Points:
                color1 = Color.White;
                color2 = Color.Black;
                break;

            case ColorMode.SkyBlue:
                color1 = Color.SkyBlue;
                color2 = Color.SkyBlue;
                break;
            }

            Color startColor = color1;

            for (int x = 0; x <= max; x++)
            {
                Color color = startColor;
                for (int z = 0; z <= max; z++)
                {
                    VertexPositionNormalColor p = fPlane.GetPoint(x, z);
                    p.Color = color;
                    fPlane.SetPoint(x, z, p);
                    if (startColor != color2)
                    {
                        if (color == color1)
                        {
                            color = color2;
                        }
                        else if (color == color2)
                        {
                            color = color1;
                        }
                    }
                }
                if (startColor == color1)
                {
                    startColor = color2;
                }
                else if (startColor == color2)
                {
                    startColor = color1;
                }
            }
        }
Example #8
0
        /// <summary>
        /// Create a new ocean.
        /// </summary>
        /// <param name="size">Size of ocean</param>
        /// <param name="seaLevel">Height of ocean.</param>
        /// <returns>An ocean model.</returns>
        public MyModel CreateOcean(int size, int seaLevel)
        {
            float collisionRadius = 1;
            int sidelength = (int)Math.Pow(2, size);
            int min = -sidelength / 2;
            int k = 0;
            // Data structures for generating vertice heightmap
            Vector3[][] points = new Vector3[sidelength][];
            Vector3[][] normals = new Vector3[sidelength][];
            Random rand = new Random();

            // Generate an ocean by calling the function
            points = genMap(sidelength, -WORLD_WIDTH, WORLD_WIDTH, -WORLD_WIDTH, WORLD_WIDTH, -seaLevel);

            // Calculate vertex normals
            normals = getNormals(points);

            VertexPositionNormalColor[] shapeArray = new VertexPositionNormalColor[sidelength * sidelength * 6];

            for (int i = 0; i < sidelength; i++)
            {
                for (int j = 0; j < sidelength; j++)
                {
                    //Each step creates a square in the map mesh
                    //Bottom triangle
                    shapeArray[k] = new VertexPositionNormalColor(points[i][j], -Vector3.UnitZ,
                        Color.SkyBlue);
                    shapeArray[k + 1] = new VertexPositionNormalColor(points[i+1][j+1], -Vector3.UnitZ,
                        Color.SkyBlue);
                    shapeArray[k + 2] = new VertexPositionNormalColor(points[i+1][j], -Vector3.UnitZ,
                        Color.SkyBlue);

                    //Top Triangle
                    shapeArray[k + 3] = new VertexPositionNormalColor(points[i][j], -Vector3.UnitZ,
                        Color.SkyBlue);
                    shapeArray[k + 4] = new VertexPositionNormalColor(points[i][j+1], -Vector3.UnitZ,
                        Color.SkyBlue);
                    shapeArray[k + 5] = new VertexPositionNormalColor(points[i+1][j+1], -Vector3.UnitZ,
                        Color.SkyBlue);

                    k += 6;
                }
            }

            MyModel m = new MyModel(game, shapeArray, collisionRadius);

            // Make reference to points
            game.worldBase.heights = points;
            m.modelMap = points;

            return m;
        }
Example #9
0
        //assume square maze
        public VertexPositionNormalColor[] GetMazeVertexWithCube(float[,] maze,float scale)
        {
            VertexPositionNormalColor[] sampleCube = GenerateScaledPolygon(GetUnitCube(), scale);
            VertexPositionNormalColor[] sampleRoad = GenerateScaledPolygon(GetUnitCubeFloor(Color.Green), scale);
            int dimension = maze.GetLength(0);
            int cubeNumVertex = sampleCube.Length;
            VertexPositionNormalColor[] mazeCubes = new VertexPositionNormalColor[dimension * dimension*cubeNumVertex];
            VertexPositionNormalColor[] tempCube;
            VertexPositionNormalColor[] tempRoad;
            int countIndex = 0;
            for (int row = 0; row < dimension; row++)
            {
                for (int col = 0; col < dimension; col++)
                {
                    if(maze[row,col]==wall)
                    {
                        tempCube = (VertexPositionNormalColor[])sampleCube.Clone();
                        tempCube = TranslatePolygonInXY(tempCube, new Vector3((float)scale * 2 * col, 0.0f, (float)scale * 2 * row));
                        for (int i = 0; i < tempCube.Length; i++)
                        {
                            mazeCubes[countIndex++] = tempCube[i];
                        }
                    }
                    /*
                    if (maze[row, col] == goal)
                    {
                        tempRoad = GenerateScaledPolygon(GetUnitCubeFloor(Color.Yellow), scale);
                        tempRoad = TranslatePolygonInXY(tempRoad, new Vector3((float)scale * 2 * col, 0.0f, (float)scale * 2 * row));
                        for (int i = 0; i < tempRoad.Length; i++)
                        {
                            mazeCubes[countIndex++] = tempRoad[i];
                        }
                    }*/

                    if (maze[row, col] == road || maze[row, col] == goal)
                    {
                        tempRoad = (VertexPositionNormalColor[])sampleRoad.Clone();
                        tempRoad = TranslatePolygonInXY(tempRoad, new Vector3((float)scale * 2 * col, 0.0f, (float)scale * 2 * row));
                        for (int i = 0; i < tempRoad.Length; i++)
                        {
                            mazeCubes[countIndex++] = tempRoad[i];
                        }
                    }
                }
            }

            //know how many vertex are for wall and floor
            numberWallAndFloor = countIndex;

            return mazeCubes;
        }
Example #10
0
        private void CreateVerticesChunks(CHeightmap cheightmap,
                                          ref Dictionary <int, VertexPositionNormalColor[]> vertexdict, int reCurisiveCounter, int xOffset)
        {
            Random rn = new Random();

            int terrainWidth  = cheightmap.Image.Width / chunksplit;
            int terrainHeight = cheightmap.Image.Height / chunksplit;
            int globaly       = 0;
            int globalx       = 0;
            int yOffset       = 0;

            if (reCurisiveCounter % chunksplit == 0 && reCurisiveCounter != 0)
            {
                xOffset += terrainWidth;
                xOffset--;
            }
            var vertices         = new VertexPositionNormalColor[terrainWidth * terrainHeight];
            var vertRandomOffset = 0.45f;

            for (int x = 0; x < terrainWidth; x++)
            {
                for (int y = 0; y < terrainHeight; y++)
                {
                    yOffset = terrainHeight * (reCurisiveCounter % chunksplit);
                    if (yOffset > 0)
                    {
                        yOffset = yOffset - reCurisiveCounter % chunksplit;
                    }
                    globalx = x + xOffset;
                    globaly = y + yOffset;
                    float height = cheightmap.HeightData[globalx, globaly].R + vertRandomOffset - (float)(rn.NextDouble() * vertRandomOffset * 2);
                    vertices[x + y * terrainWidth].Position = new Vector3(globalx, height, globaly);
                    vertices[x + y * terrainWidth].Color    = materialPick(cheightmap.HeightData[globalx, globaly].G);

                    //vertices[x + y * terrainWidth].TextureCoordinate = new Vector2((float) x / terrainWidth,
                    //(float) y / terrainHeight);
                }
            }
            vertexdict.Add(reCurisiveCounter, vertices);


            if (reCurisiveCounter + 1 < chunksplit * chunksplit)
            {
                CreateVerticesChunks(cheightmap, ref vertexdict, reCurisiveCounter + 1, xOffset);
            }
        }
Example #11
0
        /// <summary>
        /// Set colors on points on the plane
        /// </summary>
        private void SetColors(PrimitivePlane plane)
        {
            //fUpdateColors = false;

            int max = plane.Segments;

            Color color1 = Color.SkyBlue;
            Color color2 = Color.DeepSkyBlue;

            bool useColor1 = true;

            for (int x = 0; x <= max; x++)
            {
                Color color;

                for (int z = 0; z <= max; z++)
                {
                    VertexPositionNormalColor p1 = plane.GetPoint(x, z);
                    if (useColor1)
                    {
                        color = color1;
                    }
                    else
                    {
                        color = color2;
                    }
                    if (useColor1)
                    {
                        color.R = (byte)(255 * z / max);
                    }
                    useColor1 = !useColor1;


                    p1.Color = color;
                    plane.SetPoint(x, z, p1);
                }
                useColor1 = !useColor1;
            }
        }
Example #12
0
        private void ResizeBuffer(int numberOfTriangles)
        {
            int requiredBufferLength = numberOfTriangles * 3;

            if (_buffer.Length >= requiredBufferLength)
            {
                return;
            }

            // Double buffer until it is large enough.
            int newBufferLength = _buffer.Length * 2;

            while (newBufferLength < requiredBufferLength)
            {
                newBufferLength *= 2;
            }

            // Copy old buffer to new buffer.
            var newBuffer = new VertexPositionNormalColor[newBufferLength];

            Array.Copy(_buffer, newBuffer, _buffer.Length);

            _buffer = newBuffer;
        }
Example #13
0
        public override void Initialize()
        {
            base.Initialize();
            this.sBlueZoomOut               = this.CMProvider.Get(CM.EndCutscene).Load <SoundEffect>("Sounds/Ending/Cutscene64/BlueZoomOut");
            this.sProgressiveAppear         = this.CMProvider.Get(CM.EndCutscene).Load <SoundEffect>("Sounds/Ending/Cutscene64/CubesProgressiveAppear");
            this.sFadeOut                   = this.CMProvider.Get(CM.EndCutscene).Load <SoundEffect>("Sounds/Ending/Cutscene64/CubesFadeOut");
            this.LevelManager.ActualAmbient = new Color(0.25f, 0.25f, 0.25f);
            this.LevelManager.ActualDiffuse = Color.White;
            Random random = RandomHelper.Random;
            float  y1     = 1f / (float)Math.Sqrt(6.0);
            float  z1     = (float)Math.Sqrt(3.0) / 2f;
            float  y2     = (float)Math.Sqrt(2.0 / 3.0);
            float  z2     = (float)(1.0 / (2.0 * Math.Sqrt(3.0)));
            float  x      = 1f / (float)Math.Sqrt(2.0);

            VertexPositionNormalColor[] vertices = new VertexPositionNormalColor[864000];
            int[] indices = new int[1296000];
            int   num1    = 0;
            int   num2    = 0;

            for (int index1 = -100; index1 < 100; ++index1)
            {
                for (int index2 = -180; index2 < 180; ++index2)
                {
                    Color   color   = index2 != 0 || index1 != 0 ? MulticoloredSpace.Colors[random.Next(0, MulticoloredSpace.Colors.Length)] : MulticoloredSpace.MainCubeColor;
                    Vector3 vector3 = new Vector3((float)(index2 * 6), (float)(index1 * 6 + (Math.Abs(index2) % 2 == 0 ? 0 : 3)), 0.0f);
                    int     num3    = num1;
                    VertexPositionNormalColor[] positionNormalColorArray1 = vertices;
                    int index3 = num1;
                    int num4   = 1;
                    int num5   = index3 + num4;
                    positionNormalColorArray1[index3] = new VertexPositionNormalColor(new Vector3(x, -y1, -z2) + vector3, new Vector3(-1f, 0.0f, 0.0f), color);
                    VertexPositionNormalColor[] positionNormalColorArray2 = vertices;
                    int index4 = num5;
                    int num6   = 1;
                    int num7   = index4 + num6;
                    positionNormalColorArray2[index4] = new VertexPositionNormalColor(new Vector3(x, y1, z2) + vector3, new Vector3(-1f, 0.0f, 0.0f), color);
                    VertexPositionNormalColor[] positionNormalColorArray3 = vertices;
                    int index5 = num7;
                    int num8   = 1;
                    int num9   = index5 + num8;
                    positionNormalColorArray3[index5] = new VertexPositionNormalColor(new Vector3(0.0f, 0.0f, z1) + vector3, new Vector3(-1f, 0.0f, 0.0f), color);
                    VertexPositionNormalColor[] positionNormalColorArray4 = vertices;
                    int index6 = num9;
                    int num10  = 1;
                    int num11  = index6 + num10;
                    positionNormalColorArray4[index6] = new VertexPositionNormalColor(new Vector3(0.0f, -y2, z2) + vector3, new Vector3(-1f, 0.0f, 0.0f), color);
                    VertexPositionNormalColor[] positionNormalColorArray5 = vertices;
                    int index7 = num11;
                    int num12  = 1;
                    int num13  = index7 + num12;
                    positionNormalColorArray5[index7] = new VertexPositionNormalColor(new Vector3(0.0f, -y2, z2) + vector3, new Vector3(0.0f, 0.0f, -1f), color);
                    VertexPositionNormalColor[] positionNormalColorArray6 = vertices;
                    int index8 = num13;
                    int num14  = 1;
                    int num15  = index8 + num14;
                    positionNormalColorArray6[index8] = new VertexPositionNormalColor(new Vector3(0.0f, 0.0f, z1) + vector3, new Vector3(0.0f, 0.0f, -1f), color);
                    VertexPositionNormalColor[] positionNormalColorArray7 = vertices;
                    int index9 = num15;
                    int num16  = 1;
                    int num17  = index9 + num16;
                    positionNormalColorArray7[index9] = new VertexPositionNormalColor(new Vector3(-x, y1, z2) + vector3, new Vector3(0.0f, 0.0f, -1f), color);
                    VertexPositionNormalColor[] positionNormalColorArray8 = vertices;
                    int index10 = num17;
                    int num18   = 1;
                    int num19   = index10 + num18;
                    positionNormalColorArray8[index10] = new VertexPositionNormalColor(new Vector3(-x, -y1, -z2) + vector3, new Vector3(0.0f, 0.0f, -1f), color);
                    VertexPositionNormalColor[] positionNormalColorArray9 = vertices;
                    int index11 = num19;
                    int num20   = 1;
                    int num21   = index11 + num20;
                    positionNormalColorArray9[index11] = new VertexPositionNormalColor(new Vector3(0.0f, y2, -z2) + vector3, new Vector3(0.0f, 1f, 0.0f), color);
                    VertexPositionNormalColor[] positionNormalColorArray10 = vertices;
                    int index12 = num21;
                    int num22   = 1;
                    int num23   = index12 + num22;
                    positionNormalColorArray10[index12] = new VertexPositionNormalColor(new Vector3(-x, y1, z2) + vector3, new Vector3(0.0f, 1f, 0.0f), color);
                    VertexPositionNormalColor[] positionNormalColorArray11 = vertices;
                    int index13 = num23;
                    int num24   = 1;
                    int num25   = index13 + num24;
                    positionNormalColorArray11[index13] = new VertexPositionNormalColor(new Vector3(0.0f, 0.0f, z1) + vector3, new Vector3(0.0f, 1f, 0.0f), color);
                    VertexPositionNormalColor[] positionNormalColorArray12 = vertices;
                    int index14 = num25;
                    int num26   = 1;
                    num1 = index14 + num26;
                    positionNormalColorArray12[index14] = new VertexPositionNormalColor(new Vector3(x, y1, z2) + vector3, new Vector3(0.0f, 1f, 0.0f), color);
                    int[] numArray1 = indices;
                    int   index15   = num2;
                    int   num27     = 1;
                    int   num28     = index15 + num27;
                    int   num29     = num3;
                    numArray1[index15] = num29;
                    int[] numArray2 = indices;
                    int   index16   = num28;
                    int   num30     = 1;
                    int   num31     = index16 + num30;
                    int   num32     = 2 + num3;
                    numArray2[index16] = num32;
                    int[] numArray3 = indices;
                    int   index17   = num31;
                    int   num33     = 1;
                    int   num34     = index17 + num33;
                    int   num35     = 1 + num3;
                    numArray3[index17] = num35;
                    int[] numArray4 = indices;
                    int   index18   = num34;
                    int   num36     = 1;
                    int   num37     = index18 + num36;
                    int   num38     = num3;
                    numArray4[index18] = num38;
                    int[] numArray5 = indices;
                    int   index19   = num37;
                    int   num39     = 1;
                    int   num40     = index19 + num39;
                    int   num41     = 3 + num3;
                    numArray5[index19] = num41;
                    int[] numArray6 = indices;
                    int   index20   = num40;
                    int   num42     = 1;
                    int   num43     = index20 + num42;
                    int   num44     = 2 + num3;
                    numArray6[index20] = num44;
                    int[] numArray7 = indices;
                    int   index21   = num43;
                    int   num45     = 1;
                    int   num46     = index21 + num45;
                    int   num47     = 4 + num3;
                    numArray7[index21] = num47;
                    int[] numArray8 = indices;
                    int   index22   = num46;
                    int   num48     = 1;
                    int   num49     = index22 + num48;
                    int   num50     = 6 + num3;
                    numArray8[index22] = num50;
                    int[] numArray9 = indices;
                    int   index23   = num49;
                    int   num51     = 1;
                    int   num52     = index23 + num51;
                    int   num53     = 5 + num3;
                    numArray9[index23] = num53;
                    int[] numArray10 = indices;
                    int   index24    = num52;
                    int   num54      = 1;
                    int   num55      = index24 + num54;
                    int   num56      = 4 + num3;
                    numArray10[index24] = num56;
                    int[] numArray11 = indices;
                    int   index25    = num55;
                    int   num57      = 1;
                    int   num58      = index25 + num57;
                    int   num59      = 7 + num3;
                    numArray11[index25] = num59;
                    int[] numArray12 = indices;
                    int   index26    = num58;
                    int   num60      = 1;
                    int   num61      = index26 + num60;
                    int   num62      = 6 + num3;
                    numArray12[index26] = num62;
                    int[] numArray13 = indices;
                    int   index27    = num61;
                    int   num63      = 1;
                    int   num64      = index27 + num63;
                    int   num65      = 8 + num3;
                    numArray13[index27] = num65;
                    int[] numArray14 = indices;
                    int   index28    = num64;
                    int   num66      = 1;
                    int   num67      = index28 + num66;
                    int   num68      = 10 + num3;
                    numArray14[index28] = num68;
                    int[] numArray15 = indices;
                    int   index29    = num67;
                    int   num69      = 1;
                    int   num70      = index29 + num69;
                    int   num71      = 9 + num3;
                    numArray15[index29] = num71;
                    int[] numArray16 = indices;
                    int   index30    = num70;
                    int   num72      = 1;
                    int   num73      = index30 + num72;
                    int   num74      = 8 + num3;
                    numArray16[index30] = num74;
                    int[] numArray17 = indices;
                    int   index31    = num73;
                    int   num75      = 1;
                    int   num76      = index31 + num75;
                    int   num77      = 11 + num3;
                    numArray17[index31] = num77;
                    int[] numArray18 = indices;
                    int   index32    = num76;
                    int   num78      = 1;
                    num2 = index32 + num78;
                    int num79 = 10 + num3;
                    numArray18[index32] = num79;
                }
            }
            this.CubesMesh = new Mesh()
            {
                Effect      = (BaseEffect)(this.CubesEffect = (DefaultEffect) new DefaultEffect.LitVertexColored()),
                DepthWrites = false,
                AlwaysOnTop = true
            };
            Group group = this.CubesMesh.AddGroup();
            BufferedIndexedPrimitives <VertexPositionNormalColor> indexedPrimitives = new BufferedIndexedPrimitives <VertexPositionNormalColor>(vertices, indices, PrimitiveType.TriangleList);

            indexedPrimitives.UpdateBuffers();
            indexedPrimitives.CleanUp();
            group.Geometry  = (IIndexedPrimitiveCollection)indexedPrimitives;
            this.PointsMesh = new Mesh()
            {
                Effect      = (BaseEffect) new PointsFromLinesEffect(),
                DepthWrites = false,
                AlwaysOnTop = true
            };
            Color[]   colorArray   = new Color[32640];
            Vector3[] vector3Array = new Vector3[32640];
            int       index33      = 0;

            for (int index1 = -68; index1 < 68; ++index1)
            {
                for (int index2 = -120; index2 < 120; ++index2)
                {
                    vector3Array[index33] = new Vector3((float)index2 / 8f, (float)((double)index1 / 8.0 + (Math.Abs(index2) % 2 == 0 ? 0.0 : 1.0 / 16.0)), 0.0f);
                    colorArray[index33++] = RandomHelper.InList <Color>(MulticoloredSpace.Colors);
                }
            }
            this.PointsMesh.AddPoints((IList <Color>)colorArray, (IEnumerable <Vector3>)vector3Array, true);
        }
Example #14
0
 public override void Initialize()
 {
   base.Initialize();
   this.sBlueZoomOut = this.CMProvider.Get(CM.EndCutscene).Load<SoundEffect>("Sounds/Ending/Cutscene64/BlueZoomOut");
   this.sProgressiveAppear = this.CMProvider.Get(CM.EndCutscene).Load<SoundEffect>("Sounds/Ending/Cutscene64/CubesProgressiveAppear");
   this.sFadeOut = this.CMProvider.Get(CM.EndCutscene).Load<SoundEffect>("Sounds/Ending/Cutscene64/CubesFadeOut");
   this.LevelManager.ActualAmbient = new Color(0.25f, 0.25f, 0.25f);
   this.LevelManager.ActualDiffuse = Color.White;
   Random random = RandomHelper.Random;
   float y1 = 1f / (float) Math.Sqrt(6.0);
   float z1 = (float) Math.Sqrt(3.0) / 2f;
   float y2 = (float) Math.Sqrt(2.0 / 3.0);
   float z2 = (float) (1.0 / (2.0 * Math.Sqrt(3.0)));
   float x = 1f / (float) Math.Sqrt(2.0);
   VertexPositionNormalColor[] vertices = new VertexPositionNormalColor[864000];
   int[] indices = new int[1296000];
   int num1 = 0;
   int num2 = 0;
   for (int index1 = -100; index1 < 100; ++index1)
   {
     for (int index2 = -180; index2 < 180; ++index2)
     {
       Color color = index2 != 0 || index1 != 0 ? MulticoloredSpace.Colors[random.Next(0, MulticoloredSpace.Colors.Length)] : MulticoloredSpace.MainCubeColor;
       Vector3 vector3 = new Vector3((float) (index2 * 6), (float) (index1 * 6 + (Math.Abs(index2) % 2 == 0 ? 0 : 3)), 0.0f);
       int num3 = num1;
       VertexPositionNormalColor[] positionNormalColorArray1 = vertices;
       int index3 = num1;
       int num4 = 1;
       int num5 = index3 + num4;
       positionNormalColorArray1[index3] = new VertexPositionNormalColor(new Vector3(x, -y1, -z2) + vector3, new Vector3(-1f, 0.0f, 0.0f), color);
       VertexPositionNormalColor[] positionNormalColorArray2 = vertices;
       int index4 = num5;
       int num6 = 1;
       int num7 = index4 + num6;
       positionNormalColorArray2[index4] = new VertexPositionNormalColor(new Vector3(x, y1, z2) + vector3, new Vector3(-1f, 0.0f, 0.0f), color);
       VertexPositionNormalColor[] positionNormalColorArray3 = vertices;
       int index5 = num7;
       int num8 = 1;
       int num9 = index5 + num8;
       positionNormalColorArray3[index5] = new VertexPositionNormalColor(new Vector3(0.0f, 0.0f, z1) + vector3, new Vector3(-1f, 0.0f, 0.0f), color);
       VertexPositionNormalColor[] positionNormalColorArray4 = vertices;
       int index6 = num9;
       int num10 = 1;
       int num11 = index6 + num10;
       positionNormalColorArray4[index6] = new VertexPositionNormalColor(new Vector3(0.0f, -y2, z2) + vector3, new Vector3(-1f, 0.0f, 0.0f), color);
       VertexPositionNormalColor[] positionNormalColorArray5 = vertices;
       int index7 = num11;
       int num12 = 1;
       int num13 = index7 + num12;
       positionNormalColorArray5[index7] = new VertexPositionNormalColor(new Vector3(0.0f, -y2, z2) + vector3, new Vector3(0.0f, 0.0f, -1f), color);
       VertexPositionNormalColor[] positionNormalColorArray6 = vertices;
       int index8 = num13;
       int num14 = 1;
       int num15 = index8 + num14;
       positionNormalColorArray6[index8] = new VertexPositionNormalColor(new Vector3(0.0f, 0.0f, z1) + vector3, new Vector3(0.0f, 0.0f, -1f), color);
       VertexPositionNormalColor[] positionNormalColorArray7 = vertices;
       int index9 = num15;
       int num16 = 1;
       int num17 = index9 + num16;
       positionNormalColorArray7[index9] = new VertexPositionNormalColor(new Vector3(-x, y1, z2) + vector3, new Vector3(0.0f, 0.0f, -1f), color);
       VertexPositionNormalColor[] positionNormalColorArray8 = vertices;
       int index10 = num17;
       int num18 = 1;
       int num19 = index10 + num18;
       positionNormalColorArray8[index10] = new VertexPositionNormalColor(new Vector3(-x, -y1, -z2) + vector3, new Vector3(0.0f, 0.0f, -1f), color);
       VertexPositionNormalColor[] positionNormalColorArray9 = vertices;
       int index11 = num19;
       int num20 = 1;
       int num21 = index11 + num20;
       positionNormalColorArray9[index11] = new VertexPositionNormalColor(new Vector3(0.0f, y2, -z2) + vector3, new Vector3(0.0f, 1f, 0.0f), color);
       VertexPositionNormalColor[] positionNormalColorArray10 = vertices;
       int index12 = num21;
       int num22 = 1;
       int num23 = index12 + num22;
       positionNormalColorArray10[index12] = new VertexPositionNormalColor(new Vector3(-x, y1, z2) + vector3, new Vector3(0.0f, 1f, 0.0f), color);
       VertexPositionNormalColor[] positionNormalColorArray11 = vertices;
       int index13 = num23;
       int num24 = 1;
       int num25 = index13 + num24;
       positionNormalColorArray11[index13] = new VertexPositionNormalColor(new Vector3(0.0f, 0.0f, z1) + vector3, new Vector3(0.0f, 1f, 0.0f), color);
       VertexPositionNormalColor[] positionNormalColorArray12 = vertices;
       int index14 = num25;
       int num26 = 1;
       num1 = index14 + num26;
       positionNormalColorArray12[index14] = new VertexPositionNormalColor(new Vector3(x, y1, z2) + vector3, new Vector3(0.0f, 1f, 0.0f), color);
       int[] numArray1 = indices;
       int index15 = num2;
       int num27 = 1;
       int num28 = index15 + num27;
       int num29 = num3;
       numArray1[index15] = num29;
       int[] numArray2 = indices;
       int index16 = num28;
       int num30 = 1;
       int num31 = index16 + num30;
       int num32 = 2 + num3;
       numArray2[index16] = num32;
       int[] numArray3 = indices;
       int index17 = num31;
       int num33 = 1;
       int num34 = index17 + num33;
       int num35 = 1 + num3;
       numArray3[index17] = num35;
       int[] numArray4 = indices;
       int index18 = num34;
       int num36 = 1;
       int num37 = index18 + num36;
       int num38 = num3;
       numArray4[index18] = num38;
       int[] numArray5 = indices;
       int index19 = num37;
       int num39 = 1;
       int num40 = index19 + num39;
       int num41 = 3 + num3;
       numArray5[index19] = num41;
       int[] numArray6 = indices;
       int index20 = num40;
       int num42 = 1;
       int num43 = index20 + num42;
       int num44 = 2 + num3;
       numArray6[index20] = num44;
       int[] numArray7 = indices;
       int index21 = num43;
       int num45 = 1;
       int num46 = index21 + num45;
       int num47 = 4 + num3;
       numArray7[index21] = num47;
       int[] numArray8 = indices;
       int index22 = num46;
       int num48 = 1;
       int num49 = index22 + num48;
       int num50 = 6 + num3;
       numArray8[index22] = num50;
       int[] numArray9 = indices;
       int index23 = num49;
       int num51 = 1;
       int num52 = index23 + num51;
       int num53 = 5 + num3;
       numArray9[index23] = num53;
       int[] numArray10 = indices;
       int index24 = num52;
       int num54 = 1;
       int num55 = index24 + num54;
       int num56 = 4 + num3;
       numArray10[index24] = num56;
       int[] numArray11 = indices;
       int index25 = num55;
       int num57 = 1;
       int num58 = index25 + num57;
       int num59 = 7 + num3;
       numArray11[index25] = num59;
       int[] numArray12 = indices;
       int index26 = num58;
       int num60 = 1;
       int num61 = index26 + num60;
       int num62 = 6 + num3;
       numArray12[index26] = num62;
       int[] numArray13 = indices;
       int index27 = num61;
       int num63 = 1;
       int num64 = index27 + num63;
       int num65 = 8 + num3;
       numArray13[index27] = num65;
       int[] numArray14 = indices;
       int index28 = num64;
       int num66 = 1;
       int num67 = index28 + num66;
       int num68 = 10 + num3;
       numArray14[index28] = num68;
       int[] numArray15 = indices;
       int index29 = num67;
       int num69 = 1;
       int num70 = index29 + num69;
       int num71 = 9 + num3;
       numArray15[index29] = num71;
       int[] numArray16 = indices;
       int index30 = num70;
       int num72 = 1;
       int num73 = index30 + num72;
       int num74 = 8 + num3;
       numArray16[index30] = num74;
       int[] numArray17 = indices;
       int index31 = num73;
       int num75 = 1;
       int num76 = index31 + num75;
       int num77 = 11 + num3;
       numArray17[index31] = num77;
       int[] numArray18 = indices;
       int index32 = num76;
       int num78 = 1;
       num2 = index32 + num78;
       int num79 = 10 + num3;
       numArray18[index32] = num79;
     }
   }
   this.CubesMesh = new Mesh()
   {
     Effect = (BaseEffect) (this.CubesEffect = (DefaultEffect) new DefaultEffect.LitVertexColored()),
     DepthWrites = false,
     AlwaysOnTop = true
   };
   Group group = this.CubesMesh.AddGroup();
   BufferedIndexedPrimitives<VertexPositionNormalColor> indexedPrimitives = new BufferedIndexedPrimitives<VertexPositionNormalColor>(vertices, indices, PrimitiveType.TriangleList);
   indexedPrimitives.UpdateBuffers();
   indexedPrimitives.CleanUp();
   group.Geometry = (IIndexedPrimitiveCollection) indexedPrimitives;
   this.PointsMesh = new Mesh()
   {
     Effect = (BaseEffect) new PointsFromLinesEffect(),
     DepthWrites = false,
     AlwaysOnTop = true
   };
   Color[] colorArray = new Color[32640];
   Vector3[] vector3Array = new Vector3[32640];
   int index33 = 0;
   for (int index1 = -68; index1 < 68; ++index1)
   {
     for (int index2 = -120; index2 < 120; ++index2)
     {
       vector3Array[index33] = new Vector3((float) index2 / 8f, (float) ((double) index1 / 8.0 + (Math.Abs(index2) % 2 == 0 ? 0.0 : 1.0 / 16.0)), 0.0f);
       colorArray[index33++] = RandomHelper.InList<Color>(MulticoloredSpace.Colors);
     }
   }
   this.PointsMesh.AddPoints((IList<Color>) colorArray, (IEnumerable<Vector3>) vector3Array, true);
 }
Example #15
0
        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (this.Manager.KeyPressed(Keys.M))
            {
                switch (fDrawMode)
                {
                case DrawMode.Grid:
                    CurrentDrawMode = DrawMode.Solid;
                    break;

                case DrawMode.Solid:
                    CurrentDrawMode = DrawMode.WireFrame;
                    break;

                case DrawMode.WireFrame:
                    CurrentDrawMode = DrawMode.Grid;
                    break;
                }
            }
            else if (this.Manager.KeyPressed(Keys.C))
            {
                switch (fColorMode)
                {
                case ColorMode.Points:
                    CurrentColorMode = ColorMode.SkyBlue;
                    break;

                case ColorMode.SkyBlue:
                    CurrentColorMode = ColorMode.Points;
                    break;
                }
            }
            else if (this.Manager.KeyPressed(Keys.N))
            {
                switch (fNormalMode)
                {
                case NormalMode.Crazy:
                    CurrentNormalMode = NormalMode.Standard;
                    break;

                case NormalMode.Standard:
                    CurrentNormalMode = NormalMode.Crazy;
                    break;
                }
            }

            fCamera.Update(gameTime);

            double seconds = gameTime.TotalGameTime.TotalSeconds;

            if (!fHalted)
            {
                fUpdateDiagram = true;
            }

            fUpdateDiagram = fUpdateDiagram || fUpdatePlane;
            fUpdateColors  = fUpdateColors || fUpdateDiagram;
            fUpdateNormals = fUpdateNormals || fUpdateDiagram;

            if (fUpdatePlane)
            {
                SetPlane();
            }
            int max = fPlane.Segments;

            if (fUpdateDiagram)
            {
                fUpdateDiagram = false;
                for (int x = 0; x <= max; x++)
                {
                    float nX = 2.0f * (float)x / max - 1.0f;// -1 to +1
                    for (int z = 0; z <= max; z++)
                    {
                        float  nZ = 2.0f * (float)z / max - 1.0f;
                        double r  = Math.Sqrt(nX * nX + nZ * nZ);
                        // function
                        double y = nX * Math.Cos(r * 7.0f - seconds * 4.2f) +
                                   nZ * Math.Sin((r - 0.5) * 10.0f - seconds * 1.9f);

                        float height = 200.0f * (float)y;
                        fPlane.SetHeight(x, z, height);
                    }
                }
            }
            if (fUpdateColors)
            {
                SetColors();
            }
            if (fUpdateNormals)
            {
                switch (fNormalMode)
                {
                case NormalMode.Crazy:
                    for (int x = 0; x <= max; x++)
                    {
                        float nX = 2.0f * (float)x / max - 1.0f;    // -1 to +1
                        for (int z = 0; z <= max; z++)
                        {
                            float nZ = 2.0f * (float)z / max - 1.0f;
                            // function
                            double r = Math.Sqrt(nX * nX + nZ * nZ);
                            VertexPositionNormalColor p = fPlane.GetPoint(x, z);
                            p.Normal = Vector3.Normalize(new Vector3(
                                                             Convert.ToSingle(Math.Cos(r * 1.0f + 0.5f - seconds * 0.1f)),
                                                             Convert.ToSingle(Math.Cos(r * 2.0f + 2.1f - seconds * 0.2f)),
                                                             Convert.ToSingle(Math.Cos(r * 5.1f * seconds))));
                            fPlane.SetPoint(x, z, p);
                        }
                    }
                    break;

                case NormalMode.Standard:
                    fPlane.GenerateNormals();
                    break;
                }
            }

            base.Update(gameTime);
        }
Example #16
0
        public Landscape(Project2Game game)
        {
            r = new Random(seed);

            // generate the height map
            heightMap = DiamondSquareGrid(gridSize, seed, minHeight, maxHeight, roughness / 10.0f);

            // the number of vertices we will need
            int vertexCount = (gridSize - 1) * (gridSize - 1) * 6 + 12; // 12 for water

            // initialise the mesh
            VertexPositionNormalColor[] mesh = new VertexPositionNormalColor[vertexCount];

            // calculate the average height in Y off which to base colour.
            float sum = 0;
            for (int x = 0; x < gridSize - 1; x++)
            {
                for (int z = 0; z < gridSize - 1; z++)
                {
                    float y = heightMap[x][z];
                    sum += y;
                    if (y > biggestY)
                    {
                        biggestY = y;
                    }
                    else if (y < smallestY)
                    {
                        smallestY = y;
                    }
                }
            }
            averageHeight = sum / ((gridSize - 1)* (gridSize - 1));
            rangeY = biggestY - smallestY;
            waterHeight = smallestY + (rangeY / 2) - rangeY * 0.1f;

            // adjust camera to be above land and water (STATIC IN CAMERA CLASS NOW)
            // float heightAtCamera = heightAtPoint(cameraPosition.X, cameraPosition.Y);
            // cameraPosition.Y += ((waterHeight >= heightAtCamera) ? waterHeight : heightAtCamera);

            // generate vertices for the triangles based on the height map
            int counter = 0;
            for (int x=0; x<gridSize-1; x++)
            {
                for (int z=0; z<gridSize-1; z++)
                {
                    // pos Z
                    // tl - - tr
                    //  | \   |
                    //  |   \ |
                    // bl - - br  pos X

                    float botLeft = heightMap[x][z];
                    float topLeft = heightMap[x][z + 1];
                    float botRight = heightMap[x + 1][z];
                    float topRight = heightMap[x + 1][z + 1];

                    // Triangle A
                    Vector3 a1 = new Vector3(x * scale, botLeft * scale, z * scale);
                    Vector3 a2 = new Vector3(x * scale, topLeft * scale, z * scale + scale);
                    Vector3 a3 = new Vector3(x * scale + scale, botRight * scale, z * scale);
                    Vector3 aNormal = -Vector3.Cross(a1 - a2, a3  - a1);

                    mesh[counter++] = new VertexPositionNormalColor(a1, aNormal, getColor(a1.Y));
                    mesh[counter++] = new VertexPositionNormalColor(a2, aNormal, getColor(a2.Y));
                    mesh[counter++] = new VertexPositionNormalColor(a3, aNormal, getColor(a3.Y));

                    // Triangle B
                    Vector3 b1 = new Vector3(x * scale, topLeft * scale, z * scale + scale);
                    Vector3 b2 = new Vector3(x * scale + scale, topRight * scale, z * scale + scale);
                    Vector3 b3 = new Vector3(x * scale + scale, botRight * scale, z * scale);
                    Vector3 bNormal = -Vector3.Cross(b1 - b2, b3 - b1);

                    mesh[counter++] = new VertexPositionNormalColor(b1, bNormal, getColor(b1.Y));
                    mesh[counter++] = new VertexPositionNormalColor(b2, bNormal, getColor(b2.Y));
                    mesh[counter++] = new VertexPositionNormalColor(b3, bNormal, getColor(b3.Y));
                }
            }

            // WATER !
            // Top Triangle A
            Vector3 wt11 = new Vector3(0.0f, waterHeight * scale, 0.0f);
            Vector3 wt12 = new Vector3(0.0f, waterHeight * scale, (gridSize - 1) * scale);
            Vector3 wt13 = new Vector3((gridSize - 1) * scale, waterHeight * scale, 0.0f);

            mesh[counter++] = new VertexPositionNormalColor(wt11, Vector3.UnitY, waterColor);
            mesh[counter++] = new VertexPositionNormalColor(wt12, Vector3.UnitY, waterColor);
            mesh[counter++] = new VertexPositionNormalColor(wt13, Vector3.UnitY, waterColor);

            // Top Triangle B
            Vector3 wt21 = new Vector3(0.0f, waterHeight * scale, (gridSize - 1) * scale);
            Vector3 wt22 = new Vector3((gridSize - 1) * scale, waterHeight * scale, (gridSize - 1) * scale);
            Vector3 wt23 = new Vector3((gridSize - 1) * scale, waterHeight * scale, 0.0f);

            mesh[counter++] = new VertexPositionNormalColor(wt21, Vector3.UnitY, waterColor);
            mesh[counter++] = new VertexPositionNormalColor(wt22, Vector3.UnitY, waterColor);
            mesh[counter++] = new VertexPositionNormalColor(wt23, Vector3.UnitY, waterColor);

            // Bottom (reverse triangle definitions)
            mesh[counter++] = new VertexPositionNormalColor(wt11, Vector3.UnitY, waterColor);
            mesh[counter++] = new VertexPositionNormalColor(wt13, Vector3.UnitY, waterColor);
            mesh[counter++] = new VertexPositionNormalColor(wt12, Vector3.UnitY, waterColor);

            mesh[counter++] = new VertexPositionNormalColor(wt21, Vector3.UnitY, waterColor);
            mesh[counter++] = new VertexPositionNormalColor(wt23, Vector3.UnitY, waterColor);
            mesh[counter++] = new VertexPositionNormalColor(wt22, Vector3.UnitY, waterColor);

            // Create vertex buffer
            vertices = Buffer.Vertex.New(game.GraphicsDevice, mesh);
            this.effect = game.Content.Load<Effect>("Phong");

            // Setup parameters

            this.World = Matrix.Identity;
            this.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(this.World));

            basicEffect = new BasicEffect(game.GraphicsDevice)
            {
                VertexColorEnabled = true,
                View = Matrix.LookAtLH(new Vector3(0, 0, 0), new Vector3(0, 0, 0), Vector3.UnitY),
                Projection = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, (float)game.GraphicsDevice.BackBuffer.Width / game.GraphicsDevice.BackBuffer.Height, 0.1f, 100.0f),
                World = Matrix.Identity
            };

            // Lighting
            basicEffect.LightingEnabled = true;
            basicEffect.AmbientLightColor = new Vector3(0.15f, 0.15f, 0.15f);
            basicEffect.DirectionalLight0.DiffuseColor = new Vector3(0.4f, 0.4f, 0.4f);
            basicEffect.DirectionalLight0.SpecularColor = new Vector3(0.8f, 0.8f, 0.8f);

            inputLayout = VertexInputLayout.FromBuffer(0, vertices);
            this.game = game;
        }
        public Landscape(Project1Game game, float c1, float c2, float c3, float c4, int recDepth)
        {
            // setting up the random number generator
            this.rand = new Random();

            // recDepth of 0 would make a flat plane with only the 4 corner vertices
            // Determine the size of the array depending of the recursion depth
            this.arraySize = this.compArraySize(recDepth);
            this.recDepth = recDepth;

            // Creating array structure in order to store height values for all vertices
            // format will be heightMap[x][y] = z
            heightMap = new float[arraySize][];

            for (int i = 0; i < arraySize; i++){

                heightMap[i] = new float[arraySize];

            }

            // corner pattern:
            //   C1-----C2
            //   |		|
            //   C3-----C4

            // set the four corner values
            heightMap[0][0]                         = c1;
            heightMap[arraySize - 1][0]             = c2;
            heightMap[0][arraySize - 1]             = c3;
            heightMap[arraySize - 1][arraySize - 1] = c4;

            // Generate the rest of the height values
            diamondsquare();

            // Calculate vertex colour heights
            calcColourZones();

            vertexArray = new VertexPositionNormalColor[(arraySize - 1) * (6 + (arraySize - 2) * 6) + 6];

            vertexCount = 0;
            // Add the vertices to the array to make polygons
            for (int y = 0; y <= arraySize - 2; y++)
            {
                for (int x = 0; x <= arraySize - 1; x++)
                {

                    if (x == 0)
                    {

                        addPolygon(
                                   new Vector3(x * positionScale, heightMap[x][y], y * positionScale),
                                   new Vector3(x * positionScale, heightMap[x][y + 1], (y + 1) * positionScale),
                                   new Vector3((x + 1) * positionScale, heightMap[x + 1][y], y * positionScale)
                                   );

                    }
                    else if (x == arraySize - 1)
                    {

                        addPolygon(
                                   new Vector3(x * positionScale, heightMap[x][y], y * positionScale),
                                   new Vector3((x - 1) * positionScale, heightMap[x - 1][y + 1], (y + 1) * positionScale),
                                   new Vector3(x * positionScale, heightMap[x][y + 1], (y + 1) * positionScale)
                                   );

                    }
                    else
                    {
                        addPolygon(
                                   new Vector3(x * positionScale, heightMap[x][y], y * positionScale),
                                   new Vector3(x * positionScale, heightMap[x][y + 1], (y + 1) * positionScale),
                                   new Vector3((x + 1) * positionScale, heightMap[x + 1][y], y * positionScale)
                            );

                        addPolygon(
                                   new Vector3(x * positionScale, heightMap[x][y], y * positionScale),
                                   new Vector3((x - 1) * positionScale, heightMap[x - 1][y + 1], (y + 1) * positionScale),
                                   new Vector3(x * positionScale, heightMap[x][y + 1], (y + 1) * positionScale)
                            );

                    }
                }
            }

            // these vertices are for the water
            // TODO add water vertices
            Color water = new Color(new Vector4(0, 0, 255, 0.5f));
            vertexArray[vertexCount++] = new VertexPositionNormalColor(new Vector3(0, this.water, 0), Vector3.UnitY, water);
            vertexArray[vertexCount++] = new VertexPositionNormalColor(new Vector3(0, this.water, arraySize * positionScale), Vector3.UnitY, water);
            vertexArray[vertexCount++] = new VertexPositionNormalColor(new Vector3(arraySize * positionScale, this.water, arraySize * positionScale), Vector3.UnitY, water);
            vertexArray[vertexCount++] = new VertexPositionNormalColor(new Vector3(0, this.water, 0), Vector3.UnitY, water);
            vertexArray[vertexCount++] = new VertexPositionNormalColor(new Vector3(arraySize * positionScale, this.water, arraySize * positionScale), Vector3.UnitY, water);
            vertexArray[vertexCount++] = new VertexPositionNormalColor(new Vector3(arraySize * positionScale, this.water, 0), Vector3.UnitY, water);

            vertices = Buffer.Vertex.New(

                    game.GraphicsDevice,
                    vertexArray
                    );

            basicEffect = new BasicEffect(game.GraphicsDevice)
            {
                VertexColorEnabled = true,
                Projection = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, (float)game.GraphicsDevice.BackBuffer.Width / game.GraphicsDevice.BackBuffer.Height, 0.1f, 10000.0f),
                World = Matrix.Identity,
                LightingEnabled = true

            };

            basicEffect.DirectionalLight0.Enabled = true;
            basicEffect.DirectionalLight0.Direction = new Vector3((float)Math.Cos(0),
                                                                  (float)Math.Sin(0),
                                                                  (float)Math.Cos(0));
            basicEffect.DirectionalLight0.DiffuseColor = new Vector3(0.3f, 0.3f, 0.3f);
            basicEffect.AmbientLightColor = new Vector3(0.1f, 0.1f, 0.1f);
            basicEffect.EmissiveColor = new Vector3(0.5f, 0.5f, 0.5f);

            basicEffect.SpecularColor = new Vector3(0.3f, 0.5f, 0.5f);
            basicEffect.SpecularPower = 1f;

            inputLayout = VertexInputLayout.FromBuffer(0, vertices);
            this.game = game;
        }
Example #18
0
 void ConvertPartsToPrimitive(Color DefaultColor)
 {
     //Convert Vertex to VertexPositionNormalColor, with no Normal
     AsteroidVertices = new VertexPositionNormalColor[Vertices.Count];
     for (int i = 0; i < Vertices.Count; i++)
     {
         AsteroidVertices[i] = new VertexPositionNormalColor(Vertices[i].Position, Vector3.Zero, DefaultColor);
     }
     //Convert Triangles into Indices
     AsteroidIndices = new int[Triangles.Count * 3];
     for (int i = 0; i < Triangles.Count; i++)
     {
         AsteroidIndices[i * 3] = Triangles[i].Vertices[0].Index;
         AsteroidIndices[i * 3 + 1] = Triangles[i].Vertices[1].Index;
         AsteroidIndices[i * 3 + 2] = Triangles[i].Vertices[2].Index;
     }
     //Determine Normals by summing the Normals of all Triangles
     for (int i = 0; i < Triangles.Count; i++)
     {
         AsteroidVertices[Triangles[i].Vertices[0].Index].Normal += Triangles[i].Normal;
         AsteroidVertices[Triangles[i].Vertices[1].Index].Normal += Triangles[i].Normal;
         AsteroidVertices[Triangles[i].Vertices[2].Index].Normal += Triangles[i].Normal;
     }
     //Then normalize the Normals again
     for (int i = 0; i < AsteroidVertices.Length; i++)
     {
         AsteroidVertices[i].Normal.Normalize();
     }
 }
 public virtual void Initialize(VertexPositionNormalColor[] vertices, short[] indices)
 {
     InitializeWasCalled = true;
     Vertices = vertices;
 }
Example #20
0
 public VertexPositionNormalColor[] GetMazeWayOutVertexWithCube(List<Node>path, float scale,Color color)
 {
     //VertexPositionNormalColor[] sampleCube = GenerateScaledPolygon(GetUnitCube(), scale);
     VertexPositionNormalColor[] sampleRoad = GenerateScaledPolygon(GetUnitCubeFloor(Color.Green), scale);
     //int cubeNumVertex = sampleCube.Length;
     VertexPositionNormalColor[] mazeCubes = new VertexPositionNormalColor[path.Count*sampleRoad.Count()];
     VertexPositionNormalColor[] tempRoad;
     int countIndex = 0;
     foreach (var position in path)
     {
                 tempRoad = GenerateScaledPolygon(GetUnitCubeFloor(color), scale);
                 tempRoad = TranslatePolygonInXY(tempRoad, new Vector3((float)scale * 2 * position.x, 0.0f, (float)scale * 2 * position.y));
                 for (int i = 0; i < tempRoad.Length; i++)
                 {
                     mazeCubes[countIndex++] = tempRoad[i];
                 }
     }
     return mazeCubes;
 }
Example #21
0
        public MyModel CreateTexturedCube(String texturePath, Vector3 size)
        {
            Vector3 frontNorm = new Vector3(0, 0, -1);
            Vector3 backNorm = -frontNorm;
            Vector3 leftNorm = new Vector3(-1, 0, 0);
            Vector3 rightNorm = -leftNorm;
            Vector3 topNorm = new Vector3(0, 1, 0);
            Vector3 bottomNorm = -topNorm;
            VertexPositionNormalColor[] shapeArray = new VertexPositionNormalColor[]{
            new VertexPositionNormalColor(new Vector3(-1.0f, -1.0f, -1.0f), frontNorm, Color.Yellow), // Front
            new VertexPositionNormalColor(new Vector3(-1.0f, 1.0f, -1.0f), frontNorm, Color.Yellow),
            new VertexPositionNormalColor(new Vector3(1.0f, 1.0f, -1.0f), frontNorm, Color.Yellow),
            new VertexPositionNormalColor(new Vector3(-1.0f, -1.0f, -1.0f), frontNorm, Color.Yellow),
            new VertexPositionNormalColor(new Vector3(1.0f, 1.0f, -1.0f), frontNorm, Color.Yellow),
            new VertexPositionNormalColor(new Vector3(1.0f, -1.0f, -1.0f), frontNorm, Color.Yellow),

            new VertexPositionNormalColor(new Vector3(-1.0f, -1.0f, 1.0f), backNorm, Color.Red), // BACK
            new VertexPositionNormalColor(new Vector3(1.0f, 1.0f, 1.0f), backNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(-1.0f, 1.0f, 1.0f), backNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(-1.0f, -1.0f, 1.0f), backNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(1.0f, -1.0f, 1.0f), backNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(1.0f, 1.0f, 1.0f), backNorm, Color.Red),

            new VertexPositionNormalColor(new Vector3(-1.0f, 1.0f, -1.0f), topNorm, Color.Red), // Top
            new VertexPositionNormalColor(new Vector3(-1.0f, 1.0f, 1.0f), topNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(1.0f, 1.0f, 1.0f), topNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(-1.0f, 1.0f, -1.0f), topNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(1.0f, 1.0f, 1.0f), topNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(1.0f, 1.0f, -1.0f), topNorm, Color.Red),

            new VertexPositionNormalColor(new Vector3(-1.0f, -1.0f, -1.0f), bottomNorm, Color.Red), // Bottom
            new VertexPositionNormalColor(new Vector3(1.0f, -1.0f, 1.0f), bottomNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(-1.0f, -1.0f, 1.0f), bottomNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(-1.0f, -1.0f, -1.0f), bottomNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(1.0f, -1.0f, -1.0f), bottomNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(1.0f, -1.0f, 1.0f), bottomNorm, Color.Red),

            new VertexPositionNormalColor(new Vector3(-1.0f, -1.0f, -1.0f), leftNorm, Color.Red), // Left
            new VertexPositionNormalColor(new Vector3(-1.0f, -1.0f, 1.0f), leftNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(-1.0f, 1.0f, 1.0f), leftNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(-1.0f, -1.0f, -1.0f), leftNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(-1.0f, 1.0f, 1.0f), leftNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(-1.0f, 1.0f, -1.0f), leftNorm, Color.Red),

            new VertexPositionNormalColor(new Vector3(1.0f, -1.0f, -1.0f), rightNorm, Color.Red), // Right
            new VertexPositionNormalColor(new Vector3(1.0f, 1.0f, 1.0f), rightNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(1.0f, -1.0f, 1.0f), rightNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(1.0f, -1.0f, -1.0f), rightNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(1.0f, 1.0f, -1.0f), rightNorm, Color.Red),
            new VertexPositionNormalColor(new Vector3(1.0f, 1.0f, 1.0f), rightNorm, Color.Red),
            };

            for (int i = 0; i < shapeArray.Length; i++)
            {
                shapeArray[i].Position.X *= size.X / 2;
                shapeArray[i].Position.Y *= size.Y / 2;
                shapeArray[i].Position.Z *= size.Z / 2;
            }

            float collisionRadius = (size.X + size.Y + size.Z) / 6 ;
            return new MyModel(game, shapeArray, texturePath, collisionRadius);
        }
Example #22
0
        /// <summary>
        /// Loads model from vertices and indices list.
        /// </summary>
        /// <param name="vertices">The list of vertices.</param>
        /// <param name="indices">The list of indices.</param>
        public void LoadModel(ref List<Mesh.Vertex> vertices, ref List<int> indices)
        {
            VertexPositionNormalColor[] vvertices = new VertexPositionNormalColor[vertices.Count];

            int i = 0;
            foreach (var vertex in vertices)
            {
                vvertices[i].Position = vertex.Position;
                vvertices[i].Color = Color.DarkBlue;
                vvertices[i++].Normal = vertex.Normal;
            }

            int[] vindices = new int[indices.Count];
            i = 0;
            foreach (var index in indices)
            {
                vindices[i++] = index;
            }

            m_IndexBuffer = new IndexBuffer(GraphicsDevice, typeof(int), indices.Count, BufferUsage.WriteOnly);
            m_IndexBuffer.SetData(vindices);

            m_VertexBuffer = new VertexBuffer(GraphicsDevice, VertexPositionNormalColor.VertexDeclaration, vvertices.Length, BufferUsage.WriteOnly);
            m_VertexBuffer.SetData(vvertices);
        }
        public void showPath()
        {
            Vector2 positionInMazeArray = game.sphere.PositionInMaze(game.sphere.pos);
            //Cube cube = new cube();
            //List<Node> pathFromSrcToDest = maze.astar.FindPath(maze.astar.Float2DtoInt(maze.maze)
            //    , RandomMaze.WALL, maze.startPoint.x, maze.startPoint.y, maze.destPoint.x, maze.destPoint.y);
            List<Node> pathFromSrcToDest = maze.astar.FindPath(maze.astar.Float2DtoInt(maze.maze)
                , RandomMaze.WALL, (int)positionInMazeArray.X, (int)positionInMazeArray.Y, maze.destPoint.x, maze.destPoint.y);
            VertexPositionNormalColor[] wayOut = cube.GetMazeWayOutVertexWithCube(pathFromSrcToDest,CUBESCALE,Color.Red);
            VertexPositionNormalColor[] combinedWayOutAndMaze = new VertexPositionNormalColor[wayOut.Count() + myModel.shapeArray.Count()];
            Array.Copy(wayOut, combinedWayOutAndMaze, wayOut.Count());
            Array.Copy(normalMaze, 0, combinedWayOutAndMaze, wayOut.Count(), normalMaze.Count());
            myModel.shapeArray = combinedWayOutAndMaze;
            myModel.vertices = SharpDX.Toolkit.Graphics.Buffer.Vertex.New(game.GraphicsDevice, myModel.shapeArray);
            /*landScape = new VertexPositionNormalColor[terrain.Length + water.Length];

            Array.Copy(terrain, landScape, terrain.Length);
            Array.Copy(water, 0, landScape, terrain.Length, water.Length);
            */
        }
Example #24
0
        /// <summary>Initializes the heightmap.</summary>
        private void Init(Func <float, float, float, Color> calcColor)
        {
            //--------------------
            // Copy pixel data.
            //--------------------

            mHeights = new float[mTex.Width * mTex.Height];

            mPixels = new Color[mHeights.Length];
            mTex.GetData <Color>(mPixels);

            for (var i = 0; i < mHeights.Length; i++)
            {
                // Keep red channel as height. Why red channel? Because it was used in the previous
                // implementation. Works well.
                mHeights[i] = mPixels[i].R;
            }

            //--------------------
            // Blur heightmap.
            //--------------------

            var blurPixels = new float[mHeights.Length];

            Func <int, float> calcBlur = (int k) => {
                var val   = 0.0f;
                var count = 0;

                for (var i = -mBlur; i <= mBlur; i++)
                {
                    var a = k + i * mTex.Height;
                    for (var j = -mBlur; j <= mBlur; j++)
                    {
                        var k0 = a + j;
                        if (k0 < 0 || k0 >= mHeights.Length)
                        {
                            continue;
                        }

                        count++;
                        val += mHeights[k0];
                    }
                }

                return(val / count);
            };

            // Go to work, little CPUs! *cracks whip*
            Parallel.For(0, mHeights.Length, i => {
                blurPixels[i] = calcBlur(i);
            });

            // Copy back blurred values into heightmap values. We have to double-buffer to get a correct
            // result (because of the nature of blurring).
            for (var i = 0; i < mHeights.Length; i++)
            {
                mHeights[i] = blurPixels[i];
            }

            //--------------------
            // Setup vertices.
            //--------------------

            var indices = new List <int>();
            var verts   = new List <VertexPositionNormalColor>();

            // Used for smooth normals.
            var indexCache = new Dictionary <UInt64, int>();

            var indexCounter = 0;

            var xScale = 1.0f / (mTex.Width - 1);
            var yScale = 1.0f / 255.0f;
            var zScale = 1.0f / (mTex.Height - 1);

            var rnd = new Random();

            Func <int, int, int> calcVert = (i, j) => {
                UInt64 key = ((UInt64)i) << 32 | (UInt64)j;

                var k = i + j * mTex.Width;

                var x = mScale * (xScale * i - 0.5f);
                var y = mScale * (yScale * mHeights[k] - 0.5f) * mYScale;
                var z = mScale * (zScale * j - 0.5f);

                // var u = (float)i / (mTex.Width  - 1);
                // var v = (float)j / (mTex.Height - 1);

                var vert = new VertexPositionNormalColor {
                    Position = new Vector3(x, y, z),
                    Normal   = Vector3.Zero,
                    Color    = calcColor(x / mScale, (y / mScale) / mYScale, z / mScale)
                };

                if (mSmooth)
                {
                    // So, if we're doing a smooth heightmap, cache the vertex index so we can reuse it.
                    // This means triangles end up sharing vertices, in which case the normal
                    // computation will give smooth triangles.

                    if (!indexCache.ContainsKey(key))
                    {
                        verts.Add(vert);
                        indexCache[key] = indexCounter++;
                    }

                    return(indexCache[key]);
                }

                verts.Add(vert);
                return(indexCounter++);
            };

            Action <int, int, int, int, int, int> calcTri = (i0, j0, i1, j1, i2, j2) => {
                var v0 = calcVert(i0, j0);
                var v1 = calcVert(i1, j1);
                var v2 = calcVert(i2, j2);

                indices.Add(v0);
                indices.Add(v1);
                indices.Add(v2);
            };

            for (var i = 0; i < mTex.Width - mStepX; i += mStepX)
            {
                for (var j = 0; j < mTex.Height - mStepY; j += mStepY)
                {
                    // If random tris are enabled, randomize the diagonal of each triangle.
                    if (!mRandomTris || rnd.Next(0, 2) == 1)
                    {
                        calcTri(i, j, i + mStepX, j, i + mStepX, j + mStepY);
                        calcTri(i + mStepX, j + mStepY, i, j + mStepY, i, j);
                    }
                    else
                    {
                        calcTri(i, j + mStepY, i, j, i + mStepX, j);
                        calcTri(i + mStepX, j, i + mStepX, j + mStepY, i, j + mStepY);
                    }
                }
            }

            CreateModel(indices.ToArray(), verts.ToArray(), calcColor);
        }
Example #25
0
        /// <summary>
        /// Create a world base to use.
        /// </summary>
        /// <param name="size">Size of world.</param>
        /// <returns>A world model.</returns>
        public MyModel CreateWorldBase(int size)
        {
            float collisionRadius = 1;
            float magnitude = HEIGHT_INIT;
            int sidelength = (int)Math.Pow(2, size);
            int min = -sidelength / 2;
            int k = 0;
            // Data structures for generating vertice heightmap
            Vector3[][] points = new Vector3[sidelength][];
            Vector3[][] normals = new Vector3[sidelength][];
            Random rand = new Random();

            // Generate a map by calling the function
            points = genMap(sidelength, -WORLD_WIDTH, WORLD_WIDTH, -WORLD_WIDTH, WORLD_WIDTH, 0.0f);

            // Apply diamond square algorithm
            points = diamondSquare(points, rand, HEIGHT_INIT, 0, sidelength, 0, sidelength, CORNER);

            // Apply diamond square algorithm
            points = flattenSection(points, sidelength, 30,50,30,50);
            points = diamondSquare(points, rand, 1, 32, 49, 32, 49, -4);

            // Apply diamond square algorithm
            points = flattenSection(points, sidelength, 30,50,85,100);
            points = diamondSquare(points, rand, 1, 32, 49, 87, 96, -4);

            // Apply diamond square algorithm
            points = flattenSection(points, sidelength, 85,100,30,50);
            points = diamondSquare(points, rand, 1, 87, 96, 32, 49, -4);

            // Apply diamond square algorithm
            points = flattenSection(points, sidelength, 85,100,85,100);
            points = diamondSquare(points, rand, 1, 87, 96, 87, 96, -4);

            // Lower points
            points = lowerSeaFloor(points, sidelength, -1, 2.0f);

            // Calculate vertex normals
            normals = getNormals(points);

            VertexPositionNormalColor[] shapeArray = new VertexPositionNormalColor[(sidelength + 1) * (sidelength + 1) *6];

            for (int i = 0; i < sidelength; i++)
            {
                for (int j = 0; j < sidelength; j++)
                {
                    //Each step creates a square in the map mesh
                    //Bottom triangle
                    shapeArray[k] = new VertexPositionNormalColor(points[i][j], -Vector3.UnitZ,
                        getColor(points[i][j]));
                    shapeArray[k + 1] = new VertexPositionNormalColor(points[i+1][j+1], -Vector3.UnitZ,
                        getColor(points[i+1][j+1]));
                    shapeArray[k + 2] = new VertexPositionNormalColor(points[i+1][j], -Vector3.UnitZ,
                        getColor(points[i+1][j]));

                    //Top Triangle
                    shapeArray[k + 3] = new VertexPositionNormalColor(points[i][j], -Vector3.UnitZ,
                        getColor(points[i][j]));
                    shapeArray[k + 4] = new VertexPositionNormalColor(points[i][j+1], -Vector3.UnitZ,
                        getColor(points[i][j+1]));
                    shapeArray[k + 5] = new VertexPositionNormalColor(points[i+1][j+1], -Vector3.UnitZ,
                        getColor(points[i+1][j+1]));

                    k += 6;
                }
            }

            MyModel m = new MyModel(game, shapeArray, collisionRadius);

            // Make reference to points
            m.modelMap = points;

            return m;
        }
Example #26
0
        public static void ApplyTransformx(ModelMeshPart meshPart, Matrix transform)
        {
            Matrix cTransform = transform;
            Matrix cTransformInverseTranspose = Matrix.Invert(Matrix.Transpose(cTransform));


            VertexBuffer vertexBuffer = meshPart.VertexBuffer;

            VertexElement[] vs = vertexBuffer.VertexDeclaration.GetVertexElements();


            if (EqualUsages(vs, VertexPositionNormalColor.GetUsages()))
            {
                VertexPositionNormalColor[] vertices = new VertexPositionNormalColor[vertexBuffer.VertexCount];
                vertexBuffer.GetData <VertexPositionNormalColor>(vertices);
                for (int i = 0; i < vertices.Length; i++)
                {
                    vertices[i].position = Vector3.Transform(vertices[i].position, cTransform);
                    vertices[i].normal   = Vector3.Normalize(Vector3.Transform(vertices[i].normal, cTransformInverseTranspose));
                }

                vertexBuffer.SetData <VertexPositionNormalColor>(vertices);
            }
            else if (EqualUsages(vs, GetVertexPositionNormalUsage()))
            {
                int     vertexSize   = vertexBuffer.VertexDeclaration.VertexStride / 4;
                float[] verticeParts = new float[vertexBuffer.VertexCount * vertexSize];

                vertexBuffer.GetData <float>(verticeParts);

                for (int i = 0; i < verticeParts.Length; i += vertexSize)
                {
                    //transform position and normal
                    Vector3 vec = Vector3.Transform(new Vector3(verticeParts[i], verticeParts[i + 1], verticeParts[i + 2]), cTransform);
                    verticeParts[i]     = vec.X;
                    verticeParts[i + 1] = vec.Y;
                    verticeParts[i + 2] = vec.Z;
                    vec = Vector3.Transform(new Vector3(verticeParts[i + 3], verticeParts[i + 4], verticeParts[i + 5]), cTransformInverseTranspose);
                    verticeParts[i + 3] = vec.X;
                    verticeParts[i + 4] = vec.Y;
                    verticeParts[i + 5] = vec.Z;
                    vec.Normalize();
                }

                vertexBuffer.SetData <float>(verticeParts);
            }
            else if (EqualUsages(vs, GetVertexBonesUsage()))
            {
                try
                {
                    int     vertexSize   = vertexBuffer.VertexDeclaration.VertexStride / 4;
                    float[] verticeParts = new float[vertexBuffer.VertexCount * vertexSize];

                    vertexBuffer.GetData <float>(verticeParts);

                    for (int i = 0; i < verticeParts.Length; i += vertexSize)
                    {
                        //transform position and normal
                        Vector3 vec = Vector3.Transform(new Vector3(verticeParts[i], verticeParts[i + 1], verticeParts[i + 2]), cTransform);
                        verticeParts[i]     = vec.X;
                        verticeParts[i + 1] = vec.Y;
                        verticeParts[i + 2] = vec.Z;
                        vec = Vector3.Transform(new Vector3(verticeParts[i + 8], verticeParts[i + 9], verticeParts[i + 10]), cTransformInverseTranspose);
                        vec.Normalize();
                        verticeParts[i + 8]  = vec.X;
                        verticeParts[i + 9]  = vec.Y;
                        verticeParts[i + 10] = vec.Z;
                    }

                    vertexBuffer.SetData <float>(verticeParts);
                } catch
                {
                }
            }
            else
            {
                //throw new NotImplementedException();
            }
        }
        private void SetUpBuffers()
        {
            indices.Clear();
            int indexOffset = 0;

            for (int i = 0; i < particles.Count; i++)
            {
                if (particles[i].LifeBar > 0)
                {
                    vertexOffset += 4;
                }
            }
            if (vertexOffset > 0)
            {
                if (vb != null)
                {
                    vb.Dispose();
                }
                vb           = new VertexBuffer(device, VertexPositionNormalColor.SizeInBytes * vertexOffset, Usage.None, VertexPositionNormalColor.Format, Pool.Default);
                vertexOffset = 0;
                using (DataStream stream = vb.Lock(0, 0, LockFlags.None))
                {
                    for (int i = 0; i < particles.Count; i++)
                    {
                        if (particles[i].LifeBar > 0)
                        {
                            float angle = (float)Math.PI / 3.0f;

                            Matrix  billBoard = Matrix.Translation(-particles[i].Position) * CreateTransform(particles[i].Velocity) * Matrix.Translation(particles[i].Position);
                            Vector3 v1        = Vector3.TransformCoordinate(
                                new Vector3(
                                    particles[i].Position.X,
                                    particles[i].Position.Y + particleSize * 2.0f,
                                    particles[i].Position.Z),
                                billBoard);
                            Vector3 v2 = Vector3.TransformCoordinate(
                                new Vector3(
                                    particles[i].Position.X + particleSize * (float)Math.Sin(angle),
                                    particles[i].Position.Y - particleSize * (float)Math.Cos(angle),
                                    particles[i].Position.Z),
                                billBoard);
                            Vector3 v3 = Vector3.TransformCoordinate(
                                new Vector3(
                                    particles[i].Position.X - particleSize * (float)Math.Sin(angle) * (float)Math.Sin(angle / 2.0f),
                                    particles[i].Position.Y - particleSize * (float)Math.Cos(angle),
                                    particles[i].Position.Z + particleSize * (float)Math.Sin(angle) * (float)Math.Cos(angle / 2.0f)),
                                billBoard);
                            Vector3 v4 = Vector3.TransformCoordinate(
                                new Vector3(
                                    particles[i].Position.X - particleSize * (float)Math.Sin(angle) * (float)Math.Sin(angle / 2.0f),
                                    particles[i].Position.Y - particleSize * (float)Math.Cos(angle),
                                    particles[i].Position.Z - particleSize * (float)Math.Sin(angle) * (float)Math.Cos(angle / 2.0f)),
                                billBoard);


                            Vector4 v11 = new Vector4(v1 * positionScaleParam, 1.0f);
                            VertexPositionNormalColor vertex1 = new VertexPositionNormalColor(v1, Vector3.TransformNormal(new Vector3(0, 1, 0), billBoard), (int)particles[i].ColorARGB);
                            stream.Write(vertex1);

                            Vector4 v22 = new Vector4(v2 * positionScaleParam, 1.0f);
                            VertexPositionNormalColor vertex2 = new VertexPositionNormalColor(v2, Vector3.TransformNormal(v2 - particles[i].Position, billBoard), (int)particles[i].ColorARGB);
                            stream.Write(vertex2);

                            Vector4 v33 = new Vector4(v3 * positionScaleParam, 1.0f);
                            VertexPositionNormalColor vertex3 = new VertexPositionNormalColor(v3, Vector3.TransformNormal(v3 - particles[i].Position, billBoard), (int)particles[i].ColorARGB);
                            stream.Write(vertex3);

                            Vector4 v44 = new Vector4(v4 * positionScaleParam, 1.0f);
                            VertexPositionNormalColor vertex4 = new VertexPositionNormalColor(v4, Vector3.TransformNormal(v4 - particles[i].Position, billBoard), (int)particles[i].ColorARGB);
                            stream.Write(vertex4);

                            indices.AddRange(new int[] { vertexOffset, vertexOffset + 1, vertexOffset + 2, vertexOffset, vertexOffset + 2, vertexOffset + 3, vertexOffset, vertexOffset + 1, vertexOffset + 3, vertexOffset + 1, vertexOffset + 2, vertexOffset + 3, });

                            vertexOffset += 4;
                            indexOffset  += 12;
                        }
                    }
                    vb.Unlock();
                }
            }


            if (vertexOffset > 0)
            {
                if (ib != null)
                {
                    ib.Dispose();
                }
                ib = new IndexBuffer(device, sizeof(int) * indices.Count, Usage.None, Pool.Default, false);
                using (DataStream stream = ib.Lock(0, 0, LockFlags.None))
                {
                    for (int i = 0; i < indices.Count; i++)
                    {
                        stream.Write(indices[i]);
                    }
                    ib.Unlock();
                }
            }
        }
 public virtual void Initialize(VertexPositionNormalColor[] vertices, int[] indices)
 {
     this.InitializeWasCalled = true;
     this.Vertices = vertices;
 }
        public void addPolygon(Vector3 a, Vector3 b, Vector3 c)
        {
            Color[] col = new Color[3];
            Vector3[] pos = new[] { a, b, c };

            // Calc the surface normal
            Vector3 A, B, normal;
            A = b - a;
            B = c - a;
            normal = Vector3.Cross(A, B);
            normal.Normalize();

            for (int i = 0; i < 3; i++)
            {
                if (pos[i].Y > this.snow)
                {
                    col[i] = Color.White;
                }
                else if (pos[i].Y > this.rock)
                {
                    col[i] = Color.LightGray;
                }
                else if (pos[i].Y > this.water)
                {
                    col[i] = Color.Green;
                }
                else
                {
                    col[i] = Color.BlanchedAlmond;
                }

                vertexArray[vertexCount + i] = new VertexPositionNormalColor(pos[i], normal, col[i]);
            }

            vertexCount += 3;
        }
Example #30
0
        public VertexPositionNormalColor[] TranslatePolygonInXY(VertexPositionNormalColor[] cube,Vector3 translation)
        {
            for (int i = 0; i < cube.Length; i++)
            {
                cube[i].Position = cube[i].Position+translation;

            }

            return cube;
        }
        private void SetUpBuffers()
        {
            indices.Clear();
            int indexOffset = 0;

            for (int i = 0; i < particles.Count; i++)
            {
                if (particles[i].LifeBar > 0)
                {
                    vertexOffset += 4;
                }
            }
            if (vertexOffset > 0)
            {

                if (vb!=null) vb.Dispose();
                vb = new VertexBuffer(device, VertexPositionNormalColor.SizeInBytes * vertexOffset, Usage.None, VertexPositionNormalColor.Format, Pool.Default);
                vertexOffset = 0;
                using (DataStream stream = vb.Lock(0, 0, LockFlags.None))
                {
                    for (int i = 0; i < particles.Count; i++)
                    {
                        if (particles[i].LifeBar > 0)
                        {

                            float angle = (float)Math.PI / 3.0f;

                            Matrix billBoard = Matrix.Translation(-particles[i].Position) * CreateTransform(particles[i].Velocity) * Matrix.Translation(particles[i].Position);
                            Vector3 v1 = Vector3.TransformCoordinate(
                                new Vector3(
                                    particles[i].Position.X,
                                    particles[i].Position.Y + particleSize * 2.0f,
                                    particles[i].Position.Z),
                                billBoard);
                            Vector3 v2 = Vector3.TransformCoordinate(
                                new Vector3(
                                    particles[i].Position.X + particleSize * (float)Math.Sin(angle),
                                    particles[i].Position.Y - particleSize * (float)Math.Cos(angle),
                                    particles[i].Position.Z),
                                billBoard);
                            Vector3 v3 = Vector3.TransformCoordinate(
                                new Vector3(
                                    particles[i].Position.X - particleSize * (float)Math.Sin(angle) * (float)Math.Sin(angle / 2.0f),
                                    particles[i].Position.Y - particleSize * (float)Math.Cos(angle),
                                    particles[i].Position.Z + particleSize * (float)Math.Sin(angle) * (float)Math.Cos(angle / 2.0f)),
                                billBoard);
                            Vector3 v4 = Vector3.TransformCoordinate(
                                new Vector3(
                                    particles[i].Position.X - particleSize * (float)Math.Sin(angle) * (float)Math.Sin(angle / 2.0f),
                                    particles[i].Position.Y - particleSize * (float)Math.Cos(angle),
                                    particles[i].Position.Z - particleSize * (float)Math.Sin(angle) * (float)Math.Cos(angle / 2.0f)),
                                billBoard);


                            Vector4 v11 = new Vector4(v1 * positionScaleParam, 1.0f);
                            VertexPositionNormalColor vertex1 = new VertexPositionNormalColor(v1, Vector3.TransformNormal(new Vector3(0, 1, 0), billBoard), (int)particles[i].ColorARGB);
                            stream.Write(vertex1);

                            Vector4 v22 = new Vector4(v2 * positionScaleParam, 1.0f);
                            VertexPositionNormalColor vertex2 = new VertexPositionNormalColor(v2, Vector3.TransformNormal(v2 - particles[i].Position, billBoard), (int)particles[i].ColorARGB);
                            stream.Write(vertex2);

                            Vector4 v33 = new Vector4(v3 * positionScaleParam, 1.0f);
                            VertexPositionNormalColor vertex3 = new VertexPositionNormalColor(v3, Vector3.TransformNormal(v3 - particles[i].Position, billBoard), (int)particles[i].ColorARGB);
                            stream.Write(vertex3);

                            Vector4 v44 = new Vector4(v4 * positionScaleParam, 1.0f);
                            VertexPositionNormalColor vertex4 = new VertexPositionNormalColor(v4, Vector3.TransformNormal(v4 - particles[i].Position, billBoard), (int)particles[i].ColorARGB);
                            stream.Write(vertex4);

                            indices.AddRange(new int[] { vertexOffset, vertexOffset + 1, vertexOffset + 2, vertexOffset, vertexOffset + 2, vertexOffset + 3, vertexOffset, vertexOffset + 1, vertexOffset + 3, vertexOffset + 1, vertexOffset + 2, vertexOffset + 3, });

                            vertexOffset += 4;
                            indexOffset += 12;

                        }
                    }
                    vb.Unlock();
                }
            }


            if (vertexOffset > 0)
            {
                if (ib!=null) ib.Dispose(); 
                ib = new IndexBuffer(device, sizeof(int) * indices.Count, Usage.None, Pool.Default, false);
                using (DataStream stream = ib.Lock(0, 0, LockFlags.None))
                {
                    for (int i = 0; i < indices.Count; i++)
                    {
                        stream.Write(indices[i]);
                    }
                    ib.Unlock();
                }
            }

        }
Example #32
0
        private void ResizeBuffer(int numberOfTriangles)
        {
            int requiredBufferLength = numberOfTriangles * 3;
              if (_buffer.Length >= requiredBufferLength)
            return;

              // Double buffer until it is large enough.
              int newBufferLength = _buffer.Length * 2;
              while (newBufferLength < requiredBufferLength)
            newBufferLength *= 2;

              // Copy old buffer to new buffer.
              var newBuffer = new VertexPositionNormalColor[newBufferLength];
              Array.Copy(_buffer, newBuffer, _buffer.Length);

              _buffer = newBuffer;
        }
Example #33
0
        public Landscape(Game game)
        {
            Terrain = new HeightMap(10);

            terrain3D = new VertexPositionNormalColor[Terrain.max * Terrain.max * 6  + 12];
            int index = 0;
            for (int z = 0; z < Terrain.max; z++)
            {
                for (int x = 0; x < Terrain.max; x++)
                {
                    // Front left.
                    terrain3D[index] = new VertexPositionNormalColor(new Vector3(x, Terrain.get(x,z), z), Terrain.getVertexNormal(x,z) , Terrain.getColor(x,z));
                    index++;
                    // Back left.
                    terrain3D[index] = new VertexPositionNormalColor(new Vector3(x, Terrain.get(x, z + 1), z + 1), Terrain.getVertexNormal(x, z + 1), Terrain.getColor(x, z+1));
                    index++;

                    // Back right.
                    terrain3D[index] = new VertexPositionNormalColor(new Vector3(x + 1, Terrain.get(x + 1, z + 1), z + 1), Terrain.getVertexNormal(x + 1, z + 1), Terrain.getColor(x+1, z+1));
                    index++;

                    // Front left.
                    terrain3D[index] = new VertexPositionNormalColor(new Vector3(x, Terrain.get(x, z), z), Terrain.getVertexNormal(x, z), Terrain.getColor(x, z));
                    index++;

                    // Back right.
                    terrain3D[index] = new VertexPositionNormalColor(new Vector3(x + 1, Terrain.get(x + 1, z + 1), z + 1), Terrain.getVertexNormal(x + 1, z + 1), Terrain.getColor(x+1, z+1));
                    index++;

                    // Front right.
                    terrain3D[index] = new VertexPositionNormalColor(new Vector3(x + 1, Terrain.get(x + 1, z), z), Terrain.getVertexNormal(x + 1, z), Terrain.getColor(x+1, z));
                    index++;
                }
            }

            Color blue = Color.MidnightBlue;
            blue.A = 0xC0;

            waterHeight = 0.695f * Terrain.maxHeight;

            //Set Water Polygons
            // Front left.
            terrain3D[index] = new VertexPositionNormalColor(new Vector3(0.0f, waterHeight, 0.0f), new Vector3(0.0f, 1.0f, 0.0f), blue);
            index++;

            // Back left.
            terrain3D[index] = new VertexPositionNormalColor(new Vector3(0.0f, waterHeight, Terrain.max), new Vector3(0.0f, 1.0f, 0.0f), blue);
            index++;

            // Back right.
            terrain3D[index] = new VertexPositionNormalColor(new Vector3(Terrain.max, waterHeight, Terrain.max), new Vector3(0.0f, 1.0f, 0.0f), blue);
            index++;

            // Front left.
            terrain3D[index] = new VertexPositionNormalColor(new Vector3(0.0f, waterHeight, 0.0f), new Vector3(0.0f, 1.0f, 0.0f), blue);
            index++;

            // Back right.
            terrain3D[index] = new VertexPositionNormalColor(new Vector3(Terrain.max, waterHeight, Terrain.max), new Vector3(0.0f, 1.0f, 0.0f), blue);
            index++;

            // Front right.
            terrain3D[index] = new VertexPositionNormalColor(new Vector3(Terrain.max, waterHeight, 0.0f), new Vector3(0.0f, 1.0f, 0.0f), blue);
            index++;

            //water from the bottom
            // Front left.
            terrain3D[index] = new VertexPositionNormalColor(new Vector3(0.0f, waterHeight, 0.0f), new Vector3(0.0f, 1.0f, 0.0f), blue);
            index++;

            // Back right.
            terrain3D[index] = new VertexPositionNormalColor(new Vector3(Terrain.max, waterHeight, Terrain.max), new Vector3(0.0f, 1.0f, 0.0f), blue);
            index++;

            // Back left.
            terrain3D[index] = new VertexPositionNormalColor(new Vector3(0.0f, waterHeight, Terrain.max), new Vector3(0.0f, 1.0f, 0.0f), blue);
            index++;

            // Front left.
            terrain3D[index] = new VertexPositionNormalColor(new Vector3(0.0f, waterHeight, 0.0f), new Vector3(0.0f, 1.0f, 0.0f), blue);
            index++;

            // Front right.
            terrain3D[index] = new VertexPositionNormalColor(new Vector3(Terrain.max, waterHeight, 0.0f), new Vector3(0.0f, 1.0f, 0.0f), blue);
            index++;

            // Back right.
            terrain3D[index] = new VertexPositionNormalColor(new Vector3(Terrain.max, waterHeight, Terrain.max), new Vector3(0.0f, 1.0f, 0.0f), blue);
            index++;

            //initialized here because I wanted the terrain details to place the initial position/target.
            currentPosition = new Vector3(0.0f, Terrain.maxHeight, 0.0f); //start on corner of map at highest point of terrain
            currentTarget = new Vector3(Terrain.max, Terrain.maxHeight, Terrain.max); //looking across to other corner (same height)
            currentUp = Vector3.UnitY;
            prevMouseX = 0.5f;
            prevMouseY = 0.5f;

            vertices = Buffer.Vertex.New(game.GraphicsDevice, terrain3D);

            basicEffect = new BasicEffect(game.GraphicsDevice)
            {
                VertexColorEnabled = true,
                View = Matrix.LookAtLH(currentPosition, currentTarget, currentUp),
                Projection = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, (float)game.GraphicsDevice.BackBuffer.Width / game.GraphicsDevice.BackBuffer.Height, -10.0f, (float)Terrain.size * 2),
                World = Matrix.Identity,
                LightingEnabled = true
            };

            inputLayout = VertexInputLayout.FromBuffer(0, vertices);
            basicEffect.EnableDefaultLighting();

            basicEffect.AmbientLightColor = new Vector3(.1f * 255/255, .1f * 244/255, .1f * 229/255);

            this.game = game;
        }
Example #34
0
        private unsafe Mesh ConvertToMesh(GraphicsDevice graphicsDevice, PrimitiveType primitiveType, LightProbeRuntimeData lightProbeRuntimeData)
        {
            // Generate data for vertex buffer
            var vertices = new VertexPositionNormalColor[lightProbeRuntimeData.LightProbes.Length];

            for (var i = 0; i < lightProbeRuntimeData.LightProbes.Length; i++)
            {
                vertices[i] = new VertexPositionNormalColor(lightProbeRuntimeData.Vertices[i], Vector3.Zero, Color4.White);
            }

            // Generate data for index buffer
            var indices = new int[lightProbeRuntimeData.Faces.Count * 6];

            for (var i = 0; i < lightProbeRuntimeData.Faces.Count; ++i)
            {
                var currentFace = lightProbeRuntimeData.Faces[i];

                // Skip infinite edges to not clutter display
                // Maybe we could reenable it when we have better infinite nodes
                if (currentFace.Vertices[0] >= lightProbeRuntimeData.UserVertexCount ||
                    currentFace.Vertices[1] >= lightProbeRuntimeData.UserVertexCount ||
                    currentFace.Vertices[2] >= lightProbeRuntimeData.UserVertexCount)
                {
                    continue;
                }

                indices[i * 6 + 0] = currentFace.Vertices[0];
                indices[i * 6 + 1] = currentFace.Vertices[1];
                indices[i * 6 + 2] = currentFace.Vertices[1];
                indices[i * 6 + 3] = currentFace.Vertices[2];
                indices[i * 6 + 4] = currentFace.Vertices[2];
                indices[i * 6 + 5] = currentFace.Vertices[0];
            }

            var boundingBox = BoundingBox.Empty;

            for (int i = 0; i < vertices.Length; i++)
            {
                BoundingBox.Merge(ref boundingBox, ref vertices[i].Position, out boundingBox);
            }

            // Compute bounding sphere
            BoundingSphere boundingSphere;

            fixed(void *verticesPtr = vertices)
            BoundingSphere.FromPoints((IntPtr)verticesPtr, 0, vertices.Length, VertexPositionNormalTexture.Size, out boundingSphere);

            var layout = vertices[0].GetLayout();

            var meshDraw = new MeshDraw
            {
                IndexBuffer   = new IndexBufferBinding(Buffer.Index.New(graphicsDevice, indices).RecreateWith(indices), true, indices.Length),
                VertexBuffers = new[] { new VertexBufferBinding(Buffer.New(graphicsDevice, vertices, BufferFlags.VertexBuffer).RecreateWith(vertices), layout, vertices.Length) },
                DrawCount     = indices.Length,
                PrimitiveType = primitiveType,
            };

            wireframeResources.Add(meshDraw.VertexBuffers[0].Buffer);
            wireframeResources.Add(meshDraw.IndexBuffer.Buffer);

            return(new Mesh {
                Draw = meshDraw, BoundingBox = boundingBox, BoundingSphere = boundingSphere
            });
        }
Example #35
0
        //Generate a 3D model for the terrain
        private VertexPositionNormalColor[] TerrainModel(float[,] map)
        {
            VertexPositionNormalColor[] VList = new VertexPositionNormalColor[this.polycount*3];
            int index=0;

            Vector3 p1,p2,p3;
            Vector3 normal;

            //Upper Triangles in Mesh
            for (int i = 0; i < this.size-1; i++){
                for (int j = 0; j < this.size - 1;j++ ){

                    p1 = new Vector3(i, map[i, j], j);
                    p2 = new Vector3(i, map[i, j + 1], j + 1);
                    p3 = new Vector3(i + 1, map[i + 1, j + 1], j + 1);

                    normal = genNormal(p1,p2,p3);

                    VList[index] = new VertexPositionNormalColor(p1,normal,getColor(map[i,j]));
                    VList[index + 1] = new VertexPositionNormalColor(p2, normal, getColor(map[i,j+1]));
                    VList[index + 2] = new VertexPositionNormalColor(p3, normal, getColor(map[i+1,j+1]));
                    index += 3;
                }
            }

            //Lower Triangles in Mesh
            for (int i = 1; i < this.size; i++){
                for (int j = 1; j < this.size; j++){

                    p1 = new Vector3(i, map[i, j], j);
                    p2 = new Vector3(i, map[i, j - 1], j - 1);
                    p3 = new Vector3(i - 1, map[i - 1, j - 1], j - 1);

                    normal = genNormal(p1, p2, p3);

                    VList[index] = new VertexPositionNormalColor(p1, normal, getColor(map[i,j]));
                    VList[index + 1] = new VertexPositionNormalColor(p2, normal, getColor(map[i,j-1]));
                    VList[index+2] = new VertexPositionNormalColor(p3, normal, getColor(map[i-1,j-1]));
                    index += 3;
                }
            }
            return VList;
        }