Exemple #1
0
        public static Graph.Edge[] SolvePar(Graph.Edge[] edges, int verticesCount)
        {
            var mst = new Graph.Edge[verticesCount - 1];

            Sort.StartSortPar(edges);

            int i = 0;
            int e = 0;

            var subsets = new Subset[verticesCount];

            for (int v = 0; v < verticesCount; v++)
            {
                subsets[v].Parent = v;
                subsets[v].Rank   = 0;
            }

            while (e < verticesCount - 1)
            {
                Graph.Edge nextEdge = edges[i++];
                int        x        = Find(subsets, nextEdge.src);
                int        y        = Find(subsets, nextEdge.dest);

                if (x != y)
                {
                    mst[e++] = nextEdge;
                    Union(subsets, x, y);
                }
            }

            return(mst);
        }
    //public void Traverse_PostGen(Graph.Cell cell)
    //{

    //    visitedcells.Add(cell);

    //    List<Graph.Edge> unvisistedEdges = cell.Edges.FindAll(v => !visitedcells.Contains(v.Cell1) || !visitedcells.Contains(v.Cell2));

    //    if (unvisistedEdges.Count == 0)
    //    {
    //        Traverse_PostGen(path.Pop());
    //    }
    //    else
    //    {
    //        path.Push(cell);
    //        Shuffle(unvisistedEdges);
    //        foreach (Graph.Edge edge in unvisistedEdges)
    //        {
    //            Destroy(edge.Wall);
    //            Traverse_PostGen(visitedcells.Contains(edge.Cell1) ? edge.Cell2 : edge.Cell1);
    //        }
    //    }
    //}

    public void Traverse_PostGen(Graph.Cell cell)
    {
        visitedcells.Add(cell);

        List <Graph.Edge> unvisistedEdges = cell.Edges.FindAll(v => !visitedcells.Contains(v.Cell1) || !visitedcells.Contains(v.Cell2));

        Shuffle(unvisistedEdges);

        if (unvisistedEdges.Count == 0)
        {
            if (path.Count > 0)
            {
                Traverse_PostGen(path.Pop());
            }
            else
            {
                return;
            }
        }
        else
        {
            path.Push(cell);
            Graph.Edge chosenEdge = unvisistedEdges[r.Next(0, unvisistedEdges.Count)];
            Destroy(chosenEdge.Wall);
            Traverse_PostGen(visitedcells.Contains(chosenEdge.Cell1) ? chosenEdge.Cell2 : chosenEdge.Cell1);
        }
    }
    public IEnumerator getGraphFromNode(string title)
    {
        Debug.Log("reached getGraphFromNode");
        yield return(StartCoroutine(parseContentFromHTML(title)));

        Graph graph = new Graph();

        Graph.Information info      = new Graph.Information(title);
        Graph.Node        firstNode = new Graph.Node(info);
        firstNode.setPosition(0.0f, 0.0f, 0.0f);
        graph.addNode(firstNode);


        //we assume that we don't go deeper here.
        //another approach would be to go the same route as Coroutine "getGraph"
        //we use this approach here because it's easier to implement and unterstand
        //plus the depth is unlikely to go deeper
        if (activeNode.getSubchapters() != null)
        {
            foreach (Graph.Information.Chapter subChapter in activeNode.getSubchapters())
            {
                Graph.Information neighborInfo = new Graph.Information(subChapter.getTitle());
                Graph.Node        nextNode     = new Graph.Node(neighborInfo);
                nextNode.setPosition(Random.Range(-DEFAULT_WIDTH / 2, DEFAULT_WIDTH / 2), Random.Range(-DEFAULT_HEIGHT / 2, DEFAULT_HEIGHT / 2), Random.Range(-DEFAULT_LENGTH / 2, DEFAULT_LENGTH / 2));
                Graph.Edge nextedge = new Graph.Edge(firstNode, nextNode);
                graph.addNode(nextNode);
                graph.addEdge(nextedge);

                if (subChapter.getSubchapters() != null)
                {
                    foreach (Graph.Information.Chapter subSubChapter in subChapter.getSubchapters())
                    {
                        Graph.Information subNeighborInfo = new Graph.Information(subSubChapter.getTitle());
                        Graph.Node        subNextNode     = new Graph.Node(subNeighborInfo);
                        subNextNode.setPosition(Random.Range(-DEFAULT_WIDTH / 2, DEFAULT_WIDTH / 2), Random.Range(-DEFAULT_HEIGHT / 2, DEFAULT_HEIGHT / 2), Random.Range(-DEFAULT_LENGTH / 2, DEFAULT_LENGTH / 2));
                        Graph.Edge subNextedge = new Graph.Edge(nextNode, subNextNode);
                        graph.addNode(subNextNode);
                        graph.addEdge(subNextedge);
                        if (subSubChapter.getSubchapters() != null)
                        {
                            foreach (Graph.Information.Chapter subSubSubChapter in subChapter.getSubchapters())
                            {
                                Graph.Information subSubNeighborInfo = new Graph.Information(subSubChapter.getTitle());
                                Graph.Node        subSubNextNode     = new Graph.Node(subSubNeighborInfo);
                                subSubNextNode.setPosition(Random.Range(-DEFAULT_WIDTH / 2, DEFAULT_WIDTH / 2), Random.Range(-DEFAULT_HEIGHT / 2, DEFAULT_HEIGHT / 2), Random.Range(-DEFAULT_LENGTH / 2, DEFAULT_LENGTH / 2));
                                Graph.Edge subSubNextedge = new Graph.Edge(subNextNode, subSubNextNode);

                                graph.addNode(subSubNextNode);
                                graph.addEdge(subSubNextedge);
                            }
                        }
                    }
                }
            }
        }
        setGraph(graph, 100.0f, 100.0f, 100.0f);
        drawGraph();
    }
Exemple #4
0
        public void TestComparison()
        {
            Graph.Edge edge1 = new Graph.Edge(8.0d, new Graph.Node());
            Graph.Edge edge2 = new Graph.Edge(8.0d, new Graph.Node());
            Graph.Edge edge3 = new Graph.Edge(2.0d, new Graph.Node());
            Graph.Edge edge4 = new Graph.Edge(11.0d, new Graph.Node());

            Assert.AreEqual(0, edge1.CompareTo(edge2));
            Assert.AreEqual(1, edge1.CompareTo(edge3));
            Assert.AreEqual(-1, edge1.CompareTo(edge4));
        }
Exemple #5
0
    // Update is called once per frame
    void Update()
    {
        if (_graph == null)
        {
            return;
        }

        _currentFrame++;

        // Wait for the frame count to surpass the timeslice interval, so we do not execute the update every frame
        if (_currentFrame < _timesliceInterval)
        {
            return;
        }
        else
        {
            _currentFrame = 0;
        }

        // loop through all graph nodes
        foreach (var node in _graph.Nodes)
        {
            // look through the adjacent nodes
            foreach (var adjacentNode in node.Adjacent)
            {
                if (node == adjacentNode)
                {
                    continue;
                }

                if (_graph.Edges == null)
                {
                    continue;
                }

                // find an existing directional edge that is cached in the graph
                var existingEdge = _graph.Edges.Find(edge => edge.EndNode == adjacentNode &&
                                                     edge.StartNode == node);

                // create the directional edge if its not cached
                if (existingEdge == null)
                {
                    var edge = new Graph.Edge();
                    edge.StartNode = node;
                    edge.EndNode   = adjacentNode;
                    edge.Weight    = 1;

                    _graph.Edges.Add(edge);
                }
            }
        }
    }
Exemple #6
0
    public static (Graph.Edge e, int eps, int minVal) Find(Graph G)
    {
        int totalMin = 99999, totalMinK = -1, totalMinEps = -1, totalMinI = -1;

        for (int k = 0; k < G.E.Count; ++k)
        {
            Graph.Edge ak = G.E[k];
            Log.dLine(String.Format("Processing edge #{0}: {1}->{2}={3}", k, ak.a, ak.b, ak.d));
            //s(yk) =  max[vi * d(yk, xi)];
            int curMin = INF, curMinI = -1, curMinEps = 0;
            for (int eps = 0; eps <= ak.d; ++eps)
            {
                int max = -1, maxi = -1;
                for (int i = 0; i < G.N; ++i)
                {
                    if (i == ak.a || i == ak.b)
                    {
                        continue;
                    }
                    int val = G.V[i] * Math.Min(eps + G.d[ak.b, i], ak.d - eps + G.d[ak.a, i]);
                    Log.dLine(
                        String.Format("i={5}, {0}->{1}={2}, eps={3}, val={4}", ak.a, ak.b, ak.d, eps, val, i)
                        );
                    if (val > max)
                    {
                        max  = val;
                        maxi = i;
                    }
                }
                Log.dLine("-----------");
                if (max < curMin)
                {
                    curMin    = max;
                    curMinI   = maxi;
                    curMinEps = eps;
                }
            }
            Log.dLine(
                String.Format("Edge processed. curMax={0} at i={1}, eps={2}", curMin, curMinI, curMinEps)
                );
            Log.dLine("=================");
            if (curMin < totalMin)
            {
                totalMin    = curMin;
                totalMinI   = curMinI;
                totalMinK   = k;
                totalMinEps = curMinEps;
            }
        }
        return(G.E[totalMinK], totalMinEps, totalMin);
    }
    public Graph GraphFloor(Labyrinth l, int graphSeed)
    {
        Graph graph = new Graph(graphSeed);

        // Check that there won't be too many vertices, and that the walls will be properly aligned
        if (l.graphScale.x * l.graphScale.z / Mathf.Pow(l.cellSize, 2) > MAXIMUM_VERTICES && l.safeMode ||
            l.graphScale.x * l.graphScale.z % l.cellSize != 0 && l.safeMode)
        {
            string errorLog = (l.graphScale.x * l.graphScale.z % l.cellSize != 0) ?
                              "Please ensure your Graph Scale is divisible by Cell Size with a remainder of zero. Disabling Safe Mode will bypass this check, but will result in geometric anomalies." :
                              $"Please lower your graph scale or increase cell size so that it creates at most {MAXIMUM_VERTICES} vertices.\nDisabling Safe Mode will bypass this check, but crashes may occur; you are encouraged to make multiple smaller graphs instead.";
            Debug.LogError(errorLog);
            return(graph);
        }

        Vector3 cellCenter;

        // Find the center of each cell in the graph, instantiating a new node in the graph to represent each
        for (int i = 0; i < l.graphScale.z / l.cellSize; i++)
        {
            for (int j = 0; j < l.graphScale.x / l.cellSize; j++)
            {
                cellCenter = new Vector3(l.graphScale.x / 2 - j * l.cellSize - l.cellSize / 2, 0, l.graphScale.z / 2 - i * l.cellSize - l.cellSize / 2);
                graph.Nodes.Add(new Graph.Node(cellCenter));
            }
        }

        Graph.Edge edge;

        // For each node created, find its direct neighbours with ascending x or z value. Then make an edge that connects both vertices.
        foreach (Graph.Node node in graph.Nodes)
        {
            foreach (Graph.Node neighbour in graph.Nodes.FindAll(v => v.CellCenter.x == node.CellCenter.x + l.cellSize &&
                                                                 v.CellCenter.z == node.CellCenter.z ||
                                                                 v.CellCenter.z == node.CellCenter.z + l.cellSize &&
                                                                 v.CellCenter.x == node.CellCenter.x))
            {
                edge = new Graph.Edge(node, neighbour);
                node.Edges.Add(edge);
                neighbour.Edges.Add(edge);
            }
        }

        return(graph);
    }
Exemple #8
0
        public void TestInitialization()
        {
            Random rand   = new Random();
            double weight = rand.NextDouble();

            Graph.Node nextNode = new Graph.Node();

            //test init
            Graph.Edge edge = new Graph.Edge(weight, nextNode);
            Assert.AreEqual(weight, edge.Weight);
            Assert.AreEqual(nextNode, edge.Node);

            //test setter
            double newWeight = rand.NextDouble();

            Graph.Node newNode = new Graph.Node();
            edge.Weight = newWeight;
            edge.Node   = newNode;
            Assert.AreEqual(newWeight, edge.Weight);
            Assert.AreEqual(newNode, edge.Node);
        }
    /*
     * also a test function.
     * makes a simple star-shaped graph
     * /
     * /*
     * public void makeStar()
     * {
     *  Graph newGraph = new Graph();
     *  Graph.Node newNode = new Graph.Node(null);
     *  newNode.setPosition(0.0f, 0.0f, 0.0f);
     *  newGraph.addNode(newNode);
     *  for (int i = 0; i < 49; i++)
     *  {
     *      Graph.Node nextNode = new Graph.Node(null);
     *      nextNode.setPosition(Random.Range(-5.0f, 5.0f), Random.Range(-5.0f, 5.0f), Random.Range(-5.0f, 5.0f));
     *      Graph.Edge edge = new Graph.Edge(newNode, nextNode);
     *
     *      newGraph.addNode(nextNode);
     *      newGraph.addEdge(edge);
     *  }
     *
     *  setGraph(newGraph);
     * }
     */

    public void Update()
    {
        if (drawnEdges != null)
        {
            if (drawnEdges.Count > 0)
            {
                for (int i = 0; i < drawnNodes.Count; i++)
                {
                    Vector3 newPos = drawnNodes[i].transform.position;
                    if (graph.getNodes().Count > i)
                    {
                        graph.getNodes()[i].setPosition(newPos.x, newPos.y, newPos.z);
                    }
                }
                for (int i = 0; i < drawnEdges.Count; i++)
                {
                    LineRenderer line    = drawnEdges[i].GetComponent <LineRenderer>();
                    Graph.Edge   curEdge = graph.getEdges()[i];
                    line.SetPosition(0, new Vector3(curEdge.getFrom().getX(), curEdge.getFrom().getY(), curEdge.getFrom().getZ()));
                    line.SetPosition(1, new Vector3(curEdge.getTo().getX(), curEdge.getTo().getY(), curEdge.getTo().getZ()));
                }
            }
        }
    }
Exemple #10
0
        // ---  Attributes ---
        // -- Properties --
        // -- Public Attributes --
        // -- Private Attributes --
        // --- /Attributes ---

        // ---  Methods ---
        // -- Public Methods --

        /**
         * Loads all data from the TileMaps below the given node.
         * Returns a Graph object, loaded with all the required data.
         */
        public static Graph.Graph LoadGraph(Node root)
        {
            // Prepare the Graph instance.
            Graph.Graph graph = new Graph.Graph();

            // Find all tilemap subnodes.
            Generic.List <TileMap> tilemaps = FindTilemapsUnder(root);

            // Get the limits of all the tilesets.
            Rect2 limits = GetTilemapsLimits(tilemaps);
            // Compute the limits of the loops.
            Vector2 start = limits.Position;
            Vector2 end   = limits.Position + limits.Size;

            // Loop through each tilemap.
            foreach (TileMap tilemap in tilemaps)
            {
                // Loop through the limits of the tilemap.
                for (int x = (int)start.x; x < end.x; x++)
                {
                    for (int y = (int)start.y; y < end.y; y++)
                    {
                        // First, get the identifier of the cell.
                        int tileID = tilemap.GetCell(x, y);

                        // If the identifier is not -1.
                        if (tileID != -1)
                        {
                              {
                                // Get the name of the tile.
                                String tileName = tilemap.TileSet.TileGetName(tileID);

                                // Check if the tile is a wall.
                                ComputeWall(tileName, x, y, ref graph);

                                // Check if the tile is a vertex.
                                ComputeVertex(tileName, x, y, ref graph);

                                // Compute the cost of the tile.
                                ComputeCost(x, y, tilemap);
                            }
                        }

                        // If the tilemap handles zone splitting.
                        if (tilemap.CollisionMask == 0b1000)
                        {
                            // Compute the face this tile belongs to.
                            ComputeFace(x, y, ref graph);

                            // If there is a tile.
                            if (tileID != -1)
                            {
                                // Compute the resources on that tile.
                                ComputeResource(x, y, tilemap, ref graph);
                            }
                        }
                    }
                }
            }

            // Prepare the list of vertices to remove.
            Generic.List <Graph.Vertex> VerticesToRemove = new Generic.List <Graph.Vertex>();

            // Loop through each vertex.
            foreach (Graph.Vertex vtx in graph.Vertices)
            {
                // Check all four sides.
                Vector2[]  directions = new Vector2[] { Vector2.Up, Vector2.Down, Vector2.Left, Vector2.Right };
                foreach (Vector2 dir in directions)
                {
                    // Check if a wall is present and has not been computed.
                    Vector2   currentPosition = vtx.Position + dir;
                    Tile.Wall dirWall         = graph.GetWallAt(currentPosition);
                    if (dirWall != null && dirWall.Edge == null)
                    {
                        // Get the rooms on each side of the wall.
                        Graph.Face[] faces = graph.GetFacesFromWall(currentPosition);

                        // Start computing a new edge.
                        Graph.Edge edge = new Graph.Edge(faces);

                        // Add the edges to the face.
                        edge.RightFace = faces[0];
                        edge.LeftFace  = faces[1];

                        // Loop until a new vertex is found.
                        while (graph.GetVertexAt(currentPosition) == null)
                        {
                            // If the wall exists.
                            Tile.Wall wall = graph.GetWallAt(currentPosition);
                            if (wall != null)
                            {
                                // Add the wall to the edge.
                                edge.AddWall(wall);

                                // Increment the position.
                                currentPosition += dir;

                                // If the wall stops abruptly, stop execution.
                            }
                            else
                            {
                                throw new Exception("FATAL ERROR: Stray wall found @ " + currentPosition + " ...");
                            }
                        }

                        // Add the vertices to the edge.
                        edge.StartVertex = vtx;
                        edge.EndVertex   = graph.GetVertexAt(currentPosition);

                        // Add the edge to the graph.
                        vtx.Edges.Add(edge);
                        graph.AddEdge(edge);

                        // Add the edge to the face.
                        foreach (Graph.Face face in faces)
                        {
                            face.AddEdge(edge);
                        }
                    }
                }

                // After that is done, check if the vertex object is NOT a tower.
                if (!vtx.IsTower)
                {
                    // If the vertex has two edges.
                    if (vtx.Edges.Count == 2)
                    {
                        // Get the vertex's edges.
                        Tuple <Graph.Edge, Graph.Edge> edges = new Tuple <Graph.Edge, Graph.Edge>(
                            vtx.Edges[0], vtx.Edges[1]
                            );

                        // Merge the edges together.
                        edges.Item1.Merge(edges.Item2);

                        // Remove the second edge.
                        graph.RemoveEdge(edges.Item2);

                        // If the vertex has one single edge.
                    }
                    else if (vtx.Edges.Count == 1)
                    {
                        // Add the vertex's wall to the edge.
                        vtx.Edges[0].AddWall(vtx.Wall);
                    }


                    // Add the vertex to removal.
                    VerticesToRemove.Add(vtx);
                }
            }

            // Remove the vertices.
            foreach (Graph.Vertex vtx in VerticesToRemove)
            {
                graph.RemoveVertex(vtx);
            }

            // Return the generated graph.
            GD.Print(graph.ToString());
            return(graph);
        }
Exemple #11
0
 public Way(Graph.Node b, Graph.Edge e)
 {
     this.b = b;
     this.e = e;
 }
Exemple #12
0
        // TODO: optimize/clean up
        public static List <Graph.Edge> FindMST(Object source, Graph graph)
        {
            var matrix = graph.AdjacencyMatrix;

            List <Graph.Edge> mst     = new List <Graph.Edge>();
            List <Object>     visited = new List <Object>();

            // Add our source node to our visited list
            visited.Add(source);

            // While we haven't visited all nodes
            while (visited.Count < graph.Size)
            {
                Graph.Edge min = null;

                // Check all paths leading from our connected nodes
                foreach (var node in visited)
                {
                    // Iterate across its connections to find a cheaper
                    // edge
                    for (int i = 0; i < matrix.GetLength(0); i++)
                    {
                        var edge = matrix[graph.IndexOf(node), i];

                        if (edge != null)
                        {
                            // We have found an edge leading from our connected to
                            // an unconnected and is cheaper
                            if (min == null || edge.Cost < min.Cost)
                            {
                                var to = edge.Source == node ? edge.Destination : edge.Source;

                                // We haven't visited this node yet so it becomes
                                // our new min
                                if (!visited.Contains(to))
                                {
                                    min = edge;
                                }
                            }
                        }
                    }
                }

                // If we have found a new minimum edge, lets add it to our mst
                if (min != null)
                {
                    if (!visited.Contains(min.Destination))
                    {
                        visited.Add(min.Destination);
                    }

                    if (!visited.Contains(min.Source))
                    {
                        visited.Add(min.Source);
                    }

                    mst.Add(min);
                }
            }

            return(mst);
        }
    /**
     * This method uses the title of a starting article and the amount of hops (distance from the start) to generate a graph
     * It also uses maxNodes (saved in the GraphVisualizer structure), to limit maximum nodes
     *
     */
    public IEnumerator getGraph(string startingNode, int hops)
    {
        Debug.Log("hops: " + hops);
        Debug.Log("max nodes: " + maxNodes);
        measuringTime = System.Environment.TickCount;

        isAcquiringGraph = true;
        //Note: We identify graph nodes by string because of easier comprehension
        //Note: Don't confuse the lists graph is taking care of with the list of strings of neighbors...
        Graph graph = new Graph();

        Graph.Information info      = new Graph.Information(startingNode);
        Graph.Node        firstNode = new Graph.Node(info);
        firstNode.setPosition(0.0f, 0.0f, 0.0f);
        graph.addNode(firstNode);                                 //this will keep track of ALL accumulated nodes and edges

        List <Graph.Node> nodesToCheck = new List <Graph.Node>(); //these are nodes that are found in the neighborhood

        nodesToCheck.Add(firstNode);                              //this only keeps track of neighborhoods and deletes nodes that have been explored already

        //NOTE: This version of BFS does currently not keep track of a "visited" list. Since we are limited by hops (which shouldn't ever go above 3 for sanity's sake), we finish searching at some point anyway
        for (int i = 0; i < hops; i++)
        {
            Debug.Log("Hop: " + i);
            int currentNodesToCheck = nodesToCheck.Count;
            //this is the number of nodes to check the neighborhoods for.
            //All neighbors that are found will be added to "nodesToCheck" in the next loop
            for (int j = 0; j < currentNodesToCheck; j++)
            {
                Debug.Log("currentNodeToCheck: " + j);
                //this for iterates a list of nodes that will be explored
                //KEEP IN MIND it checks the amount of nodes beforehand and works on the first x found nodes because nodes are being added to the list while working on it
                //i.e. the list nodesToCheck has 1 node in the beginning (starting node), so "currentNodesToCheck" is 1
                //we now explore this node and find all neighbors and add them to the graph and to nodesToCheck
                //after the next for loop, nodesToCheck will have a lot of new nodes
                //when the hop is done, meaning the for loop iterating j has come to an end, delete the first currentNodesToCheck-many elements in nodesToCheck
                yield return(StartCoroutine(communicator.requestNeighbors(nodesToCheck[j].getName())));

                List <string> tempNeighbors = communicator.getNeighbors();
                for (int z = 0; z < tempNeighbors.Count; z++)
                {
                    Debug.Log("currentNeighborToCheck: " + z);

                    //this for adds all neighbors of a node that is currently being explored to the list of nodes to be explored and the graph
                    Graph.Information neighborInfo = new Graph.Information(tempNeighbors[z]);
                    Graph.Node        nextNode     = new Graph.Node(neighborInfo);
                    nextNode.setPosition(Random.Range(-DEFAULT_WIDTH / 2, DEFAULT_WIDTH / 2), Random.Range(-DEFAULT_HEIGHT / 2, DEFAULT_HEIGHT / 2), Random.Range(-DEFAULT_LENGTH / 2, DEFAULT_LENGTH / 2));
                    Graph.Edge nextedge = new Graph.Edge(nodesToCheck[j], nextNode);
                    if (!graph.getNodes().Exists(node => node.getName().Equals(tempNeighbors[z])))
                    {
                        graph.addNode(nextNode);                                                                                                               //add neighbor to graph if not already in graph
                    }
                    if (!graph.getEdges().Exists(edge => edge.getFrom().getName().Equals(nodesToCheck[j]) && edge.getTo().getName().Equals(tempNeighbors[z]))) //I don't want to talk about this
                    {
                        //above if should check if edge is already in list

                        int oppositeEdge = graph.getEdges().FindIndex(edge => edge.getFrom().getName().Equals(tempNeighbors[z]) && edge.getTo().getName().Equals(nodesToCheck[j]));
                        if (oppositeEdge >= 0)
                        {
                            //check if the edge exists in the opposite direction (try to find an edge where FROM is the neighbor that is looked at and TO is the node that is being explored)
                            graph.getEdges()[oppositeEdge].setBothWays(true);
                        }
                        else
                        {
                            /*
                             * IMPORTANT NOTE: THE ABOVE STEP IS NECESSARY WHEN AN EDGE IS SAVED WITH A FLAG THAT INDICATES IT GOES IN BOTH DIRECTIONS
                             * AN EDGE IS CURRENTLY MODELED SO THAT EDGES BETWEEN TWO NODES CAN BE ADDED TWICE IF THEY ARE OPPOSITES
                             * I only realised I could've left this out after I almost finished it.
                             *
                             * EDIT: Edges now have a flag that says whether it runs in both ways or not.
                             */
                            graph.addEdge(nextedge); //add edge to graph if not already in graph
                        }
                    }
                    nodesToCheck.Add(nextNode); //this adds the currently looked at node to the list of nodes to explore
                    if (graph.getNodes().Count >= maxNodes)
                    {
                        break;
                    }
                }
                if (graph.getNodes().Count >= maxNodes)
                {
                    break;
                }
            }
            nodesToCheck.RemoveRange(0, currentNodesToCheck); //see comment at start of for loop iterating j for more information on why this is necessary
            if (graph.getNodes().Count >= maxNodes)
            {
                break;
            }
        }
        setGraph(graph, 100.0f, 100.0f, 100.0f);
        isAcquiringGraph = false;
        Debug.Log("Elapsed Time: " + (System.Environment.TickCount - measuringTime));
        Debug.Log("Nodes in total: " + graph.getNodes().Count);
    }
Exemple #14
0
 /// <summary>
 /// Defines if edge is pointing to permanent data
 /// </summary>
 /// <param name="edge">Edge to check</param>
 /// <returns>True if edge is pointing to permanent data</returns>
 internal static bool IsPermanentEdge(Graph.Edge <Guid, Graph.EdgeData> edge)
 {
     return(edge.Data.Semantic == EdgeType.OfType ||                           // Types never change during runtime
            edge.ToNodeId.Equals(Constants.NullReferenceNodeId) ||             // Null never changes
            ((edge.Data.Flags & EdgeFlags.Permanent) == EdgeFlags.Permanent)); // Edge marked as permanent
 }
Exemple #15
0
    private void Build(Polygon polygon, VoronoiBase voronoi)
    {
        Dictionary <Point, Graph.Center> centerLoopup = new Dictionary <Point, Graph.Center>();

        foreach (var point in polygon.Points)
        {
            Graph.Center center = new Graph.Center
            {
                id         = data.centers.Count,
                pos        = point.ToVector(),
                neighbours = new List <Graph.Center>(),
                borders    = new List <Graph.Edge>(),
                corners    = new List <Graph.Corner>()
            };
            data.centers.Add(center);
            centerLoopup[point] = center;
        }

        foreach (var face in voronoi.Faces)
        {
            face.LoopEdges(halfEdge =>
            {
                Point voronoiEdge1  = halfEdge.Origin;
                Point voronoiEdge2  = halfEdge.Twin.Origin;
                Point delaunayEdge1 = polygon.Points[halfEdge.Face.ID];
                Point delaunayEdge2 = polygon.Points[halfEdge.Twin.Face.ID];

                Graph.Edge edge = new Graph.Edge
                {
                    id       = data.edges.Count,
                    midPoint = new Vector2((float)(voronoiEdge1.X + voronoiEdge2.X) / 2, (float)(voronoiEdge1.Y + voronoiEdge2.Y) / 2),
                    v0       = MakeCorner(voronoiEdge1),
                    v1       = MakeCorner(voronoiEdge2),
                    d0       = centerLoopup[delaunayEdge1],
                    d1       = centerLoopup[delaunayEdge2]
                };

                if (edge.d0 != null)
                {
                    edge.d0.borders.Add(edge);
                }
                if (edge.d1 != null)
                {
                    edge.d1.borders.Add(edge);
                }
                if (edge.v0 != null)
                {
                    edge.v0.protrudes.Add(edge);
                }
                if (edge.v1 != null)
                {
                    edge.v1.protrudes.Add(edge);
                }

                data.edges.Add(edge);

                // Centers point to centers.
                if (edge.d0 != null && edge.d1 != null)
                {
                    AddToCenterList(edge.d0.neighbours, edge.d1);
                    AddToCenterList(edge.d1.neighbours, edge.d0);
                }

                // Corners point to corners
                if (edge.v0 != null && edge.v1 != null)
                {
                    AddToCornerList(edge.v0.adjacent, edge.v1);
                    AddToCornerList(edge.v1.adjacent, edge.v0);
                }

                // Centers point to corners
                if (edge.d0 != null)
                {
                    AddToCornerList(edge.d0.corners, edge.v0);
                    AddToCornerList(edge.d0.corners, edge.v1);
                }
                if (edge.d1 != null)
                {
                    AddToCornerList(edge.d1.corners, edge.v0);
                    AddToCornerList(edge.d1.corners, edge.v1);
                }

                // Corners point to centers
                if (edge.v0 != null)
                {
                    AddToCenterList(edge.v0.touches, edge.d0);
                    AddToCenterList(edge.v0.touches, edge.d1);
                }
                if (edge.v1 != null)
                {
                    AddToCenterList(edge.v1.touches, edge.d0);
                    AddToCenterList(edge.v1.touches, edge.d1);
                }
            });
        }
    }