public NeuralNetwork(int countInputNodes, int countOutputNodes, int countHiddenNodes)
        {
            input_nodes = new List<Node>();
            hidden_nodes = new List<Node>();
            output_nodes = new List<Node>();

            // add input nodes
            for (int i = 0; i < countInputNodes; i++)
                input_nodes.Add(new Node());
            // add hidden nodes
            for (int i = 0; i < countHiddenNodes; i++)
                hidden_nodes.Add(new Node());
            // add output nodes
            for (int i = 0; i < countOutputNodes; i++)
                output_nodes.Add(new Node());

            // create edges from data to input
            for (int i = 0; i < input_nodes.Count; i++)
                input_nodes[i].AddEdge(true, new Edge(null, input_nodes[i], 0));

            // create edges from input to hidden
            Edge newEdge;
            for(int i  =0; i < input_nodes.Count; i++)
                for(int j = 0; j < hidden_nodes.Count; j++)
                {
                    newEdge = new Edge(input_nodes[i], hidden_nodes[j], 0);
                }

            // create edges from hidden to output

            // create edges from output to output data
        }
Esempio n. 2
0
 private bool Equals(Edge obj)
 {
     if (Direction == EdgeDirection.Undirected)
     {
         return (obj != null && 
                     (
                         (
                         obj.Vertex1.Equals(this.Vertex1) &&
                         obj.Vertex2.Equals(this.Vertex2)
                         ) ||
                         (
                         obj.Vertex1.Equals(this.Vertex2) &&
                         obj.Vertex2.Equals(this.Vertex1)
                         )
                     ) &&
             obj.Type.Equals(this.Type) &&
             obj.Relationship.Equals(this.Relationship));
     }
     else
     {
         return (obj != null &&
                 obj.Vertex1.Equals(this.Vertex1) &&
                 obj.Vertex2.Equals(this.Vertex2) &&
                 obj.Type.Equals(this.Type) &&
                 obj.Relationship.Equals(this.Relationship));
     }
 }
Esempio n. 3
0
 public ETClient(Edge e)
 {
   _sync = new object();
   _sent_blocks = new Hashtable();
   _e = e;
   _e.Subscribe(this, null );
 }
Esempio n. 4
0
        public EdgeList(Edge edge)
        {
            _edges = new List<Edge>();
            _edges.Add(edge);

            _weight = edge.Weight;
        }
Esempio n. 5
0
        public void test3()
        {
            UndirectedGraph<int, Edge<int>> graph = new UndirectedGraph<int, Edge<int>>(true);

            // Add vertices to the graph
            graph.AddVertex(0);
            graph.AddVertex(1);
            graph.AddVertex(2);
            graph.AddVertex(3);
            graph.AddVertex(4);
            // Create the edges
            Edge<int> e0_1 = new Edge<int>(0, 1);
            Edge<int> e0_2 = new Edge<int>(0, 2);
            Edge<int> e1_4 = new Edge<int>(1, 4);
            Edge<int> e3_4 = new Edge<int>(3, 4);
            Edge<int> e0_3 = new Edge<int>(0, 3);
            Edge<int> e1_2 = new Edge<int>(1, 2);
            // Add the edges
            graph.AddEdge(e0_1);
            graph.AddEdge(e0_2);
            graph.AddEdge(e1_2);
            graph.AddEdge(e1_4);
            graph.AddEdge(e3_4);
            graph.AddEdge(e0_3);

            List<int> path = new List<int>();

            HamiltonianDefiner definer = new HamiltonianDefiner(graph);
            bool isHamiltonian = definer.isHamiltonianGraph(path);
            Assert.AreEqual(isHamiltonian, true);
        }
Esempio n. 6
0
 ///<summary>Creates a new WrapperEdge.<summary>
 ///<param name="edge">The edge to wrap.</param>
 ///<param name="SubscribeToEdge">Should this subscribe to the edge.</param>
 public WrapperEdge(Edge edge, bool SubscribeToEdge) {
   _weclosed = 0;
   _edge = edge;
   if(SubscribeToEdge) {
     _edge.Subscribe(this, null);
   }
 }
Esempio n. 7
0
 private Edge(Edge prev)
 {
     qPrev = prev;
     prev.qNext = this;
     LFace = null;
     Token = 0;
 }
        public static Area CreateArea()
        {
            Area area = new Area();

            Node node0 = new Node(area, new Vector2(500, 50));
            Node node1 = new Node(area, new Vector2(50, 50));
            Node node2 = new Node(area, new Vector2(300, 70));
            Node node3 = new Node(area, new Vector2(400, 140));
            Node node4 = new Node(area, new Vector2(90, 300));
            Node node5 = new Node(area, new Vector2(450, 300));
            Node node6 = new Node(area, new Vector2(600, 400));
            Node node7 = new Node(area, new Vector2(150, 200));

            Edge edge0 = new Edge(area, node0, node3, 1);
            Edge edge1 = new Edge(area, node1, node2, 1);
            Edge edge2 = new Edge(area, node4, node3, 3);
            Edge edge3 = new Edge(area, node6, node5, 3);
            Edge edge4 = new Edge(area, node3, node5, 2);
            Edge edge5 = new Edge(area, node1, node4, 1);
            Edge edge6 = new Edge(area, node2, node7, 1);
            Edge edge7 = new Edge(area, node7, node1, 3);
            Edge edge8 = new Edge(area, node2, node3, 2);
            Edge edge9 = new Edge(area, node6, node3, 3);
            Edge edge10 = new Edge(area, node6, node4, 1);
            Edge edge11 = new Edge(area, node0, node6, 3);

            return area;
        }
Esempio n. 9
0
        public IEnumerable<int> FindTourStartingFrom(Edge startEdge)
        {
            this.InitializeVisit();

            this.VisitNode(startEdge.Head);
            yield return startEdge.Head;

            this.VisitNode(startEdge.Tail);
            yield return startEdge.Tail;

            int currentNode = startEdge.Tail;

            TaskLogger.Text = "Computing nearest neighbor tour...";

            while (unvisitedNodes.ItemsCount > 0)
            {
                int nearestUnvisitedNode = this.FindNearestUnvisitedNode(currentNode);

                this.VisitNode(nearestUnvisitedNode);
                yield return nearestUnvisitedNode;

                currentNode = nearestUnvisitedNode;

                TaskLogger.Progress = 100.0 * visitedNodes.ItemsCount / nodes.Length;
            }
        }
Esempio n. 10
0
        public Algorithm(List<List<int>> input)
        {
            // Create cities
            cities = new Vertex[input[0][0]];

            for (int i = 0; i < input[0][0]; i++)
            {
                cities[i] = new Vertex();
            }

            // Create ways
            ways = new List<Edge>();

            // and other stuff
            linked = new List<int>();
            done = new List<int>();
            routes = new List<List<int>>();

            for (int i = 1; i < input.Count; i++)
            {
                Edge way = new Edge();

                way.weight = input[i][0];
                way.u = input[i][1];
                way.v = input[i][2];

                ways.Add(way);
            }
        }
 ///<summary>Makes the SecurityOverlord listen to the edge and instantiates
 ///a new SecurityAssociation for the insecure edge.  CreateSecurityAssociation
 ///is idempotent.</summary>
 protected override void WrapEdge(Edge edge) {
   edge.Subscribe(_so, null);
   SecurityAssociation sa = _so.CreateSecurityAssociation(edge, DefaultEdgeSPI, !edge.IsInbound);
   if(edge.IsClosed) {
     sa.Close("Edge closed too quickly.");
   }
 }
Esempio n. 12
0
        /// <summary>
        /// Class constructor.
        /// </summary>
        
        /// <date>2013-07-23</date>
        public HalfEdge(Edge objEdge, Point objSiteLeft, Point objSiteRight)
        {
            this.Site = objSiteLeft;
            this.Edge = objEdge;

            // 'angle' is a value to be used for properly sorting the
            // halfsegments counterclockwise. By convention, we will
            // use the angle of the line defined by the 'site to the left'
            // to the 'site to the right'.
            // However, border edges have no 'site to the right': thus we
            // use the angle of line perpendicular to the halfsegment (the
            // edge should have both end points defined in such case.)
            if (objSiteRight != null)
            {
                this.Angle = Math.Atan2(objSiteRight.y - objSiteLeft.y, objSiteRight.x - objSiteLeft.x);
            }
            else
            {
                if (objEdge.SiteLeft == objSiteLeft)
                {
                    this.Angle = Math.Atan2(objEdge.VertexB.x - objEdge.VertexA.x, objEdge.VertexA.y - objEdge.VertexB.y);
                }
                else
                {
                    this.Angle = Math.Atan2(objEdge.VertexA.x - objEdge.VertexB.x, objEdge.VertexB.y - objEdge.VertexA.y);
                }
            }
        }
 private static Point2DCollection ClipRing(Point2DCollection ring, Edge edge)
 {
     if ((ring == null) || (ring.Count < 2))
     {
         return null;
     }
     Point2DCollection points = new Point2DCollection();
     Point2D lastPoint = ring[ring.Count - 1];
     for (int i = 0; i < ring.Count; i++)
     {
         Point2D point = ring[i];
         if (Inside(point, edge))
         {
             if (Inside(lastPoint, edge))
             {
                 points.Add(point);
             }
             else
             {
                 Point2D item = EdgeIntersection(lastPoint, point, edge);
                 points.Add(item);
                 points.Add(point);
             }
         }
         else if (Inside(lastPoint, edge))
         {
             Point2D item = EdgeIntersection(lastPoint, point, edge);
             points.Add(item);
         }
         lastPoint = point;
     }
     return points;
 }
        /// <summary>
        /// create a geometry edge, the geometry source and target have to be set already
        /// </summary>
        /// <param name="drawingEdge"></param>
        /// <param name="msaglGraph"></param>
        /// <returns></returns>
        static Core.Layout.Edge CreateGeometryEdgeAndAddItToGeometryGraph(Edge drawingEdge, GeometryGraph msaglGraph) {
            var msaglEdge = CreateGeometryEdgeFromDrawingEdge(drawingEdge);

            msaglGraph.Edges.Add(msaglEdge);
            
            return msaglEdge;
        }
Esempio n. 15
0
        internal static GeometryGraph CreateAndLayoutGraph()
        {
            double w = 30;
            double h = 20;
            GeometryGraph graph = new GeometryGraph();
            Node a = new Node( new Ellipse(w, h, new P()),"a");
            Node b = new Node( CurveFactory.CreateRectangle(w, h, new P()),"b");
            Node c = new Node( CurveFactory.CreateRectangle(w, h, new P()),"c");
            Node d = new Node(CurveFactory.CreateRectangle(w, h, new P()), "d");

            graph.Nodes.Add(a);
            graph.Nodes.Add(b);
            graph.Nodes.Add(c);
            graph.Nodes.Add(d);
            Edge e = new Edge(a, b) { Length = 10 };
            graph.Edges.Add(e);
            graph.Edges.Add(new Edge(b, c) { Length = 3 });
            graph.Edges.Add(new Edge(b, d) { Length = 4 });

            //graph.Save("c:\\tmp\\saved.msagl");
            var settings = new Microsoft.Msagl.Layout.MDS.MdsLayoutSettings();
            LayoutHelpers.CalculateLayout(graph, settings, null);

            return graph;
        }
 public EdgeViewModel(int index, Edge edge, BoundaryCondition condition)
 {
     Index = index;
     Edge = edge;
     Condition = condition;
     Types = new ObservableCollection<BoundaryConditionsType>(getTypesOfBoundaryConditions());
 }
Esempio n. 17
0
 public Halfedge(Type _lock,Edge edge=null,LR lr=null)
 {
     if(_lock!=typeof(PrivateConstrutorEnforcer)){
         Debug.LogError("halfedge constructor is private");
     }
     init(edge,lr);
 }
        /// <summary>
        /// populate the geometry including curve and arrowhead positioning for the given edge using simple
        /// straight line routing style.  Self edges will be drawn as a loop, padding is used to control the
        /// size of the loop.
        /// </summary>
        /// <param name="edge">edge to route</param>
        /// <param name="padding">controls size of loop</param>
        public static void RouteEdge(Edge edge, double padding)
        {
            ValidateArg.IsNotNull(edge, "edge");

            var eg = edge.EdgeGeometry;

            if (eg.SourcePort == null)
            {
#if SHARPKIT // Lambdas bind differently in JS
                eg.SourcePort = ((Func<Edge,RelativeFloatingPort>)(ed => new RelativeFloatingPort(() => ed.Source.BoundaryCurve,
                    () => ed.Source.Center)))(edge);
#else
                eg.SourcePort = new RelativeFloatingPort(() => edge.Source.BoundaryCurve, () => edge.Source.Center);
#endif
            }

            if (eg.TargetPort == null)
            {
#if SHARPKIT // Lambdas bind differently in JS
                eg.TargetPort = ((Func<Edge, RelativeFloatingPort>)(ed => new RelativeFloatingPort(() => ed.Target.BoundaryCurve,
                    () => ed.Target.Center)))(edge);
#else
                eg.TargetPort = new RelativeFloatingPort(() => edge.Target.BoundaryCurve, () => edge.Target.Center);
#endif
            }

            if (!ContainmentLoop(eg, padding))
            {
                eg.Curve = GetEdgeLine(edge);
            }

            Arrowheads.TrimSplineAndCalculateArrowheads(eg, eg.SourcePort.Curve,
                                                         eg.TargetPort.Curve, edge.Curve, false, false);
                      
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="e"></param>
 public MonotoneChainEdge(Edge e)
 {
     this.e = e;
     pts = e.Coordinates;
     MonotoneChainIndexer mcb = new MonotoneChainIndexer();
     startIndex = mcb.GetChainStartIndices(pts);
 }
Esempio n. 20
0
        public void RemoveExplored(Edge edge)
        {
            this.ExploredEdges.Remove(edge);

            SearchEvent ev = new SearchEvent(SearchEventType.RemovedEdgeFromExplored, edge);
            this.EventManager.AddEvent(ev);
        }
Esempio n. 21
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="e"></param>
 public MonotoneChainEdge(Edge e)
 {
     _e = e;
     _pts = e.Coordinates;
     MonotoneChainIndexer mcb = new MonotoneChainIndexer();
     _startIndex = mcb.GetChainStartIndices(_pts);
 }
        public void AddExploredEdgeToPath1(Edge edge)
        {
            this.Path1.AddExploredEdge(edge);

            SearchEvent ev = new SearchEvent(SearchEventType.AddedEdgeToExplored, edge);
            this.SEM.AddEvent(ev);
        }
Esempio n. 23
0
        public void AddTraveledEdge(Edge edge)
        {
            this.TraveledEdges.Add(edge);

            SearchEvent ev = new SearchEvent(SearchEventType.AddedEdgeToTraveled, edge);
            this.EventManager.AddEvent(ev);
        }
Esempio n. 24
0
 public void Add( Edge edge )
 {
     if( !TryAdd( edge ) )
     {
         throw new ArgumentException( "Edge already exists: " + edge.Id );
     }
 }
Esempio n. 25
0
        /// <summary>
        /// Creates stub edges for all the intersections in this
        /// Edge (if any) and inserts them into the graph.
        /// </summary>
        /// <param name="edge"></param>
        /// <param name="l"></param>
        public virtual void ComputeEdgeEnds(Edge edge, IList l)
        {
            EdgeIntersectionList eiList = edge.EdgeIntersectionList;       
            // ensure that the list has entries for the first and last point of the edge
            eiList.AddEndpoints();

            IEnumerator it = eiList.GetEnumerator();
            EdgeIntersection eiPrev = null;
            EdgeIntersection eiCurr = null;
            // no intersections, so there is nothing to do
            if (! it.MoveNext()) return;
            EdgeIntersection eiNext = (EdgeIntersection) it.Current;
            do 
            {
                eiPrev = eiCurr;
                eiCurr = eiNext;
                eiNext = null;
                
                if (it.MoveNext())
                    eiNext = (EdgeIntersection)it.Current;                

                if (eiCurr != null) 
                {
                    CreateEdgeEndForPrev(edge, l, eiCurr, eiPrev);
                    CreateEdgeEndForNext(edge, l, eiCurr, eiNext);
                }
            } 
            while (eiCurr != null);
        }
Esempio n. 26
0
        public static void Main(string[] args)
        {
            Console.Title = "Graph";

            Vertex jana = new Vertex();
            Vertex philip = new Vertex();
            Vertex markus = new Vertex();

            Edge relMarkusPhilip = new Edge();
            Edge relJanaPhilip= new Edge();

            jana.Data.Add("Class", "Person");
            philip.Data.Add("Class", "Person");
            markus.Data.Add("Class", "Person");

            jana.Data.Add("Name", "Jana");
            philip.Data.Add("Name", "Philip");
            markus.Data.Add("Name", "Markus");

            relJanaPhilip.Data.Add("Class", "Friend");
            relMarkusPhilip.Data.Add("Class", "Friend");

            relMarkusPhilip.ConnectVertices(ref markus, ref philip);
            relJanaPhilip.ConnectVertices(ref jana, ref philip);

            List<Edge> results = markus.SearchVertices("Friend");

            foreach (Edge e in results)
                Console.WriteLine(e.Data["Class"]);

            Console.ReadLine();
        }
        public void FindShortestPathForSimpleUndirectedGraphUsingDijkstraAlgorithm()
        {
            var graph = new UndirectedGraph<object, Edge<object>>(true);
            object v1 = "vertex1";
            object v2 = "vertex2";
            object v3 = "vertex3";
            var e1 = new Edge<object>(v1, v2);
            var e2 = new Edge<object>(v2, v3);
            var e3 = new Edge<object>(v3, v1);
            graph.AddVertex(v1);
            graph.AddVertex(v2);
            graph.AddVertex(v3);
            graph.AddEdge(e1);
            graph.AddEdge(e2);
            graph.AddEdge(e3);

            var algorithm = new UndirectedDijkstraShortestPathAlgorithm<object, Edge<object>>(graph, edge => (double)1);
            var observer = new UndirectedVertexPredecessorRecorderObserver<object, Edge<object>>();
            using (observer.Attach(algorithm))
            {
                algorithm.Compute(v1);
            }

            IEnumerable<Edge<object>> path;
            observer.TryGetPath(v3, out path);

            foreach (var edge in path)
            {
                Console.WriteLine(edge);
            }
        }
Esempio n. 28
0
		public static Graph Read(StreamReader stream)
		{
			int.Parse(stream.ReadLine());
			int E = int.Parse(stream.ReadLine());

			var graph = new Graph();

			for(int i = 0; i < E; ++i)
			{
				string[] r = stream.ReadLine().Trim().Split(' ');
				r = r.Where (x => x.Length > 0).ToArray();

				var edge = new Edge()
				{
					From = int.Parse(r[0]),
					To = int.Parse(r[1]),
					Weight = float.Parse(r[2]),
				};

				if(!graph.Vertices.ContainsKey(edge.From))
				{
					graph.Vertices[edge.From] = new List<Edge>();
				}
				graph.Vertices[edge.From].Add(edge);
			}

			return graph;
		}
        public void FisrstSampleInput()
        {
            int nodesCount = 4;

            var edges = new List<Edge>
            {
                new Edge(0, 1, 9),
                new Edge(0, 3, 4),
                new Edge(3, 1, 6),
                new Edge(3, 2, 11),
                new Edge(1, 2, 5)
            };

            var expectedEdges = new Edge[]
            {
                edges[1],
                edges[4],
                edges[2]
            };

            var actualEdges = KruskalAlgorithm.Kruskal(nodesCount, edges);

            CollectionAssert.AreEqual(expectedEdges, actualEdges);
            Assert.AreEqual(15, actualEdges.Sum(e => e.Weight));
        }
        protected override void OnMouseClick(MouseEventArgs e)
        {
            var x = Convert.ToInt32(Math.Floor(e.X/pixelDelta));
            var y = Convert.ToInt32(Math.Floor(e.Y/pixelDelta));
            var clickPoint = new Point(x, y);

            mousePoint = clickPoint;
            edgeFirstPoint = clickPoint;

            if (currentPolygon == null)
                currentPolygon = new Polygon(clickPoint, PanelColor.BackColor);
            else
            {
                currentPolygon.TryAddVertex(clickPoint);
                if (currentPolygon.Closed)
                {
                    polygons.Add(currentPolygon);
                    currentPolygon = null;
                    edgeFirstPoint = null;
                    currentEdge = null;
                }
            }

            Invalidate();
        }
Esempio n. 31
0
 void AppendEdgeIfNotUndefined(string str, EdgesReadonly edges, Edge edge)
 {
     AppendNumberIfNotUndefined(str, edges.ComputedEdgeValue(edge, YogaValue.Undefined));
 }
Esempio n. 32
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            var xyz = (XYZ)((Value.Container)args[0]).Item;

            var inputArg = ((Value.Container)args[1]).Item;

            var face = inputArg is Face ? (Autodesk.Revit.DB.Face)inputArg : null;

            if (face == null && !(inputArg is Plane))
            {
                throw new Exception(" Project Point On Face needs Face or Plane as argument no. 1");
            }
            if (face == null)
            {
                Plane pln = (Plane)inputArg;
                if (pln != null)
                {
                    UV     uvP      = new UV(pln.XVec.DotProduct(xyz - pln.Origin), pln.YVec.DotProduct(xyz - pln.Origin));
                    XYZ    ptP      = pln.Origin + uvP[0] * pln.XVec + uvP[1] * pln.YVec;
                    double dP       = xyz.DistanceTo(ptP);
                    Edge   eP       = null;
                    double etP      = 0.0;
                    var    resultsP = FSharpList <Value> .Empty;
                    resultsP = FSharpList <Value> .Cons(Value.NewNumber(etP), resultsP);

                    resultsP = FSharpList <Value> .Cons(Value.NewContainer(eP), resultsP);

                    resultsP = FSharpList <Value> .Cons(Value.NewNumber(dP), resultsP);

                    resultsP = FSharpList <Value> .Cons(Value.NewContainer(uvP), resultsP);

                    resultsP = FSharpList <Value> .Cons(Value.NewContainer(ptP), resultsP);

                    pts.Add(ptP);

                    return(Value.NewList(resultsP));
                }
            }

            IntersectionResult ir = face.Project(xyz);
            XYZ    pt             = ir.XYZPoint;
            UV     uv             = ir.UVPoint;
            double d = ir.Distance;
            Edge   e = null;

            try
            {
                e = ir.EdgeObject;
            }
            catch { }
            double et = 0;

            try
            {
                et = ir.EdgeParameter;
            }
            catch { }

            var results = FSharpList <Value> .Empty;

            results = FSharpList <Value> .Cons(Value.NewNumber(et), results);

            results = FSharpList <Value> .Cons(Value.NewContainer(e), results);

            results = FSharpList <Value> .Cons(Value.NewNumber(d), results);

            results = FSharpList <Value> .Cons(Value.NewContainer(uv), results);

            results = FSharpList <Value> .Cons(Value.NewContainer(xyz), results);

            pts.Add(pt);

            return(Value.NewList(results));
        }
Esempio n. 33
0
        private bool Validate(List <Edge> parse, List <IToken> i)
        {
            List <Edge> q = parse.ToList();

            q.Reverse();
            List <IToken> .Enumerator ei = _input.GetEnumerator();
            List <Edge> .Enumerator   eq = q.GetEnumerator();
            bool fei = false;
            bool feq = false;

            for (; ;)
            {
                fei = ei.MoveNext();
                IToken v = ei.Current;
                if (!fei)
                {
                    break;
                }

                bool empty = true;
                for (; empty;)
                {
                    feq = eq.MoveNext();
                    if (!feq)
                    {
                        break;
                    }

                    Edge x = eq.Current;
                    switch (x._type)
                    {
                    case TransitionType.RULE:
                        empty = true;
                        break;

                    case TransitionType.PREDICATE:
                        empty = true;
                        break;

                    case TransitionType.ACTION:
                        empty = true;
                        break;

                    case TransitionType.ATOM:
                        empty = false;
                        break;

                    case TransitionType.EPSILON:
                        empty = true;
                        break;

                    case TransitionType.INVALID:
                        empty = true;
                        break;

                    case TransitionType.NOT_SET:
                        empty = false;
                        break;

                    case TransitionType.PRECEDENCE:
                        empty = true;
                        break;

                    case TransitionType.SET:
                        empty = false;
                        break;

                    case TransitionType.WILDCARD:
                        empty = false;
                        break;

                    default:
                        throw new Exception();
                    }
                }
                Edge w = eq.Current;
                if (w == null && v == null)
                {
                    return(true);
                }
                else if (w == null)
                {
                    return(false);
                }
                else if (v == null)
                {
                    return(false);
                }

                switch (w._type)
                {
                case TransitionType.ATOM:
                {
                    IntervalSet set = w._label;
                    if (set != null && set.Count > 0)
                    {
                        if (!set.Contains(v.Type))
                        {
                            return(false);
                        }
                    }
                    break;
                }

                case TransitionType.NOT_SET:
                {
                    IntervalSet set = w._label;
                    set = set.Complement(IntervalSet.Of(TokenConstants.MinUserTokenType, _parser.Atn.maxTokenType));
                    if (set != null && set.Count > 0)
                    {
                        if (!set.Contains(v.Type))
                        {
                            return(false);
                        }
                    }
                    break;
                }

                case TransitionType.SET:
                {
                    IntervalSet set = w._label;
                    if (set != null && set.Count > 0)
                    {
                        if (!set.Contains(v.Type))
                        {
                            return(false);
                        }
                    }
                    break;
                }

                case TransitionType.WILDCARD:
                    break;

                default:
                    throw new Exception();
                }
            }
            return(true);
        }
Esempio n. 34
0
        private List <Object> ToGeometry(Topology topology, double tolerance)
        {
            if (topology == null)
            {
                return(null);
            }

            List <Object> geometries = new List <Object>();
            Vertex        vertex     = topology as Vertex;

            if (vertex != null)
            {
                geometries.Add(ToPoint(vertex));
                return(geometries);
            }

            Edge edge = topology as Edge;

            if (edge != null)
            {
                geometries.Add(ToCurve(edge));
                return(geometries);
            }

            Wire wire = topology as Wire;

            if (wire != null)
            {
                return(ToCurves(wire));
            }

            Face face = topology as Face;

            if (face != null)
            {
                geometries.Add(ToSurface(face, tolerance));
                return(geometries);
            }

            Shell shell = topology as Shell;

            if (shell != null)
            {
                return(ToBrep(shell, tolerance));
            }

            Cell cell = topology as Cell;

            if (cell != null)
            {
                return(ToBrep(cell, tolerance));
            }

            CellComplex cellComplex = topology as CellComplex;

            if (cellComplex != null)
            {
                return(ToBreps(cellComplex, tolerance));
            }

            Cluster cluster = topology as Cluster;

            if (cluster != null)
            {
                return(ToGeometries(cluster, tolerance));
            }

            Aperture aperture = topology as Aperture;

            if (aperture != null)
            {
                return(ToGeometry(aperture.Topology, tolerance));
            }

            throw new Exception("The type of the input topology is not recognized.");
        }
Esempio n. 35
0
        // Step to state and continue parsing input.
        // Returns a list of transitions leading to a state that accepts input.
        private List <List <Edge> > EnterState(Edge t)
        {
            int      here = ++entry_value;
            int      index_on_transition = t._index_at_transition;
            int      token_index         = t._index;
            ATNState state       = t._to;
            IToken   input_token = _input[token_index];

            if (_log_parse)
            {
                System.Console.Error.WriteLine("Entry " + here
                                               + " State " + state
                                               + " tokenIndex " + token_index
                                               + " " + input_token.Text
                                               );
            }

            // Upon reaching the cursor, return match.
            bool at_match = input_token.TokenIndex >= _cursor;

            if (at_match)
            {
                if (_log_parse)
                {
                    System.Console.Error.Write("Entry " + here
                                               + " return ");
                }

                List <List <Edge> > res = new List <List <Edge> >()
                {
                    new List <Edge>()
                    {
                        t
                    }
                };
                if (_log_parse)
                {
                    string str = PrintResult(res);
                    System.Console.Error.WriteLine(str);
                }
                return(res);
            }

            if (_visited.ContainsKey(new Pair <ATNState, int>(state, token_index)))
            {
                return(null);
            }

            _visited[new Pair <ATNState, int>(state, token_index)] = true;

            List <List <Edge> > result = new List <List <Edge> >();

            if (_stop_states.Contains(state))
            {
                if (_log_parse)
                {
                    System.Console.Error.Write("Entry " + here
                                               + " return ");
                }

                List <List <Edge> > res = new List <List <Edge> >()
                {
                    new List <Edge>()
                    {
                        t
                    }
                };
                if (_log_parse)
                {
                    string str = PrintResult(res);
                    System.Console.Error.WriteLine(str);
                }
                return(res);
            }

            // Search all transitions from state.
            foreach (Transition transition in state.TransitionsArray)
            {
                List <List <Edge> > matches = null;
                switch (transition.TransitionType)
                {
                case TransitionType.RULE:
                {
                    RuleTransition rule      = (RuleTransition)transition;
                    ATNState       sub_state = rule.target;
                    matches = EnterState(new Edge()
                        {
                            _from   = state,
                            _to     = rule.target,
                            _follow = rule.followState,
                            _label  = rule.Label,
                            _type   = rule.TransitionType,
                            _index  = token_index,
                            _index_at_transition = token_index
                        });
                    if (matches != null && matches.Count == 0)
                    {
                        throw new Exception();
                    }

                    if (matches != null)
                    {
                        List <List <Edge> > new_matches = new List <List <Edge> >();
                        foreach (List <Edge> match in matches)
                        {
                            Edge f           = match.First(); // "to" is possibly final state of submachine.
                            Edge l           = match.Last();  // "to" is start state of submachine.
                            bool is_final    = _stop_states.Contains(f._to);
                            bool is_at_caret = f._index >= _cursor;
                            if (!is_final)
                            {
                                new_matches.Add(match);
                            }
                            else
                            {
                                List <List <Edge> > xxx = EnterState(new Edge()
                                    {
                                        _from  = f._to,
                                        _to    = rule.followState,
                                        _label = null,
                                        _type  = TransitionType.EPSILON,
                                        _index = f._index,
                                        _index_at_transition = f._index
                                    });
                                if (xxx != null && xxx.Count == 0)
                                {
                                    throw new Exception();
                                }

                                if (xxx != null)
                                {
                                    foreach (List <Edge> y in xxx)
                                    {
                                        List <Edge> copy = y.ToList();
                                        foreach (Edge q in match)
                                        {
                                            copy.Add(q);
                                        }
                                        new_matches.Add(copy);
                                    }
                                }
                            }
                        }
                        matches = new_matches;
                    }
                }
                break;

                case TransitionType.PREDICATE:
                    if (CheckPredicate((PredicateTransition)transition))
                    {
                        matches = EnterState(new Edge()
                        {
                            _from  = state,
                            _to    = transition.target,
                            _label = transition.Label,
                            _type  = transition.TransitionType,
                            _index = token_index,
                            _index_at_transition = token_index
                        });
                        if (matches != null && matches.Count == 0)
                        {
                            throw new Exception();
                        }
                    }
                    break;

                case TransitionType.WILDCARD:
                    matches = EnterState(new Edge()
                    {
                        _from  = state,
                        _to    = transition.target,
                        _label = transition.Label,
                        _type  = transition.TransitionType,
                        _index = token_index + 1,
                        _index_at_transition = token_index
                    });
                    if (matches != null && matches.Count == 0)
                    {
                        throw new Exception();
                    }

                    break;

                default:
                    if (transition.IsEpsilon)
                    {
                        matches = EnterState(new Edge()
                        {
                            _from  = state,
                            _to    = transition.target,
                            _label = transition.Label,
                            _type  = transition.TransitionType,
                            _index = token_index,
                            _index_at_transition = token_index
                        });
                        if (matches != null && matches.Count == 0)
                        {
                            throw new Exception();
                        }
                    }
                    else
                    {
                        IntervalSet set = transition.Label;
                        if (set != null && set.Count > 0)
                        {
                            if (transition.TransitionType == TransitionType.NOT_SET)
                            {
                                set = set.Complement(IntervalSet.Of(TokenConstants.MinUserTokenType, _parser.Atn.maxTokenType));
                            }

                            if (set.Contains(input_token.Type))
                            {
                                matches = EnterState(new Edge()
                                {
                                    _from  = state,
                                    _to    = transition.target,
                                    _label = transition.Label,
                                    _type  = transition.TransitionType,
                                    _index = token_index + 1,
                                    _index_at_transition = token_index
                                });
                                if (matches != null && matches.Count == 0)
                                {
                                    throw new Exception();
                                }
                            }
                        }
                    }
                    break;
                }

                if (matches != null)
                {
                    foreach (List <Edge> match in matches)
                    {
                        List <Edge> x = match.ToList();
                        if (t != null)
                        {
                            x.Add(t);
                            Edge prev = null;
                            foreach (Edge z in x)
                            {
                                ATNState ff = z._to;
                                if (prev != null)
                                {
                                    if (prev._from != ff)
                                    {
                                        System.Console.Error.WriteLine("Fail " + PrintSingle(x));
                                        Debug.Assert(false);
                                    }
                                }

                                prev = z;
                            }
                        }
                        result.Add(x);
                    }
                }
            }
            if (result.Count == 0)
            {
                return(null);
            }

            if (_log_parse)
            {
                System.Console.Error.Write("Entry " + here
                                           + " return ");
                string str = PrintResult(result);
                System.Console.Error.WriteLine(str);
            }
            return(result);
        }
 public FiEdge(Edge mEdge)
 {
     this.mEdge = mEdge;
     source     = (FiNode)mEdge.Source.AlgorithmData;
     target     = (FiNode)mEdge.Target.AlgorithmData;
 }
Esempio n. 37
0
 public void Visit(Edge e)
 {
 }
Esempio n. 38
0
        private HashSet <ATNState> ComputeSingle(List <Edge> parse)
        {
            List <Edge>        copy   = parse.ToList();
            HashSet <ATNState> result = new HashSet <ATNState>();

            if (_log_closure)
            {
                System.Console.Error.WriteLine("Computing closure for the following parse:");
                System.Console.Error.Write(PrintSingle(parse));
                System.Console.Error.WriteLine();
            }

            if (!copy.Any())
            {
                return(result);
            }

            Edge last_transaction = copy.First();

            if (last_transaction == null)
            {
                return(result);
            }

            ATNState current_state = last_transaction._to;

            if (current_state == null)
            {
                throw new Exception();
            }

            for (; ;)
            {
                if (_log_closure)
                {
                    System.Console.Error.WriteLine("Getting closure of " + current_state.stateNumber);
                }
                HashSet <ATNState> c = closure(current_state);
                if (_log_closure)
                {
                    System.Console.Error.WriteLine("closure " + string.Join(" ", c.Select(s => s.stateNumber)));
                }
                bool           do_continue = false;
                ATN            atn         = current_state.atn;
                int            rule        = current_state.ruleIndex;
                RuleStartState start_state = atn.ruleToStartState[rule];
                RuleStopState  stop_state  = atn.ruleToStopState[rule];
                bool           changed     = false;
                foreach (ATNState s in c)
                {
                    if (result.Contains(s))
                    {
                        continue;
                    }

                    changed = true;
                    result.Add(s);
                    if (s == stop_state)
                    {
                        do_continue = true;
                    }
                }
                if (!changed)
                {
                    break;
                }

                if (!do_continue)
                {
                    break;
                }

                for (; ;)
                {
                    if (!copy.Any())
                    {
                        break;
                    }

                    copy.RemoveAt(0);
                    if (!copy.Any())
                    {
                        break;
                    }

                    last_transaction = copy.First();
                    if (start_state == last_transaction._from)
                    {
                        copy.RemoveAt(0);
                        if (!copy.Any())
                        {
                            break;
                        }

                        last_transaction = copy.First();
                        // Get follow state of rule-type transition.
                        ATNState from_state = last_transaction._from;
                        if (from_state == null)
                        {
                            break;
                        }

                        ATNState follow_state = last_transaction._follow;
                        current_state = follow_state;
                        if (current_state == null)
                        {
                            throw new Exception();
                        }

                        break;
                    }
                }
            }
            return(result);
        }
        public void MultipleStronglyConnectedComponents()
        {
            var edge12 = new Edge <int>(1, 2);
            var edge23 = new Edge <int>(2, 3);
            var edge24 = new Edge <int>(2, 4);
            var edge25 = new Edge <int>(2, 5);
            var edge31 = new Edge <int>(3, 1);
            var edge34 = new Edge <int>(3, 4);
            var edge46 = new Edge <int>(4, 6);
            var edge56 = new Edge <int>(5, 6);
            var edge57 = new Edge <int>(5, 7);
            var edge64 = new Edge <int>(6, 4);
            var edge75 = new Edge <int>(7, 5);
            var edge78 = new Edge <int>(7, 8);
            var edge86 = new Edge <int>(8, 6);
            var edge87 = new Edge <int>(8, 7);

            var graph = new AdjacencyGraph <int, Edge <int> >();

            graph.AddVerticesAndEdgeRange(new[]
            {
                edge12, edge23, edge24, edge25, edge31, edge34, edge46,
                edge56, edge57, edge64, edge75, edge78, edge86, edge87
            });
            graph.AddVertex(10);

            IMutableBidirectionalGraph <AdjacencyGraph <int, Edge <int> >, CondensedEdge <int, Edge <int>, AdjacencyGraph <int, Edge <int> > > > condensedGraph =
                graph.CondensateStronglyConnected <int, Edge <int>, AdjacencyGraph <int, Edge <int> > >();

            Assert.IsNotNull(condensedGraph);
            Assert.AreEqual(4, condensedGraph.VertexCount);
            Assert.AreEqual(3, condensedGraph.EdgeCount);

            // Condensed edge
            CollectionAssert.AreEquivalent(
                new[] { edge56, edge86 },
                condensedGraph.Edges.ElementAt(0).Edges);
            CollectionAssert.AreEquivalent(
                new[] { edge24, edge34 },
                condensedGraph.Edges.ElementAt(1).Edges);
            CollectionAssert.AreEquivalent(
                new[] { edge25 },
                condensedGraph.Edges.ElementAt(2).Edges);

            // Components
            CollectionAssert.AreEquivalent(
                new[] { 4, 6 },
                condensedGraph.Vertices.ElementAt(0).Vertices);
            CollectionAssert.AreEquivalent(
                new[] { edge46, edge64 },
                condensedGraph.Vertices.ElementAt(0).Edges);

            CollectionAssert.AreEquivalent(
                new[] { 5, 7, 8 },
                condensedGraph.Vertices.ElementAt(1).Vertices);
            CollectionAssert.AreEquivalent(
                new[] { edge57, edge75, edge78, edge87 },
                condensedGraph.Vertices.ElementAt(1).Edges);

            CollectionAssert.AreEquivalent(
                new[] { 1, 2, 3 },
                condensedGraph.Vertices.ElementAt(2).Vertices);
            CollectionAssert.AreEquivalent(
                new[] { edge12, edge23, edge31 },
                condensedGraph.Vertices.ElementAt(2).Edges);

            CollectionAssert.AreEquivalent(
                new[] { 10 },
                condensedGraph.Vertices.ElementAt(3).Vertices);
            CollectionAssert.IsEmpty(condensedGraph.Vertices.ElementAt(3).Edges);
        }
Esempio n. 40
0
    /*
     * Handles interactions with game FSM and player input.
     */
    void Update()
    {
        Player currentTurnPlayer = gamestate.GetCurrentTurnPlayer();

        UpdateHumanCardCounts();

        long   elapsedTicksSinceLastAIAction = DateTime.Now.Ticks - lastAIActionTime.Ticks;
        double secondsSinceLastAIAction      = new TimeSpan(elapsedTicksSinceLastAIAction).TotalSeconds;


        //AI Interaction
        if (currentTurnPlayer.isAI)
        {
            if (secondsSinceLastAIAction >= FORCED_TIME_BETWEEN_AI_ACTIONS)
            {
                System.Random rand = new System.Random();

                //Initial settlement placement
                if (curState == GameState.State.placeSettlement)
                {
                    List <Node> locationOptions = AIEngine.GetFavorableStartingLocations(board);

                    //Attempt to place elements in decreasing score order
                    for (int i = 0; i < locationOptions.Count; i++)
                    {
                        if (board.CanBuildSettlementHere(locationOptions[i].visual.transform, currentTurnPlayer, true))
                        {
                            lastStructurePlaced = board.PlaceSettlement(locationOptions[i].visual.transform, currentTurnPlayer, false);
                            break;
                        }
                    }
                    IncrementState();
                    UpdateTurnInfo("Placing Initial Road", currentTurnPlayer.id);
                }
                //Initial road placement
                else if (curState == GameState.State.placeRoad)
                {
                    List <Edge> favorableRoads = AIEngine.GetFavorableRoadExpansions(currentTurnPlayer, board, lastStructurePlaced);

                    foreach (Edge road in favorableRoads)
                    {
                        if (board.CanBuildRoadHere(road.visual.transform, currentTurnPlayer))
                        {
                            lastRoadPlaced = board.PlaceRoad(road.visual.transform, currentTurnPlayer, false);
                            break;
                        }
                    }

                    IncrementState();
                }
                //Roll dice
                else if (curState == GameState.State.roll)
                {
                    if (rollForAI)
                    {
                        if (Input.GetMouseButtonDown(0))
                        {
                            Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                            RaycastHit hit;
                            if (interactDebug)
                            {
                                print("mouse press");
                            }
                            if (Physics.Raycast(ray, out hit))
                            {
                                if (hit.transform == dice.transform)
                                {
                                    IncrementState();
                                    updateDice();
                                }
                            }
                        }
                    }
                    else
                    {
                        IncrementState();
                        updateDice();
                    }
                }
                //Trade with players
                else if (curState == GameState.State.trade)
                {
                    proposedObjective = null;

                    if (debugMessages)
                    {
                        print("~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~");
                    }

                    //TODO
                    List <AIEngine.Objective> objectives = AIEngine.GetObjectives(currentTurnPlayer, board, gamestate);

                    // Trade With Other Players
                    int  tradeOffersThisTurn     = 0;
                    bool hasAnyOfferBeenAccepted = false;
                    foreach (AIEngine.Objective objective in objectives)
                    {
                        if (objective.Score() > 0 && objective.TotalCardsNeeded() > 0 && tradeOffersThisTurn < 3 && !hasAnyOfferBeenAccepted)
                        {
                            TradeOffer offer = currentTurnPlayer.generateAITradeRequest(gamestate.getTurnCounter(), objective);

                            if (null != offer)
                            {
                                if (debugMessages)
                                {
                                    print("TRADENUM: " + tradeOffersThisTurn + " | " + gamestate.GetCurrentTurnPlayer() + "\nATTEMPTING TO TRADE WITH OTHER PLAYERS TO ACHIEVE OBJECT: " + objective.GetObjectiveScore());
                                }

                                tradeOffersThisTurn++;
                                hasAnyOfferBeenAccepted = tradeManager.ExecuteTradeOfferNotification(offer);
                                proposedObjective       = objective;
                            }
                        }
                    }

                    // Trade With Bank
                    foreach (AIEngine.Objective objective in objectives)
                    {
                        if (objective.Score() > 0 && objective.TotalCardsNeeded() > 0 && !hasAnyOfferBeenAccepted)
                        {
                            if (debugMessages)
                            {
                                print(gamestate.GetCurrentTurnPlayer() + " ATTEMPTING TO TRADE WITH BANK");
                            }

                            TradeOffer offer = currentTurnPlayer.generateAITradeWithBank(objective);

                            if (null != offer)
                            {
                                tradeManager.ExecuteTradeWithBank(offer, gamestate.GetCurrentTurnPlayer());
                                hasAnyOfferBeenAccepted = true;
                            }
                        }
                    }

                    if (!hasAnyOfferBeenAccepted && debugMessages)
                    {
                        print(gamestate.GetCurrentTurnPlayer() + " MADE NO TRADES THIS TURN");
                    }

                    IncrementState();
                    FORCED_TIME_BETWEEN_AI_ACTIONS = 0f;                     //TODO Remove
                }
                //Building phase
                else if (curState == GameState.State.place)
                {
                    FORCED_TIME_BETWEEN_AI_ACTIONS = 0f;                     //TODO Remove

                    //TODO
                    List <AIEngine.Objective> objectives = AIEngine.GetObjectives(currentTurnPlayer, board, gamestate);
                    foreach (AIEngine.Objective objective in objectives)
                    {
                        print(objective);
                    }

                    foreach (AIEngine.Objective objective in objectives)
                    {
                        if (objective.TotalCardsNeeded() == 0)
                        {
                            AIEngine.PerformObjective(objective, board);
                            break;
                        }
                    }

                    /*//Attempt main objective that we traded for
                     * if (proposedObjective != null) {
                     *      AIEngine.PerformObjective(proposedObjective, board);
                     * }
                     * //Attempt to get -any- objective to work
                     * else {
                     *      List<AIEngine.Objective> objectives = AIEngine.GetObjectives(currentTurnPlayer, board, gamestate);
                     *      foreach (AIEngine.Objective objective in objectives) {
                     *              if (AIEngine.PerformObjective(objective, board)) {
                     *                      break;
                     *              }
                     *      }
                     * }*/

                    IncrementState();
                }
                //Place robber
                else if (curState == GameState.State.robber)
                {
                    Player      competitorPlayer   = gamestate.BiggestCompetitorToPlayer(currentTurnPlayer);
                    List <Tile> possiblePlacements = AIEngine.GetListOfRobberPlacements(currentTurnPlayer, competitorPlayer, board);

                    bool robberPlaced = false;

                    //Attempt to place robber on recommended tiles
                    foreach (Tile tile in possiblePlacements)
                    {
                        int index = board.tiles.IndexOf(tile);
                        if (board.PlaceRobber(board.tileHitboxes[index].transform))
                        {
                            robberPlaced = true;
                            break;
                        }
                    }

                    //If for some reason we're out of recommendations...
                    while (!robberPlaced)
                    {
                        print("ERROR: ATTEMPTING TO RANDOMLY PLACE ROBBER!");
                        int tileIndex = rand.Next(board.tiles.Count);
                        robberPlaced = board.PlaceRobber(board.tileHitboxes[tileIndex].transform);
                    }

                    IncrementState();
                }

                lastAIActionTime = DateTime.Now;                 //Prevent AI from acting too quickly
            }
        }
        //Human Interaction
        else
        {
            if (Input.GetMouseButtonDown(0))
            {
                Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;
                if (interactDebug)
                {
                    print("mouse press");
                }
                if (Physics.Raycast(ray, out hit))
                {
                    //Need to place something
                    if (curState == GameState.State.placeSettlement || curState == GameState.State.placeRoad || curState == GameState.State.place)
                    {
                        bool isSetup = (curState == GameState.State.placeSettlement || curState == GameState.State.placeRoad);

                        //Choose what to build or use preselected
                        if (curState == GameState.State.place)
                        {
                            if (hit.transform == roadSelector.transform && currentTurnPlayer.CanBuildRoad())
                            {
                                objectToBuild = hit.transform;
                                if (interactDebug)
                                {
                                    print("on a building");
                                }
                            }
                            else if (hit.transform == citySelector.transform && currentTurnPlayer.CanBuildCity())
                            {
                                objectToBuild = hit.transform;
                                if (interactDebug)
                                {
                                    print("on a building");
                                }
                            }
                            else if (hit.transform == settlementSelector.transform && currentTurnPlayer.CanBuildSettlement())
                            {
                                objectToBuild = hit.transform;
                                if (interactDebug)
                                {
                                    print("on a building");
                                }
                            }
                            else if (hit.transform == endTurnButton.transform)
                            {
                                IncrementState();
                            }
                        }
                        else if (curState == GameState.State.placeSettlement)
                        {
                            objectToBuild = settlementSelector.transform;
                        }
                        else if (curState == GameState.State.placeRoad)
                        {
                            objectToBuild = roadSelector.transform;
                        }

                        if (objectToBuild != null)
                        {
                            if (objectToBuild == roadSelector.transform && board.roadHitboxes.ContainsKey(hit.transform))
                            {
                                Node structureToBuildNear = (curState == GameState.State.placeRoad) ? lastStructurePlaced : null;

                                if (board.CanBuildRoadHere(hit.transform, currentTurnPlayer, structureToBuildNear, true))
                                {
                                    lastRoadPlaced = board.PlaceRoad(hit.transform, currentTurnPlayer, !isSetup);
                                    objectToBuild  = null;
                                    if (interactDebug)
                                    {
                                        print("road built!");
                                    }
                                    if (curState == GameState.State.placeRoad)
                                    {
                                        IncrementState();
                                    }
                                }
                            }
                            else if (objectToBuild == settlementSelector.transform && board.settlementHitboxes.ContainsKey(hit.transform))
                            {
                                if (board.CanBuildSettlementHere(hit.transform, currentTurnPlayer, isSetup, true))
                                {
                                    lastStructurePlaced = board.PlaceSettlement(hit.transform, currentTurnPlayer, !isSetup);
                                    objectToBuild       = null;
                                    if (interactDebug)
                                    {
                                        print("settlement built!");
                                    }
                                    if (curState == GameState.State.placeSettlement)
                                    {
                                        IncrementState();
                                    }
                                }
                            }
                            else if (objectToBuild == citySelector.transform && board.settlements.ContainsKey(hit.transform))
                            {
                                if (board.CanBuildCityHere(hit.transform, currentTurnPlayer, true))
                                {
                                    lastStructurePlaced = board.PlaceCity(hit.transform, currentTurnPlayer);
                                    objectToBuild       = null;
                                    if (interactDebug)
                                    {
                                        print("city built!");
                                    }
                                }
                            }
                        }
                    }
                    //Place robber on a chit
                    else if (curState == GameState.State.robber)
                    {
                        if (board.PlaceRobber(hit.transform))
                        {
                            IncrementState();                              //increment if successfully placed
                        }
                    }
                    //Request trades with other players or bank
                    else if (curState == GameState.State.trade)
                    {
                        UpdateTradePanel(hit.transform);
                        if (hit.transform == endTradeButton.transform)
                        {
                            IncrementState();
                        }
                        else if (hit.transform == offerTradeButton.transform)
                        {
                            OfferTrade();
                        }
                        else if (hit.transform == endTurnButton.transform)
                        {
                            IncrementState();
                            IncrementState();
                        }


                        //tradeManager.ExecuteTradeWithBank(offer, gamestate.GetCurrentTurnPlayer());
                    }
                    //listen for click on dice
                    else if (curState == GameState.State.roll)
                    {
                        if (interactDebug)
                        {
                            print(hit.transform == dice.transform);
                        }
                        if (hit.transform == dice.transform)
                        {
                            IncrementState();
                            updateDice();
                        }
                    }
                    else
                    {
                        if (interactDebug)
                        {
                            print("should not be here");
                        }
                    }
                }
            }
        }
    }
    void KMeansClustering()
    {
        print("k-means started..");

        // calculate centroid points
        int k_means = k_clusters;

        int[] k_calculations = new int[k_means];
        for (int i = 0; i < k_means; i++)
        {
            decimal f        = Decimal.Divide(i, k_means);
            float   division = (float)f;
            k_calculations[i] = Mathf.RoundToInt(colombs_nodes.Count * (division));
            print("k means calculation: " + f + " = " + i + " / " + k_means);
        }
        print("step 0, k_means = " + k_means);
        int k_num = 0;

        foreach (int num in k_calculations)
        {
            //print(k_num +" : "+num);
            k_num++;
        }

        // Assigning centroids
        GameObject[] centroids    = new GameObject[k_means];
        VisualNode[] vs_c         = new VisualNode[k_means];
        ArrayList[]  clusternodes = new ArrayList[k_means];
        for (int i = 0; i < k_means; i++)
        {
            centroids[i]          = (GameObject)colombs_nodes[k_calculations[i]];
            vs_c[i]               = centroids[i].GetComponent <VisualNode>();
            vs_c[i].distinct_node = true;
            Vector3 localScale = vs_c[i].transform.localScale;
            if (transform.localScale.x < 2)
            {
                //vs_c[i].transform.localScale = new Vector3(localScale.x * 2, localScale.y * 2, localScale.z * 2);
            }
            clusternodes[i] = new ArrayList();
            clusternodes[i].Add(vs_c[i]);
        }
        print("step 1");

        // Assigning nodes to centroids on Euclidean Distance
        foreach (GameObject g in colombs_nodes)
        {
            if (centroids.Contains(g) == false)
            {
                VisualNode n          = g.GetComponent <VisualNode>();
                float[]    dist_array = new float[k_means];
                for (int i = 0; i < dist_array.Length; i++)
                {
                    dist_array[i] = Vector3.Distance(g.transform.localPosition, centroids[i].transform.localPosition);
                }
                float smallest_dist  = dist_array.Min();
                int   smallest_index = 0;
                for (int i = 0; i < dist_array.Length; i++)
                {
                    if (dist_array[i] == smallest_dist)
                    {
                        smallest_index = i;
                    }
                }
                clusternodes[smallest_index].Add(n);
            }
        }
        print("step 2");

        // Create Cluster Objects
        GameObject[] clusterObjects = new GameObject[k_means];
        for (int i = 0; i < k_means; i++)
        {
            clusterObjects[i] = new GameObject();
            clusterObjects[i].AddComponent <ClusterBehaviour>();
            clusterObjects[i].GetComponent <ClusterBehaviour>().setArrayList(clusternodes[i]);
            clusterObjects[i].GetComponent <ClusterBehaviour>().setClusterCentre(centroids[i]);
        }
        print("step 3");

        int cluster_index = 0;

        // Go through the three centroids and generate the clusters
        foreach (GameObject cluster_object in clusterObjects)
        {
            ClusterBehaviour clu = cluster_object.GetComponent <ClusterBehaviour>();
            // return nodes of cluster c
            ArrayList cluster_array = clu.returnClusterNodes();
            // setup meshfilters for child objects
            MeshFilter[] meshFilters = new MeshFilter[clu.returnClusterNodes().Count + 1];
            // combine instance mesh array
            CombineInstance[] combine = new CombineInstance[meshFilters.Length];
            // Color of cluster
            Color col = UnityEngine.Random.ColorHSV(0.1f, 0.8f, 0.7f, 1f, 0.5f, 1f);


            // go through each child node and add to meshFilter array
            // first cluster node
            GameObject first_node = clu.gameObject;
            meshFilters[0]       = centroids[cluster_index].GetComponent <MeshFilter>();
            combine[0].mesh      = meshFilters[0].sharedMesh;
            combine[0].transform = meshFilters[0].transform.localToWorldMatrix;
            meshFilters[0].gameObject.SetActive(false);
            nodes_already_clustered.Add(first_node.GetComponent <VisualNode>());
            // add boxcollider for each node
            BoxCollider b = cluster_object.AddComponent <BoxCollider>();
            b.size      = new Vector3(0.05f, 0.05f, 0.05f);
            b.center    = clu.transform.position;
            b.isTrigger = true;

            /*
             * ArrayList edge = n.getAllocatedEdges();
             * if (edge.Count > 0) {
             *  GameObject index0 = edge[0] as GameObject;
             *  foreach (GameObject ga in edge) {
             *      LineRenderer l = ga.GetComponent<LineRenderer>();
             *      l.material.SetColor("_TintColor", new Color(col.r, col.g, col.b, 0.01f));
             *  }
             * }
             */

            int k = 1;
            foreach (VisualNode v in clu.returnClusterNodes())
            {
                if (nodes_already_clustered.Contains(v) == false)
                {
                    GameObject g = v.gameObject;

                    meshFilters[k]       = g.GetComponent <MeshFilter>();
                    combine[k].mesh      = meshFilters[k].sharedMesh;
                    combine[k].transform = meshFilters[k].transform.localToWorldMatrix;
                    meshFilters[k].gameObject.SetActive(false);
                    //nodes.Add(v);
                    nodes_already_clustered.Add(v);
                    // add boxcollider for each node
                    BoxCollider b1 = cluster_object.AddComponent <BoxCollider>();
                    b1.size      = new Vector3(0.05f, 0.05f, 0.05f);
                    b1.center    = g.transform.position;
                    b1.isTrigger = true;
                    ArrayList edge1 = v.getAllocatedEdges();
                    v.transform.parent = cluster_object.transform;
                    vs_c[cluster_index].addClusterNode(v);

                    if (edge1.Count > 0)
                    {
                        GameObject index0 = edge1[0] as GameObject;

                        foreach (GameObject ga in edge1)
                        {
                            //LineRenderer l = ga.GetComponent<LineRenderer>();
                            //l.material.SetColor("_TintColor", new Color(col.r, col.g, col.b, 0.01f));
                        }
                    }
                }
                else
                {
                }
                k++;
            }

            // set the parent of the cluster to visualization object
            cluster_object.transform.parent = this.transform;
            // set the name of the cluster
            //cluster_object.transform.name = first_node.transform.name + " cluster";

            // add meshfilter to new cluster
            cluster_object.AddComponent <MeshFilter>();
            cluster_object.AddComponent <MeshRenderer>();
            cluster_object.GetComponent <MeshFilter>().mesh = new Mesh();
            // combine all the meshes in the mesh array "combine"
            cluster_object.GetComponent <MeshFilter>().mesh.CombineMeshes(combine);
            cluster_object.GetComponent <MeshRenderer>().material = nodeMat;
            // assign random color to cluster
            cluster_object.GetComponent <MeshRenderer>().material.color = col;
            clusters.Add(clu);
            cluster_index++;
        }
        EdgeManager edgeManager = Camera.main.GetComponent <EdgeManager> ();
        ArrayList   glEdges     = edgeManager.getEdges();

        print(glEdges.Count + "glEdge count");
        for (int i = 0; i < glEdges.Count; i++)
        {
            Edge e = (Edge)glEdges[i];
            e.setColor(e.getTransformRef().parent.GetComponent <MeshRenderer>().material.color);
        }
        print("step 4 DONE");
        clusterAllNodes         = true;
        graph_layout_recognized = false;
    }
Esempio n. 42
0
        public static bool Generate(BuildRMesh mesh, BuildRCollider collider, Vector2[] points, int[] facadeIndices, float roofBaseHeight, IVolume volume, Rect clampUV)
        {
            Roof           design     = volume.roof;
            OffsetSkeleton offsetPoly = new OffsetSkeleton(points);

            offsetPoly.direction = 1;
            offsetPoly.Execute();
            Shape shape       = offsetPoly.shape;
            int   submesh     = mesh.submeshLibrary.SubmeshAdd(design.mainSurface); // surfaceMapping.IndexOf(design.mainSurface);
            int   wallSubmesh = mesh.submeshLibrary.SubmeshAdd(design.wallSurface); //surfaceMapping.IndexOf(design.wallSurface);

            if (shape == null)
            {
                return(false);
            }

            List <Edge> edges     = new List <Edge>(shape.edges);
            List <Edge> baseEdges = new List <Edge>(shape.baseEdges);

            float shapeHeight  = shape.HeighestPoint();
            float designHeight = design.height;
            float heightScale  = designHeight / shapeHeight;

            Vector2 clampUVScale = Vector2.one;

            if (clampUV.width > 0)
            {
                FlatBounds bounds = new FlatBounds();
                for (int fvc = 0; fvc < points.Length; fvc++)
                {
                    bounds.Encapsulate(points[fvc]);
                }
                clampUVScale.x = bounds.width / clampUV.width;
                clampUVScale.y = bounds.height / clampUV.height;
            }

            Dictionary <Node, int>          shapeConnectionCount = new Dictionary <Node, int>();
            Dictionary <Node, List <Node> > shapeConnections     = new Dictionary <Node, List <Node> >();
            int edgeCount = edges.Count;

            for (int e = 0; e < edgeCount; e++)
            {
                Edge edge = edges[e];

                if (edge.length < Mathf.Epsilon)
                {
                    continue;
                }

                if (!shapeConnectionCount.ContainsKey(edge.nodeA))
                {
                    shapeConnectionCount.Add(edge.nodeA, 0);//start at zero - we need two edges to make a shape...
                    shapeConnections.Add(edge.nodeA, new List <Node> {
                        edge.nodeB
                    });
                }
                else
                {
                    shapeConnectionCount[edge.nodeA]++;
                    if (!shapeConnections[edge.nodeA].Contains(edge.nodeB))
                    {
                        shapeConnections[edge.nodeA].Add(edge.nodeB);
                    }
                }

                if (!shapeConnectionCount.ContainsKey(edge.nodeB))
                {
                    shapeConnectionCount.Add(edge.nodeB, 0);//start at zero - we need two edges to make a shape...
                    shapeConnections.Add(edge.nodeB, new List <Node> {
                        edge.nodeA
                    });
                }
                else
                {
                    shapeConnectionCount[edge.nodeB]++;
                    if (!shapeConnections[edge.nodeB].Contains(edge.nodeA))
                    {
                        shapeConnections[edge.nodeB].Add(edge.nodeA);
                    }
                }
            }

            int baseEdgeCount = baseEdges.Count;

            for (int b = 0; b < baseEdgeCount; b++)
            {
                Edge baseEdge = baseEdges[b];
                Node nodeA    = baseEdge.nodeA;
                Node nodeB    = baseEdge.nodeB;

                Node        currentNode = nodeA;
                Node        lastNode    = nodeB;
                int         itMax       = 50;
                List <Node> edgeShape   = new List <Node>()
                {
                    nodeA
                };

                while (currentNode != nodeB)
                {
                    List <Node> nodeConnections     = shapeConnections[currentNode];
                    int         nodeConnectionCount = nodeConnections.Count;
                    float       minAngle            = Mathf.Infinity;
                    Node        nextNode            = null;
                    Vector2     currentDirection    = (currentNode.position - lastNode.position).normalized;
                    for (int n = 0; n < nodeConnectionCount; n++)
                    {
                        Node connectingNode = nodeConnections[n];
                        if (connectingNode == lastNode)
                        {
                            continue;
                        }
                        Vector2 nextDirection = (connectingNode.position - currentNode.position).normalized;
                        float   nodeAngle     = JMath.SignAngleDirection(currentDirection, nextDirection);
                        if (nodeAngle < minAngle)
                        {
                            minAngle = nodeAngle;
                            nextNode = connectingNode;
                        }
                    }
                    if (nextNode != null)
                    {
                        edgeShape.Add(nextNode);
                        lastNode    = currentNode;
                        currentNode = nextNode;
                    }


                    itMax--;
                    if (itMax < 0)
                    {
                        break;
                    }
                }

                int edgeShapeCount = edgeShape.Count;
                if (edgeShapeCount < 3)
                {
                    continue;
                }
//                Debug.Log("Generate edgeShapeCount "+ edgeShapeCount);

                Vector3[] verts = new Vector3[edgeShapeCount];

                Vector2[] uvs = new Vector2[edgeShapeCount];
                Vector3   baseShapeDirection = ShapeOffset.Utils.ToV3(nodeB.position - nodeA.position).normalized;
                float     uvAngle            = JMath.SignAngle(new Vector2(baseShapeDirection.x, baseShapeDirection.z).normalized) - 90;

                Vector2[] faceShape = new Vector2[edgeShapeCount];
                Vector3[] normals   = new Vector3[edgeShapeCount];
                Vector4[] tangents  = new Vector4[edgeShapeCount];
                //                Vector3 normal = Vector3.up;//BuildRMesh.CalculateNormal(); TODO
                Vector4 tangent = BuildRMesh.CalculateTangent(baseShapeDirection);
                for (int i = 0; i < edgeShapeCount; i++)//what on earth did I write here?
                {
                    Vector3 newVert = new Vector3(edgeShape[i].position.x, edgeShape[i].height * heightScale + roofBaseHeight, edgeShape[i].position.y);
                    verts[i] = newVert;

                    Vector2 baseUV = new Vector2(newVert.x - verts[0].x, newVert.z - verts[0].z);
                    Vector2 newUV  = Vector2.zero;
                    if (i != 0)
                    {
                        newUV = JMath.Rotate(baseUV, uvAngle);
                    }
                    if (clampUV.width > Mathf.Epsilon)
                    {
                        newUV.x = Mathf.Clamp(clampUV.x + newUV.x / clampUVScale.x, clampUV.xMin, clampUV.xMax);
                        newUV.y = Mathf.Clamp(clampUV.y + newUV.y / clampUVScale.y, clampUV.yMin, clampUV.yMax);
                    }
                    else
                    {
                        if (i != 0)
                        {
                            float faceHeight = edgeShape[i].height * heightScale;
                            newUV.y = Mathf.Sqrt((newUV.y * newUV.y) + (faceHeight * faceHeight));//hypotenuse of roof to give length of roof face
                            if (design.mainSurface != null)
                            {
                                newUV = design.mainSurface.CalculateUV(newUV);
                            }
                        }
                    }
                    uvs[i] = newUV;

                    faceShape[i] = edgeShape[i].position;//used for triangulation
                    //                    normals[i] = normal;
                    tangents[i] = tangent;
                }
//                int[] tris = EarClipper.Triangulate(faceShape, 0, -1);
                int[] tris     = Poly2TriWrapper.Triangulate(faceShape, true);
                int   triCount = tris.Length;

                Vector3 normal = (verts.Length > 2 && triCount > 2) ? BuildRMesh.CalculateNormal(verts[tris[0]], verts[tris[1]], verts[tris[2]]) : Vector3.up;
                for (int i = 0; i < edgeShapeCount; i++)
                {
                    normals[i] = normal;
                }

                mesh.AddData(verts, uvs, tris, normals, tangents, submesh);

                //gable
                bool isGabled = volume[facadeIndices[b]].isGabled;
                if (isGabled)
                {
                    for (int t = 0; t < triCount; t += 3)
                    {
                        if (tris[t] == 0 || tris[t + 1] == 0 || tris[t + 2] == 0)
                        {
                            int beB = edgeShapeCount - 1;
                            if (tris[t] == beB || tris[t + 1] == beB || tris[t + 2] == beB)
                            {
                                Vector3 b0       = verts[0];
                                Vector3 b1       = verts[beB];
                                Vector3 g0       = b0;
                                Vector3 g1       = b1;
                                int     topIndex = 0;
                                for (int tx = 0; tx < 3; tx++)
                                {
                                    if (tris[t + tx] != 0 && tris[t + tx] != beB)
                                    {
                                        topIndex = tris[t + tx];
                                    }
                                }
                                Vector3 b2 = verts[topIndex];

                                Vector3 baseV = b1 - b0;
                                Vector3 dir   = baseV.normalized;
                                Vector3 face  = Vector3.Cross(Vector3.up, dir).normalized;
                                Vector3 up    = Vector3.Project(b2 - b0, Vector3.up);

                                //clear triangle
                                tris[t]     = 0;
                                tris[t + 1] = 0;
                                tris[t + 2] = 0;

                                bool  simpleGable      = volume[facadeIndices[b]].simpleGable;
                                Gable gableStyle       = volume[facadeIndices[b]].gableStyle;
                                float thickness        = volume[facadeIndices[b]].gableThickness;
                                float additionalHeight = volume[facadeIndices[b]].gableHeight;
                                float height           = up.magnitude + additionalHeight;

                                if (simpleGable || gableStyle != null)
                                {
                                    Vector3 pitchVectorA = (b2 - b0).normalized;
                                    Vector3 pitchVectorB = (b2 - b1).normalized;
                                    float   angle        = Vector3.Angle(-face, pitchVectorA);
                                    float   scale        = Mathf.Cos(angle / 57.2957795f);
                                    b0 += pitchVectorA * (thickness * (1 / scale));
                                    b1 += pitchVectorB * (thickness * (1 / scale));
                                }

                                Vector3 center = Vector3.Lerp(b0, b1, 0.5f);
                                up = Vector3.Project(b2 - b0, Vector3.up); //recalculate after b change(?)
                                Vector3 b3 = center + up;
                                if (simpleGable)                           //generate a simple gable
                                {
                                    //generate simple gable based on roof
                                    Vector3 gCenter = Vector3.Lerp(g0, g1, 0.5f);
                                    Vector3 gBaseUp = Vector3.up * additionalHeight;
                                    Vector3 gUp     = up.normalized * height;
                                    Vector3 gBack   = -face * thickness;
                                    //todo further calculations
                                    //face
                                    mesh.AddPlane(g0, g1, g0 + gBaseUp, g1 + gBaseUp, wallSubmesh);
                                    mesh.AddTri(g1 + gBaseUp, g0 + gBaseUp, gCenter + gUp, dir, wallSubmesh);
                                    //backface
                                    mesh.AddPlane(g1 + gBack, g0 + gBack, g1 + gBaseUp + gBack, g0 + gBaseUp + gBack, wallSubmesh);
                                    mesh.AddTri(g0 + gBack + gBaseUp, g1 + gBack + gBaseUp, b3 + gBaseUp, -dir, wallSubmesh);
                                    //left
                                    mesh.AddPlane(g0 + gBack, g0, g0 + gBaseUp + gBack, g0 + gBaseUp, wallSubmesh);
                                    mesh.AddPlane(g0 + gBaseUp + gBack, g0 + gBaseUp, b3 + gBaseUp, gCenter + gUp, wallSubmesh);
                                    //right
                                    mesh.AddPlane(g1, g1 + gBack, g1 + gBaseUp, g1 + gBaseUp + gBack, wallSubmesh);
                                    mesh.AddPlane(g1 + gBaseUp, g1 + gBaseUp + gBack, gCenter + gUp, b3 + gBaseUp, wallSubmesh);
                                }
                                else if (volume[facadeIndices[b]].gableStyle != null)
                                {
                                    Vector2 baseUV = new Vector2(0, volume.planHeight);
                                    GableGenerator.Generate(ref mesh, gableStyle, g0, g1, height, thickness, baseUV);
                                }
                                else
                                {
                                    mesh.AddTri(b0, b3, b1, dir, submesh);//face - no separate gable
                                }

                                mesh.AddTri(b0, b2, b3, face, submesh);  //left
                                mesh.AddTri(b1, b3, b2, -face, submesh); //right
                            }
                        }
                    }
                }
            }

            return(true);
        }
    //Optimisation Test
    void CombineMeshes()
    {
        // go through each clusterNode parent
        foreach (VisualNode n in clusterNodes)
        {
            // arraylist to be added to cluster late
            ArrayList nodes = new ArrayList();
            // setup meshfilters for child objects
            MeshFilter[] meshFilters = new MeshFilter[n.getClusterNodes().Count + 1];
            // combine instance mesh array
            CombineInstance[] combine = new CombineInstance[meshFilters.Length];
            //stop center from being combined
            nodes_already_clustered.Add(n);
            // Create a new cluster gameobject
            GameObject newCluster = new GameObject();

            // Color of cluster
            Color col = UnityEngine.Random.ColorHSV(0.1f, 0.8f, 0.7f, 1f, 0.5f, 1f);


            // go through each child node and add to meshFilter array

            // first cluster node
            GameObject c1 = n.gameObject;
            meshFilters[0]       = c1.GetComponent <MeshFilter>();
            combine[0].mesh      = meshFilters[0].sharedMesh;
            combine[0].transform = meshFilters[0].transform.localToWorldMatrix;
            meshFilters[0].gameObject.SetActive(false);
            nodes.Add(n);
            nodes_already_clustered.Add(n);
            // add boxcollider for each node
            //BoxCollider b = newCluster.AddComponent<BoxCollider>();
            //b.size = new Vector3(0.05f, 0.05f, 0.05f);
            //b.center = c1.transform.position;
            //b.isTrigger = true;
            ArrayList edge = n.getAllocatedEdges();
            if (edge.Count > 0)
            {
                GameObject index0 = edge[0] as GameObject;
                foreach (GameObject ga in edge)
                {
                    LineRenderer l = ga.GetComponent <LineRenderer>();
                    l.material.SetColor("_TintColor", new Color(col.r, col.g, col.b, 0.01f));
                }
            }

            int k = 1;

            foreach (VisualNode v in n.getClusterNodes())
            {
                if (nodes_already_clustered.Contains(v) == false)
                {
                    GameObject g = v.gameObject;
                    meshFilters[k]       = g.GetComponent <MeshFilter>();
                    combine[k].mesh      = meshFilters[k].sharedMesh;
                    combine[k].transform = meshFilters[k].transform.localToWorldMatrix;
                    meshFilters[k].gameObject.SetActive(false);
                    nodes.Add(v);
                    nodes_already_clustered.Add(v);
                    // add boxcollider for each node
                    //BoxCollider b1 = newCluster.AddComponent<BoxCollider>();
                    //b1.size = new Vector3(0.05f, 0.05f, 0.05f);
                    //b1.center = g.transform.position;
                    //b1.isTrigger = true;
                    v.transform.parent = n.transform;
                    ArrayList edge1 = v.getAllocatedEdges();
                    if (edge1.Count > 0)
                    {
                        GameObject index0 = edge1[0] as GameObject;
                        foreach (GameObject ga in edge1)
                        {
                            LineRenderer l = ga.GetComponent <LineRenderer>();
                            l.material.SetColor("_TintColor", new Color(col.r, col.g, col.b, 0.01f));
                        }
                    }
                }
                else
                {
                }
                k++;
            }

            // set the parent of the cluster to visualization object
            newCluster.transform.parent = this.transform;
            // set the name of the cluster
            newCluster.transform.name = n.transform.name + " cluster";

            // add meshfilter to new cluster
            newCluster.AddComponent <MeshFilter>();
            newCluster.AddComponent <MeshRenderer>();
            newCluster.GetComponent <MeshFilter>().mesh = new Mesh();
            // combine all the meshes in the mesh array "combine"
            newCluster.GetComponent <MeshFilter>().mesh.CombineMeshes(combine);
            newCluster.GetComponent <MeshRenderer>().material = nodeMat;
            // assign random color to cluster
            newCluster.GetComponent <MeshRenderer>().material.color = col;
            // add clustercode
            newCluster.AddComponent <ClusterBehaviour>();
            ClusterBehaviour c = newCluster.GetComponent <ClusterBehaviour>();
            n.transform.parent = c.transform;
            c.setArrayList(nodes);
            c.setClusterCentre(n.gameObject);


            // lastly, add collider (trying box colliders)
            //newCluster.AddComponent<MeshCollider>();
        }
        EdgeManager edgeManager = Camera.main.GetComponent <EdgeManager> ();
        ArrayList   glEdges     = edgeManager.getEdges();

//		print (glEdges.Count + "glEdge count");
        for (int i = 0; i < glEdges.Count; i++)
        {
            Edge e = (Edge)glEdges[i];
            e.setColor(e.getTransformRef().parent.parent.GetComponent <MeshRenderer>().material.color);
        }

        clusterAllNodes         = true;
        graph_layout_recognized = false;

        Camera.main.cullingMask = cullingmask;
    }
Esempio n. 44
0
            private void clip_line(Edge e)
            {
                double pxmin, pxmax, pymin, pymax;
                Site   s1, s2;

                double x1 = e.reg[0].coord.x;
                double y1 = e.reg[0].coord.y;
                double x2 = e.reg[1].coord.x;
                double y2 = e.reg[1].coord.y;
                double x  = x2 - x1;
                double y  = y2 - y1;

                // if the distance between the two points this line was created from is
                // less than the square root of 2, then ignore it
                if ((x * x) + (y * y) < minSquareDistanceBetweenSites)
                {
                    return;
                }
                pxmin = borderMinX;
                pymin = borderMinY;
                pxmax = borderMaxX;
                pymax = borderMaxY;

                if (e.a == 1.0 && e.b >= 0.0)
                {
                    s1 = e.ep[1];
                    s2 = e.ep[0];
                }
                else
                {
                    s1 = e.ep[0];
                    s2 = e.ep[1];
                }

                if (e.a == 1.0)
                {
                    y1 = pymin;

                    if (s1 != null && s1.coord.y > pymin)
                    {
                        y1 = s1.coord.y;
                    }
                    if (y1 > pymax)
                    {
                        y1 = pymax;
                    }
                    x1 = e.c - e.b * y1;
                    y2 = pymax;

                    if (s2 != null && s2.coord.y < pymax)
                    {
                        y2 = s2.coord.y;
                    }
                    if (y2 < pymin)
                    {
                        y2 = pymin;
                    }
                    x2 = e.c - e.b * y2;
                    if (((x1 > pxmax) & (x2 > pxmax)) | ((x1 < pxmin) & (x2 < pxmin)))
                    {
                        return;
                    }

                    if (x1 > pxmax)
                    {
                        x1 = pxmax;
                        y1 = (e.c - x1) / e.b;
                    }
                    if (x1 < pxmin)
                    {
                        x1 = pxmin;
                        y1 = (e.c - x1) / e.b;
                    }
                    if (x2 > pxmax)
                    {
                        x2 = pxmax;
                        y2 = (e.c - x2) / e.b;
                    }
                    if (x2 < pxmin)
                    {
                        x2 = pxmin;
                        y2 = (e.c - x2) / e.b;
                    }
                }
                else
                {
                    x1 = pxmin;
                    if (s1 != null && s1.coord.x > pxmin)
                    {
                        x1 = s1.coord.x;
                    }
                    if (x1 > pxmax)
                    {
                        x1 = pxmax;
                    }
                    y1 = e.c - e.a * x1;

                    x2 = pxmax;
                    if (s2 != null && s2.coord.x < pxmax)
                    {
                        x2 = s2.coord.x;
                    }
                    if (x2 < pxmin)
                    {
                        x2 = pxmin;
                    }
                    y2 = e.c - e.a * x2;

                    if (((y1 > pymax) & (y2 > pymax)) | ((y1 < pymin) & (y2 < pymin)))
                    {
                        return;
                    }

                    if (y1 > pymax)
                    {
                        y1 = pymax;
                        x1 = (e.c - y1) / e.a;
                    }
                    if (y1 < pymin)
                    {
                        y1 = pymin;
                        x1 = (e.c - y1) / e.a;
                    }
                    if (y2 > pymax)
                    {
                        y2 = pymax;
                        x2 = (e.c - y2) / e.a;
                    }
                    if (y2 < pymin)
                    {
                        y2 = pymin;
                        x2 = (e.c - y2) / e.a;
                    }
                }

                pushGraphEdge(e.reg[0], e.reg[1], x1, y1, x2, y2);
            }
Esempio n. 45
0
        private void BuildWorkflow(XmlSchema nodes, XmlDocument edges, XmlSchema types, XmlDocument presentation)
        {
            XmlDocument xpathContext = new XmlDocument();

            xpathContext.AppendChild(xpathContext.CreateElement("workflow"));

            //Instantiate all the nodes and put them into the workflow nodes list
            foreach (XmlSchemaObject obj in nodes.Items)
            {
                if (obj is XmlSchemaComplexType && ((XmlSchemaComplexType)obj).Name != null)
                {
                    Node node = new Node(((XmlSchemaComplexType)obj).Name);
                    node.Fields       = InstantiateNode(((XmlSchemaComplexType)obj), types);
                    workflow[node.ID] = node;
                }
            }

            //Parse edges
            foreach (Node node in workflow.Values)
            {
                //Append the xml of the node to the context (xml document) used to resolve xpath references
                xpathContext.FirstChild.AppendChild(xpathContext.ImportNode(node.ToXml(), true));

                //Parse the outgoing edges
                IEnumerable <XmlNode> outgoingEdges =
                    from XmlNode edge in edges.SelectNodes("/EDGES/EDGE")
                    where edge.Attributes["from"] != null && edge.Attributes["from"].Value.Equals(node.ID)
                    select edge;

                List <Edge> nodeEdges = new List <Edge>();
                foreach (XmlNode xmlEdge in outgoingEdges)
                {
                    Edge edge = new Edge();
                    edge.From = node;
                    //If to == null then the node is a final node
                    edge.To = xmlEdge.Attributes["to"] == null ? null : workflow[xmlEdge.Attributes["to"].Value];

                    //If <EDGE> or <PRECONDITION> nodes have no children then the precondition is null and the arch is always followed
                    if (xmlEdge.ChildNodes.Count == 0 || xmlEdge.FirstChild.ChildNodes.Count == 0)
                    {
                        edge.Precondition = null;
                    }
                    else
                    {
                        edge.Precondition = BuildOperation(xmlEdge.FirstChild.FirstChild, types, xpathContext) as Operation;
                    }

                    nodeEdges.Add(edge);
                }
                node.Edges = nodeEdges.ToArray();
            }

            //Look for the ONLY edge that has no "from" attributes. This points to the initial node
            XmlNode[] edgeToInitial =
                (from XmlNode edge in edges.SelectNodes("/EDGES/EDGE")
                 where edge.Attributes["from"] == null && edge.Attributes["to"] != null
                 select edge).ToArray();

            if (edgeToInitial.Length != 1)
            {
                throw new WorkflowException(WorkflowExceptionType.WorkflowSchemaBadFormat, "The workflow must have a single initial node");
            }

            initialNode = workflow[edgeToInitial[0].Attributes["to"].Value];

            //Associate description e labels (names) to nodes and fields
            foreach (XmlNode child in presentation.DocumentElement.ChildNodes)
            {
                XmlElement element = child as XmlElement;
                if (workflow.ContainsKey(element.Name))
                {
                    Node node = workflow[element.Name];
                    node.ParsePresentation(element);
                }
            }
        }
 public void addEdges(Edge e)
 {
     edges.Add(e);
 }