private void startHoverForTarget(Targetable target) { NodeData actionNode = selected.getNode(); float carryingEdgeExpected = selected.expectedVisibilityModifier(); EdgeData carryingEdge = null; if (target is NodeData) { if (graphUtility.getConnectedNodes(actionNode).Contains((NodeData)target)) { carryingEdge = graphUtility.getConnectingEdge(actionNode, (NodeData)target); carryingEdgeExpected += carryingEdge.getExpectedVisibilityIncrease(selected.CarryingEdgeVisibilityIncreaseScaleParameter, selected.CarryingEdgeMaxVisibilityIncrease, true); } } bool didCarryingEdge = false; graphUtility.VisitEdgesBetweenNodesWithVisibility(turnController.CurrentPlayer.StartingNode, actionNode, selected.PathVisibilityIncreaseScaleParameter, (edge, increaseScaleParameter) => { float expected = edge.getExpectedVisibilityIncrease(increaseScaleParameter, edge.getMaxEdgeVisibilityIncrease(selected.PathMaxVisibilityIncrease)); bool isCarryingEdge = edge != null && edge == carryingEdge; if (isCarryingEdge) { expected += carryingEdgeExpected; didCarryingEdge = true; } showEdgeText(edge, expected); } ); if (carryingEdge != null && !didCarryingEdge) { showEdgeText(carryingEdge, carryingEdgeExpected); } }
protected Vertex NextVertexInCriticalPath(Vertex vertex, ref double mean, ref double variance) { Edge targetEdge = null; foreach (Edge edge in vertex.SuccessorEdges) { targetEdge = edge; if (targetEdge is Ligature) { targetEdge = edge.PostVertex.PrincipalEdge; } EdgeData ed = (EdgeData)Edges[targetEdge]; if (ed == null) { continue; } if (IsCriticalPath(targetEdge)) { m_criticalPath.Add(targetEdge); mean += ed.MeanDuration; variance += ed.Variance2; return(targetEdge.PostVertex); } } if (targetEdge != null && targetEdge.Equals(Finish.PrincipalEdge)) { return(Finish); } throw new ApplicationException("The vertex " + vertex.Name + " is not on the critical path."); }
public void Tesellate() { List <Vector2> edgeCentalPoints = null; EdgeData.Clear(); FillData.Clear(); if (Terrain.UvMapping.EdgeTexture != null && Terrain.UvMapping.Top.Bodies.Count > 0) { TesellateEdges(out edgeCentalPoints); //I'm not sure about the material techqunique to use to avoid this sorting var triangleIndices = (List <int>)EdgeData.TriangleIndices; var sortedIndices = EdgeData.TriangleIndices .Batch(3) .Select(ints => { var indices = ints.ToArray(); return(new { indices, z = EdgeData.Positions[indices[0]].Z }); }) .OrderBy(arg => - arg.z) .SelectMany(arg => arg.indices) .ToList(); triangleIndices.Clear(); triangleIndices.AddRange(sortedIndices); } if (Terrain.UvMapping.FillTexture != null) { TesellateFill(edgeCentalPoints); } }
private void SetBoundaryEdge(Dir direction, MapNode mapNode) { EdgeData boundaryData = new EdgeData(); boundaryData.SetIsMapBoundary(); mapNode.SetEdgeData(direction, boundaryData); }
private static void CreateEdgeDataArrays(out EdgeData[] EdgeDatasFrom, out EdgeData[] EdgeDatasTo, Point[] points) { int n = points.Length; EdgeDatasFrom = new EdgeData[n]; EdgeDatasTo = new EdgeData[n]; for (int i = 0; i < n; i++) { int nextIndex = (i + 1) % n; if (points[i].Y < points[nextIndex].Y) { double inverseM = (double)(points[nextIndex].X - points[i].X) / (points[nextIndex].Y - points[i].Y); EdgeDatasTo[nextIndex] = EdgeDatasFrom[i] = new EdgeData(points[i].Y, points[nextIndex].Y, inverseM, points[i].X); } else { double inverseM = (double)(points[i].X - points[nextIndex].X) / (points[i].Y - points[nextIndex].Y); EdgeDatasTo[nextIndex] = EdgeDatasFrom[i] = new EdgeData(points[nextIndex].Y, points[i].Y, inverseM, points[nextIndex].X); } } }
public void Display(string edgeId) { this.Execute(() => { EdgeData obj = _svc.RetrieveAsync(edgeId).Result; Console.WriteLine($"ID:{obj.HardwareSerial}; Update Time = {obj.LastUpdate}"); }); }
private void AddEdgeButton_Click(object sender, EventArgs e) { EdgeDialog newEdge = new EdgeDialog(); bool repeate = true; do { if (DialogResult.OK == newEdge.ShowDialog()) { EdgeData data = new EdgeData(newEdge.Distance, EdgeType.Free); try { // add edge _forestGraph.AddEdge(newEdge.Key, newEdge.StartVertex, newEdge.TargetVertex, data); _graphPath.Clear(); _saved = false; _dijkstra.Invalidate(); RegenerateTrajectoryMatrix(); } catch (Exception ex) { ShowMessage(ex.Message); continue; } graphCanvas.Invalidate(); } repeate = false; } while (repeate); }
/// <summary> /// This method is used for getting EdgeData from object that should be EdgeData. /// </summary> /// <param name="objectToParse">object that need to be transformed to EdgeData</param> /// <returns>EdgeData that was in form of object</returns> public static EdgeData ParseEdgeData(Object objectToParse) { if (objectToParse == null) { return(null); } if (objectToParse is Dictionary <String, Object> ) { Dictionary <String, Object> dictionaryRepresentationOfObject = (Dictionary <String, Object>)objectToParse; if (dictionaryRepresentationOfObject.ContainsKey(FLAGS) && dictionaryRepresentationOfObject.ContainsKey(SEMANTIC) && dictionaryRepresentationOfObject.ContainsKey(DATA)) { int flagsValue = (int)dictionaryRepresentationOfObject[FLAGS]; EdgeType semnatic = (EdgeType)dictionaryRepresentationOfObject[SEMANTIC]; EdgeFlags flags = (EdgeFlags)flagsValue; Object data = ObjectWrapper.ParseObjectWrapper(dictionaryRepresentationOfObject[DATA]); EdgeData edgeData = new EdgeData(semnatic, flags, data); return(edgeData); } else { throw new Exception("Object is not formated right!"); } } else { throw new Exception("Object is not formated right!"); } }
public EdgeTableVisualization GenerateEdgeColorVisualization([NotNull] EdgeData data) { var options = Settings.Current.VisualizationOptions; var backgroundBrush = new SolidColorBrush(options.BackgroundColor); var visual = new DrawingVisual(); using (DrawingContext drawingContext = visual.RenderOpen()) { // Draw background drawingContext.DrawRectangle(backgroundBrush, null, new Rect(0, 0, data.Size.Width, data.Size.Height)); // Draw colors drawingContext.DrawImage(GenerateEdgeColorImage(data), new Rect(0, 0, data.Size.Width, data.Size.Height)); // Draw grid if (options.DrawGrid) { DrawingUtil.DrawGrid(drawingContext, options.GridPen, data.Size.Width, data.Size.Height); } } var image = new DrawingImage(visual.Drawing); image.Freeze(); return(new EdgeTableVisualization(image, data)); }
/// <summary> /// This method is used for getting Edge<Guid, EdgeData> from object that should be Edge. /// </summary> /// <param name="objectToParse">object that need to be transformed into Edge, /// if this is not possible this method throw an Exception</param> /// <returns>Edge<Guid, EdgeData> that represent transformed object from objectToParse. /// If objectToParse is null, this method will return null</returns> public static Edge <Guid, EdgeData> ParseEdge(Object objectToParse) { if (objectToParse == null) { return(null); } if (objectToParse is Dictionary <String, Object> ) { Dictionary <String, Object> dictionaryToParse = objectToParse as Dictionary <String, Object>; if (dictionaryToParse.ContainsKey(TO_NODE_ID) && dictionaryToParse.ContainsKey(DATA)) { Guid toNodeId = (Guid)ObjectWrapper.ParseObjectWrapper(dictionaryToParse[TO_NODE_ID]); EdgeData edgeData = (EdgeData)EdgeDataWrapper.ParseEdgeData(dictionaryToParse[DATA]); Edge <Guid, EdgeData> edge = new Edge <Guid, EdgeData>(toNodeId, edgeData); return(edge); } else { throw new Exception("Edge object is not formated in right way!"); } } else { throw new Exception("Edge object is not formated in right way!"); } }
private void recGetNodesAndEdgesReachableFrom(NodeData origin, bool reverseEdgeDirection, HashSet <NodeData> visitedNodes, HashSet <EdgeData> visitedEdges) { List <NodeData> children; if (!reverseEdgeDirection) { children = getInfluencedNodes(origin); } else { children = getInfluencingNodes(origin); } foreach (NodeData child in children) { EdgeData connectingEdge = getConnectingEdge(origin, child); //only follow each edge once if (visitedEdges.Contains(connectingEdge)) { continue; } visitedEdges.Add(connectingEdge); //only visit each node once if (visitedNodes.Contains(child)) { continue; } visitedNodes.Add(child); recGetNodesAndEdgesReachableFrom(child, reverseEdgeDirection, visitedNodes, visitedEdges); } }
protected override void Start() { base.Start(); Edge = GetComponent <EdgeData>(); turnController.OnTurnEnd += updateVisibilityRendering; VisibilityController.instance.VisibilityChanged += new VisibilityController.VisibilityChangeHandler(updateArrowHead); }
public override string ToString() { string ret = ""; ret += "Node," + Nodes.Count + "\n"; for (int i = 0; i < Nodes.Count; i++) { NodeData nddt = Nodes[i]; ret += (nddt.PositionX) + "," + (nddt.PositionY) + "," + nddt.Theta + "," + (nddt.R0) + "," + (nddt.R1) + "," + (nddt.R2) + "," + (nddt.R3) + "\n"; } ret += "Edge," + Edges.Count + "\n"; for (int i = 0; i < Edges.Count; i++) { EdgeData eddt = Edges[i]; ret += "" + eddt.AID + "," + eddt.ARID + "," + eddt.BID + "," + eddt.BRID + "\n"; } return(ret); }
private void LogEdgeNotFoundError(string msg, Edge edge) { if (s_logEdgeNotFoundError) { string logFilePath = @"./SOM_Analytical.txt"; Tasks.Task task = edge as Tasks.Task; StreamWriter sw = new StreamWriter(logFilePath); sw.WriteLine("\r\n::::::::::::::::Message::::::::::::::::\r\n" + msg + "\r\n"); sw.WriteLine("\r\n::::::::::::::::Call Stack::::::::::::::::\r\n"); StackTrace st = new StackTrace(true); sw.WriteLine(st.ToString()); sw.WriteLine("\r\n::::::::::::::::Requested Edge::::::::::::::::\r\n"); sw.WriteLine("Name : " + edge.Name + "\r\nGuid : " + task.Guid + "\r\nHashCode : " + task.GetHashCode()); sw.WriteLine("\r\n::::::::::::::::Known Edges::::::::::::::::\r\n"); foreach (DictionaryEntry de in Edges) { Edge knownEdge = (Edge)de.Key; EdgeData knownEdgeData = (EdgeData)de.Value; Tasks.Task knownTask = knownEdge as Tasks.Task; if (knownTask != null) { sw.WriteLine("Name : " + knownTask.Name + "\r\nGuid : " + knownTask.Guid + "\r\nHashCode : " + knownTask.GetHashCode()); } else { sw.WriteLine("Name : " + knownEdge.Name + "\r\nGuid : <Edge, not task, therefore no Guid>\r\nHashCode : " + knownEdge.GetHashCode()); } } sw.Flush(); sw.Close(); _Debug.WriteLine("Dumped log file to " + logFilePath); } }
List <Vector2> GetBorderingChunks(EdgeData edgeData, Vector2 chunkCoords) { List <Vector2> borderingChunkCoords = new List <Vector2>(); Vector2 newChunkCords = new Vector2(); Vector2 newVertex2D = new Vector2(); if (edgeData.onEdgeTop) { borderingChunkCoords.Add(new Vector2(chunkCoords.x, chunkCoords.y + 1)); } else if (edgeData.onEdgeBottom) { borderingChunkCoords.Add(new Vector2(chunkCoords.x, chunkCoords.y - 1)); } else if (edgeData.onEdgeRight) { borderingChunkCoords.Add(new Vector2(chunkCoords.x + 1, chunkCoords.y)); } else if (edgeData.onEdgeLeft) { borderingChunkCoords.Add(new Vector2(chunkCoords.x - 1, chunkCoords.y)); } return(borderingChunkCoords); }
/// <summary> /// This method is used for getting EdgeData from object that should be EdgeData. /// </summary> /// <param name="objectToParse">object that need to be transformed to EdgeData</param> /// <returns>EdgeData that was in form of object</returns> public static EdgeData ParseEdgeData(Object objectToParse) { if (objectToParse == null) return null; if (objectToParse is Dictionary<String, Object>) { Dictionary<String, Object> dictionaryRepresentationOfObject = (Dictionary<String, Object>)objectToParse; if (dictionaryRepresentationOfObject.ContainsKey(FLAGS) && dictionaryRepresentationOfObject.ContainsKey(SEMANTIC) && dictionaryRepresentationOfObject.ContainsKey(DATA)) { int flagsValue = (int)dictionaryRepresentationOfObject[FLAGS]; EdgeType semnatic = (EdgeType)dictionaryRepresentationOfObject[SEMANTIC]; EdgeFlags flags = (EdgeFlags)flagsValue; Object data = ObjectWrapper.ParseObjectWrapper(dictionaryRepresentationOfObject[DATA]); EdgeData edgeData = new EdgeData(semnatic, flags, data); return edgeData; } else { throw new Exception("Object is not formated right!"); } } else { throw new Exception("Object is not formated right!"); } }
public static void SetSideStreets(this RouteSegment segment, RouterDb routerDb, uint vertex, uint previousEdge, uint nextVertex) { List <RouteSegmentBranch> routeSegmentBranchList = new List <RouteSegmentBranch>(); RoutingNetwork.EdgeEnumerator edgeEnumerator = routerDb.Network.GetEdgeEnumerator(vertex); while (edgeEnumerator.MoveNext()) { if ((int)edgeEnumerator.Id != (int)previousEdge && (int)edgeEnumerator.To != (int)nextVertex) { RoutingEdge current = edgeEnumerator.Current; RouterDb db = routerDb; EdgeData data = current.Data; int profile = (int)data.Profile; data = current.Data; int metaId = (int)data.MetaId; TagsCollectionBase profileAndMeta = db.GetProfileAndMeta((uint)profile, (uint)metaId); ICoordinate firstPoint = routerDb.Network.GetFirstPoint(current, edgeEnumerator.From); routeSegmentBranchList.Add(new RouteSegmentBranch() { Latitude = firstPoint.Latitude, Longitude = firstPoint.Longitude, Tags = profileAndMeta.ConvertFrom() }); } } if (routeSegmentBranchList.Count <= 0) { return; } segment.SideStreets = routeSegmentBranchList.ToArray(); }
private EdgeData GetEdgeData(MapNode current, MapNode adjacent) { EdgeData result = new EdgeData(); result.heightChange = adjacent.WorldHeight - current.WorldHeight; return(result); }
override protected void doActivate(Targetable target) { NodeData otherNode = target.GetComponent <NodeData>(); NodeData thisNode = getNode(); EdgeData edge = graphUtility.getConnectingEdge(thisNode, otherNode); if (edge.direction == EdgeData.EdgeDirection.Unusable) { return; } bool isWin = gen.NextDouble() <= getProbabilityOfWin(target); // Take node if (isWin) { graphUtility.CaptureNode(otherNode, thisNode); } if (effect != null) { effect.additionalEffect(thisNode, target, isWin); } effect = null; }
public string ObjectsReport() { Hashtable usedNodes = new Hashtable(); // Collect used nodes AddUsedNodesRecursive(LastSnapshotId(), usedNodes); StringBuilder sb = new StringBuilder(); foreach (Guid nodeId in usedNodes.Keys) { // We found a node which is not used and should be collected var node = provider.GetNode(nodeId, NodeAccess.Read); string line = nodeId.ToString() + "\t" + node.NodeType.ToString() + "\t"; var typeData = new EdgeData(EdgeType.OfType, null); if (node.Edges.ContainsKey(typeData)) { var typeEdge = node.FindEdge(typeData); if (typeEdge != null) { line += typesService.GetTypeFromIdCached(typeEdge.ToNodeId).Name + "\t"; } } sb.AppendLine(line); } return(sb.ToString()); }
void DrawEdgeGizmos(EdgeData edge) { Rect rect = edge.m_Target.rect; Gizmos.color = Color.green * 0.5f; Gizmos.matrix = edge.m_Target.localToWorldMatrix; Gizmos.DrawCube(rect.center, rect.size); Gizmos.color = Color.yellow; switch (edge.m_Edge) { case EEdge.left: Gizmos.DrawLine(new Vector3(rect.xMin, rect.yMin), new Vector3(rect.xMin, rect.yMax)); break; case EEdge.right: Gizmos.DrawLine(new Vector3(rect.xMax, rect.yMin), new Vector3(rect.xMax, rect.yMax)); break; case EEdge.up: Gizmos.DrawLine(new Vector3(rect.xMin, rect.yMax), new Vector3(rect.xMax, rect.yMax)); break; case EEdge.down: Gizmos.DrawLine(new Vector3(rect.xMin, rect.yMin), new Vector3(rect.xMax, rect.yMin)); break; default: break; } }
/// <summary> /// Reverses the roles of vertices and faces, as when taking the dual of a polyhedron. /// </summary> public virtual void MakeDual() { if (firstExternalFaceIndex < faceFirstEdgeIndices.Length) { throw new InvalidOperationException("A dual topology cannot be derived from a topology with external faces."); } GeneralUtility.Swap(ref vertexNeighborCounts, ref faceNeighborCounts); GeneralUtility.Swap(ref vertexFirstEdgeIndices, ref faceFirstEdgeIndices); firstExternalFaceIndex = faceFirstEdgeIndices.Length; var dualEdgeData = new EdgeData[edgeData.Length]; for (int i = 0; i < edgeData.Length; ++i) { // Edges rotate clockwise to point at next faces becoming far vertices, with their // side toward far vertices becoming prev faces. dualEdgeData[i] = new EdgeData( edgeData[i].twin, // twin remains the same edgeData[edgeData[edgeData[i].twin].fNext].twin, // vNext becomes twin of vPrev, where vPrev is the fNext of twin edgeData[i].vNext, // fNext becomes what vNext had been edgeData[edgeData[i].twin].face, // far vertex becomes what had been next face edgeData[i].vertex); // prev face becomes what had been far vertex } edgeData = dualEdgeData; // Due to rotations, face data (which had been vertex data) still points to the same edges, // but vertex data (which had been face data) is now backwards, pointing to edges which // point back at the vertex; this needs to be reversed by setting first edges to their twins. for (int i = 0; i < vertexFirstEdgeIndices.Length; ++i) { vertexFirstEdgeIndices[i] = edgeData[vertexFirstEdgeIndices[i]].twin; } }
public float speed;//车速 public Car(Position carPos, EdgeData car_EdgeData, CarState carState, float speed) { this.carPos = carPos; this.car_EdgeData = car_EdgeData; this.carState = carState; this.speed = speed; }
public void TestSerialize() { var edgeData = new EdgeData() { Distance = 100.1f, Profile = 12 }; var data = EdgeDataSerializer.Serialize(edgeData); Assert.IsNotNull(data); Assert.AreEqual(1, data.Length); Assert.AreEqual((uint)16384 * (uint)(edgeData.Distance * 10) + (uint)edgeData.Profile, data[0]); edgeData = new EdgeData() { Distance = 0f, Profile = 12 }; data = EdgeDataSerializer.Serialize(edgeData); Assert.IsNotNull(data); Assert.AreEqual(1, data.Length); Assert.AreEqual((uint)16384 * (uint)(edgeData.Distance * 10) + (uint)edgeData.Profile, data[0]); edgeData = new EdgeData() { Distance = EdgeDataSerializer.MAX_DISTANCE, Profile = EdgeDataSerializer.MAX_PROFILE_COUNT - 1 }; data = EdgeDataSerializer.Serialize(edgeData); Assert.IsNotNull(data); Assert.AreEqual(1, data.Length); Assert.AreEqual((uint)16384 * (uint)(edgeData.Distance * 10) + (uint)edgeData.Profile, data[0]); edgeData = new EdgeData() { Distance = EdgeDataSerializer.MAX_DISTANCE + 0.1f, Profile = EdgeDataSerializer.MAX_PROFILE_COUNT - 1 }; Assert.Catch <ArgumentOutOfRangeException>(() => { EdgeDataSerializer.Serialize(edgeData); }); edgeData = new EdgeData() { Distance = EdgeDataSerializer.MAX_DISTANCE, Profile = EdgeDataSerializer.MAX_PROFILE_COUNT }; Assert.Catch <ArgumentOutOfRangeException>(() => { EdgeDataSerializer.Serialize(edgeData); }); }
public EdgeTableVisualization GenerateEdgeColorVisualizationWithPath([NotNull] EdgeData data, [NotNull] StParticlePath path) { var options = Settings.Current.VisualizationOptions; var backgroundBrush = new SolidColorBrush(options.BackgroundColor); var visual = new DrawingVisual(); using (DrawingContext drawingContext = visual.RenderOpen()) { // Draw background drawingContext.DrawRectangle(backgroundBrush, null, new Rect(0, 0, data.Size.Width, data.Size.Height)); // Draw colors drawingContext.DrawImage(GenerateEdgeColorImage(data), new Rect(0, 0, data.Size.Width, data.Size.Height)); // Draw grid if (options.DrawGrid) { DrawingUtil.DrawGrid(drawingContext, options.GridPen, data.Size.Width, data.Size.Height); } // Draw path if (path.Points.Count > 0) { var pathGeometry = new StreamGeometry(); using (StreamGeometryContext ctx = pathGeometry.Open()) { var points = path.Points.Select(p => new Point(p.J + 0.5, p.I + 0.5)).ToList(); ctx.BeginFigure(points.First(), true, false); ctx.PolyLineTo(points.Skip(1).ToList(), true, true); } pathGeometry.Freeze(); drawingContext.DrawGeometry(null, options.PathPen, pathGeometry); } // Draw start point if (options.DrawStartPoint) { drawingContext.PushTransform(new TranslateTransform(path.StartPoint.J + 0.5, path.StartPoint.I + 0.5)); drawingContext.DrawDrawing(options.StartPointDrawing); drawingContext.Pop(); } // Draw end point if (options.DrawEndPoint && path.EndPoint.HasValue) { var pnt = path.EndPoint.GetValueOrDefault(); drawingContext.PushTransform(new TranslateTransform(pnt.J + 0.5, pnt.I + 0.5)); drawingContext.DrawDrawing(options.EndPointDrawing); drawingContext.Pop(); } } var image = new DrawingImage(visual.Drawing); image.Freeze(); return(new EdgeTableVisualization(image, data)); }
public RingWalker(Span <ScanEdge> output) { this.output = output; this.EdgeCounter = 0; this.PreviousEdge = default; this.CurrentEdge = default; this.NextEdge = default; }
void DestroyEdge(EdgeData edgeData) { var edge = edgeTable[edgeData]; Edges.Remove(edge); edge.Destroy(); edgeTable.Remove(edgeData); }
public PrCalculation([NotNull] CalculationConstraint constraint, [NotNull] EdgeData edgeData, IEnumerable <GridIndex> calculationMask) : base(constraint, calculationMask) { constraint.AssertNotNull(nameof(constraint)); edgeData.AssertNotNull(nameof(edgeData)); m_EdgeData = edgeData; }
private void ProcessData() { m_ProccesedData = EdgeData.AllocateLike(m_Data); foreach (var i in m_ProccesedData.Bounds.EnumerateEdge()) { m_ProccesedData[i] = m_Data[i] / TotalSimulations; } }
public Edge(string iId, INode iSource, INode iTarget, EdgeData iData = null) { Id = iId; Source = iSource; Target = iTarget; Data = (iData != null) ? iData : new EdgeData(); Directed = false; }
private void addEdge(NodeData node, EdgeData edge) { if (!graph.ContainsKey(node)) { graph[node] = new List <EdgeData>(); } graph[node].Add(edge); }
private static ExplorationEdge Decode( EdgeData data, Dictionary<uint, ExplorationNode> idToNode, IEventLibrary library) { return new ExplorationEdge( idToNode[data.IdFrom], idToNode[data.IdTo], RecreateStoryEvents(data, library)); }
private static TransitionEvent[] RecreateStoryEvents( EdgeData data, IEventLibrary library) { TransitionEvent[] events = new TransitionEvent[data.EventNames.Length]; for (int i = 0; i < events.Length; i++) { EventDescriptor evtDesc = library.GetDescriptor(data.EventNames[i]); DebugUtil.Assert(evtDesc != null); events[i] = new TransitionEvent(evtDesc, data.EventParticipants[i]); } return events; }
// Method for loading the JSON data from the API controller private IEnumerator LoadLayout() { graph = new Graph(); statusText.text = "Loading radia.json..."; string rawJson = null; //var req = new WWW(apiUrl + "/functions"); string path_prefix; if (SystemInfo.operatingSystem.StartsWith ("Win")) { path_prefix = "\\"; } else { path_prefix = "/../../"; } //local app path for finding the JSON files var req = new WWW ("file://" + Application.dataPath + path_prefix + "radia.json"); yield return req; if (req.error != null) { statusText.text = "Error reading radia.json"; return false; } rawJson = req.text; statusText.text = "Processing Data"; var j = JSON.Parse(rawJson); j = j["functions"]; for(int i = 0; i < j.Count; i++) { float x = 0.0f; float y = 0.0f; float z = 0.0f; int category = 0; if (j[i]["category"] != null) { category = int.Parse(j[i]["category"]); } // (danger << 6) + (string << 5) + (fileio << 4) + (crypto << 3) + (socket << 2) + (heap << 1) + system // 64 32 16 8 4 2 1 Function nodeObject; float scale = 1.0f; if ((category & 64) == 64) { nodeObject = Instantiate(dangerPrefab, new Vector3(x, y, z), Quaternion.identity) as Function; } else if ((category & 8) == 8) { nodeObject = Instantiate(cryptoPrefab, new Vector3(x, y, z), Quaternion.identity) as Function; } else if ((category & 4) == 4) { nodeObject = Instantiate(socketPrefab, new Vector3(x, y, z), Quaternion.identity) as Function; } else if ((category & 32) == 32) { nodeObject = Instantiate(stringPrefab, new Vector3(x, y, z), Quaternion.identity) as Function; } else if ((category & 16) == 16) { nodeObject = Instantiate(filePrefab, new Vector3(x, y, z), Quaternion.identity) as Function; scale = 1.5f; } else if ((category & 1) == 1) { nodeObject = Instantiate(systemPrefab, new Vector3(x, y, z), Quaternion.identity) as Function; } else if ((category & 2) == 2) { nodeObject = Instantiate(heapPrefab, new Vector3(x, y, z), Quaternion.identity) as Function; scale = 2.0f; } else { nodeObject = Instantiate(defaultPrefab, new Vector3(x, y, z), Quaternion.identity) as Function; } nodeObject.funcname = j[i]["name"]; nodeObject.address = ulong.Parse(j[i]["address"]); nodeObject.attributes = category; if (j[i]["size"] != null) { nodeObject.size = int.Parse(j[i]["size"]); } else { nodeObject.size = 0; } nodeObject.module_name = j[i]["module_name"]; nodeObject.functag = j[i]["tag"]; nodeObject.comment = j[i]["comment"]; nodeObject.longname = j[i]["long_name"]; nodeObject.basic_blk_cnt = int.Parse(j[i]["basic_blk_cnt"]); if (j[i]["dangerous_list"] != null) { nodeObject.dangerous_calls = new string[j[i]["dangerous_list"].Count]; for (int c = 0; c < j[i]["dangerous_list"].Count; c++) { nodeObject.dangerous_calls[c] = j[i]["dangerous_list"][c]; } } if (j[i]["strings"] != null) { nodeObject.strings = new string[j[i]["strings"].Count]; for (int c = 0; c < j[i]["strings"].Count; c++) { nodeObject.strings[c] = j[i]["strings"][c]; } } nodeObject.transform.localScale += new Vector3(scale, scale, scale); nodes.Add(nodeObject.address, nodeObject); // For force directed graph NodeData data = new NodeData(); data.label = nodeObject.address.ToString(); data.mass = (float)nodeObject.size / 50.0f + 10.0f; graph.CreateNode(data); statusText.text = "Loading Functions: Function " + nodeObject.funcname; if(i % 100 == 0) yield return true; } j = JSON.Parse(rawJson); j = j["callgraph"]; for(int i = 0; i < j.Count; i++) { ulong srcid = ulong.Parse(j[i]["source"]); ulong dstid = ulong.Parse(j[i]["target"]); if (FindDupLink (srcid, dstid)) { continue; } Link linkObject = Instantiate(linkPrefab, new Vector3(0, 0, 0), Quaternion.identity) as Link; linkObject.id = i+1; linkObject.sourceId = srcid; linkObject.targetId = dstid; links.Add(linkObject.id, linkObject); // For force directed graph Node node1 = graph.GetNode(linkObject.sourceId.ToString()); Node node2 = graph.GetNode(linkObject.targetId.ToString()); EdgeData data = new EdgeData(); data.label = linkObject.sourceId.ToString()+"-"+linkObject.targetId.ToString(); data.length = 1.0f; graph.CreateEdge(node1, node2, data); statusText.text = "Loading Callgraph: Call " + linkObject.id.ToString(); if(i % 100 == 0) yield return true; } // Map node edges MapLinkFunctions(); // For force directed graph physics = new ForceDirected3D(graph, // instance of Graph stiffness, // stiffness of the spring repulsion, // node repulsion rate damping // damping rate ); render = new FDRenderer(physics); render.setController(this); statusText.text = ""; Camera.main.transform.LookAt (new Vector3 (0f, 0f, 0f)); renderThread = new Thread(new ThreadStart(FDRenderThread)); renderThread.Start (); }
/// <summary> /// Writes edge data object to stream /// </summary> /// <param name="bw">Writer to use</param> /// <param name="data">Edge data</param> private void WriteEdgeData(BinaryWriter bw, EdgeData data) { bw.Write((byte)data.Semantic); bw.Write((byte)data.Flags); if (data.Data == null) { bw.Write((byte)ObjectType.Null); } else { WriteObjectToStream(data.Data, bw); } }
/// <summary> /// TransformeEdgeData is transforming EdgeData to EdgeDataWrapper /// </summary> /// <param name="edgeData">data that need to transformed</param> /// <returns></returns> public static EdgeDataWrapper TransformeEdgeData(EdgeData edgeData) { EdgeDataWrapper edgeDataWraped = new EdgeDataWrapper(); edgeDataWraped.Flags = edgeData.Flags; edgeDataWraped.Semantic = edgeData.Semantic; ObjectWrapper objectWithType = ObjectWrapper.CreateObjectWrapper(edgeData.Data); //type of object is needed so that clent know what is type of data that is received edgeDataWraped.Data = objectWithType; return edgeDataWraped; }