コード例 #1
0
	// Use this for initialization
	void Start () 
	{
		CreateLineMaterial();
		
		mesh = new Mesh();
		Vertex2[] vertices = new Vertex2[NumberOfVertices];
		Vector3[] meshVerts = new Vector3[NumberOfVertices];
		int[] indices = new int[NumberOfVertices];
		
		Random.seed = 0;
		for (var i = 0; i < NumberOfVertices; i++)
		{
			vertices[i] = new Vertex2(size * Random.Range(-1.0f, 1.0f), size * Random.Range(-1.0f, 1.0f));
			meshVerts[i] = vertices[i].ToVector3();
			indices[i] = i;
		}
		
		mesh.vertices = meshVerts;
		mesh.SetIndices(indices, MeshTopology.Points, 0);
		//mesh.bounds = new Bounds(Vector3.zero, new Vector3((float)size,(float)size,(float)size));
		
		float now = Time.realtimeSinceStartup;
		voronoiMesh = VoronoiMesh.Create<Vertex2, Cell2>(vertices);
		float interval = Time.realtimeSinceStartup - now;

		Debug.Log("time = " + interval * 1000.0f);
		
	}
コード例 #2
0
ファイル: ExampleConvexHull2D.cs プロジェクト: fecca/Code
	// Use this for initialization
	void Start () 
	{
		CreateLineMaterial();

		mesh = new Mesh();
		Vertex2[] vertices = new Vertex2[NumberOfVertices];
		Vector3[] meshVerts = new Vector3[NumberOfVertices];
		int[] indices = new int[NumberOfVertices];

		Random.seed = 0;
		for (var i = 0; i < NumberOfVertices; i++)
		{
			vertices[i] = new Vertex2(size * Random.Range(-1.0f, 1.0f), size * Random.Range(-1.0f, 1.0f));
			meshVerts[i] = vertices[i].ToVector3();
			indices[i] = i;
		}

		mesh.vertices = meshVerts;
		mesh.SetIndices(indices, MeshTopology.Points, 0);
		//mesh.bounds = new Bounds(Vector3.zero, new Vector3((float)size,(float)size,(float)size));

		float now = Time.realtimeSinceStartup;
		ConvexHull<Vertex2, Face2> convexHull = ConvexHull.Create<Vertex2, Face2>(vertices);
		float interval = Time.realtimeSinceStartup - now;

		convexHullVertices = new List<Vertex2>(convexHull.Points);
		convexHullFaces = new List<Face2>(convexHull.Faces);

		Debug.Log("Out of the " + NumberOfVertices + " vertices, there are " + convexHullVertices.Count + " verts on the convex hull.");
		Debug.Log("time = " + interval * 1000.0f + " ms");

	}
コード例 #3
0
ファイル: Edge.cs プロジェクト: olemstrom/the-morko
    public Edge(Vertex2 start, Vertex2 end)
    {
        this.start = start;
        this.end = end;

        double width = Math.Abs (start.x - end.x);
        double height = Math.Abs (start.y - end.y);
        Size = (int)Math.Sqrt (Math.Pow (width, 2) + Math.Pow (height, 2));
    }
コード例 #4
0
ファイル: PathGenerator.cs プロジェクト: olemstrom/the-morko
    public void AddPath(Edge e)
    {
        Vertex2 start = e.start;
        Vertex2 end = e.end;
        this.end = end;

        MarkRoom (map.GetRoom (start), PathGenerator.OPEN_NOT_ENDPOINT);
        DisableAll ();
        EnableRoom (map.GetRoom (end));
        CreatePath (start);
        EnableRoom (map.GetRoom (start));
        EnableAll ();
    }
コード例 #5
0
ファイル: PathGenerator.cs プロジェクト: olemstrom/the-morko
    private List<PathNode> AllPotentialNeighbors(Vertex2 v)
    {
        List<PathNode> neighbors = new List<PathNode>();
        neighbors.Add (new PathNode(1, new Vertex2(v.x - 1, v.y)));
        neighbors.Add (new PathNode(1, new Vertex2(v.x + 1, v.y)));
        neighbors.Add (new PathNode(1, new Vertex2(v.x, v.y - 1)));
        neighbors.Add (new PathNode(1, new Vertex2(v.x, v.y + 1)));

        neighbors.Add (new PathNode(1.4, new Vertex2(v.x + 1, v.y + 1)));
        neighbors.Add (new PathNode(1.4, new Vertex2(v.x + 1, v.y - 1)));
        neighbors.Add (new PathNode(1.4, new Vertex2(v.x - 1, v.y + 1)));
        neighbors.Add (new PathNode(1.4, new Vertex2(v.x - 1, v.y - 1)));

        return neighbors;
    }
コード例 #6
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (vertex1_ != null)
            {
                hash ^= Vertex1.GetHashCode();
            }
            if (vertex2_ != null)
            {
                hash ^= Vertex2.GetHashCode();
            }
            if (vertex3_ != null)
            {
                hash ^= Vertex3.GetHashCode();
            }
            return(hash);
        }
コード例 #7
0
ファイル: ExampleDelaunay2D.cs プロジェクト: NasTul/AReco
        private void DrawCircle(Vertex2 v, float radius, int segments)
        {
            float ds = Mathf.PI * 2.0f / (float)segments;

            for (float i = -Mathf.PI; i < Mathf.PI; i += ds)
            {
                float dx0 = Mathf.Cos(i);
                float dy0 = Mathf.Sin(i);

                float x0 = v.X + dx0 * radius;
                float y0 = v.Y + dy0 * radius;

                float dx1 = Mathf.Cos(i + ds);
                float dy1 = Mathf.Sin(i + ds);

                float x1 = v.X + dx1 * radius;
                float y1 = v.Y + dy1 * radius;

                GL.Vertex3(x0, y0, 0.0f);
                GL.Vertex3(x1, y1, 0.0f);
            }
        }
コード例 #8
0
ファイル: PathGenerator.cs プロジェクト: olemstrom/the-morko
 public void Add(double cost, Vertex2 v)
 {
     queue.Enqueue(v, -cost);
 }
コード例 #9
0
ファイル: PathGenerator.cs プロジェクト: olemstrom/the-morko
    private List<PathNode> GetNeighbors(Vertex2 v)
    {
        var pNeighbors = PotentialNeighbors(v);
        var neighbors = new List<PathNode> ();
        foreach(var pNeighbor in pNeighbors) {
            if (map.IsInside (pNeighbor.location) && IsAccessible (pNeighbor.location)) neighbors.Add (pNeighbor);
        }

        return neighbors;
    }
コード例 #10
0
ファイル: PathGenerator.cs プロジェクト: olemstrom/the-morko
 private bool IsGoal(Vertex2 v)
 {
     //return v.Equals (new Vertex2(0, 0));
     return tiles [v.y, v.x] == PathGenerator.OPEN_ENDPOINT;
 }
コード例 #11
0
ファイル: DirectedEdge.cs プロジェクト: avalsa/TaskCore
 /// <summary> Создаёт глубокую копию данного объекта </summary>
 public override object Clone()
 {
     return(new DirectedEdge((Vertex)Vertex1.Clone(), (Vertex)Vertex2.Clone()));
 }
コード例 #12
0
        private void AddGeometry(SharpDevice device, Geometry_000F g, Matrix transformMatrix)
        {
            List <string> materialList = new List <string>();

            foreach (Material_0007 m in g.materialList.materialList)
            {
                if (m.texture != null)
                {
                    string textureName = m.texture.diffuseTextureName.stringString;
                    materialList.Add(textureName);
                }
                else
                {
                    materialList.Add(DefaultTexture);
                }
            }

            if ((g.geometryStruct.geometryFlags2 & GeometryFlags2.isNativeGeometry) != 0)
            {
                AddNativeData(device, g.geometryExtension, materialList, transformMatrix);
                return;
            }

            List <Vector3>       vertexList1   = new List <Vector3>();
            List <Vector3>       normalList    = new List <Vector3>();
            List <Vector2>       textCoordList = new List <Vector2>();
            List <SharpDX.Color> colorList     = new List <SharpDX.Color>();

            if ((g.geometryStruct.geometryFlags & GeometryFlags.hasVertexPositions) != 0)
            {
                MorphTarget m = g.geometryStruct.morphTargets[0];
                foreach (Vertex3 v in m.vertices)
                {
                    Vector3 pos = (Vector3)Vector3.Transform(new Vector3(v.X, v.Y, v.Z), transformMatrix);
                    vertexList1.Add(pos);
                    vertexListG.Add(pos);
                }
            }

            if ((g.geometryStruct.geometryFlags & GeometryFlags.hasNormals) != 0)
            {
                for (int i = 0; i < vertexList1.Count; i++)
                {
                    normalList.Add(new Vector3(g.geometryStruct.morphTargets[0].normals[i].X, g.geometryStruct.morphTargets[0].normals[i].Y, g.geometryStruct.morphTargets[0].normals[i].Z));
                }
            }

            if ((g.geometryStruct.geometryFlags & GeometryFlags.hasVertexColors) != 0)
            {
                for (int i = 0; i < vertexList1.Count; i++)
                {
                    RenderWareFile.Color c = g.geometryStruct.vertexColors[i];
                    colorList.Add(new SharpDX.Color(c.R, c.G, c.B, c.A));
                }
            }
            else
            {
                for (int i = 0; i < vertexList1.Count; i++)
                {
                    colorList.Add(new SharpDX.Color(1f, 1f, 1f, 1f));
                }
            }

            if ((g.geometryStruct.geometryFlags & GeometryFlags.hasTextCoords) != 0)
            {
                for (int i = 0; i < vertexList1.Count; i++)
                {
                    Vertex2 tc = g.geometryStruct.textCoords[i];
                    textCoordList.Add(new Vector2(tc.X, tc.Y));
                }
            }
            else
            {
                for (int i = 0; i < vertexList1.Count; i++)
                {
                    textCoordList.Add(new Vector2());
                }
            }

            List <SharpSubSet> SubsetList = new List <SharpSubSet>();
            List <int>         indexList  = new List <int>();
            int previousIndexCount        = 0;

            for (int i = 0; i < materialList.Count; i++)
            {
                foreach (Triangle t in g.geometryStruct.triangles)
                {
                    if (t.materialIndex == i)
                    {
                        indexList.Add(t.vertex1);
                        indexList.Add(t.vertex2);
                        indexList.Add(t.vertex3);

                        triangleList.Add(new Triangle(t.materialIndex, (ushort)(t.vertex1 + triangleListOffset), (ushort)(t.vertex2 + triangleListOffset), (ushort)(t.vertex3 + triangleListOffset)));
                    }
                }

                if (indexList.Count - previousIndexCount > 0)
                {
                    SubsetList.Add(new SharpSubSet(previousIndexCount, indexList.Count - previousIndexCount,
                                                   TextureManager.GetTextureFromDictionary(materialList[i]), materialList[i]));
                }

                previousIndexCount = indexList.Count();
            }

            triangleListOffset += vertexList1.Count;

            if (SubsetList.Count > 0)
            {
                VertexColoredTextured[] vertices = new VertexColoredTextured[vertexList1.Count];
                for (int i = 0; i < vertices.Length; i++)
                {
                    vertices[i] = new VertexColoredTextured(vertexList1[i], textCoordList[i], colorList[i]);
                }
                AddToMeshList(SharpMesh.Create(device, vertices, indexList.ToArray(), SubsetList));
            }
            else
            {
                AddToMeshList(null);
            }
        }
コード例 #13
0
 public double Distance(Vertex2 v)
 {
     return(Math.Sqrt((v.x - x) * (v.x - x) + (v.y - y) * (v.y - y)));
 }
コード例 #14
0
ファイル: Program.cs プロジェクト: addicted-by/MAI
    protected override void OnMainWindowLoad(object sender, EventArgs args)
    {
        base.VSPanelWidth = 260;
        base.ValueStorage.RightColWidth = 60;
        base.RenderDevice.VSync         = 1;

        #region Обработчики событий мыши и клавиатуры -------------------------------------------------------
        RenderDevice.MouseMoveWithLeftBtnDown  += (s, e) => { };
        RenderDevice.MouseMoveWithRightBtnDown += (s, e) => { };
        RenderDevice.MouseLeftBtnDown          += (s, e) => {
            DVector2 norm = NormalizeCoords(e.Location.X, e.Location.Y);

            double X = (norm.X - ShiftX) * Scale;
            double Y = (norm.Y - ShiftY) * Scale;

            text = $"{X}  {Y}";
            lock (locker)
            {
                vertices.Add(new Vertex2(X, Y));
            }
        };
        RenderDevice.MouseLeftBtnUp    += (s, e) => { };
        RenderDevice.MouseRightBtnDown += (s, e) => {
            DVector2 norm = NormalizeCoords(e.Location.X, e.Location.Y);

            double X = (norm.X - ShiftX) * Scale;
            double Y = (norm.Y - ShiftY) * Scale;

            foreach (Vertex2 v in vertices)
            {
                double dx = v.Point.X - X;
                double dy = v.Point.Y - Y;

                double r = Math.Sqrt(dx * dx + dy * dy);

                double radius = NormalizeDistance(VertexSize) * Scale;

                if (r < radius)
                {
                    ActiveVertex = v;
                    return;
                }
            }
        };

        RenderDevice.MouseRightBtnUp += (s, e) => {
            ActiveVertex = null;
            Pos          = new DVector2(0.0, 0.0);
        };
        RenderDevice.MouseMove += (s, e) => {
            MousePosition = new DVector2(e.Location.X + e.MovDeltaX, e.Location.Y + e.MovDeltaY);

            if (ActiveVertex != null)
            {
                double dx = NormalizeDistance(e.MovDeltaX) * Scale;
                double dy = NormalizeDistance(e.MovDeltaY) * Scale;

                if (e.MovDeltaX < 0)
                {
                    dx = -dx;
                }
                if (e.MovDeltaY > 0)
                {
                    dy = -dy;
                }

                double newX = ActiveVertex.Point.X + dx;
                double newY = ActiveVertex.Point.Y + dy;
                ActiveVertex.Point = new DVector2(newX, newY);

                Pos = ActiveVertex.Point;
            }
        };

        // Реализация управления клавиатурой
        RenderDevice.HotkeyRegister(Keys.Up, (s, e) => ShiftY                  += 0.05);
        RenderDevice.HotkeyRegister(Keys.Down, (s, e) => ShiftY                -= 0.05);
        RenderDevice.HotkeyRegister(Keys.Left, (s, e) => ShiftX                -= 0.05);
        RenderDevice.HotkeyRegister(Keys.Right, (s, e) => ShiftX               += 0.05);
        RenderDevice.HotkeyRegister(KeyMod.Shift, Keys.Up, (s, e) => ShiftY    += 0.1);
        RenderDevice.HotkeyRegister(KeyMod.Shift, Keys.Down, (s, e) => ShiftY  -= 0.1);
        RenderDevice.HotkeyRegister(KeyMod.Shift, Keys.Left, (s, e) => ShiftX  -= 0.1);
        RenderDevice.HotkeyRegister(KeyMod.Shift, Keys.Right, (s, e) => ShiftX += 0.1);

        RenderDevice.HotkeyRegister(Keys.C, (s, e) => {
            DVector2 vec = NormalizeCoords(MousePosition.X, MousePosition.Y);

            ShiftX = -vec.X + ShiftX;
            ShiftY = -vec.Y + ShiftY;
        });


        RenderDevice.MouseWheel += (s, e) => {
            float DeltaScale = -e.Delta / 10000.0f;
            Scale += DeltaScale;
        };
        RenderDevice.MouseMoveWithMiddleBtnDown += (s, e) => {
            double dx = NormalizeDistance(e.MovDeltaX);
            double dy = NormalizeDistance(e.MovDeltaY);

            if (e.MovDeltaX < 0)
            {
                dx = -dx;
            }
            if (e.MovDeltaY > 0)
            {
                dy = -dy;
            }

            ShiftX += dx;
            ShiftY += dy;
        };

        #endregion

        spline = new CatmullRomSpline(vertices, false, 1.0 / ApproxLevel);

        #region  Инициализация OGL и параметров рендера -----------------------------------------------------
        RenderDevice.AddScheduleTask((gl, s) =>
        {
            gl.FrontFace(OpenGL.GL_CCW);
            gl.Enable(OpenGL.GL_CULL_FACE);
            gl.CullFace(OpenGL.GL_BACK);

            gl.ClearColor(0, 0, 0, 0);

            gl.Enable(OpenGL.GL_DEPTH_TEST);
            gl.DepthFunc(OpenGL.GL_LEQUAL);
            gl.ClearDepth(1.0f);    // 0 - ближе, 1 - далеко
            gl.ClearStencil(0);
        });
        #endregion

        #region Обновление матрицы проекции при изменении размеров окна и запуске приложения ----------------
        RenderDevice.Resized += (s, e) =>
        {
            var gl = e.gl;

            UpdateProjectionMatrix(gl);
        };
        #endregion
    }
コード例 #15
0
 public VoronoiLink(Vertex2 p1, Vertex2 p2)
 {
     point1 = p1;
     point2 = p2;
 }
コード例 #16
0
 public bool ContainsPoint(Vertex2 p)
 {
     return(point1 == p || point2 == p);
 }
コード例 #17
0
ファイル: Map.cs プロジェクト: olemstrom/the-morko
 public bool IsInside(Vertex2 v)
 {
     int MapSize = CellCount;
     return  v.x < MapSize && v.x >= 0 && v.y < MapSize && v.y >= 0;
 }
コード例 #18
0
ファイル: Map.cs プロジェクト: olemstrom/the-morko
    public void Generate()
    {
        int tries = 0;
        while (Rooms.Count < RoomCount) {
            tries++;
            if(tries > RoomCount + 1000*1000) break;
            Random rand = new Random();
            int width = rand.Next(MinRoomSize, MaxRoomSize);
            int height = rand.Next(MinRoomSize, MaxRoomSize);
            int x = rand.Next(CellCount);
            int y = rand.Next(CellCount);

            Room room = new Room(width, height, x, y);
            if(IsInside (room) && !Overlaps(room, 2)) AddRoom (room);
        }
        //AddRoom (new Room (2, 2, 0, 0));

        RoomCount = Rooms.Count;

        Vertex2[] vertices = new Vertex2[Rooms.Count];

        int index = 0;
        foreach (Room r in Rooms) {
            vertices[index++] = r.GetCenterPoint();
        }

        voronoiMesh = VoronoiMesh.Create<Vertex2, Cell2> (vertices);
        foreach (var edge in voronoiMesh.Vertices) {
            int x1 = (int)edge.Vertices[0].x;
            int y1 = (int)edge.Vertices[0].y;
            int x2 = (int)edge.Vertices[1].x;
            int y2 = (int)edge.Vertices[1].y;
            edges.Add (new Edge(new Vertex2(x1, y1), new Vertex2(x2, y2)));

            x1 = x2;
            y1 = y2;
            x2 = (int)edge.Vertices[2].x;
            y2 = (int)edge.Vertices[2].y;
            edges.Add (new Edge(new Vertex2(x1, y1), new Vertex2(x2, y2)));

            x1 = x2;
            y1 = y2;
            x2 = (int)edge.Vertices[0].x;
            y2 = (int)edge.Vertices[0].y;
            edges.Add (new Edge(new Vertex2(x1, y1), new Vertex2(x2, y2)));
        }

        Edge[] edgeAry = new Edge[edges.Count];
        edges.CopyTo (edgeAry);

        c = new ConnectionGraph (new List<Edge>(edges));
        allEdges = edges;
        edges = c.GetEdges ();

        PathGenerator p = new PathGenerator (this);
        Edge[] pedge = new Edge[edges.Count];
        edges.CopyTo (pedge);
        Array.Sort (pedge);
        foreach (var edge in edges) {
            p.AddPath(edge);
        }

        p.GrowOpen ();
        savePaths (p);

        ptiles = p.tiles;
    }
コード例 #19
0
ファイル: Map.cs プロジェクト: olemstrom/the-morko
    public bool IsInside(Room r, Vertex2 point)
    {
        int rx = r.GetX ();
        int ry = r.GetY ();
        int rw = r.GetWidth ();
        int rh = r.GetHeight ();

        bool isx = point.x >= rx && point.x <= rx + rw;
        bool isy = point.y >= ry && point.y < ry + rh;

        return isx && isy;
    }
コード例 #20
0
ファイル: Map.cs プロジェクト: olemstrom/the-morko
    public Room GetRoom(Vertex2 point)
    {
        foreach(Room r in Rooms) {
            bool isInside = IsInside (r, point);
            if(isInside) return r;
        }

        return null;
    }
コード例 #21
0
ファイル: Triangle.cs プロジェクト: tricyclelad/HW1-OO
 public void Move(double deltaX, double deltaY)
 {
     Vertex1.Move(deltaX, deltaY);
     Vertex2.Move(deltaX, deltaY);
     Vertex3.Move(deltaX, deltaY);
 }
コード例 #22
0
 private void dfs(Vertex2 v, Vertex2 prev, List<Vertex2> visited)
 {
     HashSet<Vertex2> c = connectionMap[v];
     foreach (Vertex2 w in connectionMap[v]) {
         if(!visited.Contains(w) && (prev == null || !prev.Equals (w))) {
             visited.Add (w);
             dfs (w, v, visited);
         }
     }
 }
コード例 #23
0
    public static IEnumerable <Vertex2> FindPath(this IEnumerable <VoronoiLink> data, Vertex2 source, Vertex2 target, bool bestFirst = true)
    {
        List <DijkstraVertex> members = new List <DijkstraVertex> {
            new DijkstraVertex {
                Vertex = source
            }
        };
        List <Vertex2> searched = new List <Vertex2>();

        while (true)
        {
            var v = members.Where(m => !searched.Contains(m.Vertex)).OrderBy(m => bestFirst?m.Heuristic:m.Cost).FirstOrDefault();
            if (v == null)
            {
                return(null);                       // No vertices left unsearched
            }
            if (v.Vertex == target)
            {
                Stack <DijkstraVertex> path = new Stack <DijkstraVertex>();
                path.Push(v);
                while (path.Peek().Parent != null)
                {
                    path.Push(path.Peek().Parent);
                }
                return(path.Select(dv => dv.Vertex).ToList());
            }
            members.AddRange(data.Where(l => l.point1 == v.Vertex).Select(l => l.point2).Concat(data.Where(l => l.point2 == v.Vertex).Select(l => l.point1))
                             .Where(n => members.All(m => m.Vertex != n)).Select(n =>
            {
                var c = new DijkstraVertex {
                    Parent = v, Vertex = n, Cost = v.Cost + v.Vertex.Distance(n)
                };
                if (bestFirst)
                {
                    c.Heuristic = c.Cost + c.Vertex.Distance(target);
                }
                return(c);
            }));
            searched.Add(v.Vertex);
        }
    }
コード例 #24
0
 public TriangleFace(Vertex3 v1, Vertex3 v2, Vertex3 v3, Vertex2 vt1, Vertex2 vt2, Vertex2 vt3)
 {
     V1  = v1;
     V2  = v2;
     V3  = v3;
     VT1 = vt1;
     VT2 = vt2;
     VT3 = vt3;
 }
コード例 #25
0
    public static IEnumerable <Vertex2> ConnectedRegion(this IEnumerable <VoronoiLink> data, Vertex2 v)
    {
        List <Vertex2> members = new List <Vertex2>();

        members.Add(v);
        while (true)
        {
            int lastCount = members.Count;
            // For each member, add all vertices that are connected to it via a line but are not already a member
            foreach (Vertex2 m in members.ToArray())
            {
                members.AddRange(data.Where(l => l.point1 == m).Select(l => l.point2)
                                 .Concat(data.Where(l => l.point2 == m).Select(l => l.point1))
                                 .Where(n => !members.Contains(n)));
            }
            // If we have stopped finding neighbors, stop traversing
            if (members.Count == lastCount)
            {
                return(members);
            }
        }
    }
コード例 #26
0
ファイル: Program.cs プロジェクト: addicted-by/MAI
 public void Prolong(Vertex2 v)
 {
     vertices.Add(v);
 }
コード例 #27
0
        private void AddGeometry(SharpDevice device, Geometry_000F g, Matrix transformMatrix)
        {
            List <string> MaterialList = new List <string>();

            foreach (Material_0007 m in g.materialList.materialList)
            {
                if (m.texture != null)
                {
                    string textureName = m.texture.diffuseTextureName.stringString;
                    if (!MaterialList.Contains(textureName))
                    {
                        MaterialList.Add(textureName);
                    }
                }
                else
                {
                    MaterialList.Add(DefaultTexture);
                }
            }

            if ((g.geometryStruct.geometryFlags2 & GeometryFlags2.isNativeGeometry) != 0)
            {
                AddNativeData(device, g.geometryExtension, MaterialList, transformMatrix);
                return;
            }

            List <VertexColoredTextured> vertexList = new List <VertexColoredTextured>();

            if ((g.geometryStruct.geometryFlags & GeometryFlags.hasVertexPositions) != 0)
            {
                foreach (Vertex3 v in g.geometryStruct.morphTargets[0].vertices)
                {
                    Vector3 Position = (Vector3)Vector3.Transform(new Vector3(v.X, v.Y, v.Z), transformMatrix);

                    vertexList.Add(new VertexColoredTextured(Position, new Vector2(), SharpDX.Color.White));
                    vertexListG.Add(Position);
                }
            }

            if ((g.geometryStruct.geometryFlags & GeometryFlags.hasVertexColors) != 0)
            {
                for (int i = 0; i < vertexList.Count; i++)
                {
                    RenderWareFile.Color c = g.geometryStruct.vertexColors[i];

                    VertexColoredTextured v = vertexList[i];
                    v.Color       = new SharpDX.Color(c.R, c.G, c.B, c.A);
                    vertexList[i] = v;
                }
            }
            else
            {
                for (int i = 0; i < vertexList.Count; i++)
                {
                    VertexColoredTextured v = vertexList[i];
                    v.Color       = SharpDX.Color.White;
                    vertexList[i] = v;
                }
            }

            if ((g.geometryStruct.geometryFlags & GeometryFlags.hasTextCoords) != 0)
            {
                for (int i = 0; i < vertexList.Count; i++)
                {
                    Vertex2 tc = g.geometryStruct.textCoords[i];

                    VertexColoredTextured v = vertexList[i];
                    v.TextureCoordinate = new Vector2(tc.X, tc.Y);
                    vertexList[i]       = v;
                }
            }

            List <SharpSubSet> SubsetList = new List <SharpSubSet>();
            List <int>         indexList  = new List <int>();
            int previousIndexCount        = 0;

            for (int i = 0; i < MaterialList.Count; i++)
            {
                foreach (Triangle t in g.geometryStruct.triangles)
                {
                    if (t.materialIndex == i)
                    {
                        indexList.Add(t.vertex1);
                        indexList.Add(t.vertex2);
                        indexList.Add(t.vertex3);

                        triangleList.Add(new Triangle(t.materialIndex, (ushort)(t.vertex1 + triangleListOffset), (ushort)(t.vertex2 + triangleListOffset), (ushort)(t.vertex3 + triangleListOffset)));
                    }
                }

                if (indexList.Count - previousIndexCount > 0)
                {
                    SubsetList.Add(new SharpSubSet(previousIndexCount, indexList.Count - previousIndexCount,
                                                   TextureManager.GetTextureFromDictionary(MaterialList[i]), MaterialList[i]));
                }

                previousIndexCount = indexList.Count();
            }

            triangleListOffset += vertexList.Count;

            if (SubsetList.Count > 0)
            {
                meshList.Add(SharpMesh.Create(device, vertexList.ToArray(), indexList.ToArray(), SubsetList));
            }
        }
コード例 #28
0
        public NativeDataGC(BinaryReader binaryReader, bool fixFlag)
        {
            headerLenght = binaryReader.ReadInt32();                 // counting from after dataLenght
            dataLenght   = binaryReader.ReadInt32();                 // counting from after headerEndPosition

            long nativeDataStart = binaryReader.BaseStream.Position; // from here the file is little endian

            unknown1          = Switch(binaryReader.ReadInt16());
            meshIndex         = Switch(binaryReader.ReadInt16());
            unknown2          = Switch(binaryReader.ReadInt32());
            declarationAmount = Switch(binaryReader.ReadInt32());

            declarations = new Declaration[declarationAmount];
            for (int i = 0; i < declarationAmount; i++)
            {
                declarations[i] = new Declaration()
                {
                    startOffset     = Switch(binaryReader.ReadInt32()),
                    declarationType = (Declarations)binaryReader.ReadByte(),
                    sizeOfEntry     = binaryReader.ReadByte(),
                    byteType        = (ByteTypes)binaryReader.ReadByte(),
                    unknown2        = binaryReader.ReadByte()
                };
            }

            List <TriangleDeclaration> list = new List <TriangleDeclaration>();

            foreach (int i in MaterialList)
            {
                list.Add(new TriangleDeclaration()
                {
                    startOffset      = Switch(binaryReader.ReadInt32()),
                    size             = Switch(binaryReader.ReadInt32()),
                    MaterialIndex    = i,
                    TriangleListList = new List <TriangleList>()
                });
            }

            triangleDeclarations = list.ToArray();

            long headerEndPosition = binaryReader.BaseStream.Position;

            for (int i = 0; i < triangleDeclarations.Length; i++)
            {
                binaryReader.BaseStream.Position = headerEndPosition + triangleDeclarations[i].startOffset;

                while (!(binaryReader.BaseStream.Position == headerEndPosition + triangleDeclarations[i].startOffset + triangleDeclarations[i].size))
                {
                    byte setting = binaryReader.ReadByte();

                    if (setting == 0)
                    {
                        continue;
                    }
                    else if (setting != 0x98)
                    {
                        throw new Exception();
                    }

                    byte setting2 = binaryReader.ReadByte();

                    byte         entryAmount = binaryReader.ReadByte();
                    List <int[]> entries     = new List <int[]>();

                    for (int j = 0; j < entryAmount; j++)
                    {
                        List <int> objectList = new List <int>();

                        if (fixFlag)
                        {
                            binaryReader.BaseStream.Position += 1;
                        }

                        for (int k = 0; k < declarationAmount; k++)
                        {
                            if (declarations[k].byteType == ByteTypes.OneByte)
                            {
                                objectList.Add(binaryReader.ReadByte());
                            }
                            else if (declarations[k].byteType == ByteTypes.TwoBytes)
                            {
                                objectList.Add(Switch(binaryReader.ReadInt16()));
                            }
                            else
                            {
                                throw new Exception();
                            }
                        }

                        entries.Add(objectList.ToArray());
                    }

                    triangleDeclarations[i].TriangleListList.Add(new TriangleList()
                    {
                        setting = setting, setting2 = setting2, entryAmount = entryAmount, entries = entries
                    });
                }
            }

            for (int d = 0; d < declarations.Count(); d++)
            {
                binaryReader.BaseStream.Position = headerEndPosition + declarations[d].startOffset;

                byte[] data;
                if (d + 1 < declarations.Count())
                {
                    data = binaryReader.ReadBytes(declarations[d + 1].startOffset - declarations[d].startOffset);
                }
                else
                {
                    data = binaryReader.ReadBytes(dataLenght - declarations[d].startOffset);
                }

                declarations[d].entryList = new List <object>();

                if (declarations[d].declarationType == Declarations.Vertex)
                {
                    for (int i = 0; i + 11 < data.Count(); i += 12)
                    {
                        Vertex3 v = new Vertex3(
                            BitConverter.ToSingle(new byte[] { data[i + 3], data[i + 2], data[i + 1], data[i] }, 0),
                            BitConverter.ToSingle(new byte[] { data[i + 7], data[i + 6], data[i + 5], data[i + 4] }, 0),
                            BitConverter.ToSingle(new byte[] { data[i + 11], data[i + 10], data[i + 9], data[i + 8] }, 0));
                        declarations[d].entryList.Add(v);
                    }
                }
                else if (declarations[d].declarationType == Declarations.Normal)
                {
                    for (int i = 0; i + 11 < data.Count(); i += 12)
                    {
                        Vertex3 v = new Vertex3(
                            BitConverter.ToSingle(new byte[] { data[i + 3], data[i + 2], data[i + 1], data[i] }, 0),
                            BitConverter.ToSingle(new byte[] { data[i + 7], data[i + 6], data[i + 5], data[i + 4] }, 0),
                            BitConverter.ToSingle(new byte[] { data[i + 11], data[i + 10], data[i + 9], data[i + 8] }, 0));
                        declarations[d].entryList.Add(v);
                    }
                }
                else if (declarations[d].declarationType == Declarations.Color)
                {
                    for (int i = 0; i < data.Count(); i += 0x4)
                    {
                        Color v = new Color(new byte[] { data[i], data[i + 1], data[i + 2], data[i + 3] });
                        declarations[d].entryList.Add(v);
                    }
                }
                else if (declarations[d].declarationType == Declarations.TextCoord)
                {
                    for (int i = 0; i < data.Count(); i += 0x8)
                    {
                        Vertex2 v = new Vertex2(
                            BitConverter.ToSingle(new byte[] { data[i + 3], data[i + 2], data[i + 1], data[i] }, 0),
                            BitConverter.ToSingle(new byte[] { data[i + 7], data[i + 6], data[i + 5], data[i + 4] }, 0));
                        declarations[d].entryList.Add(v);
                    }
                }
            }
        }
コード例 #29
0
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.DarkSlateGray);

            var mouseState = Mouse.GetState(this.Window);


            base.Draw(gameTime);

            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.BlendState        = BlendState.Opaque;

            _Drawing2D.Begin(800, _UseQuadrant1 ? -600 : 600, true);

            var vp = _Drawing2D.TransformInverse(new Point2(mouseState.Position.X, mouseState.Position.Y));

            _Drawing2D.DrawLine((0, 0), (800, 600), 2, COLOR.Red);
            _Drawing2D.DrawAsset(System.Numerics.Matrix3x2.Identity, _Sprites);
            _Drawing2D.DrawAsset(System.Numerics.Matrix3x2.Identity, new _Scene2D());
            _Drawing2D.DrawAsset(System.Numerics.Matrix3x2.Identity, _DynTex);
            _Drawing2D.DrawLine((800, 0), (0, 600), 2, COLOR.Red);

            if (_Drawing2D.TryGetBackendViewportBounds(out var viewportBounds))
            {
                viewportBounds.Inflate(-10, -10);
                _Drawing2D.DrawRectangle(viewportBounds, (COLOR.Yellow, 2));
            }

            if (_Drawing2D.TryGetQuadrant(out var quadrant))
            {
                _Drawing2D.DrawTextLine((10, 70), $"{quadrant}", 15, COLOR.White);
            }

            _Drawing2D.DrawTextLine((10, 20), $"{(int)vp.X} {(int)vp.Y}", 15, COLOR.White);

            // Draw with IMeshCanvas2D extended API

            var vertices = new Vertex2[4];

            vertices[0] = new Vertex2((0, 0), (0, 0));
            vertices[1] = new Vertex2((50, 0), (1, 0));
            vertices[2] = new Vertex2((50, 50), (1, 1));
            vertices[3] = new Vertex2((0, 50), (0, 1));

            var svc = _Drawing2D.CreateTransformed2D(System.Numerics.Matrix3x2.CreateTranslation(600, 300)) as IServiceProvider;

            var xformed = svc.GetService(typeof(IMeshCanvas2D)) as IMeshCanvas2D;

            xformed?.DrawMeshPrimitive(vertices, new int[] { 0, 1, 2, 0, 2, 3 }, "Assets\\Tiles.png");

            // draw tiles with half pixel

            var tile1 = ImageSource.Create("Assets\\Tiles.png", (16, 64), (16, 16), (5, 5)).WithScale(4);
            var tile2 = ImageSource.Create("Assets\\Tiles.png", (16, 64), (16, 16), (5, 5)).WithScale(4).WithExpandedSource(-3.5f);

            _Drawing2D.DrawImage(System.Numerics.Matrix3x2.CreateTranslation(600, 500), tile1);
            _Drawing2D.DrawImage(System.Numerics.Matrix3x2.CreateTranslation(600 + 65, 500), tile2);

            var qrhead = ImageSource.Create((typeof(Game1).Assembly, "MonoGameDemo.Assets.qrhead.jpg"), (0, 0), (255, 255), (128, 128));

            _Drawing2D.DrawImage(System.Numerics.Matrix3x2.CreateScale(0.25f) * System.Numerics.Matrix3x2.CreateTranslation(125, 50), qrhead);

            _Drawing2D.DrawCircle((600, 100), 50, (COLOR.Yellow, 2));

            _Drawing2D.End();
        }
コード例 #30
0
        private void AddAtomic(SharpDevice device, AtomicSector_0009 AtomicSector, List <string> MaterialList)
        {
            if (AtomicSector.atomicSectorStruct.isNativeData)
            {
                AddNativeData(device, AtomicSector.atomicSectorExtension, MaterialList, Matrix.Identity);
                return;
            }

            List <VertexColoredTextured> vertexList = new List <VertexColoredTextured>();

            foreach (Vertex3 v in AtomicSector.atomicSectorStruct.vertexArray)
            {
                vertexList.Add(new VertexColoredTextured(new Vector3(v.X, v.Y, v.Z), new Vector2(), new SharpDX.Color()));
                vertexListG.Add(new Vector3(v.X, v.Y, v.Z));
            }

            for (int i = 0; i < vertexList.Count; i++)
            {
                RenderWareFile.Color c = AtomicSector.atomicSectorStruct.colorArray[i];

                VertexColoredTextured v = vertexList[i];
                v.Color       = new SharpDX.Color(c.R, c.G, c.B, c.A);
                vertexList[i] = v;
            }

            for (int i = 0; i < vertexList.Count; i++)
            {
                Vertex2 tc = AtomicSector.atomicSectorStruct.uvArray[i];

                VertexColoredTextured v = vertexList[i];
                v.TextureCoordinate = new Vector2(tc.X, tc.Y);
                vertexList[i]       = v;
            }

            List <SharpSubSet> SubsetList = new List <SharpSubSet>();
            List <int>         indexList  = new List <int>();
            int previousIndexCount        = 0;

            for (int i = 0; i < MaterialList.Count; i++)
            {
                for (int j = 0; j < AtomicSector.atomicSectorStruct.triangleArray.Length; j++) // each (Triangle t in AtomicSector.atomicStruct.triangleArray)
                {
                    Triangle t = AtomicSector.atomicSectorStruct.triangleArray[j];
                    if (t.materialIndex == i)
                    {
                        indexList.Add(t.vertex1);
                        indexList.Add(t.vertex2);
                        indexList.Add(t.vertex3);

                        triangleList.Add(new Triangle(t.materialIndex, (ushort)(t.vertex1 + triangleListOffset), (ushort)(t.vertex2 + triangleListOffset), (ushort)(t.vertex3 + triangleListOffset)));
                    }
                }

                if (indexList.Count - previousIndexCount > 0)
                {
                    SubsetList.Add(new SharpSubSet(previousIndexCount, indexList.Count - previousIndexCount,
                                                   TextureManager.GetTextureFromDictionary(MaterialList[i]), MaterialList[i]));
                }

                previousIndexCount = indexList.Count();
            }

            triangleListOffset += AtomicSector.atomicSectorStruct.vertexArray.Length;

            if (SubsetList.Count > 0)
            {
                AddToMeshList(SharpMesh.Create(device, vertexList.ToArray(), indexList.ToArray(), SubsetList));
            }
        }
コード例 #31
0
 public float Distance(Vertex2 v)
 {
     return(length(StoredPosition - v.StoredPosition));
 }
コード例 #32
0
ファイル: PathGenerator.cs プロジェクト: olemstrom/the-morko
 private void EnablePoint(Vertex2 v)
 {
     tiles [v.y, v.x] = PathGenerator.OPEN_ENDPOINT;
 }
コード例 #33
0
 public bool Contains(Vertex vertex)
 {
     return(Vertex1.Equals(vertex) || Vertex2.Equals(vertex));
 }
コード例 #34
0
ファイル: PathGenerator.cs プロジェクト: olemstrom/the-morko
 private bool IsAccessible(Vertex2 v)
 {
     int state = tiles[v.y, v.x];
     return state == PathGenerator.OPEN_ENDPOINT || state == PathGenerator.OPEN_NOT_ENDPOINT;
 }
コード例 #35
0
ファイル: Edge.cs プロジェクト: olemstrom/the-morko
 public bool IsConnected(Vertex2 e)
 {
     return  start.Equals (e) || end.Equals(e);
 }
コード例 #36
0
ファイル: PathGenerator.cs プロジェクト: olemstrom/the-morko
 public PathNode(double cost, Vertex2 location)
 {
     this.cost = cost;
     this.location = location;
 }
コード例 #37
0
 private bool hasCycle(Vertex2 root)
 {
     var visited = new List<Vertex2> ();
     dfs (root, null, visited);
     bool cycle = visited.Contains (root);
     return cycle;
 }
コード例 #38
0
        /*IEnumerable<Vertex2> EmitQuad(int ID, Vector2 Pos, Vector2 Size, Vector2 UV, Vector2 UVSize) {
         *      //Console.WriteLine("{0} - {1} .. {2}", ID, Pos, Pos + Size);
         *
         *      Boxes.Add(new Tuple<int, AABB>(ID, new AABB(Pos, Size)));
         *      return Vertex2.CreateQuad(Pos, Size, UV, UVSize, Color);
         * }*/

        IEnumerable <Vertex2> EmitQuad2(int ID, Vector2 Pos, Vector2 Size, Vector2 UVPos, Vector2 UVSize)
        {
            Boxes.Add(new Tuple <int, AABB>(ID, new AABB(Pos, Size)));
            return(Vertex2.CreateQuad(Pos, Size, UVPos / Texture.Size, UVSize / Texture.Size));
        }
コード例 #39
0
        public GeometryStruct_0001 Read(BinaryReader binaryReader)
        {
            sectionIdentifier = Section.Struct;
            sectionSize       = binaryReader.ReadInt32();
            renderWareVersion = binaryReader.ReadInt32();

            if (ReadFileMethods.treatStuffAsByteArray)
            {
                sectionData = binaryReader.ReadBytes(sectionSize);
                return(this);
            }

            long startSectionPosition = binaryReader.BaseStream.Position;

            geometryFlags   = (GeometryFlags)binaryReader.ReadInt16();
            geometryFlags2  = (GeometryFlags2)binaryReader.ReadInt16();
            numTriangles    = binaryReader.ReadInt32();
            numVertices     = binaryReader.ReadInt32();
            numMorphTargets = binaryReader.ReadInt32();

            if (Shared.UnpackLibraryVersion(renderWareVersion) < 0x34000)
            {
                ambient  = binaryReader.ReadSingle();
                specular = binaryReader.ReadSingle();
                diffuse  = binaryReader.ReadSingle();
            }

            if ((geometryFlags2 & GeometryFlags2.isNativeGeometry) != 0)
            {
                binaryReader.BaseStream.Position = startSectionPosition + sectionSize;
                return(this);
            }

            if ((geometryFlags & GeometryFlags.hasVertexColors) != 0)
            {
                vertexColors = new Color[numVertices];
                for (int i = 0; i < numVertices; i++)
                {
                    vertexColors[i] = new Color()
                    {
                        R = binaryReader.ReadByte(),
                        G = binaryReader.ReadByte(),
                        B = binaryReader.ReadByte(),
                        A = binaryReader.ReadByte()
                    };
                }
            }

            if ((geometryFlags & GeometryFlags.hasTextCoords) != 0)
            {
                textCoords = new Vertex2[numVertices];
                for (int i = 0; i < numVertices; i++)
                {
                    textCoords[i] = new Vertex2()
                    {
                        X = binaryReader.ReadSingle(),
                        Y = binaryReader.ReadSingle()
                    };
                }

                if ((geometryFlags & GeometryFlags.hasTextCoords2) != 0)
                {
                    binaryReader.BaseStream.Position += numVertices * 8;
                }
            }
            else if ((geometryFlags & GeometryFlags.hasTextCoords2) != 0)
            {
                textCoords = new Vertex2[numVertices * 2];
                for (int i = 0; i < numVertices * 2; i++)
                {
                    textCoords[i] = new Vertex2()
                    {
                        X = binaryReader.ReadSingle(),
                        Y = binaryReader.ReadSingle()
                    };
                }
            }

            triangles = new Triangle[numTriangles];
            for (int i = 0; i < numTriangles; i++)
            {
                triangles[i] = new Triangle()
                {
                    vertex2       = binaryReader.ReadUInt16(),
                    vertex1       = binaryReader.ReadUInt16(),
                    materialIndex = binaryReader.ReadUInt16(),
                    vertex3       = binaryReader.ReadUInt16()
                };
            }

            morphTargets = new MorphTarget[numMorphTargets];
            for (int i = 0; i < numMorphTargets; i++)
            {
                MorphTarget m = new MorphTarget();

                m.sphereCenter.X = binaryReader.ReadSingle();
                m.sphereCenter.Y = binaryReader.ReadSingle();
                m.sphereCenter.Z = binaryReader.ReadSingle();
                m.radius         = binaryReader.ReadSingle();
                m.hasVertices    = binaryReader.ReadInt32();
                m.hasNormals     = binaryReader.ReadInt32();

                if (m.hasVertices != 0)
                {
                    m.vertices = new Vertex3[numVertices];
                    for (int j = 0; j < numVertices; j++)
                    {
                        m.vertices[j] = new Vertex3()
                        {
                            X = binaryReader.ReadSingle(),
                            Y = binaryReader.ReadSingle(),
                            Z = binaryReader.ReadSingle()
                        };
                    }
                }

                if (m.vertices == null)
                {
                    throw new Exception();
                }

                if (m.hasNormals != 0)
                {
                    m.normals = new Vertex3[numVertices];
                    for (int j = 0; j < numVertices; j++)
                    {
                        m.normals[j] = new Vertex3()
                        {
                            X = binaryReader.ReadSingle(),
                            Y = binaryReader.ReadSingle(),
                            Z = binaryReader.ReadSingle()
                        };
                    }
                }

                morphTargets[i] = m;
            }

            return(this);
        }
コード例 #40
0
ファイル: PathGenerator.cs プロジェクト: olemstrom/the-morko
    private void CreatePath(Vertex2 start)
    {
        PriorityQueue frontier = new PriorityQueue ();
        frontier.Add (0, start);
        Dictionary<Vertex2, Vertex2> from = new Dictionary<Vertex2, Vertex2> ();
        Dictionary<Vertex2, double> cost = new Dictionary<Vertex2, double> ();
        cost [start] = 0;
        from [start] = null;
        Vertex2 end = null;

        while (!frontier.IsEmpty()) {
            var current = frontier.GetMin ();
            if(IsGoal(current)) {
                end = current;
                break;
            }

            foreach(PathNode neighbor in GetNeighbors(current)) {
                Vertex2 vNeighbor = neighbor.location;
                double newCost = cost[current] + neighbor.cost;
                if(!cost.ContainsKey(vNeighbor) || newCost < cost[vNeighbor]) {
                    cost[vNeighbor] = newCost;
                    frontier.Add(newCost, vNeighbor);
                    from[vNeighbor] = current;
                }
            }
        }

        if (end != null) {
            Vertex2 current = end;
            while(!current.Equals(start)) {
                EnablePoint(current);
                current = from[current];
            }
        }
    }
コード例 #41
0
 private static float Cross2(Vertex2 a, Vertex2 b)
 {
     return(a.X * b.Y - a.Y * b.X);
 }
コード例 #42
0
 private void DrawLine(Vertex2 v0, Vertex2 v1)
 {
     GL.Vertex3(v0.X, v0.Y, 0.0f);
     GL.Vertex3(v1.X, v1.Y, 0.0f);
 }
コード例 #43
0
        //Здесь мы загружаем изображение
        private void glControl_Load(object sender, EventArgs e)
        {
            loaded = true;
            Bitmap heightMapImage = new Bitmap(Image.FromFile("Ландшафт.jpg"));
            int    vIndex         = 0; //Вспомогательная переменная, которая поможет при записи двумерных данных последовательно в одномерный массив
            //Количество вершин
            int verticesQuantity = (heightMapImage.Width - 1) * (heightMapImage.Height - 1) * 6 + heightMapImage.Width * 6 * 2 + heightMapImage.Height * 6 * 2;

            Vertices = new Vertex[verticesQuantity];
            float heightMul = 0.25f; //Множитель высоты

            //Загружаем нашу карту высот
            for (int x = 0; x < heightMapImage.Width - 1; x++)
            {
                for (int z = 0; z < heightMapImage.Height - 1; z++)
                {
                    Vertices[vIndex++] = new Vertex(x, (float)heightMapImage.GetPixel(x, z).R *heightMul, z);
                    Vertices[vIndex++] = new Vertex(x + 1, (float)heightMapImage.GetPixel(x + 1, z + 1).R *heightMul, z + 1);
                    Vertices[vIndex++] = new Vertex(x + 1, (float)heightMapImage.GetPixel(x + 1, z).R *heightMul, z);

                    Vertices[vIndex++] = new Vertex(x, (float)heightMapImage.GetPixel(x, z).R *heightMul, z);
                    Vertices[vIndex++] = new Vertex(x, (float)heightMapImage.GetPixel(x, z + 1).R *heightMul, z + 1);
                    Vertices[vIndex++] = new Vertex(x + 1, (float)heightMapImage.GetPixel(x + 1, z + 1).R *heightMul, z + 1);
                }
            }

            //Этот блок можно убрать в пользу производительности
            //Здесь генерируются стенки карты (для красоты)
            for (int x = 0; x < heightMapImage.Width - 1; x++)
            {
                Vertices[vIndex++] = new Vertex(x, (float)heightMapImage.GetPixel(x, 0).R *heightMul, 0);
                Vertices[vIndex++] = new Vertex(x + 1, (float)heightMapImage.GetPixel(x + 1, 0).R *heightMul, 0);
                Vertices[vIndex++] = new Vertex(x + 1, 0, 0);


                Vertices[vIndex++] = new Vertex(x, (float)heightMapImage.GetPixel(x, 0).R *heightMul, 0);
                Vertices[vIndex++] = new Vertex(x + 1, 0, 0);
                Vertices[vIndex++] = new Vertex(x, 0, 0);
            }

            for (int x = 0; x < heightMapImage.Width - 1; x++)
            {
                Vertices[vIndex++] = new Vertex(x, (float)heightMapImage.GetPixel(x, heightMapImage.Height - 1).R *heightMul, heightMapImage.Height - 1);
                Vertices[vIndex++] = new Vertex(x + 1, 0, heightMapImage.Height - 1);
                Vertices[vIndex++] = new Vertex(x + 1, (float)heightMapImage.GetPixel(x + 1, heightMapImage.Height - 1).R *heightMul, heightMapImage.Height - 1);


                Vertices[vIndex++] = new Vertex(x, (float)heightMapImage.GetPixel(x, heightMapImage.Height - 1).R *heightMul, heightMapImage.Height - 1);
                Vertices[vIndex++] = new Vertex(x, 0, heightMapImage.Height - 1);
                Vertices[vIndex++] = new Vertex(x + 1, 0, heightMapImage.Height - 1);
            }

            for (int z = 0; z < heightMapImage.Height - 1; z++)
            {
                Vertices[vIndex++] = new Vertex(0, (float)heightMapImage.GetPixel(0, z).R *heightMul, z);
                Vertices[vIndex++] = new Vertex(0, 0, z + 1);
                Vertices[vIndex++] = new Vertex(0, (float)heightMapImage.GetPixel(0, z + 1).R *heightMul, z + 1);

                Vertices[vIndex++] = new Vertex(0, (float)heightMapImage.GetPixel(0, z).R *heightMul, z);
                Vertices[vIndex++] = new Vertex(0, 0, z);
                Vertices[vIndex++] = new Vertex(0, 0, z + 1);
            }

            for (int z = 0; z < heightMapImage.Height - 1; z++)
            {
                Vertices[vIndex++] = new Vertex(heightMapImage.Width - 1, (float)heightMapImage.GetPixel(heightMapImage.Width - 1, z).R *heightMul, z);
                Vertices[vIndex++] = new Vertex(heightMapImage.Width - 1, (float)heightMapImage.GetPixel(heightMapImage.Width - 1, z + 1).R *heightMul, z + 1);
                Vertices[vIndex++] = new Vertex(heightMapImage.Width - 1, 0, z + 1);


                Vertices[vIndex++] = new Vertex(heightMapImage.Width - 1, (float)heightMapImage.GetPixel(heightMapImage.Width - 1, z).R *heightMul, z);
                Vertices[vIndex++] = new Vertex(heightMapImage.Width - 1, 0, z + 1);
                Vertices[vIndex++] = new Vertex(heightMapImage.Width - 1, 0, z);
            }

            //Получившийся массив вершин записывается в буфер OpenGL
            GL.GenBuffers(1, out ID_VBO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, ID_VBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(Vertices.Length * Vertex.Stride), Vertices, BufferUsageHint.StaticDraw);
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);

            //Расчитываем нормаль для каждого треугольника ландшафта
            Normals = new Vertex[verticesQuantity];
            for (int index = 0; index < Vertices.Length; index += 3)
            {
                //По трём точкам находим нормаль к плоскости и записываем её в массив
                Normals[index]     = new Vertex(Vector3.Normalize(Vector3.Cross(Vertices[index + 1].tov3() - Vertices[index + 0].tov3(), Vertices[index + 2].tov3() - Vertices[index + 0].tov3())));
                Normals[index + 2] = Normals[index + 1] = Normals[index];
            }

            //Записываем массив нормалей в буфер
            GL.GenBuffers(1, out ID_NBO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, ID_NBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(Normals.Length * Vertex.Stride), Normals, BufferUsageHint.StaticDraw);
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);

            //Аналогично поступаем с текстурными координатами
            TexCoords = new Vertex2[verticesQuantity];
            vIndex    = 0;
            for (int x = 0; x < heightMapImage.Width - 1; x++)
            {
                for (int z = 0; z < heightMapImage.Height - 1; z++)
                {
                    float X_L = (float)(x) / (float)(heightMapImage.Width - 1);
                    float X_M = (float)(x + 1) / (float)(heightMapImage.Width - 1);
                    float Z_L = (float)(z) / (float)(heightMapImage.Height - 1);
                    float Z_M = (float)(z + 1) / (float)(heightMapImage.Height - 1);

                    TexCoords[vIndex++] = new Vertex2(X_L, Z_L);
                    TexCoords[vIndex++] = new Vertex2(X_M, Z_M);
                    TexCoords[vIndex++] = new Vertex2(X_M, Z_L);

                    TexCoords[vIndex++] = new Vertex2(X_L, Z_L);
                    TexCoords[vIndex++] = new Vertex2(X_L, Z_M);
                    TexCoords[vIndex++] = new Vertex2(X_M, Z_M);
                }
            }

            //Пишем их в буфер
            GL.GenBuffers(1, out ID_TBO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, ID_TBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(TexCoords.Length * Vertex2.Stride), TexCoords, BufferUsageHint.StaticDraw);
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);

            //Индексы достаточно указать 1, 2, 3, 4 ... Т.к. вершины уже расположены в массиве по порядку
            Indices = new int[Vertices.Length];
            for (int index = 0; index < Indices.Length; index++)
            {
                Indices[index] = index;
            }

            GL.GenBuffers(1, out ID_EBO);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, ID_EBO);
            GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(Indices.Length * sizeof(int)), Indices, BufferUsageHint.StaticDraw);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);

            //Загружаем изображение и получаем его Id в OpenGL
            texture = loadTexture("Текстура.jpg");
            GL.ShadeModel(ShadingModel.Smooth);
        }
コード例 #44
0
 public override int GetHashCode()
 {
     return(Id.GetHashCode() ^ Weight.GetHashCode() ^ Vertex1.GetHashCode() ^ Vertex2.GetHashCode());
 }
コード例 #45
0
ファイル: Edge.cs プロジェクト: avalsa/TaskCore
 /// <summary> GetHashCode </summary>
 public override int GetHashCode()
 {
     return(Vertex1.GetHashCode() ^ Vertex2.GetHashCode() ^ Directed.GetHashCode());
 }