public void OnNodesUpdated(AgentConnection clientConnection, NodeNetwork updatedNodes) { if (NodesUpdated != null) { NodesUpdated.Invoke(clientConnection, updatedNodes); } }
public ClientSession() { ManagedNodes = new NodeNetwork(); Database = new DatabaseConnection(); Agents = new Dictionary <String, AgentConnection>(); }
/// <summary> /// Creates all the node info with added subdivisions for the _pathTransforms array. /// </summary> /// <param name="nodeNetwork">NodeNetwork which will be modified</param> /// <returns></returns> private List<NodeInfo> CreateSubdivideNodeInfoArray(NodeNetwork nodeNetwork) { int length = _pathTransforms.Length; List<NodeInfo> nodeInfoList = new List<NodeInfo>(); NodeInfo nodeInfo; for (int i = 1; i < length; i++) { int subdivisionCount = Mathf.Max(Mathf.FloorToInt((_pathTransforms[i].position - _pathTransforms[i - 1].position).magnitude / nodeNetwork.Spacing), 1); Vector3 previousPosition = _pathTransforms[i - 1].position; Vector3 currentPosition = _pathTransforms[i].position; Vector3 interval = Vector3.zero; interval.x = (currentPosition.x - previousPosition.x) / subdivisionCount; interval.y = (currentPosition.y - previousPosition.y) / subdivisionCount; interval.z = (currentPosition.z - previousPosition.z) / subdivisionCount; // Subdivision nodes cannot be created if their NetorkPosition already exists. It will update the excisting one. for (int j = 0; j < subdivisionCount; j++) { nodeInfo = new NodeInfo(_pathTransforms[i- 1].gameObject.layer, previousPosition + j * interval); nodeInfoList.Add(nodeInfo); } if (i == length -1) { nodeInfo = new NodeInfo(_pathTransforms[i].gameObject.layer, _pathTransforms[i].position); nodeInfoList.Add(nodeInfo); } } return nodeInfoList; }
/// <summary> /// Connects the first node of the linear path to the NodeNetwork /// </summary> /// <param name="startNode">First node of the linear path</param> /// <param name="nodeNetwork">NodeNetwork which will be modified</param> private void ConnectStartToNetwork(Node startNode, NodeNetwork nodeNetwork) { if (!_useScale) { Node connectionNode = nodeNetwork.GetNodeBelow(startNode); if (connectionNode == startNode) Debug.LogError("We have a problem."); Debug.Log("ConnectionNode: " + connectionNode.WorldPosition); if (connectionNode != null) { startNode.AddConnection(connectionNode); connectionNode.AddConnection(startNode); } return; } // Gets the entire area covered by the collider. List<Node> innerNetwork = base.CreateCustomNodeNetwork(nodeNetwork); if (_pathTransforms.Length == 0 || innerNetwork.Count == 0) throw new System.Exception("No pathTransforms or innerNetwork found."); // Connect the first Node of the linearPathNetwork to all Nodes of the innerNetwork. foreach (var node in innerNetwork) { startNode.AddConnection(node); node.AddConnection(startNode); } }
/// <summary> /// Finds the nodes this gameobject overlaps, modifies their layer to the gameobject's layer or unwalkable, depending whether it is unlocked. Finally, it returns all the nodes modified. /// </summary> /// <param name="nodeNetwork">NodeNetwork which will be modified</param> /// <returns>List of all modified nodes</returns> public override List <Node> CreateCustomNodeNetwork(NodeNetwork nodeNetwork) { int layer = (_unlocked) ? gameObject.layer : NodeNetwork.UnwalkableLayer; _innerNetworkNodes = CreateCustomNodeNetwork(nodeNetwork, layer); return(_innerNetworkNodes); }
protected MazeAlgorithm(MazeCell[,] mazeCells) : base() { this.mazeCells = mazeCells; mazeRows = mazeCells.GetLength(0); mazeColumns = mazeCells.GetLength(1); nodeNetwork = GameObject.Find("NodeNetwork").GetComponent <NodeNetwork>(); }
/// <summary> /// Finds the nodes this gameobject overlaps, modifies their layer to the specified layer and returns all the nodes modified. /// </summary> /// <param name="nodeNetwork">NodeNetwork which will be modified</param> /// <param name="layer">The nodes their new layer</param> /// <returns>List of all modified nodes</returns> protected virtual List <Node> CreateCustomNodeNetwork(NodeNetwork nodeNetwork, int layer) { float spacing = nodeNetwork.Spacing; int innerNetworkSizeX = Mathf.Max(Mathf.RoundToInt(((transform.localScale.x)) / spacing), 1); int innerNetworkSizeY = Mathf.Max(Mathf.RoundToInt(((transform.localScale.y)) / spacing), 1); Vector3 size = new Vector3((transform.localScale.x), (transform.localScale.y), 0); Vector3 worldBottomLeft = transform.position - (size / 2); List <Node> innerNetworkNodes = new List <Node>(); for (int x = 0; x <= innerNetworkSizeX + 0; x++) { for (int y = 0; y <= innerNetworkSizeY; y++) { Vector3 worldPosition = worldBottomLeft + new Vector3(x * spacing, y * spacing, nodeNetwork.transform.position.z); Node node = nodeNetwork.GetNodeFromWorldPosition(worldPosition, int.MaxValue, true); if (node.LayerValue == NodeNetwork.UnwalkableLayer) { continue; } if (!innerNetworkNodes.Contains(node) && node.WorldPosition.z >= transform.position.z) { nodeNetwork.MofidyNode(node, layer); innerNetworkNodes.Add(node); } } } return(innerNetworkNodes); }
/// <summary> /// /// </summary> /// <param name="nodeNetwork">NodeNetwork which will be modified</param> /// <returns></returns> public override List<Node> CreateCustomNodeNetwork(NodeNetwork nodeNetwork) { // Create NodeInfo array for all the new nodes that need to be created. List<NodeInfo> nodeInfoList = GetNodeInfoArray(nodeNetwork); // Create the first node of the linearPathNetwork. NodeInfo nodeInfo = nodeInfoList[0]; Node currentNode = nodeNetwork.CreateCustomNode(nodeInfo.Layer, nodeInfo.WorldPosition); linearPathNetwork = new List<Node>(); linearPathNetwork.Add(currentNode); ConnectStartToNetwork(currentNode, nodeNetwork); // Create the other nodes and connect them to the linear path network. int length = nodeInfoList.Count; for (int i = 1; i < length; i++) { nodeInfo = nodeInfoList[i]; // Create new node in the linearPathNetwork. currentNode = nodeNetwork.CreateCustomNode(nodeInfo.Layer, nodeInfo.WorldPosition); currentNode.CanSimplify = false; // Connect the last 2 nodes. Node previousNode = linearPathNetwork[i - 1]; currentNode.AddConnection(previousNode); previousNode.AddConnection(currentNode); linearPathNetwork.Add(currentNode); } ConnectEndToNetwork(currentNode, nodeNetwork); return linearPathNetwork; }
void CloseNodeNetworkClick(Window callingWindow) { if (mNodeNetwork != null) { mNodeNetwork.Visible = false; mNodeNetwork = null; } }
void OnLoadNodeNetworkOk(Window callingWindow) { CloseNodeNetworkClick(null); string fileName = ((FileWindow)callingWindow).Results[0]; mNodeNetwork = FlatRedBallServices.Load <NodeNetwork>(fileName); mNodeNetwork.Visible = true; }
private void RemoveExcludedNodesViaPolygonLayer(NodeNetwork nodeNetwork, MapLayer mapLayer, Dictionary <int, Dictionary <int, PositionedNode> > allNodes) { ShapeCollection sc = this.ToShapeCollection(mapLayer.Name + " nonodes"); List <PositionedNode> nodesToRemove = GetNodesThatCollideWithShapeCollection(sc, allNodes); foreach (var node in nodesToRemove) { nodeNetwork.Remove(node); } }
private static void RemoveNodeNetwork() { if (mNodeNetwork != null) { mNodeNetwork.Visible = false; } // The editor depends on the NodeNetwork not being null mNodeNetwork = new NodeNetwork(); }
void OnLoadNodeNetworkOk(Window callingWindow) { CloseNodeNetworkClick(null); string fileName = ((FileWindow)callingWindow).Results[0]; mNodeNetwork = FlatRedBallServices.Load<NodeNetwork>(fileName); mNodeNetwork.Visible = true; }
private void NodeDataUpdated(AgentConnection agentConnection, NodeNetwork updatedNodes) { dataGridViewNodes.UpdateNodes(updatedNodes, clientConnectionManager.Session.Database); toolStripStatusLabelDatabase.Text = "DB: " + clientConnectionManager.Session.Database.GetDatabaseFilesystemSize(); int totalNodes = managedNodes.Nodes.Count; int runningNodes = managedNodes.Nodes.Count(n => n.Value.NodeState.Initialized && n.Value.NodeState.NodeOperationState.State == ProcessState.Running); toolStripStatusLabelNodeState.Text = $"Nodes: {runningNodes} / {totalNodes}"; }
public List <PositionedNode> GetPathTo(Vector3 position) { var toReturn = NodeNetwork.GetPath(ref Position, ref position); // remove node 0 if there's more than 1 node, because otherwise the user backtracks: if (toReturn.Count > 1) { toReturn.RemoveAt(0); } return(toReturn); }
private void UpdateCurrentBehavior(NodeNetwork nodeNetwork, PositionedObject target) { if (shotsLeftInClip == 0) { // do reload activity CurrentBehavior = Behavior.Reloading; var isDoneReloading = FlatRedBall.Screens.ScreenManager.CurrentScreen.PauseAdjustedSecondsSince(lastFireShotTime) > SecondsForReload; if (isDoneReloading) { shotsLeftInClip = ClipSize; CurrentBehavior = Behavior.Chasing; } //shootingAnimationLayer.StopPlay(); } else { var ai = InputDevice as TopDown.TopDownAiInput <Enemy>; var path = ai.Path; bool isLineOfSight = path.Count < 2 && target != null; bool isInRange = false; if (isLineOfSight) { isInRange = (target.Position - this.Position).Length() < MaxShootingDistance * StatMultipliers.EffectiveRangeMultiplier; } var shouldWalkForward = true; if (isInRange && MaxShootingDistance > 0) { // line of site CurrentBehavior = Behavior.Shooting; if ((this.Position - target.Position).Length() < ClosestShootingDistance) { shouldWalkForward = false; } } else { CurrentBehavior = Behavior.Chasing; } ai.IsActive = shouldWalkForward; } }
public CoinMasterForm() { InitializeComponent(); buttonEditNodeProfile_Click(null, EventArgs.Empty); ReadNodeProfiles(); //Create pop-up notifier = new Tulpep.NotificationWindow.PopupNotifier(); notifier.Delay = 10000; notifier.Click += (sender, eventArgs) => { Visible = true; BringToFront(); }; //Create workers cryptoIdWorker = new CryptoIdWorker(60000, new NodeEndpointName("Stratis", "StratisTest")); cryptoIdWorker.StateChange += DashboardWorkerStateChanged; cryptoIdWorker.DataUpdate += (source, args) => Invoke(new Action <object, CryptoIdDataUpdateEventArgs>(CryptoIdUpdated), source, args); _workers.Add(cryptoIdWorker); //Start all workers foreach (BaseWorker worker in _workers) { worker.Start(); } ClientConfigReader reader = new ClientConfigReader(); clientConfig = reader.ReadConfig(); List <String> agentList = clientConfig.GetAgentList(); this.managedNodes = new NodeNetwork(); foreach (string fullNodeName in clientConfig.NodeItems.Keys) { BlockchainNode blockchainNode = new BlockchainNode(clientConfig.NodeItems[fullNodeName]); this.managedNodes.Nodes.Add(fullNodeName, blockchainNode); } clientConnectionManager = new AgentConnectionManager(managedNodes); clientConnectionManager.Session.AgentHealthcheckStatsUpdated += (agentConnection, state, message) => Invoke(new Action <AgentConnection, AgentHealthState, String>(AgentDataTableUpdated), agentConnection, state, message); clientConnectionManager.Session.NodesUpdated += (agentConnection, updatedNodes) => Invoke(new Action <AgentConnection, NodeNetwork>(NodeDataUpdated), agentConnection, updatedNodes); clientConnectionManager.Session.AgentRegistrationUpdated += (agentConnection, agentRegistration) => Invoke(new Action <AgentConnection, AgentRegistration>(AgentRegistrationUpdated), agentConnection, agentRegistration); clientConnectionManager.ConnectToAgents(agentList); }
private void InitializeMaze() { SetCamera(); parent = GameObject.Find("MazeObjects"); nodeNetwork = GameObject.Find("NodeNetwork").GetComponent <NodeNetwork>(); widthSlider.value = mazeColumns; heightSlider.value = mazeRows; mazeCells = new MazeCell[mazeRows, mazeColumns]; for (int r = -1; r < mazeRows + 1; r++) { for (int c = -1; c < mazeColumns + 1; c++) { Vector3 newPosition = new Vector3(r * size, 0, c * size); Vector3 newFloorPosition = new Vector3(r * size, -(size / 2f), c * size); if (r >= 0 && r < mazeRows && c >= 0 && c < mazeColumns) { nodeNetwork.walkablePositions.Add(new KeyValuePair <Vector3, bool>(newPosition, false)); //Создаем клетки mazeCells[r, c] = new MazeCell(); mazeCells[r, c].floor = Instantiate(floorPrefab, newFloorPosition, Quaternion.identity) as GameObject; mazeCells[r, c].floor.name = "Floor " + r + "," + c; mazeCells[r, c].floor.transform.Rotate(Vector3.right, 90f); mazeCells[r, c].floor.transform.SetParent(parent.transform); mazeCells[r, c].wall = Instantiate(wallPrefab, newPosition, Quaternion.identity) as GameObject; mazeCells[r, c].wall.name = "Wall " + r + "," + c; mazeCells[r, c].wall.transform.SetParent(parent.transform); } else { //Содаем границу var border = Instantiate(floorPrefab, newFloorPosition, Quaternion.identity) as GameObject; border.name = "Border"; border.transform.SetParent(parent.transform); border = Instantiate(wallPrefab, newPosition, Quaternion.identity) as GameObject; border.name = "Border"; border.transform.SetParent(parent.transform); } } } }
public void UpdateNodes(NodeNetwork managedNodes, DatabaseConnection database) { Mapper.MergeDataRows(managedNodes); Mapper.UpdateDataTable(database, managedNodes); if (this.DataSource == null) { ConfigureDataGridView(); } if (SelectedRows.Count > 0) { DataGridViewRow selectedRow = SelectedRows[0]; DataGridViewRowStateChangedEventArgs e = new DataGridViewRowStateChangedEventArgs(selectedRow, DataGridViewElementStates.None); this.OnRowStateChanged(selectedRow.Index, e); } }
public AgentSession() { ManagedNodes = new NodeNetwork(); //Configure dispatchers Dispatchers = new List <DispatcherBase>(); Dispatchers.Add(new AgentHealthcheckDispatcher(this, 5000)); Dispatchers.Add(new NodeStatusDispatcher(this, 3000)); Dispatchers.Add(new ResourceFromAgentDispatcher(this, 1000)); Clients = new List <ClientConnection>(); List <String> codeDirectoryList = ManagedNodes.GetCodeDirectoryList(); GitRepositoryMonitor = new GitRepositoryMonitor(codeDirectoryList); }
void ScaleOkClick(Window callingWindow) { Vector3 scaleValue = ((Vector3OkWindow)callingWindow).Vector3Value; NodeNetwork nodeNetwork = EditorData.NodeNetwork; for (int i = 0; i < nodeNetwork.Nodes.Count; i++) { PositionedNode node = nodeNetwork.Nodes[i]; node.Position.X *= scaleValue.X; node.Position.Y *= scaleValue.Y; node.Position.Z *= scaleValue.Z; } GuiManager.RemoveWindow(callingWindow); }
public static void RemoveNodesForCollision(this NodeNetwork network, AxisAlignedRectangle collision) { var nodeCircle = new Circle { Radius = 20f }; for (var i = network.Nodes.Count - 1; i >= 0; i--) { var node = network.Nodes[i]; nodeCircle.Position = node.Position; if (collision.CollideAgainst(nodeCircle)) { network.Remove(node); } } network.UpdateShapes(); }
public void MergeDataRows(NodeNetwork managedNodes) { //Remove nodes not managed by agent List <DataRow> rowsToDelete = new List <DataRow>(); foreach (DataRow row in DataTable.Rows) { BlockchainNode node = (BlockchainNode)row["Node"]; if (!managedNodes.Nodes.ContainsKey(node.NodeEndpoint.FullNodeName)) { rowsToDelete.Add(row); } } foreach (DataRow row in rowsToDelete) { DataTable.Rows.Remove(row); } //Add and update nodes foreach (string nodeName in managedNodes.Nodes.Keys) { BlockchainNode node = managedNodes.Nodes[nodeName]; var matchingNodes = from DataRow r in DataTable.Rows let nodeInDataTable = (BlockchainNode)r["Node"] where nodeInDataTable.NodeEndpoint.FullNodeName == node.NodeEndpoint.FullNodeName select r; if (!matchingNodes.Any()) { object[] rowData = new object[2]; CreateColumnIfNotExist("Status", "", typeof(Bitmap), 16); rowData[DataTable.Columns.IndexOf("Status")] = StatusIconProvider.GrayCircle; CreateColumnIfNotExist("Node", "Node", typeof(BlockchainNode), 130); rowData[DataTable.Columns.IndexOf("Node")] = node; DataTable.Rows.Add(rowData); } } }
private static void WriteConfig() { _network = new NodeNetwork <string>(); _Stopwatch.Reset(); foreach (string filePath in Directory.GetFiles($@"{AppContext.BaseDirectory}\Training\", "*.txt")) { Console.Write("Reading text from training file: "); _Stopwatch.Start(); string rawInput = File.ReadAllText(filePath); Console.WriteLine($"{_Stopwatch.ElapsedMilliseconds}ms"); _Stopwatch.Reset(); Console.Write("Symbol to new-line replacement pass: "******"{_Stopwatch.ElapsedMilliseconds}ms"); _Stopwatch.Reset(); Console.Write("New-line split pass: "******"{_Stopwatch.ElapsedMilliseconds}ms"); _Stopwatch.Reset(); Console.WriteLine("Processing input list to create node network..."); _Stopwatch.Start(); _network.ProcessInput(splitByNewLines); Console.WriteLine($"Creation of node network completed: {_Stopwatch.ElapsedMilliseconds}ms"); _Stopwatch.Reset(); } Console.Write("Writing serialized network to file: "); _Stopwatch.Start(); File.WriteAllText("config.json", JsonConvert.SerializeObject(_network)); Console.WriteLine($"{_Stopwatch.ElapsedMilliseconds}ms"); _Stopwatch.Reset(); Console.WriteLine("All processes complete."); }
public void Activity(NodeNetwork nodeNetwork) { //If SHIFT+C is down, make the line visible and redraw it, otherwise make it invisible. if (InputManager.Keyboard.KeyDown(Keys.C) && (InputManager.Keyboard.KeyDown(Keys.LeftShift) || (InputManager.Keyboard.KeyDown(Keys.RightShift)))) { this.RelativePoint1.X = mMousePosition.X = InputManager.Mouse.WorldXAt(1); this.RelativePoint1.Y = mMousePosition.Y = InputManager.Mouse.WorldYAt(1); mNode = nodeNetwork.GetClosestNodeTo(ref mMousePosition); if (mNode != null) { this.RelativePoint2.X = mNode.Position.X; this.RelativePoint2.Y = mNode.Position.Y; this.Visible = true; } } else { this.Visible = false; } }
public void DoAiActivity(bool refreshPath, NodeNetwork nodeNetwork, PositionedObjectList <Player> players, PlayerBase playerBase, TileShapeCollection solidCollisions, TileShapeCollection pitCollision) { if (CurrentHP > 0) { DoTargetDecision(players, playerBase); if (refreshPath) { // enemies always move towards player, but really slowly when shooting RefreshPath(nodeNetwork, target, solidCollisions, pitCollision); } UpdateAimingBehavior(target); UpdatePrimaryAction(); UpdateCurrentBehavior(nodeNetwork, target); UpdateCurrentMovementValues(); } }
private static void Main(string[] args) { string output = string.Empty; try { if (File.Exists(@"config.json") && false) { _network = JsonConvert.DeserializeObject <NodeNetwork <string> >(File.ReadAllText(@"config.json")); List <string> outputs = new List <string> { "i" }; for (int i = 0; i < 10; i++) { outputs.Add(_network.DetermineOutput(outputs.Last())); } output = string.Join(' ', outputs); } else { WriteConfig(); } } catch (Exception ex) { Console.WriteLine(ex); } finally { Console.WriteLine(output); Console.ReadLine(); } }
/// <summary> /// Connects the last node of the linear path to the NodeNetwork /// </summary> /// <param name="startNode">Last node of the linear path</param> /// <param name="nodeNetwork">NodeNetwork which will be modified</param> private void ConnectEndToNetwork(Node endNode, NodeNetwork nodeNetwork) { Node connectionNode; // Depending on the connection type, the last Node will search a compatible node below it to create a network connection with. switch (_connectionType) { case ConnectionType.TwoWay: // Connects the last Node and Node below both ways. This creates a 2-way connection. connectionNode = nodeNetwork.GetNodeBelow(endNode); if (connectionNode != null) { endNode.AddConnection(connectionNode); connectionNode.AddConnection(endNode); } else throw new System.Exception("Cannot find node below."); break; case ConnectionType.OneWay: // Connects the last Node and Node below one ways. This creates a 1-way connection from start to end. connectionNode = nodeNetwork.GetNodeBelow(endNode); if (connectionNode != null) { endNode.AddConnection(connectionNode); } else throw new System.Exception("Cannot find node below."); break; case ConnectionType.Manual: // No connection made at all. Create another linearPathNetwork and connect it's end to this linearPathNetwork's end. // This creates a 2-way connection with both having an innerNetwork connected to their respective starts. break; default: break; } }
/// <summary> /// Finds the nodes this gameobject overlaps, modifies their layer to the gameobject's layer and returns all the nodes modified. /// </summary> /// <param name="nodeNetwork">NodeNetwork which will be modified</param> /// <returns>List of all modified nodes</returns> public virtual List <Node> CreateCustomNodeNetwork(NodeNetwork nodeNetwork) { return(CreateCustomNodeNetwork(nodeNetwork, gameObject.layer)); }
public void UpdateDataTable(DatabaseConnection database, NodeNetwork managedNodes) { if (managedNodes == null) { return; } foreach (string fullNodeName in managedNodes.Nodes.Keys) { foreach (DataRow dataRow in DataTable.Rows) { BlockchainNode node = managedNodes.Nodes[fullNodeName]; if (node.NodeState.Initialized && ((BlockchainNode)dataRow["Node"]).NodeEndpoint.FullNodeName.Equals(fullNodeName)) { switch (node.NodeState.NodeOperationState.State) { case ProcessState.Unknown: dataRow["Status"] = StatusIconProvider.GrayCircle; break; case ProcessState.Stopped: dataRow["Status"] = StatusIconProvider.RedCircle; break; case ProcessState.Running: dataRow["Status"] = StatusIconProvider.GreenCircle; break; case ProcessState.Starting: dataRow["Status"] = StatusIconProvider.GreenCircle; break; default: throw new ArgumentOutOfRangeException(); } dataRow["Node"] = node; CreateColumnIfNotExist("HeaderHeight", "Header", typeof(String), 40); dataRow["HeaderHeight"] = node.NodeState.NodeLogState.HeadersHeight; CreateColumnIfNotExist("ConsensusHeight", "Consen", typeof(String), 35); dataRow["ConsensusHeight"] = node.NodeState.NodeLogState.ConsensusHeight; CreateColumnIfNotExist("BlockHeight", "Block", typeof(String), 35); dataRow["BlockHeight"] = node.NodeState.NodeLogState.BlockStoreHeight; CreateColumnIfNotExist("WalletHeight", "Wallet", typeof(String), 35); dataRow["WalletHeight"] = node.NodeState.NodeLogState.WalletHeight; CreateColumnIfNotExist("NetworkHeight", "Network", typeof(String), 35); dataRow["NetworkHeight"] = node.NodeState.NodeOperationState.NetworkHeight; CreateColumnIfNotExist("Mempool", "Mpool", typeof(String), 30); dataRow["Mempool"] = node.NodeState.NodeOperationState.MempoolTransactionCount; CreateColumnIfNotExist("Events", "Events", typeof(String), 60); dataRow["Events"] = $"M: {database.GetMinedBlockCount(fullNodeName)} / R: {database.GetReorgCount(fullNodeName)}"; CreateColumnIfNotExist("Peers", "Peers", typeof(String), 70); dataRow["Peers"] = $"In:{node.NodeState.NodeOperationState.InboundPeersCount} / Out:{node.NodeState.NodeOperationState.OutboundPeersCount}"; CreateColumnIfNotExist("Uptime", "Uptime", typeof(String), 50); dataRow["Uptime"] = node.NodeState.NodeOperationState.Uptime.ToString("d'.'hh':'mm"); CreateColumnIfNotExist("Branch", "Branch", typeof(String), 100); int lastComitDays = (DateTime.Now - node.GitRepositoryInfo.LatestLocalCommitDateTime).Days; dataRow["Branch"] = $"{node.GitRepositoryInfo.CurrentBranchName} [{node.GitRepositoryInfo.CommitDifference}] {lastComitDays} days ago"; } } } }
/// <summary> /// Creates Range instance with specified estimation precision and signal strength threshhold. /// </summary> public Range() { mNodeNetwork = NodeNetwork.Instance; }
public T LoadFromFile <T>(string assetName) { string extension = FileManager.GetExtension(assetName); if (FileManager.IsRelative(assetName)) { // get the absolute path using the current relative directory assetName = FileManager.RelativeDirectory + assetName; } string fullNameWithType = assetName + typeof(T).Name; // get the dictionary by the contentManagerName. If it doesn't exist, GetDisposableDictionaryByName // will create it. if (mDisposableDictionary.ContainsKey(fullNameWithType)) { #if PROFILE mHistory.Add(new ContentLoadHistory( TimeManager.CurrentTime, typeof(T).Name, fullNameWithType, ContentLoadDetail.Cached)); #endif return((T)mDisposableDictionary[fullNameWithType]); } else if (mNonDisposableDictionary.ContainsKey(fullNameWithType)) { return((T)mNonDisposableDictionary[fullNameWithType]); } else { #if PROFILE mHistory.Add(new ContentLoadHistory( TimeManager.CurrentTime, typeof(T).Name, fullNameWithType, ContentLoadDetail.HddFromFile)); #endif #if DEBUG // The ThrowExceptionIfFileDoesntExist // call used to be done before the checks // in the dictionaries. But whatever is held // in there may not really be a file so let's check // if the file exists after we check the dictionaries. FileManager.ThrowExceptionIfFileDoesntExist(assetName); #endif IDisposable loadedAsset = null; if (typeof(T) == typeof(Texture2D) || typeof(T) == typeof(Microsoft.Xna.Framework.Graphics.Texture2D)) { // for now we'll create it here, eventually have it in a dictionary: loadedAsset = textureContentLoader.Load(assetName); } #region Scene else if (typeof(T) == typeof(FlatRedBall.Scene)) { FlatRedBall.Scene scene = FlatRedBall.Content.Scene.SceneSave.FromFile(assetName).ToScene(mName); object sceneAsObject = scene; lock (mNonDisposableDictionary) { if (!mNonDisposableDictionary.ContainsKey(fullNameWithType)) { mNonDisposableDictionary.Add(fullNameWithType, scene); } } return((T)sceneAsObject); } #endregion #region EmitterList else if (typeof(T) == typeof(EmitterList)) { EmitterList emitterList = EmitterSaveList.FromFile(assetName).ToEmitterList(mName); mNonDisposableDictionary.Add(fullNameWithType, emitterList); return((T)((object)emitterList)); } #endregion #region Image #if !MONOGAME else if (typeof(T) == typeof(Image)) { switch (extension.ToLowerInvariant()) { case "gif": Image image = Image.FromFile(assetName); loadedAsset = image; break; } } #endif #endregion #region BitmapList #if !XBOX360 && !SILVERLIGHT && !WINDOWS_PHONE && !MONOGAME else if (typeof(T) == typeof(BitmapList)) { loadedAsset = BitmapList.FromFile(assetName); } #endif #endregion #region NodeNetwork else if (typeof(T) == typeof(NodeNetwork)) { NodeNetwork nodeNetwork = NodeNetworkSave.FromFile(assetName).ToNodeNetwork(); mNonDisposableDictionary.Add(fullNameWithType, nodeNetwork); return((T)((object)nodeNetwork)); } #endregion #region ShapeCollection else if (typeof(T) == typeof(ShapeCollection)) { ShapeCollection shapeCollection = ShapeCollectionSave.FromFile(assetName).ToShapeCollection(); mNonDisposableDictionary.Add(fullNameWithType, shapeCollection); return((T)((object)shapeCollection)); } #endregion #region PositionedObjectList<Polygon> else if (typeof(T) == typeof(PositionedObjectList <FlatRedBall.Math.Geometry.Polygon>)) { PositionedObjectList <FlatRedBall.Math.Geometry.Polygon> polygons = PolygonSaveList.FromFile(assetName).ToPolygonList(); mNonDisposableDictionary.Add(fullNameWithType, polygons); return((T)((object)polygons)); } #endregion #region AnimationChainList else if (typeof(T) == typeof(AnimationChainList)) { if (assetName.EndsWith("gif")) { #if WINDOWS_8 || UWP || DESKTOP_GL throw new NotImplementedException(); #else AnimationChainList acl = new AnimationChainList(); acl.Add(FlatRedBall.Graphics.Animation.AnimationChain.FromGif(assetName, this.mName)); acl[0].ParentGifFileName = assetName; loadedAsset = acl; #endif } else { loadedAsset = AnimationChainListSave.FromFile(assetName).ToAnimationChainList(mName); } mNonDisposableDictionary.Add(fullNameWithType, loadedAsset); } #endregion else if (typeof(T) == typeof(Song)) { var loader = new SongLoader(); return((T)(object)loader.Load(assetName)); } #if MONOGAME else if (typeof(T) == typeof(SoundEffect)) { T soundEffect; if (assetName.StartsWith(@".\") || assetName.StartsWith(@"./")) { soundEffect = base.Load <T>(assetName.Substring(2)); } else { soundEffect = base.Load <T>(assetName); } return(soundEffect); } #endif #region RuntimeCsvRepresentation #if !SILVERLIGHT else if (typeof(T) == typeof(RuntimeCsvRepresentation)) { #if XBOX360 throw new NotImplementedException("Can't load CSV from file. Try instead to use the content pipeline."); #else return((T)((object)CsvFileManager.CsvDeserializeToRuntime(assetName))); #endif } #endif #endregion #region SplineList else if (typeof(T) == typeof(List <Spline>)) { List <Spline> splineList = SplineSaveList.FromFile(assetName).ToSplineList(); mNonDisposableDictionary.Add(fullNameWithType, splineList); object asObject = splineList; return((T)asObject); } else if (typeof(T) == typeof(SplineList)) { SplineList splineList = SplineSaveList.FromFile(assetName).ToSplineList(); mNonDisposableDictionary.Add(fullNameWithType, splineList); object asObject = splineList; return((T)asObject); } #endregion #region BitmapFont else if (typeof(T) == typeof(BitmapFont)) { // We used to assume the texture is named the same as the font file // But now FRB understands the .fnt file and gets the PNG from the font file //string pngFile = FileManager.RemoveExtension(assetName) + ".png"; string fntFile = FileManager.RemoveExtension(assetName) + ".fnt"; BitmapFont bitmapFont = new BitmapFont(fntFile, this.mName); object bitmapFontAsObject = bitmapFont; return((T)bitmapFontAsObject); } #endregion #region Text else if (typeof(T) == typeof(string)) { return((T)((object)FileManager.FromFileText(assetName))); } #endregion #region Catch mistakes #if DEBUG else if (typeof(T) == typeof(Spline)) { throw new Exception("Cannot load Splines. Try using the List<Spline> type instead."); } else if (typeof(T) == typeof(Emitter)) { throw new Exception("Cannot load Emitters. Try using the EmitterList type instead."); } #endif #endregion #region else, exception! else { throw new NotImplementedException("Cannot load content of type " + typeof(T).AssemblyQualifiedName + " from file. If you are loading " + "through the content pipeline be sure to remove the extension of the file " + "name."); } #endregion if (loadedAsset != null) { lock (mDisposableDictionary) { // Multiple threads could try to load this content simultaneously if (!mDisposableDictionary.ContainsKey(fullNameWithType)) { mDisposableDictionary.Add(fullNameWithType, loadedAsset); } } } return((T)loadedAsset); } }